@aglyn/tenant-data-admin 1.10.0 → 1.12.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.10.0",
3
+ "version": "1.12.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.10.0",
29
- "@aglyn/shared-util-email": "1.10.0",
30
- "@aglyn/shared-util-fbserver": "1.10.0",
31
- "@aglyn/shared-util-first-touch": "1.10.0",
32
- "@aglyn/shared-util-http": "1.10.0",
33
- "@aglyn/shared-util-tools": "1.10.0",
28
+ "@aglyn/aglyn": "1.12.0",
29
+ "@aglyn/shared-util-email": "1.12.0",
30
+ "@aglyn/shared-util-fbserver": "1.12.0",
31
+ "@aglyn/shared-util-first-touch": "1.12.0",
32
+ "@aglyn/shared-util-http": "1.12.0",
33
+ "@aglyn/shared-util-tools": "1.12.0",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -27,6 +27,11 @@
27
27
  * the subscription goes live, the proposal and the trial comp both clear,
28
28
  * so a comp granted to evaluate cannot revive free access if the customer
29
29
  * later cancels.
30
+ *
31
+ * A workspace that already subscribes can be proposed a CHANGE (AGL-4160):
32
+ * another plan or billing cadence, usually with a code for the switch. That
33
+ * proposal is marked `forSubscriber` and settled only when the subscription
34
+ * moves to it, since a subscription being live is what it starts from.
30
35
  */
31
36
  import type { AglynOrgBilling, OrgUpgradeProposal } from '@aglyn/aglyn/server';
32
37
  /** The override reason a sales-evaluation comp is granted under. */
@@ -74,9 +79,10 @@ export interface ProposeOrgUpgradeResult {
74
79
  * commit and is best-effort: the card on the org home is the proposal, and
75
80
  * an email that failed must not undo it.
76
81
  *
77
- * Refused when the workspace already has a live subscription — the question
78
- * a proposal asks is already answered — and for any plan a customer cannot
79
- * buy themselves.
82
+ * Refused for any plan a customer cannot buy themselves. A workspace with a
83
+ * live subscription can be proposed a change of plan or cadence (AGL-4160),
84
+ * stored as `forSubscriber`; a proposal of the plan and cadence it already
85
+ * has is refused, since there is nothing to propose.
80
86
  */
81
87
  export declare function proposeOrgUpgrade(options: ProposeOrgUpgradeOptions): Promise<ProposeOrgUpgradeResult>;
82
88
  /**
@@ -90,9 +96,20 @@ export declare function buildUpgradeProposal(options: Pick<ProposeOrgUpgradeOpti
90
96
  /**
91
97
  * Read the org a proposal is for, inside the caller's transaction, refusing
92
98
  * an unknown workspace and one whose subscription is already live — the
93
- * question a proposal asks is then already answered.
99
+ * question a proposal asks is then already answered. The owner hand-off,
100
+ * which proposes a first plan, reads through this.
94
101
  */
95
102
  export declare function readUpgradeProposalTarget(tx: FirebaseFirestore.Transaction, orgRef: FirebaseFirestore.DocumentReference): Promise<Partial<AglynOrgBilling>>;
103
+ /**
104
+ * Read the org a proposal is for, and whether its subscription is live
105
+ * (AGL-4160). A live subscription takes a proposal that CHANGES it — another
106
+ * plan, or the cadence it is not billed on — and refuses one it already
107
+ * answers, or no proposal at all.
108
+ */
109
+ export declare function readUpgradeProposalChange(tx: FirebaseFirestore.Transaction, orgRef: FirebaseFirestore.DocumentReference, proposal: Pick<OrgUpgradeProposal, 'plan' | 'interval'> | null): Promise<{
110
+ data: Partial<AglynOrgBilling>;
111
+ live: boolean;
112
+ }>;
96
113
  /**
97
114
  * Write the proposal and its audit row into the caller's transaction, so
98
115
  * they commit with whatever else the caller writes (AGL-1784) — the owner
@@ -136,6 +153,13 @@ export declare function withdrawOrgUpgrade(options: {
136
153
  export declare function settleSubscriptionStart(orgId: string, context: {
137
154
  status: string;
138
155
  subscriptionId?: string | null;
156
+ /**
157
+ * The plan and cadence the live subscription is on (AGL-4160). A
158
+ * proposal made to a subscriber is settled only by the subscription
159
+ * reaching it; absent, the org doc's `plan` stands in for the plan.
160
+ */
161
+ plan?: string | null;
162
+ interval?: string | null;
139
163
  }): Promise<{
140
164
  proposalCleared: boolean;
141
165
  trialCompRemoved: boolean;
@@ -26,10 +26,15 @@
26
26
  * the subscription goes live, the proposal and the trial comp both clear,
27
27
  * so a comp granted to evaluate cannot revive free access if the customer
28
28
  * later cancels.
29
+ *
30
+ * A workspace that already subscribes can be proposed a CHANGE (AGL-4160):
31
+ * another plan or billing cadence, usually with a code for the switch. That
32
+ * proposal is marked `forSubscriber` and settled only when the subscription
33
+ * moves to it, since a subscription being live is what it starts from.
29
34
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
30
35
  import { PLAN_LABELS } from "@aglyn/aglyn/app-utils/plan-entitlements";
31
36
  import { PLATFORM_BRAND_NAME } from "@aglyn/aglyn/app-utils/platform-brand";
32
- import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, normalizeUpgradeProposalNote, upgradeProposalDestination, upgradeProposalSummary } from "@aglyn/aglyn/app-utils/upgrade-proposal";
37
+ import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, normalizeUpgradeProposalNote, upgradeProposalAnsweredBy, upgradeProposalDestination, upgradeProposalSummary } from "@aglyn/aglyn/app-utils/upgrade-proposal";
33
38
  // Leaf modules, as `organizations.ts` imports its constants (AGL-1289).
