@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.
Files changed (49) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/append-only-history-write.d.ts +38 -0
  3. package/src/lib/server/append-only-history-write.js +60 -0
  4. package/src/lib/server/append-only-history-write.js.map +1 -0
  5. package/src/lib/server/billing-addons.d.ts +58 -32
  6. package/src/lib/server/billing-addons.js +100 -86
  7. package/src/lib/server/billing-addons.js.map +1 -1
  8. package/src/lib/server/bundle-links.d.ts +166 -0
  9. package/src/lib/server/bundle-links.js +286 -0
  10. package/src/lib/server/bundle-links.js.map +1 -0
  11. package/src/lib/server/client-build.d.ts +74 -0
  12. package/src/lib/server/client-build.js +264 -0
  13. package/src/lib/server/client-build.js.map +1 -0
  14. package/src/lib/server/host-memberships.d.ts +35 -2
  15. package/src/lib/server/host-memberships.js +63 -2
  16. package/src/lib/server/host-memberships.js.map +1 -1
  17. package/src/lib/server/org-billing.d.ts +4 -2
  18. package/src/lib/server/org-billing.js +5 -0
  19. package/src/lib/server/org-billing.js.map +1 -1
  20. package/src/lib/server/site-care-emails.d.ts +52 -0
  21. package/src/lib/server/site-care-emails.js +97 -0
  22. package/src/lib/server/site-care-emails.js.map +1 -0
  23. package/src/lib/server/site-care-inbound.d.ts +80 -0
  24. package/src/lib/server/site-care-inbound.js +171 -0
  25. package/src/lib/server/site-care-inbound.js.map +1 -0
  26. package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
  27. package/src/lib/server/site-care-project-reconcile.js +211 -0
  28. package/src/lib/server/site-care-project-reconcile.js.map +1 -0
  29. package/src/lib/server/site-care-project-stripe.d.ts +114 -0
  30. package/src/lib/server/site-care-project-stripe.js +305 -0
  31. package/src/lib/server/site-care-project-stripe.js.map +1 -0
  32. package/src/lib/server/site-care-projects.d.ts +169 -0
  33. package/src/lib/server/site-care-projects.js +882 -0
  34. package/src/lib/server/site-care-projects.js.map +1 -0
  35. package/src/lib/server/site-care-reconcile.d.ts +81 -0
  36. package/src/lib/server/site-care-reconcile.js +349 -0
  37. package/src/lib/server/site-care-reconcile.js.map +1 -0
  38. package/src/lib/server/site-care-requests.d.ts +243 -0
  39. package/src/lib/server/site-care-requests.js +1414 -0
  40. package/src/lib/server/site-care-requests.js.map +1 -0
  41. package/src/lib/server/site-care-stripe.d.ts +175 -0
  42. package/src/lib/server/site-care-stripe.js +375 -0
  43. package/src/lib/server/site-care-stripe.js.map +1 -0
  44. package/src/lib/server/upgrade-proposal.d.ts +40 -1
  45. package/src/lib/server/upgrade-proposal.js +92 -50
  46. package/src/lib/server/upgrade-proposal.js.map +1 -1
  47. package/src/tenancy.d.ts +1 -0
  48. package/src/tenancy.js +2 -0
  49. package/src/tenancy.js.map +1 -1
