@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/billing-addons.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 EVENT_CALENDAR_ADDON_MONTHLY_USD,\n EXTRA_HOSTS_ADDON_MAX,\n PLAN_PRICING,\n POS_REGISTER_ADDON_MONTHLY_USD,\n POS_REGISTERS_ADDON_MAX,\n resolveOrgEntitlements,\n SELF_SERVE_PLANS,\n UNLIMITED,\n type OrgPlan,\n type OrgSeatAddons,\n} from '@aglyn/aglyn/server'\n\n/**\n * Self-serve add-on price map (AGL-525): the bridge between\n * `STRIPE_PRICE_*` env price ids, `org.seatAddons` keys, and\n * `PLAN_PRICING` USD amounts. Add-ons bill as extra items on the org's\n * one subscription, so every kind has a monthly and a yearly price\n * (Stripe allows a single interval per subscription; annual orgs attach\n * the `_YEARLY` variants). Seat/member/dataset/host prices and the Aglyn AI\n * add-on (AGL-2896) are per-plan; POS registers and the Event Calendar are\n * flat. Prices are minted by `tools/scripts/setup-stripe.mjs` — keep the\n * three in sync.\n */\nexport type AddonKind = keyof Required<OrgSeatAddons>\n\nexport const ADDON_KINDS: readonly AddonKind[] = [\n 'managers',\n 'members',\n 'datasets',\n 'hosts',\n 'posRegisters',\n 'eventCalendar',\n 'aiAddon',\n]\n\nexport type BillingInterval = 'month' | 'year'\n\n/** Kinds priced per plan (env `STRIPE_PRICE_{PLAN}_{SUFFIX}[_YEARLY]`). */\nconst PER_PLAN_ENV_SUFFIX: Partial<Record<AddonKind, string>> = {\n managers: 'EXTRA_SEAT',\n members: 'EXTRA_MEMBER',\n datasets: 'EXTRA_DATASET',\n hosts: 'EXTRA_HOST',\n aiAddon: 'AI_ADDON',\n}\n\n/** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */\nconst FLAT_ENV_NAME: Partial<Record<AddonKind, string>> = {\n posRegisters: 'POS_REGISTER',\n eventCalendar: 'EVENT_CALENDAR',\n}\n\n/**\n * Every plan that is sold with a Stripe price — DERIVED, never hand-listed\n * (AGL-1340).\n *\n * The literal that used to sit here listed starter, pro, business and\n * advanced only — it predated the Scale and Agency tiers, so\n * `addonKindFromPriceId()` could not recognise a single Scale/Agency add-on\n * price coming back from Stripe. `addonPriceId()` still SOLD them (it only\n * uppercases the plan), so the money moved and the read-back returned\n * nothing: the webhook wrote `seatAddons: {all zeros}` for the\n * highest-paying orgs on the next subscription event, and `seatAddons` is an\n * ENTITLEMENT INPUT (`plan-entitlements.ts` — it raises `hostLimit` and\n * `posRegisters`, and flips the `eventCalendar` feature).\n *\n * Deriving from `SELF_SERVE_PLANS` is what stops the next tier from\n * reintroducing it: `free` has nothing to sell and `enterprise` is quoted\n * per deal (no `STRIPE_PRICE_ENTERPRISE_*` exists), so everything else is\n * by definition a paid, priced plan.\n */\nexport const PAID_PLANS: readonly OrgPlan[] = SELF_SERVE_PLANS.filter(\n (plan) => plan !== 'free',\n)\n\nfunction env(name: string): string | null {\n const value = process.env[name]\n return value ? value : null\n}\n\n/**\n * The Stripe price id for an add-on kind on a plan at a billing interval;\n * null when the plan doesn't sell it (free) or the env isn't configured.\n */\nexport function addonPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n const yearly = interval === 'year' ? '_YEARLY' : ''\n const flat = FLAT_ENV_NAME[kind]\n if (flat) return env(`STRIPE_PRICE_${flat}${yearly}`)\n const suffix = PER_PLAN_ENV_SUFFIX[kind]\n if (!suffix || plan === 'free') return null\n return env(`STRIPE_PRICE_${plan.toUpperCase()}_${suffix}${yearly}`)\n}\n\n/**\n * Reverse map: which add-on kind a subscription item's price id sells.\n * Null for non-add-on prices (the base plan item, unknown prices).\n */\nexport function addonKindFromPriceId(\n priceId: string | null | undefined,\n): AddonKind | null {\n if (!priceId) return null\n for (const kind of ADDON_KINDS) {\n for (const interval of ['month', 'year'] as const) {\n if (FLAT_ENV_NAME[kind]) {\n if (addonPriceId(kind, 'starter', interval) === priceId) return kind\n continue\n }\n for (const plan of PAID_PLANS) {\n if (addonPriceId(kind, plan, interval) === priceId) return kind\n }\n }\n }\n return null\n}\n\n/**\n * The BASE plan's Stripe price id at an interval\n * (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced\n * `enterprise`, and for an env that isn't configured. Read at call time, so\n * it never freezes a stale value at module load the way the routes'\n * `PRICE_ENV` maps do.\n */\nexport function planPriceId(\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n if (!PAID_PLANS.includes(plan)) return null\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_${plan.toUpperCase()}${yearly}`)\n}\n\n/**\n * Which plan a subscription item's price sells AND on which interval; null for\n * an add-on price, the metered price, an ad-hoc enterprise price, and anything\n * unknown.\n *\n * The interval half exists because a schedule phase read back from Stripe\n * carries price IDS and nothing else (AGL-2150): rebuilding that phase's item\n * list needs to know which interval it is priced on, and guessing it from the\n * live subscription is wrong exactly when the pending change is also an\n * interval change.\n */\nexport function planAndIntervalFromPriceId(\n priceId: string | null | undefined,\n): { plan: OrgPlan; interval: BillingInterval } | null {\n if (!priceId) return null\n for (const plan of PAID_PLANS) {\n for (const interval of ['month', 'year'] as const) {\n if (planPriceId(plan, interval) === priceId) return { plan, interval }\n }\n }\n return null\n}\n\n/**\n * Which plan a subscription item's price sells; null for an add-on price,\n * the metered price, an ad-hoc enterprise price, and anything unknown.\n */\nexport function planFromPriceId(\n priceId: string | null | undefined,\n): OrgPlan | null {\n return planAndIntervalFromPriceId(priceId)?.plan ?? null\n}\n\n/**\n * The shared metered-usage price (AGL-635) that makes reported usage\n * billable, for a given billing interval.\n *\n * Stripe rejects a subscription whose items mix `recurring.interval`, so the\n * metered item has to recur the same way the plan does. There are two prices\n * — `aglyn_metered_usage` (monthly) and `aglyn_metered_usage_yearly` — and\n * both bill $0.01 per aggregated unit against the SAME meter, because the\n * rollup posts an already-computed value in CENTS. The interval is therefore\n * the only thing that differs, and it is the only thing a caller must get\n * right.\n *\n * `interval` is REQUIRED on purpose (AGL-1280). It used to be monthly-only\n * with no argument, so the failure mode of forgetting it was attaching a\n * monthly price to a yearly subscription — the exact mixed-interval crash\n * this signature now makes unrepresentable. A default would hand that\n * footgun straight back.\n */\nexport function meteredPriceId(interval: 'month' | 'year'): string | null {\n return env(\n interval === 'year' ? 'STRIPE_PRICE_METERED_YEARLY' : 'STRIPE_PRICE_METERED',\n )\n}\n\n/**\n * Whether a price id is EITHER shared metered-usage price.\n *\n * Interval-agnostic by design: callers ask this to exclude the metered item\n * from plan/add-on reasoning, and an annual subscription's metered item must\n * be excluded just as thoroughly as a monthly one.\n */\nexport function isMeteredPriceId(priceId: string | null | undefined): boolean {\n if (!priceId) return false\n return (\n priceId === meteredPriceId('month') || priceId === meteredPriceId('year')\n )\n}\n\n/**\n * The subscription's BASE PLAN item, identified POSITIVELY (AGL-1340).\n *\n * This used to be \"whatever no add-on price claims\" — identification by\n * elimination, which quietly returns the wrong item the moment a\n * subscription carries anything the add-on map doesn't recognise: the\n * metered item, a grandfathered v1 price, a coupon-era SKU, an item added\n * by hand in the Stripe dashboard. Picking an add-on item as the plan item\n * means a plan switch re-prices the ADD-ON, and reads the billing interval\n * off it.\n *\n * So: match a known `STRIPE_PRICE_{PLAN}[_YEARLY]` first. Only when nothing\n * matches — an enterprise deal bills on an ad-hoc price, and grandfathered\n * subscriptions predate the current SKUs — fall back to the old rule,\n * minus the metered item, and finally to `items[0]` so behaviour for those\n * subscriptions is unchanged.\n */\nexport function findPlanItem<T extends { price?: { id?: string } | null }>(\n items: readonly T[] | null | undefined,\n): T | null {\n const list = items ?? []\n const byPlanPrice = list.find((item) => planFromPriceId(item?.price?.id))\n if (byPlanPrice) return byPlanPrice\n const notAnAddon = list.find(\n (item) =>\n !addonKindFromPriceId(item?.price?.id) &&\n !isMeteredPriceId(item?.price?.id),\n )\n return notAnAddon ?? list[0] ?? null\n}\n\n/**\n * Monthly USD per unit for an add-on on a plan (yearly prices are ×12 of\n * this); null when the plan doesn't sell the kind. Single pricing source\n * of truth: `PLAN_PRICING` + the two flat add-on constants.\n */\nexport function addonUnitUsd(kind: AddonKind, plan: OrgPlan): number | null {\n const pricing = PLAN_PRICING[plan]\n switch (kind) {\n case 'managers':\n return pricing.extraSeatMonthlyUsd\n case 'members':\n return pricing.extraCollaboratorMonthlyUsd\n case 'datasets':\n return pricing.extraDatasetMonthlyUsd\n case 'hosts':\n return pricing.extraHostMonthlyUsd\n case 'posRegisters':\n return POS_REGISTER_ADDON_MONTHLY_USD\n case 'eventCalendar':\n return EVENT_CALENDAR_ADDON_MONTHLY_USD\n case 'aiAddon':\n return pricing.aiAddonMonthlyUsd\n }\n}\n\n/**\n * Full add-on quantity map (explicit zeros for absent kinds) from a\n * subscription's items — the shape written to `org.seatAddons` so\n * removals and dashboard edits converge on sync (AGL-527).\n */\nexport function addonQuantitiesFromItems(\n items:\n | Array<{ price?: { id?: string } | null; quantity?: number | null }>\n | null\n | undefined,\n): Record<AddonKind, number> {\n const quantities = Object.fromEntries(\n ADDON_KINDS.map((kind) => [kind, 0]),\n ) as Record<AddonKind, number>\n for (const item of items ?? []) {\n const kind = addonKindFromPriceId(item?.price?.id)\n if (kind) {\n quantities[kind] += Math.max(0, Math.floor(Number(item?.quantity ?? 0)))\n }\n }\n return quantities\n}\n\n/**\n * Max purchasable quantity per kind, from a purchases-free entitlement\n * resolution (plan defaults + staff overrides only) so the ceiling does not\n * drift as the org buys: seat/dataset kinds stop at the plan's hard max,\n * hosts/registers use flat ceilings, the Event Calendar and Aglyn AI are 0/1\n * toggles. POS registers additionally require the `pos` feature.\n *\n * Lives here rather than inside `/api/billing/addons` because a PLAN CHANGE\n * needs the same ceiling for a different plan. The addons route asks \"how many\n * may this org buy on the plan it is on\"; `buildTargetItems` asks \"how many of\n * what it already bought can the plan it is moving to actually deliver\". Two\n * readers, one definition — a second copy is how they answer differently.\n */\nexport function addonMaxForBaseline(\n kind: AddonKind,\n baseline: ReturnType<typeof resolveOrgEntitlements>,\n): number {\n const bounded = (included: number, max: number) =>\n Number.isFinite(max) ? Math.max(0, max - included) : EXTRA_HOSTS_ADDON_MAX\n switch (kind) {\n case 'managers':\n return bounded(baseline.managersPerOrg, baseline.maxManagersPerOrg)\n case 'members':\n return bounded(baseline.membersPerHost, baseline.maxMembersPerHost)\n case 'datasets':\n return bounded(baseline.datasetsPerOrg, baseline.maxDatasetsPerOrg)\n case 'hosts':\n return baseline.hostLimit === UNLIMITED ? 0 : EXTRA_HOSTS_ADDON_MAX\n case 'posRegisters':\n return baseline.features.pos ? POS_REGISTERS_ADDON_MAX : 0\n case 'eventCalendar':\n return 1\n case 'aiAddon':\n // Org-wide like the Event Calendar: one purchase, and the price map\n // (null on Free and Enterprise) says whether the plan sells it at all.\n return 1\n }\n}\n\n/** The ceiling a PLAN would impose on an add-on kind, purchases excluded. */\nexport function addonMaxForPlan(kind: AddonKind, plan: OrgPlan): number {\n return addonMaxForBaseline(kind, resolveOrgEntitlements({ plan } as never))\n}\n"],"names":["EVENT_CALENDAR_ADDON_MONTHLY_USD","EXTRA_HOSTS_ADDON_MAX","PLAN_PRICING","POS_REGISTER_ADDON_MONTHLY_USD","POS_REGISTERS_ADDON_MAX","resolveOrgEntitlements","SELF_SERVE_PLANS","UNLIMITED","ADDON_KINDS","PER_PLAN_ENV_SUFFIX","managers","members","datasets","hosts","aiAddon","FLAT_ENV_NAME","posRegisters","eventCalendar","PAID_PLANS","filter","plan","env","name","value","process","addonPriceId","kind","interval","yearly","flat","suffix","toUpperCase","addonKindFromPriceId","priceId","planPriceId","includes","planAndIntervalFromPriceId","planFromPriceId","meteredPriceId","isMeteredPriceId","findPlanItem","items","notAnAddon","list","byPlanPrice","find","item","price","id","addonUnitUsd","pricing","extraSeatMonthlyUsd","extraCollaboratorMonthlyUsd","extraDatasetMonthlyUsd","extraHostMonthlyUsd","aiAddonMonthlyUsd","addonQuantitiesFromItems","quantities","Object","fromEntries","map","Math","max","floor","Number","quantity","addonMaxForBaseline","baseline","bounded","included","isFinite","managersPerOrg","maxManagersPerOrg","membersPerHost","maxMembersPerHost","datasetsPerOrg","maxDatasetsPerOrg","hostLimit","features","pos","addonMaxForPlan"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gCAAgC,EAChCC,qBAAqB,EACrBC,YAAY,EACZC,8BAA8B,EAC9BC,uBAAuB,EACvBC,sBAAsB,EACtBC,gBAAgB,EAChBC,SAAS,QAGJ,sBAAqB;AAe5B,OAAO,MAAMC,cAAoC;IAC/C;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA;AAID,yEAAyE,GACzE,MAAMC,sBAA0D;IAC9DC,UAAU;IACVC,SAAS;IACTC,UAAU;IACVC,OAAO;IACPC,SAAS;AACX;AAEA,2EAA2E,GAC3E,MAAMC,gBAAoD;IACxDC,cAAc;IACdC,eAAe;AACjB;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,MAAMC,aAAiCZ,iBAAiBa,MAAM,CACnE,CAACC,OAASA,SAAS,QACpB;AAED,SAASC,IAAIC,IAAY;IACvB,MAAMC,QAAQC,QAAQH,GAAG,CAACC,KAAK;IAC/B,OAAOC,QAAQA,QAAQ;AACzB;AAEA;;;CAGC,GACD,OAAO,SAASE,aACdC,IAAe,EACfN,IAAa,EACbO,QAAyB;IAEzB,MAAMC,SAASD,aAAa,SAAS,YAAY;IACjD,MAAME,OAAOd,aAAa,CAACW,KAAK;IAChC,IAAIG,MAAM,OAAOR,IAAI,CA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,GAAG,CAAC,CAAClC,OAAS;YAACA;YAAM;SAAE;IAErC,KAAK,MAAMoB,QAAQL,gBAAAA,QAAS,EAAE,CAAE;YACIK;QAAlC,MAAMpB,OAAOM,qBAAqBc,yBAAAA,cAAAA,KAAMC,KAAK,qBAAXD,YAAaE,EAAE;QACjD,IAAItB,MAAM;;YACR+B,UAAU,CAAC/B,KAAK,IAAImC,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACC,eAAOlB,wBAAAA,KAAMmB,QAAQ,mBAAI;QACtE;IACF;IACA,OAAOR;AACT;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,SAASS,oBACdxC,IAAe,EACfyC,QAAmD;IAEnD,MAAMC,UAAU,CAACC,UAAkBP,MACjCE,OAAOM,QAAQ,CAACR,OAAOD,KAAKC,GAAG,CAAC,GAAGA,MAAMO,YAAYpE;IACvD,OAAQyB;QACN,KAAK;YACH,OAAO0C,QAAQD,SAASI,cAAc,EAAEJ,SAASK,iBAAiB;QACpE,KAAK;YACH,OAAOJ,QAAQD,SAASM,cAAc,EAAEN,SAASO,iBAAiB;QACpE,KAAK;YACH,OAAON,QAAQD,SAASQ,cAAc,EAAER,SAASS,iBAAiB;QACpE,KAAK;YACH,OAAOT,SAASU,SAAS,KAAKtE,YAAY,IAAIN;QAChD,KAAK;YACH,OAAOkE,SAASW,QAAQ,CAACC,GAAG,GAAG3E,0BAA0B;QAC3D,KAAK;YACH,OAAO;QACT,KAAK;YACH,oEAAoE;YACpE,uEAAuE;YACvE,OAAO;IACX;AACF;AAEA,2EAA2E,GAC3E,OAAO,SAAS4E,gBAAgBtD,IAAe,EAAEN,IAAa;IAC5D,OAAO8C,oBAAoBxC,MAAMrB,uBAAuB;QAAEe;IAAK;AACjE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/billing-addons.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 SELF_SERVE_PLANS,\n type AiTierId,\n type OrgPlan,\n} from '@aglyn/aglyn/server'\nimport {\n ADDON_KINDS,\n addonMaxForBaseline,\n addonMaxForPlan,\n addonUnitUsd,\n type AddonKind,\n} from '@aglyn/aglyn/app-utils/bundle-intent'\n// The Aglyn AI tiers (AGL-3965) by their own module rather than the server\n// barrel: the webhook and every billing route read a subscription's AI item\n// through here, and the many route specs that stub `@aglyn/aglyn/server`\n// with a partial object would otherwise see every tier helper as undefined.\nimport {\n AI_TIER_IDS,\n defaultAiTierForPlan,\n LEGACY_AI_ADDON_TIER_BY_PLAN,\n planSellsAiTiers,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\n\n/*\n * The add-on kinds, their unit prices (the Aglyn AI tier's included) and\n * their ceilings live beside the bundle-link parser (AGL-3955), so the link,\n * the Billing card and this price map read one list. Re-exported here for\n * every server reader that already imports them from this module.\n */\nexport { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd, type AddonKind }\n\n/**\n * Self-serve add-on price map (AGL-525): the bridge between\n * `STRIPE_PRICE_*` env price ids, `org.seatAddons` keys, and\n * `PLAN_PRICING` USD amounts. Add-ons bill as extra items on the org's\n * one subscription, so every kind has a monthly and a yearly price\n * (Stripe allows a single interval per subscription; annual orgs attach\n * the `_YEARLY` variants). Seat/member/dataset/host prices are per-plan;\n * POS registers, the Event Calendar and Site Care (AGL-3954) are flat; the\n * Aglyn AI add-on is priced per TIER (AGL-3965, `STRIPE_PRICE_AI_{TIER}`),\n * on any paid plan. Prices are minted by `tools/scripts/setup-stripe.mjs` —\n * keep the three in sync.\n */\nexport type BillingInterval = 'month' | 'year'\n\n/** Kinds priced per plan (env `STRIPE_PRICE_{PLAN}_{SUFFIX}[_YEARLY]`). */\nconst PER_PLAN_ENV_SUFFIX: Partial<Record<AddonKind, string>> = {\n managers: 'EXTRA_SEAT',\n members: 'EXTRA_MEMBER',\n datasets: 'EXTRA_DATASET',\n hosts: 'EXTRA_HOST',\n}\n\n/** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */\nconst FLAT_ENV_NAME: Partial<Record<AddonKind, string>> = {\n posRegisters: 'POS_REGISTER',\n eventCalendar: 'EVENT_CALENDAR',\n siteCare: 'SITE_CARE',\n}\n\n/**\n * Every plan that is sold with a Stripe price — DERIVED, never hand-listed\n * (AGL-1340).\n *\n * The literal that used to sit here listed starter, pro, business and\n * advanced only — it predated the Scale and Agency tiers, so\n * `addonKindFromPriceId()` could not recognise a single Scale/Agency add-on\n * price coming back from Stripe. `addonPriceId()` still SOLD them (it only\n * uppercases the plan), so the money moved and the read-back returned\n * nothing: the webhook wrote `seatAddons: {all zeros}` for the\n * highest-paying orgs on the next subscription event, and `seatAddons` is an\n * ENTITLEMENT INPUT (`plan-entitlements.ts` — it raises `hostLimit` and\n * `posRegisters`, and flips the `eventCalendar` feature).\n *\n * Deriving from `SELF_SERVE_PLANS` is what stops the next tier from\n * reintroducing it: `free` has nothing to sell and `enterprise` is quoted\n * per deal (no `STRIPE_PRICE_ENTERPRISE_*` exists), so everything else is\n * by definition a paid, priced plan.\n */\nexport const PAID_PLANS: readonly OrgPlan[] = SELF_SERVE_PLANS.filter(\n (plan) => plan !== 'free',\n)\n\nfunction env(name: string): string | null {\n const value = process.env[name]\n return value ? value : null\n}\n\n/**\n * The Stripe price id of an Aglyn AI tier (AGL-3965):\n * `STRIPE_PRICE_AI_{TIER}[_YEARLY]`, lookup key `aglyn_ai_{tier}[_yearly]`.\n * The same price on every plan; null when the env isn't configured.\n */\nexport function aiTierPriceId(\n tier: AiTierId,\n interval: BillingInterval,\n): string | null {\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_AI_${tier.toUpperCase()}${yearly}`)\n}\n\n/**\n * The per-plan AI add-on price sold before tiers existed\n * (`STRIPE_PRICE_{PLAN}_AI_ADDON[_YEARLY]`, AGL-2897). Never sold again; read\n * only so an item still carrying one is recognised as the add-on and as the\n * tier with its price and band until `migrate-ai-addon-tiers.mjs` moves it.\n */\nexport function legacyAiAddonPriceId(\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n if (!PAID_PLANS.includes(plan)) return null\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_${plan.toUpperCase()}_AI_ADDON${yearly}`)\n}\n\n/**\n * Which Aglyn AI tier a price id sells (AGL-3965): a tier price, or a legacy\n * per-plan add-on price read as the tier with the same price and band\n * (`LEGACY_AI_ADDON_TIER_BY_PLAN`). Null for anything else.\n */\nexport function aiTierFromPriceId(\n priceId: string | null | undefined,\n): AiTierId | null {\n if (!priceId) return null\n for (const interval of ['month', 'year'] as const) {\n for (const tier of AI_TIER_IDS) {\n if (aiTierPriceId(tier, interval) === priceId) return tier\n }\n for (const plan of PAID_PLANS) {\n if (legacyAiAddonPriceId(plan, interval) === priceId) {\n return LEGACY_AI_ADDON_TIER_BY_PLAN[plan] ?? null\n }\n }\n }\n return null\n}\n\n/**\n * The tier a subscription's items carry (AGL-3965), or null when none is an\n * Aglyn AI item with a quantity. Written to `org.aiTier` beside the\n * `seatAddons` map `addonQuantitiesFromItems` derives from the same items.\n */\nexport function aiTierFromItems(\n items:\n | ReadonlyArray<{ price?: { id?: string } | null; quantity?: number | null }>\n | null\n | undefined,\n): AiTierId | null {\n for (const item of items ?? []) {\n const tier = aiTierFromPriceId(item?.price?.id)\n if (tier && Number(item?.quantity ?? 1) >= 1) return tier\n }\n return null\n}\n\n/**\n * The Stripe price id for an add-on kind on a plan at a billing interval;\n * null when the plan doesn't sell it (free) or the env isn't configured.\n *\n * `tier` picks the Aglyn AI tier; absent, the tier a plan-named purchase\n * means (`defaultAiTierForPlan`). Ignored for every other kind.\n */\nexport function addonPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n tier?: AiTierId | null,\n): string | null {\n const name = addonPriceEnvName(kind, plan, interval, tier)\n return name ? env(name) : null\n}\n\n/**\n * The env var that holds an add-on's price id on a plan at an interval, or\n * null where the plan sells no such price. Named on its own so a checkout\n * that Stripe refuses can say which variable points at a missing price.\n * For the Aglyn AI add-on it is the tier's (`STRIPE_PRICE_AI_{TIER}`,\n * AGL-3965), `tier` read as `addonPriceId` reads it.\n */\nexport function addonPriceEnvName(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n tier?: AiTierId | null,\n): string | null {\n const yearly = interval === 'year' ? '_YEARLY' : ''\n if (kind === 'aiAddon') {\n if (!planSellsAiTiers(plan)) return null\n const chosen = tier ?? defaultAiTierForPlan(plan)\n return chosen ? `STRIPE_PRICE_AI_${chosen.toUpperCase()}${yearly}` : null\n }\n const flat = FLAT_ENV_NAME[kind]\n if (flat) return `STRIPE_PRICE_${flat}${yearly}`\n const suffix = PER_PLAN_ENV_SUFFIX[kind]\n if (!suffix || plan === 'free') return null\n return `STRIPE_PRICE_${plan.toUpperCase()}_${suffix}${yearly}`\n}\n\n/**\n * Reverse map: which add-on kind a subscription item's price id sells.\n * Null for non-add-on prices (the base plan item, unknown prices).\n */\nexport function addonKindFromPriceId(\n priceId: string | null | undefined,\n): AddonKind | null {\n if (!priceId) return null\n if (aiTierFromPriceId(priceId)) return 'aiAddon'\n for (const kind of ADDON_KINDS) {\n if (kind === 'aiAddon') continue\n for (const interval of ['month', 'year'] as const) {\n if (FLAT_ENV_NAME[kind]) {\n if (addonPriceId(kind, 'starter', interval) === priceId) return kind\n continue\n }\n for (const plan of PAID_PLANS) {\n if (addonPriceId(kind, plan, interval) === priceId) return kind\n }\n }\n }\n return null\n}\n\n/**\n * The price an add-on item moves to on a target plan/interval: the kind's\n * price there, and for the Aglyn AI add-on the SAME tier the item carries\n * now (AGL-3965) — a tier is chosen on its own, so a plan change re-prices\n * only its interval, and a legacy per-plan item becomes the tier with its\n * price and band.\n */\nexport function addonTargetPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n currentPriceId: string | null | undefined,\n): string | null {\n const tier = kind === 'aiAddon' ? aiTierFromPriceId(currentPriceId) : null\n return addonPriceId(kind, plan, interval, tier)\n}\n\n/**\n * The BASE plan's Stripe price id at an interval\n * (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced\n * `enterprise`, and for an env that isn't configured. Read at call time, so\n * it never freezes a stale value at module load the way the routes'\n * `PRICE_ENV` maps do.\n */\nexport function planPriceId(\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n if (!PAID_PLANS.includes(plan)) return null\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_${plan.toUpperCase()}${yearly}`)\n}\n\n/**\n * Which plan a subscription item's price sells AND on which interval; null for\n * an add-on price, the metered price, an ad-hoc enterprise price, and anything\n * unknown.\n *\n * The interval half exists because a schedule phase read back from Stripe\n * carries price IDS and nothing else (AGL-2150): rebuilding that phase's item\n * list needs to know which interval it is priced on, and guessing it from the\n * live subscription is wrong exactly when the pending change is also an\n * interval change.\n */\nexport function planAndIntervalFromPriceId(\n priceId: string | null | undefined,\n): { plan: OrgPlan; interval: BillingInterval } | null {\n if (!priceId) return null\n for (const plan of PAID_PLANS) {\n for (const interval of ['month', 'year'] as const) {\n if (planPriceId(plan, interval) === priceId) return { plan, interval }\n }\n }\n return null\n}\n\n/**\n * Which plan a subscription item's price sells; null for an add-on price,\n * the metered price, an ad-hoc enterprise price, and anything unknown.\n */\nexport function planFromPriceId(\n priceId: string | null | undefined,\n): OrgPlan | null {\n return planAndIntervalFromPriceId(priceId)?.plan ?? null\n}\n\n/**\n * The shared metered-usage price (AGL-635) that makes reported usage\n * billable, for a given billing interval.\n *\n * Stripe rejects a subscription whose items mix `recurring.interval`, so the\n * metered item has to recur the same way the plan does. There are two prices\n * — `aglyn_metered_usage` (monthly) and `aglyn_metered_usage_yearly` — and\n * both bill $0.01 per aggregated unit against the SAME meter, because the\n * rollup posts an already-computed value in CENTS. The interval is therefore\n * the only thing that differs, and it is the only thing a caller must get\n * right.\n *\n * `interval` is REQUIRED on purpose (AGL-1280). It used to be monthly-only\n * with no argument, so the failure mode of forgetting it was attaching a\n * monthly price to a yearly subscription — the exact mixed-interval crash\n * this signature now makes unrepresentable. A default would hand that\n * footgun straight back.\n */\nexport function meteredPriceId(interval: 'month' | 'year'): string | null {\n return env(\n interval === 'year' ? 'STRIPE_PRICE_METERED_YEARLY' : 'STRIPE_PRICE_METERED',\n )\n}\n\n/**\n * Whether a price id is EITHER shared metered-usage price.\n *\n * Interval-agnostic by design: callers ask this to exclude the metered item\n * from plan/add-on reasoning, and an annual subscription's metered item must\n * be excluded just as thoroughly as a monthly one.\n */\nexport function isMeteredPriceId(priceId: string | null | undefined): boolean {\n if (!priceId) return false\n return (\n priceId === meteredPriceId('month') || priceId === meteredPriceId('year')\n )\n}\n\n/**\n * The subscription's BASE PLAN item, identified POSITIVELY (AGL-1340).\n *\n * This used to be \"whatever no add-on price claims\" — identification by\n * elimination, which quietly returns the wrong item the moment a\n * subscription carries anything the add-on map doesn't recognise: the\n * metered item, a grandfathered v1 price, a coupon-era SKU, an item added\n * by hand in the Stripe dashboard. Picking an add-on item as the plan item\n * means a plan switch re-prices the ADD-ON, and reads the billing interval\n * off it.\n *\n * So: match a known `STRIPE_PRICE_{PLAN}[_YEARLY]` first. Only when nothing\n * matches — an enterprise deal bills on an ad-hoc price, and grandfathered\n * subscriptions predate the current SKUs — fall back to the old rule,\n * minus the metered item, and finally to `items[0]` so behaviour for those\n * subscriptions is unchanged.\n */\nexport function findPlanItem<T extends { price?: { id?: string } | null }>(\n items: readonly T[] | null | undefined,\n): T | null {\n const list = items ?? []\n const byPlanPrice = list.find((item) => planFromPriceId(item?.price?.id))\n if (byPlanPrice) return byPlanPrice\n const notAnAddon = list.find(\n (item) =>\n !addonKindFromPriceId(item?.price?.id) &&\n !isMeteredPriceId(item?.price?.id),\n )\n return notAnAddon ?? list[0] ?? null\n}\n\n/**\n * Full add-on quantity map (explicit zeros for absent kinds) from a\n * subscription's items — the shape written to `org.seatAddons` so\n * removals and dashboard edits converge on sync (AGL-527).\n */\nexport function addonQuantitiesFromItems(\n items:\n | Array<{ price?: { id?: string } | null; quantity?: number | null }>\n | null\n | undefined,\n): Record<AddonKind, number> {\n const quantities = Object.fromEntries(\n ADDON_KINDS.map((kind) => [kind, 0]),\n ) as Record<AddonKind, number>\n for (const item of items ?? []) {\n const kind = addonKindFromPriceId(item?.price?.id)\n if (kind) {\n quantities[kind] += Math.max(0, Math.floor(Number(item?.quantity ?? 0)))\n }\n }\n return quantities\n}\n"],"names":["SELF_SERVE_PLANS","ADDON_KINDS","addonMaxForBaseline","addonMaxForPlan","addonUnitUsd","AI_TIER_IDS","defaultAiTierForPlan","LEGACY_AI_ADDON_TIER_BY_PLAN","planSellsAiTiers","PER_PLAN_ENV_SUFFIX","managers","members","datasets","hosts","FLAT_ENV_NAME","posRegisters","eventCalendar","siteCare","PAID_PLANS","filter","plan","env","name","value","process","aiTierPriceId","tier","interval","yearly","toUpperCase","legacyAiAddonPriceId","includes","aiTierFromPriceId","priceId","aiTierFromItems","items","item","price","id","Number","quantity","addonPriceId","kind","addonPriceEnvName","chosen","flat","suffix","addonKindFromPriceId","addonTargetPriceId","currentPriceId","planPriceId","planAndIntervalFromPriceId","planFromPriceId","meteredPriceId","isMeteredPriceId","findPlanItem","notAnAddon","list","byPlanPrice","find","addonQuantitiesFromItems","quantities","Object","fromEntries","map","Math","max","floor"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QAGX,sBAAqB;AAC5B,SACEC,WAAW,EACXC,mBAAmB,EACnBC,eAAe,EACfC,YAAY,QAE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,CAAC,GAAGD,KAAKE,KAAK,CAAC5B,eAAOH,wBAAAA,KAAMI,QAAQ,mBAAI;QACtE;IACF;IACA,OAAOqB;AACT"}
|
|
@@ -0,0 +1,166 @@
|
|
|
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
|
+
/**
|
|
18
|
+
* A STAFF-MINTED BUNDLE CHECKOUT LINK (AGL-3955).
|
|
19
|
+
*
|
|
20
|
+
* At a booth or on a doorstep, a staff member who built the owner's site
|
|
21
|
+
* shows a QR; the owner scans it on their own phone and lands on Billing with
|
|
22
|
+
* the plan, the add-ons, the cadence and the coupon already chosen, one tap
|
|
23
|
+
* from paid. The link itself is an ordinary Billing URL — the query the
|
|
24
|
+
* marketing CTAs and the upgrade proposal already speak — so it works without
|
|
25
|
+
* any record at all.
|
|
26
|
+
*
|
|
27
|
+
* The RECORD is for two things the URL cannot carry honestly:
|
|
28
|
+
*
|
|
29
|
+
* - the chosen domain and its price, which the Billing page shows as a line
|
|
30
|
+
* of its own and the owner then buys on the site's Custom Domain page. Read
|
|
31
|
+
* from the record, never from the URL, so an edited link cannot show a name
|
|
32
|
+
* or a price nobody quoted.
|
|
33
|
+
* - the staff accountability that lets the link stand in for the domains
|
|
34
|
+
* plugin's 72-hour paid-invoice gate, once (Zach, 2026-10-19). A staff
|
|
35
|
+
* member met the owner and is named on the `billing.bundle-link-minted`
|
|
36
|
+
* audit row; the link is for one workspace, lives 24 hours and is spent by
|
|
37
|
+
* the first purchase it pre-clears. The plugin asks through
|
|
38
|
+
* `core.purchase-gate-preclearance` and never reads this collection.
|
|
39
|
+
*
|
|
40
|
+
* Documents live in the top-level `bundleLinks` collection, keyed by an
|
|
41
|
+
* unguessable id and carrying the workspace. Only the Admin SDK reads or
|
|
42
|
+
* writes them; the rules deny every client, staff included.
|
|
43
|
+
*/
|
|
44
|
+
import type { AiTierId, OrgPlan } from '@aglyn/aglyn/server';
|
|
45
|
+
import { type AddonKind, type BundleAddons } from '@aglyn/aglyn/app-utils/bundle-intent';
|
|
46
|
+
import type { PurchaseGatePreclearance } from '@aglyn/aglyn/plugin-manager/purchase-gate-preclearance';
|
|
47
|
+
export declare const BUNDLE_LINKS_COLLECTION = "bundleLinks";
|
|
48
|
+
/** How long a link pre-clears, from its minting. */
|
|
49
|
+
export declare const BUNDLE_LINK_TTL_MS: number;
|
|
50
|
+
/** The query param that names the record, on a link that carries a domain. */
|
|
51
|
+
export declare const BUNDLE_LINK_PARAM = "bundle";
|
|
52
|
+
/** The audit action every mint writes, with the staff member's uid. */
|
|
53
|
+
export declare const BUNDLE_LINK_AUDIT_ACTION = "billing.bundle-link-minted";
|
|
54
|
+
/** Whether this deployment sells domains: the registrar the domains plugin buys through. */
|
|
55
|
+
export declare function domainsRegistrarConfigured(): boolean;
|
|
56
|
+
export interface BundleLinkDomain {
|
|
57
|
+
/** The registrable name, lower-cased. */
|
|
58
|
+
name: string;
|
|
59
|
+
/** The registrar's first-year price when the link was minted, in cents. */
|
|
60
|
+
firstYearCents: number;
|
|
61
|
+
/** The yearly renewal price, in cents. */
|
|
62
|
+
renewalCents: number;
|
|
63
|
+
/** The site the name is for: where the owner lands to buy it. */
|
|
64
|
+
hostId: string;
|
|
65
|
+
}
|
|
66
|
+
export interface BundleLinkDoc {
|
|
67
|
+
/** The staff member accountable for the link. */
|
|
68
|
+
mintedBy: string;
|
|
69
|
+
mintedByEmail: string | null;
|
|
70
|
+
/** The one workspace the link is for. */
|
|
71
|
+
workspaceId: string;
|
|
72
|
+
createdAt: number;
|
|
73
|
+
expiresAt: number;
|
|
74
|
+
/** When a purchase spent the link's preclearance; null until then. */
|
|
75
|
+
usedAt: number | null;
|
|
76
|
+
/** Which gate the purchase that spent it waived. */
|
|
77
|
+
usedFor?: string;
|
|
78
|
+
/** A staff-minted link stands in for the domains plugin's invoice-age gate, once. */
|
|
79
|
+
preclearsDomainGate: true;
|
|
80
|
+
intent: {
|
|
81
|
+
plan: OrgPlan;
|
|
82
|
+
addons?: BundleAddons;
|
|
83
|
+
interval?: 'month' | 'year';
|
|
84
|
+
coupon?: string;
|
|
85
|
+
/** The Aglyn AI tier an `ai:<tier>` entry named (AGL-3965). */
|
|
86
|
+
aiTier?: AiTierId;
|
|
87
|
+
};
|
|
88
|
+
domain?: BundleLinkDomain;
|
|
89
|
+
}
|
|
90
|
+
/** A mint refused before anything was written. */
|
|
91
|
+
export declare class BundleLinkError extends Error {
|
|
92
|
+
readonly status: number;
|
|
93
|
+
constructor(message: string, status?: number);
|
|
94
|
+
}
|
|
95
|
+
export interface MintBundleLinkOptions {
|
|
96
|
+
orgId: string;
|
|
97
|
+
/** The staff member minting it. */
|
|
98
|
+
actor: {
|
|
99
|
+
uid: string;
|
|
100
|
+
email?: string | null;
|
|
101
|
+
};
|
|
102
|
+
/** The console origin the link is built on. */
|
|
103
|
+
origin: string;
|
|
104
|
+
plan: unknown;
|
|
105
|
+
addons?: unknown;
|
|
106
|
+
interval?: unknown;
|
|
107
|
+
coupon?: unknown;
|
|
108
|
+
/** The chosen domain, quoted from the registrar's search; optional. */
|
|
109
|
+
domain?: {
|
|
110
|
+
name?: unknown;
|
|
111
|
+
firstYearCents?: unknown;
|
|
112
|
+
renewalCents?: unknown;
|
|
113
|
+
hostId?: unknown;
|
|
114
|
+
} | null;
|
|
115
|
+
/** Clock seam. */
|
|
116
|
+
now?: number;
|
|
117
|
+
}
|
|
118
|
+
export interface MintedBundleLink {
|
|
119
|
+
id: string;
|
|
120
|
+
url: string;
|
|
121
|
+
expiresAt: number;
|
|
122
|
+
intent: BundleLinkDoc['intent'];
|
|
123
|
+
domain: BundleLinkDomain | null;
|
|
124
|
+
/** Add-ons asked for that the plan does not sell, left off the link. */
|
|
125
|
+
droppedAddons: Array<AddonKind | string>;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Mint a link for one workspace: validate the bundle the way the proposal
|
|
129
|
+
* does, write the record and its audit row in one batch, and answer the URL.
|
|
130
|
+
*
|
|
131
|
+
* Refused for a plan the workspace cannot buy itself, for a workspace with a
|
|
132
|
+
* live subscription (checkout would refuse it; plan changes are Billing's),
|
|
133
|
+
* and for a domain on a deployment that does not sell domains, for a site
|
|
134
|
+
* outside the workspace, or without a price.
|
|
135
|
+
*/
|
|
136
|
+
export declare function mintBundleLink(options: MintBundleLinkOptions): Promise<MintedBundleLink>;
|
|
137
|
+
/** Whether a stored link still pre-clears: unused, unexpired, and flagged. */
|
|
138
|
+
export declare function bundleLinkIsLive(doc: Partial<BundleLinkDoc> | undefined, now: number): boolean;
|
|
139
|
+
/**
|
|
140
|
+
* The bundle links' answer to `core.purchase-gate-preclearance`.
|
|
141
|
+
*
|
|
142
|
+
* `check` reads only. `consume` marks the link used in a transaction that
|
|
143
|
+
* writes only when nothing has, so two purchases racing on one link spend it
|
|
144
|
+
* once: the second reads `usedAt` set and answers false.
|
|
145
|
+
*/
|
|
146
|
+
export declare function bundleLinkPreclearance(options?: {
|
|
147
|
+
now?: () => number;
|
|
148
|
+
}): PurchaseGatePreclearance;
|
|
149
|
+
export interface BundleLinkDomainLine {
|
|
150
|
+
name: string;
|
|
151
|
+
firstYearCents: number;
|
|
152
|
+
renewalCents: number;
|
|
153
|
+
/** The site's Custom Domain page segment: its subdomain, else its id. */
|
|
154
|
+
host: string;
|
|
155
|
+
hostId: string;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* The domain line Billing shows for a link (AGL-3955), or why there is none:
|
|
159
|
+
* the link is for another workspace, is spent or expired, names no domain,
|
|
160
|
+
* or this deployment does not sell domains (`available: false`, so the page
|
|
161
|
+
* can show the line disabled with the reason rather than hide it).
|
|
162
|
+
*/
|
|
163
|
+
export declare function readBundleLinkDomain(orgId: string, linkId: string, now?: number): Promise<{
|
|
164
|
+
domain: BundleLinkDomainLine | null;
|
|
165
|
+
available: boolean;
|
|
166
|
+
}>;
|
|
@@ -0,0 +1,286 @@
|
|
|
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
|
+
* A STAFF-MINTED BUNDLE CHECKOUT LINK (AGL-3955).
|
|
18
|
+
*
|
|
19
|
+
* At a booth or on a doorstep, a staff member who built the owner's site
|
|
20
|
+
* shows a QR; the owner scans it on their own phone and lands on Billing with
|
|
21
|
+
* the plan, the add-ons, the cadence and the coupon already chosen, one tap
|
|
22
|
+
* from paid. The link itself is an ordinary Billing URL — the query the
|
|
23
|
+
* marketing CTAs and the upgrade proposal already speak — so it works without
|
|
24
|
+
* any record at all.
|
|
25
|
+
*
|
|
26
|
+
* The RECORD is for two things the URL cannot carry honestly:
|
|
27
|
+
*
|
|
28
|
+
* - the chosen domain and its price, which the Billing page shows as a line
|
|
29
|
+
* of its own and the owner then buys on the site's Custom Domain page. Read
|
|
30
|
+
* from the record, never from the URL, so an edited link cannot show a name
|
|
31
|
+
* or a price nobody quoted.
|
|
32
|
+
* - the staff accountability that lets the link stand in for the domains
|
|
33
|
+
* plugin's 72-hour paid-invoice gate, once (Zach, 2026-10-19). A staff
|
|
34
|
+
* member met the owner and is named on the `billing.bundle-link-minted`
|
|
35
|
+
* audit row; the link is for one workspace, lives 24 hours and is spent by
|
|
36
|
+
* the first purchase it pre-clears. The plugin asks through
|
|
37
|
+
* `core.purchase-gate-preclearance` and never reads this collection.
|
|
38
|
+
*
|
|
39
|
+
* Documents live in the top-level `bundleLinks` collection, keyed by an
|
|
40
|
+
* unguessable id and carrying the workspace. Only the Admin SDK reads or
|
|
41
|
+
* writes them; the rules deny every client, staff included.
|
|
42
|
+
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
43
|
+
import { fitBundleAddonsToPlan, normalizeBundleDomain, parseBundleAddons } from "@aglyn/aglyn/app-utils/bundle-intent";
|
|
44
|
+
import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
|
|
45
|
+
import { onboardingDestination } from "@aglyn/aglyn/app-utils/onboarding-deep-link";
|
|
46
|
+
import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, upgradeProposalIntent } from "@aglyn/aglyn/app-utils/upgrade-proposal";
|
|
47
|
+
import { isLiveSubscriptionStatus, ORG_BILLING_DOC_ID, ORG_BILLING_SUBCOLLECTION } from "@aglyn/aglyn/app-utils/org-billing-doc";
|
|
48
|
+
import { FieldValue } from "firebase-admin/firestore";
|
|
49
|
+
import { setAdminAudit } from "./admin-audit-write.js";
|
|
50
|
+
import firebaseAdmin from "./firebase-admin.js";
|
|
51
|
+
export const BUNDLE_LINKS_COLLECTION = 'bundleLinks';
|
|
52
|
+
/** How long a link pre-clears, from its minting. */ export const BUNDLE_LINK_TTL_MS = 24 * 60 * 60 * 1000;
|
|
53
|
+
/** The query param that names the record, on a link that carries a domain. */ export const BUNDLE_LINK_PARAM = 'bundle';
|
|
54
|
+
/** The audit action every mint writes, with the staff member's uid. */ export const BUNDLE_LINK_AUDIT_ACTION = 'billing.bundle-link-minted';
|
|
55
|
+
/** The most a quoted domain may cost a year, in cents, before it reads as a typo. */ const DOMAIN_PRICE_MAX_CENTS = 100000;
|
|
56
|
+
/** Whether this deployment sells domains: the registrar the domains plugin buys through. */ export function domainsRegistrarConfigured() {
|
|
57
|
+
var _process_env_DOMAINS_REGISTRAR;
|
|
58
|
+
return Boolean(String((_process_env_DOMAINS_REGISTRAR = process.env['DOMAINS_REGISTRAR']) != null ? _process_env_DOMAINS_REGISTRAR : '').trim());
|
|
59
|
+
}
|
|
60
|
+
/** A mint refused before anything was written. */ export class BundleLinkError extends Error {
|
|
61
|
+
constructor(message, status = 400){
|
|
62
|
+
super(message);
|
|
63
|
+
this.name = 'BundleLinkError';
|
|
64
|
+
this.status = status;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const firestore = ()=>firebaseAdmin.app().firestore();
|
|
68
|
+
function cents(value) {
|
|
69
|
+
const number = Math.round(Number(value));
|
|
70
|
+
return Number.isFinite(number) && number > 0 && number <= DOMAIN_PRICE_MAX_CENTS ? number : null;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Mint a link for one workspace: validate the bundle the way the proposal
|
|
74
|
+
* does, write the record and its audit row in one batch, and answer the URL.
|
|
75
|
+
*
|
|
76
|
+
* Refused for a plan the workspace cannot buy itself, for a workspace with a
|
|
77
|
+
* live subscription (checkout would refuse it; plan changes are Billing's),
|
|
78
|
+
* and for a domain on a deployment that does not sell domains, for a site
|
|
79
|
+
* outside the workspace, or without a price.
|
|
80
|
+
*/ export async function mintBundleLink(options) {
|
|
81
|
+
var _options_now, _ref, _actor_email;
|
|
82
|
+
var _billingSnapshot_get;
|
|
83
|
+
const { orgId, actor, origin } = options;
|
|
84
|
+
const now = (_options_now = options.now) != null ? _options_now : Date.now();
|
|
85
|
+
if (!orgId) throw new BundleLinkError('Missing orgId');
|
|
86
|
+
if (!isUpgradeProposalPlan(options.plan)) {
|
|
87
|
+
throw new BundleLinkError('Choose a paid plan the workspace can buy itself');
|
|
88
|
+
}
|
|
89
|
+
const plan = options.plan;
|
|
90
|
+
const parsed = parseBundleAddons(options.addons);
|
|
91
|
+
const fitted = fitBundleAddonsToPlan(parsed.addons, plan);
|
|
92
|
+
const bundle = normalizeUpgradeProposalBundle(plan, {
|
|
93
|
+
addons: fitted.addons,
|
|
94
|
+
interval: options.interval,
|
|
95
|
+
coupon: options.coupon,
|
|
96
|
+
// The tier an `ai:<tier>` entry named (AGL-3965), kept with the AI add-on.
|
|
97
|
+
aiTier: parsed.aiTier
|
|
98
|
+
});
|
|
99
|
+
const intent = _extends({
|
|
100
|
+
plan
|
|
101
|
+
}, bundle);
|
|
102
|
+
const db = firestore();
|
|
103
|
+
const orgRef = db.collection('orgs').doc(orgId);
|
|
104
|
+
const [orgSnapshot, billingSnapshot] = await Promise.all([
|
|
105
|
+
orgRef.get(),
|
|
106
|
+
orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID).get()
|
|
107
|
+
]);
|
|
108
|
+
if (!orgSnapshot.exists) throw new BundleLinkError('Unknown organization', 404);
|
|
109
|
+
const slug = orgSnapshot.get('slug');
|
|
110
|
+
if (typeof slug !== 'string' || !slug) {
|
|
111
|
+
throw new BundleLinkError('This workspace has no address yet, so no link can point at it', 409);
|
|
112
|
+
}
|
|
113
|
+
const status = (_ref = (_billingSnapshot_get = billingSnapshot.get('subscription')) == null ? void 0 : _billingSnapshot_get.status) != null ? _ref : orgSnapshot.get('billingStatus');
|
|
114
|
+
if (isLiveSubscriptionStatus(status)) {
|
|
115
|
+
throw new BundleLinkError('This workspace already has a live subscription; change its plan from Billing instead', 409);
|
|
116
|
+
}
|
|
117
|
+
let domain = null;
|
|
118
|
+
if (options.domain && options.domain.name) {
|
|
119
|
+
var _options_domain_hostId;
|
|
120
|
+
if (!domainsRegistrarConfigured()) {
|
|
121
|
+
throw new BundleLinkError('Buying a domain is not available on this deployment yet', 409);
|
|
122
|
+
}
|
|
123
|
+
const name = normalizeBundleDomain(options.domain.name);
|
|
124
|
+
if (!name) throw new BundleLinkError('That is not a domain name');
|
|
125
|
+
const firstYearCents = cents(options.domain.firstYearCents);
|
|
126
|
+
const renewalCents = cents(options.domain.renewalCents);
|
|
127
|
+
if (firstYearCents === null || renewalCents === null) {
|
|
128
|
+
throw new BundleLinkError('Quote the domain’s first-year and renewal prices from its search');
|
|
129
|
+
}
|
|
130
|
+
const hostId = String((_options_domain_hostId = options.domain.hostId) != null ? _options_domain_hostId : '').trim();
|
|
131
|
+
const host = hostId ? await db.collection('hosts').doc(hostId).get() : null;
|
|
132
|
+
if (!(host == null ? void 0 : host.exists) || host.get('orgId') !== orgId) {
|
|
133
|
+
throw new BundleLinkError('Choose the site in this workspace the domain is for');
|
|
134
|
+
}
|
|
135
|
+
domain = {
|
|
136
|
+
name,
|
|
137
|
+
firstYearCents,
|
|
138
|
+
renewalCents,
|
|
139
|
+
hostId
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(createResourceUid());
|
|
143
|
+
const doc = _extends({
|
|
144
|
+
mintedBy: actor.uid,
|
|
145
|
+
mintedByEmail: (_actor_email = actor.email) != null ? _actor_email : null,
|
|
146
|
+
workspaceId: orgId,
|
|
147
|
+
createdAt: now,
|
|
148
|
+
expiresAt: now + BUNDLE_LINK_TTL_MS,
|
|
149
|
+
usedAt: null,
|
|
150
|
+
preclearsDomainGate: true,
|
|
151
|
+
intent
|
|
152
|
+
}, domain ? {
|
|
153
|
+
domain
|
|
154
|
+
} : {});
|
|
155
|
+
const batch = db.batch();
|
|
156
|
+
batch.set(ref, doc);
|
|
157
|
+
setAdminAudit(batch, db, _extends({
|
|
158
|
+
actorUid: actor.uid
|
|
159
|
+
}, actor.email ? {
|
|
160
|
+
actorEmail: actor.email
|
|
161
|
+
} : {}, {
|
|
162
|
+
action: BUNDLE_LINK_AUDIT_ACTION,
|
|
163
|
+
target: `orgs/${orgId}`,
|
|
164
|
+
after: {
|
|
165
|
+
bundleLinkId: ref.id,
|
|
166
|
+
intent,
|
|
167
|
+
domain,
|
|
168
|
+
expiresAt: doc.expiresAt,
|
|
169
|
+
preclearsDomainGate: true
|
|
170
|
+
},
|
|
171
|
+
at: FieldValue.serverTimestamp()
|
|
172
|
+
}));
|
|
173
|
+
await batch.commit();
|
|
174
|
+
const path = onboardingDestination(slug, upgradeProposalIntent(intent));
|
|
175
|
+
const url = `${origin}${path}${domain ? `&${BUNDLE_LINK_PARAM}=${ref.id}` : ''}`;
|
|
176
|
+
return {
|
|
177
|
+
id: ref.id,
|
|
178
|
+
url,
|
|
179
|
+
expiresAt: doc.expiresAt,
|
|
180
|
+
intent,
|
|
181
|
+
domain,
|
|
182
|
+
droppedAddons: [
|
|
183
|
+
...parsed.dropped,
|
|
184
|
+
...fitted.notSold
|
|
185
|
+
]
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
/** Whether a stored link still pre-clears: unused, unexpired, and flagged. */ export function bundleLinkIsLive(doc, now) {
|
|
189
|
+
return !!doc && doc.preclearsDomainGate === true && (doc.usedAt === null || doc.usedAt === undefined) && typeof doc.expiresAt === 'number' && doc.expiresAt > now;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* The workspace's live link, or null. Read by the workspace alone (a
|
|
193
|
+
* single-field equality, no composite index) and narrowed here: a workspace
|
|
194
|
+
* holds a handful of links at most, each gone in a day.
|
|
195
|
+
*/ async function liveLinkFor(orgId, now) {
|
|
196
|
+
const snapshot = await firestore().collection(BUNDLE_LINKS_COLLECTION).where('workspaceId', '==', orgId).limit(50).get();
|
|
197
|
+
const live = snapshot.docs.filter((doc)=>bundleLinkIsLive(doc.data(), now)).sort((a, b)=>{
|
|
198
|
+
var _b_get, _a_get;
|
|
199
|
+
return Number((_b_get = b.get('createdAt')) != null ? _b_get : 0) - Number((_a_get = a.get('createdAt')) != null ? _a_get : 0);
|
|
200
|
+
});
|
|
201
|
+
return live[0] ? {
|
|
202
|
+
id: live[0].id
|
|
203
|
+
} : null;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* The bundle links' answer to `core.purchase-gate-preclearance`.
|
|
207
|
+
*
|
|
208
|
+
* `check` reads only. `consume` marks the link used in a transaction that
|
|
209
|
+
* writes only when nothing has, so two purchases racing on one link spend it
|
|
210
|
+
* once: the second reads `usedAt` set and answers false.
|
|
211
|
+
*/ export function bundleLinkPreclearance(options = {}) {
|
|
212
|
+
var _options_now;
|
|
213
|
+
const clock = (_options_now = options.now) != null ? _options_now : ()=>Date.now();
|
|
214
|
+
return {
|
|
215
|
+
async check (input) {
|
|
216
|
+
var _ref;
|
|
217
|
+
const orgId = String((_ref = input == null ? void 0 : input.orgId) != null ? _ref : '').trim();
|
|
218
|
+
if (!orgId || (input == null ? void 0 : input.gate) !== 'domain-payment-history') return null;
|
|
219
|
+
const live = await liveLinkFor(orgId, clock());
|
|
220
|
+
return live ? {
|
|
221
|
+
preclearanceId: live.id
|
|
222
|
+
} : null;
|
|
223
|
+
},
|
|
224
|
+
async consume (preclearanceId) {
|
|
225
|
+
const id = String(preclearanceId != null ? preclearanceId : '').trim();
|
|
226
|
+
if (!id || id.includes('/')) return false;
|
|
227
|
+
const db = firestore();
|
|
228
|
+
const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(id);
|
|
229
|
+
return db.runTransaction(async (tx)=>{
|
|
230
|
+
const snapshot = await tx.get(ref);
|
|
231
|
+
if (!snapshot.exists) return false;
|
|
232
|
+
const now = clock();
|
|
233
|
+
if (!bundleLinkIsLive(snapshot.data(), now)) return false;
|
|
234
|
+
tx.update(ref, {
|
|
235
|
+
usedAt: now,
|
|
236
|
+
usedFor: 'domain-payment-history'
|
|
237
|
+
});
|
|
238
|
+
return true;
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* The domain line Billing shows for a link (AGL-3955), or why there is none:
|
|
245
|
+
* the link is for another workspace, is spent or expired, names no domain,
|
|
246
|
+
* or this deployment does not sell domains (`available: false`, so the page
|
|
247
|
+
* can show the line disabled with the reason rather than hide it).
|
|
248
|
+
*/ export async function readBundleLinkDomain(orgId, linkId, now = Date.now()) {
|
|
249
|
+
var _host_get;
|
|
250
|
+
const available = domainsRegistrarConfigured();
|
|
251
|
+
const id = String(linkId != null ? linkId : '').trim();
|
|
252
|
+
if (!orgId || !id || id.includes('/')) return {
|
|
253
|
+
domain: null,
|
|
254
|
+
available
|
|
255
|
+
};
|
|
256
|
+
const db = firestore();
|
|
257
|
+
const snapshot = await db.collection(BUNDLE_LINKS_COLLECTION).doc(id).get();
|
|
258
|
+
const doc = snapshot.data();
|
|
259
|
+
if (!snapshot.exists || (doc == null ? void 0 : doc.workspaceId) !== orgId || !(doc == null ? void 0 : doc.domain)) {
|
|
260
|
+
return {
|
|
261
|
+
domain: null,
|
|
262
|
+
available
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
if (!bundleLinkIsLive(doc, now)) return {
|
|
266
|
+
domain: null,
|
|
267
|
+
available
|
|
268
|
+
};
|
|
269
|
+
const host = await db.collection('hosts').doc(doc.domain.hostId).get();
|
|
270
|
+
if (!host.exists || host.get('orgId') !== orgId) return {
|
|
271
|
+
domain: null,
|
|
272
|
+
available
|
|
273
|
+
};
|
|
274
|
+
return {
|
|
275
|
+
available,
|
|
276
|
+
domain: {
|
|
277
|
+
name: doc.domain.name,
|
|
278
|
+
firstYearCents: doc.domain.firstYearCents,
|
|
279
|
+
renewalCents: doc.domain.renewalCents,
|
|
280
|
+
hostId: doc.domain.hostId,
|
|
281
|
+
host: String((_host_get = host.get('subdomain')) != null ? _host_get : doc.domain.hostId)
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
//# sourceMappingURL=bundle-links.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/bundle-links.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\n/**\n * A STAFF-MINTED BUNDLE CHECKOUT LINK (AGL-3955).\n *\n * At a booth or on a doorstep, a staff member who built the owner's site\n * shows a QR; the owner scans it on their own phone and lands on Billing with\n * the plan, the add-ons, the cadence and the coupon already chosen, one tap\n * from paid. The link itself is an ordinary Billing URL — the query the\n * marketing CTAs and the upgrade proposal already speak — so it works without\n * any record at all.\n *\n * The RECORD is for two things the URL cannot carry honestly:\n *\n * - the chosen domain and its price, which the Billing page shows as a line\n * of its own and the owner then buys on the site's Custom Domain page. Read\n * from the record, never from the URL, so an edited link cannot show a name\n * or a price nobody quoted.\n * - the staff accountability that lets the link stand in for the domains\n * plugin's 72-hour paid-invoice gate, once (Zach, 2026-10-19). A staff\n * member met the owner and is named on the `billing.bundle-link-minted`\n * audit row; the link is for one workspace, lives 24 hours and is spent by\n * the first purchase it pre-clears. The plugin asks through\n * `core.purchase-gate-preclearance` and never reads this collection.\n *\n * Documents live in the top-level `bundleLinks` collection, keyed by an\n * unguessable id and carrying the workspace. Only the Admin SDK reads or\n * writes them; the rules deny every client, staff included.\n */\n\nimport type { AiTierId, OrgPlan } from '@aglyn/aglyn/server'\nimport {\n fitBundleAddonsToPlan,\n normalizeBundleDomain,\n parseBundleAddons,\n type AddonKind,\n type BundleAddons,\n} from '@aglyn/aglyn/app-utils/bundle-intent'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { onboardingDestination } from '@aglyn/aglyn/app-utils/onboarding-deep-link'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n upgradeProposalIntent,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport type {\n PurchaseGatePreclearance,\n PurchaseGatePreclearanceInput,\n} from '@aglyn/aglyn/plugin-manager/purchase-gate-preclearance'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport firebaseAdmin from './firebase-admin'\n\nexport const BUNDLE_LINKS_COLLECTION = 'bundleLinks'\n\n/** How long a link pre-clears, from its minting. */\nexport const BUNDLE_LINK_TTL_MS = 24 * 60 * 60 * 1000\n\n/** The query param that names the record, on a link that carries a domain. */\nexport const BUNDLE_LINK_PARAM = 'bundle'\n\n/** The audit action every mint writes, with the staff member's uid. */\nexport const BUNDLE_LINK_AUDIT_ACTION = 'billing.bundle-link-minted'\n\n/** The most a quoted domain may cost a year, in cents, before it reads as a typo. */\nconst DOMAIN_PRICE_MAX_CENTS = 100_000\n\n/** Whether this deployment sells domains: the registrar the domains plugin buys through. */\nexport function domainsRegistrarConfigured(): boolean {\n return Boolean(String(process.env['DOMAINS_REGISTRAR'] ?? '').trim())\n}\n\nexport interface BundleLinkDomain {\n /** The registrable name, lower-cased. */\n name: string\n /** The registrar's first-year price when the link was minted, in cents. */\n firstYearCents: number\n /** The yearly renewal price, in cents. */\n renewalCents: number\n /** The site the name is for: where the owner lands to buy it. */\n hostId: string\n}\n\nexport interface BundleLinkDoc {\n /** The staff member accountable for the link. */\n mintedBy: string\n mintedByEmail: string | null\n /** The one workspace the link is for. */\n workspaceId: string\n createdAt: number\n expiresAt: number\n /** When a purchase spent the link's preclearance; null until then. */\n usedAt: number | null\n /** Which gate the purchase that spent it waived. */\n usedFor?: string\n /** A staff-minted link stands in for the domains plugin's invoice-age gate, once. */\n preclearsDomainGate: true\n intent: {\n plan: OrgPlan\n addons?: BundleAddons\n interval?: 'month' | 'year'\n coupon?: string\n /** The Aglyn AI tier an `ai:<tier>` entry named (AGL-3965). */\n aiTier?: AiTierId\n }\n domain?: BundleLinkDomain\n}\n\n/** A mint refused before anything was written. */\nexport class BundleLinkError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'BundleLinkError'\n this.status = status\n }\n}\n\nexport interface MintBundleLinkOptions {\n orgId: string\n /** The staff member minting it. */\n actor: { uid: string; email?: string | null }\n /** The console origin the link is built on. */\n origin: string\n plan: unknown\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /** The chosen domain, quoted from the registrar's search; optional. */\n domain?: {\n name?: unknown\n firstYearCents?: unknown\n renewalCents?: unknown\n hostId?: unknown\n } | null\n /** Clock seam. */\n now?: number\n}\n\nexport interface MintedBundleLink {\n id: string\n url: string\n expiresAt: number\n intent: BundleLinkDoc['intent']\n domain: BundleLinkDomain | null\n /** Add-ons asked for that the plan does not sell, left off the link. */\n droppedAddons: Array<AddonKind | string>\n}\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nfunction cents(value: unknown): number | null {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 && number <= DOMAIN_PRICE_MAX_CENTS ? number : null\n}\n\n/**\n * Mint a link for one workspace: validate the bundle the way the proposal\n * does, write the record and its audit row in one batch, and answer the URL.\n *\n * Refused for a plan the workspace cannot buy itself, for a workspace with a\n * live subscription (checkout would refuse it; plan changes are Billing's),\n * and for a domain on a deployment that does not sell domains, for a site\n * outside the workspace, or without a price.\n */\nexport async function mintBundleLink(options: MintBundleLinkOptions): Promise<MintedBundleLink> {\n const { orgId, actor, origin } = options\n const now = options.now ?? Date.now()\n if (!orgId) throw new BundleLinkError('Missing orgId')\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new BundleLinkError('Choose a paid plan the workspace can buy itself')\n }\n const plan: OrgPlan = options.plan\n const parsed = parseBundleAddons(options.addons)\n const fitted = fitBundleAddonsToPlan(parsed.addons, plan)\n const bundle = normalizeUpgradeProposalBundle(plan, {\n addons: fitted.addons,\n interval: options.interval,\n coupon: options.coupon,\n // The tier an `ai:<tier>` entry named (AGL-3965), kept with the AI add-on.\n aiTier: parsed.aiTier,\n })\n const intent: BundleLinkDoc['intent'] = { plan, ...bundle }\n\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const [orgSnapshot, billingSnapshot] = await Promise.all([\n orgRef.get(),\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID).get(),\n ])\n if (!orgSnapshot.exists) throw new BundleLinkError('Unknown organization', 404)\n const slug = orgSnapshot.get('slug')\n if (typeof slug !== 'string' || !slug) {\n throw new BundleLinkError('This workspace has no address yet, so no link can point at it', 409)\n }\n const status =\n (billingSnapshot.get('subscription') as { status?: unknown } | undefined)?.status ??\n orgSnapshot.get('billingStatus')\n if (isLiveSubscriptionStatus(status)) {\n throw new BundleLinkError(\n 'This workspace already has a live subscription; change its plan from Billing instead',\n 409,\n )\n }\n\n let domain: BundleLinkDomain | null = null\n if (options.domain && options.domain.name) {\n if (!domainsRegistrarConfigured()) {\n throw new BundleLinkError('Buying a domain is not available on this deployment yet', 409)\n }\n const name = normalizeBundleDomain(options.domain.name)\n if (!name) throw new BundleLinkError('That is not a domain name')\n const firstYearCents = cents(options.domain.firstYearCents)\n const renewalCents = cents(options.domain.renewalCents)\n if (firstYearCents === null || renewalCents === null) {\n throw new BundleLinkError('Quote the domain’s first-year and renewal prices from its search')\n }\n const hostId = String(options.domain.hostId ?? '').trim()\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n if (!host?.exists || host.get('orgId') !== orgId) {\n throw new BundleLinkError('Choose the site in this workspace the domain is for')\n }\n domain = { name, firstYearCents, renewalCents, hostId }\n }\n\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(createResourceUid())\n const doc: BundleLinkDoc = {\n mintedBy: actor.uid,\n mintedByEmail: actor.email ?? null,\n workspaceId: orgId,\n createdAt: now,\n expiresAt: now + BUNDLE_LINK_TTL_MS,\n usedAt: null,\n preclearsDomainGate: true,\n intent,\n ...(domain ? { domain } : {}),\n }\n const batch = db.batch()\n batch.set(ref, doc)\n setAdminAudit(batch, db, {\n actorUid: actor.uid,\n ...(actor.email ? { actorEmail: actor.email } : {}),\n action: BUNDLE_LINK_AUDIT_ACTION,\n target: `orgs/${orgId}`,\n after: {\n bundleLinkId: ref.id,\n intent,\n domain,\n expiresAt: doc.expiresAt,\n preclearsDomainGate: true,\n },\n at: FieldValue.serverTimestamp(),\n })\n await batch.commit()\n\n const path = onboardingDestination(slug, upgradeProposalIntent(intent))\n const url = `${origin}${path}${domain ? `&${BUNDLE_LINK_PARAM}=${ref.id}` : ''}`\n return {\n id: ref.id,\n url,\n expiresAt: doc.expiresAt,\n intent,\n domain,\n droppedAddons: [...parsed.dropped, ...fitted.notSold],\n }\n}\n\n/** Whether a stored link still pre-clears: unused, unexpired, and flagged. */\nexport function bundleLinkIsLive(doc: Partial<BundleLinkDoc> | undefined, now: number): boolean {\n return (\n !!doc &&\n doc.preclearsDomainGate === true &&\n (doc.usedAt === null || doc.usedAt === undefined) &&\n typeof doc.expiresAt === 'number' &&\n doc.expiresAt > now\n )\n}\n\n/**\n * The workspace's live link, or null. Read by the workspace alone (a\n * single-field equality, no composite index) and narrowed here: a workspace\n * holds a handful of links at most, each gone in a day.\n */\nasync function liveLinkFor(orgId: string, now: number): Promise<{ id: string } | null> {\n const snapshot = await firestore()\n .collection(BUNDLE_LINKS_COLLECTION)\n .where('workspaceId', '==', orgId)\n .limit(50)\n .get()\n const live = snapshot.docs\n .filter((doc) => bundleLinkIsLive(doc.data() as Partial<BundleLinkDoc>, now))\n .sort((a, b) => Number(b.get('createdAt') ?? 0) - Number(a.get('createdAt') ?? 0))\n return live[0] ? { id: live[0].id } : null\n}\n\n/**\n * The bundle links' answer to `core.purchase-gate-preclearance`.\n *\n * `check` reads only. `consume` marks the link used in a transaction that\n * writes only when nothing has, so two purchases racing on one link spend it\n * once: the second reads `usedAt` set and answers false.\n */\nexport function bundleLinkPreclearance(options: { now?: () => number } = {}): PurchaseGatePreclearance {\n const clock = options.now ?? (() => Date.now())\n return {\n async check(input: PurchaseGatePreclearanceInput) {\n const orgId = String(input?.orgId ?? '').trim()\n if (!orgId || input?.gate !== 'domain-payment-history') return null\n const live = await liveLinkFor(orgId, clock())\n return live ? { preclearanceId: live.id } : null\n },\n async consume(preclearanceId: string) {\n const id = String(preclearanceId ?? '').trim()\n if (!id || id.includes('/')) return false\n const db = firestore()\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(id)\n return db.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const now = clock()\n if (!bundleLinkIsLive(snapshot.data() as Partial<BundleLinkDoc>, now)) return false\n tx.update(ref, { usedAt: now, usedFor: 'domain-payment-history' })\n return true\n })\n },\n }\n}\n\nexport interface BundleLinkDomainLine {\n name: string\n firstYearCents: number\n renewalCents: number\n /** The site's Custom Domain page segment: its subdomain, else its id. */\n host: string\n hostId: string\n}\n\n/**\n * The domain line Billing shows for a link (AGL-3955), or why there is none:\n * the link is for another workspace, is spent or expired, names no domain,\n * or this deployment does not sell domains (`available: false`, so the page\n * can show the line disabled with the reason rather than hide it).\n */\nexport async function readBundleLinkDomain(\n orgId: string,\n linkId: string,\n now: number = Date.now(),\n): Promise<{ domain: BundleLinkDomainLine | null; available: boolean }> {\n const available = domainsRegistrarConfigured()\n const id = String(linkId ?? '').trim()\n if (!orgId || !id || id.includes('/')) return { domain: null, available }\n const db = firestore()\n const snapshot = await db.collection(BUNDLE_LINKS_COLLECTION).doc(id).get()\n const doc = snapshot.data() as Partial<BundleLinkDoc> | undefined\n if (!snapshot.exists || doc?.workspaceId !== orgId || !doc?.domain) {\n return { domain: null, available }\n }\n if (!bundleLinkIsLive(doc, now)) return { domain: null, available }\n const host = await db.collection('hosts').doc(doc.domain.hostId).get()\n if (!host.exists || host.get('orgId') !== orgId) return { domain: null, available }\n return {\n available,\n domain: {\n name: doc.domain.name,\n firstYearCents: doc.domain.firstYearCents,\n renewalCents: doc.domain.renewalCents,\n hostId: doc.domain.hostId,\n host: String(host.get('subdomain') ?? doc.domain.hostId),\n },\n }\n}\n"],"names":["fitBundleAddonsToPlan","normalizeBundleDomain","parseBundleAddons","createResourceUid","onboardingDestination","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","upgradeProposalIntent","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","FieldValue","setAdminAudit","firebaseAdmin","BUNDLE_LINKS_COLLECTION","BUNDLE_LINK_TTL_MS","BUNDLE_LINK_PARAM","BUNDLE_LINK_AUDIT_ACTION","DOMAIN_PRICE_MAX_CENTS","domainsRegistrarConfigured","process","Boolean","String","env","trim","BundleLinkError","Error","message","status","name","firestore","app","cents","value","number","Math","round","Number","isFinite","mintBundleLink","options","actor","billingSnapshot","orgId","origin","now","Date","plan","parsed","addons","fitted","bundle","interval","coupon","aiTier","intent","db","orgRef","collection","doc","orgSnapshot","Promise","all","get","exists","slug","domain","firstYearCents","renewalCents","hostId","host","ref","mintedBy","uid","mintedByEmail","email","workspaceId","createdAt","expiresAt","usedAt","preclearsDomainGate","batch","set","actorUid","actorEmail","action","target","after","bundleLinkId","id","at","serverTimestamp","commit","path","url","droppedAddons","dropped","notSold","bundleLinkIsLive","undefined","liveLinkFor","snapshot","where","limit","live","docs","filter","data","sort","a","b","bundleLinkPreclearance","clock","check","input","gate","preclearanceId","consume","includes","runTransaction","tx","update","usedFor","readBundleLinkDomain","linkId","available"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC;AAGD,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