34
39
  import { isLiveSubscriptionStatus, ORG_BILLING_DOC_ID, ORG_BILLING_SUBCOLLECTION } from "@aglyn/aglyn/app-utils/org-billing-doc";
35
40
  import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
@@ -56,23 +61,30 @@ const firestore = ()=>firebaseAdmin.app().firestore();
56
61
  * commit and is best-effort: the card on the org home is the proposal, and
57
62
  * an email that failed must not undo it.
58
63
  *
59
- * Refused when the workspace already has a live subscription — the question
60
- * a proposal asks is already answered — and for any plan a customer cannot
61
- * buy themselves.
64
+ * Refused for any plan a customer cannot buy themselves. A workspace with a
65
+ * live subscription can be proposed a change of plan or cadence (AGL-4160),
66
+ * stored as `forSubscriber`; a proposal of the plan and cadence it already
67
+ * has is refused, since there is nothing to propose.
62
68
  */ export async function proposeOrgUpgrade(options) {
63
69
  const { orgId, actor, origin } = options;
64
- const proposal = buildUpgradeProposal(options);
70
+ const built = buildUpgradeProposal(options);
65
71
  const db = firestore();
66
72
  const orgRef = db.collection('orgs').doc(orgId);
67
- const org = await db.runTransaction(async (tx)=>{
68
- const data = await readUpgradeProposalTarget(tx, orgRef);
73
+ const { org, proposal } = await db.runTransaction(async (tx)=>{
74
+ const target = await readUpgradeProposalChange(tx, orgRef, built);
75
+ const staged = target.live ? _extends({}, built, {
76
+ forSubscriber: true
77
+ }) : built;
69
78
  stageUpgradeProposal(tx, db, {
70
79
  orgId,
71
- proposal,
72
- before: data,
80
+ proposal: staged,
81
+ before: target.data,
73
82
  actorUid: actor.uid
74
83
  });
75
- return data;
84
+ return {
85
+ org: target.data,
86
+ proposal: staged
87
+ };
76
88
  });
77
89
  await recordUpgradeProposalActivity(orgId, actor, proposal);
78
90
  const emailed = await emailUpgradeProposal({
@@ -111,19 +123,43 @@ const firestore = ()=>firebaseAdmin.app().firestore();
111
123
  /**
112
124
  * Read the org a proposal is for, inside the caller's transaction, refusing
113
125
  * an unknown workspace and one whose subscription is already live — the
114
- * question a proposal asks is then already answered.
126
+ * question a proposal asks is then already answered. The owner hand-off,
127
+ * which proposes a first plan, reads through this.
115
128
  */ export async function readUpgradeProposalTarget(tx, orgRef) {
129
+ const target = await readUpgradeProposalChange(tx, orgRef, null);
130
+ return target.data;
131
+ }
132
+ /**
133
+ * Read the org a proposal is for, and whether its subscription is live
134
+ * (AGL-4160). A live subscription takes a proposal that CHANGES it — another
135
+ * plan, or the cadence it is not billed on — and refuses one it already
136
+ * answers, or no proposal at all.
137
+ */ export async function readUpgradeProposalChange(tx, orgRef, proposal) {
116
138
  var _ref;
117
- var _billing_get;
118
139
  const snapshot = await tx.get(orgRef);
119
140
  if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404);
120
141
  const data = snapshot.data();
121
142
  const billing = await tx.get(orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID));
122
- const status = (_ref = (_billing_get = billing.get('subscription')) == null ? void 0 : _billing_get.status) != null ? _ref : data.billingStatus;
123
- if (isLiveSubscriptionStatus(status)) {
143
+ const subscription = billing.get('subscription');
144
+ const status = (_ref = subscription == null ? void 0 : subscription.status) != null ? _ref : data.billingStatus;
145
+ if (!isLiveSubscriptionStatus(status)) return {
146
+ data,
147
+ live: false
148
+ };
149
+ if (!proposal) {
124
150
  throw new UpgradeProposalError('This workspace already has a live subscription, so there is nothing to propose', 409);
125
151
  }
126
- return data;
152
+ if (upgradeProposalAnsweredBy(proposal, {
153
+ plan: data.plan,
154
+ interval: subscription == null ? void 0 : subscription.interval
155
+ })) {
156
+ const cadence = (subscription == null ? void 0 : subscription.interval) === 'year' ? ', billed yearly' : (subscription == null ? void 0 : subscription.interval) === 'month' ? ', billed monthly' : '';
157
+ throw new UpgradeProposalError(`This workspace already subscribes to ${planName(data.plan)}${cadence}, so there is ` + 'nothing to propose. Propose another plan or billing cadence.', 409);
158
+ }
159
+ return {
160
+ data,
161
+ live: true
162
+ };
127
163
  }
128
164
  /**
129
165
  * Write the proposal and its audit row into the caller's transaction, so
@@ -227,11 +263,17 @@ const firestore = ()=>firebaseAdmin.app().firestore();
227
263
  const db = firestore();
228
264
  const orgRef = db.collection('orgs').doc(orgId);
229
265
  const outcome = await db.runTransaction(async (tx)=>{
230
- var _data_upgradeProposal, _data_entitlements;
266
+ var _data_upgradeProposal, _context_plan, _data_entitlements;
231
267
  const snapshot = await tx.get(orgRef);
232
268
  if (!snapshot.exists) return null;
233
269
  const data = snapshot.data();
234
- const proposal = (_data_upgradeProposal = data.upgradeProposal) != null ? _data_upgradeProposal : null;
270
+ const stored = (_data_upgradeProposal = data.upgradeProposal) != null ? _data_upgradeProposal : null;
271
+ // A change proposed to a subscriber stands until the subscription is on
272
+ // it: being live is where it started, so it settles nothing.
273
+ const proposal = (stored == null ? void 0 : stored.forSubscriber) === true && !upgradeProposalAnsweredBy(stored, {
274
+ plan: (_context_plan = context.plan) != null ? _context_plan : data.plan,
275
+ interval: context.interval
276
+ }) ? null : stored;
235
277
  const entitlements = (_data_entitlements = data.entitlements) != null ? _data_entitlements : null;
236
278
  const comp = entitlements == null ? void 0 : entitlements['planComp'];
237
279
  const trialComp = (comp == null ? void 0 : comp.reason) === TRIAL_PLAN_COMP_REASON ? comp : null;
@@ -258,7 +300,7 @@ const firestore = ()=>firebaseAdmin.app().firestore();
258
300
  target: `orgs/${orgId}`,
259
301
  reason: {
260
302
  code: 'subscription_live',
261
- note: `The subscription went live (${context.status})` + (context.subscriptionId ? `, ${context.subscriptionId}` : '') + ', which settles the upgrade proposal and ends the sales-trial comp.'
303
+ note: ((proposal == null ? void 0 : proposal.forSubscriber) ? `The subscription moved to the proposed plan (${context.status})` : `The subscription went live (${context.status})`) + (context.subscriptionId ? `, ${context.subscriptionId}` : '') + ', which settles the upgrade proposal and ends the sales-trial comp.'
262
304
  },
263
305
  before: {
264
306
  upgradeProposal: proposal,
@@ -285,7 +327,7 @@ const firestore = ()=>firebaseAdmin.app().firestore();
285
327
  if (outcome.proposal) {
286
328
  await logOrgActivity(orgId, {
287
329
  uid: null
288
- }, `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`, {
330
+ }, `The ${planName(outcome.proposal.plan)} plan proposal closed — ` + (outcome.proposal.forSubscriber ? 'the subscription moved to it' : 'the subscription is live'), {
289
331
  type: 'subscription',
290
332
  id: orgId
291
333
  });
@@ -322,15 +364,21 @@ const firestore = ()=>firebaseAdmin.app().firestore();
322
364
  const summary = upgradeProposalSummary(proposal, {
323
365
  brand: productName
324
366
  });
367
+ // A workspace that already subscribes switches; one that does not starts
368
+ // a subscription (AGL-4160).
369
+ const nextStep = proposal.forSubscriber ? 'When you are ready, switch to it from Billing. The plan is already selected ' + 'there, and Billing shows what the switch costs today, with any code applied, ' + 'before anything is charged.' : 'When you are ready, start the subscription from Billing. The plan is already ' + 'selected there, beside the others so you can compare them first.';
370
+ const unchanged = proposal.forSubscriber ? 'Nothing changes until you switch.' : 'Nothing changes until you start the subscription.';
325
371
  const content = await renderSystemEmailContent('org-upgrade-proposal', {
326
372
  'org.name': orgName,
327
373
  'plan.name': label,
328
374
  'proposal.note': (_proposal_note = proposal.note) != null ? _proposal_note : '',
329
375
  'proposal.summary': summary === label ? '' : summary,
376
+ 'proposal.nextStep': nextStep,
377
+ 'proposal.unchanged': unchanged,
330
378
  billingUrl
331
379
  }, brand, {
332
380
  subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,
333
- text: `Your ${productName} team proposed moving ${orgName} to the ${label} ` + (summary === label ? 'plan. ' : `plan (${summary}). `) + 'When you are ready, start the subscription from Billing, ' + `where the plan is already selected:\n\n${billingUrl}` + (proposal.note ? `\n\n${proposal.note}` : '')
381
+ text: `Your ${productName} team proposed moving ${orgName} to the ${label} ` + (summary === label ? 'plan. ' : `plan (${summary}). `) + (proposal.forSubscriber ? 'When you are ready, switch to it from Billing, ' : 'When you are ready, start the subscription from Billing, ') + `where the plan is already selected:\n\n${billingUrl}` + (proposal.note ? `\n\n${proposal.note}` : '')
334
382
  });
335
383
  const result = await sendEmail(_extends({
336
384
  to,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * A retired Aglyn AI tier (AGL-4025). Credits are sold by the block since\n * AGL-4144 (`ai:<blocks>` in `addons`), so a proposal naming a tier is\n * refused rather than stored with a price nobody sells.\n */\n aiTier?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused when the workspace already has a live subscription — the question\n * a proposal asks is already answered — and for any plan a customer cannot\n * buy themselves.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const proposal = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const org = await db.runTransaction(async (tx) => {\n const data = await readUpgradeProposalTarget(tx, orgRef)\n stageUpgradeProposal(tx, db, { orgId, proposal, before: data, actorUid: actor.uid })\n return data\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<\n ProposeOrgUpgradeOptions,\n 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'aiTier' | 'actor'\n > & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n if (options.aiTier != null) {\n throw new UpgradeProposalError(\n 'AI tiers were replaced by AI credit blocks. Propose a number of blocks instead.',\n )\n }\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const status =\n (billing.get('subscription') as { status?: unknown } | undefined)?.status ??\n data.billingStatus\n if (isLiveSubscriptionStatus(status)) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n return data\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: { status: string; subscriptionId?: string | null },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const proposal = data.upgradeProposal ?? null\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n `The subscription went live (${context.status})` +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n 'When you are ready, start the subscription from Billing, ' +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","proposal","buildUpgradeProposal","db","orgRef","collection","doc","org","runTransaction","tx","data","readUpgradeProposalTarget","stageUpgradeProposal","before","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","aiTier","note","proposedBy","proposedAt","now","Date","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","target","after","at","proposalActivityLine","label","planName","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,sBAAsB,QACjB,0CAAyC;AAChD,wEAAwE;AACxE,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAC/C,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,2BAAuB;AAE9B,MAAMC,YAAY,IAAMJ,cAAcK,GAAG,GAAGD,SAAS;AAErD,kEAAkE,GAClE,OAAO,MAAME,yBAAyB,QAAO;AAE7C,oDAAoD,GACpD,OAAO,MAAMC,6BAA6BC;IAExC,YAAYC,OAAe,EAAEC,SAAS,GAAG,CAAE;QACzC,KAAK,CAACD;QACN,IAAI,CAACE,IAAI,GAAG;QACZ,IAAI,CAACD,MAAM,GAAGA;IAChB;AACF;AA+BA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeE,kBACpBC,OAAiC;IAEjC,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAE,GAAGH;IACjC,MAAMI,WAAWC,qBAAqBL;IACtC,MAAMM,KAAKf;IACX,MAAMgB,SAASD,GAAGE,UAAU,CAAC,QAAQ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AAE,GAAG,EAAC;QAC/C;QAEF,MAAM2D,SAAS,MAAMpG,UAAU;YAC7B2F;YACAO,SAASD,QAAQC,OAAO;YACxBC,MAAMF,QAAQE,IAAI;WACdF,QAAQI,IAAI,GAAG;YAAEA,MAAMJ,QAAQI,IAAI;QAAC,IAAI,CAAC,GACzCT,MAAMU,QAAQ,GAAG;YAAEA,UAAUV,MAAMU,QAAQ;QAAC,IAAI,CAAC;YACrD7B,SAAS;;QAEX,IAAI2B,OAAOG,IAAI,EAAE,MAAMpG,cAAce;QACrC,OAAOkF,OAAOG,IAAI;IACpB,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;QACvD,OAAO;IACT;AACF;AAEA,SAAS1C,SAASvB,IAAa;IAC7B,OAAO,OAAOA,SAAS,YAAYA,QAAQlD,cACvCA,WAAW,CAACkD,KAAgB,GAC5BmE,OAAOnE,eAAAA,OAAQ;AACrB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n *\n * A workspace that already subscribes can be proposed a CHANGE (AGL-4160):\n * another plan or billing cadence, usually with a code for the switch. That\n * proposal is marked `forSubscriber` and settled only when the subscription\n * moves to it, since a subscription being live is what it starts from.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalAnsweredBy,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * A retired Aglyn AI tier (AGL-4025). Credits are sold by the block since\n * AGL-4144 (`ai:<blocks>` in `addons`), so a proposal naming a tier is\n * refused rather than stored with a price nobody sells.\n */\n aiTier?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused for any plan a customer cannot buy themselves. A workspace with a\n * live subscription can be proposed a change of plan or cadence (AGL-4160),\n * stored as `forSubscriber`; a proposal of the plan and cadence it already\n * has is refused, since there is nothing to propose.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const built = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const { org, proposal } = await db.runTransaction(async (tx) => {\n const target = await readUpgradeProposalChange(tx, orgRef, built)\n const staged: OrgUpgradeProposal = target.live ? { ...built, forSubscriber: true } : built\n stageUpgradeProposal(tx, db, {\n orgId,\n proposal: staged,\n before: target.data,\n actorUid: actor.uid,\n })\n return { org: target.data, proposal: staged }\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<\n ProposeOrgUpgradeOptions,\n 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'aiTier' | 'actor'\n > & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n if (options.aiTier != null) {\n throw new UpgradeProposalError(\n 'AI tiers were replaced by AI credit blocks. Propose a number of blocks instead.',\n )\n }\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered. The owner hand-off,\n * which proposes a first plan, reads through this.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const target = await readUpgradeProposalChange(tx, orgRef, null)\n return target.data\n}\n\n/**\n * Read the org a proposal is for, and whether its subscription is live\n * (AGL-4160). A live subscription takes a proposal that CHANGES it — another\n * plan, or the cadence it is not billed on — and refuses one it already\n * answers, or no proposal at all.\n */\nexport async function readUpgradeProposalChange(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n proposal: Pick<OrgUpgradeProposal, 'plan' | 'interval'> | null,\n): Promise<{ data: Partial<AglynOrgBilling>; live: boolean }> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const subscription = billing.get('subscription') as\n | { status?: unknown; interval?: unknown }\n | undefined\n const status = subscription?.status ?? data.billingStatus\n if (!isLiveSubscriptionStatus(status)) return { data, live: false }\n if (!proposal) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n if (upgradeProposalAnsweredBy(proposal, { plan: data.plan, interval: subscription?.interval })) {\n const cadence =\n subscription?.interval === 'year'\n ? ', billed yearly'\n : subscription?.interval === 'month'\n ? ', billed monthly'\n : ''\n throw new UpgradeProposalError(\n `This workspace already subscribes to ${planName(data.plan)}${cadence}, so there is ` +\n 'nothing to propose. Propose another plan or billing cadence.',\n 409,\n )\n }\n return { data, live: true }\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: {\n status: string\n subscriptionId?: string | null\n /**\n * The plan and cadence the live subscription is on (AGL-4160). A\n * proposal made to a subscriber is settled only by the subscription\n * reaching it; absent, the org doc's `plan` stands in for the plan.\n */\n plan?: string | null\n interval?: string | null\n },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const stored = data.upgradeProposal ?? null\n // A change proposed to a subscriber stands until the subscription is on\n // it: being live is where it started, so it settles nothing.\n const proposal =\n stored?.forSubscriber === true &&\n !upgradeProposalAnsweredBy(stored, {\n plan: context.plan ?? data.plan,\n interval: context.interval,\n })\n ? null\n : stored\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n (proposal?.forSubscriber\n ? `The subscription moved to the proposed plan (${context.status})`\n : `The subscription went live (${context.status})`) +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — ` +\n (outcome.proposal.forSubscriber\n ? 'the subscription moved to it'\n : 'the subscription is live'),\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n // A workspace that already subscribes switches; one that does not starts\n // a subscription (AGL-4160).\n const nextStep = proposal.forSubscriber\n ? 'When you are ready, switch to it from Billing. The plan is already selected ' +\n 'there, and Billing shows what the switch costs today, with any code applied, ' +\n 'before anything is charged.'\n : 'When you are ready, start the subscription from Billing. The plan is already ' +\n 'selected there, beside the others so you can compare them first.'\n const unchanged = proposal.forSubscriber\n ? 'Nothing changes until you switch.'\n : 'Nothing changes until you start the subscription.'\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n 'proposal.nextStep': nextStep,\n 'proposal.unchanged': unchanged,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n (proposal.forSubscriber\n ? 'When you are ready, switch to it from Billing, '\n : 'When you are ready, start the subscription from Billing, ') +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalAnsweredBy","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","built","buildUpgradeProposal","db","orgRef","collection","doc","org","proposal","runTransaction","tx","target","readUpgradeProposalChange","staged","live","forSubscriber","stageUpgradeProposal","before","data","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","aiTier","note","proposedBy","proposedAt","now","Date","readUpgradeProposalTarget","snapshot","get","exists","billing","subscription","billingStatus","interval","cadence","planName","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","after","at","proposalActivityLine","label","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","nextStep","unchanged","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;CAkBC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,yBAAyB,EACzBC,0BAA0B,EAC1BC,sBAAsB,QACjB,0CAAyC;AAChD,wEAAwE;AACxE,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAC/C,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,2BAAuB;AAE9B,MAAMC,YAAY,IAAMJ,cAAcK,GAAG,GAAGD,SAAS;AAErD,kEAAkE,GAClE,OAAO,MAAME,yBAAyB,QAAO;AAE7C,oDAAoD,GACpD,OAAO,MAAMC,6BAA6BC;IAExC,YAAYC,OAAe,EAAEC,SAAS,GAAG,CAAE;QACzC,KAAK,CAACD;QACN,IAAI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