@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
@@ -0,0 +1,211 @@
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 { readSiteCareProject, siteCareProjectStatus } from "@aglyn/aglyn/app-utils/site-care-project";
18
+ import { readOrgBilling } from "./org-billing.js";
19
+ import { listProjectInvoices, readProjectInvoice, SITE_CARE_PROJECT_METADATA_KEY } from "./site-care-project-stripe.js";
20
+ import { SITE_CARE_PROJECTS_COLLECTION } from "./site-care-projects.js";
21
+ /** The Stripe statuses a recorded invoice status may be in. */ const EXPECTED = {
22
+ open: [
23
+ 'open'
24
+ ],
25
+ paid: [
26
+ 'paid'
27
+ ],
28
+ voided: [
29
+ 'void'
30
+ ],
31
+ // A fully credited open invoice is closed by Stripe as paid at nothing.
32
+ credited: [
33
+ 'paid',
34
+ 'void'
35
+ ],
36
+ refunded: [
37
+ 'paid'
38
+ ]
39
+ };
40
+ /** Compares one workspace's projects with its Stripe invoices. Pure. */ export function compareSiteCareProjects(input) {
41
+ const findings = [];
42
+ const claimed = new Set();
43
+ for (const row of input.projects){
44
+ const { project } = row;
45
+ const at = {
46
+ orgId: input.orgId,
47
+ projectId: row.id
48
+ };
49
+ const derived = siteCareProjectStatus(project);
50
+ if (row.storedStatus && row.storedStatus !== derived) {
51
+ findings.push(_extends({}, at, {
52
+ code: 'project-status',
53
+ detail: `“${project.title}” is stored as ${row.storedStatus} but its record reads ${derived}.`
54
+ }));
55
+ }
56
+ for (const invoice of project.invoices){
57
+ var _input_invoices_get, _EXPECTED_invoice_status;
58
+ if (invoice.invoiceId) claimed.add(invoice.invoiceId);
59
+ const name = `“${project.title}” invoice ${invoice.seq} (${invoice.kind})`;
60
+ if (invoice.status === 'creating') {
61
+ findings.push(_extends({}, at, {
62
+ code: 'project-invoice-stuck',
63
+ detail: `${name} was started and never recorded. Retry it from the project.`
64
+ }));
65
+ continue;
66
+ }
67
+ if (invoice.status === 'failed') {
68
+ var _invoice_error;
69
+ findings.push(_extends({}, at, {
70
+ code: 'project-invoice-failed',
71
+ detail: `${name} failed (${(_invoice_error = invoice.error) != null ? _invoice_error : 'unknown'}). Retry it from the project.`
72
+ }));
73
+ continue;
74
+ }
75
+ if (!invoice.invoiceId) {
76
+ findings.push(_extends({}, at, {
77
+ code: 'project-invoice-missing',
78
+ detail: `${name} is ${invoice.status} with no Stripe invoice.`
79
+ }));
80
+ continue;
81
+ }
82
+ const stripe = (_input_invoices_get = input.invoices.get(invoice.invoiceId)) != null ? _input_invoices_get : null;
83
+ if (!stripe) {
84
+ findings.push(_extends({}, at, {
85
+ code: 'project-invoice-missing',
86
+ detail: `${name}: Stripe invoice ${invoice.invoiceId} is gone.`
87
+ }));
88
+ continue;
89
+ }
90
+ const expected = (_EXPECTED_invoice_status = EXPECTED[invoice.status]) != null ? _EXPECTED_invoice_status : [];
91
+ if (!expected.includes(stripe.status)) {
92
+ findings.push(_extends({}, at, {
93
+ code: 'project-invoice-status',
94
+ detail: invoice.status === 'open' && stripe.status === 'paid' ? `${name} is paid in Stripe but not recorded. Use Check payments on the project.` : `${name} is ${invoice.status} here and ${stripe.status} in Stripe (${invoice.invoiceId}).`
95
+ }));
96
+ }
97
+ if (stripe.subtotalCents !== invoice.amountCents) {
98
+ findings.push(_extends({}, at, {
99
+ code: 'project-invoice-amount',
100
+ detail: `${name}: Stripe bills ${stripe.subtotalCents} cents before tax, the record ${invoice.amountCents}.`
101
+ }));
102
+ }
103
+ }
104
+ }
105
+ for (const invoice of input.listed){
106
+ var _invoice_metadata_SITE_CARE_PROJECT_METADATA_KEY;
107
+ if (claimed.has(invoice.invoiceId)) continue;
108
+ if (invoice.status === 'void') continue;
109
+ findings.push({
110
+ orgId: input.orgId,
111
+ projectId: (_invoice_metadata_SITE_CARE_PROJECT_METADATA_KEY = invoice.metadata[SITE_CARE_PROJECT_METADATA_KEY]) != null ? _invoice_metadata_SITE_CARE_PROJECT_METADATA_KEY : null,
112
+ code: 'project-invoice-without-row',
113
+ detail: `Stripe invoice ${invoice.invoiceId} (${invoice.status}, ${invoice.subtotalCents} cents) names project ${invoice.metadata[SITE_CARE_PROJECT_METADATA_KEY]}, which does not record it.`
114
+ });
115
+ }
116
+ return findings;
117
+ }
118
+ /** How far back a settled project is still compared. */ const SETTLED_WINDOW_MS = 70 * 24 * 60 * 60 * 1000;
119
+ /**
120
+ * Reads every project still open, or settled within the window, and
121
+ * compares each workspace's with Stripe.
122
+ */ export async function reconcileSiteCareProjects(firestore, input) {
123
+ const snapshot = await firestore.collectionGroup(SITE_CARE_PROJECTS_COLLECTION).limit(2000).get();
124
+ const byOrg = new Map();
125
+ for (const doc of snapshot.docs){
126
+ var _byOrg_get, _doc_get;
127
+ const project = readSiteCareProject(doc.data());
128
+ if (!(project == null ? void 0 : project.orgId)) continue;
129
+ const settled = project.status === 'paid' || project.status === 'refunded' || project.status === 'quoted';
130
+ if (settled && input.nowMs - project.updatedAtMs > SETTLED_WINDOW_MS) continue;
131
+ const rows = (_byOrg_get = byOrg.get(project.orgId)) != null ? _byOrg_get : [];
132
+ rows.push({
133
+ id: doc.id,
134
+ project,
135
+ storedStatus: String((_doc_get = doc.get('status')) != null ? _doc_get : '')
136
+ });
137
+ byOrg.set(project.orgId, rows);
138
+ }
139
+ const result = {
140
+ projects: 0,
141
+ findings: [],
142
+ errors: []
143
+ };
144
+ for (const [orgId, rows] of byOrg){
145
+ result.projects += rows.length;
146
+ try {
147
+ var _billing_stripeCustomerId;
148
+ const invoiced = rows.filter((row)=>row.project.invoices.length);
149
+ if (!invoiced.length) {
150
+ result.findings.push(...compareSiteCareProjects({
151
+ orgId,
152
+ projects: rows,
153
+ invoices: new Map(),
154
+ listed: []
155
+ }));
156
+ continue;
157
+ }
158
+ const billing = await readOrgBilling(orgId);
159
+ const customerId = String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '');
160
+ if (!customerId) {
161
+ result.findings.push({
162
+ orgId,
163
+ projectId: null,
164
+ code: 'project-invoice-missing',
165
+ detail: 'Project invoices are recorded but the workspace has no Stripe customer.'
166
+ });
167
+ continue;
168
+ }
169
+ const sinceMs = Math.min(...invoiced.map((row)=>row.project.createdAtMs));
170
+ const list = await listProjectInvoices({
171
+ customerId,
172
+ sinceMs
173
+ }, input.stripe);
174
+ if (list.ok === false) {
175
+ result.errors.push(`${orgId}: ${list.error}`);
176
+ continue;
177
+ }
178
+ const projectIds = new Set(rows.map((row)=>row.id));
179
+ const listed = list.invoices.filter((row)=>{
180
+ var _row_metadata_SITE_CARE_PROJECT_METADATA_KEY;
181
+ return projectIds.has((_row_metadata_SITE_CARE_PROJECT_METADATA_KEY = row.metadata[SITE_CARE_PROJECT_METADATA_KEY]) != null ? _row_metadata_SITE_CARE_PROJECT_METADATA_KEY : '');
182
+ });
183
+ const invoices = new Map(list.invoices.map((row)=>[
184
+ row.invoiceId,
185
+ row
186
+ ]));
187
+ for (const row of invoiced){
188
+ for (const invoice of row.project.invoices){
189
+ if (!invoice.invoiceId || invoices.has(invoice.invoiceId)) continue;
190
+ const read = await readProjectInvoice(invoice.invoiceId, input.stripe);
191
+ if (read.ok === false) {
192
+ result.errors.push(`${orgId}/${row.id}: ${read.error}`);
193
+ continue;
194
+ }
195
+ invoices.set(invoice.invoiceId, read.state);
196
+ }
197
+ }
198
+ result.findings.push(...compareSiteCareProjects({
199
+ orgId,
200
+ projects: rows,
201
+ invoices,
202
+ listed
203
+ }));
204
+ } catch (error) {
205
+ result.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`);
206
+ }
207
+ }
208
+ return result;
209
+ }
210
+
211
+ //# sourceMappingURL=site-care-project-reconcile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-project-reconcile.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 readSiteCareProject,\n siteCareProjectStatus,\n type SiteCareProject,\n type SiteCareProjectInvoiceStatus,\n} from '@aglyn/aglyn/app-utils/site-care-project'\nimport { readOrgBilling } from './org-billing'\nimport {\n listProjectInvoices,\n readProjectInvoice,\n SITE_CARE_PROJECT_METADATA_KEY,\n type ProjectInvoiceState,\n} from './site-care-project-stripe'\nimport { SITE_CARE_PROJECTS_COLLECTION } from './site-care-projects'\nimport type { SiteCareStripeOptions } from './site-care-stripe'\n\n/**\n * SITE CARE PROJECTS IN THE DAILY RECONCILIATION (AGL-3970).\n *\n * The same scheduled check as extra time (`reconcileSiteCare` calls this):\n * each project invoice the record holds against the Stripe invoice it\n * names — status, and the amount before tax — and each Stripe invoice that\n * names a project against a record that holds it. Any difference is a\n * finding on `billing.siteCareReconciliation`. It compares and reports and\n * never changes either side: the fix is a person's, from the project.\n */\n\nexport type SiteCareProjectFindingCode =\n | 'project-invoice-stuck'\n | 'project-invoice-failed'\n | 'project-invoice-missing'\n | 'project-invoice-status'\n | 'project-invoice-amount'\n | 'project-invoice-without-row'\n | 'project-status'\n\nexport interface SiteCareProjectFinding {\n orgId: string\n projectId: string | null\n code: SiteCareProjectFindingCode\n detail: string\n}\n\nexport interface ProjectRow {\n id: string\n project: SiteCareProject\n /** The status stored on the document, which every write recomputes. */\n storedStatus: string\n}\n\n/** The Stripe statuses a recorded invoice status may be in. */\nconst EXPECTED: Readonly<Partial<Record<SiteCareProjectInvoiceStatus, readonly string[]>>> = {\n open: ['open'],\n paid: ['paid'],\n voided: ['void'],\n // A fully credited open invoice is closed by Stripe as paid at nothing.\n credited: ['paid', 'void'],\n refunded: ['paid'],\n}\n\n/** Compares one workspace's projects with its Stripe invoices. Pure. */\nexport function compareSiteCareProjects(input: {\n orgId: string\n projects: readonly ProjectRow[]\n /** Every Stripe invoice the record names, plus any listed that name a project. */\n invoices: ReadonlyMap<string, ProjectInvoiceState | null>\n /** Listed invoices that name one of this workspace's projects. */\n listed: readonly ProjectInvoiceState[]\n}): SiteCareProjectFinding[] {\n const findings: SiteCareProjectFinding[] = []\n const claimed = new Set<string>()\n for (const row of input.projects) {\n const { project } = row\n const at = { orgId: input.orgId, projectId: row.id }\n const derived = siteCareProjectStatus(project)\n if (row.storedStatus && row.storedStatus !== derived) {\n findings.push({ ...at, code: 'project-status', detail: `“${project.title}” is stored as ${row.storedStatus} but its record reads ${derived}.` })\n }\n for (const invoice of project.invoices) {\n if (invoice.invoiceId) claimed.add(invoice.invoiceId)\n const name = `“${project.title}” invoice ${invoice.seq} (${invoice.kind})`\n if (invoice.status === 'creating') {\n findings.push({ ...at, code: 'project-invoice-stuck', detail: `${name} was started and never recorded. Retry it from the project.` })\n continue\n }\n if (invoice.status === 'failed') {\n findings.push({ ...at, code: 'project-invoice-failed', detail: `${name} failed (${invoice.error ?? 'unknown'}). Retry it from the project.` })\n continue\n }\n if (!invoice.invoiceId) {\n findings.push({ ...at, code: 'project-invoice-missing', detail: `${name} is ${invoice.status} with no Stripe invoice.` })\n continue\n }\n const stripe = input.invoices.get(invoice.invoiceId) ?? null\n if (!stripe) {\n findings.push({ ...at, code: 'project-invoice-missing', detail: `${name}: Stripe invoice ${invoice.invoiceId} is gone.` })\n continue\n }\n const expected = EXPECTED[invoice.status] ?? []\n if (!expected.includes(stripe.status)) {\n findings.push({\n ...at,\n code: 'project-invoice-status',\n detail:\n invoice.status === 'open' && stripe.status === 'paid'\n ? `${name} is paid in Stripe but not recorded. Use Check payments on the project.`\n : `${name} is ${invoice.status} here and ${stripe.status} in Stripe (${invoice.invoiceId}).`,\n })\n }\n if (stripe.subtotalCents !== invoice.amountCents) {\n findings.push({\n ...at,\n code: 'project-invoice-amount',\n detail: `${name}: Stripe bills ${stripe.subtotalCents} cents before tax, the record ${invoice.amountCents}.`,\n })\n }\n }\n }\n for (const invoice of input.listed) {\n if (claimed.has(invoice.invoiceId)) continue\n if (invoice.status === 'void') continue\n findings.push({\n orgId: input.orgId,\n projectId: invoice.metadata[SITE_CARE_PROJECT_METADATA_KEY] ?? null,\n code: 'project-invoice-without-row',\n detail: `Stripe invoice ${invoice.invoiceId} (${invoice.status}, ${invoice.subtotalCents} cents) names project ${invoice.metadata[SITE_CARE_PROJECT_METADATA_KEY]}, which does not record it.`,\n })\n }\n return findings\n}\n\nexport interface SiteCareProjectReconcileResult {\n projects: number\n findings: SiteCareProjectFinding[]\n errors: string[]\n}\n\n/** How far back a settled project is still compared. */\nconst SETTLED_WINDOW_MS = 70 * 24 * 60 * 60 * 1000\n\n/**\n * Reads every project still open, or settled within the window, and\n * compares each workspace's with Stripe.\n */\nexport async function reconcileSiteCareProjects(\n firestore: FirebaseFirestore.Firestore,\n input: { nowMs: number; stripe?: SiteCareStripeOptions },\n): Promise<SiteCareProjectReconcileResult> {\n const snapshot = await firestore.collectionGroup(SITE_CARE_PROJECTS_COLLECTION).limit(2000).get()\n const byOrg = new Map<string, ProjectRow[]>()\n for (const doc of snapshot.docs) {\n const project = readSiteCareProject(doc.data())\n if (!project?.orgId) continue\n const settled = project.status === 'paid' || project.status === 'refunded' || project.status === 'quoted'\n if (settled && input.nowMs - project.updatedAtMs > SETTLED_WINDOW_MS) continue\n const rows = byOrg.get(project.orgId) ?? []\n rows.push({ id: doc.id, project, storedStatus: String(doc.get('status') ?? '') })\n byOrg.set(project.orgId, rows)\n }\n const result: SiteCareProjectReconcileResult = { projects: 0, findings: [], errors: [] }\n for (const [orgId, rows] of byOrg) {\n result.projects += rows.length\n try {\n const invoiced = rows.filter((row) => row.project.invoices.length)\n if (!invoiced.length) {\n result.findings.push(...compareSiteCareProjects({ orgId, projects: rows, invoices: new Map(), listed: [] }))\n continue\n }\n const billing = await readOrgBilling(orgId)\n const customerId = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '')\n if (!customerId) {\n result.findings.push({\n orgId,\n projectId: null,\n code: 'project-invoice-missing',\n detail: 'Project invoices are recorded but the workspace has no Stripe customer.',\n })\n continue\n }\n const sinceMs = Math.min(...invoiced.map((row) => row.project.createdAtMs))\n const list = await listProjectInvoices({ customerId, sinceMs }, input.stripe)\n if (list.ok === false) {\n result.errors.push(`${orgId}: ${list.error}`)\n continue\n }\n const projectIds = new Set(rows.map((row) => row.id))\n const listed = list.invoices.filter((row) => projectIds.has(row.metadata[SITE_CARE_PROJECT_METADATA_KEY] ?? ''))\n const invoices = new Map<string, ProjectInvoiceState | null>(list.invoices.map((row) => [row.invoiceId, row]))\n for (const row of invoiced) {\n for (const invoice of row.project.invoices) {\n if (!invoice.invoiceId || invoices.has(invoice.invoiceId)) continue\n const read = await readProjectInvoice(invoice.invoiceId, input.stripe)\n if (read.ok === false) {\n result.errors.push(`${orgId}/${row.id}: ${read.error}`)\n continue\n }\n invoices.set(invoice.invoiceId, read.state)\n }\n }\n result.findings.push(...compareSiteCareProjects({ orgId, projects: rows, invoices, listed }))\n } catch (error) {\n result.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n return result\n}\n"],"names":["readSiteCareProject","siteCareProjectStatus","readOrgBilling","listProjectInvoices","readProjectInvoice","SITE_CARE_PROJECT_METADATA_KEY","SITE_CARE_PROJECTS_COLLECTION","EXPECTED","open","paid","voided","credited","refunded","compareSiteCareProjects","input","findings","claimed","Set","row","projects","project","at","orgId","projectId","id","derived","storedStatus","push","code","detail","title","invoice","invoices","invoiceId","add","name","seq","kind","status","error","stripe","get","expected","includes","subtotalCents","amountCents","listed","has","metadata","SETTLED_WINDOW_MS","reconcileSiteCareProjects","firestore","snapshot","collectionGroup","limit","byOrg","Map","doc","docs","data","settled","nowMs","updatedAtMs","rows","String","set","result","errors","length","invoiced","filter","billing","customerId","stripeCustomerId","sinceMs","Math","min","map","createdAtMs","list","ok","projectIds","read","state","Error","message"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,mBAAmB,EACnBC,qBAAqB,QAGhB,2CAA0C;AACjD,SAASC,cAAc,QAAQ,mBAAe;AAC9C,SACEC,mBAAmB,EACnBC,kBAAkB,EAClBC,8BAA8B,QAEzB,gCAA4B;AACnC,SAASC,6BAA6B,QAAQ,0BAAsB;AAqCpE,6DAA6D,GAC7D,MAAMC,WAAuF;IAC3FC,MAAM;QAAC;KAAO;IACdC,MAAM;QAAC;KAAO;IACdC,QAAQ;QAAC;KAAO;IAChB,wEAAwE;IACxEC,UAAU;QAAC;QAAQ;KAAO;IAC1BC,UAAU;QAAC;KA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D;;YAC5G,MAAMc,WAAW,IAAIwB,IAAwCuB,KAAK/C,QAAQ,CAAC6C,GAAG,CAAC,CAAC3D,MAAQ;oBAACA,IAAIe,SAAS;oBAAEf;iBAAI;YAC5G,KAAK,MAAMA,OAAOmD,SAAU;gBAC1B,KAAK,MAAMtC,WAAWb,IAAIE,OAAO,CAACY,QAAQ,CAAE;oBAC1C,IAAI,CAACD,QAAQE,SAAS,IAAID,SAASe,GAAG,CAAChB,QAAQE,SAAS,GAAG;oBAC3D,MAAMiD,OAAO,MAAM9E,mBAAmB2B,QAAQE,SAAS,EAAEnB,MAAM0B,MAAM;oBACrE,IAAI0C,KAAKF,EAAE,KAAK,OAAO;wBACrBd,OAAOC,MAAM,CAACxC,IAAI,CAAC,GAAGL,MAAM,CAAC,EAAEJ,IAAIM,EAAE,CAAC,EAAE,EAAE0D,KAAK3C,KAAK,EAAE;wBACtD;oBACF;oBACAP,SAASiC,GAAG,CAAClC,QAAQE,SAAS,EAAEiD,KAAKC,KAAK;gBAC5C;YACF;YACAjB,OAAOnD,QAAQ,CAACY,IAAI,IAAId,wBAAwB;gBAAES;gBAAOH,UAAU4C;gBAAM/B;gBAAUc;YAAO;QAC5F,EAAE,OAAOP,OAAO;YACd2B,OAAOC,MAAM,CAACxC,IAAI,CAAC,GAAGL,MAAM,EAAE,EAAEiB,iBAAiB6C,QAAQ7C,MAAM8C,OAAO,GAAGrB,OAAOzB,QAAQ;QAC1F;IACF;IACA,OAAO2B;AACT"}
@@ -0,0 +1,114 @@
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 SiteCareProjectInvoiceKind } from '@aglyn/aglyn/app-utils/site-care-project';
18
+ import { type SiteCareStripeOptions, type SiteCareStripeResult } from './site-care-stripe';
19
+ /**
20
+ * A SITE CARE PROJECT'S INVOICES, IN STRIPE (AGL-3970).
21
+ *
22
+ * Every Stripe call the flat-quoted project invoice makes, and nothing else:
23
+ * a ONE-OFF invoice for the org's Stripe customer — not attached to the
24
+ * subscription — that Stripe does not charge automatically
25
+ * (`collection_method: send_invoice`), finalized so it has a hosted page the
26
+ * owner pays from their phone; then reading it, voiding it while unpaid, and
27
+ * (through `creditExtraTimeItem`, the same credit-note call extra time uses)
28
+ * crediting or refunding it. Staff never build one by hand in the Stripe
29
+ * dashboard; the project record is the only door, and the caller writes the
30
+ * record's history row around each call (`site-care-projects.ts`).
31
+ *
32
+ * The same pinned, form-encoded call as extra time (`site-care-stripe.ts`),
33
+ * and the same order `usage-invoice.ts` settled on: the invoice FIRST, then
34
+ * the one line attached to it by id, so nothing else pending on the customer
35
+ * can land on it (`pending_invoice_items_behavior: exclude`).
36
+ *
37
+ * ## The tax code
38
+ *
39
+ * The line is priced against the Site Care product (`price_data[product]`),
40
+ * read off the Site Care price with its tax code checked to be
41
+ * `txcd_10103001` by `siteCareExtraTimeProduct` — the product is what Stripe
42
+ * Tax computes from, and a product with any other code refuses the invoice
43
+ * rather than bill it under the wrong one. Automatic tax is on and the line
44
+ * is tax-exclusive, as every platform price is.
45
+ *
46
+ * ## Never twice
47
+ *
48
+ * Each write carries a key derived from the invoice record's own
49
+ * (`:invoice`, `:item`, `:finalize`). A retry also looks for the invoice by
50
+ * its metadata before creating one, so even past Stripe's 24-hour key window
51
+ * a lost answer is adopted rather than invoiced again.
52
+ */
53
+ /** Metadata every project invoice carries, which the webhook and the reconciliation read. */
54
+ export declare const SITE_CARE_PROJECT_METADATA_KEY = "siteCareProjectId";
55
+ export interface ProjectInvoiceInput {
56
+ customerId: string;
57
+ productId: string;
58
+ orgId: string;
59
+ projectId: string;
60
+ seq: number;
61
+ kind: SiteCareProjectInvoiceKind;
62
+ amountCents: number;
63
+ description: string;
64
+ memo: string;
65
+ idempotencyKey: string;
66
+ /** The invoice an earlier attempt made, when the record has it. */
67
+ invoiceId: string | null;
68
+ /** When the project was created: how far back an earlier attempt's invoice can be. */
69
+ sinceMs: number;
70
+ }
71
+ export interface ProjectInvoiceState {
72
+ invoiceId: string;
73
+ invoiceItemId: string | null;
74
+ status: string;
75
+ number: string | null;
76
+ hostedInvoiceUrl: string | null;
77
+ totalCents: number;
78
+ /** Before tax. */
79
+ subtotalCents: number;
80
+ amountPaidCents: number;
81
+ metadata: Record<string, string>;
82
+ }
83
+ type ProjectStripeResult<T> = SiteCareStripeResult<T> | {
84
+ ok: false;
85
+ error: string;
86
+ invoiceId?: string | null;
87
+ };
88
+ /**
89
+ * Creates (or finishes an earlier attempt at) one project invoice:
90
+ * invoice, line, finalize. Answers the finalized invoice with its hosted
91
+ * page, or the error and whatever invoice id got made on the way.
92
+ */
93
+ export declare function createProjectInvoice(input: ProjectInvoiceInput, options?: SiteCareStripeOptions): Promise<ProjectStripeResult<{
94
+ state: ProjectInvoiceState;
95
+ }>>;
96
+ /** One invoice as it stands in Stripe. */
97
+ export declare function readProjectInvoice(invoiceId: string, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
98
+ state: ProjectInvoiceState | null;
99
+ }>>;
100
+ /** Voids an unpaid invoice: the owner owes nothing on it. */
101
+ export declare function voidProjectInvoice(input: {
102
+ invoiceId: string;
103
+ idempotencyKey: string;
104
+ }, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
105
+ status: string;
106
+ }>>;
107
+ /** Every project invoice on a customer created since `sinceMs`, as the reconciliation reads them. */
108
+ export declare function listProjectInvoices(input: {
109
+ customerId: string;
110
+ sinceMs: number;
111
+ }, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
112
+ invoices: ProjectInvoiceState[];
113
+ }>>;
114
+ export {};
@@ -0,0 +1,305 @@
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 { SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE } from "@aglyn/aglyn/app-utils/site-care-project";
18
+ import { siteCareStripeCall, siteCareStripeMessage, siteCareStripeMetadata } from "./site-care-stripe.js";
19
+ /**
20
+ * A SITE CARE PROJECT'S INVOICES, IN STRIPE (AGL-3970).
21
+ *
22
+ * Every Stripe call the flat-quoted project invoice makes, and nothing else:
23
+ * a ONE-OFF invoice for the org's Stripe customer — not attached to the
24
+ * subscription — that Stripe does not charge automatically
25
+ * (`collection_method: send_invoice`), finalized so it has a hosted page the
26
+ * owner pays from their phone; then reading it, voiding it while unpaid, and
27
+ * (through `creditExtraTimeItem`, the same credit-note call extra time uses)
28
+ * crediting or refunding it. Staff never build one by hand in the Stripe
29
+ * dashboard; the project record is the only door, and the caller writes the
30
+ * record's history row around each call (`site-care-projects.ts`).
31
+ *
32
+ * The same pinned, form-encoded call as extra time (`site-care-stripe.ts`),
33
+ * and the same order `usage-invoice.ts` settled on: the invoice FIRST, then
34
+ * the one line attached to it by id, so nothing else pending on the customer
35
+ * can land on it (`pending_invoice_items_behavior: exclude`).
36
+ *
37
+ * ## The tax code
38
+ *
39
+ * The line is priced against the Site Care product (`price_data[product]`),
40
+ * read off the Site Care price with its tax code checked to be
41
+ * `txcd_10103001` by `siteCareExtraTimeProduct` — the product is what Stripe
42
+ * Tax computes from, and a product with any other code refuses the invoice
43
+ * rather than bill it under the wrong one. Automatic tax is on and the line
44
+ * is tax-exclusive, as every platform price is.
45
+ *
46
+ * ## Never twice
47
+ *
48
+ * Each write carries a key derived from the invoice record's own
49
+ * (`:invoice`, `:item`, `:finalize`). A retry also looks for the invoice by
50
+ * its metadata before creating one, so even past Stripe's 24-hour key window
51
+ * a lost answer is adopted rather than invoiced again.
52
+ */ /** Metadata every project invoice carries, which the webhook and the reconciliation read. */ export const SITE_CARE_PROJECT_METADATA_KEY = 'siteCareProjectId';
53
+ function text(value) {
54
+ return typeof value === 'string' && value ? value : null;
55
+ }
56
+ function invoiceState(body, invoiceItemId) {
57
+ var _body_id, _body_status, _body_total, _body_subtotal, _body_amount_paid, _body_metadata;
58
+ return {
59
+ invoiceId: String((_body_id = body['id']) != null ? _body_id : ''),
60
+ invoiceItemId,
61
+ status: String((_body_status = body['status']) != null ? _body_status : ''),
62
+ number: text(body['number']),
63
+ hostedInvoiceUrl: text(body['hosted_invoice_url']),
64
+ totalCents: Number((_body_total = body['total']) != null ? _body_total : 0),
65
+ subtotalCents: Number((_body_subtotal = body['subtotal']) != null ? _body_subtotal : 0),
66
+ amountPaidCents: Number((_body_amount_paid = body['amount_paid']) != null ? _body_amount_paid : 0),
67
+ metadata: (_body_metadata = body['metadata']) != null ? _body_metadata : {}
68
+ };
69
+ }
70
+ function projectMetadata(input) {
71
+ return {
72
+ [SITE_CARE_PROJECT_METADATA_KEY]: input.projectId,
73
+ orgId: input.orgId,
74
+ invoiceSeq: String(input.seq),
75
+ invoiceKind: input.kind
76
+ };
77
+ }
78
+ /** The invoice an earlier attempt made for this record, found by its metadata. */ async function findEarlierInvoice(input, options) {
79
+ var _answer_body_data;
80
+ const answer = await siteCareStripeCall(options, 'GET', 'invoices', {
81
+ customer: input.customerId,
82
+ 'created[gte]': String(Math.floor(input.sinceMs / 1000) - 60),
83
+ limit: '100'
84
+ });
85
+ if (answer.ok === false) return {
86
+ ok: false,
87
+ error: siteCareStripeMessage(answer, 'Reading the invoices failed')
88
+ };
89
+ const rows = (_answer_body_data = answer.body['data']) != null ? _answer_body_data : [];
90
+ const found = rows.find((row)=>{
91
+ var _row_metadata;
92
+ const metadata = (_row_metadata = row['metadata']) != null ? _row_metadata : {};
93
+ return metadata[SITE_CARE_PROJECT_METADATA_KEY] === input.projectId && metadata['invoiceSeq'] === String(input.seq) && row['status'] !== 'void';
94
+ });
95
+ return {
96
+ ok: true,
97
+ body: found != null ? found : null
98
+ };
99
+ }
100
+ /** The project's own line on a draft, when one is there. */ async function existingLine(invoiceId, options) {
101
+ var _lines_body_data, _text;
102
+ const lines = await siteCareStripeCall(options, 'GET', `invoices/${encodeURIComponent(invoiceId)}/lines`, {
103
+ limit: '10'
104
+ });
105
+ if (lines.ok === false) return {
106
+ ok: false,
107
+ error: siteCareStripeMessage(lines, 'Reading the invoice lines failed')
108
+ };
109
+ const row = ((_lines_body_data = lines.body['data']) != null ? _lines_body_data : [])[0];
110
+ if (!row) return {
111
+ ok: true,
112
+ invoiceItemId: null
113
+ };
114
+ return {
115
+ ok: true,
116
+ invoiceItemId: (_text = text(row['invoice_item'])) != null ? _text : text(row['id'])
117
+ };
118
+ }
119
+ /**
120
+ * Creates (or finishes an earlier attempt at) one project invoice:
121
+ * invoice, line, finalize. Answers the finalized invoice with its hosted
122
+ * page, or the error and whatever invoice id got made on the way.
123
+ */ export async function createProjectInvoice(input, options = {}) {
124
+ var _body_id, _body_status;
125
+ if (!input.customerId) return {
126
+ ok: false,
127
+ error: 'The workspace has no Stripe customer to invoice.'
128
+ };
129
+ const amountCents = Math.floor(Number(input.amountCents));
130
+ if (!Number.isInteger(amountCents) || amountCents < 100) {
131
+ return {
132
+ ok: false,
133
+ error: 'A project invoice is at least $1.'
134
+ };
135
+ }
136
+ const key = (step)=>`${input.idempotencyKey}:${step}`;
137
+ const metadata = siteCareStripeMetadata(projectMetadata(input));
138
+ let body;
139
+ if (input.invoiceId) {
140
+ const read = await siteCareStripeCall(options, 'GET', `invoices/${encodeURIComponent(input.invoiceId)}`);
141
+ if (read.ok === false) {
142
+ return {
143
+ ok: false,
144
+ error: siteCareStripeMessage(read, 'Reading the invoice failed'),
145
+ invoiceId: input.invoiceId
146
+ };
147
+ }
148
+ body = read.body;
149
+ } else {
150
+ const earlier = await findEarlierInvoice(input, options);
151
+ if (earlier.ok === false) return earlier;
152
+ body = earlier.body;
153
+ }
154
+ let fresh = false;
155
+ if (!body) {
156
+ const created = await siteCareStripeCall(options, 'POST', 'invoices', _extends({
157
+ customer: input.customerId,
158
+ collection_method: 'send_invoice',
159
+ days_until_due: String(SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE),
160
+ auto_advance: 'false',
161
+ 'automatic_tax[enabled]': 'true',
162
+ // This invoice carries the line added below and nothing else.
163
+ pending_invoice_items_behavior: 'exclude',
164
+ description: input.memo
165
+ }, metadata), key('invoice'));
166
+ if (created.ok === false) return {
167
+ ok: false,
168
+ error: siteCareStripeMessage(created, 'Stripe refused the invoice')
169
+ };
170
+ body = created.body;
171
+ fresh = true;
172
+ }
173
+ const invoiceId = String((_body_id = body['id']) != null ? _body_id : '');
174
+ if (!invoiceId) return {
175
+ ok: false,
176
+ error: 'Stripe returned an invoice with no id'
177
+ };
178
+ const status = String((_body_status = body['status']) != null ? _body_status : '');
179
+ if (status === 'void' || status === 'uncollectible') {
180
+ return {
181
+ ok: false,
182
+ error: `The invoice is ${status}; raise a new one.`,
183
+ invoiceId
184
+ };
185
+ }
186
+ if (status !== 'draft') {
187
+ const line = await existingLine(invoiceId, options);
188
+ return {
189
+ ok: true,
190
+ state: invoiceState(body, line.ok ? line.invoiceItemId : null)
191
+ };
192
+ }
193
+ let invoiceItemId = null;
194
+ if (!fresh) {
195
+ const line = await existingLine(invoiceId, options);
196
+ if (line.ok === false) return {
197
+ ok: false,
198
+ error: line.error,
199
+ invoiceId
200
+ };
201
+ invoiceItemId = line.invoiceItemId;
202
+ }
203
+ if (!invoiceItemId) {
204
+ const item = await siteCareStripeCall(options, 'POST', 'invoiceitems', _extends({
205
+ customer: input.customerId,
206
+ invoice: invoiceId,
207
+ 'price_data[product]': input.productId,
208
+ 'price_data[currency]': 'usd',
209
+ 'price_data[unit_amount]': String(amountCents),
210
+ // US sales tax is added on top of the platform's prices, and
211
+ // automatic tax refuses an unspecified behavior outright.
212
+ 'price_data[tax_behavior]': 'exclusive',
213
+ description: input.description
214
+ }, metadata), key('item'));
215
+ if (item.ok === false) {
216
+ return {
217
+ ok: false,
218
+ error: siteCareStripeMessage(item, 'Stripe refused the project line'),
219
+ invoiceId
220
+ };
221
+ }
222
+ invoiceItemId = text(item.body['id']);
223
+ }
224
+ const finalized = await siteCareStripeCall(options, 'POST', `invoices/${encodeURIComponent(invoiceId)}/finalize`, {
225
+ auto_advance: 'false'
226
+ }, key('finalize'));
227
+ if (finalized.ok === false) {
228
+ return {
229
+ ok: false,
230
+ error: siteCareStripeMessage(finalized, 'The invoice could not be finalized'),
231
+ invoiceId
232
+ };
233
+ }
234
+ const state = invoiceState(finalized.body, invoiceItemId);
235
+ if (!state.hostedInvoiceUrl) {
236
+ return {
237
+ ok: false,
238
+ error: 'Stripe finalized the invoice without a pay page.',
239
+ invoiceId
240
+ };
241
+ }
242
+ return {
243
+ ok: true,
244
+ state
245
+ };
246
+ }
247
+ /** One invoice as it stands in Stripe. */ export async function readProjectInvoice(invoiceId, options = {}) {
248
+ const answer = await siteCareStripeCall(options, 'GET', `invoices/${encodeURIComponent(invoiceId)}`);
249
+ if (answer.status === 404) return {
250
+ ok: true,
251
+ state: null
252
+ };
253
+ if (answer.ok === false) return {
254
+ ok: false,
255
+ error: siteCareStripeMessage(answer, 'Reading the invoice failed')
256
+ };
257
+ return {
258
+ ok: true,
259
+ state: invoiceState(answer.body, null)
260
+ };
261
+ }
262
+ /** Voids an unpaid invoice: the owner owes nothing on it. */ export async function voidProjectInvoice(input, options = {}) {
263
+ var _answer_body_status;
264
+ const answer = await siteCareStripeCall(options, 'POST', `invoices/${encodeURIComponent(input.invoiceId)}/void`, null, input.idempotencyKey);
265
+ if (answer.ok === false) return {
266
+ ok: false,
267
+ error: siteCareStripeMessage(answer, 'Stripe refused to void the invoice')
268
+ };
269
+ return {
270
+ ok: true,
271
+ status: String((_answer_body_status = answer.body['status']) != null ? _answer_body_status : 'void')
272
+ };
273
+ }
274
+ /** Every project invoice on a customer created since `sinceMs`, as the reconciliation reads them. */ export async function listProjectInvoices(input, options = {}) {
275
+ const invoices = [];
276
+ let startingAfter = '';
277
+ for(let page = 0; page < 10; page++){
278
+ var _answer_body_data;
279
+ const answer = await siteCareStripeCall(options, 'GET', 'invoices', _extends({
280
+ customer: input.customerId,
281
+ 'created[gte]': String(Math.floor(input.sinceMs / 1000)),
282
+ limit: '100'
283
+ }, startingAfter ? {
284
+ starting_after: startingAfter
285
+ } : {}));
286
+ if (answer.ok === false) return {
287
+ ok: false,
288
+ error: siteCareStripeMessage(answer, 'Listing invoices failed')
289
+ };
290
+ const rows = (_answer_body_data = answer.body['data']) != null ? _answer_body_data : [];
291
+ for (const row of rows){
292
+ var _row_metadata;
293
+ const metadata = (_row_metadata = row['metadata']) != null ? _row_metadata : {};
294
+ if (metadata[SITE_CARE_PROJECT_METADATA_KEY]) invoices.push(invoiceState(row, null));
295
+ }
296
+ if (answer.body['has_more'] !== true || !rows.length) break;
297
+ startingAfter = String(rows[rows.length - 1]['id']);
298
+ }
299
+ return {
300
+ ok: true,
301
+ invoices
302
+ };
303
+ }
304
+
305
+ //# sourceMappingURL=site-care-project-stripe.js.map