Skip to main content

Plants API (/v1/plants)

A plant is one solar site — the account/device-ownership boundary everything else (devices, memberships) hangs off. Telemetry for a plant (live readings, generation history) is not served here; that is the TCP Server's WebSocket side.

Contract index (feature 004)​

Where each feature 004 contract is documented. Every example on this page is illustrative.

ContractRouteSection
C01 (web list)GET /v1/plants with X-Org-IdWeb console plant list
C02GET /v1/plants/summaryPlant counts
C03GET /v1/plants/geoPlant map points
C04POST /v1/plants with X-Org-IdWeb create
C05GET /v1/plants/{plantId} (mobile and web)Plant detail
C06GET /v1/plants/{plantId}/workspacePlant Workspace
C07PATCH /v1/plants/{plantId} with X-Org-IdWeb edit
C08, C09plant settings (alert rules, tariff)Plant settings
C10, C10barchive, restore, bulk archiveArchive and restore
C11DELETE /v1/plants/{plantId} with X-Org-IdPlatform delete
C12, C12bplant tags, bulk tag, plant jobsPlant tags
C13, C14share linksShare links
R-5 (2026-11-03)plant ↔ Installer: assign, historyAssigned Installer
C15/v1/plant-draftsPlant drafts
C16, A08saved views, favouritesSaved views, Favourites
C17, C18, C19customers, partnersCustomers, Partners
C20tagsTags
C21, C22dashboard, work queueDashboard
Business profile (FR-048)org profileTeam → Business profile

GET /v1/plants — List plants visible to the caller​

This is the mobile variant (no X-Org-Id header). For the web console variant see web console plant list.

Purpose: The account's plant list screen — one query, no N+1, since membership items already carry a denormalised copy of the plant's core fields (see Architecture → Data flow).

  • HTTP method: GET
  • Endpoint: /v1/plants
  • Authentication: Required
  • Authorization: Implicit — only returns plants the caller has a membership on; there is no way to list another account's plants

Request​

Headers: Authorization: Bearer <token> (required). Path parameters: none.

Query parameters:

ParamTypeRequiredDefaultValidation
limitintegerNo251-50. This is a lenient route (CR-13): a non-integer or out-of-range limit silently falls back to the default (25) rather than being rejected (packages/core/src/pagination/list-query.ts, T002-074)
cursorstringNo—Opaque; from a previous response's nextCursor

Request body: none.

Response​

{
items: Array<{
plantId: string;
name: string;
pvCapacityKwp?: number;
timezone: string;
status: 'ACTIVE' | 'PENDING' | 'SUSPENDED';
role: 'OWNER' | 'ADMIN' | 'VIEWER'; // the caller's role on this plant
createdAt: string;
updatedAt: string;
address?: PlantAddress; // 2026-11-17 (additive): same shape as the plant detail's; absent = none
isFavorite: boolean; // 2026-11-17 (additive): the caller has starred this plant
}>;
nextCursor?: string; // omitted on the last page
}

Each item is the caller's membership item with its keys stripped, not the plant item. It has a denormalised copy of some Plant fields (PlantListItem), so it doesn't include plantType, countryCode, solarMode, gridConnection, electricityRate or any battery field (it does include address and isFavorite since 2026-11-17; see below). batteryBrand was returned here from 2026-11-05 until 2026-11-18, when battery data moved to devices on the TCP server: the home screen now picks the Elektra Boost logo from the device battery's brand. Call GET /v1/plants/{plantId} for the full plant. Items come back in plant-creation order, oldest first.

address and isFavorite (added 2026-11-17, additive). Requested by the web console (backend request B-4, interim option) so it no longer reads every plant's detail and the whole favourites list. address is read from the plant itself and has the same shape as GET /v1/plants/{plantId}: a plant saved before 2026-09-24 with a plain-text address returns { "formatted": "<text>" }; a plant with no address has no address key. isFavorite is true when the caller has starred the plant with PUT /v1/me/favorites/PLANT/{id}, and is always present. Both come from two batched reads per page (never one read per row). Older app builds ignore the new keys.

Nothing can update a plant today, so the denormalised copy can't drift yet. Any future plant-update endpoint must rewrite the membership copies in the same transaction (see Architecture → Data flow).

Successful response — illustrative example​

{
"items": [
{
"plantId": "01J9Z4A1B2C3D4E5F6G7H8J9K0",
"name": "Ghori Residence",
"pvCapacityKwp": 10,
"timezone": "Asia/Karachi",
"status": "ACTIVE",
"role": "OWNER",
"createdAt": "2026-08-01T05:30:00.000Z",
"updatedAt": "2026-08-01T05:30:00.000Z",
"address": { "formatted": "Street 14, DHA Phase 6", "city": "Karachi", "region": "Sindh" },
"isFavorite": false
}
]
}

Empty account (no plants yet):

{ "items": [] }

Failure response — auth failure (illustrative)​

API Gateway's own body, not this API's envelope (see API overview → Gateway responses):

{ "message": "Unauthorized" }

403 FORBIDDEN, 404 NOT_FOUND, 409 CONFLICT: not applicable — this endpoint has no target resource to be forbidden from or missing; an empty result set is a valid 200, not an error. 422 for limit: not applicable either — this lenient route never rejects limit; an out-of-range or non-integer value silently falls back to 25 instead (see the query-parameter table above).

HTTP status codes​

StatuscodeWhen
200—Success (including an empty list)
401— (gateway body)Missing/invalid token
500INTERNALUnexpected server error

Mobile list contents (004). Without X-Org-Id the list returns only legacy (mobile-created) plant items. Access-index copies and new-schema (web-created) plants are filtered out. The server refills a thinned page with up to 5 extra queries, so a page is normally full; it can still come back shorter than limit (even empty) with nextCursor present when that refill limit is hit. nextCursor resumes exactly after the last row read, so keep paging while nextCursor is present and never treat a short page as the last.

A malformed, legacy or foreign-query cursor is not an error either; it silently restarts from the first page (lenient, CR-13).


GET /v1/plants with X-Org-Id — Web console plant list​

Purpose: the web console's plant table. Same path as the mobile list above; sending the X-Org-Id header selects this variant. Without the header the mobile behaviour above applies unchanged.

:::note Status Verified against packages/api/src/handlers/plants-read.ts, packages/core/src/plants/repository.ts and summary.ts. Deployed on dev (the web list, /v1/plants/summary and /v1/plants/geo were verified live on 2026-10-13), but no response was captured for these docs, so all examples below are illustrative. The created-order/lifecycle list path (plants/list-paths.ts) queries GSI3, deployed to dev on 2026-10-13, so it is expected to work now, not yet re-verified on dev. :::

  • HTTP method: GET
  • Endpoint: /v1/plants
  • Authentication: Required (web-console Cognito client token)
  • Authorization: plants ≥ VIEW in the org named by X-Org-Id. Results are limited to the caller's scope: a member scoped to tags, regions, customers or a plant list only sees those plants. In the Crown HQ platform org, the built-in Super Admin and Administrator can list every org at once (see Platform-wide list below).

Request​

Headers: Authorization: Bearer <token>, X-Org-Id: <org ULID> (both required for this variant).

Query parameters (strict: any unknown parameter → 400 VALIDATION_FAILED):

ParamTypeDefaultValidation
lifecycleACTIVE | ARCHIVEDACTIVEArchived plants appear only with ARCHIVED
plantTypeenum, repeatable—Up to 5 values from RESIDENTIAL, COMMERCIAL, INDUSTRIAL; any other value → 400 VALIDATION_FAILED. INDUSTRIAL/COMMERCIAL also match plants still storing the retired UTILITY/OTHER (not yet migrated)
countryCodestring—ISO alpha-2, single
regionTagIdULID, repeatable—Up to 5
tagIdULID, repeatable—Up to 5, matched with OR
customerOrgIdULID—Single
installerOrgIdULID—Single
assignedInstallerSubstring (Cognito sub)—Single; plants assigned to this Installer (R-5)
capacityMin / capacityMaxnumber (kWp)—≥ 0, inclusive, min ≤ max
createdFrom / createdToISO date-time—from ≤ to
favoritetrue—Only the caller's starred plants
qstring—2–64 chars; every word must be a prefix of the name, code, customer name, city, region, a tag label or the street address (address.formatted, 2026-11-24). A q that is exactly one plant id (ULID, any case) returns that plant alone (matchedField: "id", no cursor) when the caller can list it, otherwise falls back to the word search. Cannot be combined with sort
operatorOrgIdULID—Platform org only (rejected in any other org): narrows the list to one org. Optional for the built-in Super Admin / Administrator (absent = every org); required for every other platform role
sortname, -name, createdAt, -createdAtnameSee the table below
limitinteger15 first page, 10 with cursor1–50; a sent value wins (lazy loading)
cursorstring—From a previous nextCursor

Which sorts are allowed depends on the filters, because each filter uses a different index:

Filters sentAllowed sort
qnone (results come back in match order)
favorite=truenone
customerOrgId, installerOrgId, tagId, regionTagId, or no filtername, -name
sort=createdAt / -createdAt with no relationship filtercreatedAt, -createdAt

Scoped callers can sort by name only. A disallowed sort returns 400 VALIDATION_FAILED with details.allowed listing the sorts you can use.

Response​

{
items: Array<WebPlantListItem & { matchedField?: 'name'|'code'|'customer'|'city'|'region'|'tag'|'address'|'id' }>;
nextCursor?: string; // omitted on the last page
refs: Refs; // display names for every org and tag id in items
}

