Reports and schedules (H01–H06)
:::info Routed
List reports is GET /v1/orgs/{orgId}/reports (ListReports, H01a).
/v1/reports has no GET — it is POST only (create/generate, H02).
Every route on this page is registered in lib/routes.ts (batch 69, route
area reports, stack cse-http-be-<stage>-api-reports) with the Cognito
authorizer, and documented in docs/openapi.yaml. The stack is created by a
default cdk synth; the web team observed these routes answering on dev on
2026-10-28. No execution has been
captured yet: every example here is illustrative, derived from the
schemas in packages/core/src/schemas.ts and the handlers in
packages/api/src/handlers/*report*.ts. Email delivery (H03c, schedule email)
stays blocked by B-02.
:::
:::warning Report pipeline gate — 503 DEPENDENCY_UNAVAILABLE
Routes that generate or dispatch a report need the report pipeline
(ReportsStack: dispatch queue, runs queue, Scheduler group), which exists
only on a stage deployed with -c busEnabled=true. On a stage without it these
routes answer 503 DEPENDENCY_UNAVAILABLE before any read or write (no
idempotency record, no report, no schedule is stored) and before the
Idempotency-Key check. Only a missing If-Match on :regenerate and
:resume is reported earlier (428, details.header: "If-Match"):
| Route | details.dependency |
|---|---|
POST /v1/reports (H02), POST /v1/reports/{reportId}:regenerate (H03a), POST /v1/plants/{plantId}/reports (H06) | report-pipeline |
POST /v1/orgs/{orgId}/report-schedules (H05b), :resume (H05f), :run-now (H05g) | report-scheduler |
Read routes (library, summary, detail, download, templates, schedule list/get)
and delete / update / :pause work regardless.
Second gate — generation switched off (422 REPORTS_GENERATE_DISABLED)
Even with the pipeline deployed, generation stays off until the owner
deploys with -c reportsGenerateEnabled=true (default off; env
REPORTS_GENERATE_ENABLED). While off, H02, :regenerate, H06, schedule create
(H05b), :resume and :run-now answer 422 UNSUPPORTED_OPERATION with
details.reason: "REPORTS_GENERATE_DISABLED" before any write, and report
detail never offers the report.regenerate capability. Order of checks:
- Missing
If-Match(:regenerate,:resumeonly) →428 - Pipeline not deployed →
503 DEPENDENCY_UNAVAILABLE - Schedule create /
:resume/:run-now: generation off →422 REPORTS_GENERATE_DISABLED, then missingIdempotency-Key→428 - H02 /
:regenerate/ H06: missingIdempotency-Key→428, then generation off →422 REPORTS_GENERATE_DISABLED
FE: on the 422 show "Report generation is not enabled yet" and hide or
disable Generate / Regenerate / Run now / Resume / New schedule; do not retry.
On the pipeline 503 show "Reports are unavailable right now" and disable the
Generate / Run now / Resume actions. Do not retry in a loop — the answer
will not change until the backend is redeployed. A transient 503 (AWS
dependency failure, no details.dependency above) may be retried once with
backoff using the same Idempotency-Key.
:::
Reports are files rendered by the TCP side (it owns the telemetry). This
API owns the report record, the library, templates, schedules, access control
and signed download URLs. No response here contains any telemetry value. See
Reports pipeline for how a report goes
from QUEUED to READY.
Common rules
| Topic | Rule |
|---|---|
| Auth | Cognito JWT on every route. Missing/invalid → gateway 401 {"message":"Unauthorized"} |
| Org context | POST /v1/reports needs X-Org-Id (missing → 400 ORG_CONTEXT_REQUIRED). /v1/reports/{reportId} and /v1/report-schedules/{scheduleId} take the org from the record, never the header |
| Non-disclosure | No path to the report/schedule → 404 NOT_FOUND; visible but level too low → 403 FORBIDDEN |
| AuthZ | reports permission category (NONE<VIEW<EDIT<MANAGE<FULL), read live from DynamoDB |
| Concurrency | Mutations of an existing record need If-Match: "<version>": absent → 428 PRECONDITION_REQUIRED, stale → 409 VERSION_CONFLICT (details.currentVersion). Responses carry ETag |
| Idempotency | Idempotency-Key (1–128, [A-Za-z0-9_-]) required where marked: absent → 428; replay → original response + Idempotent-Replayed: true; same key, different body → 422 IDEMPOTENCY_KEY_REUSED; in flight → 409 IDEMPOTENCY_IN_PROGRESS |
| Pagination | limit 1–50 (default 15 on the first page, 10 with a cursor — lazy loading), opaque cursor; bad cursor → 400 INVALID_CURSOR |
| Validation | Bodies are strict: unknown field / bad enum → 422 VALIDATION_FAILED (details.fieldErrors); unknown query param → 400 VALIDATION_FAILED (details.allowed); bad JSON → 400 MALFORMED_REQUEST |
| Errors | { "error": { "code", "message", "details"?, "requestId" } } |
| Dependencies | DynamoDB/S3/Scheduler failure → 503 DEPENDENCY_UNAVAILABLE (retry with the same Idempotency-Key); report pipeline not deployed → 503 on generating routes (see the gate above) |
| Caching | Cache-Control: no-store (templates: private, max-age=300) |
Codes. Report codes RPT-YYYY-NNNN are numbered platform-wide;
schedule codes SCH-NN are numbered per org.
Shared shapes
// ReportPeriodInput
{ "preset": "LAST_MONTH" } | { "preset": "CUSTOM", "from": "2026-08-01", "to": "2026-08-31" }
// ReportScopeInput
{ "kind": "ALL" } | { "kind": "CUSTOMER" | "REGION" | "TAG" | "PLANTS" | "BUSINESS", "ids": ["01J…"] }
BUSINESS (1–50 Business org ids) is accepted only for a
platform-wide report in the platform org.
Anywhere else it is 403 FORBIDDEN with details.reason: SCOPE_KIND_NOT_ALLOWED.
ReportSummary (list row): reportId, code, name, templateKey, templateCode, templateName, audience, type, period{preset,from,to,timezone,label,partial}, scope{kind,ids,label}, scopeLevel (OPERATOR | PLATFORM), plantCount, format, method, createdBy (USER{sub,displayName — the caller's profile display name, falling back to their subwhen none is set (2026-11-30, BE-2; reports created before this show thesub)} | SCHEDULE{scheduleId,scheduleCode}), status, stage?, percent?, reasonCode?, sizeBytes?, pages?, createdAt, readyAt?, fileExpiresAt?, downloadCount, downloaderCount, version.
Status values: QUEUED, RENDERING, READY, FAILED, EXPIRED (computed on
read when the files are past retention; reasonCode: FILES_EXPIRED).
Failure reasons (reasonCode). The full list, from ReportReasonCode in
packages/core/src/schemas.ts:
reasonCode | Set by | Meaning |
|---|---|---|
SCOPE_EMPTY | HTTP dispatcher | The scope resolved to no ACTIVE plant at render time. TCP is never contacted |
SCOPE_TOO_LARGE | HTTP dispatcher | A platform-wide report resolved to more than 5,000 plants (2026-11-25). Narrow it to fewer Businesses or plants |
TEMPLATE_UNSUPPORTED | HTTP dispatcher or renderer | The template cannot be rendered (for example PARTNER_COMMISSION_STATEMENT) |
RENDER_TIMEOUT | HTTP sweeper | No final status arrived before the render deadline (30 min + 1 min per 100 plants, 3 h max) |
UPLOAD_FAILED | HTTP | The uploaded files did not match the issued upload keys or checksums. An UPLOAD_URL_EXPIRED from the renderer is recorded as this |
UPLOAD_URL_EXPIRED | renderer | Reserved: recorded as UPLOAD_FAILED today |
DATA_INCOMPLETE | renderer | The renderer refused to file a report with missing data |
PERIOD_OUTSIDE_RETENTION | HTTP | Only with an optional retention floor, which no stage sets |
RENDERER_ERROR | renderer | Any other renderer failure |
FILES_EXPIRED | computed on read | EXPIRED: the files are past retention |
Retry policy. No failed report is retried automatically, scheduled runs included. Use Regenerate (H03a).
H01a — List report library
GET /v1/orgs/{orgId}/reports — org reports ≥ VIEW; rows the caller cannot see are skipped.
| Query | Rule |
|---|---|
status | repeatable; also GENERATING = QUEUED ∪ RENDERING |
type | repeatable report type |
method | MANUAL | SCHEDULED |
templateKey, scheduleId | exact match |
createdFrom / createdTo | ISO-8601 UTC, from ≤ to |
q | 2–64 chars, per-word prefix over name, code, template name, author; not combinable with createdFrom/To (400) |
sort | -createdAt only |
operatorOrgId | Platform org only (2026-11-26): one Business id, or all. See Browsing the Businesses from HQ |
limit, cursor | as above |
200 { "items": ReportSummary[], "nextCursor"?, "total"? }. Rows listed in the
platform org carry operator { orgId, name }. Status: 200 · 400 · 401 · 403 ·
404 · 422 · 503.
A page may hold fewer than limit rows while nextCursor is present.
Illustrative example (not executed):
GET /v1/orgs/01J9ORG…/reports?status=READY&limit=2
Authorization: Bearer <token>
:::note Admin-web 2026-11-24
Page 1 of H01a (no cursor, no q) and of H05a also carries total. These are the H01b libraryTotal and scheduleCount counters, unfiltered. See Admin-web list totals, counts and filter options.
:::
H01b — Library summary
GET /v1/orgs/{orgId}/reports/summary — org reports ≥ VIEW.
200 (illustrative): { "libraryTotal": 1842, "byStatus": { "QUEUED": 1, "RENDERING": 2, "READY": 1790, "FAILED": 9, "EXPIRED": 40 }, "templateCount": 5, "scheduleCount": 6, "approximate": true, "retentionDays": 90 }.
Counts are org-wide and approximate; a scoped member's list may show fewer rows.
Portal orgs get their own count and scheduleCount: 0. The only query
parameter is operatorOrgId (platform org, 2026-11-26): one Business's counts
plus operator { orgId, name }, or all for every Business. Status: 200 · 400 ·
401 · 403 · 404 · 422 · 503.
H01c — Get report
GET /v1/reports/{reportId} — visibility predicate on the stored scope.
200: ReportSummary plus sections, files[{fileId,kind,sizeBytes,pages?}]
(storage keys never returned), reason?, dataAsOf?, completeness?,
regeneratedAt?, renderAttempt, recipients, delivery, plantContext,
viewer.capabilities, with ETag. Poll this while generating (≥ 2 s backoff).
Deleted report → 410 GONE (details.deletedAt) for an operator member with
reports ≥ VIEW, otherwise 404. Crown platform staff can read any org's
report; since 2026-11-26 each such read is written to that org's access log
(see Browsing the Businesses from HQ).
Status: 200 · 401 · 404 · 410 · 503.
H01d — Delete report
DELETE /v1/reports/{reportId} · If-Match required — reports ≥ MANAGE on
every plant of the scope. 204. Errors: 401 · 403 · 404 · 409 INVALID_STATE
(QUEUED/RENDERING, details.status) · 409 VERSION_CONFLICT · 428 · 503.
S3 objects are deleted first; if S3 fails nothing is deleted (503).
H02 — Generate report
POST /v1/reports · X-Org-Id + Idempotency-Key required — reports ≥ EDIT
on every plant of the scope and template audience allowed.
| Field | Req | Validation |
|---|---|---|
templateKey | ✔ | in catalogue, available, audience allowed |
name | — | 1–120; default "{template} · {period label}" |
period | ✔ | preset; CUSTOM needs from,to (YYYY-MM-DD), from ≤ to ≤ today, span ≤ 366 days. No retention floor by default: old or missing data is rendered as partial ("not available" plus completeness) |
scope | ✔ | CUSTOMER/REGION/TAG ≤ 10 ids (SCOPE_TOO_BROAD), PLANTS 1–200 (LIMIT_EXCEEDED), BUSINESS 1–50 (SCOPE_TOO_BROAD, platform org only), ALL has no ids |
format | — | PDF (default) | PDF_XLSX | XLSX |
locale | — | en (default) | ur, must be in the template's locales. English only for now (owner decision, 2026-11-02): every template lists only en, so ur returns 422 VALIDATION_FAILED with fieldErrors.locale, for both reports and schedules |
202: full report (as H01c) with status: "QUEUED", Location, ETag.
| Status | code | When |
|---|---|---|
| 400 | ORG_CONTEXT_REQUIRED / MALFORMED_REQUEST | header missing / bad JSON |
| 403 | FORBIDDEN | level too low (details.deniedPlantIds ≤ 20) or details.reason: AUDIENCE_NOT_ALLOWED |
| 403 | FORBIDDEN (details.reason: SCOPE_KIND_NOT_ALLOWED) | a member of a non-personal Customer org (portal) or a Partner org asked for a scope other than PLANTS; pick plants instead. Members of a personal org report as its operator, so every scope kind, including All plants, is allowed (since 2026-11-05) |
| 404 | NOT_FOUND | a scope target is not visible |
| 409 | INVALID_STATE | PLANTS-scope plant ARCHIVED/DELETING |
| 409 | IDEMPOTENCY_IN_PROGRESS | |
| 422 | VALIDATION_FAILED, PERIOD_OUTSIDE_RETENTION (only if an optional floor is configured, see below), SCOPE_TOO_BROAD, LIMIT_EXCEEDED, IDEMPOTENCY_KEY_REUSED | |
| 422 | VALIDATION_FAILED (details.reason: PLATFORM_ORG_CONTEXT, fieldErrors["X-Org-Id"]) | X-Org-Id is the platform org (Crown HQ) and the caller is not a Super Admin or Administrator there (ACTIVE platform membership, scope ALL, built-in role). Since 2026-11-25 those two roles generate platform-wide reports instead |
| 428 | PRECONDITION_REQUIRED | no Idempotency-Key |
| 429 | RATE_LIMITED | > 20 per hour per org; Retry-After |
| 422 | UNSUPPORTED_OPERATION (details.reason: REPORTS_GENERATE_DISABLED) | generation switched off on the stage (default); do not retry |
| 503 | DEPENDENCY_UNAVAILABLE | AWS dependency failure, or report pipeline not deployed (details.dependency: report-pipeline, checked first) |
In a Business org, scope ALL means that Business's plants, never another
Business's. In the platform org it means every ACTIVE plant on the platform
(see below).
Illustrative example (not executed):
POST /v1/reports
Authorization: Bearer <token>
X-Org-Id: 01J9ORG…
Idempotency-Key: gen-7f3a
Content-Type: application/json
{ "templateKey": "CUSTOMER_MONTHLY_SUMMARY", "period": { "preset": "LAST_MONTH" },
"scope": { "kind": "CUSTOMER", "ids": ["01J9CUS…"] }, "format": "PDF_XLSX" }
Platform-wide reports (Crown HQ)
Added 2026-11-25 (console Reports review, item 1). Deployed to dev 2026-11-26 by the
owner; not yet verified end to end (no captured run on dev).
Super Admin and Administrator generate and schedule reports over the whole
platform, or part of it, without selecting a Business: they send the
platform org as X-Org-Id (H02) or {orgId} (H05b).
| Rule | Behaviour |
|---|---|
| Who | The caller's own ACTIVE platform membership with scope ALL on the built-in Super Admin or Administrator role (a custom role with the same levels does not count), platform org not suspended, MFA gate applied. Anyone else in the platform org keeps 422 PLATFORM_ORG_CONTEXT |
| Authorization | reports ≥ EDIT (generate, regenerate) or ≥ MANAGE (schedules) on the platform membership. No per-plant level is checked in each Business. Business, Installer, Partner, Customer and End User callers are unchanged |
ALL | Every ACTIVE plant on the platform: every Business, suspended Businesses and Independent End Users' personal orgs included. This is the same fleet the HQ dashboard counts. Read from the platform-wide plant list, so plants missing from that list (KI-44) are missing here too |
BUSINESS | 1–50 Business org ids (non-personal operator orgs; another id → 404 NOT_FOUND details.targetIds). Their ACTIVE plants |
PLANTS | 1–200 plant ids from any Business. Missing → 404, ARCHIVED/DELETING → 409 INVALID_STATE |
CUSTOMER, REGION, TAG | Per-Business vocabularies: 403 FORBIDDEN details.reason: SCOPE_KIND_NOT_ALLOWED |
| Templates | INTERNAL audience only (FLEET_OPERATIONS_REVIEW, DAILY_PRODUCTION_DIGEST, AVAILABILITY_BY_REGION). A CUSTOMER or PARTNER template → 403 AUDIENCE_NOT_ALLOWED. H04a in the platform org lists only these |
| Size | At most 5,000 plants at render time. More → the report is FAILED with reasonCode: SCOPE_TOO_LARGE. This cannot be checked when the request is made, because ALL and BUSINESS are resolved at render time |
| Rate limit | The usual 20 generated reports per hour per org, so all of Crown HQ shares one bucket |
| Where it is filed | In the platform org, with scopeLevel: "PLATFORM". It appears in HQ's library (H01a on the platform org) and never in a Business's library |
| Schedules | Same scopes and templates. perCustomer must be false (422 fieldErrors.perCustomer). A schedule saved in the platform org before 2026-11-25 cannot be resumed or run (422 PLATFORM_ORG_CONTEXT): delete it and create a new one. The same applies to regenerating such a report |
| Rendering | Render manifest v5 carries scopeLevel, operators[] and plants[].operatorOrgId; branding is Crown's own. See Reports pipeline. TCP renderer support for v5 is in progress on the TCP side |
Picker data. Fill the Business picker from
GET /v1/orgs/{platformOrgId}/businesses (q, status, paging) and
the plant picker from the
platform-wide plant list
(GET /v1/plants from HQ, which accepts q and operatorOrgId). H07
scope options describe one Business and are not used in the platform org.
Browsing the Businesses from HQ (2026-11-26)
Console review items 2.1–2.5. Not deployed to dev yet; nothing below has been executed against a stage.
| Item | Behaviour |
|---|---|
| Who | Super Admin or Administrator in the platform org: the same rule as generating (own ACTIVE scope-ALL membership on the built-in role, platform org not suspended), with reports ≥ VIEW on it (403 otherwise) |
operatorOrgId | Optional on H01a (GET /v1/orgs/{platformOrgId}/reports), H05a (GET /v1/orgs/{platformOrgId}/report-schedules) and H01b (…/reports/summary). A Business id (non-personal operator org) or all. Outside the platform org → 400 VALIDATION_FAILED fieldErrors.operatorOrgId; another platform-org caller → 422 VALIDATION_FAILED details.reason: PLATFORM_ORG_CONTEXT; not a Business → 404 NOT_FOUND details.targetIds |
| One Business | Exactly that Business's library or schedules, every row (no visibility predicate: the caller has scope ALL). Same filters, q (its search index), 15/10 paging, total (its counters) |
all | Every report or schedule not filed as a PLATFORM one: every Business and every Independent End User's personal org. Reports newest first; schedules in creation order. Same filters and paging. total comes from an every-Business counter. q searches only the newest 200 reports (no platform-wide search index), like portal search. A status filter is applied after the read, so a page can be shorter than limit while nextCursor is present. H05a has no q |
| H01b | operatorOrgId=<id>: that Business's libraryTotal, byStatus, scheduleCount, plus operator. all: the every-Business counters, no operator. templateCount stays HQ's |
operator { orgId, name } | On every H01a and H05a row listed in the platform org, with or without operatorOrgId (HQ's own rows name the platform org). Not on Business, Installer, Partner or Customer lists. A deleted org shows its id as name |
| Read and download | GET /v1/reports/{reportId} and /download already worked for Crown staff through the platform fallback (an ACTIVE scope-ALL platform membership with reports ≥ VIEW). Each such read or download now writes one PLATFORM_ACCESS entry to the Business's access log, with checks reports:read or reports:download. Other GET routes are still not logged |
| Opening a Business schedule | GET /v1/report-schedules/{scheduleId} looks the schedule up under X-Org-Id and the caller's own operator orgs, so from HQ send X-Org-Id: <the row's operator.orgId> (the platform fallback then applies) |
| Data | Reports: one RPT#<r>/LISTALL entry per report (GSI2 REPORTS#ALL). Schedules: GSI2 RSCH#ALL on the schedule item. Counters: ORG#ALL_OPERATORS/COUNT#…, kept by the stream. No Scan. Access patterns R-27…R-29 in cse-http-be docs/data-model.md |
Illustrative example (not executed):
GET /v1/orgs/<platformOrgId>/reports?operatorOrgId=all&status=READY
Authorization: Bearer <token>
X-Org-Id: <platformOrgId>
{
"items": [
{ "reportId": "01J…", "code": "RPT-2026-0913", "name": "Monthly summary", "status": "READY",
"scopeLevel": "OPERATOR", "operator": { "orgId": "01J9BUS…", "name": "Demo Solar Business" } }
],
"nextCursor": "eyJ…",
"total": 1203
}
(Rows shortened; every ReportSummary field is present.)
Illustrative example (not executed):
POST /v1/reports
Authorization: Bearer <token>
X-Org-Id: <platformOrgId>
Idempotency-Key: gen-hq-01
Content-Type: application/json
{ "templateKey": "FLEET_OPERATIONS_REVIEW", "period": { "preset": "LAST_MONTH" },
"scope": { "kind": "BUSINESS", "ids": ["01J9BUS…", "01J9BUT…"] } }
H03a — Regenerate
POST /v1/reports/{reportId}:regenerate · If-Match + Idempotency-Key —
reports ≥ EDIT. 202 with status: QUEUED, renderAttempt + 1. Errors: 401 ·
403 · 404 · 409 INVALID_STATE (not FAILED/EXPIRED) · 409 VERSION_CONFLICT ·
422 PERIOD_OUTSIDE_RETENTION (optional floor only) · 422 VALIDATION_FAILED PLATFORM_ORG_CONTEXT (the report
belongs to the platform org and the caller is not Super Admin / Administrator there, or it was filed there before
platform-wide reports) · 422 UNSUPPORTED_OPERATION
(TEMPLATE_UNAVAILABLE, or REPORTS_GENERATE_DISABLED while generation is off) · 428 · 429 · 503 (pipeline gate). Unknown verb on
POST /v1/reports/{reportId}:<verb> → 404. The scope is re-resolved, so plants
added to a tag since are included.
H03b — Download
GET /v1/reports/{reportId}/download?file=PDF|XLSX|PREVIEW — visibility +
reports ≥ VIEW. 200 (illustrative): { "url": "https://…", "expiresAt": "…", "fileName": "RPT-2026-0913 Customer monthly summary.pdf", "contentType": "application/pdf", "sizeBytes": 4404019 }. URL lives 300 s by default (hard cap 900 s), is served as attachment, and is never logged. The route is live in api-reports behind the JWT authorizer; it does not wait on the render pipeline, but no report reaches READY until a renderer exists (KI-41). Files come straight from S3 — the client never contacts the TCP Server for them. See Reports pipeline.
file is required when the report has more than one output kind (PDF and XLSX);
otherwise it defaults to the single one. Errors: 400 (bad/missing file) ·
401 · 404 (report or file kind absent) · 409 INVALID_STATE (not READY) · 410
GONE (details.reason: FILES_EXPIRED) · 503.
H03c — Deliver to recipients
POST /v1/reports/{reportId}:deliver — the second verb on the ReportAction
route (same as :regenerate). Registered; email delivery is blocked by B-02
(REPORT_EMAIL_ENABLED off), so today every call answers
422 UNSUPPORTED_OPERATION.
- Auth: report EDIT on the report's scope.
Idempotency-Keyrequired (428without it). NoIf-Match. - Body: none,
{}, or{ "recipientSubs": string[1..50] }(strict). Without it the report's stored recipients are used; none →422 VALIDATION_FAILED. 202(illustrative):{ "deliveryId": "<ulid>", "queued": 2, "skipped": [{ "sub": "<sub>", "reason": "NO_ACCESS" }] }.
| Status | Code | When |
|---|---|---|
| 422 | UNSUPPORTED_OPERATION (details.reason: EMAIL_DELIVERY_UNAVAILABLE) | email delivery is off (the default today); checked first |
| 409 | INVALID_STATE (details.status) | report is not READY |
| 410 | GONE (details.reason: FILES_EXPIRED) | report files have expired |
| 422 | VALIDATION_FAILED | bad body, or no recipients given and none stored |
| 428 | PRECONDITION_REQUIRED | Idempotency-Key missing |
| 401 | (API Gateway authorizer) | missing or invalid token |
| 403 / 404 | FORBIDDEN / NOT_FOUND | below EDIT / unknown report |
| 429 / 503 | throttled / dependency unavailable | retry with backoff |
A replay with the same Idempotency-Key returns the original 202 body,
read back from the stored delivery record; nothing is sent twice. Each call
writes report events in one transaction: one DELIVERY_REQUESTED summary
(queued count, skipped list) plus one DELIVERY event per recipient
(outcome: QUEUED | SKIPPED).
H04 — Templates
GET /v1/orgs/{orgId}/report-templates— org reports ≥ VIEW, audience-filtered. 200{ "items": [{ templateKey, code, name, defaultType, audience, sections, pagesEstimate, locales, branding, note, available, schedulable, perCustomerAllowed, usedCount?, samplePreviewUrl? }], "capabilities": { emailDelivery, platformReports } }(fixed catalogue, ≤ 5, no pagination).Cache-Control: private, max-age=300+ETag; 304 on match. Status: 200 · 304 · 401 · 403 · 503.- Unavailable templates are listed (
available: false, "coming soon", todayPARTNER_COMMISSION_STATEMENT). Never offer them for Generate or a schedule: H02 answers422 VALIDATION_FAILED(fieldErrors.templateKey). schedulable(=available): a schedule may use the template. Every frequency, format and delivery is allowed for every schedulable template.perCustomerAllowed:perCustomer: trueis accepted only for this template (CUSTOMER audience), and never for a platform-wide schedule.capabilities.emailDeliveryisREPORT_EMAIL_ENABLED(falseon every stage today, B-02).capabilities.platformReportsistruein the platform org, where only INTERNAL templates are listed.samplePreviewUrlis absent on every stage: no stage setsreportSamplesBaseUrl, and no sample files are hosted yet.PARTNER_COMMISSION_STATEMENThas no sample image (sampleImageunset). Show Preview only when the field is present.GET /v1/report-templates/{templateKey}?orgId=— any member; a template outside the caller's audience →404. Status: 200 · 400 · 401 · 404.
H05 — Schedules
ReportSchedule = { scheduleId, code, name, templateKey, templateName, frequency, rule, timezone, summary, scope, scopeLevel, perCustomer, recipientCount, recipients, format, delivery, locale, recipientNote?, status, nextRunAt?, lastRun?, warnings[], createdAt, updatedAt, version }.
-
lastRun = { at, fireTime?, outcome, reportIds, reportCount, unassignedPlantCount?, failure? }is the most recent run; earlier runs are in the run log (H05h).atis when it ran.fireTimeis the Scheduler fire time and is absent for Run now.reportIdsholds at most 25.reportCountincludes per-customer reports still being filed in later batches. -
ScheduleRunOutcome:FILED(at least one report filed) ·SKIPPED_EMPTY_SCOPE(no ACTIVE plant in scope) ·SKIPPED_PAUSED(a fire arrived while PAUSED) ·SKIPPED_STALE(logged only: the fire was armed for an older version or a deleted schedule; never stored) ·FAILED(seefailure). -
failure = { reasonCode, message }is present only on aFAILEDrun (2026-11-26, console review 7.2).reasonCodeis a shipped contract; values are only ever added:reasonCodeWhen TEMPLATE_UNAVAILABLEThe schedule's template is not available (a scheduled fire, or Run now answered 422 UNSUPPORTED_OPERATION)ALL_GROUPS_REFUSEDEvery report of the run was refused by generation with a 4xx. messagenames how many and the first error code, e.g.SCOPE_TOO_BROADRATE_LIMITEDRun now refused by the hourly report-generation limit (the caller also got 429)messageis English display text; do not parse it. A transient server error (5xx, throttling) is not recorded asFAILED: the runner retries the fire from its queue. -
warnings[](derived on every read):NO_RECIPIENTS: ACTIVE with no recipients.TEMPLATE_UNAVAILABLE: the template is not available.EMAIL_DELIVERY_UNAVAILABLE: deliveryEMAILorEMAIL_PORTALwhile email is off; the schedule still saves and files to the portal.NOT_ARMED(2026-11-26): ACTIVE, and the EventBridge Scheduler entry has not been synced to the currentversion(schedulerSyncedVersionbehindversion) for at least 2 minutes after the last save. The schedule will not fire. Cause: Scheduler is not configured on the stage, or the stream-router sync is failing (report_scheduler_unconfigured/ sync WARN logs). Saves sync within seconds, so the 2-minute grace keeps this warning off the create/update response.CONSECUTIVE_FAILURES(2026-11-26): the last 2 or more recorded runs wereFAILED. The schedule storesconsecutiveFailures, which goes up by one perFAILEDrun and back to 0 on any other recorded outcome. The count itself is not returned; read the run log for details.
| Op | Request | Auth | Success | Errors |
|---|---|---|---|---|
| H05a list | GET /v1/orgs/{orgId}/report-schedules?status=ACTIVE|PAUSED&limit&cursor | reports ≥ VIEW (portal orgs: empty list) | 200 {items,nextCursor?} | 400 · 401 · 403 · 503 |
| H05b create | POST /v1/orgs/{orgId}/report-schedules · Idempotency-Key | reports ≥ MANAGE on scope | 201 + ETag, Location | 400 · 401 · 403 · 404 · 409 · 422 (VALIDATION_FAILED, incl. details.reason PLATFORM_ORG_CONTEXT in the platform org for anyone but Super Admin / Administrator; SCOPE_TOO_BROAD, LIMIT_EXCEEDED, IDEMPOTENCY_KEY_REUSED, UNSUPPORTED_OPERATION REPORTS_GENERATE_DISABLED) · 428 · 503 (incl. pipeline gate) |
| H05c get | GET /v1/report-schedules/{scheduleId} | reports ≥ VIEW | 200 + ETag | 401 · 404 |
| H05d update | PATCH /v1/report-schedules/{scheduleId} · If-Match | reports ≥ MANAGE | 200 | as create + 409 VERSION_CONFLICT · 428 |
| H05e delete | DELETE /v1/report-schedules/{scheduleId} · If-Match | reports ≥ MANAGE | 204 (filed reports kept) | 401 · 403 · 404 · 409 · 428 · 503 |
| H05f pause/resume | POST …/{scheduleId}:pause / :resume · If-Match | reports ≥ MANAGE | 200 | 409 INVALID_STATE (already in that state) · 409 · 422 REPORTS_GENERATE_DISABLED (:resume) · 422 VALIDATION_FAILED PLATFORM_ORG_CONTEXT (:resume in the platform org by anyone but Super Admin / Administrator, or of a schedule saved there before 2026-11-25; :pause still works) · 428 · 503 (:resume pipeline gate) |
| H05g run now | POST …/{scheduleId}:run-now · Idempotency-Key | reports ≥ MANAGE | 202 {reportIds, reportCount, outcome: "FILED"}; empty scope → 200 SKIPPED_EMPTY_SCOPE | 401 · 403 · 404 · 422 UNSUPPORTED_OPERATION (TEMPLATE_UNAVAILABLE, REPORTS_GENERATE_DISABLED) · 422 VALIDATION_FAILED PLATFORM_ORG_CONTEXT (as :resume) · 428 · 429 · 503 (pipeline gate) |
| H05h run log | GET /v1/report-schedules/{scheduleId}/runs?limit&cursor | reports ≥ VIEW (as H05c) | 200 {items: ScheduleRun[], nextCursor?} | 400 · 401 · 403 · 404 · 503 |
The pause / resume / run-now verbs share one wire route,
POST /v1/report-schedules/{scheduleId} with {scheduleId}:<verb>; unknown
verb → 404. If-Match applies to :pause/:resume, Idempotency-Key to
:run-now.
Create body: name (1–80), templateKey, frequency, rule (time HH:mm
in 5-minute steps; WEEKLY weekday; MONTHLY dayOfMonth 1–28 or LAST;
YEARLY dayOfMonth + month; fields not applicable → 422), timezone?,
scope, perCustomer?, recipients? (0–50 {type:"USER",sub}, each must
have reports ≥ VIEW on the scope, else 422 details.invalidRecipients),
format?, delivery?, locale?. Update accepts any subset; status is not
accepted (use pause/resume). perCustomer needs a CUSTOMER-audience template and
accepts every scope kind (ALL, CUSTOMER, REGION, TAG, PLANTS; Q40).
Each run groups the scoped plants by customer and files one report per
customer with scope CUSTOMER [customerOrgId], visible to that customer
(viewerOrgId). For a REGION/TAG/PLANTS scope the report also keeps the
original scope internally (fanOutScope), and rendering includes only that
customer's plants inside it, so one customer never sees another's plants.
Plants with no customer are left out of every report and counted as
lastRun.unassignedPlantCount (absent when 0), with a
schedule_run_unassigned_plants log line. Each fan-out batch (25 customers) re-resolves the scope, so if a plant changes customer between batches of one run, a customer can be skipped in that run (known gap). Run now is allowed while PAUSED
and does not move nextRunAt.
H05h — Schedule run log
Added 2026-11-26 (console review 7.1). GET /v1/report-schedules/{scheduleId}/runs
returns the schedule's runs, newest first.
- Auth: Cognito JWT (route authorizer). The org is taken from the schedule,
as in H05c;
X-Org-Idis only a tie-break hint. The caller needsreports ≥ VIEWon the schedule's org. A schedule the caller cannot see, a portal (customer/partner) caller, or a deleted schedule →404 NOT_FOUND. - Query:
limit(1–50) andcursoronly. Withoutlimitthe first page is 15 and each page after acursoris 10. Unknown parameter, repeated parameter or badlimit→400 VALIDATION_FAILED; a cursor from another route or schedule →400 INVALID_CURSOR. - Item:
ScheduleRun = { runId, fireTime?, at, outcome, reportIds, reportCount, unassignedPlantCount?, failure? }, the same fields aslastRunplusrunId.runIdis the ISO fire time for a scheduled fire, ornow-<ULID>for Run now. - What is recorded: every run that also updates
lastRun: scheduled fires (includingSKIPPED_PAUSEDandSKIPPED_EMPTY_SCOPE), Run now, and Run now refused forTEMPLATE_UNAVAILABLEorRATE_LIMITED. A refused Run now becomeslastRuntoo. Not recorded: stale fires (SKIPPED_STALE), duplicate Scheduler deliveries, and fan-out continuation batches (batch 0 records the whole fire). A fire retried after a partial failure overwrites its own item, so each fire appears once. - Retention: each item has a 400-day TTL. Items of a deleted schedule stay
until their TTL but can no longer be read (
404). - Storage:
PK = ORG#<o>#RSCH#<s>,SK = RUN#<sortAt>#<runId>(sortAt= fire time, or the time of a Run now), entityREPORT_SCHEDULE_RUN_LOG. It is a separate partition, so the H05a schedule list never reads run items. The write is best effort: if it fails, the run still completes andlastRunis still updated (schedule_run_log_write_failedWARN log).
Illustrative example (built from the schema; not a captured response, as the route has not been called on dev yet):
{
"items": [
{
"runId": "2026-11-23T03:00:00.000Z",
"fireTime": "2026-11-23T03:00:00.000Z",
"at": "2026-11-23T03:00:04.512Z",
"outcome": "FAILED",
"reportIds": [],
"reportCount": 0,
"failure": { "reasonCode": "TEMPLATE_UNAVAILABLE", "message": "The report template of this schedule is not available" }
},
{
"runId": "now-01JD7Q3V8M2X5K9T4R6N1B0C7F",
"at": "2026-11-20T09:12:40.031Z",
"outcome": "FILED",
"reportIds": ["01JD7Q3W1A9S8D7F6G5H4J3K2M"],
"reportCount": 1
}
],
"nextCursor": "eyJ2IjoxLC4uLn0"
}
Schedule form contract (answers to the console review, 2026-11-25)
| # | Question | Answer |
|---|---|---|
| 4.1 | Recipients picker | No dedicated route yet. A recipient is valid when it has an ACTIVE membership in the schedule's org with reports ≥ VIEW, or, for a CUSTOMER scope or a per-customer schedule, an ACTIVE membership of a Customer org with reports ≥ VIEW. List candidates from the org's members (GET /v1/orgs/{orgId}/members) and expect 422 details.invalidRecipients for anyone refused. EMAIL (an external address) is still reserved (OQ-009-01); recipients are {type:"USER", sub} only |
| 4.2 | Next run preview | No dry-run route. Rule: the next fire after now at rule.time (5-minute steps) in timezone. DAILY every day; WEEKLY on weekday; MONTHLY on dayOfMonth 1–28 or LAST (the last day of each month); YEARLY on dayOfMonth + month. A time in a DST gap moves forward by the gap; a time in a DST overlap uses the first occurrence. The saved schedule's nextRunAt and summary are authoritative |
| 4.3 | Time zone | timezone defaults to the org's settings time zone, else UTC. Any IANA zone the server's Intl knows is accepted; others → 422 fieldErrors.timezone |
| 4.4 | Allowed values per template | Every frequency, format (PDF, PDF_XLSX, XLSX) and delivery for every template with schedulable: true. perCustomer only where perCustomerAllowed: true (H04) |
| 4.5 | Delivery while email is off | Accepted. The schedule carries warning EMAIL_DELIVERY_UNAVAILABLE and files to the portal. Read capabilities.emailDelivery from H04a to explain this before saving |
| 4.6 | Schedule capabilities | Not exposed per record. Every action needs reports ≥ MANAGE (view: ≥ VIEW) on the schedule's org, so derive them from the caller's level; Run now and Resume also need generation enabled |
| 4.7 | Platform schedules | Supported: see Platform-wide reports |
| 5.4 | Re-arm on update | Every save (create, PATCH, pause, resume) bumps version; the Scheduler sync re-arms the entry for the new version, and delete removes it. A fire armed for an older version is dropped as SKIPPED_STALE (log only). Not re-verified on dev in this change |
| 5.5 | DLQ alarms | Not added: the report-dispatch / report-runs DLQ-depth alarms were dropped by owner decision on 2026-10-27 to stay inside the free tier |
H06 — Plant report shortcut
POST /v1/plants/{plantId}/reports · Idempotency-Key — reports ≥ EDIT on the
plant. Optional body { templateKey?, period?, format?, locale? }; defaults:
the template flagged as the plant default for the caller's audience (operator
or customer), LAST_MONTH in the plant timezone, PDF, locale en. 202 as
H02 with scope PLANTS [plantId]. When email delivery is on, the requester is
the sole recipient; while it is off the response carries
"warnings": ["EMAIL_DELIVERY_UNAVAILABLE"]. Errors as H02, plus 409
INVALID_STATE (ARCHIVED), 410 GONE (DELETING or deleted) and 422
UNSUPPORTED_OPERATION (NO_DEFAULT_PLANT_TEMPLATE, no default template for
the audience; REPORTS_GENERATE_DISABLED while generation is off), and 503 when the pipeline is not deployed (see the gates above).
Known gaps
- Portal
qsearch scans only the newest 200 viewer rows. - Download ignores
PREVIEWwhen deciding whetherfileis required. - Per-customer schedules with scope
ALLdo not count plants that have no customer (unassignedPlantCountis only computed for REGION/TAG/PLANTS). - Schedule create / resume / run-now are refused with
503while the Scheduler wiring is absent; a schedule stored earlier on such a stage keeps a computednextRunAtbut is not armed until the pipeline is deployed (it now carries theNOT_ARMEDwarning). - A renderer
UPLOAD_URL_EXPIREDfailure is recorded asUPLOAD_FAILED; there is no automatic re-dispatch (use Regenerate). - Retention (2026-11-02): by default HTTP enforces no daily or alert-history
floor, so
PERIOD_OUTSIDE_RETENTIONis not returned. The code supports optional floors (REPORT_RETENTION_DAILY_DAYS/REPORT_RETENTION_ALERT_DAYS), but no stage sets them, and enabling one needs a CDK change. With a floor set, a period before it would get 422PERIOD_OUTSIDE_RETENTION(details.floor,details.granularity). Old or missing data is shown by the renderer as partial ("not available" pluscompleteness). - A scoped creator cannot GET or list their own PLANTS-scope report afterwards when the plant is outside their visibility predicate (R9).
- Email delivery (H03c, schedule email) blocked by B-02.
- The schedule run log (H05h) starts empty: runs before 2026-11-26 (and
before this change is deployed to dev) were never logged.
failureappears only on runs recorded after that. - No sample previews are hosted (
samplePreviewUrlabsent on every stage). The TCP side rendered samples locally on 2026-11-25 (PDF and PNG per template, synthetic fleet); hosting them and settingreportSamplesBaseUrlis an owner decision that is still open. - A platform-wide report lists at most 500 rows per table (PDF and XLSX), and its work-order sections cover the first 1,000 plants; the renderer's "Summary by Business" section covers every plant.
- HQ browsing (2026-11-26): reports and schedules created before the
2026-11-26 dev deploy have no every-Business entry, so
operatorOrgId=alldoes not list them (they are listed per Business), and the every-Business counters started at zero at that deploy. No backfill script exists yet.qwithoperatorOrgId=allsearches only the newest 200 reports.
Web console additions
See Web console additions (N-37 … N-51) for the newer, not-yet-deployed fields and routes on this area.