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.
| Contract | Route | Section |
|---|---|---|
| C01 (web list) | GET /v1/plants with X-Org-Id | Web console plant list |
| C02 | GET /v1/plants/summary | Plant counts |
| C03 | GET /v1/plants/geo | Plant map points |
| C04 | POST /v1/plants with X-Org-Id | Web create |
| C05 | GET /v1/plants/{plantId} (mobile and web) | Plant detail |
| C06 | GET /v1/plants/{plantId}/workspace | Plant Workspace |
| C07 | PATCH /v1/plants/{plantId} with X-Org-Id | Web edit |
| C08, C09 | plant settings (alert rules, tariff) | Plant settings |
| C10, C10b | archive, restore, bulk archive | Archive and restore |
| C11 | DELETE /v1/plants/{plantId} with X-Org-Id | Platform delete |
| C12, C12b | plant tags, bulk tag, plant jobs | Plant tags |
| C13, C14 | share links | Share links |
| R-5 (2026-11-03) | plant ↔ Installer: assign, history | Assigned Installer |
| C15 | /v1/plant-drafts | Plant drafts |
| C16, A08 | saved views, favourites | Saved views, Favourites |
| C17, C18, C19 | customers, partners | Customers, Partners |
| C20 | tags | Tags |
| C21, C22 | dashboard, work queue | Dashboard |
| Business profile (FR-048) | org profile | Team → 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:
| Param | Type | Required | Default | Validation |
|---|---|---|---|---|
limit | integer | No | 25 | 1-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) |
cursor | string | No | — | 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
| Status | code | When |
|---|---|---|
| 200 | — | Success (including an empty list) |
| 401 | — (gateway body) | Missing/invalid token |
| 500 | INTERNAL | Unexpected 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 ≥ VIEWin the org named byX-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):
| Param | Type | Default | Validation |
|---|---|---|---|
lifecycle | ACTIVE | ARCHIVED | ACTIVE | Archived plants appear only with ARCHIVED |
plantType | enum, 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) |
countryCode | string | — | ISO alpha-2, single |
regionTagId | ULID, repeatable | — | Up to 5 |
tagId | ULID, repeatable | — | Up to 5, matched with OR |
customerOrgId | ULID | — | Single |
installerOrgId | ULID | — | Single |
assignedInstallerSub | string (Cognito sub) | — | Single; plants assigned to this Installer (R-5) |
capacityMin / capacityMax | number (kWp) | — | ≥ 0, inclusive, min ≤ max |
createdFrom / createdTo | ISO date-time | — | from ≤ to |
favorite | true | — | Only the caller's starred plants |
q | string | — | 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 |
operatorOrgId | ULID | — | 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 |
sort | name, -name, createdAt, -createdAt | name | See the table below |
limit | integer | 15 first page, 10 with cursor | 1–50; a sent value wins (lazy loading) |
cursor | string | — | From a previous nextCursor |
Which sorts are allowed depends on the filters, because each filter uses a different index:
| Filters sent | Allowed sort |
|---|---|
q | none (results come back in match order) |
favorite=true | none |
customerOrgId, installerOrgId, tagId, regionTagId, or no filter | name, -name |
sort=createdAt / -createdAt with no relationship filter | createdAt, -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
| Status | code | When | What the FE should do |
|---|---|---|---|
| 400 | VALIDATION_FAILED | Unknown 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 |
| 400 | INVALID_CURSOR | Malformed cursor, or a cursor reused after changing filters/sort | Drop the cursor and reload page 1 |
| 401 | — (gateway body) | Missing/expired token | Refresh the token and retry |
| 403 | FORBIDDEN | Not a member of X-Org-Id, or plants below VIEW | Show "no access"; switch org |
| 404 | NOT_FOUND | Platform 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 instead | Treat the org as unavailable; switch org |
| 403 | ACCOUNT_SUSPENDED | Org policy (feature 003) | Show suspended state |
| 422 | SCOPE_TOO_BROAD | The caller's scope has more than 10 targets | Show a message; an admin must narrow the scope |
| 500 | INTERNAL | Unexpected | Retry later |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB throttled/unavailable | Retry 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 org | Result |
|---|---|
| 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 membership | 200 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); nosort.
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
ACTIVEand not the PLATFORM org. Plants of a suspended or closed org are left out. Archived plants appear only withlifecycle=ARCHIVED, as in the per-org list. - Rows: every row carries
operatorOrgId.refs.orgs[operatorOrgId]gives that org'sname,codeandkind, pluspersonal: truefor a personal org (itskindisCUSTOMER). Open a row withX-Org-Id: <operatorOrgId>. - Filters and sorts: the same as the per-org list (
name/-nameby default,createdAt/-createdAt,q,favorite,customerOrgId,tagId,regionTagId, and the metadata filters), exceptinstallerOrgId, which needsoperatorOrgIdhere (400,details.field: installerOrgId).quses 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) is400 INVALID_CURSOR. - How it reads: each plant has a small
PLANT#<p>/LISTALLentry 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/summarystill needsoperatorOrgIdfrom 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
limititems and still carrynextCursor(filtered or scope-hidden rows). Keep paging untilnextCursoris 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 whilebusEnabledis off (every stage today), so ondevnew or renamed plants do not matchqat all (KI-43). - Mobile-created plants. Since 2026-11-03 (committed, not yet deployed),
mobile
POST /v1/plants(noX-Org-Id) writes a schema v2 plant in the owner's personal org:PL-code,lifecycle: ACTIVE,version: 1and GSI keys (createPlantMobileinpackages/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 withIf-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
200withitems: [].
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-Idrequired (else400 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
| Status | code | When | What the FE should do |
|---|---|---|---|
| 400 | ORG_CONTEXT_REQUIRED | No X-Org-Id | Send the selected org |
| 400 | VALIDATION_FAILED | Unknown param, operatorOrgId misuse | Fix the query |
| 401 | — | Token | Refresh and retry |
| 403 | FORBIDDEN | Not a member / plants below VIEW | Hide the counters |
| 404 | NOT_FOUND | Platform 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 instead | Treat the org as unavailable; switch org |
| 422 | SCOPE_TOO_BROAD | The caller's scope has more than 10 targets | Show a message; an admin must narrow the scope |
| 500 | INTERNAL | Unexpected | Retry later |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB | Retry 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-Idrequired. - Query: the same filters as the web list except
sort,qandfavorite;limit1–1000 (default 1000);cursor. - Rate limit: 5 requests per second per user →
429 RATE_LIMITEDwithRetry-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
operatorOrgIdto 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
| Status | code | When | What the FE should do |
|---|---|---|---|
| 400 | ORG_CONTEXT_REQUIRED / VALIDATION_FAILED / INVALID_CURSOR | As the web list; limit over 1000 | Fix the query / restart paging |
| 401 | — | Token | Refresh and retry |
| 403 | FORBIDDEN | No access | Hide the map |
| 422 | SCOPE_TOO_BROAD | Scope with more than 10 targets | Show a message |
| 429 | RATE_LIMITED | More than 5 req/s | Wait Retry-After seconds; debounce map pans |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB | Retry 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:
201with the createdPlant,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):
- The plant item,
PLANT#<id>/META, conditional on not existing, in schema v2: every submitted field (addressandelectricityRateas DynamoDB maps, omitted optional fields absent, notnull) pluscode,schemaVersion: 2,version: 1,lifecycle: ACTIVE,operatorOrgId=customerOrgId= the caller's personal org, and the GSI1/GSI2/GSI3 keys. - The caller's
OWNERmembership,USER#<sub>/PLANT#<id>, with the denormalised list fieldsname,status,timezoneandpvCapacityKwp. It stays a legacy membership row, so the app's plant list is unchanged. - The
CODE#<code>/GUARDitem. If the code is already taken, a fresh code is allocated and the write retried, up to 3 attempts, then409 CONFLICT. - The customer link
PLANT#<id>/CUSTOMER(personal org). - A
plant.upserted.v1outbox 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
capacityKwnumber and plain-stringaddress, and have noplantType/countryCode/solarMode/gridConnection(hasBatteryis derived, so it is always present).GETendpoints return stored attributes as-is, so a client may see that older shape on such rows. That's whydocs/openapi.yamldoesn't list those fields asrequiredonPlant. 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.PENDINGexists 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
EDITor higher in the org named byX-Org-Id. An End User connected to a Business holdsplants: VIEWthere (RBAC-S11, 2026-11-23), so they get403 FORBIDDEN; gate Add plant on theplant.createcapability inGET /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 is403. 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 with422)
Request body
| Field | Type | Required | Rules |
|---|---|---|---|
name | string | yes | 1-120 chars |
plantType | enum | yes | RESIDENTIAL, COMMERCIAL, INDUSTRIAL (other values → 422 VALIDATION_FAILED) |
countryCode | string | yes | ISO 3166-1 alpha-2 |
address | object | yes | formatted 1-400 (required), city, region up to 120, latitude and longitude (both required) |
timezone | string | when not PK | IANA zone; defaults to Asia/Karachi for PK |
systemType | enum | yes | PV_ONLY, PV_GRID, PV_BATTERY, PV_GRID_BATTERY, GRID_BATTERY, OTHER |
gridConnection | enum | yes | must agree with systemType (the grid part only — since 2026-11-18 the battery part of systemType is display-only) |
exportArrangement | enum | no | NET_METERING, EXPORT, NO_EXPORT; only when GRID_CONNECTED |
gridConnectedOn | date | no | only when GRID_CONNECTED |
pvCapacityKwp | number | when PV | required for every type except GRID_BATTERY, where it is forbidden |
batteries, hasBattery, batteryCapacityKwh, batteryPowerKw, batteryBrand, batteryBrandOther | any | no | Retired 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) |
expectedAnnualYieldKwh | number | no | greater than 0 |
installation | object | no | azimuthDeg integer 0-359, tiltDeg 0-90, selfConsumptionPct integer 0-100 |
installerOrgId | ULID | no | the operator org itself, or an ACTIVE partner with relationship INSTALLER. It grants no access. |
commissionedOn | date | no | at most today + 366 days |
financial | object | no | currency (required if the object is sent), installationCost and subsidyAmount 0 or more |
tariff | object | no | tariff v2 (tariffType, currency, importRate, exportRate); currency must equal financial.currency when both are sent |
customer | object | no | Optional 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 |
inviteCustomer | boolean | no (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 |
tagIds | ULID[] | no | up to 20 (more is 422 LIMIT_EXCEEDED), unique, ACTIVE plant tags, not system tags |
devices | array | no | up 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 |
draftId | ULID | no | your 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, orFORBIDDEN(caller lacks devicesEDITin 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).REGISTEREDis 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 withparallel: trueand an identical Nexus model. Otherwise TCP refuses with aPARALLEL_*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 }.createdistruewhen a new customer was made. Absent when the request had nocustomer; the plant'scustomerOrgIdis then the Business itself. -
invitation: present only withinviteCustomer: 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 andinvitationis 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
| Status | code | When | What the FE should do |
|---|---|---|---|
| 401 | (gateway body) | missing or expired token | refresh the token and retry |
| 403 | FORBIDDEN | plants below EDIT, or the plant would be outside your scope | show a permission message; for scoped users, ask them to pick one of their tags |
| 404 | NOT_FOUND | customerOrgId, installerOrgId, a tag or draftId not visible in the org | reload the picker lists and let the user choose again |
| 409 | INVALID_STATE | customer CHURNED, partner not ACTIVE or not INSTALLER, tag DELETING | reload the picker; show which choice is no longer valid |
| 409 | IDEMPOTENCY_IN_PROGRESS | the same key is still being processed | wait a second and retry with the same key |
| 409 | CONFLICT | transaction cancelled for an unattributable reason | retry with the same key |
| 413 | PAYLOAD_TOO_LARGE | body over 256 KB | not reachable with a valid body; report a bug |
| 422 | VALIDATION_FAILED | a field or cross-field rule, duplicate staged serials, inviteCustomer with no email available | show field errors on their wizard step |
| 422 | IDEMPOTENCY_KEY_REUSED | the same key with a different body | the body changed: generate a new key and resubmit |
| 422 | LIMIT_EXCEEDED | more than 20 tags or devices | cap tags and devices at 20 in the UI |
| 428 | PRECONDITION_REQUIRED | no Idempotency-Key (details.header: "Idempotency-Key") | always send one; this is a client bug |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB throttled or unavailable | retry 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
201body again withIdempotent-Replayed: true. No second plant or customer is made. A replay rebuilds the response from the stored plant, so it omitsinvitationeven 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-NNNNprofile and the plant are written in one transaction. Nothing is left half-created on failure. - Plant code
PL-NNNNis assigned when a web create commits and never changes afterwards. Plants created from the mobile app have nocodeuntil they are migrated or first edited on the web; treatcodeas 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 byplantIdrather 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.
| Operation | Method and path | Extra headers | Success |
|---|---|---|---|
| Create | POST /v1/plant-drafts | Idempotency-Key (required) | 201 summary, Location, ETag |
| List | GET /v1/plant-drafts?limit=&cursor= | none | 200 { items, nextCursor? } |
| Get | GET /v1/plant-drafts/{draftId} | none | 200 summary + body, ETag |
| Replace | PUT /v1/plant-drafts/{draftId} | If-Match (required) | 200 summary, expiry reset |
| Delete | DELETE /v1/plant-drafts/{draftId} | none | 204 |
| Submit | POST /v1/plant-drafts/{draftId}:submit | Idempotency-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
| Status | code | When | What the FE should do |
|---|---|---|---|
| 400 | ORG_CONTEXT_REQUIRED | no X-Org-Id | send the active org |
| 400 | INVALID_CURSOR | list cursor malformed or from another query | restart the list without a cursor |
| 403 | FORBIDDEN | plants below EDIT (create, submit) | hide "Save as draft" |
| 404 | NOT_FOUND | unknown, expired, already submitted, or another user's draft | remove it from the list and refetch |
| 409 | VERSION_CONFLICT | If-Match is stale (details.currentVersion) | GET the draft again, merge or ask the user, resend with the new ETag |
| 413 | PAYLOAD_TOO_LARGE | request over 256 KB, or a draft body over 64 KB serialised | tell the user the draft is too large |
| 422 | VALIDATION_FAILED | unknown key or bad partial field; on submit, the merged body is incomplete | on submit, open the wizard on the step with the error |
| 422 | LIMIT_EXCEEDED | already 50 drafts in this org | ask the user to delete old drafts |
| 428 | PRECONDITION_REQUIRED | missing 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
ETagfrom the last response (the quotedversion, e.g."2") asIf-Matchon replace and submit. Missing is428. Two tabs editing one draft: the second save gets409 VERSION_CONFLICT. - Idempotent create and submit: same key and same body replays the
original
201; same key and different body is422 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
404and 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'sOWNER/ADMIN/VIEWERaccess-index role, same as before 003 (FR-058) - Crown staff: a Super Admin or Administrator (an
ACTIVEmembership of the Crown platform org, scopeALL) passes for every plant, with no membership in the plant's own org (evaluator.ts, thePLATFORMaccess 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:
| Param | Type | Required |
|---|---|---|
plantId | string | Yes |
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
| Status | code | When |
|---|---|---|
| 200 | — | Success |
| 401 | — (gateway body) | Missing/invalid token |
| 403 | FORBIDDEN | No membership on plantId (covers both "not yours" and "doesn't exist") |
| 404 | NOT_FOUND | Caller has a membership record but the plant metadata item itself is missing (internal consistency fault). Body: {"error":{"code":"NOT_FOUND","message":"Plant not found"}} |
| 500 | INTERNAL | Unexpected 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
VIEWor higher, checked against the caller's live access (never taken from the token). - Response 200:
PlantDetailResponse, which is aPlantDetailplusrefs(display names for org and tag ids). Headers includeETag: "<version>". Store that value and send it back asIf-Matchon PATCH. PlantDetail(and the workspaceplant) also carriesinstalledBy?andassignedInstaller?(R-5), except for a caller whose only access is a low external tier (the same rule that hidesfinancialandinstallation).installer?{ orgId, name }(2026-11-27, owner decision): this is what every console "Installer" field shows. It is the plant's Business, meaningoperatorOrgIdand 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 workspaceplant. The console no longer displaysassignedInstallerorinstalledBy; both fields are still sent unchanged. TCP rows (list_plants, inventory, devices) should follow the same rule:operatorOrgIdplus itsorg.upserted.v1name, absent whenpersonal.PlantDetailcontains everyPlantfield pluscode,version,schemaVersion,lifecycle,operatorOrgId,customerOrgId,installerOrgId?,tagIds,regionTagId?,systemType?,exportArrangement?,gridTopology,gridConnectedOn?,expectedAnnualYieldKwh?,installation?,commissionedOn?,financial?,deviceCount?,archivedAt?andneedsCompletion?.- Legacy plants (plants the mobile app created before mobile create wrote schema v2, 2026-11-03) are mapped when read. They report
version: 0and aneedsCompletionlist of the wizard fields still missing. Show a "complete this plant" prompt, then save withIf-Match: "0". - Redaction: when the caller's only access is external
VIEW/MONITOR(a customer portal or a share), the response has nofinancialand noinstallation.
// 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" } } } }
| Status | code | When | What the FE should do |
|---|---|---|---|
| 200 | — | OK | cache the ETag for editing |
| 403 | FORBIDDEN | the plant is visible but plants access is below VIEW | show a permission message |
| 404 | NOT_FOUND | unknown id, or no access path at all. The web variant never reveals whether the plant exists | show "not found" |
| 410 | GONE | plant 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-Idis optional because the org is taken from the plant. Requires plantsVIEWor higher. - Response 200:
WorkspaceResponseplus anETagheader (the plant's version). It contains:plantandrefs, as in the web detail.plantis the whole plant record: name, status, timezone, address,pvCapacityKwp, plant type, grid/battery fields, tariff (electricityRate) and everything else inPlantDetail, so a page that has the workspace does not also needGET /v1/plants/{plantId}. Since 2026-11-17plant.roleis also set: the sameOWNER/ADMIN/VIEWERthe mobile detail reports (the caller's mobile membership role, elseVIEWER).viewer.levelsandviewer.capabilities, a subset ofplant.edit,plant.archive,plant.delete,plant.tag,plant.share,alertRules.edit,tariff.edit,access.request,service.createanddevice.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 —sourceis alwaysBINDINGS(the plant ↔ serial bindings).devices[]rows are{ serial?, label?, createdAt }(up to 200;serialleft out for externalVIEW/MONITORcallers) andtruncated. Device detail and status come from TCP.stagedDevices.settings:alertRules(defaults withversion: 0if never saved),tariff(ornull) andshareLink(active,linkId?,expiresAt?). The share-link token is never returned.access:customerPortalLevel?,installerOrgId?andshareCount.counts.openWorkOrders:nulluntil the feature that owns it ships.
- Redaction: below plants
EDIT, the response has nostagedDevices,settingsoraccess. Device serials are left out for externalVIEW/MONITORcallers.plant.deleteappears only for Crown platform members with plantsFULL. - 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 ≥ EDITthrough the access evaluator. On a mobile-created plant that means the caller's role isOWNERorADMIN. AVIEWERgets403. - Idempotency: No
Idempotency-Keyand noIf-Match. Sending the same edit twice gives the same result.
Request
Headers:
| Header | Required | Notes |
|---|---|---|
Authorization: Bearer <token> | Yes | |
Content-Type: application/json | Yes | This 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:
| Param | Type | Required |
|---|---|---|
plantId | string | Yes |
Body: an object with at least one of these fields. Each follows the same rule as on create.
| Screen row | Field(s) | Type | Rules |
|---|---|---|---|
| Plant Name | name | string | 1–120 characters, trimmed |
| Plant Type | plantType | enum | RESIDENTIAL, COMMERCIAL, INDUSTRIAL (other values → 422 VALIDATION_FAILED) |
| Location | address | object | formatted ≤ 400, city ≤ 120, region ≤ 120, latitude + longitude sent together. Replaced whole: send the full new address, not one part of it |
| Location | countryCode | string | ISO 3166-1 alpha-2 (PK), case-insensitive |
| Location | timezone | string | IANA name (Asia/Karachi). Required when countryCode changes to a country other than PK. Changing to PK without one sets Asia/Karachi |
| PV Capacity | pvCapacityKwp | number | > 0, ≤ 100000 |
| Solar Usage | solarMode | enum | NONE, SELF_CONSUMPTION, GRID_EXPORT, SELF_CONSUMPTION_GRID_EXPORT |
| Grid Connection | gridConnection | enum | GRID_CONNECTED, OFF_GRID |
batteries, hasBattery, batteryCapacityKwh, batteryPowerKw, batteryBrand, batteryBrandOther | any | Not 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 Rate | electricityRate | object | { 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:
nullor""means "not sent", as on create. It never clears a value. A body where every field isnullis a422("at least one field is required").- Clearing happens through the switch, not the value.
solarMode: "NONE"removes the storedpvCapacityKwp. Sending the value together with that switch is a422, the same as on create. hasBatteryin the response is derived (2026-11-18):truewhen 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 a422when the storedsolarModeexports. Sending onlysolarMode: "SELF_CONSUMPTION"on a plant with no solar is a422unlesspvCapacityKwpis sent too. - Unknown fields, and server-owned fields such as
statusorplantId, are422. plantTypeaccepts onlyRESIDENTIAL,COMMERCIAL,INDUSTRIAL(anything else →422). A plant still storing a retiredUTILITY/OTHERis returned asINDUSTRIAL/COMMERCIAL, the same as onGET.
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
capacityKwcounts aspvCapacityKwp(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
pvCapacityKwpdeletes the oldcapacityKw, so the two can't disagree. - Setting
solarModeto anything other thanNONEon such a plant needspvCapacityKwpin 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
| Status | code | When |
|---|---|---|
| 200 | — | Updated |
| 400 | MALFORMED_REQUEST | Body isn't valid JSON, or isn't a JSON object |
| 401 | — (gateway body) | Missing or invalid token |
| 403 | FORBIDDEN | The caller can see the plant but is a VIEWER |
| 404 | NOT_FOUND | No access to the plant, or it doesn't exist (unlike GET's 403) |
| 409 | CONFLICT | Another 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 |
| 409 | INVALID_STATE | Organisation-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 |
| 413 | PAYLOAD_TOO_LARGE | Body over 256 KB |
| 415 | UNSUPPORTED_MEDIA_TYPE | Content-Type isn't application/json |
| 422 | VALIDATION_FAILED | Empty body, unknown field, a per-field rule, or a cross-field rule on the merged plant |
| 500 | INTERNAL | Unexpected server error |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB 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
EDITor higher. ChangingcustomerOrgIdalso needs customersEDITin the operator org. An End User connected to a Business holdsplants: VIEWon its plants (RBAC-S10, 2026-11-23):403 FORBIDDEN, and the workspaceviewer.capabilitiescarry noplant.edit,tariff.edit,alertRules.editorplant.sharefor them. - Headers:
X-Org-IdandIf-Match: "<version>"are required. Take the version from theETagof 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
nullclears it, which is allowed only forexportArrangement,gridConnectedOn,pvCapacityKwp,expectedAnnualYieldKwh,installation,installerOrgId,commissionedOnandfinancial. The non-nullable fields arename,plantType,countryCode,address,timezone,systemType,gridConnectionandcustomerOrgId. 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:
PlantDetailResponsewith a newETag. - 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 }
| Status | code | When | What the FE should do |
|---|---|---|---|
| 200 | — | updated | replace the cached plant and ETag |
| 400 | MALFORMED_REQUEST | invalid JSON or a malformed If-Match | client bug |
| 403 | FORBIDDEN | below plants EDIT, or customers EDIT missing for a customer change | hide the edit control |
| 404 | NOT_FOUND | the plant is not visible | show "not found" |
| 409 | VERSION_CONFLICT | stale If-Match (details.currentVersion) | reload, show the latest values, let the user re-apply |
| 409 | INVALID_STATE | plant ARCHIVED, customer CHURNED, or the partner is not an INSTALLER | restore first, or pick another customer or partner |
| 409 | INVALID_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 normally | retrying will not help; report it |
| 410 | GONE | plant DELETING | remove it from lists |
| 422 | VALIDATION_FAILED | field or cross-field rule, server-owned field, null on a required field, empty body | show field errors |
| 428 | PRECONDITION_REQUIRED | no 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-Matchand noIdempotency-Key: both calls are naturally idempotent. Attaching a tag that is already there, or removing one that isn't, returns200with the current state. - Each real change bumps the plant
version, updates tag counts and search, and publishesplant.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.
| Status | code | When | What the FE should do |
|---|---|---|---|
| 401 | — (gateway body) | Missing/expired token | Refresh token, retry |
| 403 | FORBIDDEN | plants below EDIT on this plant | Hide "Add tag" |
| 404 | NOT_FOUND | Plant or tag not found, or you have no access to the plant (non-members get 404, not 403) | Refresh |
| 409 | INVALID_STATE | Plant created by the mobile app and never saved on the web | Ask the user to open and save it on the web first |
| 409 | INVALID_STATE | System REGION tag, tag is DELETING, or plant is ARCHIVED | Explain; REGION tags follow the address |
| 409 | CONFLICT | Concurrent change to the plant | Retry |
| 410 | GONE | Plant is being deleted | Remove it from the view |
| 422 | LIMIT_EXCEEDED | The plant would have more than 20 tags (PUT) | Ask the user to remove one first |
| 422 | VALIDATION_FAILED | Tag's appliesTo doesn't include PLANT | Offer only plant tags |
| 500 / 503 | INTERNAL / DEPENDENCY_UNAVAILABLE | Server / DynamoDB | Retry (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 field | Type | Rules |
|---|---|---|
add | ULID[] | 1–10 tag ids |
remove | ULID[] | 1–10 tag ids; none may also be in add |
plantIds | ULID[] | 1–200 |
filter | object | The 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.
| Status | code | When | What the FE should do |
|---|---|---|---|
| 400 | ORG_CONTEXT_REQUIRED | No X-Org-Id | Send the active org |
| 400 | MALFORMED_REQUEST | Body not JSON | Fix the client |
| 404 | NOT_FOUND | Path 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-Id | Fix the URL / refresh the tag picker / switch org |
| 409 | INVALID_STATE | A system REGION tag in add/remove, or a tag in add is DELETING (details.tagId) | Remove it from the picker |
| 409 | IDEMPOTENCY_IN_PROGRESS | Same key still processing | Retry later with the same key |
| 415 | UNSUPPORTED_MEDIA_TYPE | No JSON content type | Fix the client |
| 422 | LIMIT_EXCEEDED | More than 200 plantIds or more than 10 tag ids (details.limit, details.field) | Split the selection or use filter |
| 422 | VALIDATION_FAILED | Neither 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 |
| 422 | IDEMPOTENCY_KEY_REUSED | Same key, different body | New key per new action |
| 428 | PRECONDITION_REQUIRED | No Idempotency-Key | Always send one |
| 503 | DEPENDENCY_UNAVAILABLE | Job-sized request with no plant-jobs queue (details.dependency: "plant-jobs"), or DynamoDB unavailable | For 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 gets404.X-Org-Idis optional and never widens access. - Query:
limit(1–50, default 25) andcursorpage throughfailures.
{ "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-Idis optional. Access is checked on the plant itself, and the header never widens it. - Headers:
If-Match(required, else428),Content-Type: application/json. NoIdempotency-Key. - Versioning:
If-Matchis the settings item's version, not the plant's. The workspace (GET /v1/plants/{plantId}/workspace) returnssettings.alertRules.version, which is0when nothing has been saved yet. SendIf-Match: "0"to create. The responseETagis the new settings version. Every save also bumps the plant's ownversion, so re-read the plantETagbefore a laterPATCH. - Archived plants are read-only:
409 INVALID_STATE.
PUT /v1/plants/{plantId}/settings/alert-rules: alert rules (C08)
- AuthZ:
alerts≥ MANAGE.
| Field | Type | Rules (default) |
|---|---|---|
underperformance.enabled | boolean | (true) |
underperformance.thresholdPct | integer | 5–90 (25) |
underperformance.windowMin | integer | 30–720 (120) |
communicationLoss.enabled | boolean | (true) |
communicationLoss.afterMin | integer | 5–1440 (30) |
batteryTemperature.enabled | boolean | Defaults 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.maxC | number | 20–80 (45) |
notifyEmail | boolean | (true) |
escalateCriticalSms | boolean | (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).
| Field | Type | Rules |
|---|---|---|
currency | string | ISO 4217, required (upper-cased) |
tariffType | enum | FLAT | TIME_OF_USE | NET_METERING | NET_BILLING, required |
importRate | number | 0–100 000. Required unless TIME_OF_USE |
exportRate | number | 0–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.degradationPctPerYear | number | 0–5 (0.5) |
assumptions.tariffEscalationPctPerYear | number | 0–50 (4) |
effectiveFrom | string | YYYY-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)
| Status | code | When | What the FE should do |
|---|---|---|---|
| 400 | MALFORMED_REQUEST | Body is not a JSON object, or If-Match is not a version | Fix the request |
| 401 | — (gateway body) | Missing/expired token | Refresh and retry |
| 403 | FORBIDDEN | alerts < MANAGE (C08) / plants < EDIT (C09) | Hide the Save button (use workspace viewer.capabilities) |
| 404 | NOT_FOUND | Unknown plant or no access path | Leave the workspace |
| 409 | VERSION_CONFLICT | Stale If-Match (details.currentVersion) | Re-fetch the workspace, re-apply, re-submit |
| 409 | INVALID_STATE | Plant is ARCHIVED, or a legacy plant never saved on the web | Show "restore first" / "complete the plant first" |
| 409 | CONFLICT | The plant changed at the same moment | Retry once |
| 410 | GONE | Plant is being deleted or was deleted | Leave the workspace |
| 415 | UNSUPPORTED_MEDIA_TYPE | Missing Content-Type: application/json | Send the header |
| 422 | VALIDATION_FAILED | Bounds, unknown field, battery rule, exportRate on OFF_GRID, NET_BILLING without exportRate, TOU overlap/gap (see below), touSchedule outside TIME_OF_USE | Show details.fieldErrors next to the fields |
| 428 | PRECONDITION_REQUIRED | No If-Match | Send "0" (first save) or the current version |
| 500 / 503 | INTERNAL / DEPENDENCY_UNAVAILABLE | Unexpected / DynamoDB | Retry 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>.
| Problem | Message |
|---|---|
| Two periods overlap | MON: periods 0 and 1 overlap (17:00-18:00) |
| A gap between periods | SAT: 10:00-11:00 is not covered |
| A day with a short end, or no periods at all | MON: 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-Idis optional. - Headers:
If-Match(plantversionfrom the detailETag; required, else428).Idempotency-Keyis 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 are422. - Response
200: the plant detail withrefs(same shape asGET /v1/plants/{plantId}withX-Org-Id),lifecyclenowARCHIVED/ACTIVE, and anETagwith 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.
| Status | code | When | What the FE should do |
|---|---|---|---|
| 400 | MALFORMED_REQUEST | Body not a JSON object / bad If-Match | Fix the request |
| 401 | — | Token | Refresh and retry |
| 403 | FORBIDDEN | plants < MANAGE | Hide Archive/Restore |
| 404 | NOT_FOUND | Unknown verb, unknown plant, or no access path | — |
| 409 | INVALID_STATE | Archive when not ACTIVE, restore when not ARCHIVED, or a legacy plant never saved on the web | Re-fetch; the plant is probably already in that state |
| 409 | VERSION_CONFLICT | Stale If-Match | Re-fetch and confirm again |
| 409 | CONFLICT / IDEMPOTENCY_IN_PROGRESS | Concurrent change / the first call with this key is still running | Retry shortly |
| 410 | GONE | Plant is being deleted | Leave the page |
| 415 | UNSUPPORTED_MEDIA_TYPE | Body sent without JSON content type | Send the header |
| 422 | VALIDATION_FAILED / IDEMPOTENCY_KEY_REUSED | Bad body / same key with a different body | Fix / use a new key |
| 428 | PRECONDITION_REQUIRED | No If-Match | Send the version |
| 500 / 503 | INTERNAL / 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 inX-Org-Id(else403), and checked again for each plant. - Headers:
X-Org-Id(required, else400 ORG_CONTEXT_REQUIRED),Idempotency-Key(required, else428),Content-Type: application/json. - Body: exactly one of
plantIds(ULID[] 1–200, duplicates collapsed) orfilter(the web plant-list filters). Items carry noIf-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).ADMINandVIEWERmembers can't delete. - Idempotency: No
Idempotency-Key. Deleting twice is harmless; the second call returns404.
Request
Headers: Authorization: Bearer <token> (required). No body, so no
Content-Type.
Path parameters:
| Param | Type | Required |
|---|---|---|
plantId | string | Yes |
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):
- 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. - Every item whose GSI1 key is
PLANT#<id>: every user's access-index row for the plant (other members drop the plant fromGET /v1/plantsimmediately) and any tag links. - Last, in one conditional transaction: the plant item
PLANT#<id>/METAand the owner's own access-index row. - 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 itsSERIALBIND#guard are deleted byunbindAllBindingsForPlant, 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, metricPlantDeviceReleaseFailed) 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
| Status | code | When |
|---|---|---|
| 204 | — | Deleted |
| 401 | — (gateway body) | Missing or invalid token |
| 403 | FORBIDDEN | The caller can see the plant but isn't its OWNER |
| 404 | NOT_FOUND | No access to the plant, it doesn't exist, or it was already deleted |
| 409 | INVALID_STATE | Organisation-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 |
| 409 | CONFLICT | The plant or the owner's role changed during the delete. Retry. |
| 500 | INTERNAL | Unexpected server error |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB 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
202body, and a laterGETreturns404, not410.plant.deletion.requested.v1is published in the same transaction as the META delete, because TCP frees the devices only on that event. TCP'splant.erasure.completed.v1reply finds no plant and is logged as already done. Nothing is recorded for theIdempotency-Key: a retry returns404. - Headers:
X-Org-Id(selects this variant),If-Match(plantversion) andIdempotency-Key. Both are required, else428 PRECONDITION_REQUIREDwithdetails.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.
| Status | code | When | What the FE should do |
|---|---|---|---|
| 400 | MALFORMED_REQUEST | If-Match is not a version | Fix the header |
| 401 | — | Token | Refresh and retry |
| 403 | FORBIDDEN | Not platform staff with plants = FULL | Hide Delete |
| 404 | NOT_FOUND | Unknown plant or no access path | — |
| 409 | INVALID_STATE | Already 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 |
| 409 | VERSION_CONFLICT | Stale If-Match | Re-fetch and confirm again |
| 409 | CONFLICT / IDEMPOTENCY_IN_PROGRESS | Concurrent change / first call with this key still running | Retry shortly |
| 410 | GONE | Already erased (tombstone; not reachable until erasure cleanup is built) | Treat as deleted |
| 422 | IDEMPOTENCY_KEY_REUSED | Same key, different request | Use a new key |
| 428 | PRECONDITION_REQUIRED | Missing If-Match or Idempotency-Key | Send both |
| 500 / 503 | INTERNAL / 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≥MANAGEon that path. That only happens when the Business setpermsLimitorportalPermsLimit{ "sharing": "MANAGE" }on aFULLgrant (Shares). Callers whose sharing comes from an organisation membership usePOST /v1/orgs/{orgId}/sharesinstead. - Headers:
Idempotency-Keyrequired (428if missing). - Body (strict; unknown keys →
422):
| Field | Type | Required | Notes |
|---|---|---|---|
grantee | { kind: "USER", sub?: string, email?: string } | Yes | Individuals only (no ORG). One of sub or email; email is trimmed and lower-cased, ≤ 254. |
level | VIEW | MONITOR | EDIT | SERVICE | FULL | Yes | Never above your own access. |
permsLimit | PermsLimit | No | sharing is always forced to NONE: a re-share can never be re-shared. |
expiresAt | ISO-8601 date-time | No | |
note | string ≤ 500 | No |
// 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") withparent, plusinvitationwhen 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 }
| Status | Code | When | FE action |
|---|---|---|---|
| 400 | MALFORMED_REQUEST | Body is not a JSON object | Bug |
| 401 | UNAUTHORIZED | Missing or expired token | Re-auth |
| 403 | FORBIDDEN | No share/portal path with sharing ≥ MANAGE; or details.reason: "ESCALATION" — level after permsLimit exceeds your own access | Hide "Share", or offer a lower level |
| 404 | NOT_FOUND | You have no access to the plant | Treat as gone |
| 409 | INVALID_STATE | Your sharing comes from an org membership (use the org share screen), or a legacy plant never saved on the web | Show the message |
| 409 | ALREADY_EXISTS | That person already has a share of this plant | Show "already shared" |
| 410 | GONE | Plant is being deleted | Remove from UI |
| 422 | VALIDATION_FAILED | Bad body, neither sub nor email, or sharing with yourself (details.field: "grantee.sub") | Fix the form |
| 428 | PRECONDITION_REQUIRED | No Idempotency-Key | Bug |
| 500 | INTERNAL | Unexpected | Retry later |
| 503 | DEPENDENCY_UNAVAILABLE | DynamoDB 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
(
parentset) 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):
| Field | Type | Rules |
|---|---|---|
plantId | ULID | the plant to transfer |
email | string | the receiver's email, trimmed and lower-cased, ≤ 254; must belong to a registered account |
businessOrgId | ULID | optional, 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 Business | the 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 Business | refused: 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 to | customerSub |
|---|---|---|
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: true | the receiver |
in no Business, no businessOrgId | their personal org (created, or reopened if closed); they stay independent | — |
| an End User of a Business | that Business (the plant also joins their scope) | the receiver |
| a Business-role user, an Installer or other staff of a Business | that 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 acting | reason | error.message (exact text) | Extra details |
|---|---|---|---|
| A Business (owner / Installer) shares with someone in another Business | USER_IN_ANOTHER_ORG | This 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 Business | USER_IN_ANOTHER_ORG | This 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 Business | ALREADY_IN_BUSINESS | You 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 since | ALREADY_IN_BUSINESS | This 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):
| Case | operatorOrgId | customerSub | ownerUserSub |
|---|---|---|---|
| Business mode | the Business (unchanged) | receiver | receiver |
| Platform → independent user | receiver's personal org | absent | receiver |
Platform → independent user + businessOrgId | the picked Business | receiver | receiver |
| Platform → End User of a Business | that Business | receiver | receiver |
| Platform → Business-role user / Installer | that Business | absent | receiver |
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, andplant.upserted.v1carries the newoperatorOrgId. (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-unshareswas 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
| Status | code / reason | When |
|---|---|---|
| 403 | FORBIDDEN | not Crown staff and not the Business role / an Installer of the Business; plants below EDIT (Business) or MANAGE (Crown); a delegated (partner) caller |
| 403 | FORBIDDEN PLANT_BLOCKED | the plant is frozen by Block B |
| 404 | NOT_FOUND | no membership in {orgId}, or the plant is not in that org |
| 404 | NOT_FOUND USER_NOT_REGISTERED | no account has this email |
| 409 | VERSION_CONFLICT | If-Match is not the current plant version |
| 409 | CONFLICT USER_IN_ANOTHER_ORG | Business 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 |
| 409 | CONFLICT NOT_AN_END_USER | Business mode: the receiver is staff of this Business |
| 409 | CONFLICT PLANT_HAS_CUSTOMER | Business mode: the plant already belongs to a customer |
| 409 | CONFLICT INVITATION_PENDING | Business mode: the email has a pending invitation to the Business (details.inviteId) — revoke it first |
| 409 | CONFLICT ALREADY_OWNER | Platform mode: the receiver already owns the plant where it is |
| 409 | CONFLICT MOVE_IN_PROGRESS | the receiver's plants are still being moved; retry in a minute |
| 409 | CONFLICT PLANT_CHANGED / RECEIVER_CHANGED | changed meanwhile; reload and retry |
| 409 | INVALID_STATE NOT_A_BUSINESS, BUSINESS_NOT_ACTIVE | Business mode: {orgId} is not an ACTIVE Business; Platform mode: the picked businessOrgId is not an ACTIVE Business (missing → 404) |
| 409 | INVALID_STATE MEMBER_NOT_ACTIVE | the receiver's membership is suspended |
| 409 | INVALID_STATE ACCOUNT_BLOCKED | the receiver's account is blocked |
| 409 | INVALID_STATE | the plant is archived or being deleted |
| 422 | VALIDATION_FAILED | bad body; businessOrgId sent by a Business caller |
| 422 | LIMIT_EXCEEDED | the receiver already holds 50 memberships |
| 428 | PRECONDITION_REQUIRED | If-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):
| Field | Type | Required | Notes |
|---|---|---|---|
plantId | ULID | yes | |
email | string (email, ≤ 254) | yes | trimmed and lower-cased |
businessOrgId | ULID | no | Crown 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:
- Caller and plant checks run first and fail as errors, exactly as on the transfer:
403/404/409PLANT_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. - The per-caller rate limit: 20 checks per minute and 200 per day, then
429 RATE_LIMITEDwithRetry-After. This step is there because the check reveals whether an email has an account. - The email is resolved with Cognito
ListUsers(exactemailfilter). If no account has it, the answer isfound: false. - Recipient checks: blocked account, plant move running, memberships, pending invitation, already owner. A refusal
comes back as
200witheligible: false, the transfer'sreasonand itsmessage.
Response 200:
| Field | Type | Notes |
|---|---|---|
found | boolean | false 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. |
eligible | boolean | true means the transfer would be accepted right now |
reason | string | null | null 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 |
message | string | null | Added 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_OWNERis only found when the person already has one.
Errors
| Status | code / reason | When |
|---|---|---|
| 403 | FORBIDDEN | as on the transfer: not allowed to transfer in {orgId}, plants too low, a delegated (partner) caller |
| 403 | FORBIDDEN PLANT_BLOCKED | the plant is frozen by Block B |
| 404 | NOT_FOUND | no membership in {orgId}; the plant is not in that org; a picked businessOrgId does not exist |
| 409 | CONFLICT PLANT_HAS_CUSTOMER | Business mode: the plant already belongs to a customer |
| 409 | INVALID_STATE NOT_A_BUSINESS, BUSINESS_NOT_ACTIVE | {orgId} (Business mode) or the picked businessOrgId (Platform mode) is not an ACTIVE Business |
| 409 | INVALID_STATE | the plant is archived or being deleted, or has no org yet |
| 422 | VALIDATION_FAILED | bad body; businessOrgId sent by a Business caller |
| 429 | RATE_LIMITED | more 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.
| Event | New 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 User | the caller |
| A Business owner or Installer who owns plants leaves the Business | the Business owner |
Web PATCH setting customerOrgId to an end user's personal org | that end user |
| Plant delete | unchanged 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:
| Field | Meaning | Changes |
|---|---|---|
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 ≥ MANAGEin the plant's Business (the Business role holds it; the Installer template does not). A scoped caller's own scope must cover the plant, otherwise404. Super Admin and Admin reach it through the platform fallback. - Headers:
If-Match: "<plant version>"(required; missing428, stale409 VERSION_CONFLICT). NoIdempotency-Key(versioned). - Body (strict):
{ "sub": "<memberSub>" }to assign or move,{ "sub": null }to unassign. The target must be an ACTIVE member of the Business, otherwise404 NOT_FOUND. - Effect (one transaction): plant
version+ 1 andassignedInstallerset (or removed); the previous Installer loses the access that came only from the assignment and getsaccess.revoked.v1(scopeUSER,plantIds, reasonINSTALLER_REASSIGNED); a history entry;PLANT_INSTALLER_CHANGEDin the Business's access log;plant.upserted.v1withassignedInstallerSub. Shares the previous Installer made, and End Users' access, are unchanged.installedBynever 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" }
}
| Status | code | When |
|---|---|---|
| 403 | FORBIDDEN | plants below MANAGE in the Business |
| 404 | NOT_FOUND | Plant not visible (or not a web plant), or the target is not an ACTIVE member |
| 409 | VERSION_CONFLICT / INVALID_STATE | Stale If-Match / plant being deleted |
| 422 | VALIDATION_FAILED | Body shape |
| 428 | PRECONDITION_REQUIRED | If-Match missing |
GET /v1/plants/{plantId}/installer-history
- Authorization:
plants ≥ VIEWin the plant's Business (scope must cover the plant). - Query:
limit(1 to 50; default 15 on the first page, 10 with acursor(lazy loading)),cursor. - Response
200:{ installedBy?, items: [{ at, by, from, to }], nextCursor? }, oldest first.from/toare{ sub, displayName }ornull. When the creator was auto-assigned, the first entry is that registration (from: null). Abythat was Crown staff acting through platform access carriesviaPlatform: trueand, for a reader outside the Crown org, reads as{ "displayName": "Crown Support", "viaPlatform": true }with nosub(RBAC-S3, 2026-11-23 — before this the marker was dropped and the staff member was named).
Share links (C13, C14)
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 ≥ EDITandsharing ≥ MANAGE(Business and Installers since 2026-11-26; a connected End User holdssharing: VIEW) — else403 FORBIDDEN. Whether customer-portal users may share is still open (OQ-06). - Headers:
Idempotency-Keyrequired (428if 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
urlstraight away. An idempotent replay of the same request returns201withouturland with"tokenShownOnce": true. If the user lost the link, create a new one. urlis<SHARE_LINK_BASE_URL>/share/<share-token>.SHARE_LINK_BASE_URLcomes from the CDK context keyshareLinkBaseUrl(the console's public https origin, see Operations). dev sets it tohttps://cse-admin-web.vercel.appincdk.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 readsGET /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 atexpiresAt(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 theurlreturned by create. - Public share page: this repo defines no host for a public share page. Create builds
urlas${SHARE_LINK_BASE_URL}/share/<token>(packages/core/src/plants/share-links.ts), whereSHARE_LINK_BASE_URL(packages/core/src/config.ts) is set on every API function from-c shareLinkBaseUrl(lib/route-family.ts). It must be anhttps://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 againstexpiresAt. - 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
429with{"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):
| Field | Notes |
|---|---|
plant.code, plant.name, plant.plantType | Always present |
plant.city, plant.region, plant.countryCode | When set. No street, no coordinates |
plant.pvCapacityKwp, plant.timezone | When set |
plant.gridTopology, plant.commissionedOn | When set |
plant.hasBattery | Always (derived from the plant's devices, 2026-11-18) |
expiresAt | Link expiry |
live.available | Always 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 } }