@aglyn/tenant-data-admin 1.0.0-beta.270 → 1.0.0-beta.272

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.
Files changed (58) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/append-only-history-write.d.ts +38 -0
  3. package/src/lib/server/append-only-history-write.js +60 -0
  4. package/src/lib/server/append-only-history-write.js.map +1 -0
  5. package/src/lib/server/billing-addons.d.ts +58 -32
  6. package/src/lib/server/billing-addons.js +100 -86
  7. package/src/lib/server/billing-addons.js.map +1 -1
  8. package/src/lib/server/bundle-links.d.ts +166 -0
  9. package/src/lib/server/bundle-links.js +286 -0
  10. package/src/lib/server/bundle-links.js.map +1 -0
  11. package/src/lib/server/client-build.d.ts +74 -0
  12. package/src/lib/server/client-build.js +264 -0
  13. package/src/lib/server/client-build.js.map +1 -0
  14. package/src/lib/server/domain-ownership.d.ts +205 -0
  15. package/src/lib/server/domain-ownership.js +575 -0
  16. package/src/lib/server/domain-ownership.js.map +1 -0
  17. package/src/lib/server/erase.d.ts +17 -0
  18. package/src/lib/server/erase.js +21 -0
  19. package/src/lib/server/erase.js.map +1 -1
  20. package/src/lib/server/host-memberships.d.ts +35 -2
  21. package/src/lib/server/host-memberships.js +63 -2
  22. package/src/lib/server/host-memberships.js.map +1 -1
  23. package/src/lib/server/org-billing.d.ts +4 -2
  24. package/src/lib/server/org-billing.js +5 -0
  25. package/src/lib/server/org-billing.js.map +1 -1
  26. package/src/lib/server/site-care-emails.d.ts +53 -0
  27. package/src/lib/server/site-care-emails.js +97 -0
  28. package/src/lib/server/site-care-emails.js.map +1 -0
  29. package/src/lib/server/site-care-inbound.d.ts +123 -0
  30. package/src/lib/server/site-care-inbound.js +197 -0
  31. package/src/lib/server/site-care-inbound.js.map +1 -0
  32. package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
  33. package/src/lib/server/site-care-project-reconcile.js +211 -0
  34. package/src/lib/server/site-care-project-reconcile.js.map +1 -0
  35. package/src/lib/server/site-care-project-stripe.d.ts +114 -0
  36. package/src/lib/server/site-care-project-stripe.js +305 -0
  37. package/src/lib/server/site-care-project-stripe.js.map +1 -0
  38. package/src/lib/server/site-care-projects.d.ts +169 -0
  39. package/src/lib/server/site-care-projects.js +882 -0
  40. package/src/lib/server/site-care-projects.js.map +1 -0
  41. package/src/lib/server/site-care-reconcile.d.ts +81 -0
  42. package/src/lib/server/site-care-reconcile.js +349 -0
  43. package/src/lib/server/site-care-reconcile.js.map +1 -0
  44. package/src/lib/server/site-care-requests.d.ts +243 -0
  45. package/src/lib/server/site-care-requests.js +1414 -0
  46. package/src/lib/server/site-care-requests.js.map +1 -0
  47. package/src/lib/server/site-care-stripe.d.ts +175 -0
  48. package/src/lib/server/site-care-stripe.js +375 -0
  49. package/src/lib/server/site-care-stripe.js.map +1 -0
  50. package/src/lib/server/sso-provisioning.d.ts +6 -0
  51. package/src/lib/server/sso-provisioning.js +7 -0
  52. package/src/lib/server/sso-provisioning.js.map +1 -1
  53. package/src/lib/server/upgrade-proposal.d.ts +40 -1
  54. package/src/lib/server/upgrade-proposal.js +92 -50
  55. package/src/lib/server/upgrade-proposal.js.map +1 -1
  56. package/src/tenancy.d.ts +1 -0
  57. package/src/tenancy.js +2 -0
  58. package/src/tenancy.js.map +1 -1
@@ -81,6 +81,7 @@ export declare const membershipRow: (orgId: string, meta: HostMeta | undefined,
81
81
  nameLower: string;
82
82
  searchTokens: string[];
83
83
  hasCustomDomain: boolean;
84
+ cname: string | FieldValue;
84
85
  createdAt: unknown;
85
86
  favicon: string | FieldValue;
86
87
  role: string;
@@ -88,6 +89,38 @@ export declare const membershipRow: (orgId: string, meta: HostMeta | undefined,
88
89
  subdomain?: string;
89
90
  orgId: string;
90
91
  };
92
+ /**
93
+ * The host-document paths a membership row is derived from. A writer that
94
+ * changes any of them owes `syncHostProjectionForMembers` (AGL-3972): the
95
+ * rows are written by the Admin SDK at these writers and nowhere else, so a
96
+ * change that skips the re-fan leaves every member's list on the old value
97
+ * until something unrelated rewrites the row.
98
+ */
99
+ export declare const PROJECTED_HOST_PATHS: readonly string[];
100
+ /** Whether a write that changed these paths owes the membership re-fan. */
101
+ export declare const changesProjectedHostFields: (paths: readonly string[]) => boolean;
102
+ /** The longest site name the console's Display name field accepts. */
103
+ export declare const HOST_DISPLAY_NAME_MAX = 200;
104
+ /**
105
+ * The host-document update for a mirrored field a person changed in the
106
+ * console (AGL-3972), read from a `/api/hosts/sync-memberships` body.
107
+ *
108
+ * The console used to write `displayName` and `seo.favicon` from the browser
109
+ * and then ping the server to re-fan the rows, chained on the write's
110
+ * server acknowledgement. Under the multi-tab cache that acknowledgement can
111
+ * take a minute (AGL-3806), and a page left in that minute, or a ping that
112
+ * failed, left the rows on the old name for good. The server now writes the
113
+ * field and re-fans in the same request, so the two cannot come apart.
114
+ *
115
+ * Answers `null` when the body names neither field (a plain re-fan), and an
116
+ * error for a value the console would never send. A favicon of `''` is the
117
+ * Remove button's clear, kept as `''` because that is what the card writes.
118
+ */
119
+ export declare function projectedHostFieldsUpdate(body: Record<string, unknown> | null | undefined): {
120
+ update: Record<string, unknown> | null;
121
+ } | {
122
+ error: string;
123
+ };
91
124
  /**
92
125
  * Re-sync ONE member's projection rows across all the org's hosts: set a row
93
126
  * for every host the member can reach, delete the row for every host they
@@ -97,8 +130,8 @@ export declare const membershipRow: (orgId: string, meta: HostMeta | undefined,
97
130
  export declare function syncMemberHostProjections(orgId: string, uid: string): Promise<void>;
98
131
  /**
99
132
  * Re-sync ONE host's projection rows across all org members: set a row for
100
- * every member who can reach it, delete for those who cannot. Call after a
101
- * host is created, renamed, or its displayName changes.
133
+ * every member who can reach it, delete for those who cannot. Call after
134
+ * any write that changes one of `PROJECTED_HOST_PATHS`.
102
135
  */
103
136
  export declare function syncHostProjectionForMembers(orgId: string, hostId: string): Promise<void>;
104
137
  /** Delete every projection row for a member across the org's hosts (member removed). */
@@ -186,6 +186,11 @@ const membershipRef = (db, uid, hostId)=>db.collection('users').doc(uid).collect
186
186
  // list takes can carry. Stored as `false`, never left out, because a query
187
187
  // cannot find a document by a field it lacks.
188
188
  hasCustomDomain: hasCustomDomain(meta),
189
+ // The custom domain itself (AGL-3972), so a list shows the address the
190
+ // site answers on rather than only its platform subdomain. Deleted, not
191
+ // omitted, when the domain is released, for the merge reason the favicon
192
+ // below gives.
193
+ cname: hasCustomDomain(meta) ? String(meta == null ? void 0 : meta.cname).trim() : FieldValue.delete(),
189
194
  // What the Sites list's Created filter and order read. NULL rather than
190
195
  // absent for a site that never recorded one: `orderBy('createdAt')` drops
191
196
  // a document MISSING the field, and a site must not vanish from the list
@@ -201,6 +206,62 @@ const membershipRef = (db, uid, hostId)=>db.collection('users').doc(uid).collect
201
206
  updatedAt: FieldValue.serverTimestamp()
202
207
  });
203
208
  };
