@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-project-stripe.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 SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE,\n type SiteCareProjectInvoiceKind,\n} from '@aglyn/aglyn/app-utils/site-care-project'\nimport {\n siteCareStripeCall,\n siteCareStripeMessage,\n siteCareStripeMetadata,\n type SiteCareStripeOptions,\n type SiteCareStripeResult,\n} from './site-care-stripe'\n\n/**\n * A SITE CARE PROJECT'S INVOICES, IN STRIPE (AGL-3970).\n *\n * Every Stripe call the flat-quoted project invoice makes, and nothing else:\n * a ONE-OFF invoice for the org's Stripe customer — not attached to the\n * subscription — that Stripe does not charge automatically\n * (`collection_method: send_invoice`), finalized so it has a hosted page the\n * owner pays from their phone; then reading it, voiding it while unpaid, and\n * (through `creditExtraTimeItem`, the same credit-note call extra time uses)\n * crediting or refunding it. Staff never build one by hand in the Stripe\n * dashboard; the project record is the only door, and the caller writes the\n * record's history row around each call (`site-care-projects.ts`).\n *\n * The same pinned, form-encoded call as extra time (`site-care-stripe.ts`),\n * and the same order `usage-invoice.ts` settled on: the invoice FIRST, then\n * the one line attached to it by id, so nothing else pending on the customer\n * can land on it (`pending_invoice_items_behavior: exclude`).\n *\n * ## The tax code\n *\n * The line is priced against the Site Care product (`price_data[product]`),\n * read off the Site Care price with its tax code checked to be\n * `txcd_10103001` by `siteCareExtraTimeProduct` — the product is what Stripe\n * Tax computes from, and a product with any other code refuses the invoice\n * rather than bill it under the wrong one. Automatic tax is on and the line\n * is tax-exclusive, as every platform price is.\n *\n * ## Never twice\n *\n * Each write carries a key derived from the invoice record's own\n * (`:invoice`, `:item`, `:finalize`). A retry also looks for the invoice by\n * its metadata before creating one, so even past Stripe's 24-hour key window\n * a lost answer is adopted rather than invoiced again.\n */\n\n/** Metadata every project invoice carries, which the webhook and the reconciliation read. */\nexport const SITE_CARE_PROJECT_METADATA_KEY = 'siteCareProjectId'\n\nexport interface ProjectInvoiceInput {\n customerId: string\n productId: string\n orgId: string\n projectId: string\n seq: number\n kind: SiteCareProjectInvoiceKind\n amountCents: number\n description: string\n memo: string\n idempotencyKey: string\n /** The invoice an earlier attempt made, when the record has it. */\n invoiceId: string | null\n /** When the project was created: how far back an earlier attempt's invoice can be. */\n sinceMs: number\n}\n\nexport interface ProjectInvoiceState {\n invoiceId: string\n invoiceItemId: string | null\n status: string\n number: string | null\n hostedInvoiceUrl: string | null\n totalCents: number\n /** Before tax. */\n subtotalCents: number\n amountPaidCents: number\n metadata: Record<string, string>\n}\n\ntype ProjectStripeResult<T> = SiteCareStripeResult<T> | { ok: false; error: string; invoiceId?: string | null }\n\nfunction text(value: unknown): string | null {\n return typeof value === 'string' && value ? value : null\n}\n\nfunction invoiceState(body: Record<string, unknown>, invoiceItemId: string | null): ProjectInvoiceState {\n return {\n invoiceId: String(body['id'] ?? ''),\n invoiceItemId,\n status: String(body['status'] ?? ''),\n number: text(body['number']),\n hostedInvoiceUrl: text(body['hosted_invoice_url']),\n totalCents: Number(body['total'] ?? 0),\n subtotalCents: Number(body['subtotal'] ?? 0),\n amountPaidCents: Number(body['amount_paid'] ?? 0),\n metadata: (body['metadata'] as Record<string, string> | undefined) ?? {},\n }\n}\n\nfunction projectMetadata(input: Pick<ProjectInvoiceInput, 'orgId' | 'projectId' | 'seq' | 'kind'>): Record<string, string> {\n return {\n [SITE_CARE_PROJECT_METADATA_KEY]: input.projectId,\n orgId: input.orgId,\n invoiceSeq: String(input.seq),\n invoiceKind: input.kind,\n }\n}\n\n/** The invoice an earlier attempt made for this record, found by its metadata. */\nasync function findEarlierInvoice(\n input: ProjectInvoiceInput,\n options: SiteCareStripeOptions,\n): Promise<SiteCareStripeResult<{ body: Record<string, unknown> | null }>> {\n const answer = await siteCareStripeCall(options, 'GET', 'invoices', {\n customer: input.customerId,\n 'created[gte]': String(Math.floor(input.sinceMs / 1000) - 60),\n limit: '100',\n })\n if (answer.ok === false) return { ok: false, error: siteCareStripeMessage(answer, 'Reading the invoices failed') }\n const rows = (answer.body['data'] as Array<Record<string, unknown>> | undefined) ?? []\n const found = rows.find((row) => {\n const metadata = (row['metadata'] as Record<string, string> | undefined) ?? {}\n return (\n metadata[SITE_CARE_PROJECT_METADATA_KEY] === input.projectId &&\n metadata['invoiceSeq'] === String(input.seq) &&\n row['status'] !== 'void'\n )\n })\n return { ok: true, body: found ?? null }\n}\n\n/** The project's own line on a draft, when one is there. */\nasync function existingLine(\n invoiceId: string,\n options: SiteCareStripeOptions,\n): Promise<SiteCareStripeResult<{ invoiceItemId: string | null }>> {\n const lines = await siteCareStripeCall(options, 'GET', `invoices/${encodeURIComponent(invoiceId)}/lines`, {\n limit: '10',\n })\n if (lines.ok === false) return { ok: false, error: siteCareStripeMessage(lines, 'Reading the invoice lines failed') }\n const row = ((lines.body['data'] as Array<Record<string, unknown>> | undefined) ?? [])[0]\n if (!row) return { ok: true, invoiceItemId: null }\n return { ok: true, invoiceItemId: text(row['invoice_item']) ?? text(row['id']) }\n}\n\n/**\n * Creates (or finishes an earlier attempt at) one project invoice:\n * invoice, line, finalize. Answers the finalized invoice with its hosted\n * page, or the error and whatever invoice id got made on the way.\n */\nexport async function createProjectInvoice(\n input: ProjectInvoiceInput,\n options: SiteCareStripeOptions = {},\n): Promise<ProjectStripeResult<{ state: ProjectInvoiceState }>> {\n if (!input.customerId) return { ok: false, error: 'The workspace has no Stripe customer to invoice.' }\n const amountCents = Math.floor(Number(input.amountCents))\n if (!Number.isInteger(amountCents) || amountCents < 100) {\n return { ok: false, error: 'A project invoice is at least $1.' }\n }\n const key = (step: string) => `${input.idempotencyKey}:${step}`\n const metadata = siteCareStripeMetadata(projectMetadata(input))\n\n let body: Record<string, unknown> | null\n if (input.invoiceId) {\n const read = await siteCareStripeCall(options, 'GET', `invoices/${encodeURIComponent(input.invoiceId)}`)\n if (read.ok === false) {\n return { ok: false, error: siteCareStripeMessage(read, 'Reading the invoice failed'), invoiceId: input.invoiceId }\n }\n body = read.body\n } else {\n const earlier = await findEarlierInvoice(input, options)\n if (earlier.ok === false) return earlier\n body = earlier.body\n }\n let fresh = false\n if (!body) {\n const created = await siteCareStripeCall(\n options,\n 'POST',\n 'invoices',\n {\n customer: input.customerId,\n collection_method: 'send_invoice',\n days_until_due: String(SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE),\n auto_advance: 'false',\n 'automatic_tax[enabled]': 'true',\n // This invoice carries the line added below and nothing else.\n pending_invoice_items_behavior: 'exclude',\n description: input.memo,\n ...metadata,\n },\n key('invoice'),\n )\n if (created.ok === false) return { ok: false, error: siteCareStripeMessage(created, 'Stripe refused the invoice') }\n body = created.body\n fresh = true\n }\n const invoiceId = String(body['id'] ?? '')\n if (!invoiceId) return { ok: false, error: 'Stripe returned an invoice with no id' }\n const status = String(body['status'] ?? '')\n if (status === 'void' || status === 'uncollectible') {\n return { ok: false, error: `The invoice is ${status}; raise a new one.`, invoiceId }\n }\n if (status !== 'draft') {\n const line = await existingLine(invoiceId, options)\n return { ok: true, state: invoiceState(body, line.ok ? line.invoiceItemId : null) }\n }\n\n let invoiceItemId: string | null = null\n if (!fresh) {\n const line = await existingLine(invoiceId, options)\n if (line.ok === false) return { ok: false, error: line.error, invoiceId }\n invoiceItemId = line.invoiceItemId\n }\n if (!invoiceItemId) {\n const item = await siteCareStripeCall(\n options,\n 'POST',\n 'invoiceitems',\n {\n customer: input.customerId,\n invoice: invoiceId,\n 'price_data[product]': input.productId,\n 'price_data[currency]': 'usd',\n 'price_data[unit_amount]': String(amountCents),\n // US sales tax is added on top of the platform's prices, and\n // automatic tax refuses an unspecified behavior outright.\n 'price_data[tax_behavior]': 'exclusive',\n description: input.description,\n ...metadata,\n },\n key('item'),\n )\n if (item.ok === false) {\n return { ok: false, error: siteCareStripeMessage(item, 'Stripe refused the project line'), invoiceId }\n }\n invoiceItemId = text(item.body['id'])\n }\n const finalized = await siteCareStripeCall(\n options,\n 'POST',\n `invoices/${encodeURIComponent(invoiceId)}/finalize`,\n { auto_advance: 'false' },\n key('finalize'),\n )\n if (finalized.ok === false) {\n return { ok: false, error: siteCareStripeMessage(finalized, 'The invoice could not be finalized'), invoiceId }\n }\n const state = invoiceState(finalized.body, invoiceItemId)\n if (!state.hostedInvoiceUrl) {\n return { ok: false, error: 'Stripe finalized the invoice without a pay page.', invoiceId }\n }\n return { ok: true, state }\n}\n\n/** One invoice as it stands in Stripe. */\nexport async function readProjectInvoice(\n invoiceId: string,\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ state: ProjectInvoiceState | null }>> {\n const answer = await siteCareStripeCall(options, 'GET', `invoices/${encodeURIComponent(invoiceId)}`)\n if (answer.status === 404) return { ok: true, state: null }\n if (answer.ok === false) return { ok: false, error: siteCareStripeMessage(answer, 'Reading the invoice failed') }\n return { ok: true, state: invoiceState(answer.body, null) }\n}\n\n/** Voids an unpaid invoice: the owner owes nothing on it. */\nexport async function voidProjectInvoice(\n input: { invoiceId: string; idempotencyKey: string },\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ status: string }>> {\n const answer = await siteCareStripeCall(\n options,\n 'POST',\n `invoices/${encodeURIComponent(input.invoiceId)}/void`,\n null,\n input.idempotencyKey,\n )\n if (answer.ok === false) return { ok: false, error: siteCareStripeMessage(answer, 'Stripe refused to void the invoice') }\n return { ok: true, status: String(answer.body['status'] ?? 'void') }\n}\n\n/** Every project invoice on a customer created since `sinceMs`, as the reconciliation reads them. */\nexport async function listProjectInvoices(\n input: { customerId: string; sinceMs: number },\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ invoices: ProjectInvoiceState[] }>> {\n const invoices: ProjectInvoiceState[] = []\n let startingAfter = ''\n for (let page = 0; page < 10; page++) {\n const answer = await siteCareStripeCall(options, 'GET', 'invoices', {\n customer: input.customerId,\n 'created[gte]': String(Math.floor(input.sinceMs / 1000)),\n limit: '100',\n ...(startingAfter ? { starting_after: startingAfter } : {}),\n })\n if (answer.ok === false) return { ok: false, error: siteCareStripeMessage(answer, 'Listing invoices failed') }\n const rows = (answer.body['data'] as Array<Record<string, unknown>> | undefined) ?? []\n for (const row of rows) {\n const metadata = (row['metadata'] as Record<string, string> | undefined) ?? {}\n if (metadata[SITE_CARE_PROJECT_METADATA_KEY]) invoices.push(invoiceState(row, null))\n }\n if (answer.body['has_more'] !== true || !rows.length) break\n startingAfter = String(rows[rows.length - 1]['id'])\n }\n return { ok: true, invoices }\n}\n"],"names":["SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE","siteCareStripeCall","siteCareStripeMessage","siteCareStripeMetadata","SITE_CARE_PROJECT_METADATA_KEY","text","value","invoiceState","body","invoiceItemId","invoiceId","String","status","number","hostedInvoiceUrl","totalCents","Number","subtotalCents","amountPaidCents","metadata","projectMetadata","input","projectId","orgId","invoiceSeq","seq","invoiceKind","kind","findEarlierInvoice","options","answer","customer","customerId","Math","floor","sinceMs","limit","ok","error","rows","found","find","row","existingLine","lines","encodeURIComponent","createProjectInvoice","amountCents","isInteger","key","step","idempotencyKey","read","earlier","fresh","created","collection_method","days_until_due","auto_advance","pending_invoice_items_behavior","description","memo","line","state","item","invoice","productId","finalized","readProjectInvoice","voidProjectInvoice","listProjectInvoices","invoices","startingAfter","page","starting_after","push","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wCAAwC,QAEnC,2CAA0C;AACjD,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,sBAAsB,QAGjB,wBAAoB;AAE3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GAED,2FAA2F,GAC3F,OAAO,MAAMC,iCAAiC,oBAAmB;AAkCjE,SAASC,KAAKC,KAAc;IAC1B,OAAO,OAAOA,UAAU,YAAYA,QAAQA,QAAQ;AACtD;AAEA,SAASC,aAAaC,IAA6B,EAAEC,aAA4B;QAE3DD,UAEHA,cAGIA,aACGA,gBACEA,mBACbA;IATb,OAAO;QACLE,WAAWC,QAAOH,WAAAA,IAAI,CAAC,KAAK,YAAVA,WAAc;QAChCC;QACAG,QAAQD,QAAOH,eAAAA,IAAI,CAAC,SAAS,YAAdA,eAAkB;QACjCK,QAAQR,KAAKG,IAAI,CAAC,SAAS;QAC3BM,kBAAkBT,KAAKG,IAAI,CAAC,qBAAqB;QACjDO,YAAYC,QAAOR,cAAAA,IAAI,CAAC,QAAQ,YAAbA,cAAiB;QACpCS,eAAeD,QAAOR,iBAAAA,IAAI,CAAC,WAAW,YAAhBA,iBAAoB;QAC1CU,iBAAiBF,QAAOR,oBAAAA,IAAI,CAAC,cAAc,YAAnBA,oBAAuB;QAC/CW,QAAQ,GAAGX,iBAAAA,IAAI,CAAC,WAAW,YAAhBA,iBAA2D,CAAC;IACzE;AACF;AAEA,SAASY,gBAAgBC,KAAwE;IAC/F,OAAO;QACL,CAACjB,+BAA+B,EAAEiB,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,+BAA+B,EAAEmE,SAASI,IAAI,CAACpE,aAAamC,KAAK;QAChF;QACA,IAAIZ,OAAOtB,IAAI,CAAC,WAAW,KAAK,QAAQ,CAAC+B,KAAKqC,MAAM,EAAE;QACtDJ,gBAAgB7D,OAAO4B,IAAI,CAACA,KAAKqC,MAAM,GAAG,EAAE,CAAC,KAAK;IACpD;IACA,OAAO;QAAEvC,IAAI;QAAMkC;IAAS;AAC9B"}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { type AppendOnlyHistoryRow } from '@aglyn/aglyn/app-utils/append-only-history';
|
|
18
|
+
import { type SiteCareProject, type SiteCareProjectAcceptance, type SiteCareProjectInvoice } from '@aglyn/aglyn/app-utils/site-care-project';
|
|
19
|
+
import { type SiteCareEmailResult } from './site-care-emails';
|
|
20
|
+
import { type SiteCareActor, type SiteCareDeps } from './site-care-requests';
|
|
21
|
+
/**
|
|
22
|
+
* SITE CARE PROJECTS, WITH FIRESTORE AND STRIPE (AGL-3970).
|
|
23
|
+
*
|
|
24
|
+
* The staff "Charge for work": a flat-quoted project on the org
|
|
25
|
+
* (`orgs/{orgId}/siteCareProjects/{id}`) holding the scope, the quote, the
|
|
26
|
+
* owner's recorded yes, every invoice it raised and the launch, with an
|
|
27
|
+
* append-only history beside it (`…/siteCareProjects/{id}/siteCareHistory`).
|
|
28
|
+
* None of it is in the Firestore rules: every read and write passes the
|
|
29
|
+
* console's routes, as Site Care requests do.
|
|
30
|
+
*
|
|
31
|
+
* The same discipline as Site Care extra time, from the same modules:
|
|
32
|
+
* every change writes its history row in the same batch or transaction as
|
|
33
|
+
* the change, and a staff member's change writes its `adminAudit` row there
|
|
34
|
+
* too. Money moves in two steps around the Stripe calls — a `creating`
|
|
35
|
+
* invoice and its `invoice.requested` row commit first, then the calls under
|
|
36
|
+
* the invoice's own idempotency key, then the result and its row together —
|
|
37
|
+
* so a success with no row behind it is a `creating` invoice the
|
|
38
|
+
* reconciliation reports and a retry adopts. Reversals write their intent
|
|
39
|
+
* row before the call, keyed by the invoice's own key.
|
|
40
|
+
*
|
|
41
|
+
* The arithmetic is `@aglyn/aglyn/app-utils/site-care-project`, the yes
|
|
42
|
+
* `owner-approval-record`, the row `append-only-history`, the Stripe calls
|
|
43
|
+
* `site-care-project-stripe.ts`.
|
|
44
|
+
*/
|
|
45
|
+
export declare const SITE_CARE_PROJECTS_COLLECTION = "siteCareProjects";
|
|
46
|
+
export interface SiteCareProjectQuoteInput {
|
|
47
|
+
title: unknown;
|
|
48
|
+
scope: unknown;
|
|
49
|
+
kind: unknown;
|
|
50
|
+
estimatedHours: unknown;
|
|
51
|
+
/** A price above the computed one; blank means the computed one. */
|
|
52
|
+
priceUsd?: unknown;
|
|
53
|
+
}
|
|
54
|
+
/** Quotes a project on a workspace. Nothing bills until the owner's yes is recorded. */
|
|
55
|
+
export declare function createSiteCareProject(firestore: FirebaseFirestore.Firestore, input: SiteCareProjectQuoteInput & {
|
|
56
|
+
orgId: string;
|
|
57
|
+
actor: SiteCareActor;
|
|
58
|
+
}, deps?: SiteCareDeps): Promise<{
|
|
59
|
+
projectId: string;
|
|
60
|
+
project: SiteCareProject;
|
|
61
|
+
}>;
|
|
62
|
+
/**
|
|
63
|
+
* Changes a project's name, scope or price, with a reason — only until the
|
|
64
|
+
* first invoice is sent. Any change is a new quote version, so a yes the
|
|
65
|
+
* owner gave to the old one no longer invoices anything.
|
|
66
|
+
*/
|
|
67
|
+
export declare function editSiteCareProject(firestore: FirebaseFirestore.Firestore, input: SiteCareProjectQuoteInput & {
|
|
68
|
+
orgId: string;
|
|
69
|
+
projectId: string;
|
|
70
|
+
actor: SiteCareActor;
|
|
71
|
+
reason: unknown;
|
|
72
|
+
}, deps?: SiteCareDeps): Promise<SiteCareProject>;
|
|
73
|
+
/**
|
|
74
|
+
* Records — or corrects — how and when the owner accepted the quote as it
|
|
75
|
+
* stands, and emails them the confirmation of the scope and price that is
|
|
76
|
+
* the written record. Nothing is invoiced before this.
|
|
77
|
+
*/
|
|
78
|
+
export declare function recordSiteCareProjectAcceptance(firestore: FirebaseFirestore.Firestore, input: {
|
|
79
|
+
orgId: string;
|
|
80
|
+
projectId: string;
|
|
81
|
+
actor: SiteCareActor & {
|
|
82
|
+
uid: string;
|
|
83
|
+
};
|
|
84
|
+
acceptance: Record<string, unknown>;
|
|
85
|
+
}, deps?: SiteCareDeps): Promise<SiteCareProjectAcceptance>;
|
|
86
|
+
/**
|
|
87
|
+
* Raises the project's next invoice — the whole price, or the deposit —
|
|
88
|
+
* on the owner's current yes, and emails them the pay link.
|
|
89
|
+
*/
|
|
90
|
+
export declare function sendSiteCareProjectInvoice(firestore: FirebaseFirestore.Firestore, input: {
|
|
91
|
+
orgId: string;
|
|
92
|
+
projectId: string;
|
|
93
|
+
actor: SiteCareActor;
|
|
94
|
+
}, deps?: SiteCareDeps): Promise<SiteCareProjectInvoice>;
|
|
95
|
+
/** Re-runs an invoice that failed, or whose result never landed, under its own key. */
|
|
96
|
+
export declare function retrySiteCareProjectInvoice(firestore: FirebaseFirestore.Firestore, input: {
|
|
97
|
+
orgId: string;
|
|
98
|
+
projectId: string;
|
|
99
|
+
seq: number;
|
|
100
|
+
actor: SiteCareActor;
|
|
101
|
+
}, deps?: SiteCareDeps): Promise<SiteCareProjectInvoice>;
|
|
102
|
+
/** Emails the owner an open invoice's pay link again. */
|
|
103
|
+
export declare function resendSiteCareProjectInvoice(firestore: FirebaseFirestore.Firestore, input: {
|
|
104
|
+
orgId: string;
|
|
105
|
+
projectId: string;
|
|
106
|
+
seq: number;
|
|
107
|
+
actor: SiteCareActor;
|
|
108
|
+
}, deps?: SiteCareDeps): Promise<SiteCareEmailResult>;
|
|
109
|
+
/**
|
|
110
|
+
* Marks the project launched. A half-and-half project raises its balance
|
|
111
|
+
* invoice from the same record, in the same step, and emails the pay link.
|
|
112
|
+
* Launch comes after the first invoice is paid: both splits are paid up
|
|
113
|
+
* front before work starts.
|
|
114
|
+
*/
|
|
115
|
+
export declare function launchSiteCareProject(firestore: FirebaseFirestore.Firestore, input: {
|
|
116
|
+
orgId: string;
|
|
117
|
+
projectId: string;
|
|
118
|
+
actor: SiteCareActor;
|
|
119
|
+
}, deps?: SiteCareDeps): Promise<{
|
|
120
|
+
project: SiteCareProject;
|
|
121
|
+
invoice: SiteCareProjectInvoice | null;
|
|
122
|
+
}>;
|
|
123
|
+
export type SiteCareProjectPaymentOutcome = 'recorded' | 'already' | 'ignored';
|
|
124
|
+
/**
|
|
125
|
+
* Records a project invoice as paid — from the billing webhook's
|
|
126
|
+
* `invoice.paid`, or from staff's "Check payments" when a delivery was
|
|
127
|
+
* missed — and emails the owner the receipt. Idempotent: a redelivery of a
|
|
128
|
+
* payment already recorded changes nothing and sends nothing.
|
|
129
|
+
*/
|
|
130
|
+
export declare function recordSiteCareProjectPayment(firestore: FirebaseFirestore.Firestore, input: {
|
|
131
|
+
orgId: string;
|
|
132
|
+
invoiceId: string;
|
|
133
|
+
metadata: Readonly<Record<string, string>>;
|
|
134
|
+
amountPaidCents: number;
|
|
135
|
+
paidOutOfBand?: boolean;
|
|
136
|
+
}, deps?: SiteCareDeps): Promise<SiteCareProjectPaymentOutcome>;
|
|
137
|
+
/**
|
|
138
|
+
* Reads each unpaid invoice of a project from Stripe and records any that
|
|
139
|
+
* were paid, for a webhook delivery that never arrived.
|
|
140
|
+
*/
|
|
141
|
+
export declare function checkSiteCareProjectPayments(firestore: FirebaseFirestore.Firestore, input: {
|
|
142
|
+
orgId: string;
|
|
143
|
+
projectId: string;
|
|
144
|
+
}, deps?: SiteCareDeps): Promise<{
|
|
145
|
+
recorded: number;
|
|
146
|
+
}>;
|
|
147
|
+
export type SiteCareProjectReversal = 'void' | 'credit' | 'refund';
|
|
148
|
+
/**
|
|
149
|
+
* Voids an unpaid invoice, credits it, or refunds a paid one — from the
|
|
150
|
+
* record, with a reason, never by hand in Stripe. The intent row commits
|
|
151
|
+
* before the call; the owner is emailed the outcome.
|
|
152
|
+
*/
|
|
153
|
+
export declare function reverseSiteCareProjectInvoice(firestore: FirebaseFirestore.Firestore, input: {
|
|
154
|
+
orgId: string;
|
|
155
|
+
projectId: string;
|
|
156
|
+
seq: number;
|
|
157
|
+
actor: SiteCareActor;
|
|
158
|
+
action: unknown;
|
|
159
|
+
reason: unknown;
|
|
160
|
+
}, deps?: SiteCareDeps): Promise<SiteCareProjectInvoice>;
|
|
161
|
+
export interface SiteCareProjectView {
|
|
162
|
+
projectId: string;
|
|
163
|
+
project: SiteCareProject;
|
|
164
|
+
history: Array<AppendOnlyHistoryRow & {
|
|
165
|
+
$id: string;
|
|
166
|
+
}>;
|
|
167
|
+
}
|
|
168
|
+
/** A workspace's projects, newest first, each with its history. */
|
|
169
|
+
export declare function readSiteCareProjects(firestore: FirebaseFirestore.Firestore, orgId: string): Promise<SiteCareProjectView[]>;
|