@aglyn/tenant-data-admin 1.0.0-beta.269 → 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/render-cache.d.ts +10 -3
- package/src/lib/render-cache.js +10 -3
- package/src/lib/render-cache.js.map +1 -1
- 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 -30
- package/src/lib/server/billing-addons.js +102 -77
- 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/configured-url-fetch.d.ts +26 -0
- package/src/lib/server/configured-url-fetch.js +68 -0
- package/src/lib/server/configured-url-fetch.js.map +1 -1
- package/src/lib/server/custom-domain-redirects.d.ts +50 -0
- package/src/lib/server/custom-domain-redirects.js +61 -0
- package/src/lib/server/custom-domain-redirects.js.map +1 -0
- package/src/lib/server/host-custom-domain.d.ts +125 -0
- package/src/lib/server/host-custom-domain.js +395 -0
- package/src/lib/server/host-custom-domain.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/host-released-names.d.ts +1 -2
- package/src/lib/server/host-released-names.js +4 -2
- package/src/lib/server/host-released-names.js.map +1 -1
- package/src/lib/server/media-photo-links.d.ts +196 -0
- package/src/lib/server/media-photo-links.js +290 -0
- package/src/lib/server/media-photo-links.js.map +1 -0
- 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/organizations.d.ts +25 -1
- package/src/lib/server/organizations.js +62 -2
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/personal-data-export.js +21 -1
- package/src/lib/server/personal-data-export.js.map +1 -1
- package/src/lib/server/push-delivery.js +32 -14
- package/src/lib/server/push-delivery.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/tenant-dns-check.d.ts +58 -0
- package/src/lib/server/tenant-dns-check.js +197 -0
- package/src/lib/server/tenant-dns-check.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 +5 -0
- package/src/tenancy.js +10 -0
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1,1414 @@
|
|
|
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 { describeHours, ownerApprovalSentence, readOwnerApprovalInput, readOwnerApprovalRecord } from "@aglyn/aglyn/app-utils/owner-approval-record";
|
|
20
|
+
import { hasSiteCare, resolveEffectivePlan, SITE_CARE_EXTRA_HOUR_USD } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
21
|
+
import { 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 } from "@aglyn/aglyn/app-utils/site-care";
|
|
22
|
+
import { addBusinessDays } from "@aglyn/aglyn/app-utils/support-tiers";
|
|
23
|
+
import { 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 } from "@aglyn/shared-util-email";
|
|
24
|
+
import { createHash } from "node:crypto";
|
|
25
|
+
import { FieldValue, Timestamp } from "firebase-admin/firestore";
|
|
26
|
+
import { appendHistoryRow, commitHistoryRow, readHistoryRows } from "./append-only-history-write.js";
|
|
27
|
+
import { notifyStaff } from "./notifications.js";
|
|
28
|
+
import { readOrgBilling } from "./org-billing.js";
|
|
29
|
+
import { sendSiteCareEmail } from "./site-care-emails.js";
|
|
30
|
+
import { createExtraTimeItem, creditExtraTimeItem, deleteExtraTimeItem, extraTimeItemIsEditable, readExtraTimeItem, siteCareExtraTimeProduct, siteCareSubscriptionId, subscriptionInvoiceFinalizedSince, updateExtraTimeItem } from "./site-care-stripe.js";
|
|
31
|
+
/**
|
|
32
|
+
* SITE CARE REQUESTS, WITH FIRESTORE AND STRIPE (AGL-3959).
|
|
33
|
+
*
|
|
34
|
+
* A request is a support ticket (`supportTickets/{id}`, `kind: 'siteCare'`)
|
|
35
|
+
* with a `siteCare` map holding everything about the work: the timer, the
|
|
36
|
+
* one number staff close it with, how its minutes counted against the
|
|
37
|
+
* included hour, the owner's recorded approval, the extra-time charge and
|
|
38
|
+
* the publish that shipped it. Beside it, an append-only history
|
|
39
|
+
* (`supportTickets/{id}/siteCareHistory`), and per workspace and month a
|
|
40
|
+
* document for goodwill minutes with its own history
|
|
41
|
+
* (`orgs/{orgId}/siteCareMonths/{YYYY-MM}`). None of it is in the Firestore
|
|
42
|
+
* rules: every read and write passes the console's routes, as the rest of
|
|
43
|
+
* the support system does.
|
|
44
|
+
*
|
|
45
|
+
* Every change writes its history row in the same batch or transaction as
|
|
46
|
+
* the change, and a staff member's change writes its `adminAudit` row there
|
|
47
|
+
* too. Money moves in two steps around the Stripe call: a `charge.requested`
|
|
48
|
+
* row and a `creating` charge commit first, then the call, then the result
|
|
49
|
+
* and its row commit together. A Stripe success with no row behind it is a
|
|
50
|
+
* `creating` charge with no item — which the reconciliation reports, and
|
|
51
|
+
* which `retrySiteCareCharge` settles under the same idempotency key.
|
|
52
|
+
*
|
|
53
|
+
* The arithmetic is `@aglyn/aglyn/app-utils/site-care`, the approval record
|
|
54
|
+
* `owner-approval-record`, the row `append-only-history`.
|
|
55
|
+
*/ const TICKETS = 'supportTickets';
|
|
56
|
+
export const SITE_CARE_HISTORY_COLLECTION = 'siteCareHistory';
|
|
57
|
+
export const SITE_CARE_MONTHS_COLLECTION = 'siteCareMonths';
|
|
58
|
+
/** A refusal the caller turns into a response. */ export class SiteCareError extends Error {
|
|
59
|
+
constructor(message, status = 400, detail = null){
|
|
60
|
+
super(message);
|
|
61
|
+
this.name = 'SiteCareError';
|
|
62
|
+
this.status = status;
|
|
63
|
+
this.detail = detail;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const nowOf = (deps)=>{
|
|
67
|
+
var _deps_now;
|
|
68
|
+
return ((_deps_now = deps.now) != null ? _deps_now : Date.now)();
|
|
69
|
+
};
|
|
70
|
+
const emailOf = (deps)=>{
|
|
71
|
+
var _deps_email;
|
|
72
|
+
return (_deps_email = deps.email) != null ? _deps_email : sendSiteCareEmail;
|
|
73
|
+
};
|
|
74
|
+
function ticketRef(firestore, ticketId) {
|
|
75
|
+
return firestore.collection(TICKETS).doc(ticketId);
|
|
76
|
+
}
|
|
77
|
+
function ticketHistory(firestore, ticketId) {
|
|
78
|
+
return ticketRef(firestore, ticketId).collection(SITE_CARE_HISTORY_COLLECTION);
|
|
79
|
+
}
|
|
80
|
+
function monthRef(firestore, orgId, month) {
|
|
81
|
+
return firestore.collection('orgs').doc(orgId).collection(SITE_CARE_MONTHS_COLLECTION).doc(month);
|
|
82
|
+
}
|
|
83
|
+
function monthHistory(firestore, orgId, month) {
|
|
84
|
+
return monthRef(firestore, orgId, month).collection(SITE_CARE_HISTORY_COLLECTION);
|
|
85
|
+
}
|
|
86
|
+
function requestAudit(orgId, ticketId, action) {
|
|
87
|
+
return {
|
|
88
|
+
action: `siteCare.${action}`,
|
|
89
|
+
scope: 'siteCare',
|
|
90
|
+
target: `orgs/${orgId}/siteCare/${ticketId}`
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function monthAudit(orgId, month, action) {
|
|
94
|
+
return {
|
|
95
|
+
action: `siteCare.${action}`,
|
|
96
|
+
scope: 'siteCare',
|
|
97
|
+
target: `orgs/${orgId}/siteCareMonths/${month}`
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** A fresh request's map. */ export function newSiteCareRequest(input) {
|
|
101
|
+
return {
|
|
102
|
+
source: input.source,
|
|
103
|
+
hostId: input.hostId,
|
|
104
|
+
requesterEmail: input.requesterEmail,
|
|
105
|
+
state: 'open',
|
|
106
|
+
month: input.month,
|
|
107
|
+
timerStartedAtMs: null,
|
|
108
|
+
timerStartedByUid: null,
|
|
109
|
+
closedAtMs: null,
|
|
110
|
+
minutesLogged: null,
|
|
111
|
+
timerMinutes: null,
|
|
112
|
+
countedMinutes: 0,
|
|
113
|
+
includedMinutesUsed: 0,
|
|
114
|
+
overMinutes: 0,
|
|
115
|
+
billedHours: 0,
|
|
116
|
+
absorbed: false,
|
|
117
|
+
approval: null,
|
|
118
|
+
charge: null,
|
|
119
|
+
chargeSeq: 0,
|
|
120
|
+
publish: null
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/** A stored map read back with every field present. */ export function readSiteCareRequest(value) {
|
|
124
|
+
var _stored_hostId, _stored_requesterEmail, _stored_charge, _stored_publish;
|
|
125
|
+
if (!value || typeof value !== 'object') return null;
|
|
126
|
+
const stored = value;
|
|
127
|
+
const base = newSiteCareRequest({
|
|
128
|
+
source: stored.source === 'email' ? 'email' : 'console',
|
|
129
|
+
hostId: (_stored_hostId = stored.hostId) != null ? _stored_hostId : null,
|
|
130
|
+
requesterEmail: (_stored_requesterEmail = stored.requesterEmail) != null ? _stored_requesterEmail : null,
|
|
131
|
+
month: isSiteCareMonthKey(stored.month) ? stored.month : siteCareMonthKey(Date.now())
|
|
132
|
+
});
|
|
133
|
+
return _extends({}, base, stored, {
|
|
134
|
+
approval: readOwnerApprovalRecord(stored.approval),
|
|
135
|
+
charge: (_stored_charge = stored.charge) != null ? _stored_charge : null,
|
|
136
|
+
chargeSeq: Number(stored.chargeSeq) || 0,
|
|
137
|
+
publish: (_stored_publish = stored.publish) != null ? _stored_publish : null
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
function loadedTicket(snapshot) {
|
|
141
|
+
var _snapshot_data, _data_orgId, _data_subject;
|
|
142
|
+
const data = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : null;
|
|
143
|
+
if (!data) throw new SiteCareError('Unknown request', 404);
|
|
144
|
+
if (data['kind'] !== SITE_CARE_TICKET_KIND) throw new SiteCareError('That ticket is not a Site Care request', 400);
|
|
145
|
+
const request = readSiteCareRequest(data['siteCare']);
|
|
146
|
+
if (!request) throw new SiteCareError('That ticket has no Site Care record', 409);
|
|
147
|
+
return {
|
|
148
|
+
ref: snapshot.ref,
|
|
149
|
+
orgId: String((_data_orgId = data['orgId']) != null ? _data_orgId : ''),
|
|
150
|
+
subject: String((_data_subject = data['subject']) != null ? _data_subject : ''),
|
|
151
|
+
request,
|
|
152
|
+
data
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/** The org document joined with its billing keys, as `hasSiteCare` reads it. */ export async function readSiteCareOrg(firestore, orgId) {
|
|
156
|
+
var _snapshot_data;
|
|
157
|
+
const snapshot = await firestore.collection('orgs').doc(orgId).get();
|
|
158
|
+
if (!snapshot.exists) return null;
|
|
159
|
+
const billing = await readOrgBilling(orgId);
|
|
160
|
+
return _extends({
|
|
161
|
+
$id: orgId
|
|
162
|
+
}, (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {}, billing != null ? billing : {});
|
|
163
|
+
}
|
|
164
|
+
/** Whether a workspace has Site Care in force. */ export function orgHasSiteCare(org) {
|
|
165
|
+
return Boolean(org) && hasSiteCare(org);
|
|
166
|
+
}
|
|
167
|
+
/** The owner's address, from the owner's member row. */ export async function siteCareOwnerEmail(firestore, orgId, org) {
|
|
168
|
+
const ownerUid = typeof (org == null ? void 0 : org['ownerUid']) === 'string' ? org['ownerUid'] : '';
|
|
169
|
+
if (!ownerUid) return null;
|
|
170
|
+
const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(ownerUid).get();
|
|
171
|
+
const email = member.get('email');
|
|
172
|
+
return typeof email === 'string' && email ? email : null;
|
|
173
|
+
}
|
|
174
|
+
/** Records an email as the request's (or the month's) history row. */ async function recordEmail(firestore, history, result, what, atMs, subjectId) {
|
|
175
|
+
var _result_reason;
|
|
176
|
+
await commitHistoryRow(firestore, history, historyRow({
|
|
177
|
+
atMs,
|
|
178
|
+
by: {
|
|
179
|
+
uid: null,
|
|
180
|
+
email: null
|
|
181
|
+
},
|
|
182
|
+
kind: result.sent ? 'email.sent' : 'email.notSent',
|
|
183
|
+
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'}).`,
|
|
184
|
+
after: {
|
|
185
|
+
subject: result.subject,
|
|
186
|
+
to: result.to,
|
|
187
|
+
sent: result.sent
|
|
188
|
+
},
|
|
189
|
+
subjectId
|
|
190
|
+
})).catch((error)=>console.error('[site-care] email history row failed', error));
|
|
191
|
+
}
|
|
192
|
+
/** A document id derived from a received message, alphanumeric so it fits a reply address. */ export function siteCareMessageDocId(prefix, key) {
|
|
193
|
+
return `${prefix}${createHash('sha256').update(key).digest('hex').slice(0, 24)}`;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Opens a request: the tagged ticket, its first message, the opening history
|
|
197
|
+
* row, the staff notice and the "we have your request" email. Shared by the
|
|
198
|
+
* console's "Request a change" and the inbound address.
|
|
199
|
+
*/ export async function openSiteCareRequest(firestore, input, deps = {}) {
|
|
200
|
+
var _input_subject, _input_body, _input_requester_email, _input_requester_email1, _input_org_name;
|
|
201
|
+
const subject = String((_input_subject = input.subject) != null ? _input_subject : '').trim().slice(0, SITE_CARE_SUBJECT_MAX);
|
|
202
|
+
const body = String((_input_body = input.body) != null ? _input_body : '').trim().slice(0, SITE_CARE_BODY_MAX);
|
|
203
|
+
if (!subject) throw new SiteCareError('Say what you would like changed.', 400);
|
|
204
|
+
if (!body) throw new SiteCareError('Describe the change.', 400);
|
|
205
|
+
if (!orgHasSiteCare(input.org)) {
|
|
206
|
+
throw new SiteCareError('Site Care is not on this workspace. Add it on Billing.', 403);
|
|
207
|
+
}
|
|
208
|
+
const nowMs = nowOf(deps);
|
|
209
|
+
const month = siteCareMonthKey(nowMs);
|
|
210
|
+
const dueAtMs = addBusinessDays(nowMs, SITE_CARE_RESPONSE_BUSINESS_DAYS);
|
|
211
|
+
const ref = input.dedupeKey ? firestore.collection(TICKETS).doc(siteCareMessageDocId('care', input.dedupeKey)) : firestore.collection(TICKETS).doc(createResourceUid());
|
|
212
|
+
if (input.dedupeKey && (await ref.get()).exists) return {
|
|
213
|
+
ticketId: ref.id,
|
|
214
|
+
dueAtMs,
|
|
215
|
+
duplicate: true
|
|
216
|
+
};
|
|
217
|
+
const now = FieldValue.serverTimestamp();
|
|
218
|
+
const batch = firestore.batch();
|
|
219
|
+
batch.create(ref, {
|
|
220
|
+
orgId: input.orgId,
|
|
221
|
+
subject,
|
|
222
|
+
status: 'open',
|
|
223
|
+
kind: SITE_CARE_TICKET_KIND,
|
|
224
|
+
plan: resolveEffectivePlan(input.org),
|
|
225
|
+
supportTier: 'siteCare',
|
|
226
|
+
supportTierRank: 0,
|
|
227
|
+
// Site Care's promise is DONE within two business days, so the clock
|
|
228
|
+
// runs until the request closes, not until the first staff reply.
|
|
229
|
+
responseDueAt: Timestamp.fromMillis(dueAtMs),
|
|
230
|
+
firstRespondedAt: null,
|
|
231
|
+
siteCare: newSiteCareRequest({
|
|
232
|
+
source: input.source,
|
|
233
|
+
hostId: input.hostId,
|
|
234
|
+
requesterEmail: input.requester.email,
|
|
235
|
+
month
|
|
236
|
+
}),
|
|
237
|
+
siteCareMonth: month,
|
|
238
|
+
siteCareOrgMonth: siteCareOrgMonth(input.orgId, month),
|
|
239
|
+
createdAt: now,
|
|
240
|
+
updatedAt: now
|
|
241
|
+
});
|
|
242
|
+
batch.create(ref.collection('messages').doc(createResourceUid()), {
|
|
243
|
+
authorId: input.requester.uid,
|
|
244
|
+
authorEmail: input.requester.email,
|
|
245
|
+
staff: false,
|
|
246
|
+
body,
|
|
247
|
+
source: input.source,
|
|
248
|
+
createdAt: now
|
|
249
|
+
});
|
|
250
|
+
appendHistoryRow(batch, firestore, ref.collection(SITE_CARE_HISTORY_COLLECTION), historyRow({
|
|
251
|
+
atMs: nowMs,
|
|
252
|
+
by: input.requester,
|
|
253
|
+
kind: 'request.opened',
|
|
254
|
+
summary: `${(_input_requester_email = input.requester.email) != null ? _input_requester_email : 'The owner'} asked ${input.source === 'email' ? 'by email' : 'from the console'}: “${subject}”.`,
|
|
255
|
+
after: {
|
|
256
|
+
subject,
|
|
257
|
+
source: input.source,
|
|
258
|
+
dueAtMs
|
|
259
|
+
},
|
|
260
|
+
subjectId: ref.id
|
|
261
|
+
}));
|
|
262
|
+
await batch.commit();
|
|
263
|
+
await notifyStaff({
|
|
264
|
+
type: 'support.ticketOpened',
|
|
265
|
+
title: `New Site Care request: ${subject}`,
|
|
266
|
+
body: `${(_input_requester_email1 = input.requester.email) != null ? _input_requester_email1 : 'An owner'} asked ${input.source === 'email' ? 'by email' : 'from the console'} ` + `for workspace ${String((_input_org_name = input.org['name']) != null ? _input_org_name : input.orgId)} (${input.orgId}). ` + `It is due done by ${formatSiteCareDate(dueAtMs)}.`,
|
|
267
|
+
link: `/admin/support?ticketId=${ref.id}`,
|
|
268
|
+
orgId: input.orgId
|
|
269
|
+
});
|
|
270
|
+
const due = new Date(dueAtMs).toLocaleDateString('en-US', {
|
|
271
|
+
weekday: 'long',
|
|
272
|
+
month: 'long',
|
|
273
|
+
day: 'numeric',
|
|
274
|
+
timeZone: 'America/Chicago'
|
|
275
|
+
});
|
|
276
|
+
const result = await emailOf(deps)({
|
|
277
|
+
key: SITE_CARE_REQUEST_RECEIVED_EMAIL_KEY,
|
|
278
|
+
to: input.requester.email,
|
|
279
|
+
org: input.org,
|
|
280
|
+
requestId: ref.id,
|
|
281
|
+
merge: {
|
|
282
|
+
'request.title': subject,
|
|
283
|
+
'request.message': body,
|
|
284
|
+
'request.due': due
|
|
285
|
+
},
|
|
286
|
+
fallback: {
|
|
287
|
+
subject: `We have your request: ${subject}`,
|
|
288
|
+
text: `We received “${subject}” and will have it done by ${due}.\n\n${body}`
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
await recordEmail(firestore, ref.collection(SITE_CARE_HISTORY_COLLECTION), result, 'the request receipt', nowOf(deps), ref.id);
|
|
292
|
+
return {
|
|
293
|
+
ticketId: ref.id,
|
|
294
|
+
dueAtMs
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Adds a reply that arrived by email to its request's thread. The sender
|
|
299
|
+
* must be a member of the request's workspace.
|
|
300
|
+
*/ export async function appendSiteCareReply(firestore, input, deps = {}) {
|
|
301
|
+
var _input_body, _input_from_email, _input_from_email1;
|
|
302
|
+
const snapshot = await ticketRef(firestore, input.ticketId).get();
|
|
303
|
+
if (!snapshot.exists) return {
|
|
304
|
+
appended: false
|
|
305
|
+
};
|
|
306
|
+
const ticket = loadedTicket(snapshot);
|
|
307
|
+
const body = String((_input_body = input.body) != null ? _input_body : '').trim().slice(0, SITE_CARE_BODY_MAX);
|
|
308
|
+
if (!body) return {
|
|
309
|
+
appended: false
|
|
310
|
+
};
|
|
311
|
+
const nowMs = nowOf(deps);
|
|
312
|
+
const now = FieldValue.serverTimestamp();
|
|
313
|
+
const messageRef = input.dedupeKey ? ticket.ref.collection('messages').doc(siteCareMessageDocId('mail', input.dedupeKey)) : ticket.ref.collection('messages').doc(createResourceUid());
|
|
314
|
+
if (input.dedupeKey && (await messageRef.get()).exists) return {
|
|
315
|
+
appended: false
|
|
316
|
+
};
|
|
317
|
+
const batch = firestore.batch();
|
|
318
|
+
batch.create(messageRef, {
|
|
319
|
+
authorId: input.from.uid,
|
|
320
|
+
authorEmail: input.from.email,
|
|
321
|
+
staff: false,
|
|
322
|
+
body,
|
|
323
|
+
source: 'email',
|
|
324
|
+
createdAt: now
|
|
325
|
+
});
|
|
326
|
+
batch.update(ticket.ref, {
|
|
327
|
+
status: 'open',
|
|
328
|
+
updatedAt: now
|
|
329
|
+
});
|
|
330
|
+
appendHistoryRow(batch, firestore, ticketHistory(firestore, input.ticketId), historyRow({
|
|
331
|
+
atMs: nowMs,
|
|
332
|
+
by: input.from,
|
|
333
|
+
kind: 'request.replied',
|
|
334
|
+
summary: `${(_input_from_email = input.from.email) != null ? _input_from_email : 'The owner'} replied by email.`,
|
|
335
|
+
subjectId: input.ticketId
|
|
336
|
+
}));
|
|
337
|
+
await batch.commit();
|
|
338
|
+
await notifyStaff({
|
|
339
|
+
type: 'support.ticketReply',
|
|
340
|
+
title: `Site Care reply: ${ticket.subject}`,
|
|
341
|
+
body: `${(_input_from_email1 = input.from.email) != null ? _input_from_email1 : 'The owner'} replied by email on “${ticket.subject.slice(0, 120)}” for workspace ${ticket.orgId}.`,
|
|
342
|
+
link: `/admin/support?ticketId=${input.ticketId}`,
|
|
343
|
+
orgId: ticket.orgId
|
|
344
|
+
});
|
|
345
|
+
return {
|
|
346
|
+
appended: true
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
// ── Timer ───────────────────────────────────────────────────────────────────
|
|
350
|
+
/**
|
|
351
|
+
* Starts the request's timer the first time staff open it. A second open,
|
|
352
|
+
* a reload or another staff member opening it changes nothing.
|
|
353
|
+
*/ export async function startSiteCareTimer(firestore, input, deps = {}) {
|
|
354
|
+
return firestore.runTransaction(async (tx)=>{
|
|
355
|
+
const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)));
|
|
356
|
+
if (ticket.request.state !== 'open' || ticket.request.timerStartedAtMs) return ticket.request;
|
|
357
|
+
const nowMs = nowOf(deps);
|
|
358
|
+
const request = _extends({}, ticket.request, {
|
|
359
|
+
timerStartedAtMs: nowMs,
|
|
360
|
+
timerStartedByUid: input.actor.uid
|
|
361
|
+
});
|
|
362
|
+
tx.update(ticket.ref, {
|
|
363
|
+
siteCare: request,
|
|
364
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
365
|
+
});
|
|
366
|
+
appendHistoryRow(tx, firestore, ticketHistory(firestore, input.ticketId), historyRow({
|
|
367
|
+
atMs: nowMs,
|
|
368
|
+
by: input.actor,
|
|
369
|
+
kind: 'timer.started',
|
|
370
|
+
summary: 'Started work.',
|
|
371
|
+
after: {
|
|
372
|
+
timerStartedAtMs: nowMs
|
|
373
|
+
},
|
|
374
|
+
subjectId: input.ticketId
|
|
375
|
+
}), requestAudit(ticket.orgId, input.ticketId, 'timer.started'));
|
|
376
|
+
return request;
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
async function readMonthContext(reader, firestore, orgId, month, excludeTicketId) {
|
|
380
|
+
var _monthSnap_get;
|
|
381
|
+
const query = firestore.collection(TICKETS).where('siteCareOrgMonth', '==', siteCareOrgMonth(orgId, month));
|
|
382
|
+
const [monthSnap, requests] = reader ? await Promise.all([
|
|
383
|
+
reader.get(monthRef(firestore, orgId, month)),
|
|
384
|
+
reader.get(query)
|
|
385
|
+
]) : await Promise.all([
|
|
386
|
+
monthRef(firestore, orgId, month).get(),
|
|
387
|
+
query.get()
|
|
388
|
+
]);
|
|
389
|
+
const others = requests.docs.filter((doc)=>doc.id !== excludeTicketId).map((doc)=>{
|
|
390
|
+
var _doc_get;
|
|
391
|
+
return siteCareStatementRequest(doc.id, String((_doc_get = doc.get('subject')) != null ? _doc_get : ''), readSiteCareRequest(doc.get('siteCare')));
|
|
392
|
+
});
|
|
393
|
+
return {
|
|
394
|
+
goodwillMinutes: Number((_monthSnap_get = monthSnap.get('goodwillMinutes')) != null ? _monthSnap_get : 0) || 0,
|
|
395
|
+
otherIncludedUsed: others.filter((r)=>r.state === 'closed').reduce((sum, r)=>sum + r.includedMinutesUsed, 0),
|
|
396
|
+
others
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
function statementWith(month, context, ticketId, subject, request) {
|
|
400
|
+
return siteCareMonthStatement({
|
|
401
|
+
month,
|
|
402
|
+
goodwillMinutes: context.goodwillMinutes,
|
|
403
|
+
requests: [
|
|
404
|
+
...context.others,
|
|
405
|
+
siteCareStatementRequest(ticketId, subject, request)
|
|
406
|
+
]
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/** Why a close or a correction is blocked, as the staff panel says it. */ export function siteCareBlockedMessage(verdict) {
|
|
410
|
+
var _verdict_approvedHours;
|
|
411
|
+
return verdict.reason === 'no-approval' ? `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.` : `This needs ${describeHours(verdict.requiredHours)} of extra time and the owner approved ${describeHours((_verdict_approvedHours = verdict.approvedHours) != null ? _verdict_approvedHours : 0)}. Ask the owner first, or absorb it.`;
|
|
412
|
+
}
|
|
413
|
+
// ── Publish link ────────────────────────────────────────────────────────────
|
|
414
|
+
/**
|
|
415
|
+
* The newest publish on any of the workspace's sites since `sinceMs`, from
|
|
416
|
+
* each site's activity log — the change the request shipped.
|
|
417
|
+
*/ export async function findSiteCarePublish(firestore, orgId, sinceMs) {
|
|
418
|
+
const hosts = await firestore.collection('hosts').where('orgId', '==', orgId).limit(10).get();
|
|
419
|
+
let best = null;
|
|
420
|
+
for (const host of hosts.docs){
|
|
421
|
+
const rows = await host.ref.collection('activity').where('createdAt', '>=', Timestamp.fromMillis(sinceMs)).orderBy('createdAt', 'desc').limit(50).get();
|
|
422
|
+
for (const row of rows.docs){
|
|
423
|
+
var _ref;
|
|
424
|
+
var _row_get_toMillis, _row_get;
|
|
425
|
+
const action = row.get('action');
|
|
426
|
+
if (!isSiteCarePublishAction(action)) continue;
|
|
427
|
+
const atMs = (_ref = (_row_get = row.get('createdAt')) == null ? void 0 : (_row_get_toMillis = _row_get.toMillis) == null ? void 0 : _row_get_toMillis.call(_row_get)) != null ? _ref : 0;
|
|
428
|
+
if (!best || atMs > best.atMs) {
|
|
429
|
+
var _row_get1, _row_get2;
|
|
430
|
+
best = {
|
|
431
|
+
hostId: host.id,
|
|
432
|
+
activityId: row.id,
|
|
433
|
+
action: String(action),
|
|
434
|
+
targetName: (_row_get1 = row.get('target.name')) != null ? _row_get1 : null,
|
|
435
|
+
targetId: (_row_get2 = row.get('target.id')) != null ? _row_get2 : null,
|
|
436
|
+
atMs
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
break;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return best;
|
|
443
|
+
}
|
|
444
|
+
// ── Charges ─────────────────────────────────────────────────────────────────
|
|
445
|
+
function chargeKey(ticketId, seq) {
|
|
446
|
+
return `site-care:${ticketId}:charge:${seq}`;
|
|
447
|
+
}
|
|
448
|
+
function newCharge(input) {
|
|
449
|
+
return {
|
|
450
|
+
status: 'creating',
|
|
451
|
+
hours: input.hours,
|
|
452
|
+
amountCents: siteCareExtraTimeCents(input.hours),
|
|
453
|
+
description: input.description,
|
|
454
|
+
idempotencyKey: chargeKey(input.ticketId, input.seq),
|
|
455
|
+
invoiceItemId: null,
|
|
456
|
+
invoiceId: null,
|
|
457
|
+
creditNoteId: null,
|
|
458
|
+
refundId: null,
|
|
459
|
+
error: null,
|
|
460
|
+
updatedAtMs: input.nowMs
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
function chargeRequestedRow(ticketId, charge, actor, nowMs) {
|
|
464
|
+
return historyRow({
|
|
465
|
+
atMs: nowMs,
|
|
466
|
+
by: actor,
|
|
467
|
+
kind: 'charge.requested',
|
|
468
|
+
summary: `Adding ${describeHours(charge.hours)} of extra time (${formatSiteCareUsd(charge.amountCents)}) to the next invoice.`,
|
|
469
|
+
after: {
|
|
470
|
+
hours: charge.hours,
|
|
471
|
+
amountCents: charge.amountCents,
|
|
472
|
+
idempotencyKey: charge.idempotencyKey
|
|
473
|
+
},
|
|
474
|
+
subjectId: ticketId
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Creates the Stripe item for a `creating` (or `failed`) charge and records
|
|
479
|
+
* the outcome. The key is the charge's own, so a retry after a lost
|
|
480
|
+
* response returns the item the first call made rather than a second one.
|
|
481
|
+
*/ async function settleCharge(firestore, input, deps) {
|
|
482
|
+
var _billing_stripeCustomerId;
|
|
483
|
+
const snapshot = await ticketRef(firestore, input.ticketId).get();
|
|
484
|
+
const ticket = loadedTicket(snapshot);
|
|
485
|
+
const charge = ticket.request.charge;
|
|
486
|
+
if (!charge || charge.status !== 'creating' && charge.status !== 'failed') return charge;
|
|
487
|
+
const billing = await readOrgBilling(ticket.orgId);
|
|
488
|
+
const customerId = String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '');
|
|
489
|
+
const subscription = await siteCareSubscriptionId(customerId, deps.stripe);
|
|
490
|
+
const product = subscription.ok ? await siteCareExtraTimeProduct(deps.stripe) : null;
|
|
491
|
+
const created = subscription.ok && (product == null ? void 0 : product.ok) ? await createExtraTimeItem({
|
|
492
|
+
customerId,
|
|
493
|
+
subscriptionId: subscription.subscriptionId,
|
|
494
|
+
productId: product.productId,
|
|
495
|
+
hours: charge.hours,
|
|
496
|
+
description: charge.description,
|
|
497
|
+
metadata: {
|
|
498
|
+
siteCareRequestId: input.ticketId,
|
|
499
|
+
orgId: ticket.orgId,
|
|
500
|
+
month: ticket.request.month
|
|
501
|
+
},
|
|
502
|
+
idempotencyKey: charge.idempotencyKey
|
|
503
|
+
}, deps.stripe) : null;
|
|
504
|
+
const nowMs = nowOf(deps);
|
|
505
|
+
const error = subscription.ok === false ? subscription.error : product && product.ok === false ? product.error : created && created.ok === false ? created.error : null;
|
|
506
|
+
const next = created && created.ok ? _extends({}, charge, {
|
|
507
|
+
status: 'pending',
|
|
508
|
+
invoiceItemId: created.invoiceItemId,
|
|
509
|
+
error: null,
|
|
510
|
+
updatedAtMs: nowMs
|
|
511
|
+
}) : _extends({}, charge, {
|
|
512
|
+
status: 'failed',
|
|
513
|
+
error: error != null ? error : 'Unknown failure',
|
|
514
|
+
updatedAtMs: nowMs
|
|
515
|
+
});
|
|
516
|
+
const batch = firestore.batch();
|
|
517
|
+
batch.update(ticket.ref, {
|
|
518
|
+
'siteCare.charge': next,
|
|
519
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
520
|
+
});
|
|
521
|
+
appendHistoryRow(batch, firestore, ticketHistory(firestore, input.ticketId), historyRow({
|
|
522
|
+
atMs: nowMs,
|
|
523
|
+
by: input.actor,
|
|
524
|
+
kind: next.status === 'pending' ? 'charge.created' : 'charge.failed',
|
|
525
|
+
summary: next.status === 'pending' ? `Added ${describeHours(next.hours)} of extra time (${formatSiteCareUsd(next.amountCents)}) to the next invoice.` : `The extra time could not be added to the invoice: ${next.error}`,
|
|
526
|
+
after: {
|
|
527
|
+
status: next.status,
|
|
528
|
+
invoiceItemId: next.invoiceItemId,
|
|
529
|
+
error: next.error
|
|
530
|
+
},
|
|
531
|
+
stripe: next.status === 'pending' && next.invoiceItemId ? {
|
|
532
|
+
object: 'invoiceitem',
|
|
533
|
+
id: next.invoiceItemId,
|
|
534
|
+
amountCents: next.amountCents
|
|
535
|
+
} : null,
|
|
536
|
+
subjectId: input.ticketId
|
|
537
|
+
}), requestAudit(ticket.orgId, input.ticketId, next.status === 'pending' ? 'charge.created' : 'charge.failed'));
|
|
538
|
+
await batch.commit();
|
|
539
|
+
return next;
|
|
540
|
+
}
|
|
541
|
+
/** Re-runs a charge that failed, or whose result never landed. */ export async function retrySiteCareCharge(firestore, input, deps = {}) {
|
|
542
|
+
var _ticket_request_charge;
|
|
543
|
+
const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get());
|
|
544
|
+
const status = (_ticket_request_charge = ticket.request.charge) == null ? void 0 : _ticket_request_charge.status;
|
|
545
|
+
if (status !== 'failed' && status !== 'creating') {
|
|
546
|
+
throw new SiteCareError('There is no charge waiting to be retried on this request.', 409);
|
|
547
|
+
}
|
|
548
|
+
return settleCharge(firestore, input, deps);
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Closes a request with one number. Refuses with the verdict when the
|
|
552
|
+
* minutes take the month past the included hour and no approval covers it
|
|
553
|
+
* — the panel then offers "Ask the owner first" and "Absorb it".
|
|
554
|
+
*/ export async function closeSiteCareRequest(firestore, input, deps = {}) {
|
|
555
|
+
var _ref, _first_request_timerStartedAtMs;
|
|
556
|
+
var _first_data_createdAt_toMillis, _first_data_createdAt;
|
|
557
|
+
const minutes = readSiteCareMinutes(input.minutes);
|
|
558
|
+
if (minutes === null) throw new SiteCareError('Enter the minutes this took.', 400);
|
|
559
|
+
const nowMs = nowOf(deps);
|
|
560
|
+
const month = siteCareMonthKey(nowMs);
|
|
561
|
+
const first = loadedTicket(await ticketRef(firestore, input.ticketId).get());
|
|
562
|
+
const publish = await findSiteCarePublish(firestore, first.orgId, (_ref = (_first_request_timerStartedAtMs = first.request.timerStartedAtMs) != null ? _first_request_timerStartedAtMs : (_first_data_createdAt = first.data['createdAt']) == null ? void 0 : (_first_data_createdAt_toMillis = _first_data_createdAt.toMillis) == null ? void 0 : _first_data_createdAt_toMillis.call(_first_data_createdAt)) != null ? _ref : nowMs).catch(()=>null);
|
|
563
|
+
const result = await firestore.runTransaction(async (tx)=>{
|
|
564
|
+
var _ref;
|
|
565
|
+
const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)));
|
|
566
|
+
if (ticket.request.state === 'closed') throw new SiteCareError('This request is already closed. Correct its minutes instead.', 409);
|
|
567
|
+
const context = await readMonthContext(tx, firestore, ticket.orgId, month, input.ticketId);
|
|
568
|
+
const allocation = allocateSiteCareMinutes({
|
|
569
|
+
minutes,
|
|
570
|
+
otherIncludedUsed: context.otherIncludedUsed,
|
|
571
|
+
goodwillMinutes: context.goodwillMinutes
|
|
572
|
+
});
|
|
573
|
+
const verdict = siteCareCloseVerdict({
|
|
574
|
+
requiredHours: allocation.requiredHours,
|
|
575
|
+
approval: ticket.request.approval,
|
|
576
|
+
absorb: input.absorb === true
|
|
577
|
+
});
|
|
578
|
+
if (verdict.ok === false) {
|
|
579
|
+
throw new SiteCareError(siteCareBlockedMessage(verdict), 409, {
|
|
580
|
+
blocked: verdict,
|
|
581
|
+
allocation
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
const timerMinutes = ticket.request.timerStartedAtMs ? Math.round((nowMs - ticket.request.timerStartedAtMs) / 60000) : null;
|
|
585
|
+
let request = _extends({}, ticket.request, {
|
|
586
|
+
state: 'closed',
|
|
587
|
+
month,
|
|
588
|
+
closedAtMs: nowMs,
|
|
589
|
+
minutesLogged: minutes,
|
|
590
|
+
timerMinutes,
|
|
591
|
+
countedMinutes: allocation.countedMinutes,
|
|
592
|
+
includedMinutesUsed: allocation.includedMinutesUsed,
|
|
593
|
+
overMinutes: allocation.overMinutes,
|
|
594
|
+
billedHours: verdict.billedHours,
|
|
595
|
+
absorbed: verdict.absorbed,
|
|
596
|
+
publish
|
|
597
|
+
});
|
|
598
|
+
let charge = null;
|
|
599
|
+
if (verdict.billedHours > 0) {
|
|
600
|
+
var _ref1;
|
|
601
|
+
var _request_approval;
|
|
602
|
+
const statement = statementWith(month, context, input.ticketId, ticket.subject, request);
|
|
603
|
+
const seq = request.chargeSeq + 1;
|
|
604
|
+
charge = newCharge({
|
|
605
|
+
ticketId: input.ticketId,
|
|
606
|
+
seq,
|
|
607
|
+
hours: verdict.billedHours,
|
|
608
|
+
description: siteCareExtraTimeDescription({
|
|
609
|
+
title: ticket.subject,
|
|
610
|
+
minutesLogged: minutes,
|
|
611
|
+
overMinutes: allocation.overMinutes,
|
|
612
|
+
billedHours: verdict.billedHours,
|
|
613
|
+
approvedHours: (_ref1 = (_request_approval = request.approval) == null ? void 0 : _request_approval.hours) != null ? _ref1 : null,
|
|
614
|
+
statement
|
|
615
|
+
}),
|
|
616
|
+
nowMs
|
|
617
|
+
});
|
|
618
|
+
request = _extends({}, request, {
|
|
619
|
+
charge,
|
|
620
|
+
chargeSeq: seq
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
const statement = statementWith(month, context, input.ticketId, ticket.subject, request);
|
|
624
|
+
tx.update(ticket.ref, _extends({
|
|
625
|
+
siteCare: request,
|
|
626
|
+
siteCareMonth: month,
|
|
627
|
+
siteCareOrgMonth: siteCareOrgMonth(ticket.orgId, month),
|
|
628
|
+
status: 'closed'
|
|
629
|
+
}, ticket.data['firstRespondedAt'] ? {} : {
|
|
630
|
+
firstRespondedAt: FieldValue.serverTimestamp()
|
|
631
|
+
}, {
|
|
632
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
633
|
+
}));
|
|
634
|
+
const history = ticketHistory(firestore, input.ticketId);
|
|
635
|
+
if (timerMinutes !== null) {
|
|
636
|
+
appendHistoryRow(tx, firestore, history, historyRow({
|
|
637
|
+
atMs: nowMs,
|
|
638
|
+
by: input.actor,
|
|
639
|
+
kind: 'timer.stopped',
|
|
640
|
+
summary: `Stopped work after ${formatSiteCareMinutes(timerMinutes)} on the timer.`,
|
|
641
|
+
after: {
|
|
642
|
+
timerMinutes
|
|
643
|
+
},
|
|
644
|
+
subjectId: input.ticketId
|
|
645
|
+
}));
|
|
646
|
+
}
|
|
647
|
+
appendHistoryRow(tx, firestore, history, historyRow({
|
|
648
|
+
atMs: nowMs,
|
|
649
|
+
by: input.actor,
|
|
650
|
+
kind: 'request.closed',
|
|
651
|
+
summary: `Finished “${ticket.subject}”: ${formatSiteCareMinutes(minutes)} of work, ` + `${allocation.includedMinutesUsed} included minutes used` + (allocation.overMinutes > 0 ? verdict.absorbed ? `, ${formatSiteCareMinutes(allocation.overMinutes)} past the included hour absorbed at no charge.` : `, ${describeHours(verdict.billedHours)} of extra time billed.` : '.'),
|
|
652
|
+
after: {
|
|
653
|
+
minutesLogged: minutes,
|
|
654
|
+
timerMinutes,
|
|
655
|
+
countedMinutes: allocation.countedMinutes,
|
|
656
|
+
includedMinutesUsed: allocation.includedMinutesUsed,
|
|
657
|
+
overMinutes: allocation.overMinutes,
|
|
658
|
+
billedHours: verdict.billedHours,
|
|
659
|
+
absorbed: verdict.absorbed,
|
|
660
|
+
publishActivityId: (_ref = publish == null ? void 0 : publish.activityId) != null ? _ref : null
|
|
661
|
+
},
|
|
662
|
+
subjectId: input.ticketId
|
|
663
|
+
}), requestAudit(ticket.orgId, input.ticketId, verdict.absorbed ? 'request.closedAbsorbed' : 'request.closed'));
|
|
664
|
+
if (charge) {
|
|
665
|
+
appendHistoryRow(tx, firestore, history, chargeRequestedRow(input.ticketId, charge, input.actor, nowMs));
|
|
666
|
+
}
|
|
667
|
+
return {
|
|
668
|
+
ticket,
|
|
669
|
+
request,
|
|
670
|
+
statement
|
|
671
|
+
};
|
|
672
|
+
});
|
|
673
|
+
let request = result.request;
|
|
674
|
+
if (request.charge) {
|
|
675
|
+
const settled = await settleCharge(firestore, {
|
|
676
|
+
ticketId: input.ticketId,
|
|
677
|
+
actor: input.actor
|
|
678
|
+
}, deps);
|
|
679
|
+
request = _extends({}, request, {
|
|
680
|
+
charge: settled
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
await emailDoneSummary(firestore, result.ticket, request, result.statement, deps);
|
|
684
|
+
return {
|
|
685
|
+
request,
|
|
686
|
+
statement: result.statement
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
function billingSentence(request) {
|
|
690
|
+
var _request_charge;
|
|
691
|
+
if (request.overMinutes <= 0) return 'No extra charge: this fit in your included hour.';
|
|
692
|
+
if (request.absorbed || request.billedHours === 0) {
|
|
693
|
+
return 'It ran past your included hour, and we did not charge for the extra time.';
|
|
694
|
+
}
|
|
695
|
+
const status = (_request_charge = request.charge) == null ? void 0 : _request_charge.status;
|
|
696
|
+
if (status === 'failed') {
|
|
697
|
+
return `It ran past your included hour; we will add ${describeHours(request.billedHours)} of extra time to your next invoice.`;
|
|
698
|
+
}
|
|
699
|
+
return `${describeHours(request.billedHours)} of extra time (${formatSiteCareUsd(siteCareExtraTimeCents(request.billedHours))}, at $${SITE_CARE_EXTRA_HOUR_USD} an hour, the time you approved) will be on your next invoice.`;
|
|
700
|
+
}
|
|
701
|
+
function minutesLeftSentence(statement) {
|
|
702
|
+
return `${formatSiteCareMinutes(statement.minutesLeft)} of this month’s included time`;
|
|
703
|
+
}
|
|
704
|
+
async function emailDoneSummary(firestore, ticket, request, statement, deps) {
|
|
705
|
+
var _ref, _siteCarePublishSentence, _request_minutesLogged, _request_minutesLogged1;
|
|
706
|
+
const org = await readSiteCareOrg(firestore, ticket.orgId);
|
|
707
|
+
const to = (_ref = await siteCareOwnerEmail(firestore, ticket.orgId, org)) != null ? _ref : request.requesterEmail;
|
|
708
|
+
const changes = (_siteCarePublishSentence = siteCarePublishSentence(request.publish, formatSiteCareDate)) != null ? _siteCarePublishSentence : `We made the change you asked for: “${ticket.subject}”.`;
|
|
709
|
+
const result = await emailOf(deps)({
|
|
710
|
+
key: SITE_CARE_REQUEST_DONE_EMAIL_KEY,
|
|
711
|
+
to,
|
|
712
|
+
org,
|
|
713
|
+
requestId: ticket.ref.id,
|
|
714
|
+
merge: {
|
|
715
|
+
'request.title': ticket.subject,
|
|
716
|
+
'request.changes': changes,
|
|
717
|
+
'request.minutes': formatSiteCareMinutes((_request_minutesLogged = request.minutesLogged) != null ? _request_minutesLogged : 0),
|
|
718
|
+
'month.minutesLeft': minutesLeftSentence(statement),
|
|
719
|
+
'request.billing': billingSentence(request)
|
|
720
|
+
},
|
|
721
|
+
fallback: {
|
|
722
|
+
subject: `Done: ${ticket.subject}`,
|
|
723
|
+
text: `We finished your request “${ticket.subject}”. ${billingSentence(request)}\n\n` + `What changed: ${changes}\nTime: ${formatSiteCareMinutes((_request_minutesLogged1 = request.minutesLogged) != null ? _request_minutesLogged1 : 0)}\n` + `Left this month: ${minutesLeftSentence(statement)}`
|
|
724
|
+
}
|
|
725
|
+
});
|
|
726
|
+
await recordEmail(firestore, ticketHistory(firestore, ticket.ref.id), result, 'the summary', nowOf(deps), ticket.ref.id);
|
|
727
|
+
}
|
|
728
|
+
// ── Approval ────────────────────────────────────────────────────────────────
|
|
729
|
+
/**
|
|
730
|
+
* Records — or corrects — how the owner said yes to extra time, and emails
|
|
731
|
+
* them the confirmation that is the written record.
|
|
732
|
+
*/ export async function recordSiteCareApproval(firestore, input, deps = {}) {
|
|
733
|
+
const nowMs = nowOf(deps);
|
|
734
|
+
const { ticket, record, previous } = await firestore.runTransaction(async (tx)=>{
|
|
735
|
+
const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)));
|
|
736
|
+
const previous = ticket.request.approval;
|
|
737
|
+
const read = readOwnerApprovalInput(input.approval, {
|
|
738
|
+
rateUsd: SITE_CARE_EXTRA_HOUR_USD,
|
|
739
|
+
nowMs,
|
|
740
|
+
by: {
|
|
741
|
+
uid: input.actor.uid,
|
|
742
|
+
email: input.actor.email
|
|
743
|
+
},
|
|
744
|
+
previous
|
|
745
|
+
});
|
|
746
|
+
if (read.ok === false) throw new SiteCareError(read.error, 400);
|
|
747
|
+
const record = read.record;
|
|
748
|
+
tx.update(ticket.ref, {
|
|
749
|
+
'siteCare.approval': record,
|
|
750
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
751
|
+
});
|
|
752
|
+
appendHistoryRow(tx, firestore, ticketHistory(firestore, input.ticketId), historyRow({
|
|
753
|
+
atMs: nowMs,
|
|
754
|
+
by: input.actor,
|
|
755
|
+
kind: previous ? 'approval.corrected' : 'approval.recorded',
|
|
756
|
+
summary: previous ? `Corrected the approval: ${describeHours(previous.hours)} → ${describeHours(record.hours)}, ${record.channel}.` : ownerApprovalSentence(record, ticket.subject, formatSiteCareDate),
|
|
757
|
+
reason: record.correctionReason,
|
|
758
|
+
before: previous ? _extends({}, previous) : null,
|
|
759
|
+
after: _extends({}, record),
|
|
760
|
+
subjectId: input.ticketId
|
|
761
|
+
}), requestAudit(ticket.orgId, input.ticketId, previous ? 'approval.corrected' : 'approval.recorded'));
|
|
762
|
+
return {
|
|
763
|
+
ticket,
|
|
764
|
+
record,
|
|
765
|
+
previous
|
|
766
|
+
};
|
|
767
|
+
});
|
|
768
|
+
const org = await readSiteCareOrg(firestore, ticket.orgId);
|
|
769
|
+
const to = await siteCareOwnerEmail(firestore, ticket.orgId, org);
|
|
770
|
+
const sentence = ownerApprovalSentence(record, ticket.subject, formatSiteCareDate);
|
|
771
|
+
const correction = previous ? `This corrects the earlier record (${describeHours(previous.hours)}): ${record.correctionReason}` : '';
|
|
772
|
+
const heading = previous ? 'Corrected: your approval of extra time' : 'You approved extra time';
|
|
773
|
+
const result = await emailOf(deps)({
|
|
774
|
+
key: SITE_CARE_APPROVAL_EMAIL_KEY,
|
|
775
|
+
to,
|
|
776
|
+
org,
|
|
777
|
+
requestId: input.ticketId,
|
|
778
|
+
merge: {
|
|
779
|
+
'request.title': ticket.subject,
|
|
780
|
+
'approval.heading': heading,
|
|
781
|
+
'approval.sentence': sentence,
|
|
782
|
+
'approval.correction': correction
|
|
783
|
+
},
|
|
784
|
+
fallback: {
|
|
785
|
+
subject: `${heading}: extra time for ${ticket.subject}`,
|
|
786
|
+
text: `${sentence} ${correction}\n\nIf this is not what you agreed to, reply to this email.`
|
|
787
|
+
}
|
|
788
|
+
});
|
|
789
|
+
await recordEmail(firestore, ticketHistory(firestore, input.ticketId), result, 'the approval confirmation', nowOf(deps), input.ticketId);
|
|
790
|
+
return record;
|
|
791
|
+
}
|
|
792
|
+
// ── Corrections ─────────────────────────────────────────────────────────────
|
|
793
|
+
/**
|
|
794
|
+
* Whether the request's minutes may still change: until the subscription
|
|
795
|
+
* invoice that carries (or would carry) them finalizes.
|
|
796
|
+
*/ async function assertMinutesEditable(orgId, request, deps) {
|
|
797
|
+
var _billing_stripeCustomerId, _request_closedAtMs;
|
|
798
|
+
const charge = request.charge;
|
|
799
|
+
if (charge && charge.status === 'creating') {
|
|
800
|
+
throw new SiteCareError('A charge on this request is still being created. Retry it first.', 409);
|
|
801
|
+
}
|
|
802
|
+
if (charge && charge.status === 'pending' && charge.invoiceItemId) {
|
|
803
|
+
const read = await readExtraTimeItem(charge.invoiceItemId, deps.stripe);
|
|
804
|
+
if (read.ok === false) throw new SiteCareError(read.error, 502);
|
|
805
|
+
if (!extraTimeItemIsEditable(read.state.stage) && read.state.stage !== 'deleted') {
|
|
806
|
+
throw new SiteCareError('The invoice with this extra time has been finalized, so its minutes are locked. Void, credit or refund the charge instead.', 409);
|
|
807
|
+
}
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
const billing = await readOrgBilling(orgId);
|
|
811
|
+
const customerId = String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '');
|
|
812
|
+
if (!customerId) return;
|
|
813
|
+
const subscription = await siteCareSubscriptionId(customerId, deps.stripe);
|
|
814
|
+
if (subscription.ok === false) return;
|
|
815
|
+
const finalized = await subscriptionInvoiceFinalizedSince({
|
|
816
|
+
subscriptionId: subscription.subscriptionId,
|
|
817
|
+
sinceMs: (_request_closedAtMs = request.closedAtMs) != null ? _request_closedAtMs : 0
|
|
818
|
+
}, deps.stripe);
|
|
819
|
+
if (finalized.ok === false) throw new SiteCareError(finalized.error, 502);
|
|
820
|
+
if (finalized.finalized) {
|
|
821
|
+
throw new SiteCareError('The invoice for this request’s month has been finalized, so its minutes are locked.', 409);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Changes the minutes on a closed request, with a reason, and recomputes its
|
|
826
|
+
* share of the included hour and its extra time: a pending item is corrected
|
|
827
|
+
* or deleted, a new one is added only under an approval. The owner gets a
|
|
828
|
+
* "corrected" summary with the before and after.
|
|
829
|
+
*/ export async function correctSiteCareMinutes(firestore, input, deps = {}) {
|
|
830
|
+
var _ref, _result_old_minutesLogged, _result_old_minutesLogged1;
|
|
831
|
+
var _result_live;
|
|
832
|
+
const minutes = readSiteCareMinutes(input.minutes);
|
|
833
|
+
if (minutes === null) throw new SiteCareError('Enter the corrected minutes.', 400);
|
|
834
|
+
const reason = requireHistoryReason(input.reason);
|
|
835
|
+
if (reason.ok === false) throw new SiteCareError(reason.error, 400);
|
|
836
|
+
const before = loadedTicket(await ticketRef(firestore, input.ticketId).get());
|
|
837
|
+
if (before.request.state !== 'closed') {
|
|
838
|
+
throw new SiteCareError('Only a finished request’s minutes are corrected; close it instead.', 409);
|
|
839
|
+
}
|
|
840
|
+
await assertMinutesEditable(before.orgId, before.request, deps);
|
|
841
|
+
const nowMs = nowOf(deps);
|
|
842
|
+
const result = await firestore.runTransaction(async (tx)=>{
|
|
843
|
+
var _input_absorb, _ref, _old_minutesLogged, _ref1;
|
|
844
|
+
var _old_charge, _request_approval, _old_charge1, _request_charge;
|
|
845
|
+
const ticket = loadedTicket(await tx.get(ticketRef(firestore, input.ticketId)));
|
|
846
|
+
const old = ticket.request;
|
|
847
|
+
if (((_old_charge = old.charge) == null ? void 0 : _old_charge.status) === 'creating') {
|
|
848
|
+
throw new SiteCareError('A charge on this request is still being created. Retry it first.', 409);
|
|
849
|
+
}
|
|
850
|
+
const month = old.month;
|
|
851
|
+
const context = await readMonthContext(tx, firestore, ticket.orgId, month, input.ticketId);
|
|
852
|
+
const allocation = allocateSiteCareMinutes({
|
|
853
|
+
minutes,
|
|
854
|
+
otherIncludedUsed: context.otherIncludedUsed,
|
|
855
|
+
goodwillMinutes: context.goodwillMinutes
|
|
856
|
+
});
|
|
857
|
+
const verdict = siteCareCloseVerdict({
|
|
858
|
+
requiredHours: allocation.requiredHours,
|
|
859
|
+
approval: old.approval,
|
|
860
|
+
absorb: (_input_absorb = input.absorb) != null ? _input_absorb : old.absorbed
|
|
861
|
+
});
|
|
862
|
+
if (verdict.ok === false) {
|
|
863
|
+
throw new SiteCareError(siteCareBlockedMessage(verdict), 409, {
|
|
864
|
+
blocked: verdict,
|
|
865
|
+
allocation
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
let request = _extends({}, old, {
|
|
869
|
+
minutesLogged: minutes,
|
|
870
|
+
countedMinutes: allocation.countedMinutes,
|
|
871
|
+
includedMinutesUsed: allocation.includedMinutesUsed,
|
|
872
|
+
overMinutes: allocation.overMinutes,
|
|
873
|
+
billedHours: verdict.billedHours,
|
|
874
|
+
absorbed: verdict.absorbed
|
|
875
|
+
});
|
|
876
|
+
const live = old.charge && old.charge.status === 'pending' ? old.charge : null;
|
|
877
|
+
const statementNow = statementWith(month, context, input.ticketId, ticket.subject, request);
|
|
878
|
+
const description = siteCareExtraTimeDescription({
|
|
879
|
+
title: ticket.subject,
|
|
880
|
+
minutesLogged: minutes,
|
|
881
|
+
overMinutes: allocation.overMinutes,
|
|
882
|
+
billedHours: verdict.billedHours,
|
|
883
|
+
approvedHours: (_ref = (_request_approval = request.approval) == null ? void 0 : _request_approval.hours) != null ? _ref : null,
|
|
884
|
+
statement: statementNow
|
|
885
|
+
});
|
|
886
|
+
// What the Stripe side must do, decided here and done after the commit.
|
|
887
|
+
let stripeStep = 'none';
|
|
888
|
+
if (live && verdict.billedHours === 0) stripeStep = 'delete';
|
|
889
|
+
else if (live && (live.hours !== verdict.billedHours || live.description !== description)) stripeStep = 'update';
|
|
890
|
+
else if (!live && verdict.billedHours > 0) stripeStep = 'create';
|
|
891
|
+
if (stripeStep === 'create') {
|
|
892
|
+
const seq = request.chargeSeq + 1;
|
|
893
|
+
request = _extends({}, request, {
|
|
894
|
+
chargeSeq: seq,
|
|
895
|
+
charge: newCharge({
|
|
896
|
+
ticketId: input.ticketId,
|
|
897
|
+
seq,
|
|
898
|
+
hours: verdict.billedHours,
|
|
899
|
+
description,
|
|
900
|
+
nowMs
|
|
901
|
+
})
|
|
902
|
+
});
|
|
903
|
+
} else if (((_old_charge1 = old.charge) == null ? void 0 : _old_charge1.status) === 'failed' && verdict.billedHours === 0) {
|
|
904
|
+
// A charge Stripe refused never made an item, and the corrected time
|
|
905
|
+
// no longer owes one: it is settled as voided, so the reconciliation
|
|
906
|
+
// stops reporting hours that are no longer owed.
|
|
907
|
+
request = _extends({}, request, {
|
|
908
|
+
charge: _extends({}, old.charge, {
|
|
909
|
+
status: 'voided',
|
|
910
|
+
updatedAtMs: nowMs
|
|
911
|
+
})
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
tx.update(ticket.ref, {
|
|
915
|
+
siteCare: request,
|
|
916
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
917
|
+
});
|
|
918
|
+
const history = ticketHistory(firestore, input.ticketId);
|
|
919
|
+
// The correction's own row id keys its Stripe call: one correction, one
|
|
920
|
+
// key, so a retried call cannot apply it twice (and a later correction,
|
|
921
|
+
// with its own row, is never mistaken for a replay of this one).
|
|
922
|
+
const correctionRef = appendHistoryRow(tx, firestore, history, historyRow({
|
|
923
|
+
atMs: nowMs,
|
|
924
|
+
by: input.actor,
|
|
925
|
+
kind: 'minutes.corrected',
|
|
926
|
+
summary: `Corrected the time from ${formatSiteCareMinutes((_old_minutesLogged = old.minutesLogged) != null ? _old_minutesLogged : 0)} to ${formatSiteCareMinutes(minutes)}.`,
|
|
927
|
+
reason: reason.reason,
|
|
928
|
+
before: {
|
|
929
|
+
minutesLogged: old.minutesLogged,
|
|
930
|
+
countedMinutes: old.countedMinutes,
|
|
931
|
+
includedMinutesUsed: old.includedMinutesUsed,
|
|
932
|
+
overMinutes: old.overMinutes,
|
|
933
|
+
billedHours: old.billedHours
|
|
934
|
+
},
|
|
935
|
+
after: {
|
|
936
|
+
minutesLogged: minutes,
|
|
937
|
+
countedMinutes: allocation.countedMinutes,
|
|
938
|
+
includedMinutesUsed: allocation.includedMinutesUsed,
|
|
939
|
+
overMinutes: allocation.overMinutes,
|
|
940
|
+
billedHours: verdict.billedHours,
|
|
941
|
+
chargeStatus: (_ref1 = (_request_charge = request.charge) == null ? void 0 : _request_charge.status) != null ? _ref1 : null
|
|
942
|
+
},
|
|
943
|
+
subjectId: input.ticketId
|
|
944
|
+
}), requestAudit(ticket.orgId, input.ticketId, 'minutes.corrected'));
|
|
945
|
+
if (stripeStep === 'create' && request.charge) {
|
|
946
|
+
appendHistoryRow(tx, firestore, history, chargeRequestedRow(input.ticketId, request.charge, input.actor, nowMs));
|
|
947
|
+
}
|
|
948
|
+
return {
|
|
949
|
+
ticket,
|
|
950
|
+
old,
|
|
951
|
+
request,
|
|
952
|
+
statement: statementNow,
|
|
953
|
+
stripeStep,
|
|
954
|
+
live,
|
|
955
|
+
description,
|
|
956
|
+
correctionId: correctionRef.id
|
|
957
|
+
};
|
|
958
|
+
});
|
|
959
|
+
let request = result.request;
|
|
960
|
+
if (result.stripeStep === 'create') {
|
|
961
|
+
const settled = await settleCharge(firestore, {
|
|
962
|
+
ticketId: input.ticketId,
|
|
963
|
+
actor: input.actor
|
|
964
|
+
}, deps);
|
|
965
|
+
request = _extends({}, request, {
|
|
966
|
+
charge: settled
|
|
967
|
+
});
|
|
968
|
+
} else if ((result.stripeStep === 'update' || result.stripeStep === 'delete') && ((_result_live = result.live) == null ? void 0 : _result_live.invoiceItemId)) {
|
|
969
|
+
request = await correctLiveCharge(firestore, {
|
|
970
|
+
ticket: result.ticket,
|
|
971
|
+
request,
|
|
972
|
+
live: result.live,
|
|
973
|
+
step: result.stripeStep,
|
|
974
|
+
hours: request.billedHours,
|
|
975
|
+
description: result.description,
|
|
976
|
+
actor: input.actor,
|
|
977
|
+
reason: reason.reason,
|
|
978
|
+
correctionId: result.correctionId
|
|
979
|
+
}, deps);
|
|
980
|
+
}
|
|
981
|
+
const org = await readSiteCareOrg(firestore, result.ticket.orgId);
|
|
982
|
+
const to = (_ref = await siteCareOwnerEmail(firestore, result.ticket.orgId, org)) != null ? _ref : request.requesterEmail;
|
|
983
|
+
const emailed = await emailOf(deps)({
|
|
984
|
+
key: SITE_CARE_REQUEST_CORRECTED_EMAIL_KEY,
|
|
985
|
+
to,
|
|
986
|
+
org,
|
|
987
|
+
requestId: input.ticketId,
|
|
988
|
+
merge: {
|
|
989
|
+
'request.title': result.ticket.subject,
|
|
990
|
+
'correction.before': formatSiteCareMinutes((_result_old_minutesLogged = result.old.minutesLogged) != null ? _result_old_minutesLogged : 0),
|
|
991
|
+
'correction.after': formatSiteCareMinutes(minutes),
|
|
992
|
+
'correction.reason': reason.reason,
|
|
993
|
+
'request.billing': billingSentence(request),
|
|
994
|
+
'month.minutesLeft': minutesLeftSentence(result.statement)
|
|
995
|
+
},
|
|
996
|
+
fallback: {
|
|
997
|
+
subject: `Corrected: the time on ${result.ticket.subject}`,
|
|
998
|
+
text: `We corrected the time on “${result.ticket.subject}” from ${formatSiteCareMinutes((_result_old_minutesLogged1 = result.old.minutesLogged) != null ? _result_old_minutesLogged1 : 0)} ` + `to ${formatSiteCareMinutes(minutes)}. ${reason.reason} ${billingSentence(request)}`
|
|
999
|
+
}
|
|
1000
|
+
});
|
|
1001
|
+
await recordEmail(firestore, ticketHistory(firestore, input.ticketId), emailed, 'the corrected summary', nowOf(deps), input.ticketId);
|
|
1002
|
+
return {
|
|
1003
|
+
request,
|
|
1004
|
+
statement: result.statement
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* The idempotency key of a correction's Stripe call: the charge's own key
|
|
1009
|
+
* and the id of the history row that records the correction. A clock would
|
|
1010
|
+
* make every retry a new request to Stripe; the row id makes it the same one.
|
|
1011
|
+
*/ export function siteCareCorrectionKey(chargeKey, correctionId) {
|
|
1012
|
+
return `${chargeKey}:fix:${correctionId}`;
|
|
1013
|
+
}
|
|
1014
|
+
/** Updates or deletes a pending item after a correction, with its row. */ async function correctLiveCharge(firestore, input, deps) {
|
|
1015
|
+
const itemId = String(input.live.invoiceItemId);
|
|
1016
|
+
const nowMs = nowOf(deps);
|
|
1017
|
+
const seqKey = siteCareCorrectionKey(input.live.idempotencyKey, input.correctionId);
|
|
1018
|
+
const outcome = input.step === 'delete' ? await deleteExtraTimeItem(itemId, deps.stripe) : await updateExtraTimeItem({
|
|
1019
|
+
invoiceItemId: itemId,
|
|
1020
|
+
hours: input.hours,
|
|
1021
|
+
description: input.description,
|
|
1022
|
+
idempotencyKey: seqKey
|
|
1023
|
+
}, deps.stripe);
|
|
1024
|
+
const outcomeError = outcome.ok === false ? outcome.error : null;
|
|
1025
|
+
const charge = outcomeError === null ? input.step === 'delete' ? _extends({}, input.live, {
|
|
1026
|
+
status: 'voided',
|
|
1027
|
+
updatedAtMs: nowMs,
|
|
1028
|
+
error: null
|
|
1029
|
+
}) : _extends({}, input.live, {
|
|
1030
|
+
hours: input.hours,
|
|
1031
|
+
amountCents: siteCareExtraTimeCents(input.hours),
|
|
1032
|
+
description: input.description,
|
|
1033
|
+
updatedAtMs: nowMs,
|
|
1034
|
+
error: null
|
|
1035
|
+
}) : _extends({}, input.live, {
|
|
1036
|
+
error: outcomeError,
|
|
1037
|
+
updatedAtMs: nowMs
|
|
1038
|
+
});
|
|
1039
|
+
const batch = firestore.batch();
|
|
1040
|
+
batch.update(input.ticket.ref, {
|
|
1041
|
+
'siteCare.charge': charge,
|
|
1042
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
1043
|
+
});
|
|
1044
|
+
appendHistoryRow(batch, firestore, ticketHistory(firestore, input.ticket.ref.id), historyRow({
|
|
1045
|
+
atMs: nowMs,
|
|
1046
|
+
by: input.actor,
|
|
1047
|
+
kind: outcomeError !== null ? 'charge.correctionFailed' : input.step === 'delete' ? 'charge.voided' : 'charge.updated',
|
|
1048
|
+
summary: outcomeError !== null ? `The charge could not be corrected in Stripe: ${outcomeError}` : input.step === 'delete' ? `Removed the extra-time charge (${formatSiteCareUsd(input.live.amountCents)}) before it was invoiced.` : `Changed the extra-time charge from ${describeHours(input.live.hours)} to ${describeHours(input.hours)}.`,
|
|
1049
|
+
reason: input.reason,
|
|
1050
|
+
before: {
|
|
1051
|
+
hours: input.live.hours,
|
|
1052
|
+
amountCents: input.live.amountCents,
|
|
1053
|
+
description: input.live.description
|
|
1054
|
+
},
|
|
1055
|
+
after: {
|
|
1056
|
+
hours: charge.hours,
|
|
1057
|
+
amountCents: charge.amountCents,
|
|
1058
|
+
status: charge.status,
|
|
1059
|
+
error: charge.error
|
|
1060
|
+
},
|
|
1061
|
+
stripe: {
|
|
1062
|
+
object: 'invoiceitem',
|
|
1063
|
+
id: itemId,
|
|
1064
|
+
amountCents: charge.amountCents
|
|
1065
|
+
},
|
|
1066
|
+
subjectId: input.ticket.ref.id
|
|
1067
|
+
}), requestAudit(input.ticket.orgId, input.ticket.ref.id, outcomeError !== null ? 'charge.correctionFailed' : input.step === 'delete' ? 'charge.voided' : 'charge.updated'));
|
|
1068
|
+
await batch.commit();
|
|
1069
|
+
return _extends({}, input.request, {
|
|
1070
|
+
charge
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Voids, credits or refunds a request's extra-time charge, with a reason —
|
|
1075
|
+
* deleted before its invoice finalizes, credited after, refunded once paid.
|
|
1076
|
+
* `absorb` also records that the request is not charged for its extra time.
|
|
1077
|
+
*/ export async function reverseSiteCareCharge(firestore, input, deps = {}) {
|
|
1078
|
+
const reason = requireHistoryReason(input.reason);
|
|
1079
|
+
if (reason.ok === false) throw new SiteCareError(reason.error, 400);
|
|
1080
|
+
const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get());
|
|
1081
|
+
const charge = ticket.request.charge;
|
|
1082
|
+
if (!charge || !SITE_CARE_LIVE_CHARGE_STATUSES.includes(charge.status) || !charge.invoiceItemId) {
|
|
1083
|
+
throw new SiteCareError('There is no extra-time charge on this request to reverse.', 409);
|
|
1084
|
+
}
|
|
1085
|
+
const read = await readExtraTimeItem(charge.invoiceItemId, deps.stripe);
|
|
1086
|
+
if (read.ok === false) throw new SiteCareError(read.error, 502);
|
|
1087
|
+
const stage = read.state.stage;
|
|
1088
|
+
if (stage === 'void' || stage === 'uncollectible') {
|
|
1089
|
+
throw new SiteCareError(`The invoice with this charge is ${stage}; there is nothing to reverse.`, 409);
|
|
1090
|
+
}
|
|
1091
|
+
const nowMs = nowOf(deps);
|
|
1092
|
+
const intended = stage === 'paid' ? 'refund' : stage === 'open' ? 'credit' : 'void';
|
|
1093
|
+
// The intent first, so a call whose answer is lost still left a row.
|
|
1094
|
+
await commitHistoryRow(firestore, ticketHistory(firestore, input.ticketId), historyRow({
|
|
1095
|
+
atMs: nowMs,
|
|
1096
|
+
by: input.actor,
|
|
1097
|
+
kind: `charge.${intended}Requested`,
|
|
1098
|
+
summary: `Reversing the extra-time charge (${formatSiteCareUsd(charge.amountCents)}): ${intended}.`,
|
|
1099
|
+
reason: reason.reason,
|
|
1100
|
+
before: {
|
|
1101
|
+
status: charge.status,
|
|
1102
|
+
stage
|
|
1103
|
+
},
|
|
1104
|
+
subjectId: input.ticketId
|
|
1105
|
+
}), requestAudit(ticket.orgId, input.ticketId, `charge.${intended}Requested`));
|
|
1106
|
+
let next;
|
|
1107
|
+
let stripeRef;
|
|
1108
|
+
if (intended === 'void') {
|
|
1109
|
+
const deleted = stage === 'deleted' ? {
|
|
1110
|
+
ok: true,
|
|
1111
|
+
deleted: true
|
|
1112
|
+
} : await deleteExtraTimeItem(charge.invoiceItemId, deps.stripe);
|
|
1113
|
+
if (deleted.ok === false) throw new SiteCareError(deleted.error, 502);
|
|
1114
|
+
next = _extends({}, charge, {
|
|
1115
|
+
status: 'voided',
|
|
1116
|
+
updatedAtMs: nowOf(deps),
|
|
1117
|
+
error: null
|
|
1118
|
+
});
|
|
1119
|
+
stripeRef = {
|
|
1120
|
+
object: 'invoiceitem',
|
|
1121
|
+
id: charge.invoiceItemId,
|
|
1122
|
+
amountCents: charge.amountCents
|
|
1123
|
+
};
|
|
1124
|
+
} else {
|
|
1125
|
+
const credited = await creditExtraTimeItem({
|
|
1126
|
+
invoiceId: String(read.state.invoiceId),
|
|
1127
|
+
invoiceItemId: charge.invoiceItemId,
|
|
1128
|
+
refund: intended === 'refund',
|
|
1129
|
+
memo: `Site Care: ${reason.reason}`,
|
|
1130
|
+
metadata: {
|
|
1131
|
+
siteCareRequestId: input.ticketId,
|
|
1132
|
+
orgId: ticket.orgId
|
|
1133
|
+
},
|
|
1134
|
+
idempotencyKey: `${charge.idempotencyKey}:${intended}`
|
|
1135
|
+
}, deps.stripe);
|
|
1136
|
+
if (credited.ok === false) throw new SiteCareError(credited.error, 502);
|
|
1137
|
+
next = _extends({}, charge, {
|
|
1138
|
+
status: intended === 'refund' ? 'refunded' : 'credited',
|
|
1139
|
+
invoiceId: read.state.invoiceId,
|
|
1140
|
+
creditNoteId: credited.creditNoteId,
|
|
1141
|
+
refundId: credited.refundId,
|
|
1142
|
+
updatedAtMs: nowOf(deps),
|
|
1143
|
+
error: null
|
|
1144
|
+
});
|
|
1145
|
+
stripeRef = {
|
|
1146
|
+
object: 'credit_note',
|
|
1147
|
+
id: credited.creditNoteId,
|
|
1148
|
+
amountCents: credited.amountCents
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
const batch = firestore.batch();
|
|
1152
|
+
batch.update(ticket.ref, _extends({
|
|
1153
|
+
'siteCare.charge': next
|
|
1154
|
+
}, input.absorb ? {
|
|
1155
|
+
'siteCare.absorbed': true,
|
|
1156
|
+
'siteCare.billedHours': 0
|
|
1157
|
+
} : {}, {
|
|
1158
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
1159
|
+
}));
|
|
1160
|
+
const doneKind = next.status === 'voided' ? 'charge.voided' : next.status === 'refunded' ? 'charge.refunded' : 'charge.credited';
|
|
1161
|
+
appendHistoryRow(batch, firestore, ticketHistory(firestore, input.ticketId), historyRow({
|
|
1162
|
+
atMs: nowOf(deps),
|
|
1163
|
+
by: input.actor,
|
|
1164
|
+
kind: doneKind,
|
|
1165
|
+
summary: next.status === 'voided' ? `Removed the extra-time charge (${formatSiteCareUsd(charge.amountCents)}); it will not be invoiced.` : next.status === 'refunded' ? `Refunded the extra-time charge (${formatSiteCareUsd(charge.amountCents)} plus its tax).` : `Credited the extra-time charge (${formatSiteCareUsd(charge.amountCents)} plus its tax) back on the invoice.`,
|
|
1166
|
+
reason: reason.reason,
|
|
1167
|
+
before: {
|
|
1168
|
+
status: charge.status
|
|
1169
|
+
},
|
|
1170
|
+
after: {
|
|
1171
|
+
status: next.status,
|
|
1172
|
+
creditNoteId: next.creditNoteId,
|
|
1173
|
+
refundId: next.refundId,
|
|
1174
|
+
absorbed: input.absorb === true
|
|
1175
|
+
},
|
|
1176
|
+
stripe: stripeRef,
|
|
1177
|
+
subjectId: input.ticketId
|
|
1178
|
+
}), requestAudit(ticket.orgId, input.ticketId, doneKind));
|
|
1179
|
+
await batch.commit();
|
|
1180
|
+
const org = await readSiteCareOrg(firestore, ticket.orgId);
|
|
1181
|
+
const to = await siteCareOwnerEmail(firestore, ticket.orgId, org);
|
|
1182
|
+
const heading = next.status === 'voided' ? 'Charge removed' : next.status === 'refunded' ? 'Charge refunded' : 'Charge credited';
|
|
1183
|
+
const amount = formatSiteCareUsd(charge.amountCents);
|
|
1184
|
+
const sentence = next.status === 'voided' ? `The ${amount} for ${describeHours(charge.hours)} of extra time will not be on your next invoice.` : next.status === 'refunded' ? `We refunded the ${amount} for ${describeHours(charge.hours)} of extra time, with its tax, to the card it was paid with.` : `We credited the ${amount} for ${describeHours(charge.hours)} of extra time, with its tax, on the invoice it was on.`;
|
|
1185
|
+
const result = await emailOf(deps)({
|
|
1186
|
+
key: SITE_CARE_CHARGE_REVERSED_EMAIL_KEY,
|
|
1187
|
+
to,
|
|
1188
|
+
org,
|
|
1189
|
+
requestId: input.ticketId,
|
|
1190
|
+
merge: {
|
|
1191
|
+
'request.title': ticket.subject,
|
|
1192
|
+
'charge.heading': heading,
|
|
1193
|
+
'charge.sentence': sentence,
|
|
1194
|
+
'charge.reason': reason.reason
|
|
1195
|
+
},
|
|
1196
|
+
fallback: {
|
|
1197
|
+
subject: `${heading}: ${ticket.subject}`,
|
|
1198
|
+
text: `${sentence}\n\nWhy: ${reason.reason}`
|
|
1199
|
+
}
|
|
1200
|
+
});
|
|
1201
|
+
await recordEmail(firestore, ticketHistory(firestore, input.ticketId), result, 'the charge notice', nowOf(deps), input.ticketId);
|
|
1202
|
+
return next;
|
|
1203
|
+
}
|
|
1204
|
+
// ── Goodwill ────────────────────────────────────────────────────────────────
|
|
1205
|
+
/** Adds included minutes to a workspace's month, with a reason. */ export async function addSiteCareGoodwill(firestore, input, deps = {}) {
|
|
1206
|
+
var _input_month;
|
|
1207
|
+
const month = String((_input_month = input.month) != null ? _input_month : '');
|
|
1208
|
+
if (!isSiteCareMonthKey(month)) throw new SiteCareError('Choose the month.', 400);
|
|
1209
|
+
const minutes = readSiteCareMinutes(input.minutes);
|
|
1210
|
+
if (minutes === null) throw new SiteCareError('Enter the goodwill minutes.', 400);
|
|
1211
|
+
const reason = requireHistoryReason(input.reason);
|
|
1212
|
+
if (reason.ok === false) throw new SiteCareError(reason.error, 400);
|
|
1213
|
+
const nowMs = nowOf(deps);
|
|
1214
|
+
return firestore.runTransaction(async (tx)=>{
|
|
1215
|
+
var _snapshot_get;
|
|
1216
|
+
const ref = monthRef(firestore, input.orgId, month);
|
|
1217
|
+
const snapshot = await tx.get(ref);
|
|
1218
|
+
const before = Number((_snapshot_get = snapshot.get('goodwillMinutes')) != null ? _snapshot_get : 0) || 0;
|
|
1219
|
+
const after = before + minutes;
|
|
1220
|
+
tx.set(ref, {
|
|
1221
|
+
orgId: input.orgId,
|
|
1222
|
+
month,
|
|
1223
|
+
goodwillMinutes: after,
|
|
1224
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
1225
|
+
}, {
|
|
1226
|
+
merge: true
|
|
1227
|
+
});
|
|
1228
|
+
appendHistoryRow(tx, firestore, monthHistory(firestore, input.orgId, month), historyRow({
|
|
1229
|
+
atMs: nowMs,
|
|
1230
|
+
by: input.actor,
|
|
1231
|
+
kind: 'goodwill.added',
|
|
1232
|
+
summary: `Added ${formatSiteCareMinutes(minutes)} of included time to this month, at no charge.`,
|
|
1233
|
+
reason: reason.reason,
|
|
1234
|
+
before: {
|
|
1235
|
+
goodwillMinutes: before
|
|
1236
|
+
},
|
|
1237
|
+
after: {
|
|
1238
|
+
goodwillMinutes: after
|
|
1239
|
+
}
|
|
1240
|
+
}), monthAudit(input.orgId, month, 'goodwill.added'));
|
|
1241
|
+
return {
|
|
1242
|
+
goodwillMinutes: after
|
|
1243
|
+
};
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
/** Every request of a workspace's month, each with its history, and the totals. */ export async function readSiteCareMonth(firestore, input) {
|
|
1247
|
+
var _monthSnap_get;
|
|
1248
|
+
if (!isSiteCareMonthKey(input.month)) throw new SiteCareError('Choose the month.', 400);
|
|
1249
|
+
const [snapshot, monthSnap, monthRows] = await Promise.all([
|
|
1250
|
+
firestore.collection(TICKETS).where('siteCareOrgMonth', '==', siteCareOrgMonth(input.orgId, input.month)).limit(200).get(),
|
|
1251
|
+
monthRef(firestore, input.orgId, input.month).get(),
|
|
1252
|
+
readHistoryRows(monthHistory(firestore, input.orgId, input.month))
|
|
1253
|
+
]);
|
|
1254
|
+
const requests = await Promise.all(snapshot.docs.map(async (doc)=>{
|
|
1255
|
+
var _doc_get, _doc_get1;
|
|
1256
|
+
return {
|
|
1257
|
+
ticketId: doc.id,
|
|
1258
|
+
subject: String((_doc_get = doc.get('subject')) != null ? _doc_get : ''),
|
|
1259
|
+
status: String((_doc_get1 = doc.get('status')) != null ? _doc_get1 : ''),
|
|
1260
|
+
request: readSiteCareRequest(doc.get('siteCare')),
|
|
1261
|
+
history: await readHistoryRows(doc.ref.collection(SITE_CARE_HISTORY_COLLECTION))
|
|
1262
|
+
};
|
|
1263
|
+
}));
|
|
1264
|
+
requests.sort((a, b)=>{
|
|
1265
|
+
var _a_request_closedAtMs, _b_request_closedAtMs;
|
|
1266
|
+
return ((_a_request_closedAtMs = a.request.closedAtMs) != null ? _a_request_closedAtMs : Infinity) - ((_b_request_closedAtMs = b.request.closedAtMs) != null ? _b_request_closedAtMs : Infinity);
|
|
1267
|
+
});
|
|
1268
|
+
const goodwillMinutes = Number((_monthSnap_get = monthSnap.get('goodwillMinutes')) != null ? _monthSnap_get : 0) || 0;
|
|
1269
|
+
return {
|
|
1270
|
+
orgId: input.orgId,
|
|
1271
|
+
month: input.month,
|
|
1272
|
+
goodwillMinutes,
|
|
1273
|
+
statement: siteCareMonthStatement({
|
|
1274
|
+
month: input.month,
|
|
1275
|
+
goodwillMinutes,
|
|
1276
|
+
requests: requests.map((r)=>siteCareStatementRequest(r.ticketId, r.subject, r.request))
|
|
1277
|
+
}),
|
|
1278
|
+
requests,
|
|
1279
|
+
monthHistory: monthRows
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
/** One request as the statement lists it, in the owner's words. */ export function siteCareStatementLine(view) {
|
|
1283
|
+
var _ref, _r_minutesLogged;
|
|
1284
|
+
var _r_charge;
|
|
1285
|
+
const r = view.request;
|
|
1286
|
+
if (r.state !== 'closed') return `${view.subject}: in progress`;
|
|
1287
|
+
const billed = r.billedHours > 0 ? `${describeHours(r.billedHours)} billed (${formatSiteCareUsd(siteCareExtraTimeCents(r.billedHours))}), ${siteCareChargeWords((_ref = (_r_charge = r.charge) == null ? void 0 : _r_charge.status) != null ? _ref : null).toLowerCase()}` : r.overMinutes > 0 ? 'extra time not charged' : 'included';
|
|
1288
|
+
return `${view.subject}: ${formatSiteCareMinutes((_r_minutesLogged = r.minutesLogged) != null ? _r_minutesLogged : 0)}, ${billed}`;
|
|
1289
|
+
}
|
|
1290
|
+
/** Every recorded row of the month, oldest first, as dated lines. */ export function siteCareStatementHistory(view) {
|
|
1291
|
+
const rows = [
|
|
1292
|
+
...view.monthHistory,
|
|
1293
|
+
...view.requests.flatMap((r)=>r.history)
|
|
1294
|
+
].sort((a, b)=>a.atMs - b.atMs);
|
|
1295
|
+
return rows.map((row)=>`${formatSiteCareDate(row.atMs)}: ${row.summary}${row.reason ? ` Why: ${row.reason}` : ''}`);
|
|
1296
|
+
}
|
|
1297
|
+
/** Emails the owner the month's statement, on demand. */ export async function sendSiteCareStatement(firestore, input, deps = {}) {
|
|
1298
|
+
var _result_reason;
|
|
1299
|
+
const view = await readSiteCareMonth(firestore, input);
|
|
1300
|
+
const org = await readSiteCareOrg(firestore, input.orgId);
|
|
1301
|
+
const to = await siteCareOwnerEmail(firestore, input.orgId, org);
|
|
1302
|
+
const summary = siteCareMonthSentence(view.statement);
|
|
1303
|
+
const lines = view.requests.map(siteCareStatementLine).join('\n') || 'No requests this month.';
|
|
1304
|
+
const history = siteCareStatementHistory(view).join('\n') || 'Nothing recorded yet.';
|
|
1305
|
+
const result = await emailOf(deps)({
|
|
1306
|
+
key: SITE_CARE_STATEMENT_EMAIL_KEY,
|
|
1307
|
+
to,
|
|
1308
|
+
org,
|
|
1309
|
+
requestId: null,
|
|
1310
|
+
merge: {
|
|
1311
|
+
'month.label': view.statement.monthLabel,
|
|
1312
|
+
'statement.summary': summary,
|
|
1313
|
+
'statement.lines': lines,
|
|
1314
|
+
'statement.history': history
|
|
1315
|
+
},
|
|
1316
|
+
fallback: {
|
|
1317
|
+
subject: `Your Site Care statement for ${view.statement.monthLabel}`,
|
|
1318
|
+
text: `${summary}\n\n${lines}\n\nEverything we recorded:\n${history}`
|
|
1319
|
+
}
|
|
1320
|
+
});
|
|
1321
|
+
await commitHistoryRow(firestore, monthHistory(firestore, input.orgId, input.month), historyRow({
|
|
1322
|
+
atMs: nowOf(deps),
|
|
1323
|
+
by: input.actor,
|
|
1324
|
+
kind: result.sent ? 'statement.sent' : 'statement.notSent',
|
|
1325
|
+
summary: result.sent ? `Emailed the ${view.statement.monthLabel} statement to ${result.to}.` : `The ${view.statement.monthLabel} statement was not sent (${(_result_reason = result.reason) != null ? _result_reason : 'unknown'}).`,
|
|
1326
|
+
after: {
|
|
1327
|
+
to: result.to,
|
|
1328
|
+
sent: result.sent,
|
|
1329
|
+
summary
|
|
1330
|
+
}
|
|
1331
|
+
}), monthAudit(input.orgId, input.month, result.sent ? 'statement.sent' : 'statement.notSent'));
|
|
1332
|
+
return result;
|
|
1333
|
+
}
|
|
1334
|
+
// ── The quote reply ─────────────────────────────────────────────────────────
|
|
1335
|
+
/**
|
|
1336
|
+
* "This one is bigger than Site Care covers, here is the quote": staff send
|
|
1337
|
+
* it from the request; it lands on the thread and in the owner's inbox. The
|
|
1338
|
+
* invoice itself is the staff "Charge for work" (AGL-3970).
|
|
1339
|
+
*/ export async function sendSiteCareQuote(firestore, input, deps = {}) {
|
|
1340
|
+
var _input_scope, _ref, _result_reason;
|
|
1341
|
+
const amount = Number(input.amountUsd);
|
|
1342
|
+
if (!Number.isInteger(amount) || amount < 1 || amount > 100000) {
|
|
1343
|
+
throw new SiteCareError('Enter the quote as a whole number of dollars.', 400);
|
|
1344
|
+
}
|
|
1345
|
+
const scope = String((_input_scope = input.scope) != null ? _input_scope : '').trim().slice(0, 1000);
|
|
1346
|
+
if (!scope) throw new SiteCareError('Say what the price covers.', 400);
|
|
1347
|
+
const ticket = loadedTicket(await ticketRef(firestore, input.ticketId).get());
|
|
1348
|
+
const org = await readSiteCareOrg(firestore, ticket.orgId);
|
|
1349
|
+
const to = (_ref = await siteCareOwnerEmail(firestore, ticket.orgId, org)) != null ? _ref : ticket.request.requesterEmail;
|
|
1350
|
+
const price = `$${amount}`;
|
|
1351
|
+
const result = await emailOf(deps)({
|
|
1352
|
+
key: SITE_CARE_QUOTE_EMAIL_KEY,
|
|
1353
|
+
to,
|
|
1354
|
+
org,
|
|
1355
|
+
requestId: input.ticketId,
|
|
1356
|
+
merge: {
|
|
1357
|
+
'request.title': ticket.subject,
|
|
1358
|
+
'quote.amount': price,
|
|
1359
|
+
'quote.scope': scope
|
|
1360
|
+
},
|
|
1361
|
+
fallback: {
|
|
1362
|
+
subject: `A quote for ${ticket.subject}`,
|
|
1363
|
+
text: `Site Care covers changes to what your site already has. “${ticket.subject}” adds something new, ` + `so it is a project with one flat price: ${price}.\n\nWhat it covers: ${scope}\n\n` + 'Reply to say yes and we will send the invoice. Nothing is charged until you do.'
|
|
1364
|
+
}
|
|
1365
|
+
});
|
|
1366
|
+
const nowMs = nowOf(deps);
|
|
1367
|
+
const batch = firestore.batch();
|
|
1368
|
+
batch.create(ticket.ref.collection('messages').doc(createResourceUid()), {
|
|
1369
|
+
authorId: input.actor.uid,
|
|
1370
|
+
authorEmail: input.actor.email,
|
|
1371
|
+
staff: true,
|
|
1372
|
+
body: `Quote sent: ${price} — ${scope}`,
|
|
1373
|
+
createdAt: FieldValue.serverTimestamp()
|
|
1374
|
+
});
|
|
1375
|
+
batch.update(ticket.ref, {
|
|
1376
|
+
updatedAt: FieldValue.serverTimestamp()
|
|
1377
|
+
});
|
|
1378
|
+
appendHistoryRow(batch, firestore, ticketHistory(firestore, input.ticketId), historyRow({
|
|
1379
|
+
atMs: nowMs,
|
|
1380
|
+
by: input.actor,
|
|
1381
|
+
kind: result.sent ? 'quote.sent' : 'quote.notSent',
|
|
1382
|
+
summary: result.sent ? `Sent a flat quote of ${price}: this is bigger than Site Care covers.` : `The quote of ${price} was not emailed (${(_result_reason = result.reason) != null ? _result_reason : 'unknown'}).`,
|
|
1383
|
+
after: {
|
|
1384
|
+
amountUsd: amount,
|
|
1385
|
+
scope,
|
|
1386
|
+
to: result.to,
|
|
1387
|
+
sent: result.sent
|
|
1388
|
+
},
|
|
1389
|
+
subjectId: input.ticketId
|
|
1390
|
+
}), requestAudit(ticket.orgId, input.ticketId, result.sent ? 'quote.sent' : 'quote.notSent'));
|
|
1391
|
+
await batch.commit();
|
|
1392
|
+
return result;
|
|
1393
|
+
}
|
|
1394
|
+
/** Everything the staff panel shows for one request. */ export async function readSiteCareRequestPanel(firestore, ticketId, deps = {}) {
|
|
1395
|
+
const ticket = loadedTicket(await ticketRef(firestore, ticketId).get());
|
|
1396
|
+
const nowMs = nowOf(deps);
|
|
1397
|
+
const month = ticket.request.state === 'closed' ? ticket.request.month : siteCareMonthKey(nowMs);
|
|
1398
|
+
const [history, context] = await Promise.all([
|
|
1399
|
+
readHistoryRows(ticketHistory(firestore, ticketId)),
|
|
1400
|
+
readMonthContext(null, firestore, ticket.orgId, month, ticketId)
|
|
1401
|
+
]);
|
|
1402
|
+
const pool = siteCareIncludedPool(context.goodwillMinutes);
|
|
1403
|
+
return {
|
|
1404
|
+
ticketId,
|
|
1405
|
+
orgId: ticket.orgId,
|
|
1406
|
+
subject: ticket.subject,
|
|
1407
|
+
request: ticket.request,
|
|
1408
|
+
history,
|
|
1409
|
+
suggestedMinutes: closeMinutesFromTimer(ticket.request.timerStartedAtMs, nowMs),
|
|
1410
|
+
monthMinutesLeft: Math.max(0, pool - context.otherIncludedUsed)
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
//# sourceMappingURL=site-care-requests.js.map
|