209
+ /**
210
+ * The host-document paths a membership row is derived from. A writer that
211
+ * changes any of them owes `syncHostProjectionForMembers` (AGL-3972): the
212
+ * rows are written by the Admin SDK at these writers and nowhere else, so a
213
+ * change that skips the re-fan leaves every member's list on the old value
214
+ * until something unrelated rewrites the row.
215
+ */ export const PROJECTED_HOST_PATHS = [
216
+ 'displayName',
217
+ 'subdomain',
218
+ 'cname',
219
+ 'seo.favicon',
220
+ 'createdAt'
221
+ ];
222
+ /** Whether a write that changed these paths owes the membership re-fan. */ export const changesProjectedHostFields = (paths)=>paths.some((path)=>PROJECTED_HOST_PATHS.includes(path));
223
+ /** The longest site name the console's Display name field accepts. */ export const HOST_DISPLAY_NAME_MAX = 200;
224
+ /**
225
+ * The host-document update for a mirrored field a person changed in the
226
+ * console (AGL-3972), read from a `/api/hosts/sync-memberships` body.
227
+ *
228
+ * The console used to write `displayName` and `seo.favicon` from the browser
229
+ * and then ping the server to re-fan the rows, chained on the write's
230
+ * server acknowledgement. Under the multi-tab cache that acknowledgement can
231
+ * take a minute (AGL-3806), and a page left in that minute, or a ping that
232
+ * failed, left the rows on the old name for good. The server now writes the
233
+ * field and re-fans in the same request, so the two cannot come apart.
234
+ *
235
+ * Answers `null` when the body names neither field (a plain re-fan), and an
236
+ * error for a value the console would never send. A favicon of `''` is the
237
+ * Remove button's clear, kept as `''` because that is what the card writes.
238
+ */ export function projectedHostFieldsUpdate(body) {
239
+ const update = {};
240
+ if (body && 'displayName' in body) {
241
+ const name = typeof body['displayName'] === 'string' ? body['displayName'].trim() : '';
242
+ if (!name) return {
243
+ error: 'A site needs a name.'
244
+ };
245
+ if (name.length > HOST_DISPLAY_NAME_MAX) {
246
+ return {
247
+ error: `A site name is ${HOST_DISPLAY_NAME_MAX} characters at most.`
248
+ };
249
+ }
250
+ update['displayName'] = name;
251
+ }
252
+ if (body && 'favicon' in body) {
253
+ const favicon = body['favicon'];
254
+ if (typeof favicon !== 'string' || favicon.length > 2048) {
255
+ return {
256
+ error: 'The favicon must be a link or a media reference.'
257
+ };
258
+ }
259
+ update['seo.favicon'] = favicon.trim();
260
+ }
261
+ return {
262
+ update: Object.keys(update).length ? update : null
263
+ };
264
+ }
204
265
  /** Runs a set of write operations in ≤CHUNK-sized batches. */ const commitChunked = async (db, ops)=>{
205
266
  for(let i = 0; i < ops.length; i += CHUNK){
206
267
  const batch = db.batch();
@@ -264,8 +325,8 @@ const membershipRef = (db, uid, hostId)=>db.collection('users').doc(uid).collect
264
325
  }
265
326
  /**
266
327
  * Re-sync ONE host's projection rows across all org members: set a row for
267
- * every member who can reach it, delete for those who cannot. Call after a
268
- * host is created, renamed, or its displayName changes.
328
+ * every member who can reach it, delete for those who cannot. Call after
329
+ * any write that changes one of `PROJECTED_HOST_PATHS`.
269
330
  */ export async function syncHostProjectionForMembers(orgId, hostId) {
270
331
  const db = firestore();
271
332
  const [members, meta] = await Promise.all([
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-memberships.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 * Per-user host membership projection (AGL-844): a reverse index at\n * `users/{uid}/hostMemberships/{hostId}` mirroring `hosts/{hostId}.memberRoles`\n * — the hosts a user can reach in an org, denormalized with the name so the\n * site switcher and subdomain→id routing can query + order + name-prefix-search\n * a user's own sites without loading the whole `hosts` collection (which the\n * rules can only serve unordered under a per-user `memberRoles.{uid}` filter).\n *\n * Because it lives under the user's own doc it is owner-readable and already\n * membership-filtered, so `where(orgId==…) orderBy(nameLower|updatedAt)` is a\n * plain composite index (no dynamic map path). Admin-SDK-written only.\n *\n * It is a best-effort convenience index, NOT an authorization source: real\n * access stays gated by `hosts/{hostId}.memberRoles` in the rules, so a stale\n * row at worst shows a site that then 404s on read — never grants access.\n *\n * Writers are scoped, mirroring the `users/{uid}/orgs` reverse index: a member\n * change re-syncs THAT member across the org's hosts; a host change re-syncs\n * THAT host across members. Kept in sync at the same points as `memberRoles`\n * (see `syncHostMemberRoles` callers) plus the erase/displayName gaps (AGL-855).\n *\n * ## The Sites list is a query over these rows (AGL-3321)\n *\n * The organization's Sites list pages, filters and searches THIS collection —\n * `where(orgId ==)`, plus the reader's clauses, ordered by `nameLower` or\n * `createdAt` — and joins each row to the host document by id for display.\n * It cannot query `hosts` itself: the rules serve a non-staff LIST of `hosts`\n * only under a `memberRoles.{uid}` clause, a composite on that per-user map\n * path can exist for no order but the document id, and a predicated listen\n * over the mutable `memberRoles`/`orgId` is what tombstoned host documents\n * for every other reader (AGL-1190, `useOrgHosts`).\n *\n * So a row carries what that list asks of a site: `searchTokens` (the quick\n * search, over the name, the platform subdomain and the custom domain),\n * `hasCustomDomain` (the Custom domain filter) and the host's `createdAt`\n * (immutable, set once at create). Every field is derived from the host\n * document in `membershipRow`, so a re-sync from any writer re-derives all of\n * them; the writers of their source fields — create, the owner and staff\n * renames, the Setup name save, and the domain attach and detach routes (the\n * only writers of `cname`) — each re-sync. Rows written before AGL-3321 are\n * stamped by `tools/scripts/backfill-host-memberships-list-fields.mjs`.\n */\n\nimport {\n hostRoleFor,\n isOrgWideMember,\n nameSearchKey,\n type AglynOrganization,\n type AglynOrgMember,\n} from '@aglyn/aglyn/server'\nimport { nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Firestore caps a batch at 500 writes; commit in chunks below that. */\nconst CHUNK = 400\n\ninterface HostMeta {\n displayName?: string\n subdomain?: string\n favicon?: string\n /** The custom domain, which the Sites list's search finds a site by. */\n cname?: string\n /** When the site was created: set once, by `claimHostForOrg`, and never moved. */\n createdAt?: unknown\n /** Whether the site document was there to read. */\n exists?: boolean\n}\n\nconst orgHostIds = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> => {\n const org = (await db.collection('orgs').doc(orgId).get()).data() as\n | AglynOrganization\n | undefined\n return Object.keys(org?.hosts ?? {})\n}\n\nconst readHostMeta = async (\n db: FirebaseFirestore.Firestore,\n hostIds: string[],\n): Promise<Map<string, HostMeta>> => {\n if (hostIds.length === 0) return new Map()\n const snaps = await db.getAll(\n ...hostIds.map((id) => db.collection('hosts').doc(id)),\n )\n return new Map(\n snaps.map((snap) => [\n snap.id,\n {\n displayName: snap.get('displayName'),\n subdomain: snap.get('subdomain'),\n // The switcher renders from the projection, not the host doc, so the\n // favicon has to travel with it (AGL-1071).\n favicon: snap.get('seo')?.favicon,\n cname: snap.get('cname'),\n createdAt: snap.get('createdAt'),\n exists: snap.exists,\n },\n ]),\n )\n}\n\nconst readOrgMembers = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<AglynOrgMember[]> => {\n const snap = await db\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .get()\n return snap.docs.map((d) => ({ $id: d.id, ...d.data() }) as AglynOrgMember)\n}\n\nconst membershipRef = (\n db: FirebaseFirestore.Firestore,\n uid: string,\n hostId: string,\n) => db.collection('users').doc(uid).collection('hostMemberships').doc(hostId)\n\n/** A tail of a word begins after any character that is not a letter or a digit. */\nconst WORD_SEPARATOR = /[^\\p{L}\\p{N}]/u\n\n/**\n * A word, and every tail of it that begins after a separator:\n * `shop.harbor-bakery.com` is itself, `harbor-bakery.com`, `bakery.com` and\n * `com`. Walked by codepoint, so a tail never starts inside a surrogate pair.\n */\nconst wordTails = (word: string): string[] => {\n const chars = [...word]\n const tails = [word]\n for (let at = 1; at < chars.length; at += 1) {\n if (WORD_SEPARATOR.test(chars[at - 1]) && !WORD_SEPARATOR.test(chars[at])) {\n tails.push(chars.slice(at).join(''))\n }\n }\n return tails\n}\n\n/**\n * The words a site is FOUND by in the Sites list's quick search (AGL-3321):\n * its name, its platform subdomain and its custom domain, as the word-prefix\n * tokens `nameSearchTokens` writes, which the list's query asks for with one\n * `array-contains` on the first typed word (`nameSearchNormalizers.token`).\n *\n * A subdomain or a domain is one \"word\" to `nameSearchTokens`, so the prefixes\n * of `harbor-bakery` alone would find it by `harbor` and never by `bakery`.\n * Every tail that begins after a separator is tokenized too, which is what\n * lets `bakery`, `bakery.com` and `shop.harbor` all find\n * `shop.harbor-bakery.com` — the words a reader remembers of an address.\n *\n * The platform apex is not a word here: it is the same on every site, so it\n * narrows nothing, and the subdomain in front of it is.\n *\n * Its script-side twin, for the backfill and the seeds that write these rows,\n * is `tools/scripts/lib/host-membership-search-tokens.mjs`; both answer\n * `tools/scripts/lib/host-membership-search-tokens.fixtures.json`, which this\n * library's spec asserts too.\n */\nexport function hostMembershipSearchTokens(\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n): string[] {\n const words = [meta?.displayName, meta?.subdomain, meta?.cname]\n .map((value) => nameSearchKey(typeof value === 'string' ? value : ''))\n .flatMap((key) => (key ? key.split(' ') : []))\n .flatMap(wordTails)\n return nameSearchTokens(words.join(' '))\n}\n\n/**\n * Whether a site has a custom domain connected, as the Sites card lists it:\n * a non-blank `cname`, which only the domain attach route writes and only the\n * detach route removes.\n */\nexport const hasCustomDomain = (meta: Pick<HostMeta, 'cname'> | undefined): boolean =>\n typeof meta?.cname === 'string' && meta.cname.trim() !== ''\n\n/**\n * The keys the staff Sites list (`/admin/sites`) queries on the SITE document\n * itself: the same name key, search tokens and custom-domain flag the\n * membership rows carry, so staff find a site by its name, subdomain or\n * domain across every organization without walking anyone's projection.\n *\n * Stamped by `syncHostProjectionForMembers` — the funnel every create,\n * rename, domain attach and domain release already calls — and by\n * `tools/scripts/backfill-host-search-fields.mjs` on the sites written before\n * it. `hasCustomDomain` is stored as `false`, never left out, for the reason\n * the membership row gives: a query cannot find a document by a field it\n * lacks.\n */\nexport const hostSearchFields = (\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n) => ({\n nameLower: nameSearchKey(meta?.displayName ?? ''),\n searchTokens: hostMembershipSearchTokens(meta),\n hasCustomDomain: hasCustomDomain(meta),\n})\n\n/** A Firestore timestamp, as opposed to a legacy number or string. */\nconst isTimestamp = (value: unknown): boolean =>\n typeof (value as { toMillis?: unknown } | null | undefined)?.toMillis === 'function'\n\n/**\n * Shape one projection row. Exported for tests: the favicon rule below is a\n * delete-vs-omit decision that is invisible in review and silent in\n * production when wrong (AGL-1071).\n */\nexport const membershipRow = (\n orgId: string,\n meta: HostMeta | undefined,\n role: string,\n) => {\n const displayName = meta?.displayName ?? ''\n return {\n orgId,\n ...(meta?.subdomain ? { subdomain: meta.subdomain } : {}),\n displayName,\n nameLower: nameSearchKey(displayName),\n // What the Sites list searches (AGL-3321). Re-derived on every sync, so a\n // rename, a domain attach or a domain release moves it with the host.\n searchTokens: hostMembershipSearchTokens(meta),\n // The Custom domain filter (AGL-3321): an equality, which every order the\n // list takes can carry. Stored as `false`, never left out, because a query\n // cannot find a document by a field it lacks.\n hasCustomDomain: hasCustomDomain(meta),\n // What the Sites list's Created filter and order read. NULL rather than\n // absent for a site that never recorded one: `orderBy('createdAt')` drops\n // a document MISSING the field, and a site must not vanish from the list\n // because it is sorted by a date it does not have.\n createdAt: isTimestamp(meta?.createdAt) ? meta?.createdAt : null,\n // DELETE rather than omit when the site has no favicon (AGL-1071). These\n // rows are written with `{ merge: true }`, so omitting the key leaves\n // whatever was there — clearing a favicon would keep showing the old one\n // in the switcher until something unrelated rewrote the row. The clear\n // path writes `seo.favicon: ''`, so test truthiness, not nullishness.\n favicon: meta?.favicon ? meta.favicon : FieldValue.delete(),\n role,\n updatedAt: FieldValue.serverTimestamp(),\n }\n}\n\n/** Runs a set of write operations in ≤CHUNK-sized batches. */\nconst commitChunked = async (\n db: FirebaseFirestore.Firestore,\n ops: Array<(batch: FirebaseFirestore.WriteBatch) => void>,\n): Promise<void> => {\n for (let i = 0; i < ops.length; i += CHUNK) {\n const batch = db.batch()\n for (const op of ops.slice(i, i + CHUNK)) op(batch)\n await batch.commit()\n }\n}\n\n/**\n * Mirror the member's org-wide reach onto their `users/{uid}/orgs/{orgId}`\n * row (AGL-1032), so the console can tell a site collaborator from an\n * org-wide viewer without a second read on every org route.\n *\n * Rides the projection pass rather than being a call the membership APIs\n * each have to remember: every path that changes a member's reach — add,\n * role change, grant, revoke, ownership transfer — already re-syncs their\n * host rows, so one funnel keeps the mirror true and self-heals a row an\n * earlier failure left stale.\n *\n * Only ever UPDATES an existing row. The reverse index is created with the\n * membership and deleted with it; a `set`/merge here on a removed member\n * would resurrect a half-row with no `orgName` or `slug`, and the console\n * renders that as a nameless workspace nobody can open.\n */\nasync function syncMemberOrgReach(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n uid: string,\n member: AglynOrgMember | null,\n): Promise<void> {\n if (!member) return\n const ref = db.collection('users').doc(uid).collection('orgs').doc(orgId)\n const snap = await ref.get()\n if (!snap.exists) return\n const orgWide = isOrgWideMember(member)\n if (snap.get('orgWide') === orgWide) return\n await ref.set({ orgWide }, { merge: true })\n}\n\n/**\n * Re-sync ONE member's projection rows across all the org's hosts: set a row\n * for every host the member can reach, delete the row for every host they\n * cannot (a role downgrade silently drops hosts). Call after any change to a\n * single member (add / role change / grant / revoke / ownership step).\n */\nexport async function syncMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const [memberSnap, hostIds] = await Promise.all([\n db.collection('orgs').doc(orgId).collection('members').doc(uid).get(),\n orgHostIds(db, orgId),\n ])\n const member = memberSnap.exists\n ? ({ $id: uid, ...memberSnap.data() } as AglynOrgMember)\n : null\n await syncMemberOrgReach(db, orgId, uid, member)\n const meta = await readHostMeta(db, hostIds)\n const ops = hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, uid, hostId)\n if (role) batch.set(ref, membershipRow(orgId, meta.get(hostId), role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n}\n\n/**\n * Re-sync ONE host's projection rows across all org members: set a row for\n * every member who can reach it, delete for those who cannot. Call after a\n * host is created, renamed, or its displayName changes.\n */\nexport async function syncHostProjectionForMembers(\n orgId: string,\n hostId: string,\n): Promise<void> {\n const db = firestore()\n const [members, meta] = await Promise.all([\n readOrgMembers(db, orgId),\n readHostMeta(db, [hostId]),\n ])\n const hostMeta = meta.get(hostId)\n const ops = members.map((member) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, member.$id, hostId)\n if (role) batch.set(ref, membershipRow(orgId, hostMeta, role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n // The staff Sites list's keys, on the site itself. `update`, never a\n // merge-set: a site erased since the read must not be minted back as a\n // phantom carrying only these three keys (the AGL-1765 shape). Outside the\n // batch so a site gone missing cannot fail its members' rows.\n if (hostMeta?.exists) {\n await db\n .collection('hosts')\n .doc(hostId)\n .update(hostSearchFields(hostMeta))\n .catch(() => undefined)\n }\n}\n\n/** Delete every projection row for a member across the org's hosts (member removed). */\nexport async function deleteMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const hostIds = await orgHostIds(db, orgId)\n await commitChunked(\n db,\n hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n }),\n )\n}\n\n/** Delete every member's projection row for one host (host erased). */\nexport async function deleteHostProjectionForAllMembers(\n orgId: string,\n hostId: string,\n /**\n * Holders to clear besides the org's members: the host's own `memberRoles`\n * keys. A site collaborator who is not an org member has a row too, and\n * the site switcher kept listing a deleted site for them.\n */\n extraUids: readonly string[] = [],\n): Promise<void> {\n const db = firestore()\n const members = await readOrgMembers(db, orgId)\n const uids = new Set<string>([\n ...members.map((member) => member.$id),\n ...extraUids.filter(Boolean),\n ])\n await deleteHostProjectionForUids(hostId, [...uids])\n}\n\n/** Delete the projection row of one host for exactly these users. */\nexport async function deleteHostProjectionForUids(\n hostId: string,\n uids: readonly string[],\n): Promise<void> {\n const db = firestore()\n await commitChunked(\n db,\n [...new Set(uids.filter(Boolean))].map(\n (uid) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n },\n ),\n )\n}\n"],"names":["hostRoleFor","isOrgWideMember","nameSearchKey","nameSearchTokens","FieldValue","firebaseAdmin","firestore","app","CHUNK","orgHostIds","db","orgId","org","collection","doc","get","data","Object","keys","hosts","readHostMeta","hostIds","length","Map","snaps","getAll","map","id","snap","displayName","subdomain","favicon","cname","createdAt","exists","readOrgMembers","docs","d","$id","membershipRef","uid","hostId","WORD_SEPARATOR","wordTails","word","chars","tails","at","test","push","slice","join","hostMembershipSearchTokens","meta","words","value","flatMap","key","split","hasCustomDomain","trim","hostSearchFields","nameLower","searchTokens","isTimestamp","toMillis","membershipRow","role","delete","updatedAt","serverTimestamp","commitChunked","ops","i","batch","op","commit","syncMemberOrgReach","member","ref","orgWide","set","merge","syncMemberHostProjections","memberSnap","Promise","all","syncHostProjectionForMembers","members","hostMeta","update","catch","undefined","deleteMemberHostProjections","deleteHostProjectionForAllMembers","extraUids","uids","Set","filter","Boolean","deleteHostProjectionForUids"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GAED,SACEA,WAAW,EACXC,eAAe,EACfC,aAAa,QAGR,sBAAqB;AAC5B,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAE5C,MAAMC,YAAY,IAAMD,cAAcE,GAAG,GAAGD,SAAS;AAErD,uEAAuE,GACvE,MAAME,QAAQ;AAcd,MAAMC,aAAa,OACjBC,IACAC;;IAEA,MAAMC,MAAM,AAAC,CAAA,MAAMF,GAAGG,UAAU,CAAC,QAAQC,GAAG,CAACH,OAAOI,GAAG,EAAC,EAAGC,IAAI;IAG/D,OAAOC,OAAOC,IAAI,SAACN,uBAAAA,IAAKO,KAAK,mBAAI,CAAC;AACpC;AAEA,MAAMC,eAAe,OACnBV,IACAW;IAEA,IAAIA,QAAQC,MAAM,KAAK,GAAG,OAAO,IAAIC;IACrC,MAAMC,QAAQ,MAAMd,GAAGe,MAAM,IACxBJ,QAAQK,GAAG,CAAC,CAACC,KAAOjB,GAAGG,UAAU,CAAC,SAASC,GAAG,CAACa;IAEpD,OAAO,IAAIJ,IACTC,MAAME,GAAG,CAAC,CAACE;YAOEA;eAPO;YAClBA,KAAKD,EAAE;YACP;gBACEE,aAAaD,KAAKb,GAAG,CAAC;gBACtBe,WAAWF,KAAKb,GAAG,CAAC;gBACpB,qEAAqE;gBACrE,4CAA4C;gBAC5CgB,OAAO,GAAEH,YAAAA,KAAKb,GAAG,CAAC,2BAATa,UAAiBG,OAAO;gBACjCC,OAAOJ,KA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UAAU,MAAMZ,WAAWC,IAAIC;IACrC,MAAM4D,cACJ7D,IACAW,QAAQK,GAAG,CAAC,CAACe,SAAW,CAACiC;YACvBA,MAAMN,MAAM,CAAC7B,cAAc7B,IAAI8B,KAAKC;QACtC;AAEJ;AAEA,qEAAqE,GACrE,OAAO,eAAeqD,kCACpBnF,KAAa,EACb8B,MAAc,EACd;;;;GAIC,GACDsD,YAA+B,EAAE;IAEjC,MAAMrF,KAAKJ;IACX,MAAMkF,UAAU,MAAMrD,eAAezB,IAAIC;IACzC,MAAMqF,OAAO,IAAIC,IAAY;WACxBT,QAAQ9D,GAAG,CAAC,CAACoD,SAAWA,OAAOxC,GAAG;WAClCyD,UAAUG,MAAM,CAACC;KACrB;IACD,MAAMC,4BAA4B3D,QAAQ;WAAIuD;KAAK;AACrD;AAEA,mEAAmE,GACnE,OAAO,eAAeI,4BACpB3D,MAAc,EACduD,IAAuB;IAEvB,MAAMtF,KAAKJ;IACX,MAAMiE,cACJ7D,IACA;WAAI,IAAIuF,IAAID,KAAKE,MAAM,CAACC;KAAU,CAACzE,GAAG,CACpC,CAACc,MAAQ,CAACkC;YACRA,MAAMN,MAAM,CAAC7B,cAAc7B,IAAI8B,KAAKC;QACtC;AAGN"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-memberships.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 * Per-user host membership projection (AGL-844): a reverse index at\n * `users/{uid}/hostMemberships/{hostId}` mirroring `hosts/{hostId}.memberRoles`\n * — the hosts a user can reach in an org, denormalized with the name so the\n * site switcher and subdomain→id routing can query + order + name-prefix-search\n * a user's own sites without loading the whole `hosts` collection (which the\n * rules can only serve unordered under a per-user `memberRoles.{uid}` filter).\n *\n * Because it lives under the user's own doc it is owner-readable and already\n * membership-filtered, so `where(orgId==…) orderBy(nameLower|updatedAt)` is a\n * plain composite index (no dynamic map path). Admin-SDK-written only.\n *\n * It is a best-effort convenience index, NOT an authorization source: real\n * access stays gated by `hosts/{hostId}.memberRoles` in the rules, so a stale\n * row at worst shows a site that then 404s on read — never grants access.\n *\n * Writers are scoped, mirroring the `users/{uid}/orgs` reverse index: a member\n * change re-syncs THAT member across the org's hosts; a host change re-syncs\n * THAT host across members. Kept in sync at the same points as `memberRoles`\n * (see `syncHostMemberRoles` callers) plus the erase/displayName gaps (AGL-855).\n *\n * ## The Sites list is a query over these rows (AGL-3321)\n *\n * The organization's Sites list pages, filters and searches THIS collection —\n * `where(orgId ==)`, plus the reader's clauses, ordered by `nameLower` or\n * `createdAt` — and joins each row to the host document by id for display.\n * It cannot query `hosts` itself: the rules serve a non-staff LIST of `hosts`\n * only under a `memberRoles.{uid}` clause, a composite on that per-user map\n * path can exist for no order but the document id, and a predicated listen\n * over the mutable `memberRoles`/`orgId` is what tombstoned host documents\n * for every other reader (AGL-1190, `useOrgHosts`).\n *\n * So a row carries what that list asks of a site: `searchTokens` (the quick\n * search, over the name, the platform subdomain and the custom domain),\n * `hasCustomDomain` (the Custom domain filter) and the host's `createdAt`\n * (immutable, set once at create). Every field is derived from the host\n * document in `membershipRow`, so a re-sync from any writer re-derives all of\n * them; the writers of their source fields — create, the owner and staff\n * renames, the Setup name save, and the domain attach and detach routes (the\n * only writers of `cname`) — each re-sync. Rows written before AGL-3321 are\n * stamped by `tools/scripts/backfill-host-memberships-list-fields.mjs`.\n */\n\nimport {\n hostRoleFor,\n isOrgWideMember,\n nameSearchKey,\n type AglynOrganization,\n type AglynOrgMember,\n} from '@aglyn/aglyn/server'\nimport { nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Firestore caps a batch at 500 writes; commit in chunks below that. */\nconst CHUNK = 400\n\ninterface HostMeta {\n displayName?: string\n subdomain?: string\n favicon?: string\n /** The custom domain, which the Sites list's search finds a site by. */\n cname?: string\n /** When the site was created: set once, by `claimHostForOrg`, and never moved. */\n createdAt?: unknown\n /** Whether the site document was there to read. */\n exists?: boolean\n}\n\nconst orgHostIds = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<string[]> => {\n const org = (await db.collection('orgs').doc(orgId).get()).data() as\n | AglynOrganization\n | undefined\n return Object.keys(org?.hosts ?? {})\n}\n\nconst readHostMeta = async (\n db: FirebaseFirestore.Firestore,\n hostIds: string[],\n): Promise<Map<string, HostMeta>> => {\n if (hostIds.length === 0) return new Map()\n const snaps = await db.getAll(\n ...hostIds.map((id) => db.collection('hosts').doc(id)),\n )\n return new Map(\n snaps.map((snap) => [\n snap.id,\n {\n displayName: snap.get('displayName'),\n subdomain: snap.get('subdomain'),\n // The switcher renders from the projection, not the host doc, so the\n // favicon has to travel with it (AGL-1071).\n favicon: snap.get('seo')?.favicon,\n cname: snap.get('cname'),\n createdAt: snap.get('createdAt'),\n exists: snap.exists,\n },\n ]),\n )\n}\n\nconst readOrgMembers = async (\n db: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<AglynOrgMember[]> => {\n const snap = await db\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .get()\n return snap.docs.map((d) => ({ $id: d.id, ...d.data() }) as AglynOrgMember)\n}\n\nconst membershipRef = (\n db: FirebaseFirestore.Firestore,\n uid: string,\n hostId: string,\n) => db.collection('users').doc(uid).collection('hostMemberships').doc(hostId)\n\n/** A tail of a word begins after any character that is not a letter or a digit. */\nconst WORD_SEPARATOR = /[^\\p{L}\\p{N}]/u\n\n/**\n * A word, and every tail of it that begins after a separator:\n * `shop.harbor-bakery.com` is itself, `harbor-bakery.com`, `bakery.com` and\n * `com`. Walked by codepoint, so a tail never starts inside a surrogate pair.\n */\nconst wordTails = (word: string): string[] => {\n const chars = [...word]\n const tails = [word]\n for (let at = 1; at < chars.length; at += 1) {\n if (WORD_SEPARATOR.test(chars[at - 1]) && !WORD_SEPARATOR.test(chars[at])) {\n tails.push(chars.slice(at).join(''))\n }\n }\n return tails\n}\n\n/**\n * The words a site is FOUND by in the Sites list's quick search (AGL-3321):\n * its name, its platform subdomain and its custom domain, as the word-prefix\n * tokens `nameSearchTokens` writes, which the list's query asks for with one\n * `array-contains` on the first typed word (`nameSearchNormalizers.token`).\n *\n * A subdomain or a domain is one \"word\" to `nameSearchTokens`, so the prefixes\n * of `harbor-bakery` alone would find it by `harbor` and never by `bakery`.\n * Every tail that begins after a separator is tokenized too, which is what\n * lets `bakery`, `bakery.com` and `shop.harbor` all find\n * `shop.harbor-bakery.com` — the words a reader remembers of an address.\n *\n * The platform apex is not a word here: it is the same on every site, so it\n * narrows nothing, and the subdomain in front of it is.\n *\n * Its script-side twin, for the backfill and the seeds that write these rows,\n * is `tools/scripts/lib/host-membership-search-tokens.mjs`; both answer\n * `tools/scripts/lib/host-membership-search-tokens.fixtures.json`, which this\n * library's spec asserts too.\n */\nexport function hostMembershipSearchTokens(\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n): string[] {\n const words = [meta?.displayName, meta?.subdomain, meta?.cname]\n .map((value) => nameSearchKey(typeof value === 'string' ? value : ''))\n .flatMap((key) => (key ? key.split(' ') : []))\n .flatMap(wordTails)\n return nameSearchTokens(words.join(' '))\n}\n\n/**\n * Whether a site has a custom domain connected, as the Sites card lists it:\n * a non-blank `cname`, which only the domain attach route writes and only the\n * detach route removes.\n */\nexport const hasCustomDomain = (meta: Pick<HostMeta, 'cname'> | undefined): boolean =>\n typeof meta?.cname === 'string' && meta.cname.trim() !== ''\n\n/**\n * The keys the staff Sites list (`/admin/sites`) queries on the SITE document\n * itself: the same name key, search tokens and custom-domain flag the\n * membership rows carry, so staff find a site by its name, subdomain or\n * domain across every organization without walking anyone's projection.\n *\n * Stamped by `syncHostProjectionForMembers` — the funnel every create,\n * rename, domain attach and domain release already calls — and by\n * `tools/scripts/backfill-host-search-fields.mjs` on the sites written before\n * it. `hasCustomDomain` is stored as `false`, never left out, for the reason\n * the membership row gives: a query cannot find a document by a field it\n * lacks.\n */\nexport const hostSearchFields = (\n meta: Pick<HostMeta, 'displayName' | 'subdomain' | 'cname'> | undefined,\n) => ({\n nameLower: nameSearchKey(meta?.displayName ?? ''),\n searchTokens: hostMembershipSearchTokens(meta),\n hasCustomDomain: hasCustomDomain(meta),\n})\n\n/** A Firestore timestamp, as opposed to a legacy number or string. */\nconst isTimestamp = (value: unknown): boolean =>\n typeof (value as { toMillis?: unknown } | null | undefined)?.toMillis === 'function'\n\n/**\n * Shape one projection row. Exported for tests: the favicon rule below is a\n * delete-vs-omit decision that is invisible in review and silent in\n * production when wrong (AGL-1071).\n */\nexport const membershipRow = (\n orgId: string,\n meta: HostMeta | undefined,\n role: string,\n) => {\n const displayName = meta?.displayName ?? ''\n return {\n orgId,\n ...(meta?.subdomain ? { subdomain: meta.subdomain } : {}),\n displayName,\n nameLower: nameSearchKey(displayName),\n // What the Sites list searches (AGL-3321). Re-derived on every sync, so a\n // rename, a domain attach or a domain release moves it with the host.\n searchTokens: hostMembershipSearchTokens(meta),\n // The Custom domain filter (AGL-3321): an equality, which every order the\n // list takes can carry. Stored as `false`, never left out, because a query\n // cannot find a document by a field it lacks.\n hasCustomDomain: hasCustomDomain(meta),\n // The custom domain itself (AGL-3972), so a list shows the address the\n // site answers on rather than only its platform subdomain. Deleted, not\n // omitted, when the domain is released, for the merge reason the favicon\n // below gives.\n cname: hasCustomDomain(meta) ? String(meta?.cname).trim() : FieldValue.delete(),\n // What the Sites list's Created filter and order read. NULL rather than\n // absent for a site that never recorded one: `orderBy('createdAt')` drops\n // a document MISSING the field, and a site must not vanish from the list\n // because it is sorted by a date it does not have.\n createdAt: isTimestamp(meta?.createdAt) ? meta?.createdAt : null,\n // DELETE rather than omit when the site has no favicon (AGL-1071). These\n // rows are written with `{ merge: true }`, so omitting the key leaves\n // whatever was there — clearing a favicon would keep showing the old one\n // in the switcher until something unrelated rewrote the row. The clear\n // path writes `seo.favicon: ''`, so test truthiness, not nullishness.\n favicon: meta?.favicon ? meta.favicon : FieldValue.delete(),\n role,\n updatedAt: FieldValue.serverTimestamp(),\n }\n}\n\n/**\n * The host-document paths a membership row is derived from. A writer that\n * changes any of them owes `syncHostProjectionForMembers` (AGL-3972): the\n * rows are written by the Admin SDK at these writers and nowhere else, so a\n * change that skips the re-fan leaves every member's list on the old value\n * until something unrelated rewrites the row.\n */\nexport const PROJECTED_HOST_PATHS: readonly string[] = [\n 'displayName',\n 'subdomain',\n 'cname',\n 'seo.favicon',\n 'createdAt',\n]\n\n/** Whether a write that changed these paths owes the membership re-fan. */\nexport const changesProjectedHostFields = (paths: readonly string[]): boolean =>\n paths.some((path) => PROJECTED_HOST_PATHS.includes(path))\n\n/** The longest site name the console's Display name field accepts. */\nexport const HOST_DISPLAY_NAME_MAX = 200\n\n/**\n * The host-document update for a mirrored field a person changed in the\n * console (AGL-3972), read from a `/api/hosts/sync-memberships` body.\n *\n * The console used to write `displayName` and `seo.favicon` from the browser\n * and then ping the server to re-fan the rows, chained on the write's\n * server acknowledgement. Under the multi-tab cache that acknowledgement can\n * take a minute (AGL-3806), and a page left in that minute, or a ping that\n * failed, left the rows on the old name for good. The server now writes the\n * field and re-fans in the same request, so the two cannot come apart.\n *\n * Answers `null` when the body names neither field (a plain re-fan), and an\n * error for a value the console would never send. A favicon of `''` is the\n * Remove button's clear, kept as `''` because that is what the card writes.\n */\nexport function projectedHostFieldsUpdate(\n body: Record<string, unknown> | null | undefined,\n): { update: Record<string, unknown> | null } | { error: string } {\n const update: Record<string, unknown> = {}\n if (body && 'displayName' in body) {\n const name = typeof body['displayName'] === 'string' ? body['displayName'].trim() : ''\n if (!name) return { error: 'A site needs a name.' }\n if (name.length > HOST_DISPLAY_NAME_MAX) {\n return { error: `A site name is ${HOST_DISPLAY_NAME_MAX} characters at most.` }\n }\n update['displayName'] = name\n }\n if (body && 'favicon' in body) {\n const favicon = body['favicon']\n if (typeof favicon !== 'string' || favicon.length > 2_048) {\n return { error: 'The favicon must be a link or a media reference.' }\n }\n update['seo.favicon'] = favicon.trim()\n }\n return { update: Object.keys(update).length ? update : null }\n}\n\n/** Runs a set of write operations in ≤CHUNK-sized batches. */\nconst commitChunked = async (\n db: FirebaseFirestore.Firestore,\n ops: Array<(batch: FirebaseFirestore.WriteBatch) => void>,\n): Promise<void> => {\n for (let i = 0; i < ops.length; i += CHUNK) {\n const batch = db.batch()\n for (const op of ops.slice(i, i + CHUNK)) op(batch)\n await batch.commit()\n }\n}\n\n/**\n * Mirror the member's org-wide reach onto their `users/{uid}/orgs/{orgId}`\n * row (AGL-1032), so the console can tell a site collaborator from an\n * org-wide viewer without a second read on every org route.\n *\n * Rides the projection pass rather than being a call the membership APIs\n * each have to remember: every path that changes a member's reach — add,\n * role change, grant, revoke, ownership transfer — already re-syncs their\n * host rows, so one funnel keeps the mirror true and self-heals a row an\n * earlier failure left stale.\n *\n * Only ever UPDATES an existing row. The reverse index is created with the\n * membership and deleted with it; a `set`/merge here on a removed member\n * would resurrect a half-row with no `orgName` or `slug`, and the console\n * renders that as a nameless workspace nobody can open.\n */\nasync function syncMemberOrgReach(\n db: FirebaseFirestore.Firestore,\n orgId: string,\n uid: string,\n member: AglynOrgMember | null,\n): Promise<void> {\n if (!member) return\n const ref = db.collection('users').doc(uid).collection('orgs').doc(orgId)\n const snap = await ref.get()\n if (!snap.exists) return\n const orgWide = isOrgWideMember(member)\n if (snap.get('orgWide') === orgWide) return\n await ref.set({ orgWide }, { merge: true })\n}\n\n/**\n * Re-sync ONE member's projection rows across all the org's hosts: set a row\n * for every host the member can reach, delete the row for every host they\n * cannot (a role downgrade silently drops hosts). Call after any change to a\n * single member (add / role change / grant / revoke / ownership step).\n */\nexport async function syncMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const [memberSnap, hostIds] = await Promise.all([\n db.collection('orgs').doc(orgId).collection('members').doc(uid).get(),\n orgHostIds(db, orgId),\n ])\n const member = memberSnap.exists\n ? ({ $id: uid, ...memberSnap.data() } as AglynOrgMember)\n : null\n await syncMemberOrgReach(db, orgId, uid, member)\n const meta = await readHostMeta(db, hostIds)\n const ops = hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, uid, hostId)\n if (role) batch.set(ref, membershipRow(orgId, meta.get(hostId), role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n}\n\n/**\n * Re-sync ONE host's projection rows across all org members: set a row for\n * every member who can reach it, delete for those who cannot. Call after\n * any write that changes one of `PROJECTED_HOST_PATHS`.\n */\nexport async function syncHostProjectionForMembers(\n orgId: string,\n hostId: string,\n): Promise<void> {\n const db = firestore()\n const [members, meta] = await Promise.all([\n readOrgMembers(db, orgId),\n readHostMeta(db, [hostId]),\n ])\n const hostMeta = meta.get(hostId)\n const ops = members.map((member) => (batch: FirebaseFirestore.WriteBatch) => {\n const role = hostRoleFor(member, hostId)\n const ref = membershipRef(db, member.$id, hostId)\n if (role) batch.set(ref, membershipRow(orgId, hostMeta, role), { merge: true })\n else batch.delete(ref)\n })\n await commitChunked(db, ops)\n // The staff Sites list's keys, on the site itself. `update`, never a\n // merge-set: a site erased since the read must not be minted back as a\n // phantom carrying only these three keys (the AGL-1765 shape). Outside the\n // batch so a site gone missing cannot fail its members' rows.\n if (hostMeta?.exists) {\n await db\n .collection('hosts')\n .doc(hostId)\n .update(hostSearchFields(hostMeta))\n .catch(() => undefined)\n }\n}\n\n/** Delete every projection row for a member across the org's hosts (member removed). */\nexport async function deleteMemberHostProjections(\n orgId: string,\n uid: string,\n): Promise<void> {\n const db = firestore()\n const hostIds = await orgHostIds(db, orgId)\n await commitChunked(\n db,\n hostIds.map((hostId) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n }),\n )\n}\n\n/** Delete every member's projection row for one host (host erased). */\nexport async function deleteHostProjectionForAllMembers(\n orgId: string,\n hostId: string,\n /**\n * Holders to clear besides the org's members: the host's own `memberRoles`\n * keys. A site collaborator who is not an org member has a row too, and\n * the site switcher kept listing a deleted site for them.\n */\n extraUids: readonly string[] = [],\n): Promise<void> {\n const db = firestore()\n const members = await readOrgMembers(db, orgId)\n const uids = new Set<string>([\n ...members.map((member) => member.$id),\n ...extraUids.filter(Boolean),\n ])\n await deleteHostProjectionForUids(hostId, [...uids])\n}\n\n/** Delete the projection row of one host for exactly these users. */\nexport async function deleteHostProjectionForUids(\n hostId: string,\n uids: readonly string[],\n): Promise<void> {\n const db = firestore()\n await commitChunked(\n db,\n [...new Set(uids.filter(Boolean))].map(\n (uid) => (batch: FirebaseFirestore.WriteBatch) => {\n batch.delete(membershipRef(db, uid, hostId))\n },\n ),\n )\n}\n"],"names":["hostRoleFor","isOrgWideMember","nameSearchKey","nameSearchTokens","FieldValue","firebaseAdmin","firestore","app","CHUNK","orgHostIds","db","orgId","org","collection","doc","get","data","Object","keys","hosts","readHostMeta","hostIds","length","Map","snaps","getAll","map","id","snap","displayName","subdomain","favicon","cname","createdAt","exists","readOrgMembers","docs","d","$id","membershipRef","uid","hostId","WORD_SEPARATOR","wordTails","word","chars","tails","at","test","push","slice","join","hostMembershipSearchTokens","meta","words","value","flatMap","key","split","hasCustomDomain","trim","hostSearchFields","nameLower","searchTokens","isTimestamp","toMillis","membershipRow","role","String","delete","updatedAt","serverTimestamp","PROJECTED_HOST_PATHS","changesProjectedHostFields","paths","some","path","includes","HOST_DISPLAY_NAME_MAX","projectedHostFieldsUpdate","body","update","name","error","commitChunked","ops","i","batch","op","commit","syncMemberOrgReach","member","ref","orgWide","set","merge","syncMemberHostProjections","memberSnap","Promise","all","syncHostProjectionForMembers","members","hostMeta","catch","undefined","deleteMemberHostProjections","deleteHostProjectionForAllMembers","extraUids","uids","Set","filter","Boolean","deleteHostProjectionForUids"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GAED,SACEA,WAAW,EACXC,eAAe,EACfC,aAAa,QAGR,sBAAqB;AAC5B,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAE5C,MAAMC,YAAY,IAAMD,cAAcE,GAAG,GAAGD,SAAS;AAErD,uEAAuE,GACvE,MAAME,QAAQ;AAcd,MAAMC,aAAa,OACjBC,IACAC;;IAEA,MAAMC,MAAM,AAAC,CAAA,MAAMF,GAAGG,UAAU,CAAC,QAAQC,GAAG,CAACH,OAAOI,GAAG,EAAC,EAAGC,IAAI;IAG/D,OAAOC,OAAOC,IAAI,SAACN,uBAAAA,IAAKO,KAAK,mBAAI,CAAC;AACpC;AAEA,MAAMC,eAAe,OACnBV,IACAW;IAEA,IAAIA,QAAQC,MAAM,KAAK,GAAG,OAAO,IAAIC;IACrC,MAAMC,QAAQ,MAAMd,GAAGe,MAAM,IACxBJ,QAAQK,GAAG,CAAC,CAACC,KAAOjB,GAAGG,UAAU,CAAC,SAASC,GAAG,CAACa;IAEpD,OAAO,IAAIJ,IACTC,MAAME,GAAG,CAAC,CAACE;YAOEA;eAPO;YAClBA,KAAKD,EAAE;YACP;gBACEE,aAAaD,KAAKb,GAAG,CAAC;gBACtBe,WAAWF,KAAKb,GAAG,CAAC;gBACpB,qEAAqE;gBACrE,4CAA4C;gBAC5CgB,OAAO,GAAEH,YAAAA,KAAKb,GAAG,CAAC,2BAATa,UAAiBG,OAAO;gBACjCC,OAAOJ,KAAKb,GAAG,CAAC;gBAChBkB,WAAWL,KAAKb,GAAG,CAA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M,CAAC9B,cAAc7B,IAAI8B,KAAKC;QACtC;AAEJ;AAEA,qEAAqE,GACrE,OAAO,eAAeiE,kCACpB/F,KAAa,EACb8B,MAAc,EACd;;;;GAIC,GACDkE,YAA+B,EAAE;IAEjC,MAAMjG,KAAKJ;IACX,MAAM+F,UAAU,MAAMlE,eAAezB,IAAIC;IACzC,MAAMiG,OAAO,IAAIC,IAAY;WACxBR,QAAQ3E,GAAG,CAAC,CAACiE,SAAWA,OAAOrD,GAAG;WAClCqE,UAAUG,MAAM,CAACC;KACrB;IACD,MAAMC,4BAA4BvE,QAAQ;WAAImE;KAAK;AACrD;AAEA,mEAAmE,GACnE,OAAO,eAAeI,4BACpBvE,MAAc,EACdmE,IAAuB;IAEvB,MAAMlG,KAAKJ;IACX,MAAM8E,cACJ1E,IACA;WAAI,IAAImG,IAAID,KAAKE,MAAM,CAACC;KAAU,CAACrF,GAAG,CACpC,CAACc,MAAQ,CAAC+C;YACRA,MAAMlB,MAAM,CAAC9B,cAAc7B,IAAI8B,KAAKC;QACtC;AAGN"}
@@ -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 { hasInlineOrgBilling, type OrgBillingDoc, type OrgInlineBilling } from '@aglyn/aglyn/server';
17
+ import { hasInlineOrgBilling, type OrgBillingDoc, type OrgInlineBilling, type AiTierId } from '@aglyn/aglyn/server';
18
18
  /** `orgs/{orgId}/billing/stripe`. */
19
19
  export declare function orgBillingRef(orgId: string): FirebaseFirestore.DocumentReference<FirebaseFirestore.DocumentData, FirebaseFirestore.DocumentData>;
20
20
  /**
@@ -82,7 +82,9 @@ export declare function readOrgBillingCustomerModes(orgId: string): Promise<{
82
82
  * a doc that no longer exists, and it is the only thing standing between an org
83
83
  * the backfill somehow missed and a paying workspace rendering as Free.
84
84
  */
85
- export declare function writeOrgBilling(orgId: string, patch: Partial<OrgBillingDoc> & Pick<OrgInlineBilling, 'seatAddons'>, options?: {
85
+ export declare function writeOrgBilling(orgId: string, patch: Partial<OrgBillingDoc> & Pick<OrgInlineBilling, 'seatAddons'> & {
86
+ aiTier?: AiTierId | null;
87
+ }, options?: {
86
88
  writeInline?: boolean;
87
89
  }): Promise<void>;
88
90
  /**
@@ -197,6 +197,11 @@ import { firebaseAdmin } from "./firebase-admin.js";
197
197
  if (patch.seatAddons !== undefined) {
198
198
  orgPatch['seatAddons'] = patch.seatAddons;
199
199
  }
200
+ // Which Aglyn AI tier those quantities hold (AGL-3965), derived from the
201
+ // same items and read from the same document, so it travels with them.
202
+ if (patch.aiTier !== undefined) {
203
+ orgPatch['aiTier'] = patch.aiTier;
204
+ }
200
205
  if (Object.keys(orgPatch).length) batch.set(orgRef, orgPatch, {
201
206
  merge: true
202
207
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-billing.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 { deploymentLivemode } from '@aglyn/aglyn/app-utils/stripe-deployment-mode'\nimport {\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n STRIPE_CUSTOMER_ID_TEST_FIELD,\n STRIPE_CUSTOMER_INDEX_COLLECTION,\n hasInlineOrgBilling,\n orgBillingStatusFrom,\n pickOrgBillingFields,\n type OrgBillingDoc,\n type OrgInlineBilling,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * Server-side accessors for the manager-gated billing document (AGL-1028).\n *\n * Every server surface that used to read `orgs/{orgId}.stripeCustomerId` /\n * `.subscription` / `.seatAddons` goes through here instead. All of them are\n * Admin SDK, so rules never applied to them — this is a path change, not a\n * permission change. The permission change is entirely in the rules, where the\n * new subcollection is gated on `canManageOrg()`.\n */\n\nconst db = () => firebaseAdmin.app().firestore()\n\n/**\n * Which PHYSICAL field holds this deployment's Stripe customer id (AGL-2486).\n *\n * Live keeps `stripeCustomerId`, so live behaviour is byte-identical to before\n * this existed and no stored document needs migrating. Test mode gets its own\n * slot, which starts empty on every org — the first test-mode checkout mints a\n * fresh test customer instead of sending a live `cus_…` to a `sk_test` key and\n * taking a 502.\n *\n * Read at call time rather than at module load: a spec flips\n * `process.env.STRIPE_SECRET_KEY` between cases, and a cached verdict would\n * make the second case answer for the first.\n */\nfunction customerIdField(): 'stripeCustomerId' | typeof STRIPE_CUSTOMER_ID_TEST_FIELD {\n return deploymentLivemode() ? 'stripeCustomerId' : STRIPE_CUSTOMER_ID_TEST_FIELD\n}\n\n/**\n * Collapse a stored billing document to the logical shape callers expect.\n *\n * `stripeCustomerId` on the RESULT always means \"the customer id for the mode\n * this deployment spends in\". The test id never leaks out under its physical\n * name, and — the part that matters — test mode does NOT fall back to the live\n * id when its own slot is empty. That fallback is precisely the bug: it is what\n * sent `cus_UuQjDdd1oxPMNH` to a `sk_test` key.\n */\nfunction projectBillingMode(doc: OrgBillingDoc): OrgBillingDoc {\n const stored = { ...(doc ?? {}) } as Record<string, unknown>\n const testId = stored[STRIPE_CUSTOMER_ID_TEST_FIELD]\n // The physical twin never reaches a caller in either mode: every reader\n // treats `stripeCustomerId` as THE customer, so a second field carrying a\n // second answer is exactly the ambiguity this fix removes.\n delete stored[STRIPE_CUSTOMER_ID_TEST_FIELD]\n if (deploymentLivemode()) return stored as OrgBillingDoc\n // No `??` fallback to the live id. That fallback IS the bug.\n stored['stripeCustomerId'] = (testId ?? null) as string | null\n return stored as OrgBillingDoc\n}\n\n/** `orgs/{orgId}/billing/stripe`. */\nexport function orgBillingRef(orgId: string) {\n return db()\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_BILLING_SUBCOLLECTION)\n .doc(ORG_BILLING_DOC_ID)\n}\n\n/**\n * Reads an org's commercial keys, falling back to the org doc.\n *\n * The fallback is what makes the migration safe to land in pieces: a reader\n * repointed here keeps working against an org that has not been backfilled\n * yet, and keeps working if the backfill missed one. It stops being reachable\n * only when the inline fields are finally deleted from the org doc — which is\n * the LAST step, taken once production has been observed reading from the new\n * location.\n *\n * Without it, the failure mode is silent and expensive: a missing billing doc\n * reads as `undefined`, which every caller downstream interprets as \"no\n * subscription\", i.e. a paying workspace rendered as Free.\n */\nexport async function readOrgBilling(orgId: string): Promise<OrgBillingDoc> {\n if (!orgId) return {}\n return projectBillingMode(await readStoredOrgBilling(orgId))\n}\n\n/**\n * The STORED document, before any mode projection — both physical ids intact.\n *\n * Private on purpose: a caller holding this holds two answers to \"which\n * customer\", which is the ambiguity `projectBillingMode` exists to remove. It\n * is factored out only so the mode census below reads the very same bytes\n * `readOrgBilling` reads, org-doc fallback included. Two separate reads would\n * be two chances to diverge, and the census exists precisely to explain what\n * `readOrgBilling` returned.\n */\nasync function readStoredOrgBilling(orgId: string): Promise<OrgBillingDoc> {\n const billingSnapshot = await orgBillingRef(orgId).get()\n if (billingSnapshot.exists) {\n return (billingSnapshot.data() ?? {}) as OrgBillingDoc\n }\n const orgSnapshot = await db().collection('orgs').doc(orgId).get()\n // The legacy inline fields predate mode-keying entirely, so anything found\n // there is a LIVE id by construction — the org doc was last written by a\n // `sk_live_` deployment. Projected by the caller all the same, so a\n // test-mode read of an un-backfilled org gets no customer rather than a live\n // one.\n return pickOrgBillingFields(orgSnapshot.data() as never) as OrgBillingDoc\n}\n\n/**\n * Which Stripe MODES this org has a stored customer for (AGL-2486, follow-up).\n *\n * `readOrgBilling` answering `stripeCustomerId: null` has two completely\n * different meanings — \"this workspace has never been billed\" and \"this\n * workspace's customer lives in the other Stripe world and THIS deployment\n * cannot see it\" — and every surface downstream rendered them as the same\n * sentence, \"No invoices yet.\" That is the swallowed-query-as-measured-zero\n * shape: nothing looks wrong, and the wrong reading is the reassuring one.\n *\n * The fix is NOT to fall back to the other mode's id — that fallback is the\n * original bug, and it stays deleted. It is to let a caller say which of the\n * two silences it is looking at.\n *\n * Returns BOOLEANS, never ids. A test-mode surface asking this question must\n * not come away holding a live `cus_…`: it would have no legitimate use for\n * one, and putting it in a JSON response would publish a live customer id to\n * every browser on a test deployment.\n */\nexport async function readOrgBillingCustomerModes(\n orgId: string,\n): Promise<{ live: boolean; test: boolean }> {\n if (!orgId) return { live: false, test: false }\n const stored = (await readStoredOrgBilling(orgId)) as Record<string, unknown>\n // A stored `null` (the webhook's \"Stripe says this is gone\") and an empty\n // string are both absences, so presence is a non-empty STRING — not `in`,\n // and not truthiness on an unknown.\n const present = (value: unknown) => typeof value === 'string' && value.length > 0\n return {\n live: present(stored['stripeCustomerId']),\n test: present(stored[STRIPE_CUSTOMER_ID_TEST_FIELD]),\n }\n}\n\n/**\n * Writes the commercial keys to the billing doc, and onto the org doc the\n * entitlement inputs that stay there.\n *\n * Three writes, one batch:\n *\n * 1. the billing doc itself, `merge: true` to match what the org-doc write did;\n * 2. the org doc, merged, with what entitlement resolution reads there:\n * `billingStatus`, so the AGL-275 dunning banner keeps working for\n * non-managers who can no longer read `subscription`; and `seatAddons`,\n * which never moved (`ORG_BILLING_MOVED_KEYS`), whenever the patch carries\n * the add-on quantities;\n * 3. the `stripeCustomers` reverse index, so the webhook can still resolve an\n * org from a Stripe customer id without a query.\n *\n * `writeInline` mirrored the keys back onto the org doc as well. It was on\n * during the migration so a rollback lost nothing, and is now OFF: writing them\n * inline is what the whole issue exists to stop, and leaving it on would let the\n * next Stripe webhook silently re-add the fields minutes after they were\n * deleted, re-opening the exposure with nothing to show for it.\n *\n * The option survives for a deliberate one-off rollback, and nothing passes it.\n *\n * The READ fallback in `readOrgBilling` deliberately stays. It costs one get on\n * a doc that no longer exists, and it is the only thing standing between an org\n * the backfill somehow missed and a paying workspace rendering as Free.\n */\nexport async function writeOrgBilling(\n orgId: string,\n patch: Partial<OrgBillingDoc> & Pick<OrgInlineBilling, 'seatAddons'>,\n options: { writeInline?: boolean } = {},\n): Promise<void> {\n if (!orgId) return\n const { writeInline = false } = options\n const fields = pickOrgBillingFields(patch as never) as Record<string, unknown>\n // The logical key becomes the mode's PHYSICAL key (AGL-2486). A test-mode\n // write therefore cannot overwrite the live customer id — which it silently\n // did before this, destroying the live linkage on the first completed test\n // checkout.\n const field = customerIdField()\n if (field !== 'stripeCustomerId' && 'stripeCustomerId' in fields) {\n fields[field] = fields['stripeCustomerId']\n delete fields['stripeCustomerId']\n }\n const batch = db().batch()\n const orgRef = db().collection('orgs').doc(orgId)\n\n batch.set(orgBillingRef(orgId), fields, { merge: true })\n\n // The status mirror is derived, so it is only written when this patch\n // actually carries a subscription — otherwise a partial update (a seat-addon\n // change, say) would blank the banner's input.\n const orgPatch: Record<string, unknown> = writeInline ? { ...fields } : {}\n if (patch.subscription !== undefined) {\n orgPatch['billingStatus'] = orgBillingStatusFrom(patch)\n }\n // The add-on quantities are what grants and removes an add-on, and the org\n // doc is the only place they are read from: a subscription sync that wrote\n // them nowhere would charge for an add-on bought at checkout without\n // granting it, and leave a removed one in place. Merged with the rest of\n // this patch, so the explicit zeros of a sync converge while a key the\n // subscription items do not name survives.\n if (patch.seatAddons !== undefined) {\n orgPatch['seatAddons'] = patch.seatAddons\n }\n if (Object.keys(orgPatch).length) batch.set(orgRef, orgPatch, { merge: true })\n\n // Off the PHYSICAL field, so a test-mode write indexes its own customer.\n // The index needs no mode-keying of its own: it is keyed by the customer id,\n // and Stripe ids are unique across modes, so the live and test entries are\n // two documents that both resolve to this org.\n const customerId = fields[field]\n if (typeof customerId === 'string' && customerId) {\n batch.set(\n db().collection(STRIPE_CUSTOMER_INDEX_COLLECTION).doc(customerId),\n { orgId, updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp() },\n { merge: true },\n )\n }\n\n await batch.commit()\n}\n\n/**\n * Resolves an org id from a Stripe customer id.\n *\n * Prefers the reverse index; falls back to the legacy `where('stripeCustomerId')`\n * query on `orgs` for customers whose index entry has not been written yet.\n * The fallback disappears with the inline fields.\n */\nexport async function findOrgIdByStripeCustomer(\n customerId: string,\n): Promise<string | null> {\n if (!customerId) return null\n const indexed = await db()\n .collection(STRIPE_CUSTOMER_INDEX_COLLECTION)\n .doc(customerId)\n .get()\n const mapped = indexed.get('orgId')\n if (typeof mapped === 'string' && mapped) return mapped\n const legacy = await db()\n .collection('orgs')\n .where('stripeCustomerId', '==', customerId)\n .limit(1)\n .get()\n return legacy.docs[0]?.id ?? null\n}\n\n/** Re-exported so callers do not need a second import to test migration state. */\nexport { hasInlineOrgBilling }\n"],"names":["deploymentLivemode","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","STRIPE_CUSTOMER_ID_TEST_FIELD","STRIPE_CUSTOMER_INDEX_COLLECTION","hasInlineOrgBilling","orgBillingStatusFrom","pickOrgBillingFields","firebaseAdmin","db","app","firestore","customerIdField","projectBillingMode","doc","stored","testId","orgBillingRef","orgId","collection","readOrgBilling","readStoredOrgBilling","billingSnapshot","get","exists","data","orgSnapshot","readOrgBillingCustomerModes","live","test","present","value","length","writeOrgBilling","patch","options","writeInline","fields","field","batch","orgRef","set","merge","orgPatch","subscription","undefined","seatAddons","Object","keys","customerId","updatedAt","FieldValue","serverTimestamp","commit","findOrgIdByStripeCustomer","legacy","indexed","mapped","where","limit","docs","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,gDAA+C;AAClF,SACEC,kBAAkB,EAClBC,yBAAyB,EACzBC,6BAA6B,EAC7BC,gCAAgC,EAChCC,mBAAmB,EACnBC,oBAAoB,EACpBC,oBAAoB,QAGf,sBAAqB;AAC5B,SAASC,aAAa,QAAQ,sBAAkB;AAEhD;;;;;;;;CAQC,GAED,MAAMC,KAAK,IAAMD,cAAcE,GAAG,GAAGC,SAAS;AAE9C;;;;;;;;;;;;CA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X,MAAM,EAAEO,MAAME,GAAG,CAACD,QAAQG,UAAU;QAAED,OAAO;IAAK;IAE5E,yEAAyE;IACzE,6EAA6E;IAC7E,2EAA2E;IAC3E,+CAA+C;IAC/C,MAAMO,aAAaZ,MAAM,CAACC,MAAM;IAChC,IAAI,OAAOW,eAAe,YAAYA,YAAY;QAChDV,MAAME,GAAG,CACPhC,KAAKU,UAAU,CAACf,kCAAkCU,GAAG,CAACmC,aACtD;YAAE/B;YAAOgC,WAAW1C,cAAcG,SAAS,CAACwC,UAAU,CAACC,eAAe;QAAG,GACzE;YAAEV,OAAO;QAAK;IAElB;IAEA,MAAMH,MAAMc,MAAM;AACpB;AAEA;;;;;;CAMC,GACD,OAAO,eAAeC,0BACpBL,UAAkB;;QAcXM;IAZP,IAAI,CAACN,YAAY,OAAO;IACxB,MAAMO,UAAU,MAAM/C,KACnBU,UAAU,CAACf,kCACXU,GAAG,CAACmC,YACJ1B,GAAG;IACN,MAAMkC,SAASD,QAAQjC,GAAG,CAAC;IAC3B,IAAI,OAAOkC,WAAW,YAAYA,QAAQ,OAAOA;IACjD,MAAMF,SAAS,MAAM9C,KAClBU,UAAU,CAAC,QACXuC,KAAK,CAAC,oBAAoB,MAAMT,YAChCU,KAAK,CAAC,GACNpC,GAAG;IACN,gBAAOgC,gBAAAA,OAAOK,IAAI,CAAC,EAAE,qBAAdL,cAAgBM,EAAE,mBAAI;AAC/B;AAEA,gFAAgF,GAChF,SAASxD,mBAAmB,GAAE"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-billing.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 { deploymentLivemode } from '@aglyn/aglyn/app-utils/stripe-deployment-mode'\nimport {\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n STRIPE_CUSTOMER_ID_TEST_FIELD,\n STRIPE_CUSTOMER_INDEX_COLLECTION,\n hasInlineOrgBilling,\n orgBillingStatusFrom,\n pickOrgBillingFields,\n type OrgBillingDoc,\n type OrgInlineBilling,\n type AiTierId,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * Server-side accessors for the manager-gated billing document (AGL-1028).\n *\n * Every server surface that used to read `orgs/{orgId}.stripeCustomerId` /\n * `.subscription` / `.seatAddons` goes through here instead. All of them are\n * Admin SDK, so rules never applied to them — this is a path change, not a\n * permission change. The permission change is entirely in the rules, where the\n * new subcollection is gated on `canManageOrg()`.\n */\n\nconst db = () => firebaseAdmin.app().firestore()\n\n/**\n * Which PHYSICAL field holds this deployment's Stripe customer id (AGL-2486).\n *\n * Live keeps `stripeCustomerId`, so live behaviour is byte-identical to before\n * this existed and no stored document needs migrating. Test mode gets its own\n * slot, which starts empty on every org — the first test-mode checkout mints a\n * fresh test customer instead of sending a live `cus_…` to a `sk_test` key and\n * taking a 502.\n *\n * Read at call time rather than at module load: a spec flips\n * `process.env.STRIPE_SECRET_KEY` between cases, and a cached verdict would\n * make the second case answer for the first.\n */\nfunction customerIdField(): 'stripeCustomerId' | typeof STRIPE_CUSTOMER_ID_TEST_FIELD {\n return deploymentLivemode() ? 'stripeCustomerId' : STRIPE_CUSTOMER_ID_TEST_FIELD\n}\n\n/**\n * Collapse a stored billing document to the logical shape callers expect.\n *\n * `stripeCustomerId` on the RESULT always means \"the customer id for the mode\n * this deployment spends in\". The test id never leaks out under its physical\n * name, and — the part that matters — test mode does NOT fall back to the live\n * id when its own slot is empty. That fallback is precisely the bug: it is what\n * sent `cus_UuQjDdd1oxPMNH` to a `sk_test` key.\n */\nfunction projectBillingMode(doc: OrgBillingDoc): OrgBillingDoc {\n const stored = { ...(doc ?? {}) } as Record<string, unknown>\n const testId = stored[STRIPE_CUSTOMER_ID_TEST_FIELD]\n // The physical twin never reaches a caller in either mode: every reader\n // treats `stripeCustomerId` as THE customer, so a second field carrying a\n // second answer is exactly the ambiguity this fix removes.\n delete stored[STRIPE_CUSTOMER_ID_TEST_FIELD]\n if (deploymentLivemode()) return stored as OrgBillingDoc\n // No `??` fallback to the live id. That fallback IS the bug.\n stored['stripeCustomerId'] = (testId ?? null) as string | null\n return stored as OrgBillingDoc\n}\n\n/** `orgs/{orgId}/billing/stripe`. */\nexport function orgBillingRef(orgId: string) {\n return db()\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_BILLING_SUBCOLLECTION)\n .doc(ORG_BILLING_DOC_ID)\n}\n\n/**\n * Reads an org's commercial keys, falling back to the org doc.\n *\n * The fallback is what makes the migration safe to land in pieces: a reader\n * repointed here keeps working against an org that has not been backfilled\n * yet, and keeps working if the backfill missed one. It stops being reachable\n * only when the inline fields are finally deleted from the org doc — which is\n * the LAST step, taken once production has been observed reading from the new\n * location.\n *\n * Without it, the failure mode is silent and expensive: a missing billing doc\n * reads as `undefined`, which every caller downstream interprets as \"no\n * subscription\", i.e. a paying workspace rendered as Free.\n */\nexport async function readOrgBilling(orgId: string): Promise<OrgBillingDoc> {\n if (!orgId) return {}\n return projectBillingMode(await readStoredOrgBilling(orgId))\n}\n\n/**\n * The STORED document, before any mode projection — both physical ids intact.\n *\n * Private on purpose: a caller holding this holds two answers to \"which\n * customer\", which is the ambiguity `projectBillingMode` exists to remove. It\n * is factored out only so the mode census below reads the very same bytes\n * `readOrgBilling` reads, org-doc fallback included. Two separate reads would\n * be two chances to diverge, and the census exists precisely to explain what\n * `readOrgBilling` returned.\n */\nasync function readStoredOrgBilling(orgId: string): Promise<OrgBillingDoc> {\n const billingSnapshot = await orgBillingRef(orgId).get()\n if (billingSnapshot.exists) {\n return (billingSnapshot.data() ?? {}) as OrgBillingDoc\n }\n const orgSnapshot = await db().collection('orgs').doc(orgId).get()\n // The legacy inline fields predate mode-keying entirely, so anything found\n // there is a LIVE id by construction — the org doc was last written by a\n // `sk_live_` deployment. Projected by the caller all the same, so a\n // test-mode read of an un-backfilled org gets no customer rather than a live\n // one.\n return pickOrgBillingFields(orgSnapshot.data() as never) as OrgBillingDoc\n}\n\n/**\n * Which Stripe MODES this org has a stored customer for (AGL-2486, follow-up).\n *\n * `readOrgBilling` answering `stripeCustomerId: null` has two completely\n * different meanings — \"this workspace has never been billed\" and \"this\n * workspace's customer lives in the other Stripe world and THIS deployment\n * cannot see it\" — and every surface downstream rendered them as the same\n * sentence, \"No invoices yet.\" That is the swallowed-query-as-measured-zero\n * shape: nothing looks wrong, and the wrong reading is the reassuring one.\n *\n * The fix is NOT to fall back to the other mode's id — that fallback is the\n * original bug, and it stays deleted. It is to let a caller say which of the\n * two silences it is looking at.\n *\n * Returns BOOLEANS, never ids. A test-mode surface asking this question must\n * not come away holding a live `cus_…`: it would have no legitimate use for\n * one, and putting it in a JSON response would publish a live customer id to\n * every browser on a test deployment.\n */\nexport async function readOrgBillingCustomerModes(\n orgId: string,\n): Promise<{ live: boolean; test: boolean }> {\n if (!orgId) return { live: false, test: false }\n const stored = (await readStoredOrgBilling(orgId)) as Record<string, unknown>\n // A stored `null` (the webhook's \"Stripe says this is gone\") and an empty\n // string are both absences, so presence is a non-empty STRING — not `in`,\n // and not truthiness on an unknown.\n const present = (value: unknown) => typeof value === 'string' && value.length > 0\n return {\n live: present(stored['stripeCustomerId']),\n test: present(stored[STRIPE_CUSTOMER_ID_TEST_FIELD]),\n }\n}\n\n/**\n * Writes the commercial keys to the billing doc, and onto the org doc the\n * entitlement inputs that stay there.\n *\n * Three writes, one batch:\n *\n * 1. the billing doc itself, `merge: true` to match what the org-doc write did;\n * 2. the org doc, merged, with what entitlement resolution reads there:\n * `billingStatus`, so the AGL-275 dunning banner keeps working for\n * non-managers who can no longer read `subscription`; and `seatAddons`,\n * which never moved (`ORG_BILLING_MOVED_KEYS`), whenever the patch carries\n * the add-on quantities;\n * 3. the `stripeCustomers` reverse index, so the webhook can still resolve an\n * org from a Stripe customer id without a query.\n *\n * `writeInline` mirrored the keys back onto the org doc as well. It was on\n * during the migration so a rollback lost nothing, and is now OFF: writing them\n * inline is what the whole issue exists to stop, and leaving it on would let the\n * next Stripe webhook silently re-add the fields minutes after they were\n * deleted, re-opening the exposure with nothing to show for it.\n *\n * The option survives for a deliberate one-off rollback, and nothing passes it.\n *\n * The READ fallback in `readOrgBilling` deliberately stays. It costs one get on\n * a doc that no longer exists, and it is the only thing standing between an org\n * the backfill somehow missed and a paying workspace rendering as Free.\n */\nexport async function writeOrgBilling(\n orgId: string,\n patch: Partial<OrgBillingDoc> &\n Pick<OrgInlineBilling, 'seatAddons'> & { aiTier?: AiTierId | null },\n options: { writeInline?: boolean } = {},\n): Promise<void> {\n if (!orgId) return\n const { writeInline = false } = options\n const fields = pickOrgBillingFields(patch as never) as Record<string, unknown>\n // The logical key becomes the mode's PHYSICAL key (AGL-2486). A test-mode\n // write therefore cannot overwrite the live customer id — which it silently\n // did before this, destroying the live linkage on the first completed test\n // checkout.\n const field = customerIdField()\n if (field !== 'stripeCustomerId' && 'stripeCustomerId' in fields) {\n fields[field] = fields['stripeCustomerId']\n delete fields['stripeCustomerId']\n }\n const batch = db().batch()\n const orgRef = db().collection('orgs').doc(orgId)\n\n batch.set(orgBillingRef(orgId), fields, { merge: true })\n\n // The status mirror is derived, so it is only written when this patch\n // actually carries a subscription — otherwise a partial update (a seat-addon\n // change, say) would blank the banner's input.\n const orgPatch: Record<string, unknown> = writeInline ? { ...fields } : {}\n if (patch.subscription !== undefined) {\n orgPatch['billingStatus'] = orgBillingStatusFrom(patch)\n }\n // The add-on quantities are what grants and removes an add-on, and the org\n // doc is the only place they are read from: a subscription sync that wrote\n // them nowhere would charge for an add-on bought at checkout without\n // granting it, and leave a removed one in place. Merged with the rest of\n // this patch, so the explicit zeros of a sync converge while a key the\n // subscription items do not name survives.\n if (patch.seatAddons !== undefined) {\n orgPatch['seatAddons'] = patch.seatAddons\n }\n // Which Aglyn AI tier those quantities hold (AGL-3965), derived from the\n // same items and read from the same document, so it travels with them.\n if (patch.aiTier !== undefined) {\n orgPatch['aiTier'] = patch.aiTier\n }\n if (Object.keys(orgPatch).length) batch.set(orgRef, orgPatch, { merge: true })\n\n // Off the PHYSICAL field, so a test-mode write indexes its own customer.\n // The index needs no mode-keying of its own: it is keyed by the customer id,\n // and Stripe ids are unique across modes, so the live and test entries are\n // two documents that both resolve to this org.\n const customerId = fields[field]\n if (typeof customerId === 'string' && customerId) {\n batch.set(\n db().collection(STRIPE_CUSTOMER_INDEX_COLLECTION).doc(customerId),\n { orgId, updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp() },\n { merge: true },\n )\n }\n\n await batch.commit()\n}\n\n/**\n * Resolves an org id from a Stripe customer id.\n *\n * Prefers the reverse index; falls back to the legacy `where('stripeCustomerId')`\n * query on `orgs` for customers whose index entry has not been written yet.\n * The fallback disappears with the inline fields.\n */\nexport async function findOrgIdByStripeCustomer(\n customerId: string,\n): Promise<string | null> {\n if (!customerId) return null\n const indexed = await db()\n .collection(STRIPE_CUSTOMER_INDEX_COLLECTION)\n .doc(customerId)\n .get()\n const mapped = indexed.get('orgId')\n if (typeof mapped === 'string' && mapped) return mapped\n const legacy = await db()\n .collection('orgs')\n .where('stripeCustomerId', '==', customerId)\n .limit(1)\n .get()\n return legacy.docs[0]?.id ?? null\n}\n\n/** Re-exported so callers do not need a second import to test migration state. */\nexport { hasInlineOrgBilling }\n"],"names":["deploymentLivemode","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","STRIPE_CUSTOMER_ID_TEST_FIELD","STRIPE_CUSTOMER_INDEX_COLLECTION","hasInlineOrgBilling","orgBillingStatusFrom","pickOrgBillingFields","firebaseAdmin","db","app","firestore","customerIdField","projectBillingMode","doc","stored","testId","orgBillingRef","orgId","collection","readOrgBilling","readStoredOrgBilling","billingSnapshot","get","exists","data","orgSnapshot","readOrgBillingCustomerModes","live","test","present","value","length","writeOrgBilling","patch","options","writeInline","fields","field","batch","orgRef","set","merge","orgPatch","subscription","undefined","seatAddons","aiTier","Object","keys","customerId","updatedAt","FieldValue","serverTimestamp","commit","findOrgIdByStripeCustomer","legacy","indexed","mapped","where","limit","docs","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,gDAA+C;AAClF,SACEC,kBAAkB,EAClBC,yBAAyB,EACzBC,6BAA6B,EAC7BC,gCAAgC,EAChCC,mBAAmB,EACnBC,oBAAoB,EACpBC,oBAAoB,QAIf,sBAAqB;AAC5B,SAASC,aAAa,QAAQ,sBAAkB;AAEhD;;;;;;;;CAQC,GAED,MAAMC,KAAK,IAAMD,cAAcE,GAAG,GAAGC,SAAS;AAE9C;;;;;;;;;;;;CAYC,GACD,SAASC;IACP,OAAOZ,uBAAuB,qBAAqBG;AACrD;AAEA;;;;;;;;CAQC,GACD,SAASU,mBAAmBC,GAAkB;IAC5C,MAAMC,SAAS,aAAMD,cAAAA,MAAO,CAAC;IAC7B,MAAME,SAASD,MAAM,CAACZ,8BAA8B;IACpD,wEAAwE;IACxE,0EAA0E;IAC1E,2DAA2D;IAC3D,OAAOY,MAAM,CAACZ,8BAA8B;IAC5C,IAAIH,sBAAsB,OAAOe;IACjC,6DAA6D;IAC7DA,MAAM,CAAC,mBAAmB,GAAIC,iBAAAA,SAAU;IACxC,OAAOD;AACT;AAEA,mCAAmC,GACnC,OAAO,SAASE,cAAcC,KAAa;IACzC,OAAOT,KACJU,UAAU,CAAC,QACXL,GAAG,CAACI,OACJC,UAAU,CAACjB,2BACXY,GAAG,CAACb;AACT;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAemB,eAAeF,KAAa;IAChD,IAAI,CAACA,OAAO,OAAO,CAAC;IACpB,OAAOL,mBAAmB,MAAMQ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,MAAMhD,KACnBU,UAAU,CAACf,kCACXU,GAAG,CAACoC,YACJ3B,GAAG;IACN,MAAMmC,SAASD,QAAQlC,GAAG,CAAC;IAC3B,IAAI,OAAOmC,WAAW,YAAYA,QAAQ,OAAOA;IACjD,MAAMF,SAAS,MAAM/C,KAClBU,UAAU,CAAC,QACXwC,KAAK,CAAC,oBAAoB,MAAMT,YAChCU,KAAK,CAAC,GACNrC,GAAG;IACN,gBAAOiC,gBAAAA,OAAOK,IAAI,CAAC,EAAE,qBAAdL,cAAgBM,EAAE,mBAAI;AAC/B;AAEA,gFAAgF,GAChF,SAASzD,mBAAmB,GAAE"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * SENDING THE SITE CARE EMAILS (AGL-3959).
19
+ *
20
+ * Every Site Care email is a catalog key (`site-care-emails.ts` in
21
+ * `shared-util-email`), rendered in the WORKSPACE's brand — a white-label
22
+ * agency's client hears from the agency — and sent from the platform's
23
+ * address with a Reply-To that threads the answer onto the same request:
24
+ * `support+<requestId>@<inbound mail domain>` (AGL-3997), or the support
25
+ * address for an email about no one request. Metered as platform mail, like
26
+ * the success manager's copy: this is the service the owner pays for, not
27
+ * mail the workspace sent.
28
+ *
29
+ * Never throws. The caller records what it returns as the request's
30
+ * `email.sent` history row, so whether an email went is a fact on the
31
+ * request rather than an assumption.
32
+ */
33
+ /** The address a request's emails reply to, so the answer joins it. */
34
+ export declare function siteCareReplyTo(requestId: string | null): string;
35
+ export interface SiteCareEmailInput {
36
+ key: string;
37
+ to: string | null;
38
+ /** The workspace whose brand the email is sent in; null is the platform's. */
39
+ org: Readonly<Record<string, unknown>> | null;
40
+ requestId: string | null;
41
+ merge: Record<string, string>;
42
+ fallback: {
43
+ subject: string;
44
+ text: string;
45
+ };
46
+ }
47
+ export interface SiteCareEmailResult {
48
+ sent: boolean;
49
+ to: string | null;
50
+ subject: string;
51
+ reason?: string;
52
+ }
53
+ export declare function sendSiteCareEmail(input: SiteCareEmailInput): Promise<SiteCareEmailResult>;
@@ -0,0 +1,97 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { inboundMailDomain } from "@aglyn/aglyn/app-utils/inbound-mail-domain";
18
+ import { siteCareReplyAddress } from "@aglyn/aglyn/app-utils/site-care";
19
+ import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
20
+ import { meterPlatformEmail } from "./email-metering.js";
21
+ import { renderSystemEmailContent, systemEmailBrand } from "./render-system-email.js";
22
+ /**
23
+ * SENDING THE SITE CARE EMAILS (AGL-3959).
24
+ *
25
+ * Every Site Care email is a catalog key (`site-care-emails.ts` in
26
+ * `shared-util-email`), rendered in the WORKSPACE's brand — a white-label
27
+ * agency's client hears from the agency — and sent from the platform's
28
+ * address with a Reply-To that threads the answer onto the same request:
29
+ * `support+<requestId>@<inbound mail domain>` (AGL-3997), or the support
30
+ * address for an email about no one request. Metered as platform mail, like
31
+ * the success manager's copy: this is the service the owner pays for, not
32
+ * mail the workspace sent.
33
+ *
34
+ * Never throws. The caller records what it returns as the request's
35
+ * `email.sent` history row, so whether an email went is a fact on the
36
+ * request rather than an assumption.
37
+ */ /** The address a request's emails reply to, so the answer joins it. */ export function siteCareReplyTo(requestId) {
38
+ return siteCareReplyAddress(requestId, inboundMailDomain());
39
+ }
40
+ export async function sendSiteCareEmail(input) {
41
+ var _input_to;
42
+ const to = String((_input_to = input.to) != null ? _input_to : '').trim();
43
+ if (!to) return {
44
+ sent: false,
45
+ to: null,
46
+ subject: input.fallback.subject,
47
+ reason: 'no-recipient'
48
+ };
49
+ if (!isEmailConfigured()) {
50
+ return {
51
+ sent: false,
52
+ to,
53
+ subject: input.fallback.subject,
54
+ reason: 'unconfigured'
55
+ };
56
+ }
57
+ try {
58
+ var _result_reason;
59
+ const brand = systemEmailBrand(input.org);
60
+ const content = await renderSystemEmailContent(input.key, _extends({}, brand.orgName ? {
61
+ 'org.name': brand.orgName
62
+ } : {}, input.merge), brand, input.fallback);
63
+ const result = await sendEmail(_extends({
64
+ to,
65
+ subject: content.subject,
66
+ text: content.text
67
+ }, content.html ? {
68
+ html: content.html
69
+ } : {}, brand.fromName ? {
70
+ fromName: brand.fromName
71
+ } : {}, {
72
+ replyTo: siteCareReplyTo(input.requestId),
73
+ context: input.key
74
+ }));
75
+ if (result.sent) await meterPlatformEmail();
76
+ return result.sent ? {
77
+ sent: true,
78
+ to,
79
+ subject: content.subject
80
+ } : {
81
+ sent: false,
82
+ to,
83
+ subject: content.subject,
84
+ reason: String((_result_reason = result.reason) != null ? _result_reason : 'not-sent')
85
+ };
86
+ } catch (error) {
87
+ console.error(`[site-care] ${input.key} email failed`, error);
88
+ return {
89
+ sent: false,
90
+ to,
91
+ subject: input.fallback.subject,
92
+ reason: 'error'
93
+ };
94
+ }
95
+ }
96
+
97
+ //# sourceMappingURL=site-care-emails.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-emails.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 { inboundMailDomain } from '@aglyn/aglyn/app-utils/inbound-mail-domain'\nimport { siteCareReplyAddress } from '@aglyn/aglyn/app-utils/site-care'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { meterPlatformEmail } from './email-metering'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\n/**\n * SENDING THE SITE CARE EMAILS (AGL-3959).\n *\n * Every Site Care email is a catalog key (`site-care-emails.ts` in\n * `shared-util-email`), rendered in the WORKSPACE's brand — a white-label\n * agency's client hears from the agency — and sent from the platform's\n * address with a Reply-To that threads the answer onto the same request:\n * `support+<requestId>@<inbound mail domain>` (AGL-3997), or the support\n * address for an email about no one request. Metered as platform mail, like\n * the success manager's copy: this is the service the owner pays for, not\n * mail the workspace sent.\n *\n * Never throws. The caller records what it returns as the request's\n * `email.sent` history row, so whether an email went is a fact on the\n * request rather than an assumption.\n */\n\n/** The address a request's emails reply to, so the answer joins it. */\nexport function siteCareReplyTo(requestId: string | null): string {\n return siteCareReplyAddress(requestId, inboundMailDomain())\n}\n\nexport interface SiteCareEmailInput {\n key: string\n to: string | null\n /** The workspace whose brand the email is sent in; null is the platform's. */\n org: Readonly<Record<string, unknown>> | null\n requestId: string | null\n merge: Record<string, string>\n fallback: { subject: string; text: string }\n}\n\nexport interface SiteCareEmailResult {\n sent: boolean\n to: string | null\n subject: string\n reason?: string\n}\n\nexport async function sendSiteCareEmail(input: SiteCareEmailInput): Promise<SiteCareEmailResult> {\n const to = String(input.to ?? '').trim()\n if (!to) return { sent: false, to: null, subject: input.fallback.subject, reason: 'no-recipient' }\n if (!isEmailConfigured()) {\n return { sent: false, to, subject: input.fallback.subject, reason: 'unconfigured' }\n }\n try {\n const brand = systemEmailBrand(input.org)\n const content = await renderSystemEmailContent(\n input.key,\n { ...(brand.orgName ? { 'org.name': brand.orgName } : {}), ...input.merge },\n brand,\n input.fallback,\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 replyTo: siteCareReplyTo(input.requestId),\n context: input.key,\n })\n if (result.sent) await meterPlatformEmail()\n return result.sent\n ? { sent: true, to, subject: content.subject }\n : {\n sent: false,\n to,\n subject: content.subject,\n reason: String((result as { reason?: unknown }).reason ?? 'not-sent'),\n }\n } catch (error) {\n console.error(`[site-care] ${input.key} email failed`, error)\n return { sent: false, to, subject: input.fallback.subject, reason: 'error' }\n }\n}\n"],"names":["inboundMailDomain","siteCareReplyAddress","isEmailConfigured","sendEmail","meterPlatformEmail","renderSystemEmailContent","systemEmailBrand","siteCareReplyTo","requestId","sendSiteCareEmail","input","to","String","trim","sent","subject","fallback","reason","brand","org","content","key","orgName","merge","result","text","html","fromName","replyTo","context","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,oBAAoB,QAAQ,mCAAkC;AACvE,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,kBAAkB,QAAQ,sBAAkB;AACrD,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,2BAAuB;AAE9B;;;;;;;;;;;;;;;CAeC,GAED,qEAAqE,GACrE,OAAO,SAASC,gBAAgBC,SAAwB;IACtD,OAAOP,qBAAqBO,WAAWR;AACzC;AAmBA,OAAO,eAAeS,kBAAkBC,KA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