@@ -0,0 +1,375 @@
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 { SITE_CARE_EXTRA_HOUR_USD } from "@aglyn/aglyn/app-utils/plan-entitlements";
18
+ import { SITE_CARE_EXTRA_TIME_TAX_CODE } from "@aglyn/aglyn/app-utils/site-care";
19
+ import { isLiveSubscriptionStatus } from "@aglyn/aglyn/app-utils/org-billing-doc";
20
+ import { USAGE_INVOICE_API_VERSION } from "./usage-invoice.js";
21
+ async function stripeCall(options, method, path, params = null, idempotencyKey = null) {
22
+ var _ref, _options_secretKey, _options_fetchImpl;
23
+ const secretKey = (_ref = (_options_secretKey = options.secretKey) != null ? _options_secretKey : process.env['STRIPE_SECRET_KEY']) != null ? _ref : '';
24
+ if (!secretKey) {
25
+ return {
26
+ ok: false,
27
+ status: 501,
28
+ body: {
29
+ error: {
30
+ message: 'Stripe is not configured'
31
+ }
32
+ }
33
+ };
34
+ }
35
+ const fetchImpl = (_options_fetchImpl = options.fetchImpl) != null ? _options_fetchImpl : fetch;
36
+ const query = method === 'GET' && params ? `?${new URLSearchParams(params).toString()}` : '';
37
+ const response = await fetchImpl(`https://api.stripe.com/v1/${path}${query}`, {
38
+ method,
39
+ headers: _extends({
40
+ Authorization: `Bearer ${secretKey}`,
41
+ 'Stripe-Version': USAGE_INVOICE_API_VERSION
42
+ }, method === 'POST' ? {
43
+ 'Content-Type': 'application/x-www-form-urlencoded'
44
+ } : {}, method !== 'GET' && idempotencyKey ? {
45
+ 'Idempotency-Key': idempotencyKey
46
+ } : {}),
47
+ body: method === 'POST' && params ? new URLSearchParams(params).toString() : undefined
48
+ });
49
+ const body = await response.json().catch(()=>({}));
50
+ return {
51
+ ok: response.ok,
52
+ status: response.status,
53
+ body
54
+ };
55
+ }
56
+ function stripeMessage(answer, fallback) {
57
+ var _answer_body_error, _answer_body;
58
+ const message = (_answer_body = answer.body) == null ? void 0 : (_answer_body_error = _answer_body['error']) == null ? void 0 : _answer_body_error.message;
59
+ return typeof message === 'string' && message ? message : fallback;
60
+ }
61
+ function metadataParams(metadata) {
62
+ const params = {};
63
+ for (const [key, value] of Object.entries(metadata))params[`metadata[${key}]`] = String(value);
64
+ return params;
65
+ }
66
+ /**
67
+ * The pinned, form-encoded Stripe call and its helpers, shared with the
68
+ * flat-quoted project invoice (AGL-3970, `site-care-project-stripe.ts`) so
69
+ * both Site Care money paths speak to Stripe the same way.
70
+ */ export { metadataParams as siteCareStripeMetadata, stripeCall as siteCareStripeCall, stripeMessage as siteCareStripeMessage, };
71
+ /**
72
+ * The org's live subscription, which the item is attached to so it rides
73
+ * that subscription's next invoice.
74
+ */ export async function siteCareSubscriptionId(customerId, options = {}) {
75
+ var _answer_body_data;
76
+ if (!customerId) return {
77
+ ok: false,
78
+ error: 'The workspace has no Stripe customer.'
79
+ };
80
+ const answer = await stripeCall(options, 'GET', 'subscriptions', {
81
+ customer: customerId,
82
+ status: 'all',
83
+ limit: '10'
84
+ });
85
+ if (answer.ok === false) return {
86
+ ok: false,
87
+ error: stripeMessage(answer, 'Reading the subscription failed')
88
+ };
89
+ const rows = (_answer_body_data = answer.body['data']) != null ? _answer_body_data : [];
90
+ const live = rows.find((row)=>{
91
+ var _row_status;
92
+ return isLiveSubscriptionStatus(String((_row_status = row['status']) != null ? _row_status : ''));
93
+ });
94
+ return live ? {
95
+ ok: true,
96
+ subscriptionId: String(live['id'])
97
+ } : {
98
+ ok: false,
99
+ error: 'The workspace has no live subscription to add extra time to.'
100
+ };
101
+ }
102
+ /**
103
+ * The Site Care product, read off the add-on's price, with its tax code
104
+ * checked. `priceId` defaults to the monthly add-on price; the product is
105
+ * the same for the yearly one.
106
+ */ export async function siteCareExtraTimeProduct(options = {}) {
107
+ var _ref, _ref1, _options_priceId, _ref2, _ref3;
108
+ var _product_tax_code;
109
+ const priceId = (_ref = (_ref1 = (_options_priceId = options.priceId) != null ? _options_priceId : process.env['STRIPE_PRICE_SITE_CARE']) != null ? _ref1 : process.env['STRIPE_PRICE_SITE_CARE_YEARLY']) != null ? _ref : '';
110
+ if (!priceId) return {
111
+ ok: false,
112
+ error: 'The Site Care price is not configured (STRIPE_PRICE_SITE_CARE).'
113
+ };
114
+ const answer = await stripeCall(options, 'GET', `prices/${encodeURIComponent(priceId)}`, {
115
+ 'expand[]': 'product'
116
+ });
117
+ if (answer.ok === false) return {
118
+ ok: false,
119
+ error: stripeMessage(answer, 'Reading the Site Care price failed')
120
+ };
121
+ const product = answer.body['product'];
122
+ const productId = typeof product === 'string' ? product : String((_ref2 = product == null ? void 0 : product['id']) != null ? _ref2 : '');
123
+ if (!productId) return {
124
+ ok: false,
125
+ error: 'The Site Care price names no product.'
126
+ };
127
+ const taxCode = typeof product === 'object' && product ? typeof product['tax_code'] === 'string' ? product['tax_code'] : String((_ref3 = (_product_tax_code = product['tax_code']) == null ? void 0 : _product_tax_code['id']) != null ? _ref3 : '') : '';
128
+ if (taxCode !== SITE_CARE_EXTRA_TIME_TAX_CODE) {
129
+ return {
130
+ ok: false,
131
+ error: `The Site Care product carries tax code ${taxCode || 'none'}, not ${SITE_CARE_EXTRA_TIME_TAX_CODE}; nothing was charged.`
132
+ };
133
+ }
134
+ return {
135
+ ok: true,
136
+ productId
137
+ };
138
+ }
139
+ /** Adds the extra time to the subscription's next invoice. */ export async function createExtraTimeItem(input, options = {}) {
140
+ var _answer_body_id, _answer_body_amount;
141
+ const hours = Math.floor(input.hours);
142
+ if (!Number.isInteger(hours) || hours < 1) return {
143
+ ok: false,
144
+ error: 'Extra time bills in whole hours, at least one.'
145
+ };
146
+ const answer = await stripeCall(options, 'POST', 'invoiceitems', _extends({
147
+ customer: input.customerId,
148
+ subscription: input.subscriptionId,
149
+ 'price_data[product]': input.productId,
150
+ 'price_data[currency]': 'usd',
151
+ 'price_data[unit_amount]': String(SITE_CARE_EXTRA_HOUR_USD * 100),
152
+ // US sales tax is added on top of the platform's prices, and automatic
153
+ // tax refuses an unspecified behavior outright.
154
+ 'price_data[tax_behavior]': 'exclusive',
155
+ quantity: String(hours),
156
+ description: input.description
157
+ }, metadataParams(input.metadata)), input.idempotencyKey);
158
+ if (answer.ok === false) return {
159
+ ok: false,
160
+ error: stripeMessage(answer, 'Stripe refused the extra-time item')
161
+ };
162
+ const invoiceItemId = String((_answer_body_id = answer.body['id']) != null ? _answer_body_id : '');
163
+ if (!invoiceItemId) return {
164
+ ok: false,
165
+ error: 'Stripe returned an item with no id'
166
+ };
167
+ return {
168
+ ok: true,
169
+ invoiceItemId,
170
+ amountCents: Number((_answer_body_amount = answer.body['amount']) != null ? _answer_body_amount : hours * SITE_CARE_EXTRA_HOUR_USD * 100)
171
+ };
172
+ }
173
+ /** Corrects the hours and description of an item not yet on a finalized invoice. */ export async function updateExtraTimeItem(input, options = {}) {
174
+ var _answer_body_amount;
175
+ const answer = await stripeCall(options, 'POST', `invoiceitems/${encodeURIComponent(input.invoiceItemId)}`, {
176
+ quantity: String(Math.floor(input.hours)),
177
+ description: input.description
178
+ }, input.idempotencyKey);
179
+ if (answer.ok === false) return {
180
+ ok: false,
181
+ error: stripeMessage(answer, 'Stripe refused the correction')
182
+ };
183
+ return {
184
+ ok: true,
185
+ amountCents: Number((_answer_body_amount = answer.body['amount']) != null ? _answer_body_amount : 0)
186
+ };
187
+ }
188
+ /** Reads an item and, when it is on one, its invoice. */ export async function readExtraTimeItem(invoiceItemId, options = {}) {
189
+ var _item_amount, _item_quantity, _item_description, _item_metadata, _ref, _invoice_body_status;
190
+ var _item_invoice;
191
+ const answer = await stripeCall(options, 'GET', `invoiceitems/${encodeURIComponent(invoiceItemId)}`);
192
+ if (answer.status === 404) {
193
+ return {
194
+ ok: true,
195
+ state: {
196
+ stage: 'deleted',
197
+ invoiceId: null,
198
+ amountCents: 0,
199
+ quantity: 0,
200
+ description: '',
201
+ metadata: {}
202
+ }
203
+ };
204
+ }
205
+ if (answer.ok === false) return {
206
+ ok: false,
207
+ error: stripeMessage(answer, 'Reading the extra-time item failed')
208
+ };
209
+ const item = answer.body;
210
+ const base = {
211
+ amountCents: Number((_item_amount = item['amount']) != null ? _item_amount : 0),
212
+ quantity: Number((_item_quantity = item['quantity']) != null ? _item_quantity : 0),
213
+ description: String((_item_description = item['description']) != null ? _item_description : ''),
214
+ metadata: (_item_metadata = item['metadata']) != null ? _item_metadata : {}
215
+ };
216
+ if (item['deleted'] === true) return {
217
+ ok: true,
218
+ state: _extends({
219
+ stage: 'deleted',
220
+ invoiceId: null
221
+ }, base)
222
+ };
223
+ const invoiceId = typeof item['invoice'] === 'string' ? item['invoice'] : String((_ref = (_item_invoice = item['invoice']) == null ? void 0 : _item_invoice['id']) != null ? _ref : '') || null;
224
+ if (!invoiceId) return {
225
+ ok: true,
226
+ state: _extends({
227
+ stage: 'pending',
228
+ invoiceId: null
229
+ }, base)
230
+ };
231
+ const invoice = await stripeCall(options, 'GET', `invoices/${encodeURIComponent(invoiceId)}`);
232
+ if (invoice.ok === false) return {
233
+ ok: false,
234
+ error: stripeMessage(invoice, 'Reading the invoice failed')
235
+ };
236
+ const status = String((_invoice_body_status = invoice.body['status']) != null ? _invoice_body_status : '');
237
+ const stage = status === 'draft' || status === 'open' || status === 'paid' || status === 'void' || status === 'uncollectible' ? status : 'open';
238
+ return {
239
+ ok: true,
240
+ state: _extends({
241
+ stage,
242
+ invoiceId
243
+ }, base)
244
+ };
245
+ }
246
+ /** Whether the item can still be corrected or deleted rather than credited. */ export function extraTimeItemIsEditable(stage) {
247
+ return stage === 'pending' || stage === 'draft';
248
+ }
249
+ /** Deletes an item that has not reached a finalized invoice. */ export async function deleteExtraTimeItem(invoiceItemId, options = {}) {
250
+ const answer = await stripeCall(options, 'DELETE', `invoiceitems/${encodeURIComponent(invoiceItemId)}`);
251
+ if (answer.status === 404 || answer.ok) return {
252
+ ok: true,
253
+ deleted: true
254
+ };
255
+ return {
256
+ ok: false,
257
+ error: stripeMessage(answer, 'Stripe refused to delete the item')
258
+ };
259
+ }
260
+ /**
261
+ * Credits an item on a finalized invoice — and refunds it when the invoice
262
+ * was paid. The credit note names the item's own line, so tax comes back
263
+ * with it; on a paid invoice its whole total is refunded to the card.
264
+ */ export async function creditExtraTimeItem(input, options = {}) {
265
+ var _lines_body_data, _line_quantity, _created_body_id, _ref, _created_body_total;
266
+ const lines = await stripeCall(options, 'GET', `invoices/${encodeURIComponent(input.invoiceId)}/lines`, {
267
+ limit: '100'
268
+ });
269
+ if (lines.ok === false) return {
270
+ ok: false,
271
+ error: stripeMessage(lines, 'Reading the invoice lines failed')
272
+ };
273
+ const line = ((_lines_body_data = lines.body['data']) != null ? _lines_body_data : []).find((row)=>row['invoice_item'] === input.invoiceItemId);
274
+ if (!line) return {
275
+ ok: false,
276
+ error: 'The extra-time line is not on that invoice.'
277
+ };
278
+ const lineParams = {
279
+ invoice: input.invoiceId,
280
+ 'lines[0][type]': 'invoice_line_item',
281
+ 'lines[0][invoice_line_item]': String(line['id']),
282
+ 'lines[0][quantity]': String(Number((_line_quantity = line['quantity']) != null ? _line_quantity : 1) || 1)
283
+ };
284
+ let refundParams = {};
285
+ if (input.refund) {
286
+ var _preview_body_total;
287
+ const preview = await stripeCall(options, 'GET', 'credit_notes/preview', lineParams);
288
+ if (preview.ok === false) return {
289
+ ok: false,
290
+ error: stripeMessage(preview, 'Previewing the credit failed')
291
+ };
292
+ refundParams = {
293
+ refund_amount: String(Number((_preview_body_total = preview.body['total']) != null ? _preview_body_total : 0))
294
+ };
295
+ }
296
+ const created = await stripeCall(options, 'POST', 'credit_notes', _extends({}, lineParams, refundParams, {
297
+ reason: 'order_change',
298
+ memo: input.memo.slice(0, 500)
299
+ }, metadataParams(input.metadata)), input.idempotencyKey);
300
+ if (created.ok === false) return {
301
+ ok: false,
302
+ error: stripeMessage(created, 'Stripe refused the credit note')
303
+ };
304
+ const refund = created.body['refund'];
305
+ return {
306
+ ok: true,
307
+ creditNoteId: String((_created_body_id = created.body['id']) != null ? _created_body_id : ''),
308
+ refundId: typeof refund === 'string' ? refund : String((_ref = refund == null ? void 0 : refund['id']) != null ? _ref : '') || null,
309
+ amountCents: Number((_created_body_total = created.body['total']) != null ? _created_body_total : 0)
310
+ };
311
+ }
312
+ /**
313
+ * Whether a subscription invoice created since `sinceMs` has finalized —
314
+ * the point after which a request's minutes are no longer edited, only its
315
+ * charge reversed.
316
+ */ export async function subscriptionInvoiceFinalizedSince(input, options = {}) {
317
+ var _answer_body_data;
318
+ const answer = await stripeCall(options, 'GET', 'invoices', {
319
+ subscription: input.subscriptionId,
320
+ 'created[gte]': String(Math.floor(input.sinceMs / 1000)),
321
+ limit: '10'
322
+ });
323
+ if (answer.ok === false) return {
324
+ ok: false,
325
+ error: stripeMessage(answer, 'Reading the invoices failed')
326
+ };
327
+ const rows = (_answer_body_data = answer.body['data']) != null ? _answer_body_data : [];
328
+ return {
329
+ ok: true,
330
+ finalized: rows.some((row)=>{
331
+ var _row_status;
332
+ return String((_row_status = row['status']) != null ? _row_status : '') !== 'draft';
333
+ })
334
+ };
335
+ }
336
+ /** Every Site Care extra-time item on a customer created since `sinceMs`. */ export async function listSiteCareExtraTimeItems(input, options = {}) {
337
+ const items = [];
338
+ let startingAfter = '';
339
+ for(let page = 0; page < 10; page++){
340
+ var _answer_body_data;
341
+ const answer = await stripeCall(options, 'GET', 'invoiceitems', _extends({
342
+ customer: input.customerId,
343
+ 'created[gte]': String(Math.floor(input.sinceMs / 1000)),
344
+ limit: '100'
345
+ }, startingAfter ? {
346
+ starting_after: startingAfter
347
+ } : {}));
348
+ if (answer.ok === false) return {
349
+ ok: false,
350
+ error: stripeMessage(answer, 'Listing invoice items failed')
351
+ };
352
+ const rows = (_answer_body_data = answer.body['data']) != null ? _answer_body_data : [];
353
+ for (const row of rows){
354
+ var _row_metadata, _row_amount, _row_quantity, _row_description, _metadata_month;
355
+ const metadata = (_row_metadata = row['metadata']) != null ? _row_metadata : {};
356
+ if (!metadata['siteCareRequestId']) continue;
357
+ items.push({
358
+ id: String(row['id']),
359
+ amountCents: Number((_row_amount = row['amount']) != null ? _row_amount : 0),
360
+ quantity: Number((_row_quantity = row['quantity']) != null ? _row_quantity : 0),
361
+ description: String((_row_description = row['description']) != null ? _row_description : ''),
362
+ requestId: String(metadata['siteCareRequestId']),
363
+ month: String((_metadata_month = metadata['month']) != null ? _metadata_month : '')
364
+ });
365
+ }
366
+ if (answer.body['has_more'] !== true || !rows.length) break;
367
+ startingAfter = String(rows[rows.length - 1]['id']);
368
+ }
369
+ return {
370
+ ok: true,
371
+ items
372
+ };
373
+ }
374
+
375
+ //# sourceMappingURL=site-care-stripe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/site-care-stripe.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n SITE_CARE_EXTRA_HOUR_USD,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { SITE_CARE_EXTRA_TIME_TAX_CODE } from '@aglyn/aglyn/app-utils/site-care'\nimport { isLiveSubscriptionStatus } from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { USAGE_INVOICE_API_VERSION } from './usage-invoice'\n\n/**\n * SITE CARE EXTRA TIME, IN STRIPE (AGL-3959).\n *\n * Every Stripe call the extra-time charge makes, and nothing else: the item\n * on the org's subscription that rides its next invoice, a correction of it\n * while that invoice is still a draft, and its reversal — deleted before the\n * invoice finalizes, credited after, refunded once paid. Staff never do any\n * of this by hand in the Stripe dashboard; the request is the only door, and\n * the caller writes the request's history row in the same step as each call\n * (`site-care-requests.ts`).\n *\n * The same pinned API version and form-encoded fetch `usage-invoice.ts`\n * uses, for the same reason: an invoice item's parameters have moved between\n * versions, and a charge that silently changed shape under a Dashboard\n * upgrade is what pinning prevents. `fetchImpl` and `secretKey` are the\n * specs' seams.\n *\n * ## The tax code is the product's, and it is checked\n *\n * The line is priced against the Site Care product (`price_data[product]`),\n * because the product is what carries the tax code Stripe Tax computes from;\n * the product is read off the Site Care price the subscription already\n * carries, and a product whose tax code is not `txcd_10103001` refuses the\n * charge rather than billing it untaxed or under the wrong code.\n */\n\ntype StripeFetch = typeof fetch\n\nexport interface SiteCareStripeOptions {\n secretKey?: string\n fetchImpl?: StripeFetch\n}\n\ninterface StripeAnswer {\n ok: boolean\n status: number\n body: Record<string, unknown>\n}\n\nasync function stripeCall(\n options: SiteCareStripeOptions,\n method: 'GET' | 'POST' | 'DELETE',\n path: string,\n params: Record<string, string> | null = null,\n idempotencyKey: string | null = null,\n): Promise<StripeAnswer> {\n const secretKey = options.secretKey ?? process.env['STRIPE_SECRET_KEY'] ?? ''\n if (!secretKey) {\n return { ok: false, status: 501, body: { error: { message: 'Stripe is not configured' } } }\n }\n const fetchImpl = options.fetchImpl ?? fetch\n const query = method === 'GET' && params ? `?${new URLSearchParams(params).toString()}` : ''\n const response = await fetchImpl(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${secretKey}`,\n 'Stripe-Version': USAGE_INVOICE_API_VERSION,\n ...(method === 'POST' ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}),\n ...(method !== 'GET' && idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),\n },\n body: method === 'POST' && params ? new URLSearchParams(params).toString() : undefined,\n })\n const body = (await response.json().catch(() => ({}))) as Record<string, unknown>\n return { ok: response.ok, status: response.status, body }\n}\n\nfunction stripeMessage(answer: StripeAnswer, fallback: string): string {\n const message = (answer.body?.['error'] as { message?: unknown } | undefined)?.message\n return typeof message === 'string' && message ? message : fallback\n}\n\nfunction metadataParams(metadata: Readonly<Record<string, string>>): Record<string, string> {\n const params: Record<string, string> = {}\n for (const [key, value] of Object.entries(metadata)) params[`metadata[${key}]`] = String(value)\n return params\n}\n\n/**\n * The pinned, form-encoded Stripe call and its helpers, shared with the\n * flat-quoted project invoice (AGL-3970, `site-care-project-stripe.ts`) so\n * both Site Care money paths speak to Stripe the same way.\n */\nexport {\n metadataParams as siteCareStripeMetadata,\n stripeCall as siteCareStripeCall,\n stripeMessage as siteCareStripeMessage,\n}\nexport type { StripeAnswer as SiteCareStripeAnswer }\n\nexport type SiteCareStripeResult<T> = ({ ok: true } & T) | { ok: false; error: string }\n\n/**\n * The org's live subscription, which the item is attached to so it rides\n * that subscription's next invoice.\n */\nexport async function siteCareSubscriptionId(\n customerId: string,\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ subscriptionId: string }>> {\n if (!customerId) return { ok: false, error: 'The workspace has no Stripe customer.' }\n const answer = await stripeCall(options, 'GET', 'subscriptions', {\n customer: customerId,\n status: 'all',\n limit: '10',\n })\n if (answer.ok === false) return { ok: false, error: stripeMessage(answer, 'Reading the subscription failed') }\n const rows = (answer.body['data'] as Array<Record<string, unknown>> | undefined) ?? []\n const live = rows.find((row) => isLiveSubscriptionStatus(String(row['status'] ?? '')))\n return live\n ? { ok: true, subscriptionId: String(live['id']) }\n : { ok: false, error: 'The workspace has no live subscription to add extra time to.' }\n}\n\n/**\n * The Site Care product, read off the add-on's price, with its tax code\n * checked. `priceId` defaults to the monthly add-on price; the product is\n * the same for the yearly one.\n */\nexport async function siteCareExtraTimeProduct(\n options: SiteCareStripeOptions & { priceId?: string | null } = {},\n): Promise<SiteCareStripeResult<{ productId: string }>> {\n const priceId =\n options.priceId ??\n process.env['STRIPE_PRICE_SITE_CARE'] ??\n process.env['STRIPE_PRICE_SITE_CARE_YEARLY'] ??\n ''\n if (!priceId) return { ok: false, error: 'The Site Care price is not configured (STRIPE_PRICE_SITE_CARE).' }\n const answer = await stripeCall(options, 'GET', `prices/${encodeURIComponent(priceId)}`, {\n 'expand[]': 'product',\n })\n if (answer.ok === false) return { ok: false, error: stripeMessage(answer, 'Reading the Site Care price failed') }\n const product = answer.body['product'] as Record<string, unknown> | string | undefined\n const productId = typeof product === 'string' ? product : String(product?.['id'] ?? '')\n if (!productId) return { ok: false, error: 'The Site Care price names no product.' }\n const taxCode =\n typeof product === 'object' && product\n ? typeof product['tax_code'] === 'string'\n ? product['tax_code']\n : String((product['tax_code'] as Record<string, unknown> | null)?.['id'] ?? '')\n : ''\n if (taxCode !== SITE_CARE_EXTRA_TIME_TAX_CODE) {\n return {\n ok: false,\n error: `The Site Care product carries tax code ${taxCode || 'none'}, not ${SITE_CARE_EXTRA_TIME_TAX_CODE}; nothing was charged.`,\n }\n }\n return { ok: true, productId }\n}\n\nexport interface ExtraTimeItemInput {\n customerId: string\n subscriptionId: string\n productId: string\n hours: number\n description: string\n metadata: Readonly<Record<string, string>>\n idempotencyKey: string\n}\n\n/** Adds the extra time to the subscription's next invoice. */\nexport async function createExtraTimeItem(\n input: ExtraTimeItemInput,\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ invoiceItemId: string; amountCents: number }>> {\n const hours = Math.floor(input.hours)\n if (!Number.isInteger(hours) || hours < 1) return { ok: false, error: 'Extra time bills in whole hours, at least one.' }\n const answer = await stripeCall(\n options,\n 'POST',\n 'invoiceitems',\n {\n customer: input.customerId,\n subscription: input.subscriptionId,\n 'price_data[product]': input.productId,\n 'price_data[currency]': 'usd',\n 'price_data[unit_amount]': String(SITE_CARE_EXTRA_HOUR_USD * 100),\n // US sales tax is added on top of the platform's prices, and automatic\n // tax refuses an unspecified behavior outright.\n 'price_data[tax_behavior]': 'exclusive',\n quantity: String(hours),\n description: input.description,\n ...metadataParams(input.metadata),\n },\n input.idempotencyKey,\n )\n if (answer.ok === false) return { ok: false, error: stripeMessage(answer, 'Stripe refused the extra-time item') }\n const invoiceItemId = String(answer.body['id'] ?? '')\n if (!invoiceItemId) return { ok: false, error: 'Stripe returned an item with no id' }\n return { ok: true, invoiceItemId, amountCents: Number(answer.body['amount'] ?? hours * SITE_CARE_EXTRA_HOUR_USD * 100) }\n}\n\n/** Corrects the hours and description of an item not yet on a finalized invoice. */\nexport async function updateExtraTimeItem(\n input: { invoiceItemId: string; hours: number; description: string; idempotencyKey: string },\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ amountCents: number }>> {\n const answer = await stripeCall(\n options,\n 'POST',\n `invoiceitems/${encodeURIComponent(input.invoiceItemId)}`,\n { quantity: String(Math.floor(input.hours)), description: input.description },\n input.idempotencyKey,\n )\n if (answer.ok === false) return { ok: false, error: stripeMessage(answer, 'Stripe refused the correction') }\n return { ok: true, amountCents: Number(answer.body['amount'] ?? 0) }\n}\n\n/**\n * Where an item stands: still pending (no invoice), on a draft invoice, or\n * on one that finalized — open, paid, void or uncollectible — or gone.\n */\nexport type ExtraTimeItemStage =\n | 'pending'\n | 'draft'\n | 'open'\n | 'paid'\n | 'void'\n | 'uncollectible'\n | 'deleted'\n\nexport interface ExtraTimeItemState {\n stage: ExtraTimeItemStage\n invoiceId: string | null\n amountCents: number\n quantity: number\n description: string\n metadata: Record<string, string>\n}\n\n/** Reads an item and, when it is on one, its invoice. */\nexport async function readExtraTimeItem(\n invoiceItemId: string,\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ state: ExtraTimeItemState }>> {\n const answer = await stripeCall(options, 'GET', `invoiceitems/${encodeURIComponent(invoiceItemId)}`)\n if (answer.status === 404) {\n return {\n ok: true,\n state: { stage: 'deleted', invoiceId: null, amountCents: 0, quantity: 0, description: '', metadata: {} },\n }\n }\n if (answer.ok === false) return { ok: false, error: stripeMessage(answer, 'Reading the extra-time item failed') }\n const item = answer.body\n const base = {\n amountCents: Number(item['amount'] ?? 0),\n quantity: Number(item['quantity'] ?? 0),\n description: String(item['description'] ?? ''),\n metadata: (item['metadata'] as Record<string, string> | undefined) ?? {},\n }\n if (item['deleted'] === true) return { ok: true, state: { stage: 'deleted', invoiceId: null, ...base } }\n const invoiceId =\n typeof item['invoice'] === 'string'\n ? item['invoice']\n : String((item['invoice'] as Record<string, unknown> | null)?.['id'] ?? '') || null\n if (!invoiceId) return { ok: true, state: { stage: 'pending', invoiceId: null, ...base } }\n const invoice = await stripeCall(options, 'GET', `invoices/${encodeURIComponent(invoiceId)}`)\n if (invoice.ok === false) return { ok: false, error: stripeMessage(invoice, 'Reading the invoice failed') }\n const status = String(invoice.body['status'] ?? '')\n const stage: ExtraTimeItemStage =\n status === 'draft' || status === 'open' || status === 'paid' || status === 'void' || status === 'uncollectible'\n ? status\n : 'open'\n return { ok: true, state: { stage, invoiceId, ...base } }\n}\n\n/** Whether the item can still be corrected or deleted rather than credited. */\nexport function extraTimeItemIsEditable(stage: ExtraTimeItemStage): boolean {\n return stage === 'pending' || stage === 'draft'\n}\n\n/** Deletes an item that has not reached a finalized invoice. */\nexport async function deleteExtraTimeItem(\n invoiceItemId: string,\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ deleted: true }>> {\n const answer = await stripeCall(options, 'DELETE', `invoiceitems/${encodeURIComponent(invoiceItemId)}`)\n if (answer.status === 404 || answer.ok) return { ok: true, deleted: true }\n return { ok: false, error: stripeMessage(answer, 'Stripe refused to delete the item') }\n}\n\n/**\n * Credits an item on a finalized invoice — and refunds it when the invoice\n * was paid. The credit note names the item's own line, so tax comes back\n * with it; on a paid invoice its whole total is refunded to the card.\n */\nexport async function creditExtraTimeItem(\n input: {\n invoiceId: string\n invoiceItemId: string\n refund: boolean\n memo: string\n metadata: Readonly<Record<string, string>>\n idempotencyKey: string\n },\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ creditNoteId: string; refundId: string | null; amountCents: number }>> {\n const lines = await stripeCall(options, 'GET', `invoices/${encodeURIComponent(input.invoiceId)}/lines`, {\n limit: '100',\n })\n if (lines.ok === false) return { ok: false, error: stripeMessage(lines, 'Reading the invoice lines failed') }\n const line = ((lines.body['data'] as Array<Record<string, unknown>> | undefined) ?? []).find(\n (row) => row['invoice_item'] === input.invoiceItemId,\n )\n if (!line) return { ok: false, error: 'The extra-time line is not on that invoice.' }\n const lineParams = {\n invoice: input.invoiceId,\n 'lines[0][type]': 'invoice_line_item',\n 'lines[0][invoice_line_item]': String(line['id']),\n 'lines[0][quantity]': String(Number(line['quantity'] ?? 1) || 1),\n }\n let refundParams: Record<string, string> = {}\n if (input.refund) {\n const preview = await stripeCall(options, 'GET', 'credit_notes/preview', lineParams)\n if (preview.ok === false) return { ok: false, error: stripeMessage(preview, 'Previewing the credit failed') }\n refundParams = { refund_amount: String(Number(preview.body['total'] ?? 0)) }\n }\n const created = await stripeCall(\n options,\n 'POST',\n 'credit_notes',\n {\n ...lineParams,\n ...refundParams,\n reason: 'order_change',\n memo: input.memo.slice(0, 500),\n ...metadataParams(input.metadata),\n },\n input.idempotencyKey,\n )\n if (created.ok === false) return { ok: false, error: stripeMessage(created, 'Stripe refused the credit note') }\n const refund = created.body['refund']\n return {\n ok: true,\n creditNoteId: String(created.body['id'] ?? ''),\n refundId:\n typeof refund === 'string'\n ? refund\n : String((refund as Record<string, unknown> | null)?.['id'] ?? '') || null,\n amountCents: Number(created.body['total'] ?? 0),\n }\n}\n\n/**\n * Whether a subscription invoice created since `sinceMs` has finalized —\n * the point after which a request's minutes are no longer edited, only its\n * charge reversed.\n */\nexport async function subscriptionInvoiceFinalizedSince(\n input: { subscriptionId: string; sinceMs: number },\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ finalized: boolean }>> {\n const answer = await stripeCall(options, 'GET', 'invoices', {\n subscription: input.subscriptionId,\n 'created[gte]': String(Math.floor(input.sinceMs / 1000)),\n limit: '10',\n })\n if (answer.ok === false) return { ok: false, error: stripeMessage(answer, 'Reading the invoices failed') }\n const rows = (answer.body['data'] as Array<Record<string, unknown>> | undefined) ?? []\n return { ok: true, finalized: rows.some((row) => String(row['status'] ?? '') !== 'draft') }\n}\n\n/** One extra-time item as the reconciliation reads it. */\nexport interface StripeExtraTimeItem {\n id: string\n amountCents: number\n quantity: number\n description: string\n requestId: string\n /** The month the request counted in, from the item's metadata. */\n month: string\n}\n\n/** Every Site Care extra-time item on a customer created since `sinceMs`. */\nexport async function listSiteCareExtraTimeItems(\n input: { customerId: string; sinceMs: number },\n options: SiteCareStripeOptions = {},\n): Promise<SiteCareStripeResult<{ items: StripeExtraTimeItem[] }>> {\n const items: StripeExtraTimeItem[] = []\n let startingAfter = ''\n for (let page = 0; page < 10; page++) {\n const answer = await stripeCall(options, 'GET', 'invoiceitems', {\n customer: input.customerId,\n 'created[gte]': String(Math.floor(input.sinceMs / 1000)),\n limit: '100',\n ...(startingAfter ? { starting_after: startingAfter } : {}),\n })\n if (answer.ok === false) return { ok: false, error: stripeMessage(answer, 'Listing invoice items failed') }\n const rows = (answer.body['data'] as Array<Record<string, unknown>> | undefined) ?? []\n for (const row of rows) {\n const metadata = (row['metadata'] as Record<string, string> | undefined) ?? {}\n if (!metadata['siteCareRequestId']) continue\n items.push({\n id: String(row['id']),\n amountCents: Number(row['amount'] ?? 0),\n quantity: Number(row['quantity'] ?? 0),\n description: String(row['description'] ?? ''),\n requestId: String(metadata['siteCareRequestId']),\n month: String(metadata['month'] ?? ''),\n })\n }\n if (answer.body['has_more'] !== true || !rows.length) break\n startingAfter = String(rows[rows.length - 1]['id'])\n }\n return { ok: true, items }\n}\n"],"names":["SITE_CARE_EXTRA_HOUR_USD","SITE_CARE_EXTRA_TIME_TAX_CODE","isLiveSubscriptionStatus","USAGE_INVOICE_API_VERSION","stripeCall","options","method","path","params","idempotencyKey","secretKey","process","env","ok","status","body","error","message","fetchImpl","fetch","query","URLSearchParams","toString","response","headers","Authorization","undefined","json","catch","stripeMessage","answer","fallback","metadataParams","metadata","key","value","Object","entries","String","siteCareStripeMetadata","siteCareStripeCall","siteCareStripeMessage","siteCareSubscriptionId","customerId","customer","limit","rows","live","find","row","subscriptionId","siteCareExtraTimeProduct","product","priceId","encodeURIComponent","productId","taxCode","createExtraTimeItem","input","hours","Math","floor","Number","isInteger","subscription","quantity","description","invoiceItemId","amountCents","updateExtraTimeItem","readExtraTimeItem","item","invoice","state","stage","invoiceId","base","extraTimeItemIsEditable","deleteExtraTimeItem","deleted","creditExtraTimeItem","lines","line","created","lineParams","refundParams","refund","preview","refund_amount","reason","memo","slice","creditNoteId","refundId","subscriptionInvoiceFinalizedSince","sinceMs","finalized","some","listSiteCareExtraTimeItems","items","startingAfter","page","starting_after","push","id","requestId","month","length"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,QACnB,2CAA0C;AACjD,SAASC,6BAA6B,QAAQ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,OAAOf,IAAI,CAAC,OAAO,YAAnBe,oBAAsE,EAAE;QACtF,KAAK,MAAMmB,OAAOH,KAAM;gBACJG,eAIIA,aACHA,eACGA,kBAENhB;YARhB,MAAMA,YAAYgB,gBAAAA,GAAG,CAAC,WAAW,YAAfA,gBAA0D,CAAC;YAC7E,IAAI,CAAChB,QAAQ,CAAC,oBAAoB,EAAE;YACpCkE,MAAMI,IAAI,CAAC;gBACTC,IAAIlE,OAAOW,GAAG,CAAC,KAAK;gBACpBmB,aAAaN,QAAOb,cAAAA,GAAG,CAAC,SAAS,YAAbA,cAAiB;gBACrCgB,UAAUH,QAAOb,gBAAAA,GAAG,CAAC,WAAW,YAAfA,gBAAmB;gBACpCiB,aAAa5B,QAAOW,mBAAAA,GAAG,CAAC,cAAc,YAAlBA,mBAAsB;gBAC1CwD,WAAWnE,OAAOL,QAAQ,CAAC,oBAAoB;gBAC/CyE,OAAOpE,QAAOL,kBAAAA,QAAQ,CAAC,QAAQ,YAAjBA,kBAAqB;YACrC;QACF;QACA,IAAIH,OAAOf,IAAI,CAAC,WAAW,KAAK,QAAQ,CAAC+B,KAAK6D,MAAM,EAAE;QACtDP,gBAAgB9D,OAAOQ,IAAI,CAACA,KAAK6D,MAAM,GAAG,EAAE,CAAC,KAAK;IACpD;IACA,OAAO;QAAE9F,IAAI;QAAMsF;IAAM;AAC3B"}
@@ -28,7 +28,7 @@
28
28
  * so a comp granted to evaluate cannot revive free access if the customer
