@antelopejs/dms-saas 0.7.0 → 0.7.2
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/PlanChangeReview.vue +53 -7
- package/frontend-vue/app/build/public/routes.ts +3 -1
- package/frontend-vue/app/components/WorkspaceCreateModal.vue +23 -5
- package/frontend-vue/app/composables/usePlanChangeReview.ts +25 -0
- package/frontend-vue/app/composables/useSaasRegistration.ts +25 -6
- package/frontend-vue/app/composables/useStripePaymentElement.ts +28 -12
- package/frontend-vue/app/custom-pages/auth/no-workspace.vue +23 -4
- package/frontend-vue/i18n/locales/saas-tenant-billing-en-GB.json +436 -432
- package/frontend-vue/i18n/locales/saas-tenant-billing-fr-FR.json +436 -432
- package/package.json +4 -4
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PlanChangeIncompatibleError = void 0;
|
|
4
|
+
exports.previewGuardedFreeChange = previewGuardedFreeChange;
|
|
5
|
+
exports.scheduleGuardedFreeChange = scheduleGuardedFreeChange;
|
|
6
|
+
exports.cancelGuardedFreeChange = cancelGuardedFreeChange;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const interface_database_decorators_1 = require("@antelopejs/interface-database-decorators");
|
|
9
|
+
const db_1 = require("../db");
|
|
10
|
+
const plan_changes_1 = require("../implementations/dms-saas/plan-changes");
|
|
11
|
+
const client_1 = require("../stripe/client");
|
|
12
|
+
const payload_shapes_1 = require("../stripe/payload-shapes");
|
|
13
|
+
const guarded_state_1 = require("./guarded-state");
|
|
14
|
+
const inventory_barrier_1 = require("./inventory-barrier");
|
|
15
|
+
class PlanChangeIncompatibleError extends Error {
|
|
16
|
+
incompatibilities;
|
|
17
|
+
constructor(incompatibilities) {
|
|
18
|
+
super("The workspace is incompatible with the target plan");
|
|
19
|
+
this.incompatibilities = incompatibilities;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
exports.PlanChangeIncompatibleError = PlanChangeIncompatibleError;
|
|
23
|
+
async function readSubscription(tenantId) {
|
|
24
|
+
const subscription = await (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId).findOne();
|
|
25
|
+
if (!subscription)
|
|
26
|
+
throw new Error("Workspace subscription is missing");
|
|
27
|
+
return subscription;
|
|
28
|
+
}
|
|
29
|
+
async function previewGuardedFreeChange(tenantId, targetPlan) {
|
|
30
|
+
const current = await readSubscription(tenantId);
|
|
31
|
+
const issues = await (0, plan_changes_1.validateGuardedPlanChange)({
|
|
32
|
+
tenantId,
|
|
33
|
+
currentPlan: current.planId
|
|
34
|
+
? ((await (0, interface_database_decorators_1.GetModel)(db_1.PlanModel).get(current.planId)) ?? null)
|
|
35
|
+
: null,
|
|
36
|
+
targetPlan,
|
|
37
|
+
operationId: (0, node_crypto_1.randomUUID)(),
|
|
38
|
+
phase: "preview",
|
|
39
|
+
effectiveAt: current.currentPeriodEnd ?? null,
|
|
40
|
+
});
|
|
41
|
+
if (issues.length)
|
|
42
|
+
throw new PlanChangeIncompatibleError(issues);
|
|
43
|
+
}
|
|
44
|
+
async function prepareFreeChange(tenantId, targetPlan) {
|
|
45
|
+
if (targetPlan.price !== 0 || targetPlan.paymentProviderRefs?.stripePriceId) {
|
|
46
|
+
throw new Error("Guarded paid-to-paid downgrades are not supported");
|
|
47
|
+
}
|
|
48
|
+
const policy = (0, plan_changes_1.getPlanChangePolicy)();
|
|
49
|
+
const model = (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId);
|
|
50
|
+
const current = await readSubscription(tenantId);
|
|
51
|
+
if (!current.stripeSubscriptionId || current.status !== "active") {
|
|
52
|
+
throw new Error("A paid active subscription is required");
|
|
53
|
+
}
|
|
54
|
+
const stripe = (0, client_1.getStripeClient)();
|
|
55
|
+
const live = await stripe.subscriptions.retrieve(current.stripeSubscriptionId);
|
|
56
|
+
const effectiveAt = (0, payload_shapes_1.readSubscriptionPeriodEnd)(live);
|
|
57
|
+
if (!effectiveAt ||
|
|
58
|
+
effectiveAt.getTime() <= Date.now() ||
|
|
59
|
+
live.status !== "active" ||
|
|
60
|
+
live.schedule ||
|
|
61
|
+
live.cancel_at_period_end) {
|
|
62
|
+
throw new Error("Existing provider state requires reconciliation before scheduling");
|
|
63
|
+
}
|
|
64
|
+
const change = {
|
|
65
|
+
operationId: (0, node_crypto_1.randomUUID)(),
|
|
66
|
+
policyName: policy.name,
|
|
67
|
+
targetPlanId: targetPlan._id,
|
|
68
|
+
stripeSubscriptionId: current.stripeSubscriptionId,
|
|
69
|
+
effectiveAt,
|
|
70
|
+
requestedAt: new Date(),
|
|
71
|
+
barrierId: (0, node_crypto_1.randomUUID)(),
|
|
72
|
+
phase: "preparing",
|
|
73
|
+
incompatibilities: [],
|
|
74
|
+
};
|
|
75
|
+
await (0, guarded_state_1.prepareGuardedPlanChange)(model, current, change);
|
|
76
|
+
return change;
|
|
77
|
+
}
|
|
78
|
+
async function scheduleGuardedFreeChange(tenantId, targetPlan) {
|
|
79
|
+
const change = await prepareFreeChange(tenantId, targetPlan);
|
|
80
|
+
const model = (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId);
|
|
81
|
+
const effectiveAt = change.effectiveAt;
|
|
82
|
+
try {
|
|
83
|
+
const drained = await (0, inventory_barrier_1.drainPlanInventory)(tenantId, model, change);
|
|
84
|
+
const issues = await (0, plan_changes_1.validateGuardedPlanChange)({
|
|
85
|
+
tenantId,
|
|
86
|
+
currentPlan: drained.planId
|
|
87
|
+
? ((await (0, interface_database_decorators_1.GetModel)(db_1.PlanModel).get(drained.planId)) ?? null)
|
|
88
|
+
: null,
|
|
89
|
+
targetPlan,
|
|
90
|
+
operationId: change.operationId,
|
|
91
|
+
phase: "schedule",
|
|
92
|
+
effectiveAt,
|
|
93
|
+
}, change.policyName);
|
|
94
|
+
if (issues.length)
|
|
95
|
+
throw new PlanChangeIncompatibleError(issues);
|
|
96
|
+
await (0, guarded_state_1.admitGuardedProviderEffect)(model, drained);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
const latest = await readSubscription(tenantId);
|
|
100
|
+
if (latest.guardedPlanChange?.operationId === change.operationId &&
|
|
101
|
+
latest.guardedPlanChange.phase === "preparing") {
|
|
102
|
+
await (0, guarded_state_1.abortGuardedPreparation)(model, latest);
|
|
103
|
+
}
|
|
104
|
+
await (0, inventory_barrier_1.releasePlanInventory)(tenantId, change);
|
|
105
|
+
const aborted = await readSubscription(tenantId);
|
|
106
|
+
if (aborted.guardedPlanChange?.operationId === change.operationId &&
|
|
107
|
+
aborted.guardedPlanChange.phase === "aborting") {
|
|
108
|
+
await (0, guarded_state_1.completeGuardedAbort)(model, aborted);
|
|
109
|
+
}
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
await (0, inventory_barrier_1.releasePlanInventory)(tenantId, change);
|
|
113
|
+
const stripe = (0, client_1.getStripeClient)();
|
|
114
|
+
await stripe.subscriptions.update(change.stripeSubscriptionId, { cancel_at_period_end: true }, {
|
|
115
|
+
idempotencyKey: `free-downgrade:schedule:${change.operationId}`,
|
|
116
|
+
});
|
|
117
|
+
const confirmed = await stripe.subscriptions.retrieve(change.stripeSubscriptionId);
|
|
118
|
+
if (!confirmed.cancel_at_period_end ||
|
|
119
|
+
confirmed.schedule ||
|
|
120
|
+
(0, payload_shapes_1.readSubscriptionPeriodEnd)(confirmed)?.getTime() !== effectiveAt.getTime()) {
|
|
121
|
+
throw new Error("Downgrade provider confirmation requires reconciliation");
|
|
122
|
+
}
|
|
123
|
+
await (0, guarded_state_1.confirmGuardedSchedule)(model, await readSubscription(tenantId));
|
|
124
|
+
return effectiveAt;
|
|
125
|
+
}
|
|
126
|
+
async function cancelGuardedFreeChange(tenantId) {
|
|
127
|
+
const model = (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId);
|
|
128
|
+
const current = await readSubscription(tenantId);
|
|
129
|
+
const change = current.guardedPlanChange;
|
|
130
|
+
if (!change)
|
|
131
|
+
return;
|
|
132
|
+
if (change.phase === "preparing" || change.phase === "aborting") {
|
|
133
|
+
if (change.phase === "preparing")
|
|
134
|
+
await (0, guarded_state_1.abortGuardedPreparation)(model, current);
|
|
135
|
+
await (0, inventory_barrier_1.releasePlanInventory)(tenantId, change);
|
|
136
|
+
await (0, guarded_state_1.completeGuardedAbort)(model, await readSubscription(tenantId));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
await (0, guarded_state_1.admitGuardedCancellation)(model, current);
|
|
140
|
+
const stripe = (0, client_1.getStripeClient)();
|
|
141
|
+
await stripe.subscriptions.update(change.stripeSubscriptionId, { cancel_at_period_end: false }, {
|
|
142
|
+
idempotencyKey: `free-downgrade:cancel:${change.operationId}`,
|
|
143
|
+
});
|
|
144
|
+
const confirmed = await stripe.subscriptions.retrieve(change.stripeSubscriptionId);
|
|
145
|
+
if (confirmed.status !== "active" ||
|
|
146
|
+
confirmed.cancel_at_period_end ||
|
|
147
|
+
confirmed.schedule) {
|
|
148
|
+
throw new Error("Downgrade cancellation requires reconciliation");
|
|
149
|
+
}
|
|
150
|
+
await (0, guarded_state_1.confirmGuardedCancellation)(model, await readSubscription(tenantId));
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=guarded-free.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
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AAC,QAAQ,EAClB,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACpE,CAAC;IACD,MAAM,IAAA,0CAA0B,EAAC,KAAK,EAAE,MAAM,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC;AAC5E,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function reconcileGuardedFreeChange(tenantId: string): Promise<boolean>;
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.reconcileGuardedFreeChange = reconcileGuardedFreeChange;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const interface_database_decorators_1 = require("@antelopejs/interface-database-decorators");
|
|
6
|
+
const db_1 = require("../db");
|
|
7
|
+
const plan_changes_1 = require("../implementations/dms-saas/plan-changes");
|
|
8
|
+
const client_1 = require("../stripe/client");
|
|
9
|
+
const billing_state_1 = require("../billing-state");
|
|
10
|
+
const lifecycle_outbox_1 = require("../operator-actions/lifecycle-outbox");
|
|
11
|
+
const notifications_1 = require("../notifications");
|
|
12
|
+
const inventory_barrier_1 = require("./inventory-barrier");
|
|
13
|
+
const guarded_state_1 = require("./guarded-state");
|
|
14
|
+
const complimentary_1 = require("../workspaces/complimentary");
|
|
15
|
+
const subscription_access_gate_1 = require("../auth/subscription-access-gate");
|
|
16
|
+
const INVENTORY_PREPARATION_MAX_MS = 30_000;
|
|
17
|
+
async function notifyBlocked(tenantId, change) {
|
|
18
|
+
await (0, lifecycle_outbox_1.dispatchWorkspaceLifecycle)({
|
|
19
|
+
tenantId,
|
|
20
|
+
operationId: `${change.operationId}:blocked`,
|
|
21
|
+
planChangeOperationId: change.operationId,
|
|
22
|
+
transition: "suspended",
|
|
23
|
+
requestedAt: new Date(change.effectiveAt),
|
|
24
|
+
});
|
|
25
|
+
await (0, notifications_1.notifyTenantOwners)(tenantId, notifications_1.workspaceSuspendedSubject, {
|
|
26
|
+
eventId: `free-downgrade:blocked:${change.operationId}`,
|
|
27
|
+
icon: "i-ph-warning",
|
|
28
|
+
title: "Free downgrade requires attention",
|
|
29
|
+
description: "The paid period ended, but Free could not be safely activated. Execution is blocked; data is retained. Resolve the reported incompatibilities before resuming.",
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
async function recordBlocked(tenantId, current, issues, preserveProviderPhase = false) {
|
|
33
|
+
const change = current.guardedPlanChange;
|
|
34
|
+
if (!change)
|
|
35
|
+
return;
|
|
36
|
+
const model = (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId);
|
|
37
|
+
const patch = {
|
|
38
|
+
guardedPlanChange: {
|
|
39
|
+
...change,
|
|
40
|
+
phase: preserveProviderPhase ? change.phase : "blocked",
|
|
41
|
+
incompatibilities: issues,
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
if (!preserveProviderPhase) {
|
|
45
|
+
patch.domainTransition = null;
|
|
46
|
+
patch.paidUsagePeriods = (0, complimentary_1.closePaidUsagePeriods)(current, new Date(change.effectiveAt));
|
|
47
|
+
}
|
|
48
|
+
const outcome = await model.mutateRevision(current, patch);
|
|
49
|
+
if (outcome !== "applied")
|
|
50
|
+
throw new Error("Downgrade incident persistence requires reconciliation");
|
|
51
|
+
await (0, billing_state_1.recomputeTenantBillingState)(tenantId);
|
|
52
|
+
}
|
|
53
|
+
async function completeFreeActivation(tenantId, current) {
|
|
54
|
+
const change = current.guardedPlanChange;
|
|
55
|
+
if (!change || change.phase !== "activating")
|
|
56
|
+
return;
|
|
57
|
+
if (!subscription_access_gate_1.BLOCKING_STATUSES.has(current.status)) {
|
|
58
|
+
await (0, lifecycle_outbox_1.dispatchWorkspaceLifecycle)({
|
|
59
|
+
tenantId,
|
|
60
|
+
operationId: `${change.operationId}:reactivate`,
|
|
61
|
+
planChangeOperationId: change.operationId,
|
|
62
|
+
transition: "reactivation_requested",
|
|
63
|
+
requestedAt: new Date(change.effectiveAt),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const outcome = await (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId).mutateRevision(current, {
|
|
67
|
+
guardedPlanChange: null,
|
|
68
|
+
pendingPlanId: null,
|
|
69
|
+
pendingPlanChangeAt: null,
|
|
70
|
+
domainTransition: null,
|
|
71
|
+
});
|
|
72
|
+
if (outcome !== "applied")
|
|
73
|
+
throw new Error("Free activation requires reconciliation");
|
|
74
|
+
await (0, billing_state_1.recomputeTenantBillingState)(tenantId);
|
|
75
|
+
}
|
|
76
|
+
async function recoverInventoryPreparation(tenantId, current, change) {
|
|
77
|
+
const model = (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId);
|
|
78
|
+
if (change.phase === "preparing") {
|
|
79
|
+
if (Date.now() - new Date(change.requestedAt).getTime() >=
|
|
80
|
+
INVENTORY_PREPARATION_MAX_MS) {
|
|
81
|
+
await (0, guarded_state_1.abortGuardedPreparation)(model, current);
|
|
82
|
+
await (0, inventory_barrier_1.releasePlanInventory)(tenantId, change);
|
|
83
|
+
const aborted = await model.findOne();
|
|
84
|
+
if (aborted?.guardedPlanChange?.operationId === change.operationId &&
|
|
85
|
+
aborted.guardedPlanChange.phase === "aborting") {
|
|
86
|
+
await (0, guarded_state_1.completeGuardedAbort)(model, aborted);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
if (change.phase === "aborting") {
|
|
92
|
+
await (0, inventory_barrier_1.releasePlanInventory)(tenantId, change);
|
|
93
|
+
await (0, guarded_state_1.completeGuardedAbort)(model, current);
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
if (change.phase === "effective") {
|
|
97
|
+
if (change.validationStartedAt &&
|
|
98
|
+
Date.now() - new Date(change.validationStartedAt).getTime() >=
|
|
99
|
+
INVENTORY_PREPARATION_MAX_MS) {
|
|
100
|
+
await recordBlocked(tenantId, current, [
|
|
101
|
+
{
|
|
102
|
+
code: "validation_interrupted",
|
|
103
|
+
message: "Inventory validation did not finish",
|
|
104
|
+
},
|
|
105
|
+
]);
|
|
106
|
+
await (0, inventory_barrier_1.releasePlanInventory)(tenantId, change);
|
|
107
|
+
await notifyBlocked(tenantId, change);
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
async function reconcileGuardedFreeChange(tenantId) {
|
|
114
|
+
const current = await (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId).findOne();
|
|
115
|
+
const change = current?.guardedPlanChange;
|
|
116
|
+
if (!current || !change)
|
|
117
|
+
return false;
|
|
118
|
+
if (await recoverInventoryPreparation(tenantId, current, change))
|
|
119
|
+
return true;
|
|
120
|
+
await (0, inventory_barrier_1.releasePlanInventory)(tenantId, change);
|
|
121
|
+
if (change.phase === "activating") {
|
|
122
|
+
await completeFreeActivation(tenantId, current);
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
if (new Date(change.effectiveAt).getTime() > Date.now())
|
|
126
|
+
return true;
|
|
127
|
+
if (!["scheduled", "blocked"].includes(change.phase)) {
|
|
128
|
+
await recordBlocked(tenantId, current, [
|
|
129
|
+
{
|
|
130
|
+
code: "billing_reconciliation_required",
|
|
131
|
+
message: "A billing or inventory operation has not settled",
|
|
132
|
+
},
|
|
133
|
+
], true);
|
|
134
|
+
await notifyBlocked(tenantId, change);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
if (change.phase === "blocked")
|
|
138
|
+
await notifyBlocked(tenantId, change);
|
|
139
|
+
try {
|
|
140
|
+
const live = await (0, client_1.getStripeClient)().subscriptions.retrieve(change.stripeSubscriptionId);
|
|
141
|
+
if (live.status !== "canceled")
|
|
142
|
+
throw new Error("Stripe has not confirmed cancellation");
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
await recordBlocked(tenantId, current, [
|
|
146
|
+
{
|
|
147
|
+
code: "provider_not_cancelled",
|
|
148
|
+
message: "Provider cancellation could not be confirmed",
|
|
149
|
+
},
|
|
150
|
+
]);
|
|
151
|
+
await notifyBlocked(tenantId, change);
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
await validateAndCommitFree(tenantId, current, change);
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
async function validateAndCommitFree(tenantId, current, change) {
|
|
158
|
+
const model = (0, interface_database_decorators_1.GetModel)(db_1.TenantSubscriptionModel, tenantId);
|
|
159
|
+
const effective = {
|
|
160
|
+
...change,
|
|
161
|
+
phase: "effective",
|
|
162
|
+
barrierId: (0, node_crypto_1.randomUUID)(),
|
|
163
|
+
validationStartedAt: new Date(),
|
|
164
|
+
};
|
|
165
|
+
if ((await model.mutateRevision(current, { guardedPlanChange: effective })) !==
|
|
166
|
+
"applied") {
|
|
167
|
+
throw new Error("Another landing attempt changed the subscription");
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const drained = await (0, inventory_barrier_1.drainPlanInventory)(tenantId, model, effective);
|
|
171
|
+
const targetPlan = await (0, interface_database_decorators_1.GetModel)(db_1.PlanModel).get(change.targetPlanId);
|
|
172
|
+
if (!targetPlan ||
|
|
173
|
+
targetPlan.price !== 0 ||
|
|
174
|
+
targetPlan.paymentProviderRefs?.stripePriceId) {
|
|
175
|
+
throw new Error("The target is no longer a Free plan");
|
|
176
|
+
}
|
|
177
|
+
const issues = await (0, plan_changes_1.validateGuardedPlanChange)({
|
|
178
|
+
tenantId,
|
|
179
|
+
currentPlan: drained.planId
|
|
180
|
+
? ((await (0, interface_database_decorators_1.GetModel)(db_1.PlanModel).get(drained.planId)) ?? null)
|
|
181
|
+
: null,
|
|
182
|
+
targetPlan,
|
|
183
|
+
operationId: change.operationId,
|
|
184
|
+
phase: "effective",
|
|
185
|
+
effectiveAt: new Date(change.effectiveAt),
|
|
186
|
+
}, change.policyName);
|
|
187
|
+
if (issues.length) {
|
|
188
|
+
await recordBlocked(tenantId, drained, issues);
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
const outcome = await model.mutateRevision(drained, {
|
|
192
|
+
planId: targetPlan._id,
|
|
193
|
+
stripeSubscriptionId: null,
|
|
194
|
+
stripeCheckoutSessionId: null,
|
|
195
|
+
paidUsagePeriods: (0, complimentary_1.closePaidUsagePeriods)(drained, new Date(change.effectiveAt)),
|
|
196
|
+
guardedPlanChange: {
|
|
197
|
+
...effective,
|
|
198
|
+
phase: "activating",
|
|
199
|
+
incompatibilities: [],
|
|
200
|
+
},
|
|
201
|
+
domainTransition: null,
|
|
202
|
+
});
|
|
203
|
+
if (outcome !== "applied")
|
|
204
|
+
throw new Error("Free landing revision changed");
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
const latest = await model.findOne();
|
|
209
|
+
if (latest?.guardedPlanChange?.barrierId === effective.barrierId &&
|
|
210
|
+
latest.guardedPlanChange.phase === "effective") {
|
|
211
|
+
await recordBlocked(tenantId, latest, [
|
|
212
|
+
{
|
|
213
|
+
code: "validation_unavailable",
|
|
214
|
+
message: error instanceof Error
|
|
215
|
+
? error.message
|
|
216
|
+
: "Inventory validation unavailable",
|
|
217
|
+
},
|
|
218
|
+
]);
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
await (0, inventory_barrier_1.releasePlanInventory)(tenantId, effective);
|
|
226
|
+
}
|
|
227
|
+
const latest = await model.findOne();
|
|
228
|
+
if (latest?.guardedPlanChange?.phase === "blocked")
|
|
229
|
+
await notifyBlocked(tenantId, latest.guardedPlanChange);
|
|
230
|
+
else if (latest)
|
|
231
|
+
await completeFreeActivation(tenantId, latest);
|
|
232
|
+
}
|
|
233
|
+
//# sourceMappingURL=guarded-landing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guar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AClE,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { GuardedPlanChange, TenantSubscription, TenantSubscriptionModel } from "../db";
|
|
2
|
+
export declare function isGuardedPlanChangeBlocked(subscription: TenantSubscription, now?: Date): boolean;
|
|
3
|
+
export declare function prepareGuardedPlanChange(model: TenantSubscriptionModel, current: TenantSubscription, change: GuardedPlanChange): Promise<void>;
|
|
4
|
+
export declare function abortGuardedPreparation(model: TenantSubscriptionModel, current: TenantSubscription): Promise<void>;
|
|
5
|
+
export declare function completeGuardedAbort(model: TenantSubscriptionModel, current: TenantSubscription): Promise<void>;
|
|
6
|
+
export declare function admitGuardedProviderEffect(model: TenantSubscriptionModel, current: TenantSubscription): Promise<void>;
|
|
7
|
+
export declare function confirmGuardedSchedule(model: TenantSubscriptionModel, current: TenantSubscription): Promise<void>;
|
|
8
|
+
export declare function admitGuardedCancellation(model: TenantSubscriptionModel, current: TenantSubscription): Promise<void>;
|
|
9
|
+
export declare function confirmGuardedCancellation(model: TenantSubscriptionModel, current: TenantSubscription): Promise<void>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isGuardedPlanChangeBlocked = isGuardedPlanChangeBlocked;
|
|
4
|
+
exports.prepareGuardedPlanChange = prepareGuardedPlanChange;
|
|
5
|
+
exports.abortGuardedPreparation = abortGuardedPreparation;
|
|
6
|
+
exports.completeGuardedAbort = completeGuardedAbort;
|
|
7
|
+
exports.admitGuardedProviderEffect = admitGuardedProviderEffect;
|
|
8
|
+
exports.confirmGuardedSchedule = confirmGuardedSchedule;
|
|
9
|
+
exports.admitGuardedCancellation = admitGuardedCancellation;
|
|
10
|
+
exports.confirmGuardedCancellation = confirmGuardedCancellation;
|
|
11
|
+
function isGuardedPlanChangeBlocked(subscription, now = new Date()) {
|
|
12
|
+
const change = subscription.guardedPlanChange;
|
|
13
|
+
if (!change)
|
|
14
|
+
return false;
|
|
15
|
+
if (change.phase === "aborting")
|
|
16
|
+
return false;
|
|
17
|
+
return (change.phase === "blocked" ||
|
|
18
|
+
new Date(change.effectiveAt).getTime() <= now.getTime());
|
|
19
|
+
}
|
|
20
|
+
async function compareAndSet(model, current, patch) {
|
|
21
|
+
if (current.deletionStartedAt)
|
|
22
|
+
throw new Error("Subscription deletion has started");
|
|
23
|
+
if ((await model.mutateRevision(current, patch)) !== "applied") {
|
|
24
|
+
throw new Error("Plan change revision changed; reload without replaying provider effects");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
async function prepareGuardedPlanChange(model, current, change) {
|
|
28
|
+
if (current.domainTransition ||
|
|
29
|
+
current.guardedPlanChange ||
|
|
30
|
+
current.pendingPlanId) {
|
|
31
|
+
throw new Error("An existing plan transition requires reconciliation");
|
|
32
|
+
}
|
|
33
|
+
if (change.phase !== "preparing" ||
|
|
34
|
+
current.stripeSubscriptionId !== change.stripeSubscriptionId) {
|
|
35
|
+
throw new Error("Invalid downgrade preparation");
|
|
36
|
+
}
|
|
37
|
+
await compareAndSet(model, current, {
|
|
38
|
+
guardedPlanChange: change,
|
|
39
|
+
pendingPlanId: change.targetPlanId,
|
|
40
|
+
pendingPlanChangeAt: change.effectiveAt,
|
|
41
|
+
domainTransition: {
|
|
42
|
+
operationId: change.operationId,
|
|
43
|
+
kind: "change_plan",
|
|
44
|
+
targetPlanId: change.targetPlanId,
|
|
45
|
+
requestedAt: change.requestedAt,
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
async function abortGuardedPreparation(model, current) {
|
|
50
|
+
const change = requirePhase(current, "preparing");
|
|
51
|
+
await compareAndSet(model, current, {
|
|
52
|
+
guardedPlanChange: { ...change, phase: "aborting" },
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
async function completeGuardedAbort(model, current) {
|
|
56
|
+
requirePhase(current, "aborting");
|
|
57
|
+
await compareAndSet(model, current, {
|
|
58
|
+
guardedPlanChange: null,
|
|
59
|
+
pendingPlanId: null,
|
|
60
|
+
pendingPlanChangeAt: null,
|
|
61
|
+
domainTransition: null,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function requirePhase(current, phase) {
|
|
65
|
+
const change = current.guardedPlanChange;
|
|
66
|
+
if (!change || change.phase !== phase)
|
|
67
|
+
throw new Error(`Expected downgrade phase ${phase}`);
|
|
68
|
+
if (current.domainTransition &&
|
|
69
|
+
current.domainTransition.operationId !== change.operationId) {
|
|
70
|
+
throw new Error("Another billing intent owns the subscription");
|
|
71
|
+
}
|
|
72
|
+
return change;
|
|
73
|
+
}
|
|
74
|
+
async function admitGuardedProviderEffect(model, current) {
|
|
75
|
+
const change = requirePhase(current, "preparing");
|
|
76
|
+
await compareAndSet(model, current, {
|
|
77
|
+
guardedPlanChange: { ...change, phase: "provider_pending" },
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
async function confirmGuardedSchedule(model, current) {
|
|
81
|
+
const change = requirePhase(current, "provider_pending");
|
|
82
|
+
await compareAndSet(model, current, {
|
|
83
|
+
guardedPlanChange: { ...change, phase: "scheduled" },
|
|
84
|
+
domainTransition: null,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
async function admitGuardedCancellation(model, current) {
|
|
88
|
+
const change = requirePhase(current, "scheduled");
|
|
89
|
+
if (isGuardedPlanChangeBlocked(current))
|
|
90
|
+
throw new Error("The downgrade deadline has passed");
|
|
91
|
+
await compareAndSet(model, current, {
|
|
92
|
+
guardedPlanChange: { ...change, phase: "cancel_pending" },
|
|
93
|
+
domainTransition: {
|
|
94
|
+
operationId: change.operationId,
|
|
95
|
+
kind: "change_plan",
|
|
96
|
+
targetPlanId: null,
|
|
97
|
+
requestedAt: change.requestedAt,
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
async function confirmGuardedCancellation(model, current) {
|
|
102
|
+
requirePhase(current, "cancel_pending");
|
|
103
|
+
await compareAndSet(model, current, {
|
|
104
|
+
guardedPlanChange: null,
|
|
105
|
+
pendingPlanId: null,
|
|
106
|
+
pendingPlanChangeAt: null,
|
|
107
|
+
domainTransition: null,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=guarded-state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guarded-state.js","sourceRoot":"","sources":["../../src/plan-changes/guarded-state.ts"],"names":[],"mappings":";;AAOA,gEAWC;AAiBD,4DA6BC;AAMD,0DAQC;AAGD,oDAWC;AAmBD,gEAQC;AAGD,wDASC;AAGD,4DAgBC;AAGD,gEAWC;AA7JD,SAAgB,0BAA0B,CACxC,YAAgC,EAChC,GAAG,GAAG,IAAI,IAAI,EAAE;IAEhB,MAAM,MAAM,GAAG,YAAY,CAAC,iBAAiB,CAAC;IAC9C,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC1B,IAAI,MAAM,CAAC,KAAK,KAAK,UAAU;QAAE,OAAO,KAAK,CAAC;IAC9C,OAAO,CACL,MAAM,CAAC,KAAK,KAAK,SAAS;QAC1B,IAAI,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,OAAO,EAAE,IAAI,GAAG,CAAC,OAAO,EAAE,CACxD,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,aAAa,CAC1B,KAA8B,EAC9B,OAA2B,EAC3B,KAAkC;IAElC,IAAI,OAAO,CAAC,iBAAiB;QAC3B,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,IAAI,CAAC,MAAM,KAAK,CAAC,cAAc,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,KAAK,SAAS,EAAE,CAAC;QAC/D,MAAM,IAAI,KAAK,CACb,yEAAyE,CAC1E,CAAC;IACJ,CAAC;AACH,CAAC;AAGM,KAAK,UAAU,wBAAwB,CAC5C,KAA8B,EAC9B,OAA2B,EAC3B,MAAyB;IAEzB,IACE,OAAO,CAAC,gBAAg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G,MAAM,EAAE,KAAK,EAAE,gBAAgB,EAAE;QACzD,gBAAgB,EAAE;YAChB,WAAW,EAAE,MAAM,CAAC,WAAW;YAC/B,IAAI,EAAE,aAAa;YACnB,YAAY,EAAE,IAAI;YAClB,WAAW,EAAE,MAAM,CAAC,WAAW;SAChC;KACF,CAAC,CAAC;AACL,CAAC;AAGM,KAAK,UAAU,0BAA0B,CAC9C,KAA8B,EAC9B,OAA2B;IAE3B,YAAY,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;IACxC,MAAM,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE;QAClC,iBAAiB,EAAE,IAAI;QACvB,aAAa,EAAE,IAAI;QACnB,mBAAmB,EAAE,IAAI;QACzB,gBAAgB,EAAE,IAAI;KACvB,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { GuardedPlanChange, TenantSubscription, TenantSubscriptionModel } from "../db";
|
|
2
|
+
export declare function drainPlanInventory(tenantId: string, model: TenantSubscriptionModel, change: GuardedPlanChange): Promise<TenantSubscription>;
|
|
3
|
+
export declare function releasePlanInventory(tenantId: string, change: GuardedPlanChange): Promise<void>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.drainPlanInventory = drainPlanInventory;
|
|
4
|
+
exports.releasePlanInventory = releasePlanInventory;
|
|
5
|
+
const promises_1 = require("node:timers/promises");
|
|
6
|
+
const tenant_lifecycle_1 = require("@antelopejs/interface-dms/tenant-lifecycle");
|
|
7
|
+
const DRAIN_WAIT_MS = 2000;
|
|
8
|
+
const DRAIN_POLL_MS = 50;
|
|
9
|
+
async function drainPlanInventory(tenantId, model, change) {
|
|
10
|
+
const deadline = Date.now() + DRAIN_WAIT_MS;
|
|
11
|
+
while (Date.now() <= deadline) {
|
|
12
|
+
const inventory = await (0, tenant_lifecycle_1.observeTenantLifecycle)(tenantId);
|
|
13
|
+
const current = await model.findOne();
|
|
14
|
+
if (!current ||
|
|
15
|
+
current.guardedPlanChange?.barrierId !== change.barrierId ||
|
|
16
|
+
current.guardedPlanChange.phase !== change.phase) {
|
|
17
|
+
throw new Error("Inventory preparation is no longer current");
|
|
18
|
+
}
|
|
19
|
+
if (inventory.closed)
|
|
20
|
+
throw new Error("Tenant deletion has closed inventory admission");
|
|
21
|
+
if (inventory.barrierId === change.barrierId) {
|
|
22
|
+
if (inventory.activeAttemptIds.length === 0)
|
|
23
|
+
return current;
|
|
24
|
+
}
|
|
25
|
+
else if (inventory.barrierId) {
|
|
26
|
+
throw new Error("Another inventory preparation is active");
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
await (0, tenant_lifecycle_1.pauseTenantLifecycleAdmission)(tenantId, change.barrierId, inventory.revision);
|
|
30
|
+
}
|
|
31
|
+
await (0, promises_1.setTimeout)(DRAIN_POLL_MS);
|
|
32
|
+
}
|
|
33
|
+
throw new Error("Inventory writers have not drained; retry after they finish");
|
|
34
|
+
}
|
|
35
|
+
async function releasePlanInventory(tenantId, change) {
|
|
36
|
+
await (0, tenant_lifecycle_1.resumeTenantLifecycleAdmission)(tenantId, change.barrierId);
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=inventory-barrier.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inventory-barrier.js","sourceRoot":"","sources":["../../src/plan-changes/inventory-barrier.ts"],"names":[],"mappings":";;AAgBA,gDAoCC;AAGD,oDAKC;AA5DD,mDAA2D;AAC3D,iFAIoD;AAOpD,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,aAAa,GAAG,EAAE,CAAC;AAGlB,KAAK,UAAU,kBAAkB,CACtC,QAAgB,EAChB,KAA8B,EAC9B,MAAyB;IAEzB,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,aAAa,CAAC;IAC5C,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,QAAQ,EAAE,CAAC;QAG9B,MAAM,SAAS,GAAG,MAAM,IAAA,yCAAsB,EAAC,QAAQ,CAAC,CAAC;QACzD,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE,CAAC;QACtC,IACE,CAAC,OAAO;YACR,OAAO,CAAC,iBAAiB,EAAE,SAAS,KAAK,MAAM,CAAC,SAAS;YACzD,OAAO,CAAC,iBAAiB,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,EAChD,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAChE,CAAC;QACD,IAAI,SAAS,CAAC,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACpE,IAAI,SAAS,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,EAAE,CAAC;YAC7C,IAAI,SAAS,CAAC,gBAAgB,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,OAAO,CAAC;QAC9D,CAAC;aAAM,IAAI,SAAS,CAAC,SAAS,EAAE,CAAC;YAC/B,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;QAC7D,CAAC;aAAM,CAAC;YACN,MAAM,IAAA,gDAA6B,EACjC,QAAQ,EACR,MAAM,CAAC,SAAS,EAChB,SAAS,CAAC,QAAQ,CACnB,CAAC;QACJ,CAAC;QACD,MAAM,IAAA,qBAAK,EAAC,aAAa,CAAC,CAAC;IAC7B,CAAC;IACD,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;AACJ,CAAC;AAGM,KAAK,UAAU,oBAAoB,CACxC,QAAgB,EAChB,MAAyB;IAEzB,MAAM,IAAA,iDAA8B,EAAC,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;AACnE,CAAC"}
|
package/dist/plans/seat-hooks.js
CHANGED
|
@@ -6,7 +6,9 @@ const interface_api_util_1 = require("@antelopejs/interface-api-util");
|
|
|
6
6
|
const interface_database_decorators_1 = require("@antelopejs/interface-database-decorators");
|
|
7
7
|
const hooks_1 = require("@antelopejs/interface-dms/hooks");
|
|
8
8
|
const invite_extensions_1 = require("@antelopejs/interface-dms/invite-extensions");
|
|
9
|
-
const db_1 = require("
|
|
9
|
+
const db_1 = require("@antelopejs/interface-dms/auth/db");
|
|
10
|
+
const db_2 = require("../db");
|
|
11
|
+
const plan_changes_1 = require("../implementations/dms-saas/plan-changes");
|
|
10
12
|
const platform_support_1 = require("./platform-support");
|
|
11
13
|
const seat_capacity_1 = require("./seat-capacity");
|
|
12
14
|
const seat_sync_1 = require("./seat-sync");
|
|
@@ -19,8 +21,8 @@ const REISSUED_INVITE_REASONS = new Set([
|
|
|
19
21
|
"replaced",
|
|
20
22
|
]);
|
|
21
23
|
async function getActivePlanForTenant(tenantId) {
|
|
22
|
-
const tenantSubscriptionModel = (0, interface_database_decorators_1.GetModel)(
|
|
23
|
-
const planModel = (0, interface_database_decorators_1.GetModel)(
|
|
24
|
+
const tenantSubscriptionModel = (0, interface_database_decorators_1.GetModel)(db_2.TenantSubscriptionModel, tenantId);
|
|
25
|
+
const planModel = (0, interface_database_decorators_1.GetModel)(db_2.PlanModel);
|
|
24
26
|
const subscription = await tenantSubscriptionModel.findOne();
|
|
25
27
|
if (!subscription?.planId)
|
|
26
28
|
return null;
|
|
@@ -35,6 +37,11 @@ async function enforceSeatCapacity(tenantId, releasedInviteeEmail) {
|
|
|
35
37
|
return;
|
|
36
38
|
const occupied = await (0, seat_capacity_1.countOccupiedSeats)(tenantId, releasedInviteeEmail);
|
|
37
39
|
(0, interface_api_util_1.assert)((0, seat_capacity_1.hasSeatCapacity)(active.plan.maxMembers, occupied), HTTP_PAYMENT_REQUIRED, "saas.errors.plan.seat_limit_reached");
|
|
40
|
+
const constraints = await (0, plan_changes_1.GetTenantPlanConstraints)(tenantId);
|
|
41
|
+
(0, interface_api_util_1.assert)(!constraints.admissionBlocked, 409, "Inventory preparation is in progress");
|
|
42
|
+
if (constraints.pendingPlan) {
|
|
43
|
+
(0, interface_api_util_1.assert)((0, seat_capacity_1.hasSeatCapacity)(constraints.pendingPlan.maxMembers, occupied), HTTP_PAYMENT_REQUIRED, "saas.errors.plan.seat_limit_reached");
|
|
44
|
+
}
|
|
38
45
|
}
|
|
39
46
|
async function resolveInviteSeatAvailability({ tenantId, }) {
|
|
40
47
|
const active = await getActivePlanForTenant(tenantId);
|
|
@@ -78,6 +85,24 @@ async function syncSeatsAfterRemoval(tenantId, removedUserIds, idempotencyKey) {
|
|
|
78
85
|
}
|
|
79
86
|
function registerSeatHooks() {
|
|
80
87
|
(0, invite_extensions_1.RegisterInviteAvailability)(resolveInviteSeatAvailability);
|
|
88
|
+
(0, hooks_1.RegisterHook)(hooks_1.Hook.MEMBER_BEING_CHANGED, async ({ tenantId, userId, isTenantOwner, previousIsTenantOwner, deliveryId, }) => {
|
|
89
|
+
const constraints = await (0, plan_changes_1.GetTenantPlanConstraints)(tenantId);
|
|
90
|
+
(0, interface_api_util_1.assert)(!constraints.admissionBlocked, 409, "Inventory preparation is in progress");
|
|
91
|
+
const nextHoldsSeat = !(await (0, platform_support_1.isPlatformSupportEntry)(userId, isTenantOwner));
|
|
92
|
+
const heldSeat = previousIsTenantOwner !== null &&
|
|
93
|
+
!(await (0, platform_support_1.isPlatformSupportEntry)(userId, previousIsTenantOwner));
|
|
94
|
+
if (!nextHoldsSeat || heldSeat)
|
|
95
|
+
return undefined;
|
|
96
|
+
const user = deliveryId
|
|
97
|
+
? await (0, interface_database_decorators_1.GetModel)(db_1.UserModel).get(userId)
|
|
98
|
+
: undefined;
|
|
99
|
+
const occupied = await (0, seat_capacity_1.countOccupiedSeats)(tenantId, user?.email);
|
|
100
|
+
for (const plan of [constraints.currentPlan, constraints.pendingPlan]) {
|
|
101
|
+
if (plan)
|
|
102
|
+
(0, interface_api_util_1.assert)((0, seat_capacity_1.fitsWithinSeatLimit)(plan.maxMembers, occupied + 1), HTTP_PAYMENT_REQUIRED, "saas.errors.plan.seat_limit_reached");
|
|
103
|
+
}
|
|
104
|
+
return undefined;
|
|
105
|
+
});
|
|
81
106
|
(0, hooks_1.RegisterHook)(hooks_1.Hook.MEMBER_BEING_ADDED, async ({ tenantId, userId, isTenantOwner, deliveryId }) => {
|
|
82
107
|
if (deliveryId)
|
|
83
108
|
return undefined;
|