WebPlantListItem fields: plantId, code, name, plantType, lifecycle, countryCode, address, pvCapacityKwp, systemType, gridTopology, hasBattery, customerOrgId, installerOrgId?, installedBy?, assignedInstaller?, tagIds, regionTagId?, deviceCount?, timezone? (the plant's IANA zone; added 2026-11-17), createdAt, updatedAt, version, isFavorite, operatorOrgId (the owning org; added 2026-11-03, ADR 0016), and blocked: true only on a plant frozen by Block B (RBAC v2, 2026-11-14 — show a badge and disable opening it; opening is 403 PLANT_BLOCKED). The same blocked flag appears on favorites rows and on GET /v1/plants/geo rows. matchedField is only present when q was sent (address = street address, id = exact plant id). Street address tokens are search tokens like the others: they are written by the stream-router (KI-43: not deployed on dev), so on dev a plant matches its street only after npm run rebuild:projections has run since the 2026-11-24 change. The plant-id match needs no token. There are no totals or page numbers; use the summary for counts. No telemetry is returned; join live data from the TCP side by plantId.

Which plants are listed. Only schema-v2 plants. Every plant the mobile app has created since 2026-11-03 is v2 and is listed in its owner's personal org (and in the Business it later moves to). A mobile plant created before 2026-11-03 that has never been migrated belongs to no org, so it cannot appear in any org's list until it is migrated: by its first web edit, by a move into a Business, or by scripts/migrate-legacy-plants.ts. Until then the mobile list (no X-Org-Id) is the only list that shows it; that list now also carries address and isFavorite (see above).

Refs:

{
orgs: Record<orgId, { name: string; code?: string; kind: 'PLATFORM'|'OPERATOR'|'PARTNER'|'CUSTOMER';
personal?: true /* an Independent End User's personal org (ADR 0016) */ }>;
tags: Record<tagId, { label: string; group: 'SEGMENT'|'REGION'|'SERVICE'|'COMMERCIAL'|'COMPLIANCE';
color: 'NEUTRAL'|'INFO'|'SUCCESS'|'WARNING'|'ERROR'|'ACCENT'; system: boolean }>;
}

An id with no entry in refs (for example a deleted tag) should be shown as unknown rather than treated as an error.

Successful response — illustrative example​

{
"items": [{
"plantId": "01JB5Q0000000000000000000A", "code": "PL-0518", "name": "DHA Phase 6 Residence",
"plantType": "RESIDENTIAL", "lifecycle": "ACTIVE", "countryCode": "PK",
"address": { "formatted": "Street 14, DHA Phase 6", "city": "Karachi", "region": "Sindh", "latitude": 24.8, "longitude": 67.07 },
"pvCapacityKwp": 12, "systemType": "PV_GRID_BATTERY", "gridTopology": "ON_GRID_BACKUP", "hasBattery": true,
"customerOrgId": "01JB5R0000000000000000000A", "tagIds": ["01JB5T0000000000000000000A"],
"timezone": "Asia/Karachi",
"createdAt": "2025-03-03T09:00:00.000Z", "updatedAt": "2026-09-01T10:00:00.000Z", "version": 4,
"isFavorite": true, "operatorOrgId": "01JB5P0000000000000000000A", "matchedField": "customer"
}],
"nextCursor": "eyJ…",
"refs": {
"orgs": { "01JB5R0000000000000000000A": { "name": "A. Kazmi", "code": "CU-1042", "kind": "CUSTOMER" } },
"tags": { "01JB5T0000000000000000000A": { "label": "VIP", "group": "SEGMENT", "color": "ACCENT", "system": false } }
}
}

Failure response — disallowed sort (illustrative)​

{ "error": { "code": "VALIDATION_FAILED", "message": "…", "details": { "allowed": ["name", "-name"] }, "requestId": "…" } }

Errors​

StatuscodeWhenWhat the FE should do
400VALIDATION_FAILEDUnknown param (details.unknown), bad enum, disallowed sort (details.allowed), q under 2 chars, more than 5 tag values, operatorOrgId missing in the platform org for a role other than the built-in Super Admin / Administrator (details.field: operatorOrgId) or sent from any other org, installerOrgId in the platform-wide list without operatorOrgId (details.field: installerOrgId)Fix the query; offer only details.allowed sorts; in the platform-wide list ask for a Business before filtering by installer
400INVALID_CURSORMalformed cursor, or a cursor reused after changing filters/sortDrop the cursor and reload page 1
401— (gateway body)Missing/expired tokenRefresh the token and retry
403FORBIDDENNot a member of X-Org-Id, or plants below VIEWShow "no access"; switch org
404NOT_FOUNDPlatform staff with no membership of their own in X-Org-Id who are NOT eligible for the platform fallback (platform membership not ACTIVE/ALL-scoped, or the org is non-ACTIVE or PLATFORM). An eligible platform member is evaluated at the platform role's own levels insteadTreat the org as unavailable; switch org
403ACCOUNT_SUSPENDEDOrg policy (feature 003)Show suspended state
422SCOPE_TOO_BROADThe caller's scope has more than 10 targetsShow a message; an admin must narrow the scope
500INTERNALUnexpectedRetry later
503DEPENDENCY_UNAVAILABLEDynamoDB throttled/unavailableRetry with backoff

Platform-wide list (ADR 0016)​

:::note Status Committed 2026-11-03, not deployed. Verified against packages/core/src/plants/list-paths.ts (chooseAllOrgPath), repository.ts (listAllOrgs) and packages/api/src/handlers/plants-read.ts; covered by unit tests and an authored (not run) DynamoDB Local test. Not executed against any stage. :::

With X-Org-Id = the Crown HQ PLATFORM org and no operatorOrgId:

Caller in the platform orgResult
Built-in Super Admin or Administrator role, membership ACTIVE, scope ALL, MFA gate passed (the same rule as platform-wide search, ADR 0015)Plants of every org, personal orgs (Independent End Users) included, and — since 2026-12-01 (F13) — plants Crown HQ operates itself (its own PLATFORM org), which were left out before, so the list now matches TCP's list_plants for HQ. Plants of a suspended or closed org stay out
Any other platform role (a custom "Admin with assigned permissions", or not scope ALL)400 VALIDATION_FAILED, details.field: operatorOrgId (unchanged)
An MFA-gated platform membership200 with no items

operatorOrgId still narrows the list to one org for everyone in the platform org. Other orgs are unchanged: own org and authorized plants only.

:::info Admins: all plants or favourites only (owner 2026-11-25) A built-in Super Admin or Administrator gets the same two options on the web console and the mobile app:

  • All plants (default): no favorite → every plant of every org (Business, Installer-served and End User plants alike).
  • My favourites: favorite=true → only the plants they starred (Favourites); no sort.

Both use the shared lazy paging: 15 on the first page, 10 after, limit up to 50. A cursor from one option is rejected by the other (400 INVALID_CURSOR): restart from page 1 when switching. Step-by-step for app developers: Plant list by profile. :::

  • Which plants: those whose owning org is ACTIVE and not the PLATFORM org. Plants of a suspended or closed org are left out. Archived plants appear only with lifecycle=ARCHIVED, as in the per-org list.
  • Rows: every row carries operatorOrgId. refs.orgs[operatorOrgId] gives that org's name, code and kind, plus personal: true for a personal org (its kind is CUSTOMER). Open a row with X-Org-Id: <operatorOrgId>.
  • Filters and sorts: the same as the per-org list (name/-name by default, createdAt/-createdAt, q, favorite, customerOrgId, tagId, regionTagId, and the metadata filters), except installerOrgId, which needs operatorOrgId here (400, details.field: installerOrgId). q uses platform-wide search tokens, which are written by the stream-router (KI-43).
  • Paging: pages can be short and still carry nextCursor; keep paging until it is absent. A cursor from the per-org list (or with other filters or sort) is 400 INVALID_CURSOR.
  • How it reads: each plant has a small PLANT#<p>/LISTALL entry in one of four shards, written in the same transaction as the plant on create, rename, archive/restore and delete request. A page queries the four shards, merges them by name (or creation), and loads each plant before applying filters.
  • Plants created before the deploy appear only after the backfill (npm run rebuild:projections -- --all-orgs --execute, see Operations).
  • Not covered: GET /v1/plants/summary still needs operatorOrgId from the platform org for every role (its counters are kept per org).

Platform-wide response — illustrative example​

{
"items": [
{ "plantId": "01JB5Q0000000000000000000A", "code": "PL-0518", "name": "Askari Roof", "lifecycle": "ACTIVE",
"operatorOrgId": "01JB5P0000000000000000000A", "customerOrgId": "01JB5R0000000000000000000A",
"plantType": "RESIDENTIAL", "countryCode": "PK", "gridTopology": "ON_GRID", "hasBattery": false, "tagIds": [],
"createdAt": "2025-03-03T09:00:00.000Z", "updatedAt": "2026-09-01T10:00:00.000Z", "version": 4, "isFavorite": false },
{ "plantId": "01JB5Q0000000000000000000B", "code": "PL-0731", "name": "Home", "lifecycle": "ACTIVE",
"operatorOrgId": "01JB5U0000000000000000000A", "customerOrgId": "01JB5U0000000000000000000A",
"plantType": "RESIDENTIAL", "countryCode": "PK", "gridTopology": "ON_GRID", "hasBattery": false, "tagIds": [],
"createdAt": "2026-10-30T08:00:00.000Z", "updatedAt": "2026-10-30T08:00:00.000Z", "version": 1, "isFavorite": false }
],
"nextCursor": "eyJ…",
"refs": {
"orgs": {
"01JB5P0000000000000000000A": { "name": "Sunrise Solar", "code": "OR-0012", "kind": "OPERATOR" },
"01JB5R0000000000000000000A": { "name": "A. Kazmi", "code": "CU-1042", "kind": "CUSTOMER" },
"01JB5U0000000000000000000A": { "name": "Sara Ali", "kind": "CUSTOMER", "personal": true }
},
"tags": {}
}
}

Edge cases​

  • Short pages: a page can have fewer than limit items and still carry nextCursor (filtered or scope-hidden rows). Keep paging until nextCursor is absent.
  • Renamed during paging: a plant renamed between pages can appear on a later page again or be skipped; de-duplicate by plantId.
  • Search is eventually consistent: a just-created or renamed plant can take a few seconds to match q. Search tokens are written by the stream-router, which is not deployed while busEnabled is off (every stage today), so on dev new or renamed plants do not match q at all (KI-43).
  • Mobile-created plants. Since 2026-11-03 (committed, not yet deployed), mobile POST /v1/plants (no X-Org-Id) writes a schema v2 plant in the owner's personal org: PL- code, lifecycle: ACTIVE, version: 1 and GSI keys (createPlantMobile in packages/core/src/plants/repository.ts). Such a plant is in the web list of that personal org at once, and in search once the stream-router has processed it. Plants the app created before that deploy are still legacy: they stay missing from the web list until migrated (npm run migrate:legacy-plants, run by a human) or saved on the web with If-Match: "0". The app can still edit and delete its own v2 personal plants (the 2026-10-29 fix), which was the reason mobile create had stayed legacy until now.
  • Empty result is 200 with items: [].

GET /v1/plants/summary — Plant counts​

Purpose: the counters above the web plant table and the dashboard.

  • Auth: Required. Authorization: plants ≥ VIEW.
  • Headers: X-Org-Id required (else 400 ORG_CONTEXT_REQUIRED).
  • Query: operatorOrgId (platform org only). Nothing else. Unlike the list, it is required from the platform org for every role, the built-in Super Admin and Administrator included: the counters are kept per org, so there is no platform-wide summary (ADR 0016 §5).

Response​

{
approximate: true;
scoped: boolean;
plantCount?: number; capacityKwp?: number; expectedAnnualYieldKwh?: number;
byLifecycle?: Record<string, number>; byPlantType?: Record<string, number>; byCountry?: Record<string, number>;
byRegionTag: Record<tagId, number>; byTag: Record<tagId, number>; byCustomer: Record<orgId, number>;
byInstaller?: Record<orgId, number>;
refs: Refs;
}

Counts are approximate: they come from counters updated a few seconds after each change, so they can briefly disagree with the list. A scoped caller (scoped: true) gets only byTag, byRegionTag and byCustomer for their own targets; the other fields are omitted, so the FE must treat them as optional. A caller scoped to an explicit plant list, or signed in to a CUSTOMER or PARTNER org, gets scoped: true with empty maps. byCustomer and byInstaller are the top 50 by count.

Successful response — illustrative example​

{ "approximate": true, "scoped": false, "plantCount": 1284, "capacityKwp": 9800.4, "expectedAnnualYieldKwh": 15876000,
"byLifecycle": { "ACTIVE": 1284, "ARCHIVED": 17 }, "byPlantType": { "RESIDENTIAL": 902, "INDUSTRIAL": 31 },
"byCountry": { "PK": 1270, "AE": 14 }, "byRegionTag": { "01JB5U0000000000000000000A": 219 },
"byTag": { "01JB5T0000000000000000000A": 48 }, "byCustomer": { "01JB5R0000000000000000000A": 6 },
"byInstaller": {}, "refs": { "orgs": {}, "tags": {} } }

Errors​

StatuscodeWhenWhat the FE should do
400ORG_CONTEXT_REQUIREDNo X-Org-IdSend the selected org
400VALIDATION_FAILEDUnknown param, operatorOrgId misuseFix the query
401—TokenRefresh and retry
403FORBIDDENNot a member / plants below VIEWHide the counters
404NOT_FOUNDPlatform staff with no membership of their own in X-Org-Id who are NOT eligible for the platform fallback (platform membership not ACTIVE/ALL-scoped, or the org is non-ACTIVE or PLATFORM). An eligible platform member is evaluated at the platform role's own levels insteadTreat the org as unavailable; switch org
422SCOPE_TOO_BROADThe caller's scope has more than 10 targetsShow a message; an admin must narrow the scope
500INTERNALUnexpectedRetry later
503DEPENDENCY_UNAVAILABLEDynamoDBRetry with backoff

GET /v1/plants/geo — Plant map points​

Purpose: the map view. Returns coordinates only, up to 1,000 per page.

  • Auth: Required. Authorization: plants ≥ VIEW, scope-filtered like the list.
  • Headers: X-Org-Id required.
  • Query: the same filters as the web list except sort, q and favorite; limit 1–1000 (default 1000); cursor.
  • Rate limit: 5 requests per second per user → 429 RATE_LIMITED with Retry-After.
  • Platform-wide: the platform-wide list rule applies here too (committed 2026-11-03, not deployed): the built-in Super Admin / Administrator in the platform org may omit operatorOrgId to map every org.

Response​

{ items: Array<{ plantId: string; code: string; name: string; latitude: number; longitude: number;
regionTagId?: string; plantType?: PlantType; operatorOrgId?: string /* ADR 0016 */ }>;
nextCursor?: string }

Plants without coordinates are left out. Fetch the next page with cursor until nextCursor is absent.

Successful response — illustrative example​

{ "items": [{ "plantId": "01JB5Q0000000000000000000A", "code": "PL-0518", "name": "DHA Phase 6 Residence",
"latitude": 24.8, "longitude": 67.07, "plantType": "RESIDENTIAL" }] }

Errors​

StatuscodeWhenWhat the FE should do
400ORG_CONTEXT_REQUIRED / VALIDATION_FAILED / INVALID_CURSORAs the web list; limit over 1000Fix the query / restart paging
401—TokenRefresh and retry
403FORBIDDENNo accessHide the map
422SCOPE_TOO_BROADScope with more than 10 targetsShow a message
429RATE_LIMITEDMore than 5 req/sWait Retry-After seconds; debounce map pans
503DEPENDENCY_UNAVAILABLEDynamoDBRetry with backoff

POST /v1/plants — Create a plant​

Creates a plant and the caller's OWNER membership in one atomic DynamoDB transaction. It's the submit of the app's create-plant wizard (screens 08-10; the battery step was removed on 2026-11-20), sent as one request. The caller is stored as the plant's owner (ownerUserSub, ADR 0029) — see Plant ownership, share and unshare.

  • HTTP method: POST
  • Endpoint: /v1/plants
  • Authentication: Required
  • Authorization: None beyond authentication. Any signed-in caller may create a plant and becomes its OWNER
  • Body: CreatePlantInput, strict JSON
  • Responses: 201 with the created Plant, 401 (gateway body), 422 VALIDATION_FAILED, 500 INTERNAL

The full contract is on its own page: Create a plant: FE integration guide. It covers every field and option, every validation and cross-field rule with the exact server message, the conditional UI each rule implies, success handling for screen 12, error handling, and retry safety.

DynamoDB writes: the next PL- code is taken from the platform sequence, then one TransactWriteCommand with five Puts (changed 2026-11-03, committed, not yet deployed; before that it wrote only items 1 and 2, in the legacy shape):

  1. The plant item, PLANT#<id>/META, conditional on not existing, in schema v2: every submitted field (address and electricityRate as DynamoDB maps, omitted optional fields absent, not null) plus code, schemaVersion: 2, version: 1, lifecycle: ACTIVE, operatorOrgId = customerOrgId = the caller's personal org, and the GSI1/GSI2/GSI3 keys.
  2. The caller's OWNER membership, USER#<sub>/PLANT#<id>, with the denormalised list fields name, status, timezone and pvCapacityKwp. It stays a legacy membership row, so the app's plant list is unchanged.
  3. The CODE#<code>/GUARD item. If the code is already taken, a fresh code is allocated and the write retried, up to 3 attempts, then 409 CONFLICT.
  4. The customer link PLANT#<id>/CUSTOMER (personal org).
  5. A plant.upserted.v1 outbox row.

This is the same shape npm run migrate:legacy-plants gives an old plant. The stream-router then writes the plant's search tokens and counters, so it appears in search suggestions and the web plant list without a migration. The 201 body is unchanged: it does not include code or version.

The new plant is not made the caller's selectedPlantId (KI-11).

Edge cases​

  • Plants created before the wizard fields were added (2026-09-24) aren't migrated. They keep the old capacityKw number and plain-string address, and have no plantType/countryCode/solarMode/gridConnection (hasBattery is derived, so it is always present). GET endpoints return stored attributes as-is, so a client may see that older shape on such rows. That's why docs/openapi.yaml doesn't list those fields as required on Plant. A client should treat them as optional on read.
  • "Setup Required" isn't a stored status. Screen 12's badge means "no device yet". The server always stores status: ACTIVE. PENDING exists in the enum but nothing sets it.

POST /v1/plants with X-Org-Id: create a plant from the web console​

:::note Status Feature 004, contract C04 web. Verified against packages/api/src/handlers/plants-write.ts and CreatePlantWebInput in packages/core/src/schemas.ts. No captured run is quoted here: every example is illustrative. :::

Sending X-Org-Id selects the web variant. Without the header the request is the mobile create above, which is unchanged.

  • HTTP method: POST
  • Endpoint: /v1/plants
  • Authentication: Cognito ID token (web client), Authorization: Bearer <id token>
  • Authorization: plants permission EDIT or higher in the org named by X-Org-Id. An End User connected to a Business holds plants: VIEW there (RBAC-S11, 2026-11-23), so they get 403 FORBIDDEN; gate Add plant on the plant.create capability in GET /v1/me/context. After creation the plant must fall inside the caller's scope. For example, a TAG-scoped member must include one of their own tags, or the request is 403. Since 2026-11-03 (R-5) a member of a Business on a custom role (the Installer role or a copy) becomes the plant's assigned Installer, so the new plant is inside their access even with an empty scope. See Assigned Installer.
  • Headers: X-Org-Id (required, selects this variant), Idempotency-Key (required, 1-128 chars [A-Za-z0-9_-]), Content-Type: application/json
  • Body: CreatePlantWebInput, strict (unknown keys are rejected with 422)

Request body​

FieldTypeRequiredRules
namestringyes1-120 chars
plantTypeenumyesRESIDENTIAL, COMMERCIAL, INDUSTRIAL (other values → 422 VALIDATION_FAILED)
countryCodestringyesISO 3166-1 alpha-2
addressobjectyesformatted 1-400 (required), city, region up to 120, latitude and longitude (both required)
timezonestringwhen not PKIANA zone; defaults to Asia/Karachi for PK
systemTypeenumyesPV_ONLY, PV_GRID, PV_BATTERY, PV_GRID_BATTERY, GRID_BATTERY, OTHER
gridConnectionenumyesmust agree with systemType (the grid part only — since 2026-11-18 the battery part of systemType is display-only)
exportArrangementenumnoNET_METERING, EXPORT, NO_EXPORT; only when GRID_CONNECTED
gridConnectedOndatenoonly when GRID_CONNECTED
pvCapacityKwpnumberwhen PVrequired for every type except GRID_BATTERY, where it is forbidden
batteries, hasBattery, batteryCapacityKwh, batteryPowerKw, batteryBrand, batteryBrandOtheranynoRetired 2026-11-20: accepted with any value and ignored (never a 422, never stored or sent). Add batteries per device on the TCP server (add_device_battery)
expectedAnnualYieldKwhnumbernogreater than 0
installationobjectnoazimuthDeg integer 0-359, tiltDeg 0-90, selfConsumptionPct integer 0-100
installerOrgIdULIDnothe operator org itself, or an ACTIVE partner with relationship INSTALLER. It grants no access.
commissionedOndatenoat most today + 366 days
financialobjectnocurrency (required if the object is sent), installationCost and subsidyAmount 0 or more
tariffobjectnotariff v2 (tariffType, currency, importRate, exportRate); currency must equal financial.currency when both are sent
customerobjectnoOptional since 2026-11-20. When sent, exactly one of { customerOrgId } or { newCustomer: { name, customerType, business?, city?, contact?: { name, jobTitle, phone (E.164), email } } }. When omitted, the plant has no separate customer: customerOrgId is the Business itself (the X-Org-Id org), no customer link, customer profile, customer plant count or customerName search text is written, the creator owns the plant (ownerUserSub), and the response has no customer field. Attach the end user afterwards by sharing the plant
inviteCustomerbooleanno (false)needs a customer (true without one → 422 VALIDATION_FAILED) and a contact email (new customer) or an email on the existing customer's profile
tagIdsULID[]noup to 20 (more is 422 LIMIT_EXCEEDED), unique, ACTIVE plant tags, not system tags
devicesarraynoup to 20 (more is 422 LIMIT_EXCEEDED) { serial, kind?, connectionMethod? }; serial 3-64 chars [A-Za-z0-9._ -], unique after normalisation. ADR 0012: kind and connectionMethod are optional and display-only (device type lives in TCP). Optional — the 2026-11-20 web flow sends none: create the plant, then over the TCP WebSocket probe the logger with check_logger ({ loggerId, plantId? }) and register it with register_device_web (loggerId + plantId); batteries and other devices are added later, one request at a time
draftIdULIDnoyour draft in this org; deleted in the same transaction

System type to grid/battery mapping: PV_ONLY = off-grid, no battery; PV_GRID = grid-connected, no battery; PV_BATTERY = off-grid with battery; PV_GRID_BATTERY = grid-connected with battery; GRID_BATTERY = grid-connected with battery and no PV; OTHER = any combination. The server derives the mobile solarMode from these, so mobile readers still get a valid value.

The whole body is validated even if the user skipped wizard steps. Show the 422 field errors on the step that owns the field.

Request: illustrative example​

POST /v1/plants
Authorization: Bearer <id token>
X-Org-Id: 01JB5Q0000000000000000000A
Idempotency-Key: 6f1c2a9e-create-plant-1
Content-Type: application/json
{
"name": "Sundar Industrial Estate",
"plantType": "INDUSTRIAL",
"countryCode": "PK",
"address": { "formatted": "Plot 7, Sundar", "city": "Lahore", "region": "Punjab", "latitude": 31.55, "longitude": 74.34 },
"systemType": "PV_GRID",
"gridConnection": "GRID_CONNECTED",
"exportArrangement": "NET_METERING",
"pvCapacityKwp": 860
}

This is the 2026-11-20 web flow: no customer and no devices. After the 201, use the TCP WebSocket: check_logger with { "loggerId": "…", "plantId": "<new plantId>" }, then register_device_web with loggerId + plantId (inverter and logger first; batteries and other devices later, one request each). To give the plant to an end user, share it with POST /v1/orgs/{orgId}/plant-transfers. Sending customer (an existing customer or a newCustomer) and staged devices is still supported.

Response​

201 Created with headers Location: /v1/plants/{plantId} and ETag (the plant's version, e.g. "1"; send it as If-Match on later edits). The body is the plant detail plus:

  • stagedDevices: one entry per sent device, in request order (StagedDevice, see schemas): { serialNorm, serialRaw, kind?, connectionMethod?, state, reason? }. ADR 0012: after the plant commits, each serial is bound to the new plant (a plant ↔ serial binding, the same write as a D02 claim), one device at a time:

    • REGISTERED: bound to this plant.
    • REJECTED + reason: INVALID_SERIAL, ALREADY_REGISTERED (bound to another plant; the owner is never named), PLANT_NOT_BINDABLE, or FORBIDDEN (caller lacks devices EDIT in the plant's org).
    • STAGED: a transient error left it unprocessed; claim it later with D02.

    A rejected device never fails the plant: the response is still 201. Show each rejected row with its reason. The app still registers each bound device with TCP over the WebSocket (app flow). The same list is returned by the workspace (stagedDevices). REGISTERED is this server's binding only. It does not apply TCP's parallel-inverter rule (2026-11-23). When more than one inverter is staged, TCP accepts the second and later ones only with parallel: true and an identical Nexus model. Otherwise TCP refuses with a PARALLEL_* code, and that refusal is the real outcome. Warn the user in the wizard when they stage more than one inverter.

  • customer: { customerOrgId, code, created }. created is true when a new customer was made. Absent when the request had no customer; the plant's customerOrgId is then the Business itself.

  • invitation: present only with inviteCustomer: true, { inviteId, status: "PENDING_DELIVERY" }. No email is sent: the customer sees it in-app (GET /v1/me/invitations). The invitation is created after the plant commits; if that step fails, the plant still exists and invitation is simply absent. Offer a "resend invite" action in that case.

Successful response: illustrative example​

{
"plantId": "01JB5Q00000000000000000001",
"code": "PL-2264",
"name": "Sundar Industrial Estate",
"plantType": "INDUSTRIAL",
"systemType": "PV_GRID",
"lifecycle": "ACTIVE",
"version": 1,
"operatorOrgId": "01JB5Q0000000000000000000A",
"customerOrgId": "01JB5Q0000000000000000000A",
"ownerUserSub": "<creator sub, lower-case>",
"hasBattery": false
}

For the request above (no customer, no devices): no customer and no stagedDevices in the body, and customerOrgId equals operatorOrgId. With customer or devices sent, the body also carries "customer": { "customerOrgId": "…", "code": "CU-1042", "created": true } and one stagedDevices entry per device.

Errors​

StatuscodeWhenWhat the FE should do
401(gateway body)missing or expired tokenrefresh the token and retry
403FORBIDDENplants below EDIT, or the plant would be outside your scopeshow a permission message; for scoped users, ask them to pick one of their tags
404NOT_FOUNDcustomerOrgId, installerOrgId, a tag or draftId not visible in the orgreload the picker lists and let the user choose again
409INVALID_STATEcustomer CHURNED, partner not ACTIVE or not INSTALLER, tag DELETINGreload the picker; show which choice is no longer valid
409IDEMPOTENCY_IN_PROGRESSthe same key is still being processedwait a second and retry with the same key
409CONFLICTtransaction cancelled for an unattributable reasonretry with the same key
413PAYLOAD_TOO_LARGEbody over 256 KBnot reachable with a valid body; report a bug
422VALIDATION_FAILEDa field or cross-field rule, duplicate staged serials, inviteCustomer with no email availableshow field errors on their wizard step
422IDEMPOTENCY_KEY_REUSEDthe same key with a different bodythe body changed: generate a new key and resubmit
422LIMIT_EXCEEDEDmore than 20 tags or devicescap tags and devices at 20 in the UI
428PRECONDITION_REQUIREDno Idempotency-Key (details.header: "Idempotency-Key")always send one; this is a client bug
503DEPENDENCY_UNAVAILABLEDynamoDB throttled or unavailableretry with the same key and backoff

Query-string errors elsewhere in this API are 400; body errors here are 422.

Failure response: missing Idempotency-Key (illustrative)​

{ "error": { "code": "PRECONDITION_REQUIRED", "message": "Idempotency-Key header is required", "details": { "header": "Idempotency-Key" } } }

Edge cases​

  • Idempotent replay, same key and same body: you get the original 201 body again with Idempotent-Replayed: true. No second plant or customer is made. A replay rebuilds the response from the stored plant, so it omits invitation even if the original response had one; keep the invitation from the first response. Create the key once when the user presses Create, and reuse it for every retry of that submission (timeouts, network drops).
  • Same key, different body: 422 IDEMPOTENCY_KEY_REUSED. If the user edits the form after a failed submit, generate a new key.
  • Double click or concurrent duplicates: exactly one plant is created; the others get the replay or 409 IDEMPOTENCY_IN_PROGRESS.
  • New customer: the customer org, its CU-NNNN profile and the plant are written in one transaction. Nothing is left half-created on failure.
  • Plant code PL-NNNN is assigned when a web create commits and never changes afterwards. Plants created from the mobile app have no code until they are migrated or first edited on the web; treat code as optional on read.
  • Eventual consistency: the plant list, summary counts and search update from the change stream a moment after the 201. Navigate to the detail page by plantId rather than refetching the list.
  • Large payloads: the API Gateway body limit is 256 KB (413). A valid create body is far smaller.

Plant drafts (/v1/plant-drafts): save the wizard and finish later​

:::note Deployed Feature 004 (contract C15). Live on dev (verified 2026-10-13). Examples are illustrative, not captured runs. :::

A draft holds a partial web create body. Drafts are private to their author, scoped to the X-Org-Id org, and expire 30 days after the last save. A user can hold at most 50 drafts per org.

All routes need the web ID token and X-Org-Id. Creating and submitting need plants EDIT or higher in that org.

OperationMethod and pathExtra headersSuccess
CreatePOST /v1/plant-draftsIdempotency-Key (required)201 summary, Location, ETag
ListGET /v1/plant-drafts?limit=&cursor=none200 { items, nextCursor? }
GetGET /v1/plant-drafts/{draftId}none200 summary + body, ETag
ReplacePUT /v1/plant-drafts/{draftId}If-Match (required)200 summary, expiry reset
DeleteDELETE /v1/plant-drafts/{draftId}none204
SubmitPOST /v1/plant-drafts/{draftId}:submitIdempotency-Key and If-Match (required)201 as web create

Create/replace body: { body, lastStep? }. body is a partial CreatePlantWebInput: every field optional, nested objects partial, unknown keys rejected, at most 64 KB serialised. lastStep is 1-6, the wizard step to reopen on.

Summary: { draftId, orgId, title, lastStep, version, expiresAt, updatedAt }. title comes from the draft's name.

Submit: an optional body of CreatePlantWebInput fields is merged over the stored draft. The result is validated as a full create, then the plant is created and the draft deleted in one transaction. The response and errors are the web create's.

Create: illustrative example​

// request: POST /v1/plant-drafts (X-Org-Id, Idempotency-Key)
{ "body": { "name": "Sundar Industrial Estate", "plantType": "INDUSTRIAL" }, "lastStep": 2 }

// 201 response
{ "draftId": "01JB5D00000000000000000001", "orgId": "01JB5Q0000000000000000000A", "title": "Sundar Industrial Estate",
"lastStep": 2, "version": 1, "expiresAt": "2026-11-11T10:00:00.000Z", "updatedAt": "2026-10-12T10:00:00.000Z" }

Errors​

StatuscodeWhenWhat the FE should do
400ORG_CONTEXT_REQUIREDno X-Org-Idsend the active org
400INVALID_CURSORlist cursor malformed or from another queryrestart the list without a cursor
403FORBIDDENplants below EDIT (create, submit)hide "Save as draft"
404NOT_FOUNDunknown, expired, already submitted, or another user's draftremove it from the list and refetch
409VERSION_CONFLICTIf-Match is stale (details.currentVersion)GET the draft again, merge or ask the user, resend with the new ETag
413PAYLOAD_TOO_LARGErequest over 256 KB, or a draft body over 64 KB serialisedtell the user the draft is too large
422VALIDATION_FAILEDunknown key or bad partial field; on submit, the merged body is incompleteon submit, open the wizard on the step with the error
422LIMIT_EXCEEDEDalready 50 drafts in this orgask the user to delete old drafts
428PRECONDITION_REQUIREDmissing Idempotency-Key or If-Match (details.header)client bug: always send them

Submit also returns every web create error above.

Edge cases​

  • If-Match: send the ETag from the last response (the quoted version, e.g. "2") as If-Match on replace and submit. Missing is 428. Two tabs editing one draft: the second save gets 409 VERSION_CONFLICT.
  • Idempotent create and submit: same key and same body replays the original 201; same key and different body is 422 IDEMPOTENCY_KEY_REUSED.
  • Second submit: the draft is gone after a successful submit, so a later submit with a new key is 404. A retry with the original key replays the created plant.
  • Expiry: each save resets the 30-day clock. An expired draft is 404 and disappears from the list (DynamoDB TTL can lag up to a few days; the server hides expired drafts on read).
  • Delete is naturally idempotent: deleting a missing draft still returns 204.
  • Privacy: other users in the org, including admins, never see your drafts.

GET /v1/plants/{plantId} — Plant detail​

Purpose: Full detail for one plant, including the caller's own role.

  • HTTP method: GET
  • Endpoint: /v1/plants/{plantId}
  • Authentication: Required
  • Authorization: Caller must have plants ≥ VIEW, evaluated through the canonical access evaluator (packages/core/src/access/evaluator.ts) — for a legacy single-owner plant this is satisfied by the caller's OWNER/ ADMIN/VIEWER access-index role, same as before 003 (FR-058)
  • Crown staff: a Super Admin or Administrator (an ACTIVE membership of the Crown platform org, scope ALL) passes for every plant, with no membership in the plant's own org (evaluator.ts, the PLATFORM access path).

:::tip Opening a plant after a device import When the app registers, imports or looks up a device over the TCP WebSocket (register_device_web, import_devices, check_serial), the reply carries the device's plantId. The app opens the plant by calling this endpoint with that id. No other HTTP call is involved: devices and device favourites are TCP-only. The full mobile flow is in the TCP Server's device import and favourites mobile guide. :::

Request​

Headers: Authorization: Bearer <token> (required).

Path parameters:

ParamTypeRequired
plantIdstringYes

Query parameters: none. Request body: none.

Response​

Plant, plus role (the caller's role on this plant, read from their membership item). Unlike the list endpoint, this returns every stored plant field (address, solar, grid, tariff, battery).

DynamoDB calls (changed by feature 003, response unchanged — FR-058): in parallel, the evaluator's loadAccessFacts query for the caller plus a GetItem on the caller's legacy access-index role; then GetItem on PLANT#<id>/META. Before 003 this was a single GetItem on the membership item.

Successful response — illustrative example​

{
"plantId": "01J9Z4A1B2C3D4E5F6G7H8J9K0",
"name": "Ghori Residence",
"plantType": "RESIDENTIAL",
"countryCode": "PK",
"address": { "formatted": "Karachi, Sindh, Pakistan", "city": "Karachi", "region": "Sindh" },
"timezone": "Asia/Karachi",
"solarMode": "SELF_CONSUMPTION",
"pvCapacityKwp": 10,
"gridConnection": "GRID_CONNECTED",
"electricityRate": { "amountPerKwh": 65, "currency": "PKR" },
"hasBattery": true,
"status": "ACTIVE",
"role": "OWNER",
"createdAt": "2026-08-01T05:30:00.000Z",
"updatedAt": "2026-08-01T05:30:00.000Z"
}

Failure response — authorization / not-found failure (illustrative)​

{ "error": { "code": "FORBIDDEN", "message": "You do not have access to this plant" } }

:::note 403, not 404, for "doesn't exist" This endpoint deliberately returns 403 FORBIDDEN both when plantId belongs to a plant the caller has no membership on and when plantId doesn't exist at all — the membership check runs first and fails identically either way. This avoids leaking "that ID exists but isn't yours" versus "that ID doesn't exist" to a caller probing IDs. (404 NOT_FOUND is only possible on the narrower path where the caller does have a membership record but the plant's own metadata item is somehow missing — an internal consistency fault, not a normal client-facing case.) :::

Failure response — auth failure (illustrative)​

API Gateway's own body, not this API's envelope (see API overview → Gateway responses):

{ "message": "Unauthorized" }

HTTP status codes​

StatuscodeWhen
200—Success
401— (gateway body)Missing/invalid token
403FORBIDDENNo membership on plantId (covers both "not yours" and "doesn't exist")
404NOT_FOUNDCaller has a membership record but the plant metadata item itself is missing (internal consistency fault). Body: {"error":{"code":"NOT_FOUND","message":"Plant not found"}}
500INTERNALUnexpected server error

Web variant: GET /v1/plants/{plantId} with X-Org-Id (C05)​

:::note Deployed This variant is deployed on dev. The DynamoDB key fix for legacy (mobile-created) plants (previously 500) is deployed to dev 2026-10-13; not yet re-verified with a signed-in call. Every example here is illustrative, derived from PlantDetail / PlantDetailResponse in packages/core/src/schemas.ts and from getPlantById in plants-read.ts. :::

Sending X-Org-Id selects this variant. The mobile response above does not change.

  • Authorization: plants VIEW or higher, checked against the caller's live access (never taken from the token).
  • Response 200: PlantDetailResponse, which is a PlantDetail plus refs (display names for org and tag ids). Headers include ETag: "<version>". Store that value and send it back as If-Match on PATCH.
  • PlantDetail (and the workspace plant) also carries installedBy? and assignedInstaller? (R-5), except for a caller whose only access is a low external tier (the same rule that hides financial and installation).
  • installer? { orgId, name } (2026-11-27, owner decision): this is what every console "Installer" field shows. It is the plant's Business, meaning operatorOrgId and that org's name, because the installer acts for the Business. It is absent when the plant has no Business (an End User's personal org, or an org that cannot be resolved); the console shows "-" then. Returned on this detail and on the workspace plant. The console no longer displays assignedInstaller or installedBy; both fields are still sent unchanged. TCP rows (list_plants, inventory, devices) should follow the same rule: operatorOrgId plus its org.upserted.v1 name, absent when personal.
  • PlantDetail contains every Plant field plus code, version, schemaVersion, lifecycle, operatorOrgId, customerOrgId, installerOrgId?, tagIds, regionTagId?, systemType?, exportArrangement?, gridTopology, gridConnectedOn?, expectedAnnualYieldKwh?, installation?, commissionedOn?, financial?, deviceCount?, archivedAt? and needsCompletion?.
  • Legacy plants (plants the mobile app created before mobile create wrote schema v2, 2026-11-03) are mapped when read. They report version: 0 and a needsCompletion list of the wizard fields still missing. Show a "complete this plant" prompt, then save with If-Match: "0".
  • Redaction: when the caller's only access is external VIEW/MONITOR (a customer portal or a share), the response has no financial and no installation.
// illustrative example (abbreviated)
// ETag: "4"
{ "plantId": "01JB…", "name": "Sundar Mills Roof", "code": "PL-0042", "version": 4, "schemaVersion": 2,
"lifecycle": "ACTIVE", "operatorOrgId": "01JA…", "customerOrgId": "01JC…", "tagIds": ["01JT…"],
"timezone": "Asia/Karachi", "pvCapacityKwp": 250, "gridTopology": { "phases": 3 },
"refs": { "orgs": { "01JC…": { "name": "Sundar Textiles" } }, "tags": { "01JT…": { "label": "Punjab" } } } }
StatuscodeWhenWhat the FE should do
200—OKcache the ETag for editing
403FORBIDDENthe plant is visible but plants access is below VIEWshow a permission message
404NOT_FOUNDunknown id, or no access path at all. The web variant never reveals whether the plant existsshow "not found"
410GONEplant DELETING or deleted (details.lifecycle)remove it from lists; show "deleted"

GET /v1/plants/{plantId}/workspace: Plant Workspace in one call (C06)​

:::note Deployed Deployed on dev (verified 2026-10-13). The DynamoDB key fix for legacy (mobile-created) plants (previously 500) is deployed to dev 2026-10-13; not yet re-verified with a signed-in call. Illustrative only. The shape comes from WorkspaceResponse in packages/core/src/schemas.ts. :::

  • Method / endpoint: GET /v1/plants/{plantId}/workspace
  • Auth: Cognito ID token. X-Org-Id is optional because the org is taken from the plant. Requires plants VIEW or higher.
  • Response 200: WorkspaceResponse plus an ETag header (the plant's version). It contains:
    • plant and refs, as in the web detail. plant is the whole plant record: name, status, timezone, address, pvCapacityKwp, plant type, grid/battery fields, tariff (electricityRate) and everything else in PlantDetail, so a page that has the workspace does not also need GET /v1/plants/{plantId}. Since 2026-11-17 plant.role is also set: the same OWNER/ADMIN/VIEWER the mobile detail reports (the caller's mobile membership role, else VIEWER).
    • viewer.levels and viewer.capabilities, a subset of plant.edit, plant.archive, plant.delete, plant.tag, plant.share, alertRules.edit, tariff.edit, access.request, service.create and device.register. Use capabilities to show or hide buttons. Every write still re-checks permission.
    • isFavorite: whether the caller starred the plant (PUT /v1/me/favorites/PLANT/{id}). It reads the same item that call writes, so it is correct for every plant, including unmigrated mobile plants (covered by a unit test, 2026-11-17).
    • registry: ADR 0012 — source is always BINDINGS (the plant ↔ serial bindings). devices[] rows are { serial?, label?, createdAt } (up to 200; serial left out for external VIEW/MONITOR callers) and truncated. Device detail and status come from TCP.
    • stagedDevices.
    • settings: alertRules (defaults with version: 0 if never saved), tariff (or null) and shareLink (active, linkId?, expiresAt?). The share-link token is never returned.
    • access: customerPortalLevel?, installerOrgId? and shareCount.
    • counts.openWorkOrders: null until the feature that owns it ships.
  • Redaction: below plants EDIT, the response has no stagedDevices, settings or access. Device serials are left out for external VIEW/MONITOR callers. plant.delete appears only for Crown platform members with plants FULL.
  • Errors: same as the web detail (403, 404, 410), plus 401.
// illustrative example (abbreviated)
{ "plant": { "plantId": "01JB…", "code": "PL-0042", "version": 4, "name": "Sundar Mills Roof", "status": "ACTIVE",
"timezone": "Asia/Karachi", "pvCapacityKwp": 250, "role": "VIEWER",
"address": { "formatted": "Plot 7, Sundar", "city": "Lahore" } },
"refs": { "orgs": {}, "tags": {} },
"viewer": { "levels": { "plants": "MANAGE" }, "capabilities": ["plant.edit", "plant.archive", "plant.tag"] },
"isFavorite": false,
"registry": { "source": "BINDINGS", "devices": [], "truncated": false },
"stagedDevices": [], "settings": { "alertRules": { "version": 0 }, "tariff": null, "shareLink": { "active": false } },
"access": { "shareCount": 0 }, "counts": { "openWorkOrders": null } }

PATCH /v1/plants/{plantId} — Edit plant settings (mobile)​

Purpose: Saves edits from the mobile Plant Settings screen. Send only the fields that changed. Built separately from the web console's planned edit (roadmap C07: If-Match, full web plant detail), which will extend this same route for organisation-managed plants.

  • HTTP method: PATCH
  • Endpoint: /v1/plants/{plantId}
  • Authentication: Required
  • Authorization: plants ≥ EDIT through the access evaluator. On a mobile-created plant that means the caller's role is OWNER or ADMIN. A VIEWER gets 403.
  • Idempotency: No Idempotency-Key and no If-Match. Sending the same edit twice gives the same result.

Request​

Headers:

HeaderRequiredNotes
Authorization: Bearer <token>Yes
Content-Type: application/jsonYesThis is a strict route. Any other value is 415 UNSUPPORTED_MEDIA_TYPE. Dart's http package sends text/plain unless you set it.

Path parameters:

ParamTypeRequired
plantIdstringYes

Body: an object with at least one of these fields. Each follows the same rule as on create.

Screen rowField(s)TypeRules
Plant Namenamestring1–120 characters, trimmed
Plant TypeplantTypeenumRESIDENTIAL, COMMERCIAL, INDUSTRIAL (other values → 422 VALIDATION_FAILED)
Locationaddressobjectformatted ≤ 400, city ≤ 120, region ≤ 120, latitude + longitude sent together. Replaced whole: send the full new address, not one part of it
LocationcountryCodestringISO 3166-1 alpha-2 (PK), case-insensitive
LocationtimezonestringIANA name (Asia/Karachi). Required when countryCode changes to a country other than PK. Changing to PK without one sets Asia/Karachi
PV CapacitypvCapacityKwpnumber> 0, ≤ 100000
Solar UsagesolarModeenumNONE, SELF_CONSUMPTION, GRID_EXPORT, SELF_CONSUMPTION_GRID_EXPORT
Grid ConnectiongridConnectionenumGRID_CONNECTED, OFF_GRID
Battery Storagebatteries, hasBattery, batteryCapacityKwh, batteryPowerKw, batteryBrand, batteryBrandOtheranyNot editable here (2026-11-18). Accepted and ignored (any value, never a 422). A body with only these fields is a valid no-op (200). Every edit also removes old stored values. Edit the battery on the TCP server over the WebSocket. Since 2026-11-20 create ignores them too (after create).
Electricity RateelectricityRateobject{ amountPerKwh ≥ 0, currency: 3-letter ISO 4217 }. Replaced whole

The Devices row is not editable here; use the devices routes.

Behaviour to build the client against:

  • null or "" means "not sent", as on create. It never clears a value. A body where every field is null is a 422 ("at least one field is required").
  • Clearing happens through the switch, not the value. solarMode: "NONE" removes the stored pvCapacityKwp. Sending the value together with that switch is a 422, the same as on create.
  • hasBattery in the response is derived (2026-11-18): true when a device bound to the plant has a battery on the TCP server.
  • Cross-field rules run on the merged plant, not just the body. For example, sending only gridConnection: "OFF_GRID" is a 422 when the stored solarMode exports. Sending only solarMode: "SELF_CONSUMPTION" on a plant with no solar is a 422 unless pvCapacityKwp is sent too.
  • Unknown fields, and server-owned fields such as status or plantId, are 422.
  • plantType accepts only RESIDENTIAL, COMMERCIAL, INDUSTRIAL (anything else → 422). A plant still storing a retired UTILITY/OTHER is returned as INDUSTRIAL/COMMERCIAL, the same as on GET.

Plants created before 2026-09-24 have no plantType, countryCode, solarMode or gridConnection. They store capacity as capacityKw and the address as a plain string. Editing them works:

  • A cross-field rule runs only once the fields it compares exist, so a rename never fails because the wizard fields are missing.
  • The stored capacityKw counts as pvCapacityKwp (for the rules and in the response), and a string address is returned as { "formatted": "…" }. Neither is rewritten unless the request changes it.
  • Writing or clearing pvCapacityKwp deletes the old capacityKw, so the two can't disagree.
  • Setting solarMode to anything other than NONE on such a plant needs pvCapacityKwp in the same request when no capacity is stored at all.

Request — illustrative example​

{ "name": "Rooftop", "electricityRate": { "amountPerKwh": 55, "currency": "PKR" } }

Response​

200 OK with the whole updated plant, in the same shape as GET /v1/plants/{plantId} (including the caller's role). Replace the screen's state with it.

A new name, timezone or pvCapacityKwp also updates every member's GET /v1/plants row in the same write, so the plant list shows it right away.

DynamoDB calls (packages/core/src/plants/repository.ts updatePlant): evaluator access load; consistent GetItem on PLANT#<id>/META; a GSI1 query GSI1PK = PLANT#<id>, begins_with(GSI1SK, USER#) for the members' access-index rows; then one TransactWriteItems that updates META (on the condition that updatedAt is unchanged since the read) and every member's row. A plant with more than 99 members spills into further transactions; a mobile plant in practice never has that many.

Successful response — illustrative example​

{
"plantId": "01J9Z4A1B2C3D4E5F6G7H8J9K0",
"name": "Rooftop",
"plantType": "RESIDENTIAL",
"countryCode": "PK",
"address": { "formatted": "Karachi, Sindh, Pakistan", "city": "Karachi", "region": "Sindh" },
"timezone": "Asia/Karachi",
"solarMode": "SELF_CONSUMPTION",
"pvCapacityKwp": 6,
"gridConnection": "GRID_CONNECTED",
"electricityRate": { "amountPerKwh": 55, "currency": "PKR" },
"hasBattery": true,
"status": "ACTIVE",
"role": "OWNER",
"createdAt": "2026-08-01T05:30:00.000Z",
"updatedAt": "2026-10-09T07:10:00.000Z"
}

Failure response — rule broken on the merged plant (illustrative)​

{
"error": {
"code": "VALIDATION_FAILED",
"message": "Request validation failed",
"details": { "formErrors": [], "fieldErrors": { "solarMode": ["an OFF_GRID plant cannot use an exporting solar mode"] } }
}
}

Failure response — viewer (illustrative)​

{ "error": { "code": "FORBIDDEN", "message": "You do not have permission to edit this plant" } }

Failure response — concurrent edit (illustrative)​

{ "error": { "code": "CONFLICT", "message": "This plant was changed at the same time; reload it and try again" } }

HTTP status codes​

StatuscodeWhen
200—Updated
400MALFORMED_REQUESTBody isn't valid JSON, or isn't a JSON object
401— (gateway body)Missing or invalid token
403FORBIDDENThe caller can see the plant but is a VIEWER
404NOT_FOUNDNo access to the plant, or it doesn't exist (unlike GET's 403)
409CONFLICTAnother edit to this plant landed at the same moment, or a member was removed mid-write. Message: "This plant was changed at the same time; reload it and try again". Reload and retry. A 409 CONFLICT with a generic message can also come from DynamoDB throttling the write transaction (shared classifier); a retry is safe
409INVALID_STATEOrganisation-managed (web) plant: a schema v2 plant that is not the caller's own personal plant, or one that is ARCHIVED/DELETING. Edit it through the web console instead. Exception (2026-10-29, not yet deployed): the caller's own migrated plant (v2, ACTIVE, operator and customer org = the caller's personal org) is editable here; the edit goes through the web edit logic, so it bumps version and keeps search keys and the customer link in step
413PAYLOAD_TOO_LARGEBody over 256 KB
415UNSUPPORTED_MEDIA_TYPEContent-Type isn't application/json
422VALIDATION_FAILEDEmpty body, unknown field, a per-field rule, or a cross-field rule on the merged plant
500INTERNALUnexpected server error
503DEPENDENCY_UNAVAILABLEDynamoDB throttled or unavailable. Resending the same edit is safe

Executions: none captured signed in. The route is deployed on dev: a no-token call returns 401 (probe 2026-11-03). The examples above are illustrative, taken from the handler and core code.

Web variant: PATCH /v1/plants/{plantId} with X-Org-Id (C07)​

:::note Deployed on dev Routed on dev: PATCH with no token returns 401 (probe 2026-11-03). Not yet run signed in, so the examples are illustrative. The body is UpdatePlantWebInput and the logic is in packages/core/src/plants/patch.ts. The mobile contract above does not change, and the mobile variant ignores If-Match. :::

  • Authorization: plants EDIT or higher. Changing customerOrgId also needs customers EDIT in the operator org. An End User connected to a Business holds plants: VIEW on its plants (RBAC-S10, 2026-11-23): 403 FORBIDDEN, and the workspace viewer.capabilities carry no plant.edit, tariff.edit, alertRules.edit or plant.share for them.
  • Headers: X-Org-Id and If-Match: "<version>" are required. Take the version from the ETag of the last GET, workspace or PATCH. Send "0" for a legacy plant. Content-Type: application/json.
  • Body: strict JSON merge with at least one field. Leaving a field out keeps it. Setting it to null clears it, which is allowed only for exportArrangement, gridConnectedOn, pvCapacityKwp, expectedAnnualYieldKwh, installation, installerOrgId, commissionedOn and financial. The non-nullable fields are name, plantType, countryCode, address, timezone, systemType, gridConnection and customerOrgId. Server-owned fields (code, version, lifecycle, operatorOrgId, and so on) and unknown keys are rejected. The retired battery fields (hasBattery, batteryPowerKw, batteryCapacityKwh, 2026-11-18) are the exception: accepted and ignored, and the edit removes any stored copies. Cross-field rules are re-checked on the merged plant.
  • Response 200: PlantDetailResponse with a new ETag.
  • Side effects:
    • Renaming updates the customer, installer and tag links and the search tokens. Each user's copy in their plant list is updated in the same write when there are 25 or fewer; above that, they update shortly afterwards.
    • Changing the region swaps the system region tag.
    • Changing the customer, region or country writes an access-log entry recording who gains or loses visibility.
    • A legacy plant is rewritten to schema v2 and given a PL- code.
    • Emits plant.upserted.v1.
// illustrative request
// PATCH /v1/plants/01JB… X-Org-Id: 01JA… If-Match: "4"
{ "name": "Sundar Mills Roof A", "installerOrgId": null }
StatuscodeWhenWhat the FE should do
200—updatedreplace the cached plant and ETag
400MALFORMED_REQUESTinvalid JSON or a malformed If-Matchclient bug
403FORBIDDENbelow plants EDIT, or customers EDIT missing for a customer changehide the edit control
404NOT_FOUNDthe plant is not visibleshow "not found"
409VERSION_CONFLICTstale If-Match (details.currentVersion)reload, show the latest values, let the user re-apply
409INVALID_STATEplant ARCHIVED, customer CHURNED, or the partner is not an INSTALLERrestore first, or pick another customer or partner
409INVALID_STATE (details.reason: CUSTOMER_LINK_MISSING)a rename found the plant's customer link row missing mid-write (2026-11-30, BE-1). Before this fix, renaming a Business plant with no separate customer always failed with 409 CONFLICT; such a plant now renames normallyretrying will not help; report it
410GONEplant DELETINGremove it from lists
422VALIDATION_FAILEDfield or cross-field rule, server-owned field, null on a required field, empty bodyshow field errors
428PRECONDITION_REQUIREDno If-Match (details.header: "If-Match")always send it; client bug
// illustrative 409
{ "error": { "code": "VERSION_CONFLICT", "message": "…", "details": { "currentVersion": 5 } } }

Plant tags (C12)​

Attach and remove tags on one plant, or on many plants at once. Tags are managed in the Tags API. Tagging can change who sees a plant: members with a TAG scope gain or lose access when a tag is added or removed, so every change is written to the access log with the number of members affected.

:::caution Code-complete, not yet captured against a real deployment As of 2026-10-13 these routes are in lib/routes.ts (AttachPlantTag, DetachPlantTag, PlantsCollectionAction, GetPlantJob). No execution has been captured; the examples are illustrative, derived from the schemas and handlers. :::

PUT /v1/plants/{plantId}/tags/{tagId} and DELETE /v1/plants/{plantId}/tags/{tagId}​

  • Auth: Cognito access token. AuthZ: plants ≥ EDIT on that plant.
  • Headers: none extra. No If-Match and no Idempotency-Key: both calls are naturally idempotent. Attaching a tag that is already there, or removing one that isn't, returns 200 with the current state.
  • Each real change bumps the plant version, updates tag counts and search, and publishes plant.upserted.v1.

Response 200 (with ETag):

{ "tagIds": ["01JB0000000000000000000T01"], "version": 8,
"impact": { "membersGaining": 1, "membersLosing": 0 } }

impact counts members whose TAG scope starts (membersGaining) or stops (membersLosing) covering this plant. approximate: true appears when the org has more members than one scan reads; treat the numbers as a lower bound.

StatuscodeWhenWhat the FE should do
401— (gateway body)Missing/expired tokenRefresh token, retry
403FORBIDDENplants below EDIT on this plantHide "Add tag"
404NOT_FOUNDPlant or tag not found, or you have no access to the plant (non-members get 404, not 403)Refresh
409INVALID_STATEPlant created by the mobile app and never saved on the webAsk the user to open and save it on the web first
409INVALID_STATESystem REGION tag, tag is DELETING, or plant is ARCHIVEDExplain; REGION tags follow the address
409CONFLICTConcurrent change to the plantRetry
410GONEPlant is being deletedRemove it from the view
422LIMIT_EXCEEDEDThe plant would have more than 20 tags (PUT)Ask the user to remove one first
422VALIDATION_FAILEDTag's appliesTo doesn't include PLANTOffer only plant tags
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEServer / DynamoDBRetry (safe: idempotent)

POST /v1/plants:bulk-tag: add or remove tags on many plants​

Deployed as POST /v1/{collection} with the colon-verb in the path segment; call it exactly as POST /v1/plants:bulk-tag. Any other collection or verb is 404.

  • AuthZ: plants ≥ EDIT, checked plant by plant.
  • Headers: X-Org-Id (required), Idempotency-Key (required), Content-Type: application/json.
Body fieldTypeRules
addULID[]1–10 tag ids
removeULID[]1–10 tag ids; none may also be in add
plantIdsULID[]1–200
filterobjectThe web plant-list filters (as in GET /v1/plants with X-Org-Id), for "Select all N matching"

Send at least one of add/remove, and exactly one of plantIds/filter.

Up to 50 plantIds run immediately. Response 200 with one result per plant; a plant you can't edit or that is archived is an item with ok: false, not a failed request:

{ "results": [
{ "plantId": "01JB00000000000000000000P1", "ok": true },
{ "plantId": "01JB00000000000000000000P2", "ok": false, "error": { "code": "FORBIDDEN" } } ] }

More than 50 ids, or a filter, become a background plant job. Response 202 with a Location header:

{ "jobId": "01JB00000000000000000000J1", "status": "QUEUED", "links": { "self": "/v1/plant-jobs/01JB00000000000000000000J1" } }

:::warning Large bulk jobs need infrastructure that is not live yet Plant jobs need the plant-jobs SQS queue, which only exists when the API stack is deployed with -c busEnabled=true. Without it, a job-sized request fails 503 DEPENDENCY_UNAVAILABLE with details.dependency: "plant-jobs" and nothing is changed. Tell the user to select 50 plants or fewer. Even with the queue deployed, no worker is connected to it yet (owner decision pending), so accepted jobs stay QUEUED. :::

Replaying the same Idempotency-Key returns the same result or the same jobId.

StatuscodeWhenWhat the FE should do
400ORG_CONTEXT_REQUIREDNo X-Org-IdSend the active org
400MALFORMED_REQUESTBody not JSONFix the client
404NOT_FOUNDPath is not plants:bulk-tag; a tag id in add/remove doesn't exist in the org (details.tagId); or you aren't a member of X-Org-IdFix the URL / refresh the tag picker / switch org
409INVALID_STATEA system REGION tag in add/remove, or a tag in add is DELETING (details.tagId)Remove it from the picker
409IDEMPOTENCY_IN_PROGRESSSame key still processingRetry later with the same key
415UNSUPPORTED_MEDIA_TYPENo JSON content typeFix the client
422LIMIT_EXCEEDEDMore than 200 plantIds or more than 10 tag ids (details.limit, details.field)Split the selection or use filter
422VALIDATION_FAILEDNeither add nor remove; both or neither of plantIds/filter; a tag in both lists; a tag in add whose appliesTo lacks PLANT (details.tagId)Fix the body; offer only plant tags
422IDEMPOTENCY_KEY_REUSEDSame key, different bodyNew key per new action
428PRECONDITION_REQUIREDNo Idempotency-KeyAlways send one
503DEPENDENCY_UNAVAILABLEJob-sized request with no plant-jobs queue (details.dependency: "plant-jobs"), or DynamoDB unavailableFor plant-jobs: limit to 50 plants. Otherwise retry with backoff

GET /v1/plant-jobs/{jobId}: poll a bulk job (C12b, proposed)​

:::note Proposed contract The shape may still change. :::

  • AuthZ: the user who started the job, or plants ≥ MANAGE in the job's org. Anyone else gets 404. X-Org-Id is optional and never widens access.
  • Query: limit (1–50, default 25) and cursor page through failures.
{ "jobId": "01JB00000000000000000000J1", "kind": "BULK_TAG", "status": "PARTIALLY_SUCCEEDED",
"counts": { "matched": 120, "succeeded": 118, "failed": 2, "skipped": 0 },
"startedAt": "2026-10-13T10:00:01.000Z", "finishedAt": "2026-10-13T10:00:09.000Z",
"failures": { "items": [ { "plantId": "01JB00000000000000000000P2", "errorCode": "FORBIDDEN" } ] } }

status is one of QUEUED, RUNNING, SUCCEEDED, PARTIALLY_SUCCEEDED, FAILED. Poll every few seconds until it's not QUEUED/RUNNING. Today jobs stay QUEUED (see the warning above), so stop polling after a while.

Errors: 400 VALIDATION_FAILED / INVALID_CURSOR, 401, 404 NOT_FOUND, 500, 503.


Plant settings (C08, C09)​

Both routes are on the Plant Workspace Settings tabs. Each replaces the whole settings item: send every field you want kept.

  • Auth: a Cognito access token. X-Org-Id is optional. Access is checked on the plant itself, and the header never widens it.
  • Headers: If-Match (required, else 428), Content-Type: application/json. No Idempotency-Key.
  • Versioning: If-Match is the settings item's version, not the plant's. The workspace (GET /v1/plants/{plantId}/workspace) returns settings.alertRules.version, which is 0 when nothing has been saved yet. Send If-Match: "0" to create. The response ETag is the new settings version. Every save also bumps the plant's own version, so re-read the plant ETag before a later PATCH.
  • Archived plants are read-only: 409 INVALID_STATE.

PUT /v1/plants/{plantId}/settings/alert-rules: alert rules (C08)​

  • AuthZ: alerts ≥ MANAGE.
FieldTypeRules (default)
underperformance.enabledboolean(true)
underperformance.thresholdPctinteger5–90 (25)
underperformance.windowMininteger30–720 (120)
communicationLoss.enabledboolean(true)
communicationLoss.afterMininteger5–1440 (30)
batteryTemperature.enabledbooleanDefaults to the plant's derived hasBattery (a bound device has a battery on the TCP server, 2026-11-18). true on a plant without one is 422.
batteryTemperature.maxCnumber20–80 (45)
notifyEmailboolean(true)
escalateCriticalSmsboolean(false)

Every field is optional. An omitted field gets its default, and unknown fields are 422. Response 200, illustrative:

{ "version": 1,
"underperformance": { "enabled": true, "thresholdPct": 30, "windowMin": 120 },
"communicationLoss": { "enabled": true, "afterMin": 30 },
"batteryTemperature": { "enabled": false, "maxC": 45 },
"notifyEmail": true, "escalateCriticalSms": false, "updatedAt": "2026-10-13T08:00:00.000Z" }

The new rules are published to the TCP side (plant.alert-rules.updated.v1), which evaluates alarms. This API does not raise alarms itself.

PUT /v1/plants/{plantId}/settings/tariff: tariff and billing (C09)​

  • AuthZ: plants ≥ EDIT (so never a connected End User, RBAC-S10).
FieldTypeRules
currencystringISO 4217, required (upper-cased)
tariffTypeenumFLAT | TIME_OF_USE | NET_METERING | NET_BILLING, required
importRatenumber0–100 000. Required unless TIME_OF_USE
exportRatenumber0–100 000. Required for NET_BILLING. Rejected on an OFF_GRID plant
touSchedule[]object[]TIME_OF_USE only (and required there). 1–24 periods {days: MON..SUN[] (unique, ≥1), start "HH:MM", end "HH:MM" after start or "24:00", rate 0–100 000}. On every day, periods must not overlap and must cover 00:00–24:00.
assumptions.degradationPctPerYearnumber0–5 (0.5)
assumptions.tariffEscalationPctPerYearnumber0–50 (4)
effectiveFromstringYYYY-MM-DD, optional

Response 200: the stored tariff plus version (and updatedAt). In the same transaction the plant's electricityRate (what the mobile app reads) is set to {amountPerKwh, currency}. amountPerKwh is importRate, or the highest TOU rate for TIME_OF_USE. A plant.upserted.v1 event follows.

Errors (both routes)​

StatuscodeWhenWhat the FE should do
400MALFORMED_REQUESTBody is not a JSON object, or If-Match is not a versionFix the request
401— (gateway body)Missing/expired tokenRefresh and retry
403FORBIDDENalerts < MANAGE (C08) / plants < EDIT (C09)Hide the Save button (use workspace viewer.capabilities)
404NOT_FOUNDUnknown plant or no access pathLeave the workspace
409VERSION_CONFLICTStale If-Match (details.currentVersion)Re-fetch the workspace, re-apply, re-submit
409INVALID_STATEPlant is ARCHIVED, or a legacy plant never saved on the webShow "restore first" / "complete the plant first"
409CONFLICTThe plant changed at the same momentRetry once
410GONEPlant is being deleted or was deletedLeave the workspace
415UNSUPPORTED_MEDIA_TYPEMissing Content-Type: application/jsonSend the header
422VALIDATION_FAILEDBounds, unknown field, battery rule, exportRate on OFF_GRID, NET_BILLING without exportRate, TOU overlap/gap (see below), touSchedule outside TIME_OF_USEShow details.fieldErrors next to the fields
428PRECONDITION_REQUIREDNo If-MatchSend "0" (first save) or the current version
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLEUnexpected / DynamoDBRetry with backoff

Edge cases: two saves sent at once on the same version: one wins, the other gets 409 VERSION_CONFLICT. A second "0" create after a successful one is also VERSION_CONFLICT. Saving settings does not need X-Org-Id.

Time-of-use 422 messages (PUT …/settings/tariff; issue #17 R-3, written 2026-11-13, not committed or deployed yet). Every day with a problem is reported, not only the first. Each problem is one string in details.fieldErrors.touSchedule, starting with the day, so the editor can show it next to that day. Period numbers are positions in touSchedule, counting from 0. Before this change the 422 stopped at the first failing day, with periods overlap on <DAY> or periods must cover 00:00-24:00 on <DAY>.

ProblemMessage
Two periods overlapMON: periods 0 and 1 overlap (17:00-18:00)
A gap between periodsSAT: 10:00-11:00 is not covered
A day with a short end, or no periods at allMON: 22:30-24:00 is not covered, SUN: 00:00-24:00 is not covered
// illustrative example — derived from TariffInput in packages/core/src/schemas.ts, not a captured response
{ "error": { "code": "VALIDATION_FAILED", "message": "Request validation failed",
"details": { "formErrors": [], "fieldErrors": { "touSchedule": ["SAT: 10:00-11:00 is not covered", "SUN: 00:00-24:00 is not covered"] } } } }

Match on code, not on the message text: messages may be reworded, codes never change.

Archive and restore (C10, C10b)​

POST /v1/plants/{plantId}:archive and POST /v1/plants/{plantId}:restore​

Colon-verb routes: the API Gateway route is POST /v1/plants/{plantId}, and the handler reads the verb after :. A missing or unknown verb is 404 NOT_FOUND.

  • AuthZ: plants ≥ MANAGE on the plant. X-Org-Id is optional.
  • Headers: If-Match (plant version from the detail ETag; required, else 428). Idempotency-Key is optional: a replay with the same key returns the plant's current detail.
  • Body: optional, { "reason": "string 1–200" }. Send no body, or {}, if there is no reason. Unknown fields are 422.
  • Response 200: the plant detail with refs (same shape as GET /v1/plants/{plantId} with X-Org-Id), lifecycle now ARCHIVED / ACTIVE, and an ETag with the new version.

Effects, all in one transaction: the lifecycle counters, the "by created" index partition, an access-log entry, and plant.archived.v1 / plant.restored.v1 (other features stop or resume schedules on that event). While ARCHIVED, PATCH, tag, settings and share-link writes return 409 INVALID_STATE. Reads still work. Archived plants appear in the web list when you filter lifecycle=ARCHIVED.

StatuscodeWhenWhat the FE should do
400MALFORMED_REQUESTBody not a JSON object / bad If-MatchFix the request
401—TokenRefresh and retry
403FORBIDDENplants < MANAGEHide Archive/Restore
404NOT_FOUNDUnknown verb, unknown plant, or no access path—
409INVALID_STATEArchive when not ACTIVE, restore when not ARCHIVED, or a legacy plant never saved on the webRe-fetch; the plant is probably already in that state
409VERSION_CONFLICTStale If-MatchRe-fetch and confirm again
409CONFLICT / IDEMPOTENCY_IN_PROGRESSConcurrent change / the first call with this key is still runningRetry shortly
410GONEPlant is being deletedLeave the page
415UNSUPPORTED_MEDIA_TYPEBody sent without JSON content typeSend the header
422VALIDATION_FAILED / IDEMPOTENCY_KEY_REUSEDBad body / same key with a different bodyFix / use a new key
428PRECONDITION_REQUIREDNo If-MatchSend the version
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLE—Retry with backoff

POST /v1/plants:bulk-archive: archive many plants (C10b)​

Routed in lib/routes.ts (PlantsCollectionAction, actions bulk-tag/bulk-archive) as POST /v1/{collection} (like bulk-tag). Call it exactly as POST /v1/plants:bulk-archive.

  • AuthZ: plants ≥ MANAGE in X-Org-Id (else 403), and checked again for each plant.
  • Headers: X-Org-Id (required, else 400 ORG_CONTEXT_REQUIRED), Idempotency-Key (required, else 428), Content-Type: application/json.
  • Body: exactly one of plantIds (ULID[] 1–200, duplicates collapsed) or filter (the web plant-list filters). Items carry no If-Match: each plant is archived at its current version.

Up to 50 plantIds → 200 { "results": [ { "plantId", "ok", "error"?: { "code" } } ] }. A plant that is not ACTIVE (INVALID_STATE), not archivable by you (FORBIDDEN), unknown (NOT_FOUND) or being deleted (GONE) is an item with ok: false, not a failed request. More than 50 ids, or a filter → 202 plant job + Location: /v1/plant-jobs/{jobId}. Poll it as described for bulk-tag. The same plant-jobs queue caveats apply: without the queue, a job-sized request is 503, and jobs stay QUEUED until a consumer exists.

Errors: 400 ORG_CONTEXT_REQUIRED / MALFORMED_REQUEST, 401, 403 FORBIDDEN, 404 NOT_FOUND (unknown collection/verb), 409 IDEMPOTENCY_IN_PROGRESS, 415, 422 LIMIT_EXCEEDED (more than 200 plantIds; details.limit, details.field), 422 VALIDATION_FAILED (both or neither of plantIds/filter, bad ids), 428, 503 DEPENDENCY_UNAVAILABLE.

DELETE /v1/plants/{plantId} — Delete a plant (owner, mobile)​

Purpose: Lets the plant's owner delete their own plant from the mobile app. This is a simple hard delete, built separately from the planned platform delete flow (C11: soft DELETING state, tombstone, TCP erasure, Crown staff only). That flow uses this same route with X-Org-Id: see the next section.

  • HTTP method: DELETE
  • Endpoint: /v1/plants/{plantId}
  • Authentication: Required
  • Authorization: The caller's access-index role on the plant must be OWNER (the account that created it). ADMIN and VIEWER members can't delete.
  • Idempotency: No Idempotency-Key. Deleting twice is harmless; the second call returns 404.

Request​

Headers: Authorization: Bearer <token> (required). No body, so no Content-Type.

Path parameters:

ParamTypeRequired
plantIdstringYes

Query parameters: none (any sent are ignored). Request body: none (any sent is ignored).

What gets deleted​

All in this service's DynamoDB table (packages/core/src/plants/repository.ts deletePlant):

  1. Every item under PLANT#<id>: the plant's devices (DEVICE#<serial>), share plant links and pending access-request guards. Removing a device frees its serial, so it can be claimed onto another plant afterwards.
  2. Every item whose GSI1 key is PLANT#<id>: every user's access-index row for the plant (other members drop the plant from GET /v1/plants immediately) and any tag links.
  3. Last, in one conditional transaction: the plant item PLANT#<id>/META and the owner's own access-index row.
  4. One more pass over PLANT#<id> to catch a device claimed while steps 1-3 ran. Once the plant item is gone no new claim can commit, so this pass leaves nothing behind.

Steps 1-2 run before step 3 on purpose. If the request fails part-way (a timeout, or 503), the plant is still visible to the owner and calling DELETE again finishes the job. It never leaves a plant nobody can see.

Not deleted:

  • Telemetry, readings and alarms for the plant's devices live in the TCP backend. This service never connects to it, so nothing there is erased.
  • Every serial binding of the plant (DEVICE#<serialNorm>) and its SERIALBIND# guard are deleted by unbindAllBindingsForPlant, freeing each serial for a claim on another plant. The release runs before the dependents sweep: if it fails the request fails, nothing is deleted, and the FE may retry. It runs again after the plant record is deleted; a failure there is logged (plant_after_deleting_hook_failed, metric PlantDeviceReleaseFailed) and the final sweep skipped. No event is published for the release.
  • Org-level share records (ORG#<o>/SHARE#<id>) and access-request records that name the plant are left in place. They point at a plant that no longer exists, and nothing resolves them to a plant any more.

Users whose selectedPlantId was this plant are moved to another of their plants (or cleared) the next time they call GET /v1/me, through the existing self-healing read.

Response​

204 No Content, empty body.

Failure response — not the owner (illustrative)​

{ "error": { "code": "FORBIDDEN", "message": "Only the plant owner can delete this plant" } }

Failure response — no access, or already deleted (illustrative)​

{ "error": { "code": "NOT_FOUND", "message": "Plant not found" } }

:::note 404 here, not 403 like GET GET /v1/plants/{plantId} returns 403 for a plant the caller can't see (an older exception kept for the shipped app). This route follows the normal rule: no access at all is 404, visible but not owner is 403. Treat 404 after a retried delete as "already deleted". :::

Failure response — organisation-managed plant (illustrative)​

{ "error": { "code": "INVALID_STATE", "message": "This plant is managed by an organisation and cannot be deleted from the app" } }

Only plants created by the mobile app can be deleted here. A plant created through the web console (new schema) is deleted through the platform flow instead.

HTTP status codes​

StatuscodeWhen
204—Deleted
401— (gateway body)Missing or invalid token
403FORBIDDENThe caller can see the plant but isn't its OWNER
404NOT_FOUNDNo access to the plant, it doesn't exist, or it was already deleted
409INVALID_STATEOrganisation-managed (web) plant. Exception (2026-10-29, not yet deployed): the owner's own migrated plant (v2, ACTIVE, operator and customer org = the owner's personal org) is deleted here too, synchronously, including its code guard and customer link, with a plant.deletion.requested.v1 event for the TCP server. It first claims the plant (lifecycle: DELETING); if a web edit or reassignment wins that race the app gets 409 CONFLICT and nothing is removed. If a delete is interrupted after the claim, the owner's next DELETE resumes it
409CONFLICTThe plant or the owner's role changed during the delete. Retry.
500INTERNALUnexpected server error
503DEPENDENCY_UNAVAILABLEDynamoDB throttled or unavailable. Retry; the delete resumes where it stopped.

Executions: none captured signed in. The route is deployed on dev: a no-token call returns 401 (probe 2026-11-03). The examples above are illustrative, taken from the handler and core code.

DELETE /v1/plants/{plantId} with X-Org-Id: platform delete (C11)​

Purpose: Crown staff delete an organisation-managed plant (Plant Workspace → Delete, "permanently removed"). The same route without X-Org-Id is the mobile owner delete above, and it is unchanged.

  • Auth: Cognito access token. AuthZ: a PLATFORM membership with plants = FULL (Super Admin, Administrator), a Business plant manager on a plant with no customer, or the personal-org owner. Crown staff may delete any plant (owner rule 2026-12-02), whoever created or owns it, with or without a customer, and also when the plant is blocked (status: SUSPENDED, Block B) or its Business is suspended. A blocked plant stays view-only for Crown staff in every other respect.
  • Legacy plants (mobile-created, never saved on the web): Crown staff get a synchronous hard delete instead of the saga below. The bindings are released before and after, every dependent item and every user's access-index row is removed, then META. The response is the same 202 body, and a later GET returns 404, not 410. plant.deletion.requested.v1 is published in the same transaction as the META delete, because TCP frees the devices only on that event. TCP's plant.erasure.completed.v1 reply finds no plant and is logged as already done. Nothing is recorded for the Idempotency-Key: a retry returns 404.
  • Headers: X-Org-Id (selects this variant), If-Match (plant version) and Idempotency-Key. Both are required, else 428 PRECONDITION_REQUIRED with details.header.
  • Body: none.

Response 202 (illustrative):

{ "plantId": "01JB00000000000000000000P1", "lifecycle": "DELETING", "deletionRequestedAt": "2026-10-13T08:00:00.000Z" }

What happens, in one transaction: the plant becomes DELETING and disappears from every list, map, summary and search. Every user's access-index copy is removed (more than 25 copies are finished asynchronously). A pending-deletion marker is written. Then, in a second transaction after DELETING commits, plant.deletion.requested.v1 is published for the TCP side (telemetry erasure); since ADR 0012 it carries the plant's complete bound serials list. If that publish fails, the device-binding release hooks are skipped and the hourly pending-deletion sweep republishes the event; the bindings are then released when TCP confirms erasure (onPlantErasureCompleted).

Devices are released. Once, right after the DELETING commit, every serial binding of the plant and its SERIALBIND# guard are deleted (unbindAllBindingsForPlant, 25 bindings per transaction, a failed chunk retried one binding at a time). No event is published for the release. A release failure is logged, not returned; the release is idempotent and is retried when TCP reports erasure complete. HTTP keeps no owner org or owner user for a serial, so a released device is free: any user or Business can claim it (TCP clears its own owner_org_id/owner_user_id on erasure). The serial can then be claimed on another plant; the only unbind route is DELETE /v1/plants/{plantId}/devices/{serial}. FE: a device list fetched before the delete is stale; refetch it.

When TCP reports erasure complete (plant.erasure.completed.v1, see KI-42), onPlantErasureCompleted (packages/core/src/plants/lifecycle.ts) deletes every remaining item of the plant, writes a tombstone and removes the pending marker. A duplicate or out-of-order event is a logged no-op. The hourly sweep emits PlantDeletionOverdue for a plant DELETING more than 24 h, which raises the PlantDeletionOverdue alarm. Until the TCP reply arrives, GET keeps returning 410. The plant code is never reused.

After the 202, GET /v1/plants/{plantId} with X-Org-Id returns 410 GONE with details.lifecycle (DELETING). An id that never existed stays 404. The other plant routes (workspace, PATCH, settings, archive) also return 410.

StatuscodeWhenWhat the FE should do
400MALFORMED_REQUESTIf-Match is not a versionFix the header
401—TokenRefresh and retry
403FORBIDDENNot platform staff with plants = FULLHide Delete
404NOT_FOUNDUnknown plant or no access path—
409INVALID_STATEAlready DELETING, or a legacy plant never saved on the web and the caller is not Crown staff (the running-commands blocker, details.commandIds, was removed by ADR 0012)Show the reason
409VERSION_CONFLICTStale If-MatchRe-fetch and confirm again
409CONFLICT / IDEMPOTENCY_IN_PROGRESSConcurrent change / first call with this key still runningRetry shortly
410GONEAlready erased (tombstone; not reachable until erasure cleanup is built)Treat as deleted
422IDEMPOTENCY_KEY_REUSEDSame key, different requestUse a new key
428PRECONDITION_REQUIREDMissing If-Match or Idempotency-KeySend both
500 / 503INTERNAL / DEPENDENCY_UNAVAILABLE—Retry with the same key

Edge cases: retrying with the same Idempotency-Key returns the same 202 body. A retry with a new key after success is 409 INVALID_STATE (already deleting). Lists may still show the plant for a moment until the projections catch up.

Executions (archive/restore, bulk-archive, settings, platform delete): none captured signed in. On dev, POST …:archive, POST …:restore, PUT …/settings/alert-rules, PUT …/settings/tariff and DELETE /v1/plants/{plantId} all return 401 with no token (probe 2026-11-03), so they are deployed. Every example above is illustrative, taken from the schemas and handler code.

POST /v1/plants/{plantId}/shares — Re-share one plant​

A Connected End User shares one plant onward with another person (policy §8.1, built 2026-11-03). Verified against packages/core/src/repositories/reshares.ts and packages/api/src/handlers/plants-write.ts. Not run against any deployment; examples are illustrative.

  • Auth: Cognito JWT (Authorization: Bearer <id-token>).
  • Authz: the caller must reach the plant through a share granted to them personally or through their customer portal, with sharing ≥ MANAGE on that path. That only happens when the Business set permsLimit or portalPermsLimit { "sharing": "MANAGE" } on a FULL grant (Shares). Callers whose sharing comes from an organisation membership use POST /v1/orgs/{orgId}/shares instead.
  • Headers: Idempotency-Key required (428 if missing).
  • Body (strict; unknown keys → 422):
FieldTypeRequiredNotes
grantee{ kind: "USER", sub?: string, email?: string }YesIndividuals only (no ORG). One of sub or email; email is trimmed and lower-cased, ≤ 254.
levelVIEW | MONITOR | EDIT | SERVICE | FULLYesNever above your own access.
permsLimitPermsLimitNosharing is always forced to NONE: a re-share can never be re-shared.
expiresAtISO-8601 date-timeNo
notestring ≤ 500No
// illustrative example — request
{ "grantee": { "kind": "USER", "email": "brother@example.com" }, "level": "MONITOR" }
  • Response 201: the share as in the share list (selector: { kind: "PLANTS", ids: [plantId] }, permsLimit.sharing: "NONE") with parent, plus invitation when the grantee was given by email.
// illustrative example — response (invitation omitted)
{ "shareId": "01JB7R0000000000000000000S", "code": "SH-0042",
"grantee": { "kind": "USER", "name": "brother@example.com", "contactMasked": "b***@example.com" },
"level": "MONITOR", "permsLimit": { "sharing": "NONE" },
"parent": { "kind": "SHARE", "shareId": "01JB7R0000000000000000000A", "sub": "<caller-sub>" },
"selector": { "kind": "PLANTS", "ids": ["01JB7R0000000000000000000P"] },
"status": "INVITED", "expired": false, "sharedBy": { "sub": "<caller-sub>", "name": "Ali" },
"since": "2026-11-03T08:00:00.000Z", "version": 1 }
StatusCodeWhenFE action
400MALFORMED_REQUESTBody is not a JSON objectBug
401UNAUTHORIZEDMissing or expired tokenRe-auth
403FORBIDDENNo share/portal path with sharing ≥ MANAGE; or details.reason: "ESCALATION" — level after permsLimit exceeds your own accessHide "Share", or offer a lower level
404NOT_FOUNDYou have no access to the plantTreat as gone
409INVALID_STATEYour sharing comes from an org membership (use the org share screen), or a legacy plant never saved on the webShow the message
409ALREADY_EXISTSThat person already has a share of this plantShow "already shared"
410GONEPlant is being deletedRemove from UI
422VALIDATION_FAILEDBad body, neither sub nor email, or sharing with yourself (details.field: "grantee.sub")Fix the form
428PRECONDITION_REQUIREDNo Idempotency-KeyBug
500INTERNALUnexpectedRetry later
503DEPENDENCY_UNAVAILABLEDynamoDB unavailable, or a repeat of an already-completed Idempotency-Key (no replay body)Retry with backoff; refresh the share list instead of replaying

Edge cases:

  • The Business that owns the plant sees the re-share in its share list (parent set) and can suspend or revoke it.
  • A re-share is checked against its parent on every request: it grants nothing once the parent share is revoked, expired, re-scoped off the plant or no longer carries sharing ≥ MANAGE, or the parent portal is closed or no longer sharing, or the re-sharer left the customer org. A valid one is capped at the parent's ceiling. Live realtime tickets keep their levels until they expire (≤ 600 s).

POST /v1/orgs/{orgId}/plant-transfers: transfer a plant to a registered user​

Added 2026-11-19 (ADR 0028), replacing the 2026-11-16 plant handover (/plant-handovers and its invitation path are removed). The examples below are illustrative, derived from PlantTransferInput / PlantTransferResponse in schemas.ts and plants/transfer.ts; no response body has been captured for this page.

:::warning Fixed 2026-11-26: 500 INTERNAL on a first share

First run against dev on 2026-11-26, from the mobile app (reported by the mobile team): every Business-mode share returned 500 INTERNAL and wrote nothing. A Platform-mode share to an independent receiver with no businessOrgId succeeded. Cause: when the receiver was not yet a customer of the Business, the transaction updated the receiver's customer list entry (ORG#<personal org> / LISTALL#CUSTOMER) twice, once for the entry and once for the +1 plant count. DynamoDB rejects that with a ValidationException. It wasn't a cancellation, so it became a 500. The same bug hit Platform mode whenever the receiver ended up as an End User customer (a picked businessOrgId, or an End User of a Business). Fixed in code on 2026-11-26: the count is folded into the entry write, and the unit tests now reject a transaction that names one item twice. Dev needs a redeploy (npm run deploy:dev) before the fix is live. :::

A plant is transferred by email to an already registered account. No invitation is ever created: an email with no account is refused (404, reason: USER_NOT_REGISTERED) — the person signs up in the app first. The email is resolved with Cognito ListUsers (exact email filter).

Headers: If-Match = the plant's version (required, 428 if missing); Idempotency-Key (required).

Body (strict JSON):

FieldTypeRules
plantIdULIDthe plant to transfer
emailstringthe receiver's email, trimmed and lower-cased, ≤ 254; must belong to a registered account
businessOrgIdULIDoptional, Crown staff only (2026-11-20, ADR 0029; a Business caller sending it gets 422): the Business an independent receiver joins, picked from GET /v1/orgs/{orgId}/businesses (send an ACTIVE one)

Who calls decides the rules​

Business mode. {orgId} is the caller's Business. Caller: the Business role (team ≥ MANAGE) or an Installer of the Business, and plants ≥ EDIT on the plant, which must be in {orgId}. The plant stays in the Business.

The receiver is…Result
an ACTIVE End User member of the Businessthe plant joins their scope
in no Business (independent)they are added directly as an End User of the Business (scope = this plant), in the same transaction; as on any join, their own personal plants move into the Business
a member of another live Business (any role, even suspended)refused up front: 409 USER_IN_ANOTHER_ORG — see one Business per person
staff of this Business (Business role, Installer, …)refused: 409 NOT_AN_END_USER
a suspended member of this Businessrefused: 409 MEMBER_NOT_ACTIVE

The plant then has customerSub = ownerUserSub = the receiver (customerSource: TRANSFER). A plant that already has a customer is refused (PLANT_HAS_CUSTOMER). If the email has a live pending invitation to the Business, revoke it first (INVITATION_PENDING).

The receiver becomes a customer of the Business (2026-11-25): the plant's customerOrgId becomes the receiver's personal org (created, and kept closed, if they never had one) and they get a customer profile there. They appear in GET /v1/orgs/{orgId}/customers, for the Business and for the Installers whose plants are shared with them. The response is unchanged.

Platform mode. The caller is Crown staff — Super Admin or Administrator — acting in {orgId} with plants ≥ MANAGE: from the Crown org any plant, or through platform access in another org only that org's plants. The plant moves to the receiver's org and the receiver becomes its owner:

The receiver is…The plant goes tocustomerSub
in no Business, businessOrgId sent (2026-11-20)that Business; the receiver joins it as an End User (scope = this plant, same transaction; their own personal plants then move in); joinedBusiness: truethe receiver
in no Business, no businessOrgIdtheir personal org (created, or reopened if closed); they stay independent—
an End User of a Businessthat Business (the plant also joins their scope)the receiver
a Business-role user, an Installer or other staff of a Businessthat Business—

operatorOrgId = the destination and ownerUserSub = the receiver. customerOrgId = the destination, except when the receiver is an End User of the destination Business (the two rows with customerSub): then it is the receiver's personal org and they become a customer of that Business (2026-11-25, as in Business mode). The previous customer link and homeOrgId are removed. When the org changes, the Installer assignment is removed, the old org's open work orders on the plant are cancelled and TCP gets access.revoked.v1 (PLANT_MOVED) for the old org. Transferring to the current owner where nothing would change is refused (ALREADY_OWNER). A suspended membership in the receiver's Business is refused (MEMBER_NOT_ACTIVE). A businessOrgId naming a Business other than the one the receiver already belongs to is refused (409 USER_IN_ANOTHER_ORG); a picked org that is missing (404), not a Business (NOT_A_BUSINESS) or not ACTIVE (BUSINESS_NOT_ACTIVE) is refused.

Both modes: the plant must be ACTIVE (not archived) and not blocked; the receiver's account must not be blocked (ACCOUNT_BLOCKED), and a plant move still running for them is finished first or refused (MOVE_IN_PROGRESS).

One Business per person​

A person belongs to at most one Business at a time, whatever their role there: End User, Installer, Business owner or any other (ADR 0026 D5). They can't leave on their own; there is no "leave business" route. They are free to join another Business only when the first one removes them (membership REMOVED), or when that Business is closed. A suspended membership still counts, so suspension is not a way out.

Every way in enforces this: sharing a plant (plant-transfers, and plant-transfer-checks in advance), accepting an invitation, sending or approving a join request, and creating a Business. Since 2026-11-26 every refusal carries a message that is safe to show as is on web and mobile. The reason codes keep their existing names:

Who is actingreasonerror.message (exact text)Extra details
A Business (owner / Installer) shares with someone in another BusinessUSER_IN_ANOTHER_ORGThis person already belongs to another business. They can join yours only after that business removes them.none: the other Business is never named to a Business
Crown staff pick a businessOrgId for someone already in a different BusinessUSER_IN_ANOTHER_ORGThis person already belongs to "<name>", so the plant can only move there. They can join another business only after "<name>" removes them.orgId, orgName
The person themself accepts an invitation, sends a join request or creates a BusinessALREADY_IN_BUSINESSYou already belong to "<name>". You can join or create another business only after "<name>" removes you.orgId, orgName (their own Business)
A Business approves a join request from someone who has joined another Business sinceALREADY_IN_BUSINESSThis person now belongs to another business. They can join yours only after that business removes them.none (2026-11-26: orgId is no longer sent)

The check returns the same text in its message field (below), so the Share dialog can show it before the user presses Continue.

Known gap: the rule is checked by reading the person's memberships just before the write. It is not locked in the same transaction, so two Businesses adding the same person within the same few milliseconds could both succeed. This has not been observed.

What TCP receives​

Every transfer bumps the plant version and writes one plant.upserted.v1 in the same transaction (no new fields):

CaseoperatorOrgIdcustomerSubownerUserSub
Business modethe Business (unchanged)receiverreceiver
Platform → independent userreceiver's personal orgabsentreceiver
Platform → independent user + businessOrgIdthe picked Businessreceiverreceiver
Platform → End User of a Businessthat Businessreceiverreceiver
Platform → Business-role user / Installerthat Businessabsentreceiver

ownerUserSub is stored on the plant (META ownerUserSub), so every later plant.upserted.v1 (edits, tags, settings, Installer change, block) keeps carrying it. TCP moves the plant's devices to operatorOrgId and sets their owner to ownerUserSub (else customerSub) — see integration bus.

When the receiver leaves​

  • An End User detached or removed from the Business (or the Business closed): since ADR 0036 (2026-11-27, not deployed) a transferred plant moves to their personal org with the plants they brought in; they stay ownerUserSub, the transfer link (customerSource, transferredAt, …) is removed, and plant.upserted.v1 carries the new operatorOrgId. (2026-11-20 to 2026-11-27 it stayed in the Business and the remover became owner.) Their customer profile in the Business is closed (CHURNED, 2026-11-25).
  • A Business-role user or Installer removed from the Business: the plants they own stay and the Business owner (the first ACTIVE Business-role member) becomes their owner (2026-11-20; before: no owner). If the Business has no other Business-role member, the owner is left unchanged.
  • Taking the End User off one plant without removing them from the Business is no longer possible: plant-unshares was removed 2026-11-27 (ADR 0035).

After a Business-mode transfer the End User has the connected End User levels on the plant: plants: VIEW (since 2026-11-23, RBAC-S10; was EDIT), and commands and register writes only once the Business turns their remote control on (default off). The Business can no longer delete the plant (403 PLANT_HAS_CUSTOMER; Crown staff can).

Illustrative request and response (Business mode, receiver joins as End User):

POST /v1/orgs/01J9BUSINESS00000000000000/plant-transfers
If-Match: "4"
Idempotency-Key: 6f1c2a
Content-Type: application/json

{ "plantId": "01J9PLANT000000000000000001", "email": "customer@example.com" }
{
"plantId": "01J9PLANT000000000000000001",
"version": 5,
"mode": "BUSINESS",
"operatorOrgId": "01J9BUSINESS00000000000000",
"previousOperatorOrgId": "01J9BUSINESS00000000000000",
"receiverSub": "<cognito sub>",
"customerSub": "<cognito sub>",
"ownerUserSub": "<cognito sub, lower-case>",
"joinedBusiness": true
}

Illustrative response (platform mode from the Crown org, receiver independent): mode: "PLATFORM", operatorOrgId = the receiver's personal org, previousOperatorOrgId = where the plant was, no customerSub, joinedBusiness: false.

Errors​

Statuscode / reasonWhen
403FORBIDDENnot Crown staff and not the Business role / an Installer of the Business; plants below EDIT (Business) or MANAGE (Crown); a delegated (partner) caller
403FORBIDDEN PLANT_BLOCKEDthe plant is frozen by Block B
404NOT_FOUNDno membership in {orgId}, or the plant is not in that org
404NOT_FOUND USER_NOT_REGISTEREDno account has this email
409VERSION_CONFLICTIf-Match is not the current plant version
409CONFLICT USER_IN_ANOTHER_ORGBusiness mode: the receiver belongs to another Business (message: they can join only after that Business removes them; no id or name). Platform mode: businessOrgId names a Business other than the receiver's (details.orgId, orgName). See one Business per person
409CONFLICT NOT_AN_END_USERBusiness mode: the receiver is staff of this Business
409CONFLICT PLANT_HAS_CUSTOMERBusiness mode: the plant already belongs to a customer
409CONFLICT INVITATION_PENDINGBusiness mode: the email has a pending invitation to the Business (details.inviteId) — revoke it first
409CONFLICT ALREADY_OWNERPlatform mode: the receiver already owns the plant where it is
409CONFLICT MOVE_IN_PROGRESSthe receiver's plants are still being moved; retry in a minute
409CONFLICT PLANT_CHANGED / RECEIVER_CHANGEDchanged meanwhile; reload and retry
409INVALID_STATE NOT_A_BUSINESS, BUSINESS_NOT_ACTIVEBusiness mode: {orgId} is not an ACTIVE Business; Platform mode: the picked businessOrgId is not an ACTIVE Business (missing → 404)
409INVALID_STATE MEMBER_NOT_ACTIVEthe receiver's membership is suspended
409INVALID_STATE ACCOUNT_BLOCKEDthe receiver's account is blocked
409INVALID_STATEthe plant is archived or being deleted
422VALIDATION_FAILEDbad body; businessOrgId sent by a Business caller
422LIMIT_EXCEEDEDthe receiver already holds 50 memberships
428PRECONDITION_REQUIREDIf-Match or Idempotency-Key missing

POST /v1/orgs/{orgId}/plant-transfer-checks: check the recipient before sharing​

:::note Superseded 2026-11-30 POST /v1/orgs/{orgId}/account-checks with purpose: "PLANT_TRANSFER" gives the same answers for the same inputs and shares this route's rate-limit bucket. This route stays until the console has moved, then is retired. :::

Added 2026-11-20 for the web console's Share plant dialog. Deployed to dev on 2026-11-20; no request has been captured against it yet, so no real response is shown here. The examples below are illustrative, derived from PlantTransferCheckResponse in schemas.ts and plants/transfer-check.ts.

A read-only answer to two questions before the user presses Continue: who does this email belong to, and would plant-transfers accept them? It runs the transfer's own rule functions in the same order, so a refusal here uses the same reason code the transfer would.

The route is a plain path, not plant-transfers:check. API Gateway can't put a :verb on a fixed path segment. A collection verb would have to share POST /v1/orgs/{orgId}/{collection} with the maintenance-plans function and give that function Cognito ListUsers.

Headers: none beyond auth. No If-Match (the plant version is not compared) and no Idempotency-Key. Nothing is written except the caller's rate-limit counter.

Body (strict JSON, the same body as the transfer, so the email stays out of URLs and access logs):

FieldTypeRequiredNotes
plantIdULIDyes
emailstring (email, ≤ 254)yestrimmed and lower-cased
businessOrgIdULIDnoCrown staff only, as on the transfer (422 from a Business caller)

Who may call: the same callers as the transfer. In Business mode, the Business role (team ≥ MANAGE) or an Installer of the Business, with plants ≥ EDIT on the plant. In Platform mode, Super Admin / Administrator with plants ≥ MANAGE.

Order of checks:

  1. Caller and plant checks run first and fail as errors, exactly as on the transfer: 403 / 404 / 409 PLANT_HAS_CUSTOMER / PLANT_BLOCKED / plant not ACTIVE / NOT_A_BUSINESS / BUSINESS_NOT_ACTIVE / 422. A caller who could not transfer this plant gets one of these and never an answer about the email.
  2. The per-caller rate limit: 20 checks per minute and 200 per day, then 429 RATE_LIMITED with Retry-After. This step is there because the check reveals whether an email has an account.
  3. The email is resolved with Cognito ListUsers (exact email filter). If no account has it, the answer is found: false.
  4. Recipient checks: blocked account, plant move running, memberships, pending invitation, already owner. A refusal comes back as 200 with eligible: false, the transfer's reason and its message.

Response 200:

FieldTypeNotes
foundbooleanfalse means no account uses this email
recipient{ displayName: string | null, email }Only when found. displayName is the person's display name, or null if they set none. email is normalised. No sub, org id or phone.
eligiblebooleantrue means the transfer would be accepted right now
reasonstring | nullnull when eligible. Otherwise one of USER_NOT_REGISTERED, USER_IN_ANOTHER_ORG, NOT_AN_END_USER, ALREADY_OWNER, INVITATION_PENDING, MEMBER_NOT_ACTIVE, ACCOUNT_BLOCKED, LIMIT_EXCEEDED, MOVE_IN_PROGRESS
messagestring | nullAdded 2026-11-26. null when eligible. Otherwise the exact error.message the transfer would return for reason, safe to show as is (for USER_IN_ANOTHER_ORG see one Business per person). Map reason to your own text if you prefer; message is the fallback for a reason the app doesn't know

Both Business and Crown callers see the full display name. A Business sees that name on its members list once the transfer is done anyway.

Illustrative responses​

{ "found": true, "recipient": { "displayName": "Ali Khan", "email": "ali@example.com" }, "eligible": true, "reason": null, "message": null }
{
"found": true,
"recipient": { "displayName": "Ali Khan", "email": "ali@example.com" },
"eligible": false,
"reason": "USER_IN_ANOTHER_ORG",
"message": "This person already belongs to another business. They can join yours only after that business removes them."
}
{ "found": false, "eligible": false, "reason": "USER_NOT_REGISTERED", "message": "No registered account has this email — the person signs up in the app first" }

The console allows Continue only when found && eligible.

A pass is not a guarantee. The transfer checks everything again. If the person joins another business between the check and the transfer, the transfer still refuses with its usual error.

Two differences from the transfer:

  • A stuck plant move is reported as MOVE_IN_PROGRESS. The check doesn't try to resume it; the transfer does.
  • For an independent receiver in Platform mode, the check doesn't create a personal org. So ALREADY_OWNER is only found when the person already has one.

Errors​

Statuscode / reasonWhen
403FORBIDDENas on the transfer: not allowed to transfer in {orgId}, plants too low, a delegated (partner) caller
403FORBIDDEN PLANT_BLOCKEDthe plant is frozen by Block B
404NOT_FOUNDno membership in {orgId}; the plant is not in that org; a picked businessOrgId does not exist
409CONFLICT PLANT_HAS_CUSTOMERBusiness mode: the plant already belongs to a customer
409INVALID_STATE NOT_A_BUSINESS, BUSINESS_NOT_ACTIVE{orgId} (Business mode) or the picked businessOrgId (Platform mode) is not an ACTIVE Business
409INVALID_STATEthe plant is archived or being deleted, or has no org yet
422VALIDATION_FAILEDbad body; businessOrgId sent by a Business caller
429RATE_LIMITEDmore than 20 checks a minute or 200 a day by this caller (Retry-After header)

POST /v1/orgs/{orgId}/plant-unshares: unshare a plant​

Removed 2026-11-27 (ADR 0035, owner decision). This route no longer exists; API Gateway returns 404 for it. A plant cannot be unshared any more: it can only be deleted and created again in another org, or transferred to another person. Detaching or removing an End User from a Business (:detach / :remove) still moves their plants back to their own account.

Plant ownership, share and unshare (2026-11-20)​

Owner decision 2026-11-20 (ADR 0029). Every plant has an owner, stored on the plant (ownerUserSub, lower-case Cognito sub), returned on the web plant detail (PlantDetail.ownerUserSub, next to customerSub = the End User it is shared with) and sent to TCP on every plant.upserted.v1. TCP makes the plant's devices — and their batteries — follow it.

EventNew owner
Create (mobile, web, any role)the creator
Create that assigns an end user (Crown end-user-plants; web create whose customer.customerOrgId is an end user's personal org)that end user
Share (plant-transfers)the end user
Unshare (plant-unshares), or :detach / :remove of the End Userthe caller
A Business owner or Installer who owns plants leaves the Businessthe Business owner
Web PATCH setting customerOrgId to an end user's personal orgthat end user
Plant deleteunchanged behaviour (devices go back to the Business's unbound stock on TCP)

Plants created before 2026-11-20 get a stored owner from the human-run backfill npm run migrate:plant-owners (see Operations).

Assigned Installer (R-5)​

Owner decision 2026-11-03 (R-5 decision 2). Built 2026-11-03; not yet run against a deployed stage. Every example below is illustrative.

Each plant of a Business records two people:

FieldMeaningChanges
installedBy { sub, displayName, at, viaPlatform? }The member who registered the plant (POST /v1/plants with X-Org-Id). viaPlatform: true (2026-11-12) = Crown staff through platform access; readers outside the Crown org get { displayName: "Crown Support", at, viaPlatform: true }. The installer history's by works the same way.Never.
assignedInstaller { sub, displayName }The Installer the plant is assigned to now. Absent = nobody.Through the route below.

Who is assigned at creation. The installing member is always the token's sub, from the web console or the mobile app alike (both create through POST /v1/plants with X-Org-Id = the Business); the body cannot name someone else. They are auto-assigned when they hold a custom role in the Business (the Installer role or a copy of it). Built-in roles (the Business owner, Admin, Super Admin) see every plant already and are not auto-assigned. A mobile create without X-Org-Id lands in the caller's personal org and has no Installer link.

Registering needs plants ≥ EDIT. The seeded Installer template has plants: EDIT since 2026-11-03 (owner decision), so a new Installer can register plants at once. Installer roles seeded before that keep plants: VIEW until the Business raises them with PATCH /v1/orgs/{orgId}/roles/{roleId}.

What the assignment gives. The assigned Installer reaches the plant at their own role's levels, as if it were in their scope: plant decisions, the plant list, realtime tickets and alert audiences all include it. It is an access path, not a scope edit, so a reassignment removes it cleanly. End Users get nothing through it: they still need a share or a customer portal. Installers hold sharing: MANAGE (owner 2026-11-26, reversing RBAC-S6 of 2026-11-23), so they share any plant of the Business, create share links and decide access requests, whoever added the plant. Inviting an End User into the Business is unaffected.

Existing plants have no installedBy and no assignedInstaller. The Business assigns them with the route below; nothing is guessed.

The Business (scope ALL) keeps visibility and management of every plant, whoever is assigned.

POST /v1/plants/{plantId}/installer​

  • Authorization: plants ≥ MANAGE in the plant's Business (the Business role holds it; the Installer template does not). A scoped caller's own scope must cover the plant, otherwise 404. Super Admin and Admin reach it through the platform fallback.
  • Headers: If-Match: "<plant version>" (required; missing 428, stale 409 VERSION_CONFLICT). No Idempotency-Key (versioned).
  • Body (strict): { "sub": "<memberSub>" } to assign or move, { "sub": null } to unassign. The target must be an ACTIVE member of the Business, otherwise 404 NOT_FOUND.
  • Effect (one transaction): plant version + 1 and assignedInstaller set (or removed); the previous Installer loses the access that came only from the assignment and gets access.revoked.v1 (scope USER, plantIds, reason INSTALLER_REASSIGNED); a history entry; PLANT_INSTALLER_CHANGED in the Business's access log; plant.upserted.v1 with assignedInstallerSub. Shares the previous Installer made, and End Users' access, are unchanged. installedBy never changes. The same Installer again writes nothing.
  • Response 200, ETag = the new plant version:
{
"plantId": "<plantId>",
"version": 4,
"installedBy": { "sub": "<installerA>", "displayName": "Installer A", "at": "2026-11-03T08:00:00.000Z" },
"assignedInstaller": { "sub": "<installerB>", "displayName": "Installer B" }
}
StatuscodeWhen
403FORBIDDENplants below MANAGE in the Business
404NOT_FOUNDPlant not visible (or not a web plant), or the target is not an ACTIVE member
409VERSION_CONFLICT / INVALID_STATEStale If-Match / plant being deleted
422VALIDATION_FAILEDBody shape
428PRECONDITION_REQUIREDIf-Match missing

GET /v1/plants/{plantId}/installer-history​

  • Authorization: plants ≥ VIEW in the plant's Business (scope must cover the plant).
  • Query: limit (1 to 50; default 15 on the first page, 10 with a cursor (lazy loading)), cursor.
  • Response 200: { installedBy?, items: [{ at, by, from, to }], nextCursor? }, oldest first. from/to are { sub, displayName } or null. When the creator was auto-assigned, the first entry is that registration (from: null). A by that was Crown staff acting through platform access carries viaPlatform: true and, for a reader outside the Crown org, reads as { "displayName": "Crown Support", "viaPlatform": true } with no sub (RBAC-S3, 2026-11-23 — before this the marker was dropped and the staff member was named).

A plant can have one public read-only link, for showing a plant to someone without an account. Verified against packages/core/src/plants/share-links.ts, packages/api/src/handlers/plants-write.ts and packages/api/src/handlers/share-link-public.ts.

:::note Deployed on dev, not yet run signed in On dev (probe 2026-11-03): POST /v1/plants/{plantId}/share-links and DELETE …/share-links/{linkId} return 401 with no token, and GET /v1/share-links/not-a-real-token returns the 400 shown below. Create and revoke have not been run signed in, so their examples are illustrative, derived from the schema and handler code. :::

POST /v1/plants/{plantId}/share-links — Create or rotate​

  • Auth: JWT, plants ≥ EDIT and sharing ≥ MANAGE (Business and Installers since 2026-11-26; a connected End User holds sharing: VIEW) — else 403 FORBIDDEN. Whether customer-portal users may share is still open (OQ-06).
  • Headers: Idempotency-Key required (428 if missing).
  • Body (optional): { "expiresInDays": 1..365 }, default 90.
  • Response 201:
// illustrative example
{ "linkId": "01JB7R0000000000000000000A", "url": "https://cse-admin-web.vercel.app/share/<share-token>", "expiresAt": "2027-01-11T08:00:00.000Z" }
  • The token is shown once. It is 32 random bytes in base64url (43 characters). Only its SHA-256 is stored; it is never logged or written to the access log. Copy url straight away. An idempotent replay of the same request returns 201 without url and with "tokenShownOnce": true. If the user lost the link, create a new one.
  • url is <SHARE_LINK_BASE_URL>/share/<share-token>. SHARE_LINK_BASE_URL comes from the CDK context key shareLinkBaseUrl (the console's public https origin, see Operations). dev sets it to https://cse-admin-web.vercel.app in cdk.json (stages.dev, since 2026-11-03), so a dev deploy since then returns an absolute URL on that origin (code reading; no signed-in create captured yet). A stage deployed without the key returns a relative URL (/share/<share-token>); the FE should then prefix the console host. The link opens nothing until the console hosts a public /share/<share-token> page that reads GET /v1/share-links/{token} (Public view, below): this API returns the data, the page is the console's (issue #17, R-1). Links not revoked expire on their own at expiresAt (default 90 days after creation).
  • Rotation: creating again replaces the link. The old token stops working at once.
  • Rate limit: 10 creates per plant per day → 429 RATE_LIMITED.
  • Errors: 403, 404, 409 INVALID_STATE (archived plant, or a legacy plant not yet saved on the web), 410 GONE (plant being deleted), 422, 428, 429.

DELETE /v1/plants/{plantId}/share-links/{linkId} — Revoke​

plants ≥ EDIT and sharing ≥ MANAGE. 204, also when the link was already revoked or rotated away. 404 when linkId was never a link of this plant. Also 403 (below plants ≥ EDIT), 409 INVALID_STATE (archived plant, or a legacy plant not yet saved on the web) and 410 GONE (plant being deleted).

GET /v1/share-links/{token} — Public view​

Captured execution (dev, 2026-11-03, no token): GET /v1/share-links/not-a-real-token → 400 (requestId replaced):

{"error":{"code":"VALIDATION_FAILED","message":"Malformed share link token","details":{"field":"token"},"requestId":"<id>"}}
  • Full URL: <API base URL>/v1/share-links/{token} — the same API host as every other /v1/ route (no separate share host). The token is the last path segment of the url returned by create.
  • Public share page: this repo defines no host for a public share page. Create builds url as ${SHARE_LINK_BASE_URL}/share/<token> (packages/core/src/plants/share-links.ts), where SHARE_LINK_BASE_URL (packages/core/src/config.ts) is set on every API function from -c shareLinkBaseUrl (lib/route-family.ts). It must be an https:// origin with no path, or synth fails. Unset, the URL is relative. Hosting the /share/<token> page (which calls this API route) is the web console's job. Report links (/reports/<id>) use the same base.
  • Expired / revoked links: 404 — expiry is checked at read time against expiresAt.
  • Auth: none (the only public route of this feature). Do not send Authorization.
  • Token: exactly 43 base64url characters, otherwise 400 VALIDATION_FAILED.
  • Throttle: 10 requests/s, burst 20, at API Gateway. Over that, a gateway 429 with {"message":"Too Many Requests"} (not the error envelope).
  • Response headers: Cache-Control: no-store, Referrer-Policy: no-referrer.
  • 404 NOT_FOUND for an unknown, revoked, expired, archived or deleting plant. These are deliberately indistinguishable.

The response contains only these fields (strict allow-list):

FieldNotes
plant.code, plant.name, plant.plantTypeAlways present
plant.city, plant.region, plant.countryCodeWhen set. No street, no coordinates
plant.pvCapacityKwp, plant.timezoneWhen set
plant.gridTopology, plant.commissionedOnWhen set
plant.hasBatteryAlways (derived from the plant's devices, 2026-11-18)
expiresAtLink expiry
live.availableAlways false until TCP provides live data (TCP-REQ-10)

No customer data, contacts, device serials, settings, tariff, financials or org IDs.

// illustrative example — GET /v1/share-links/<share-token>
{ "plant": { "code": "PL-0518", "name": "DHA Phase 6 Residence", "plantType": "RESIDENTIAL", "city": "Karachi",
"region": "Sindh", "countryCode": "PK", "pvCapacityKwp": 12, "timezone": "Asia/Karachi", "gridTopology": "ON_GRID_BACKUP",
"hasBattery": true, "commissionedOn": "2025-03-03" }, "expiresAt": "2027-01-11T08:00:00.000Z", "live": { "available": false } }