@aglyn/tenant-data-admin 1.0.0-beta.275 → 1.0.0-beta.282

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 (34) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/account-emails.js +18 -4
  3. package/src/lib/server/account-emails.js.map +1 -1
  4. package/src/lib/server/bundle-links.d.ts +5 -0
  5. package/src/lib/server/bundle-links.js +4 -2
  6. package/src/lib/server/bundle-links.js.map +1 -1
  7. package/src/lib/server/erase.js +9 -0
  8. package/src/lib/server/erase.js.map +1 -1
  9. package/src/lib/server/media-strong-digest.js +33 -5
  10. package/src/lib/server/media-strong-digest.js.map +1 -1
  11. package/src/lib/server/organizations.js +20 -0
  12. package/src/lib/server/organizations.js.map +1 -1
  13. package/src/lib/server/owner-handoff-emails.d.ts +43 -0
  14. package/src/lib/server/owner-handoff-emails.js +134 -0
  15. package/src/lib/server/owner-handoff-emails.js.map +1 -0
  16. package/src/lib/server/personal-data-export.js +18 -4
  17. package/src/lib/server/personal-data-export.js.map +1 -1
  18. package/src/lib/server/render-monitor.d.ts +8 -4
  19. package/src/lib/server/render-monitor.js +12 -8
  20. package/src/lib/server/render-monitor.js.map +1 -1
  21. package/src/lib/server/site-care-inbound.d.ts +75 -4
  22. package/src/lib/server/site-care-inbound.js +236 -26
  23. package/src/lib/server/site-care-inbound.js.map +1 -1
  24. package/src/lib/server/site-care-reconcile.d.ts +36 -2
  25. package/src/lib/server/site-care-reconcile.js +219 -54
  26. package/src/lib/server/site-care-reconcile.js.map +1 -1
  27. package/src/lib/server/site-care-requests.d.ts +43 -1
  28. package/src/lib/server/site-care-requests.js +117 -6
  29. package/src/lib/server/site-care-requests.js.map +1 -1
  30. package/src/lib/server/upgrade-proposal.d.ts +6 -1
  31. package/src/lib/server/upgrade-proposal.js.map +1 -1
  32. package/src/lib/server/upload-cors-reconcile.d.ts +2 -2
  33. package/src/lib/server/upload-cors-reconcile.js +2 -2
  34. package/src/lib/server/upload-cors-reconcile.js.map +1 -1
@@ -14,13 +14,141 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { previousSiteCareMonthKey, siteCareExtraTimeCents, siteCareMonthKey, siteCareMonthStatement, siteCareStatementRequest } from "@aglyn/aglyn/app-utils/site-care";
17
+ */ import { countedSiteCareMinutes, previousSiteCareMonthKey, siteCareCloseVerdict, siteCareExtraTimeCents, siteCareIncludedPool, siteCareMonthKey, siteCareMonthStatement, siteCareStatementRequest } from "@aglyn/aglyn/app-utils/site-care";
18
18
  import { readOrgBilling } from "./org-billing.js";
19
19
  import { raiseOperatorAlert } from "./operator-alerts.js";
20
- import { readSiteCareRequest } from "./site-care-requests.js";
20
+ import { readSiteCareRequest, SITE_CARE_MONTHS_COLLECTION } from "./site-care-requests.js";
21
21
  import { reconcileSiteCareProjects } from "./site-care-project-reconcile.js";
22
22
  import { listSiteCareExtraTimeItems, readExtraTimeItem } from "./site-care-stripe.js";
