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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) 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/host-memberships.d.ts +35 -2
  15. package/src/lib/server/host-memberships.js +63 -2
  16. package/src/lib/server/host-memberships.js.map +1 -1
  17. package/src/lib/server/org-billing.d.ts +4 -2
  18. package/src/lib/server/org-billing.js +5 -0
  19. package/src/lib/server/org-billing.js.map +1 -1
  20. package/src/lib/server/site-care-emails.d.ts +52 -0
  21. package/src/lib/server/site-care-emails.js +97 -0
  22. package/src/lib/server/site-care-emails.js.map +1 -0
  23. package/src/lib/server/site-care-inbound.d.ts +80 -0
  24. package/src/lib/server/site-care-inbound.js +171 -0
  25. package/src/lib/server/site-care-inbound.js.map +1 -0
  26. package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
  27. package/src/lib/server/site-care-project-reconcile.js +211 -0
  28. package/src/lib/server/site-care-project-reconcile.js.map +1 -0
  29. package/src/lib/server/site-care-project-stripe.d.ts +114 -0
  30. package/src/lib/server/site-care-project-stripe.js +305 -0
  31. package/src/lib/server/site-care-project-stripe.js.map +1 -0
  32. package/src/lib/server/site-care-projects.d.ts +169 -0
  33. package/src/lib/server/site-care-projects.js +882 -0
  34. package/src/lib/server/site-care-projects.js.map +1 -0
  35. package/src/lib/server/site-care-reconcile.d.ts +81 -0
  36. package/src/lib/server/site-care-reconcile.js +349 -0
  37. package/src/lib/server/site-care-reconcile.js.map +1 -0
  38. package/src/lib/server/site-care-requests.d.ts +243 -0
  39. package/src/lib/server/site-care-requests.js +1414 -0
  40. package/src/lib/server/site-care-requests.js.map +1 -0
  41. package/src/lib/server/site-care-stripe.d.ts +175 -0
  42. package/src/lib/server/site-care-stripe.js +375 -0
  43. package/src/lib/server/site-care-stripe.js.map +1 -0
  44. package/src/lib/server/upgrade-proposal.d.ts +40 -1
  45. package/src/lib/server/upgrade-proposal.js +92 -50
  46. package/src/lib/server/upgrade-proposal.js.map +1 -1
  47. package/src/tenancy.d.ts +1 -0
  48. package/src/tenancy.js +2 -0
  49. package/src/tenancy.js.map +1 -1
