@aglyn/tenant-data-admin 1.0.0-beta.270 → 1.0.0-beta.271
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/server/append-only-history-write.d.ts +38 -0
- package/src/lib/server/append-only-history-write.js +60 -0
- package/src/lib/server/append-only-history-write.js.map +1 -0
- package/src/lib/server/billing-addons.d.ts +58 -32
- package/src/lib/server/billing-addons.js +100 -86
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +166 -0
- package/src/lib/server/bundle-links.js +286 -0
- package/src/lib/server/bundle-links.js.map +1 -0
- package/src/lib/server/client-build.d.ts +74 -0
- package/src/lib/server/client-build.js +264 -0
- package/src/lib/server/client-build.js.map +1 -0
- package/src/lib/server/host-memberships.d.ts +35 -2
- package/src/lib/server/host-memberships.js +63 -2
- package/src/lib/server/host-memberships.js.map +1 -1
- package/src/lib/server/org-billing.d.ts +4 -2
- package/src/lib/server/org-billing.js +5 -0
- package/src/lib/server/org-billing.js.map +1 -1
- package/src/lib/server/site-care-emails.d.ts +52 -0
- package/src/lib/server/site-care-emails.js +97 -0
- package/src/lib/server/site-care-emails.js.map +1 -0
- package/src/lib/server/site-care-inbound.d.ts +80 -0
- package/src/lib/server/site-care-inbound.js +171 -0
- package/src/lib/server/site-care-inbound.js.map +1 -0
- package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
- package/src/lib/server/site-care-project-reconcile.js +211 -0
- package/src/lib/server/site-care-project-reconcile.js.map +1 -0
- package/src/lib/server/site-care-project-stripe.d.ts +114 -0
- package/src/lib/server/site-care-project-stripe.js +305 -0
- package/src/lib/server/site-care-project-stripe.js.map +1 -0
- package/src/lib/server/site-care-projects.d.ts +169 -0
- package/src/lib/server/site-care-projects.js +882 -0
- package/src/lib/server/site-care-projects.js.map +1 -0
- package/src/lib/server/site-care-reconcile.d.ts +81 -0
- package/src/lib/server/site-care-reconcile.js +349 -0
- package/src/lib/server/site-care-reconcile.js.map +1 -0
- package/src/lib/server/site-care-requests.d.ts +243 -0
- package/src/lib/server/site-care-requests.js +1414 -0
- package/src/lib/server/site-care-requests.js.map +1 -0
- package/src/lib/server/site-care-stripe.d.ts +175 -0
- package/src/lib/server/site-care-stripe.js +375 -0
- package/src/lib/server/site-care-stripe.js.map +1 -0
- package/src/lib/server/upgrade-proposal.d.ts +40 -1
- package/src/lib/server/upgrade-proposal.js +92 -50
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/tenancy.d.ts +1 -0
- package/src/tenancy.js +2 -0
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-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,EACpBC,wBAAwB,QACnB,2CAA0C;AACjD,SACEC,uBAAuB,EACvBC,qBAAqB,EACrBC,kBAAkB,EAClBC,qBAAqB,EACrBC,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBC,mBAAmB,EACnBC,kBAAkB,EAClBC,8BAA8B,EAC9BC,gCAAgC,EAChCC,qBAAqB,EACrBC,qBAAqB,EACrBC,mBAAmB,EACnBC,oBAAoB,EACpBC,sBAAsB,EACtBC,4BAA4B,EAC5BC,oBAAoB,EACpBC,gBAAgB,EAChBC,qBAAqB,EACrBC,sBAAsB,EACtBC,gBAAgB,EAChBC,uBAAuB,EACvBC,wBAAwB,QAOnB,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,cAAc,QAAQ,mBAAe;AAC9C,SAASC,iBAAiB,QAAkC,wBAAoB;AAChF,SACEC,mBAAmB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AOO,IAAI,GAAG,eAAe;IAE1E,MAAMuB,MAAMgB,MAAM;IAClB,OAAO9C;AACT;AAgBA,sDAAsD,GACtD,OAAO,eAAemN,yBACpB9Q,SAAsC,EACtCC,QAAgB,EAChBP,OAAqB,CAAC,CAAC;IAEvB,MAAM8H,SAASjF,aAAa,MAAMxC,UAAUC,WAAWC,UAAU8C,GAAG;IACpE,MAAMoC,QAAQ1F,MAAMC;IACpB,MAAMa,QAAQiH,OAAO9E,OAAO,CAACvB,KAAK,KAAK,WAAWqG,OAAO9E,OAAO,CAACnC,KAAK,GAAGvD,iBAAiBmI;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"}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* SITE CARE EXTRA TIME, IN STRIPE (AGL-3959).
|
|
19
|
+
*
|
|
20
|
+
* Every Stripe call the extra-time charge makes, and nothing else: the item
|
|
21
|
+
* on the org's subscription that rides its next invoice, a correction of it
|
|
22
|
+
* while that invoice is still a draft, and its reversal — deleted before the
|
|
23
|
+
* invoice finalizes, credited after, refunded once paid. Staff never do any
|
|
24
|
+
* of this by hand in the Stripe dashboard; the request is the only door, and
|
|
25
|
+
* the caller writes the request's history row in the same step as each call
|
|
26
|
+
* (`site-care-requests.ts`).
|
|
27
|
+
*
|
|
28
|
+
* The same pinned API version and form-encoded fetch `usage-invoice.ts`
|
|
29
|
+
* uses, for the same reason: an invoice item's parameters have moved between
|
|
30
|
+
* versions, and a charge that silently changed shape under a Dashboard
|
|
31
|
+
* upgrade is what pinning prevents. `fetchImpl` and `secretKey` are the
|
|
32
|
+
* specs' seams.
|
|
33
|
+
*
|
|
34
|
+
* ## The tax code is the product's, and it is checked
|
|
35
|
+
*
|
|
36
|
+
* The line is priced against the Site Care product (`price_data[product]`),
|
|
37
|
+
* because the product is what carries the tax code Stripe Tax computes from;
|
|
38
|
+
* the product is read off the Site Care price the subscription already
|
|
39
|
+
* carries, and a product whose tax code is not `txcd_10103001` refuses the
|
|
40
|
+
* charge rather than billing it untaxed or under the wrong code.
|
|
41
|
+
*/
|
|
42
|
+
type StripeFetch = typeof fetch;
|
|
43
|
+
export interface SiteCareStripeOptions {
|
|
44
|
+
secretKey?: string;
|
|
45
|
+
fetchImpl?: StripeFetch;
|
|
46
|
+
}
|
|
47
|
+
interface StripeAnswer {
|
|
48
|
+
ok: boolean;
|
|
49
|
+
status: number;
|
|
50
|
+
body: Record<string, unknown>;
|
|
51
|
+
}
|
|
52
|
+
declare function stripeCall(options: SiteCareStripeOptions, method: 'GET' | 'POST' | 'DELETE', path: string, params?: Record<string, string> | null, idempotencyKey?: string | null): Promise<StripeAnswer>;
|
|
53
|
+
declare function stripeMessage(answer: StripeAnswer, fallback: string): string;
|
|
54
|
+
declare function metadataParams(metadata: Readonly<Record<string, string>>): Record<string, string>;
|
|
55
|
+
/**
|
|
56
|
+
* The pinned, form-encoded Stripe call and its helpers, shared with the
|
|
57
|
+
* flat-quoted project invoice (AGL-3970, `site-care-project-stripe.ts`) so
|
|
58
|
+
* both Site Care money paths speak to Stripe the same way.
|
|
59
|
+
*/
|
|
60
|
+
export { metadataParams as siteCareStripeMetadata, stripeCall as siteCareStripeCall, stripeMessage as siteCareStripeMessage, };
|
|
61
|
+
export type { StripeAnswer as SiteCareStripeAnswer };
|
|
62
|
+
export type SiteCareStripeResult<T> = ({
|
|
63
|
+
ok: true;
|
|
64
|
+
} & T) | {
|
|
65
|
+
ok: false;
|
|
66
|
+
error: string;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* The org's live subscription, which the item is attached to so it rides
|
|
70
|
+
* that subscription's next invoice.
|
|
71
|
+
*/
|
|
72
|
+
export declare function siteCareSubscriptionId(customerId: string, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
|
|
73
|
+
subscriptionId: string;
|
|
74
|
+
}>>;
|
|
75
|
+
/**
|
|
76
|
+
* The Site Care product, read off the add-on's price, with its tax code
|
|
77
|
+
* checked. `priceId` defaults to the monthly add-on price; the product is
|
|
78
|
+
* the same for the yearly one.
|
|
79
|
+
*/
|
|
80
|
+
export declare function siteCareExtraTimeProduct(options?: SiteCareStripeOptions & {
|
|
81
|
+
priceId?: string | null;
|
|
82
|
+
}): Promise<SiteCareStripeResult<{
|
|
83
|
+
productId: string;
|
|
84
|
+
}>>;
|
|
85
|
+
export interface ExtraTimeItemInput {
|
|
86
|
+
customerId: string;
|
|
87
|
+
subscriptionId: string;
|
|
88
|
+
productId: string;
|
|
89
|
+
hours: number;
|
|
90
|
+
description: string;
|
|
91
|
+
metadata: Readonly<Record<string, string>>;
|
|
92
|
+
idempotencyKey: string;
|
|
93
|
+
}
|
|
94
|
+
/** Adds the extra time to the subscription's next invoice. */
|
|
95
|
+
export declare function createExtraTimeItem(input: ExtraTimeItemInput, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
|
|
96
|
+
invoiceItemId: string;
|
|
97
|
+
amountCents: number;
|
|
98
|
+
}>>;
|
|
99
|
+
/** Corrects the hours and description of an item not yet on a finalized invoice. */
|
|
100
|
+
export declare function updateExtraTimeItem(input: {
|
|
101
|
+
invoiceItemId: string;
|
|
102
|
+
hours: number;
|
|
103
|
+
description: string;
|
|
104
|
+
idempotencyKey: string;
|
|
105
|
+
}, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
|
|
106
|
+
amountCents: number;
|
|
107
|
+
}>>;
|
|
108
|
+
/**
|
|
109
|
+
* Where an item stands: still pending (no invoice), on a draft invoice, or
|
|
110
|
+
* on one that finalized — open, paid, void or uncollectible — or gone.
|
|
111
|
+
*/
|
|
112
|
+
export type ExtraTimeItemStage = 'pending' | 'draft' | 'open' | 'paid' | 'void' | 'uncollectible' | 'deleted';
|
|
113
|
+
export interface ExtraTimeItemState {
|
|
114
|
+
stage: ExtraTimeItemStage;
|
|
115
|
+
invoiceId: string | null;
|
|
116
|
+
amountCents: number;
|
|
117
|
+
quantity: number;
|
|
118
|
+
description: string;
|
|
119
|
+
metadata: Record<string, string>;
|
|
120
|
+
}
|
|
121
|
+
/** Reads an item and, when it is on one, its invoice. */
|
|
122
|
+
export declare function readExtraTimeItem(invoiceItemId: string, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
|
|
123
|
+
state: ExtraTimeItemState;
|
|
124
|
+
}>>;
|
|
125
|
+
/** Whether the item can still be corrected or deleted rather than credited. */
|
|
126
|
+
export declare function extraTimeItemIsEditable(stage: ExtraTimeItemStage): boolean;
|
|
127
|
+
/** Deletes an item that has not reached a finalized invoice. */
|
|
128
|
+
export declare function deleteExtraTimeItem(invoiceItemId: string, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
|
|
129
|
+
deleted: true;
|
|
130
|
+
}>>;
|
|
131
|
+
/**
|
|
132
|
+
* Credits an item on a finalized invoice — and refunds it when the invoice
|
|
133
|
+
* was paid. The credit note names the item's own line, so tax comes back
|
|
134
|
+
* with it; on a paid invoice its whole total is refunded to the card.
|
|
135
|
+
*/
|
|
136
|
+
export declare function creditExtraTimeItem(input: {
|
|
137
|
+
invoiceId: string;
|
|
138
|
+
invoiceItemId: string;
|
|
139
|
+
refund: boolean;
|
|
140
|
+
memo: string;
|
|
141
|
+
metadata: Readonly<Record<string, string>>;
|
|
142
|
+
idempotencyKey: string;
|
|
143
|
+
}, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
|
|
144
|
+
creditNoteId: string;
|
|
145
|
+
refundId: string | null;
|
|
146
|
+
amountCents: number;
|
|
147
|
+
}>>;
|
|
148
|
+
/**
|
|
149
|
+
* Whether a subscription invoice created since `sinceMs` has finalized —
|
|
150
|
+
* the point after which a request's minutes are no longer edited, only its
|
|
151
|
+
* charge reversed.
|
|
152
|
+
*/
|
|
153
|
+
export declare function subscriptionInvoiceFinalizedSince(input: {
|
|
154
|
+
subscriptionId: string;
|
|
155
|
+
sinceMs: number;
|
|
156
|
+
}, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
|
|
157
|
+
finalized: boolean;
|
|
158
|
+
}>>;
|
|
159
|
+
/** One extra-time item as the reconciliation reads it. */
|
|
160
|
+
export interface StripeExtraTimeItem {
|
|
161
|
+
id: string;
|
|
162
|
+
amountCents: number;
|
|
163
|
+
quantity: number;
|
|
164
|
+
description: string;
|
|
165
|
+
requestId: string;
|
|
166
|
+
/** The month the request counted in, from the item's metadata. */
|
|
167
|
+
month: string;
|
|
168
|
+
}
|
|
169
|
+
/** Every Site Care extra-time item on a customer created since `sinceMs`. */
|
|
170
|
+
export declare function listSiteCareExtraTimeItems(input: {
|
|
171
|
+
customerId: string;
|
|
172
|
+
sinceMs: number;
|
|
173
|
+
}, options?: SiteCareStripeOptions): Promise<SiteCareStripeResult<{
|
|
174
|
+
items: StripeExtraTimeItem[];
|
|
175
|
+
}>>;
|