@aglyn/aglyn 1.7.0 → 1.9.0
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 +11 -11
- package/src/lib/app-utils/ai-credit-blocks.d.ts +124 -0
- package/src/lib/app-utils/ai-credit-blocks.js +122 -0
- package/src/lib/app-utils/ai-credit-blocks.js.map +1 -0
- package/src/lib/app-utils/bundle-intent.d.ts +17 -51
- package/src/lib/app-utils/bundle-intent.js +30 -74
- package/src/lib/app-utils/bundle-intent.js.map +1 -1
- package/src/lib/app-utils/contacts.d.ts +4 -1
- package/src/lib/app-utils/contacts.js.map +1 -1
- package/src/lib/app-utils/docs-help-sections.generated.js +3 -3
- package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
- package/src/lib/app-utils/docs-help.generated.d.ts +1 -1
- package/src/lib/app-utils/docs-help.generated.js +1 -1
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/docs-index.generated.js +97 -97
- package/src/lib/app-utils/docs-index.generated.js.map +1 -1
- package/src/lib/app-utils/error-beacon.d.ts +25 -1
- package/src/lib/app-utils/error-beacon.js +55 -4
- package/src/lib/app-utils/error-beacon.js.map +1 -1
- package/src/lib/app-utils/foreign-script.d.ts +1 -1
- package/src/lib/app-utils/foreign-script.js +1 -1
- package/src/lib/app-utils/foreign-script.js.map +1 -1
- package/src/lib/app-utils/margin-utilization.js +6 -5
- package/src/lib/app-utils/margin-utilization.js.map +1 -1
- package/src/lib/app-utils/onboarding-deep-link.d.ts +10 -11
- package/src/lib/app-utils/onboarding-deep-link.js +37 -32
- package/src/lib/app-utils/onboarding-deep-link.js.map +1 -1
- package/src/lib/app-utils/operator-alerts.js +17 -0
- package/src/lib/app-utils/operator-alerts.js.map +1 -1
- package/src/lib/app-utils/plan-entitlements.d.ts +142 -150
- package/src/lib/app-utils/plan-entitlements.js +202 -201
- package/src/lib/app-utils/plan-entitlements.js.map +1 -1
- package/src/lib/app-utils/release-flags.d.ts +6 -4
- package/src/lib/app-utils/release-flags.js +8 -9
- package/src/lib/app-utils/release-flags.js.map +1 -1
- package/src/lib/app-utils/server.d.ts +1 -0
- package/src/lib/app-utils/server.js +3 -0
- package/src/lib/app-utils/server.js.map +1 -1
- package/src/lib/app-utils/site-interactions.d.ts +1 -1
- package/src/lib/app-utils/site-interactions.js +2 -2
- package/src/lib/app-utils/site-interactions.js.map +1 -1
- package/src/lib/app-utils/transactional-email-ceiling.d.ts +119 -0
- package/src/lib/app-utils/transactional-email-ceiling.js +134 -0
- package/src/lib/app-utils/transactional-email-ceiling.js.map +1 -0
- package/src/lib/app-utils/upgrade-proposal.d.ts +17 -7
- package/src/lib/app-utils/upgrade-proposal.js +20 -13
- package/src/lib/app-utils/upgrade-proposal.js.map +1 -1
- package/src/lib/foundation/definitions/org-billing.types.d.ts +4 -29
- package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
- package/src/lib/foundation/definitions/organization.types.d.ts +1 -3
- package/src/lib/foundation/definitions/organization.types.js.map +1 -1
- package/src/lib/foundation/index.d.ts +1 -1
- package/src/lib/foundation/index.js.map +1 -1
- package/src/lib/plugin-manager/first-party-plugins.generated.d.ts +0 -6
- package/src/lib/plugin-manager/first-party-plugins.generated.js +9 -55
- package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
- package/src/lib/plugin-manager/plugin-usage-axes.d.ts +14 -0
- package/src/lib/plugin-manager/plugin-usage-axes.js.map +1 -1
- package/src/lib/plugin-manager/video-embed-provider.d.ts +29 -0
- package/src/lib/plugin-manager/video-embed-provider.js +26 -7
- package/src/lib/plugin-manager/video-embed-provider.js.map +1 -1
- package/src/lib/plugin-manager/video-embed-providers.generated.d.ts +11 -0
- package/src/lib/plugin-manager/video-embed-providers.generated.js +161 -0
- package/src/lib/plugin-manager/video-embed-providers.generated.js.map +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/margin-utilization.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// Imported from BOTH graphs — the staff page (client) and the App Route that\n// serves it — so it may import neither entry barrel, for the reason\n// `usage-metering.ts` states at its own head. The specific modules underneath\n// are safe in both.\nimport type { AglynOrgBilling, OrgPlan } from '../foundation'\nimport {\n AI_TIERS,\n INFRA_COGS_PER_SITE_USD,\n MARGIN_SCOPE_NOTE,\n netMarginRating,\n orgListPriceMonthlyUsd,\n orgMonthlyCogsUsd,\n resolveAiTier,\n orgMonthlyRevenueUsd,\n orgNetMonthlyRevenueUsd,\n orgSiteCount,\n pageViewsFromBandwidthGb,\n resolveOrgEntitlements,\n resolveEffectivePlan,\n type DiscountMarginRating,\n type OrgCogsResult,\n type OrgUsageRollupInput,\n} from './plan-entitlements'\nimport { planQuotaOf } from '../plugin-manager/plugin-plan-entitlements'\nimport {\n declaredMeterReading,\n pluginUsageBands,\n type ResolvedPluginUsageBand,\n} from '../plugin-manager/plugin-usage-axes'\n\nexport { MARGIN_SCOPE_NOTE }\n\n/**\n * WHAT SHARE OF THE BANDS THEY BOUGHT DO CUSTOMERS ACTUALLY SPEND?\n *\n * `tier-margin-floor.spec.ts` proves what every tier costs at 100% of every\n * band, and pins the margin at 3 / 25 / 50 / 100%. Which of those four columns\n * the business is actually operating in has never been measured — and the\n * spread between them is the whole question, because on Pro the same price\n * list yields 89.3% at the 3% column and 7.1% at the 100% one.\n *\n * Everything needed to answer it was already recorded and already priced. The\n * monthly rollup carries the meters, `ORG_COGS_UNIT_RATES_USD` carries their\n * unit costs, and `orgMonthlyCogsUsd` already turns one into the other. What\n * did not exist was the DIVISION: usage over the band the plan sold, per org\n * and across the fleet.\n *\n * This module is that division, and nothing else. It runs no query, holds no\n * rate of its own and re-derives no cost — every dollar here comes back out of\n * `orgMonthlyCogsUsd`, so a surface built on it cannot come to disagree with\n * the discount guardrail about what an org costs.\n *\n * ## The three answers a band can give, and why two of them are not numbers\n *\n * A percentage needs a denominator, and two of the bands in `PLAN_ENTITLEMENTS`\n * do not supply one:\n *\n * * `UNLIMITED` — `Number.POSITIVE_INFINITY`. Enterprise carries it on\n * contacts, API requests and dataset storage. `used / Infinity` is 0, which\n * would render the platform's largest customers as its lightest users; and\n * a model that clamps to 100% instead would render them as its heaviest.\n * Both are inventions. The band is UNCAPPED, the fraction is `null`, and no\n * aggregate may average it in either direction.\n * * `0` — Free carries it on email sends, API requests and dataset storage.\n * `0 / 0` is `NaN` and `n / 0` is `Infinity`. Neither is a utilization. The\n * band admits nothing, so there is no allowance to be a fraction of, and an\n * org that spent the meter anyway did so with no included band behind it —\n * which is a cost signal in its own right, reported as\n * `usageWithNoAllowance` rather than folded into a percentile.\n *\n * The two are kept DISTINCT from each other and from `0%`. An uncapped band\n * and an exhausted one are opposite facts, and the recurring defect in this\n * repo's cost work is exactly that an absent figure reads as a zero one.\n *\n * ## What the bands are\n *\n * `meteredIncludedAllowance` sizes three of them and is the shape followed\n * here: the two PER-HOST bands are expanded by `hostLimit`, the rest are\n * org-wide as stored. `contactsPerHost` is org-wide DESPITE ITS NAME —\n * `checkContactQuota` compares it against an org-wide headcount, and\n * `tier-margin-floor.spec.ts` costs it unexpanded. Following either of those\n * and not the name is what keeps this table agreeing with both.\n */\n\n/**\n * The platform's own bands, at the positions the plugins' declared bands\n * interleave with (`order`, a multiple of 10 here) — every meter\n * `orgMonthlyCogsUsd` prices that is the platform's, plus `hosts`.\n */\nconst CORE_BANDS: ReadonlyArray<{ id: string; label: string; order: number }> = [\n { id: 'hosts', label: 'Sites', order: 10 },\n { id: 'storageGb', label: 'Media storage', order: 20 },\n { id: 'pageViews', label: 'Bandwidth (page views)', order: 30 },\n { id: 'dataStorageMb', label: 'Dataset storage', order: 50 },\n { id: 'apiRequests', label: 'API requests', order: 60 },\n { id: 'emailSends', label: 'Email sends', order: 80 },\n]\n\n/**\n * Every band the table reads, in column order: the platform's, and each one a\n * plugin declares beside the meter it contributes (`plugin-usage-axes.ts`) —\n * the AI plugin's credits, the CRM's records, the forms plugin's\n * submissions, the workflows plugin's runs.\n *\n * A plugin band sold in a unit OF cost is measured in that unit rather than\n * in the dollars the rollup stores: the AI plugin's credits are the dollars\n * over its declared unit cost, rounded up, which is the one conversion the\n * customer's own meter uses. It is also the band most worth watching —\n * provider spend is the only line item on the platform whose unit cost is\n * real money paid to a third party, and the only one that can clear the\n * $2/site floor on its own.\n */\nconst BANDS: ReadonlyArray<{\n id: string\n label: string\n order: number\n declared?: ResolvedPluginUsageBand\n}> = [\n ...CORE_BANDS,\n ...pluginUsageBands().map((declared) => ({\n id: declared.id,\n label: declared.label,\n order: declared.order,\n declared,\n })),\n].sort((a, b) => a.order - b.order)\n\n/** Every band, keyed by what it measures, in column order. */\nexport const UTILIZATION_BANDS: readonly string[] = BANDS.map((band) => band.id)\n\nexport type UtilizationBand = string\n\n/** Column headings, so the page and the aggregate name a band identically. */\nexport const UTILIZATION_BAND_LABELS: Readonly<Record<UtilizationBand, string>> =\n Object.fromEntries(BANDS.map((band) => [band.id, band.label]))\n\n/**\n * Why a band has no percentage, or that it has one.\n *\n * `uncapped` and `noAllowance` are the two non-numbers described at the head\n * of this module. They are separate values rather than one `null` because the\n * remedies are opposite: an uncapped band is a pricing exposure, an exhausted\n * one is an upgrade conversation.\n */\nexport type BandState = 'measured' | 'uncapped' | 'noAllowance'\n\nexport interface BandUtilization {\n band: UtilizationBand\n /** The org-wide included allowance. `Infinity` when uncapped, 0 when none. */\n included: number\n /** What the rollup recorded. Always a finite, non-negative number. */\n used: number\n state: BandState\n /**\n * Share of the band consumed, as a fraction of 1.\n *\n * `null` for every state but `measured`, and callers must render it as\n * neither 0 nor 1. It is NOT clamped: an org past its included band reads\n * above 1, which is the number worth seeing.\n */\n fraction: number | null\n}\n\n/** One org's realised position: what it consumed, what it cost, what it paid. */\nexport interface OrgMarginRow {\n orgId: string\n name: string | null\n plan: OrgPlan\n /** The rollup month these figures describe, or null when none has run. */\n month: string | null\n bands: Record<UtilizationBand, BandUtilization>\n /**\n * The shared cost model's answer — the same function and the same fields\n * `/api/admin/org-discount` underwrites against.\n */\n cogs: OrgCogsResult\n /** Pre-discount sticker price. */\n listPriceUsd: number\n /** List price net of any per-org discount. */\n mrrUsd: number\n /** MRR net of Stripe's processing fee — the base the margin is taken on. */\n netRevenueUsd: number\n /**\n * The AI add-on's share of `listPriceUsd` (AGL-2930) — already INSIDE\n * `listPriceUsd`, `mrrUsd` and `netRevenueUsd`, because\n * `orgListPriceMonthlyUsd` folds every purchased add-on. Named here so the\n * surface can show that the assist band's cost has revenue against it\n * rather than reading as pure margin drag; adding it again would count it\n * twice. 0 on a custom-priced deal, whose quote already folds the add-on\n * into one negotiated figure.\n */\n aiAddonRevenueUsd: number\n /**\n * `(net revenue − COGS) / net revenue`, the same arithmetic\n * `checkDiscountMargin` rates a discount on. See `MARGIN_SCOPE_NOTE`: it is\n * a contribution margin, not a profit.\n *\n * `null` when the org bills nothing. A free or comped org has no revenue to\n * take a fraction of, and reporting it as 0% or −100% would put a customer\n * who was never meant to be profitable at the top of a list whose whole\n * purpose is finding the one who was.\n */\n marginPct: number | null\n rating: DiscountMarginRating | null\n}\n\n/**\n * A rollup as this surface reads it: every field `orgMonthlyCogsUsd` prices.\n *\n * The two run counters used to be the surface's own extension of that shape\n * — recorded and banded but unpriced. Since 2026-09-07 the cost model prices\n * them at `perRun`, so the shape is the model's and nothing here is extra.\n */\nexport type UtilizationRollup = OrgUsageRollupInput\n\nconst finite = (value: unknown): number => {\n const parsed = Number(value ?? 0)\n return Number.isFinite(parsed) && parsed > 0 ? parsed : 0\n}\n\n/**\n * The org-wide included band for every metered axis, on this org's plan and\n * with this org's overrides and add-ons applied.\n *\n * `resolveOrgEntitlements` rather than `PLAN_ENTITLEMENTS[plan]`: a staff\n * entitlement override and a purchased host add-on both change what the\n * customer actually bought, and measuring consumption against the catalogue\n * row instead of the resolved one is the same class of error as measuring it\n * against a constant.\n */\nexport function orgIncludedBands(\n org: Partial<AglynOrgBilling> | null | undefined,\n): Record<UtilizationBand, number> {\n const entitlements = resolveOrgEntitlements(org)\n const hostLimit = Math.max(1, entitlements.hostLimit)\n const included: Record<UtilizationBand, number> = {\n hosts: entitlements.hostLimit,\n // Per host, expanded by the host limit — `meteredIncludedAllowance`\n // expands the per-host bands and nothing else.\n storageGb: (hostLimit * entitlements.storagePerHostMb) / 1024,\n // Bandwidth IS the page-view band, expressed in the unit customers buy.\n pageViews: pageViewsFromBandwidthGb(entitlements.bandwidthGb),\n // Org-wide, in the unit the rollup stores. `dataStorageMbPerOrg` is\n // megabytes and so is `dataStorageMb`; the GB conversion happens inside\n // `orgMonthlyCogsUsd` and must not happen twice.\n dataStorageMb: entitlements.dataStorageMbPerOrg,\n apiRequests: entitlements.apiRequestsPerMonth,\n emailSends: entitlements.emailSendsPerMonth,\n }\n // A plugin's band reads the entitlement its declaration names — absent is\n // nothing included — expanded by the host limit where it is per site.\n for (const band of pluginUsageBands()) {\n const figure = planQuotaOf(entitlements, band.entitlement)\n included[band.id] = band.perHost ? hostLimit * figure : figure\n }\n return included\n}\n\n/** One band's reading. The whole of the `UNLIMITED` and zero-band rule. */\nexport function bandUtilization(\n band: UtilizationBand,\n used: number,\n included: number,\n): BandUtilization {\n const usedSafe = Number.isFinite(used) && used > 0 ? used : 0\n if (!Number.isFinite(included)) {\n return { band, included: Number.POSITIVE_INFINITY, used: usedSafe, state: 'uncapped', fraction: null }\n }\n if (!(included > 0)) {\n return { band, included: 0, used: usedSafe, state: 'noAllowance', fraction: null }\n }\n return { band, included, used: usedSafe, state: 'measured', fraction: usedSafe / included }\n}\n\n/**\n * What the rollup recorded, per band.\n *\n * `hosts` comes from the ORG rather than the rollup: `orgSiteCount` is what\n * the cost floor is charged on and what `checkDiscountMargin` counts, and a\n * site added since the cron last ran is a site the org has. The rollup's own\n * `hostCount` is a snapshot of the same thing at cron time.\n */\nfunction bandUsage(\n org: Partial<AglynOrgBilling> | null | undefined,\n rollup: UtilizationRollup | null | undefined,\n): Record<UtilizationBand, number> {\n const used: Record<UtilizationBand, number> = {\n hosts: orgSiteCount(org),\n storageGb: finite(rollup?.storageGb),\n pageViews: finite(rollup?.pageViews),\n dataStorageMb: finite(rollup?.dataStorageMb),\n apiRequests: finite(rollup?.apiRequests),\n emailSends: finite(rollup?.emailSends),\n }\n for (const band of pluginUsageBands()) {\n const reading = declaredMeterReading(rollup, band)\n // Dollars on the rollup, a unit of cost on the band: rounded UP, so spend\n // already made never reads as less of the band.\n used[band.id] =\n band.unitCostUsd && reading > 0\n ? Math.ceil(reading / band.unitCostUsd)\n : reading\n }\n return used\n}\n\nexport interface OrgMarginInput {\n orgId: string\n name?: string | null\n /** The merged `{...orgDoc, ...billingDoc}` every revenue helper reads. */\n org: Partial<AglynOrgBilling> | null | undefined\n rollup: UtilizationRollup | null | undefined\n month?: string | null\n}\n\n/**\n * One org's realised utilization, cost and margin.\n *\n * The cost is `orgMonthlyCogsUsd`'s, unmodified, floor included — the same\n * `max(measured, $2 × sites)` the guardrail applies. On production today that\n * floor is what every org's figure is, which is worth reading off the `basis`\n * field rather than assuming the meters are driving anything yet.\n */\nexport function orgMarginRow(input: OrgMarginInput): OrgMarginRow {\n const { org, rollup } = input\n const included = orgIncludedBands(org)\n const used = bandUsage(org, rollup)\n const bands = Object.fromEntries(\n UTILIZATION_BANDS.map((band) => [band, bandUtilization(band, used[band], included[band])]),\n ) as Record<UtilizationBand, BandUtilization>\n\n const cogs = orgMonthlyCogsUsd(rollup, orgSiteCount(org))\n const listPriceUsd = orgListPriceMonthlyUsd(org)\n const mrrUsd = orgMonthlyRevenueUsd(org)\n const netRevenueUsd = orgNetMonthlyRevenueUsd(org)\n // Only when the org bills something at all — `listPriceUsd` is 0 for a\n // comped or lapsed org whatever its `seatAddons` say, and the add-on's\n // share of nothing is nothing. `resolveAiTier` already drops a dead\n // subscription's add-on; the list-price check catches the comped one.\n const plan = resolveEffectivePlan(org)\n const customPriced =\n typeof org?.subscription?.customMonthlyUsd === 'number' &&\n org.subscription.customMonthlyUsd > 0\n // The tier's own price (AGL-3965); `resolveAiTier` drops a dead one.\n const aiTier = resolveAiTier(org)\n const aiAddonRevenueUsd =\n listPriceUsd > 0 && !customPriced && aiTier\n ? finite(AI_TIERS[aiTier].monthlyUsd)\n : 0\n // A margin needs revenue to be a fraction OF. Free and comped orgs have\n // none, and inventing one for them fills the top of a worst-first list with\n // customers who were never billed.\n const marginPct =\n netRevenueUsd > 0\n ? Math.round(((netRevenueUsd - cogs.cogsUsd) / netRevenueUsd) * 10000) / 10000\n : null\n\n return {\n orgId: input.orgId,\n name: input.name ?? null,\n plan,\n month: input.month ?? null,\n bands,\n cogs,\n listPriceUsd,\n mrrUsd,\n netRevenueUsd,\n aiAddonRevenueUsd,\n marginPct,\n rating: marginPct === null ? null : netMarginRating(marginPct),\n }\n}\n\n/**\n * Nearest-rank percentile over a sample sorted ascending.\n *\n * `null` for an empty sample. A median of nothing is not zero, and the fleet\n * view exists to answer a question that has no answer yet for most bands.\n */\nexport function percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n const rank = Math.ceil(p * sorted.length)\n return sorted[Math.min(sorted.length - 1, Math.max(0, rank - 1))]\n}\n\nexport interface BandDistribution {\n band: UtilizationBand\n /**\n * Orgs a percentage EXISTS for — a finite, positive band. Every percentile\n * below is over this sample and no other.\n */\n counted: number\n /** Excluded because the band is `UNLIMITED`. Not 0%, not 100%: no answer. */\n excludedUncapped: number\n /** Excluded because the plan includes none of this meter. */\n excludedNoAllowance: number\n /**\n * Orgs with no included allowance that spent the meter anyway — cost with no\n * band behind it. Excluded from the percentiles, reported on its own.\n */\n usageWithNoAllowance: number\n p50: number | null\n p25: number | null\n p75: number | null\n p90: number | null\n max: number | null\n /** Orgs at or past 100% of the band, out of `counted`. */\n overBand: number\n}\n\nexport interface FleetUtilization {\n /** Orgs folded in — every row handed to it, whatever its plan. */\n orgs: number\n /** Of those, how many had a usage rollup at all. */\n withRollup: number\n distributions: BandDistribution[]\n /** Median contribution margin across orgs that bill something. */\n medianMarginPct: number | null\n /** Orgs billing something whose margin sits under `NET_MARGIN_FLOOR_PCT`. */\n orgsUnderFloor: number\n /** Orgs billing something whose COGS exceeds their net revenue. */\n orgsUnderwater: number\n /** Total measured COGS and net revenue across the fold, in USD. */\n totalCogsUsd: number\n totalNetRevenueUsd: number\n /** Of `totalNetRevenueUsd`'s gross, how much the AI add-on brought in. */\n totalAiAddonRevenueUsd: number\n}\n\n/**\n * The fleet answer: the median and spread of utilization per band.\n *\n * This is the figure every margin projection has been assuming. It is folded\n * over whatever rows the caller read — see the route's truncation disclosure,\n * because a distribution over a partial fleet is a distribution over a partial\n * fleet and must say so.\n *\n * An org WITHOUT a rollup still contributes its `hosts` band (the org doc\n * knows its own sites) and is excluded from the other seven by having no\n * measurement, not by being scored at zero. `withRollup` is what says how much\n * of the fold is real.\n */\nexport function fleetUtilization(rows: readonly OrgMarginRow[]): FleetUtilization {\n const distributions = UTILIZATION_BANDS.map<BandDistribution>((band) => {\n const sample: number[] = []\n let excludedUncapped = 0\n let excludedNoAllowance = 0\n let usageWithNoAllowance = 0\n for (const row of rows) {\n const reading = row.bands[band]\n if (!reading) continue\n // A band the cron has never measured contributes nothing rather than a\n // zero: `hosts` is known without a rollup, the seven meters are not.\n if (band !== 'hosts' && row.month === null) continue\n if (reading.state === 'uncapped') {\n excludedUncapped += 1\n continue\n }\n if (reading.state === 'noAllowance') {\n excludedNoAllowance += 1\n if (reading.used > 0) usageWithNoAllowance += 1\n continue\n }\n sample.push(reading.fraction as number)\n }\n sample.sort((a, b) => a - b)\n return {\n band,\n counted: sample.length,\n excludedUncapped,\n excludedNoAllowance,\n usageWithNoAllowance,\n p50: percentile(sample, 0.5),\n p25: percentile(sample, 0.25),\n p75: percentile(sample, 0.75),\n p90: percentile(sample, 0.9),\n max: sample.length ? sample[sample.length - 1] : null,\n overBand: sample.filter((fraction) => fraction >= 1).length,\n }\n })\n\n const margins = rows\n .map((row) => row.marginPct)\n .filter((margin): margin is number => margin !== null)\n .sort((a, b) => a - b)\n\n return {\n orgs: rows.length,\n withRollup: rows.filter((row) => row.month !== null).length,\n distributions,\n medianMarginPct: percentile(margins, 0.5),\n orgsUnderFloor: margins.filter((margin) => netMarginRating(margin) !== 'ok').length,\n orgsUnderwater: margins.filter((margin) => margin < 0).length,\n totalCogsUsd: Math.round(rows.reduce((sum, row) => sum + row.cogs.cogsUsd, 0) * 100) / 100,\n totalNetRevenueUsd:\n Math.round(rows.reduce((sum, row) => sum + row.netRevenueUsd, 0) * 100) / 100,\n totalAiAddonRevenueUsd:\n Math.round(\n rows.reduce((sum, row) => sum + (row.aiAddonRevenueUsd ?? 0), 0) * 100,\n ) / 100,\n }\n}\n\n/**\n * Worst margin first — the ordering the surface exists for.\n *\n * An org with no revenue has no margin and sorts to the END regardless. It\n * cannot be the unprofitable customer this list is looking for, and putting\n * the free tier at the top would bury the one org that is.\n */\nexport function byWorstMargin(a: OrgMarginRow, b: OrgMarginRow): number {\n if (a.marginPct === null && b.marginPct === null) return b.cogs.cogsUsd - a.cogs.cogsUsd\n if (a.marginPct === null) return 1\n if (b.marginPct === null) return -1\n return a.marginPct - b.marginPct || b.cogs.cogsUsd - a.cogs.cogsUsd\n}\n\n/** Re-exported so the page states the floor it is colouring against. */\nexport { INFRA_COGS_PER_SITE_USD }\n"],"names":["AI_TIERS","INFRA_COGS_PER_SITE_USD","MARGIN_SCOPE_NOTE","netMarginRating","orgListPriceMonthlyUsd","orgMonthlyCogsUsd","resolveAiTier","orgMonthlyRevenueUsd","orgNetMonthlyRevenueUsd","orgSiteCount","pageViewsFromBandwidthGb","resolveOrgEntitlements","resolveEffectivePlan","planQuotaOf","declaredMeterReading","pluginUsageBands","CORE_BANDS","id","label","order","BANDS","map","declared","sort","a","b","UTILIZATION_BANDS","band","UTILIZATION_BAND_LABELS","Object","fromEntries","finite","value","parsed","Number","isFinite","orgIncludedBands","org","entitlements","hostLimit","Math","max","included","hosts","storageGb","storagePerHostMb","pageViews","bandwidthGb","dataStorageMb","dataStorageMbPerOrg","apiRequests","apiRequestsPerMonth","emailSends","emailSendsPerMonth","figure","entitlement","perHost","bandUtilization","used","usedSafe","POSITIVE_INFINITY","state","fraction","bandUsage","rollup","reading","unitCostUsd","ceil","orgMarginRow","input","bands","cogs","listPriceUsd","mrrUsd","netRevenueUsd","plan","customPriced","subscription","customMonthlyUsd","aiTier","aiAddonRevenueUsd","monthlyUsd","marginPct","round","cogsUsd","orgId","name","month","rating","percentile","sorted","p","length","rank","min","fleetUtilization","rows","distributions","sample","excludedUncapped","excludedNoAllowance","usageWithNoAllowance","row","push","counted","p50","p25","p75","p90","overBand","filter","margins","margin","orgs","withRollup","medianMarginPct","orgsUnderFloor","orgsUnderwater","totalCogsUsd","reduce","sum","totalNetRevenueUsd","totalAiAddonRevenueUsd","byWorstMargin"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,6EAA6E;AAC7E,oEAAoE;AACpE,8EAA8E;AAC9E,oBAAoB;AAEpB,SACEA,QAAQ,EACRC,uBAAuB,EACvBC,iBAAiB,EACjBC,eAAe,EACfC,sBAAsB,EACtBC,iBAAiB,EACjBC,aAAa,EACbC,oBAAoB,EACpBC,uBAAuB,EACvBC,YAAY,EACZC,wBAAwB,EACxBC,sBAAsB,EACtBC,oBAAoB,QAIf,yBAAqB;AAC5B,SAASC,WAAW,QAAQ,gDAA4C;AACxE,SACEC,oBAAoB,EACpBC,gBAAgB,QAEX,yCAAqC;AAE5C,SAASb,iBAAiB,GAAE;AAE5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AACa,KAAKuB,MAAM,CAAC,CAACC,KAAKlB,MAAQkB,MAAMlB,IAAI5B,aAAa,EAAE,KAAK,OAAO;QAC5EgD,wBACElF,KAAK2C,KAAK,CACRa,KAAKuB,MAAM,CAAC,CAACC,KAAKlB;gBAAeA;mBAAPkB,QAAOlB,yBAAAA,IAAItB,iBAAiB,YAArBsB,yBAAyB;WAAI,KAAK,OACjE;IACR;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASqB,cAAcnG,CAAe,EAAEC,CAAe;IAC5D,IAAID,EAAE0D,SAAS,KAAK,QAAQzD,EAAEyD,SAAS,KAAK,MAAM,OAAOzD,EAAE8C,IAAI,CAACa,OAAO,GAAG5D,EAAE+C,IAAI,CAACa,OAAO;IACxF,IAAI5D,EAAE0D,SAAS,KAAK,MAAM,OAAO;IACjC,IAAIzD,EAAEyD,SAAS,KAAK,MAAM,OAAO,CAAC;IAClC,OAAO1D,EAAE0D,SAAS,GAAGzD,EAAEyD,SAAS,IAAIzD,EAAE8C,IAAI,CAACa,OAAO,GAAG5D,EAAE+C,IAAI,CAACa,OAAO;AACrE;AAEA,sEAAsE,GACtE,SAASnF,uBAAuB,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/margin-utilization.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// Imported from BOTH graphs — the staff page (client) and the App Route that\n// serves it — so it may import neither entry barrel, for the reason\n// `usage-metering.ts` states at its own head. The specific modules underneath\n// are safe in both.\nimport type { AglynOrgBilling, OrgPlan } from '../foundation'\nimport { aiCreditBlocksMonthlyUsd } from './ai-credit-blocks'\nimport {\n INFRA_COGS_PER_SITE_USD,\n MARGIN_SCOPE_NOTE,\n netMarginRating,\n orgListPriceMonthlyUsd,\n orgMonthlyCogsUsd,\n resolveAiCreditBlocks,\n orgMonthlyRevenueUsd,\n orgNetMonthlyRevenueUsd,\n orgSiteCount,\n pageViewsFromBandwidthGb,\n resolveOrgEntitlements,\n resolveEffectivePlan,\n type DiscountMarginRating,\n type OrgCogsResult,\n type OrgUsageRollupInput,\n} from './plan-entitlements'\nimport { planQuotaOf } from '../plugin-manager/plugin-plan-entitlements'\nimport {\n declaredMeterReading,\n pluginUsageBands,\n type ResolvedPluginUsageBand,\n} from '../plugin-manager/plugin-usage-axes'\n\nexport { MARGIN_SCOPE_NOTE }\n\n/**\n * WHAT SHARE OF THE BANDS THEY BOUGHT DO CUSTOMERS ACTUALLY SPEND?\n *\n * `tier-margin-floor.spec.ts` proves what every tier costs at 100% of every\n * band, and pins the margin at 3 / 25 / 50 / 100%. Which of those four columns\n * the business is actually operating in has never been measured — and the\n * spread between them is the whole question, because on Pro the same price\n * list yields 89.3% at the 3% column and 7.1% at the 100% one.\n *\n * Everything needed to answer it was already recorded and already priced. The\n * monthly rollup carries the meters, `ORG_COGS_UNIT_RATES_USD` carries their\n * unit costs, and `orgMonthlyCogsUsd` already turns one into the other. What\n * did not exist was the DIVISION: usage over the band the plan sold, per org\n * and across the fleet.\n *\n * This module is that division, and nothing else. It runs no query, holds no\n * rate of its own and re-derives no cost — every dollar here comes back out of\n * `orgMonthlyCogsUsd`, so a surface built on it cannot come to disagree with\n * the discount guardrail about what an org costs.\n *\n * ## The three answers a band can give, and why two of them are not numbers\n *\n * A percentage needs a denominator, and two of the bands in `PLAN_ENTITLEMENTS`\n * do not supply one:\n *\n * * `UNLIMITED` — `Number.POSITIVE_INFINITY`. Enterprise carries it on\n * contacts, API requests and dataset storage. `used / Infinity` is 0, which\n * would render the platform's largest customers as its lightest users; and\n * a model that clamps to 100% instead would render them as its heaviest.\n * Both are inventions. The band is UNCAPPED, the fraction is `null`, and no\n * aggregate may average it in either direction.\n * * `0` — Free carries it on email sends, API requests and dataset storage.\n * `0 / 0` is `NaN` and `n / 0` is `Infinity`. Neither is a utilization. The\n * band admits nothing, so there is no allowance to be a fraction of, and an\n * org that spent the meter anyway did so with no included band behind it —\n * which is a cost signal in its own right, reported as\n * `usageWithNoAllowance` rather than folded into a percentile.\n *\n * The two are kept DISTINCT from each other and from `0%`. An uncapped band\n * and an exhausted one are opposite facts, and the recurring defect in this\n * repo's cost work is exactly that an absent figure reads as a zero one.\n *\n * ## What the bands are\n *\n * `meteredIncludedAllowance` sizes three of them and is the shape followed\n * here: the two PER-HOST bands are expanded by `hostLimit`, the rest are\n * org-wide as stored. `contactsPerHost` is org-wide DESPITE ITS NAME —\n * `checkContactQuota` compares it against an org-wide headcount, and\n * `tier-margin-floor.spec.ts` costs it unexpanded. Following either of those\n * and not the name is what keeps this table agreeing with both.\n */\n\n/**\n * The platform's own bands, at the positions the plugins' declared bands\n * interleave with (`order`, a multiple of 10 here) — every meter\n * `orgMonthlyCogsUsd` prices that is the platform's, plus `hosts`.\n */\nconst CORE_BANDS: ReadonlyArray<{ id: string; label: string; order: number }> = [\n { id: 'hosts', label: 'Sites', order: 10 },\n { id: 'storageGb', label: 'Media storage', order: 20 },\n { id: 'pageViews', label: 'Bandwidth (page views)', order: 30 },\n { id: 'dataStorageMb', label: 'Dataset storage', order: 50 },\n { id: 'apiRequests', label: 'API requests', order: 60 },\n { id: 'emailSends', label: 'Email sends', order: 80 },\n]\n\n/**\n * Every band the table reads, in column order: the platform's, and each one a\n * plugin declares beside the meter it contributes (`plugin-usage-axes.ts`) —\n * the AI plugin's credits, the CRM's records, the forms plugin's\n * submissions, the workflows plugin's runs.\n *\n * A plugin band sold in a unit OF cost is measured in that unit rather than\n * in the dollars the rollup stores: the AI plugin's credits are the dollars\n * over its declared unit cost, rounded up, which is the one conversion the\n * customer's own meter uses. It is also the band most worth watching —\n * provider spend is the only line item on the platform whose unit cost is\n * real money paid to a third party, and the only one that can clear the\n * $2/site floor on its own.\n */\nconst BANDS: ReadonlyArray<{\n id: string\n label: string\n order: number\n declared?: ResolvedPluginUsageBand\n}> = [\n ...CORE_BANDS,\n ...pluginUsageBands().map((declared) => ({\n id: declared.id,\n label: declared.label,\n order: declared.order,\n declared,\n })),\n].sort((a, b) => a.order - b.order)\n\n/** Every band, keyed by what it measures, in column order. */\nexport const UTILIZATION_BANDS: readonly string[] = BANDS.map((band) => band.id)\n\nexport type UtilizationBand = string\n\n/** Column headings, so the page and the aggregate name a band identically. */\nexport const UTILIZATION_BAND_LABELS: Readonly<Record<UtilizationBand, string>> =\n Object.fromEntries(BANDS.map((band) => [band.id, band.label]))\n\n/**\n * Why a band has no percentage, or that it has one.\n *\n * `uncapped` and `noAllowance` are the two non-numbers described at the head\n * of this module. They are separate values rather than one `null` because the\n * remedies are opposite: an uncapped band is a pricing exposure, an exhausted\n * one is an upgrade conversation.\n */\nexport type BandState = 'measured' | 'uncapped' | 'noAllowance'\n\nexport interface BandUtilization {\n band: UtilizationBand\n /** The org-wide included allowance. `Infinity` when uncapped, 0 when none. */\n included: number\n /** What the rollup recorded. Always a finite, non-negative number. */\n used: number\n state: BandState\n /**\n * Share of the band consumed, as a fraction of 1.\n *\n * `null` for every state but `measured`, and callers must render it as\n * neither 0 nor 1. It is NOT clamped: an org past its included band reads\n * above 1, which is the number worth seeing.\n */\n fraction: number | null\n}\n\n/** One org's realised position: what it consumed, what it cost, what it paid. */\nexport interface OrgMarginRow {\n orgId: string\n name: string | null\n plan: OrgPlan\n /** The rollup month these figures describe, or null when none has run. */\n month: string | null\n bands: Record<UtilizationBand, BandUtilization>\n /**\n * The shared cost model's answer — the same function and the same fields\n * `/api/admin/org-discount` underwrites against.\n */\n cogs: OrgCogsResult\n /** Pre-discount sticker price. */\n listPriceUsd: number\n /** List price net of any per-org discount. */\n mrrUsd: number\n /** MRR net of Stripe's processing fee — the base the margin is taken on. */\n netRevenueUsd: number\n /**\n * The AI add-on's share of `listPriceUsd` (AGL-2930) — already INSIDE\n * `listPriceUsd`, `mrrUsd` and `netRevenueUsd`, because\n * `orgListPriceMonthlyUsd` folds every purchased add-on. Named here so the\n * surface can show that the assist band's cost has revenue against it\n * rather than reading as pure margin drag; adding it again would count it\n * twice. 0 on a custom-priced deal, whose quote already folds the add-on\n * into one negotiated figure.\n */\n aiAddonRevenueUsd: number\n /**\n * `(net revenue − COGS) / net revenue`, the same arithmetic\n * `checkDiscountMargin` rates a discount on. See `MARGIN_SCOPE_NOTE`: it is\n * a contribution margin, not a profit.\n *\n * `null` when the org bills nothing. A free or comped org has no revenue to\n * take a fraction of, and reporting it as 0% or −100% would put a customer\n * who was never meant to be profitable at the top of a list whose whole\n * purpose is finding the one who was.\n */\n marginPct: number | null\n rating: DiscountMarginRating | null\n}\n\n/**\n * A rollup as this surface reads it: every field `orgMonthlyCogsUsd` prices.\n *\n * The two run counters used to be the surface's own extension of that shape\n * — recorded and banded but unpriced. Since 2026-09-07 the cost model prices\n * them at `perRun`, so the shape is the model's and nothing here is extra.\n */\nexport type UtilizationRollup = OrgUsageRollupInput\n\nconst finite = (value: unknown): number => {\n const parsed = Number(value ?? 0)\n return Number.isFinite(parsed) && parsed > 0 ? parsed : 0\n}\n\n/**\n * The org-wide included band for every metered axis, on this org's plan and\n * with this org's overrides and add-ons applied.\n *\n * `resolveOrgEntitlements` rather than `PLAN_ENTITLEMENTS[plan]`: a staff\n * entitlement override and a purchased host add-on both change what the\n * customer actually bought, and measuring consumption against the catalogue\n * row instead of the resolved one is the same class of error as measuring it\n * against a constant.\n */\nexport function orgIncludedBands(\n org: Partial<AglynOrgBilling> | null | undefined,\n): Record<UtilizationBand, number> {\n const entitlements = resolveOrgEntitlements(org)\n const hostLimit = Math.max(1, entitlements.hostLimit)\n const included: Record<UtilizationBand, number> = {\n hosts: entitlements.hostLimit,\n // Per host, expanded by the host limit — `meteredIncludedAllowance`\n // expands the per-host bands and nothing else.\n storageGb: (hostLimit * entitlements.storagePerHostMb) / 1024,\n // Bandwidth IS the page-view band, expressed in the unit customers buy.\n pageViews: pageViewsFromBandwidthGb(entitlements.bandwidthGb),\n // Org-wide, in the unit the rollup stores. `dataStorageMbPerOrg` is\n // megabytes and so is `dataStorageMb`; the GB conversion happens inside\n // `orgMonthlyCogsUsd` and must not happen twice.\n dataStorageMb: entitlements.dataStorageMbPerOrg,\n apiRequests: entitlements.apiRequestsPerMonth,\n emailSends: entitlements.emailSendsPerMonth,\n }\n // A plugin's band reads the entitlement its declaration names — absent is\n // nothing included — expanded by the host limit where it is per site.\n for (const band of pluginUsageBands()) {\n const figure = planQuotaOf(entitlements, band.entitlement)\n included[band.id] = band.perHost ? hostLimit * figure : figure\n }\n return included\n}\n\n/** One band's reading. The whole of the `UNLIMITED` and zero-band rule. */\nexport function bandUtilization(\n band: UtilizationBand,\n used: number,\n included: number,\n): BandUtilization {\n const usedSafe = Number.isFinite(used) && used > 0 ? used : 0\n if (!Number.isFinite(included)) {\n return { band, included: Number.POSITIVE_INFINITY, used: usedSafe, state: 'uncapped', fraction: null }\n }\n if (!(included > 0)) {\n return { band, included: 0, used: usedSafe, state: 'noAllowance', fraction: null }\n }\n return { band, included, used: usedSafe, state: 'measured', fraction: usedSafe / included }\n}\n\n/**\n * What the rollup recorded, per band.\n *\n * `hosts` comes from the ORG rather than the rollup: `orgSiteCount` is what\n * the cost floor is charged on and what `checkDiscountMargin` counts, and a\n * site added since the cron last ran is a site the org has. The rollup's own\n * `hostCount` is a snapshot of the same thing at cron time.\n */\nfunction bandUsage(\n org: Partial<AglynOrgBilling> | null | undefined,\n rollup: UtilizationRollup | null | undefined,\n): Record<UtilizationBand, number> {\n const used: Record<UtilizationBand, number> = {\n hosts: orgSiteCount(org),\n storageGb: finite(rollup?.storageGb),\n pageViews: finite(rollup?.pageViews),\n dataStorageMb: finite(rollup?.dataStorageMb),\n apiRequests: finite(rollup?.apiRequests),\n emailSends: finite(rollup?.emailSends),\n }\n for (const band of pluginUsageBands()) {\n const reading = declaredMeterReading(rollup, band)\n // Dollars on the rollup, a unit of cost on the band: rounded UP, so spend\n // already made never reads as less of the band.\n used[band.id] =\n band.unitCostUsd && reading > 0\n ? Math.ceil(reading / band.unitCostUsd)\n : reading\n }\n return used\n}\n\nexport interface OrgMarginInput {\n orgId: string\n name?: string | null\n /** The merged `{...orgDoc, ...billingDoc}` every revenue helper reads. */\n org: Partial<AglynOrgBilling> | null | undefined\n rollup: UtilizationRollup | null | undefined\n month?: string | null\n}\n\n/**\n * One org's realised utilization, cost and margin.\n *\n * The cost is `orgMonthlyCogsUsd`'s, unmodified, floor included — the same\n * `max(measured, $2 × sites)` the guardrail applies. On production today that\n * floor is what every org's figure is, which is worth reading off the `basis`\n * field rather than assuming the meters are driving anything yet.\n */\nexport function orgMarginRow(input: OrgMarginInput): OrgMarginRow {\n const { org, rollup } = input\n const included = orgIncludedBands(org)\n const used = bandUsage(org, rollup)\n const bands = Object.fromEntries(\n UTILIZATION_BANDS.map((band) => [band, bandUtilization(band, used[band], included[band])]),\n ) as Record<UtilizationBand, BandUtilization>\n\n const cogs = orgMonthlyCogsUsd(rollup, orgSiteCount(org))\n const listPriceUsd = orgListPriceMonthlyUsd(org)\n const mrrUsd = orgMonthlyRevenueUsd(org)\n const netRevenueUsd = orgNetMonthlyRevenueUsd(org)\n // Only when the org bills something at all — `listPriceUsd` is 0 for a\n // comped or lapsed org whatever its `seatAddons` say, and the add-on's\n // share of nothing is nothing. `resolveAiCreditBlocks` already drops a dead\n // subscription's add-on; the list-price check catches the comped one.\n const plan = resolveEffectivePlan(org)\n const customPriced =\n typeof org?.subscription?.customMonthlyUsd === 'number' &&\n org.subscription.customMonthlyUsd > 0\n // $10 a credit block (AGL-4144); `resolveAiCreditBlocks` drops a dead one.\n const aiBlocks = resolveAiCreditBlocks(org)\n const aiAddonRevenueUsd =\n listPriceUsd > 0 && !customPriced && aiBlocks > 0\n ? finite(aiCreditBlocksMonthlyUsd(aiBlocks))\n : 0\n // A margin needs revenue to be a fraction OF. Free and comped orgs have\n // none, and inventing one for them fills the top of a worst-first list with\n // customers who were never billed.\n const marginPct =\n netRevenueUsd > 0\n ? Math.round(((netRevenueUsd - cogs.cogsUsd) / netRevenueUsd) * 10000) / 10000\n : null\n\n return {\n orgId: input.orgId,\n name: input.name ?? null,\n plan,\n month: input.month ?? null,\n bands,\n cogs,\n listPriceUsd,\n mrrUsd,\n netRevenueUsd,\n aiAddonRevenueUsd,\n marginPct,\n rating: marginPct === null ? null : netMarginRating(marginPct),\n }\n}\n\n/**\n * Nearest-rank percentile over a sample sorted ascending.\n *\n * `null` for an empty sample. A median of nothing is not zero, and the fleet\n * view exists to answer a question that has no answer yet for most bands.\n */\nexport function percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n const rank = Math.ceil(p * sorted.length)\n return sorted[Math.min(sorted.length - 1, Math.max(0, rank - 1))]\n}\n\nexport interface BandDistribution {\n band: UtilizationBand\n /**\n * Orgs a percentage EXISTS for — a finite, positive band. Every percentile\n * below is over this sample and no other.\n */\n counted: number\n /** Excluded because the band is `UNLIMITED`. Not 0%, not 100%: no answer. */\n excludedUncapped: number\n /** Excluded because the plan includes none of this meter. */\n excludedNoAllowance: number\n /**\n * Orgs with no included allowance that spent the meter anyway — cost with no\n * band behind it. Excluded from the percentiles, reported on its own.\n */\n usageWithNoAllowance: number\n p50: number | null\n p25: number | null\n p75: number | null\n p90: number | null\n max: number | null\n /** Orgs at or past 100% of the band, out of `counted`. */\n overBand: number\n}\n\nexport interface FleetUtilization {\n /** Orgs folded in — every row handed to it, whatever its plan. */\n orgs: number\n /** Of those, how many had a usage rollup at all. */\n withRollup: number\n distributions: BandDistribution[]\n /** Median contribution margin across orgs that bill something. */\n medianMarginPct: number | null\n /** Orgs billing something whose margin sits under `NET_MARGIN_FLOOR_PCT`. */\n orgsUnderFloor: number\n /** Orgs billing something whose COGS exceeds their net revenue. */\n orgsUnderwater: number\n /** Total measured COGS and net revenue across the fold, in USD. */\n totalCogsUsd: number\n totalNetRevenueUsd: number\n /** Of `totalNetRevenueUsd`'s gross, how much the AI add-on brought in. */\n totalAiAddonRevenueUsd: number\n}\n\n/**\n * The fleet answer: the median and spread of utilization per band.\n *\n * This is the figure every margin projection has been assuming. It is folded\n * over whatever rows the caller read — see the route's truncation disclosure,\n * because a distribution over a partial fleet is a distribution over a partial\n * fleet and must say so.\n *\n * An org WITHOUT a rollup still contributes its `hosts` band (the org doc\n * knows its own sites) and is excluded from the other seven by having no\n * measurement, not by being scored at zero. `withRollup` is what says how much\n * of the fold is real.\n */\nexport function fleetUtilization(rows: readonly OrgMarginRow[]): FleetUtilization {\n const distributions = UTILIZATION_BANDS.map<BandDistribution>((band) => {\n const sample: number[] = []\n let excludedUncapped = 0\n let excludedNoAllowance = 0\n let usageWithNoAllowance = 0\n for (const row of rows) {\n const reading = row.bands[band]\n if (!reading) continue\n // A band the cron has never measured contributes nothing rather than a\n // zero: `hosts` is known without a rollup, the seven meters are not.\n if (band !== 'hosts' && row.month === null) continue\n if (reading.state === 'uncapped') {\n excludedUncapped += 1\n continue\n }\n if (reading.state === 'noAllowance') {\n excludedNoAllowance += 1\n if (reading.used > 0) usageWithNoAllowance += 1\n continue\n }\n sample.push(reading.fraction as number)\n }\n sample.sort((a, b) => a - b)\n return {\n band,\n counted: sample.length,\n excludedUncapped,\n excludedNoAllowance,\n usageWithNoAllowance,\n p50: percentile(sample, 0.5),\n p25: percentile(sample, 0.25),\n p75: percentile(sample, 0.75),\n p90: percentile(sample, 0.9),\n max: sample.length ? sample[sample.length - 1] : null,\n overBand: sample.filter((fraction) => fraction >= 1).length,\n }\n })\n\n const margins = rows\n .map((row) => row.marginPct)\n .filter((margin): margin is number => margin !== null)\n .sort((a, b) => a - b)\n\n return {\n orgs: rows.length,\n withRollup: rows.filter((row) => row.month !== null).length,\n distributions,\n medianMarginPct: percentile(margins, 0.5),\n orgsUnderFloor: margins.filter((margin) => netMarginRating(margin) !== 'ok').length,\n orgsUnderwater: margins.filter((margin) => margin < 0).length,\n totalCogsUsd: Math.round(rows.reduce((sum, row) => sum + row.cogs.cogsUsd, 0) * 100) / 100,\n totalNetRevenueUsd:\n Math.round(rows.reduce((sum, row) => sum + row.netRevenueUsd, 0) * 100) / 100,\n totalAiAddonRevenueUsd:\n Math.round(\n rows.reduce((sum, row) => sum + (row.aiAddonRevenueUsd ?? 0), 0) * 100,\n ) / 100,\n }\n}\n\n/**\n * Worst margin first — the ordering the surface exists for.\n *\n * An org with no revenue has no margin and sorts to the END regardless. It\n * cannot be the unprofitable customer this list is looking for, and putting\n * the free tier at the top would bury the one org that is.\n */\nexport function byWorstMargin(a: OrgMarginRow, b: OrgMarginRow): number {\n if (a.marginPct === null && b.marginPct === null) return b.cogs.cogsUsd - a.cogs.cogsUsd\n if (a.marginPct === null) return 1\n if (b.marginPct === null) return -1\n return a.marginPct - b.marginPct || b.cogs.cogsUsd - a.cogs.cogsUsd\n}\n\n/** Re-exported so the page states the floor it is colouring against. */\nexport { INFRA_COGS_PER_SITE_USD }\n"],"names":["aiCreditBlocksMonthlyUsd","INFRA_COGS_PER_SITE_USD","MARGIN_SCOPE_NOTE","netMarginRating","orgListPriceMonthlyUsd","orgMonthlyCogsUsd","resolveAiCreditBlocks","orgMonthlyRevenueUsd","orgNetMonthlyRevenueUsd","orgSiteCount","pageViewsFromBandwidthGb","resolveOrgEntitlements","resolveEffectivePlan","planQuotaOf","declaredMeterReading","pluginUsageBands","CORE_BANDS","id","label","order","BANDS","map","declared","sort","a","b","UTILIZATION_BANDS","band","UTILIZATION_BAND_LABELS","Object","fromEntries","finite","value","parsed","Number","isFinite","orgIncludedBands","org","entitlements","hostLimit","Math","max","included","hosts","storageGb","storagePerHostMb","pageViews","bandwidthGb","dataStorageMb","dataStorageMbPerOrg","apiRequests","apiRequestsPerMonth","emailSends","emailSendsPerMonth","figure","entitlement","perHost","bandUtilization","used","usedSafe","POSITIVE_INFINITY","state","fraction","bandUsage","rollup","reading","unitCostUsd","ceil","orgMarginRow","input","bands","cogs","listPriceUsd","mrrUsd","netRevenueUsd","plan","customPriced","subscription","customMonthlyUsd","aiBlocks","aiAddonRevenueUsd","marginPct","round","cogsUsd","orgId","name","month","rating","percentile","sorted","p","length","rank","min","fleetUtilization","rows","distributions","sample","excludedUncapped","excludedNoAllowance","usageWithNoAllowance","row","push","counted","p50","p25","p75","p90","overBand","filter","margins","margin","orgs","withRollup","medianMarginPct","orgsUnderFloor","orgsUnderwater","totalCogsUsd","reduce","sum","totalNetRevenueUsd","totalAiAddonRevenueUsd","byWorstMargin"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,6EAA6E;AAC7E,oEAAoE;AACpE,8EAA8E;AAC9E,oBAAoB;AAEpB,SAASA,wBAAwB,QAAQ,wBAAoB;AAC7D,SACEC,uBAAuB,EACvBC,iBAAiB,EACjBC,eAAe,EACfC,sBAAsB,EACtBC,iBAAiB,EACjBC,qBAAqB,EACrBC,oBAAoB,EACpBC,uBAAuB,EACvBC,YAAY,EACZC,wBAAwB,EACxBC,sBAAsB,EACtBC,oBAAoB,QAIf,yBAAqB;AAC5B,SAASC,WAAW,QAAQ,gDAA4C;AACxE,SACEC,oBAAoB,EACpBC,gBAAgB,QAEX,yCAAqC;AAE5C,SAASb,iBAAiB,GAAE;AAE5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkDC,GAED;;;;CAIC,GACD,MAAMc,aAA0E;IAC9E;QAAEC,IAAI;QAASC,OAAO;QAASC,OAAO;IAAG;IACzC;QAAEF,IAAI;QAAaC,OAAO;QAAiBC,OAAO;IAAG;IACrD;QAAEF,IAAI;QAAaC,OAAO;QAA0BC,OAAO;IAAG;IAC9D;QAAEF,IAAI;QAAiBC,OAAO;QAAmBC,OAAO;IAAG;IAC3D;QAAEF,IAAI;QAAeC,OAAO;QAAgBC,OAAO;IAAG;IACtD;QAAEF,IAA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SAAS,KAAK,QAAQxD,EAAEwD,SAAS,KAAK,MAAM,OAAOxD,EAAE8C,IAAI,CAACY,OAAO,GAAG3D,EAAE+C,IAAI,CAACY,OAAO;IACxF,IAAI3D,EAAEyD,SAAS,KAAK,MAAM,OAAO;IACjC,IAAIxD,EAAEwD,SAAS,KAAK,MAAM,OAAO,CAAC;IAClC,OAAOzD,EAAEyD,SAAS,GAAGxD,EAAEwD,SAAS,IAAIxD,EAAE8C,IAAI,CAACY,OAAO,GAAG3D,EAAE+C,IAAI,CAACY,OAAO;AACrE;AAEA,sEAAsE,GACtE,SAASlF,uBAAuB,GAAE"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import type {
|
|
17
|
+
import type { OrgPlan } from '../foundation/definitions/org-billing.types';
|
|
18
18
|
import { type BundleAddons } from './bundle-intent';
|
|
19
19
|
/**
|
|
20
20
|
* The marketing → console onboarding deep link (AGL-1117).
|
|
@@ -58,7 +58,9 @@ export interface OnboardingPlanIntent {
|
|
|
58
58
|
contactSales: boolean;
|
|
59
59
|
/**
|
|
60
60
|
* The Aglyn AI add-on, asked for alongside the plan (AGL-2897):
|
|
61
|
-
* `?plan=pro&interval=month&ai=1`.
|
|
61
|
+
* `?plan=pro&interval=month&ai=1`. Since AGL-4144 it is credits by the
|
|
62
|
+
* block: `ai=1` (or `yes`, `true`) asks for one block, `ai=3` for three,
|
|
63
|
+
* written into `addons.aiAddon`; a retired tier name asks for nothing.
|
|
62
64
|
*
|
|
63
65
|
* Present only when the link said so, and only ever `true` — the add-on
|
|
64
66
|
* rides the plan checkout as a second subscription item, so a flag that
|
|
@@ -67,13 +69,6 @@ export interface OnboardingPlanIntent {
|
|
|
67
69
|
* the add-on is quoted with the deal, not bought through a checkout.
|
|
68
70
|
*/
|
|
69
71
|
ai?: true;
|
|
70
|
-
/**
|
|
71
|
-
* The Aglyn AI tier the link named (AGL-3965): `?ai=boost`, or an
|
|
72
|
-
* `ai:boost` token in `addons=` (AGL-3955). Present only with `ai`; absent,
|
|
73
|
-
* `ai=1` means the tier with the plan's old price and band
|
|
74
|
-
* (`defaultAiTierForPlan`), which is what checkout sells.
|
|
75
|
-
*/
|
|
76
|
-
aiTier?: AiTierId;
|
|
77
72
|
/**
|
|
78
73
|
* Every add-on the `addons=` param preselects (AGL-3955), parsed by the
|
|
79
74
|
* shared `parseBundleAddons`. Absent when it named none. `ai=1` stays the
|
|
@@ -104,7 +99,11 @@ export interface OnboardingPlanIntent {
|
|
|
104
99
|
* what they already have.
|
|
105
100
|
*/
|
|
106
101
|
export declare function parseOnboardingPlanIntent(params: URLSearchParams | Record<string, string | string[] | undefined> | null | undefined): OnboardingPlanIntent | null;
|
|
107
|
-
/**
|
|
102
|
+
/**
|
|
103
|
+
* The whole add-on set an intent asks for: `addons=` and the `ai` flag
|
|
104
|
+
* together. The flag means at least one credit block; a count in `addons`
|
|
105
|
+
* says how many.
|
|
106
|
+
*/
|
|
108
107
|
export declare function intentAddons(intent: Pick<OnboardingPlanIntent, 'ai' | 'addons'> | null | undefined): BundleAddons;
|
|
109
108
|
/**
|
|
110
109
|
* The intent as query params — the one place the wire form is written
|
|
@@ -142,7 +141,7 @@ export declare function onboardingPlanQuery(intent: OnboardingPlanIntent): strin
|
|
|
142
141
|
*/
|
|
143
142
|
export declare function onboardingSignupHref(signupUrl: string, plan: OrgPlan, interval: OnboardingInterval | null, options?: {
|
|
144
143
|
ai?: boolean;
|
|
145
|
-
|
|
144
|
+
aiBlocks?: number;
|
|
146
145
|
}): string;
|
|
147
146
|
/**
|
|
148
147
|
* Where a freshly provisioned workspace should land, given the plan the
|
|
@@ -15,15 +15,14 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
17
|
import { bundleAddonsParam, hasBundleAddons, normalizeBundleCoupon, parseBundleAddons } from "./bundle-intent.js";
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
];
|
|
18
|
+
import { AI_CREDIT_BLOCKS_MAX } from "./ai-credit-blocks.js";
|
|
19
|
+
import { isCustomPricedPlan, SELF_SERVE_PLANS } from "./plan-entitlements.js";
|
|
20
|
+
/**
|
|
21
|
+
* The plans a link may carry into checkout: every self-serve plan but Free
|
|
22
|
+
* (see below). Derived since pricing v4 (AGL-4126), so a retired plan's old
|
|
23
|
+
* link (`?plan=business`) carries no intent rather than quoting a plan that
|
|
24
|
+
* is no longer sold.
|
|
25
|
+
*/ const PURCHASABLE_PLANS = SELF_SERVE_PLANS.filter((plan)=>plan !== 'free');
|
|
27
26
|
/**
|
|
28
27
|
* Read a plan intent off the URL, or null when there isn't a usable one.
|
|
29
28
|
*
|
|
@@ -32,7 +31,7 @@ const SELF_SERVE_PLANS = [
|
|
|
32
31
|
* Returning an intent for it would send someone to a billing page to buy
|
|
33
32
|
* what they already have.
|
|
34
33
|
*/ export function parseOnboardingPlanIntent(params) {
|
|
35
|
-
var
|
|
34
|
+
var _addons_aiAddon;
|
|
36
35
|
if (!params) return null;
|
|
37
36
|
const read = (key)=>{
|
|
38
37
|
var _ref;
|
|
@@ -52,7 +51,7 @@ const SELF_SERVE_PLANS = [
|
|
|
52
51
|
contactSales: true
|
|
53
52
|
};
|
|
54
53
|
}
|
|
55
|
-
if (!
|
|
54
|
+
if (!PURCHASABLE_PLANS.includes(plan)) return null;
|
|
56
55
|
const interval = read('interval');
|
|
57
56
|
const known = interval === 'year' || interval === 'annual' || interval === 'month';
|
|
58
57
|
// The add-on is opt-in by an explicit affirmative. Anything else — absent,
|
|
@@ -69,10 +68,12 @@ const SELF_SERVE_PLANS = [
|
|
|
69
68
|
const parsedAddons = parseBundleAddons(rawParam('addons'));
|
|
70
69
|
const addons = _extends({}, parsedAddons.addons);
|
|
71
70
|
const coupon = normalizeBundleCoupon(rawParam('coupon'));
|
|
72
|
-
// `?ai=<
|
|
73
|
-
// `
|
|
74
|
-
|
|
75
|
-
const
|
|
71
|
+
// `?ai=<blocks>` asks for that many credit blocks (AGL-4144), held to the
|
|
72
|
+
// ceiling; `1`, `true` and `yes` ask for one. Anything else, a retired
|
|
73
|
+
// tier name included, is not an affirmative.
|
|
74
|
+
const aiBlocks = /^\d+$/.test(ai) ? Math.min(AI_CREDIT_BLOCKS_MAX, Number(ai)) : 0;
|
|
75
|
+
const aiStated = ai === 'true' || ai === 'yes' || aiBlocks > 0;
|
|
76
|
+
if (aiBlocks > 1) addons.aiAddon = Math.max((_addons_aiAddon = addons.aiAddon) != null ? _addons_aiAddon : 0, aiBlocks);
|
|
76
77
|
return _extends({
|
|
77
78
|
plan: plan,
|
|
78
79
|
// Anything unrecognized falls to monthly, never to yearly: guessing the
|
|
@@ -86,8 +87,6 @@ const SELF_SERVE_PLANS = [
|
|
|
86
87
|
contactSales: false
|
|
87
88
|
}, aiStated || addons.aiAddon ? {
|
|
88
89
|
ai: true
|
|
89
|
-
} : {}, aiTier ? {
|
|
90
|
-
aiTier
|
|
91
90
|
} : {}, hasBundleAddons(addons) ? {
|
|
92
91
|
addons
|
|
93
92
|
} : {}, coupon ? {
|
|
@@ -96,11 +95,15 @@ const SELF_SERVE_PLANS = [
|
|
|
96
95
|
droppedAddons: parsedAddons.dropped
|
|
97
96
|
} : {});
|
|
98
97
|
}
|
|
99
|
-
/**
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
98
|
+
/**
|
|
99
|
+
* The whole add-on set an intent asks for: `addons=` and the `ai` flag
|
|
100
|
+
* together. The flag means at least one credit block; a count in `addons`
|
|
101
|
+
* says how many.
|
|
102
|
+
*/ export function intentAddons(intent) {
|
|
103
|
+
var _ref, _addons_aiAddon;
|
|
104
|
+
const addons = _extends({}, (_ref = intent == null ? void 0 : intent.addons) != null ? _ref : {});
|
|
105
|
+
if (intent == null ? void 0 : intent.ai) addons.aiAddon = Math.max(1, (_addons_aiAddon = addons.aiAddon) != null ? _addons_aiAddon : 0);
|
|
106
|
+
return addons;
|
|
104
107
|
}
|
|
105
108
|
/**
|
|
106
109
|
* The intent as query params — the one place the wire form is written
|
|
@@ -111,19 +114,18 @@ const SELF_SERVE_PLANS = [
|
|
|
111
114
|
* `&interval=` unconditionally, which turned the parser's monthly DEFAULT into
|
|
112
115
|
* a statement the next reader could not tell from the real thing.
|
|
113
116
|
*/ export function onboardingPlanQuery(intent) {
|
|
114
|
-
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
const addons =
|
|
119
|
-
if (intent.ai) addons.aiAddon = 1;
|
|
117
|
+
// `ai=1` stays the spelling when one credit block is the only add-on, so
|
|
118
|
+
// the published pricing CTAs and every hop between them read unchanged;
|
|
119
|
+
// `ai=3` for three (AGL-4144). Any other add-on writes the whole set as
|
|
120
|
+
// `addons=` (AGL-3955), Aglyn AI with it.
|
|
121
|
+
const addons = intentAddons(intent);
|
|
120
122
|
const others = Object.keys(addons).some((kind)=>{
|
|
121
123
|
var _addons_kind;
|
|
122
124
|
return kind !== 'aiAddon' && ((_addons_kind = addons[kind]) != null ? _addons_kind : 0) > 0;
|
|
123
125
|
});
|
|
124
126
|
const coupon = normalizeBundleCoupon(intent.coupon);
|
|
125
127
|
return `plan=${encodeURIComponent(intent.plan)}` + (intent.intervalStated ? `&interval=${intent.interval}` : '') + (others ? // readable when it is read aloud or typed off a QR's caption.
|
|
126
|
-
`&addons=${bundleAddonsParam(addons
|
|
128
|
+
`&addons=${bundleAddonsParam(addons)}` : addons.aiAddon ? `&ai=${addons.aiAddon}` : '') + (coupon ? `&coupon=${encodeURIComponent(coupon)}` : '');
|
|
127
129
|
}
|
|
128
130
|
/**
|
|
129
131
|
* The signup URL a marketing CTA should carry — the WRITER half of the
|
|
@@ -149,6 +151,7 @@ const SELF_SERVE_PLANS = [
|
|
|
149
151
|
* link into the besigner pastes a string this contract's own parser agrees
|
|
150
152
|
* with rather than one they typed.
|
|
151
153
|
*/ export function onboardingSignupHref(signupUrl, plan, interval, options = {}) {
|
|
154
|
+
var _options_aiBlocks, _options_aiBlocks1, _options_aiBlocks2;
|
|
152
155
|
const contactSales = isCustomPricedPlan(plan);
|
|
153
156
|
// A custom-priced plan is quoted, not bought, so `parseOnboardingPlanIntent`
|
|
154
157
|
// reports `intervalStated: false` for it HOWEVER the link is written. Writing
|
|
@@ -162,10 +165,12 @@ const SELF_SERVE_PLANS = [
|
|
|
162
165
|
interval: stated ? interval : 'month',
|
|
163
166
|
intervalStated: stated,
|
|
164
167
|
contactSales
|
|
165
|
-
}, (options.ai || options.
|
|
168
|
+
}, (options.ai || ((_options_aiBlocks = options.aiBlocks) != null ? _options_aiBlocks : 0) > 0) && !contactSales ? {
|
|
166
169
|
ai: true
|
|
167
|
-
} : {}, options.
|
|
168
|
-
|
|
170
|
+
} : {}, ((_options_aiBlocks1 = options.aiBlocks) != null ? _options_aiBlocks1 : 0) > 1 && !contactSales ? {
|
|
171
|
+
addons: {
|
|
172
|
+
aiAddon: Math.min(AI_CREDIT_BLOCKS_MAX, Math.floor((_options_aiBlocks2 = options.aiBlocks) != null ? _options_aiBlocks2 : 0))
|
|
173
|
+
}
|
|
169
174
|
} : {}))}`;
|
|
170
175
|
}
|
|
171
176
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/onboarding-deep-link.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 type { AiTierId, OrgPlan } from '../foundation/definitions/org-billing.types'\nimport {\n bundleAddonsParam,\n hasBundleAddons,\n normalizeBundleCoupon,\n parseBundleAddons,\n type BundleAddons,\n} from './bundle-intent'\nimport { isAiTierId, isCustomPricedPlan } from './plan-entitlements'\n\n/**\n * The marketing → console onboarding deep link (AGL-1117).\n *\n * `app.aglyn.com/signup?plan=pro&interval=year`, optionally `&ai=1` for the\n * Aglyn AI add-on (AGL-2897), or `&ai=<tier>` (`&ai=boost`) for a named\n * Aglyn AI tier (AGL-3965). The bundle checkout link (AGL-3955) adds\n * `&addons=siteCare,ai:boost,extraHost:2` for any add-on the plan sells and\n * `&coupon=<code>` for a promotion code to apply at checkout.\n *\n * This is a CONTRACT with a site we do not control and cannot deploy in\n * lockstep with. So it is parsed defensively and in one place: the pricing\n * page will eventually be edited by someone who has never read this file, and\n * a typo in a CTA must degrade to ordinary signup rather than break it or —\n * far worse — silently start someone on the wrong plan.\n */\nexport type OnboardingInterval = 'month' | 'year'\n\nexport interface OnboardingPlanIntent {\n plan: OrgPlan\n interval: OnboardingInterval\n /**\n * Whether the link ACTUALLY said an interval, as opposed to `interval`\n * being the safe default below (AGL-1535).\n *\n * Some CTAs carry a plan and deliberately no interval — the /pricing scale\n * strip quotes monthly and annual side by side and commits to neither. The\n * billing page honours that (it only lets a *stated* interval move the\n * toggle, so an annual org is not silently flipped to monthly on arrival),\n * but every hop between the CTA and that page used to re-serialize the\n * intent with `&interval=month` appended — which made the omission\n * unrecoverable one redirect after it was made. Carrying the distinction is\n * what keeps \"no interval stated\" a thing the last reader can still see.\n */\n intervalStated: boolean\n /**\n * Enterprise is quoted, not bought. The CTA still carries `plan=enterprise`\n * because that is what the visitor clicked, and the console has to route\n * them to contact-sales rather than to a checkout that cannot price it\n * (AGL-1110).\n */\n contactSales: boolean\n /**\n * The Aglyn AI add-on, asked for alongside the plan (AGL-2897):\n * `?plan=pro&interval=month&ai=1`.\n *\n * Present only when the link said so, and only ever `true` — the add-on\n * rides the plan checkout as a second subscription item, so a flag that\n * was never stated must not be told apart from one that was set to false\n * by every hop that re-serializes the intent. Enterprise never carries it:\n * the add-on is quoted with the deal, not bought through a checkout.\n */\n ai?: true\n /**\n * The Aglyn AI tier the link named (AGL-3965): `?ai=boost`, or an\n * `ai:boost` token in `addons=` (AGL-3955). Present only with `ai`; absent,\n * `ai=1` means the tier with the plan's old price and band\n * (`defaultAiTierForPlan`), which is what checkout sells.\n */\n aiTier?: AiTierId\n /**\n * Every add-on the `addons=` param preselects (AGL-3955), parsed by the\n * shared `parseBundleAddons`. Absent when it named none. `ai=1` stays the\n * `ai` flag above; an `ai` token here sets that flag too, so a reader that\n * wants the whole set reads both (`intentAddons`).\n * Whether the plan sells each one is the reader's question\n * (`fitBundleAddonsToPlan`), because the owner can pick another plan.\n */\n addons?: BundleAddons\n /**\n * A promotion code to apply at checkout (AGL-3955). Applied only: codes are\n * minted on the staff Coupons page. An invalid or expired one is dropped by\n * the Billing page with a notice, never an error page.\n */\n coupon?: string\n /**\n * Add-on tokens the link named that nothing understood, as written, so the\n * page can say in one line that they were left off.\n */\n droppedAddons?: string[]\n}\n\nconst SELF_SERVE_PLANS: readonly OrgPlan[] = [\n 'starter',\n 'pro',\n 'business',\n 'scale',\n 'advanced',\n 'agency',\n]\n\n/**\n * Read a plan intent off the URL, or null when there isn't a usable one.\n *\n * Null for `free` on purpose: it is a real plan but not a purchase, so there\n * is nothing to carry into checkout and a new org already starts there.\n * Returning an intent for it would send someone to a billing page to buy\n * what they already have.\n */\nexport function parseOnboardingPlanIntent(\n params:\n | URLSearchParams\n | Record<string, string | string[] | undefined>\n | null\n | undefined,\n): OnboardingPlanIntent | null {\n if (!params) return null\n const read = (key: string): string => {\n const raw =\n params instanceof URLSearchParams ? params.get(key) : params[key]\n // Next gives `string[]` for a repeated param. Take the first rather than\n // joining, so `?plan=pro&plan=free` cannot become the string \"pro,free\"\n // and fall through to null — the first is what the CTA meant.\n return String((Array.isArray(raw) ? raw[0] : raw) ?? '')\n .trim()\n .toLowerCase()\n }\n const plan = read('plan')\n if (!plan) return null\n if (isCustomPricedPlan(plan as OrgPlan)) {\n return {\n plan: plan as OrgPlan,\n interval: 'month',\n intervalStated: false,\n contactSales: true,\n }\n }\n if (!SELF_SERVE_PLANS.includes(plan as OrgPlan)) return null\n const interval = read('interval')\n const known = interval === 'year' || interval === 'annual' || interval === 'month'\n // The add-on is opt-in by an explicit affirmative. Anything else — absent,\n // empty, `0`, `false`, a typo — is \"not asked for\": a checkout that adds a\n // paid item off a malformed link is the expensive direction to be wrong in.\n const ai = read('ai')\n // The bundle (AGL-3955). Read case-preserving: a coupon code is typed the\n // way Stripe stores it, and `read` lower-cases.\n const rawParam = (key: string): string => {\n const raw = params instanceof URLSearchParams ? params.get(key) : params[key]\n return String((Array.isArray(raw) ? raw[0] : raw) ?? '').trim()\n }\n const parsedAddons = parseBundleAddons(rawParam('addons'))\n const addons: BundleAddons = { ...parsedAddons.addons }\n const coupon = normalizeBundleCoupon(rawParam('coupon'))\n // `?ai=<tier>` names the tier outright; otherwise an `ai:<tier>` token in\n // `addons=` does (AGL-3965).\n const aiTier = isAiTierId(ai) ? ai : (parsedAddons.aiTier ?? null)\n const aiStated = ai === '1' || ai === 'true' || ai === 'yes' || aiTier !== null\n return {\n plan: plan as OrgPlan,\n // Anything unrecognized falls to monthly, never to yearly: guessing the\n // longer commitment from a malformed link is the expensive direction to\n // be wrong in.\n interval: interval === 'year' || interval === 'annual' ? 'year' : 'month',\n // A junk interval is not a stated one: `?interval=decade` means the link\n // is broken, and the reader should fall back to what it knows about the\n // org rather than be told \"monthly\" with a straight face.\n intervalStated: known,\n contactSales: false,\n ...(aiStated || addons.aiAddon ? { ai: true } : {}),\n ...(aiTier ? { aiTier } : {}),\n ...(hasBundleAddons(addons) ? { addons } : {}),\n ...(coupon ? { coupon } : {}),\n ...(parsedAddons.dropped.length ? { droppedAddons: parsedAddons.dropped } : {}),\n }\n}\n\n/** The whole add-on set an intent asks for: `addons=` and the `ai` flag together. */\nexport function intentAddons(intent: Pick<OnboardingPlanIntent, 'ai' | 'addons'> | null | undefined): BundleAddons {\n return { ...(intent?.addons ?? {}), ...(intent?.ai ? { aiAddon: 1 } : {}) }\n}\n\n/**\n * The intent as query params — the one place the wire form is written\n * (AGL-1535).\n *\n * Every hop that re-serializes an intent (the signup landing, the auth-bounce\n * `continue`, the home jump) used to build this string by hand and append\n * `&interval=` unconditionally, which turned the parser's monthly DEFAULT into\n * a statement the next reader could not tell from the real thing.\n */\nexport function onboardingPlanQuery(intent: OnboardingPlanIntent): string {\n // `ai=1` stays the spelling when Aglyn AI is the only add-on, so the\n // published pricing CTAs and every hop between them read unchanged. Any\n // other add-on writes the whole set as `addons=` (AGL-3955), Aglyn AI with it.\n const addons: BundleAddons = { ...(intent.addons ?? {}) }\n if (intent.ai) addons.aiAddon = 1\n const others = Object.keys(addons).some(\n (kind) => kind !== 'aiAddon' && (addons[kind as keyof BundleAddons] ?? 0) > 0,\n )\n const coupon = normalizeBundleCoupon(intent.coupon)\n return (\n `plan=${encodeURIComponent(intent.plan)}` +\n (intent.intervalStated ? `&interval=${intent.interval}` : '') +\n (others\n ? // Fixed tokens, letters, digits, `:` and `,` only, so the link stays\n // readable when it is read aloud or typed off a QR's caption.\n `&addons=${bundleAddonsParam(addons, intent.aiTier)}`\n : addons.aiAddon\n ? `&ai=${intent.aiTier ?? '1'}`\n : '') +\n (coupon ? `&coupon=${encodeURIComponent(coupon)}` : '')\n )\n}\n\n/**\n * The signup URL a marketing CTA should carry — the WRITER half of the\n * contract above (AGL-1989).\n *\n * The contract had a parser and a re-serializer but nothing that produced a\n * link in the first place, so every published CTA was hand-typed. That is how\n * `/pricing` came to have six CTAs carrying `interval=` and three carrying\n * none: the \"Need more scale?\" strip quotes Scale, Advanced and Agency at both\n * cadences and its CHOOSE links say only `?plan=scale`, so a visitor who had\n * just picked Annual arrived pre-selected for a MONTHLY plan and silently lost\n * the annual discount they were shown. Nothing could have caught it, because\n * the string that should have been published existed nowhere a check could\n * read it.\n *\n * `interval: null` is a real and different thing from `'month'`: it means the\n * CTA does not commit to a cadence, which the billing page honours by leaving\n * an annual org on annual (`intervalStated`). Callers with a cadence to state\n * must state it.\n *\n * The marketing site is authored content, not code, so this does not publish\n * anything — it is what the authoring input quotes, so the person clicking the\n * link into the besigner pastes a string this contract's own parser agrees\n * with rather than one they typed.\n */\nexport function onboardingSignupHref(\n signupUrl: string,\n plan: OrgPlan,\n interval: OnboardingInterval | null,\n options: { ai?: boolean; aiTier?: AiTierId } = {},\n): string {\n const contactSales = isCustomPricedPlan(plan)\n // A custom-priced plan is quoted, not bought, so `parseOnboardingPlanIntent`\n // reports `intervalStated: false` for it HOWEVER the link is written. Writing\n // `?plan=enterprise&interval=year` anyway puts a claim on the wire that no\n // reader honours — and before AGL-1864 fixed the reader, that exact link\n // flipped an annual org to monthly on arrival. Drop it at the source, which\n // is the last place it can be dropped before it is published.\n const stated = interval != null && contactSales === false\n return `${signupUrl}?${onboardingPlanQuery({\n plan,\n interval: stated ? interval : 'month',\n intervalStated: stated,\n contactSales,\n // The add-on CTA (AGL-2897). Dropped for a custom-priced plan for the\n // same reason the interval is: the parser refuses it there, so writing\n // it would publish a claim no reader honors.\n ...((options.ai || options.aiTier) && !contactSales ? { ai: true } : {}),\n ...(options.aiTier && !contactSales ? { aiTier: options.aiTier } : {}),\n })}`\n}\n\n/**\n * Where a freshly provisioned workspace should land, given the plan the\n * visitor picked on the marketing site.\n *\n * Deliberately returns a path rather than pushing: signup owns the\n * navigation, and a pure function is the half worth testing.\n */\nexport function onboardingDestination(\n orgSlug: string,\n intent: OnboardingPlanIntent | null,\n): string {\n if (!orgSlug) return '/'\n if (!intent) return `/${orgSlug}`\n // Enterprise is a conversation, not a checkout (AGL-1110).\n if (intent.contactSales) return `/${orgSlug}/support?topic=enterprise`\n return `/${orgSlug}/billing?${onboardingPlanQuery(intent)}`\n}\n"],"names":["bundleAddonsParam","hasBundleAddons","normalizeBundleCoupon","parseBundleAddons","isAiTierId","isCustomPricedPlan","SELF_SERVE_PLANS","parseOnboardingPlanIntent","params","parsedAddons","read","key","Array","raw","URLSearchParams","get","String","isArray","trim","toLowerCase","plan","interval","intervalStated","contactSales","includes","known","ai","rawParam","addons","coupon","aiTier","aiStated","aiAddon","dropped","length","droppedAddons","intentAddons","intent","onboardingPlanQuery","others","Object","keys","some","kind","encodeURIComponent","onboardingSignupHref","signupUrl","options","stated","onboardingDestination","orgSlug"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,iBAAiB,EACjBC,eAAe,EACfC,qBAAqB,EACrBC,iBAAiB,QAEZ,qBAAiB;AACxB,SAASC,UAAU,EAAEC,kBAAkB,QAAQ,yBAAqB;AAmFpE,MAAMC,mBAAuC;IAC3C;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;;;;;CAOC,GACD,OAAO,SAASC,0BACdC,MAIa;QAyCyBC;IAvCtC,IAAI,CAACD,QAAQ,OAAO;IACpB,MAAME,OAAO,CAACC;YAMGC;QALf,MAAMC,MACJL,kBAAkBM,kBAAkBN,OAAOO,GAAG,CAACJ,OAAOH,MAAM,CAACG,IAAI;QACnE,yEAAyE;QACzE,wEAAwE;QACxE,8DAA8D;QAC9D,OAAOK,QAAQJ,OAAAA,MAAMK,OAAO,CAACJ,OAAOA,GAAG,CAAC,EAAE,GAAGA,eAA9BD,OAAsC,IAClDM,IAAI,GACJC,WAAW;IAChB;IACA,MAAMC,OAAOV,KAAK;IAClB,IAAI,CAACU,MAAM,OAAO;IAClB,IAAIf,mBAAmBe,OAAkB;QACvC,OAAO;YACLA,MAAMA;YACNC,UAAU;YACVC,gBAAgB;YAChBC,cAAc;QAChB;IACF;IACA,IAAI,CAACjB,iBAAiBkB,QAAQ,CAACJ,OAAkB,OAAO;IACxD,MAAMC,WAAWX,KAAK;IACtB,MAAMe,QAAQJ,aAAa,UAAUA,aAAa,YAAYA,aAAa;IAC3E,2EAA2E;IAC3E,2EAA2E;IAC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AoB;QACzClB;QACAC,UAAU2B,SAAS3B,WAAW;QAC9BC,gBAAgB0B;QAChBzB;OAII,AAACwB,CAAAA,QAAQrB,EAAE,IAAIqB,QAAQjB,MAAM,AAAD,KAAM,CAACP,eAAe;QAAEG,IAAI;IAAK,IAAI,CAAC,GAClEqB,QAAQjB,MAAM,IAAI,CAACP,eAAe;QAAEO,QAAQiB,QAAQjB,MAAM;IAAC,IAAI,CAAC,KAClE;AACN;AAEA;;;;;;CAMC,GACD,OAAO,SAASmB,sBACdC,OAAe,EACfb,MAAmC;IAEnC,IAAI,CAACa,SAAS,OAAO;IACrB,IAAI,CAACb,QAAQ,OAAO,CAAC,CAAC,EAAEa,SAAS;IACjC,2DAA2D;IAC3D,IAAIb,OAAOd,YAAY,EAAE,OAAO,CAAC,CAAC,EAAE2B,QAAQ,yBAAyB,CAAC;IACtE,OAAO,CAAC,CAAC,EAAEA,QAAQ,SAAS,EAAEZ,oBAAoBD,SAAS;AAC7D"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/onboarding-deep-link.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 type { OrgPlan } from '../foundation/definitions/org-billing.types'\nimport {\n bundleAddonsParam,\n hasBundleAddons,\n normalizeBundleCoupon,\n parseBundleAddons,\n type BundleAddons,\n} from './bundle-intent'\nimport { AI_CREDIT_BLOCKS_MAX } from './ai-credit-blocks'\nimport { isCustomPricedPlan, SELF_SERVE_PLANS } from './plan-entitlements'\n\n/**\n * The marketing → console onboarding deep link (AGL-1117).\n *\n * `app.aglyn.com/signup?plan=pro&interval=year`, optionally `&ai=1` for the\n * Aglyn AI add-on (AGL-2897), or `&ai=<tier>` (`&ai=boost`) for a named\n * Aglyn AI tier (AGL-3965). The bundle checkout link (AGL-3955) adds\n * `&addons=siteCare,ai:boost,extraHost:2` for any add-on the plan sells and\n * `&coupon=<code>` for a promotion code to apply at checkout.\n *\n * This is a CONTRACT with a site we do not control and cannot deploy in\n * lockstep with. So it is parsed defensively and in one place: the pricing\n * page will eventually be edited by someone who has never read this file, and\n * a typo in a CTA must degrade to ordinary signup rather than break it or —\n * far worse — silently start someone on the wrong plan.\n */\nexport type OnboardingInterval = 'month' | 'year'\n\nexport interface OnboardingPlanIntent {\n plan: OrgPlan\n interval: OnboardingInterval\n /**\n * Whether the link ACTUALLY said an interval, as opposed to `interval`\n * being the safe default below (AGL-1535).\n *\n * Some CTAs carry a plan and deliberately no interval — the /pricing scale\n * strip quotes monthly and annual side by side and commits to neither. The\n * billing page honours that (it only lets a *stated* interval move the\n * toggle, so an annual org is not silently flipped to monthly on arrival),\n * but every hop between the CTA and that page used to re-serialize the\n * intent with `&interval=month` appended — which made the omission\n * unrecoverable one redirect after it was made. Carrying the distinction is\n * what keeps \"no interval stated\" a thing the last reader can still see.\n */\n intervalStated: boolean\n /**\n * Enterprise is quoted, not bought. The CTA still carries `plan=enterprise`\n * because that is what the visitor clicked, and the console has to route\n * them to contact-sales rather than to a checkout that cannot price it\n * (AGL-1110).\n */\n contactSales: boolean\n /**\n * The Aglyn AI add-on, asked for alongside the plan (AGL-2897):\n * `?plan=pro&interval=month&ai=1`. Since AGL-4144 it is credits by the\n * block: `ai=1` (or `yes`, `true`) asks for one block, `ai=3` for three,\n * written into `addons.aiAddon`; a retired tier name asks for nothing.\n *\n * Present only when the link said so, and only ever `true` — the add-on\n * rides the plan checkout as a second subscription item, so a flag that\n * was never stated must not be told apart from one that was set to false\n * by every hop that re-serializes the intent. Enterprise never carries it:\n * the add-on is quoted with the deal, not bought through a checkout.\n */\n ai?: true\n /**\n * Every add-on the `addons=` param preselects (AGL-3955), parsed by the\n * shared `parseBundleAddons`. Absent when it named none. `ai=1` stays the\n * `ai` flag above; an `ai` token here sets that flag too, so a reader that\n * wants the whole set reads both (`intentAddons`).\n * Whether the plan sells each one is the reader's question\n * (`fitBundleAddonsToPlan`), because the owner can pick another plan.\n */\n addons?: BundleAddons\n /**\n * A promotion code to apply at checkout (AGL-3955). Applied only: codes are\n * minted on the staff Coupons page. An invalid or expired one is dropped by\n * the Billing page with a notice, never an error page.\n */\n coupon?: string\n /**\n * Add-on tokens the link named that nothing understood, as written, so the\n * page can say in one line that they were left off.\n */\n droppedAddons?: string[]\n}\n\n/**\n * The plans a link may carry into checkout: every self-serve plan but Free\n * (see below). Derived since pricing v4 (AGL-4126), so a retired plan's old\n * link (`?plan=business`) carries no intent rather than quoting a plan that\n * is no longer sold.\n */\nconst PURCHASABLE_PLANS: readonly OrgPlan[] = SELF_SERVE_PLANS.filter(\n (plan) => plan !== 'free',\n)\n\n/**\n * Read a plan intent off the URL, or null when there isn't a usable one.\n *\n * Null for `free` on purpose: it is a real plan but not a purchase, so there\n * is nothing to carry into checkout and a new org already starts there.\n * Returning an intent for it would send someone to a billing page to buy\n * what they already have.\n */\nexport function parseOnboardingPlanIntent(\n params:\n | URLSearchParams\n | Record<string, string | string[] | undefined>\n | null\n | undefined,\n): OnboardingPlanIntent | null {\n if (!params) return null\n const read = (key: string): string => {\n const raw =\n params instanceof URLSearchParams ? params.get(key) : params[key]\n // Next gives `string[]` for a repeated param. Take the first rather than\n // joining, so `?plan=pro&plan=free` cannot become the string \"pro,free\"\n // and fall through to null — the first is what the CTA meant.\n return String((Array.isArray(raw) ? raw[0] : raw) ?? '')\n .trim()\n .toLowerCase()\n }\n const plan = read('plan')\n if (!plan) return null\n if (isCustomPricedPlan(plan as OrgPlan)) {\n return {\n plan: plan as OrgPlan,\n interval: 'month',\n intervalStated: false,\n contactSales: true,\n }\n }\n if (!PURCHASABLE_PLANS.includes(plan as OrgPlan)) return null\n const interval = read('interval')\n const known = interval === 'year' || interval === 'annual' || interval === 'month'\n // The add-on is opt-in by an explicit affirmative. Anything else — absent,\n // empty, `0`, `false`, a typo — is \"not asked for\": a checkout that adds a\n // paid item off a malformed link is the expensive direction to be wrong in.\n const ai = read('ai')\n // The bundle (AGL-3955). Read case-preserving: a coupon code is typed the\n // way Stripe stores it, and `read` lower-cases.\n const rawParam = (key: string): string => {\n const raw = params instanceof URLSearchParams ? params.get(key) : params[key]\n return String((Array.isArray(raw) ? raw[0] : raw) ?? '').trim()\n }\n const parsedAddons = parseBundleAddons(rawParam('addons'))\n const addons: BundleAddons = { ...parsedAddons.addons }\n const coupon = normalizeBundleCoupon(rawParam('coupon'))\n // `?ai=<blocks>` asks for that many credit blocks (AGL-4144), held to the\n // ceiling; `1`, `true` and `yes` ask for one. Anything else, a retired\n // tier name included, is not an affirmative.\n const aiBlocks = /^\\d+$/.test(ai) ? Math.min(AI_CREDIT_BLOCKS_MAX, Number(ai)) : 0\n const aiStated = ai === 'true' || ai === 'yes' || aiBlocks > 0\n if (aiBlocks > 1) addons.aiAddon = Math.max(addons.aiAddon ?? 0, aiBlocks)\n return {\n plan: plan as OrgPlan,\n // Anything unrecognized falls to monthly, never to yearly: guessing the\n // longer commitment from a malformed link is the expensive direction to\n // be wrong in.\n interval: interval === 'year' || interval === 'annual' ? 'year' : 'month',\n // A junk interval is not a stated one: `?interval=decade` means the link\n // is broken, and the reader should fall back to what it knows about the\n // org rather than be told \"monthly\" with a straight face.\n intervalStated: known,\n contactSales: false,\n ...(aiStated || addons.aiAddon ? { ai: true } : {}),\n ...(hasBundleAddons(addons) ? { addons } : {}),\n ...(coupon ? { coupon } : {}),\n ...(parsedAddons.dropped.length ? { droppedAddons: parsedAddons.dropped } : {}),\n }\n}\n\n/**\n * The whole add-on set an intent asks for: `addons=` and the `ai` flag\n * together. The flag means at least one credit block; a count in `addons`\n * says how many.\n */\nexport function intentAddons(intent: Pick<OnboardingPlanIntent, 'ai' | 'addons'> | null | undefined): BundleAddons {\n const addons: BundleAddons = { ...(intent?.addons ?? {}) }\n if (intent?.ai) addons.aiAddon = Math.max(1, addons.aiAddon ?? 0)\n return addons\n}\n\n/**\n * The intent as query params — the one place the wire form is written\n * (AGL-1535).\n *\n * Every hop that re-serializes an intent (the signup landing, the auth-bounce\n * `continue`, the home jump) used to build this string by hand and append\n * `&interval=` unconditionally, which turned the parser's monthly DEFAULT into\n * a statement the next reader could not tell from the real thing.\n */\nexport function onboardingPlanQuery(intent: OnboardingPlanIntent): string {\n // `ai=1` stays the spelling when one credit block is the only add-on, so\n // the published pricing CTAs and every hop between them read unchanged;\n // `ai=3` for three (AGL-4144). Any other add-on writes the whole set as\n // `addons=` (AGL-3955), Aglyn AI with it.\n const addons = intentAddons(intent)\n const others = Object.keys(addons).some(\n (kind) => kind !== 'aiAddon' && (addons[kind as keyof BundleAddons] ?? 0) > 0,\n )\n const coupon = normalizeBundleCoupon(intent.coupon)\n return (\n `plan=${encodeURIComponent(intent.plan)}` +\n (intent.intervalStated ? `&interval=${intent.interval}` : '') +\n (others\n ? // Fixed tokens, letters, digits, `:` and `,` only, so the link stays\n // readable when it is read aloud or typed off a QR's caption.\n `&addons=${bundleAddonsParam(addons)}`\n : addons.aiAddon\n ? `&ai=${addons.aiAddon}`\n : '') +\n (coupon ? `&coupon=${encodeURIComponent(coupon)}` : '')\n )\n}\n\n/**\n * The signup URL a marketing CTA should carry — the WRITER half of the\n * contract above (AGL-1989).\n *\n * The contract had a parser and a re-serializer but nothing that produced a\n * link in the first place, so every published CTA was hand-typed. That is how\n * `/pricing` came to have six CTAs carrying `interval=` and three carrying\n * none: the \"Need more scale?\" strip quotes Scale, Advanced and Agency at both\n * cadences and its CHOOSE links say only `?plan=scale`, so a visitor who had\n * just picked Annual arrived pre-selected for a MONTHLY plan and silently lost\n * the annual discount they were shown. Nothing could have caught it, because\n * the string that should have been published existed nowhere a check could\n * read it.\n *\n * `interval: null` is a real and different thing from `'month'`: it means the\n * CTA does not commit to a cadence, which the billing page honours by leaving\n * an annual org on annual (`intervalStated`). Callers with a cadence to state\n * must state it.\n *\n * The marketing site is authored content, not code, so this does not publish\n * anything — it is what the authoring input quotes, so the person clicking the\n * link into the besigner pastes a string this contract's own parser agrees\n * with rather than one they typed.\n */\nexport function onboardingSignupHref(\n signupUrl: string,\n plan: OrgPlan,\n interval: OnboardingInterval | null,\n options: { ai?: boolean; aiBlocks?: number } = {},\n): string {\n const contactSales = isCustomPricedPlan(plan)\n // A custom-priced plan is quoted, not bought, so `parseOnboardingPlanIntent`\n // reports `intervalStated: false` for it HOWEVER the link is written. Writing\n // `?plan=enterprise&interval=year` anyway puts a claim on the wire that no\n // reader honours — and before AGL-1864 fixed the reader, that exact link\n // flipped an annual org to monthly on arrival. Drop it at the source, which\n // is the last place it can be dropped before it is published.\n const stated = interval != null && contactSales === false\n return `${signupUrl}?${onboardingPlanQuery({\n plan,\n interval: stated ? interval : 'month',\n intervalStated: stated,\n contactSales,\n // The add-on CTA (AGL-2897). Dropped for a custom-priced plan for the\n // same reason the interval is: the parser refuses it there, so writing\n // it would publish a claim no reader honors.\n ...((options.ai || (options.aiBlocks ?? 0) > 0) && !contactSales ? { ai: true } : {}),\n ...((options.aiBlocks ?? 0) > 1 && !contactSales\n ? { addons: { aiAddon: Math.min(AI_CREDIT_BLOCKS_MAX, Math.floor(options.aiBlocks ?? 0)) } }\n : {}),\n })}`\n}\n\n/**\n * Where a freshly provisioned workspace should land, given the plan the\n * visitor picked on the marketing site.\n *\n * Deliberately returns a path rather than pushing: signup owns the\n * navigation, and a pure function is the half worth testing.\n */\nexport function onboardingDestination(\n orgSlug: string,\n intent: OnboardingPlanIntent | null,\n): string {\n if (!orgSlug) return '/'\n if (!intent) return `/${orgSlug}`\n // Enterprise is a conversation, not a checkout (AGL-1110).\n if (intent.contactSales) return `/${orgSlug}/support?topic=enterprise`\n return `/${orgSlug}/billing?${onboardingPlanQuery(intent)}`\n}\n"],"names":["bundleAddonsParam","hasBundleAddons","normalizeBundleCoupon","parseBundleAddons","AI_CREDIT_BLOCKS_MAX","isCustomPricedPlan","SELF_SERVE_PLANS","PURCHASABLE_PLANS","filter","plan","parseOnboardingPlanIntent","params","addons","read","key","Array","raw","URLSearchParams","get","String","isArray","trim","toLowerCase","interval","intervalStated","contactSales","includes","known","ai","rawParam","parsedAddons","coupon","aiBlocks","test","Math","min","Number","aiStated","aiAddon","max","dropped","length","droppedAddons","intentAddons","intent","onboardingPlanQuery","others","Object","keys","some","kind","encodeURIComponent","onboardingSignupHref","signupUrl","options","stated","floor","onboardingDestination","orgSlug"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,iBAAiB,EACjBC,eAAe,EACfC,qBAAqB,EACrBC,iBAAiB,QAEZ,qBAAiB;AACxB,SAASC,oBAAoB,QAAQ,wBAAoB;AACzD,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,yBAAqB;AA8E1E;;;;;CAKC,GACD,MAAMC,oBAAwCD,iBAAiBE,MAAM,CACnE,CAACC,OAASA,SAAS;AAGrB;;;;;;;CAOC,GACD,OAAO,SAASC,0BACdC,MAIa;QA4C+BC;IA1C5C,IAAI,CAACD,QAAQ,OAAO;IACpB,MAAME,OAAO,CAACC;YAMGC;QALf,MAAMC,MACJL,kBAAkBM,kBAAkBN,OAAOO,GAAG,CAACJ,OAAOH,MAAM,CAACG,IAAI;QACnE,yEAAyE;QACzE,wEAAwE;QACxE,8DAA8D;QAC9D,OAAOK,QAAQJ,OAAAA,MAAMK,OAAO,CAACJ,OAAOA,GAAG,CAAC,EAAE,GAAGA,eAA9BD,OAAsC,IAClDM,IAAI,GACJC,WAAW;IAChB;IACA,MAAMb,OAAOI,KAAK;IAClB,IAAI,CAACJ,MAAM,OAAO;IAClB,IAAIJ,mBAAmBI,OAAkB;QACvC,OAAO;YACLA,MAAMA;YACNc,UAAU;YACVC,gBAAgB;YAChBC,cAAc;QAChB;IACF;IACA,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A+C,CAAC,CAAC;QAkB3BA,mBACfA,oBAC8DA;IAlBrE,MAAM7B,eAAepB,mBAAmBI;IACxC,6EAA6E;IAC7E,8EAA8E;IAC9E,2EAA2E;IAC3E,yEAAyE;IACzE,4EAA4E;IAC5E,8DAA8D;IAC9D,MAAM8C,SAAShC,YAAY,QAAQE,iBAAiB;IACpD,OAAO,GAAG4B,UAAU,CAAC,EAAER,oBAAoB;QACzCpC;QACAc,UAAUgC,SAAShC,WAAW;QAC9BC,gBAAgB+B;QAChB9B;OAII,AAAC6B,CAAAA,QAAQ1B,EAAE,IAAI,EAAC0B,oBAAAA,QAAQtB,QAAQ,YAAhBsB,oBAAoB,KAAK,CAAA,KAAM,CAAC7B,eAAe;QAAEG,IAAI;IAAK,IAAI,CAAC,GAC/E,EAAC0B,qBAAAA,QAAQtB,QAAQ,YAAhBsB,qBAAoB,KAAK,KAAK,CAAC7B,eAChC;QAAEb,QAAQ;YAAE0B,SAASJ,KAAKC,GAAG,CAAC/B,sBAAsB8B,KAAKsB,KAAK,EAACF,qBAAAA,QAAQtB,QAAQ,YAAhBsB,qBAAoB;QAAI;IAAE,IACzF,CAAC,KACH;AACN;AAEA;;;;;;CAMC,GACD,OAAO,SAASG,sBACdC,OAAe,EACfd,MAAmC;IAEnC,IAAI,CAACc,SAAS,OAAO;IACrB,IAAI,CAACd,QAAQ,OAAO,CAAC,CAAC,EAAEc,SAAS;IACjC,2DAA2D;IAC3D,IAAId,OAAOnB,YAAY,EAAE,OAAO,CAAC,CAAC,EAAEiC,QAAQ,yBAAyB,CAAC;IACtE,OAAO,CAAC,CAAC,EAAEA,QAAQ,SAAS,EAAEb,oBAAoBD,SAAS;AAC7D"}
|
|
@@ -536,6 +536,23 @@ const DAY = 24 * 60;
|
|
|
536
536
|
dedupeWindowMinutes: 6 * 60,
|
|
537
537
|
defaultEnabled: true
|
|
538
538
|
},
|
|
539
|
+
{
|
|
540
|
+
// An abuse ceiling, not a fault (AGL-4145): every other workspace's mail
|
|
541
|
+
// is unaffected, and the one that reached it is refused only until
|
|
542
|
+
// 00:00 UTC. Told once per workspace per day; the refusal count is on
|
|
543
|
+
// `orgs/{orgId}/counters/transactionalEmailsRefused`.
|
|
544
|
+
type: 'deliverability.transactionalCeilingReached',
|
|
545
|
+
label: 'A workspace reached its daily transactional email ceiling',
|
|
546
|
+
description: 'A workspace’s sites sent as many transactional emails today as its abuse ceiling allows, so the rest of today’s are refused until 00:00 UTC. Security mail still sends. Find out whether it is real traffic: if it is, raise that workspace’s ceiling with an override; if it is not, lock it.',
|
|
547
|
+
tier: 'should',
|
|
548
|
+
category: 'deliverability',
|
|
549
|
+
title: '{{orgName}} reached its daily transactional email ceiling',
|
|
550
|
+
body: 'Workspace {{orgName}} ({{orgId}}) has sent {{used}} transactional emails today against a ceiling of {{ceiling}} a day, so further ones are refused until 00:00 UTC. The first refused came from {{context}}. Security mail still sends. If this is real traffic, raise the ceiling with an override on the organization; if it is not, lock it on Staff → Lockdown (/admin/lockdown).',
|
|
551
|
+
link: '/admin/orgs/{{orgId}}',
|
|
552
|
+
delivery: 'immediate',
|
|
553
|
+
dedupeWindowMinutes: DAY,
|
|
554
|
+
defaultEnabled: true
|
|
555
|
+
},
|
|
539
556
|
{
|
|
540
557
|
type: 'deliverability.gatewayBlocking',
|
|
541
558
|
label: 'A recipient gateway is blocking the shared domain',
|