@@ -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,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MAAMY,UAAU;IAC3C;IACA,IAAIC,OAAOC,IAAI,CAACL,UAAUX,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,IA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;QAcXM;IAZP,IAAI,CAACN,YAAY,OAAO;IACxB,MAAMO,UAAU,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,52 @@
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
+ * `care+<requestId>@<inbound mail domain>`. Metered as platform mail, like
25
+ * the success manager's copy: this is the service the owner pays for, not
26
+ * mail the workspace sent.
27
+ *
28
+ * Never throws. The caller records what it returns as the request's
29
+ * `email.sent` history row, so whether an email went is a fact on the
30
+ * request rather than an assumption.
31
+ */
32
+ /** The address a request's emails reply to, so the answer joins it. */
33
+ export declare function siteCareReplyTo(requestId: string | null): string;
34
+ export interface SiteCareEmailInput {
35
+ key: string;
36
+ to: string | null;
37
+ /** The workspace whose brand the email is sent in; null is the platform's. */
38
+ org: Readonly<Record<string, unknown>> | null;
39
+ requestId: string | null;
40
+ merge: Record<string, string>;
41
+ fallback: {
42
+ subject: string;
43
+ text: string;
44
+ };
45
+ }
46
+ export interface SiteCareEmailResult {
47
+ sent: boolean;
48
+ to: string | null;
49
+ subject: string;
50
+ reason?: string;
51
+ }
52
+ 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 { SITE_CARE_INBOUND_LOCAL_PART } 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
+ * `care+<requestId>@<inbound mail domain>`. Metered as platform mail, like
30
+ * the success manager's copy: this is the service the owner pays for, not
31
+ * mail the workspace sent.
32
+ *
33
+ * Never throws. The caller records what it returns as the request's
34
+ * `email.sent` history row, so whether an email went is a fact on the
35
+ * request rather than an assumption.
36
+ */ /** The address a request's emails reply to, so the answer joins it. */ export function siteCareReplyTo(requestId) {
37
+ const local = requestId ? `${SITE_CARE_INBOUND_LOCAL_PART}+${requestId}` : SITE_CARE_INBOUND_LOCAL_PART;
38
+ return `${local}@${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 { SITE_CARE_INBOUND_LOCAL_PART } 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 * `care+<requestId>@<inbound mail domain>`. 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 const local = requestId ? `${SITE_CARE_INBOUND_LOCAL_PART}+${requestId}` : SITE_CARE_INBOUND_LOCAL_PART\n return `${local}@${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","SITE_CARE_INBOUND_LOCAL_PART","isEmailConfigured","sendEmail","meterPlatformEmail","renderSystemEmailContent","systemEmailBrand","siteCareReplyTo","requestId","local","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,4BAA4B,QAAQ,mCAAkC;AAC/E,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,kBAAkB,QAAQ,sBAAkB;AACrD,SACEC,wBAAwB,EACxBC,gBAAg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K,QAAQL,OAAO;QAAC,IAC3C;YACED,MAAM;YACNH;YACAI,SAASK,QAAQL,OAAO;YACxBE,QAAQL,QAAO,iBAAA,AAACY,OAAgCP,MAAM,YAAvC,iBAA2C;QAC5D;IACN,EAAE,OAAOa,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,YAAY,EAAEpB,MAAMW,GAAG,CAAC,aAAa,CAAC,EAAES;QACvD,OAAO;YAAEhB,MAAM;YAAOH;YAAII,SAASL,MAAMM,QAAQ,CAACD,OAAO;YAAEE,QAAQ;QAAQ;IAC7E;AACF"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type ReceivedEmail } from '@aglyn/shared-util-email';
18
+ import { type SiteCareDeps } from './site-care-requests';
19
+ /**
20
+ * THE SITE CARE ADDRESS (AGL-3959): `care@<inbound mail domain>`.
21
+ *
22
+ * An owner emails or forwards a change to the address and it becomes a Site
23
+ * Care request on their workspace, matched by the sender's address against
24
+ * the members of workspaces that have Site Care. A reply to any Site Care
25
+ * email goes to `care+<requestId>@…` and joins that request's thread, when
26
+ * the sender is a member of its workspace. A sender who matches nobody gets
27
+ * a reply asking them to write from the address on the account; the message
28
+ * itself is not kept.
29
+ */
30
+ /** What a received message was addressed to, of the Site Care address. */
31
+ export type SiteCareInboundTarget = {
32
+ kind: 'new';
33
+ } | {
34
+ kind: 'reply';
35
+ requestId: string;
36
+ };
37
+ /** The Site Care target among a message's recipients, or null. */
38
+ export declare function siteCareInboundTarget(recipients: readonly string[], domain: string): SiteCareInboundTarget | null;
39
+ export interface SiteCareSenderMatch {
40
+ orgId: string;
41
+ org: Record<string, unknown>;
42
+ uid: string;
43
+ email: string;
44
+ }
45
+ /** The account an address signs in with: its uid, or null when it has none. */
46
+ export type SiteCareAccountLookup = (email: string) => Promise<{
47
+ uid: string;
48
+ } | null>;
49
+ /**
50
+ * Every pool, not only the project's: an owner who signs in through SSO is a
51
+ * GCIP tenant user the project pool never returns (AGL-1122), and their mail
52
+ * would be answered as a stranger's.
53
+ */
54
+ export declare const findSiteCareAccount: SiteCareAccountLookup;
55
+ /**
56
+ * The Site Care workspace a sender belongs to: the account their address
57
+ * signs in with (in any pool), then the workspaces it is a member of, the
58
+ * first with Site Care in force (by id, so the choice is stable).
59
+ */
60
+ export declare function findSiteCareWorkspaceForSender(firestore: FirebaseFirestore.Firestore, findAccount: SiteCareAccountLookup, sender: string): Promise<SiteCareSenderMatch | null>;
61
+ /** The words of a message, above any quoted history. */
62
+ export declare function siteCareMessageBody(message: Pick<ReceivedEmail, 'text' | 'html'>): string;
63
+ export type SiteCareInboundOutcome = {
64
+ outcome: 'opened';
65
+ requestId: string;
66
+ } | {
67
+ outcome: 'replied';
68
+ requestId: string;
69
+ } | {
70
+ outcome: 'unknown-sender';
71
+ } | {
72
+ outcome: 'empty';
73
+ };
74
+ /** Files one received message addressed to the Site Care address. */
75
+ export declare function fileSiteCareInboundEmail(firestore: FirebaseFirestore.Firestore, input: {
76
+ target: SiteCareInboundTarget;
77
+ message: ReceivedEmail;
78
+ /** The seam a spec replaces; every auth pool by default. */
79
+ findAccount?: SiteCareAccountLookup;
80
+ }, deps?: SiteCareDeps): Promise<SiteCareInboundOutcome>;
@@ -0,0 +1,171 @@
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
+ */ import { emailAddressOf, htmlToPlainText, stripQuotedHistory, threadSubject } from "@aglyn/aglyn/app-utils/email-text";
17
+ import { SITE_CARE_INBOUND_LOCAL_PART } from "@aglyn/aglyn/app-utils/site-care";
18
+ import { SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY } from "@aglyn/shared-util-email";
19
+ import { appendSiteCareReply, openSiteCareRequest, orgHasSiteCare, readSiteCareOrg } from "./site-care-requests.js";
20
+ import { findUserByEmailAcrossPools } from "./auth-pools.js";
21
+ import { sendSiteCareEmail } from "./site-care-emails.js";
22
+ /** The Site Care target among a message's recipients, or null. */ export function siteCareInboundTarget(recipients, domain) {
23
+ let found = null;
24
+ for (const value of recipients){
25
+ var _ref;
26
+ var _exec;
27
+ // Validated (and lowercased) for the domain, but the local part is read
28
+ // as written: a request id is a case-sensitive Firestore id, and
29
+ // lowercasing `care+AbC…` would look up a ticket that does not exist.
30
+ const address = emailAddressOf(value);
31
+ if (!address) continue;
32
+ const raw = String(value != null ? value : '').trim();
33
+ const written = ((_ref = (_exec = /<([^<>]+)>\s*$/.exec(raw)) == null ? void 0 : _exec[1]) != null ? _ref : raw).trim();
34
+ const at = written.lastIndexOf('@');
35
+ if (at <= 0 || address.slice(address.lastIndexOf('@') + 1) !== domain.toLowerCase()) continue;
36
+ const local = written.slice(0, at);
37
+ if (local.toLowerCase() === SITE_CARE_INBOUND_LOCAL_PART) {
38
+ found = found != null ? found : {
39
+ kind: 'new'
40
+ };
41
+ continue;
42
+ }
43
+ const prefix = `${SITE_CARE_INBOUND_LOCAL_PART}+`;
44
+ if (local.toLowerCase().startsWith(prefix)) {
45
+ const requestId = local.slice(prefix.length);
46
+ // Firestore ids: 20 characters of [A-Za-z0-9]; anything else by shape
47
+ // is refused rather than looked up.
48
+ if (/^[A-Za-z0-9]{10,40}$/.test(requestId)) return {
49
+ kind: 'reply',
50
+ requestId
51
+ };
52
+ }
53
+ }
54
+ return found;
55
+ }
56
+ /**
57
+ * Every pool, not only the project's: an owner who signs in through SSO is a
58
+ * GCIP tenant user the project pool never returns (AGL-1122), and their mail
59
+ * would be answered as a stranger's.
60
+ */ export const findSiteCareAccount = async (email)=>{
61
+ const found = await findUserByEmailAcrossPools(email).catch(()=>null);
62
+ return found ? {
63
+ uid: found.record.uid
64
+ } : null;
65
+ };
66
+ /**
67
+ * The Site Care workspace a sender belongs to: the account their address
68
+ * signs in with (in any pool), then the workspaces it is a member of, the
69
+ * first with Site Care in force (by id, so the choice is stable).
70
+ */ export async function findSiteCareWorkspaceForSender(firestore, findAccount, sender) {
71
+ const email = emailAddressOf(sender);
72
+ if (!email) return null;
73
+ const user = await findAccount(email).catch(()=>null);
74
+ if (!user) return null;
75
+ const memberships = await firestore.collection('users').doc(user.uid).collection('orgs').limit(25).get();
76
+ const orgIds = memberships.docs.map((doc)=>doc.id).sort();
77
+ for (const orgId of orgIds){
78
+ const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(user.uid).get();
79
+ if (!member.exists) continue;
80
+ const org = await readSiteCareOrg(firestore, orgId);
81
+ if (org && orgHasSiteCare(org)) return {
82
+ orgId,
83
+ org,
84
+ uid: user.uid,
85
+ email
86
+ };
87
+ }
88
+ return null;
89
+ }
90
+ /** The words of a message, above any quoted history. */ export function siteCareMessageBody(message) {
91
+ var _message_text;
92
+ const plain = (((_message_text = message.text) == null ? void 0 : _message_text.trim()) ? message.text : htmlToPlainText(message.html)).replace(/\r\n?/g, '\n');
93
+ return stripQuotedHistory(plain).trim();
94
+ }
95
+ /** Files one received message addressed to the Site Care address. */ export async function fileSiteCareInboundEmail(firestore, input, deps = {}) {
96
+ var _input_findAccount;
97
+ const { message } = input;
98
+ const body = siteCareMessageBody(message);
99
+ const sender = emailAddressOf(message.from);
100
+ if (input.target.kind === 'reply') {
101
+ var _ticket_get, _input_findAccount1;
102
+ const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get();
103
+ const orgId = String((_ticket_get = ticket.get('orgId')) != null ? _ticket_get : '');
104
+ const match = sender ? await findSiteCareWorkspaceForSender(firestore, (_input_findAccount1 = input.findAccount) != null ? _input_findAccount1 : findSiteCareAccount, sender) : null;
105
+ // Only a member of the request's own workspace may add to it.
106
+ const member = match && orgId ? (await firestore.collection('orgs').doc(orgId).collection('members').doc(match.uid).get()).exists : false;
107
+ if (ticket.exists && member && match) {
108
+ if (!body) return {
109
+ outcome: 'empty'
110
+ };
111
+ await appendSiteCareReply(firestore, {
112
+ ticketId: ticket.id,
113
+ from: {
114
+ uid: match.uid,
115
+ email: match.email
116
+ },
117
+ body,
118
+ dedupeKey: message.messageId || message.id
119
+ }, deps);
120
+ return {
121
+ outcome: 'replied',
122
+ requestId: ticket.id
123
+ };
124
+ }
125
+ // A reply that cannot join its request is read as a new one below.
126
+ }
127
+ const match = sender ? await findSiteCareWorkspaceForSender(firestore, (_input_findAccount = input.findAccount) != null ? _input_findAccount : findSiteCareAccount, sender) : null;
128
+ if (!match) {
129
+ if (sender) {
130
+ var _deps_email;
131
+ await ((_deps_email = deps.email) != null ? _deps_email : sendSiteCareEmail)({
132
+ key: SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY,
133
+ to: sender,
134
+ org: null,
135
+ requestId: null,
136
+ merge: {
137
+ 'sender.email': sender
138
+ },
139
+ fallback: {
140
+ subject: 'We could not match your email to an account',
141
+ text: `We got your message from ${sender}, but no workspace with Site Care has that address as a member. ` + 'Please send it again from the email address you sign in with.'
142
+ }
143
+ });
144
+ }
145
+ return {
146
+ outcome: 'unknown-sender'
147
+ };
148
+ }
149
+ if (!body && !threadSubject(message.subject)) return {
150
+ outcome: 'empty'
151
+ };
152
+ const opened = await openSiteCareRequest(firestore, {
153
+ orgId: match.orgId,
154
+ org: match.org,
155
+ hostId: null,
156
+ subject: threadSubject(message.subject) || body.split('\n')[0].slice(0, 150) || 'A change by email',
157
+ body: body || threadSubject(message.subject),
158
+ requester: {
159
+ uid: match.uid,
160
+ email: match.email
161
+ },
162
+ source: 'email',
163
+ dedupeKey: message.messageId || message.id
164
+ }, deps);
165
+ return {
166
+ outcome: 'opened',
167
+ requestId: opened.ticketId
168
+ };
169
+ }
170
+
171
+ //# sourceMappingURL=site-care-inbound.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-inbound.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n emailAddressOf,\n htmlToPlainText,\n stripQuotedHistory,\n threadSubject,\n} from '@aglyn/aglyn/app-utils/email-text'\nimport { SITE_CARE_INBOUND_LOCAL_PART } from '@aglyn/aglyn/app-utils/site-care'\nimport {\n SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY,\n type ReceivedEmail,\n} from '@aglyn/shared-util-email'\nimport {\n appendSiteCareReply,\n openSiteCareRequest,\n orgHasSiteCare,\n readSiteCareOrg,\n type SiteCareDeps,\n} from './site-care-requests'\nimport { findUserByEmailAcrossPools } from './auth-pools'\nimport { sendSiteCareEmail } from './site-care-emails'\n\n/**\n * THE SITE CARE ADDRESS (AGL-3959): `care@<inbound mail domain>`.\n *\n * An owner emails or forwards a change to the address and it becomes a Site\n * Care request on their workspace, matched by the sender's address against\n * the members of workspaces that have Site Care. A reply to any Site Care\n * email goes to `care+<requestId>@…` and joins that request's thread, when\n * the sender is a member of its workspace. A sender who matches nobody gets\n * a reply asking them to write from the address on the account; the message\n * itself is not kept.\n */\n\n/** What a received message was addressed to, of the Site Care address. */\nexport type SiteCareInboundTarget = { kind: 'new' } | { kind: 'reply'; requestId: string }\n\n/** The Site Care target among a message's recipients, or null. */\nexport function siteCareInboundTarget(\n recipients: readonly string[],\n domain: string,\n): SiteCareInboundTarget | null {\n let found: SiteCareInboundTarget | null = null\n for (const value of recipients) {\n // Validated (and lowercased) for the domain, but the local part is read\n // as written: a request id is a case-sensitive Firestore id, and\n // lowercasing `care+AbC…` would look up a ticket that does not exist.\n const address = emailAddressOf(value)\n if (!address) continue\n const raw = String(value ?? '').trim()\n const written = (/<([^<>]+)>\\s*$/.exec(raw)?.[1] ?? raw).trim()\n const at = written.lastIndexOf('@')\n if (at <= 0 || address.slice(address.lastIndexOf('@') + 1) !== domain.toLowerCase()) continue\n const local = written.slice(0, at)\n if (local.toLowerCase() === SITE_CARE_INBOUND_LOCAL_PART) {\n found = found ?? { kind: 'new' }\n continue\n }\n const prefix = `${SITE_CARE_INBOUND_LOCAL_PART}+`\n if (local.toLowerCase().startsWith(prefix)) {\n const requestId = local.slice(prefix.length)\n // Firestore ids: 20 characters of [A-Za-z0-9]; anything else by shape\n // is refused rather than looked up.\n if (/^[A-Za-z0-9]{10,40}$/.test(requestId)) return { kind: 'reply', requestId }\n }\n }\n return found\n}\n\nexport interface SiteCareSenderMatch {\n orgId: string\n org: Record<string, unknown>\n uid: string\n email: string\n}\n\n/** The account an address signs in with: its uid, or null when it has none. */\nexport type SiteCareAccountLookup = (email: string) => Promise<{ uid: string } | null>\n\n/**\n * Every pool, not only the project's: an owner who signs in through SSO is a\n * GCIP tenant user the project pool never returns (AGL-1122), and their mail\n * would be answered as a stranger's.\n */\nexport const findSiteCareAccount: SiteCareAccountLookup = async (email) => {\n const found = await findUserByEmailAcrossPools(email).catch(() => null)\n return found ? { uid: found.record.uid } : null\n}\n\n/**\n * The Site Care workspace a sender belongs to: the account their address\n * signs in with (in any pool), then the workspaces it is a member of, the\n * first with Site Care in force (by id, so the choice is stable).\n */\nexport async function findSiteCareWorkspaceForSender(\n firestore: FirebaseFirestore.Firestore,\n findAccount: SiteCareAccountLookup,\n sender: string,\n): Promise<SiteCareSenderMatch | null> {\n const email = emailAddressOf(sender)\n if (!email) return null\n const user = await findAccount(email).catch(() => null)\n if (!user) return null\n const memberships = await firestore.collection('users').doc(user.uid).collection('orgs').limit(25).get()\n const orgIds = memberships.docs.map((doc) => doc.id).sort()\n for (const orgId of orgIds) {\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(user.uid).get()\n if (!member.exists) continue\n const org = await readSiteCareOrg(firestore, orgId)\n if (org && orgHasSiteCare(org)) return { orgId, org, uid: user.uid, email }\n }\n return null\n}\n\n/** The words of a message, above any quoted history. */\nexport function siteCareMessageBody(message: Pick<ReceivedEmail, 'text' | 'html'>): string {\n const plain = (message.text?.trim() ? message.text : htmlToPlainText(message.html)).replace(/\\r\\n?/g, '\\n')\n return stripQuotedHistory(plain).trim()\n}\n\nexport type SiteCareInboundOutcome =\n | { outcome: 'opened'; requestId: string }\n | { outcome: 'replied'; requestId: string }\n | { outcome: 'unknown-sender' }\n | { outcome: 'empty' }\n\n/** Files one received message addressed to the Site Care address. */\nexport async function fileSiteCareInboundEmail(\n firestore: FirebaseFirestore.Firestore,\n input: {\n target: SiteCareInboundTarget\n message: ReceivedEmail\n /** The seam a spec replaces; every auth pool by default. */\n findAccount?: SiteCareAccountLookup\n },\n deps: SiteCareDeps = {},\n): Promise<SiteCareInboundOutcome> {\n const { message } = input\n const body = siteCareMessageBody(message)\n const sender = emailAddressOf(message.from)\n if (input.target.kind === 'reply') {\n const ticket = await firestore.collection('supportTickets').doc(input.target.requestId).get()\n const orgId = String(ticket.get('orgId') ?? '')\n const match = sender ? await findSiteCareWorkspaceForSender(firestore, input.findAccount ?? findSiteCareAccount, sender) : null\n // Only a member of the request's own workspace may add to it.\n const member =\n match && orgId\n ? (await firestore.collection('orgs').doc(orgId).collection('members').doc(match.uid).get()).exists\n : false\n if (ticket.exists && member && match) {\n if (!body) return { outcome: 'empty' }\n await appendSiteCareReply(\n firestore,\n {\n ticketId: ticket.id,\n from: { uid: match.uid, email: match.email },\n body,\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'replied', requestId: ticket.id }\n }\n // A reply that cannot join its request is read as a new one below.\n }\n const match = sender ? await findSiteCareWorkspaceForSender(firestore, input.findAccount ?? findSiteCareAccount, sender) : null\n if (!match) {\n if (sender) {\n await (deps.email ?? sendSiteCareEmail)({\n key: SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY,\n to: sender,\n org: null,\n requestId: null,\n merge: { 'sender.email': sender },\n fallback: {\n subject: 'We could not match your email to an account',\n text:\n `We got your message from ${sender}, but no workspace with Site Care has that address as a member. ` +\n 'Please send it again from the email address you sign in with.',\n },\n })\n }\n return { outcome: 'unknown-sender' }\n }\n if (!body && !threadSubject(message.subject)) return { outcome: 'empty' }\n const opened = await openSiteCareRequest(\n firestore,\n {\n orgId: match.orgId,\n org: match.org,\n hostId: null,\n subject: threadSubject(message.subject) || body.split('\\n')[0].slice(0, 150) || 'A change by email',\n body: body || threadSubject(message.subject),\n requester: { uid: match.uid, email: match.email },\n source: 'email',\n dedupeKey: message.messageId || message.id,\n },\n deps,\n )\n return { outcome: 'opened', requestId: opened.ticketId }\n}\n"],"names":["emailAddressOf","htmlToPlainText","stripQuotedHistory","threadSubject","SITE_CARE_INBOUND_LOCAL_PART","SITE_CARE_UNKNOWN_SENDER_EMAIL_KEY","appendSiteCareReply","openSiteCareRequest","orgHasSiteCare","readSiteCareOrg","findUserByEmailAcrossPools","sendSiteCareEmail","siteCareInboundTarget","recipients","domain","found","value","address","raw","String","trim","written","exec","at","lastIndexOf","slice","toLowerCase","local","kind","prefix","startsWith","requestId","length","test","findSiteCareAccount","email","catch","uid","record","findSiteCareWorkspaceForSender","firestore","findAccount","sender","user","memberships","collection","doc","limit","get","orgIds","docs","map","id","sort","orgId","member","exists","org","siteCareMessageBody","message","plain","text","html","replace","fileSiteCareInboundEmail","input","deps","body","from","target","ticket","match","outcome","ticketId","dedupeKey","messageId","key","to","merge","fallback","subject","opened","hostId","split","requester","source"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,eAAe,EACfC,kBAAkB,EAClBC,aAAa,QACR,oCAAmC;AAC1C,SAASC,4BAA4B,QAAQ,mCAAkC;AAC/E,SACEC,kCAAkC,QAE7B,2BAA0B;AACjC,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,cAAc,EACdC,eAAe,QAEV,0BAAsB;AAC7B,SAASC,0BAA0B,QAAQ,kBAAc;AACzD,SAASC,iBAAiB,QAAQ,wBAAoB;AAiBtD,gEAAgE,GAChE,OAAO,SAASC,sBACdC,UAA6B,EAC7BC,MAAc;IAEd,IAAIC,QAAsC;IAC1C,KAAK,MAAMC,SAASH,WAAY;;YAOb;QANjB,wEAAwE;QACxE,iEAAiE;QACjE,sEAAsE;QACtE,MAAMI,UAAUjB,eAAegB;QAC/B,IAAI,CAACC,SAAS;QACd,MAAMC,MAAMC,OAAOH,gBAAAA,QAAS,IAAII,IAAI;QACpC,MAAMC,UAAU,UAAC,QAAA,iBAAiBC,IAAI,CAACJ,yBAAtB,KAA4B,CAAC,EAAE,mBAAIA,KAAKE,IAAI;QAC7D,MAAMG,KAAKF,QAAQG,WAAW,CAAC;QAC/B,IAAID,MAAM,KAAKN,QAAQQ,KAAK,CAACR,QAAQO,WAAW,CAAC,OAAO,OAAOV,OAAOY,WAAW,IAAI;QACrF,MAAMC,QAAQN,QAAQI,KAAK,CAAC,GAAGF;QAC/B,IAAII,MAAMD,WAAW,OAAOtB,8BAA8B;YACxDW,QAAQA,gBAAAA,QAAS;gBAAEa,MAAM;YAAM;YAC/B;QACF;QACA,MAAMC,SAAS,GAAGzB,6BAA6B,CAAC,CAAC;QACjD,IAAIuB,M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IhB,QAAQP,EAAE;IAC5C,GACAc;IAEF,OAAO;QAAEM,SAAS;QAAUzC,WAAWkD,OAAOR,QAAQ;IAAC;AACzD"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type SiteCareProject } from '@aglyn/aglyn/app-utils/site-care-project';
18
+ import { type ProjectInvoiceState } from './site-care-project-stripe';
19
+ import type { SiteCareStripeOptions } from './site-care-stripe';
20
+ /**
21
+ * SITE CARE PROJECTS IN THE DAILY RECONCILIATION (AGL-3970).
22
+ *
23
+ * The same scheduled check as extra time (`reconcileSiteCare` calls this):
24
+ * each project invoice the record holds against the Stripe invoice it
25
+ * names — status, and the amount before tax — and each Stripe invoice that
26
+ * names a project against a record that holds it. Any difference is a
27
+ * finding on `billing.siteCareReconciliation`. It compares and reports and
28
+ * never changes either side: the fix is a person's, from the project.
29
+ */
30
+ export type SiteCareProjectFindingCode = 'project-invoice-stuck' | 'project-invoice-failed' | 'project-invoice-missing' | 'project-invoice-status' | 'project-invoice-amount' | 'project-invoice-without-row' | 'project-status';
31
+ export interface SiteCareProjectFinding {
32
+ orgId: string;
33
+ projectId: string | null;
34
+ code: SiteCareProjectFindingCode;
35
+ detail: string;
36
+ }
37
+ export interface ProjectRow {
38
+ id: string;
39
+ project: SiteCareProject;
40
+ /** The status stored on the document, which every write recomputes. */
41
+ storedStatus: string;
42
+ }
43
+ /** Compares one workspace's projects with its Stripe invoices. Pure. */
44
+ export declare function compareSiteCareProjects(input: {
45
+ orgId: string;
46
+ projects: readonly ProjectRow[];
47
+ /** Every Stripe invoice the record names, plus any listed that name a project. */
48
+ invoices: ReadonlyMap<string, ProjectInvoiceState | null>;
49
+ /** Listed invoices that name one of this workspace's projects. */
50
+ listed: readonly ProjectInvoiceState[];
51
+ }): SiteCareProjectFinding[];
52
+ export interface SiteCareProjectReconcileResult {
53
+ projects: number;
54
+ findings: SiteCareProjectFinding[];
55
+ errors: string[];
56
+ }
57
+ /**
58
+ * Reads every project still open, or settled within the window, and
59
+ * compares each workspace's with Stripe.
60
+ */
61
+ export declare function reconcileSiteCareProjects(firestore: FirebaseFirestore.Firestore, input: {
62
+ nowMs: number;
63
+ stripe?: SiteCareStripeOptions;
64
+ }): Promise<SiteCareProjectReconcileResult>;