29
29
  * later cancels.
30
30
  */
31
- import type { OrgUpgradeProposal } from '@aglyn/aglyn/server';
31
+ import type { AglynOrgBilling, OrgUpgradeProposal } from '@aglyn/aglyn/server';
32
32
  /** The override reason a sales-evaluation comp is granted under. */
33
33
  export declare const TRIAL_PLAN_COMP_REASON = "trial";
34
34
  /** A proposal refused before anything was written. */
@@ -40,6 +40,13 @@ export interface ProposeOrgUpgradeOptions {
40
40
  orgId: string;
41
41
  plan: unknown;
42
42
  note?: unknown;
43
+ /**
44
+ * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any
45
+ * shape `parseBundleAddons` reads; fitted to the plan before storing.
46
+ */
47
+ addons?: unknown;
48
+ interval?: unknown;
49
+ coupon?: unknown;
43
50
  /** The staff member proposing. */
44
51
  actor: {
45
52
  uid: string;
@@ -66,6 +73,38 @@ export interface ProposeOrgUpgradeResult {
66
73
  * buy themselves.
67
74
  */
68
75
  export declare function proposeOrgUpgrade(options: ProposeOrgUpgradeOptions): Promise<ProposeOrgUpgradeResult>;
76
+ /**
77
+ * The proposal as it will be stored, or the refusal: a plan the workspace
78
+ * can buy itself, a bounded note, and the bundle fitted to the plan
79
+ * (AGL-3956). Nothing is read or written.
80
+ */
81
+ export declare function buildUpgradeProposal(options: Pick<ProposeOrgUpgradeOptions, 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'actor'> & {
82
+ now?: number;
83
+ }): OrgUpgradeProposal;
84
+ /**
85
+ * Read the org a proposal is for, inside the caller's transaction, refusing
86
+ * an unknown workspace and one whose subscription is already live — the
87
+ * question a proposal asks is then already answered.
88
+ */
89
+ export declare function readUpgradeProposalTarget(tx: FirebaseFirestore.Transaction, orgRef: FirebaseFirestore.DocumentReference): Promise<Partial<AglynOrgBilling>>;
90
+ /**
91
+ * Write the proposal and its audit row into the caller's transaction, so
92
+ * they commit with whatever else the caller writes (AGL-1784) — the owner
93
+ * invitation, for a hand-off that proposes in the same act (AGL-3956).
94
+ */
95
+ export declare function stageUpgradeProposal(tx: FirebaseFirestore.Transaction, db: FirebaseFirestore.Firestore, options: {
96
+ orgId: string;
97
+ proposal: OrgUpgradeProposal;
98
+ before: Partial<AglynOrgBilling>;
99
+ actorUid: string;
100
+ }): void;
101
+ /** "Proposed the Starter plan", naming the bundle when there is one. */
102
+ export declare function proposalActivityLine(proposal: OrgUpgradeProposal): string;
103
+ /** The workspace's feed line for a proposal, after it commits. */
104
+ export declare function recordUpgradeProposalActivity(orgId: string, actor: {
105
+ uid: string;
106
+ email?: string | null;
107
+ }, proposal: OrgUpgradeProposal): Promise<void>;
69
108
  /** Remove a standing proposal, audited. Answers whether one stood. */
70
109
  export declare function withdrawOrgUpgrade(options: {
71
110
  orgId: string;