@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,882 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { historyRow, requireHistoryReason } from "@aglyn/aglyn/app-utils/append-only-history";
|
|
18
|
+
import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
|
|
19
|
+
import { OWNER_APPROVAL_CHANNEL_WORDS, readOwnerApprovalInput } from "@aglyn/aglyn/app-utils/owner-approval-record";
|
|
20
|
+
import { formatSiteCareDate, formatSiteCareUsd, SITE_CARE_TIME_ZONE } from "@aglyn/aglyn/app-utils/site-care";
|
|
21
|
+
import { latestSiteCareProjectInvoice, readSiteCareProject, readSiteCareProjectScope, readSiteCareProjectTitle, SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE, SITE_CARE_PROJECT_MAX_HOURS, siteCareProjectAcceptanceIsCurrent, siteCareProjectAcceptanceSentence, siteCareProjectInvoiceDescription, siteCareProjectInvoiceMemo, siteCareProjectInvoiceWords, siteCareProjectNextInvoice, siteCareProjectQuote, siteCareProjectQuoteIsEditable, siteCareProjectSplitSentence, siteCareProjectStatus } from "@aglyn/aglyn/app-utils/site-care-project";
|
|
22
|
+
import { SITE_CARE_PROJECT_ACCEPTANCE_EMAIL_KEY, SITE_CARE_PROJECT_INVOICE_EMAIL_KEY, SITE_CARE_PROJECT_PAID_EMAIL_KEY, SITE_CARE_PROJECT_REVERSED_EMAIL_KEY } from "@aglyn/shared-util-email";
|
|
23
|
+
import { FieldValue } from "firebase-admin/firestore";
|
|
24
|
+
import { appendHistoryRow, commitHistoryRow, readHistoryRows } from "./append-only-history-write.js";
|
|
25
|
+
import { readOrgBilling } from "./org-billing.js";
|
|
26
|
+
import { sendSiteCareEmail } from "./site-care-emails.js";
|
|
27
|
+
import { createProjectInvoice, readProjectInvoice, SITE_CARE_PROJECT_METADATA_KEY, voidProjectInvoice } from "./site-care-project-stripe.js";
|
|
28
|
+
import { readSiteCareOrg, SITE_CARE_HISTORY_COLLECTION, SiteCareError, siteCareOwnerEmail } from "./site-care-requests.js";
|
|
29
|
+
import { creditExtraTimeItem, siteCareExtraTimeProduct } from "./site-care-stripe.js";
|
|
30
|
+
/**
|
|
31
|
+
* SITE CARE PROJECTS, WITH FIRESTORE AND STRIPE (AGL-3970).
|
|
32
|
+
*
|
|
33
|
+
* The staff "Charge for work": a flat-quoted project on the org
|
|
34
|
+
* (`orgs/{orgId}/siteCareProjects/{id}`) holding the scope, the quote, the
|
|
35
|
+
* owner's recorded yes, every invoice it raised and the launch, with an
|
|
36
|
+
* append-only history beside it (`…/siteCareProjects/{id}/siteCareHistory`).
|
|
37
|
+
* None of it is in the Firestore rules: every read and write passes the
|
|
38
|
+
* console's routes, as Site Care requests do.
|
|
39
|
+
*
|
|
40
|
+
* The same discipline as Site Care extra time, from the same modules:
|
|
41
|
+
* every change writes its history row in the same batch or transaction as
|
|
42
|
+
* the change, and a staff member's change writes its `adminAudit` row there
|
|
43
|
+
* too. Money moves in two steps around the Stripe calls — a `creating`
|
|
44
|
+
* invoice and its `invoice.requested` row commit first, then the calls under
|
|
45
|
+
* the invoice's own idempotency key, then the result and its row together —
|
|
46
|
+
* so a success with no row behind it is a `creating` invoice the
|
|
47
|
+
* reconciliation reports and a retry adopts. Reversals write their intent
|
|
48
|
+
* row before the call, keyed by the invoice's own key.
|
|
49
|
+
*
|
|
50
|
+
* The arithmetic is `@aglyn/aglyn/app-utils/site-care-project`, the yes
|
|
51
|
+
* `owner-approval-record`, the row `append-only-history`, the Stripe calls
|
|
52
|
+
* `site-care-project-stripe.ts`.
|
|
53
|
+
*/ export const SITE_CARE_PROJECTS_COLLECTION = 'siteCareProjects';
|
|
54
|
+
function projectRef(firestore, orgId, projectId) {
|
|
55
|
+
return firestore.collection('orgs').doc(orgId).collection(SITE_CARE_PROJECTS_COLLECTION).doc(projectId);
|
|
56
|
+
}
|
|
57
|
+
function projectHistory(firestore, orgId, projectId) {
|
|
58
|
+
return projectRef(firestore, orgId, projectId).collection(SITE_CARE_HISTORY_COLLECTION);
|
|
59
|
+
}
|
|
60
|
+
function projectAudit(orgId, projectId, action) {
|
|
61
|
+
return {
|
|
62
|
+
action: `siteCareProject.${action}`,
|
|
63
|
+
scope: 'siteCare',
|
|
64
|
+
target: `orgs/${orgId}/${SITE_CARE_PROJECTS_COLLECTION}/${projectId}`
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const nowOf = (deps)=>{
|
|
68
|
+
var _deps_now;
|
|
69
|
+
return ((_deps_now = deps.now) != null ? _deps_now : Date.now)();
|
|
70
|
+
};
|
|
71
|
+
const emailOf = (deps)=>{
|
|
72
|
+
var _deps_email;
|
|
73
|
+
return (_deps_email = deps.email) != null ? _deps_email : sendSiteCareEmail;
|
|
74
|
+
};
|
|
75
|
+
/** The project as it is stored: every field, its status recomputed. */ function projectDoc(project) {
|
|
76
|
+
return _extends({}, project, {
|
|
77
|
+
status: siteCareProjectStatus(project),
|
|
78
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
function loadedProject(snapshot) {
|
|
82
|
+
const data = snapshot.exists ? snapshot.data() : null;
|
|
83
|
+
if (!data) throw new SiteCareError('Unknown project', 404);
|
|
84
|
+
const project = readSiteCareProject(data);
|
|
85
|
+
if (!project) throw new SiteCareError('That project record is unreadable', 409);
|
|
86
|
+
return project;
|
|
87
|
+
}
|
|
88
|
+
function findInvoice(project, seq) {
|
|
89
|
+
const invoice = project.invoices.find((row)=>row.seq === seq);
|
|
90
|
+
if (!invoice) throw new SiteCareError('Unknown invoice on this project', 404);
|
|
91
|
+
return invoice;
|
|
92
|
+
}
|
|
93
|
+
function withInvoice(project, next) {
|
|
94
|
+
return _extends({}, project, {
|
|
95
|
+
invoices: project.invoices.map((row)=>row.seq === next.seq ? next : row)
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
function invoiceStripeRef(invoice) {
|
|
99
|
+
return invoice.invoiceId ? {
|
|
100
|
+
object: 'invoice',
|
|
101
|
+
id: invoice.invoiceId,
|
|
102
|
+
amountCents: invoice.totalCents || invoice.amountCents
|
|
103
|
+
} : null;
|
|
104
|
+
}
|
|
105
|
+
/** "Nov 2, 2026". */ function formatSiteCareDay(ms) {
|
|
106
|
+
return new Date(ms).toLocaleDateString('en-US', {
|
|
107
|
+
timeZone: SITE_CARE_TIME_ZONE,
|
|
108
|
+
month: 'short',
|
|
109
|
+
day: 'numeric',
|
|
110
|
+
year: 'numeric'
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** Records an email as the project's history row. Never throws. */ async function recordProjectEmail(firestore, orgId, projectId, result, what, atMs) {
|
|
114
|
+
var _result_reason;
|
|
115
|
+
await commitHistoryRow(firestore, projectHistory(firestore, orgId, projectId), historyRow({
|
|
116
|
+
atMs,
|
|
117
|
+
by: {
|
|
118
|
+
uid: null,
|
|
119
|
+
email: null
|
|
120
|
+
},
|
|
121
|
+
kind: result.sent ? 'email.sent' : 'email.notSent',
|
|
122
|
+
summary: result.sent ? `Emailed ${what} to ${result.to}.` : `The ${what} email was not sent${result.to ? ` to ${result.to}` : ''} (${(_result_reason = result.reason) != null ? _result_reason : 'unknown'}).`,
|
|
123
|
+
after: {
|
|
124
|
+
subject: result.subject,
|
|
125
|
+
to: result.to,
|
|
126
|
+
sent: result.sent
|
|
127
|
+
},
|
|
128
|
+
subjectId: projectId
|
|
129
|
+
})).catch((error)=>console.error('[site-care-projects] email history row failed', error));
|
|
130
|
+
}
|
|
131
|
+
/** Emails the owner, in the workspace's brand, and records it on the project. */ async function emailOwner(firestore, input, deps) {
|
|
132
|
+
const org = await readSiteCareOrg(firestore, input.orgId);
|
|
133
|
+
const to = await siteCareOwnerEmail(firestore, input.orgId, org);
|
|
134
|
+
const result = await emailOf(deps)({
|
|
135
|
+
key: input.key,
|
|
136
|
+
to,
|
|
137
|
+
org,
|
|
138
|
+
requestId: null,
|
|
139
|
+
merge: input.merge,
|
|
140
|
+
fallback: input.fallback
|
|
141
|
+
});
|
|
142
|
+
await recordProjectEmail(firestore, input.orgId, input.projectId, result, input.what, nowOf(deps));
|
|
143
|
+
return result;
|
|
144
|
+
}
|
|
145
|
+
function scopeText(project) {
|
|
146
|
+
return project.scope.map((line)=>`- ${line}`).join('\n');
|
|
147
|
+
}
|
|
148
|
+
function readQuoteInput(input) {
|
|
149
|
+
const title = readSiteCareProjectTitle(input.title);
|
|
150
|
+
if (title.ok === false) throw new SiteCareError(title.error, 400);
|
|
151
|
+
const scope = readSiteCareProjectScope(input.scope);
|
|
152
|
+
if (scope.ok === false) throw new SiteCareError(scope.error, 400);
|
|
153
|
+
const quote = siteCareProjectQuote({
|
|
154
|
+
kind: input.kind,
|
|
155
|
+
estimatedHours: input.estimatedHours,
|
|
156
|
+
priceUsd: input.priceUsd
|
|
157
|
+
});
|
|
158
|
+
if (quote.ok === false) throw new SiteCareError(quote.error, 400);
|
|
159
|
+
return {
|
|
160
|
+
title: title.title,
|
|
161
|
+
scope: scope.scope,
|
|
162
|
+
quote: quote.quote
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/** Quotes a project on a workspace. Nothing bills until the owner's yes is recorded. */ export async function createSiteCareProject(firestore, input, deps = {}) {
|
|
166
|
+
if (!input.orgId) throw new SiteCareError('Missing orgId', 400);
|
|
167
|
+
const { title, scope, quote } = readQuoteInput(input);
|
|
168
|
+
const org = await firestore.collection('orgs').doc(input.orgId).get();
|
|
169
|
+
if (!org.exists) throw new SiteCareError('Unknown workspace', 404);
|
|
170
|
+
const nowMs = nowOf(deps);
|
|
171
|
+
// Minted once, before the write: every invoice's Stripe idempotency key is
|
|
172
|
+
// built from this id, so it is fixed for the life of the project.
|
|
173
|
+
const ref = firestore.collection('orgs').doc(input.orgId).collection(SITE_CARE_PROJECTS_COLLECTION).doc(createResourceUid());
|
|
174
|
+
const project = {
|
|
175
|
+
orgId: input.orgId,
|
|
176
|
+
title,
|
|
177
|
+
scope,
|
|
178
|
+
quote,
|
|
179
|
+
quoteVersion: 1,
|
|
180
|
+
acceptance: null,
|
|
181
|
+
invoices: [],
|
|
182
|
+
invoiceSeq: 0,
|
|
183
|
+
firstInvoiceSentAtMs: null,
|
|
184
|
+
launchedAtMs: null,
|
|
185
|
+
launchedByUid: null,
|
|
186
|
+
status: 'quoted',
|
|
187
|
+
createdAtMs: nowMs,
|
|
188
|
+
createdByUid: input.actor.uid,
|
|
189
|
+
createdByEmail: input.actor.email,
|
|
190
|
+
updatedAtMs: nowMs
|
|
191
|
+
};
|
|
192
|
+
const batch = firestore.batch();
|
|
193
|
+
batch.create(ref, _extends({}, projectDoc(project), {
|
|
194
|
+
createdAt: FieldValue.serverTimestamp()
|
|
195
|
+
}));
|
|
196
|
+
appendHistoryRow(batch, firestore, ref.collection(SITE_CARE_HISTORY_COLLECTION), historyRow({
|
|
197
|
+
atMs: nowMs,
|
|
198
|
+
by: input.actor,
|
|
199
|
+
kind: 'project.quoted',
|
|
200
|
+
summary: `Quoted “${title}”: ${siteCareProjectSplitSentence(quote)}`,
|
|
201
|
+
after: {
|
|
202
|
+
title,
|
|
203
|
+
scope,
|
|
204
|
+
quote: _extends({}, quote)
|
|
205
|
+
},
|
|
206
|
+
subjectId: ref.id
|
|
207
|
+
}), projectAudit(input.orgId, ref.id, 'quoted'));
|
|
208
|
+
await batch.commit();
|
|
209
|
+
return {
|
|
210
|
+
projectId: ref.id,
|
|
211
|
+
project
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Changes a project's name, scope or price, with a reason — only until the
|
|
216
|
+
* first invoice is sent. Any change is a new quote version, so a yes the
|
|
217
|
+
* owner gave to the old one no longer invoices anything.
|
|
218
|
+
*/ export async function editSiteCareProject(firestore, input, deps = {}) {
|
|
219
|
+
const reason = requireHistoryReason(input.reason);
|
|
220
|
+
if (reason.ok === false) throw new SiteCareError(reason.error, 400);
|
|
221
|
+
const { title, scope, quote } = readQuoteInput(input);
|
|
222
|
+
const nowMs = nowOf(deps);
|
|
223
|
+
return firestore.runTransaction(async (tx)=>{
|
|
224
|
+
const ref = projectRef(firestore, input.orgId, input.projectId);
|
|
225
|
+
const project = loadedProject(await tx.get(ref));
|
|
226
|
+
if (!siteCareProjectQuoteIsEditable(project)) {
|
|
227
|
+
throw new SiteCareError('The first invoice is sent, so the quote is fixed. Void or credit an invoice from the project, and quote a new project for a new price.', 409);
|
|
228
|
+
}
|
|
229
|
+
const changed = title !== project.title || scope.join('\n') !== project.scope.join('\n') || quote.kind !== project.quote.kind || quote.estimatedHours !== project.quote.estimatedHours || quote.priceUsd !== project.quote.priceUsd;
|
|
230
|
+
if (!changed) throw new SiteCareError('Nothing changed.', 400);
|
|
231
|
+
const next = _extends({}, project, {
|
|
232
|
+
title,
|
|
233
|
+
scope,
|
|
234
|
+
quote,
|
|
235
|
+
quoteVersion: project.quoteVersion + 1,
|
|
236
|
+
updatedAtMs: nowMs
|
|
237
|
+
});
|
|
238
|
+
tx.set(ref, projectDoc(next));
|
|
239
|
+
const priceMoved = quote.priceUsd !== project.quote.priceUsd;
|
|
240
|
+
appendHistoryRow(tx, firestore, projectHistory(firestore, input.orgId, input.projectId), historyRow({
|
|
241
|
+
atMs: nowMs,
|
|
242
|
+
by: input.actor,
|
|
243
|
+
kind: 'quote.corrected',
|
|
244
|
+
summary: (priceMoved ? `Changed the quote from ${formatSiteCareUsd(project.quote.priceUsd * 100)} to ${formatSiteCareUsd(quote.priceUsd * 100)}.` : 'Changed the quote’s name or scope; the price is the same.') + (project.acceptance ? ' The owner’s yes must be recorded again for this quote.' : ''),
|
|
245
|
+
reason: reason.reason,
|
|
246
|
+
before: {
|
|
247
|
+
title: project.title,
|
|
248
|
+
scope: project.scope,
|
|
249
|
+
quote: _extends({}, project.quote),
|
|
250
|
+
quoteVersion: project.quoteVersion
|
|
251
|
+
},
|
|
252
|
+
after: {
|
|
253
|
+
title,
|
|
254
|
+
scope,
|
|
255
|
+
quote: _extends({}, quote),
|
|
256
|
+
quoteVersion: next.quoteVersion
|
|
257
|
+
},
|
|
258
|
+
subjectId: input.projectId
|
|
259
|
+
}), projectAudit(input.orgId, input.projectId, 'quote.corrected'));
|
|
260
|
+
return next;
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
// ── The owner's yes ─────────────────────────────────────────────────────────
|
|
264
|
+
/**
|
|
265
|
+
* Records — or corrects — how and when the owner accepted the quote as it
|
|
266
|
+
* stands, and emails them the confirmation of the scope and price that is
|
|
267
|
+
* the written record. Nothing is invoiced before this.
|
|
268
|
+
*/ export async function recordSiteCareProjectAcceptance(firestore, input, deps = {}) {
|
|
269
|
+
const nowMs = nowOf(deps);
|
|
270
|
+
const { project, record, previous } = await firestore.runTransaction(async (tx)=>{
|
|
271
|
+
const ref = projectRef(firestore, input.orgId, input.projectId);
|
|
272
|
+
const project = loadedProject(await tx.get(ref));
|
|
273
|
+
// A correction is of a yes to THIS quote; a yes to an older quote is
|
|
274
|
+
// replaced by a new one, which needs no reason — the quote changed.
|
|
275
|
+
const previous = siteCareProjectAcceptanceIsCurrent(project) ? project.acceptance : null;
|
|
276
|
+
const read = readOwnerApprovalInput(_extends({}, input.acceptance, {
|
|
277
|
+
hours: project.quote.billedHours
|
|
278
|
+
}), {
|
|
279
|
+
rateUsd: project.quote.rateUsd,
|
|
280
|
+
nowMs,
|
|
281
|
+
by: {
|
|
282
|
+
uid: input.actor.uid,
|
|
283
|
+
email: input.actor.email
|
|
284
|
+
},
|
|
285
|
+
previous,
|
|
286
|
+
maxHours: SITE_CARE_PROJECT_MAX_HOURS
|
|
287
|
+
});
|
|
288
|
+
if (read.ok === false) throw new SiteCareError(read.error, 400);
|
|
289
|
+
const record = _extends({}, read.record, previous || !project.acceptance ? {} : {
|
|
290
|
+
version: project.acceptance.version + 1
|
|
291
|
+
}, {
|
|
292
|
+
quoteVersion: project.quoteVersion,
|
|
293
|
+
priceUsd: project.quote.priceUsd
|
|
294
|
+
});
|
|
295
|
+
const next = _extends({}, project, {
|
|
296
|
+
acceptance: record,
|
|
297
|
+
updatedAtMs: nowMs
|
|
298
|
+
});
|
|
299
|
+
tx.set(ref, projectDoc(next));
|
|
300
|
+
appendHistoryRow(tx, firestore, projectHistory(firestore, input.orgId, input.projectId), historyRow({
|
|
301
|
+
atMs: nowMs,
|
|
302
|
+
by: input.actor,
|
|
303
|
+
kind: previous ? 'acceptance.corrected' : 'acceptance.recorded',
|
|
304
|
+
summary: previous ? `Corrected how the owner accepted the quote: ${OWNER_APPROVAL_CHANNEL_WORDS[record.channel]} on ${formatSiteCareDate(record.approvedAtMs)}.` : siteCareProjectAcceptanceSentence(record, project, formatSiteCareDate),
|
|
305
|
+
reason: record.correctionReason,
|
|
306
|
+
before: previous ? _extends({}, previous) : null,
|
|
307
|
+
after: _extends({}, record),
|
|
308
|
+
subjectId: input.projectId
|
|
309
|
+
}), projectAudit(input.orgId, input.projectId, previous ? 'acceptance.corrected' : 'acceptance.recorded'));
|
|
310
|
+
return {
|
|
311
|
+
project: next,
|
|
312
|
+
record,
|
|
313
|
+
previous
|
|
314
|
+
};
|
|
315
|
+
});
|
|
316
|
+
const sentence = siteCareProjectAcceptanceSentence(record, project, formatSiteCareDate);
|
|
317
|
+
const correction = previous ? `This corrects the earlier record: ${record.correctionReason}` : '';
|
|
318
|
+
const heading = previous ? 'Corrected: the quote you accepted' : 'You accepted our quote';
|
|
319
|
+
await emailOwner(firestore, {
|
|
320
|
+
orgId: input.orgId,
|
|
321
|
+
projectId: input.projectId,
|
|
322
|
+
key: SITE_CARE_PROJECT_ACCEPTANCE_EMAIL_KEY,
|
|
323
|
+
what: previous ? 'the corrected acceptance confirmation' : 'the acceptance confirmation',
|
|
324
|
+
merge: {
|
|
325
|
+
'project.title': project.title,
|
|
326
|
+
'project.scope': scopeText(project),
|
|
327
|
+
'acceptance.heading': heading,
|
|
328
|
+
'acceptance.sentence': sentence,
|
|
329
|
+
'acceptance.correction': correction
|
|
330
|
+
},
|
|
331
|
+
fallback: {
|
|
332
|
+
subject: `${heading}: ${project.title}`,
|
|
333
|
+
text: `${sentence} ${correction}\n\nWhat it covers:\n${scopeText(project)}\n\nIf this is not what you agreed to, reply to this email before you pay.`
|
|
334
|
+
}
|
|
335
|
+
}, deps);
|
|
336
|
+
return record;
|
|
337
|
+
}
|
|
338
|
+
// ── Invoices ────────────────────────────────────────────────────────────────
|
|
339
|
+
function invoiceKey(projectId, seq) {
|
|
340
|
+
return `site-care-project:${projectId}:invoice:${seq}`;
|
|
341
|
+
}
|
|
342
|
+
/** Writes a `creating` invoice and its intent row, under the rules of `siteCareProjectNextInvoice`. */ async function raiseInvoice(firestore, input, deps, prepare) {
|
|
343
|
+
const nowMs = nowOf(deps);
|
|
344
|
+
return firestore.runTransaction(async (tx)=>{
|
|
345
|
+
const ref = projectRef(firestore, input.orgId, input.projectId);
|
|
346
|
+
let project = loadedProject(await tx.get(ref));
|
|
347
|
+
const history = projectHistory(firestore, input.orgId, input.projectId);
|
|
348
|
+
const prepared = prepare ? prepare(project, nowMs) : null;
|
|
349
|
+
if (prepared) project = prepared.project;
|
|
350
|
+
const next = siteCareProjectNextInvoice(project);
|
|
351
|
+
if (next.ok === false) throw new SiteCareError(next.error, 409);
|
|
352
|
+
const seq = project.invoiceSeq + 1;
|
|
353
|
+
const invoice = {
|
|
354
|
+
seq,
|
|
355
|
+
kind: next.kind,
|
|
356
|
+
status: 'creating',
|
|
357
|
+
amountCents: next.amountCents,
|
|
358
|
+
description: siteCareProjectInvoiceDescription(project, next.kind),
|
|
359
|
+
idempotencyKey: invoiceKey(input.projectId, seq),
|
|
360
|
+
invoiceId: null,
|
|
361
|
+
invoiceItemId: null,
|
|
362
|
+
number: null,
|
|
363
|
+
hostedInvoiceUrl: null,
|
|
364
|
+
totalCents: 0,
|
|
365
|
+
amountPaidCents: 0,
|
|
366
|
+
creditNoteId: null,
|
|
367
|
+
refundId: null,
|
|
368
|
+
error: null,
|
|
369
|
+
createdAtMs: nowMs,
|
|
370
|
+
updatedAtMs: nowMs,
|
|
371
|
+
paidAtMs: null
|
|
372
|
+
};
|
|
373
|
+
const updated = _extends({}, project, {
|
|
374
|
+
invoices: [
|
|
375
|
+
...project.invoices,
|
|
376
|
+
invoice
|
|
377
|
+
],
|
|
378
|
+
invoiceSeq: seq,
|
|
379
|
+
updatedAtMs: nowMs
|
|
380
|
+
});
|
|
381
|
+
tx.set(ref, projectDoc(updated));
|
|
382
|
+
if (prepared) appendHistoryRow(tx, firestore, history, prepared.row, prepared.audit);
|
|
383
|
+
appendHistoryRow(tx, firestore, history, historyRow({
|
|
384
|
+
atMs: nowMs,
|
|
385
|
+
by: input.actor,
|
|
386
|
+
kind: 'invoice.requested',
|
|
387
|
+
summary: `Raising the ${siteCareProjectInvoiceWords(invoice.kind)} invoice: ${formatSiteCareUsd(invoice.amountCents)} plus tax.`,
|
|
388
|
+
after: {
|
|
389
|
+
seq,
|
|
390
|
+
kind: invoice.kind,
|
|
391
|
+
amountCents: invoice.amountCents,
|
|
392
|
+
idempotencyKey: invoice.idempotencyKey
|
|
393
|
+
},
|
|
394
|
+
subjectId: input.projectId
|
|
395
|
+
}), projectAudit(input.orgId, input.projectId, 'invoice.requested'));
|
|
396
|
+
return seq;
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
/** Emails the owner one invoice's pay link. */ async function emailInvoice(firestore, input, deps) {
|
|
400
|
+
var _invoice_number, _invoice_hostedInvoiceUrl, _invoice_hostedInvoiceUrl1;
|
|
401
|
+
const { project, invoice } = input;
|
|
402
|
+
const words = siteCareProjectInvoiceWords(invoice.kind);
|
|
403
|
+
const heading = invoice.kind === 'full' ? 'Your invoice' : `Your ${words} invoice`;
|
|
404
|
+
const amount = formatSiteCareUsd(invoice.amountCents);
|
|
405
|
+
const sentence = invoice.kind === 'deposit' ? `This is the deposit for “${project.title}”: ${amount}, half of the quote. We start work once it is paid, and invoice the other half when the project launches.` : invoice.kind === 'final' ? `“${project.title}” is live. This is the balance: ${amount}, the second half of the quote.` : `This is the ${amount} for “${project.title}”, in full. We start work once it is paid.`;
|
|
406
|
+
const due = formatSiteCareDay(invoice.createdAtMs + SITE_CARE_PROJECT_INVOICE_DAYS_UNTIL_DUE * 86400000);
|
|
407
|
+
const total = formatSiteCareUsd(invoice.totalCents || invoice.amountCents);
|
|
408
|
+
return emailOwner(firestore, {
|
|
409
|
+
orgId: input.orgId,
|
|
410
|
+
projectId: input.projectId,
|
|
411
|
+
key: SITE_CARE_PROJECT_INVOICE_EMAIL_KEY,
|
|
412
|
+
what: `${input.resent ? 'the pay link again for ' : 'the pay link for '}the ${words} invoice`,
|
|
413
|
+
merge: {
|
|
414
|
+
'project.title': project.title,
|
|
415
|
+
'project.scope': scopeText(project),
|
|
416
|
+
'invoice.heading': heading,
|
|
417
|
+
'invoice.sentence': `${sentence} Tax is included in the total.`,
|
|
418
|
+
'invoice.amount': total,
|
|
419
|
+
'invoice.number': (_invoice_number = invoice.number) != null ? _invoice_number : '',
|
|
420
|
+
'invoice.due': due,
|
|
421
|
+
'invoice.payUrl': (_invoice_hostedInvoiceUrl = invoice.hostedInvoiceUrl) != null ? _invoice_hostedInvoiceUrl : ''
|
|
422
|
+
},
|
|
423
|
+
fallback: {
|
|
424
|
+
subject: `${heading}: ${project.title}`,
|
|
425
|
+
text: `${sentence}\n\nAmount: ${total}\nDue: ${due}\nPay here: ${(_invoice_hostedInvoiceUrl1 = invoice.hostedInvoiceUrl) != null ? _invoice_hostedInvoiceUrl1 : ''}`
|
|
426
|
+
}
|
|
427
|
+
}, deps);
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Makes the Stripe invoice for a `creating` (or `failed`) record and writes
|
|
431
|
+
* the outcome; on success, emails the owner the pay link.
|
|
432
|
+
*/ async function settleInvoice(firestore, input, deps) {
|
|
433
|
+
var _billing_stripeCustomerId;
|
|
434
|
+
const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get());
|
|
435
|
+
const invoice = findInvoice(project, input.seq);
|
|
436
|
+
if (invoice.status !== 'creating' && invoice.status !== 'failed') return invoice;
|
|
437
|
+
const billing = await readOrgBilling(input.orgId);
|
|
438
|
+
const customerId = String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '');
|
|
439
|
+
const product = customerId ? await siteCareExtraTimeProduct(deps.stripe) : {
|
|
440
|
+
ok: false,
|
|
441
|
+
error: 'The workspace has no Stripe customer to invoice.'
|
|
442
|
+
};
|
|
443
|
+
const created = product.ok ? await createProjectInvoice({
|
|
444
|
+
customerId,
|
|
445
|
+
productId: product.productId,
|
|
446
|
+
orgId: input.orgId,
|
|
447
|
+
projectId: input.projectId,
|
|
448
|
+
seq: invoice.seq,
|
|
449
|
+
kind: invoice.kind,
|
|
450
|
+
amountCents: invoice.amountCents,
|
|
451
|
+
description: invoice.description,
|
|
452
|
+
memo: siteCareProjectInvoiceMemo(project),
|
|
453
|
+
idempotencyKey: invoice.idempotencyKey,
|
|
454
|
+
invoiceId: invoice.invoiceId,
|
|
455
|
+
sinceMs: project.createdAtMs
|
|
456
|
+
}, deps.stripe) : null;
|
|
457
|
+
const nowMs = nowOf(deps);
|
|
458
|
+
let next;
|
|
459
|
+
if (created && created.ok) {
|
|
460
|
+
var _state_invoiceItemId;
|
|
461
|
+
const state = created.state;
|
|
462
|
+
next = _extends({}, invoice, {
|
|
463
|
+
status: state.status === 'paid' ? 'paid' : 'open',
|
|
464
|
+
invoiceId: state.invoiceId,
|
|
465
|
+
invoiceItemId: (_state_invoiceItemId = state.invoiceItemId) != null ? _state_invoiceItemId : invoice.invoiceItemId,
|
|
466
|
+
number: state.number,
|
|
467
|
+
hostedInvoiceUrl: state.hostedInvoiceUrl,
|
|
468
|
+
totalCents: state.totalCents,
|
|
469
|
+
amountPaidCents: state.amountPaidCents,
|
|
470
|
+
error: null,
|
|
471
|
+
updatedAtMs: nowMs,
|
|
472
|
+
paidAtMs: state.status === 'paid' ? nowMs : null
|
|
473
|
+
});
|
|
474
|
+
} else {
|
|
475
|
+
var _created_invoiceId;
|
|
476
|
+
const error = product.ok === false ? product.error : created && created.ok === false ? created.error : 'Unknown failure';
|
|
477
|
+
const madeId = created && created.ok === false && 'invoiceId' in created ? (_created_invoiceId = created.invoiceId) != null ? _created_invoiceId : null : null;
|
|
478
|
+
next = _extends({}, invoice, {
|
|
479
|
+
status: 'failed',
|
|
480
|
+
invoiceId: madeId != null ? madeId : invoice.invoiceId,
|
|
481
|
+
error,
|
|
482
|
+
updatedAtMs: nowMs
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
const saved = await firestore.runTransaction(async (tx)=>{
|
|
486
|
+
var _current_firstInvoiceSentAtMs;
|
|
487
|
+
const ref = projectRef(firestore, input.orgId, input.projectId);
|
|
488
|
+
const current = loadedProject(await tx.get(ref));
|
|
489
|
+
const sent = next.status === 'open' || next.status === 'paid';
|
|
490
|
+
const updated = _extends({}, withInvoice(current, next), {
|
|
491
|
+
firstInvoiceSentAtMs: (_current_firstInvoiceSentAtMs = current.firstInvoiceSentAtMs) != null ? _current_firstInvoiceSentAtMs : sent ? nowMs : null,
|
|
492
|
+
updatedAtMs: nowMs
|
|
493
|
+
});
|
|
494
|
+
tx.set(ref, projectDoc(updated));
|
|
495
|
+
const words = siteCareProjectInvoiceWords(next.kind);
|
|
496
|
+
appendHistoryRow(tx, firestore, projectHistory(firestore, input.orgId, input.projectId), historyRow({
|
|
497
|
+
atMs: nowMs,
|
|
498
|
+
by: input.actor,
|
|
499
|
+
kind: sent ? 'invoice.sent' : 'invoice.failed',
|
|
500
|
+
summary: sent ? `Sent the ${words} invoice${next.number ? ` ${next.number}` : ''}: ${formatSiteCareUsd(next.totalCents || next.amountCents)} with tax.` : `The ${words} invoice could not be made: ${next.error}`,
|
|
501
|
+
after: {
|
|
502
|
+
seq: next.seq,
|
|
503
|
+
status: next.status,
|
|
504
|
+
invoiceId: next.invoiceId,
|
|
505
|
+
number: next.number,
|
|
506
|
+
totalCents: next.totalCents,
|
|
507
|
+
error: next.error
|
|
508
|
+
},
|
|
509
|
+
stripe: sent ? invoiceStripeRef(next) : null,
|
|
510
|
+
subjectId: input.projectId
|
|
511
|
+
}), projectAudit(input.orgId, input.projectId, sent ? 'invoice.sent' : 'invoice.failed'));
|
|
512
|
+
return updated;
|
|
513
|
+
});
|
|
514
|
+
if (next.status === 'open' || next.status === 'paid') {
|
|
515
|
+
await emailInvoice(firestore, {
|
|
516
|
+
orgId: input.orgId,
|
|
517
|
+
projectId: input.projectId,
|
|
518
|
+
project: saved,
|
|
519
|
+
invoice: next
|
|
520
|
+
}, deps);
|
|
521
|
+
}
|
|
522
|
+
return next;
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Raises the project's next invoice — the whole price, or the deposit —
|
|
526
|
+
* on the owner's current yes, and emails them the pay link.
|
|
527
|
+
*/ export async function sendSiteCareProjectInvoice(firestore, input, deps = {}) {
|
|
528
|
+
const seq = await raiseInvoice(firestore, input, deps);
|
|
529
|
+
return settleInvoice(firestore, _extends({}, input, {
|
|
530
|
+
seq
|
|
531
|
+
}), deps);
|
|
532
|
+
}
|
|
533
|
+
/** Re-runs an invoice that failed, or whose result never landed, under its own key. */ export async function retrySiteCareProjectInvoice(firestore, input, deps = {}) {
|
|
534
|
+
const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get());
|
|
535
|
+
const status = findInvoice(project, input.seq).status;
|
|
536
|
+
if (status !== 'failed' && status !== 'creating') {
|
|
537
|
+
throw new SiteCareError('That invoice is not waiting to be retried.', 409);
|
|
538
|
+
}
|
|
539
|
+
return settleInvoice(firestore, input, deps);
|
|
540
|
+
}
|
|
541
|
+
/** Emails the owner an open invoice's pay link again. */ export async function resendSiteCareProjectInvoice(firestore, input, deps = {}) {
|
|
542
|
+
const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get());
|
|
543
|
+
const invoice = findInvoice(project, input.seq);
|
|
544
|
+
if (invoice.status !== 'open' || !invoice.hostedInvoiceUrl) {
|
|
545
|
+
throw new SiteCareError('Only an unpaid invoice’s pay link is sent again.', 409);
|
|
546
|
+
}
|
|
547
|
+
return emailInvoice(firestore, {
|
|
548
|
+
orgId: input.orgId,
|
|
549
|
+
projectId: input.projectId,
|
|
550
|
+
project,
|
|
551
|
+
invoice,
|
|
552
|
+
resent: true
|
|
553
|
+
}, deps);
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Marks the project launched. A half-and-half project raises its balance
|
|
557
|
+
* invoice from the same record, in the same step, and emails the pay link.
|
|
558
|
+
* Launch comes after the first invoice is paid: both splits are paid up
|
|
559
|
+
* front before work starts.
|
|
560
|
+
*/ export async function launchSiteCareProject(firestore, input, deps = {}) {
|
|
561
|
+
const markLaunched = (project, nowMs)=>{
|
|
562
|
+
if (project.launchedAtMs) throw new SiteCareError('This project is already marked launched.', 409);
|
|
563
|
+
const first = latestSiteCareProjectInvoice(project, project.quote.split === 'full' ? 'full' : 'deposit');
|
|
564
|
+
if ((first == null ? void 0 : first.status) !== 'paid') {
|
|
565
|
+
throw new SiteCareError(project.quote.split === 'full' ? 'Mark it launched once the invoice is paid.' : 'Mark it launched once the deposit is paid.', 409);
|
|
566
|
+
}
|
|
567
|
+
return {
|
|
568
|
+
project: _extends({}, project, {
|
|
569
|
+
launchedAtMs: nowMs,
|
|
570
|
+
launchedByUid: input.actor.uid,
|
|
571
|
+
updatedAtMs: nowMs
|
|
572
|
+
}),
|
|
573
|
+
row: historyRow({
|
|
574
|
+
atMs: nowMs,
|
|
575
|
+
by: input.actor,
|
|
576
|
+
kind: 'project.launched',
|
|
577
|
+
summary: project.quote.split === 'half' ? `Marked “${project.title}” launched; the balance is invoiced now.` : `Marked “${project.title}” launched.`,
|
|
578
|
+
after: {
|
|
579
|
+
launchedAtMs: nowMs
|
|
580
|
+
},
|
|
581
|
+
subjectId: input.projectId
|
|
582
|
+
}),
|
|
583
|
+
audit: projectAudit(input.orgId, input.projectId, 'launched')
|
|
584
|
+
};
|
|
585
|
+
};
|
|
586
|
+
const before = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get());
|
|
587
|
+
if (before.quote.split === 'full') {
|
|
588
|
+
const nowMs = nowOf(deps);
|
|
589
|
+
const project = await firestore.runTransaction(async (tx)=>{
|
|
590
|
+
const ref = projectRef(firestore, input.orgId, input.projectId);
|
|
591
|
+
const marked = markLaunched(loadedProject(await tx.get(ref)), nowMs);
|
|
592
|
+
tx.set(ref, projectDoc(marked.project));
|
|
593
|
+
appendHistoryRow(tx, firestore, projectHistory(firestore, input.orgId, input.projectId), marked.row, marked.audit);
|
|
594
|
+
return marked.project;
|
|
595
|
+
});
|
|
596
|
+
return {
|
|
597
|
+
project,
|
|
598
|
+
invoice: null
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
const seq = await raiseInvoice(firestore, input, deps, markLaunched);
|
|
602
|
+
const invoice = await settleInvoice(firestore, _extends({}, input, {
|
|
603
|
+
seq
|
|
604
|
+
}), deps);
|
|
605
|
+
const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get());
|
|
606
|
+
return {
|
|
607
|
+
project,
|
|
608
|
+
invoice
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Records a project invoice as paid — from the billing webhook's
|
|
613
|
+
* `invoice.paid`, or from staff's "Check payments" when a delivery was
|
|
614
|
+
* missed — and emails the owner the receipt. Idempotent: a redelivery of a
|
|
615
|
+
* payment already recorded changes nothing and sends nothing.
|
|
616
|
+
*/ export async function recordSiteCareProjectPayment(firestore, input, deps = {}) {
|
|
617
|
+
const projectId = input.metadata[SITE_CARE_PROJECT_METADATA_KEY];
|
|
618
|
+
if (!projectId || !input.invoiceId) return 'ignored';
|
|
619
|
+
const nowMs = nowOf(deps);
|
|
620
|
+
const result = await firestore.runTransaction(async (tx)=>{
|
|
621
|
+
var _project_firstInvoiceSentAtMs;
|
|
622
|
+
const ref = projectRef(firestore, input.orgId, projectId);
|
|
623
|
+
const snapshot = await tx.get(ref);
|
|
624
|
+
if (!snapshot.exists) return null;
|
|
625
|
+
const project = loadedProject(snapshot);
|
|
626
|
+
const invoice = project.invoices.find((row)=>row.invoiceId === input.invoiceId);
|
|
627
|
+
if (!invoice) return null;
|
|
628
|
+
if (invoice.status === 'paid') return {
|
|
629
|
+
outcome: 'already',
|
|
630
|
+
project,
|
|
631
|
+
invoice
|
|
632
|
+
};
|
|
633
|
+
// A voided or credited invoice reads as "paid" at nothing once fully
|
|
634
|
+
// credited; that is not money arriving.
|
|
635
|
+
const unpayable = [
|
|
636
|
+
'voided',
|
|
637
|
+
'credited',
|
|
638
|
+
'refunded'
|
|
639
|
+
];
|
|
640
|
+
if (unpayable.includes(invoice.status)) return null;
|
|
641
|
+
const paid = _extends({}, invoice, {
|
|
642
|
+
status: 'paid',
|
|
643
|
+
amountPaidCents: Math.max(0, Math.floor(input.amountPaidCents)),
|
|
644
|
+
error: null,
|
|
645
|
+
paidAtMs: nowMs,
|
|
646
|
+
updatedAtMs: nowMs
|
|
647
|
+
});
|
|
648
|
+
const updated = _extends({}, withInvoice(project, paid), {
|
|
649
|
+
firstInvoiceSentAtMs: (_project_firstInvoiceSentAtMs = project.firstInvoiceSentAtMs) != null ? _project_firstInvoiceSentAtMs : nowMs,
|
|
650
|
+
updatedAtMs: nowMs
|
|
651
|
+
});
|
|
652
|
+
tx.set(ref, projectDoc(updated));
|
|
653
|
+
appendHistoryRow(tx, firestore, projectHistory(firestore, input.orgId, projectId), historyRow({
|
|
654
|
+
atMs: nowMs,
|
|
655
|
+
by: {
|
|
656
|
+
uid: null,
|
|
657
|
+
email: null
|
|
658
|
+
},
|
|
659
|
+
kind: 'invoice.paid',
|
|
660
|
+
summary: `Received ${formatSiteCareUsd(paid.amountPaidCents)} for the ${siteCareProjectInvoiceWords(paid.kind)}${input.paidOutOfBand ? ' (marked paid outside the card page)' : ''}.`,
|
|
661
|
+
before: {
|
|
662
|
+
status: invoice.status
|
|
663
|
+
},
|
|
664
|
+
after: {
|
|
665
|
+
status: 'paid',
|
|
666
|
+
amountPaidCents: paid.amountPaidCents
|
|
667
|
+
},
|
|
668
|
+
stripe: {
|
|
669
|
+
object: 'invoice',
|
|
670
|
+
id: input.invoiceId,
|
|
671
|
+
amountCents: paid.amountPaidCents
|
|
672
|
+
},
|
|
673
|
+
subjectId: projectId
|
|
674
|
+
}));
|
|
675
|
+
return {
|
|
676
|
+
outcome: 'recorded',
|
|
677
|
+
project: updated,
|
|
678
|
+
invoice: paid
|
|
679
|
+
};
|
|
680
|
+
});
|
|
681
|
+
if (!result) return 'ignored';
|
|
682
|
+
if (result.outcome === 'already') return 'already';
|
|
683
|
+
const { project, invoice } = result;
|
|
684
|
+
const amount = formatSiteCareUsd(invoice.amountPaidCents);
|
|
685
|
+
const sentence = `Thank you. We received your payment of ${amount} for “${project.title}”.`;
|
|
686
|
+
const next = invoice.kind === 'deposit' ? 'We are starting work. The other half is invoiced when your project launches.' : invoice.kind === 'final' ? 'The project is paid in full. Thank you!' : 'The project is paid in full. We start work now and will let you know when it is live.';
|
|
687
|
+
await emailOwner(firestore, {
|
|
688
|
+
orgId: input.orgId,
|
|
689
|
+
projectId,
|
|
690
|
+
key: SITE_CARE_PROJECT_PAID_EMAIL_KEY,
|
|
691
|
+
what: 'the payment receipt',
|
|
692
|
+
merge: {
|
|
693
|
+
'project.title': project.title,
|
|
694
|
+
'payment.amount': amount,
|
|
695
|
+
'payment.sentence': sentence,
|
|
696
|
+
'payment.next': next
|
|
697
|
+
},
|
|
698
|
+
fallback: {
|
|
699
|
+
subject: `Payment received: ${project.title}`,
|
|
700
|
+
text: `${sentence} ${next}`
|
|
701
|
+
}
|
|
702
|
+
}, deps);
|
|
703
|
+
return 'recorded';
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Reads each unpaid invoice of a project from Stripe and records any that
|
|
707
|
+
* were paid, for a webhook delivery that never arrived.
|
|
708
|
+
*/ export async function checkSiteCareProjectPayments(firestore, input, deps = {}) {
|
|
709
|
+
const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get());
|
|
710
|
+
let recorded = 0;
|
|
711
|
+
for (const invoice of project.invoices){
|
|
712
|
+
var _read_state;
|
|
713
|
+
if (invoice.status !== 'open' || !invoice.invoiceId) continue;
|
|
714
|
+
const read = await readProjectInvoice(invoice.invoiceId, deps.stripe);
|
|
715
|
+
if (read.ok === false) throw new SiteCareError(read.error, 502);
|
|
716
|
+
if (((_read_state = read.state) == null ? void 0 : _read_state.status) !== 'paid') continue;
|
|
717
|
+
const outcome = await recordSiteCareProjectPayment(firestore, {
|
|
718
|
+
orgId: input.orgId,
|
|
719
|
+
invoiceId: invoice.invoiceId,
|
|
720
|
+
metadata: {
|
|
721
|
+
[SITE_CARE_PROJECT_METADATA_KEY]: input.projectId
|
|
722
|
+
},
|
|
723
|
+
amountPaidCents: read.state.amountPaidCents
|
|
724
|
+
}, deps);
|
|
725
|
+
if (outcome === 'recorded') recorded += 1;
|
|
726
|
+
}
|
|
727
|
+
return {
|
|
728
|
+
recorded
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Voids an unpaid invoice, credits it, or refunds a paid one — from the
|
|
733
|
+
* record, with a reason, never by hand in Stripe. The intent row commits
|
|
734
|
+
* before the call; the owner is emailed the outcome.
|
|
735
|
+
*/ export async function reverseSiteCareProjectInvoice(firestore, input, deps = {}) {
|
|
736
|
+
var _input_action, _ref;
|
|
737
|
+
var _read_state;
|
|
738
|
+
const action = String((_input_action = input.action) != null ? _input_action : '');
|
|
739
|
+
if (action !== 'void' && action !== 'credit' && action !== 'refund') {
|
|
740
|
+
throw new SiteCareError('Choose void, credit or refund.', 400);
|
|
741
|
+
}
|
|
742
|
+
const reason = requireHistoryReason(input.reason);
|
|
743
|
+
if (reason.ok === false) throw new SiteCareError(reason.error, 400);
|
|
744
|
+
const project = loadedProject(await projectRef(firestore, input.orgId, input.projectId).get());
|
|
745
|
+
const invoice = findInvoice(project, input.seq);
|
|
746
|
+
if (!invoice.invoiceId || invoice.status !== 'open' && invoice.status !== 'paid') {
|
|
747
|
+
throw new SiteCareError('Only a sent invoice, unpaid or paid, can be voided, credited or refunded.', 409);
|
|
748
|
+
}
|
|
749
|
+
const read = await readProjectInvoice(invoice.invoiceId, deps.stripe);
|
|
750
|
+
if (read.ok === false) throw new SiteCareError(read.error, 502);
|
|
751
|
+
const stage = (_ref = (_read_state = read.state) == null ? void 0 : _read_state.status) != null ? _ref : 'missing';
|
|
752
|
+
if (action === 'refund' && stage !== 'paid') {
|
|
753
|
+
throw new SiteCareError(`The invoice is ${stage} in Stripe, not paid; void or credit it instead.`, 409);
|
|
754
|
+
}
|
|
755
|
+
if (action !== 'refund' && stage !== 'open') {
|
|
756
|
+
throw new SiteCareError(stage === 'paid' ? 'The invoice is paid. Check payments to record it, then refund it.' : `The invoice is ${stage} in Stripe; there is nothing to ${action}.`, 409);
|
|
757
|
+
}
|
|
758
|
+
if (action !== 'void' && !invoice.invoiceItemId) {
|
|
759
|
+
throw new SiteCareError('The record has no line to credit on this invoice.', 409);
|
|
760
|
+
}
|
|
761
|
+
const words = siteCareProjectInvoiceWords(invoice.kind);
|
|
762
|
+
const amount = formatSiteCareUsd(invoice.amountCents);
|
|
763
|
+
const history = projectHistory(firestore, input.orgId, input.projectId);
|
|
764
|
+
// The intent first, so a call whose answer is lost still left a row.
|
|
765
|
+
await commitHistoryRow(firestore, history, historyRow({
|
|
766
|
+
atMs: nowOf(deps),
|
|
767
|
+
by: input.actor,
|
|
768
|
+
kind: `invoice.${action}Requested`,
|
|
769
|
+
summary: `Reversing the ${words} invoice (${amount}): ${action}.`,
|
|
770
|
+
reason: reason.reason,
|
|
771
|
+
before: {
|
|
772
|
+
seq: invoice.seq,
|
|
773
|
+
status: invoice.status,
|
|
774
|
+
stage
|
|
775
|
+
},
|
|
776
|
+
subjectId: input.projectId
|
|
777
|
+
}), projectAudit(input.orgId, input.projectId, `invoice.${action}Requested`));
|
|
778
|
+
let next;
|
|
779
|
+
let stripe;
|
|
780
|
+
if (action === 'void') {
|
|
781
|
+
const voided = await voidProjectInvoice({
|
|
782
|
+
invoiceId: invoice.invoiceId,
|
|
783
|
+
idempotencyKey: `${invoice.idempotencyKey}:void`
|
|
784
|
+
}, deps.stripe);
|
|
785
|
+
if (voided.ok === false) throw new SiteCareError(voided.error, 502);
|
|
786
|
+
next = _extends({}, invoice, {
|
|
787
|
+
status: 'voided',
|
|
788
|
+
error: null,
|
|
789
|
+
updatedAtMs: nowOf(deps)
|
|
790
|
+
});
|
|
791
|
+
stripe = {
|
|
792
|
+
object: 'invoice',
|
|
793
|
+
id: invoice.invoiceId,
|
|
794
|
+
amountCents: invoice.totalCents || invoice.amountCents
|
|
795
|
+
};
|
|
796
|
+
} else {
|
|
797
|
+
const credited = await creditExtraTimeItem({
|
|
798
|
+
invoiceId: invoice.invoiceId,
|
|
799
|
+
invoiceItemId: String(invoice.invoiceItemId),
|
|
800
|
+
refund: action === 'refund',
|
|
801
|
+
memo: `Project: ${reason.reason}`,
|
|
802
|
+
metadata: {
|
|
803
|
+
[SITE_CARE_PROJECT_METADATA_KEY]: input.projectId,
|
|
804
|
+
orgId: input.orgId
|
|
805
|
+
},
|
|
806
|
+
idempotencyKey: `${invoice.idempotencyKey}:${action}`
|
|
807
|
+
}, deps.stripe);
|
|
808
|
+
if (credited.ok === false) throw new SiteCareError(credited.error, 502);
|
|
809
|
+
next = _extends({}, invoice, {
|
|
810
|
+
status: action === 'refund' ? 'refunded' : 'credited',
|
|
811
|
+
creditNoteId: credited.creditNoteId,
|
|
812
|
+
refundId: credited.refundId,
|
|
813
|
+
error: null,
|
|
814
|
+
updatedAtMs: nowOf(deps)
|
|
815
|
+
});
|
|
816
|
+
stripe = {
|
|
817
|
+
object: 'credit_note',
|
|
818
|
+
id: credited.creditNoteId,
|
|
819
|
+
amountCents: credited.amountCents
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
const doneKind = `invoice.${next.status}`;
|
|
823
|
+
await firestore.runTransaction(async (tx)=>{
|
|
824
|
+
const ref = projectRef(firestore, input.orgId, input.projectId);
|
|
825
|
+
const current = loadedProject(await tx.get(ref));
|
|
826
|
+
tx.set(ref, projectDoc(_extends({}, withInvoice(current, next), {
|
|
827
|
+
updatedAtMs: nowOf(deps)
|
|
828
|
+
})));
|
|
829
|
+
appendHistoryRow(tx, firestore, history, historyRow({
|
|
830
|
+
atMs: nowOf(deps),
|
|
831
|
+
by: input.actor,
|
|
832
|
+
kind: doneKind,
|
|
833
|
+
summary: next.status === 'voided' ? `Voided the ${words} invoice (${amount}); nothing is owed on it.` : next.status === 'refunded' ? `Refunded the ${words} (${amount} plus its tax) to the card it was paid with.` : `Credited the ${words} invoice (${amount} plus its tax); nothing is owed on it.`,
|
|
834
|
+
reason: reason.reason,
|
|
835
|
+
before: {
|
|
836
|
+
status: invoice.status
|
|
837
|
+
},
|
|
838
|
+
after: {
|
|
839
|
+
status: next.status,
|
|
840
|
+
creditNoteId: next.creditNoteId,
|
|
841
|
+
refundId: next.refundId
|
|
842
|
+
},
|
|
843
|
+
stripe,
|
|
844
|
+
subjectId: input.projectId
|
|
845
|
+
}), projectAudit(input.orgId, input.projectId, doneKind));
|
|
846
|
+
});
|
|
847
|
+
const heading = next.status === 'voided' ? 'Invoice canceled' : next.status === 'refunded' ? 'Payment refunded' : 'Invoice credited';
|
|
848
|
+
const sentence = next.status === 'voided' ? `We canceled the ${amount} ${words} invoice for “${project.title}”. You do not owe it.` : next.status === 'refunded' ? `We refunded the ${amount} ${words} for “${project.title}”, with its tax, to the card it was paid with.` : `We credited the ${amount} ${words} invoice for “${project.title}”, with its tax. You do not owe it.`;
|
|
849
|
+
await emailOwner(firestore, {
|
|
850
|
+
orgId: input.orgId,
|
|
851
|
+
projectId: input.projectId,
|
|
852
|
+
key: SITE_CARE_PROJECT_REVERSED_EMAIL_KEY,
|
|
853
|
+
what: 'the invoice notice',
|
|
854
|
+
merge: {
|
|
855
|
+
'project.title': project.title,
|
|
856
|
+
'reversal.heading': heading,
|
|
857
|
+
'reversal.sentence': sentence,
|
|
858
|
+
'reversal.reason': reason.reason
|
|
859
|
+
},
|
|
860
|
+
fallback: {
|
|
861
|
+
subject: `${heading}: ${project.title}`,
|
|
862
|
+
text: `${sentence}\n\nWhy: ${reason.reason}`
|
|
863
|
+
}
|
|
864
|
+
}, deps);
|
|
865
|
+
return next;
|
|
866
|
+
}
|
|
867
|
+
/** A workspace's projects, newest first, each with its history. */ export async function readSiteCareProjects(firestore, orgId) {
|
|
868
|
+
const snapshot = await firestore.collection('orgs').doc(orgId).collection(SITE_CARE_PROJECTS_COLLECTION).orderBy('createdAtMs', 'desc').limit(100).get();
|
|
869
|
+
const views = await Promise.all(snapshot.docs.map(async (doc)=>{
|
|
870
|
+
const project = readSiteCareProject(doc.data());
|
|
871
|
+
if (!project) return null;
|
|
872
|
+
const history = await readHistoryRows(doc.ref.collection(SITE_CARE_HISTORY_COLLECTION));
|
|
873
|
+
return {
|
|
874
|
+
projectId: doc.id,
|
|
875
|
+
project,
|
|
876
|
+
history
|
|
877
|
+
};
|
|
878
|
+
}));
|
|
879
|
+
return views.filter((view)=>Boolean(view)).sort((a, b)=>b.project.createdAtMs - a.project.createdAtMs);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
//# sourceMappingURL=site-care-projects.js.map
|