From 8a633a0f6bef2d87d001cdb14d996c883255d45f Mon Sep 17 00:00:00 2001 From: Sergei Date: Mon, 19 Jan 2026 23:01:47 -0800 Subject: [PATCH] Add attachDeviceToDeployment method to api.ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements API method to link WP sensors to a beneficiary's deployment via the Legacy API set_deployment endpoint. Uses proper authentication through getLegacyWebViewCredentials() and follows existing API patterns. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- services/api.ts | 59 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/services/api.ts b/services/api.ts index bed0e8f..edaaa58 100644 --- a/services/api.ts +++ b/services/api.ts @@ -1782,6 +1782,65 @@ class ApiService { } } + /** + * Attach device to deployment via Legacy API + * Uses set_deployment endpoint to link a WP sensor to a beneficiary's deployment + * + * @param deploymentId - The deployment ID to attach the device to + * @param wellId - The device's well_id (from BLE scan, e.g., 497) + * @param ssid - WiFi network SSID + * @param password - WiFi network password + */ + async attachDeviceToDeployment( + deploymentId: number, + wellId: number, + ssid: string, + password: string + ): Promise> { + try { + const creds = await this.getLegacyWebViewCredentials(); + if (!creds) { + return { ok: false, error: { message: 'Not authenticated with Legacy API', code: 'UNAUTHORIZED' } }; + } + + // Call set_deployment to attach device + const formData = new URLSearchParams({ + function: 'set_deployment', + user_name: creds.userName, + token: creds.token, + deployment: deploymentId.toString(), + devices: JSON.stringify([wellId]), + wifis: JSON.stringify([`${ssid}|${password}`]), + reuse_existing_devices: '1', + }); + + console.log('[API] attachDeviceToDeployment: deployment=', deploymentId, 'wellId=', wellId, 'ssid=', ssid); + + const response = await fetch(API_BASE_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: formData.toString(), + }); + + if (!response.ok) { + return { ok: false, error: { message: 'Failed to attach device to deployment' } }; + } + + const data = await response.json(); + + if (data.status !== '200 OK') { + console.error('[API] attachDeviceToDeployment failed:', data); + return { ok: false, error: { message: data.message || 'Failed to attach device' } }; + } + + console.log('[API] attachDeviceToDeployment success'); + return { ok: true, data: { success: true } }; + } catch (error: any) { + console.error('[API] attachDeviceToDeployment error:', error); + return { ok: false, error: { message: error.message || 'Network error', code: 'NETWORK_ERROR' } }; + } + } + /** * Detach device from beneficiary */