@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.
- package/package.json +7 -7
- package/src/lib/server/append-only-history-write.d.ts +38 -0
- package/src/lib/server/append-only-history-write.js +60 -0
- package/src/lib/server/append-only-history-write.js.map +1 -0
- package/src/lib/server/billing-addons.d.ts +58 -32
- package/src/lib/server/billing-addons.js +100 -86
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +166 -0
- package/src/lib/server/bundle-links.js +286 -0
- package/src/lib/server/bundle-links.js.map +1 -0
- package/src/lib/server/client-build.d.ts +74 -0
- package/src/lib/server/client-build.js +264 -0
- package/src/lib/server/client-build.js.map +1 -0
- package/src/lib/server/host-memberships.d.ts +35 -2
- package/src/lib/server/host-memberships.js +63 -2
- package/src/lib/server/host-memberships.js.map +1 -1
- package/src/lib/server/org-billing.d.ts +4 -2
- package/src/lib/server/org-billing.js +5 -0
- package/src/lib/server/org-billing.js.map +1 -1
- package/src/lib/server/site-care-emails.d.ts +52 -0
- package/src/lib/server/site-care-emails.js +97 -0
- package/src/lib/server/site-care-emails.js.map +1 -0
- package/src/lib/server/site-care-inbound.d.ts +80 -0
- package/src/lib/server/site-care-inbound.js +171 -0
- package/src/lib/server/site-care-inbound.js.map +1 -0
- package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
- package/src/lib/server/site-care-project-reconcile.js +211 -0
- package/src/lib/server/site-care-project-reconcile.js.map +1 -0
- package/src/lib/server/site-care-project-stripe.d.ts +114 -0
- package/src/lib/server/site-care-project-stripe.js +305 -0
- package/src/lib/server/site-care-project-stripe.js.map +1 -0
- package/src/lib/server/site-care-projects.d.ts +169 -0
- package/src/lib/server/site-care-projects.js +882 -0
- package/src/lib/server/site-care-projects.js.map +1 -0
- package/src/lib/server/site-care-reconcile.d.ts +81 -0
- package/src/lib/server/site-care-reconcile.js +349 -0
- package/src/lib/server/site-care-reconcile.js.map +1 -0
- package/src/lib/server/site-care-requests.d.ts +243 -0
- package/src/lib/server/site-care-requests.js +1414 -0
- package/src/lib/server/site-care-requests.js.map +1 -0
- package/src/lib/server/site-care-stripe.d.ts +175 -0
- package/src/lib/server/site-care-stripe.js +375 -0
- package/src/lib/server/site-care-stripe.js.map +1 -0
- package/src/lib/server/upgrade-proposal.d.ts +40 -1
- package/src/lib/server/upgrade-proposal.js +92 -50
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/tenancy.d.ts +1 -0
- package/src/tenancy.js +2 -0
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-projects.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 historyRow,\n requireHistoryReason,\n type AppendOnlyHistoryRow,\n type HistoryStripeRef,\n} from '@aglyn/aglyn/app-utils/append-only-history'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport {\n OWNER_APPROVAL_CHANNEL_WORDS,\n readOwnerApprovalInput,\n} from '@aglyn/aglyn/app-utils/owner-approval-record'\nimport {\n formatSiteCareDate,\n formatSiteCareUsd,\n SITE_CARE_TIME_ZONE,\n} from '@aglyn/aglyn/app-utils/site-care'\nimport {\n latestSiteCareProjectInvoice,\n readSiteCareProject,\n readSiteCareProjectScope,\n readSiteCareProjectTitle,\n SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE,\n SITE_CARE_PROJECT_MAX_HOURS,\n siteCareProjectAcceptanceIsCurrent,\n siteCareProjectAcceptanceSentence,\n siteCareProjectInvoiceDescription,\n siteCareProjectInvoiceMemo,\n siteCareProjectInvoiceWords,\n siteCareProjectNextInvoice,\n siteCareProjectQuote,\n siteCareProjectQuoteIsEditable,\n siteCareProjectSplitSentence,\n siteCareProjectStatus,\n type SiteCareProject,\n type SiteCareProjectAcceptance,\n type SiteCareProjectInvoice,\n type SiteCareProjectInvoiceStatus,\n} from '@aglyn/aglyn/app-utils/site-care-project'\nimport {\n SITE_CARE_PROJECT_ACCEPTANCE_EMAIL_KEY,\n SITE_CARE_PROJECT_INVOICE_EMAIL_KEY,\n SITE_CARE_PROJECT_PAID_EMAIL_KEY,\n SITE_CARE_PROJECT_REVERSED_EMAIL_KEY,\n} from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n appendHistoryRow,\n commitHistoryRow,\n readHistoryRows,\n type HistoryAudit,\n} from './append-only-history-write'\nimport { readOrgBilling } from './org-billing'\nimport { sendSiteCareEmail, type SiteCareEmailResult } from './site-care-emails'\nimport {\n createProjectInvoice,\n readProjectInvoice,\n SITE_CARE_PROJECT_METADATA_KEY,\n voidProjectInvoice,\n} from './site-care-project-stripe'\nimport {\n readSiteCareOrg,\n SITE_CARE_HISTORY_COLLECTION,\n SiteCareError,\n siteCareOwnerEmail,\n type SiteCareActor,\n type SiteCareDeps,\n} from './site-care-requests'\nimport { creditExtraTimeItem, siteCareExtraTimeProduct } from './site-care-stripe'\n\n/**\n * SITE CARE PROJECTS, WITH FIRESTORE AND STRIPE (AGL-3970).\n *\n * The staff \"Charge for work\": a flat-quoted project on the org\n * (`orgs/{orgId}/siteCareProjects/{id}`) holding the scope, the quote, the\n * owner's recorded yes, every invoice it raised and the launch, with an\n * append-only history beside it (`…/siteCareProjects/{id}/siteCareHistory`).\n * None of it is in the Firestore rules: every read and write passes the\n * console's routes, as Site Care requests do.\n *\n * The same discipline as Site Care extra time, from the same modules:\n * every change writes its history row in the same batch or transaction as\n * the change, and a staff member's change writes its `adminAudit` row there\n * too. Money moves in two steps around the Stripe calls — a `creating`\n * invoice and its `invoice.requested` row commit first, then the calls under\n * the invoice's own idempotency key, then the result and its row together —\n * so a success with no row behind it is a `creating` invoice the\n * reconciliation reports and a retry adopts. Reversals write their intent\n * row before the call, keyed by the invoice's own key.\n *\n * The arithmetic is `@aglyn/aglyn/app-utils/site-care-project`, the yes\n * `owner-approval-record`, the row `append-only-history`, the Stripe calls\n * `site-care-project-stripe.ts`.\n */\n\nexport const SITE_CARE_PROJECTS_COLLECTION = 'siteCareProjects'\n\nfunction projectRef(firestore: FirebaseFirestore.Firestore, orgId: string, projectId: string) {\n return firestore.collection('orgs').doc(orgId).collection(SITE_CARE_PROJECTS_COLLECTION).doc(projectId)\n}\n\nfunction projectHistory(firestore: FirebaseFirestore.Firestore, orgId: string, projectId: string) {\n return projectRef(firestore, orgId, projectId).collection(SITE_CARE_HISTORY_COLLECTION)\n}\n\nfunction projectAudit(orgId: string, projectId: string, action: string): HistoryAudit {\n return {\n action: `siteCareProject.${action}`,\n scope: 'siteCare',\n target: `orgs/${orgId}/${SITE_CARE_PROJECTS_COLLECTION}/${projectId}`,\n }\n}\n\nconst nowOf = (deps: SiteCareDeps) => (deps.now ?? Date.now)()\nconst emailOf = (deps: SiteCareDeps) => deps.email ?? sendSiteCareEmail\n\n/** The project as it is stored: every field, its status recomputed. */\nfunction projectDoc(project: SiteCareProject): Record<string, unknown> {\n return {\n ...project,\n status: siteCareProjectStatus(project),\n updatedAt: FieldValue.serverTimestamp(),\n }\n}\n\nfunction loadedProject(snapshot: FirebaseFirestore.DocumentSnapshot): SiteCareProject {\n const data = snapshot.exists ? snapshot.data() : null\n if (!data) throw new SiteCareError('Unknown project', 404)\n const project = readSiteCareProject(data)\n if (!project) throw new SiteCareError('That project record is unreadable', 409)\n return project\n}\n\nfunction findInvoice(project: SiteCareProject, seq: number): SiteCareProjectInvoice {\n const invoice = project.invoices.find((row) => row.seq === seq)\n if (!invoice) throw new SiteCareError('Unknown invoice on this project', 404)\n return invoice\n}\n\nfunction withInvoice(project: SiteCareProject, next: SiteCareProjectInvoice): SiteCareProject {\n return { ...project, invoices: project.invoices.map((row) => (row.seq === next.seq ? next : row)) }\n}\n\nfunction invoiceStripeRef(invoice: SiteCareProjectInvoice): HistoryStripeRef | null {\n return invoice.invoiceId ? { object: 'invoice', id: invoice.invoiceId, amountCents: invoice.totalCents || invoice.amountCents } : null\n}\n\n/** \"Nov 2, 2026\". */\nfunction formatSiteCareDay(ms: number): string {\n return new Date(ms).toLocaleDateString('en-US', {\n timeZone: SITE_CARE_TIME_ZONE,\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n })\n}\n\n/** Records an email as the project's history row. Never throws. */\nasync function recordProjectEmail(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n projectId: string,\n result: SiteCareEmailResult,\n what: string,\n atMs: number,\n): Promise<void> {\n await commitHistoryRow(\n firestore,\n projectHistory(firestore, orgId, projectId),\n historyRow({\n atMs,\n by: { uid: null, email: null },\n kind: result.sent ? 'email.sent' : 'email.notSent',\n summary: result.sent\n ? `Emailed ${what} to ${result.to}.`\n : `The ${what} email was not sent${result.to ? ` to ${result.to}` : ''} (${result.reason ?? 'unknown'}).`,\n after: { subject: result.subject, to: result.to, sent: result.sent },\n subjectId: projectId,\n }),\n ).catch((error) => console.error('[site-care-projects] email history row failed', error))\n}\n\n/** Emails the owner, in the workspace's brand, and records it on the project. */\nasync function emailOwner(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n projectId: string\n key: string\n what: string\n merge: Record<string, string>\n fallback: { subject: string; text: string }\n },\n deps: SiteCareDeps,\n): Promise<SiteCareEmailResult> {\n const org = await readSiteCareOrg(firestore, input.orgId)\n const to = await siteCareOwnerEmail(firestore, input.orgId, org)\n const result = await emailOf(deps)({\n key: input.key,\n to,\n org,\n requestId: null,\n merge: input.merge,\n fallback: input.fallback,\n })\n await recordProjectEmail(firestore, input.orgId, input.projectId, result, input.what, nowOf(deps))\n return result\n}\n\nfunction scopeText(project: Pick<SiteCareProject, 'scope'>): string {\n return project.scope.map((line) => `- ${line}`).join('\\n')\n}\n\n// ── Quote ───────────────────────────────────────────────────────────────────\n\nexport interface SiteCareProjectQuoteInput {\n title: unknown\n scope: unknown\n kind: unknown\n estimatedHours: unknown\n /** A price above the computed one; blank means the computed one. */\n priceUsd?: unknown\n}\n\nfunction readQuoteInput(input: SiteCareProjectQuoteInput) {\n const title = readSiteCareProjectTitle(input.title)\n if (title.ok === false) throw new SiteCareError(title.error, 400)\n const scope = readSiteCareProjectScope(input.scope)\n if (scope.ok === false) throw new SiteCareError(scope.error, 400)\n const quote = siteCareProjectQuote({ kind: input.kind, estimatedHours: input.estimatedHours, priceUsd: input.priceUsd })\n if (quote.ok === false) throw new SiteCareError(quote.error, 400)\n return { title: title.title, scope: scope.scope, quote: quote.quote }\n}\n\n/** Quotes a project on a workspace. Nothing bills until the owner's yes is recorded. */\nexport async function createSiteCareProject(\n firestore: FirebaseFirestore.Firestore,\n input: SiteCareProjectQuoteInput & { orgId: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<{ projectId: string; project: SiteCareProject }> {\n if (!input.orgId) throw new SiteCareError('Missing orgId', 400)\n const { title, scope, quote } = readQuoteInput(input)\n const org = await firestore.collection('orgs').doc(input.orgId).get()\n if (!org.exists) throw new SiteCareError('Unknown workspace', 404)\n const nowMs = nowOf(deps)\n // Minted once, before the write: every invoice's Stripe idempotency key is\n // built from this id, so it is fixed for the life of the project.\n const ref = firestore\n .collection('orgs')\n .doc(input.orgId)\n .collection(SITE_CARE_PROJECTS_COLLECTION)\n .doc(createResourceUid())\n const project: SiteCareProject = {\n orgId: input.orgId,\n title,\n scope,\n quote,\n quoteVersion: 1,\n acceptance: null,\n invoices: [],\n invoiceSeq: 0,\n firstInvoiceSentAtMs: null,\n launchedAtMs: null,\n launchedByUid: null,\n status: 'quoted',\n createdAtMs: nowMs,\n createdByUid: input.actor.uid,\n createdByEmail: input.actor.email,\n updatedAtMs: nowMs,\n }\n const batch = firestore.batch()\n batch.create(ref, { ...projectDoc(project), createdAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n batch,\n firestore,\n ref.collection(SITE_CARE_HISTORY_COLLECTION),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'project.quoted',\n summary: `Quoted “${title}”: ${siteCareProjectSplitSentence(quote)}`,\n after: { title, scope, quote: { ...quote } },\n subjectId: ref.id,\n }),\n projectAudit(input.orgId, ref.id, 'quoted'),\n )\n await batch.commit()\n return { projectId: ref.id, project }\n}\n\n/**\n * Changes a project's name, scope or price, with a reason — only until the\n * first invoice is sent. Any change is a new quote version, so a yes the\n * owner gave to the old one no longer invoices anything.\n */\nexport async function editSiteCareProject(\n firestore: FirebaseFirestore.Firestore,\n input: SiteCareProjectQuoteInput & { orgId: string; projectId: string; actor: SiteCareActor; reason: unknown },\n deps: SiteCareDeps = {},\n): Promise<SiteCareProject> {\n const reason = requireHistoryReason(input.reason)\n if (reason.ok === false) throw new SiteCareError(reason.error, 400)\n const { title, scope, quote } = readQuoteInput(input)\n const nowMs = nowOf(deps)\n return firestore.runTransaction(async (tx) => {\n const ref = projectRef(firestore, input.orgId, input.projectId)\n const project = loadedProject(await tx.get(ref))\n if (!siteCareProjectQuoteIsEditable(project)) {\n throw new SiteCareError(\n 'The first invoice is sent, so the quote is fixed. Void or credit an invoice from the project, and quote a new project for a new price.',\n 409,\n )\n }\n const changed =\n title !== project.title ||\n scope.join('\\n') !== project.scope.join('\\n') ||\n quote.kind !== project.quote.kind ||\n quote.estimatedHours !== project.quote.estimatedHours ||\n quote.priceUsd !== project.quote.priceUsd\n if (!changed) throw new SiteCareError('Nothing changed.', 400)\n const next: SiteCareProject = {\n ...project,\n title,\n scope,\n quote,\n quoteVersion: project.quoteVersion + 1,\n updatedAtMs: nowMs,\n }\n tx.set(ref, projectDoc(next))\n const priceMoved = quote.priceUsd !== project.quote.priceUsd\n appendHistoryRow(\n tx,\n firestore,\n projectHistory(firestore, input.orgId, input.projectId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'quote.corrected',\n summary:\n (priceMoved\n ? `Changed the quote from ${formatSiteCareUsd(project.quote.priceUsd * 100)} to ${formatSiteCareUsd(quote.priceUsd * 100)}.`\n : 'Changed the quote’s name or scope; the price is the same.') +\n (project.acceptance ? ' The owner’s yes must be recorded again for this quote.' : ''),\n reason: reason.reason,\n before: { title: project.title, scope: project.scope, quote: { ...project.quote }, quoteVersion: project.quoteVersion },\n after: { title, scope, quote: { ...quote }, quoteVersion: next.quoteVersion },\n subjectId: input.projectId,\n }),\n projectAudit(input.orgId, input.projectId, 'quote.corrected'),\n )\n return next\n })\n}\n\n// ── The owner's yes ─────────────────────────────────────────────────────────\n\n/**\n * Records — or corrects — how and when the owner accepted the quote as it\n * stands, and emails them the confirmation of the scope and price that is\n * the written record. Nothing is invoiced before this.\n */\nexport async function recordSiteCareProjectAcceptance(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string; actor: SiteCareActor & { uid: string }; acceptance: Record<string, unknown> },\n deps: SiteCareDeps = {},\n): Promise<SiteCareProjectAcceptance> {\n const nowMs = nowOf(deps)\n const { project, record, previous } = await firestore.runTransaction(async (tx) => {\n const ref = projectRef(firestore, input.orgId, input.projectId)\n const project = loadedProject(await tx.get(ref))\n // A correction is of a yes to THIS quote; a yes to an older quote is\n // replaced by a new one, which needs no reason — the quote changed.\n const previous = siteCareProjectAcceptanceIsCurrent(project) ? project.acceptance : null\n const read = readOwnerApprovalInput(\n { ...input.acceptance, hours: project.quote.billedHours },\n {\n rateUsd: project.quote.rateUsd,\n nowMs,\n by: { uid: input.actor.uid, email: input.actor.email },\n previous,\n maxHours: SITE_CARE_PROJECT_MAX_HOURS,\n },\n )\n if (read.ok === false) throw new SiteCareError(read.error, 400)\n const record: SiteCareProjectAcceptance = {\n ...read.record,\n ...(previous || !project.acceptance ? {} : { version: project.acceptance.version + 1 }),\n quoteVersion: project.quoteVersion,\n priceUsd: project.quote.priceUsd,\n }\n const next: SiteCareProject = { ...project, acceptance: record, updatedAtMs: nowMs }\n tx.set(ref, projectDoc(next))\n appendHistoryRow(\n tx,\n firestore,\n projectHistory(firestore, input.orgId, input.projectId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: previous ? 'acceptance.corrected' : 'acceptance.recorded',\n summary: previous\n ? `Corrected how the owner accepted the quote: ${OWNER_APPROVAL_CHANNEL_WORDS[record.channel]} on ${formatSiteCareDate(record.approvedAtMs)}.`\n : siteCareProjectAcceptanceSentence(record, project, formatSiteCareDate),\n reason: record.correctionReason,\n before: previous ? { ...previous } : null,\n after: { ...record },\n subjectId: input.projectId,\n }),\n projectAudit(input.orgId, input.projectId, previous ? 'acceptance.corrected' : 'acceptance.recorded'),\n )\n return { project: next, record, previous }\n })\n const sentence = siteCareProjectAcceptanceSentence(record, project, formatSiteCareDate)\n const correction = previous ? `This corrects the earlier record: ${record.correctionReason}` : ''\n const heading = previous ? 'Corrected: the quote you accepted' : 'You accepted our quote'\n await emailOwner(\n firestore,\n {\n orgId: input.orgId,\n projectId: input.projectId,\n key: SITE_CARE_PROJECT_ACCEPTANCE_EMAIL_KEY,\n what: previous ? 'the corrected acceptance confirmation' : 'the acceptance confirmation',\n merge: {\n 'project.title': project.title,\n 'project.scope': scopeText(project),\n 'acceptance.heading': heading,\n 'acceptance.sentence': sentence,\n 'acceptance.correction': correction,\n },\n fallback: {\n subject: `${heading}: ${project.title}`,\n text: `${sentence} ${correction}\\n\\nWhat it covers:\\n${scopeText(project)}\\n\\nIf this is not what you agreed to, reply to this email before you pay.`,\n },\n },\n deps,\n )\n return record\n}\n\n// ── Invoices ────────────────────────────────────────────────────────────────\n\nfunction invoiceKey(projectId: string, seq: number): string {\n return `site-care-project:${projectId}:invoice:${seq}`\n}\n\n/** Writes a `creating` invoice and its intent row, under the rules of `siteCareProjectNextInvoice`. */\nasync function raiseInvoice(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string; actor: SiteCareActor },\n deps: SiteCareDeps,\n prepare?: (project: SiteCareProject, nowMs: number) => { project: SiteCareProject; row: AppendOnlyHistoryRow; audit: HistoryAudit } | null,\n): Promise<number> {\n const nowMs = nowOf(deps)\n return firestore.runTransaction(async (tx) => {\n const ref = projectRef(firestore, input.orgId, input.projectId)\n let project = loadedProject(await tx.get(ref))\n const history = projectHistory(firestore, input.orgId, input.projectId)\n const prepared = prepare ? prepare(project, nowMs) : null\n if (prepared) project = prepared.project\n const next = siteCareProjectNextInvoice(project)\n if (next.ok === false) throw new SiteCareError(next.error, 409)\n const seq = project.invoiceSeq + 1\n const invoice: SiteCareProjectInvoice = {\n seq,\n kind: next.kind,\n status: 'creating',\n amountCents: next.amountCents,\n description: siteCareProjectInvoiceDescription(project, next.kind),\n idempotencyKey: invoiceKey(input.projectId, seq),\n invoiceId: null,\n invoiceItemId: null,\n number: null,\n hostedInvoiceUrl: null,\n totalCents: 0,\n amountPaidCents: 0,\n creditNoteId: null,\n refundId: null,\n error: null,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n paidAtMs: null,\n }\n const updated: SiteCareProject = {\n ...project,\n invoices: [...project.invoices, invoice],\n invoiceSeq: seq,\n updatedAtMs: nowMs,\n }\n tx.set(ref, projectDoc(updated))\n if (prepared) appendHistoryRow(tx, firestore, history, prepared.row, prepared.audit)\n appendHistoryRow(\n tx,\n firestore,\n history,\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'invoice.requested',\n summary: `Raising the ${siteCareProjectInvoiceWords(invoice.kind)} invoice: ${formatSiteCareUsd(invoice.amountCents)} plus tax.`,\n after: { seq, kind: invoice.kind, amountCents: invoice.amountCents, idempotencyKey: invoice.idempotencyKey },\n subjectId: input.projectId,\n }),\n projectAudit(input.orgId, input.projectId, 'invoice.requested'),\n )\n return seq\n })\n}\n\n/** Emails the owner one invoice's pay link. */\nasync function emailInvoice(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string; project: SiteCareProject; invoice: SiteCareProjectInvoice; resent?: boolean },\n deps: SiteCareDeps,\n): Promise<SiteCareEmailResult> {\n const { project, invoice } = input\n const words = siteCareProjectInvoiceWords(invoice.kind)\n const heading = invoice.kind === 'full' ? 'Your invoice' : `Your ${words} invoice`\n const amount = formatSiteCareUsd(invoice.amountCents)\n const sentence =\n invoice.kind === 'deposit'\n ? `This is the deposit for “${project.title}”: ${amount}, half of the quote. We start work once it is paid, and invoice the other half when the project launches.`\n : invoice.kind === 'final'\n ? `“${project.title}” is live. This is the balance: ${amount}, the second half of the quote.`\n : `This is the ${amount} for “${project.title}”, in full. We start work once it is paid.`\n const due = formatSiteCareDay(invoice.createdAtMs + SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE * 86_400_000)\n const total = formatSiteCareUsd(invoice.totalCents || invoice.amountCents)\n return emailOwner(\n firestore,\n {\n orgId: input.orgId,\n projectId: input.projectId,\n key: SITE_CARE_PROJECT_INVOICE_EMAIL_KEY,\n what: `${input.resent ? 'the pay link again for ' : 'the pay link for '}the ${words} invoice`,\n merge: {\n 'project.title': project.title,\n 'project.scope': scopeText(project),\n 'invoice.heading': heading,\n 'invoice.sentence': `${sentence} Tax is included in the total.`,\n 'invoice.amount': total,\n 'invoice.number': invoice.number ?? '',\n 'invoice.due': due,\n 'invoice.payUrl': invoice.hostedInvoiceUrl ?? '',\n },\n fallback: {\n subject: `${heading}: ${project.title}`,\n text: `${sentence}\\n\\nAmount: ${total}\\nDue: ${due}\\nPay here: ${invoice.hostedInvoiceUrl ?? ''}`,\n },\n },\n deps,\n )\n}\n\n/**\n * Makes the Stripe invoice for a `creating` (or `failed`) record and writes\n * the outcome; on success, emails the owner the pay link.\n */\nasync function settleInvoice(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string; seq: number; actor: SiteCareActor },\n deps: SiteCareDeps,\n): Promise<SiteCareProjectInvoice> {\n const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get())\n const invoice = findInvoice(project, input.seq)\n if (invoice.status !== 'creating' && invoice.status !== 'failed') return invoice\n const billing = await readOrgBilling(input.orgId)\n const customerId = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '')\n const product = customerId\n ? await siteCareExtraTimeProduct(deps.stripe)\n : ({ ok: false, error: 'The workspace has no Stripe customer to invoice.' } as const)\n const created = product.ok\n ? await createProjectInvoice(\n {\n customerId,\n productId: product.productId,\n orgId: input.orgId,\n projectId: input.projectId,\n seq: invoice.seq,\n kind: invoice.kind,\n amountCents: invoice.amountCents,\n description: invoice.description,\n memo: siteCareProjectInvoiceMemo(project),\n idempotencyKey: invoice.idempotencyKey,\n invoiceId: invoice.invoiceId,\n sinceMs: project.createdAtMs,\n },\n deps.stripe,\n )\n : null\n const nowMs = nowOf(deps)\n let next: SiteCareProjectInvoice\n if (created && created.ok) {\n const state = created.state\n next = {\n ...invoice,\n status: state.status === 'paid' ? 'paid' : 'open',\n invoiceId: state.invoiceId,\n invoiceItemId: state.invoiceItemId ?? invoice.invoiceItemId,\n number: state.number,\n hostedInvoiceUrl: state.hostedInvoiceUrl,\n totalCents: state.totalCents,\n amountPaidCents: state.amountPaidCents,\n error: null,\n updatedAtMs: nowMs,\n paidAtMs: state.status === 'paid' ? nowMs : null,\n }\n } else {\n const error = product.ok === false ? product.error : created && created.ok === false ? created.error : 'Unknown failure'\n const madeId = created && created.ok === false && 'invoiceId' in created ? (created.invoiceId ?? null) : null\n next = { ...invoice, status: 'failed', invoiceId: madeId ?? invoice.invoiceId, error, updatedAtMs: nowMs }\n }\n const saved = await firestore.runTransaction(async (tx) => {\n const ref = projectRef(firestore, input.orgId, input.projectId)\n const current = loadedProject(await tx.get(ref))\n const sent = next.status === 'open' || next.status === 'paid'\n const updated: SiteCareProject = {\n ...withInvoice(current, next),\n firstInvoiceSentAtMs: current.firstInvoiceSentAtMs ?? (sent ? nowMs : null),\n updatedAtMs: nowMs,\n }\n tx.set(ref, projectDoc(updated))\n const words = siteCareProjectInvoiceWords(next.kind)\n appendHistoryRow(\n tx,\n firestore,\n projectHistory(firestore, input.orgId, input.projectId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: sent ? 'invoice.sent' : 'invoice.failed',\n summary: sent\n ? `Sent the ${words} invoice${next.number ? ` ${next.number}` : ''}: ${formatSiteCareUsd(next.totalCents || next.amountCents)} with tax.`\n : `The ${words} invoice could not be made: ${next.error}`,\n after: {\n seq: next.seq,\n status: next.status,\n invoiceId: next.invoiceId,\n number: next.number,\n totalCents: next.totalCents,\n error: next.error,\n },\n stripe: sent ? invoiceStripeRef(next) : null,\n subjectId: input.projectId,\n }),\n projectAudit(input.orgId, input.projectId, sent ? 'invoice.sent' : 'invoice.failed'),\n )\n return updated\n })\n if (next.status === 'open' || next.status === 'paid') {\n await emailInvoice(firestore, { orgId: input.orgId, projectId: input.projectId, project: saved, invoice: next }, deps)\n }\n return next\n}\n\n/**\n * Raises the project's next invoice — the whole price, or the deposit —\n * on the owner's current yes, and emails them the pay link.\n */\nexport async function sendSiteCareProjectInvoice(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareProjectInvoice> {\n const seq = await raiseInvoice(firestore, input, deps)\n return settleInvoice(firestore, { ...input, seq }, deps)\n}\n\n/** Re-runs an invoice that failed, or whose result never landed, under its own key. */\nexport async function retrySiteCareProjectInvoice(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string; seq: number; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareProjectInvoice> {\n const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get())\n const status = findInvoice(project, input.seq).status\n if (status !== 'failed' && status !== 'creating') {\n throw new SiteCareError('That invoice is not waiting to be retried.', 409)\n }\n return settleInvoice(firestore, input, deps)\n}\n\n/** Emails the owner an open invoice's pay link again. */\nexport async function resendSiteCareProjectInvoice(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string; seq: number; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareEmailResult> {\n const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get())\n const invoice = findInvoice(project, input.seq)\n if (invoice.status !== 'open' || !invoice.hostedInvoiceUrl) {\n throw new SiteCareError('Only an unpaid invoice’s pay link is sent again.', 409)\n }\n return emailInvoice(firestore, { orgId: input.orgId, projectId: input.projectId, project, invoice, resent: true }, deps)\n}\n\n/**\n * Marks the project launched. A half-and-half project raises its balance\n * invoice from the same record, in the same step, and emails the pay link.\n * Launch comes after the first invoice is paid: both splits are paid up\n * front before work starts.\n */\nexport async function launchSiteCareProject(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<{ project: SiteCareProject; invoice: SiteCareProjectInvoice | null }> {\n const markLaunched = (project: SiteCareProject, nowMs: number) => {\n if (project.launchedAtMs) throw new SiteCareError('This project is already marked launched.', 409)\n const first = latestSiteCareProjectInvoice(project, project.quote.split === 'full' ? 'full' : 'deposit')\n if (first?.status !== 'paid') {\n throw new SiteCareError(\n project.quote.split === 'full'\n ? 'Mark it launched once the invoice is paid.'\n : 'Mark it launched once the deposit is paid.',\n 409,\n )\n }\n return {\n project: { ...project, launchedAtMs: nowMs, launchedByUid: input.actor.uid, updatedAtMs: nowMs },\n row: historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'project.launched',\n summary:\n project.quote.split === 'half'\n ? `Marked “${project.title}” launched; the balance is invoiced now.`\n : `Marked “${project.title}” launched.`,\n after: { launchedAtMs: nowMs },\n subjectId: input.projectId,\n }),\n audit: projectAudit(input.orgId, input.projectId, 'launched'),\n }\n }\n const before = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get())\n if (before.quote.split === 'full') {\n const nowMs = nowOf(deps)\n const project = await firestore.runTransaction(async (tx) => {\n const ref = projectRef(firestore, input.orgId, input.projectId)\n const marked = markLaunched(loadedProject(await tx.get(ref)), nowMs)\n tx.set(ref, projectDoc(marked.project))\n appendHistoryRow(tx, firestore, projectHistory(firestore, input.orgId, input.projectId), marked.row, marked.audit)\n return marked.project\n })\n return { project, invoice: null }\n }\n const seq = await raiseInvoice(firestore, input, deps, markLaunched)\n const invoice = await settleInvoice(firestore, { ...input, seq }, deps)\n const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get())\n return { project, invoice }\n}\n\n// ── Payments ────────────────────────────────────────────────────────────────\n\nexport type SiteCareProjectPaymentOutcome = 'recorded' | 'already' | 'ignored'\n\n/**\n * Records a project invoice as paid — from the billing webhook's\n * `invoice.paid`, or from staff's \"Check payments\" when a delivery was\n * missed — and emails the owner the receipt. Idempotent: a redelivery of a\n * payment already recorded changes nothing and sends nothing.\n */\nexport async function recordSiteCareProjectPayment(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n invoiceId: string\n metadata: Readonly<Record<string, string>>\n amountPaidCents: number\n paidOutOfBand?: boolean\n },\n deps: SiteCareDeps = {},\n): Promise<SiteCareProjectPaymentOutcome> {\n const projectId = input.metadata[SITE_CARE_PROJECT_METADATA_KEY]\n if (!projectId || !input.invoiceId) return 'ignored'\n const nowMs = nowOf(deps)\n const result = await firestore.runTransaction(async (tx) => {\n const ref = projectRef(firestore, input.orgId, projectId)\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return null\n const project = loadedProject(snapshot)\n const invoice = project.invoices.find((row) => row.invoiceId === input.invoiceId)\n if (!invoice) return null\n if (invoice.status === 'paid') return { outcome: 'already' as const, project, invoice }\n // A voided or credited invoice reads as \"paid\" at nothing once fully\n // credited; that is not money arriving.\n const unpayable: SiteCareProjectInvoiceStatus[] = ['voided', 'credited', 'refunded']\n if (unpayable.includes(invoice.status)) return null\n const paid: SiteCareProjectInvoice = {\n ...invoice,\n status: 'paid',\n amountPaidCents: Math.max(0, Math.floor(input.amountPaidCents)),\n error: null,\n paidAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n const updated: SiteCareProject = {\n ...withInvoice(project, paid),\n firstInvoiceSentAtMs: project.firstInvoiceSentAtMs ?? nowMs,\n updatedAtMs: nowMs,\n }\n tx.set(ref, projectDoc(updated))\n appendHistoryRow(\n tx,\n firestore,\n projectHistory(firestore, input.orgId, projectId),\n historyRow({\n atMs: nowMs,\n by: { uid: null, email: null },\n kind: 'invoice.paid',\n summary: `Received ${formatSiteCareUsd(paid.amountPaidCents)} for the ${siteCareProjectInvoiceWords(paid.kind)}${input.paidOutOfBand ? ' (marked paid outside the card page)' : ''}.`,\n before: { status: invoice.status },\n after: { status: 'paid', amountPaidCents: paid.amountPaidCents },\n stripe: { object: 'invoice', id: input.invoiceId, amountCents: paid.amountPaidCents },\n subjectId: projectId,\n }),\n )\n return { outcome: 'recorded' as const, project: updated, invoice: paid }\n })\n if (!result) return 'ignored'\n if (result.outcome === 'already') return 'already'\n const { project, invoice } = result\n const amount = formatSiteCareUsd(invoice.amountPaidCents)\n const sentence = `Thank you. We received your payment of ${amount} for “${project.title}”.`\n const next =\n invoice.kind === 'deposit'\n ? 'We are starting work. The other half is invoiced when your project launches.'\n : invoice.kind === 'final'\n ? 'The project is paid in full. Thank you!'\n : 'The project is paid in full. We start work now and will let you know when it is live.'\n await emailOwner(\n firestore,\n {\n orgId: input.orgId,\n projectId,\n key: SITE_CARE_PROJECT_PAID_EMAIL_KEY,\n what: 'the payment receipt',\n merge: {\n 'project.title': project.title,\n 'payment.amount': amount,\n 'payment.sentence': sentence,\n 'payment.next': next,\n },\n fallback: { subject: `Payment received: ${project.title}`, text: `${sentence} ${next}` },\n },\n deps,\n )\n return 'recorded'\n}\n\n/**\n * Reads each unpaid invoice of a project from Stripe and records any that\n * were paid, for a webhook delivery that never arrived.\n */\nexport async function checkSiteCareProjectPayments(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; projectId: string },\n deps: SiteCareDeps = {},\n): Promise<{ recorded: number }> {\n const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get())\n let recorded = 0\n for (const invoice of project.invoices) {\n if (invoice.status !== 'open' || !invoice.invoiceId) continue\n const read = await readProjectInvoice(invoice.invoiceId, deps.stripe)\n if (read.ok === false) throw new SiteCareError(read.error, 502)\n if (read.state?.status !== 'paid') continue\n const outcome = await recordSiteCareProjectPayment(\n firestore,\n {\n orgId: input.orgId,\n invoiceId: invoice.invoiceId,\n metadata: { [SITE_CARE_PROJECT_METADATA_KEY]: input.projectId },\n amountPaidCents: read.state.amountPaidCents,\n },\n deps,\n )\n if (outcome === 'recorded') recorded += 1\n }\n return { recorded }\n}\n\n// ── Reversals ───────────────────────────────────────────────────────────────\n\nexport type SiteCareProjectReversal = 'void' | 'credit' | 'refund'\n\n/**\n * Voids an unpaid invoice, credits it, or refunds a paid one — from the\n * record, with a reason, never by hand in Stripe. The intent row commits\n * before the call; the owner is emailed the outcome.\n */\nexport async function reverseSiteCareProjectInvoice(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n projectId: string\n seq: number\n actor: SiteCareActor\n action: unknown\n reason: unknown\n },\n deps: SiteCareDeps = {},\n): Promise<SiteCareProjectInvoice> {\n const action = String(input.action ?? '') as SiteCareProjectReversal\n if (action !== 'void' && action !== 'credit' && action !== 'refund') {\n throw new SiteCareError('Choose void, credit or refund.', 400)\n }\n const reason = requireHistoryReason(input.reason)\n if (reason.ok === false) throw new SiteCareError(reason.error, 400)\n const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get())\n const invoice = findInvoice(project, input.seq)\n if (!invoice.invoiceId || (invoice.status !== 'open' && invoice.status !== 'paid')) {\n throw new SiteCareError('Only a sent invoice, unpaid or paid, can be voided, credited or refunded.', 409)\n }\n const read = await readProjectInvoice(invoice.invoiceId, deps.stripe)\n if (read.ok === false) throw new SiteCareError(read.error, 502)\n const stage = read.state?.status ?? 'missing'\n if (action === 'refund' && stage !== 'paid') {\n throw new SiteCareError(`The invoice is ${stage} in Stripe, not paid; void or credit it instead.`, 409)\n }\n if (action !== 'refund' && stage !== 'open') {\n throw new SiteCareError(\n stage === 'paid'\n ? 'The invoice is paid. Check payments to record it, then refund it.'\n : `The invoice is ${stage} in Stripe; there is nothing to ${action}.`,\n 409,\n )\n }\n if (action !== 'void' && !invoice.invoiceItemId) {\n throw new SiteCareError('The record has no line to credit on this invoice.', 409)\n }\n const words = siteCareProjectInvoiceWords(invoice.kind)\n const amount = formatSiteCareUsd(invoice.amountCents)\n const history = projectHistory(firestore, input.orgId, input.projectId)\n // The intent first, so a call whose answer is lost still left a row.\n await commitHistoryRow(\n firestore,\n history,\n historyRow({\n atMs: nowOf(deps),\n by: input.actor,\n kind: `invoice.${action}Requested`,\n summary: `Reversing the ${words} invoice (${amount}): ${action}.`,\n reason: reason.reason,\n before: { seq: invoice.seq, status: invoice.status, stage },\n subjectId: input.projectId,\n }),\n projectAudit(input.orgId, input.projectId, `invoice.${action}Requested`),\n )\n let next: SiteCareProjectInvoice\n let stripe: HistoryStripeRef\n if (action === 'void') {\n const voided = await voidProjectInvoice(\n { invoiceId: invoice.invoiceId, idempotencyKey: `${invoice.idempotencyKey}:void` },\n deps.stripe,\n )\n if (voided.ok === false) throw new SiteCareError(voided.error, 502)\n next = { ...invoice, status: 'voided', error: null, updatedAtMs: nowOf(deps) }\n stripe = { object: 'invoice', id: invoice.invoiceId, amountCents: invoice.totalCents || invoice.amountCents }\n } else {\n const credited = await creditExtraTimeItem(\n {\n invoiceId: invoice.invoiceId,\n invoiceItemId: String(invoice.invoiceItemId),\n refund: action === 'refund',\n memo: `Project: ${reason.reason}`,\n metadata: { [SITE_CARE_PROJECT_METADATA_KEY]: input.projectId, orgId: input.orgId },\n idempotencyKey: `${invoice.idempotencyKey}:${action}`,\n },\n deps.stripe,\n )\n if (credited.ok === false) throw new SiteCareError(credited.error, 502)\n next = {\n ...invoice,\n status: action === 'refund' ? 'refunded' : 'credited',\n creditNoteId: credited.creditNoteId,\n refundId: credited.refundId,\n error: null,\n updatedAtMs: nowOf(deps),\n }\n stripe = { object: 'credit_note', id: credited.creditNoteId, amountCents: credited.amountCents }\n }\n const doneKind = `invoice.${next.status}`\n await firestore.runTransaction(async (tx) => {\n const ref = projectRef(firestore, input.orgId, input.projectId)\n const current = loadedProject(await tx.get(ref))\n tx.set(ref, projectDoc({ ...withInvoice(current, next), updatedAtMs: nowOf(deps) }))\n appendHistoryRow(\n tx,\n firestore,\n history,\n historyRow({\n atMs: nowOf(deps),\n by: input.actor,\n kind: doneKind,\n summary:\n next.status === 'voided'\n ? `Voided the ${words} invoice (${amount}); nothing is owed on it.`\n : next.status === 'refunded'\n ? `Refunded the ${words} (${amount} plus its tax) to the card it was paid with.`\n : `Credited the ${words} invoice (${amount} plus its tax); nothing is owed on it.`,\n reason: reason.reason,\n before: { status: invoice.status },\n after: { status: next.status, creditNoteId: next.creditNoteId, refundId: next.refundId },\n stripe,\n subjectId: input.projectId,\n }),\n projectAudit(input.orgId, input.projectId, doneKind),\n )\n })\n const heading =\n next.status === 'voided' ? 'Invoice canceled' : next.status === 'refunded' ? 'Payment refunded' : 'Invoice credited'\n const sentence =\n next.status === 'voided'\n ? `We canceled the ${amount} ${words} invoice for “${project.title}”. You do not owe it.`\n : next.status === 'refunded'\n ? `We refunded the ${amount} ${words} for “${project.title}”, with its tax, to the card it was paid with.`\n : `We credited the ${amount} ${words} invoice for “${project.title}”, with its tax. You do not owe it.`\n await emailOwner(\n firestore,\n {\n orgId: input.orgId,\n projectId: input.projectId,\n key: SITE_CARE_PROJECT_REVERSED_EMAIL_KEY,\n what: 'the invoice notice',\n merge: {\n 'project.title': project.title,\n 'reversal.heading': heading,\n 'reversal.sentence': sentence,\n 'reversal.reason': reason.reason,\n },\n fallback: { subject: `${heading}: ${project.title}`, text: `${sentence}\\n\\nWhy: ${reason.reason}` },\n },\n deps,\n )\n return next\n}\n\n// ── Reading ─────────────────────────────────────────────────────────────────\n\nexport interface SiteCareProjectView {\n projectId: string\n project: SiteCareProject\n history: Array<AppendOnlyHistoryRow & { $id: string }>\n}\n\n/** A workspace's projects, newest first, each with its history. */\nexport async function readSiteCareProjects(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<SiteCareProjectView[]> {\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(SITE_CARE_PROJECTS_COLLECTION)\n .orderBy('createdAtMs', 'desc')\n .limit(100)\n .get()\n const views = await Promise.all(\n snapshot.docs.map(async (doc) => {\n const project = readSiteCareProject(doc.data())\n if (!project) return null\n const history = await readHistoryRows(doc.ref.collection(SITE_CARE_HISTORY_COLLECTION))\n return { projectId: doc.id, project, history }\n }),\n )\n return views\n .filter((view): view is SiteCareProjectView => Boolean(view))\n .sort((a, b) => b.project.createdAtMs - a.project.createdAtMs)\n}\n"],"names":["historyRow","requireHistoryReason","createResourceUid","OWNER_APPROVAL_CHANNEL_WORDS","readOwnerApprovalInput","formatSiteCareDate","formatSiteCareUsd","SITE_CARE_TIME_ZONE","latestSiteCareProjectInvoice","readSiteCareProject","readSiteCareProjectScope","readSiteCareProjectTitle","SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE","SITE_CARE_PROJECT_MAX_HOURS","siteCareProjectAcceptanceIsCurrent","siteCareProjectAcceptanceSentence","siteCareProjectInvoiceDescription","siteCareProjectInvoiceMemo","siteCareProjectInvoiceWords","siteCareProjectNextInvoice","siteCareProjectQuote","siteCareProjectQuoteIsEditable","siteCareProjectSplitSentence","siteCareProjectStatus","SITE_CARE_PROJECT_ACCEPTANCE_EMAIL_KEY","SITE_CARE_PROJECT_INVOICE_EMAIL_KEY","SITE_CARE_PROJECT_PAID_EMAIL_KEY","SITE_CARE_PROJECT_REVERSED_EMAIL_KEY","FieldValue","appendHistoryRow","commitHistoryRow","readHistoryRows","readOrgBilling","sendSiteCareEmail","createProjectInvoice","readProjectInvoice","SITE_CARE_PROJECT_METADATA_KEY","voidProjectInvoice","readSiteCareOrg","SITE_CARE_HISTORY_COLLECTION","SiteCareError","siteCareOwnerEmail","creditExtraTimeItem","siteCareExtraTimeProduct","SITE_CARE_PROJECTS_COLLECTION","projectRef","firestore","orgId","projectId","collection","doc","projectHistory","projectAudit","action","scope","target","nowOf","deps","now","Date","emailOf","email","projectDoc","project","status","updatedAt","serverTimestamp","loadedProject","snapshot","data","exists","findInvoice","seq","invoice","invoices","find","row","withInvoice","next","map","invoiceStripeRef","invoiceId","object","id","amountCents","totalCents","formatSiteCareDay","ms","toLocaleDateString","timeZone","month","day","year","recordProjectEmail","result","what","atMs","by","uid","kind","sent","summary","to","reason","after","subject","subjectId","catch","error","console","emailOwner","input","org","key","requestId","merge","fallback","scopeText","line","join","readQuoteInput","title","ok","quote","estimatedHours","priceUsd","createSiteCareProject","get","nowMs","ref","quoteVersion","acceptance","invoiceSeq","firstInvoiceSentAtMs","launchedAtMs","launchedByUid","createdAtMs","createdByUid","actor","createdByEmail","updatedAtMs","batch","create","createdAt","commit","editSiteCareProject","runTransaction","tx","changed","set","priceMoved","before","recordSiteCareProjectAcceptance","record","previous","read","hours","billedHours","rateUsd","maxHours","version","channel","approvedAtMs","correctionReason","sentence","correction","heading","text","invoiceKey","raiseInvoice","prepare","history","prepared","description","idempotencyKey","invoiceItemId","number","hostedInvoiceUrl","amountPaidCents","creditNoteId","refundId","paidAtMs","updated","audit","emailInvoice","words","amount","due","total","resent","settleInvoice","billing","customerId","String","stripeCustomerId","product","stripe","created","productId","memo","sinceMs","state","madeId","saved","current","sendSiteCareProjectInvoice","retrySiteCareProjectInvoice","resendSiteCareProjectInvoice","launchSiteCareProject","markLaunched","first","split","marked","recordSiteCareProjectPayment","metadata","outcome","unpayable","includes","paid","Math","max","floor","paidOutOfBand","checkSiteCareProjectPayments","recorded","reverseSiteCareProjectInvoice","stage","voided","credited","refund","doneKind","readSiteCareProjects","orderBy","limit","views","Promise","all","docs","filter","view","Boolean","sort","a","b"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,G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EpL,OAAO,CAACyE,WAAW,GAAG0G,EAAEnL,OAAO,CAACyE,WAAW;AACjE"}
|
|
@@ -0,0 +1,81 @@
|
|
|
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 SiteCareRequest } from '@aglyn/aglyn/app-utils/site-care';
|
|
18
|
+
import { type SiteCareProjectFindingCode } from './site-care-project-reconcile';
|
|
19
|
+
import { type SiteCareStripeOptions, type StripeExtraTimeItem } from './site-care-stripe';
|
|
20
|
+
/**
|
|
21
|
+
* THE SITE CARE RECONCILIATION (AGL-3959).
|
|
22
|
+
*
|
|
23
|
+
* Once a day, for the current month and the one before: each request's
|
|
24
|
+
* billed hours against the Stripe invoice item that carries them — amount,
|
|
25
|
+
* quantity and description — and each month's billed total against the sum
|
|
26
|
+
* of its Stripe items. Any difference is a finding, and a workspace-month
|
|
27
|
+
* with findings raises `billing.siteCareReconciliation` (Should know)
|
|
28
|
+
* rather than passing silently. The same shape as the pricing-drift check:
|
|
29
|
+
* it compares and reports, and never changes anything on either side — the
|
|
30
|
+
* fix is a person's, from the request.
|
|
31
|
+
*
|
|
32
|
+
* What it catches, by construction of how charges are written:
|
|
33
|
+
* - a Stripe item with no row behind it (the call succeeded, the record did
|
|
34
|
+
* not land): a `creating` charge, or an item no request claims;
|
|
35
|
+
* - a row with no Stripe object: a `pending` charge whose item is gone, or a
|
|
36
|
+
* `failed` one still owing hours;
|
|
37
|
+
* - an item somebody edited in the Stripe dashboard: amount, quantity or
|
|
38
|
+
* description that no longer match the request.
|
|
39
|
+
*/
|
|
40
|
+
export type SiteCareFindingCode = 'charge-stuck' | 'charge-failed' | 'item-missing' | 'item-mismatch' | 'item-not-voided' | 'item-without-row' | 'hours-mismatch' | 'month-total' | 'no-customer' | SiteCareProjectFindingCode;
|
|
41
|
+
export interface SiteCareFinding {
|
|
42
|
+
orgId: string;
|
|
43
|
+
month: string;
|
|
44
|
+
requestId: string | null;
|
|
45
|
+
code: SiteCareFindingCode;
|
|
46
|
+
detail: string;
|
|
47
|
+
}
|
|
48
|
+
export interface SiteCareReconcileReport {
|
|
49
|
+
months: string[];
|
|
50
|
+
orgs: number;
|
|
51
|
+
requests: number;
|
|
52
|
+
/** Projects compared (AGL-3970). */
|
|
53
|
+
projects: number;
|
|
54
|
+
findings: SiteCareFinding[];
|
|
55
|
+
alerted: number;
|
|
56
|
+
errors: string[];
|
|
57
|
+
}
|
|
58
|
+
interface RequestRow {
|
|
59
|
+
id: string;
|
|
60
|
+
orgId: string;
|
|
61
|
+
subject: string;
|
|
62
|
+
request: SiteCareRequest;
|
|
63
|
+
}
|
|
64
|
+
/** Compares one workspace's requests with its Stripe items. Pure. */
|
|
65
|
+
export declare function compareSiteCareCharges(input: {
|
|
66
|
+
orgId: string;
|
|
67
|
+
requests: readonly RequestRow[];
|
|
68
|
+
items: readonly StripeExtraTimeItem[];
|
|
69
|
+
/** Items read one by one because the listing did not reach them. */
|
|
70
|
+
readItems?: ReadonlyMap<string, {
|
|
71
|
+
deleted: boolean;
|
|
72
|
+
item: StripeExtraTimeItem | null;
|
|
73
|
+
}>;
|
|
74
|
+
}): SiteCareFinding[];
|
|
75
|
+
/** Runs the check over the current and previous month. */
|
|
76
|
+
export declare function reconcileSiteCare(firestore: FirebaseFirestore.Firestore, input: {
|
|
77
|
+
nowMs?: number;
|
|
78
|
+
dryRun: boolean;
|
|
79
|
+
stripe?: SiteCareStripeOptions;
|
|
80
|
+
}): Promise<SiteCareReconcileReport>;
|
|
81
|
+
export {};
|
|
@@ -0,0 +1,349 @@
|
|
|
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 { previousSiteCareMonthKey, siteCareExtraTimeCents, siteCareMonthKey, siteCareMonthStatement, siteCareStatementRequest } from "@aglyn/aglyn/app-utils/site-care";
|
|
18
|
+
import { readOrgBilling } from "./org-billing.js";
|
|
19
|
+
import { raiseOperatorAlert } from "./operator-alerts.js";
|
|
20
|
+
import { readSiteCareRequest } from "./site-care-requests.js";
|
|
21
|
+
import { reconcileSiteCareProjects } from "./site-care-project-reconcile.js";
|
|
22
|
+
import { listSiteCareExtraTimeItems, readExtraTimeItem } from "./site-care-stripe.js";
|
|
23
|
+
/** Compares one workspace's requests with its Stripe items. Pure. */ export function compareSiteCareCharges(input) {
|
|
24
|
+
const findings = [];
|
|
25
|
+
const byId = new Map(input.items.map((item)=>[
|
|
26
|
+
item.id,
|
|
27
|
+
item
|
|
28
|
+
]));
|
|
29
|
+
const claimed = new Set();
|
|
30
|
+
const months = new Set();
|
|
31
|
+
for (const row of input.requests){
|
|
32
|
+
var _ref, _byId_get, _input_items_find;
|
|
33
|
+
var _input_readItems_get, _input_readItems, _input_readItems_get1, _input_readItems1;
|
|
34
|
+
const { request } = row;
|
|
35
|
+
months.add(request.month);
|
|
36
|
+
const charge = request.charge;
|
|
37
|
+
const at = {
|
|
38
|
+
orgId: input.orgId,
|
|
39
|
+
month: request.month,
|
|
40
|
+
requestId: row.id
|
|
41
|
+
};
|
|
42
|
+
if (!charge) {
|
|
43
|
+
if (request.billedHours > 0) {
|
|
44
|
+
findings.push(_extends({}, at, {
|
|
45
|
+
code: 'hours-mismatch',
|
|
46
|
+
detail: `“${row.subject}” bills ${request.billedHours} h with no charge recorded.`
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (charge.invoiceItemId) claimed.add(charge.invoiceItemId);
|
|
52
|
+
const fromStripe = charge.invoiceItemId ? (_ref = (_byId_get = byId.get(charge.invoiceItemId)) != null ? _byId_get : (_input_readItems = input.readItems) == null ? void 0 : (_input_readItems_get = _input_readItems.get(charge.invoiceItemId)) == null ? void 0 : _input_readItems_get.item) != null ? _ref : null : (_input_items_find = input.items.find((item)=>item.requestId === row.id)) != null ? _input_items_find : null;
|
|
53
|
+
const deleted = charge.invoiceItemId ? ((_input_readItems1 = input.readItems) == null ? void 0 : (_input_readItems_get1 = _input_readItems1.get(charge.invoiceItemId)) == null ? void 0 : _input_readItems_get1.deleted) === true : false;
|
|
54
|
+
if (fromStripe) claimed.add(fromStripe.id);
|
|
55
|
+
switch(charge.status){
|
|
56
|
+
case 'creating':
|
|
57
|
+
findings.push(_extends({}, at, {
|
|
58
|
+
code: 'charge-stuck',
|
|
59
|
+
detail: fromStripe ? `“${row.subject}”: Stripe item ${fromStripe.id} exists but the request never recorded it. Retry the charge to record it.` : `“${row.subject}”: a charge was started and never finished. Retry it.`
|
|
60
|
+
}));
|
|
61
|
+
break;
|
|
62
|
+
case 'failed':
|
|
63
|
+
var _charge_error;
|
|
64
|
+
findings.push(_extends({}, at, {
|
|
65
|
+
code: 'charge-failed',
|
|
66
|
+
detail: `“${row.subject}”: ${charge.hours} h owed with no Stripe item (${(_charge_error = charge.error) != null ? _charge_error : 'failed'}).`
|
|
67
|
+
}));
|
|
68
|
+
break;
|
|
69
|
+
case 'pending':
|
|
70
|
+
{
|
|
71
|
+
if (!fromStripe || deleted) {
|
|
72
|
+
findings.push(_extends({}, at, {
|
|
73
|
+
code: 'item-missing',
|
|
74
|
+
detail: `“${row.subject}”: Stripe item ${charge.invoiceItemId} is gone.`
|
|
75
|
+
}));
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
const expected = siteCareExtraTimeCents(charge.hours);
|
|
79
|
+
const problems = [];
|
|
80
|
+
if (fromStripe.amountCents !== expected) problems.push(`amount ${fromStripe.amountCents} ≠ ${expected}`);
|
|
81
|
+
if (fromStripe.quantity !== charge.hours) problems.push(`quantity ${fromStripe.quantity} ≠ ${charge.hours}`);
|
|
82
|
+
if (fromStripe.description !== charge.description) problems.push('description differs');
|
|
83
|
+
if (problems.length) {
|
|
84
|
+
findings.push(_extends({}, at, {
|
|
85
|
+
code: 'item-mismatch',
|
|
86
|
+
detail: `“${row.subject}” (${fromStripe.id}): ${problems.join(', ')}.`
|
|
87
|
+
}));
|
|
88
|
+
}
|
|
89
|
+
if (request.billedHours !== charge.hours && !request.absorbed) {
|
|
90
|
+
findings.push(_extends({}, at, {
|
|
91
|
+
code: 'hours-mismatch',
|
|
92
|
+
detail: `“${row.subject}”: billed ${request.billedHours} h but the charge is ${charge.hours} h.`
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
case 'voided':
|
|
98
|
+
if (fromStripe && !deleted) {
|
|
99
|
+
findings.push(_extends({}, at, {
|
|
100
|
+
code: 'item-not-voided',
|
|
101
|
+
detail: `“${row.subject}”: voided here, but Stripe item ${fromStripe.id} is still there.`
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
break;
|
|
105
|
+
default:
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
for (const item of input.items){
|
|
110
|
+
var _;
|
|
111
|
+
if (claimed.has(item.id)) continue;
|
|
112
|
+
findings.push({
|
|
113
|
+
orgId: input.orgId,
|
|
114
|
+
month: (_ = [
|
|
115
|
+
...months
|
|
116
|
+
][0]) != null ? _ : '',
|
|
117
|
+
requestId: item.requestId || null,
|
|
118
|
+
code: 'item-without-row',
|
|
119
|
+
detail: `Stripe item ${item.id} (${item.amountCents} cents) names request ${item.requestId}, which does not record it.`
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
// The month's total against Stripe's.
|
|
123
|
+
for (const month of months){
|
|
124
|
+
const inMonth = input.requests.filter((row)=>row.request.month === month);
|
|
125
|
+
const statement = siteCareMonthStatement({
|
|
126
|
+
month,
|
|
127
|
+
goodwillMinutes: 0,
|
|
128
|
+
requests: inMonth.map((row)=>siteCareStatementRequest(row.id, row.subject, row.request))
|
|
129
|
+
});
|
|
130
|
+
const stripeTotal = inMonth.filter((row)=>{
|
|
131
|
+
var _row_request_charge;
|
|
132
|
+
return ((_row_request_charge = row.request.charge) == null ? void 0 : _row_request_charge.status) === 'pending' && row.request.charge.invoiceItemId;
|
|
133
|
+
}).reduce((sum, row)=>{
|
|
134
|
+
var _ref, _byId_get;
|
|
135
|
+
var _row_request_charge, _input_readItems_get, _input_readItems;
|
|
136
|
+
const id = String((_row_request_charge = row.request.charge) == null ? void 0 : _row_request_charge.invoiceItemId);
|
|
137
|
+
const item = (_ref = (_byId_get = byId.get(id)) != null ? _byId_get : (_input_readItems = input.readItems) == null ? void 0 : (_input_readItems_get = _input_readItems.get(id)) == null ? void 0 : _input_readItems_get.item) != null ? _ref : null;
|
|
138
|
+
return sum + (item ? item.amountCents : 0);
|
|
139
|
+
}, 0);
|
|
140
|
+
const pendingRecorded = inMonth.filter((row)=>{
|
|
141
|
+
var _row_request_charge;
|
|
142
|
+
return ((_row_request_charge = row.request.charge) == null ? void 0 : _row_request_charge.status) === 'pending';
|
|
143
|
+
}).reduce((sum, row)=>{
|
|
144
|
+
var _ref;
|
|
145
|
+
var _row_request_charge;
|
|
146
|
+
return sum + ((_ref = (_row_request_charge = row.request.charge) == null ? void 0 : _row_request_charge.amountCents) != null ? _ref : 0);
|
|
147
|
+
}, 0);
|
|
148
|
+
if (stripeTotal !== pendingRecorded) {
|
|
149
|
+
findings.push({
|
|
150
|
+
orgId: input.orgId,
|
|
151
|
+
month,
|
|
152
|
+
requestId: null,
|
|
153
|
+
code: 'month-total',
|
|
154
|
+
detail: `The ${month} statement bills ${statement.extraBilledCents} cents (${pendingRecorded} on pending items) and Stripe holds ${stripeTotal}.`
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return findings;
|
|
159
|
+
}
|
|
160
|
+
/** Runs the check over the current and previous month. */ export async function reconcileSiteCare(firestore, input) {
|
|
161
|
+
var _input_nowMs;
|
|
162
|
+
const nowMs = (_input_nowMs = input.nowMs) != null ? _input_nowMs : Date.now();
|
|
163
|
+
const current = siteCareMonthKey(nowMs);
|
|
164
|
+
const months = [
|
|
165
|
+
current,
|
|
166
|
+
previousSiteCareMonthKey(current)
|
|
167
|
+
];
|
|
168
|
+
const snapshot = await firestore.collection('supportTickets').where('siteCareMonth', 'in', months).limit(2000).get();
|
|
169
|
+
const byOrg = new Map();
|
|
170
|
+
for (const doc of snapshot.docs){
|
|
171
|
+
var _doc_get, _byOrg_get, _doc_get1;
|
|
172
|
+
const request = readSiteCareRequest(doc.get('siteCare'));
|
|
173
|
+
const orgId = String((_doc_get = doc.get('orgId')) != null ? _doc_get : '');
|
|
174
|
+
if (!request || !orgId || request.state !== 'closed') continue;
|
|
175
|
+
const rows = (_byOrg_get = byOrg.get(orgId)) != null ? _byOrg_get : [];
|
|
176
|
+
rows.push({
|
|
177
|
+
id: doc.id,
|
|
178
|
+
orgId,
|
|
179
|
+
subject: String((_doc_get1 = doc.get('subject')) != null ? _doc_get1 : ''),
|
|
180
|
+
request
|
|
181
|
+
});
|
|
182
|
+
byOrg.set(orgId, rows);
|
|
183
|
+
}
|
|
184
|
+
const report = {
|
|
185
|
+
months,
|
|
186
|
+
orgs: byOrg.size,
|
|
187
|
+
requests: [
|
|
188
|
+
...byOrg.values()
|
|
189
|
+
].reduce((sum, rows)=>sum + rows.length, 0),
|
|
190
|
+
projects: 0,
|
|
191
|
+
findings: [],
|
|
192
|
+
alerted: 0,
|
|
193
|
+
errors: []
|
|
194
|
+
};
|
|
195
|
+
// Seventy days reaches back past the start of the previous month.
|
|
196
|
+
const sinceMs = nowMs - 70 * 24 * 60 * 60 * 1000;
|
|
197
|
+
for (const [orgId, rows] of byOrg){
|
|
198
|
+
try {
|
|
199
|
+
var _billing_stripeCustomerId, _orgSnap_get;
|
|
200
|
+
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({
|
|
206
|
+
orgId,
|
|
207
|
+
month: current,
|
|
208
|
+
requestId: null,
|
|
209
|
+
code: 'no-customer',
|
|
210
|
+
detail: 'Charges are recorded but the workspace has no Stripe customer.'
|
|
211
|
+
});
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const listed = await listSiteCareExtraTimeItems({
|
|
215
|
+
customerId,
|
|
216
|
+
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)
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
}
|
|
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
|
+
report.findings.push(...findings);
|
|
258
|
+
if (input.dryRun || !findings.length) continue;
|
|
259
|
+
const byMonth = new Map();
|
|
260
|
+
for (const finding of findings){
|
|
261
|
+
var _byMonth_get;
|
|
262
|
+
const list = (_byMonth_get = byMonth.get(finding.month)) != null ? _byMonth_get : [];
|
|
263
|
+
list.push(finding);
|
|
264
|
+
byMonth.set(finding.month, list);
|
|
265
|
+
}
|
|
266
|
+
const orgSnap = await firestore.collection('orgs').doc(orgId).get();
|
|
267
|
+
const orgName = String((_orgSnap_get = orgSnap.get('name')) != null ? _orgSnap_get : orgId);
|
|
268
|
+
for (const [month, list] of byMonth){
|
|
269
|
+
const result = await raiseOperatorAlert('billing.siteCareReconciliation', {
|
|
270
|
+
dedupeKey: `${orgId}:${month}`,
|
|
271
|
+
context: {
|
|
272
|
+
orgId,
|
|
273
|
+
orgName,
|
|
274
|
+
month,
|
|
275
|
+
count: list.length,
|
|
276
|
+
findings: list.map((finding)=>finding.detail).join(' ')
|
|
277
|
+
},
|
|
278
|
+
orgId
|
|
279
|
+
});
|
|
280
|
+
if (result.outcome !== 'deduped' && result.outcome !== 'below-threshold') report.alerted += 1;
|
|
281
|
+
}
|
|
282
|
+
} catch (error) {
|
|
283
|
+
report.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
await reconcileProjectsInto(firestore, report, {
|
|
287
|
+
nowMs,
|
|
288
|
+
dryRun: input.dryRun,
|
|
289
|
+
stripe: input.stripe
|
|
290
|
+
});
|
|
291
|
+
return report;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* The flat-quoted projects (AGL-3970), in the same run and on the same
|
|
295
|
+
* alert: one per workspace with findings, deduplicated a day like the
|
|
296
|
+
* month's, its `month` naming the projects rather than a month.
|
|
297
|
+
*/ async function reconcileProjectsInto(firestore, report, input) {
|
|
298
|
+
const current = siteCareMonthKey(input.nowMs);
|
|
299
|
+
let projects;
|
|
300
|
+
try {
|
|
301
|
+
projects = await reconcileSiteCareProjects(firestore, {
|
|
302
|
+
nowMs: input.nowMs,
|
|
303
|
+
stripe: input.stripe
|
|
304
|
+
});
|
|
305
|
+
} catch (error) {
|
|
306
|
+
report.errors.push(`projects: ${error instanceof Error ? error.message : String(error)}`);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
report.projects = projects.projects;
|
|
310
|
+
report.errors.push(...projects.errors);
|
|
311
|
+
const byOrg = new Map();
|
|
312
|
+
for (const finding of projects.findings){
|
|
313
|
+
var _byOrg_get;
|
|
314
|
+
const row = {
|
|
315
|
+
orgId: finding.orgId,
|
|
316
|
+
month: current,
|
|
317
|
+
requestId: finding.projectId,
|
|
318
|
+
code: finding.code,
|
|
319
|
+
detail: finding.detail
|
|
320
|
+
};
|
|
321
|
+
report.findings.push(row);
|
|
322
|
+
const list = (_byOrg_get = byOrg.get(finding.orgId)) != null ? _byOrg_get : [];
|
|
323
|
+
list.push(row);
|
|
324
|
+
byOrg.set(finding.orgId, list);
|
|
325
|
+
}
|
|
326
|
+
if (input.dryRun) return;
|
|
327
|
+
for (const [orgId, list] of byOrg){
|
|
328
|
+
try {
|
|
329
|
+
var _orgSnap_get;
|
|
330
|
+
const orgSnap = await firestore.collection('orgs').doc(orgId).get();
|
|
331
|
+
const result = await raiseOperatorAlert('billing.siteCareReconciliation', {
|
|
332
|
+
dedupeKey: `${orgId}:projects`,
|
|
333
|
+
context: {
|
|
334
|
+
orgId,
|
|
335
|
+
orgName: String((_orgSnap_get = orgSnap.get('name')) != null ? _orgSnap_get : orgId),
|
|
336
|
+
month: 'projects',
|
|
337
|
+
count: list.length,
|
|
338
|
+
findings: list.map((finding)=>finding.detail).join(' ')
|
|
339
|
+
},
|
|
340
|
+
orgId
|
|
341
|
+
});
|
|
342
|
+
if (result.outcome !== 'deduped' && result.outcome !== 'below-threshold') report.alerted += 1;
|
|
343
|
+
} catch (error) {
|
|
344
|
+
report.errors.push(`${orgId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
//# sourceMappingURL=site-care-reconcile.js.map
|