@antelopejs/dms-saas 0.7.0 → 0.7.1
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/README.md +3 -3
- package/dist/auth/subscription-access-gate.d.ts +1 -0
- package/dist/auth/subscription-access-gate.js +19 -4
- package/dist/auth/subscription-access-gate.js.map +1 -1
- package/dist/config/runtime.d.ts +2 -0
- package/dist/config/runtime.js +12 -0
- package/dist/config/runtime.js.map +1 -1
- package/dist/crons/reconcile-guarded-downgrades.d.ts +3 -0
- package/dist/crons/reconcile-guarded-downgrades.js +39 -0
- package/dist/crons/reconcile-guarded-downgrades.js.map +1 -0
- package/dist/crons/reconcile-invoice-line-injections.d.ts +2 -0
- package/dist/crons/reconcile-invoice-line-injections.js +19 -0
- package/dist/crons/reconcile-invoice-line-injections.js.map +1 -0
- package/dist/crons/register.js +4 -0
- package/dist/crons/register.js.map +1 -1
- package/dist/implementations/dms-saas/plan-changes.d.ts +14 -0
- package/dist/implementations/dms-saas/plan-changes.js +118 -0
- package/dist/implementations/dms-saas/plan-changes.js.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/invoice-line-items/billing-window.js +6 -1
- package/dist/invoice-line-items/billing-window.js.map +1 -1
- package/dist/invoice-line-items/index.d.ts +1 -0
- package/dist/invoice-line-items/index.js +1 -0
- package/dist/invoice-line-items/index.js.map +1 -1
- package/dist/invoice-line-items/injection.d.ts +8 -1
- package/dist/invoice-line-items/injection.js +11 -59
- package/dist/invoice-line-items/injection.js.map +1 -1
- package/dist/invoice-line-items/recovery/admission.d.ts +11 -0
- package/dist/invoice-line-items/recovery/admission.js +54 -0
- package/dist/invoice-line-items/recovery/admission.js.map +1 -0
- package/dist/invoice-line-items/recovery/discovery.d.ts +1 -0
- package/dist/invoice-line-items/recovery/discovery.js +77 -0
- package/dist/invoice-line-items/recovery/discovery.js.map +1 -0
- package/dist/invoice-line-items/recovery/index.d.ts +6 -0
- package/dist/invoice-line-items/recovery/index.js +23 -0
- package/dist/invoice-line-items/recovery/index.js.map +1 -0
- package/dist/invoice-line-items/recovery/managed-lines.d.ts +25 -0
- package/dist/invoice-line-items/recovery/managed-lines.js +113 -0
- package/dist/invoice-line-items/recovery/managed-lines.js.map +1 -0
- package/dist/invoice-line-items/recovery/process.d.ts +3 -0
- package/dist/invoice-line-items/recovery/process.js +271 -0
- package/dist/invoice-line-items/recovery/process.js.map +1 -0
- package/dist/invoice-line-items/recovery/reconcile.d.ts +1 -0
- package/dist/invoice-line-items/recovery/reconcile.js +23 -0
- package/dist/invoice-line-items/recovery/reconcile.js.map +1 -0
- package/dist/invoice-line-items/recovery/task.model.d.ts +36 -0
- package/dist/invoice-line-items/recovery/task.model.js +108 -0
- package/dist/invoice-line-items/recovery/task.model.js.map +1 -0
- package/dist/invoice-line-items/recovery/task.table.d.ts +29 -0
- package/dist/invoice-line-items/recovery/task.table.js +119 -0
- package/dist/invoice-line-items/recovery/task.table.js.map +1 -0
- package/dist/operator-actions/db/lifecycle-delivery.table.d.ts +1 -0
- package/dist/operator-actions/db/lifecycle-delivery.table.js +4 -0
- package/dist/operator-actions/db/lifecycle-delivery.table.js.map +1 -1
- package/dist/operator-actions/lifecycle-outbox.d.ts +1 -0
- package/dist/operator-actions/lifecycle-outbox.js +7 -1
- package/dist/operator-actions/lifecycle-outbox.js.map +1 -1
- package/dist/plan-changes/deferred.js +17 -0
- package/dist/plan-changes/deferred.js.map +1 -1
- package/dist/plan-changes/guarded-free.d.ts +9 -0
- package/dist/plan-changes/guarded-free.js +152 -0
- package/dist/plan-changes/guarded-free.js.map +1 -0
- package/dist/plan-changes/guarded-landing.d.ts +1 -0
- package/dist/plan-changes/guarded-landing.js +233 -0
- package/dist/plan-changes/guarded-landing.js.map +1 -0
- package/dist/plan-changes/guarded-state.d.ts +9 -0
- package/dist/plan-changes/guarded-state.js +110 -0
- package/dist/plan-changes/guarded-state.js.map +1 -0
- package/dist/plan-changes/inventory-barrier.d.ts +3 -0
- package/dist/plan-changes/inventory-barrier.js +38 -0
- package/dist/plan-changes/inventory-barrier.js.map +1 -0
- package/dist/plans/seat-hooks.js +28 -3
- package/dist/plans/seat-hooks.js.map +1 -1
- package/dist/routes/tenant/tenant-plan-ops.d.ts +1 -0
- package/dist/routes/tenant/tenant-plan-ops.js +16 -0
- package/dist/routes/tenant/tenant-plan-ops.js.map +1 -1
- package/dist/routes/tenant/tenant-plan.js +13 -3
- package/dist/routes/tenant/tenant-plan.js.map +1 -1
- package/dist/stripe/webhook-handlers.js +7 -1
- package/dist/stripe/webhook-handlers.js.map +1 -1
- package/dist/stripe/webhook-shared.js +5 -0
- package/dist/stripe/webhook-shared.js.map +1 -1
- package/dist/types/config.d.ts +3 -0
- package/frontend-vue/app/build/public/routes.ts +3 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"injection.js","sourceRoot":"","sources":["../../src/invoice-line-items/injection.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"injection.js","sourceRoot":"","sources":["../../src/invoice-line-items/injection.ts"],"names":[],"mappings":";;;AAkDA,oDAOC;AAWD,oDAqBC;AAMD,4DAqBC;AAED,wDAWC;AAED,sDAgBC;AAiCD,4EAkBC;AAtMD,gEAA6D;AAC7D,6FAAqE;AASrE,0FAAwG;AAExG,6CAAmD;AACnD,6DAGkC;AAClC,8BAAgD;AAChD,qDAA0D;AAG7C,QAAA,iBAAiB,GAAG,aAAa,CAAC;AAElC,QAAA,sBAAsB,GAAG,kBAAkB,CAAC;AACzD,MAAM,sBAAsB,GAAG,kBAAkB,CAAC;AAClD,MAAM,kBAAkB,GAAG,cAAc,CAAC;AAC1C,MAAM,sBAAsB,GAAG,mBAAmB,CAAC;AACnD,MAAM,4BAA4B,GAAG,oBAAoB,CAAC;AAC1D,MAAM,oBAAoB,GAAG,OAAO,CAAC;AACrC,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,cAAc,GAAG,GAA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Q,CAAC;KACtD,EACD;QACE,cAAc,EAAE,GAAG,sBAAsB,IAAI,OAAO,CAAC,SAAS,IAAI,QAAQ,CAAC,OAAO,EAAE;KACrF,CACF,CAAC;AACJ,CAAC;AAED,SAAS,KAAK,CAAC,YAAoB;IACjC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;AACrE,CAAC;AAGM,KAAK,UAAU,gCAAgC,CACpD,UAAkB,EAClB,MAA8B,EAC9B,QAAiC;IAEjC,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,eAAe,EAAE,OAAO,IAAI,CAAC,EAAE,CAAC;QAC/D,IAAI,CAAC;YACH,MAAM,qBAAqB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1D,OAAO;QACT,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,OAAO,KAAK,eAAe;gBAAE,MAAM,KAAK,CAAC;YAC7C,iBAAO,CAAC,IAAI,CACV,GAAG,UAAU,mBAAmB,QAAQ,CAAC,OAAO,gBAAgB,MAAM,CAAC,OAAO,CAAC,SAAS,EAAE,EAC1F,KAAK,CACN,CAAC;YACF,MAAM,KAAK,CAAC,cAAc,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import type { InvoiceLineInjection, InvoiceLineInjectionSource } from "./task.table";
|
|
3
|
+
export interface CycleInvoiceAdmission {
|
|
4
|
+
invoice: Stripe.Invoice;
|
|
5
|
+
tenantId: string;
|
|
6
|
+
customerId: string;
|
|
7
|
+
source: InvoiceLineInjectionSource;
|
|
8
|
+
eventId: string | null;
|
|
9
|
+
}
|
|
10
|
+
export declare function registerCycleInvoice(admission: CycleInvoiceAdmission): Promise<InvoiceLineInjection | null>;
|
|
11
|
+
export declare function admitCycleInvoice(admission: CycleInvoiceAdmission): Promise<void>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerCycleInvoice = registerCycleInvoice;
|
|
4
|
+
exports.admitCycleInvoice = admitCycleInvoice;
|
|
5
|
+
const interface_database_decorators_1 = require("@antelopejs/interface-database-decorators");
|
|
6
|
+
const invoice_line_items_1 = require("../../implementations/dms-saas/invoice-line-items");
|
|
7
|
+
const config_1 = require("../../config");
|
|
8
|
+
const payload_shapes_1 = require("../../stripe/payload-shapes");
|
|
9
|
+
const injection_1 = require("../injection");
|
|
10
|
+
const process_1 = require("./process");
|
|
11
|
+
const task_model_1 = require("./task.model");
|
|
12
|
+
async function registerCycleInvoice(admission) {
|
|
13
|
+
const providerIds = expectedProviderIds();
|
|
14
|
+
if (providerIds.length === 0)
|
|
15
|
+
return null;
|
|
16
|
+
if (!(0, injection_1.canInjectIntoInvoice)(admission.invoice))
|
|
17
|
+
return null;
|
|
18
|
+
const subscriptionId = (0, payload_shapes_1.readInvoiceSubscriptionId)(admission.invoice);
|
|
19
|
+
if (!subscriptionId)
|
|
20
|
+
return null;
|
|
21
|
+
const target = await (0, injection_1.buildInjectionTarget)(admission.invoice, admission.tenantId, admission.customerId);
|
|
22
|
+
if (!target)
|
|
23
|
+
return null;
|
|
24
|
+
return (0, interface_database_decorators_1.GetModel)(task_model_1.InvoiceLineInjectionModel).register({
|
|
25
|
+
_id: target.context.invoiceId,
|
|
26
|
+
tenantId: admission.tenantId,
|
|
27
|
+
customerId: admission.customerId,
|
|
28
|
+
stripeSubscriptionId: subscriptionId,
|
|
29
|
+
currency: target.context.currency,
|
|
30
|
+
periodStart: target.context.periodStart,
|
|
31
|
+
periodEnd: target.context.periodEnd,
|
|
32
|
+
source: admission.source,
|
|
33
|
+
eventId: admission.eventId,
|
|
34
|
+
providerIds,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function expectedProviderIds() {
|
|
38
|
+
const required = (0, config_1.getRequiredInvoiceLineProviders)();
|
|
39
|
+
const registered = (0, invoice_line_items_1.getInvoiceLineItemsProviders)().map((provider) => provider.id);
|
|
40
|
+
return [...new Set([...required, ...registered])].sort();
|
|
41
|
+
}
|
|
42
|
+
async function admitCycleInvoice(admission) {
|
|
43
|
+
const registered = await registerCycleInvoice(admission);
|
|
44
|
+
if (!registered)
|
|
45
|
+
return;
|
|
46
|
+
const task = await (0, process_1.processInvoiceLineInjection)(registered._id);
|
|
47
|
+
if (task?.suspendedAt)
|
|
48
|
+
return;
|
|
49
|
+
const why = task?.state === "needs_operator"
|
|
50
|
+
? `operator required before suspension (${task.reason})`
|
|
51
|
+
: `suspension not confirmed yet (${task?.lastError ?? "held by another worker"}); the recovery task retries it`;
|
|
52
|
+
throw new Error(`Invoice ${registered._id}: ${why}`);
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=admission.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admission.js","sourceRoot":"","sources":["../../../src/invoice-line-items/recovery/admission.ts"],"names":[],"mappings":";;AA0BA,oDA0BC;AA4BD,8CAYC;AA5FD,6FAAqE;AAErE,0FAAiG;AACjG,yCAA+D;AAC/D,gEAAwE;AACxE,4CAA0E;AAC1E,uCAAwD;AACxD,6CAAyD;AAmBlD,KAAK,UAAU,oBAAoB,CACxC,SAAgC;IAEhC,MAAM,WAAW,GAAG,mBAAmB,EAAE,CAAC;IAC1C,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1C,IAAI,CAAC,IAAA,gCAAoB,EAAC,SAAS,CAAC,OAAO,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1D,MAAM,cAAc,GAAG,IAAA,0CAAyB,EAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACpE,IAAI,CAAC,cAAc;QAAE,OAAO,IAAI,CAAC;IACjC,MAAM,MA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OAAO;IAC9B,MAAM,GAAG,GACP,IAAI,EAAE,KAAK,KAAK,gBAAgB;QAC9B,CAAC,CAAC,wCAAwC,IAAI,CAAC,MAAM,GAAG;QACxD,CAAC,CAAC,iCAAiC,IAAI,EAAE,SAAS,IAAI,wBAAwB,iCAAiC,CAAC;IACpH,MAAM,IAAI,KAAK,CAAC,WAAW,UAAU,CAAC,GAAG,KAAK,GAAG,EAAE,CAAC,CAAC;AACvD,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function discoverUnregisteredCycleInvoices(): Promise<number>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.discoverUnregisteredCycleInvoices = discoverUnregisteredCycleInvoices;
|
|
4
|
+
const logging_1 = require("@antelopejs/interface-core/logging");
|
|
5
|
+
const interface_database_1 = require("@antelopejs/interface-database");
|
|
6
|
+
const interface_database_decorators_1 = require("@antelopejs/interface-database-decorators");
|
|
7
|
+
const billing_1 = require("@antelopejs/interface-dms-saas/billing");
|
|
8
|
+
const config_1 = require("../../config");
|
|
9
|
+
const db_1 = require("../../db");
|
|
10
|
+
const client_1 = require("../../stripe/client");
|
|
11
|
+
const utils_1 = require("../../utils");
|
|
12
|
+
const admission_1 = require("./admission");
|
|
13
|
+
const task_model_1 = require("./task.model");
|
|
14
|
+
const LOG_PREFIX = "[dms-saas:invoice-line-recovery]";
|
|
15
|
+
const DRAFT_PAGE_SIZE = 100;
|
|
16
|
+
const MS_PER_SECOND = 1000;
|
|
17
|
+
async function managedSubscriptions() {
|
|
18
|
+
const rows = await (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, interface_database_1.CROSS_INSTANCE).getAll();
|
|
19
|
+
return rows
|
|
20
|
+
.filter((row) => !!row.stripeCustomerId &&
|
|
21
|
+
!!row.stripeSubscriptionId &&
|
|
22
|
+
!(0, billing_1.isComplimentarySubscription)(row) &&
|
|
23
|
+
(row.paidUsagePeriods ?? []).some((period) => period.stripeSubscriptionId === row.stripeSubscriptionId))
|
|
24
|
+
.map((row) => ({
|
|
25
|
+
tenantId: (0, utils_1.getRowInstance)(row),
|
|
26
|
+
customerId: row.stripeCustomerId,
|
|
27
|
+
stripeSubscriptionId: row.stripeSubscriptionId,
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
function isDiscoverable(invoice, since) {
|
|
31
|
+
return (invoice.billing_reason === "subscription_cycle" &&
|
|
32
|
+
invoice.status === "draft" &&
|
|
33
|
+
invoice.auto_advance === true &&
|
|
34
|
+
invoice.created * MS_PER_SECOND >= since.getTime());
|
|
35
|
+
}
|
|
36
|
+
async function discoverForSubscription(managed, since) {
|
|
37
|
+
const tasks = (0, interface_database_decorators_1.GetModel)(task_model_1.InvoiceLineInjectionModel);
|
|
38
|
+
let registered = 0;
|
|
39
|
+
for await (const invoice of (0, client_1.getStripeClient)().invoices.list({
|
|
40
|
+
subscription: managed.stripeSubscriptionId,
|
|
41
|
+
customer: managed.customerId,
|
|
42
|
+
status: "draft",
|
|
43
|
+
created: { gte: Math.floor(since.getTime() / MS_PER_SECOND) },
|
|
44
|
+
limit: DRAFT_PAGE_SIZE,
|
|
45
|
+
})) {
|
|
46
|
+
if (!isDiscoverable(invoice, since) || !invoice.id)
|
|
47
|
+
continue;
|
|
48
|
+
if (await tasks.get(invoice.id))
|
|
49
|
+
continue;
|
|
50
|
+
const task = await (0, admission_1.registerCycleInvoice)({
|
|
51
|
+
invoice,
|
|
52
|
+
tenantId: managed.tenantId,
|
|
53
|
+
customerId: managed.customerId,
|
|
54
|
+
source: "discovery",
|
|
55
|
+
eventId: null,
|
|
56
|
+
});
|
|
57
|
+
if (task)
|
|
58
|
+
registered += 1;
|
|
59
|
+
}
|
|
60
|
+
return registered;
|
|
61
|
+
}
|
|
62
|
+
async function discoverUnregisteredCycleInvoices() {
|
|
63
|
+
const since = (0, config_1.getInvoiceDiscoverySince)();
|
|
64
|
+
if (!since)
|
|
65
|
+
return 0;
|
|
66
|
+
let registered = 0;
|
|
67
|
+
for (const managed of await managedSubscriptions()) {
|
|
68
|
+
try {
|
|
69
|
+
registered += await discoverForSubscription(managed, since);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
logging_1.Logging.Error(`${LOG_PREFIX} discovery failed for workspace '${managed.tenantId}'`, error);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return registered;
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=discovery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discovery.js","sourceRoot":"","sources":["../../../src/invoice-line-items/recovery/discovery.ts"],"names":[],"mappings":";;AAwFA,8EAeC;AAvGD,gEAA6D;AAC7D,uEAAgE;AAChE,6FAAqE;AACrE,oEAAqF;AAErF,yCAAwD;AACxD,iCAAmD;AACnD,gDAAsD;AACtD,uCAA6C;AAC7C,2CAAmD;AACnD,6CAAyD;AAEzD,MAAM,UAAU,GAAG,kCAAkC,CAAC;AACtD,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,MAAM,aAAa,GAAG,IAAI,CAAC;AAQ3B,KAAK,UAAU,oBAAoB;IACjC,MAAM,IAAI,GAAG,MAAM,IAAA,wCAAQ,EAAC,4BAAuB,EAAE,mCAAc,CAAC,CAAC,MAAM,EAAE,CAAC;IAC9E,OAAO,IAAI;SACR,MAAM,CACL,CAAC,GAAG,EAAE,EAAE,CACN,CAAC,CAAC,GAAG,CAAC,gBAAgB;QACtB,CAAC,CAAC,GAAG,CAAC,oBAAoB;QAC1B,CAAC,IAAA,qCAA2B,EAAC,GAAG,CAAC;QACjC,CAAC,GAAG,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC,IAAI,CAC/B,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,oBAAoB,KAAK,GAAG,CAAC,oBAAoB,CACrE,CACJ;SACA,GAAG,CAAC,CAAC,GAAG,EAAE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,UAAU,EAAE,OAAO,CAAC,UAAU;YAC9B,MAAM,EAAE,WAAW;YACnB,OAAO,EAAE,IAAI;SACd,CAAC,CAAC;QACH,IAAI,IAAI;YAAE,UAAU,IAAI,CAAC,CAAC;IAC5B,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAOM,KAAK,UAAU,iCAAiC;IACrD,MAAM,KAAK,GAAG,IAAA,iCAAwB,GAAE,CAAC;IACzC,IAAI,CAAC,KAAK;QAAE,OAAO,CAAC,CAAC;IACrB,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,KAAK,MAAM,OAAO,IAAI,MAAM,oBAAoB,EAAE,EAAE,CAAC;QACnD,IAAI,CAAC;YACH,UAAU,IAAI,MAAM,uBAAuB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QAC9D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,iBAAO,CAAC,KAAK,CACX,GAAG,UAAU,oCAAoC,OAAO,CAAC,QAAQ,GAAG,EACpE,KAAK,CACN,CAAC;QACJ,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./admission"), exports);
|
|
18
|
+
__exportStar(require("./discovery"), exports);
|
|
19
|
+
__exportStar(require("./process"), exports);
|
|
20
|
+
__exportStar(require("./reconcile"), exports);
|
|
21
|
+
__exportStar(require("./task.model"), exports);
|
|
22
|
+
__exportStar(require("./task.table"), exports);
|
|
23
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/invoice-line-items/recovery/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8CAA4B;AAC5B,8CAA4B;AAC5B,4CAA0B;AAC1B,8CAA4B;AAC5B,+CAA6B;AAC7B,+CAA6B"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { InvoiceLineItemsProvider, PreparedInvoiceLineItem } from "@antelopejs/interface-dms-saas/invoice-line-items";
|
|
2
|
+
import { selectInvoiceLineItemsToCreate } from "@antelopejs/interface-dms-saas/invoice-line-items";
|
|
3
|
+
import type Stripe from "stripe";
|
|
4
|
+
import type { InvoiceLineInjection } from "./task.table";
|
|
5
|
+
export interface ManagedLine {
|
|
6
|
+
provider: string;
|
|
7
|
+
lineKey: string;
|
|
8
|
+
amount: number;
|
|
9
|
+
currency: string;
|
|
10
|
+
periodStart: number;
|
|
11
|
+
periodEnd: number;
|
|
12
|
+
}
|
|
13
|
+
export interface ProviderSelection {
|
|
14
|
+
accepted: PreparedInvoiceLineItem[];
|
|
15
|
+
invalidKeys: string[];
|
|
16
|
+
}
|
|
17
|
+
export type LinesComparison = "match" | "missing_only" | "duplicate" | "unexpected_or_changed";
|
|
18
|
+
export declare function listInvoiceItems(invoiceId: string): Promise<Stripe.InvoiceItem[]>;
|
|
19
|
+
export declare function managedLinesOf(items: readonly Stripe.InvoiceItem[]): ManagedLine[];
|
|
20
|
+
export declare function selectProviderLines(provider: InvoiceLineItemsProvider, lines: Parameters<typeof selectInvoiceLineItemsToCreate>[1]): ProviderSelection;
|
|
21
|
+
export declare function expectedLine(task: InvoiceLineInjection, provider: string, prepared: PreparedInvoiceLineItem): ManagedLine;
|
|
22
|
+
export declare function compareManagedLines(expected: readonly ManagedLine[], actual: readonly ManagedLine[]): LinesComparison;
|
|
23
|
+
export declare function identityMismatch(invoice: Stripe.Invoice, task: InvoiceLineInjection): string | null;
|
|
24
|
+
export declare function isSuspendedDraft(invoice: Stripe.Invoice): boolean;
|
|
25
|
+
export declare function invoiceFingerprint(task: InvoiceLineInjection, lines: readonly ManagedLine[]): string;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.listInvoiceItems = listInvoiceItems;
|
|
4
|
+
exports.managedLinesOf = managedLinesOf;
|
|
5
|
+
exports.selectProviderLines = selectProviderLines;
|
|
6
|
+
exports.expectedLine = expectedLine;
|
|
7
|
+
exports.compareManagedLines = compareManagedLines;
|
|
8
|
+
exports.identityMismatch = identityMismatch;
|
|
9
|
+
exports.isSuspendedDraft = isSuspendedDraft;
|
|
10
|
+
exports.invoiceFingerprint = invoiceFingerprint;
|
|
11
|
+
const invoice_line_items_1 = require("@antelopejs/interface-dms-saas/invoice-line-items");
|
|
12
|
+
const client_1 = require("../../stripe/client");
|
|
13
|
+
const payload_shapes_1 = require("../../stripe/payload-shapes");
|
|
14
|
+
const injection_1 = require("../injection");
|
|
15
|
+
const INVOICE_ITEMS_PAGE_SIZE = 100;
|
|
16
|
+
const MS_PER_SECOND = 1000;
|
|
17
|
+
const DRAFT = "draft";
|
|
18
|
+
async function listInvoiceItems(invoiceId) {
|
|
19
|
+
const items = [];
|
|
20
|
+
for await (const item of (0, client_1.getStripeClient)().invoiceItems.list({
|
|
21
|
+
invoice: invoiceId,
|
|
22
|
+
limit: INVOICE_ITEMS_PAGE_SIZE,
|
|
23
|
+
})) {
|
|
24
|
+
items.push(item);
|
|
25
|
+
}
|
|
26
|
+
return items;
|
|
27
|
+
}
|
|
28
|
+
function managedLinesOf(items) {
|
|
29
|
+
return items
|
|
30
|
+
.filter((item) => typeof item.metadata?.[injection_1.LINE_KEY_METADATA] === "string" &&
|
|
31
|
+
typeof item.metadata?.[injection_1.LINE_PROVIDER_METADATA] === "string")
|
|
32
|
+
.map((item) => ({
|
|
33
|
+
provider: item.metadata?.[injection_1.LINE_PROVIDER_METADATA],
|
|
34
|
+
lineKey: item.metadata?.[injection_1.LINE_KEY_METADATA],
|
|
35
|
+
amount: item.amount,
|
|
36
|
+
currency: item.currency.toLowerCase(),
|
|
37
|
+
periodStart: item.period?.start ?? 0,
|
|
38
|
+
periodEnd: item.period?.end ?? 0,
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
function selectProviderLines(provider, lines) {
|
|
42
|
+
const selection = (0, invoice_line_items_1.selectInvoiceLineItemsToCreate)(provider.id, lines, new Set());
|
|
43
|
+
return {
|
|
44
|
+
accepted: selection.accepted,
|
|
45
|
+
invalidKeys: selection.skipped
|
|
46
|
+
.filter((line) => line.reason === "invalid" || line.reason === "duplicate_key")
|
|
47
|
+
.map((line) => line.lineKey),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function toSeconds(date) {
|
|
51
|
+
return Math.floor(new Date(date).getTime() / MS_PER_SECOND);
|
|
52
|
+
}
|
|
53
|
+
function expectedLine(task, provider, prepared) {
|
|
54
|
+
return {
|
|
55
|
+
provider,
|
|
56
|
+
lineKey: prepared.lineKey,
|
|
57
|
+
amount: prepared.item.amountCents,
|
|
58
|
+
currency: task.currency.toLowerCase(),
|
|
59
|
+
periodStart: toSeconds(task.periodStart),
|
|
60
|
+
periodEnd: toSeconds(task.periodEnd),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function canonical(line) {
|
|
64
|
+
return [
|
|
65
|
+
line.provider,
|
|
66
|
+
line.lineKey,
|
|
67
|
+
line.amount,
|
|
68
|
+
line.currency,
|
|
69
|
+
line.periodStart,
|
|
70
|
+
line.periodEnd,
|
|
71
|
+
].join("|");
|
|
72
|
+
}
|
|
73
|
+
function compareManagedLines(expected, actual) {
|
|
74
|
+
const keys = actual.map((line) => line.lineKey);
|
|
75
|
+
if (new Set(keys).size !== keys.length)
|
|
76
|
+
return "duplicate";
|
|
77
|
+
const wanted = new Map(expected.map((line) => [line.lineKey, canonical(line)]));
|
|
78
|
+
for (const line of actual) {
|
|
79
|
+
if (wanted.get(line.lineKey) !== canonical(line))
|
|
80
|
+
return "unexpected_or_changed";
|
|
81
|
+
}
|
|
82
|
+
return actual.length === expected.length ? "match" : "missing_only";
|
|
83
|
+
}
|
|
84
|
+
function identityMismatch(invoice, task) {
|
|
85
|
+
const customer = typeof invoice.customer === "string"
|
|
86
|
+
? invoice.customer
|
|
87
|
+
: invoice.customer?.id;
|
|
88
|
+
if (invoice.id !== task._id)
|
|
89
|
+
return "invoice";
|
|
90
|
+
if (customer !== task.customerId)
|
|
91
|
+
return "customer";
|
|
92
|
+
if ((0, payload_shapes_1.readInvoiceSubscriptionId)(invoice) !== task.stripeSubscriptionId)
|
|
93
|
+
return "subscription";
|
|
94
|
+
if (invoice.currency.toLowerCase() !== task.currency.toLowerCase())
|
|
95
|
+
return "currency";
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
function isSuspendedDraft(invoice) {
|
|
99
|
+
return invoice.status === DRAFT && invoice.auto_advance === false;
|
|
100
|
+
}
|
|
101
|
+
function invoiceFingerprint(task, lines) {
|
|
102
|
+
return JSON.stringify({
|
|
103
|
+
invoice: task._id,
|
|
104
|
+
customer: task.customerId,
|
|
105
|
+
subscription: task.stripeSubscriptionId,
|
|
106
|
+
currency: task.currency.toLowerCase(),
|
|
107
|
+
periodStart: toSeconds(task.periodStart),
|
|
108
|
+
periodEnd: toSeconds(task.periodEnd),
|
|
109
|
+
providers: [...task.providerIds].sort(),
|
|
110
|
+
lines: lines.map(canonical).sort(),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=managed-lines.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"managed-lines.js","sourceRoot":"","sources":["../../../src/invoice-line-items/recovery/managed-lines.ts"],"names":[],"mappings":";;AAuCA,4CAWC;AAGD,wCAiBC;AAGD,kDAiBC;AAOD,oCAaC;AAkBD,kDAcC;AAaD,4CAeC;AAGD,4CAEC;AAOD,gDAcC;AAhMD,0FAAmG;AAEnG,gDAAsD;AACtD,gEAAwE;AACxE,4CAAyE;AAGzE,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,KAAK,GAAG,OAAO,CAAC;AA0Bf,KAAK,UAAU,gBAAgB,CACpC,SAAiB;IAEjB,MAAM,KAAK,GAAyB,EAAE,CAAC;IACvC,IAAI,KAAK,EAAE,MAAM,IAAI,IAAI,IAAA,wBAAe,GAAE,CAAC,YAAY,CAAC,IAAI,CAAC;QAC3D,OAAO,EAAE,SAAS;QAClB,KAAK,EAAE,uBAAuB;KAC/B,CAAC,EAAE,CAAC;QACH,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAGD,SAAgB,cAAc,CAC5B,KAAoC;IAEpC,OAAO,KAAK;SACT,MAAM,CACL,CAAC,IAAI,EAAE,EAAE,CACP,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC,6BAAiB,CAAC,KAAK,QAAQ;QACtD,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC,kCAAsB,CAAC,KAAK,QAAQ,CAC9D;SACA,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACd,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,kCAAsB,CAAW;QAC3D,OAAO,EAAE,IAAI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,EAAE,KAAK,IAAI,CAAC,GAAG;QAAE,OAAO,SAAS,CAAC;IAC9C,IAAI,QAAQ,KAAK,IAAI,CAAC,UAAU;QAAE,OAAO,UAAU,CAAC;IACpD,IAAI,IAAA,0CAAyB,EAAC,OAAO,CAAC,KAAK,IAAI,CAAC,oBAAoB;QAClE,OAAO,cAAc,CAAC;IACxB,IAAI,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,KAAK,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE;QAChE,OAAO,UAAU,CAAC;IACpB,OAAO,IAAI,CAAC;AACd,CAAC;AAGD,SAAgB,gBAAgB,CAAC,OAAuB;IACtD,OAAO,OAAO,CAAC,MAAM,KAAK,KAAK,IAAI,OAAO,CAAC,YAAY,KAAK,KAAK,CAAC;AACpE,CAAC;AAOD,SAAgB,kBAAkB,CAChC,IAA0B,EAC1B,KAA6B;IAE7B,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,OAAO,EAAE,IAAI,CAAC,GAAG;QACjB,QAAQ,EAAE,IAAI,CAAC,UAAU;QACzB,YAAY,EAAE,IAAI,CAAC,oBAAoB;QACvC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE;QACrC,WAAW,EAAE,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC;QACxC,SAAS,EAAE,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC;QACpC,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,IAAI,EAAE;QACvC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE;KACnC,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.INVOICE_LINE_LEASE_MS = void 0;
|
|
4
|
+
exports.processInvoiceLineInjection = processInvoiceLineInjection;
|
|
5
|
+
const logging_1 = require("@antelopejs/interface-core/logging");
|
|
6
|
+
const interface_database_decorators_1 = require("@antelopejs/interface-database-decorators");
|
|
7
|
+
const db_1 = require("@antelopejs/interface-dms-saas/db");
|
|
8
|
+
const invoice_line_items_1 = require("@antelopejs/interface-dms-saas/invoice-line-items");
|
|
9
|
+
const invoice_line_items_2 = require("../../implementations/dms-saas/invoice-line-items");
|
|
10
|
+
const client_1 = require("../../stripe/client");
|
|
11
|
+
const injection_1 = require("../injection");
|
|
12
|
+
const managed_lines_1 = require("./managed-lines");
|
|
13
|
+
const task_model_1 = require("./task.model");
|
|
14
|
+
const LOG_PREFIX = "[dms-saas:invoice-line-recovery]";
|
|
15
|
+
exports.INVOICE_LINE_LEASE_MS = 5 * 60 * 1000;
|
|
16
|
+
const RETRY_AFTER_MS = 5 * 60 * 1000;
|
|
17
|
+
const SUSPEND_KEY_PREFIX = "saas-invoice-suspend";
|
|
18
|
+
const FINALIZE_KEY_PREFIX = "saas-invoice-finalize";
|
|
19
|
+
const INVOICE_CREATED_EVENT = "invoice.created";
|
|
20
|
+
const DRAFT = "draft";
|
|
21
|
+
const RECOGNIZED_FINAL_STATUSES = new Set(["open", "paid"]);
|
|
22
|
+
const MAX_STEPS_PER_RUN = 4;
|
|
23
|
+
class LeaseLostError extends Error {
|
|
24
|
+
}
|
|
25
|
+
function model() {
|
|
26
|
+
return (0, interface_database_decorators_1.GetModel)(task_model_1.InvoiceLineInjectionModel);
|
|
27
|
+
}
|
|
28
|
+
async function holdLease(lease) {
|
|
29
|
+
if (!(await model().renew(lease, exports.INVOICE_LINE_LEASE_MS)))
|
|
30
|
+
throw new LeaseLostError(lease.task._id);
|
|
31
|
+
}
|
|
32
|
+
async function transition(lease, patch) {
|
|
33
|
+
if (!(await model().advance(lease, patch)))
|
|
34
|
+
throw new LeaseLostError(lease.task._id);
|
|
35
|
+
return "advanced";
|
|
36
|
+
}
|
|
37
|
+
function toOperator(lease, reason) {
|
|
38
|
+
logging_1.Logging.Error(`${LOG_PREFIX} invoice ${lease.task._id} of workspace '${lease.task.tenantId}' needs an operator: ${reason}`);
|
|
39
|
+
return transition(lease, { state: "needs_operator", reason });
|
|
40
|
+
}
|
|
41
|
+
function errorText(error) {
|
|
42
|
+
return error instanceof Error ? error.message : String(error);
|
|
43
|
+
}
|
|
44
|
+
async function retryLater(lease, lastError) {
|
|
45
|
+
await transition(lease, {
|
|
46
|
+
lastError,
|
|
47
|
+
attemptCount: lease.task.attemptCount + 1,
|
|
48
|
+
nextAttemptAt: new Date(Date.now() + RETRY_AFTER_MS),
|
|
49
|
+
});
|
|
50
|
+
return "wait";
|
|
51
|
+
}
|
|
52
|
+
async function retrieveInvoice(invoiceId) {
|
|
53
|
+
const invoice = await (0, client_1.getStripeClient)().invoices.retrieve(invoiceId);
|
|
54
|
+
if (!invoice)
|
|
55
|
+
throw new Error(`Stripe returned no invoice for ${invoiceId}`);
|
|
56
|
+
return invoice;
|
|
57
|
+
}
|
|
58
|
+
function stateOf(invoice) {
|
|
59
|
+
return `${invoice.status}/auto_advance=${invoice.auto_advance}`;
|
|
60
|
+
}
|
|
61
|
+
async function suspend(lease) {
|
|
62
|
+
const invoiceId = lease.task._id;
|
|
63
|
+
const before = await retrieveInvoice(invoiceId);
|
|
64
|
+
const foreign = (0, managed_lines_1.identityMismatch)(before, lease.task);
|
|
65
|
+
if (foreign)
|
|
66
|
+
return toOperator(lease, `before_suspension:identity_${foreign}`);
|
|
67
|
+
if (before.status !== DRAFT)
|
|
68
|
+
return toOperator(lease, `before_suspension:finalized:${stateOf(before)}`);
|
|
69
|
+
let requestError = null;
|
|
70
|
+
await holdLease(lease);
|
|
71
|
+
try {
|
|
72
|
+
await (0, client_1.getStripeClient)().invoices.update(invoiceId, { auto_advance: false }, { idempotencyKey: `${SUSPEND_KEY_PREFIX}:${invoiceId}` });
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
requestError = errorText(error);
|
|
76
|
+
}
|
|
77
|
+
const invoice = await retrieveInvoice(invoiceId);
|
|
78
|
+
if ((0, managed_lines_1.isSuspendedDraft)(invoice))
|
|
79
|
+
return transition(lease, {
|
|
80
|
+
state: "suspended",
|
|
81
|
+
suspendedAt: new Date(),
|
|
82
|
+
lastError: null,
|
|
83
|
+
});
|
|
84
|
+
if (invoice.status !== DRAFT)
|
|
85
|
+
return toOperator(lease, `before_suspension:finalized:${stateOf(invoice)}`);
|
|
86
|
+
return retryLater(lease, requestError ?? "suspension_not_visible");
|
|
87
|
+
}
|
|
88
|
+
function contextOf(task) {
|
|
89
|
+
return {
|
|
90
|
+
tenantId: task.tenantId,
|
|
91
|
+
invoiceId: task._id,
|
|
92
|
+
currency: task.currency,
|
|
93
|
+
periodStart: new Date(task.periodStart),
|
|
94
|
+
periodEnd: new Date(task.periodEnd),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
async function resolveAll(task) {
|
|
98
|
+
const resolved = {
|
|
99
|
+
expected: [],
|
|
100
|
+
accepted: [],
|
|
101
|
+
blocked: null,
|
|
102
|
+
waiting: null,
|
|
103
|
+
};
|
|
104
|
+
const registered = new Map((0, invoice_line_items_2.getInvoiceLineItemsProviders)().map((provider) => [provider.id, provider]));
|
|
105
|
+
for (const providerId of task.providerIds) {
|
|
106
|
+
const provider = registered.get(providerId);
|
|
107
|
+
if (!provider) {
|
|
108
|
+
resolved.waiting ??= `provider_missing:${providerId}`;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const resolution = (0, invoice_line_items_1.normalizeInvoiceLineItemsResolution)(await provider.resolve(contextOf(task)));
|
|
112
|
+
if (resolution.status === "blocked") {
|
|
113
|
+
resolved.blocked = `provider_blocked:${provider.id}:${resolution.reason}`;
|
|
114
|
+
return resolved;
|
|
115
|
+
}
|
|
116
|
+
if (resolution.status === "not_ready") {
|
|
117
|
+
resolved.waiting ??= `provider_not_ready:${provider.id}:${resolution.reason}`;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
const selection = (0, managed_lines_1.selectProviderLines)(provider, resolution.lines);
|
|
121
|
+
if (selection.invalidKeys.length > 0) {
|
|
122
|
+
resolved.blocked = `provider_invalid_lines:${provider.id}:${selection.invalidKeys.join(",")}`;
|
|
123
|
+
return resolved;
|
|
124
|
+
}
|
|
125
|
+
for (const prepared of selection.accepted) {
|
|
126
|
+
resolved.accepted.push({ provider: provider.id, prepared });
|
|
127
|
+
resolved.expected.push((0, managed_lines_1.expectedLine)(task, provider.id, prepared));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return resolved;
|
|
131
|
+
}
|
|
132
|
+
async function createMissingLines(lease, resolved, existing) {
|
|
133
|
+
const present = new Set(existing.map((line) => line.lineKey));
|
|
134
|
+
const { task } = lease;
|
|
135
|
+
for (const { provider, prepared } of resolved.accepted) {
|
|
136
|
+
if (present.has(prepared.lineKey))
|
|
137
|
+
continue;
|
|
138
|
+
await holdLease(lease);
|
|
139
|
+
await (0, injection_1.createInvoiceLineItemWithRetries)(provider, { customerId: task.customerId, context: contextOf(task) }, prepared);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function draftProblem(invoice, task) {
|
|
143
|
+
const foreign = (0, managed_lines_1.identityMismatch)(invoice, task);
|
|
144
|
+
if (foreign)
|
|
145
|
+
return `identity_${foreign}`;
|
|
146
|
+
if (!(0, managed_lines_1.isSuspendedDraft)(invoice))
|
|
147
|
+
return `left_suspension:${stateOf(invoice)}`;
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
async function injectLines(lease) {
|
|
151
|
+
const { task } = lease;
|
|
152
|
+
const problem = draftProblem(await retrieveInvoice(task._id), task);
|
|
153
|
+
if (problem)
|
|
154
|
+
return toOperator(lease, problem);
|
|
155
|
+
let resolved;
|
|
156
|
+
try {
|
|
157
|
+
resolved = await resolveAll(task);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
return retryLater(lease, `provider_failed:${errorText(error)}`);
|
|
161
|
+
}
|
|
162
|
+
if (resolved.blocked)
|
|
163
|
+
return toOperator(lease, resolved.blocked);
|
|
164
|
+
if (resolved.waiting)
|
|
165
|
+
return retryLater(lease, resolved.waiting);
|
|
166
|
+
const before = (0, managed_lines_1.managedLinesOf)(await (0, managed_lines_1.listInvoiceItems)(task._id));
|
|
167
|
+
const beforeComparison = (0, managed_lines_1.compareManagedLines)(resolved.expected, before);
|
|
168
|
+
if (beforeComparison === "duplicate" ||
|
|
169
|
+
beforeComparison === "unexpected_or_changed")
|
|
170
|
+
return toOperator(lease, `managed_lines_${beforeComparison}`);
|
|
171
|
+
await createMissingLines(lease, resolved, before);
|
|
172
|
+
const after = (0, managed_lines_1.managedLinesOf)(await (0, managed_lines_1.listInvoiceItems)(task._id));
|
|
173
|
+
const comparison = (0, managed_lines_1.compareManagedLines)(resolved.expected, after);
|
|
174
|
+
if (comparison === "missing_only")
|
|
175
|
+
return retryLater(lease, "managed_lines_not_yet_visible");
|
|
176
|
+
if (comparison !== "match")
|
|
177
|
+
return toOperator(lease, `managed_lines_${comparison}`);
|
|
178
|
+
return transition(lease, {
|
|
179
|
+
state: "finalizing",
|
|
180
|
+
fingerprint: (0, managed_lines_1.invoiceFingerprint)(task, after),
|
|
181
|
+
lastError: null,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
async function matchesRecord(invoice, task) {
|
|
185
|
+
if ((0, managed_lines_1.identityMismatch)(invoice, task))
|
|
186
|
+
return false;
|
|
187
|
+
const lines = (0, managed_lines_1.managedLinesOf)(await (0, managed_lines_1.listInvoiceItems)(task._id));
|
|
188
|
+
return (0, managed_lines_1.invoiceFingerprint)(task, lines) === task.fingerprint;
|
|
189
|
+
}
|
|
190
|
+
async function finalize(lease) {
|
|
191
|
+
const { task } = lease;
|
|
192
|
+
let invoice = await retrieveInvoice(task._id);
|
|
193
|
+
let requestError = null;
|
|
194
|
+
if (invoice.status === DRAFT) {
|
|
195
|
+
const problem = draftProblem(invoice, task);
|
|
196
|
+
if (problem)
|
|
197
|
+
return toOperator(lease, `before_finalize:${problem}`);
|
|
198
|
+
if (!(await matchesRecord(invoice, task)))
|
|
199
|
+
return toOperator(lease, "before_finalize:changed_since_verified");
|
|
200
|
+
await holdLease(lease);
|
|
201
|
+
try {
|
|
202
|
+
await (0, client_1.getStripeClient)().invoices.finalizeInvoice(task._id, { auto_advance: true }, { idempotencyKey: `${FINALIZE_KEY_PREFIX}:${task._id}` });
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
requestError = errorText(error);
|
|
206
|
+
}
|
|
207
|
+
invoice = await retrieveInvoice(task._id);
|
|
208
|
+
}
|
|
209
|
+
if (invoice.status === DRAFT)
|
|
210
|
+
return retryLater(lease, requestError ?? "finalization_not_visible");
|
|
211
|
+
if (!RECOGNIZED_FINAL_STATUSES.has(invoice.status ?? ""))
|
|
212
|
+
return toOperator(lease, `finalized_as:${invoice.status}`);
|
|
213
|
+
if (!(await matchesRecord(invoice, task)))
|
|
214
|
+
return toOperator(lease, `finalized_with_external_changes:${invoice.status}`);
|
|
215
|
+
return transition(lease, { state: "finalized", lastError: null });
|
|
216
|
+
}
|
|
217
|
+
const STEPS = {
|
|
218
|
+
registered: suspend,
|
|
219
|
+
suspended: injectLines,
|
|
220
|
+
finalizing: finalize,
|
|
221
|
+
};
|
|
222
|
+
async function closeWebhookReceipt(task) {
|
|
223
|
+
if (!task.eventId || !task.suspendedAt)
|
|
224
|
+
return;
|
|
225
|
+
const staleBefore = new Date(Date.now() - exports.INVOICE_LINE_LEASE_MS);
|
|
226
|
+
await (0, interface_database_decorators_1.GetModel)(db_1.StripeWebhookEventModel).resolveTakenOver(task.eventId, INVOICE_CREATED_EVENT, staleBefore, `resolved by invoice line injection task (${task.state})`);
|
|
227
|
+
}
|
|
228
|
+
async function runSteps(lease) {
|
|
229
|
+
for (let i = 0; i < MAX_STEPS_PER_RUN; i += 1) {
|
|
230
|
+
const step = STEPS[lease.task.state];
|
|
231
|
+
if (!step)
|
|
232
|
+
return;
|
|
233
|
+
if ((await step(lease)) === "wait")
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
async function processInvoiceLineInjection(invoiceId) {
|
|
238
|
+
const current = await model().get(invoiceId);
|
|
239
|
+
if (!current)
|
|
240
|
+
return undefined;
|
|
241
|
+
const lease = await model().acquire(current, exports.INVOICE_LINE_LEASE_MS);
|
|
242
|
+
if (!lease)
|
|
243
|
+
return current;
|
|
244
|
+
try {
|
|
245
|
+
await runSteps(lease);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
if (error instanceof LeaseLostError) {
|
|
249
|
+
logging_1.Logging.Warn(`${LOG_PREFIX} invoice ${invoiceId}: lease taken over, stopping`);
|
|
250
|
+
return model().get(invoiceId);
|
|
251
|
+
}
|
|
252
|
+
logging_1.Logging.Error(`${LOG_PREFIX} invoice ${invoiceId}: step failed`, error);
|
|
253
|
+
await model()
|
|
254
|
+
.advance(lease, {
|
|
255
|
+
lastError: errorText(error),
|
|
256
|
+
attemptCount: lease.task.attemptCount + 1,
|
|
257
|
+
nextAttemptAt: new Date(Date.now() + RETRY_AFTER_MS),
|
|
258
|
+
})
|
|
259
|
+
.catch(() => undefined);
|
|
260
|
+
}
|
|
261
|
+
await model()
|
|
262
|
+
.release(lease)
|
|
263
|
+
.catch(() => undefined);
|
|
264
|
+
const latest = await model().get(invoiceId);
|
|
265
|
+
if (latest)
|
|
266
|
+
await closeWebhookReceipt(latest).catch((error) => {
|
|
267
|
+
logging_1.Logging.Warn(`${LOG_PREFIX} invoice ${invoiceId}: receipt not closed`, error);
|
|
268
|
+
});
|
|
269
|
+
return latest;
|
|
270
|
+
}
|
|
271
|
+
//# sourceMappingURL=process.js.map
|