23
- /** Compares one workspace's requests with its Stripe items. Pure. */ export function compareSiteCareCharges(input) {
23
+ /**
24
+ * The whole hours a closed request should bill, from its own minutes and
25
+ * approval: the close's verdict, re-run. `null` when no approval covers the
26
+ * over-time and it was not absorbed — nothing may bill, and the request
27
+ * should not have closed that way.
28
+ */ export function siteCareLedgerHours(request) {
29
+ const overMinutes = Math.max(0, Number(request.overMinutes) || 0);
30
+ const verdict = siteCareCloseVerdict({
31
+ requiredHours: overMinutes > 0 ? Math.ceil(overMinutes / 60) : 0,
32
+ approval: request.approval,
33
+ absorb: request.absorbed
34
+ });
35
+ return verdict.ok ? verdict.billedHours : null;
36
+ }
37
+ /**
38
+ * One workspace's closed requests against their own ledger. Pure, and needs
39
+ * no Stripe: a workspace whose charges cannot be listed is still checked.
40
+ */ export function compareSiteCareLedger(input) {
41
+ const findings = [];
42
+ const months = new Set();
43
+ for (const row of input.requests){
44
+ const { request } = row;
45
+ months.add(request.month);
46
+ const at = {
47
+ orgId: input.orgId,
48
+ month: request.month,
49
+ requestId: row.id
50
+ };
51
+ const title = `“${row.subject}”`;
52
+ // The minutes: logged → counted in whole blocks → included + over.
53
+ const logged = Number(request.minutesLogged) || 0;
54
+ const minuteProblems = [];
55
+ if (request.countedMinutes !== countedSiteCareMinutes(logged)) {
56
+ minuteProblems.push(`${logged} min logged count as ${countedSiteCareMinutes(logged)}, recorded ${request.countedMinutes}`);
57
+ }
58
+ if (request.includedMinutesUsed + request.overMinutes !== request.countedMinutes) {
59
+ minuteProblems.push(`${request.includedMinutesUsed} included + ${request.overMinutes} over ≠ ${request.countedMinutes} counted`);
60
+ }
61
+ if (request.includedMinutesUsed < 0 || request.overMinutes < 0) minuteProblems.push('negative minutes');
62
+ if (minuteProblems.length) {
63
+ findings.push(_extends({}, at, {
64
+ code: 'ledger-minutes',
65
+ detail: `${title}: ${minuteProblems.join('; ')}.`
66
+ }));
67
+ }
68
+ // The hours: whole started hours of over-time, never below the approval.
69
+ const charge = request.charge;
70
+ const owing = charge !== null && (charge.status === 'creating' || charge.status === 'pending' || charge.status === 'failed');
71
+ const expected = siteCareLedgerHours(request);
72
+ if (expected === null) {
73
+ if (request.billedHours > 0 || owing) {
74
+ findings.push(_extends({}, at, {
75
+ code: 'ledger-unapproved',
76
+ detail: request.approval ? `${title}: bills ${request.billedHours} h for ${request.overMinutes} min past the included hour, more than the ${request.approval.hours} h the owner approved.` : `${title}: bills ${request.billedHours} h for ${request.overMinutes} min past the included hour with no approval on file.`
77
+ }));
78
+ } else {
79
+ findings.push(_extends({}, at, {
80
+ code: 'ledger-unapproved',
81
+ detail: `${title}: ${request.overMinutes} min past the included hour, neither billed nor absorbed.`
82
+ }));
83
+ }
84
+ } else {
85
+ if (request.billedHours !== expected) {
86
+ findings.push(_extends({}, at, {
87
+ code: 'ledger-hours',
88
+ detail: `${title}: records ${request.billedHours} h billed, but ${request.overMinutes} min past the included hour${request.approval ? ` with ${request.approval.hours} h approved` : ''} come to ${expected} h.`
89
+ }));
90
+ }
91
+ if (owing && charge.hours !== expected) {
92
+ findings.push(_extends({}, at, {
93
+ code: 'ledger-hours',
94
+ detail: `${title}: the ${charge.status} charge is for ${charge.hours} h; the logged time comes to ${expected} h.`
95
+ }));
96
+ }
97
+ }
98
+ if (charge && charge.amountCents !== siteCareExtraTimeCents(charge.hours)) {
99
+ findings.push(_extends({}, at, {
100
+ code: 'ledger-amount',
101
+ detail: `${title}: the charge records ${charge.amountCents} cents for ${charge.hours} h, which is ${siteCareExtraTimeCents(charge.hours)}.`
102
+ }));
103
+ }
104
+ }
105
+ for (const month of months){
106
+ var _ref;
107
+ var _input_goodwillByMonth;
108
+ const inMonth = input.requests.filter((row)=>row.request.month === month);
109
+ // The included pool is never overdrawn: each close takes only what the
110
+ // month's earlier requests left of it.
111
+ const pool = siteCareIncludedPool((_ref = (_input_goodwillByMonth = input.goodwillByMonth) == null ? void 0 : _input_goodwillByMonth.get(month)) != null ? _ref : 0);
112
+ const included = inMonth.reduce((sum, row)=>sum + (Number(row.request.includedMinutesUsed) || 0), 0);
113
+ if (included > pool) {
114
+ findings.push({
115
+ orgId: input.orgId,
116
+ month,
117
+ requestId: null,
118
+ code: 'ledger-minutes',
119
+ detail: `${month}: ${included} included minutes used of a ${pool}-minute allowance.`
120
+ });
121
+ }
122
+ // The month's pending charges against what the ledger says they come to.
123
+ const pending = inMonth.filter((row)=>{
124
+ var _row_request_charge;
125
+ return ((_row_request_charge = row.request.charge) == null ? void 0 : _row_request_charge.status) === 'pending';
126
+ });
127
+ const recorded = pending.reduce((sum, row)=>{
128
+ var _ref;
129
+ var _row_request_charge;
130
+ return sum + ((_ref = (_row_request_charge = row.request.charge) == null ? void 0 : _row_request_charge.amountCents) != null ? _ref : 0);
131
+ }, 0);
132
+ const ledger = pending.reduce((sum, row)=>{
133
+ var _siteCareLedgerHours;
134
+ return sum + siteCareExtraTimeCents((_siteCareLedgerHours = siteCareLedgerHours(row.request)) != null ? _siteCareLedgerHours : 0);
135
+ }, 0);
136
+ if (recorded !== ledger) {
137
+ findings.push({
138
+ orgId: input.orgId,
139
+ month,
140
+ requestId: null,
141
+ code: 'month-ledger',
142
+ detail: `The ${month} pending charges record ${recorded} cents; the logged time and approvals behind them come to ${ledger}.`
143
+ });
144
+ }
145
+ }
146
+ return findings;
147
+ }
148
+ /**
149
+ * Compares one workspace's requests with its Stripe items, and with their
150
+ * own ledger ({@link compareSiteCareLedger}). Pure.
151
+ */ export function compareSiteCareCharges(input) {
24
152
  const findings = [];
25
153
  const byId = new Map(input.items.map((item)=>[
26
154
  item.id,
@@ -86,6 +214,17 @@ import { listSiteCareExtraTimeItems, readExtraTimeItem } from "./site-care-strip
86
214
  detail: `“${row.subject}” (${fromStripe.id}): ${problems.join(', ')}.`
87
215
  }));
88
216
  }
217
+ // What the owner will be invoiced against what the ledger says,
218
+ // when the charge itself has drifted (otherwise the line above
219
+ // already names the difference).
220
+ const ledgerHours = siteCareLedgerHours(request);
221
+ const ledgerCents = siteCareExtraTimeCents(ledgerHours != null ? ledgerHours : 0);
222
+ if (ledgerCents !== expected && fromStripe.amountCents !== ledgerCents) {
223
+ findings.push(_extends({}, at, {
224
+ code: 'ledger-amount',
225
+ detail: `“${row.subject}” (${fromStripe.id}): Stripe will invoice ${fromStripe.amountCents} cents; the logged time and approval come to ${ledgerCents}.`
226
+ }));
227
+ }
89
228
  if (request.billedHours !== charge.hours && !request.absorbed) {
90
229
  findings.push(_extends({}, at, {
91
230
  code: 'hours-mismatch',
@@ -121,10 +260,12 @@ import { listSiteCareExtraTimeItems, readExtraTimeItem } from "./site-care-strip
121
260
  }
122
261
  // The month's total against Stripe's.
123
262
  for (const month of months){
263
+ var _ref1;
264
+ var _input_goodwillByMonth;
124
265
  const inMonth = input.requests.filter((row)=>row.request.month === month);
125
266
  const statement = siteCareMonthStatement({
126
267
  month,
127
- goodwillMinutes: 0,
268
+ goodwillMinutes: (_ref1 = (_input_goodwillByMonth = input.goodwillByMonth) == null ? void 0 : _input_goodwillByMonth.get(month)) != null ? _ref1 : 0,
128
269
  requests: inMonth.map((row)=>siteCareStatementRequest(row.id, row.subject, row.request))
129
270
  });
130
271
  const stripeTotal = inMonth.filter((row)=>{
@@ -155,8 +296,18 @@ import { listSiteCareExtraTimeItems, readExtraTimeItem } from "./site-care-strip
155
296
  });
156
297
  }
157
298
  }
299
+ findings.push(...compareSiteCareLedger(input));
158
300
  return findings;
159
301
  }
302
+ /** Each month's goodwill minutes for one workspace, from its month documents. */ async function readGoodwill(firestore, orgId, months) {
303
+ const goodwill = new Map();
304
+ for (const month of months){
305
+ var _snapshot_get;
306
+ const snapshot = await firestore.collection('orgs').doc(orgId).collection(SITE_CARE_MONTHS_COLLECTION).doc(month).get();
307
+ goodwill.set(month, Math.max(0, Number((_snapshot_get = snapshot.get('goodwillMinutes')) != null ? _snapshot_get : 0) || 0));
308
+ }
309
+ return goodwill;
310
+ }
160
311
  /** Runs the check over the current and previous month. */ export async function reconcileSiteCare(firestore, input) {
161
312
  var _input_nowMs;
162
313
  const nowMs = (_input_nowMs = input.nowMs) != null ? _input_nowMs : Date.now();
@@ -196,64 +347,78 @@ import { listSiteCareExtraTimeItems, readExtraTimeItem } from "./site-care-strip
196
347
  const sinceMs = nowMs - 70 * 24 * 60 * 60 * 1000;
197
348
  for (const [orgId, rows] of byOrg){
198
349
  try {
199
- var _billing_stripeCustomerId, _orgSnap_get;
350
+ var _ref, _orgSnap_get;
351
+ const goodwillByMonth = await readGoodwill(firestore, orgId, months);
200
352
  const charged = rows.filter((row)=>row.request.charge);
201
- if (!charged.length) continue;
202
- const billing = await readOrgBilling(orgId);
203
- const customerId = String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '');
204
- if (!customerId) {
205
- report.findings.push({
353
+ // Our own ledger first, and on its own wherever Stripe is not read: a
354
+ // workspace with no charge, no customer, or a listing that failed is
355
+ // still checked against itself (AGL-4031).
356
+ const ledgerOnly = ()=>compareSiteCareLedger({
206
357
  orgId,
207
- month: current,
208
- requestId: null,
209
- code: 'no-customer',
210
- detail: 'Charges are recorded but the workspace has no Stripe customer.'
358
+ requests: rows,
359
+ goodwillByMonth
211
360
  });
212
- continue;
213
- }
214
- const listed = await listSiteCareExtraTimeItems({
361
+ let findings;
362
+ const billing = charged.length ? await readOrgBilling(orgId) : null;
363
+ const customerId = String((_ref = billing == null ? void 0 : billing.stripeCustomerId) != null ? _ref : '');
364
+ const listed = customerId ? await listSiteCareExtraTimeItems({
215
365
  customerId,
216
366
  sinceMs
217
- }, input.stripe);
218
- if (listed.ok === false) {
219
- report.errors.push(`${orgId}: ${listed.error}`);
220
- continue;
221
- }
222
- const listedIds = new Set(listed.items.map((item)=>item.id));
223
- const readItems = new Map();
224
- for (const row of charged){
225
- var _read_state_metadata_siteCareRequestId, _read_state_metadata_month;
226
- var _row_request_charge;
227
- const id = (_row_request_charge = row.request.charge) == null ? void 0 : _row_request_charge.invoiceItemId;
228
- if (!id || listedIds.has(id)) continue;
229
- const read = await readExtraTimeItem(id, input.stripe);
230
- if (read.ok === false) {
231
- report.errors.push(`${orgId}/${row.id}: ${read.error}`);
232
- continue;
233
- }
234
- readItems.set(id, {
235
- deleted: read.state.stage === 'deleted',
236
- item: read.state.stage === 'deleted' ? null : {
237
- id,
238
- amountCents: read.state.amountCents,
239
- quantity: read.state.quantity,
240
- description: read.state.description,
241
- requestId: String((_read_state_metadata_siteCareRequestId = read.state.metadata['siteCareRequestId']) != null ? _read_state_metadata_siteCareRequestId : row.id),
242
- month: String((_read_state_metadata_month = read.state.metadata['month']) != null ? _read_state_metadata_month : row.request.month)
367
+ }, input.stripe) : null;
368
+ if (!charged.length) {
369
+ findings = ledgerOnly();
370
+ } else if (!customerId) {
371
+ findings = [
372
+ {
373
+ orgId,
374
+ month: current,
375
+ requestId: null,
376
+ code: 'no-customer',
377
+ detail: 'Charges are recorded but the workspace has no Stripe customer.'
378
+ },
379
+ ...ledgerOnly()
380
+ ];
381
+ } else if (!listed || listed.ok === false) {
382
+ report.errors.push(`${orgId}: ${listed && listed.ok === false ? listed.error : 'no listing'}`);
383
+ findings = ledgerOnly();
384
+ } else {
385
+ const listedIds = new Set(listed.items.map((item)=>item.id));
386
+ const readItems = new Map();
387
+ for (const row of charged){
388
+ var _read_state_metadata_siteCareRequestId, _read_state_metadata_month;
389
+ var _row_request_charge;
390
+ const id = (_row_request_charge = row.request.charge) == null ? void 0 : _row_request_charge.invoiceItemId;
391
+ if (!id || listedIds.has(id)) continue;
392
+ const read = await readExtraTimeItem(id, input.stripe);
393
+ if (read.ok === false) {
394
+ report.errors.push(`${orgId}/${row.id}: ${read.error}`);
395
+ continue;
243
396
  }
397
+ readItems.set(id, {
398
+ deleted: read.state.stage === 'deleted',
399
+ item: read.state.stage === 'deleted' ? null : {
400
+ id,
401
+ amountCents: read.state.amountCents,
402
+ quantity: read.state.quantity,
403
+ description: read.state.description,
404
+ requestId: String((_read_state_metadata_siteCareRequestId = read.state.metadata['siteCareRequestId']) != null ? _read_state_metadata_siteCareRequestId : row.id),
405
+ month: String((_read_state_metadata_month = read.state.metadata['month']) != null ? _read_state_metadata_month : row.request.month)
406
+ }
407
+ });
408
+ }
409
+ // Only items for these months' requests are judged here: an older
410
+ // month's item inside the listing window belongs to a month this run
411
+ // does not read.
412
+ const requestIds = new Set(rows.map((row)=>row.id));
413
+ const items = listed.items.filter((item)=>requestIds.has(item.requestId) || months.includes(item.month));
414
+ findings = compareSiteCareCharges({
415
+ orgId,
416
+ requests: rows,
417
+ items,
418
+ readItems,
419
+ goodwillByMonth
244
420
  });
245
421
  }
246
- // Only items for these months' requests are judged here: an older
247
- // month's item inside the listing window belongs to a month this run
248
- // does not read.
249
- const requestIds = new Set(rows.map((row)=>row.id));
250
- const items = listed.items.filter((item)=>requestIds.has(item.requestId) || months.includes(item.month));
251
- const findings = compareSiteCareCharges({
252
- orgId,
253
- requests: rows,
254
- items,
255
- readItems
256
- });
257
422
  report.findings.push(...findings);
258
423
  if (input.dryRun || !findings.length) continue;
259
424
  const byMonth = new Map();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-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 previousSiteCareMonthKey,\n siteCareExtraTimeCents,\n siteCareMonthKey,\n siteCareMonthStatement,\n siteCareStatementRequest,\n type SiteCareRequest,\n} from '@aglyn/aglyn/app-utils/site-care'\nimport { readOrgBilling } from './org-billing'\nimport { raiseOperatorAlert } from './operator-alerts'\nimport { readSiteCareRequest } from './site-care-requests'\nimport {\n reconcileSiteCareProjects,\n type SiteCareProjectFindingCode,\n} from './site-care-project-reconcile'\nimport {\n listSiteCareExtraTimeItems,\n readExtraTimeItem,\n type SiteCareStripeOptions,\n type StripeExtraTimeItem,\n} from './site-care-stripe'\n\n/**\n * THE SITE CARE RECONCILIATION (AGL-3959).\n *\n * Once a day, for the current month and the one before: each request's\n * billed hours against the Stripe invoice item that carries them — amount,\n * quantity and description — and each month's billed total against the sum\n * of its Stripe items. Any difference is a finding, and a workspace-month\n * with findings raises `billing.siteCareReconciliation` (Should know)\n * rather than passing silently. The same shape as the pricing-drift check:\n * it compares and reports, and never changes anything on either side — the\n * fix is a person's, from the request.\n *\n * What it catches, by construction of how charges are written:\n * - a Stripe item with no row behind it (the call succeeded, the record did\n * not land): a `creating` charge, or an item no request claims;\n * - a row with no Stripe object: a `pending` charge whose item is gone, or a\n * `failed` one still owing hours;\n * - an item somebody edited in the Stripe dashboard: amount, quantity or\n * description that no longer match the request.\n */\n\nexport type SiteCareFindingCode =\n | 'charge-stuck'\n | 'charge-failed'\n | 'item-missing'\n | 'item-mismatch'\n | 'item-not-voided'\n | 'item-without-row'\n | 'hours-mismatch'\n | 'month-total'\n | 'no-customer'\n // A flat-quoted project's invoices (AGL-3970), in the same check.\n | SiteCareProjectFindingCode\n\nexport interface SiteCareFinding {\n orgId: string\n month: string\n requestId: string | null\n code: SiteCareFindingCode\n detail: string\n}\n\nexport interface SiteCareReconcileReport {\n months: string[]\n orgs: number\n requests: number\n /** Projects compared (AGL-3970). */\n projects: number\n findings: SiteCareFinding[]\n alerted: number\n errors: string[]\n}\n\ninterface RequestRow {\n id: string\n orgId: string\n subject: string\n request: SiteCareRequest\n}\n\n/** Compares one workspace's requests with its Stripe items. Pure. */\nexport function compareSiteCareCharges(input: {\n orgId: string\n requests: readonly RequestRow[]\n items: readonly StripeExtraTimeItem[]\n /** Items read one by one because the listing did not reach them. */\n readItems?: ReadonlyMap<string, { deleted: boolean; item: StripeExtraTimeItem | null }>\n}): SiteCareFinding[] {\n const findings: SiteCareFinding[] = []\n const byId = new Map(input.items.map((item) => [item.id, item]))\n const claimed = new Set<string>()\n const months = new Set<string>()\n for (const row of input.requests) {\n const { request } = row\n months.add(request.month)\n const charge = request.charge\n const at = { orgId: input.orgId, month: request.month, requestId: row.id }\n if (!charge) {\n if (request.billedHours > 0) {\n findings.push({ ...at, code: 'hours-mismatch', detail: `“${row.subject}” bills ${request.billedHours} h with no charge recorded.` })\n }\n continue\n }\n if (charge.invoiceItemId) claimed.add(charge.invoiceItemId)\n const fromStripe = charge.invoiceItemId\n ? (byId.get(charge.invoiceItemId) ?? input.readItems?.get(charge.invoiceItemId)?.item ?? null)\n : (input.items.find((item) => item.requestId === row.id) ?? null)\n const deleted = charge.invoiceItemId ? input.readItems?.get(charge.invoiceItemId)?.deleted === true : false\n if (fromStripe) claimed.add(fromStripe.id)\n switch (charge.status) {\n case 'creating':\n findings.push({\n ...at,\n code: 'charge-stuck',\n detail: fromStripe\n ? `“${row.subject}”: Stripe item ${fromStripe.id} exists but the request never recorded it. Retry the charge to record it.`\n : `“${row.subject}”: a charge was started and never finished. Retry it.`,\n })\n break\n case 'failed':\n findings.push({ ...at, code: 'charge-failed', detail: `“${row.subject}”: ${charge.hours} h owed with no Stripe item (${charge.error ?? 'failed'}).` })\n break\n case 'pending': {\n if (!fromStripe || deleted) {\n findings.push({ ...at, code: 'item-missing', detail: `“${row.subject}”: Stripe item ${charge.invoiceItemId} is gone.` })\n break\n }\n const expected = siteCareExtraTimeCents(charge.hours)\n const problems: string[] = []\n if (fromStripe.amountCents !== expected) problems.push(`amount ${fromStripe.amountCents} ≠ ${expected}`)\n if (fromStripe.quantity !== charge.hours) problems.push(`quantity ${fromStripe.quantity} ≠ ${charge.hours}`)\n if (fromStripe.description !== charge.description) problems.push('description differs')\n if (problems.length) {\n findings.push({ ...at, code: 'item-mismatch', detail: `“${row.subject}” (${fromStripe.id}): ${problems.join(', ')}.` })\n }\n if (request.billedHours !== charge.hours && !request.absorbed) {\n findings.push({ ...at, code: 'hours-mismatch', detail: `“${row.subject}”: billed ${request.billedHours} h but the charge is ${charge.hours} h.` })\n }\n break\n }\n case 'voided':\n if (fromStripe && !deleted) {\n findings.push({ ...at, code: 'item-not-voided', detail: `“${row.subject}”: voided here, but Stripe item ${fromStripe.id} is still there.` })\n }\n break\n default:\n break\n }\n }\n for (const item of input.items) {\n if (claimed.has(item.id)) continue\n findings.push({\n orgId: input.orgId,\n month: [...months][0] ?? '',\n requestId: item.requestId || null,\n code: 'item-without-row',\n detail: `Stripe item ${item.id} (${item.amountCents} cents) names request ${item.requestId}, which does not record it.`,\n })\n }\n // The month's total against Stripe's.\n for (const month of months) {\n const inMonth = input.requests.filter((row) => row.request.month === month)\n const statement = siteCareMonthStatement({\n month,\n goodwillMinutes: 0,\n requests: inMonth.map((row) => siteCareStatementRequest(row.id, row.subject, row.request)),\n })\n const stripeTotal = inMonth\n .filter((row) => row.request.charge?.status === 'pending' && row.request.charge.invoiceItemId)\n .reduce((sum, row) => {\n const id = String(row.request.charge?.invoiceItemId)\n const item = byId.get(id) ?? input.readItems?.get(id)?.item ?? null\n return sum + (item ? item.amountCents : 0)\n }, 0)\n const pendingRecorded = inMonth\n .filter((row) => row.request.charge?.status === 'pending')\n .reduce((sum, row) => sum + (row.request.charge?.amountCents ?? 0), 0)\n if (stripeTotal !== pendingRecorded) {\n findings.push({\n orgId: input.orgId,\n month,\n requestId: null,\n code: 'month-total',\n detail: `The ${month} statement bills ${statement.extraBilledCents} cents (${pendingRecorded} on pending items) and Stripe holds ${stripeTotal}.`,\n })\n }\n }\n return findings\n}\n\n/** Runs the check over the current and previous month. */\nexport async function reconcileSiteCare(\n firestore: FirebaseFirestore.Firestore,\n input: { nowMs?: number; dryRun: boolean; stripe?: SiteCareStripeOptions },\n): Promise<SiteCareReconcileReport> {\n const nowMs = input.nowMs ?? Date.now()\n const current = siteCareMonthKey(nowMs)\n const months = [current, previousSiteCareMonthKey(current)]\n const snapshot = await firestore.collection('supportTickets').where('siteCareMonth', 'in', months).limit(2000).get()\n const byOrg = new Map<string, RequestRow[]>()\n for (const doc of snapshot.docs) {\n const request = readSiteCareRequest(doc.get('siteCare'))\n const orgId = String(doc.get('orgId') ?? '')\n if (!request || !orgId || request.state !== 'closed') continue\n const rows = byOrg.get(orgId) ?? []\n rows.push({ id: doc.id, orgId, subject: String(doc.get('subject') ?? ''), request })\n byOrg.set(orgId, rows)\n }\n const report: SiteCareReconcileReport = {\n months,\n orgs: byOrg.size,\n requests: [...byOrg.values()].reduce((sum, rows) => sum + rows.length, 0),\n projects: 0,\n findings: [],\n alerted: 0,\n errors: [],\n }\n // Seventy days reaches back past the start of the previous month.\n const sinceMs = nowMs - 70 * 24 * 60 * 60 * 1000\n for (const [orgId, rows] of byOrg) {\n try {\n const charged = rows.filter((row) => row.request.charge)\n if (!charged.length) continue\n const billing = await readOrgBilling(orgId)\n const customerId = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '')\n if (!customerId) {\n report.findings.push({ orgId, month: current, requestId: null, code: 'no-customer', detail: 'Charges are recorded but the workspace has no Stripe customer.' })\n continue\n }\n const listed = await listSiteCareExtraTimeItems({ customerId, sinceMs }, input.stripe)\n if (listed.ok === false) {\n report.errors.push(`${orgId}: ${listed.error}`)\n continue\n }\n const listedIds = new Set(listed.items.map((item) => item.id))\n const readItems = new Map<string, { deleted: boolean; item: StripeExtraTimeItem | null }>()\n for (const row of charged) {\n const id = row.request.charge?.invoiceItemId\n if (!id || listedIds.has(id)) continue\n const read = await readExtraTimeItem(id, input.stripe)\n if (read.ok === false) {\n report.errors.push(`${orgId}/${row.id}: ${read.error}`)\n continue\n }\n readItems.set(id, {\n deleted: read.state.stage === 'deleted',\n item:\n read.state.stage === 'deleted'\n ? null\n : {\n id,\n amountCents: read.state.amountCents,\n quantity: read.state.quantity,\n description: read.state.description,\n requestId: String(read.state.metadata['siteCareRequestId'] ?? row.id),\n month: String(read.state.metadata['month'] ?? row.request.month),\n },\n })\n }\n // Only items for these months' requests are judged here: an older\n // month's item inside the listing window belongs to a month this run\n // does not read.\n const requestIds = new Set(rows.map((row) => row.id))\n const items = listed.items.filter(\n (item) => requestIds.has(item.requestId) || months.includes(item.month),\n )\n const findings = compareSiteCareCharges({ orgId, requests: rows, items, readItems })\n report.findings.push(...findings)\n if (input.dryRun || !findings.length) continue\n const byMonth = new Map<string, SiteCareFinding[]>()\n for (const finding of findings) {\n const list = byMonth.get(finding.month) ?? []\n list.push(finding)\n byMonth.set(finding.month, list)\n }\n const orgSnap = await firestore.collection('orgs').doc(orgId).get()\n const orgName = String(orgSnap.get('name') ?? orgId)\n for (const [month, list] of byMonth) {\n const result = await raiseOperatorAlert('billing.siteCareReconciliation', {\n dedupeKey: `${orgId}:${month}`,\n context: {\n orgId,\n orgName,\n month,\n count: list.length,\n findings: list.map((finding) => finding.detail).join(' '),\n },\n orgId,\n })\n if (result.outcome !== 'deduped' && result.outcome !== 'below-threshold') report.alerted += 1\n }\n } catch (error) {\n report.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n await reconcileProjectsInto(firestore, report, { nowMs, dryRun: input.dryRun, stripe: input.stripe })\n return report\n}\n\n/**\n * The flat-quoted projects (AGL-3970), in the same run and on the same\n * alert: one per workspace with findings, deduplicated a day like the\n * month's, its `month` naming the projects rather than a month.\n */\nasync function reconcileProjectsInto(\n firestore: FirebaseFirestore.Firestore,\n report: SiteCareReconcileReport,\n input: { nowMs: number; dryRun: boolean; stripe?: SiteCareStripeOptions },\n): Promise<void> {\n const current = siteCareMonthKey(input.nowMs)\n let projects\n try {\n projects = await reconcileSiteCareProjects(firestore, { nowMs: input.nowMs, stripe: input.stripe })\n } catch (error) {\n report.errors.push(`projects: ${error instanceof Error ? error.message : String(error)}`)\n return\n }\n report.projects = projects.projects\n report.errors.push(...projects.errors)\n const byOrg = new Map<string, SiteCareFinding[]>()\n for (const finding of projects.findings) {\n const row: SiteCareFinding = {\n orgId: finding.orgId,\n month: current,\n requestId: finding.projectId,\n code: finding.code,\n detail: finding.detail,\n }\n report.findings.push(row)\n const list = byOrg.get(finding.orgId) ?? []\n list.push(row)\n byOrg.set(finding.orgId, list)\n }\n if (input.dryRun) return\n for (const [orgId, list] of byOrg) {\n try {\n const orgSnap = await firestore.collection('orgs').doc(orgId).get()\n const result = await raiseOperatorAlert('billing.siteCareReconciliation', {\n dedupeKey: `${orgId}:projects`,\n context: {\n orgId,\n orgName: String(orgSnap.get('name') ?? orgId),\n month: 'projects',\n count: list.length,\n findings: list.map((finding) => finding.detail).join(' '),\n },\n orgId,\n })\n if (result.outcome !== 'deduped' && result.outcome !== 'below-threshold') report.alerted += 1\n } catch (error) {\n report.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n}\n"],"names":["previousSiteCareMonthKey","siteCareExtraTimeCents","siteCareMonthKey","siteCareMonthStatement","siteCareStatementRequest","readOrgBilling","raiseOperatorAlert","readSiteCareRequest","reconcileSiteCareProjects","listSiteCareExtraTimeItems","readExtraTimeItem","compareSiteCareCharges","input","findings","byId","Map","items","map","item","id","claimed","Set","months","row","requests","request","add","month","charge","at","orgId","requestId","billedHours","push","code","detail","subject","invoiceItemId","fromStripe","get","readItems","find","deleted","status","hours","error","expected","problems","amountCents","quantity","description","length","join","absorbed","has","inMonth","filter","statement","goodwillMinutes","stripeTotal","reduce","sum","String","pendingRecorded","extraBilledCents","reconcileSiteCare","firestore","nowMs","Date","now","current","snapshot","collection","where","limit","byOrg","doc","docs","state","rows","set","report","orgs","size","values","projects","alerted","errors","sinceMs","orgSnap","charged","billing","customerId","stripeCustomerId","listed","stripe","ok","listedIds","read","stage","metadata","requestIds","includes","dryRun","byMonth","finding","list","orgName","result","dedupeKey","context","count","outcome","Error","message","reconcileProjectsInto","projectId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,sBAAsB,EACtBC,gBAAgB,EAChBC,sBAAsB,EACtBC,wBAAwB,QAEnB,mCAAkC;AACzC,SAASC,cAAc,QAAQ,mBAAe;AAC9C,SAASC,kBAAkB,QAAQ,uBAAmB;AACtD,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SACEC,yBAAyB,QAEpB,mCAA+B;AACtC,SACEC,0BAA0B,EAC1BC,iBAAiB,QAGZ,wBAAoB;AA8D3B,mEAAmE,GACnE,OAAO,SAASC,uBAAuBC,KAMtC;IACC,MAAMC,WAA8B,EAAE;IACtC,MAAMC,OAAO,IAAIC,IAAIH,MAAMI,KAAK,CAACC,GAAG,CAAC,CAACC,OAAS;YAACA,KAAKC,EAAE;YAAED;SAAK;IAC9D,MAAME,UAAU,IAAIC;IACpB,MAAMC,SAAS,IAAID;IACnB,KAAK,MAAME,OAAOX,MAAMY,QAAQ,CAAE;YAa3BV,MAAAA,WACAF;YADkCA,sBAAAA,kBAEAA,uBAAAA;QA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I,OAAO,KAAK,aAAaJ,OAAOI,OAAO,KAAK,mBAAmB/B,OAAOK,OAAO,IAAI;QAC9F,EAAE,OAAOzC,OAAO;YACdoC,OAAOM,MAAM,CAACtD,IAAI,CAAC,GAAGH,MAAM,EAAE,EAAEe,iBAAiBoE,QAAQpE,MAAMqE,OAAO,GAAGpD,OAAOjB,QAAQ;QAC1F;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-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 countedSiteCareMinutes,\n previousSiteCareMonthKey,\n siteCareCloseVerdict,\n siteCareExtraTimeCents,\n siteCareIncludedPool,\n siteCareMonthKey,\n siteCareMonthStatement,\n siteCareStatementRequest,\n type SiteCareRequest,\n} from '@aglyn/aglyn/app-utils/site-care'\nimport { readOrgBilling } from './org-billing'\nimport { raiseOperatorAlert } from './operator-alerts'\nimport { readSiteCareRequest, SITE_CARE_MONTHS_COLLECTION } from './site-care-requests'\nimport {\n reconcileSiteCareProjects,\n type SiteCareProjectFindingCode,\n} from './site-care-project-reconcile'\nimport {\n listSiteCareExtraTimeItems,\n readExtraTimeItem,\n type SiteCareStripeOptions,\n type StripeExtraTimeItem,\n} from './site-care-stripe'\n\n/**\n * THE SITE CARE RECONCILIATION (AGL-3959).\n *\n * Once a day, for the current month and the one before: each request's\n * billed hours against the Stripe invoice item that carries them — amount,\n * quantity and description — and each month's billed total against the sum\n * of its Stripe items. Any difference is a finding, and a workspace-month\n * with findings raises `billing.siteCareReconciliation` (Should know)\n * rather than passing silently. The same shape as the pricing-drift check:\n * it compares and reports, and never changes anything on either side — the\n * fix is a person's, from the request.\n *\n * What it catches, by construction of how charges are written:\n * - a Stripe item with no row behind it (the call succeeded, the record did\n * not land): a `creating` charge, or an item no request claims;\n * - a row with no Stripe object: a `pending` charge whose item is gone, or a\n * `failed` one still owing hours;\n * - an item somebody edited in the Stripe dashboard: amount, quantity or\n * description that no longer match the request.\n *\n * ## And against our own ledger (AGL-4031)\n *\n * Comparing a charge with Stripe proves the two copies agree; it cannot\n * prove either is right. So every closed request is also checked against\n * the facts its charge is derived from — the minutes logged, how they were\n * counted against the included hour, the owner's recorded approval — by the\n * same arithmetic the close uses (`allocateSiteCareMinutes`'s counting and\n * `siteCareCloseVerdict`): $79 per STARTED hour of over-time, whole hours,\n * never below the hours approved, nothing without an approval unless it was\n * absorbed. A request, a charge, a Stripe item or a month total that does\n * not come to that number is a finding, whichever side it is on.\n */\n\nexport type SiteCareFindingCode =\n | 'charge-stuck'\n | 'charge-failed'\n | 'item-missing'\n | 'item-mismatch'\n | 'item-not-voided'\n | 'item-without-row'\n | 'hours-mismatch'\n | 'month-total'\n | 'no-customer'\n // Against our own ledger (AGL-4031).\n | 'ledger-minutes'\n | 'ledger-unapproved'\n | 'ledger-hours'\n | 'ledger-amount'\n | 'month-ledger'\n // A flat-quoted project's invoices (AGL-3970), in the same check.\n | SiteCareProjectFindingCode\n\nexport interface SiteCareFinding {\n orgId: string\n month: string\n requestId: string | null\n code: SiteCareFindingCode\n detail: string\n}\n\nexport interface SiteCareReconcileReport {\n months: string[]\n orgs: number\n requests: number\n /** Projects compared (AGL-3970). */\n projects: number\n findings: SiteCareFinding[]\n alerted: number\n errors: string[]\n}\n\ninterface RequestRow {\n id: string\n orgId: string\n subject: string\n request: SiteCareRequest\n}\n\n/**\n * The whole hours a closed request should bill, from its own minutes and\n * approval: the close's verdict, re-run. `null` when no approval covers the\n * over-time and it was not absorbed — nothing may bill, and the request\n * should not have closed that way.\n */\nexport function siteCareLedgerHours(request: SiteCareRequest): number | null {\n const overMinutes = Math.max(0, Number(request.overMinutes) || 0)\n const verdict = siteCareCloseVerdict({\n requiredHours: overMinutes > 0 ? Math.ceil(overMinutes / 60) : 0,\n approval: request.approval,\n absorb: request.absorbed,\n })\n return verdict.ok ? verdict.billedHours : null\n}\n\n/**\n * One workspace's closed requests against their own ledger. Pure, and needs\n * no Stripe: a workspace whose charges cannot be listed is still checked.\n */\nexport function compareSiteCareLedger(input: {\n orgId: string\n requests: readonly RequestRow[]\n /** Goodwill minutes per month, from the month documents; 0 when absent. */\n goodwillByMonth?: ReadonlyMap<string, number>\n}): SiteCareFinding[] {\n const findings: SiteCareFinding[] = []\n const months = new Set<string>()\n for (const row of input.requests) {\n const { request } = row\n months.add(request.month)\n const at = { orgId: input.orgId, month: request.month, requestId: row.id }\n const title = `“${row.subject}”`\n // The minutes: logged → counted in whole blocks → included + over.\n const logged = Number(request.minutesLogged) || 0\n const minuteProblems: string[] = []\n if (request.countedMinutes !== countedSiteCareMinutes(logged)) {\n minuteProblems.push(`${logged} min logged count as ${countedSiteCareMinutes(logged)}, recorded ${request.countedMinutes}`)\n }\n if (request.includedMinutesUsed + request.overMinutes !== request.countedMinutes) {\n minuteProblems.push(\n `${request.includedMinutesUsed} included + ${request.overMinutes} over ≠ ${request.countedMinutes} counted`,\n )\n }\n if (request.includedMinutesUsed < 0 || request.overMinutes < 0) minuteProblems.push('negative minutes')\n if (minuteProblems.length) {\n findings.push({ ...at, code: 'ledger-minutes', detail: `${title}: ${minuteProblems.join('; ')}.` })\n }\n // The hours: whole started hours of over-time, never below the approval.\n const charge = request.charge\n const owing = charge !== null && (charge.status === 'creating' || charge.status === 'pending' || charge.status === 'failed')\n const expected = siteCareLedgerHours(request)\n if (expected === null) {\n if (request.billedHours > 0 || owing) {\n findings.push({\n ...at,\n code: 'ledger-unapproved',\n detail: request.approval\n ? `${title}: bills ${request.billedHours} h for ${request.overMinutes} min past the included hour, more than the ${request.approval.hours} h the owner approved.`\n : `${title}: bills ${request.billedHours} h for ${request.overMinutes} min past the included hour with no approval on file.`,\n })\n } else {\n findings.push({\n ...at,\n code: 'ledger-unapproved',\n detail: `${title}: ${request.overMinutes} min past the included hour, neither billed nor absorbed.`,\n })\n }\n } else {\n if (request.billedHours !== expected) {\n findings.push({\n ...at,\n code: 'ledger-hours',\n detail: `${title}: records ${request.billedHours} h billed, but ${request.overMinutes} min past the included hour${\n request.approval ? ` with ${request.approval.hours} h approved` : ''\n } come to ${expected} h.`,\n })\n }\n if (owing && charge.hours !== expected) {\n findings.push({\n ...at,\n code: 'ledger-hours',\n detail: `${title}: the ${charge.status} charge is for ${charge.hours} h; the logged time comes to ${expected} h.`,\n })\n }\n }\n if (charge && charge.amountCents !== siteCareExtraTimeCents(charge.hours)) {\n findings.push({\n ...at,\n code: 'ledger-amount',\n detail: `${title}: the charge records ${charge.amountCents} cents for ${charge.hours} h, which is ${siteCareExtraTimeCents(charge.hours)}.`,\n })\n }\n }\n for (const month of months) {\n const inMonth = input.requests.filter((row) => row.request.month === month)\n // The included pool is never overdrawn: each close takes only what the\n // month's earlier requests left of it.\n const pool = siteCareIncludedPool(input.goodwillByMonth?.get(month) ?? 0)\n const included = inMonth.reduce((sum, row) => sum + (Number(row.request.includedMinutesUsed) || 0), 0)\n if (included > pool) {\n findings.push({\n orgId: input.orgId,\n month,\n requestId: null,\n code: 'ledger-minutes',\n detail: `${month}: ${included} included minutes used of a ${pool}-minute allowance.`,\n })\n }\n // The month's pending charges against what the ledger says they come to.\n const pending = inMonth.filter((row) => row.request.charge?.status === 'pending')\n const recorded = pending.reduce((sum, row) => sum + (row.request.charge?.amountCents ?? 0), 0)\n const ledger = pending.reduce((sum, row) => sum + siteCareExtraTimeCents(siteCareLedgerHours(row.request) ?? 0), 0)\n if (recorded !== ledger) {\n findings.push({\n orgId: input.orgId,\n month,\n requestId: null,\n code: 'month-ledger',\n detail: `The ${month} pending charges record ${recorded} cents; the logged time and approvals behind them come to ${ledger}.`,\n })\n }\n }\n return findings\n}\n\n/**\n * Compares one workspace's requests with its Stripe items, and with their\n * own ledger ({@link compareSiteCareLedger}). Pure.\n */\nexport function compareSiteCareCharges(input: {\n orgId: string\n requests: readonly RequestRow[]\n items: readonly StripeExtraTimeItem[]\n /** Items read one by one because the listing did not reach them. */\n readItems?: ReadonlyMap<string, { deleted: boolean; item: StripeExtraTimeItem | null }>\n /** Goodwill minutes per month, from the month documents; 0 when absent. */\n goodwillByMonth?: ReadonlyMap<string, number>\n}): SiteCareFinding[] {\n const findings: SiteCareFinding[] = []\n const byId = new Map(input.items.map((item) => [item.id, item]))\n const claimed = new Set<string>()\n const months = new Set<string>()\n for (const row of input.requests) {\n const { request } = row\n months.add(request.month)\n const charge = request.charge\n const at = { orgId: input.orgId, month: request.month, requestId: row.id }\n if (!charge) {\n if (request.billedHours > 0) {\n findings.push({ ...at, code: 'hours-mismatch', detail: `“${row.subject}” bills ${request.billedHours} h with no charge recorded.` })\n }\n continue\n }\n if (charge.invoiceItemId) claimed.add(charge.invoiceItemId)\n const fromStripe = charge.invoiceItemId\n ? (byId.get(charge.invoiceItemId) ?? input.readItems?.get(charge.invoiceItemId)?.item ?? null)\n : (input.items.find((item) => item.requestId === row.id) ?? null)\n const deleted = charge.invoiceItemId ? input.readItems?.get(charge.invoiceItemId)?.deleted === true : false\n if (fromStripe) claimed.add(fromStripe.id)\n switch (charge.status) {\n case 'creating':\n findings.push({\n ...at,\n code: 'charge-stuck',\n detail: fromStripe\n ? `“${row.subject}”: Stripe item ${fromStripe.id} exists but the request never recorded it. Retry the charge to record it.`\n : `“${row.subject}”: a charge was started and never finished. Retry it.`,\n })\n break\n case 'failed':\n findings.push({ ...at, code: 'charge-failed', detail: `“${row.subject}”: ${charge.hours} h owed with no Stripe item (${charge.error ?? 'failed'}).` })\n break\n case 'pending': {\n if (!fromStripe || deleted) {\n findings.push({ ...at, code: 'item-missing', detail: `“${row.subject}”: Stripe item ${charge.invoiceItemId} is gone.` })\n break\n }\n const expected = siteCareExtraTimeCents(charge.hours)\n const problems: string[] = []\n if (fromStripe.amountCents !== expected) problems.push(`amount ${fromStripe.amountCents} ≠ ${expected}`)\n if (fromStripe.quantity !== charge.hours) problems.push(`quantity ${fromStripe.quantity} ≠ ${charge.hours}`)\n if (fromStripe.description !== charge.description) problems.push('description differs')\n if (problems.length) {\n findings.push({ ...at, code: 'item-mismatch', detail: `“${row.subject}” (${fromStripe.id}): ${problems.join(', ')}.` })\n }\n // What the owner will be invoiced against what the ledger says,\n // when the charge itself has drifted (otherwise the line above\n // already names the difference).\n const ledgerHours = siteCareLedgerHours(request)\n const ledgerCents = siteCareExtraTimeCents(ledgerHours ?? 0)\n if (ledgerCents !== expected && fromStripe.amountCents !== ledgerCents) {\n findings.push({\n ...at,\n code: 'ledger-amount',\n detail: `“${row.subject}” (${fromStripe.id}): Stripe will invoice ${fromStripe.amountCents} cents; the logged time and approval come to ${ledgerCents}.`,\n })\n }\n if (request.billedHours !== charge.hours && !request.absorbed) {\n findings.push({ ...at, code: 'hours-mismatch', detail: `“${row.subject}”: billed ${request.billedHours} h but the charge is ${charge.hours} h.` })\n }\n break\n }\n case 'voided':\n if (fromStripe && !deleted) {\n findings.push({ ...at, code: 'item-not-voided', detail: `“${row.subject}”: voided here, but Stripe item ${fromStripe.id} is still there.` })\n }\n break\n default:\n break\n }\n }\n for (const item of input.items) {\n if (claimed.has(item.id)) continue\n findings.push({\n orgId: input.orgId,\n month: [...months][0] ?? '',\n requestId: item.requestId || null,\n code: 'item-without-row',\n detail: `Stripe item ${item.id} (${item.amountCents} cents) names request ${item.requestId}, which does not record it.`,\n })\n }\n // The month's total against Stripe's.\n for (const month of months) {\n const inMonth = input.requests.filter((row) => row.request.month === month)\n const statement = siteCareMonthStatement({\n month,\n goodwillMinutes: input.goodwillByMonth?.get(month) ?? 0,\n requests: inMonth.map((row) => siteCareStatementRequest(row.id, row.subject, row.request)),\n })\n const stripeTotal = inMonth\n .filter((row) => row.request.charge?.status === 'pending' && row.request.charge.invoiceItemId)\n .reduce((sum, row) => {\n const id = String(row.request.charge?.invoiceItemId)\n const item = byId.get(id) ?? input.readItems?.get(id)?.item ?? null\n return sum + (item ? item.amountCents : 0)\n }, 0)\n const pendingRecorded = inMonth\n .filter((row) => row.request.charge?.status === 'pending')\n .reduce((sum, row) => sum + (row.request.charge?.amountCents ?? 0), 0)\n if (stripeTotal !== pendingRecorded) {\n findings.push({\n orgId: input.orgId,\n month,\n requestId: null,\n code: 'month-total',\n detail: `The ${month} statement bills ${statement.extraBilledCents} cents (${pendingRecorded} on pending items) and Stripe holds ${stripeTotal}.`,\n })\n }\n }\n findings.push(...compareSiteCareLedger(input))\n return findings\n}\n\n/** Each month's goodwill minutes for one workspace, from its month documents. */\nasync function readGoodwill(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n months: readonly string[],\n): Promise<Map<string, number>> {\n const goodwill = new Map<string, number>()\n for (const month of months) {\n const snapshot = await firestore.collection('orgs').doc(orgId).collection(SITE_CARE_MONTHS_COLLECTION).doc(month).get()\n goodwill.set(month, Math.max(0, Number(snapshot.get('goodwillMinutes') ?? 0) || 0))\n }\n return goodwill\n}\n\n/** Runs the check over the current and previous month. */\nexport async function reconcileSiteCare(\n firestore: FirebaseFirestore.Firestore,\n input: { nowMs?: number; dryRun: boolean; stripe?: SiteCareStripeOptions },\n): Promise<SiteCareReconcileReport> {\n const nowMs = input.nowMs ?? Date.now()\n const current = siteCareMonthKey(nowMs)\n const months = [current, previousSiteCareMonthKey(current)]\n const snapshot = await firestore.collection('supportTickets').where('siteCareMonth', 'in', months).limit(2000).get()\n const byOrg = new Map<string, RequestRow[]>()\n for (const doc of snapshot.docs) {\n const request = readSiteCareRequest(doc.get('siteCare'))\n const orgId = String(doc.get('orgId') ?? '')\n if (!request || !orgId || request.state !== 'closed') continue\n const rows = byOrg.get(orgId) ?? []\n rows.push({ id: doc.id, orgId, subject: String(doc.get('subject') ?? ''), request })\n byOrg.set(orgId, rows)\n }\n const report: SiteCareReconcileReport = {\n months,\n orgs: byOrg.size,\n requests: [...byOrg.values()].reduce((sum, rows) => sum + rows.length, 0),\n projects: 0,\n findings: [],\n alerted: 0,\n errors: [],\n }\n // Seventy days reaches back past the start of the previous month.\n const sinceMs = nowMs - 70 * 24 * 60 * 60 * 1000\n for (const [orgId, rows] of byOrg) {\n try {\n const goodwillByMonth = await readGoodwill(firestore, orgId, months)\n const charged = rows.filter((row) => row.request.charge)\n // Our own ledger first, and on its own wherever Stripe is not read: a\n // workspace with no charge, no customer, or a listing that failed is\n // still checked against itself (AGL-4031).\n const ledgerOnly = () => compareSiteCareLedger({ orgId, requests: rows, goodwillByMonth })\n let findings: SiteCareFinding[]\n const billing = charged.length ? await readOrgBilling(orgId) : null\n const customerId = String((billing as { stripeCustomerId?: unknown } | null)?.stripeCustomerId ?? '')\n const listed = customerId ? await listSiteCareExtraTimeItems({ customerId, sinceMs }, input.stripe) : null\n if (!charged.length) {\n findings = ledgerOnly()\n } else if (!customerId) {\n findings = [\n { orgId, month: current, requestId: null, code: 'no-customer', detail: 'Charges are recorded but the workspace has no Stripe customer.' },\n ...ledgerOnly(),\n ]\n } else if (!listed || listed.ok === false) {\n report.errors.push(`${orgId}: ${listed && listed.ok === false ? listed.error : 'no listing'}`)\n findings = ledgerOnly()\n } else {\n const listedIds = new Set(listed.items.map((item) => item.id))\n const readItems = new Map<string, { deleted: boolean; item: StripeExtraTimeItem | null }>()\n for (const row of charged) {\n const id = row.request.charge?.invoiceItemId\n if (!id || listedIds.has(id)) continue\n const read = await readExtraTimeItem(id, input.stripe)\n if (read.ok === false) {\n report.errors.push(`${orgId}/${row.id}: ${read.error}`)\n continue\n }\n readItems.set(id, {\n deleted: read.state.stage === 'deleted',\n item:\n read.state.stage === 'deleted'\n ? null\n : {\n id,\n amountCents: read.state.amountCents,\n quantity: read.state.quantity,\n description: read.state.description,\n requestId: String(read.state.metadata['siteCareRequestId'] ?? row.id),\n month: String(read.state.metadata['month'] ?? row.request.month),\n },\n })\n }\n // Only items for these months' requests are judged here: an older\n // month's item inside the listing window belongs to a month this run\n // does not read.\n const requestIds = new Set(rows.map((row) => row.id))\n const items = listed.items.filter(\n (item) => requestIds.has(item.requestId) || months.includes(item.month),\n )\n findings = compareSiteCareCharges({ orgId, requests: rows, items, readItems, goodwillByMonth })\n }\n report.findings.push(...findings)\n if (input.dryRun || !findings.length) continue\n const byMonth = new Map<string, SiteCareFinding[]>()\n for (const finding of findings) {\n const list = byMonth.get(finding.month) ?? []\n list.push(finding)\n byMonth.set(finding.month, list)\n }\n const orgSnap = await firestore.collection('orgs').doc(orgId).get()\n const orgName = String(orgSnap.get('name') ?? orgId)\n for (const [month, list] of byMonth) {\n const result = await raiseOperatorAlert('billing.siteCareReconciliation', {\n dedupeKey: `${orgId}:${month}`,\n context: {\n orgId,\n orgName,\n month,\n count: list.length,\n findings: list.map((finding) => finding.detail).join(' '),\n },\n orgId,\n })\n if (result.outcome !== 'deduped' && result.outcome !== 'below-threshold') report.alerted += 1\n }\n } catch (error) {\n report.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n await reconcileProjectsInto(firestore, report, { nowMs, dryRun: input.dryRun, stripe: input.stripe })\n return report\n}\n\n/**\n * The flat-quoted projects (AGL-3970), in the same run and on the same\n * alert: one per workspace with findings, deduplicated a day like the\n * month's, its `month` naming the projects rather than a month.\n */\nasync function reconcileProjectsInto(\n firestore: FirebaseFirestore.Firestore,\n report: SiteCareReconcileReport,\n input: { nowMs: number; dryRun: boolean; stripe?: SiteCareStripeOptions },\n): Promise<void> {\n const current = siteCareMonthKey(input.nowMs)\n let projects\n try {\n projects = await reconcileSiteCareProjects(firestore, { nowMs: input.nowMs, stripe: input.stripe })\n } catch (error) {\n report.errors.push(`projects: ${error instanceof Error ? error.message : String(error)}`)\n return\n }\n report.projects = projects.projects\n report.errors.push(...projects.errors)\n const byOrg = new Map<string, SiteCareFinding[]>()\n for (const finding of projects.findings) {\n const row: SiteCareFinding = {\n orgId: finding.orgId,\n month: current,\n requestId: finding.projectId,\n code: finding.code,\n detail: finding.detail,\n }\n report.findings.push(row)\n const list = byOrg.get(finding.orgId) ?? []\n list.push(row)\n byOrg.set(finding.orgId, list)\n }\n if (input.dryRun) return\n for (const [orgId, list] of byOrg) {\n try {\n const orgSnap = await firestore.collection('orgs').doc(orgId).get()\n const result = await raiseOperatorAlert('billing.siteCareReconciliation', {\n dedupeKey: `${orgId}:projects`,\n context: {\n orgId,\n orgName: String(orgSnap.get('name') ?? orgId),\n month: 'projects',\n count: list.length,\n findings: list.map((finding) => finding.detail).join(' '),\n },\n orgId,\n })\n if (result.outcome !== 'deduped' && result.outcome !== 'below-threshold') report.alerted += 1\n } catch (error) {\n report.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n}\n"],"names":["countedSiteCareMinutes","previousSiteCareMonthKey","siteCareCloseVerdict","siteCareExtraTimeCents","siteCareIncludedPool","siteCareMonthKey","siteCareMonthStatement","siteCareStatementRequest","readOrgBilling","raiseOperatorAlert","readSiteCareRequest","SITE_CARE_MONTHS_COLLECTION","reconcileSiteCareProjects","listSiteCareExtraTimeItems","readExtraTimeItem","siteCareLedgerHours","request","overMinutes","Math","max","Number","verdict","requiredHours","ceil","approval","absorb","absorbed","ok","billedHours","compareSiteCareLedger","input","findings","months","Set","row","requests","add","month","at","orgId","requestId","id","title","subject","logged","minutesLogged","minuteProblems","countedMinutes","push","includedMinutesUsed","length","code","detail","join","charge","owing","status","expected","hours","amountCents","inMonth","filter","pool","goodwillByMonth","get","included","reduce","sum","pending","recorded","ledger","compareSiteCareCharges","byId","Map","items","map","item","claimed","invoiceItemId","fromStripe","readItems","find","deleted","error","problems","quantity","description","ledgerHours","ledgerCents","has","statement","goodwillMinutes","stripeTotal","String","pendingRecorded","extraBilledCents","readGoodwill","firestore","goodwill","snapshot","collection","doc","set","reconcileSiteCare","nowMs","Date","now","current","where","limit","byOrg","docs","state","rows","report","orgs","size","values","projects","alerted","errors","sinceMs","orgSnap","charged","ledgerOnly","billing","customerId","stripeCustomerId","listed","stripe","listedIds","read","stage","metadata","requestIds","includes","dryRun","byMonth","finding","list","orgName","result","dedupeKey","context","count","outcome","Error","message","reconcileProjectsInto","projectId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,wBAAwB,EACxBC,oBAAoB,EACpBC,sBAAsB,EACtBC,oBAAoB,EACpBC,gBAAgB,EAChBC,sBAAsB,EACtBC,wBAAwB,QAEnB,mCAAkC;AACzC,SAASC,cAAc,QAAQ,mBAAe;AAC9C,SAASC,kBAAkB,QAAQ,uBAAmB;AACtD,SAASC,mBAAmB,EAAEC,2BAA2B,QAAQ,0BAAsB;AACvF,SACEC,yBAAyB,QAEpB,mCAA+B;AACtC,SACEC,0BAA0B,EAC1BC,iBAAiB,QAGZ,wBAAoB;AAgF3B;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,OAAwB;IAC1D,MAAMC,cAAcC,KAAKC,GAAG,CAAC,GAAGC,OAAOJ,QAAQC,WAAW,KAAK;IAC/D,MAAMI,UAAUnB,qBAAqB;QACnCoB,eAAeL,cAAc,IAAIC,KAAKK,IAAI,CAACN,cAAc,MAAM;QAC/DO,UAAUR,QAAQQ,QAAQ;QAC1BC,QAAQT,QAAQU,QAAQ;IAC1B;IACA,OAAOL,QAAQM,EAAE,GAAGN,QAAQO,WAAW,GAAG;AAC5C;AAEA;;;CAGC,GACD,OAAO,SAASC,sBAAsBC,KAKrC;IACC,MAAMC,WAA8B,EAAE;IACtC,MAAMC,SAAS,IAAIC;IACnB,KAAK,MAAMC,OAAOJ,MAAMK,QAAQ,CAAE;QAChC,MAAM,EAAEnB,OAAO,EAAE,GAAGkB;QACpBF,OAAOI,GAAG,CAACpB,QAAQqB,KAAK;QACxB,MAAMC,KAAK;YAAEC,OAAOT,MAAMS,KAAK;YAAEF,OAAOrB,QAAQqB,KAAK;YAAEG,WAAWN,IAAIO,E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QAAQnG,KAAK,EAAEoG;IAC3B;IACA,IAAI7G,MAAM0G,MAAM,EAAE;IAClB,KAAK,MAAM,CAACjG,OAAOoG,KAAK,IAAI7B,MAAO;QACjC,IAAI;gBAMkBY;YALpB,MAAMA,UAAU,MAAMzB,UAAUG,UAAU,CAAC,QAAQC,GAAG,CAAC9D,OAAOyB,GAAG;YACjE,MAAM6E,SAAS,MAAMpI,mBAAmB,kCAAkC;gBACxEqI,WAAW,GAAGvG,MAAM,SAAS,CAAC;gBAC9BwG,SAAS;oBACPxG;oBACAqG,SAAS/C,QAAO6B,eAAAA,QAAQ1D,GAAG,CAAC,mBAAZ0D,eAAuBnF;oBACvCF,OAAO;oBACP2G,OAAOL,KAAKzF,MAAM;oBAClBnB,UAAU4G,KAAKhE,GAAG,CAAC,CAAC+D,UAAYA,QAAQtF,MAAM,EAAEC,IAAI,CAAC;gBACvD;gBACAd;YACF;YACA,IAAIsG,OAAOI,OAAO,KAAK,aAAaJ,OAAOI,OAAO,KAAK,mBAAmB/B,OAAOK,OAAO,IAAI;QAC9F,EAAE,OAAOpC,OAAO;YACd+B,OAAOM,MAAM,CAACxE,IAAI,CAAC,GAAGT,MAAM,EAAE,EAAE4C,iBAAiB+D,QAAQ/D,MAAMgE,OAAO,GAAGtD,OAAOV,QAAQ;QAC1F;IACF;AACF"}
@@ -16,7 +16,7 @@
16
16
  */
17
17
  import { type AppendOnlyHistoryRow } from '@aglyn/aglyn/app-utils/append-only-history';
18
18
  import { type OwnerApprovalRecord } from '@aglyn/aglyn/app-utils/owner-approval-record';
19
- import { type SiteCareCharge, type SiteCareCloseVerdict, type SiteCareMonthStatement, type SiteCarePublishLink, type SiteCareRequest, type SiteCareSource } from '@aglyn/aglyn/app-utils/site-care';
19
+ import { type SiteCareCharge, type SiteCareCloseVerdict, type SiteCareMonthStatement, type SiteCarePublishLink, type SiteCareRequest, type SiteCareSource, type SiteCareWorkspaceCandidate } from '@aglyn/aglyn/app-utils/site-care';
20
20
  import { sendSiteCareEmail, type SiteCareEmailResult } from './site-care-emails';
21
21
  import { type SiteCareStripeOptions } from './site-care-stripe';
22
22
  export declare const SITE_CARE_HISTORY_COLLECTION = "siteCareHistory";
@@ -67,6 +67,12 @@ export interface OpenSiteCareRequestInput {
67
67
  * twice.
68
68
  */
69
69
  dedupeKey?: string | null;
70
+ /**
71
+ * Every Site Care workspace an emailed request's sender belongs to, the
72
+ * one it is filed on included (AGL-4031). Kept, for staff only, when there
73
+ * is more than one, so staff can move the request to the right one.
74
+ */
75
+ candidates?: readonly SiteCareWorkspaceCandidate[];
70
76
  }
71
77
  /** A document id derived from a received message, alphanumeric so it fits a reply address. */
72
78
  export declare function siteCareMessageDocId(prefix: string, key: string): string;
@@ -100,6 +106,38 @@ export declare function startSiteCareTimer(firestore: FirebaseFirestore.Firestor
100
106
  ticketId: string;
101
107
  actor: SiteCareActor;
102
108
  }, deps?: SiteCareDeps): Promise<SiteCareRequest>;
109
+ /** The candidates recorded for a request, or none. */
110
+ export declare function readSiteCareCandidatesFor(firestore: FirebaseFirestore.Firestore, ticketId: string): Promise<SiteCareWorkspaceCandidate[]>;
111
+ export interface MoveSiteCareResult {
112
+ request: SiteCareRequest;
113
+ fromOrgId: string;
114
+ orgId: string;
115
+ }
116
+ /**
117
+ * Moves an open request to another Site Care workspace its sender belongs
118
+ * to (AGL-4031): an emailed request from a sender in several is filed on a
119
+ * default one, and staff move it when it belongs to another.
120
+ *
121
+ * Refused for a closed request, one with a charge or an owner's approval on
122
+ * it ({@link siteCareMoveBlockedReason}), and for any workspace that is not
123
+ * one of the candidates recorded at intake, no longer has Site Care, or no
124
+ * longer has the sender as a member.
125
+ *
126
+ * What moves is everything the request holds against a workspace: the
127
+ * ticket's `orgId` and plan, and its month key (`siteCareOrgMonth`), which
128
+ * is what puts a request in a workspace's month. A month's totals are not
129
+ * stored: they are read from the requests that carry its key, and an open
130
+ * request has logged no minutes yet (they are logged at close), so changing
131
+ * the key in this one write takes it out of the old workspace's month and
132
+ * into the new one's at once. A site it named is cleared, since that site
133
+ * is the old workspace's. The `request.moved` row and the staff audit row
134
+ * commit in the same transaction; nothing earlier is rewritten.
135
+ */
136
+ export declare function moveSiteCareRequest(firestore: FirebaseFirestore.Firestore, input: {
137
+ ticketId: string;
138
+ actor: SiteCareActor;
139
+ orgId: unknown;
140
+ }, deps?: SiteCareDeps): Promise<MoveSiteCareResult>;
103
141
  /** Why a close or a correction is blocked, as the staff panel says it. */
104
142
  export declare function siteCareBlockedMessage(verdict: Extract<SiteCareCloseVerdict, {
105
143
  ok: false;
@@ -238,6 +276,10 @@ export interface SiteCareRequestPanel {
238
276
  suggestedMinutes: number;
239
277
  /** What this request's month looks like with its other requests. */
240
278
  monthMinutesLeft: number;
279
+ /** Other Site Care workspaces the sender belongs to (AGL-4031). */
280
+ otherWorkspaces: SiteCareWorkspaceCandidate[];
281
+ /** Why "Move to workspace" is refused, or null when it is offered. */
282
+ moveBlockedReason: string | null;
241
283
  }
242
284
  /** Everything the staff panel shows for one request. */
243
285
  export declare function readSiteCareRequestPanel(firestore: FirebaseFirestore.Firestore, ticketId: string, deps?: SiteCareDeps): Promise<SiteCareRequestPanel>;