@aglyn/tenant-data-admin 1.0.0-beta.269 → 1.0.0-beta.271
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/render-cache.d.ts +10 -3
- package/src/lib/render-cache.js +10 -3
- package/src/lib/render-cache.js.map +1 -1
- package/src/lib/server/append-only-history-write.d.ts +38 -0
- package/src/lib/server/append-only-history-write.js +60 -0
- package/src/lib/server/append-only-history-write.js.map +1 -0
- package/src/lib/server/billing-addons.d.ts +58 -30
- package/src/lib/server/billing-addons.js +102 -77
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +166 -0
- package/src/lib/server/bundle-links.js +286 -0
- package/src/lib/server/bundle-links.js.map +1 -0
- package/src/lib/server/client-build.d.ts +74 -0
- package/src/lib/server/client-build.js +264 -0
- package/src/lib/server/client-build.js.map +1 -0
- package/src/lib/server/configured-url-fetch.d.ts +26 -0
- package/src/lib/server/configured-url-fetch.js +68 -0
- package/src/lib/server/configured-url-fetch.js.map +1 -1
- package/src/lib/server/custom-domain-redirects.d.ts +50 -0
- package/src/lib/server/custom-domain-redirects.js +61 -0
- package/src/lib/server/custom-domain-redirects.js.map +1 -0
- package/src/lib/server/host-custom-domain.d.ts +125 -0
- package/src/lib/server/host-custom-domain.js +395 -0
- package/src/lib/server/host-custom-domain.js.map +1 -0
- package/src/lib/server/host-memberships.d.ts +35 -2
- package/src/lib/server/host-memberships.js +63 -2
- package/src/lib/server/host-memberships.js.map +1 -1
- package/src/lib/server/host-released-names.d.ts +1 -2
- package/src/lib/server/host-released-names.js +4 -2
- package/src/lib/server/host-released-names.js.map +1 -1
- package/src/lib/server/media-photo-links.d.ts +196 -0
- package/src/lib/server/media-photo-links.js +290 -0
- package/src/lib/server/media-photo-links.js.map +1 -0
- package/src/lib/server/org-billing.d.ts +4 -2
- package/src/lib/server/org-billing.js +5 -0
- package/src/lib/server/org-billing.js.map +1 -1
- package/src/lib/server/organizations.d.ts +25 -1
- package/src/lib/server/organizations.js +62 -2
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/personal-data-export.js +21 -1
- package/src/lib/server/personal-data-export.js.map +1 -1
- package/src/lib/server/push-delivery.js +32 -14
- package/src/lib/server/push-delivery.js.map +1 -1
- package/src/lib/server/site-care-emails.d.ts +52 -0
- package/src/lib/server/site-care-emails.js +97 -0
- package/src/lib/server/site-care-emails.js.map +1 -0
- package/src/lib/server/site-care-inbound.d.ts +80 -0
- package/src/lib/server/site-care-inbound.js +171 -0
- package/src/lib/server/site-care-inbound.js.map +1 -0
- package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
- package/src/lib/server/site-care-project-reconcile.js +211 -0
- package/src/lib/server/site-care-project-reconcile.js.map +1 -0
- package/src/lib/server/site-care-project-stripe.d.ts +114 -0
- package/src/lib/server/site-care-project-stripe.js +305 -0
- package/src/lib/server/site-care-project-stripe.js.map +1 -0
- package/src/lib/server/site-care-projects.d.ts +169 -0
- package/src/lib/server/site-care-projects.js +882 -0
- package/src/lib/server/site-care-projects.js.map +1 -0
- package/src/lib/server/site-care-reconcile.d.ts +81 -0
- package/src/lib/server/site-care-reconcile.js +349 -0
- package/src/lib/server/site-care-reconcile.js.map +1 -0
- package/src/lib/server/site-care-requests.d.ts +243 -0
- package/src/lib/server/site-care-requests.js +1414 -0
- package/src/lib/server/site-care-requests.js.map +1 -0
- package/src/lib/server/site-care-stripe.d.ts +175 -0
- package/src/lib/server/site-care-stripe.js +375 -0
- package/src/lib/server/site-care-stripe.js.map +1 -0
- package/src/lib/server/tenant-dns-check.d.ts +58 -0
- package/src/lib/server/tenant-dns-check.js +197 -0
- package/src/lib/server/tenant-dns-check.js.map +1 -0
- package/src/lib/server/upgrade-proposal.d.ts +40 -1
- package/src/lib/server/upgrade-proposal.js +92 -50
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/tenancy.d.ts +5 -0
- package/src/tenancy.js +10 -0
- package/src/tenancy.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-data-admin",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.271",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.0.0-beta.
|
|
29
|
-
"@aglyn/shared-util-email": "1.0.0-beta.
|
|
30
|
-
"@aglyn/shared-util-fbserver": "1.0.0-beta.
|
|
31
|
-
"@aglyn/shared-util-first-touch": "1.0.0-beta.
|
|
32
|
-
"@aglyn/shared-util-http": "1.0.0-beta.
|
|
33
|
-
"@aglyn/shared-util-tools": "1.0.0-beta.
|
|
28
|
+
"@aglyn/aglyn": "1.0.0-beta.271",
|
|
29
|
+
"@aglyn/shared-util-email": "1.0.0-beta.271",
|
|
30
|
+
"@aglyn/shared-util-fbserver": "1.0.0-beta.271",
|
|
31
|
+
"@aglyn/shared-util-first-touch": "1.0.0-beta.271",
|
|
32
|
+
"@aglyn/shared-util-http": "1.0.0-beta.271",
|
|
33
|
+
"@aglyn/shared-util-tools": "1.0.0-beta.271",
|
|
34
34
|
"@msgpack/msgpack": "^3.1.3",
|
|
35
35
|
"@swc/helpers": "0.5.23",
|
|
36
36
|
"sharp": "^0.35.5",
|
|
@@ -94,9 +94,16 @@ export declare const tenantDataTag: (hostId: string) => string;
|
|
|
94
94
|
* ⛔ NOT for reads that change OUTSIDE a publish. Two deliberately keep their
|
|
95
95
|
* own short TTLs and must not be moved onto this one:
|
|
96
96
|
*
|
|
97
|
-
* - `ORG_BILLING_TTL_SECONDS` —
|
|
98
|
-
*
|
|
99
|
-
*
|
|
97
|
+
* - `ORG_BILLING_TTL_SECONDS` — the request-time org read (the lockdown
|
|
98
|
+
* verdict and the other dynamic routes), where a bandwidth cap or a
|
|
99
|
+
* suspension stamped straight onto the doc arrives by TTL alone. The
|
|
100
|
+
* render's own org read is on this backstop instead (`scope: 'render'`):
|
|
101
|
+
* plan transitions, staff overrides and org settings all announce
|
|
102
|
+
* themselves through `revalidateOrgHosts`.
|
|
103
|
+
*
|
|
104
|
+
* ⚠️ Any TTL read inside the ISR render also caps the PAGE: `unstable_cache`
|
|
105
|
+
* lowers the regeneration's `revalidate` to the shortest TTL it saw, so one
|
|
106
|
+
* 60s entry holds the catch-all's 3600 at 60.
|
|
100
107
|
* - `HOST_ALIAS_TTL_SECONDS` / `HOST_DOC_TTL_SECONDS` — a custom domain
|
|
101
108
|
* attaching is the customer sitting there waiting for their site
|
|
102
109
|
* (AGL-2010), and the `cname--` alias entry expires only by TTL.
|
package/src/lib/render-cache.js
CHANGED
|
@@ -92,9 +92,16 @@
|
|
|
92
92
|
* ⛔ NOT for reads that change OUTSIDE a publish. Two deliberately keep their
|
|
93
93
|
* own short TTLs and must not be moved onto this one:
|
|
94
94
|
*
|
|
95
|
-
* - `ORG_BILLING_TTL_SECONDS` —
|
|
96
|
-
*
|
|
97
|
-
*
|
|
95
|
+
* - `ORG_BILLING_TTL_SECONDS` — the request-time org read (the lockdown
|
|
96
|
+
* verdict and the other dynamic routes), where a bandwidth cap or a
|
|
97
|
+
* suspension stamped straight onto the doc arrives by TTL alone. The
|
|
98
|
+
* render's own org read is on this backstop instead (`scope: 'render'`):
|
|
99
|
+
* plan transitions, staff overrides and org settings all announce
|
|
100
|
+
* themselves through `revalidateOrgHosts`.
|
|
101
|
+
*
|
|
102
|
+
* ⚠️ Any TTL read inside the ISR render also caps the PAGE: `unstable_cache`
|
|
103
|
+
* lowers the regeneration's `revalidate` to the shortest TTL it saw, so one
|
|
104
|
+
* 60s entry holds the catch-all's 3600 at 60.
|
|
98
105
|
* - `HOST_ALIAS_TTL_SECONDS` / `HOST_DOC_TTL_SECONDS` — a custom domain
|
|
99
106
|
* attaching is the customer sitting there waiting for their site
|
|
100
107
|
* (AGL-2010), and the `cname--` alias entry expires only by TTL.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/tenant/data/admin/src/lib/render-cache.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { unstable_cache } from 'next/cache'\n\n/**\n * Cross-request caching for the tenant render path's Firestore reads\n * (AGL-1302, the caching half of AGL-1151).\n *\n * Every tenant SSR render fanned out to ~15–40 uncached Admin-SDK reads —\n * host resolution, org billing, screen + version, the layout chain, and the\n * whole compose bundle (components, variables, functions, datasets,\n * workflows, plugin installs). None of that data is per-visitor, and almost\n * all of it is identical across every path on a site, so a 50-route sweep\n * paid the same host-scoped reads 50 times over. Routine verification\n * traffic alone burned ~44K reads/day (87% of the free tier).\n *\n * This module is deliberately a THIN wrapper around `unstable_cache` rather\n * than a cache of its own, so invalidation stays Next's: entries are tagged\n * and the existing publish/revalidate path (`/api/revalidate`, AGL-1150)\n * busts them with `revalidateTag` the same moment it drops the page HTML.\n *\n * Ground rules encoded here, because `unstable_cache` enforces none of them:\n *\n * - VALUES ARE JSON. `unstable_cache` stores `JSON.stringify(result)`, so a\n * cache HIT returns plain data while a MISS would return live objects —\n * Firestore `Timestamp`s, most importantly, whose `.seconds` getter decays\n * to `_seconds` across the round trip. Serving two shapes for the same\n * read is how a schedule check works in testing and misfires in\n * production, so `withRenderCache` normalizes the MISS through the same\n * JSON round trip. Callers whose logic needs live `Timestamp` semantics\n * must not cache that read (see the pending-`publishSchedule` guards at\n * the call sites).\n *\n * - NEGATIVES ARE NOT CACHED unless a caller opts in via `store`. A\n * transient miss (host not found, doc missing) cached for the TTL is a\n * self-inflicted outage; the Firestore negative-cache class of bug is\n * exactly this shape.\n *\n * - OUTSIDE NEXT (jest, scripts) there is no incremental cache and\n * `unstable_cache` throws its `incrementalCache missing` invariant before\n * running the callback. The wrapper catches precisely that and falls back\n * to the uncached read, so shared-lib specs exercise the same code path\n * they always did.\n *\n * - NEVER cache per-user reads through this. Everything cached here must be\n * a pure function of published site data.\n */\n\n/**\n * One tag per host covers every host-scoped cached doc — the host doc, the\n * compose bundle, plugin installs, the sitemap payload. The tenant\n * `/api/revalidate` route busts it on publish (alongside its existing\n * `revalidatePath` calls), so a publish is exactly as instant as AGL-1150\n * made it; the TTL is only the backstop for writes that never announce\n * themselves.\n */\nexport const tenantDataTag = (hostId: string): string => `tenant-data:${hostId}`\n\n/**\n * The backstop TTL for published site data — every read that\n * `revalidateTag(tenantDataTag(hostId))` busts on publish.\n *\n * WHY AN HOUR AND NOT A MINUTE (2026-08-26, from the Vercel cost review).\n *\n * Every cache in this layer shipped at 60s, and the page above them was\n * `revalidate = 60` too. Setting the backstop to the same order as the\n * request rate makes it the PRIMARY propagation mechanism rather than a\n * backstop: the whole chain expired together, so a render a minute paid the\n * full sequential Firestore walk — host, org billing, redirect rules, page\n * resolution, screen, compose bundle, enrichers — and none of it was ever\n * stale in a way anyone could observe, because the publish path had already\n * busted the tag the moment the content changed.\n *\n * Measured on `/[host]/[scheme]/[[...slug]]`: 0.78 GB-hr across 635 invocations, a P75\n * of 3.65s, and ~4.4 GB-s per render — the most expensive route per hit in\n * the account, on a site with no real traffic yet.\n *\n * So the TTL goes back to being what `withRenderCache`'s own docstring says\n * it is: \"the backstop for writes that never announce themselves.\" An hour\n * bounds an unannounced direct-to-Firestore edit. Everything that goes\n * through the product announces itself and is busted in the same instant it\n * always was, so publish latency is unchanged.\n *\n * ⛔ NOT for reads that change OUTSIDE a publish. Two deliberately keep their\n * own short TTLs and must not be moved onto this one:\n *\n * - `ORG_BILLING_TTL_SECONDS` — a plan change happens in the console and\n * nothing busts the tenant tag for it, so this TTL is the ONLY thing\n * propagating an upgrade or a downgrade to the live site.\n * - `HOST_ALIAS_TTL_SECONDS` / `HOST_DOC_TTL_SECONDS` — a custom domain\n * attaching is the customer sitting there waiting for their site\n * (AGL-2010), and the `cname--` alias entry expires only by TTL.\n *\n * Takedowns are unaffected either way: the middleware runs ahead of every\n * cache here and carries its own memo, which is what\n * `lockdown-middleware-propagation.spec.ts` measures.\n */\nexport const PUBLISHED_SITE_DATA_TTL_SECONDS = 3600\n\n/**\n * The backstop for the one read a screen publish changes under an UNCHANGED\n * cache key — the version pointer (AGL-2573).\n *\n * The hour above is argued on the premise that \"everything that goes through\n * the product announces itself\". That premise held for eleven days in August\n * and then did not: the tenant refused the announce and every publish on the\n * platform fell back to this TTL. The announce is still the mechanism — no TTL\n * can make a publish instant, because the page above these caches is ISR-held\n * and does not re-run a loader to notice a fresher document — but a backstop\n * only bounds a failure, and an hour is not a bound anyone would choose for\n * \"your published page is not the page you published\".\n *\n * Applied to the POINTER alone, deliberately, because the pointer alone is\n * what makes the hour expensive. `get-screen-version` is keyed by `versionId`,\n * so the body of a newly published version misses on its own; the only thing\n * standing between a visitor and it is the screen document that names which\n * version is live. That document is one small read, and shortening it leaves\n * the expensive reads — the compose bundle, the node trees — at the hour the\n * cost review set.\n *\n * The principle rather than a tuned figure: **the pointer must never be staler\n * than the HTML that reads it** — `<=` the tenant catch-all's ISR window\n * (`apps/tenant/app/[host]/[scheme]/[[...slug]]/page.tsx`), which\n * `publish-pointer-tracks-page-window.spec.ts` enforces. Above the window, the\n * page regenerates and faithfully rebuilds itself from a stale pointer, which\n * is the failure being closed.\n *\n * It matched that window exactly while the window was also 600s. It no longer\n * does, and staying at 600 under an hour-long window is the deliberate choice\n * (AGL-2690): the loader runs only when the page regenerates, so a shorter TTL\n * here costs the same single read per regeneration — a miss instead of a hit —\n * and buys a rebuild from data at most ten minutes old rather than up to an\n * hour old. That difference only shows when the publish announce is down, and\n * the announce has been down for eleven days once already.\n *\n * The read cost this adds is one document per page REGENERATION rather than\n * one per hour — regenerations are already bounded by the ISR window, so the\n * ceiling is the render rate and not the request rate. That is the price of\n * the bound, and it is the cheapest read on the path.\n */\nexport const PUBLISH_POINTER_TTL_SECONDS = 600\n\n/**\n * The alias→hostId resolution is tagged separately because it is the one\n * cache keyed BEFORE the hostId is known. It only changes on subdomain\n * rename or custom-domain (dis)connect, never on publish.\n */\nexport const tenantHostAliasTag = (alias: string): string =>\n `tenant-host:${alias}`\n\n/**\n * A value that must be RETURNED but not STORED (a negative result, or a doc\n * carrying a pending publish schedule). Thrown out of the cached callback so\n * `unstable_cache` never writes it, caught by the wrapper and unwrapped.\n */\nclass BypassStore extends Error {\n constructor(readonly value: unknown) {\n super('render-cache bypass')\n this.name = 'RenderCacheBypass'\n }\n}\n\nconst isMissingIncrementalCache = (error: unknown): boolean =>\n error instanceof Error && error.message.includes('incrementalCache missing')\n\n/**\n * The same normalization the page props already go through (`JSON.parse(\n * JSON.stringify(...))` at every loader exit), applied at the cache boundary\n * so hits and misses hand back byte-identical shapes.\n */\nexport function toPlainJson<T>(value: T): T {\n if (value === undefined || value === null) return value\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nexport interface RenderCacheOptions<T> {\n /**\n * Cache key parts. The FIRST part must be unique per read helper — every\n * call funnels through the same callback source, and `unstable_cache` keys\n * on callback text + key parts, so the name prefix is what keeps\n * `getScreen` and `getComponents` from colliding.\n */\n key: readonly string[]\n /** TTL in seconds — the staleness backstop when no tag bust arrives. */\n revalidate: number\n /** Tags `revalidateTag` can bust — see `tenantDataTag`. */\n tags: readonly string[]\n /** The uncached read. Must resolve to JSON-serializable data. */\n read: () => Promise<T>\n /**\n * Return `false` to serve the value WITHOUT storing it. Negative results\n * and docs whose live `Timestamp` semantics matter (pending publish\n * schedules) belong here. `undefined` is never stored regardless.\n */\n store?: (value: T) => boolean\n}\n\nexport async function withRenderCache<T>(\n options: RenderCacheOptions<T>,\n): Promise<T> {\n const { key, revalidate, tags, read, store } = options\n const cached = unstable_cache(\n async () => {\n const value = toPlainJson(await read())\n if (value === undefined || (store && !store(value))) {\n throw new BypassStore(value)\n }\n return value\n },\n [...key],\n { revalidate, tags: [...tags] },\n )\n try {\n return await cached()\n } catch (error) {\n if (error instanceof BypassStore) return error.value as T\n // No Next server context (jest, one-off scripts): the invariant throws\n // before the callback runs, so reading directly is not a double read.\n if (isMissingIncrementalCache(error)) return toPlainJson(await read())\n throw error\n }\n}\n"],"names":["unstable_cache","tenantDataTag","hostId","PUBLISHED_SITE_DATA_TTL_SECONDS","PUBLISH_POINTER_TTL_SECONDS","tenantHostAliasTag","alias","BypassStore","Error","value","name","isMissingIncrementalCache","error","message","includes","toPlainJson","undefined","JSON","parse","stringify","withRenderCache","options","key","revalidate","tags","read","store","cached"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,QAAQ,aAAY;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED;;;;;;;CAOC,GACD,OAAO,MAAMC,gBAAgB,CAACC,SAA2B,CAAC,YAAY,EAAEA,QAAQ,CAAA;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCC,GACD,OAAO,MAAMC,kCAAkC,KAAI;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwCC,GACD,OAAO,MAAMC,8BAA8B,IAAG;AAE9C;;;;CAIC,GACD,OAAO,MAAMC,qBAAqB,CAACC,QACjC,CAAC,YAAY,EAAEA,OAAO,CAAA;AAExB;;;;CAIC,GACD,IAAA,AAAMC,cAAN,MAAMA,oBAAoBC;IACxB,YAAY,AAASC,KAAc,CAAE;QACnC,KAAK,CAAC,6BADaA,QAAAA;QAEnB,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA,MAAMC,4BAA4B,CAACC,QACjCA,iBAAiBJ,SAASI,MAAMC,OAAO,CAACC,QAAQ,CAAC;AAEnD;;;;CAIC,GACD,OAAO,SAASC,YAAeN,KAAQ;IACrC,IAAIA,UAAUO,aAAaP,UAAU,MAAM,OAAOA;IAClD,OAAOQ,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACV;AACnC;AAwBA,OAAO,eAAeW,gBACpBC,OAA8B;IAE9B,MAAM,EAAEC,GAAG,EAAEC,UAAU,EAAEC,IAAI,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAC/C,MAAMM,SAAS3B,eACb;QACE,MAAMS,QAAQM,YAAY,MAAMU;QAChC,IAAIhB,UAAUO,aAAcU,SAAS,CAACA,MAAMjB,QAAS;YACnD,MAAM,IAAIF,YAAYE;QACxB;QACA,OAAOA;IACT,GACA;WAAIa;KAAI,EACR;QAAEC;QAAYC,MAAM;eAAIA;SAAK;IAAC;IAEhC,IAAI;QACF,OAAO,MAAMG;IACf,EAAE,OAAOf,OAAO;QACd,IAAIA,iBAAiBL,aAAa,OAAOK,MAAMH,KAAK;QACpD,uEAAuE;QACvE,sEAAsE;QACtE,IAAIE,0BAA0BC,QAAQ,OAAOG,YAAY,MAAMU;QAC/D,MAAMb;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/tenant/data/admin/src/lib/render-cache.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { unstable_cache } from 'next/cache'\n\n/**\n * Cross-request caching for the tenant render path's Firestore reads\n * (AGL-1302, the caching half of AGL-1151).\n *\n * Every tenant SSR render fanned out to ~15–40 uncached Admin-SDK reads —\n * host resolution, org billing, screen + version, the layout chain, and the\n * whole compose bundle (components, variables, functions, datasets,\n * workflows, plugin installs). None of that data is per-visitor, and almost\n * all of it is identical across every path on a site, so a 50-route sweep\n * paid the same host-scoped reads 50 times over. Routine verification\n * traffic alone burned ~44K reads/day (87% of the free tier).\n *\n * This module is deliberately a THIN wrapper around `unstable_cache` rather\n * than a cache of its own, so invalidation stays Next's: entries are tagged\n * and the existing publish/revalidate path (`/api/revalidate`, AGL-1150)\n * busts them with `revalidateTag` the same moment it drops the page HTML.\n *\n * Ground rules encoded here, because `unstable_cache` enforces none of them:\n *\n * - VALUES ARE JSON. `unstable_cache` stores `JSON.stringify(result)`, so a\n * cache HIT returns plain data while a MISS would return live objects —\n * Firestore `Timestamp`s, most importantly, whose `.seconds` getter decays\n * to `_seconds` across the round trip. Serving two shapes for the same\n * read is how a schedule check works in testing and misfires in\n * production, so `withRenderCache` normalizes the MISS through the same\n * JSON round trip. Callers whose logic needs live `Timestamp` semantics\n * must not cache that read (see the pending-`publishSchedule` guards at\n * the call sites).\n *\n * - NEGATIVES ARE NOT CACHED unless a caller opts in via `store`. A\n * transient miss (host not found, doc missing) cached for the TTL is a\n * self-inflicted outage; the Firestore negative-cache class of bug is\n * exactly this shape.\n *\n * - OUTSIDE NEXT (jest, scripts) there is no incremental cache and\n * `unstable_cache` throws its `incrementalCache missing` invariant before\n * running the callback. The wrapper catches precisely that and falls back\n * to the uncached read, so shared-lib specs exercise the same code path\n * they always did.\n *\n * - NEVER cache per-user reads through this. Everything cached here must be\n * a pure function of published site data.\n */\n\n/**\n * One tag per host covers every host-scoped cached doc — the host doc, the\n * compose bundle, plugin installs, the sitemap payload. The tenant\n * `/api/revalidate` route busts it on publish (alongside its existing\n * `revalidatePath` calls), so a publish is exactly as instant as AGL-1150\n * made it; the TTL is only the backstop for writes that never announce\n * themselves.\n */\nexport const tenantDataTag = (hostId: string): string => `tenant-data:${hostId}`\n\n/**\n * The backstop TTL for published site data — every read that\n * `revalidateTag(tenantDataTag(hostId))` busts on publish.\n *\n * WHY AN HOUR AND NOT A MINUTE (2026-08-26, from the Vercel cost review).\n *\n * Every cache in this layer shipped at 60s, and the page above them was\n * `revalidate = 60` too. Setting the backstop to the same order as the\n * request rate makes it the PRIMARY propagation mechanism rather than a\n * backstop: the whole chain expired together, so a render a minute paid the\n * full sequential Firestore walk — host, org billing, redirect rules, page\n * resolution, screen, compose bundle, enrichers — and none of it was ever\n * stale in a way anyone could observe, because the publish path had already\n * busted the tag the moment the content changed.\n *\n * Measured on `/[host]/[scheme]/[[...slug]]`: 0.78 GB-hr across 635 invocations, a P75\n * of 3.65s, and ~4.4 GB-s per render — the most expensive route per hit in\n * the account, on a site with no real traffic yet.\n *\n * So the TTL goes back to being what `withRenderCache`'s own docstring says\n * it is: \"the backstop for writes that never announce themselves.\" An hour\n * bounds an unannounced direct-to-Firestore edit. Everything that goes\n * through the product announces itself and is busted in the same instant it\n * always was, so publish latency is unchanged.\n *\n * ⛔ NOT for reads that change OUTSIDE a publish. Two deliberately keep their\n * own short TTLs and must not be moved onto this one:\n *\n * - `ORG_BILLING_TTL_SECONDS` — the request-time org read (the lockdown\n * verdict and the other dynamic routes), where a bandwidth cap or a\n * suspension stamped straight onto the doc arrives by TTL alone. The\n * render's own org read is on this backstop instead (`scope: 'render'`):\n * plan transitions, staff overrides and org settings all announce\n * themselves through `revalidateOrgHosts`.\n *\n * ⚠️ Any TTL read inside the ISR render also caps the PAGE: `unstable_cache`\n * lowers the regeneration's `revalidate` to the shortest TTL it saw, so one\n * 60s entry holds the catch-all's 3600 at 60.\n * - `HOST_ALIAS_TTL_SECONDS` / `HOST_DOC_TTL_SECONDS` — a custom domain\n * attaching is the customer sitting there waiting for their site\n * (AGL-2010), and the `cname--` alias entry expires only by TTL.\n *\n * Takedowns are unaffected either way: the middleware runs ahead of every\n * cache here and carries its own memo, which is what\n * `lockdown-middleware-propagation.spec.ts` measures.\n */\nexport const PUBLISHED_SITE_DATA_TTL_SECONDS = 3600\n\n/**\n * The backstop for the one read a screen publish changes under an UNCHANGED\n * cache key — the version pointer (AGL-2573).\n *\n * The hour above is argued on the premise that \"everything that goes through\n * the product announces itself\". That premise held for eleven days in August\n * and then did not: the tenant refused the announce and every publish on the\n * platform fell back to this TTL. The announce is still the mechanism — no TTL\n * can make a publish instant, because the page above these caches is ISR-held\n * and does not re-run a loader to notice a fresher document — but a backstop\n * only bounds a failure, and an hour is not a bound anyone would choose for\n * \"your published page is not the page you published\".\n *\n * Applied to the POINTER alone, deliberately, because the pointer alone is\n * what makes the hour expensive. `get-screen-version` is keyed by `versionId`,\n * so the body of a newly published version misses on its own; the only thing\n * standing between a visitor and it is the screen document that names which\n * version is live. That document is one small read, and shortening it leaves\n * the expensive reads — the compose bundle, the node trees — at the hour the\n * cost review set.\n *\n * The principle rather than a tuned figure: **the pointer must never be staler\n * than the HTML that reads it** — `<=` the tenant catch-all's ISR window\n * (`apps/tenant/app/[host]/[scheme]/[[...slug]]/page.tsx`), which\n * `publish-pointer-tracks-page-window.spec.ts` enforces. Above the window, the\n * page regenerates and faithfully rebuilds itself from a stale pointer, which\n * is the failure being closed.\n *\n * It matched that window exactly while the window was also 600s. It no longer\n * does, and staying at 600 under an hour-long window is the deliberate choice\n * (AGL-2690): the loader runs only when the page regenerates, so a shorter TTL\n * here costs the same single read per regeneration — a miss instead of a hit —\n * and buys a rebuild from data at most ten minutes old rather than up to an\n * hour old. That difference only shows when the publish announce is down, and\n * the announce has been down for eleven days once already.\n *\n * The read cost this adds is one document per page REGENERATION rather than\n * one per hour — regenerations are already bounded by the ISR window, so the\n * ceiling is the render rate and not the request rate. That is the price of\n * the bound, and it is the cheapest read on the path.\n */\nexport const PUBLISH_POINTER_TTL_SECONDS = 600\n\n/**\n * The alias→hostId resolution is tagged separately because it is the one\n * cache keyed BEFORE the hostId is known. It only changes on subdomain\n * rename or custom-domain (dis)connect, never on publish.\n */\nexport const tenantHostAliasTag = (alias: string): string =>\n `tenant-host:${alias}`\n\n/**\n * A value that must be RETURNED but not STORED (a negative result, or a doc\n * carrying a pending publish schedule). Thrown out of the cached callback so\n * `unstable_cache` never writes it, caught by the wrapper and unwrapped.\n */\nclass BypassStore extends Error {\n constructor(readonly value: unknown) {\n super('render-cache bypass')\n this.name = 'RenderCacheBypass'\n }\n}\n\nconst isMissingIncrementalCache = (error: unknown): boolean =>\n error instanceof Error && error.message.includes('incrementalCache missing')\n\n/**\n * The same normalization the page props already go through (`JSON.parse(\n * JSON.stringify(...))` at every loader exit), applied at the cache boundary\n * so hits and misses hand back byte-identical shapes.\n */\nexport function toPlainJson<T>(value: T): T {\n if (value === undefined || value === null) return value\n return JSON.parse(JSON.stringify(value)) as T\n}\n\nexport interface RenderCacheOptions<T> {\n /**\n * Cache key parts. The FIRST part must be unique per read helper — every\n * call funnels through the same callback source, and `unstable_cache` keys\n * on callback text + key parts, so the name prefix is what keeps\n * `getScreen` and `getComponents` from colliding.\n */\n key: readonly string[]\n /** TTL in seconds — the staleness backstop when no tag bust arrives. */\n revalidate: number\n /** Tags `revalidateTag` can bust — see `tenantDataTag`. */\n tags: readonly string[]\n /** The uncached read. Must resolve to JSON-serializable data. */\n read: () => Promise<T>\n /**\n * Return `false` to serve the value WITHOUT storing it. Negative results\n * and docs whose live `Timestamp` semantics matter (pending publish\n * schedules) belong here. `undefined` is never stored regardless.\n */\n store?: (value: T) => boolean\n}\n\nexport async function withRenderCache<T>(\n options: RenderCacheOptions<T>,\n): Promise<T> {\n const { key, revalidate, tags, read, store } = options\n const cached = unstable_cache(\n async () => {\n const value = toPlainJson(await read())\n if (value === undefined || (store && !store(value))) {\n throw new BypassStore(value)\n }\n return value\n },\n [...key],\n { revalidate, tags: [...tags] },\n )\n try {\n return await cached()\n } catch (error) {\n if (error instanceof BypassStore) return error.value as T\n // No Next server context (jest, one-off scripts): the invariant throws\n // before the callback runs, so reading directly is not a double read.\n if (isMissingIncrementalCache(error)) return toPlainJson(await read())\n throw error\n }\n}\n"],"names":["unstable_cache","tenantDataTag","hostId","PUBLISHED_SITE_DATA_TTL_SECONDS","PUBLISH_POINTER_TTL_SECONDS","tenantHostAliasTag","alias","BypassStore","Error","value","name","isMissingIncrementalCache","error","message","includes","toPlainJson","undefined","JSON","parse","stringify","withRenderCache","options","key","revalidate","tags","read","store","cached"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,QAAQ,aAAY;AAE3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED;;;;;;;CAOC,GACD,OAAO,MAAMC,gBAAgB,CAACC,SAA2B,CAAC,YAAY,EAAEA,QAAQ,CAAA;AAEhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GACD,OAAO,MAAMC,kCAAkC,KAAI;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwCC,GACD,OAAO,MAAMC,8BAA8B,IAAG;AAE9C;;;;CAIC,GACD,OAAO,MAAMC,qBAAqB,CAACC,QACjC,CAAC,YAAY,EAAEA,OAAO,CAAA;AAExB;;;;CAIC,GACD,IAAA,AAAMC,cAAN,MAAMA,oBAAoBC;IACxB,YAAY,AAASC,KAAc,CAAE;QACnC,KAAK,CAAC,6BADaA,QAAAA;QAEnB,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA,MAAMC,4BAA4B,CAACC,QACjCA,iBAAiBJ,SAASI,MAAMC,OAAO,CAACC,QAAQ,CAAC;AAEnD;;;;CAIC,GACD,OAAO,SAASC,YAAeN,KAAQ;IACrC,IAAIA,UAAUO,aAAaP,UAAU,MAAM,OAAOA;IAClD,OAAOQ,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACV;AACnC;AAwBA,OAAO,eAAeW,gBACpBC,OAA8B;IAE9B,MAAM,EAAEC,GAAG,EAAEC,UAAU,EAAEC,IAAI,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAC/C,MAAMM,SAAS3B,eACb;QACE,MAAMS,QAAQM,YAAY,MAAMU;QAChC,IAAIhB,UAAUO,aAAcU,SAAS,CAACA,MAAMjB,QAAS;YACnD,MAAM,IAAIF,YAAYE;QACxB;QACA,OAAOA;IACT,GACA;WAAIa;KAAI,EACR;QAAEC;QAAYC,MAAM;eAAIA;SAAK;IAAC;IAEhC,IAAI;QACF,OAAO,MAAMG;IACf,EAAE,OAAOf,OAAO;QACd,IAAIA,iBAAiBL,aAAa,OAAOK,MAAMH,KAAK;QACpD,uEAAuE;QACvE,sEAAsE;QACtE,IAAIE,0BAA0BC,QAAQ,OAAOG,YAAY,MAAMU;QAC/D,MAAMb;IACR;AACF"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { type AppendOnlyHistoryRow } from '@aglyn/aglyn/app-utils/append-only-history';
|
|
18
|
+
/** A batch or a transaction: anything that creates and sets a document. */
|
|
19
|
+
type HistoryWriter = Pick<FirebaseFirestore.WriteBatch, 'create' | 'set'> | Pick<FirebaseFirestore.Transaction, 'create' | 'set'>;
|
|
20
|
+
/** The staff audit row a history row is mirrored to. */
|
|
21
|
+
export interface HistoryAudit {
|
|
22
|
+
action: string;
|
|
23
|
+
scope: string;
|
|
24
|
+
/** A path naming the org, so the staff org page's audit card finds it. */
|
|
25
|
+
target: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Creates one history row in the writer, and its audit row beside it when
|
|
29
|
+
* `audit` is given. Returns the new row's reference.
|
|
30
|
+
*/
|
|
31
|
+
export declare function appendHistoryRow(writer: HistoryWriter, firestore: FirebaseFirestore.Firestore, history: FirebaseFirestore.CollectionReference, row: AppendOnlyHistoryRow, audit?: HistoryAudit | null): FirebaseFirestore.DocumentReference;
|
|
32
|
+
/** Writes one row on its own (with its audit row), for a step with no other write. */
|
|
33
|
+
export declare function commitHistoryRow(firestore: FirebaseFirestore.Firestore, history: FirebaseFirestore.CollectionReference, row: AppendOnlyHistoryRow, audit?: HistoryAudit | null): Promise<void>;
|
|
34
|
+
/** A history's rows, oldest first, with their ids. */
|
|
35
|
+
export declare function readHistoryRows(history: FirebaseFirestore.CollectionReference, limit?: number): Promise<Array<AppendOnlyHistoryRow & {
|
|
36
|
+
$id: string;
|
|
37
|
+
}>>;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { sortHistoryRows } from "@aglyn/aglyn/app-utils/append-only-history";
|
|
18
|
+
import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
|
|
19
|
+
import { FieldValue } from "firebase-admin/firestore";
|
|
20
|
+
import { setAdminAudit } from "./admin-audit-write.js";
|
|
21
|
+
/**
|
|
22
|
+
* Creates one history row in the writer, and its audit row beside it when
|
|
23
|
+
* `audit` is given. Returns the new row's reference.
|
|
24
|
+
*/ export function appendHistoryRow(writer, firestore, history, row, audit) {
|
|
25
|
+
// Minted once, before the write: the id is what the row's Stripe
|
|
26
|
+
// idempotency key is built from, so it never changes once written.
|
|
27
|
+
const ref = history.doc(createResourceUid());
|
|
28
|
+
writer.create(ref, row);
|
|
29
|
+
if (audit) {
|
|
30
|
+
setAdminAudit(writer, firestore, _extends({
|
|
31
|
+
actorUid: row.byUid,
|
|
32
|
+
actorEmail: row.byEmail,
|
|
33
|
+
action: audit.action,
|
|
34
|
+
scope: audit.scope,
|
|
35
|
+
target: audit.target,
|
|
36
|
+
reason: row.reason,
|
|
37
|
+
note: row.summary,
|
|
38
|
+
before: row.before,
|
|
39
|
+
after: row.after
|
|
40
|
+
}, row.stripe ? {
|
|
41
|
+
stripe: row.stripe
|
|
42
|
+
} : {}, {
|
|
43
|
+
at: FieldValue.serverTimestamp()
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
return ref;
|
|
47
|
+
}
|
|
48
|
+
/** Writes one row on its own (with its audit row), for a step with no other write. */ export async function commitHistoryRow(firestore, history, row, audit) {
|
|
49
|
+
const batch = firestore.batch();
|
|
50
|
+
appendHistoryRow(batch, firestore, history, row, audit);
|
|
51
|
+
await batch.commit();
|
|
52
|
+
}
|
|
53
|
+
/** A history's rows, oldest first, with their ids. */ export async function readHistoryRows(history, limit = 500) {
|
|
54
|
+
const snapshot = await history.orderBy('atMs', 'asc').limit(limit).get();
|
|
55
|
+
return sortHistoryRows(snapshot.docs.map((doc)=>_extends({
|
|
56
|
+
$id: doc.id
|
|
57
|
+
}, doc.data())));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
//# sourceMappingURL=append-only-history-write.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/append-only-history-write.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type AppendOnlyHistoryRow,\n sortHistoryRows,\n} from '@aglyn/aglyn/app-utils/append-only-history'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\n\n/*\n * THE WRITE SIDE OF AN APPEND-ONLY HISTORY (AGL-3959).\n *\n * A row is CREATED, never set over and never updated: `create` fails on an\n * id that exists, so no code path here can rewrite what happened. Each row\n * goes into the caller's batch beside the change it records, and — when a\n * staff member made the change — beside its `adminAudit` row, so the two\n * commit together or not at all. Reused by every approval-gated charge\n * (Site Care extra time now, AGL-3970's project invoices next); the row's\n * shape and rules are `@aglyn/aglyn/app-utils/append-only-history`.\n */\n\n/** A batch or a transaction: anything that creates and sets a document. */\ntype HistoryWriter =\n | Pick<FirebaseFirestore.WriteBatch, 'create' | 'set'>\n | Pick<FirebaseFirestore.Transaction, 'create' | 'set'>\n\n/** The staff audit row a history row is mirrored to. */\nexport interface HistoryAudit {\n action: string\n scope: string\n /** A path naming the org, so the staff org page's audit card finds it. */\n target: string\n}\n\n/**\n * Creates one history row in the writer, and its audit row beside it when\n * `audit` is given. Returns the new row's reference.\n */\nexport function appendHistoryRow(\n writer: HistoryWriter,\n firestore: FirebaseFirestore.Firestore,\n history: FirebaseFirestore.CollectionReference,\n row: AppendOnlyHistoryRow,\n audit?: HistoryAudit | null,\n): FirebaseFirestore.DocumentReference {\n // Minted once, before the write: the id is what the row's Stripe\n // idempotency key is built from, so it never changes once written.\n const ref = history.doc(createResourceUid())\n ;(writer as Pick<FirebaseFirestore.WriteBatch, 'create'>).create(ref, row)\n if (audit) {\n setAdminAudit(writer as Pick<FirebaseFirestore.WriteBatch, 'set'>, firestore, {\n actorUid: row.byUid,\n actorEmail: row.byEmail,\n action: audit.action,\n scope: audit.scope,\n target: audit.target,\n reason: row.reason,\n note: row.summary,\n before: row.before,\n after: row.after,\n ...(row.stripe ? { stripe: row.stripe } : {}),\n at: FieldValue.serverTimestamp(),\n })\n }\n return ref\n}\n\n/** Writes one row on its own (with its audit row), for a step with no other write. */\nexport async function commitHistoryRow(\n firestore: FirebaseFirestore.Firestore,\n history: FirebaseFirestore.CollectionReference,\n row: AppendOnlyHistoryRow,\n audit?: HistoryAudit | null,\n): Promise<void> {\n const batch = firestore.batch()\n appendHistoryRow(batch, firestore, history, row, audit)\n await batch.commit()\n}\n\n/** A history's rows, oldest first, with their ids. */\nexport async function readHistoryRows(\n history: FirebaseFirestore.CollectionReference,\n limit = 500,\n): Promise<Array<AppendOnlyHistoryRow & { $id: string }>> {\n const snapshot = await history.orderBy('atMs', 'asc').limit(limit).get()\n return sortHistoryRows(\n snapshot.docs.map((doc) => ({ $id: doc.id, ...(doc.data() as AppendOnlyHistoryRow) })),\n )\n}\n"],"names":["sortHistoryRows","createResourceUid","FieldValue","setAdminAudit","appendHistoryRow","writer","firestore","history","row","audit","ref","doc","create","actorUid","byUid","actorEmail","byEmail","action","scope","target","reason","note","summary","before","after","stripe","at","serverTimestamp","commitHistoryRow","batch","commit","readHistoryRows","limit","snapshot","orderBy","get","docs","map","$id","id","data"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,eAAe,QACV,6CAA4C;AACnD,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AA2BnD;;;CAGC,GACD,OAAO,SAASC,iBACdC,MAAqB,EACrBC,SAAsC,EACtCC,OAA8C,EAC9CC,GAAyB,EACzBC,KAA2B;IAE3B,iEAAiE;IACjE,mEAAmE;IACnE,MAAMC,MAAMH,QAAQI,GAAG,CAACV;IACtBI,OAAwDO,MAAM,CAACF,KAAKF;IACtE,IAAIC,OAAO;QACTN,cAAcE,QAAqDC,WAAW;YAC5EO,UAAUL,IAAIM,KAAK;YACnBC,YAAYP,IAAIQ,OAAO;YACvBC,QAAQR,MAAMQ,MAAM;YACpBC,OAAOT,MAAMS,KAAK;YAClBC,QAAQV,MAAMU,MAAM;YACpBC,QAAQZ,IAAIY,MAAM;YAClBC,MAAMb,IAAIc,OAAO;YACjBC,QAAQf,IAAIe,MAAM;YAClBC,OAAOhB,IAAIgB,KAAK;WACZhB,IAAIiB,MAAM,GAAG;YAAEA,QAAQjB,IAAIiB,MAAM;QAAC,IAAI,CAAC;YAC3CC,IAAIxB,WAAWyB,eAAe;;IAElC;IACA,OAAOjB;AACT;AAEA,oFAAoF,GACpF,OAAO,eAAekB,iBACpBtB,SAAsC,EACtCC,OAA8C,EAC9CC,GAAyB,EACzBC,KAA2B;IAE3B,MAAMoB,QAAQvB,UAAUuB,KAAK;IAC7BzB,iBAAiByB,OAAOvB,WAAWC,SAASC,KAAKC;IACjD,MAAMoB,MAAMC,MAAM;AACpB;AAEA,oDAAoD,GACpD,OAAO,eAAeC,gBACpBxB,OAA8C,EAC9CyB,QAAQ,GAAG;IAEX,MAAMC,WAAW,MAAM1B,QAAQ2B,OAAO,CAAC,QAAQ,OAAOF,KAAK,CAACA,OAAOG,GAAG;IACtE,OAAOnC,gBACLiC,SAASG,IAAI,CAACC,GAAG,CAAC,CAAC1B,MAAS;YAAE2B,KAAK3B,IAAI4B,EAAE;WAAM5B,IAAI6B,IAAI;AAE3D"}
|
|
@@ -14,20 +14,21 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import {
|
|
17
|
+
import { type AiTierId, type OrgPlan } from '@aglyn/aglyn/server';
|
|
18
|
+
import { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd, type AddonKind } from '@aglyn/aglyn/app-utils/bundle-intent';
|
|
19
|
+
export { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd, type AddonKind };
|
|
18
20
|
/**
|
|
19
21
|
* Self-serve add-on price map (AGL-525): the bridge between
|
|
20
22
|
* `STRIPE_PRICE_*` env price ids, `org.seatAddons` keys, and
|
|
21
23
|
* `PLAN_PRICING` USD amounts. Add-ons bill as extra items on the org's
|
|
22
24
|
* one subscription, so every kind has a monthly and a yearly price
|
|
23
25
|
* (Stripe allows a single interval per subscription; annual orgs attach
|
|
24
|
-
* the `_YEARLY` variants). Seat/member/dataset/host prices
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
26
|
+
* the `_YEARLY` variants). Seat/member/dataset/host prices are per-plan;
|
|
27
|
+
* POS registers, the Event Calendar and Site Care (AGL-3954) are flat; the
|
|
28
|
+
* Aglyn AI add-on is priced per TIER (AGL-3965, `STRIPE_PRICE_AI_{TIER}`),
|
|
29
|
+
* on any paid plan. Prices are minted by `tools/scripts/setup-stripe.mjs` —
|
|
30
|
+
* keep the three in sync.
|
|
28
31
|
*/
|
|
29
|
-
export type AddonKind = keyof Required<OrgSeatAddons>;
|
|
30
|
-
export declare const ADDON_KINDS: readonly AddonKind[];
|
|
31
32
|
export type BillingInterval = 'month' | 'year';
|
|
32
33
|
/**
|
|
33
34
|
* Every plan that is sold with a Stripe price — DERIVED, never hand-listed
|
|
@@ -49,16 +50,65 @@ export type BillingInterval = 'month' | 'year';
|
|
|
49
50
|
* by definition a paid, priced plan.
|
|
50
51
|
*/
|
|
51
52
|
export declare const PAID_PLANS: readonly OrgPlan[];
|
|
53
|
+
/**
|
|
54
|
+
* The Stripe price id of an Aglyn AI tier (AGL-3965):
|
|
55
|
+
* `STRIPE_PRICE_AI_{TIER}[_YEARLY]`, lookup key `aglyn_ai_{tier}[_yearly]`.
|
|
56
|
+
* The same price on every plan; null when the env isn't configured.
|
|
57
|
+
*/
|
|
58
|
+
export declare function aiTierPriceId(tier: AiTierId, interval: BillingInterval): string | null;
|
|
59
|
+
/**
|
|
60
|
+
* The per-plan AI add-on price sold before tiers existed
|
|
61
|
+
* (`STRIPE_PRICE_{PLAN}_AI_ADDON[_YEARLY]`, AGL-2897). Never sold again; read
|
|
62
|
+
* only so an item still carrying one is recognised as the add-on and as the
|
|
63
|
+
* tier with its price and band until `migrate-ai-addon-tiers.mjs` moves it.
|
|
64
|
+
*/
|
|
65
|
+
export declare function legacyAiAddonPriceId(plan: OrgPlan, interval: BillingInterval): string | null;
|
|
66
|
+
/**
|
|
67
|
+
* Which Aglyn AI tier a price id sells (AGL-3965): a tier price, or a legacy
|
|
68
|
+
* per-plan add-on price read as the tier with the same price and band
|
|
69
|
+
* (`LEGACY_AI_ADDON_TIER_BY_PLAN`). Null for anything else.
|
|
70
|
+
*/
|
|
71
|
+
export declare function aiTierFromPriceId(priceId: string | null | undefined): AiTierId | null;
|
|
72
|
+
/**
|
|
73
|
+
* The tier a subscription's items carry (AGL-3965), or null when none is an
|
|
74
|
+
* Aglyn AI item with a quantity. Written to `org.aiTier` beside the
|
|
75
|
+
* `seatAddons` map `addonQuantitiesFromItems` derives from the same items.
|
|
76
|
+
*/
|
|
77
|
+
export declare function aiTierFromItems(items: ReadonlyArray<{
|
|
78
|
+
price?: {
|
|
79
|
+
id?: string;
|
|
80
|
+
} | null;
|
|
81
|
+
quantity?: number | null;
|
|
82
|
+
}> | null | undefined): AiTierId | null;
|
|
52
83
|
/**
|
|
53
84
|
* The Stripe price id for an add-on kind on a plan at a billing interval;
|
|
54
85
|
* null when the plan doesn't sell it (free) or the env isn't configured.
|
|
86
|
+
*
|
|
87
|
+
* `tier` picks the Aglyn AI tier; absent, the tier a plan-named purchase
|
|
88
|
+
* means (`defaultAiTierForPlan`). Ignored for every other kind.
|
|
55
89
|
*/
|
|
56
|
-
export declare function addonPriceId(kind: AddonKind, plan: OrgPlan, interval: BillingInterval): string | null;
|
|
90
|
+
export declare function addonPriceId(kind: AddonKind, plan: OrgPlan, interval: BillingInterval, tier?: AiTierId | null): string | null;
|
|
91
|
+
/**
|
|
92
|
+
* The env var that holds an add-on's price id on a plan at an interval, or
|
|
93
|
+
* null where the plan sells no such price. Named on its own so a checkout
|
|
94
|
+
* that Stripe refuses can say which variable points at a missing price.
|
|
95
|
+
* For the Aglyn AI add-on it is the tier's (`STRIPE_PRICE_AI_{TIER}`,
|
|
96
|
+
* AGL-3965), `tier` read as `addonPriceId` reads it.
|
|
97
|
+
*/
|
|
98
|
+
export declare function addonPriceEnvName(kind: AddonKind, plan: OrgPlan, interval: BillingInterval, tier?: AiTierId | null): string | null;
|
|
57
99
|
/**
|
|
58
100
|
* Reverse map: which add-on kind a subscription item's price id sells.
|
|
59
101
|
* Null for non-add-on prices (the base plan item, unknown prices).
|
|
60
102
|
*/
|
|
61
103
|
export declare function addonKindFromPriceId(priceId: string | null | undefined): AddonKind | null;
|
|
104
|
+
/**
|
|
105
|
+
* The price an add-on item moves to on a target plan/interval: the kind's
|
|
106
|
+
* price there, and for the Aglyn AI add-on the SAME tier the item carries
|
|
107
|
+
* now (AGL-3965) — a tier is chosen on its own, so a plan change re-prices
|
|
108
|
+
* only its interval, and a legacy per-plan item becomes the tier with its
|
|
109
|
+
* price and band.
|
|
110
|
+
*/
|
|
111
|
+
export declare function addonTargetPriceId(kind: AddonKind, plan: OrgPlan, interval: BillingInterval, currentPriceId: string | null | undefined): string | null;
|
|
62
112
|
/**
|
|
63
113
|
* The BASE plan's Stripe price id at an interval
|
|
64
114
|
* (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced
|
|
@@ -136,12 +186,6 @@ export declare function findPlanItem<T extends {
|
|
|
136
186
|
id?: string;
|
|
137
187
|
} | null;
|
|
138
188
|
}>(items: readonly T[] | null | undefined): T | null;
|
|
139
|
-
/**
|
|
140
|
-
* Monthly USD per unit for an add-on on a plan (yearly prices are ×12 of
|
|
141
|
-
* this); null when the plan doesn't sell the kind. Single pricing source
|
|
142
|
-
* of truth: `PLAN_PRICING` + the two flat add-on constants.
|
|
143
|
-
*/
|
|
144
|
-
export declare function addonUnitUsd(kind: AddonKind, plan: OrgPlan): number | null;
|
|
145
189
|
/**
|
|
146
190
|
* Full add-on quantity map (explicit zeros for absent kinds) from a
|
|
147
191
|
* subscription's items — the shape written to `org.seatAddons` so
|
|
@@ -153,19 +197,3 @@ export declare function addonQuantitiesFromItems(items: Array<{
|
|
|
153
197
|
} | null;
|
|
154
198
|
quantity?: number | null;
|
|
155
199
|
}> | null | undefined): Record<AddonKind, number>;
|
|
156
|
-
/**
|
|
157
|
-
* Max purchasable quantity per kind, from a purchases-free entitlement
|
|
158
|
-
* resolution (plan defaults + staff overrides only) so the ceiling does not
|
|
159
|
-
* drift as the org buys: seat/dataset kinds stop at the plan's hard max,
|
|
160
|
-
* hosts/registers use flat ceilings, the Event Calendar and Aglyn AI are 0/1
|
|
161
|
-
* toggles. POS registers additionally require the `pos` feature.
|
|
162
|
-
*
|
|
163
|
-
* Lives here rather than inside `/api/billing/addons` because a PLAN CHANGE
|
|
164
|
-
* needs the same ceiling for a different plan. The addons route asks "how many
|
|
165
|
-
* may this org buy on the plan it is on"; `buildTargetItems` asks "how many of
|
|
166
|
-
* what it already bought can the plan it is moving to actually deliver". Two
|
|
167
|
-
* readers, one definition — a second copy is how they answer differently.
|
|
168
|
-
*/
|
|
169
|
-
export declare function addonMaxForBaseline(kind: AddonKind, baseline: ReturnType<typeof resolveOrgEntitlements>): number;
|
|
170
|
-
/** The ceiling a PLAN would impose on an add-on kind, purchases excluded. */
|
|
171
|
-
export declare function addonMaxForPlan(kind: AddonKind, plan: OrgPlan): number;
|
|
@@ -13,26 +13,29 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/ import {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
16
|
+
*/ import { SELF_SERVE_PLANS } from "@aglyn/aglyn/server";
|
|
17
|
+
import { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd } from "@aglyn/aglyn/app-utils/bundle-intent";
|
|
18
|
+
// The Aglyn AI tiers (AGL-3965) by their own module rather than the server
|
|
19
|
+
// barrel: the webhook and every billing route read a subscription's AI item
|
|
20
|
+
// through here, and the many route specs that stub `@aglyn/aglyn/server`
|
|
21
|
+
// with a partial object would otherwise see every tier helper as undefined.
|
|
22
|
+
import { AI_TIER_IDS, defaultAiTierForPlan, LEGACY_AI_ADDON_TIER_BY_PLAN, planSellsAiTiers } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
23
|
+
/*
|
|
24
|
+
* The add-on kinds, their unit prices (the Aglyn AI tier's included) and
|
|
25
|
+
* their ceilings live beside the bundle-link parser (AGL-3955), so the link,
|
|
26
|
+
* the Billing card and this price map read one list. Re-exported here for
|
|
27
|
+
* every server reader that already imports them from this module.
|
|
28
|
+
*/ export { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd };
|
|
26
29
|
/** Kinds priced per plan (env `STRIPE_PRICE_{PLAN}_{SUFFIX}[_YEARLY]`). */ const PER_PLAN_ENV_SUFFIX = {
|
|
27
30
|
managers: 'EXTRA_SEAT',
|
|
28
31
|
members: 'EXTRA_MEMBER',
|
|
29
32
|
datasets: 'EXTRA_DATASET',
|
|
30
|
-
hosts: 'EXTRA_HOST'
|
|
31
|
-
aiAddon: 'AI_ADDON'
|
|
33
|
+
hosts: 'EXTRA_HOST'
|
|
32
34
|
};
|
|
33
35
|
/** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */ const FLAT_ENV_NAME = {
|
|
34
36
|
posRegisters: 'POS_REGISTER',
|
|
35
|
-
eventCalendar: 'EVENT_CALENDAR'
|
|
37
|
+
eventCalendar: 'EVENT_CALENDAR',
|
|
38
|
+
siteCare: 'SITE_CARE'
|
|
36
39
|
};
|
|
37
40
|
/**
|
|
38
41
|
* Every plan that is sold with a Stripe price — DERIVED, never hand-listed
|
|
@@ -57,23 +60,96 @@ function env(name) {
|
|
|
57
60
|
const value = process.env[name];
|
|
58
61
|
return value ? value : null;
|
|
59
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* The Stripe price id of an Aglyn AI tier (AGL-3965):
|
|
65
|
+
* `STRIPE_PRICE_AI_{TIER}[_YEARLY]`, lookup key `aglyn_ai_{tier}[_yearly]`.
|
|
66
|
+
* The same price on every plan; null when the env isn't configured.
|
|
67
|
+
*/ export function aiTierPriceId(tier, interval) {
|
|
68
|
+
const yearly = interval === 'year' ? '_YEARLY' : '';
|
|
69
|
+
return env(`STRIPE_PRICE_AI_${tier.toUpperCase()}${yearly}`);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The per-plan AI add-on price sold before tiers existed
|
|
73
|
+
* (`STRIPE_PRICE_{PLAN}_AI_ADDON[_YEARLY]`, AGL-2897). Never sold again; read
|
|
74
|
+
* only so an item still carrying one is recognised as the add-on and as the
|
|
75
|
+
* tier with its price and band until `migrate-ai-addon-tiers.mjs` moves it.
|
|
76
|
+
*/ export function legacyAiAddonPriceId(plan, interval) {
|
|
77
|
+
if (!PAID_PLANS.includes(plan)) return null;
|
|
78
|
+
const yearly = interval === 'year' ? '_YEARLY' : '';
|
|
79
|
+
return env(`STRIPE_PRICE_${plan.toUpperCase()}_AI_ADDON${yearly}`);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Which Aglyn AI tier a price id sells (AGL-3965): a tier price, or a legacy
|
|
83
|
+
* per-plan add-on price read as the tier with the same price and band
|
|
84
|
+
* (`LEGACY_AI_ADDON_TIER_BY_PLAN`). Null for anything else.
|
|
85
|
+
*/ export function aiTierFromPriceId(priceId) {
|
|
86
|
+
if (!priceId) return null;
|
|
87
|
+
for (const interval of [
|
|
88
|
+
'month',
|
|
89
|
+
'year'
|
|
90
|
+
]){
|
|
91
|
+
for (const tier of AI_TIER_IDS){
|
|
92
|
+
if (aiTierPriceId(tier, interval) === priceId) return tier;
|
|
93
|
+
}
|
|
94
|
+
for (const plan of PAID_PLANS){
|
|
95
|
+
if (legacyAiAddonPriceId(plan, interval) === priceId) {
|
|
96
|
+
var _LEGACY_AI_ADDON_TIER_BY_PLAN_plan;
|
|
97
|
+
return (_LEGACY_AI_ADDON_TIER_BY_PLAN_plan = LEGACY_AI_ADDON_TIER_BY_PLAN[plan]) != null ? _LEGACY_AI_ADDON_TIER_BY_PLAN_plan : null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The tier a subscription's items carry (AGL-3965), or null when none is an
|
|
105
|
+
* Aglyn AI item with a quantity. Written to `org.aiTier` beside the
|
|
106
|
+
* `seatAddons` map `addonQuantitiesFromItems` derives from the same items.
|
|
107
|
+
*/ export function aiTierFromItems(items) {
|
|
108
|
+
for (const item of items != null ? items : []){
|
|
109
|
+
var _ref;
|
|
110
|
+
var _item_price;
|
|
111
|
+
const tier = aiTierFromPriceId(item == null ? void 0 : (_item_price = item.price) == null ? void 0 : _item_price.id);
|
|
112
|
+
if (tier && Number((_ref = item == null ? void 0 : item.quantity) != null ? _ref : 1) >= 1) return tier;
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
60
116
|
/**
|
|
61
117
|
* The Stripe price id for an add-on kind on a plan at a billing interval;
|
|
62
118
|
* null when the plan doesn't sell it (free) or the env isn't configured.
|
|
63
|
-
|
|
119
|
+
*
|
|
120
|
+
* `tier` picks the Aglyn AI tier; absent, the tier a plan-named purchase
|
|
121
|
+
* means (`defaultAiTierForPlan`). Ignored for every other kind.
|
|
122
|
+
*/ export function addonPriceId(kind, plan, interval, tier) {
|
|
123
|
+
const name = addonPriceEnvName(kind, plan, interval, tier);
|
|
124
|
+
return name ? env(name) : null;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The env var that holds an add-on's price id on a plan at an interval, or
|
|
128
|
+
* null where the plan sells no such price. Named on its own so a checkout
|
|
129
|
+
* that Stripe refuses can say which variable points at a missing price.
|
|
130
|
+
* For the Aglyn AI add-on it is the tier's (`STRIPE_PRICE_AI_{TIER}`,
|
|
131
|
+
* AGL-3965), `tier` read as `addonPriceId` reads it.
|
|
132
|
+
*/ export function addonPriceEnvName(kind, plan, interval, tier) {
|
|
64
133
|
const yearly = interval === 'year' ? '_YEARLY' : '';
|
|
134
|
+
if (kind === 'aiAddon') {
|
|
135
|
+
if (!planSellsAiTiers(plan)) return null;
|
|
136
|
+
const chosen = tier != null ? tier : defaultAiTierForPlan(plan);
|
|
137
|
+
return chosen ? `STRIPE_PRICE_AI_${chosen.toUpperCase()}${yearly}` : null;
|
|
138
|
+
}
|
|
65
139
|
const flat = FLAT_ENV_NAME[kind];
|
|
66
|
-
if (flat) return
|
|
140
|
+
if (flat) return `STRIPE_PRICE_${flat}${yearly}`;
|
|
67
141
|
const suffix = PER_PLAN_ENV_SUFFIX[kind];
|
|
68
142
|
if (!suffix || plan === 'free') return null;
|
|
69
|
-
return
|
|
143
|
+
return `STRIPE_PRICE_${plan.toUpperCase()}_${suffix}${yearly}`;
|
|
70
144
|
}
|
|
71
145
|
/**
|
|
72
146
|
* Reverse map: which add-on kind a subscription item's price id sells.
|
|
73
147
|
* Null for non-add-on prices (the base plan item, unknown prices).
|
|
74
148
|
*/ export function addonKindFromPriceId(priceId) {
|
|
75
149
|
if (!priceId) return null;
|
|
150
|
+
if (aiTierFromPriceId(priceId)) return 'aiAddon';
|
|
76
151
|
for (const kind of ADDON_KINDS){
|
|
152
|
+
if (kind === 'aiAddon') continue;
|
|
77
153
|
for (const interval of [
|
|
78
154
|
'month',
|
|
79
155
|
'year'
|
|
@@ -89,6 +165,16 @@ function env(name) {
|
|
|
89
165
|
}
|
|
90
166
|
return null;
|
|
91
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* The price an add-on item moves to on a target plan/interval: the kind's
|
|
170
|
+
* price there, and for the Aglyn AI add-on the SAME tier the item carries
|
|
171
|
+
* now (AGL-3965) — a tier is chosen on its own, so a plan change re-prices
|
|
172
|
+
* only its interval, and a legacy per-plan item becomes the tier with its
|
|
173
|
+
* price and band.
|
|
174
|
+
*/ export function addonTargetPriceId(kind, plan, interval, currentPriceId) {
|
|
175
|
+
const tier = kind === 'aiAddon' ? aiTierFromPriceId(currentPriceId) : null;
|
|
176
|
+
return addonPriceId(kind, plan, interval, tier);
|
|
177
|
+
}
|
|
92
178
|
/**
|
|
93
179
|
* The BASE plan's Stripe price id at an interval
|
|
94
180
|
* (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced
|
|
@@ -193,29 +279,6 @@ function env(name) {
|
|
|
193
279
|
});
|
|
194
280
|
return (_ref = notAnAddon != null ? notAnAddon : list[0]) != null ? _ref : null;
|
|
195
281
|
}
|
|
196
|
-
/**
|
|
197
|
-
* Monthly USD per unit for an add-on on a plan (yearly prices are ×12 of
|
|
198
|
-
* this); null when the plan doesn't sell the kind. Single pricing source
|
|
199
|
-
* of truth: `PLAN_PRICING` + the two flat add-on constants.
|
|
200
|
-
*/ export function addonUnitUsd(kind, plan) {
|
|
201
|
-
const pricing = PLAN_PRICING[plan];
|
|
202
|
-
switch(kind){
|
|
203
|
-
case 'managers':
|
|
204
|
-
return pricing.extraSeatMonthlyUsd;
|
|
205
|
-
case 'members':
|
|
206
|
-
return pricing.extraCollaboratorMonthlyUsd;
|
|
207
|
-
case 'datasets':
|
|
208
|
-
return pricing.extraDatasetMonthlyUsd;
|
|
209
|
-
case 'hosts':
|
|
210
|
-
return pricing.extraHostMonthlyUsd;
|
|
211
|
-
case 'posRegisters':
|
|
212
|
-
return POS_REGISTER_ADDON_MONTHLY_USD;
|
|
213
|
-
case 'eventCalendar':
|
|
214
|
-
return EVENT_CALENDAR_ADDON_MONTHLY_USD;
|
|
215
|
-
case 'aiAddon':
|
|
216
|
-
return pricing.aiAddonMonthlyUsd;
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
282
|
/**
|
|
220
283
|
* Full add-on quantity map (explicit zeros for absent kinds) from a
|
|
221
284
|
* subscription's items — the shape written to `org.seatAddons` so
|
|
@@ -235,43 +298,5 @@ function env(name) {
|
|
|
235
298
|
}
|
|
236
299
|
return quantities;
|
|
237
300
|
}
|
|
238
|
-
/**
|
|
239
|
-
* Max purchasable quantity per kind, from a purchases-free entitlement
|
|
240
|
-
* resolution (plan defaults + staff overrides only) so the ceiling does not
|
|
241
|
-
* drift as the org buys: seat/dataset kinds stop at the plan's hard max,
|
|
242
|
-
* hosts/registers use flat ceilings, the Event Calendar and Aglyn AI are 0/1
|
|
243
|
-
* toggles. POS registers additionally require the `pos` feature.
|
|
244
|
-
*
|
|
245
|
-
* Lives here rather than inside `/api/billing/addons` because a PLAN CHANGE
|
|
246
|
-
* needs the same ceiling for a different plan. The addons route asks "how many
|
|
247
|
-
* may this org buy on the plan it is on"; `buildTargetItems` asks "how many of
|
|
248
|
-
* what it already bought can the plan it is moving to actually deliver". Two
|
|
249
|
-
* readers, one definition — a second copy is how they answer differently.
|
|
250
|
-
*/ export function addonMaxForBaseline(kind, baseline) {
|
|
251
|
-
const bounded = (included, max)=>Number.isFinite(max) ? Math.max(0, max - included) : EXTRA_HOSTS_ADDON_MAX;
|
|
252
|
-
switch(kind){
|
|
253
|
-
case 'managers':
|
|
254
|
-
return bounded(baseline.managersPerOrg, baseline.maxManagersPerOrg);
|
|
255
|
-
case 'members':
|
|
256
|
-
return bounded(baseline.membersPerHost, baseline.maxMembersPerHost);
|
|
257
|
-
case 'datasets':
|
|
258
|
-
return bounded(baseline.datasetsPerOrg, baseline.maxDatasetsPerOrg);
|
|
259
|
-
case 'hosts':
|
|
260
|
-
return baseline.hostLimit === UNLIMITED ? 0 : EXTRA_HOSTS_ADDON_MAX;
|
|
261
|
-
case 'posRegisters':
|
|
262
|
-
return baseline.features.pos ? POS_REGISTERS_ADDON_MAX : 0;
|
|
263
|
-
case 'eventCalendar':
|
|
264
|
-
return 1;
|
|
265
|
-
case 'aiAddon':
|
|
266
|
-
// Org-wide like the Event Calendar: one purchase, and the price map
|
|
267
|
-
// (null on Free and Enterprise) says whether the plan sells it at all.
|
|
268
|
-
return 1;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
/** The ceiling a PLAN would impose on an add-on kind, purchases excluded. */ export function addonMaxForPlan(kind, plan) {
|
|
272
|
-
return addonMaxForBaseline(kind, resolveOrgEntitlements({
|
|
273
|
-
plan
|
|
274
|
-
}));
|
|
275
|
-
}
|
|
276
301
|
|
|
277
302
|
//# sourceMappingURL=billing-addons.js.map
|