@aglyn/tenant-data-admin 1.0.0-beta.277 → 1.0.0-beta.283

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
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-requests.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 describeHours,\n ownerApprovalSentence,\n readOwnerApprovalInput,\n readOwnerApprovalRecord,\n type OwnerApprovalRecord,\n} from '@aglyn/aglyn/app-utils/owner-approval-record'\nimport {\n hasSiteCare,\n resolveEffectivePlan,\n SITE_CARE_EXTRA_HOUR_USD,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n allocateSiteCareMinutes,\n closeMinutesFromTimer,\n formatSiteCareDate,\n formatSiteCareMinutes,\n formatSiteCareUsd,\n isSiteCareMonthKey,\n isSiteCarePublishAction,\n readSiteCareMinutes,\n SITE_CARE_BODY_MAX,\n SITE_CARE_LIVE_CHARGE_STATUSES,\n SITE_CARE_RESPONSE_BUSINESS_DAYS,\n SITE_CARE_SUBJECT_MAX,\n SITE_CARE_TICKET_KIND,\n siteCareChargeWords,\n siteCareCloseVerdict,\n siteCareExtraTimeCents,\n siteCareExtraTimeDescription,\n siteCareIncludedPool,\n siteCareMonthKey,\n siteCareMonthSentence,\n siteCareMonthStatement,\n siteCareOrgMonth,\n siteCarePublishSentence,\n siteCareStatementRequest,\n type SiteCareCharge,\n type SiteCareCloseVerdict,\n type SiteCareMonthStatement,\n type SiteCarePublishLink,\n type SiteCareRequest,\n type SiteCareSource,\n} from '@aglyn/aglyn/app-utils/site-care'\nimport { addBusinessDays } from '@aglyn/aglyn/app-utils/support-tiers'\nimport {\n SITE_CARE_APPROVAL_EMAIL_KEY,\n SITE_CARE_CHARGE_REVERSED_EMAIL_KEY,\n SITE_CARE_QUOTE_EMAIL_KEY,\n SITE_CARE_REQUEST_CORRECTED_EMAIL_KEY,\n SITE_CARE_REQUEST_DONE_EMAIL_KEY,\n SITE_CARE_REQUEST_RECEIVED_EMAIL_KEY,\n SITE_CARE_STATEMENT_EMAIL_KEY,\n} from '@aglyn/shared-util-email'\nimport { createHash } from 'node:crypto'\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n appendHistoryRow,\n commitHistoryRow,\n readHistoryRows,\n type HistoryAudit,\n} from './append-only-history-write'\nimport { notifyStaff } from './notifications'\nimport { readOrgBilling } from './org-billing'\nimport { sendSiteCareEmail, type SiteCareEmailResult } from './site-care-emails'\nimport {\n createExtraTimeItem,\n creditExtraTimeItem,\n deleteExtraTimeItem,\n extraTimeItemIsEditable,\n readExtraTimeItem,\n siteCareExtraTimeProduct,\n siteCareSubscriptionId,\n subscriptionInvoiceFinalizedSince,\n updateExtraTimeItem,\n type SiteCareStripeOptions,\n} from './site-care-stripe'\n\n/**\n * SITE CARE REQUESTS, WITH FIRESTORE AND STRIPE (AGL-3959).\n *\n * A request is a support ticket (`supportTickets/{id}`, `kind: 'siteCare'`)\n * with a `siteCare` map holding everything about the work: the timer, the\n * one number staff close it with, how its minutes counted against the\n * included hour, the owner's recorded approval, the extra-time charge and\n * the publish that shipped it. Beside it, an append-only history\n * (`supportTickets/{id}/siteCareHistory`), and per workspace and month a\n * document for goodwill minutes with its own history\n * (`orgs/{orgId}/siteCareMonths/{YYYY-MM}`). None of it is in the Firestore\n * rules: every read and write passes the console's routes, as the rest of\n * the support system does.\n *\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 call: a `charge.requested`\n * row and a `creating` charge commit first, then the call, then the result\n * and its row commit together. A Stripe success with no row behind it is a\n * `creating` charge with no item — which the reconciliation reports, and\n * which `retrySiteCareCharge` settles under the same idempotency key.\n *\n * The arithmetic is `@aglyn/aglyn/app-utils/site-care`, the approval record\n * `owner-approval-record`, the row `append-only-history`.\n */\n\nconst TICKETS = 'supportTickets'\nexport const SITE_CARE_HISTORY_COLLECTION = 'siteCareHistory'\nexport const SITE_CARE_MONTHS_COLLECTION = 'siteCareMonths'\n\n/** Who did something. `uid` null is the platform itself. */\nexport interface SiteCareActor {\n uid: string | null\n email: string | null\n}\n\n/** A refusal the caller turns into a response. */\nexport class SiteCareError extends Error {\n readonly status: number\n readonly detail: Record<string, unknown> | null\n constructor(message: string, status = 400, detail: Record<string, unknown> | null = null) {\n super(message)\n this.name = 'SiteCareError'\n this.status = status\n this.detail = detail\n }\n}\n\n/** The seams a spec replaces. */\nexport interface SiteCareDeps {\n now?: () => number\n stripe?: SiteCareStripeOptions\n email?: typeof sendSiteCareEmail\n}\n\nconst nowOf = (deps: SiteCareDeps) => (deps.now ?? Date.now)()\nconst emailOf = (deps: SiteCareDeps) => deps.email ?? sendSiteCareEmail\n\nfunction ticketRef(firestore: FirebaseFirestore.Firestore, ticketId: string) {\n return firestore.collection(TICKETS).doc(ticketId)\n}\n\nfunction ticketHistory(firestore: FirebaseFirestore.Firestore, ticketId: string) {\n return ticketRef(firestore, ticketId).collection(SITE_CARE_HISTORY_COLLECTION)\n}\n\nfunction monthRef(firestore: FirebaseFirestore.Firestore, orgId: string, month: string) {\n return firestore.collection('orgs').doc(orgId).collection(SITE_CARE_MONTHS_COLLECTION).doc(month)\n}\n\nfunction monthHistory(firestore: FirebaseFirestore.Firestore, orgId: string, month: string) {\n return monthRef(firestore, orgId, month).collection(SITE_CARE_HISTORY_COLLECTION)\n}\n\nfunction requestAudit(orgId: string, ticketId: string, action: string): HistoryAudit {\n return { action: `siteCare.${action}`, scope: 'siteCare', target: `orgs/${orgId}/siteCare/${ticketId}` }\n}\n\nfunction monthAudit(orgId: string, month: string, action: string): HistoryAudit {\n return { action: `siteCare.${action}`, scope: 'siteCare', target: `orgs/${orgId}/siteCareMonths/${month}` }\n}\n\n/** A fresh request's map. */\nexport function newSiteCareRequest(input: {\n source: SiteCareSource\n hostId: string | null\n requesterEmail: string | null\n month: string\n}): SiteCareRequest {\n return {\n source: input.source,\n hostId: input.hostId,\n requesterEmail: input.requesterEmail,\n state: 'open',\n month: input.month,\n timerStartedAtMs: null,\n timerStartedByUid: null,\n closedAtMs: null,\n minutesLogged: null,\n timerMinutes: null,\n countedMinutes: 0,\n includedMinutesUsed: 0,\n overMinutes: 0,\n billedHours: 0,\n absorbed: false,\n approval: null,\n charge: null,\n chargeSeq: 0,\n publish: null,\n }\n}\n\n/** A stored map read back with every field present. */\nexport function readSiteCareRequest(value: unknown): SiteCareRequest | null {\n if (!value || typeof value !== 'object') return null\n const stored = value as Partial<SiteCareRequest>\n const base = newSiteCareRequest({\n source: stored.source === 'email' ? 'email' : 'console',\n hostId: stored.hostId ?? null,\n requesterEmail: stored.requesterEmail ?? null,\n month: isSiteCareMonthKey(stored.month) ? stored.month : siteCareMonthKey(Date.now()),\n })\n return {\n ...base,\n ...stored,\n approval: readOwnerApprovalRecord(stored.approval),\n charge: stored.charge ?? null,\n chargeSeq: Number(stored.chargeSeq) || 0,\n publish: stored.publish ?? null,\n } as SiteCareRequest\n}\n\ninterface LoadedTicket {\n ref: FirebaseFirestore.DocumentReference\n orgId: string\n subject: string\n request: SiteCareRequest\n data: Record<string, unknown>\n}\n\nfunction loadedTicket(snapshot: FirebaseFirestore.DocumentSnapshot): LoadedTicket {\n const data = (snapshot.data() ?? null) as Record<string, unknown> | null\n if (!data) throw new SiteCareError('Unknown request', 404)\n if (data['kind'] !== SITE_CARE_TICKET_KIND) throw new SiteCareError('That ticket is not a Site Care request', 400)\n const request = readSiteCareRequest(data['siteCare'])\n if (!request) throw new SiteCareError('That ticket has no Site Care record', 409)\n return {\n ref: snapshot.ref,\n orgId: String(data['orgId'] ?? ''),\n subject: String(data['subject'] ?? ''),\n request,\n data,\n }\n}\n\n/** The org document joined with its billing keys, as `hasSiteCare` reads it. */\nexport async function readSiteCareOrg(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<Record<string, unknown> | null> {\n const snapshot = await firestore.collection('orgs').doc(orgId).get()\n if (!snapshot.exists) return null\n const billing = await readOrgBilling(orgId)\n return { $id: orgId, ...(snapshot.data() ?? {}), ...(billing ?? {}) }\n}\n\n/** Whether a workspace has Site Care in force. */\nexport function orgHasSiteCare(org: Record<string, unknown> | null): boolean {\n return Boolean(org) && hasSiteCare(org as never)\n}\n\n/** The owner's address, from the owner's member row. */\nexport async function siteCareOwnerEmail(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n org: Record<string, unknown> | null,\n): Promise<string | null> {\n const ownerUid = typeof org?.['ownerUid'] === 'string' ? (org['ownerUid'] as string) : ''\n if (!ownerUid) return null\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(ownerUid).get()\n const email = member.get('email')\n return typeof email === 'string' && email ? email : null\n}\n\n/** Records an email as the request's (or the month's) history row. */\nasync function recordEmail(\n firestore: FirebaseFirestore.Firestore,\n history: FirebaseFirestore.CollectionReference,\n result: SiteCareEmailResult,\n what: string,\n atMs: number,\n subjectId: string | null,\n): Promise<void> {\n await commitHistoryRow(\n firestore,\n history,\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,\n }),\n ).catch((error) => console.error('[site-care] email history row failed', error))\n}\n\n// ── Intake ──────────────────────────────────────────────────────────────────\n\nexport interface OpenSiteCareRequestInput {\n orgId: string\n org: Record<string, unknown>\n hostId: string | null\n subject: string\n body: string\n requester: SiteCareActor\n source: SiteCareSource\n /**\n * A received message's id, when the request came by email: the ticket is\n * keyed by it, so a provider redelivering the same message opens nothing\n * twice.\n */\n dedupeKey?: string | null\n}\n\n/** A document id derived from a received message, alphanumeric so it fits a reply address. */\nexport function siteCareMessageDocId(prefix: string, key: string): string {\n return `${prefix}${createHash('sha256').update(key).digest('hex').slice(0, 24)}`\n}\n\n/**\n * Opens a request: the tagged ticket, its first message, the opening history\n * row, the staff notice and the \"we have your request\" email. Shared by the\n * console's \"Request a change\" and the inbound address.\n */\nexport async function openSiteCareRequest(\n firestore: FirebaseFirestore.Firestore,\n input: OpenSiteCareRequestInput,\n deps: SiteCareDeps = {},\n): Promise<{ ticketId: string; dueAtMs: number; duplicate?: boolean }> {\n const subject = String(input.subject ?? '').trim().slice(0, SITE_CARE_SUBJECT_MAX)\n const body = String(input.body ?? '').trim().slice(0, SITE_CARE_BODY_MAX)\n if (!subject) throw new SiteCareError('Say what you would like changed.', 400)\n if (!body) throw new SiteCareError('Describe the change.', 400)\n if (!orgHasSiteCare(input.org)) {\n throw new SiteCareError('Site Care is not on this workspace. Add it on Billing.', 403)\n }\n const nowMs = nowOf(deps)\n const month = siteCareMonthKey(nowMs)\n const dueAtMs = addBusinessDays(nowMs, SITE_CARE_RESPONSE_BUSINESS_DAYS)\n const ref = input.dedupeKey\n ? firestore.collection(TICKETS).doc(siteCareMessageDocId('care', input.dedupeKey))\n : firestore.collection(TICKETS).doc(createResourceUid())\n if (input.dedupeKey && (await ref.get()).exists) return { ticketId: ref.id, dueAtMs, duplicate: true }\n const now = FieldValue.serverTimestamp()\n const batch = firestore.batch()\n batch.create(ref, {\n orgId: input.orgId,\n subject,\n status: 'open',\n kind: SITE_CARE_TICKET_KIND,\n plan: resolveEffectivePlan(input.org as never),\n supportTier: 'siteCare',\n supportTierRank: 0,\n // Site Care's promise is DONE within two business days, so the clock\n // runs until the request closes, not until the first staff reply.\n responseDueAt: Timestamp.fromMillis(dueAtMs),\n firstRespondedAt: null,\n siteCare: newSiteCareRequest({\n source: input.source,\n hostId: input.hostId,\n requesterEmail: input.requester.email,\n month,\n }),\n siteCareMonth: month,\n siteCareOrgMonth: siteCareOrgMonth(input.orgId, month),\n createdAt: now,\n updatedAt: now,\n })\n batch.create(ref.collection('messages').doc(createResourceUid()), {\n authorId: input.requester.uid,\n authorEmail: input.requester.email,\n staff: false,\n body,\n source: input.source,\n createdAt: now,\n })\n appendHistoryRow(\n batch,\n firestore,\n ref.collection(SITE_CARE_HISTORY_COLLECTION),\n historyRow({\n atMs: nowMs,\n by: input.requester,\n kind: 'request.opened',\n summary: `${input.requester.email ?? 'The owner'} asked ${\n input.source === 'email' ? 'by email' : 'from the console'\n }: “${subject}”.`,\n after: { subject, source: input.source, dueAtMs },\n subjectId: ref.id,\n }),\n )\n await batch.commit()\n\n await notifyStaff({\n type: 'support.ticketOpened',\n title: `New Site Care request: ${subject}`,\n body:\n `${input.requester.email ?? 'An owner'} asked ${input.source === 'email' ? 'by email' : 'from the console'} ` +\n `for workspace ${String(input.org['name'] ?? input.orgId)} (${input.orgId}). ` +\n `It is due done by ${formatSiteCareDate(dueAtMs)}.`,\n link: `/admin/support?ticketId=${ref.id}`,\n orgId: input.orgId,\n })\n\n const due = new Date(dueAtMs).toLocaleDateString('en-US', {\n weekday: 'long',\n month: 'long',\n day: 'numeric',\n timeZone: 'America/Chicago',\n })\n const result = await emailOf(deps)({\n key: SITE_CARE_REQUEST_RECEIVED_EMAIL_KEY,\n to: input.requester.email,\n org: input.org,\n requestId: ref.id,\n merge: { 'request.title': subject, 'request.message': body, 'request.due': due },\n fallback: {\n subject: `We have your request: ${subject}`,\n text: `We received “${subject}” and will have it done by ${due}.\\n\\n${body}`,\n },\n })\n await recordEmail(firestore, ref.collection(SITE_CARE_HISTORY_COLLECTION), result, 'the request receipt', nowOf(deps), ref.id)\n return { ticketId: ref.id, dueAtMs }\n}\n\n/**\n * Adds a reply that arrived by email to its request's thread. The sender\n * must be a member of the request's workspace.\n */\nexport async function appendSiteCareReply(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; from: SiteCareActor; body: string; dedupeKey?: string | null },\n deps: SiteCareDeps = {},\n): Promise<{ appended: boolean }> {\n const snapshot = await ticketRef(firestore, input.ticketId).get()\n if (!snapshot.exists) return { appended: false }\n const ticket = loadedTicket(snapshot)\n const body = String(input.body ?? '').trim().slice(0, SITE_CARE_BODY_MAX)\n if (!body) return { appended: false }\n const nowMs = nowOf(deps)\n const now = FieldValue.serverTimestamp()\n const messageRef = input.dedupeKey\n ? ticket.ref.collection('messages').doc(siteCareMessageDocId('mail', input.dedupeKey))\n : ticket.ref.collection('messages').doc(createResourceUid())\n if (input.dedupeKey && (await messageRef.get()).exists) return { appended: false }\n const batch = firestore.batch()\n batch.create(messageRef, {\n authorId: input.from.uid,\n authorEmail: input.from.email,\n staff: false,\n body,\n source: 'email',\n createdAt: now,\n })\n batch.update(ticket.ref, { status: 'open', updatedAt: now })\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.from,\n kind: 'request.replied',\n summary: `${input.from.email ?? 'The owner'} replied by email.`,\n subjectId: input.ticketId,\n }),\n )\n await batch.commit()\n await notifyStaff({\n type: 'support.ticketReply',\n title: `Site Care reply: ${ticket.subject}`,\n body: `${input.from.email ?? 'The owner'} replied by email on “${ticket.subject.slice(0, 120)}” for workspace ${ticket.orgId}.`,\n link: `/admin/support?ticketId=${input.ticketId}`,\n orgId: ticket.orgId,\n })\n return { appended: true }\n}\n\n// ── Timer ───────────────────────────────────────────────────────────────────\n\n/**\n * Starts the request's timer the first time staff open it. A second open,\n * a reload or another staff member opening it changes nothing.\n */\nexport async function startSiteCareTimer(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareRequest> {\n return firestore.runTransaction(async (tx) => {\n const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)))\n if (ticket.request.state !== 'open' || ticket.request.timerStartedAtMs) return ticket.request\n const nowMs = nowOf(deps)\n const request: SiteCareRequest = {\n ...ticket.request,\n timerStartedAtMs: nowMs,\n timerStartedByUid: input.actor.uid,\n }\n tx.update(ticket.ref, { siteCare: request, updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n tx,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'timer.started',\n summary: 'Started work.',\n after: { timerStartedAtMs: nowMs },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, 'timer.started'),\n )\n return request\n })\n}\n\n// ── Allocation against the month ────────────────────────────────────────────\n\ninterface MonthContext {\n goodwillMinutes: number\n /** Included minutes the month's OTHER closed requests used. */\n otherIncludedUsed: number\n /** The month's requests as the statement reads them, this one excluded. */\n others: ReturnType<typeof siteCareStatementRequest>[]\n}\n\nasync function readMonthContext(\n reader: Pick<FirebaseFirestore.Transaction, 'get'> | null,\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n month: string,\n excludeTicketId: string,\n): Promise<MonthContext> {\n const query = firestore.collection(TICKETS).where('siteCareOrgMonth', '==', siteCareOrgMonth(orgId, month))\n const [monthSnap, requests] = reader\n ? await Promise.all([reader.get(monthRef(firestore, orgId, month)), reader.get(query)])\n : await Promise.all([monthRef(firestore, orgId, month).get(), query.get()])\n const others = requests.docs\n .filter((doc) => doc.id !== excludeTicketId)\n .map((doc) =>\n siteCareStatementRequest(doc.id, String(doc.get('subject') ?? ''), readSiteCareRequest(doc.get('siteCare'))),\n )\n return {\n goodwillMinutes: Number(monthSnap.get('goodwillMinutes') ?? 0) || 0,\n otherIncludedUsed: others\n .filter((r) => r.state === 'closed')\n .reduce((sum, r) => sum + r.includedMinutesUsed, 0),\n others,\n }\n}\n\nfunction statementWith(\n month: string,\n context: MonthContext,\n ticketId: string,\n subject: string,\n request: SiteCareRequest,\n): SiteCareMonthStatement {\n return siteCareMonthStatement({\n month,\n goodwillMinutes: context.goodwillMinutes,\n requests: [...context.others, siteCareStatementRequest(ticketId, subject, request)],\n })\n}\n\n/** Why a close or a correction is blocked, as the staff panel says it. */\nexport function siteCareBlockedMessage(verdict: Extract<SiteCareCloseVerdict, { ok: false }>): string {\n return verdict.reason === 'no-approval'\n ? `This takes the month past the included hour by ${describeHours(verdict.requiredHours)}, and no approval is on file. Ask the owner first, or absorb it.`\n : `This needs ${describeHours(verdict.requiredHours)} of extra time and the owner approved ${describeHours(\n verdict.approvedHours ?? 0,\n )}. Ask the owner first, or absorb it.`\n}\n\n// ── Publish link ────────────────────────────────────────────────────────────\n\n/**\n * The newest publish on any of the workspace's sites since `sinceMs`, from\n * each site's activity log — the change the request shipped.\n */\nexport async function findSiteCarePublish(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n sinceMs: number,\n): Promise<SiteCarePublishLink | null> {\n const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).limit(10).get()\n let best: SiteCarePublishLink | null = null\n for (const host of hosts.docs) {\n const rows = await host.ref\n .collection('activity')\n .where('createdAt', '>=', Timestamp.fromMillis(sinceMs))\n .orderBy('createdAt', 'desc')\n .limit(50)\n .get()\n for (const row of rows.docs) {\n const action = row.get('action')\n if (!isSiteCarePublishAction(action)) continue\n const atMs = (row.get('createdAt') as Timestamp | undefined)?.toMillis?.() ?? 0\n if (!best || atMs > best.atMs) {\n best = {\n hostId: host.id,\n activityId: row.id,\n action: String(action),\n targetName: (row.get('target.name') as string | undefined) ?? null,\n targetId: (row.get('target.id') as string | undefined) ?? null,\n atMs,\n }\n }\n break\n }\n }\n return best\n}\n\n// ── Charges ─────────────────────────────────────────────────────────────────\n\nfunction chargeKey(ticketId: string, seq: number): string {\n return `site-care:${ticketId}:charge:${seq}`\n}\n\nfunction newCharge(input: {\n ticketId: string\n seq: number\n hours: number\n description: string\n nowMs: number\n}): SiteCareCharge {\n return {\n status: 'creating',\n hours: input.hours,\n amountCents: siteCareExtraTimeCents(input.hours),\n description: input.description,\n idempotencyKey: chargeKey(input.ticketId, input.seq),\n invoiceItemId: null,\n invoiceId: null,\n creditNoteId: null,\n refundId: null,\n error: null,\n updatedAtMs: input.nowMs,\n }\n}\n\nfunction chargeRequestedRow(\n ticketId: string,\n charge: SiteCareCharge,\n actor: SiteCareActor,\n nowMs: number,\n): AppendOnlyHistoryRow {\n return historyRow({\n atMs: nowMs,\n by: actor,\n kind: 'charge.requested',\n summary: `Adding ${describeHours(charge.hours)} of extra time (${formatSiteCareUsd(charge.amountCents)}) to the next invoice.`,\n after: { hours: charge.hours, amountCents: charge.amountCents, idempotencyKey: charge.idempotencyKey },\n subjectId: ticketId,\n })\n}\n\n/**\n * Creates the Stripe item for a `creating` (or `failed`) charge and records\n * the outcome. The key is the charge's own, so a retry after a lost\n * response returns the item the first call made rather than a second one.\n */\nasync function settleCharge(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor },\n deps: SiteCareDeps,\n): Promise<SiteCareCharge | null> {\n const snapshot = await ticketRef(firestore, input.ticketId).get()\n const ticket = loadedTicket(snapshot)\n const charge = ticket.request.charge\n if (!charge || (charge.status !== 'creating' && charge.status !== 'failed')) return charge\n const billing = await readOrgBilling(ticket.orgId)\n const customerId = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '')\n const subscription = await siteCareSubscriptionId(customerId, deps.stripe)\n const product = subscription.ok ? await siteCareExtraTimeProduct(deps.stripe) : null\n const created =\n subscription.ok && product?.ok\n ? await createExtraTimeItem(\n {\n customerId,\n subscriptionId: subscription.subscriptionId,\n productId: product.productId,\n hours: charge.hours,\n description: charge.description,\n metadata: {\n siteCareRequestId: input.ticketId,\n orgId: ticket.orgId,\n month: ticket.request.month,\n },\n idempotencyKey: charge.idempotencyKey,\n },\n deps.stripe,\n )\n : null\n const nowMs = nowOf(deps)\n const error = subscription.ok === false\n ? subscription.error\n : product && product.ok === false\n ? product.error\n : created && created.ok === false\n ? created.error\n : null\n const next: SiteCareCharge =\n created && created.ok\n ? { ...charge, status: 'pending', invoiceItemId: created.invoiceItemId, error: null, updatedAtMs: nowMs }\n : { ...charge, status: 'failed', error: error ?? 'Unknown failure', updatedAtMs: nowMs }\n const batch = firestore.batch()\n batch.update(ticket.ref, { 'siteCare.charge': next, updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: next.status === 'pending' ? 'charge.created' : 'charge.failed',\n summary:\n next.status === 'pending'\n ? `Added ${describeHours(next.hours)} of extra time (${formatSiteCareUsd(next.amountCents)}) to the next invoice.`\n : `The extra time could not be added to the invoice: ${next.error}`,\n after: { status: next.status, invoiceItemId: next.invoiceItemId, error: next.error },\n stripe:\n next.status === 'pending' && next.invoiceItemId\n ? { object: 'invoiceitem', id: next.invoiceItemId, amountCents: next.amountCents }\n : null,\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, next.status === 'pending' ? 'charge.created' : 'charge.failed'),\n )\n await batch.commit()\n return next\n}\n\n/** Re-runs a charge that failed, or whose result never landed. */\nexport async function retrySiteCareCharge(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareCharge | null> {\n const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n const status = ticket.request.charge?.status\n if (status !== 'failed' && status !== 'creating') {\n throw new SiteCareError('There is no charge waiting to be retried on this request.', 409)\n }\n return settleCharge(firestore, input, deps)\n}\n\n// ── Close ───────────────────────────────────────────────────────────────────\n\nexport interface CloseSiteCareInput {\n ticketId: string\n actor: SiteCareActor\n minutes: unknown\n absorb?: boolean\n}\n\nexport interface CloseSiteCareResult {\n request: SiteCareRequest\n statement: SiteCareMonthStatement\n}\n\n/**\n * Closes a request with one number. Refuses with the verdict when the\n * minutes take the month past the included hour and no approval covers it\n * — the panel then offers \"Ask the owner first\" and \"Absorb it\".\n */\nexport async function closeSiteCareRequest(\n firestore: FirebaseFirestore.Firestore,\n input: CloseSiteCareInput,\n deps: SiteCareDeps = {},\n): Promise<CloseSiteCareResult> {\n const minutes = readSiteCareMinutes(input.minutes)\n if (minutes === null) throw new SiteCareError('Enter the minutes this took.', 400)\n const nowMs = nowOf(deps)\n const month = siteCareMonthKey(nowMs)\n const first = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n const publish = await findSiteCarePublish(\n firestore,\n first.orgId,\n first.request.timerStartedAtMs ?? (first.data['createdAt'] as Timestamp | undefined)?.toMillis?.() ?? nowMs,\n ).catch(() => null)\n\n const result = await firestore.runTransaction(async (tx) => {\n const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)))\n if (ticket.request.state === 'closed') throw new SiteCareError('This request is already closed. Correct its minutes instead.', 409)\n const context = await readMonthContext(tx, firestore, ticket.orgId, month, input.ticketId)\n const allocation = allocateSiteCareMinutes({\n minutes,\n otherIncludedUsed: context.otherIncludedUsed,\n goodwillMinutes: context.goodwillMinutes,\n })\n const verdict = siteCareCloseVerdict({\n requiredHours: allocation.requiredHours,\n approval: ticket.request.approval,\n absorb: input.absorb === true,\n })\n if (verdict.ok === false) {\n throw new SiteCareError(siteCareBlockedMessage(verdict), 409, { blocked: verdict, allocation })\n }\n const timerMinutes = ticket.request.timerStartedAtMs\n ? Math.round((nowMs - ticket.request.timerStartedAtMs) / 60_000)\n : null\n let request: SiteCareRequest = {\n ...ticket.request,\n state: 'closed',\n month,\n closedAtMs: nowMs,\n minutesLogged: minutes,\n timerMinutes,\n countedMinutes: allocation.countedMinutes,\n includedMinutesUsed: allocation.includedMinutesUsed,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n absorbed: verdict.absorbed,\n publish,\n }\n let charge: SiteCareCharge | null = null\n if (verdict.billedHours > 0) {\n const statement = statementWith(month, context, input.ticketId, ticket.subject, request)\n const seq = request.chargeSeq + 1\n charge = newCharge({\n ticketId: input.ticketId,\n seq,\n hours: verdict.billedHours,\n description: siteCareExtraTimeDescription({\n title: ticket.subject,\n minutesLogged: minutes,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n approvedHours: request.approval?.hours ?? null,\n statement,\n }),\n nowMs,\n })\n request = { ...request, charge, chargeSeq: seq }\n }\n const statement = statementWith(month, context, input.ticketId, ticket.subject, request)\n tx.update(ticket.ref, {\n siteCare: request,\n siteCareMonth: month,\n siteCareOrgMonth: siteCareOrgMonth(ticket.orgId, month),\n status: 'closed',\n // The promise was \"done\", and it is: the SLA sweep stops here even if\n // the owner later replies and reopens the thread.\n ...(ticket.data['firstRespondedAt'] ? {} : { firstRespondedAt: FieldValue.serverTimestamp() }),\n updatedAt: FieldValue.serverTimestamp(),\n })\n const history = ticketHistory(firestore, input.ticketId)\n if (timerMinutes !== null) {\n appendHistoryRow(\n tx,\n firestore,\n history,\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'timer.stopped',\n summary: `Stopped work after ${formatSiteCareMinutes(timerMinutes)} on the timer.`,\n after: { timerMinutes },\n subjectId: input.ticketId,\n }),\n )\n }\n appendHistoryRow(\n tx,\n firestore,\n history,\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'request.closed',\n summary:\n `Finished “${ticket.subject}”: ${formatSiteCareMinutes(minutes)} of work, ` +\n `${allocation.includedMinutesUsed} included minutes used` +\n (allocation.overMinutes > 0\n ? verdict.absorbed\n ? `, ${formatSiteCareMinutes(allocation.overMinutes)} past the included hour absorbed at no charge.`\n : `, ${describeHours(verdict.billedHours)} of extra time billed.`\n : '.'),\n after: {\n minutesLogged: minutes,\n timerMinutes,\n countedMinutes: allocation.countedMinutes,\n includedMinutesUsed: allocation.includedMinutesUsed,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n absorbed: verdict.absorbed,\n publishActivityId: publish?.activityId ?? null,\n },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, verdict.absorbed ? 'request.closedAbsorbed' : 'request.closed'),\n )\n if (charge) {\n appendHistoryRow(tx, firestore, history, chargeRequestedRow(input.ticketId, charge, input.actor, nowMs))\n }\n return { ticket, request, statement }\n })\n\n let request = result.request\n if (request.charge) {\n const settled = await settleCharge(firestore, { ticketId: input.ticketId, actor: input.actor }, deps)\n request = { ...request, charge: settled }\n }\n await emailDoneSummary(firestore, result.ticket, request, result.statement, deps)\n return { request, statement: result.statement }\n}\n\nfunction billingSentence(request: SiteCareRequest): string {\n if (request.overMinutes <= 0) return 'No extra charge: this fit in your included hour.'\n if (request.absorbed || request.billedHours === 0) {\n return 'It ran past your included hour, and we did not charge for the extra time.'\n }\n const status = request.charge?.status\n if (status === 'failed') {\n return `It ran past your included hour; we will add ${describeHours(request.billedHours)} of extra time to your next invoice.`\n }\n return `${describeHours(request.billedHours)} of extra time (${formatSiteCareUsd(\n siteCareExtraTimeCents(request.billedHours),\n )}, at $${SITE_CARE_EXTRA_HOUR_USD} an hour, the time you approved) will be on your next invoice.`\n}\n\nfunction minutesLeftSentence(statement: SiteCareMonthStatement): string {\n return `${formatSiteCareMinutes(statement.minutesLeft)} of this month’s included time`\n}\n\nasync function emailDoneSummary(\n firestore: FirebaseFirestore.Firestore,\n ticket: LoadedTicket,\n request: SiteCareRequest,\n statement: SiteCareMonthStatement,\n deps: SiteCareDeps,\n): Promise<void> {\n const org = await readSiteCareOrg(firestore, ticket.orgId)\n const to = (await siteCareOwnerEmail(firestore, ticket.orgId, org)) ?? request.requesterEmail\n const changes =\n siteCarePublishSentence(request.publish, formatSiteCareDate) ?? `We made the change you asked for: “${ticket.subject}”.`\n const result = await emailOf(deps)({\n key: SITE_CARE_REQUEST_DONE_EMAIL_KEY,\n to,\n org,\n requestId: ticket.ref.id,\n merge: {\n 'request.title': ticket.subject,\n 'request.changes': changes,\n 'request.minutes': formatSiteCareMinutes(request.minutesLogged ?? 0),\n 'month.minutesLeft': minutesLeftSentence(statement),\n 'request.billing': billingSentence(request),\n },\n fallback: {\n subject: `Done: ${ticket.subject}`,\n text:\n `We finished your request “${ticket.subject}”. ${billingSentence(request)}\\n\\n` +\n `What changed: ${changes}\\nTime: ${formatSiteCareMinutes(request.minutesLogged ?? 0)}\\n` +\n `Left this month: ${minutesLeftSentence(statement)}`,\n },\n })\n await recordEmail(firestore, ticketHistory(firestore, ticket.ref.id), result, 'the summary', nowOf(deps), ticket.ref.id)\n}\n\n// ── Approval ────────────────────────────────────────────────────────────────\n\n/**\n * Records — or corrects — how the owner said yes to extra time, and emails\n * them the confirmation that is the written record.\n */\nexport async function recordSiteCareApproval(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor & { uid: string }; approval: Record<string, unknown> },\n deps: SiteCareDeps = {},\n): Promise<OwnerApprovalRecord> {\n const nowMs = nowOf(deps)\n const { ticket, record, previous } = await firestore.runTransaction(async (tx) => {\n const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)))\n const previous = ticket.request.approval\n const read = readOwnerApprovalInput(input.approval, {\n rateUsd: SITE_CARE_EXTRA_HOUR_USD,\n nowMs,\n by: { uid: input.actor.uid, email: input.actor.email },\n previous,\n })\n if (read.ok === false) throw new SiteCareError(read.error, 400)\n const record = read.record\n tx.update(ticket.ref, { 'siteCare.approval': record, updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n tx,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: previous ? 'approval.corrected' : 'approval.recorded',\n summary: previous\n ? `Corrected the approval: ${describeHours(previous.hours)} → ${describeHours(record.hours)}, ${record.channel}.`\n : ownerApprovalSentence(record, ticket.subject, formatSiteCareDate),\n reason: record.correctionReason,\n before: previous ? { ...previous } : null,\n after: { ...record },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, previous ? 'approval.corrected' : 'approval.recorded'),\n )\n return { ticket, record, previous }\n })\n const org = await readSiteCareOrg(firestore, ticket.orgId)\n const to = await siteCareOwnerEmail(firestore, ticket.orgId, org)\n const sentence = ownerApprovalSentence(record, ticket.subject, formatSiteCareDate)\n const correction = previous\n ? `This corrects the earlier record (${describeHours(previous.hours)}): ${record.correctionReason}`\n : ''\n const heading = previous ? 'Corrected: your approval of extra time' : 'You approved extra time'\n const result = await emailOf(deps)({\n key: SITE_CARE_APPROVAL_EMAIL_KEY,\n to,\n org,\n requestId: input.ticketId,\n merge: {\n 'request.title': ticket.subject,\n 'approval.heading': heading,\n 'approval.sentence': sentence,\n 'approval.correction': correction,\n },\n fallback: {\n subject: `${heading}: extra time for ${ticket.subject}`,\n text: `${sentence} ${correction}\\n\\nIf this is not what you agreed to, reply to this email.`,\n },\n })\n await recordEmail(firestore, ticketHistory(firestore, input.ticketId), result, 'the approval confirmation', nowOf(deps), input.ticketId)\n return record\n}\n\n// ── Corrections ─────────────────────────────────────────────────────────────\n\n/**\n * Whether the request's minutes may still change: until the subscription\n * invoice that carries (or would carry) them finalizes.\n */\nasync function assertMinutesEditable(\n orgId: string,\n request: SiteCareRequest,\n deps: SiteCareDeps,\n): Promise<void> {\n const charge = request.charge\n if (charge && charge.status === 'creating') {\n throw new SiteCareError('A charge on this request is still being created. Retry it first.', 409)\n }\n if (charge && charge.status === 'pending' && charge.invoiceItemId) {\n const read = await readExtraTimeItem(charge.invoiceItemId, deps.stripe)\n if (read.ok === false) throw new SiteCareError(read.error, 502)\n if (!extraTimeItemIsEditable(read.state.stage) && read.state.stage !== 'deleted') {\n throw new SiteCareError(\n 'The invoice with this extra time has been finalized, so its minutes are locked. Void, credit or refund the charge instead.',\n 409,\n )\n }\n return\n }\n const billing = await readOrgBilling(orgId)\n const customerId = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '')\n if (!customerId) return\n const subscription = await siteCareSubscriptionId(customerId, deps.stripe)\n if (subscription.ok === false) return\n const finalized = await subscriptionInvoiceFinalizedSince(\n { subscriptionId: subscription.subscriptionId, sinceMs: request.closedAtMs ?? 0 },\n deps.stripe,\n )\n if (finalized.ok === false) throw new SiteCareError(finalized.error, 502)\n if (finalized.finalized) {\n throw new SiteCareError(\n 'The invoice for this request’s month has been finalized, so its minutes are locked.',\n 409,\n )\n }\n}\n\n/**\n * Changes the minutes on a closed request, with a reason, and recomputes its\n * share of the included hour and its extra time: a pending item is corrected\n * or deleted, a new one is added only under an approval. The owner gets a\n * \"corrected\" summary with the before and after.\n */\nexport async function correctSiteCareMinutes(\n firestore: FirebaseFirestore.Firestore,\n input: {\n ticketId: string\n actor: SiteCareActor\n minutes: unknown\n reason: unknown\n absorb?: boolean\n },\n deps: SiteCareDeps = {},\n): Promise<CloseSiteCareResult> {\n const minutes = readSiteCareMinutes(input.minutes)\n if (minutes === null) throw new SiteCareError('Enter the corrected minutes.', 400)\n const reason = requireHistoryReason(input.reason)\n if (reason.ok === false) throw new SiteCareError(reason.error, 400)\n const before = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n if (before.request.state !== 'closed') {\n throw new SiteCareError('Only a finished request’s minutes are corrected; close it instead.', 409)\n }\n await assertMinutesEditable(before.orgId, before.request, deps)\n const nowMs = nowOf(deps)\n\n const result = await firestore.runTransaction(async (tx) => {\n const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)))\n const old = ticket.request\n if (old.charge?.status === 'creating') {\n throw new SiteCareError('A charge on this request is still being created. Retry it first.', 409)\n }\n const month = old.month\n const context = await readMonthContext(tx, firestore, ticket.orgId, month, input.ticketId)\n const allocation = allocateSiteCareMinutes({\n minutes,\n otherIncludedUsed: context.otherIncludedUsed,\n goodwillMinutes: context.goodwillMinutes,\n })\n const verdict = siteCareCloseVerdict({\n requiredHours: allocation.requiredHours,\n approval: old.approval,\n absorb: input.absorb ?? old.absorbed,\n })\n if (verdict.ok === false) {\n throw new SiteCareError(siteCareBlockedMessage(verdict), 409, { blocked: verdict, allocation })\n }\n let request: SiteCareRequest = {\n ...old,\n minutesLogged: minutes,\n countedMinutes: allocation.countedMinutes,\n includedMinutesUsed: allocation.includedMinutesUsed,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n absorbed: verdict.absorbed,\n }\n const live = old.charge && old.charge.status === 'pending' ? old.charge : null\n const statementNow = statementWith(month, context, input.ticketId, ticket.subject, request)\n const description = siteCareExtraTimeDescription({\n title: ticket.subject,\n minutesLogged: minutes,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n approvedHours: request.approval?.hours ?? null,\n statement: statementNow,\n })\n // What the Stripe side must do, decided here and done after the commit.\n let stripeStep: 'none' | 'update' | 'delete' | 'create' = 'none'\n if (live && verdict.billedHours === 0) stripeStep = 'delete'\n else if (live && (live.hours !== verdict.billedHours || live.description !== description)) stripeStep = 'update'\n else if (!live && verdict.billedHours > 0) stripeStep = 'create'\n if (stripeStep === 'create') {\n const seq = request.chargeSeq + 1\n request = {\n ...request,\n chargeSeq: seq,\n charge: newCharge({ ticketId: input.ticketId, seq, hours: verdict.billedHours, description, nowMs }),\n }\n } else if (old.charge?.status === 'failed' && verdict.billedHours === 0) {\n // A charge Stripe refused never made an item, and the corrected time\n // no longer owes one: it is settled as voided, so the reconciliation\n // stops reporting hours that are no longer owed.\n request = { ...request, charge: { ...old.charge, status: 'voided', updatedAtMs: nowMs } }\n }\n tx.update(ticket.ref, { siteCare: request, updatedAt: FieldValue.serverTimestamp() })\n const history = ticketHistory(firestore, input.ticketId)\n // The correction's own row id keys its Stripe call: one correction, one\n // key, so a retried call cannot apply it twice (and a later correction,\n // with its own row, is never mistaken for a replay of this one).\n const correctionRef = appendHistoryRow(\n tx,\n firestore,\n history,\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'minutes.corrected',\n summary: `Corrected the time from ${formatSiteCareMinutes(old.minutesLogged ?? 0)} to ${formatSiteCareMinutes(minutes)}.`,\n reason: reason.reason,\n before: {\n minutesLogged: old.minutesLogged,\n countedMinutes: old.countedMinutes,\n includedMinutesUsed: old.includedMinutesUsed,\n overMinutes: old.overMinutes,\n billedHours: old.billedHours,\n },\n after: {\n minutesLogged: minutes,\n countedMinutes: allocation.countedMinutes,\n includedMinutesUsed: allocation.includedMinutesUsed,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n chargeStatus: request.charge?.status ?? null,\n },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, 'minutes.corrected'),\n )\n if (stripeStep === 'create' && request.charge) {\n appendHistoryRow(tx, firestore, history, chargeRequestedRow(input.ticketId, request.charge, input.actor, nowMs))\n }\n return {\n ticket,\n old,\n request,\n statement: statementNow,\n stripeStep,\n live,\n description,\n correctionId: correctionRef.id,\n }\n })\n\n let request = result.request\n if (result.stripeStep === 'create') {\n const settled = await settleCharge(firestore, { ticketId: input.ticketId, actor: input.actor }, deps)\n request = { ...request, charge: settled }\n } else if ((result.stripeStep === 'update' || result.stripeStep === 'delete') && result.live?.invoiceItemId) {\n request = await correctLiveCharge(\n firestore,\n {\n ticket: result.ticket,\n request,\n live: result.live,\n step: result.stripeStep,\n hours: request.billedHours,\n description: result.description,\n actor: input.actor,\n reason: reason.reason,\n correctionId: result.correctionId,\n },\n deps,\n )\n }\n\n const org = await readSiteCareOrg(firestore, result.ticket.orgId)\n const to = (await siteCareOwnerEmail(firestore, result.ticket.orgId, org)) ?? request.requesterEmail\n const emailed = await emailOf(deps)({\n key: SITE_CARE_REQUEST_CORRECTED_EMAIL_KEY,\n to,\n org,\n requestId: input.ticketId,\n merge: {\n 'request.title': result.ticket.subject,\n 'correction.before': formatSiteCareMinutes(result.old.minutesLogged ?? 0),\n 'correction.after': formatSiteCareMinutes(minutes),\n 'correction.reason': reason.reason,\n 'request.billing': billingSentence(request),\n 'month.minutesLeft': minutesLeftSentence(result.statement),\n },\n fallback: {\n subject: `Corrected: the time on ${result.ticket.subject}`,\n text:\n `We corrected the time on “${result.ticket.subject}” from ${formatSiteCareMinutes(result.old.minutesLogged ?? 0)} ` +\n `to ${formatSiteCareMinutes(minutes)}. ${reason.reason} ${billingSentence(request)}`,\n },\n })\n await recordEmail(firestore, ticketHistory(firestore, input.ticketId), emailed, 'the corrected summary', nowOf(deps), input.ticketId)\n return { request, statement: result.statement }\n}\n\n/**\n * The idempotency key of a correction's Stripe call: the charge's own key\n * and the id of the history row that records the correction. A clock would\n * make every retry a new request to Stripe; the row id makes it the same one.\n */\nexport function siteCareCorrectionKey(chargeKey: string, correctionId: string): string {\n return `${chargeKey}:fix:${correctionId}`\n}\n\n/** Updates or deletes a pending item after a correction, with its row. */\nasync function correctLiveCharge(\n firestore: FirebaseFirestore.Firestore,\n input: {\n ticket: LoadedTicket\n request: SiteCareRequest\n live: SiteCareCharge\n step: 'update' | 'delete'\n hours: number\n description: string\n actor: SiteCareActor\n reason: string\n /** The `minutes.corrected` history row this Stripe call carries out. */\n correctionId: string\n },\n deps: SiteCareDeps,\n): Promise<SiteCareRequest> {\n const itemId = String(input.live.invoiceItemId)\n const nowMs = nowOf(deps)\n const seqKey = siteCareCorrectionKey(input.live.idempotencyKey, input.correctionId)\n const outcome =\n input.step === 'delete'\n ? await deleteExtraTimeItem(itemId, deps.stripe)\n : await updateExtraTimeItem(\n { invoiceItemId: itemId, hours: input.hours, description: input.description, idempotencyKey: seqKey },\n deps.stripe,\n )\n const outcomeError = outcome.ok === false ? outcome.error : null\n const charge: SiteCareCharge = outcomeError === null\n ? input.step === 'delete'\n ? { ...input.live, status: 'voided', updatedAtMs: nowMs, error: null }\n : {\n ...input.live,\n hours: input.hours,\n amountCents: siteCareExtraTimeCents(input.hours),\n description: input.description,\n updatedAtMs: nowMs,\n error: null,\n }\n : { ...input.live, error: outcomeError, updatedAtMs: nowMs }\n const batch = firestore.batch()\n batch.update(input.ticket.ref, { 'siteCare.charge': charge, updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticket.ref.id),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: outcomeError !== null ? 'charge.correctionFailed' : input.step === 'delete' ? 'charge.voided' : 'charge.updated',\n summary: outcomeError !== null\n ? `The charge could not be corrected in Stripe: ${outcomeError}`\n : input.step === 'delete'\n ? `Removed the extra-time charge (${formatSiteCareUsd(input.live.amountCents)}) before it was invoiced.`\n : `Changed the extra-time charge from ${describeHours(input.live.hours)} to ${describeHours(input.hours)}.`,\n reason: input.reason,\n before: { hours: input.live.hours, amountCents: input.live.amountCents, description: input.live.description },\n after: { hours: charge.hours, amountCents: charge.amountCents, status: charge.status, error: charge.error },\n stripe: { object: 'invoiceitem', id: itemId, amountCents: charge.amountCents },\n subjectId: input.ticket.ref.id,\n }),\n requestAudit(\n input.ticket.orgId,\n input.ticket.ref.id,\n outcomeError !== null ? 'charge.correctionFailed' : input.step === 'delete' ? 'charge.voided' : 'charge.updated',\n ),\n )\n await batch.commit()\n return { ...input.request, charge }\n}\n\n/**\n * Voids, credits or refunds a request's extra-time charge, with a reason —\n * deleted before its invoice finalizes, credited after, refunded once paid.\n * `absorb` also records that the request is not charged for its extra time.\n */\nexport async function reverseSiteCareCharge(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor; reason: unknown; absorb?: boolean },\n deps: SiteCareDeps = {},\n): Promise<SiteCareCharge> {\n const reason = requireHistoryReason(input.reason)\n if (reason.ok === false) throw new SiteCareError(reason.error, 400)\n const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n const charge = ticket.request.charge\n if (!charge || !SITE_CARE_LIVE_CHARGE_STATUSES.includes(charge.status) || !charge.invoiceItemId) {\n throw new SiteCareError('There is no extra-time charge on this request to reverse.', 409)\n }\n const read = await readExtraTimeItem(charge.invoiceItemId, deps.stripe)\n if (read.ok === false) throw new SiteCareError(read.error, 502)\n const stage = read.state.stage\n if (stage === 'void' || stage === 'uncollectible') {\n throw new SiteCareError(`The invoice with this charge is ${stage}; there is nothing to reverse.`, 409)\n }\n const nowMs = nowOf(deps)\n const intended = stage === 'paid' ? 'refund' : stage === 'open' ? 'credit' : 'void'\n // The intent first, so a call whose answer is lost still left a row.\n await commitHistoryRow(\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: `charge.${intended}Requested`,\n summary: `Reversing the extra-time charge (${formatSiteCareUsd(charge.amountCents)}): ${intended}.`,\n reason: reason.reason,\n before: { status: charge.status, stage },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, `charge.${intended}Requested`),\n )\n let next: SiteCareCharge\n let stripeRef: HistoryStripeRef\n if (intended === 'void') {\n const deleted = stage === 'deleted' ? ({ ok: true, deleted: true } as const) : await deleteExtraTimeItem(charge.invoiceItemId, deps.stripe)\n if (deleted.ok === false) throw new SiteCareError(deleted.error, 502)\n next = { ...charge, status: 'voided', updatedAtMs: nowOf(deps), error: null }\n stripeRef = { object: 'invoiceitem', id: charge.invoiceItemId, amountCents: charge.amountCents }\n } else {\n const credited = await creditExtraTimeItem(\n {\n invoiceId: String(read.state.invoiceId),\n invoiceItemId: charge.invoiceItemId,\n refund: intended === 'refund',\n memo: `Site Care: ${reason.reason}`,\n metadata: { siteCareRequestId: input.ticketId, orgId: ticket.orgId },\n idempotencyKey: `${charge.idempotencyKey}:${intended}`,\n },\n deps.stripe,\n )\n if (credited.ok === false) throw new SiteCareError(credited.error, 502)\n next = {\n ...charge,\n status: intended === 'refund' ? 'refunded' : 'credited',\n invoiceId: read.state.invoiceId,\n creditNoteId: credited.creditNoteId,\n refundId: credited.refundId,\n updatedAtMs: nowOf(deps),\n error: null,\n }\n stripeRef = { object: 'credit_note', id: credited.creditNoteId, amountCents: credited.amountCents }\n }\n const batch = firestore.batch()\n batch.update(ticket.ref, {\n 'siteCare.charge': next,\n ...(input.absorb ? { 'siteCare.absorbed': true, 'siteCare.billedHours': 0 } : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n const doneKind = next.status === 'voided' ? 'charge.voided' : next.status === 'refunded' ? 'charge.refunded' : 'charge.credited'\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowOf(deps),\n by: input.actor,\n kind: doneKind,\n summary:\n next.status === 'voided'\n ? `Removed the extra-time charge (${formatSiteCareUsd(charge.amountCents)}); it will not be invoiced.`\n : next.status === 'refunded'\n ? `Refunded the extra-time charge (${formatSiteCareUsd(charge.amountCents)} plus its tax).`\n : `Credited the extra-time charge (${formatSiteCareUsd(charge.amountCents)} plus its tax) back on the invoice.`,\n reason: reason.reason,\n before: { status: charge.status },\n after: { status: next.status, creditNoteId: next.creditNoteId, refundId: next.refundId, absorbed: input.absorb === true },\n stripe: stripeRef,\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, doneKind),\n )\n await batch.commit()\n\n const org = await readSiteCareOrg(firestore, ticket.orgId)\n const to = await siteCareOwnerEmail(firestore, ticket.orgId, org)\n const heading =\n next.status === 'voided' ? 'Charge removed' : next.status === 'refunded' ? 'Charge refunded' : 'Charge credited'\n const amount = formatSiteCareUsd(charge.amountCents)\n const sentence =\n next.status === 'voided'\n ? `The ${amount} for ${describeHours(charge.hours)} of extra time will not be on your next invoice.`\n : next.status === 'refunded'\n ? `We refunded the ${amount} for ${describeHours(charge.hours)} of extra time, with its tax, to the card it was paid with.`\n : `We credited the ${amount} for ${describeHours(charge.hours)} of extra time, with its tax, on the invoice it was on.`\n const result = await emailOf(deps)({\n key: SITE_CARE_CHARGE_REVERSED_EMAIL_KEY,\n to,\n org,\n requestId: input.ticketId,\n merge: {\n 'request.title': ticket.subject,\n 'charge.heading': heading,\n 'charge.sentence': sentence,\n 'charge.reason': reason.reason,\n },\n fallback: { subject: `${heading}: ${ticket.subject}`, text: `${sentence}\\n\\nWhy: ${reason.reason}` },\n })\n await recordEmail(firestore, ticketHistory(firestore, input.ticketId), result, 'the charge notice', nowOf(deps), input.ticketId)\n return next\n}\n\n// ── Goodwill ────────────────────────────────────────────────────────────────\n\n/** Adds included minutes to a workspace's month, with a reason. */\nexport async function addSiteCareGoodwill(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; month: unknown; minutes: unknown; reason: unknown; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<{ goodwillMinutes: number }> {\n const month = String(input.month ?? '')\n if (!isSiteCareMonthKey(month)) throw new SiteCareError('Choose the month.', 400)\n const minutes = readSiteCareMinutes(input.minutes)\n if (minutes === null) throw new SiteCareError('Enter the goodwill minutes.', 400)\n const reason = requireHistoryReason(input.reason)\n if (reason.ok === false) throw new SiteCareError(reason.error, 400)\n const nowMs = nowOf(deps)\n return firestore.runTransaction(async (tx) => {\n const ref = monthRef(firestore, input.orgId, month)\n const snapshot = await tx.get(ref)\n const before = Number(snapshot.get('goodwillMinutes') ?? 0) || 0\n const after = before + minutes\n tx.set(ref, { orgId: input.orgId, month, goodwillMinutes: after, updatedAt: FieldValue.serverTimestamp() }, { merge: true })\n appendHistoryRow(\n tx,\n firestore,\n monthHistory(firestore, input.orgId, month),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'goodwill.added',\n summary: `Added ${formatSiteCareMinutes(minutes)} of included time to this month, at no charge.`,\n reason: reason.reason,\n before: { goodwillMinutes: before },\n after: { goodwillMinutes: after },\n }),\n monthAudit(input.orgId, month, 'goodwill.added'),\n )\n return { goodwillMinutes: after }\n })\n}\n\n// ── The month ───────────────────────────────────────────────────────────────\n\nexport interface SiteCareMonthRequestView {\n ticketId: string\n subject: string\n status: string\n request: SiteCareRequest\n history: Array<AppendOnlyHistoryRow & { $id: string }>\n}\n\nexport interface SiteCareMonthView {\n orgId: string\n month: string\n statement: SiteCareMonthStatement\n goodwillMinutes: number\n requests: SiteCareMonthRequestView[]\n monthHistory: Array<AppendOnlyHistoryRow & { $id: string }>\n}\n\n/** Every request of a workspace's month, each with its history, and the totals. */\nexport async function readSiteCareMonth(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; month: string },\n): Promise<SiteCareMonthView> {\n if (!isSiteCareMonthKey(input.month)) throw new SiteCareError('Choose the month.', 400)\n const [snapshot, monthSnap, monthRows] = await Promise.all([\n firestore\n .collection(TICKETS)\n .where('siteCareOrgMonth', '==', siteCareOrgMonth(input.orgId, input.month))\n .limit(200)\n .get(),\n monthRef(firestore, input.orgId, input.month).get(),\n readHistoryRows(monthHistory(firestore, input.orgId, input.month)),\n ])\n const requests = await Promise.all(\n snapshot.docs.map(async (doc) => ({\n ticketId: doc.id,\n subject: String(doc.get('subject') ?? ''),\n status: String(doc.get('status') ?? ''),\n request: readSiteCareRequest(doc.get('siteCare')) as SiteCareRequest,\n history: await readHistoryRows(doc.ref.collection(SITE_CARE_HISTORY_COLLECTION)),\n })),\n )\n requests.sort((a, b) => (a.request.closedAtMs ?? Infinity) - (b.request.closedAtMs ?? Infinity))\n const goodwillMinutes = Number(monthSnap.get('goodwillMinutes') ?? 0) || 0\n return {\n orgId: input.orgId,\n month: input.month,\n goodwillMinutes,\n statement: siteCareMonthStatement({\n month: input.month,\n goodwillMinutes,\n requests: requests.map((r) => siteCareStatementRequest(r.ticketId, r.subject, r.request)),\n }),\n requests,\n monthHistory: monthRows,\n }\n}\n\n/** One request as the statement lists it, in the owner's words. */\nexport function siteCareStatementLine(view: SiteCareMonthRequestView): string {\n const r = view.request\n if (r.state !== 'closed') return `${view.subject}: in progress`\n const billed =\n r.billedHours > 0\n ? `${describeHours(r.billedHours)} billed (${formatSiteCareUsd(siteCareExtraTimeCents(r.billedHours))}), ${siteCareChargeWords(\n r.charge?.status ?? null,\n ).toLowerCase()}`\n : r.overMinutes > 0\n ? 'extra time not charged'\n : 'included'\n return `${view.subject}: ${formatSiteCareMinutes(r.minutesLogged ?? 0)}, ${billed}`\n}\n\n/** Every recorded row of the month, oldest first, as dated lines. */\nexport function siteCareStatementHistory(view: SiteCareMonthView): string[] {\n const rows = [...view.monthHistory, ...view.requests.flatMap((r) => r.history)].sort((a, b) => a.atMs - b.atMs)\n return rows.map(\n (row) => `${formatSiteCareDate(row.atMs)}: ${row.summary}${row.reason ? ` Why: ${row.reason}` : ''}`,\n )\n}\n\n/** Emails the owner the month's statement, on demand. */\nexport async function sendSiteCareStatement(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; month: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareEmailResult> {\n const view = await readSiteCareMonth(firestore, input)\n const org = await readSiteCareOrg(firestore, input.orgId)\n const to = await siteCareOwnerEmail(firestore, input.orgId, org)\n const summary = siteCareMonthSentence(view.statement)\n const lines = view.requests.map(siteCareStatementLine).join('\\n') || 'No requests this month.'\n const history = siteCareStatementHistory(view).join('\\n') || 'Nothing recorded yet.'\n const result = await emailOf(deps)({\n key: SITE_CARE_STATEMENT_EMAIL_KEY,\n to,\n org,\n requestId: null,\n merge: {\n 'month.label': view.statement.monthLabel,\n 'statement.summary': summary,\n 'statement.lines': lines,\n 'statement.history': history,\n },\n fallback: {\n subject: `Your Site Care statement for ${view.statement.monthLabel}`,\n text: `${summary}\\n\\n${lines}\\n\\nEverything we recorded:\\n${history}`,\n },\n })\n await commitHistoryRow(\n firestore,\n monthHistory(firestore, input.orgId, input.month),\n historyRow({\n atMs: nowOf(deps),\n by: input.actor,\n kind: result.sent ? 'statement.sent' : 'statement.notSent',\n summary: result.sent\n ? `Emailed the ${view.statement.monthLabel} statement to ${result.to}.`\n : `The ${view.statement.monthLabel} statement was not sent (${result.reason ?? 'unknown'}).`,\n after: { to: result.to, sent: result.sent, summary },\n }),\n monthAudit(input.orgId, input.month, result.sent ? 'statement.sent' : 'statement.notSent'),\n )\n return result\n}\n\n// ── The quote reply ─────────────────────────────────────────────────────────\n\n/**\n * \"This one is bigger than Site Care covers, here is the quote\": staff send\n * it from the request; it lands on the thread and in the owner's inbox. The\n * invoice itself is the staff \"Charge for work\" (AGL-3970).\n */\nexport async function sendSiteCareQuote(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor; amountUsd: unknown; scope: unknown },\n deps: SiteCareDeps = {},\n): Promise<SiteCareEmailResult> {\n const amount = Number(input.amountUsd)\n if (!Number.isInteger(amount) || amount < 1 || amount > 100_000) {\n throw new SiteCareError('Enter the quote as a whole number of dollars.', 400)\n }\n const scope = String(input.scope ?? '').trim().slice(0, 1000)\n if (!scope) throw new SiteCareError('Say what the price covers.', 400)\n const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n const org = await readSiteCareOrg(firestore, ticket.orgId)\n const to = (await siteCareOwnerEmail(firestore, ticket.orgId, org)) ?? ticket.request.requesterEmail\n const price = `$${amount}`\n const result = await emailOf(deps)({\n key: SITE_CARE_QUOTE_EMAIL_KEY,\n to,\n org,\n requestId: input.ticketId,\n merge: { 'request.title': ticket.subject, 'quote.amount': price, 'quote.scope': scope },\n fallback: {\n subject: `A quote for ${ticket.subject}`,\n text:\n `Site Care covers changes to what your site already has. “${ticket.subject}” adds something new, ` +\n `so it is a project with one flat price: ${price}.\\n\\nWhat it covers: ${scope}\\n\\n` +\n 'Reply to say yes and we will send the invoice. Nothing is charged until you do.',\n },\n })\n const nowMs = nowOf(deps)\n const batch = firestore.batch()\n batch.create(ticket.ref.collection('messages').doc(createResourceUid()), {\n authorId: input.actor.uid,\n authorEmail: input.actor.email,\n staff: true,\n body: `Quote sent: ${price} — ${scope}`,\n createdAt: FieldValue.serverTimestamp(),\n })\n batch.update(ticket.ref, { updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: result.sent ? 'quote.sent' : 'quote.notSent',\n summary: result.sent\n ? `Sent a flat quote of ${price}: this is bigger than Site Care covers.`\n : `The quote of ${price} was not emailed (${result.reason ?? 'unknown'}).`,\n after: { amountUsd: amount, scope, to: result.to, sent: result.sent },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, result.sent ? 'quote.sent' : 'quote.notSent'),\n )\n await batch.commit()\n return result\n}\n\n// ── A ticket's panel ────────────────────────────────────────────────────────\n\nexport interface SiteCareRequestPanel {\n ticketId: string\n orgId: string\n subject: string\n request: SiteCareRequest\n history: Array<AppendOnlyHistoryRow & { $id: string }>\n /** The close's prefilled number, from the timer. */\n suggestedMinutes: number\n /** What this request's month looks like with its other requests. */\n monthMinutesLeft: number\n}\n\n/** Everything the staff panel shows for one request. */\nexport async function readSiteCareRequestPanel(\n firestore: FirebaseFirestore.Firestore,\n ticketId: string,\n deps: SiteCareDeps = {},\n): Promise<SiteCareRequestPanel> {\n const ticket = loadedTicket(await ticketRef(firestore, ticketId).get())\n const nowMs = nowOf(deps)\n const month = ticket.request.state === 'closed' ? ticket.request.month : siteCareMonthKey(nowMs)\n const [history, context] = await Promise.all([\n readHistoryRows(ticketHistory(firestore, ticketId)),\n readMonthContext(null, firestore, ticket.orgId, month, ticketId),\n ])\n const pool = siteCareIncludedPool(context.goodwillMinutes)\n return {\n ticketId,\n orgId: ticket.orgId,\n subject: ticket.subject,\n request: ticket.request,\n history,\n suggestedMinutes: closeMinutesFromTimer(ticket.request.timerStartedAtMs, nowMs),\n monthMinutesLeft: Math.max(0, pool - context.otherIncludedUsed),\n }\n}\n"],"names":["historyRow","requireHistoryReason","createResourceUid","describeHours","ownerApprovalSentence","readOwnerApprovalInput","readOwnerApprovalRecord","hasSiteCare","resolveEffectivePlan","SITE_CARE_EXTRA_HOUR_USD","allocateSiteCareMinutes","closeMinutesFromTimer","formatSiteCareDate","formatSiteCareMinutes","formatSiteCareUsd","isSiteCareMonthKey","isSiteCarePublishAction","readSiteCareMinutes","SITE_CARE_BODY_MAX","SITE_CARE_LIVE_CHARGE_STATUSES","SITE_CARE_RESPONSE_BUSINESS_DAYS","SITE_CARE_SUBJECT_MAX","SITE_CARE_TICKET_KIND","siteCareChargeWords","siteCareCloseVerdict","siteCareExtraTimeCents","siteCareExtraTimeDescription","siteCareIncludedPool","siteCareMonthKey","siteCareMonthSentence","siteCareMonthStatement","siteCareOrgMonth","siteCarePublishSentence","siteCareStatementRequest","addBusinessDays","SITE_CARE_APPROVAL_EMAIL_KEY","SITE_CARE_CHARGE_REVERSED_EMAIL_KEY","SITE_CARE_QUOTE_EMAIL_KEY","SITE_CARE_REQUEST_CORRECTED_EMAIL_KEY","SITE_CARE_REQUEST_DONE_EMAIL_KEY","SITE_CARE_REQUEST_RECEIVED_EMAIL_KEY","SITE_CARE_STATEMENT_EMAIL_KEY","createHash","FieldValue","Timestamp","appendHistoryRow","commitHistoryRow","readHistoryRows","notifyStaff","readOrgBilling","sendSiteCareEmail","createExtraTimeItem","creditExtraTimeItem","deleteExtraTimeItem","extraTimeItemIsEditable","readExtraTimeItem","siteCareExtraTimeProduct","siteCareSubscriptionId","subscriptionInvoiceFinalizedSince","updateExtraTimeItem","TICKETS","SITE_CARE_HISTORY_COLLECTION","SITE_CARE_MONTHS_COLLECTION","SiteCareError","Error","message","status","detail","name","nowOf","deps","now","Date","emailOf","email","ticketRef","firestore","ticketId","collection","doc","ticketHistory","monthRef","orgId","month","monthHistory","requestAudit","action","scope","target","monthAudit","newSiteCareRequest","input","source","hostId","requesterEmail","state","timerStartedAtMs","timerStartedByUid","closedAtMs","minutesLogged","timerMinutes","countedMinutes","includedMinutesUsed","overMinutes","billedHours","absorbed","approval","charge","chargeSeq","publish","readSiteCareRequest","value","stored","base","Number","loadedTicket","snapshot","data","request","ref","String","subject","readSiteCareOrg","get","exists","billing","$id","orgHasSiteCare","org","Boolean","siteCareOwnerEmail","ownerUid","member","recordEmail","history","result","what","atMs","subjectId","by","uid","kind","sent","summary","to","reason","after","catch","error","console","siteCareMessageDocId","prefix","key","update","digest","slice","openSiteCareRequest","trim","body","nowMs","dueAtMs","dedupeKey","id","duplicate","serverTimestamp","batch","create","plan","supportTier","supportTierRank","responseDueAt","fromMillis","firstRespondedAt","siteCare","requester","siteCareMonth","createdAt","updatedAt","authorId","authorEmail","staff","commit","type","title","link","due","toLocaleDateString","weekday","day","timeZone","requestId","merge","fallback","text","appendSiteCareReply","appended","ticket","messageRef","from","startSiteCareTimer","runTransaction","tx","actor","readMonthContext","reader","excludeTicketId","monthSnap","query","where","requests","Promise","all","others","docs","filter","map","goodwillMinutes","otherIncludedUsed","r","reduce","sum","statementWith","context","siteCareBlockedMessage","verdict","requiredHours","approvedHours","findSiteCarePublish","sinceMs","hosts","limit","best","host","rows","orderBy","row","toMillis","activityId","targetName","targetId","chargeKey","seq","newCharge","hours","amountCents","description","idempotencyKey","invoiceItemId","invoiceId","creditNoteId","refundId","updatedAtMs","chargeRequestedRow","settleCharge","customerId","stripeCustomerId","subscription","stripe","product","ok","created","subscriptionId","productId","metadata","siteCareRequestId","next","object","retrySiteCareCharge","closeSiteCareRequest","first","minutes","allocation","absorb","blocked","Math","round","statement","publishActivityId","settled","emailDoneSummary","billingSentence","minutesLeftSentence","minutesLeft","changes","recordSiteCareApproval","record","previous","read","rateUsd","channel","correctionReason","before","sentence","correction","heading","assertMinutesEditable","stage","finalized","correctSiteCareMinutes","old","live","statementNow","stripeStep","correctionRef","chargeStatus","correctionId","correctLiveCharge","step","emailed","siteCareCorrectionKey","itemId","seqKey","outcome","outcomeError","reverseSiteCareCharge","includes","intended","stripeRef","deleted","credited","refund","memo","doneKind","amount","addSiteCareGoodwill","set","readSiteCareMonth","monthRows","sort","a","b","Infinity","siteCareStatementLine","view","billed","toLowerCase","siteCareStatementHistory","flatMap","sendSiteCareStatement","lines","join","monthLabel","sendSiteCareQuote","amountUsd","isInteger","price","readSiteCareRequestPanel","pool","suggestedMinutes","monthMinutesLeft","max"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,oBAAoB,QAGf,6CAA4C;AACnD,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,aAAa,EACbC,qBAAqB,EACrBC,sBAAsB,EACtBC,uBAAuB,QAElB,+CAA8C;AACrD,SACEC,WAAW,EACXC,oBAAoB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;IAC1F,MAAM,CAACzB,SAASwF,QAAQ,GAAG,MAAMZ,QAAQC,GAAG,CAAC;QAC3CpK,gBAAgBiC,cAAcJ,WAAWC;QACzC8H,iBAAiB,MAAM/H,WAAWwH,OAAOlH,KAAK,EAAEC,OAAON;KACxD;IACD,MAAM8Q,OAAOhU,qBAAqBmM,QAAQN,eAAe;IACzD,OAAO;QACL3I;QACAK,OAAOkH,OAAOlH,KAAK;QACnBuC,SAAS2E,OAAO3E,OAAO;QACvBH,SAAS8E,OAAO9E,OAAO;QACvBgB;QACAsN,kBAAkBjV,sBAAsByL,OAAO9E,OAAO,CAACtB,gBAAgB,EAAE+D;QACzE8L,kBAAkB3E,KAAK4E,GAAG,CAAC,GAAGH,OAAO7H,QAAQL,iBAAiB;IAChE;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-requests.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 describeHours,\n ownerApprovalSentence,\n readOwnerApprovalInput,\n readOwnerApprovalRecord,\n type OwnerApprovalRecord,\n} from '@aglyn/aglyn/app-utils/owner-approval-record'\nimport {\n hasSiteCare,\n resolveEffectivePlan,\n SITE_CARE_EXTRA_HOUR_USD,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n allocateSiteCareMinutes,\n closeMinutesFromTimer,\n formatSiteCareDate,\n formatSiteCareMinutes,\n formatSiteCareUsd,\n isSiteCareMonthKey,\n isSiteCarePublishAction,\n otherSiteCareCandidates,\n readSiteCareCandidates,\n readSiteCareMinutes,\n SITE_CARE_BODY_MAX,\n SITE_CARE_LIVE_CHARGE_STATUSES,\n SITE_CARE_RESPONSE_BUSINESS_DAYS,\n SITE_CARE_STAFF_COLLECTION,\n SITE_CARE_SUBJECT_MAX,\n SITE_CARE_TICKET_KIND,\n siteCareCandidatesSentence,\n siteCareChargeWords,\n siteCareCloseVerdict,\n siteCareExtraTimeCents,\n siteCareExtraTimeDescription,\n siteCareIncludedPool,\n siteCareMonthKey,\n siteCareMonthSentence,\n siteCareMonthStatement,\n siteCareMoveBlockedReason,\n siteCareOrgMonth,\n siteCarePublishSentence,\n siteCareStatementRequest,\n type SiteCareCharge,\n type SiteCareCloseVerdict,\n type SiteCareMonthStatement,\n type SiteCarePublishLink,\n type SiteCareRequest,\n type SiteCareSource,\n type SiteCareWorkspaceCandidate,\n} from '@aglyn/aglyn/app-utils/site-care'\nimport { addBusinessDays } from '@aglyn/aglyn/app-utils/support-tiers'\nimport {\n SITE_CARE_APPROVAL_EMAIL_KEY,\n SITE_CARE_CHARGE_REVERSED_EMAIL_KEY,\n SITE_CARE_QUOTE_EMAIL_KEY,\n SITE_CARE_REQUEST_CORRECTED_EMAIL_KEY,\n SITE_CARE_REQUEST_DONE_EMAIL_KEY,\n SITE_CARE_REQUEST_RECEIVED_EMAIL_KEY,\n SITE_CARE_STATEMENT_EMAIL_KEY,\n} from '@aglyn/shared-util-email'\nimport { createHash } from 'node:crypto'\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\nimport {\n appendHistoryRow,\n commitHistoryRow,\n readHistoryRows,\n type HistoryAudit,\n} from './append-only-history-write'\nimport { notifyStaff } from './notifications'\nimport { readOrgBilling } from './org-billing'\nimport { sendSiteCareEmail, type SiteCareEmailResult } from './site-care-emails'\nimport {\n createExtraTimeItem,\n creditExtraTimeItem,\n deleteExtraTimeItem,\n extraTimeItemIsEditable,\n readExtraTimeItem,\n siteCareExtraTimeProduct,\n siteCareSubscriptionId,\n subscriptionInvoiceFinalizedSince,\n updateExtraTimeItem,\n type SiteCareStripeOptions,\n} from './site-care-stripe'\n\n/**\n * SITE CARE REQUESTS, WITH FIRESTORE AND STRIPE (AGL-3959).\n *\n * A request is a support ticket (`supportTickets/{id}`, `kind: 'siteCare'`)\n * with a `siteCare` map holding everything about the work: the timer, the\n * one number staff close it with, how its minutes counted against the\n * included hour, the owner's recorded approval, the extra-time charge and\n * the publish that shipped it. Beside it, an append-only history\n * (`supportTickets/{id}/siteCareHistory`), and per workspace and month a\n * document for goodwill minutes with its own history\n * (`orgs/{orgId}/siteCareMonths/{YYYY-MM}`). An emailed request from a\n * sender in several Site Care workspaces also keeps every one of them, for\n * staff only, at `supportTickets/{id}/siteCareStaff/intake` (AGL-4031): the\n * ticket itself is returned to the workspace's members, and which other\n * workspaces the sender belongs to is not theirs to read. None of it is in the Firestore\n * rules: every read and write passes the console's routes, as the rest of\n * the support system does.\n *\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 call: a `charge.requested`\n * row and a `creating` charge commit first, then the call, then the result\n * and its row commit together. A Stripe success with no row behind it is a\n * `creating` charge with no item — which the reconciliation reports, and\n * which `retrySiteCareCharge` settles under the same idempotency key.\n *\n * The arithmetic is `@aglyn/aglyn/app-utils/site-care`, the approval record\n * `owner-approval-record`, the row `append-only-history`.\n */\n\nconst TICKETS = 'supportTickets'\nexport const SITE_CARE_HISTORY_COLLECTION = 'siteCareHistory'\nexport const SITE_CARE_MONTHS_COLLECTION = 'siteCareMonths'\nconst SITE_CARE_INTAKE_DOC = 'intake'\n\n/** Who did something. `uid` null is the platform itself. */\nexport interface SiteCareActor {\n uid: string | null\n email: string | null\n}\n\n/** A refusal the caller turns into a response. */\nexport class SiteCareError extends Error {\n readonly status: number\n readonly detail: Record<string, unknown> | null\n constructor(message: string, status = 400, detail: Record<string, unknown> | null = null) {\n super(message)\n this.name = 'SiteCareError'\n this.status = status\n this.detail = detail\n }\n}\n\n/** The seams a spec replaces. */\nexport interface SiteCareDeps {\n now?: () => number\n stripe?: SiteCareStripeOptions\n email?: typeof sendSiteCareEmail\n}\n\nconst nowOf = (deps: SiteCareDeps) => (deps.now ?? Date.now)()\nconst emailOf = (deps: SiteCareDeps) => deps.email ?? sendSiteCareEmail\n\nfunction ticketRef(firestore: FirebaseFirestore.Firestore, ticketId: string) {\n return firestore.collection(TICKETS).doc(ticketId)\n}\n\nfunction ticketHistory(firestore: FirebaseFirestore.Firestore, ticketId: string) {\n return ticketRef(firestore, ticketId).collection(SITE_CARE_HISTORY_COLLECTION)\n}\n\nfunction intakeRef(firestore: FirebaseFirestore.Firestore, ticketId: string) {\n return ticketRef(firestore, ticketId).collection(SITE_CARE_STAFF_COLLECTION).doc(SITE_CARE_INTAKE_DOC)\n}\n\nfunction monthRef(firestore: FirebaseFirestore.Firestore, orgId: string, month: string) {\n return firestore.collection('orgs').doc(orgId).collection(SITE_CARE_MONTHS_COLLECTION).doc(month)\n}\n\nfunction monthHistory(firestore: FirebaseFirestore.Firestore, orgId: string, month: string) {\n return monthRef(firestore, orgId, month).collection(SITE_CARE_HISTORY_COLLECTION)\n}\n\nfunction requestAudit(orgId: string, ticketId: string, action: string): HistoryAudit {\n return { action: `siteCare.${action}`, scope: 'siteCare', target: `orgs/${orgId}/siteCare/${ticketId}` }\n}\n\nfunction monthAudit(orgId: string, month: string, action: string): HistoryAudit {\n return { action: `siteCare.${action}`, scope: 'siteCare', target: `orgs/${orgId}/siteCareMonths/${month}` }\n}\n\n/** A fresh request's map. */\nexport function newSiteCareRequest(input: {\n source: SiteCareSource\n hostId: string | null\n requesterEmail: string | null\n month: string\n}): SiteCareRequest {\n return {\n source: input.source,\n hostId: input.hostId,\n requesterEmail: input.requesterEmail,\n state: 'open',\n month: input.month,\n timerStartedAtMs: null,\n timerStartedByUid: null,\n closedAtMs: null,\n minutesLogged: null,\n timerMinutes: null,\n countedMinutes: 0,\n includedMinutesUsed: 0,\n overMinutes: 0,\n billedHours: 0,\n absorbed: false,\n approval: null,\n charge: null,\n chargeSeq: 0,\n publish: null,\n }\n}\n\n/** A stored map read back with every field present. */\nexport function readSiteCareRequest(value: unknown): SiteCareRequest | null {\n if (!value || typeof value !== 'object') return null\n const stored = value as Partial<SiteCareRequest>\n const base = newSiteCareRequest({\n source: stored.source === 'email' ? 'email' : 'console',\n hostId: stored.hostId ?? null,\n requesterEmail: stored.requesterEmail ?? null,\n month: isSiteCareMonthKey(stored.month) ? stored.month : siteCareMonthKey(Date.now()),\n })\n return {\n ...base,\n ...stored,\n approval: readOwnerApprovalRecord(stored.approval),\n charge: stored.charge ?? null,\n chargeSeq: Number(stored.chargeSeq) || 0,\n publish: stored.publish ?? null,\n } as SiteCareRequest\n}\n\ninterface LoadedTicket {\n ref: FirebaseFirestore.DocumentReference\n orgId: string\n subject: string\n request: SiteCareRequest\n data: Record<string, unknown>\n}\n\nfunction loadedTicket(snapshot: FirebaseFirestore.DocumentSnapshot): LoadedTicket {\n const data = (snapshot.data() ?? null) as Record<string, unknown> | null\n if (!data) throw new SiteCareError('Unknown request', 404)\n if (data['kind'] !== SITE_CARE_TICKET_KIND) throw new SiteCareError('That ticket is not a Site Care request', 400)\n const request = readSiteCareRequest(data['siteCare'])\n if (!request) throw new SiteCareError('That ticket has no Site Care record', 409)\n return {\n ref: snapshot.ref,\n orgId: String(data['orgId'] ?? ''),\n subject: String(data['subject'] ?? ''),\n request,\n data,\n }\n}\n\n/** The org document joined with its billing keys, as `hasSiteCare` reads it. */\nexport async function readSiteCareOrg(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n): Promise<Record<string, unknown> | null> {\n const snapshot = await firestore.collection('orgs').doc(orgId).get()\n if (!snapshot.exists) return null\n const billing = await readOrgBilling(orgId)\n return { $id: orgId, ...(snapshot.data() ?? {}), ...(billing ?? {}) }\n}\n\n/** Whether a workspace has Site Care in force. */\nexport function orgHasSiteCare(org: Record<string, unknown> | null): boolean {\n return Boolean(org) && hasSiteCare(org as never)\n}\n\n/** The owner's address, from the owner's member row. */\nexport async function siteCareOwnerEmail(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n org: Record<string, unknown> | null,\n): Promise<string | null> {\n const ownerUid = typeof org?.['ownerUid'] === 'string' ? (org['ownerUid'] as string) : ''\n if (!ownerUid) return null\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(ownerUid).get()\n const email = member.get('email')\n return typeof email === 'string' && email ? email : null\n}\n\n/** Records an email as the request's (or the month's) history row. */\nasync function recordEmail(\n firestore: FirebaseFirestore.Firestore,\n history: FirebaseFirestore.CollectionReference,\n result: SiteCareEmailResult,\n what: string,\n atMs: number,\n subjectId: string | null,\n): Promise<void> {\n await commitHistoryRow(\n firestore,\n history,\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,\n }),\n ).catch((error) => console.error('[site-care] email history row failed', error))\n}\n\n// ── Intake ──────────────────────────────────────────────────────────────────\n\nexport interface OpenSiteCareRequestInput {\n orgId: string\n org: Record<string, unknown>\n hostId: string | null\n subject: string\n body: string\n requester: SiteCareActor\n source: SiteCareSource\n /**\n * A received message's id, when the request came by email: the ticket is\n * keyed by it, so a provider redelivering the same message opens nothing\n * twice.\n */\n dedupeKey?: string | null\n /**\n * Every Site Care workspace an emailed request's sender belongs to, the\n * one it is filed on included (AGL-4031). Kept, for staff only, when there\n * is more than one, so staff can move the request to the right one.\n */\n candidates?: readonly SiteCareWorkspaceCandidate[]\n}\n\n/** A document id derived from a received message, alphanumeric so it fits a reply address. */\nexport function siteCareMessageDocId(prefix: string, key: string): string {\n return `${prefix}${createHash('sha256').update(key).digest('hex').slice(0, 24)}`\n}\n\n/**\n * Opens a request: the tagged ticket, its first message, the opening history\n * row, the staff notice and the \"we have your request\" email. Shared by the\n * console's \"Request a change\" and the inbound address.\n */\nexport async function openSiteCareRequest(\n firestore: FirebaseFirestore.Firestore,\n input: OpenSiteCareRequestInput,\n deps: SiteCareDeps = {},\n): Promise<{ ticketId: string; dueAtMs: number; duplicate?: boolean }> {\n const subject = String(input.subject ?? '').trim().slice(0, SITE_CARE_SUBJECT_MAX)\n const body = String(input.body ?? '').trim().slice(0, SITE_CARE_BODY_MAX)\n if (!subject) throw new SiteCareError('Say what you would like changed.', 400)\n if (!body) throw new SiteCareError('Describe the change.', 400)\n if (!orgHasSiteCare(input.org)) {\n throw new SiteCareError('Site Care is not on this workspace. Add it on Billing.', 403)\n }\n const nowMs = nowOf(deps)\n const month = siteCareMonthKey(nowMs)\n const dueAtMs = addBusinessDays(nowMs, SITE_CARE_RESPONSE_BUSINESS_DAYS)\n const ref = input.dedupeKey\n ? firestore.collection(TICKETS).doc(siteCareMessageDocId('care', input.dedupeKey))\n : firestore.collection(TICKETS).doc(createResourceUid())\n if (input.dedupeKey && (await ref.get()).exists) return { ticketId: ref.id, dueAtMs, duplicate: true }\n const candidates = readSiteCareCandidates(input.candidates)\n const others = candidates.length > 1 ? otherSiteCareCandidates(candidates, input.orgId) : []\n const now = FieldValue.serverTimestamp()\n const batch = firestore.batch()\n batch.create(ref, {\n orgId: input.orgId,\n subject,\n status: 'open',\n kind: SITE_CARE_TICKET_KIND,\n plan: resolveEffectivePlan(input.org as never),\n supportTier: 'siteCare',\n supportTierRank: 0,\n // Site Care's promise is DONE within two business days, so the clock\n // runs until the request closes, not until the first staff reply.\n responseDueAt: Timestamp.fromMillis(dueAtMs),\n firstRespondedAt: null,\n siteCare: newSiteCareRequest({\n source: input.source,\n hostId: input.hostId,\n requesterEmail: input.requester.email,\n month,\n }),\n siteCareMonth: month,\n siteCareOrgMonth: siteCareOrgMonth(input.orgId, month),\n createdAt: now,\n updatedAt: now,\n })\n batch.create(ref.collection('messages').doc(createResourceUid()), {\n authorId: input.requester.uid,\n authorEmail: input.requester.email,\n staff: false,\n body,\n source: input.source,\n createdAt: now,\n })\n if (others.length) {\n batch.create(ref.collection(SITE_CARE_STAFF_COLLECTION).doc(SITE_CARE_INTAKE_DOC), {\n candidates,\n filedOnOrgId: input.orgId,\n createdAt: now,\n })\n }\n appendHistoryRow(\n batch,\n firestore,\n ref.collection(SITE_CARE_HISTORY_COLLECTION),\n historyRow({\n atMs: nowMs,\n by: input.requester,\n kind: 'request.opened',\n summary: `${input.requester.email ?? 'The owner'} asked ${\n input.source === 'email' ? 'by email' : 'from the console'\n }: “${subject}”.`,\n after: { subject, source: input.source, dueAtMs },\n subjectId: ref.id,\n }),\n )\n await batch.commit()\n\n await notifyStaff({\n type: 'support.ticketOpened',\n title: `New Site Care request: ${subject}`,\n body:\n `${input.requester.email ?? 'An owner'} asked ${input.source === 'email' ? 'by email' : 'from the console'} ` +\n `for workspace ${String(input.org['name'] ?? input.orgId)} (${input.orgId}). ` +\n `It is due done by ${formatSiteCareDate(dueAtMs)}.` +\n (others.length\n ? ` The sender is in more than one Site Care workspace. ${siteCareCandidatesSentence(\n others.map((other) => ({ ...other, name: `${other.name} (${other.orgId})` })),\n )}. If it belongs to one of those, move it from the Site Care card on the request.`\n : ''),\n link: `/admin/support?ticketId=${ref.id}`,\n orgId: input.orgId,\n })\n\n const due = new Date(dueAtMs).toLocaleDateString('en-US', {\n weekday: 'long',\n month: 'long',\n day: 'numeric',\n timeZone: 'America/Chicago',\n })\n const result = await emailOf(deps)({\n key: SITE_CARE_REQUEST_RECEIVED_EMAIL_KEY,\n to: input.requester.email,\n org: input.org,\n requestId: ref.id,\n merge: { 'request.title': subject, 'request.message': body, 'request.due': due },\n fallback: {\n subject: `We have your request: ${subject}`,\n text: `We received “${subject}” and will have it done by ${due}.\\n\\n${body}`,\n },\n })\n await recordEmail(firestore, ref.collection(SITE_CARE_HISTORY_COLLECTION), result, 'the request receipt', nowOf(deps), ref.id)\n return { ticketId: ref.id, dueAtMs }\n}\n\n/**\n * Adds a reply that arrived by email to its request's thread. The sender\n * must be a member of the request's workspace.\n */\nexport async function appendSiteCareReply(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; from: SiteCareActor; body: string; dedupeKey?: string | null },\n deps: SiteCareDeps = {},\n): Promise<{ appended: boolean }> {\n const snapshot = await ticketRef(firestore, input.ticketId).get()\n if (!snapshot.exists) return { appended: false }\n const ticket = loadedTicket(snapshot)\n const body = String(input.body ?? '').trim().slice(0, SITE_CARE_BODY_MAX)\n if (!body) return { appended: false }\n const nowMs = nowOf(deps)\n const now = FieldValue.serverTimestamp()\n const messageRef = input.dedupeKey\n ? ticket.ref.collection('messages').doc(siteCareMessageDocId('mail', input.dedupeKey))\n : ticket.ref.collection('messages').doc(createResourceUid())\n if (input.dedupeKey && (await messageRef.get()).exists) return { appended: false }\n const batch = firestore.batch()\n batch.create(messageRef, {\n authorId: input.from.uid,\n authorEmail: input.from.email,\n staff: false,\n body,\n source: 'email',\n createdAt: now,\n })\n batch.update(ticket.ref, { status: 'open', updatedAt: now })\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.from,\n kind: 'request.replied',\n summary: `${input.from.email ?? 'The owner'} replied by email.`,\n subjectId: input.ticketId,\n }),\n )\n await batch.commit()\n await notifyStaff({\n type: 'support.ticketReply',\n title: `Site Care reply: ${ticket.subject}`,\n body: `${input.from.email ?? 'The owner'} replied by email on “${ticket.subject.slice(0, 120)}” for workspace ${ticket.orgId}.`,\n link: `/admin/support?ticketId=${input.ticketId}`,\n orgId: ticket.orgId,\n })\n return { appended: true }\n}\n\n// ── Timer ───────────────────────────────────────────────────────────────────\n\n/**\n * Starts the request's timer the first time staff open it. A second open,\n * a reload or another staff member opening it changes nothing.\n */\nexport async function startSiteCareTimer(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareRequest> {\n return firestore.runTransaction(async (tx) => {\n const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)))\n if (ticket.request.state !== 'open' || ticket.request.timerStartedAtMs) return ticket.request\n const nowMs = nowOf(deps)\n const request: SiteCareRequest = {\n ...ticket.request,\n timerStartedAtMs: nowMs,\n timerStartedByUid: input.actor.uid,\n }\n tx.update(ticket.ref, { siteCare: request, updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n tx,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'timer.started',\n summary: 'Started work.',\n after: { timerStartedAtMs: nowMs },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, 'timer.started'),\n )\n return request\n })\n}\n\n// ── Moving to another workspace ─────────────────────────────────────────────\n\n/** The candidates recorded for a request, or none. */\nexport async function readSiteCareCandidatesFor(\n firestore: FirebaseFirestore.Firestore,\n ticketId: string,\n): Promise<SiteCareWorkspaceCandidate[]> {\n const snapshot = await intakeRef(firestore, ticketId).get()\n return readSiteCareCandidates(snapshot.get('candidates'))\n}\n\nexport interface MoveSiteCareResult {\n request: SiteCareRequest\n fromOrgId: string\n orgId: string\n}\n\n/**\n * Moves an open request to another Site Care workspace its sender belongs\n * to (AGL-4031): an emailed request from a sender in several is filed on a\n * default one, and staff move it when it belongs to another.\n *\n * Refused for a closed request, one with a charge or an owner's approval on\n * it ({@link siteCareMoveBlockedReason}), and for any workspace that is not\n * one of the candidates recorded at intake, no longer has Site Care, or no\n * longer has the sender as a member.\n *\n * What moves is everything the request holds against a workspace: the\n * ticket's `orgId` and plan, and its month key (`siteCareOrgMonth`), which\n * is what puts a request in a workspace's month. A month's totals are not\n * stored: they are read from the requests that carry its key, and an open\n * request has logged no minutes yet (they are logged at close), so changing\n * the key in this one write takes it out of the old workspace's month and\n * into the new one's at once. A site it named is cleared, since that site\n * is the old workspace's. The `request.moved` row and the staff audit row\n * commit in the same transaction; nothing earlier is rewritten.\n */\nexport async function moveSiteCareRequest(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor; orgId: unknown },\n deps: SiteCareDeps = {},\n): Promise<MoveSiteCareResult> {\n const targetOrgId = typeof input.orgId === 'string' ? input.orgId.trim() : ''\n if (!targetOrgId) throw new SiteCareError('Choose the workspace to move it to.', 400)\n const target = await readSiteCareOrg(firestore, targetOrgId)\n if (!orgHasSiteCare(target)) {\n throw new SiteCareError('That workspace does not have Site Care, so the request cannot move there.', 409)\n }\n const nowMs = nowOf(deps)\n return firestore.runTransaction(async (tx) => {\n const [ticketSnap, intakeSnap] = await Promise.all([\n tx.get(ticketRef(firestore, input.ticketId)),\n tx.get(intakeRef(firestore, input.ticketId)),\n ])\n const ticket = loadedTicket(ticketSnap)\n const candidates = readSiteCareCandidates(intakeSnap.get('candidates'))\n const others = otherSiteCareCandidates(candidates, ticket.orgId)\n const blocked = siteCareMoveBlockedReason(ticket.request, others)\n if (blocked) throw new SiteCareError(blocked, 409)\n const candidate = others.find((other) => other.orgId === targetOrgId)\n if (!candidate) {\n throw new SiteCareError(\n targetOrgId === ticket.orgId\n ? 'The request is already on that workspace.'\n : 'The sender is not recorded as a member of that workspace, so the request cannot move there.',\n 409,\n )\n }\n const member = await tx.get(firestore.collection('orgs').doc(targetOrgId).collection('members').doc(candidate.uid))\n if (!member.exists) {\n throw new SiteCareError('The sender is no longer a member of that workspace, so the request cannot move there.', 409)\n }\n const fromOrgId = ticket.orgId\n const toName = String(target?.['name'] ?? '') || candidate.name\n const request: SiteCareRequest = { ...ticket.request, hostId: null }\n tx.update(ticket.ref, {\n orgId: targetOrgId,\n plan: resolveEffectivePlan(target as never),\n siteCare: request,\n siteCareOrgMonth: siteCareOrgMonth(targetOrgId, request.month),\n updatedAt: FieldValue.serverTimestamp(),\n })\n appendHistoryRow(\n tx,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'request.moved',\n // The new workspace's statement and export read this row, so it\n // names only that workspace; the one it left is an id in `before`.\n summary: `Moved to ${toName}, the workspace it belongs to.`,\n before: { orgId: fromOrgId, hostId: ticket.request.hostId },\n after: { orgId: targetOrgId, hostId: null, month: request.month },\n subjectId: input.ticketId,\n }),\n requestAudit(targetOrgId, input.ticketId, 'request.moved'),\n )\n return { request, fromOrgId, orgId: targetOrgId }\n })\n}\n\n// ── Allocation against the month ────────────────────────────────────────────\n\ninterface MonthContext {\n goodwillMinutes: number\n /** Included minutes the month's OTHER closed requests used. */\n otherIncludedUsed: number\n /** The month's requests as the statement reads them, this one excluded. */\n others: ReturnType<typeof siteCareStatementRequest>[]\n}\n\nasync function readMonthContext(\n reader: Pick<FirebaseFirestore.Transaction, 'get'> | null,\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n month: string,\n excludeTicketId: string,\n): Promise<MonthContext> {\n const query = firestore.collection(TICKETS).where('siteCareOrgMonth', '==', siteCareOrgMonth(orgId, month))\n const [monthSnap, requests] = reader\n ? await Promise.all([reader.get(monthRef(firestore, orgId, month)), reader.get(query)])\n : await Promise.all([monthRef(firestore, orgId, month).get(), query.get()])\n const others = requests.docs\n .filter((doc) => doc.id !== excludeTicketId)\n .map((doc) =>\n siteCareStatementRequest(doc.id, String(doc.get('subject') ?? ''), readSiteCareRequest(doc.get('siteCare'))),\n )\n return {\n goodwillMinutes: Number(monthSnap.get('goodwillMinutes') ?? 0) || 0,\n otherIncludedUsed: others\n .filter((r) => r.state === 'closed')\n .reduce((sum, r) => sum + r.includedMinutesUsed, 0),\n others,\n }\n}\n\nfunction statementWith(\n month: string,\n context: MonthContext,\n ticketId: string,\n subject: string,\n request: SiteCareRequest,\n): SiteCareMonthStatement {\n return siteCareMonthStatement({\n month,\n goodwillMinutes: context.goodwillMinutes,\n requests: [...context.others, siteCareStatementRequest(ticketId, subject, request)],\n })\n}\n\n/** Why a close or a correction is blocked, as the staff panel says it. */\nexport function siteCareBlockedMessage(verdict: Extract<SiteCareCloseVerdict, { ok: false }>): string {\n return verdict.reason === 'no-approval'\n ? `This takes the month past the included hour by ${describeHours(verdict.requiredHours)}, and no approval is on file. Ask the owner first, or absorb it.`\n : `This needs ${describeHours(verdict.requiredHours)} of extra time and the owner approved ${describeHours(\n verdict.approvedHours ?? 0,\n )}. Ask the owner first, or absorb it.`\n}\n\n// ── Publish link ────────────────────────────────────────────────────────────\n\n/**\n * The newest publish on any of the workspace's sites since `sinceMs`, from\n * each site's activity log — the change the request shipped.\n */\nexport async function findSiteCarePublish(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n sinceMs: number,\n): Promise<SiteCarePublishLink | null> {\n const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).limit(10).get()\n let best: SiteCarePublishLink | null = null\n for (const host of hosts.docs) {\n const rows = await host.ref\n .collection('activity')\n .where('createdAt', '>=', Timestamp.fromMillis(sinceMs))\n .orderBy('createdAt', 'desc')\n .limit(50)\n .get()\n for (const row of rows.docs) {\n const action = row.get('action')\n if (!isSiteCarePublishAction(action)) continue\n const atMs = (row.get('createdAt') as Timestamp | undefined)?.toMillis?.() ?? 0\n if (!best || atMs > best.atMs) {\n best = {\n hostId: host.id,\n activityId: row.id,\n action: String(action),\n targetName: (row.get('target.name') as string | undefined) ?? null,\n targetId: (row.get('target.id') as string | undefined) ?? null,\n atMs,\n }\n }\n break\n }\n }\n return best\n}\n\n// ── Charges ─────────────────────────────────────────────────────────────────\n\nfunction chargeKey(ticketId: string, seq: number): string {\n return `site-care:${ticketId}:charge:${seq}`\n}\n\nfunction newCharge(input: {\n ticketId: string\n seq: number\n hours: number\n description: string\n nowMs: number\n}): SiteCareCharge {\n return {\n status: 'creating',\n hours: input.hours,\n amountCents: siteCareExtraTimeCents(input.hours),\n description: input.description,\n idempotencyKey: chargeKey(input.ticketId, input.seq),\n invoiceItemId: null,\n invoiceId: null,\n creditNoteId: null,\n refundId: null,\n error: null,\n updatedAtMs: input.nowMs,\n }\n}\n\nfunction chargeRequestedRow(\n ticketId: string,\n charge: SiteCareCharge,\n actor: SiteCareActor,\n nowMs: number,\n): AppendOnlyHistoryRow {\n return historyRow({\n atMs: nowMs,\n by: actor,\n kind: 'charge.requested',\n summary: `Adding ${describeHours(charge.hours)} of extra time (${formatSiteCareUsd(charge.amountCents)}) to the next invoice.`,\n after: { hours: charge.hours, amountCents: charge.amountCents, idempotencyKey: charge.idempotencyKey },\n subjectId: ticketId,\n })\n}\n\n/**\n * Creates the Stripe item for a `creating` (or `failed`) charge and records\n * the outcome. The key is the charge's own, so a retry after a lost\n * response returns the item the first call made rather than a second one.\n */\nasync function settleCharge(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor },\n deps: SiteCareDeps,\n): Promise<SiteCareCharge | null> {\n const snapshot = await ticketRef(firestore, input.ticketId).get()\n const ticket = loadedTicket(snapshot)\n const charge = ticket.request.charge\n if (!charge || (charge.status !== 'creating' && charge.status !== 'failed')) return charge\n const billing = await readOrgBilling(ticket.orgId)\n const customerId = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '')\n const subscription = await siteCareSubscriptionId(customerId, deps.stripe)\n const product = subscription.ok ? await siteCareExtraTimeProduct(deps.stripe) : null\n const created =\n subscription.ok && product?.ok\n ? await createExtraTimeItem(\n {\n customerId,\n subscriptionId: subscription.subscriptionId,\n productId: product.productId,\n hours: charge.hours,\n description: charge.description,\n metadata: {\n siteCareRequestId: input.ticketId,\n orgId: ticket.orgId,\n month: ticket.request.month,\n },\n idempotencyKey: charge.idempotencyKey,\n },\n deps.stripe,\n )\n : null\n const nowMs = nowOf(deps)\n const error = subscription.ok === false\n ? subscription.error\n : product && product.ok === false\n ? product.error\n : created && created.ok === false\n ? created.error\n : null\n const next: SiteCareCharge =\n created && created.ok\n ? { ...charge, status: 'pending', invoiceItemId: created.invoiceItemId, error: null, updatedAtMs: nowMs }\n : { ...charge, status: 'failed', error: error ?? 'Unknown failure', updatedAtMs: nowMs }\n const batch = firestore.batch()\n batch.update(ticket.ref, { 'siteCare.charge': next, updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: next.status === 'pending' ? 'charge.created' : 'charge.failed',\n summary:\n next.status === 'pending'\n ? `Added ${describeHours(next.hours)} of extra time (${formatSiteCareUsd(next.amountCents)}) to the next invoice.`\n : `The extra time could not be added to the invoice: ${next.error}`,\n after: { status: next.status, invoiceItemId: next.invoiceItemId, error: next.error },\n stripe:\n next.status === 'pending' && next.invoiceItemId\n ? { object: 'invoiceitem', id: next.invoiceItemId, amountCents: next.amountCents }\n : null,\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, next.status === 'pending' ? 'charge.created' : 'charge.failed'),\n )\n await batch.commit()\n return next\n}\n\n/** Re-runs a charge that failed, or whose result never landed. */\nexport async function retrySiteCareCharge(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareCharge | null> {\n const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n const status = ticket.request.charge?.status\n if (status !== 'failed' && status !== 'creating') {\n throw new SiteCareError('There is no charge waiting to be retried on this request.', 409)\n }\n return settleCharge(firestore, input, deps)\n}\n\n// ── Close ───────────────────────────────────────────────────────────────────\n\nexport interface CloseSiteCareInput {\n ticketId: string\n actor: SiteCareActor\n minutes: unknown\n absorb?: boolean\n}\n\nexport interface CloseSiteCareResult {\n request: SiteCareRequest\n statement: SiteCareMonthStatement\n}\n\n/**\n * Closes a request with one number. Refuses with the verdict when the\n * minutes take the month past the included hour and no approval covers it\n * — the panel then offers \"Ask the owner first\" and \"Absorb it\".\n */\nexport async function closeSiteCareRequest(\n firestore: FirebaseFirestore.Firestore,\n input: CloseSiteCareInput,\n deps: SiteCareDeps = {},\n): Promise<CloseSiteCareResult> {\n const minutes = readSiteCareMinutes(input.minutes)\n if (minutes === null) throw new SiteCareError('Enter the minutes this took.', 400)\n const nowMs = nowOf(deps)\n const month = siteCareMonthKey(nowMs)\n const first = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n const publish = await findSiteCarePublish(\n firestore,\n first.orgId,\n first.request.timerStartedAtMs ?? (first.data['createdAt'] as Timestamp | undefined)?.toMillis?.() ?? nowMs,\n ).catch(() => null)\n\n const result = await firestore.runTransaction(async (tx) => {\n const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)))\n if (ticket.request.state === 'closed') throw new SiteCareError('This request is already closed. Correct its minutes instead.', 409)\n const context = await readMonthContext(tx, firestore, ticket.orgId, month, input.ticketId)\n const allocation = allocateSiteCareMinutes({\n minutes,\n otherIncludedUsed: context.otherIncludedUsed,\n goodwillMinutes: context.goodwillMinutes,\n })\n const verdict = siteCareCloseVerdict({\n requiredHours: allocation.requiredHours,\n approval: ticket.request.approval,\n absorb: input.absorb === true,\n })\n if (verdict.ok === false) {\n throw new SiteCareError(siteCareBlockedMessage(verdict), 409, { blocked: verdict, allocation })\n }\n const timerMinutes = ticket.request.timerStartedAtMs\n ? Math.round((nowMs - ticket.request.timerStartedAtMs) / 60_000)\n : null\n let request: SiteCareRequest = {\n ...ticket.request,\n state: 'closed',\n month,\n closedAtMs: nowMs,\n minutesLogged: minutes,\n timerMinutes,\n countedMinutes: allocation.countedMinutes,\n includedMinutesUsed: allocation.includedMinutesUsed,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n absorbed: verdict.absorbed,\n publish,\n }\n let charge: SiteCareCharge | null = null\n if (verdict.billedHours > 0) {\n const statement = statementWith(month, context, input.ticketId, ticket.subject, request)\n const seq = request.chargeSeq + 1\n charge = newCharge({\n ticketId: input.ticketId,\n seq,\n hours: verdict.billedHours,\n description: siteCareExtraTimeDescription({\n title: ticket.subject,\n minutesLogged: minutes,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n approvedHours: request.approval?.hours ?? null,\n statement,\n }),\n nowMs,\n })\n request = { ...request, charge, chargeSeq: seq }\n }\n const statement = statementWith(month, context, input.ticketId, ticket.subject, request)\n tx.update(ticket.ref, {\n siteCare: request,\n siteCareMonth: month,\n siteCareOrgMonth: siteCareOrgMonth(ticket.orgId, month),\n status: 'closed',\n // The promise was \"done\", and it is: the SLA sweep stops here even if\n // the owner later replies and reopens the thread.\n ...(ticket.data['firstRespondedAt'] ? {} : { firstRespondedAt: FieldValue.serverTimestamp() }),\n updatedAt: FieldValue.serverTimestamp(),\n })\n const history = ticketHistory(firestore, input.ticketId)\n if (timerMinutes !== null) {\n appendHistoryRow(\n tx,\n firestore,\n history,\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'timer.stopped',\n summary: `Stopped work after ${formatSiteCareMinutes(timerMinutes)} on the timer.`,\n after: { timerMinutes },\n subjectId: input.ticketId,\n }),\n )\n }\n appendHistoryRow(\n tx,\n firestore,\n history,\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'request.closed',\n summary:\n `Finished “${ticket.subject}”: ${formatSiteCareMinutes(minutes)} of work, ` +\n `${allocation.includedMinutesUsed} included minutes used` +\n (allocation.overMinutes > 0\n ? verdict.absorbed\n ? `, ${formatSiteCareMinutes(allocation.overMinutes)} past the included hour absorbed at no charge.`\n : `, ${describeHours(verdict.billedHours)} of extra time billed.`\n : '.'),\n after: {\n minutesLogged: minutes,\n timerMinutes,\n countedMinutes: allocation.countedMinutes,\n includedMinutesUsed: allocation.includedMinutesUsed,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n absorbed: verdict.absorbed,\n publishActivityId: publish?.activityId ?? null,\n },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, verdict.absorbed ? 'request.closedAbsorbed' : 'request.closed'),\n )\n if (charge) {\n appendHistoryRow(tx, firestore, history, chargeRequestedRow(input.ticketId, charge, input.actor, nowMs))\n }\n return { ticket, request, statement }\n })\n\n let request = result.request\n if (request.charge) {\n const settled = await settleCharge(firestore, { ticketId: input.ticketId, actor: input.actor }, deps)\n request = { ...request, charge: settled }\n }\n await emailDoneSummary(firestore, result.ticket, request, result.statement, deps)\n return { request, statement: result.statement }\n}\n\nfunction billingSentence(request: SiteCareRequest): string {\n if (request.overMinutes <= 0) return 'No extra charge: this fit in your included hour.'\n if (request.absorbed || request.billedHours === 0) {\n return 'It ran past your included hour, and we did not charge for the extra time.'\n }\n const status = request.charge?.status\n if (status === 'failed') {\n return `It ran past your included hour; we will add ${describeHours(request.billedHours)} of extra time to your next invoice.`\n }\n return `${describeHours(request.billedHours)} of extra time (${formatSiteCareUsd(\n siteCareExtraTimeCents(request.billedHours),\n )}, at $${SITE_CARE_EXTRA_HOUR_USD} an hour, the time you approved) will be on your next invoice.`\n}\n\nfunction minutesLeftSentence(statement: SiteCareMonthStatement): string {\n return `${formatSiteCareMinutes(statement.minutesLeft)} of this month’s included time`\n}\n\nasync function emailDoneSummary(\n firestore: FirebaseFirestore.Firestore,\n ticket: LoadedTicket,\n request: SiteCareRequest,\n statement: SiteCareMonthStatement,\n deps: SiteCareDeps,\n): Promise<void> {\n const org = await readSiteCareOrg(firestore, ticket.orgId)\n const to = (await siteCareOwnerEmail(firestore, ticket.orgId, org)) ?? request.requesterEmail\n const changes =\n siteCarePublishSentence(request.publish, formatSiteCareDate) ?? `We made the change you asked for: “${ticket.subject}”.`\n const result = await emailOf(deps)({\n key: SITE_CARE_REQUEST_DONE_EMAIL_KEY,\n to,\n org,\n requestId: ticket.ref.id,\n merge: {\n 'request.title': ticket.subject,\n 'request.changes': changes,\n 'request.minutes': formatSiteCareMinutes(request.minutesLogged ?? 0),\n 'month.minutesLeft': minutesLeftSentence(statement),\n 'request.billing': billingSentence(request),\n },\n fallback: {\n subject: `Done: ${ticket.subject}`,\n text:\n `We finished your request “${ticket.subject}”. ${billingSentence(request)}\\n\\n` +\n `What changed: ${changes}\\nTime: ${formatSiteCareMinutes(request.minutesLogged ?? 0)}\\n` +\n `Left this month: ${minutesLeftSentence(statement)}`,\n },\n })\n await recordEmail(firestore, ticketHistory(firestore, ticket.ref.id), result, 'the summary', nowOf(deps), ticket.ref.id)\n}\n\n// ── Approval ────────────────────────────────────────────────────────────────\n\n/**\n * Records — or corrects — how the owner said yes to extra time, and emails\n * them the confirmation that is the written record.\n */\nexport async function recordSiteCareApproval(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor & { uid: string }; approval: Record<string, unknown> },\n deps: SiteCareDeps = {},\n): Promise<OwnerApprovalRecord> {\n const nowMs = nowOf(deps)\n const { ticket, record, previous } = await firestore.runTransaction(async (tx) => {\n const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)))\n const previous = ticket.request.approval\n const read = readOwnerApprovalInput(input.approval, {\n rateUsd: SITE_CARE_EXTRA_HOUR_USD,\n nowMs,\n by: { uid: input.actor.uid, email: input.actor.email },\n previous,\n })\n if (read.ok === false) throw new SiteCareError(read.error, 400)\n const record = read.record\n tx.update(ticket.ref, { 'siteCare.approval': record, updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n tx,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: previous ? 'approval.corrected' : 'approval.recorded',\n summary: previous\n ? `Corrected the approval: ${describeHours(previous.hours)} → ${describeHours(record.hours)}, ${record.channel}.`\n : ownerApprovalSentence(record, ticket.subject, formatSiteCareDate),\n reason: record.correctionReason,\n before: previous ? { ...previous } : null,\n after: { ...record },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, previous ? 'approval.corrected' : 'approval.recorded'),\n )\n return { ticket, record, previous }\n })\n const org = await readSiteCareOrg(firestore, ticket.orgId)\n const to = await siteCareOwnerEmail(firestore, ticket.orgId, org)\n const sentence = ownerApprovalSentence(record, ticket.subject, formatSiteCareDate)\n const correction = previous\n ? `This corrects the earlier record (${describeHours(previous.hours)}): ${record.correctionReason}`\n : ''\n const heading = previous ? 'Corrected: your approval of extra time' : 'You approved extra time'\n const result = await emailOf(deps)({\n key: SITE_CARE_APPROVAL_EMAIL_KEY,\n to,\n org,\n requestId: input.ticketId,\n merge: {\n 'request.title': ticket.subject,\n 'approval.heading': heading,\n 'approval.sentence': sentence,\n 'approval.correction': correction,\n },\n fallback: {\n subject: `${heading}: extra time for ${ticket.subject}`,\n text: `${sentence} ${correction}\\n\\nIf this is not what you agreed to, reply to this email.`,\n },\n })\n await recordEmail(firestore, ticketHistory(firestore, input.ticketId), result, 'the approval confirmation', nowOf(deps), input.ticketId)\n return record\n}\n\n// ── Corrections ─────────────────────────────────────────────────────────────\n\n/**\n * Whether the request's minutes may still change: until the subscription\n * invoice that carries (or would carry) them finalizes.\n */\nasync function assertMinutesEditable(\n orgId: string,\n request: SiteCareRequest,\n deps: SiteCareDeps,\n): Promise<void> {\n const charge = request.charge\n if (charge && charge.status === 'creating') {\n throw new SiteCareError('A charge on this request is still being created. Retry it first.', 409)\n }\n if (charge && charge.status === 'pending' && charge.invoiceItemId) {\n const read = await readExtraTimeItem(charge.invoiceItemId, deps.stripe)\n if (read.ok === false) throw new SiteCareError(read.error, 502)\n if (!extraTimeItemIsEditable(read.state.stage) && read.state.stage !== 'deleted') {\n throw new SiteCareError(\n 'The invoice with this extra time has been finalized, so its minutes are locked. Void, credit or refund the charge instead.',\n 409,\n )\n }\n return\n }\n const billing = await readOrgBilling(orgId)\n const customerId = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '')\n if (!customerId) return\n const subscription = await siteCareSubscriptionId(customerId, deps.stripe)\n if (subscription.ok === false) return\n const finalized = await subscriptionInvoiceFinalizedSince(\n { subscriptionId: subscription.subscriptionId, sinceMs: request.closedAtMs ?? 0 },\n deps.stripe,\n )\n if (finalized.ok === false) throw new SiteCareError(finalized.error, 502)\n if (finalized.finalized) {\n throw new SiteCareError(\n 'The invoice for this request’s month has been finalized, so its minutes are locked.',\n 409,\n )\n }\n}\n\n/**\n * Changes the minutes on a closed request, with a reason, and recomputes its\n * share of the included hour and its extra time: a pending item is corrected\n * or deleted, a new one is added only under an approval. The owner gets a\n * \"corrected\" summary with the before and after.\n */\nexport async function correctSiteCareMinutes(\n firestore: FirebaseFirestore.Firestore,\n input: {\n ticketId: string\n actor: SiteCareActor\n minutes: unknown\n reason: unknown\n absorb?: boolean\n },\n deps: SiteCareDeps = {},\n): Promise<CloseSiteCareResult> {\n const minutes = readSiteCareMinutes(input.minutes)\n if (minutes === null) throw new SiteCareError('Enter the corrected minutes.', 400)\n const reason = requireHistoryReason(input.reason)\n if (reason.ok === false) throw new SiteCareError(reason.error, 400)\n const before = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n if (before.request.state !== 'closed') {\n throw new SiteCareError('Only a finished request’s minutes are corrected; close it instead.', 409)\n }\n await assertMinutesEditable(before.orgId, before.request, deps)\n const nowMs = nowOf(deps)\n\n const result = await firestore.runTransaction(async (tx) => {\n const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)))\n const old = ticket.request\n if (old.charge?.status === 'creating') {\n throw new SiteCareError('A charge on this request is still being created. Retry it first.', 409)\n }\n const month = old.month\n const context = await readMonthContext(tx, firestore, ticket.orgId, month, input.ticketId)\n const allocation = allocateSiteCareMinutes({\n minutes,\n otherIncludedUsed: context.otherIncludedUsed,\n goodwillMinutes: context.goodwillMinutes,\n })\n const verdict = siteCareCloseVerdict({\n requiredHours: allocation.requiredHours,\n approval: old.approval,\n absorb: input.absorb ?? old.absorbed,\n })\n if (verdict.ok === false) {\n throw new SiteCareError(siteCareBlockedMessage(verdict), 409, { blocked: verdict, allocation })\n }\n let request: SiteCareRequest = {\n ...old,\n minutesLogged: minutes,\n countedMinutes: allocation.countedMinutes,\n includedMinutesUsed: allocation.includedMinutesUsed,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n absorbed: verdict.absorbed,\n }\n const live = old.charge && old.charge.status === 'pending' ? old.charge : null\n const statementNow = statementWith(month, context, input.ticketId, ticket.subject, request)\n const description = siteCareExtraTimeDescription({\n title: ticket.subject,\n minutesLogged: minutes,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n approvedHours: request.approval?.hours ?? null,\n statement: statementNow,\n })\n // What the Stripe side must do, decided here and done after the commit.\n let stripeStep: 'none' | 'update' | 'delete' | 'create' = 'none'\n if (live && verdict.billedHours === 0) stripeStep = 'delete'\n else if (live && (live.hours !== verdict.billedHours || live.description !== description)) stripeStep = 'update'\n else if (!live && verdict.billedHours > 0) stripeStep = 'create'\n if (stripeStep === 'create') {\n const seq = request.chargeSeq + 1\n request = {\n ...request,\n chargeSeq: seq,\n charge: newCharge({ ticketId: input.ticketId, seq, hours: verdict.billedHours, description, nowMs }),\n }\n } else if (old.charge?.status === 'failed' && verdict.billedHours === 0) {\n // A charge Stripe refused never made an item, and the corrected time\n // no longer owes one: it is settled as voided, so the reconciliation\n // stops reporting hours that are no longer owed.\n request = { ...request, charge: { ...old.charge, status: 'voided', updatedAtMs: nowMs } }\n }\n tx.update(ticket.ref, { siteCare: request, updatedAt: FieldValue.serverTimestamp() })\n const history = ticketHistory(firestore, input.ticketId)\n // The correction's own row id keys its Stripe call: one correction, one\n // key, so a retried call cannot apply it twice (and a later correction,\n // with its own row, is never mistaken for a replay of this one).\n const correctionRef = appendHistoryRow(\n tx,\n firestore,\n history,\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'minutes.corrected',\n summary: `Corrected the time from ${formatSiteCareMinutes(old.minutesLogged ?? 0)} to ${formatSiteCareMinutes(minutes)}.`,\n reason: reason.reason,\n before: {\n minutesLogged: old.minutesLogged,\n countedMinutes: old.countedMinutes,\n includedMinutesUsed: old.includedMinutesUsed,\n overMinutes: old.overMinutes,\n billedHours: old.billedHours,\n },\n after: {\n minutesLogged: minutes,\n countedMinutes: allocation.countedMinutes,\n includedMinutesUsed: allocation.includedMinutesUsed,\n overMinutes: allocation.overMinutes,\n billedHours: verdict.billedHours,\n chargeStatus: request.charge?.status ?? null,\n },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, 'minutes.corrected'),\n )\n if (stripeStep === 'create' && request.charge) {\n appendHistoryRow(tx, firestore, history, chargeRequestedRow(input.ticketId, request.charge, input.actor, nowMs))\n }\n return {\n ticket,\n old,\n request,\n statement: statementNow,\n stripeStep,\n live,\n description,\n correctionId: correctionRef.id,\n }\n })\n\n let request = result.request\n if (result.stripeStep === 'create') {\n const settled = await settleCharge(firestore, { ticketId: input.ticketId, actor: input.actor }, deps)\n request = { ...request, charge: settled }\n } else if ((result.stripeStep === 'update' || result.stripeStep === 'delete') && result.live?.invoiceItemId) {\n request = await correctLiveCharge(\n firestore,\n {\n ticket: result.ticket,\n request,\n live: result.live,\n step: result.stripeStep,\n hours: request.billedHours,\n description: result.description,\n actor: input.actor,\n reason: reason.reason,\n correctionId: result.correctionId,\n },\n deps,\n )\n }\n\n const org = await readSiteCareOrg(firestore, result.ticket.orgId)\n const to = (await siteCareOwnerEmail(firestore, result.ticket.orgId, org)) ?? request.requesterEmail\n const emailed = await emailOf(deps)({\n key: SITE_CARE_REQUEST_CORRECTED_EMAIL_KEY,\n to,\n org,\n requestId: input.ticketId,\n merge: {\n 'request.title': result.ticket.subject,\n 'correction.before': formatSiteCareMinutes(result.old.minutesLogged ?? 0),\n 'correction.after': formatSiteCareMinutes(minutes),\n 'correction.reason': reason.reason,\n 'request.billing': billingSentence(request),\n 'month.minutesLeft': minutesLeftSentence(result.statement),\n },\n fallback: {\n subject: `Corrected: the time on ${result.ticket.subject}`,\n text:\n `We corrected the time on “${result.ticket.subject}” from ${formatSiteCareMinutes(result.old.minutesLogged ?? 0)} ` +\n `to ${formatSiteCareMinutes(minutes)}. ${reason.reason} ${billingSentence(request)}`,\n },\n })\n await recordEmail(firestore, ticketHistory(firestore, input.ticketId), emailed, 'the corrected summary', nowOf(deps), input.ticketId)\n return { request, statement: result.statement }\n}\n\n/**\n * The idempotency key of a correction's Stripe call: the charge's own key\n * and the id of the history row that records the correction. A clock would\n * make every retry a new request to Stripe; the row id makes it the same one.\n */\nexport function siteCareCorrectionKey(chargeKey: string, correctionId: string): string {\n return `${chargeKey}:fix:${correctionId}`\n}\n\n/** Updates or deletes a pending item after a correction, with its row. */\nasync function correctLiveCharge(\n firestore: FirebaseFirestore.Firestore,\n input: {\n ticket: LoadedTicket\n request: SiteCareRequest\n live: SiteCareCharge\n step: 'update' | 'delete'\n hours: number\n description: string\n actor: SiteCareActor\n reason: string\n /** The `minutes.corrected` history row this Stripe call carries out. */\n correctionId: string\n },\n deps: SiteCareDeps,\n): Promise<SiteCareRequest> {\n const itemId = String(input.live.invoiceItemId)\n const nowMs = nowOf(deps)\n const seqKey = siteCareCorrectionKey(input.live.idempotencyKey, input.correctionId)\n const outcome =\n input.step === 'delete'\n ? await deleteExtraTimeItem(itemId, deps.stripe)\n : await updateExtraTimeItem(\n { invoiceItemId: itemId, hours: input.hours, description: input.description, idempotencyKey: seqKey },\n deps.stripe,\n )\n const outcomeError = outcome.ok === false ? outcome.error : null\n const charge: SiteCareCharge = outcomeError === null\n ? input.step === 'delete'\n ? { ...input.live, status: 'voided', updatedAtMs: nowMs, error: null }\n : {\n ...input.live,\n hours: input.hours,\n amountCents: siteCareExtraTimeCents(input.hours),\n description: input.description,\n updatedAtMs: nowMs,\n error: null,\n }\n : { ...input.live, error: outcomeError, updatedAtMs: nowMs }\n const batch = firestore.batch()\n batch.update(input.ticket.ref, { 'siteCare.charge': charge, updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticket.ref.id),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: outcomeError !== null ? 'charge.correctionFailed' : input.step === 'delete' ? 'charge.voided' : 'charge.updated',\n summary: outcomeError !== null\n ? `The charge could not be corrected in Stripe: ${outcomeError}`\n : input.step === 'delete'\n ? `Removed the extra-time charge (${formatSiteCareUsd(input.live.amountCents)}) before it was invoiced.`\n : `Changed the extra-time charge from ${describeHours(input.live.hours)} to ${describeHours(input.hours)}.`,\n reason: input.reason,\n before: { hours: input.live.hours, amountCents: input.live.amountCents, description: input.live.description },\n after: { hours: charge.hours, amountCents: charge.amountCents, status: charge.status, error: charge.error },\n stripe: { object: 'invoiceitem', id: itemId, amountCents: charge.amountCents },\n subjectId: input.ticket.ref.id,\n }),\n requestAudit(\n input.ticket.orgId,\n input.ticket.ref.id,\n outcomeError !== null ? 'charge.correctionFailed' : input.step === 'delete' ? 'charge.voided' : 'charge.updated',\n ),\n )\n await batch.commit()\n return { ...input.request, charge }\n}\n\n/**\n * Voids, credits or refunds a request's extra-time charge, with a reason —\n * deleted before its invoice finalizes, credited after, refunded once paid.\n * `absorb` also records that the request is not charged for its extra time.\n */\nexport async function reverseSiteCareCharge(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor; reason: unknown; absorb?: boolean },\n deps: SiteCareDeps = {},\n): Promise<SiteCareCharge> {\n const reason = requireHistoryReason(input.reason)\n if (reason.ok === false) throw new SiteCareError(reason.error, 400)\n const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n const charge = ticket.request.charge\n if (!charge || !SITE_CARE_LIVE_CHARGE_STATUSES.includes(charge.status) || !charge.invoiceItemId) {\n throw new SiteCareError('There is no extra-time charge on this request to reverse.', 409)\n }\n const read = await readExtraTimeItem(charge.invoiceItemId, deps.stripe)\n if (read.ok === false) throw new SiteCareError(read.error, 502)\n const stage = read.state.stage\n if (stage === 'void' || stage === 'uncollectible') {\n throw new SiteCareError(`The invoice with this charge is ${stage}; there is nothing to reverse.`, 409)\n }\n const nowMs = nowOf(deps)\n const intended = stage === 'paid' ? 'refund' : stage === 'open' ? 'credit' : 'void'\n // The intent first, so a call whose answer is lost still left a row.\n await commitHistoryRow(\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: `charge.${intended}Requested`,\n summary: `Reversing the extra-time charge (${formatSiteCareUsd(charge.amountCents)}): ${intended}.`,\n reason: reason.reason,\n before: { status: charge.status, stage },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, `charge.${intended}Requested`),\n )\n let next: SiteCareCharge\n let stripeRef: HistoryStripeRef\n if (intended === 'void') {\n const deleted = stage === 'deleted' ? ({ ok: true, deleted: true } as const) : await deleteExtraTimeItem(charge.invoiceItemId, deps.stripe)\n if (deleted.ok === false) throw new SiteCareError(deleted.error, 502)\n next = { ...charge, status: 'voided', updatedAtMs: nowOf(deps), error: null }\n stripeRef = { object: 'invoiceitem', id: charge.invoiceItemId, amountCents: charge.amountCents }\n } else {\n const credited = await creditExtraTimeItem(\n {\n invoiceId: String(read.state.invoiceId),\n invoiceItemId: charge.invoiceItemId,\n refund: intended === 'refund',\n memo: `Site Care: ${reason.reason}`,\n metadata: { siteCareRequestId: input.ticketId, orgId: ticket.orgId },\n idempotencyKey: `${charge.idempotencyKey}:${intended}`,\n },\n deps.stripe,\n )\n if (credited.ok === false) throw new SiteCareError(credited.error, 502)\n next = {\n ...charge,\n status: intended === 'refund' ? 'refunded' : 'credited',\n invoiceId: read.state.invoiceId,\n creditNoteId: credited.creditNoteId,\n refundId: credited.refundId,\n updatedAtMs: nowOf(deps),\n error: null,\n }\n stripeRef = { object: 'credit_note', id: credited.creditNoteId, amountCents: credited.amountCents }\n }\n const batch = firestore.batch()\n batch.update(ticket.ref, {\n 'siteCare.charge': next,\n ...(input.absorb ? { 'siteCare.absorbed': true, 'siteCare.billedHours': 0 } : {}),\n updatedAt: FieldValue.serverTimestamp(),\n })\n const doneKind = next.status === 'voided' ? 'charge.voided' : next.status === 'refunded' ? 'charge.refunded' : 'charge.credited'\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowOf(deps),\n by: input.actor,\n kind: doneKind,\n summary:\n next.status === 'voided'\n ? `Removed the extra-time charge (${formatSiteCareUsd(charge.amountCents)}); it will not be invoiced.`\n : next.status === 'refunded'\n ? `Refunded the extra-time charge (${formatSiteCareUsd(charge.amountCents)} plus its tax).`\n : `Credited the extra-time charge (${formatSiteCareUsd(charge.amountCents)} plus its tax) back on the invoice.`,\n reason: reason.reason,\n before: { status: charge.status },\n after: { status: next.status, creditNoteId: next.creditNoteId, refundId: next.refundId, absorbed: input.absorb === true },\n stripe: stripeRef,\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, doneKind),\n )\n await batch.commit()\n\n const org = await readSiteCareOrg(firestore, ticket.orgId)\n const to = await siteCareOwnerEmail(firestore, ticket.orgId, org)\n const heading =\n next.status === 'voided' ? 'Charge removed' : next.status === 'refunded' ? 'Charge refunded' : 'Charge credited'\n const amount = formatSiteCareUsd(charge.amountCents)\n const sentence =\n next.status === 'voided'\n ? `The ${amount} for ${describeHours(charge.hours)} of extra time will not be on your next invoice.`\n : next.status === 'refunded'\n ? `We refunded the ${amount} for ${describeHours(charge.hours)} of extra time, with its tax, to the card it was paid with.`\n : `We credited the ${amount} for ${describeHours(charge.hours)} of extra time, with its tax, on the invoice it was on.`\n const result = await emailOf(deps)({\n key: SITE_CARE_CHARGE_REVERSED_EMAIL_KEY,\n to,\n org,\n requestId: input.ticketId,\n merge: {\n 'request.title': ticket.subject,\n 'charge.heading': heading,\n 'charge.sentence': sentence,\n 'charge.reason': reason.reason,\n },\n fallback: { subject: `${heading}: ${ticket.subject}`, text: `${sentence}\\n\\nWhy: ${reason.reason}` },\n })\n await recordEmail(firestore, ticketHistory(firestore, input.ticketId), result, 'the charge notice', nowOf(deps), input.ticketId)\n return next\n}\n\n// ── Goodwill ────────────────────────────────────────────────────────────────\n\n/** Adds included minutes to a workspace's month, with a reason. */\nexport async function addSiteCareGoodwill(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; month: unknown; minutes: unknown; reason: unknown; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<{ goodwillMinutes: number }> {\n const month = String(input.month ?? '')\n if (!isSiteCareMonthKey(month)) throw new SiteCareError('Choose the month.', 400)\n const minutes = readSiteCareMinutes(input.minutes)\n if (minutes === null) throw new SiteCareError('Enter the goodwill minutes.', 400)\n const reason = requireHistoryReason(input.reason)\n if (reason.ok === false) throw new SiteCareError(reason.error, 400)\n const nowMs = nowOf(deps)\n return firestore.runTransaction(async (tx) => {\n const ref = monthRef(firestore, input.orgId, month)\n const snapshot = await tx.get(ref)\n const before = Number(snapshot.get('goodwillMinutes') ?? 0) || 0\n const after = before + minutes\n tx.set(ref, { orgId: input.orgId, month, goodwillMinutes: after, updatedAt: FieldValue.serverTimestamp() }, { merge: true })\n appendHistoryRow(\n tx,\n firestore,\n monthHistory(firestore, input.orgId, month),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: 'goodwill.added',\n summary: `Added ${formatSiteCareMinutes(minutes)} of included time to this month, at no charge.`,\n reason: reason.reason,\n before: { goodwillMinutes: before },\n after: { goodwillMinutes: after },\n }),\n monthAudit(input.orgId, month, 'goodwill.added'),\n )\n return { goodwillMinutes: after }\n })\n}\n\n// ── The month ───────────────────────────────────────────────────────────────\n\nexport interface SiteCareMonthRequestView {\n ticketId: string\n subject: string\n status: string\n request: SiteCareRequest\n history: Array<AppendOnlyHistoryRow & { $id: string }>\n}\n\nexport interface SiteCareMonthView {\n orgId: string\n month: string\n statement: SiteCareMonthStatement\n goodwillMinutes: number\n requests: SiteCareMonthRequestView[]\n monthHistory: Array<AppendOnlyHistoryRow & { $id: string }>\n}\n\n/** Every request of a workspace's month, each with its history, and the totals. */\nexport async function readSiteCareMonth(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; month: string },\n): Promise<SiteCareMonthView> {\n if (!isSiteCareMonthKey(input.month)) throw new SiteCareError('Choose the month.', 400)\n const [snapshot, monthSnap, monthRows] = await Promise.all([\n firestore\n .collection(TICKETS)\n .where('siteCareOrgMonth', '==', siteCareOrgMonth(input.orgId, input.month))\n .limit(200)\n .get(),\n monthRef(firestore, input.orgId, input.month).get(),\n readHistoryRows(monthHistory(firestore, input.orgId, input.month)),\n ])\n const requests = await Promise.all(\n snapshot.docs.map(async (doc) => ({\n ticketId: doc.id,\n subject: String(doc.get('subject') ?? ''),\n status: String(doc.get('status') ?? ''),\n request: readSiteCareRequest(doc.get('siteCare')) as SiteCareRequest,\n history: await readHistoryRows(doc.ref.collection(SITE_CARE_HISTORY_COLLECTION)),\n })),\n )\n requests.sort((a, b) => (a.request.closedAtMs ?? Infinity) - (b.request.closedAtMs ?? Infinity))\n const goodwillMinutes = Number(monthSnap.get('goodwillMinutes') ?? 0) || 0\n return {\n orgId: input.orgId,\n month: input.month,\n goodwillMinutes,\n statement: siteCareMonthStatement({\n month: input.month,\n goodwillMinutes,\n requests: requests.map((r) => siteCareStatementRequest(r.ticketId, r.subject, r.request)),\n }),\n requests,\n monthHistory: monthRows,\n }\n}\n\n/** One request as the statement lists it, in the owner's words. */\nexport function siteCareStatementLine(view: SiteCareMonthRequestView): string {\n const r = view.request\n if (r.state !== 'closed') return `${view.subject}: in progress`\n const billed =\n r.billedHours > 0\n ? `${describeHours(r.billedHours)} billed (${formatSiteCareUsd(siteCareExtraTimeCents(r.billedHours))}), ${siteCareChargeWords(\n r.charge?.status ?? null,\n ).toLowerCase()}`\n : r.overMinutes > 0\n ? 'extra time not charged'\n : 'included'\n return `${view.subject}: ${formatSiteCareMinutes(r.minutesLogged ?? 0)}, ${billed}`\n}\n\n/** Every recorded row of the month, oldest first, as dated lines. */\nexport function siteCareStatementHistory(view: SiteCareMonthView): string[] {\n const rows = [...view.monthHistory, ...view.requests.flatMap((r) => r.history)].sort((a, b) => a.atMs - b.atMs)\n return rows.map(\n (row) => `${formatSiteCareDate(row.atMs)}: ${row.summary}${row.reason ? ` Why: ${row.reason}` : ''}`,\n )\n}\n\n/** Emails the owner the month's statement, on demand. */\nexport async function sendSiteCareStatement(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; month: string; actor: SiteCareActor },\n deps: SiteCareDeps = {},\n): Promise<SiteCareEmailResult> {\n const view = await readSiteCareMonth(firestore, input)\n const org = await readSiteCareOrg(firestore, input.orgId)\n const to = await siteCareOwnerEmail(firestore, input.orgId, org)\n const summary = siteCareMonthSentence(view.statement)\n const lines = view.requests.map(siteCareStatementLine).join('\\n') || 'No requests this month.'\n const history = siteCareStatementHistory(view).join('\\n') || 'Nothing recorded yet.'\n const result = await emailOf(deps)({\n key: SITE_CARE_STATEMENT_EMAIL_KEY,\n to,\n org,\n requestId: null,\n merge: {\n 'month.label': view.statement.monthLabel,\n 'statement.summary': summary,\n 'statement.lines': lines,\n 'statement.history': history,\n },\n fallback: {\n subject: `Your Site Care statement for ${view.statement.monthLabel}`,\n text: `${summary}\\n\\n${lines}\\n\\nEverything we recorded:\\n${history}`,\n },\n })\n await commitHistoryRow(\n firestore,\n monthHistory(firestore, input.orgId, input.month),\n historyRow({\n atMs: nowOf(deps),\n by: input.actor,\n kind: result.sent ? 'statement.sent' : 'statement.notSent',\n summary: result.sent\n ? `Emailed the ${view.statement.monthLabel} statement to ${result.to}.`\n : `The ${view.statement.monthLabel} statement was not sent (${result.reason ?? 'unknown'}).`,\n after: { to: result.to, sent: result.sent, summary },\n }),\n monthAudit(input.orgId, input.month, result.sent ? 'statement.sent' : 'statement.notSent'),\n )\n return result\n}\n\n// ── The quote reply ─────────────────────────────────────────────────────────\n\n/**\n * \"This one is bigger than Site Care covers, here is the quote\": staff send\n * it from the request; it lands on the thread and in the owner's inbox. The\n * invoice itself is the staff \"Charge for work\" (AGL-3970).\n */\nexport async function sendSiteCareQuote(\n firestore: FirebaseFirestore.Firestore,\n input: { ticketId: string; actor: SiteCareActor; amountUsd: unknown; scope: unknown },\n deps: SiteCareDeps = {},\n): Promise<SiteCareEmailResult> {\n const amount = Number(input.amountUsd)\n if (!Number.isInteger(amount) || amount < 1 || amount > 100_000) {\n throw new SiteCareError('Enter the quote as a whole number of dollars.', 400)\n }\n const scope = String(input.scope ?? '').trim().slice(0, 1000)\n if (!scope) throw new SiteCareError('Say what the price covers.', 400)\n const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get())\n const org = await readSiteCareOrg(firestore, ticket.orgId)\n const to = (await siteCareOwnerEmail(firestore, ticket.orgId, org)) ?? ticket.request.requesterEmail\n const price = `$${amount}`\n const result = await emailOf(deps)({\n key: SITE_CARE_QUOTE_EMAIL_KEY,\n to,\n org,\n requestId: input.ticketId,\n merge: { 'request.title': ticket.subject, 'quote.amount': price, 'quote.scope': scope },\n fallback: {\n subject: `A quote for ${ticket.subject}`,\n text:\n `Site Care covers changes to what your site already has. “${ticket.subject}” adds something new, ` +\n `so it is a project with one flat price: ${price}.\\n\\nWhat it covers: ${scope}\\n\\n` +\n 'Reply to say yes and we will send the invoice. Nothing is charged until you do.',\n },\n })\n const nowMs = nowOf(deps)\n const batch = firestore.batch()\n batch.create(ticket.ref.collection('messages').doc(createResourceUid()), {\n authorId: input.actor.uid,\n authorEmail: input.actor.email,\n staff: true,\n body: `Quote sent: ${price} — ${scope}`,\n createdAt: FieldValue.serverTimestamp(),\n })\n batch.update(ticket.ref, { updatedAt: FieldValue.serverTimestamp() })\n appendHistoryRow(\n batch,\n firestore,\n ticketHistory(firestore, input.ticketId),\n historyRow({\n atMs: nowMs,\n by: input.actor,\n kind: result.sent ? 'quote.sent' : 'quote.notSent',\n summary: result.sent\n ? `Sent a flat quote of ${price}: this is bigger than Site Care covers.`\n : `The quote of ${price} was not emailed (${result.reason ?? 'unknown'}).`,\n after: { amountUsd: amount, scope, to: result.to, sent: result.sent },\n subjectId: input.ticketId,\n }),\n requestAudit(ticket.orgId, input.ticketId, result.sent ? 'quote.sent' : 'quote.notSent'),\n )\n await batch.commit()\n return result\n}\n\n// ── A ticket's panel ────────────────────────────────────────────────────────\n\nexport interface SiteCareRequestPanel {\n ticketId: string\n orgId: string\n subject: string\n request: SiteCareRequest\n history: Array<AppendOnlyHistoryRow & { $id: string }>\n /** The close's prefilled number, from the timer. */\n suggestedMinutes: number\n /** What this request's month looks like with its other requests. */\n monthMinutesLeft: number\n /** Other Site Care workspaces the sender belongs to (AGL-4031). */\n otherWorkspaces: SiteCareWorkspaceCandidate[]\n /** Why \"Move to workspace\" is refused, or null when it is offered. */\n moveBlockedReason: string | null\n}\n\n/** Everything the staff panel shows for one request. */\nexport async function readSiteCareRequestPanel(\n firestore: FirebaseFirestore.Firestore,\n ticketId: string,\n deps: SiteCareDeps = {},\n): Promise<SiteCareRequestPanel> {\n const ticket = loadedTicket(await ticketRef(firestore, ticketId).get())\n const nowMs = nowOf(deps)\n const month = ticket.request.state === 'closed' ? ticket.request.month : siteCareMonthKey(nowMs)\n const [history, context, candidates] = await Promise.all([\n readHistoryRows(ticketHistory(firestore, ticketId)),\n readMonthContext(null, firestore, ticket.orgId, month, ticketId),\n readSiteCareCandidatesFor(firestore, ticketId),\n ])\n const otherWorkspaces = otherSiteCareCandidates(candidates, ticket.orgId)\n const pool = siteCareIncludedPool(context.goodwillMinutes)\n return {\n ticketId,\n orgId: ticket.orgId,\n subject: ticket.subject,\n request: ticket.request,\n history,\n suggestedMinutes: closeMinutesFromTimer(ticket.request.timerStartedAtMs, nowMs),\n monthMinutesLeft: Math.max(0, pool - context.otherIncludedUsed),\n otherWorkspaces,\n moveBlockedReason: otherWorkspaces.length ? siteCareMoveBlockedReason(ticket.request, otherWorkspaces) : null,\n }\n}\n"],"names":["historyRow","requireHistoryReason","createResourceUid","describeHours","ownerApprovalSentence","readOwnerApprovalInput","readOwnerApprovalRecord","hasSiteCare","resolveEffectivePlan","SITE_CARE_EXTRA_HOUR_USD","allocateSiteCareMinutes","closeMinutesFromTimer","formatSiteCareDate","formatSiteCareMinutes","formatSiteCareUsd","isSiteCareMonthKey","isSiteCarePublishAction","otherSiteCareCandidates","readSiteCareCandidates","readSiteCareMinutes","SITE_CARE_BODY_MAX","SITE_CARE_LIVE_CHARGE_STATUSES","SITE_CARE_RESPONSE_BUSINESS_DAYS","SITE_CARE_STAFF_COLLECTION","SITE_CARE_SUBJECT_MAX","SITE_CARE_TICKET_KIND","siteCareCandidatesSentence","siteCareChargeWords","siteCareCloseVerdict","siteCareExtraTimeCents","siteCareExtraTimeDescription","siteCareIncludedPool","siteCareMonthKey","siteCareMonthSentence","siteCareMonthStatement","siteCareMoveBlockedReason","siteCareOrgMonth","siteCarePublishSentence","siteCareStatementRequest","addBusinessDays","SITE_CARE_APPROVAL_EMAIL_KEY","SITE_CARE_CHARGE_REVERSED_EMAIL_KEY","SITE_CARE_QUOTE_EMAIL_KEY","SITE_CARE_REQUEST_CORRECTED_EMAIL_KEY","SITE_CARE_REQUEST_DONE_EMAIL_KEY","SITE_CARE_REQUEST_RECEIVED_EMAIL_KEY","SITE_CARE_STATEMENT_EMAIL_KEY","createHash","FieldValue","Timestamp","appendHistoryRow","commitHistoryRow","readHistoryRows","notifyStaff","readOrgBilling","sendSiteCareEmail","createExtraTimeItem","creditExtraTimeItem","deleteExtraTimeItem","extraTimeItemIsEditable","readExtraTimeItem","siteCareExtraTimeProduct","siteCareSubscriptionId","subscriptionInvoiceFinalizedSince","updateExtraTimeItem","TICKETS","SITE_CARE_HISTORY_COLLECTION","SITE_CARE_MONTHS_COLLECTION","SITE_CARE_INTAKE_DOC","SiteCareError","Error","message","status","detail","name","nowOf","deps","now","Date","emailOf","email","ticketRef","firestore","ticketId","collection","doc","ticketHistory","intakeRef","monthRef","orgId","month","monthHistory","requestAudit","action","scope","target","monthAudit","newSiteCareRequest","input","source","hostId","requesterEmail","state","timerStartedAtMs","timerStartedByUid","closedAtMs","minutesLogged","timerMinutes","countedMinutes","includedMinutesUsed","overMinutes","billedHours","absorbed","approval","charge","chargeSeq","publish","readSiteCareRequest","value","stored","base","Number","loadedTicket","snapshot","data","request","ref","String","subject","readSiteCareOrg","get","exists","billing","$id","orgHasSiteCare","org","Boolean","siteCareOwnerEmail","ownerUid","member","recordEmail","history","result","what","atMs","subjectId","by","uid","kind","sent","summary","to","reason","after","catch","error","console","siteCareMessageDocId","prefix","key","update","digest","slice","openSiteCareRequest","trim","body","nowMs","dueAtMs","dedupeKey","id","duplicate","candidates","others","length","serverTimestamp","batch","create","plan","supportTier","supportTierRank","responseDueAt","fromMillis","firstRespondedAt","siteCare","requester","siteCareMonth","createdAt","updatedAt","authorId","authorEmail","staff","filedOnOrgId","commit","type","title","map","other","link","due","toLocaleDateString","weekday","day","timeZone","requestId","merge","fallback","text","appendSiteCareReply","appended","ticket","messageRef","from","startSiteCareTimer","runTransaction","tx","actor","readSiteCareCandidatesFor","moveSiteCareRequest","targetOrgId","ticketSnap","intakeSnap","Promise","all","blocked","candidate","find","fromOrgId","toName","before","readMonthContext","reader","excludeTicketId","monthSnap","query","where","requests","docs","filter","goodwillMinutes","otherIncludedUsed","r","reduce","sum","statementWith","context","siteCareBlockedMessage","verdict","requiredHours","approvedHours","findSiteCarePublish","sinceMs","hosts","limit","best","host","rows","orderBy","row","toMillis","activityId","targetName","targetId","chargeKey","seq","newCharge","hours","amountCents","description","idempotencyKey","invoiceItemId","invoiceId","creditNoteId","refundId","updatedAtMs","chargeRequestedRow","settleCharge","customerId","stripeCustomerId","subscription","stripe","product","ok","created","subscriptionId","productId","metadata","siteCareRequestId","next","object","retrySiteCareCharge","closeSiteCareRequest","first","minutes","allocation","absorb","Math","round","statement","publishActivityId","settled","emailDoneSummary","billingSentence","minutesLeftSentence","minutesLeft","changes","recordSiteCareApproval","record","previous","read","rateUsd","channel","correctionReason","sentence","correction","heading","assertMinutesEditable","stage","finalized","correctSiteCareMinutes","old","live","statementNow","stripeStep","correctionRef","chargeStatus","correctionId","correctLiveCharge","step","emailed","siteCareCorrectionKey","itemId","seqKey","outcome","outcomeError","reverseSiteCareCharge","includes","intended","stripeRef","deleted","credited","refund","memo","doneKind","amount","addSiteCareGoodwill","set","readSiteCareMonth","monthRows","sort","a","b","Infinity","siteCareStatementLine","view","billed","toLowerCase","siteCareStatementHistory","flatMap","sendSiteCareStatement","lines","join","monthLabel","sendSiteCareQuote","amountUsd","isInteger","price","readSiteCareRequestPanel","otherWorkspaces","pool","suggestedMinutes","monthMinutesLeft","max","moveBlockedReason"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,oBAAoB,QAGf,6CAA4C;AACnD,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,aAAa,EACbC,qBAAqB,EACrBC,sBAAsB,EACtBC,uBAAuB,QAElB,+CAA8C;AACrD,SACEC,WAAW,EACXC,oBAAoB,EACpBC,wBAAwB,QACnB,2CAA0C;AACjD,SACEC,uBAAuB,EACvBC,qBAAqB,EACrBC,kBAAkB,EAClBC,qBAAqB,EACrBC,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBC,uBAAuB,EACvBC,sBAAsB,EACtBC,mBAAmB,EACnBC,kBAAkB,EAClBC,8BAA8B,EAC9BC,gCAAgC,EAChCC,0BAA0B,EAC1BC,qBAAqB,EACrBC,qBAAqB,EACrBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,oBAAoB,EACpBC,sBAAsB,EACtBC,4BAA4B,EAC5BC,oBAAoB,EACpBC,gBAAgB,EAChBC,qBAAqB,EACrBC,sBAAsB,EACtBC,yBAAyB,EACzBC,gBAAgB,EAChBC,uBAAuB,EACvBC,wBAAwB,QAQnB,mCAAkC;AACzC,SAASC,eAAe,QAAQ,uCAAsC;AACtE,SACEC,4BAA4B,EAC5BC,mCAAmC,EACnCC,yBAAyB,EACzBC,qCAAqC,EACrCC,gCAAgC,EAChCC,oCAAoC,EACpCC,6BAA6B,QACxB,2BAA0B;AACjC,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,eAAe,QAEV,iCAA6B;AACpC,SAASC,WAAW,QAAQ,qBAAiB;AAC7C,SAASC,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