API reference
Billing
Clients, plans, subscriptions, invoices, payments and enforcement.
Billing: clients
Clients and their portal links.
/api/billing/clients
List clients
Lists every billing client (archived ones included), ordered by name, with their subscriptions (each including its site), the outstanding balance across their open invoices, and the domains they are billed for.
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- outstanding is in minor units (sum of amount โ amountPaid over open/partial/overdue invoices, summed across currencies).
- The response includes each client's portalToken (the secret for the read-only client portal at /api/portal/{token}).
- subscriptions includes cancelled ones; each subscription embeds the full Site row.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/clients" \
-H "Authorization: Bearer $ORCH_TOKEN"[
{
"id": 12,
"name": "Ada Lovelace",
"email": "[email protected]",
"phone": "+995 555 12 34 56",
"telegramChatId": null,
"company": "Example LLC",
"taxId": "404123456",
"currency": "GEL",
"locale": "en",
"portalToken": "9f1c2e7a4b6d8f0a1c3e5a7b9d1f3a5c7e9b1d3f5a7c9e1b",
"notes": null,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z",
"subscriptions": [
{
"id": 5,
"siteId": 7,
"clientId": 12,
"planId": 3,
"amount": 3000,
"currency": "GEL",
"interval": "monthly",
"intervalDays": null,
"anchorDay": 1,
"startDate": "2026-11-27T10:00:00.000Z",
"nextInvoiceAt": "2026-12-01T00:00:00.000Z",
"status": "active",
"enforcementLevel": "none",
"lastEnforcedAt": null,
"neverAutoSuspend": false,
"gracePeriodDays": 3,
"dunningPolicy": "",
"suspendedAt": null,
"cancelledAt": null,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z",
"site": {
"id": 7,
"domain": "shop.example.com",
"serverId": null,
"status": "active",
"phpVersion": "8.3"
}
}
],
"outstanding": 2000,
"sites": [
"shop.example.com"
]
}
]
/api/billing/clients
Create a client
Creates a billing client and generates its read-only portal token (48 hex characters).
- Token or session
- Admin
- Audit:
billing.client_created
Body
namestringrequired- Client name.1โ200 chars
emailstring- Contact email (also shown on the suspension page as contact).max 200 chars; format not checked
phonestring- Contact phone (used as contact when there is no email).max 60 chars
telegramChatIdstring- Telegram chat id.max 60 chars
companystring- Company name.max 200 chars
taxIdstring- Tax id.max 60 chars
currencystring- Client currency.one of: GEL, USD, EUR; default GEL
localestring- Language of dunning messages and the suspension page.one of: ka, en; default ka
notesstring- Free-form notes.max 2000 chars
Errors
- 400
body/name must NOT have fewer than 1 charactersSchema validation failure (FST_ERR_VALIDATION; message varies by field).- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Unknown body fields are removed silently (additionalProperties: false); archived cannot be set at creation.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/clients" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Ada Lovelace",
"email": "[email protected]",
"company": "Example LLC",
"currency": "GEL",
"locale": "en"
}'{
"id": 12,
"name": "Ada Lovelace",
"email": "[email protected]",
"phone": "+995 555 12 34 56",
"telegramChatId": null,
"company": "Example LLC",
"taxId": "404123456",
"currency": "GEL",
"locale": "en",
"portalToken": "9f1c2e7a4b6d8f0a1c3e5a7b9d1f3a5c7e9b1d3f5a7c9e1b",
"notes": null,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
}
/api/billing/clients/{id}
Update a client
Updates a client. The body is passed to the database as-is after removing id and portalToken (use rotate-token to change the portal token). Send archived: true to archive a client.
- Token or session
- Admin
- Audit:
billing.client_updated
Path parameters
idintegerrequired- Client id.not validated (Number(...) of the path segment)
Body
namestring- Client name.not validated
emailstring- Contact email.not validated
phonestring- Contact phone.not validated
telegramChatIdstring- Telegram chat id.not validated
companystring- Company name.not validated
taxIdstring- Tax id.not validated
currencystring- Client currency (GEL, USD or EUR expected).not validated
localestring- ka or en.not validated
notesstring- Free-form notes.not validated
archivedboolean- Archive (true) or unarchive (false) the client.not validated
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- No request schema: any field that is not a Client column (or a value of the wrong type) makes Prisma throw โ 500. id and portalToken are silently dropped.
- No client with this id makes the Prisma call throw; there is no 404 branch, so Fastify's default error handler answers 500.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X PATCH "https://panel.example.com/api/billing/clients/5" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"phone": "+995 555 12 34 56",
"archived": false
}'{
"id": 12,
"name": "Ada Lovelace",
"email": "[email protected]",
"phone": "+995 555 12 34 56",
"telegramChatId": null,
"company": "Example LLC",
"taxId": "404123456",
"currency": "GEL",
"locale": "en",
"portalToken": "9f1c2e7a4b6d8f0a1c3e5a7b9d1f3a5c7e9b1d3f5a7c9e1b",
"notes": null,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
}
/api/billing/clients/{id}
Delete a client
Permanently deletes a client that has no subscriptions and no invoices. Clients with billing history must be archived instead (PATCH with archived: true).
- Token or session
- Admin
- Audit:
billing.client_deleted
Path parameters
idintegerrequired- Client id.not validated (Number(...) of the path segment)
Errors
- 400
Client has 1 subscription(s) and 3 invoice(s). Archive the client instead of deleting.The client has any subscription (including cancelled) or any invoice; the counts are filled in.- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- No client with this id makes the Prisma call throw; there is no 404 branch, so Fastify's default error handler answers 500.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X DELETE "https://panel.example.com/api/billing/clients/5" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"deleted": true
}
/api/billing/clients/{id}/rotate-token
Rotate client portal token
Generates a new random portal token (24 random bytes, 48 hex characters) for the client, immediately invalidating the old read-only portal link.
- Token or session
- Admin
- Audit:
billing.portal_token_rotated
Path parameters
idintegerrequired- Client id.not validated (Number(...) of the path segment)
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- The token is the credential for the public client portal (/api/portal/{token}; the web UI builds the link as <origin>/client/<token>). Treat it as a secret.
- No body is read; the web client sends {}.
- No client with this id makes the Prisma call throw; there is no 404 branch, so Fastify's default error handler answers 500.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/clients/5/rotate-token" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"portalToken": "3b7e1f9a2c4d6e8f0a1b3c5d7e9f1a2b4c6d8e0f1a3b5c7d"
}
Billing: plans and subscriptions
Plans and per-site subscriptions.
/api/billing/plans
List plans
Lists all billing plans (archived included), ordered by name.
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- amount is in minor units; dunningPolicy is the stored JSON string ("" = default ladder).
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/plans" \
-H "Authorization: Bearer $ORCH_TOKEN"[
{
"id": 3,
"name": "Standard",
"amount": 3000,
"currency": "GEL",
"interval": "monthly",
"intervalDays": null,
"dunningPolicy": "",
"gracePeriodDays": 3,
"autoSuspend": true,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
}
]
/api/billing/plans
Create a plan
Creates a billing plan: a reusable price, interval, grace period and optional dunning ladder that subscriptions can reference.
- Token or session
- Admin
Body
namestringrequired- Plan name (unique).not validated; required by the database
amountintegerrequired- Price. JSON number = minor units (3000 = 30.00); string = major units ("30.00").not validated beyond parsing; number or decimal string
currencystring- Currency (used for string parsing too).not validated; GEL, USD or EUR expected; default GEL
intervalstring- Billing interval.not validated; monthly, yearly or custom_days expected; default monthly
intervalDaysinteger- Days per period when interval is custom_days.not validated; default null
gracePeriodDaysinteger- Days past due before any enforcement (notifications still go out).not validated; default 3
autoSuspendboolean- false = subscriptions on this plan never escalate past banner.not validated; default true
dunningPolicyarray- Dunning ladder: JSON array of steps { offsetDays: integer (days relative to the invoice due date; negative = before it is due), action: one of remind, invoice_due, banner, restrict, suspend, stop_workers, final_warning, archive }. Stored JSON-stringified; empty/omitted = inherit (subscription โ plan โ built-in default ladder). Invalid steps are dropped when read; if nothing valid remains the default ladder is used.not validated; JSON-stringified when truthy
dunningPolicy[].offsetDaysintegerrequired- Days relative to the due date (negative = before).not validated
dunningPolicy[].actionstringrequired- Ladder action.one of: remind, invoice_due, banner, restrict, suspend, stop_workers, final_warning, archive (invalid steps ignored when read)
Errors
- 400
Invalid amountamount is not a number and does not parse as a decimal amount (missing amount included).- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Money: every stored/returned amount is an INTEGER in the currency's minor unit (tetri for GEL, cents for USD/EUR; 3000 = 30.00). Where a field accepts both, a JSON number is taken as minor units as-is, while a string is parsed as MAJOR units ("30", "30.5", "1 200,75" โ whitespace removed, comma accepted as decimal separator, rounded half-up to 2 decimals).
- No request schema: missing name, a duplicate name or wrong-typed fields make Prisma throw โ 500. Negative or zero amounts are NOT rejected here, and a fractional JSON number is passed to an Int column (Prisma error โ 500).
- Passing dunningPolicy as a string stores JSON.stringify(<string>) (double-encoded), which reads back as "not an array" โ default ladder. Send an array.
- No audit entry is written.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/plans" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Standard",
"amount": "30.00",
"currency": "GEL",
"interval": "monthly",
"gracePeriodDays": 3,
"autoSuspend": true,
"dunningPolicy": [
{
"offsetDays": -7,
"action": "remind"
},
{
"offsetDays": 0,
"action": "invoice_due"
},
{
"offsetDays": 5,
"action": "banner"
},
{
"offsetDays": 14,
"action": "suspend"
}
]
}'{
"id": 3,
"name": "Standard",
"amount": 3000,
"currency": "GEL",
"interval": "monthly",
"intervalDays": null,
"dunningPolicy": "[{\"offsetDays\":-7,\"action\":\"remind\"},{\"offsetDays\":0,\"action\":\"invoice_due\"},{\"offsetDays\":5,\"action\":\"banner\"},{\"offsetDays\":14,\"action\":\"suspend\"}]",
"gracePeriodDays": 3,
"autoSuspend": true,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
}
/api/billing/plans/{id}
Update a plan
Updates a plan. The body is passed to the database as-is (id removed), except that a string amount is parsed from major units and an array dunningPolicy is JSON-stringified. Changing a plan never rewrites existing subscriptions' amount or issued invoices.
- Token or session
- Admin
Path parameters
idintegerrequired- Plan id.not validated (Number(...) of the path segment)
Body
namestring- Plan name.not validated
amountinteger- Price: number = minor units; string = major units.not validated; an unparseable string is silently ignored
currencystring- Currency.not validated
intervalstring- monthly, yearly or custom_days.not validated
intervalDaysinteger- Days per period for custom_days.not validated
gracePeriodDaysinteger- Grace period in days.not validated
autoSuspendboolean- Allow escalation past banner.not validated
archivedboolean- Archive flag.not validated
dunningPolicyarray- Dunning ladder: JSON array of steps { offsetDays: integer (days relative to the invoice due date; negative = before it is due), action: one of remind, invoice_due, banner, restrict, suspend, stop_workers, final_warning, archive }. Stored JSON-stringified; empty/omitted = inherit (subscription โ plan โ built-in default ladder). Invalid steps are dropped when read; if nothing valid remains the default ladder is used. A string is stored verbatim (so "" resets to the default ladder).not validated
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Money: every stored/returned amount is an INTEGER in the currency's minor unit (tetri for GEL, cents for USD/EUR; 3000 = 30.00). Where a field accepts both, a JSON number is taken as minor units as-is, while a string is parsed as MAJOR units ("30", "30.5", "1 200,75" โ whitespace removed, comma accepted as decimal separator, rounded half-up to 2 decimals).
- No request schema: unknown fields or wrong types make Prisma throw โ 500. No plan with this id makes the Prisma call throw; there is no 404 branch, so Fastify's default error handler answers 500.
- No audit entry is written.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X PATCH "https://panel.example.com/api/billing/plans/2" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"amount": "35.00",
"gracePeriodDays": 5
}'{
"id": 3,
"name": "Standard",
"amount": 3500,
"currency": "GEL",
"interval": "monthly",
"intervalDays": null,
"dunningPolicy": "",
"gracePeriodDays": 5,
"autoSuspend": true,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
}
/api/billing/default-policy
Get the default dunning ladder
Returns the built-in dunning ladder used when neither the subscription nor its plan defines one.
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Actions: remind / invoice_due / final_warning only notify; banner injects a payment-overdue banner; restrict blocks /admin and /login while the public site stays up; suspend serves a branded 503 page; stop_workers also stops queue workers and the scheduler (site stays suspended); archive maps to level archived. The type comment in dunning.ts describes archive as "backup + remove files, never deletes the database", but site-suspend.sh serves archived exactly like suspend (503 page) and no backup/file removal is implemented in the tick or the script.
- Days are calendar days in the Asia/Tbilisi time zone.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/default-policy" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"policy": [
{
"offsetDays": -7,
"action": "remind"
},
{
"offsetDays": 0,
"action": "invoice_due"
},
{
"offsetDays": 4,
"action": "banner"
},
{
"offsetDays": 7,
"action": "restrict"
},
{
"offsetDays": 10,
"action": "suspend"
},
{
"offsetDays": 30,
"action": "stop_workers"
},
{
"offsetDays": 60,
"action": "final_warning"
},
{
"offsetDays": 90,
"action": "archive"
}
]
}
/api/billing/subscriptions
List subscriptions
Lists every subscription (cancelled included), ordered by id, with its site, client and plan.
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- status: active | past_due | suspended | cancelled | paused. enforcementLevel: none | banner | restrict | suspend | archived. amount in minor units.
- Embedded client rows include portalToken; site rows are full Site rows.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/subscriptions" \
-H "Authorization: Bearer $ORCH_TOKEN"[
{
"id": 5,
"siteId": 7,
"clientId": 12,
"planId": 3,
"amount": 3000,
"currency": "GEL",
"interval": "monthly",
"intervalDays": null,
"anchorDay": 1,
"startDate": "2026-11-27T10:00:00.000Z",
"nextInvoiceAt": "2026-12-01T00:00:00.000Z",
"status": "active",
"enforcementLevel": "none",
"lastEnforcedAt": null,
"neverAutoSuspend": false,
"gracePeriodDays": 3,
"dunningPolicy": "",
"suspendedAt": null,
"cancelledAt": null,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z",
"site": {
"id": 7,
"domain": "shop.example.com",
"serverId": null,
"status": "active",
"phpVersion": "8.3"
},
"client": {
"id": 12,
"name": "Ada Lovelace",
"email": "[email protected]",
"phone": "+995 555 12 34 56",
"telegramChatId": null,
"company": "Example LLC",
"taxId": "404123456",
"currency": "GEL",
"locale": "en",
"portalToken": "9f1c2e7a4b6d8f0a1c3e5a7b9d1f3a5c7e9b1d3f5a7c9e1b",
"notes": null,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
},
"plan": {
"id": 3,
"name": "Standard",
"amount": 3000,
"currency": "GEL",
"interval": "monthly",
"intervalDays": null,
"dunningPolicy": "",
"gracePeriodDays": 3,
"autoSuspend": true,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
}
}
]
/api/billing/subscriptions
Create a subscription
Starts billing a site for a client. Price, currency, interval and grace period come from the body, falling back to the plan. The first invoice is due at startDate (default now) and is issued by the next billing tick. A site can hold only one subscription: if its previous one was cancelled, that row is reactivated in place (same id and invoice history, leftover open invoices voided, enforcement cleared).
- Token or session
- Admin
- Audit:
billing.subscription_created
Body
siteIdintegerrequired- Site to bill.
clientIdintegerrequired- Client who pays.
planIdinteger- Plan to inherit defaults from.nullable
amountinteger- Price per period: integer = minor units (3000), string = major units ("30.00"). Falls back to the plan amount.integer (minor units) or string (major units); must resolve to > 0
currencystring- Currency; falls back to the plan, then GEL.one of: GEL, USD, EUR
intervalstring- Billing interval; falls back to the plan, then monthly.one of: monthly, yearly, custom_days
intervalDaysinteger- Days per period for custom_days; falls back to the plan.nullable
anchorDayinteger- Day of the month invoices are anchored to (monthly/yearly).1โ28, nullable
startDatestring- Start of the first period (and due date of the first invoice). Default now.date string parsed with new Date(); an invalid date fails with 500
gracePeriodDaysinteger- Days past due before enforcement; falls back to the plan, then 3.0โ60
neverAutoSuspendboolean- VIP valve: never escalate past banner.default false
dunningPolicyarray- Dunning ladder: JSON array of steps { offsetDays: integer (days relative to the invoice due date; negative = before it is due), action: one of remind, invoice_due, banner, restrict, suspend, stop_workers, final_warning, archive }. Stored JSON-stringified; empty/omitted = inherit (subscription โ plan โ built-in default ladder). Invalid steps are dropped when read; if nothing valid remains the default ladder is used.any JSON accepted by the schema; JSON-stringified when truthy
Errors
- 400
Invalid amountNo amount in the body or plan, it does not parse, or it is โค 0.- 400
body must have required property 'siteId'Schema validation failure (FST_ERR_VALIDATION; message varies).- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.- 409
This site already has a subscription.The site already has a subscription that is not cancelled.
- Money: every stored/returned amount is an INTEGER in the currency's minor unit (tetri for GEL, cents for USD/EUR; 3000 = 30.00). Where a field accepts both, a JSON number is taken as minor units as-is, while a string is parsed as MAJOR units ("30", "30.5", "1 200,75" โ whitespace removed, comma accepted as decimal separator, rounded half-up to 2 decimals). Here the schema limits amount to an integer or a string.
- Audit action is billing.subscription_reactivated instead when a cancelled subscription is reused. Both return 201.
- nextInvoiceAt is set to startDate, so the first invoice is issued (due immediately) by the next tick once startDate has passed, or right away with POST /subscriptions/{id}/issue-invoice.
- A planId that does not exist is treated as "no plan"; a siteId/clientId that does not exist makes Prisma throw โ 500.
- Passing dunningPolicy as a string stores it double-encoded (โ default ladder when read). Send an array.
- Unknown body fields are removed silently (additionalProperties: false). status/enforcementLevel cannot be set.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/subscriptions" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"siteId": 7,
"clientId": 12,
"planId": 3,
"amount": "30.00",
"currency": "GEL",
"interval": "monthly",
"anchorDay": 1,
"startDate": "2026-12-01",
"gracePeriodDays": 3,
"neverAutoSuspend": false
}'{
"id": 5,
"siteId": 7,
"clientId": 12,
"planId": 3,
"amount": 3000,
"currency": "GEL",
"interval": "monthly",
"intervalDays": null,
"anchorDay": 1,
"startDate": "2026-11-27T10:00:00.000Z",
"nextInvoiceAt": "2026-12-01T00:00:00.000Z",
"status": "active",
"enforcementLevel": "none",
"lastEnforcedAt": null,
"neverAutoSuspend": false,
"gracePeriodDays": 3,
"dunningPolicy": "",
"suspendedAt": null,
"cancelledAt": null,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z",
"site": {
"id": 7,
"domain": "shop.example.com",
"serverId": null,
"status": "active",
"phpVersion": "8.3"
},
"client": {
"id": 12,
"name": "Ada Lovelace",
"email": "[email protected]",
"phone": "+995 555 12 34 56",
"telegramChatId": null,
"company": "Example LLC",
"taxId": "404123456",
"currency": "GEL",
"locale": "en",
"portalToken": "9f1c2e7a4b6d8f0a1c3e5a7b9d1f3a5c7e9b1d3f5a7c9e1b",
"notes": null,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
}
}
/api/billing/subscriptions/{id}
Update a subscription
Updates a subscription's billing terms. The body is passed to the database after removing id, siteId and the serving-layer state fields (enforcementLevel, status, suspendedAt, lastEnforcedAt), which only change through enforcement. A string amount is parsed from major units, an array dunningPolicy is JSON-stringified, and startDate / nextInvoiceAt strings are converted to dates.
- Token or session
- Admin
- Audit:
billing.subscription_updated
Path parameters
idintegerrequired- Subscription id.not validated (Number(...) of the path segment)
Body
clientIdinteger- Move the subscription to another client.not validated
planIdinteger- Plan id or null.not validated
amountinteger- Price: number = minor units; string = major units (parsed with body currency, default GEL decimals).not validated; an unparseable string is silently ignored
currencystring- GEL, USD or EUR.not validated
intervalstring- monthly, yearly or custom_days.not validated
intervalDaysinteger- Days per period for custom_days.not validated
anchorDayinteger- Billing day of month.not validated (1โ28 is only enforced on create; values are clamped to 1โ28 when computing dates)
startDatestring- Subscription start date.not validated; converted with new Date() when truthy
nextInvoiceAtstring- When the next invoice is issued (moves the billing anchor).not validated; converted with new Date() when truthy
gracePeriodDaysinteger- Grace period in days.not validated
neverAutoSuspendboolean- VIP valve: never escalate past banner.not validated
dunningPolicyarray- Dunning ladder: JSON array of steps { offsetDays: integer (days relative to the invoice due date; negative = before it is due), action: one of remind, invoice_due, banner, restrict, suspend, stop_workers, final_warning, archive }. Stored JSON-stringified; empty/omitted = inherit (subscription โ plan โ built-in default ladder). Invalid steps are dropped when read; if nothing valid remains the default ladder is used. null/""/false clears the override (inherit); a string is stored verbatim.not validated
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Money: every stored/returned amount is an INTEGER in the currency's minor unit (tetri for GEL, cents for USD/EUR; 3000 = 30.00). Where a field accepts both, a JSON number is taken as minor units as-is, while a string is parsed as MAJOR units ("30", "30.5", "1 200,75" โ whitespace removed, comma accepted as decimal separator, rounded half-up to 2 decimals).
- enforcementLevel, status, suspendedAt, lastEnforcedAt, id and siteId are silently dropped. Use /enforce to change the level and DELETE to cancel; there is no API to set status paused.
- No request schema: unknown fields or wrong types make Prisma throw โ 500. No subscription with this id makes the Prisma call throw; there is no 404 branch, so Fastify's default error handler answers 500.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X PATCH "https://panel.example.com/api/billing/subscriptions/7" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"amount": "45.00",
"neverAutoSuspend": true
}'{
"id": 5,
"siteId": 7,
"clientId": 12,
"planId": 3,
"amount": 4500,
"currency": "GEL",
"interval": "monthly",
"intervalDays": null,
"anchorDay": 1,
"startDate": "2026-11-27T10:00:00.000Z",
"nextInvoiceAt": "2026-12-01T00:00:00.000Z",
"status": "active",
"enforcementLevel": "none",
"lastEnforcedAt": null,
"neverAutoSuspend": true,
"gracePeriodDays": 3,
"dunningPolicy": "",
"suspendedAt": null,
"cancelledAt": null,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
}
/api/billing/subscriptions/{id}
Cancel a subscription
Stops billing a site. Any enforcement on the site is lifted first (always applied, regardless of the master switch), every still-open invoice (open, partial, overdue) is voided, and the subscription is marked cancelled. The row is kept so billing can be re-added later (POST /subscriptions reactivates it).
- Token or session
- Admin
- Audit:
billing.subscription_cancelled
Path parameters
idintegerrequired- Subscription id.not validated (Number(...) of the path segment)
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Not a hard delete: status โ cancelled, cancelledAt set, enforcementLevel โ none. A billing event of type cancelled is recorded.
- Partially paid invoices are voided too (their payments stay recorded).
- No subscription with this id makes the Prisma call throw; there is no 404 branch, so Fastify's default error handler answers 500.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X DELETE "https://panel.example.com/api/billing/subscriptions/7" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"cancelled": true,
"invoicesVoided": 1
}
/api/billing/subscriptions/{id}/preview
Preview next dunning step
Read-only "what happens next" for one subscription: the oldest unpaid invoice, days overdue, the level the site should be at now and the next ladder step that can actually fire (steps beyond the neverAutoSuspend/autoSuspend cap are skipped).
- Token or session
- Admin
Path parameters
idintegerrequired- Subscription id.not validated (Number(...) of the path segment)
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.- 404
Subscription not foundNo subscription with this id.
- When nothing is owed the shape is reduced: { domain, currentLevel, balance: 0, daysOverdue: null, targetLevel: "none", next: null, policy }.
- balance is in minor units; next is null when no further step can fire; next.level is null for notify-only actions; policy is the effective ladder (subscription โ plan โ default).
- Works for any status including cancelled; it does not check the master switch.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/subscriptions/7/preview" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"domain": "shop.example.com",
"invoice": "INV-2026-0042",
"balance": 2000,
"currency": "GEL",
"daysOverdue": 5,
"currentLevel": "banner",
"targetLevel": "banner",
"withinGrace": false,
"cappedByPolicy": false,
"next": {
"action": "restrict",
"level": "restrict",
"date": "2026-11-08T00:00:00.000Z",
"daysAway": 2
},
"policy": [
{
"offsetDays": -7,
"action": "remind"
},
{
"offsetDays": 0,
"action": "invoice_due"
},
{
"offsetDays": 4,
"action": "banner"
},
{
"offsetDays": 7,
"action": "restrict"
},
{
"offsetDays": 10,
"action": "suspend"
},
{
"offsetDays": 30,
"action": "stop_workers"
},
{
"offsetDays": 60,
"action": "final_warning"
},
{
"offsetDays": 90,
"action": "archive"
}
]
}
/api/billing/subscriptions/{id}/events
List subscription billing events
Returns the newest 100 billing events of a subscription (invoices issued, payments, notifications, enforcement transitions, dry runs, voids, cancellation).
- Token or session
- Admin
Path parameters
idintegerrequired- Subscription id.not validated (Number(...) of the path segment)
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Types written by the code: invoice_issued, payment_recorded, invoice_voided, cancelled, notify:<action> (remind, invoice_due, final_warning), dry_run (an enforcement that was not applied, with detail = reason), and the applied level name (banner, restrict, suspend, archived) or restored.
- An unknown subscription id returns [] (no 404).
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/subscriptions/7/events" \
-H "Authorization: Bearer $ORCH_TOKEN"[
{
"id": 88,
"subscriptionId": 5,
"invoiceId": 42,
"type": "banner",
"fromLevel": "none",
"toLevel": "banner",
"detail": null,
"dryRun": false,
"createdAt": "2026-11-27T10:00:00.000Z"
},
{
"id": 87,
"subscriptionId": 5,
"invoiceId": 42,
"type": "notify:invoice_due",
"fromLevel": null,
"toLevel": null,
"detail": "Hosting payment due today",
"dryRun": false,
"createdAt": "2026-11-27T10:00:00.000Z"
}
]
Billing: invoices and payments
Invoices, payments and voiding.
/api/billing/subscriptions/{id}/issue-invoice
Issue the next invoice now
Issues the invoice for the subscription's current billing period (starting at nextInvoiceAt) immediately and advances the billing anchor to the next period. The invoice number is allocated sequentially per year (INV-<year>-<4-digit seq>) and the invoice is due at the period start.
- Token or session
- Admin
- Audit:
billing.invoice_issued
Path parameters
idintegerrequired- Subscription id.not validated (Number(...) of the path segment)
Errors
- 400
Nothing to invoice (cancelled/paused subscription?)No subscription with this id, or its status is cancelled or paused.- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Idempotent per period: if a non-void invoice already covers the period it is returned instead of creating a duplicate (the anchor is moved past it).
- It does not wait for nextInvoiceAt to arrive: calling it repeatedly issues one invoice per call for successive future periods.
- amount is in minor units (a snapshot of the subscription amount). The created Invoice has status open and one line item "Hosting โ <domain>".
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/subscriptions/7/issue-invoice" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"id": 42,
"number": "INV-2026-0042",
"amount": 3000,
"currency": "GEL",
"dueDate": "2026-11-01T00:00:00.000Z"
}
/api/billing/invoices
List invoices
Lists up to 500 invoices, newest first, optionally filtered, with client, site and payments, plus the remaining balance and a formatted amount.
- Token or session
- Admin
Query parameters
statusstring- Exact invoice status.not validated; draft, open, partial, paid, overdue or void
clientIdinteger- Only this client's invoices.not validated
siteIdinteger- Only this site's invoices.not validated
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- balance (minor units) is 0 for void invoices, otherwise max(0, amount โ amountPaid). amountFormatted formats amount (not balance), e.g. "30.00 โพ", "$30.00", "โฌ30.00".
- lineItems is a JSON string. Invoice status values: draft | open | partial | paid | overdue | void (the code creates open; the tick flips open โ overdue once past due; payments set partial/paid).
- A non-numeric clientId/siteId becomes NaN and makes Prisma throw โ 500. Hard limit of 500 rows, no pagination.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/invoices" \
-H "Authorization: Bearer $ORCH_TOKEN"[
{
"id": 42,
"number": "INV-2026-0042",
"clientId": 12,
"subscriptionId": 5,
"siteId": 7,
"periodStart": "2026-11-01T00:00:00.000Z",
"periodEnd": "2026-12-01T00:00:00.000Z",
"issuedAt": "2026-11-01T00:00:00.000Z",
"dueDate": "2026-11-01T00:00:00.000Z",
"amount": 3000,
"amountPaid": 1000,
"currency": "GEL",
"status": "partial",
"paidAt": null,
"lineItems": "[{\"description\":\"Hosting โ shop.example.com\",\"periodStart\":\"2026-11-01T00:00:00.000Z\",\"periodEnd\":\"2026-12-01T00:00:00.000Z\",\"amount\":3000,\"currency\":\"GEL\"}]",
"notes": null,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z",
"client": {
"id": 12,
"name": "Ada Lovelace",
"email": "[email protected]",
"phone": "+995 555 12 34 56",
"telegramChatId": null,
"company": "Example LLC",
"taxId": "404123456",
"currency": "GEL",
"locale": "en",
"portalToken": "9f1c2e7a4b6d8f0a1c3e5a7b9d1f3a5c7e9b1d3f5a7c9e1b",
"notes": null,
"archived": false,
"createdAt": "2026-11-27T10:00:00.000Z",
"updatedAt": "2026-11-27T10:00:00.000Z"
},
"site": {
"id": 7,
"domain": "shop.example.com",
"serverId": null,
"status": "active",
"phpVersion": "8.3"
},
"payments": [
{
"id": 9,
"invoiceId": 42,
"amount": 1000,
"currency": "GEL",
"method": "bank_transfer",
"source": "manual",
"reference": "TBC-778812",
"externalId": null,
"receivedAt": "2026-11-27T10:00:00.000Z",
"recordedById": null,
"note": null,
"createdAt": "2026-11-27T10:00:00.000Z"
}
],
"balance": 2000,
"amountFormatted": "30.00 โพ"
}
]
/api/billing/invoices/overdue
List overdue invoices
Lists every open, partial or overdue invoice whose due date has passed, oldest due first, in a compact shape.
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- balance is in minor units. Selection is by due date < now (not by status = overdue).
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/invoices/overdue" \
-H "Authorization: Bearer $ORCH_TOKEN"[
{
"id": 42,
"number": "INV-2026-0042",
"client": "Ada Lovelace",
"domain": "shop.example.com",
"balance": 2000,
"currency": "GEL",
"dueDate": "2026-11-01T00:00:00.000Z"
}
]
/api/billing/invoices/{id}/pay
Record a payment
Records a manual payment against an invoice; omit amount to settle the full remaining balance. The invoice status is recomputed from the sum of its payments (partial or paid). When the invoice becomes fully paid and nothing else is owed on that subscription, the site is restored immediately (regardless of the master switch) and the subscription returns to active.
- Token or session
- Admin
- Audit:
billing.payment_recorded
Path parameters
idintegerrequired- Invoice id.not validated (Number(...) of the path segment)
Body
amountinteger- Amount received: integer = minor units (2000), string = major units in the invoice currency ("20.00"). Omit for the full remaining balance.integer (minor units) or string (major units); must resolve to > 0
methodstring- Payment method.one of: cash, bank_transfer, card, other; default cash
referencestring- Bank reference or receipt number.max 200 chars
notestring- Free-form note.max 500 chars
receivedAtstring- When the money was received. Default now.date string parsed with new Date()
Errors
- 400
Could not record payment (void invoice or zero amount)The invoice is void, or amount was omitted and nothing is left to pay.- 400
Invalid amountamount given but does not parse or is โค 0.- 400
body/method must be equal to one of the allowed valuesSchema validation failure (FST_ERR_VALIDATION; message varies).- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.- 404
Invoice not foundNo invoice with this id.
- Money: every stored/returned amount is an INTEGER in the currency's minor unit (tetri for GEL, cents for USD/EUR; 3000 = 30.00). Where a field accepts both, a JSON number is taken as minor units as-is, while a string is parsed as MAJOR units ("30", "30.5", "1 200,75" โ whitespace removed, comma accepted as decimal separator, rounded half-up to 2 decimals). Here the schema limits amount to an integer or a string.
- Overpayment is allowed: an amount larger than the balance is recorded in full and the invoice becomes paid (balance never goes below 0). Explicit amounts can also be recorded on an already paid invoice.
- amount, amountPaid and balance in the response are minor units. duplicate is always false for this route (it records with source manual and no externalId). restored is true only when the site was actually moved back to none.
- Emits the billing.invoice_paid event (payload { invoiceId, number, currency, fullyPaid, restored }) on every recorded payment, partial ones included, and billing.restored ({ invoiceId, subscriptionId }) when the site was restored.
- The payment's recordedById is read from request.user.id, which the auth payload does not set (it uses userId), so it appears to be stored as null.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/invoices/42/pay" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"amount": "20.00",
"method": "bank_transfer",
"reference": "TBC-778812"
}'{
"invoiceId": 42,
"status": "paid",
"amount": 3000,
"amountPaid": 3000,
"balance": 0,
"fullyPaid": true,
"duplicate": false,
"restored": true
}
/api/billing/invoices/{id}/void
Void an invoice
Voids an unpaid invoice that has no payments. If the subscription's billing anchor had already moved past this invoice's period, it is rolled back to the period start so the period is billed again by the next tick.
- Token or session
- Admin
- Audit:
billing.invoice_voided
Path parameters
idintegerrequired- Invoice id.not validated (Number(...) of the path segment)
Errors
- 400
A paid invoice cannot be voided.The invoice status is paid.- 400
This invoice has recorded payments โ refund or reallocate them before voiding.The invoice is partially paid (amountPaid > 0).- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.- 404
Invoice not foundNo invoice with this id.
- Voiding an already void invoice returns { voided: true } (no periodRestored field) and writes no audit entry.
- An invoice_voided billing event is recorded on the subscription. Voiding does not lift enforcement by itself; the next tick restores the site if nothing else is owed.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/invoices/42/void" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"voided": true,
"periodRestored": true
}
Billing: enforcement and reports
The overdue ladder, the daily run, previews and reports.
/api/billing/overview
Get billing overview
Dashboard totals: master-switch mode, client and subscription counts, monthly recurring revenue, outstanding receivables with an aging breakdown, and how many subscriptions are suspended or past due.
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- currency is simply the currency of the first non-cancelled subscription (GEL when there are none); mrr and outstanding are plain sums of minor units across ALL currencies โ they are not converted.
- clients counts non-archived clients; subscriptions counts every subscription whose status is not cancelled.
- mrr counts active, past_due and suspended subscriptions: monthly = amount, yearly = round(amount/12), custom_days = round(amount*30/intervalDays).
- aging buckets (minor units) are by whole days past dueDate over open/partial/overdue invoices: current (โค0 days), d1_30, d31_60, d61_plus; total = sum.
- suspended = subscriptions with enforcementLevel suspend or archived; pastDue = subscriptions with status past_due.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/overview" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"mode": "off",
"currency": "GEL",
"clients": 8,
"subscriptions": 11,
"mrr": 33000,
"outstanding": 9000,
"aging": {
"current": 3000,
"d1_30": 6000,
"d31_60": 0,
"d61_plus": 0,
"total": 9000
},
"suspended": 1,
"pastDue": 2
}
/api/billing/enforcement
Get enforcement mode
Returns the billing enforcement master switch. Anything other than "on" or "dry_run" stored in the setting (including no setting) reads as "off".
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Modes: off = never touch a site (default; billing fails closed), dry_run = record what would happen without changing anything, on = apply banners/restrictions/suspensions.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/enforcement" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"mode": "off"
}
/api/billing/enforcement
Set enforcement mode
Sets the billing enforcement master switch (stored in the settings table under the key billing_enforcement). It only gates automatic and manual escalation; restoring a site is always allowed.
- Token or session
- Admin
- Audit:
billing.enforcement_mode
Body
modestringrequired- New master-switch mode.one of: off, dry_run, on
Errors
- 400
body/mode must be equal to one of the allowed valuesmode missing or not one of off, dry_run, on (Fastify schema validation, code FST_ERR_VALIDATION).- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Unknown body fields are removed silently (additionalProperties: false).
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X PUT "https://panel.example.com/api/billing/enforcement" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"mode": "dry_run"
}'{
"mode": "dry_run"
}
/api/billing/run-tick
Run the billing tick now
Runs the same daily billing tick the scheduler runs, synchronously, and returns its report: issues invoices whose anchor date has arrived, flips past-due invoices to overdue, sends each due dunning notification once, and moves sites up or down the dunning ladder according to the master switch. With dryRun: true nothing is written, sent or applied โ the report only describes what a real run would do.
- Token or session
- Admin
- Audit:
billing.tick_manual
Body
dryRunboolean- Preview only: forces mode dry_run for this run regardless of the master switch.not validated (no schema; truthy check), default false
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Response shape: { mode: "off"|"dry_run"|"on", issued: string[], notified: string[], escalated: string[], restored: string[], skipped: string[], errors: string[] }. mode is "dry_run" when dryRun was true, otherwise the master-switch value.
- Real run line formats: issued = invoice numbers ("INV-2026-0042"); notified = "<domain>: <action>"; escalated = "<domain>: <from> โ <to>"; restored = "<domain>"; skipped = "<domain>: <reason>" (e.g. "billing enforcement is off", "site is deploying โ deferred", "apply failed: โฆ"); errors = "issue #<subId>: <message>" or "sub #<subId>: <message>". Dry-run lines are prefixed with "would โฆ".
- A real (non-dry) run issues invoices and SENDS notifications (panel notification + Telegram) even when the master switch is "off"; only escalation is blocked by "off" (reported under skipped). Restoring a site that no longer owes anything is applied even when the switch is "off".
- Only subscriptions with status active, past_due or suspended are processed. The oldest unpaid (open/partial/overdue) invoice drives the ladder; the grace period (subscription โ plan) withholds enforcement but not notifications; neverAutoSuspend or a plan with autoSuspend=false caps the level at banner.
- Idempotent: invoices are issued once per period, notifications once per invoice per rung, and enforcement only acts when the target level differs from the stored one. Can take a while โ runs nginx changes over SSH for remote sites.
- Emits the billing.suspended event when a site is moved to suspend or archived.
- The body is read without a schema; send a JSON object (an empty JSON body with Content-Type application/json is rejected by Fastify).
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/run-tick" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"dryRun": true
}'{
"mode": "dry_run",
"issued": [
"would issue for shop.example.com"
],
"notified": [
"shop.example.com: would send invoice_due"
],
"escalated": [
"blog.example.com: would enforce (none โ banner)"
],
"restored": [],
"skipped": [],
"errors": []
}
/api/billing/subscriptions/{id}/enforce
Force an enforcement level
Manually moves one subscription's site to an enforcement level. "none" restores the site and is always applied; banner, restrict and suspend go through the same guarded path as the tick and respect the master switch, the neverAutoSuspend cap and running deploys. When applied, the subscription's enforcementLevel, status, suspendedAt and lastEnforcedAt are updated.
- Token or session
- Admin
- Audit:
billing.enforce
Path parameters
idintegerrequired- Subscription id.not validated (Number(...) of the path segment)
Body
levelstringrequired- Target level.one of: none, banner, restrict, suspend
Errors
- 400
body/level must be equal to one of the allowed valueslevel missing or invalid (schema validation).- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.- 404
Subscription not foundNo subscription with this id, or its site no longer exists.
- Response shape: { applied: boolean, dryRun: boolean, from: level, to: level, reason?: string, output?: string } โ always 200, even when nothing was applied. Typical reasons: "billing enforcement is off", "already at this level", "site is deploying โ deferred", "dry run: would move none โ banner", "site not found", "apply failed: <message>". output is the site-suspend.sh stdout+stderr when applied.
- to is the capped level: with neverAutoSuspend=true, restrict/suspend are capped to banner.
- "none" is forced: it bypasses the "off" switch and also dry_run mode (the site really is restored).
- Status mapping on success: none โ active, suspend โ suspended, banner/restrict โ past_due. "archived" cannot be requested here (only the tick's archive rung reaches it).
- Audit: the route itself writes no audit entry; the enforcer writes billing.enforce on a successful apply (without a user id) or billing.enforce_failed when the script fails. A BillingEvent row is recorded for every attempt except the "already at this level" no-op.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl -X POST "https://panel.example.com/api/billing/subscriptions/7/enforce" \
-H "Authorization: Bearer $ORCH_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"level": "banner"
}'{
"applied": true,
"dryRun": false,
"from": "none",
"to": "banner",
"output": "billing enforcement for shop.example.com set to: banner\n"
}
/api/billing/profitability
Get per-site profitability
For every non-cancelled subscription, compares what the site is billed with its share of the hosting server's monthly cost (server cost divided by ALL sites on that server, billed or not).
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Sites with serverId null live on the local server and use the local server row's monthlyCostMinor.
- netMarginMinor = amount โ costShareMinor with no currency conversion (the subscription currency and the server cost currency may differ).
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/profitability" \
-H "Authorization: Bearer $ORCH_TOKEN"[
{
"siteId": 7,
"domain": "shop.example.com",
"client": "Ada Lovelace",
"amount": 3000,
"currency": "GEL",
"amountFormatted": "30.00 โพ",
"serverId": null,
"sitesOnServer": 4,
"serverCostMinor": 8000,
"costShareMinor": 2000,
"netMarginMinor": 1000,
"status": "active",
"enforcementLevel": "none"
}
]
/api/billing/server-economics
Get server economics
Read-only report per server: monthly cost, revenue from the billed sites it hosts (per currency), margin in the server's cost currency, revenue per site and the latest CPU/RAM/disk utilisation sample.
- Token or session
- Admin
Errors
- 401
Invalid or expired access tokenThe personal access token is unknown, revoked or expired.- 401
UnauthorizedNo token, or an invalid session.- 403
Forbidden: insufficient roleYour role may not call this endpoint.
- Sites with serverId null are counted under the local server. Revenue counts non-cancelled subscriptions only.
- marginMinor and revenuePerSiteMinor only use revenue in the server's costCurrency (default GEL); revenue in other currencies appears only in revenueByCurrency.
- utilization is null when the server has no metric sample.
- All /api/billing routes are admin-only (file-level preHandler hooks: authenticate + requireRole(['admin'])).
curl "https://panel.example.com/api/billing/server-economics" \
-H "Authorization: Bearer $ORCH_TOKEN"{
"servers": [
{
"serverId": 1,
"name": "Local",
"kind": "local",
"siteCount": 4,
"billedSiteCount": 3,
"costMinor": 8000,
"costCurrency": "GEL",
"costFormatted": "80.00 โพ",
"revenueByCurrency": [
{
"currency": "GEL",
"minor": 9000,
"formatted": "90.00 โพ"
}
],
"marginMinor": 1000,
"marginCurrency": "GEL",
"marginFormatted": "10.00 โพ",
"revenuePerSiteMinor": 2250,
"utilization": {
"cpu": 23.5,
"ram": 61.2,
"disk": 48,
"at": "2026-11-27T10:00:00.000Z"
}
}
]
}