import { beforeEach, describe, expect, it, vi } from "vitest"; import { applyLagoSubscriptionSync, applyMolliePaymentSync, BILLING_SYNC_IDEMPOTENCY_SCOPE, normalizeLagoSubscriptionStatus, normalizeMolliePaymentStatus, resolveLagoSubscriptionProductKind, type ApplyMolliePaymentSyncInput, type BillingSyncClient, } from "./billing-sync.server.js"; type FakeState = { inactiveTenantIds: Set; idempotency: Map; subscriptions: Map>; products: Array<{ id: string; code?: string | null; lagoPlanCode?: string | null; kind?: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override"; }>; tenantProducts: Array & { id: string }>; tenantPrices: Array & { id: string }>; acquisitions: Map & { id: string }>; checkoutSessions: Map & { id: string }>; portalClaims: Map & { id: string }>; portalDomains: Map & { id: string }>; outboxEvents: Array & { id: string }>; queries: Array<{ sql: string; values: unknown[] }>; sequence: string[]; auditEvents: unknown[]; activities: unknown[]; }; type IdempotencyFindUniqueArgs = Parameters[0]; type IdempotencyCreateArgs = Parameters[0]; type AuditCreateArgs = Parameters[0]; type ActivityCreateArgs = Parameters[0]; type TenantSubscriptionUpsertArgs = Parameters[0]; type TenantSubscriptionFindUniqueArgs = Parameters[0]; type SubscriptionProductFindFirstArgs = Parameters[0]; type TenantSubscriptionProductFindFirstArgs = Parameters[0]; type TenantSubscriptionProductCreateArgs = Parameters[0]; type TenantSubscriptionProductUpdateArgs = Parameters[0]; type TenantSubscriptionProductUpdateManyArgs = Parameters[0]; type TenantSubscriptionProductPriceDeleteManyArgs = Parameters[0]; type TenantSubscriptionProductPriceCreateArgs = Parameters[0]; type TenantProductAcquisitionFindFirstArgs = Parameters[0]; type TenantProductAcquisitionFindUniqueArgs = Parameters[0]; type TenantProductAcquisitionUpdateArgs = Parameters[0]; type TenantProductAcquisitionUpdateManyArgs = Parameters[0]; type CheckoutSessionStatusUpdateManyArgs = Parameters[0]; function createFakeClient(state: Partial = {}): BillingSyncClient { const fake: FakeState = { idempotency: state.idempotency ?? new Map(), subscriptions: state.subscriptions ?? new Map(), products: state.products ?? [], tenantProducts: state.tenantProducts ?? [], tenantPrices: state.tenantPrices ?? [], acquisitions: new Map( [...(state.acquisitions ?? new Map())].map(([id, row]) => [ id, { createdAt: new Date("2026-07-16T10:00:00.000Z"), providerStartedAt: new Date("2026-07-16T10:00:00.000Z"), providerAttempt: 1, providerPaymentId: null, providerPaymentExpiresAt: null, providerPaidAt: null, reservationExpiresAt: new Date("2026-08-01T10:00:00.000Z"), ...row, }, ]) ), checkoutSessions: state.checkoutSessions ?? new Map(), portalClaims: state.portalClaims ?? new Map(), portalDomains: state.portalDomains ?? new Map(), outboxEvents: state.outboxEvents ?? [], queries: state.queries ?? [], sequence: state.sequence ?? [], auditEvents: state.auditEvents ?? [], activities: state.activities ?? [], inactiveTenantIds: state.inactiveTenantIds ?? new Set(), }; let client: BillingSyncClient; client = { async $transaction(callback: (transaction: BillingSyncClient) => Promise) { return callback(client); }, async $queryRaw(strings: TemplateStringsArray, ...values: unknown[]) { const sql = strings.join("?"); fake.queries.push({ sql, values }); if (sql.includes("pg_advisory_xact_lock")) fake.sequence.push(`advisory:${String(values[1])}`); if (sql.includes('FROM "PortalCustomDomain"')) fake.sequence.push(`domain-lock:${String(values[1])}`); if (sql.includes('FROM "PortalDomainHostnameClaim"')) fake.sequence.push(`claim-lock:${String(values[1])}`); return []; }, idempotencyKey: { async findUnique({ where }: IdempotencyFindUniqueArgs) { const unique = where.idempotency_key_partition_scope_key; const row = fake.idempotency.get(`${unique.partitionKey}:${unique.scope}:${unique.key}`); return row ? ({ id: "idem_1", createdAt: new Date("2026-07-04T00:00:00.000Z"), updatedAt: new Date("2026-07-04T00:00:00.000Z"), expiresAt: null, tenantId: unique.partitionKey.startsWith("tenant:") ? unique.partitionKey.slice("tenant:".length) : null, partitionKey: unique.partitionKey, systemOwned: unique.partitionKey === "system", scope: unique.scope, key: unique.key, requestHash: "hash", responseStatus: 200, responseBody: row.responseBody, responseHeaders: null, } as never) : null; }, async create({ data }: IdempotencyCreateArgs) { fake.idempotency.set(`${data.partitionKey}:${data.scope}:${data.key}`, { responseBody: data.responseBody }); return { id: `idem_${fake.idempotency.size}`, createdAt: new Date(), updatedAt: new Date(), ...data } as never; }, }, auditEvent: { async findFirst() { return null; }, async create({ data }: AuditCreateArgs) { fake.auditEvents.push(data); return { ...data } as never; }, }, activity: { async create({ data }: ActivityCreateArgs) { fake.activities.push(data); return { id: `activity_${fake.activities.length}` }; }, }, tenant: { async findUnique({ where }: { where: { id: string }; select: { active: true } }) { return { active: !fake.inactiveTenantIds.has(where.id) }; }, }, tenantSubscription: { async findUnique({ where }: TenantSubscriptionFindUniqueArgs) { const subscription = fake.subscriptions.get(where.tenantId); return subscription ? ({ frozenAt: null, cancelledAt: null, ...subscription } as never) : null; }, async upsert({ where, create, update }: TenantSubscriptionUpsertArgs) { fake.sequence.push("subscription-upsert"); const current = fake.subscriptions.get(where.tenantId); const next = { ...(current ?? { id: `sub_${fake.subscriptions.size + 1}` }), ...(current ? update : create), tenantId: where.tenantId }; fake.subscriptions.set(where.tenantId, next); return next as never; }, }, subscriptionProduct: { async findFirst({ where }: SubscriptionProductFindFirstArgs) { const product = fake.products.find((candidate) => where.OR.some( (condition) => (condition.id !== undefined && condition.id === candidate.id) || (condition.code !== undefined && condition.code === candidate.code) || (condition.lagoPlanCode !== undefined && condition.lagoPlanCode === candidate.lagoPlanCode) ) ); return product ? { ...product, kind: product.kind ?? "base_plan" } : null; }, }, tenantSubscriptionProduct: { async findFirst({ where }: TenantSubscriptionProductFindFirstArgs) { return ( fake.tenantProducts.find( (product) => product.tenantSubscriptionId === where.tenantSubscriptionId && where.OR.some( (condition) => (condition.id !== undefined && condition.id === product.id) || (condition.lagoSubscriptionId !== undefined && condition.lagoSubscriptionId === product.lagoSubscriptionId) || (condition.billingProviderSubscriptionId !== undefined && condition.billingProviderSubscriptionId === product.billingProviderSubscriptionId) || (condition.subscriptionProductId !== undefined && condition.subscriptionProductId === product.subscriptionProductId) || (condition.planCode !== undefined && condition.planCode === product.planCode) ) ) ?? null ); }, async findMany({ where }: Parameters[0]) { return fake.tenantProducts .filter((product) => product.tenantSubscriptionId === where.tenantSubscriptionId && product.cancelledAt == null) .filter( (product) => (fake.products.find((candidate) => candidate.id === product.subscriptionProductId)?.kind ?? "base_plan") === where.subscriptionProduct.kind ) .map((product) => ({ id: String(product.id), subscriptionProductId: String(product.subscriptionProductId), billingProviderSubscriptionId: typeof product.billingProviderSubscriptionId === "string" ? product.billingProviderSubscriptionId : null, lagoSubscriptionId: typeof product.lagoSubscriptionId === "string" ? product.lagoSubscriptionId : null, endsAt: product.endsAt instanceof Date ? product.endsAt : null, subscriptionProduct: { code: fake.products.find((candidate) => candidate.id === product.subscriptionProductId)?.code ?? null, }, })); }, async create({ data }: TenantSubscriptionProductCreateArgs) { const row = { id: `tenant_product_${fake.tenantProducts.length + 1}`, ...data }; fake.tenantProducts.push(row); return row; }, async update({ where, data }: TenantSubscriptionProductUpdateArgs) { const index = fake.tenantProducts.findIndex((row) => row.id === where.id); fake.tenantProducts[index] = { ...fake.tenantProducts[index], ...data }; return fake.tenantProducts[index]; }, async updateMany({ where, data }: TenantSubscriptionProductUpdateManyArgs) { const now = new Date(); let count = 0; for (let index = 0; index < fake.tenantProducts.length; index += 1) { const row = fake.tenantProducts[index]; if (where.tenantSubscriptionId !== undefined && row.tenantSubscriptionId !== where.tenantSubscriptionId) continue; if (typeof where.id === "string" && row.id !== where.id) continue; const requiredKind = (where.subscriptionProduct as { kind?: string } | undefined)?.kind; const rowKind = fake.products.find((product) => product.id === row.subscriptionProductId)?.kind ?? "base_plan"; if (requiredKind && rowKind !== requiredKind) continue; const idCondition = where.id as { not?: string } | undefined; if (idCondition?.not && row.id === idCondition.not) continue; if (row.cancelledAt !== null && row.cancelledAt !== undefined) continue; const endsAt = row.endsAt instanceof Date ? row.endsAt : row.endsAt ? new Date(String(row.endsAt)) : null; if (endsAt && endsAt <= now) continue; fake.tenantProducts[index] = { ...row, ...data }; count += 1; } return { count }; }, }, tenantSubscriptionProductPrice: { async deleteMany({ where }: TenantSubscriptionProductPriceDeleteManyArgs) { const before = fake.tenantPrices.length; fake.tenantPrices = fake.tenantPrices.filter( (row) => row.tenantSubscriptionProductId !== where.tenantSubscriptionProductId || row.isMetered !== where.isMetered ); return { count: before - fake.tenantPrices.length }; }, async create({ data }: TenantSubscriptionProductPriceCreateArgs) { const row = { id: `tenant_price_${fake.tenantPrices.length + 1}`, ...data }; fake.tenantPrices.push(row); return row; }, }, tenantProductAcquisition: { async findFirst({ where }: TenantProductAcquisitionFindFirstArgs) { const row = fake.acquisitions.get(where.id); return row?.tenantId === where.tenantId ? (row as never) : null; }, async findUnique({ where }: TenantProductAcquisitionFindUniqueArgs) { return (fake.acquisitions.get(where.id) as never) ?? null; }, async update({ where, data }: TenantProductAcquisitionUpdateArgs) { fake.sequence.push("acquisition-update"); const row = fake.acquisitions.get(where.id); if (!row) throw new Error("missing acquisition"); const next = applyFakeData(row, data); fake.acquisitions.set(where.id, next); return next as never; }, async updateMany({ where, data }: TenantProductAcquisitionUpdateManyArgs) { fake.sequence.push("acquisition-update-many"); let count = 0; for (const [id, row] of fake.acquisitions) { if (!matchesFlatWhere(row, where)) continue; fake.acquisitions.set(id, applyFakeData(row, data)); count += 1; } return { count }; }, async findMany(args: { where?: Record }) { return [...fake.acquisitions.values()] .filter((row) => !args.where?.tenantId || row.tenantId === args.where.tenantId) .filter((row) => !args.where?.status || row.status === args.where.status) .filter((row) => { const id = args.where?.id as { not?: string } | undefined; return !id?.not || row.id !== id.not; }) .map((row) => ({ id: row.id, tenantSubscriptionProductId: row.tenantSubscriptionProductId ?? null, lagoSubscriptionId: row.lagoSubscriptionId ?? null, providerPaymentId: row.providerPaymentId ?? null, invoiceExternalId: row.invoiceExternalId ?? null, providerAttempt: Number(row.providerAttempt ?? 1), version: Number(row.version ?? 0), scopeKey: String(row.scopeKey), quantity: Number(row.quantity ?? 1), cancelledAt: row.cancelledAt ?? null, expiredAt: row.expiredAt ?? null, refundedAt: row.refundedAt ?? null, subscriptionProduct: { code: fake.products.find((product) => product.id === row.subscriptionProductId)?.code ?? null, }, })); }, }, checkoutSessionStatus: { async updateMany({ where, data }: CheckoutSessionStatusUpdateManyArgs) { let count = 0; for (const [id, row] of fake.checkoutSessions) { if (!matchesFlatWhere(row, where)) continue; fake.checkoutSessions.set(id, applyFakeData(row, data)); count += 1; } return { count }; }, }, portalDomainHostnameClaim: { async findMany(args: { where?: Record }) { return [...fake.portalClaims.values()] .filter((claim) => matchesPortalClaim(claim, args.where ?? {}, fake)) .sort((left, right) => left.id.localeCompare(right.id)) .map((claim) => ({ id: claim.id })); }, async findFirst(args: { where?: Record }) { const claim = [...fake.portalClaims.values()].find((candidate) => matchesFlatWhere(candidate, args.where ?? {})); if (!claim) return null; const domain = [...fake.portalDomains.values()].find((candidate) => candidate.claimId === claim.id) ?? null; return { ...claim, customDomain: domain }; }, async updateMany(args: { where?: Record; data?: Record }) { fake.sequence.push("claim-cas"); let count = 0; for (const [id, claim] of fake.portalClaims) { if (!matchesFlatWhere(claim, args.where ?? {})) continue; fake.portalClaims.set(id, applyFakeData(claim, args.data ?? {})); count += 1; } return { count }; }, }, portalCustomDomain: { async updateMany(args: { where?: Record; data?: Record }) { fake.sequence.push("domain-cas"); let count = 0; for (const [id, domain] of fake.portalDomains) { if (!matchesFlatWhere(domain, args.where ?? {})) continue; fake.portalDomains.set(id, applyFakeData(domain, args.data ?? {})); count += 1; } return { count }; }, }, outboxEvent: { async create({ data }: { data: Record }) { fake.sequence.push(`outbox:${String(data.eventType)}`); const event = { id: `outbox_${fake.outboxEvents.length + 1}`, ...data }; fake.outboxEvents.push(event); return event as never; }, async findUnique({ where }: { where: { dispatchKey: string } }) { return (fake.outboxEvents.find((event) => event.dispatchKey === where.dispatchKey) as never) ?? null; }, }, __state: fake, } as unknown as BillingSyncClient; return client; } function applyFakeData(row: Record & { id: string }, data: Record): Record & { id: string } { const next = { ...row }; for (const [key, value] of Object.entries(data)) { next[key] = value && typeof value === "object" && "increment" in value ? Number(next[key] ?? 0) + Number(value.increment) : value; } return next; } function matchesFlatWhere(row: Record, where: Record): boolean { return Object.entries(where).every(([key, value]) => { if (key === "customDomain") return true; if (key === "OR" && Array.isArray(value)) { return value.some((condition) => matchesFlatWhere(row, condition as Record)); } if (value && typeof value === "object" && "in" in value) return (value.in as unknown[]).includes(row[key]); if (value === null) return row[key] == null; return row[key] === value; }); } function matchesPortalClaim(row: Record, where: Record, state: FakeState): boolean { const { OR, ...baseWhere } = where; if (!matchesFlatWhere(row, baseWhere)) return false; if ( Array.isArray(OR) && !OR.some((condition) => { const candidate = condition as Record; const relation = (candidate.customDomain as { is?: Record } | undefined)?.is; if (relation) { const domain = [...state.portalDomains.values()].find((item) => item.claimId === row.id); return Boolean(domain && matchesFlatWhere(domain, relation)); } return matchesFlatWhere(row, candidate); }) ) { return false; } const customDomainWhere = (where.customDomain as { is?: Record } | undefined)?.is; if (!customDomainWhere) return true; const domain = [...state.portalDomains.values()].find((candidate) => candidate.claimId === row.id); return Boolean(domain && matchesFlatWhere(domain, customDomainWhere)); } function createPortalDomainState(overrides: Record = {}): { claim: Record & { id: string }; domain: Record & { id: string }; } { const deprovisioningStartedAt = new Date("2026-07-17T09:00:00.000Z"); const claim = { id: "claim_1", tenantId: "tenant_1", portalId: "portal_1", hostname: "portal.saas-ctrl.com", generation: 2, billingScopeKey: "portal-domain:claim_1", releasedAt: null, cooldownUntil: null, }; const domain = { id: "domain_1", tenantId: "tenant_1", portalId: "portal_1", claimId: "claim_1", generation: 2, status: "deprovisioning", activeOrigin: null, entitlementValidatedAt: new Date("2026-07-17T08:00:00.000Z"), paymentAcquisitionId: null, controllerCommandId: "command_2", controllerContentHash: "content_2", controllerResultContentHash: null, controllerResultAttempt: 0, controllerResultStatus: null, lastHealthAckAt: null, provisionedAt: new Date("2026-07-16T08:00:00.000Z"), nextRevalidationAt: null, firstFailureAt: null, lastFailureAt: null, failureCount: 0, lastFailureCode: null, nextRetryAt: null, tlsObservedAt: null, certificateExpiresAt: null, disabledAt: deprovisioningStartedAt, disabledReason: "entitlement_lost", deprovisioningStartedAt, deprovisionedAt: null, killSwitchEnabled: false, killSwitchReason: null, cooldownUntil: null, releasedAt: null, ...overrides, }; return { claim, domain }; } function getFakeState(client: BillingSyncClient): FakeState { return (client as unknown as { __state: FakeState }).__state; } function serializeFakeAcquisitionTransactions(client: BillingSyncClient): { readonly client: BillingSyncClient; readonly firstAcquisitionRead: Promise; readonly secondLockAttempt: Promise; readonly resumeFirst: () => void; readonly lockAttempts: () => number; } { type TransactionClient = BillingSyncClient & { $queryRaw(strings: TemplateStringsArray, ...values: unknown[]): Promise; }; const base = client as TransactionClient; let transactionNumber = 0; let lockAttempts = 0; let lockTail = Promise.resolve(); let resolveFirstRead!: () => void; let resolveSecondLockAttempt!: () => void; let resolveResumeFirst!: () => void; const firstAcquisitionRead = new Promise((resolve) => { resolveFirstRead = resolve; }); const secondLockAttempt = new Promise((resolve) => { resolveSecondLockAttempt = resolve; }); const resumeFirstPromise = new Promise((resolve) => { resolveResumeFirst = resolve; }); async function acquireLock(): Promise<() => void> { const previous = lockTail; let release!: () => void; lockTail = new Promise((resolve) => { release = resolve; }); await previous; return release; } const serialized = { ...client, async $transaction(callback: (transaction: TransactionClient) => Promise): Promise { const currentTransaction = ++transactionNumber; let releaseAcquisitionLock: (() => void) | null = null; let acquisitionLocked = false; let paused = false; const transaction = { ...client, async $queryRaw(strings: TemplateStringsArray, ...values: unknown[]) { if (strings.join("?").includes("26004")) { lockAttempts += 1; if (lockAttempts === 2) resolveSecondLockAttempt(); releaseAcquisitionLock = await acquireLock(); acquisitionLocked = true; } return base.$queryRaw(strings, ...values); }, tenantProductAcquisition: { ...client.tenantProductAcquisition, async findFirst(args: TenantProductAcquisitionFindFirstArgs) { const row = await client.tenantProductAcquisition.findFirst(args); if (currentTransaction === 1 && acquisitionLocked && !paused) { paused = true; resolveFirstRead(); await resumeFirstPromise; } return row; }, }, } as TransactionClient; try { return await callback(transaction); } finally { const release = releaseAcquisitionLock as (() => void) | null; if (release) release(); } }, } as unknown as BillingSyncClient; return { client: serialized, firstAcquisitionRead, secondLockAttempt, resumeFirst: resolveResumeFirst, lockAttempts: () => lockAttempts, }; } function productPaymentSyncFields(acquisitionId: string, overrides: Partial = {}): Partial { const paymentExpiresAt = new Date("2026-07-30T10:00:00.000Z"); return { providerPaymentId: `mollie_${acquisitionId}`, paymentExternalId: acquisitionId, paymentAmountCents: null, paymentCurrency: null, paymentExpiresAt, paymentPaidAt: new Date("2026-07-16T12:00:00.000Z"), reservationExpiresAt: new Date("2026-08-01T10:00:00.000Z"), receivedAt: new Date("2026-07-16T12:00:00.000Z"), ...overrides, }; } describe("billing-sync.server", () => { beforeEach(() => { vi.clearAllMocks(); }); it.each([ ["active", "active"], ["trialing", "trial"], ["payment_failed", "past_due"], ["paused", "frozen"], ["terminated", "cancelled"], ] as const)("maps Lago status %s to %s", (input, expected) => { expect(normalizeLagoSubscriptionStatus(input)).toBe(expected); }); it.each([ ["paid", "active"], ["authorized", null], ["failed", "past_due"], ["expired", "past_due"], ["refunded", "past_due"], ["open", null], ] as const)("maps Mollie payment status %s to %s", (input, expected) => { expect(normalizeMolliePaymentStatus(input)).toBe(expected); }); it("resolves the local product kind for a Lago plan code", async () => { const client = createFakeClient({ products: [ { id: "product_starter", code: "starter", lagoPlanCode: "starter", kind: "base_plan", }, { id: "product_portal", code: "portal", lagoPlanCode: "customer_portal_monthly", kind: "recurring_add_on", }, ], }); await expect(resolveLagoSubscriptionProductKind(" customer_portal_monthly ", client)).resolves.toBe("recurring_add_on"); await expect(resolveLagoSubscriptionProductKind("hg_price_2026_07_30_1_starter_a9ef59efd15309db", client)).resolves.toBe("base_plan"); await expect(resolveLagoSubscriptionProductKind("hg_price_2026_07_30_1_starter_annual_sepa_a9ef59efd15309db", client)).resolves.toBe("base_plan"); await expect(resolveLagoSubscriptionProductKind("hg_price_2026_07_30_1_unknown_a9ef59efd15309db", client)).resolves.toBeNull(); await expect(resolveLagoSubscriptionProductKind("hg_price_2026_07_30_1_starter_not-a-digest", client)).resolves.toBeNull(); await expect(resolveLagoSubscriptionProductKind("missing", client)).resolves.toBeNull(); await expect(resolveLagoSubscriptionProductKind(" ", client)).resolves.toBeNull(); }); it("cancels a managed base-plan entitlement when Lago terminates the subscription", async () => { const receivedAt = new Date("2026-07-31T01:00:00.000Z"); const client = createFakeClient({ products: [{ id: "product_starter", code: "starter", lagoPlanCode: "starter", kind: "base_plan" }], subscriptions: new Map([["tenant_1", { id: "subscription_1", tenantId: "tenant_1", status: "active", planCode: "starter" }]]), tenantProducts: [ { id: "tenant_product_starter", tenantSubscriptionId: "subscription_1", subscriptionProductId: "product_starter", lagoSubscriptionId: "lago_subscription_1", planCode: "starter", cancelledAt: null, endsAt: null, }, ], }); await applyLagoSubscriptionSync( { tenantId: "tenant_1", eventKey: "lago:managed-starter:terminated", lagoSubscriptionId: "lago_subscription_1", planCode: "hg_price_2026_07_30_1_starter_a9ef59efd15309db", productKind: "base_plan", status: "terminated", receivedAt, }, client ); const state = getFakeState(client); expect(state.subscriptions.get("tenant_1")).toMatchObject({ status: "cancelled", planCode: "starter" }); expect(state.tenantProducts).toContainEqual( expect.objectContaining({ id: "tenant_product_starter", cancelledAt: receivedAt, endsAt: receivedAt, }) ); }); it("does not cancel the replacement plan when Lago terminates the previous provider version", async () => { const receivedAt = new Date("2026-08-01T00:00:00.000Z"); const client = createFakeClient({ products: [ { id: "product_core", code: "core", lagoPlanCode: "core", kind: "base_plan" }, { id: "product_swarm", code: "swarm", lagoPlanCode: "swarm", kind: "base_plan" }, ], subscriptions: new Map([["tenant_1", { id: "subscription_1", tenantId: "tenant_1", status: "active", planCode: "swarm" }]]), tenantProducts: [ { id: "tenant_product_core", tenantSubscriptionId: "subscription_1", subscriptionProductId: "product_core", lagoSubscriptionId: "stable_subscription_1", billingProviderSubscriptionId: "lago_version_old", planCode: "core", cancelledAt: null, endsAt: receivedAt, }, { id: "tenant_product_swarm", tenantSubscriptionId: "subscription_1", subscriptionProductId: "product_swarm", lagoSubscriptionId: "stable_subscription_1", billingProviderSubscriptionId: "lago_version_new", planCode: "swarm", cancelledAt: null, endsAt: null, }, ], }); const result = await applyLagoSubscriptionSync( { tenantId: "tenant_1", eventKey: "lago:old-version:terminated", lagoSubscriptionId: "stable_subscription_1", billingProviderSubscriptionId: "lago_version_old", planCode: "core", productKind: "base_plan", status: "terminated", receivedAt, }, client ); const state = getFakeState(client); expect(result.status).toBe("active"); expect(state.subscriptions.get("tenant_1")).toMatchObject({ status: "active", planCode: "swarm" }); expect(state.tenantProducts.find((product) => product.id === "tenant_product_core")).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt, }); expect(state.tenantProducts.find((product) => product.id === "tenant_product_swarm")).toMatchObject({ cancelledAt: null, endsAt: null, }); }); it("mirrors Lago subscription state into the local tenant subscription and product entitlement link", async () => { const client = createFakeClient({ products: [{ id: "product_1", code: "pro", lagoPlanCode: "lago_pro" }], }); const commitmentEndsAt = new Date("2027-07-01T00:00:00.000Z"); const result = await applyLagoSubscriptionSync( { tenantId: "tenant_1", eventKey: "lago:sub_1:active", lagoCustomerId: "cus_1", lagoSubscriptionId: "sub_1", billingProviderSubscriptionId: "lago_version_1", fromCheckoutSessionId: "hgco_1", status: "active", planCode: "lago_pro", subscriptionPriceId: "price_pro_monthly", seatQuantity: 7, officeSeatQuantity: 3, fieldSeatQuantity: 4, billingCadence: "annual_sepa", commitmentEndsAt, storageAddOnCodes: ["storage_500gb", " storage_100gb "], invoiceExternalId: "inv_1", currentPeriodStart: new Date("2026-07-01T00:00:00.000Z"), currentPeriodEnd: new Date("2026-08-01T00:00:00.000Z"), }, client ); const state = getFakeState(client); expect(result).toEqual({ tenantId: "tenant_1", provider: "lago", idempotencyKey: "lago:sub_1:active", replayed: false, status: "active" }); expect(state.subscriptions.get("tenant_1")).toMatchObject({ status: "active", lagoCustomerId: "cus_1", planCode: "lago_pro", seatQuantity: 7, officeSeatQuantity: 3, fieldSeatQuantity: 4, billingCadence: "annual_sepa", commitmentEndsAt, storageAddOnCodes: ["storage_100gb", "storage_500gb"], lastInvoiceExternalId: "inv_1", pastDueSince: null, frozenAt: null, cancelledAt: null, }); expect(state.tenantProducts).toHaveLength(1); expect(state.tenantProducts[0]).toMatchObject({ subscriptionProductId: "product_1", lagoSubscriptionId: "sub_1", billingProviderSubscriptionId: "lago_version_1", fromCheckoutSessionId: "hgco_1", planCode: "pro", quantity: 7, officeSeatQuantity: 3, fieldSeatQuantity: 4, billingCadence: "annual_sepa", commitmentEndsAt, storageAddOnCodes: ["storage_100gb", "storage_500gb"], }); expect(state.tenantPrices).toEqual([ expect.objectContaining({ tenantSubscriptionProductId: state.tenantProducts[0]!.id, subscriptionPriceId: "price_pro_monthly", quantity: 7, isMetered: false, }), ]); expect(state.idempotency.has(`tenant:tenant_1:${BILLING_SYNC_IDEMPOTENCY_SCOPE}:lago:sub_1:active`)).toBe(true); expect(state.auditEvents).toHaveLength(1); expect(state.activities).toHaveLength(1); expect(state.activities[0]).toMatchObject({ activityType: "billing_state_changed", subjectType: "tenant", subjectId: "tenant_1", summaryText: "activity.runtime.billing.statusChanged", }); }); it("ends other active tenant products when a paid plan change becomes active", async () => { const receivedAt = new Date("2026-07-04T12:00:00.000Z"); const client = createFakeClient({ products: [ { id: "product_pro", code: "pro", lagoPlanCode: "pro" }, { id: "product_business", code: "business", lagoPlanCode: "business" }, ], subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "pro" }]]), tenantProducts: [ { id: "tenant_product_pro", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_pro", planCode: "pro", lagoSubscriptionId: "lago_pro", cancelledAt: null, endsAt: null, }, ], }); await applyLagoSubscriptionSync( { tenantId: "tenant_1", eventKey: "lago:business:active", lagoSubscriptionId: "lago_business", status: "active", planCode: "business", seatQuantity: 1, receivedAt, }, client ); const state = getFakeState(client); expect(state.tenantProducts).toHaveLength(2); expect(state.tenantProducts.find((product) => product.id === "tenant_product_pro")).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt, }); expect(state.tenantProducts.find((product) => product.subscriptionProductId === "product_business")).toMatchObject({ cancelledAt: null, endsAt: null, lagoSubscriptionId: "lago_business", planCode: "business", }); }); it("retires an exact standalone storage subscription when the composite base selection becomes active", async () => { const receivedAt = new Date("2026-07-04T12:00:00.000Z"); const client = createFakeClient({ products: [ { id: "product_core", code: "starter", lagoPlanCode: "starter", kind: "base_plan" }, { id: "product_storage", code: "storage_500gb", lagoPlanCode: "storage_500gb", kind: "recurring_add_on" }, ], subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "starter" }]]), tenantProducts: [ { id: "tenant_product_storage_legacy", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_storage", lagoSubscriptionId: "lago_storage_legacy", billingProviderSubscriptionId: "lago_storage_version_legacy", cancelledAt: null, endsAt: null, }, ], }); await applyLagoSubscriptionSync({ tenantId: "tenant_1", eventKey: "lago:core:composite-storage-active", lagoSubscriptionId: "lago_core_composite", billingProviderSubscriptionId: "lago_core_composite_version", planCode: "starter", productKind: "base_plan", storageAddOnCodes: ["storage_500gb"], status: "active", receivedAt, }, client); const state = getFakeState(client); expect(state.tenantProducts.find((product) => product.id === "tenant_product_storage_legacy")).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt, }); expect(state.outboxEvents).toEqual(expect.arrayContaining([ expect.objectContaining({ payload: expect.objectContaining({ acquisitionId: "legacy:tenant_product_storage_legacy", action: "terminate_lago_subscription", lagoSubscriptionId: "lago_storage_legacy", }), }), ])); }); it("activates a recurring add-on without ending or replacing the active base plan", async () => { const receivedAt = new Date("2026-07-16T12:00:00.000Z"); const client = createFakeClient({ products: [ { id: "product_business", code: "business", lagoPlanCode: "business", kind: "base_plan" }, { id: "product_portal", code: "customer_portal_monthly", lagoPlanCode: "customer_portal_monthly", kind: "recurring_add_on" }, ], subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), tenantProducts: [ { id: "tenant_product_business", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_business", planCode: "business", cancelledAt: null, endsAt: null, }, ], }); const result = await applyLagoSubscriptionSync( { tenantId: "tenant_1", eventKey: "lago:portal:active", productKind: "recurring_add_on", lagoSubscriptionId: "lago_portal", status: "active", planCode: "customer_portal_monthly", subscriptionPriceId: "price_portal_monthly", receivedAt, }, client ); const state = getFakeState(client); expect(result.status).toBeNull(); expect(state.subscriptions.get("tenant_1")).toMatchObject({ status: "active", planCode: "business" }); expect(state.tenantProducts.find((product) => product.id === "tenant_product_business")).toMatchObject({ cancelledAt: null, endsAt: null }); expect(state.tenantProducts.find((product) => product.subscriptionProductId === "product_portal")).toMatchObject({ lagoSubscriptionId: "lago_portal", cancelledAt: null, endsAt: null, }); }); it("rejects a recurring Lago add-on when the active base subscription is frozen", async () => { const client = createFakeClient({ products: [ { id: "product_portal", code: "customer_portal_monthly", lagoPlanCode: "customer_portal_monthly", kind: "recurring_add_on", }, ], subscriptions: new Map([ [ "tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", frozenAt: new Date("2026-07-17T09:00:00.000Z"), cancelledAt: null, }, ], ]), }); await expect( applyLagoSubscriptionSync( { tenantId: "tenant_1", eventKey: "lago:portal:frozen-base", productKind: "recurring_add_on", lagoSubscriptionId: "lago_portal", status: "active", planCode: "customer_portal_monthly", subscriptionPriceId: "price_portal_monthly", }, client ) ).rejects.toThrow("An active base subscription is required for product acquisitions."); expect(getFakeState(client).tenantProducts).toHaveLength(0); }); it("persists the server-decided self-service trial window", async () => { const trialStartsAt = new Date("2026-07-15T10:00:00.000Z"); const trialEndsAt = new Date("2026-07-29T10:00:00.000Z"); const client = createFakeClient({ products: [{ id: "product_trial", code: "starter", lagoPlanCode: "starter" }], }); await applyLagoSubscriptionSync( { tenantId: "tenant_trial", eventKey: "lago:trial:started", lagoSubscriptionId: "lago_trial", status: "trial", planCode: "starter", seatQuantity: 3, trialStartsAt, trialEndsAt, receivedAt: trialStartsAt, }, client ); expect(getFakeState(client).subscriptions.get("tenant_trial")).toMatchObject({ status: "trial", planCode: "starter", seatQuantity: 3, trialStartsAt, trialEndsAt, pastDueSince: null, frozenAt: null, cancelledAt: null, }); }); it("replays duplicate provider events without mutating or auditing again", async () => { const client = createFakeClient(); await applyMolliePaymentSync({ tenantId: "tenant_1", eventKey: "mollie:pay_1", paymentExternalId: "pay_1", status: "paid" }, client); const second = await applyMolliePaymentSync({ tenantId: "tenant_1", eventKey: "mollie:pay_1", paymentExternalId: "pay_1", status: "paid" }, client); const state = getFakeState(client); expect(second.replayed).toBe(true); expect(second.status).toBe("active"); expect(state.auditEvents).toHaveLength(1); expect(state.activities).toHaveLength(1); }); it("marks failed Mollie payments as past_due and preserves invoice/payment references", async () => { const client = createFakeClient(); const receivedAt = new Date("2026-07-04T12:00:00.000Z"); await applyMolliePaymentSync( { tenantId: "tenant_2", eventKey: "mollie:pay_failed", mollieCustomerId: "cst_1", paymentExternalId: "pay_failed", invoiceExternalId: "inv_failed", status: "failed", receivedAt, }, client ); expect(getFakeState(client).subscriptions.get("tenant_2")).toMatchObject({ status: "past_due", mollieCustomerId: "cst_1", lastInvoiceExternalId: "inv_failed", lastPaymentExternalId: "pay_failed", pastDueSince: receivedAt, frozenAt: null, }); }); it("settles a recurring invoice only against the exact tenant ledger", async () => { const client = createFakeClient({ checkoutSessions: new Map([ [ "hgrc_invoice_1", { id: "hgrc_invoice_1", tenantId: "tenant_1", invoiceExternalId: "invoice_1", lagoSubscriptionId: "subscription_1", providerPaymentId: "tr_recurring_1", pending: true, status: "pending", }, ], ]), }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:recurring:paid", providerPaymentId: "tr_recurring_1", paymentExternalId: "hgrc_invoice_1", invoiceExternalId: "invoice_1", lagoSubscriptionId: "subscription_1", status: "paid", recurringInvoiceCollection: true, }, client ); expect(result.status).toBe("active"); expect(getFakeState(client).checkoutSessions.get("hgrc_invoice_1")).toMatchObject({ pending: false, status: "paid", }); expect(getFakeState(client).subscriptions.get("tenant_1")).toMatchObject({ status: "active", lastInvoiceExternalId: "invoice_1", lastPaymentExternalId: "hgrc_invoice_1", }); }); it("marks the exact self-service checkout paid before Lago can emit its initial invoice", async () => { const client = createFakeClient({ checkoutSessions: new Map([ [ "hgco_123", { id: "hgco_123", tenantId: "tenant_1", invoiceExternalId: "hgco_123", lagoSubscriptionId: "hgco_123", providerPaymentId: "tr_checkout_1", pending: true, status: "open", }, ], ]), }); await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:self-service:paid", providerPaymentId: "tr_checkout_1", paymentExternalId: "hgco_123", invoiceExternalId: "hgco_123", lagoSubscriptionId: "hgco_123", status: "paid", selfServiceCheckout: true, }, client ); expect(getFakeState(client).checkoutSessions.get("hgco_123")).toMatchObject({ pending: false, status: "paid" }); }); it("fails closed when a recurring payment cannot match its exact ledger", async () => { const client = createFakeClient(); await expect( applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:recurring:missing", providerPaymentId: "tr_recurring_1", paymentExternalId: "hgrc_missing", invoiceExternalId: "invoice_1", lagoSubscriptionId: "subscription_1", status: "failed", recurringInvoiceCollection: true, }, client ) ).rejects.toThrow("exact tenant ledger match"); }); it("records a failed self-service checkout without poisoning an existing active subscription", async () => { const client = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "starter" }]]), }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:self-service:failed", paymentExternalId: "payment_change", invoiceExternalId: "checkout_change", status: "failed", preserveSubscriptionStatus: true, }, client ); expect(result.status).toBeNull(); expect(getFakeState(client).subscriptions.get("tenant_1")).toMatchObject({ status: "active", planCode: "starter", lastPaymentExternalId: "payment_change", }); }); it.each(["failed", "expired", "refunded", "charged_back", "canceled"])( "keeps a %s add-on payment failure local to the acquisition", async (paymentStatus) => { const client = createFakeClient({ subscriptions: new Map([ [ "tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business", lastInvoiceExternalId: "base_invoice", lastPaymentExternalId: "base_payment", }, ], ]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: `add_on_invoice_${paymentStatus}`, tenantSubscriptionProductId: null, lagoSubscriptionId: "lago_portal", }, ], ]), }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: `mollie:add-on:${paymentStatus}`, productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1", { paymentPaidAt: null }), invoiceExternalId: `add_on_invoice_${paymentStatus}`, lagoSubscriptionId: "lago_portal", status: paymentStatus, }, client ); expect(result.status).toBeNull(); expect(getFakeState(client).subscriptions.get("tenant_1")).toMatchObject({ status: "active", planCode: "business", lastInvoiceExternalId: "base_invoice", lastPaymentExternalId: "base_payment", }); expect(getFakeState(client).acquisitions.get("acquisition_1")).toMatchObject({ status: paymentStatus === "canceled" ? "cancelled" : paymentStatus === "charged_back" ? "failed" : paymentStatus, }); } ); it.each([null, "cancelled"])("revokes a refunded add-on when the base subscription is %s", async (baseStatus) => { const subscriptions = new Map(); if (baseStatus) { subscriptions.set("tenant_1", { id: "sub_1", tenantId: "tenant_1", status: baseStatus, cancelledAt: new Date("2026-07-15T00:00:00.000Z"), }); } const client = createFakeClient({ subscriptions, acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "active", version: 4, quantity: 1, invoiceExternalId: "invoice_refund_1", tenantSubscriptionProductId: "tenant_product_1", lagoSubscriptionId: "acquisition_1", }, ], ]), tenantProducts: [ { id: "tenant_product_1", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_portal", lagoSubscriptionId: "acquisition_1", cancelledAt: null, endsAt: null, }, ], }); const receivedAt = new Date("2026-07-16T12:00:00.000Z"); await expect( applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: `mollie:add-on:refunded:${baseStatus ?? "missing"}`, productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1", { paymentPaidAt: null }), invoiceExternalId: "invoice_refund_1", lagoSubscriptionId: "acquisition_1", status: "refunded", receivedAt, }, client ) ).resolves.toMatchObject({ status: null }); const state = getFakeState(client); expect(state.acquisitions.get("acquisition_1")).toMatchObject({ status: "refunded", refundedAt: receivedAt }); expect(state.tenantProducts[0]).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt }); expect(state.subscriptions.size).toBe(baseStatus ? 1 : 0); }); it("fails closed when Mollie partially refunds an already active add-on", async () => { const receivedAt = new Date("2026-07-17T12:30:00.000Z"); const paidAt = new Date("2026-07-16T12:00:00.000Z"); const client = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "active", version: 4, quantity: 1, amountCents: 4_900, currency: "EUR", providerAttempt: 1, providerPaymentId: "mollie_acquisition_1", providerPaidAt: paidAt, invoiceExternalId: "invoice_portal_1", tenantSubscriptionProductId: "tenant_product_1", lagoSubscriptionId: "lago_portal_1", }, ], ]), tenantProducts: [ { id: "tenant_product_1", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_portal", lagoSubscriptionId: "lago_portal_1", cancelledAt: null, endsAt: null, }, ], }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:add-on:partial-refund:1000", productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1", { paymentAmountCents: 4_900, paymentAmountRefundedCents: 1_000, paymentCurrency: "EUR", paymentPaidAt: null, }), invoiceExternalId: "invoice_portal_1", lagoSubscriptionId: "lago_portal_1", status: "paid", receivedAt, }, client ); const state = getFakeState(client); expect(result.productAcquisitionDisposition).toBe("quarantined"); expect(state.acquisitions.get("acquisition_1")).toMatchObject({ status: "failed", failedAt: receivedAt, failureCode: "provider.payment_partial_refund", providerPaidAt: paidAt, }); expect(state.tenantProducts[0]).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt }); expect(state.outboxEvents).toEqual([ expect.objectContaining({ eventType: "billing.product-acquisition.provider-side-effect", payload: expect.objectContaining({ acquisitionId: "acquisition_1", acquisitionStatus: "failed", action: "terminate_lago_subscription", lagoSubscriptionId: "lago_portal_1", providerPaymentId: "mollie_acquisition_1", }), }), ]); expect(state.auditEvents).toContainEqual( expect.objectContaining({ action: "PRODUCT_ACQUISITION_PARTIAL_REFUND_QUARANTINED", targetId: "acquisition_1", outcome: "failure", metadata: expect.objectContaining({ failureCode: "provider.payment_partial_refund", amountCents: 4_900, refundedCents: 1_000, previousStatus: "active", }), }) ); }); it("serializes a paid redirect before a concurrent partial refund so the refund cannot be lost", async () => { const receivedAt = new Date("2026-07-17T12:30:00.000Z"); const providerPaidAt = new Date("2026-07-16T12:00:00.000Z"); const providerPaymentExpiresAt = new Date("2026-07-30T10:00:00.000Z"); const baseClient = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "active", version: 4, quantity: 1, amountCents: 4_900, currency: "EUR", providerAttempt: 1, providerPaymentId: "mollie_acquisition_1", providerPaymentExpiresAt, providerPaidAt, invoiceExternalId: "invoice_portal_1", tenantSubscriptionProductId: "tenant_product_1", lagoSubscriptionId: "lago_portal_1", }, ], ]), tenantProducts: [ { id: "tenant_product_1", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_portal", lagoSubscriptionId: "lago_portal_1", cancelledAt: null, endsAt: null, }, ], }); const serialized = serializeFakeAcquisitionTransactions(baseClient); const metadata = { tenantId: "tenant_1", productKind: "recurring_add_on" as const, productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", invoiceExternalId: "invoice_portal_1", lagoSubscriptionId: "lago_portal_1", status: "paid", receivedAt, }; const payment = productPaymentSyncFields("acquisition_1", { paymentAmountCents: 4_900, paymentCurrency: "EUR", paymentExpiresAt: providerPaymentExpiresAt, paymentPaidAt: providerPaidAt, receivedAt, }); const paidRedirect = applyMolliePaymentSync({ ...metadata, ...payment, eventKey: "mollie:redirect:paid" }, serialized.client); await serialized.firstAcquisitionRead; const partialRefund = applyMolliePaymentSync( { ...metadata, ...payment, eventKey: "mollie:webhook:partial-refund:1000", paymentAmountRefundedCents: 1_000, }, serialized.client ); await serialized.secondLockAttempt; serialized.resumeFirst(); await expect(Promise.all([paidRedirect, partialRefund])).resolves.toEqual([ expect.objectContaining({ productAcquisitionDisposition: "ignored" }), expect.objectContaining({ productAcquisitionDisposition: "quarantined" }), ]); const state = getFakeState(baseClient); expect(serialized.lockAttempts()).toBe(2); expect(state.acquisitions.get("acquisition_1")).toMatchObject({ status: "failed", version: 6, failedAt: receivedAt, failureCode: "provider.payment_partial_refund", }); expect(state.tenantProducts[0]).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt }); expect(state.outboxEvents).toEqual([ expect.objectContaining({ eventType: "billing.product-acquisition.provider-side-effect", payload: expect.objectContaining({ acquisitionId: "acquisition_1", acquisitionStatus: "failed", action: "terminate_lago_subscription", lagoSubscriptionId: "lago_portal_1", }), }), ]); }); it("queues exact invoice failure when Mollie partially refunds an active one-time setup", async () => { const receivedAt = new Date("2026-07-17T13:00:00.000Z"); const { claim, domain } = createPortalDomainState(); const client = createFakeClient({ products: [{ id: "product_domain_setup", code: "customer_portal_domain_setup", kind: "one_time_setup" }], subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), acquisitions: new Map([ [ "acquisition_setup_1", { id: "acquisition_setup_1", tenantId: "tenant_1", subscriptionProductId: "product_domain_setup", subscriptionPriceId: "price_domain_setup", productKind: "one_time_setup", scopeKey: "portal-domain:claim_1", status: "active", version: 2, quantity: 1, amountCents: 19_900, currency: "EUR", providerAttempt: 1, providerPaymentId: "mollie_acquisition_setup_1", providerPaidAt: new Date("2026-07-16T12:00:00.000Z"), invoiceExternalId: "invoice_setup_exact_1", tenantSubscriptionProductId: null, lagoSubscriptionId: null, }, ], ]), portalClaims: new Map([[claim.id, claim]]), portalDomains: new Map([[domain.id, domain]]), }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:domain-setup:partial-refund:2500", productKind: "one_time_setup", productAcquisitionId: "acquisition_setup_1", productScopeKey: "portal-domain:claim_1", subscriptionProductId: "product_domain_setup", subscriptionPriceId: "price_domain_setup", ...productPaymentSyncFields("acquisition_setup_1", { paymentAmountCents: 19_900, paymentAmountRefundedCents: 2_500, paymentCurrency: "EUR", }), invoiceExternalId: "invoice_setup_exact_1", status: "paid", receivedAt, }, client ); const state = getFakeState(client); expect(result.productAcquisitionDisposition).toBe("quarantined"); expect(state.acquisitions.get("acquisition_setup_1")).toMatchObject({ status: "failed", failedAt: receivedAt, failureCode: "provider.payment_partial_refund", }); expect(state.outboxEvents).toEqual([ expect.objectContaining({ eventType: "billing.product-acquisition.provider-side-effect", payload: expect.objectContaining({ acquisitionId: "acquisition_setup_1", acquisitionStatus: "failed", action: "mark_lago_invoice_failed", invoiceExternalId: "invoice_setup_exact_1", lagoSubscriptionId: null, }), }), ]); expect(state.sequence).not.toContain("domain-cas"); expect(state.portalClaims.get("claim_1")).toMatchObject({ generation: 2 }); }); it("quarantines a paid add-on when its base subscription is inactive", async () => { const client = createFakeClient({ subscriptions: new Map(), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: "invoice_without_base_1", tenantSubscriptionProductId: null, lagoSubscriptionId: "acquisition_1", }, ], ]), }); await expect( applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:add-on:paid-without-base", productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1"), invoiceExternalId: "invoice_without_base_1", lagoSubscriptionId: "acquisition_1", status: "paid", receivedAt: new Date("2026-07-17T10:00:00.000Z"), }, client ) ).resolves.toMatchObject({ productAcquisitionDisposition: "quarantined" }); expect(getFakeState(client).subscriptions.size).toBe(0); expect(getFakeState(client).acquisitions.get("acquisition_1")).toMatchObject({ status: "payment_pending", failureCode: "provider.payment_paid_base_subscription_inactive", }); }); it("quarantines a paid add-on when its active base subscription is frozen", async () => { const client = createFakeClient({ subscriptions: new Map([ [ "tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", frozenAt: new Date("2026-07-17T09:00:00.000Z"), cancelledAt: null, }, ], ]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: "invoice_frozen_base_1", tenantSubscriptionProductId: null, lagoSubscriptionId: "acquisition_1", }, ], ]), }); await expect( applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:add-on:paid-frozen-base", productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1"), invoiceExternalId: "invoice_frozen_base_1", lagoSubscriptionId: "acquisition_1", status: "paid", receivedAt: new Date("2026-07-17T10:00:00.000Z"), }, client ) ).resolves.toMatchObject({ productAcquisitionDisposition: "quarantined" }); expect(getFakeState(client).acquisitions.get("acquisition_1")).toMatchObject({ status: "payment_pending", failureCode: "provider.payment_paid_base_subscription_inactive", }); }); it("quarantines a paid add-on when the tenant was deactivated before the webhook", async () => { const client = createFakeClient({ inactiveTenantIds: new Set(["tenant_1"]), subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", cancelledAt: null }]]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: "invoice_inactive_tenant_1", tenantSubscriptionProductId: null, lagoSubscriptionId: "lago_portal", }, ], ]), }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:add-on:paid-inactive-tenant", productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1"), invoiceExternalId: "invoice_inactive_tenant_1", lagoSubscriptionId: "lago_portal", status: "paid", receivedAt: new Date("2026-07-17T10:00:00.000Z"), }, client ); expect(result.productAcquisitionDisposition).toBe("quarantined"); expect(getFakeState(client).tenantProducts).toHaveLength(0); expect(getFakeState(client).acquisitions.get("acquisition_1")).toMatchObject({ status: "payment_pending", failureCode: "provider.payment_tenant_inactive", }); }); it("reuses the exact bound provider window when a paid Mollie response omits expiresAt", async () => { const receivedAt = new Date("2026-07-16T12:00:00.000Z"); const providerPaymentExpiresAt = new Date("2026-07-30T10:00:00.000Z"); const reservationExpiresAt = new Date("2026-08-01T10:00:00.000Z"); const client = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "starter" }]]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, amountCents: 1_999, currency: "EUR", providerAttempt: 2, providerPaymentId: "mollie_acquisition_1", providerPaymentExpiresAt, providerPaidAt: null, reservationExpiresAt, invoiceExternalId: "acquisition_1:attempt:2", tenantSubscriptionProductId: null, lagoSubscriptionId: "acquisition_1:attempt:2", }, ], ]), }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:add-on:paid-without-terminal-expiry", productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1", { providerPaymentId: "mollie_acquisition_1", paymentExternalId: "acquisition_1:attempt:2", paymentAmountCents: 1_999, paymentCurrency: "EUR", paymentExpiresAt: null, reservationExpiresAt: null, }), invoiceExternalId: "acquisition_1:attempt:2", lagoSubscriptionId: "acquisition_1:attempt:2", status: "paid", receivedAt, }, client ); const state = getFakeState(client); expect(result.productAcquisitionDisposition).toBe("applied"); expect(state.acquisitions.get("acquisition_1")).toMatchObject({ status: "active", providerPaymentExpiresAt, reservationExpiresAt, failureCode: null, }); expect(state.tenantProducts).toHaveLength(1); }); it("quarantines a nonterminal Mollie response that omits its provider window", async () => { const providerPaymentExpiresAt = new Date("2026-07-30T10:00:00.000Z"); const reservationExpiresAt = new Date("2026-08-01T10:00:00.000Z"); const client = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "starter" }]]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, amountCents: 1_999, currency: "EUR", providerAttempt: 2, providerPaymentId: "mollie_acquisition_1", providerPaymentExpiresAt, providerPaidAt: null, reservationExpiresAt, invoiceExternalId: "acquisition_1:attempt:2", tenantSubscriptionProductId: null, lagoSubscriptionId: "acquisition_1:attempt:2", }, ], ]), }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:add-on:open-without-provider-window", productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1", { providerPaymentId: "mollie_acquisition_1", paymentExternalId: "acquisition_1:attempt:2", paymentAmountCents: 1_999, paymentCurrency: "EUR", paymentExpiresAt: null, paymentPaidAt: null, reservationExpiresAt: null, }), invoiceExternalId: "acquisition_1:attempt:2", lagoSubscriptionId: "acquisition_1:attempt:2", status: "open", }, client ); expect(result.productAcquisitionDisposition).toBe("quarantined"); expect(getFakeState(client).acquisitions.get("acquisition_1")).toMatchObject({ status: "payment_pending", providerPaymentExpiresAt: null, failureCode: "provider.payment_window_quarantined", }); expect(getFakeState(client).tenantProducts).toHaveLength(0); }); it.each([ ["missing stored expiry", null, new Date("2026-08-01T10:00:00.000Z"), new Date("2026-07-16T12:00:00.000Z")], ["inconsistent stored reservation", new Date("2026-07-30T10:00:00.000Z"), new Date("2026-08-01T10:00:00.001Z"), new Date("2026-07-16T12:00:00.000Z")], ["missing paid timestamp", new Date("2026-07-30T10:00:00.000Z"), new Date("2026-08-01T10:00:00.000Z"), null], ["paid after provider expiry", new Date("2026-07-30T10:00:00.000Z"), new Date("2026-08-01T10:00:00.000Z"), new Date("2026-07-30T10:00:00.001Z")], ] as const)("keeps a paid Mollie response fail-closed for %s", async (_case, providerPaymentExpiresAt, reservationExpiresAt, paymentPaidAt) => { const client = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "starter" }]]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, amountCents: 1_999, currency: "EUR", providerAttempt: 2, providerPaymentId: "mollie_acquisition_1", providerPaymentExpiresAt, providerPaidAt: null, reservationExpiresAt, invoiceExternalId: "acquisition_1:attempt:2", tenantSubscriptionProductId: null, lagoSubscriptionId: "acquisition_1:attempt:2", }, ], ]), }); const result = await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: `mollie:add-on:paid-invalid-window:${_case}`, productKind: "recurring_add_on", productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", ...productPaymentSyncFields("acquisition_1", { providerPaymentId: "mollie_acquisition_1", paymentExternalId: "acquisition_1:attempt:2", paymentAmountCents: 1_999, paymentCurrency: "EUR", paymentExpiresAt: null, paymentPaidAt, reservationExpiresAt: null, }), invoiceExternalId: "acquisition_1:attempt:2", lagoSubscriptionId: "acquisition_1:attempt:2", status: "paid", }, client ); const state = getFakeState(client); expect(result.productAcquisitionDisposition).toBe("quarantined"); expect(state.acquisitions.get("acquisition_1")).toMatchObject({ status: "payment_pending", failureCode: "provider.payment_paid_window_invalid", }); expect(state.tenantProducts).toHaveLength(0); }); it("activates and refunds an acquired product through idempotent Mollie webhook transitions", async () => { const receivedAt = new Date("2026-07-16T12:00:00.000Z"); const client = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), acquisitions: new Map([ [ "acquisition_1", { id: "acquisition_1", tenantId: "tenant_1", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: "invoice_portal_1", tenantSubscriptionProductId: null, lagoSubscriptionId: "lago_portal", }, ], ]), }); const metadata = { tenantId: "tenant_1", productKind: "recurring_add_on" as const, productAcquisitionId: "acquisition_1", productScopeKey: "tenant", subscriptionProductId: "product_portal", subscriptionPriceId: "price_portal_monthly", invoiceExternalId: "invoice_portal_1", lagoSubscriptionId: "lago_portal", }; await applyMolliePaymentSync( { ...metadata, ...productPaymentSyncFields("acquisition_1"), eventKey: "mollie:add-on:paid", status: "paid", receivedAt, }, client ); const state = getFakeState(client); expect(state.subscriptions.get("tenant_1")).toMatchObject({ status: "active", planCode: "business" }); expect(state.tenantProducts).toHaveLength(1); expect(state.tenantProducts[0]).toMatchObject({ tenantSubscriptionId: "sub_1", subscriptionProductId: "product_portal", lagoSubscriptionId: "lago_portal", cancelledAt: null, }); expect(state.acquisitions.get("acquisition_1")).toMatchObject({ status: "active", tenantSubscriptionProductId: state.tenantProducts[0]!.id, activatedAt: receivedAt, }); await applyMolliePaymentSync( { ...metadata, ...productPaymentSyncFields("acquisition_1", { paymentPaidAt: null }), eventKey: "mollie:add-on:refunded:1999", status: "refunded", receivedAt, }, client ); expect(state.acquisitions.get("acquisition_1")).toMatchObject({ status: "refunded", refundedAt: receivedAt }); expect(state.tenantProducts[0]).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt }); expect(state.subscriptions.get("tenant_1")).toMatchObject({ status: "active", planCode: "business" }); }); it("atomically replaces an active email marketing tier only after the new payment is confirmed", async () => { const receivedAt = new Date("2026-07-16T12:00:00.000Z"); const client = createFakeClient({ products: [ { id: "product_email_s", code: "email_marketing_s", kind: "recurring_add_on" }, { id: "product_email_m", code: "email_marketing_m", kind: "recurring_add_on" }, ], subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "starter" }]]), tenantProducts: [ { id: "tenant_product_email_s", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_email_s", lagoSubscriptionId: "lago_email_s", cancelledAt: null, endsAt: null, }, ], acquisitions: new Map([ [ "acquisition_email_s", { id: "acquisition_email_s", tenantId: "tenant_1", subscriptionProductId: "product_email_s", subscriptionPriceId: "price_email_s", productKind: "recurring_add_on", scopeKey: "tenant", status: "active", version: 4, quantity: 1, providerAttempt: 1, providerPaymentId: "mollie_email_s", invoiceExternalId: "invoice_email_s", tenantSubscriptionProductId: "tenant_product_email_s", lagoSubscriptionId: "lago_email_s", }, ], [ "acquisition_email_m", { id: "acquisition_email_m", tenantId: "tenant_1", subscriptionProductId: "product_email_m", subscriptionPriceId: "price_email_m", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: "invoice_email_m", tenantSubscriptionProductId: null, lagoSubscriptionId: "lago_email_m", }, ], ]), }); await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:email-tier:m:paid", productKind: "recurring_add_on", productAcquisitionId: "acquisition_email_m", productScopeKey: "tenant", subscriptionProductId: "product_email_m", subscriptionPriceId: "price_email_m", ...productPaymentSyncFields("acquisition_email_m"), invoiceExternalId: "invoice_email_m", lagoSubscriptionId: "lago_email_m", status: "paid", receivedAt, }, client ); const state = getFakeState(client); expect(state.acquisitions.get("acquisition_email_s")).toMatchObject({ status: "cancelled", cancelledAt: receivedAt, }); expect(state.tenantProducts.find((product) => product.id === "tenant_product_email_s")).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt, }); expect(state.acquisitions.get("acquisition_email_m")).toMatchObject({ status: "active", tenantSubscriptionProductId: expect.any(String), }); expect(state.outboxEvents).toEqual( expect.arrayContaining([ expect.objectContaining({ eventType: "billing.product-acquisition.provider-side-effect", payload: expect.objectContaining({ acquisitionId: "acquisition_email_s", acquisitionStatus: "cancelled", action: "terminate_lago_subscription", lagoSubscriptionId: "lago_email_s", }), }), ]) ); expect(state.auditEvents).toEqual( expect.arrayContaining([ expect.objectContaining({ action: "EMAIL_MARKETING_TIER_REPLACED", targetId: "acquisition_email_s", metadata: expect.objectContaining({ replacementAcquisitionId: "acquisition_email_m", replacementProductCode: "email_marketing_m", }), }), ]) ); }); it("revokes a legacy email tier, terminates its exact provider subscription and preserves the paid replacement", async () => { const receivedAt = new Date("2026-07-16T12:00:00.000Z"); const client = createFakeClient({ products: [ { id: "product_email_s", code: "email_marketing_s", kind: "recurring_add_on" }, { id: "product_email_m", code: "email_marketing_m", kind: "recurring_add_on" }, ], subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "starter" }]]), tenantProducts: [ { id: "tenant_product_email_s_legacy", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_email_s", lagoSubscriptionId: "lago_email_s_orphaned", billingProviderSubscriptionId: "lago_email_s_version_orphaned", cancelledAt: null, endsAt: null, }, { id: "acquisition_email_m", tenantSubscriptionId: "sub_1", subscriptionProductId: "product_email_m", lagoSubscriptionId: "lago_email_m", billingProviderSubscriptionId: "lago_email_m_version", cancelledAt: null, endsAt: null, }, ], acquisitions: new Map([ [ "acquisition_email_m", { id: "acquisition_email_m", tenantId: "tenant_1", subscriptionProductId: "product_email_m", subscriptionPriceId: "price_email_m", productKind: "recurring_add_on", scopeKey: "tenant", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: "invoice_email_m", tenantSubscriptionProductId: null, lagoSubscriptionId: "lago_email_m", lagoProviderSubscriptionId: "lago_email_m_version", }, ], ]), }); await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:email-tier:m:paid-with-legacy-predecessor", productKind: "recurring_add_on", productAcquisitionId: "acquisition_email_m", productScopeKey: "tenant", subscriptionProductId: "product_email_m", subscriptionPriceId: "price_email_m", ...productPaymentSyncFields("acquisition_email_m"), invoiceExternalId: "invoice_email_m", lagoSubscriptionId: "lago_email_m", lagoProviderSubscriptionId: "lago_email_m_version", status: "paid", receivedAt, }, client ); const state = getFakeState(client); expect(state.tenantProducts.find((product) => product.id === "tenant_product_email_s_legacy")).toMatchObject({ cancelledAt: receivedAt, endsAt: receivedAt, }); expect(state.tenantProducts.find((product) => product.id === "acquisition_email_m")).toMatchObject({ cancelledAt: null, endsAt: null, lagoSubscriptionId: "lago_email_m", }); expect(state.acquisitions.get("acquisition_email_m")).toMatchObject({ status: "active", tenantSubscriptionProductId: "acquisition_email_m", }); expect(state.outboxEvents).toEqual( expect.arrayContaining([ expect.objectContaining({ payload: expect.objectContaining({ acquisitionId: "legacy:tenant_product_email_s_legacy", acquisitionStatus: "cancelled", action: "terminate_lago_subscription", lagoSubscriptionId: "lago_email_s_orphaned", }), }), ]) ); expect(state.auditEvents).toEqual( expect.arrayContaining([ expect.objectContaining({ action: "EMAIL_MARKETING_TIER_REPLACED", targetType: "TenantSubscriptionProduct", targetId: "tenant_product_email_s_legacy", metadata: expect.objectContaining({ legacyEntitlement: true, providerTerminationQueued: true, replacementAcquisitionId: "acquisition_email_m", }), }), ]) ); }); it("serializes a paid portal-domain activation and fences the old deprovision generation", async () => { const receivedAt = new Date("2026-07-17T10:00:00.000Z"); const { claim, domain } = createPortalDomainState(); const client = createFakeClient({ products: [{ id: "product_domain", code: "customer_portal_domain_setup", kind: "one_time_setup" }], subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), acquisitions: new Map([ [ "acquisition_domain_1", { id: "acquisition_domain_1", tenantId: "tenant_1", subscriptionProductId: "product_domain", subscriptionPriceId: "price_domain", productKind: "one_time_setup", scopeKey: "portal-domain:claim_1", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: "invoice_domain_1", tenantSubscriptionProductId: null, lagoSubscriptionId: null, }, ], ]), portalClaims: new Map([[claim.id, claim]]), portalDomains: new Map([[domain.id, domain]]), }); await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:portal-domain:paid", productKind: "one_time_setup", productAcquisitionId: "acquisition_domain_1", productScopeKey: "portal-domain:claim_1", subscriptionProductId: "product_domain", subscriptionPriceId: "price_domain", ...productPaymentSyncFields("acquisition_domain_1"), invoiceExternalId: "invoice_domain_1", status: "paid", receivedAt, }, client ); const state = getFakeState(client); expect(state.sequence.indexOf("advisory:claim_1")).toBeLessThan(state.sequence.indexOf("domain-lock:claim_1")); expect(state.sequence.indexOf("domain-lock:claim_1")).toBeLessThan(state.sequence.indexOf("claim-lock:claim_1")); expect(state.sequence.indexOf("claim-lock:claim_1")).toBeLessThan(state.sequence.indexOf("acquisition-update-many")); expect(state.sequence.indexOf("acquisition-update")).toBeLessThan(state.sequence.indexOf("domain-cas")); expect(state.sequence.indexOf("domain-cas")).toBeLessThan(state.sequence.indexOf("claim-cas")); expect(state.sequence.indexOf("claim-cas")).toBeLessThan(state.sequence.indexOf("outbox:portal.domain.command.requested")); const billingLockQuery = state.queries.find((query) => query.sql.includes("hashtextextended('portal-domain-billing:")); expect(billingLockQuery).toMatchObject({ values: ["tenant_1", "claim_1"] }); expect(billingLockQuery?.sql).toContain("hashtextextended('portal-domain-billing:' || ? || ':' || ?, 26003)"); expect(state.acquisitions.get("acquisition_domain_1")).toMatchObject({ status: "active" }); expect(state.portalClaims.get("claim_1")).toMatchObject({ generation: 3, releasedAt: null, cooldownUntil: null }); expect(state.portalDomains.get("domain_1")).toMatchObject({ generation: 3, status: "provisioning", disabledReason: null, paymentAcquisitionId: "acquisition_domain_1", }); expect(state.outboxEvents).toEqual( expect.arrayContaining([ expect.objectContaining({ eventType: "billing.product-acquisition.provider-side-effect", payload: expect.objectContaining({ action: "mark_lago_invoice_succeeded", invoiceExternalId: "invoice_domain_1" }), }), expect.objectContaining({ eventType: "portal.domain.command.requested", dispatchKey: "portal-domain:claim_1:3:provision", payload: expect.objectContaining({ claimId: "claim_1", generation: 3, action: "provision" }), }), ]) ); }); it("uses the same portal-domain fence before a refund revokes entitlement", async () => { const { claim, domain } = createPortalDomainState({ status: "active", disabledReason: null, deprovisioningStartedAt: null }); const client = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), acquisitions: new Map([ [ "acquisition_domain_1", { id: "acquisition_domain_1", tenantId: "tenant_1", subscriptionProductId: "product_domain", subscriptionPriceId: "price_domain", productKind: "one_time_setup", scopeKey: "portal-domain:claim_1", status: "active", version: 2, quantity: 1, invoiceExternalId: "invoice_domain_refund_1", tenantSubscriptionProductId: null, lagoSubscriptionId: null, }, ], ]), portalClaims: new Map([[claim.id, claim]]), portalDomains: new Map([[domain.id, domain]]), }); await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:portal-domain:refunded", productKind: "one_time_setup", productAcquisitionId: "acquisition_domain_1", productScopeKey: "portal-domain:claim_1", subscriptionProductId: "product_domain", subscriptionPriceId: "price_domain", ...productPaymentSyncFields("acquisition_domain_1", { paymentPaidAt: null }), invoiceExternalId: "invoice_domain_refund_1", status: "refunded", }, client ); const state = getFakeState(client); expect(state.sequence.indexOf("advisory:claim_1")).toBeLessThan(state.sequence.indexOf("domain-lock:claim_1")); expect(state.sequence.indexOf("domain-lock:claim_1")).toBeLessThan(state.sequence.indexOf("claim-lock:claim_1")); expect(state.sequence.indexOf("claim-lock:claim_1")).toBeLessThan(state.sequence.indexOf("acquisition-update-many")); expect(state.acquisitions.get("acquisition_domain_1")).toMatchObject({ status: "refunded" }); expect(state.sequence).not.toContain("domain-cas"); }); it("recovers a paid domain when the old deprovision acknowledgement won first", async () => { const completedAt = new Date("2026-07-17T09:30:00.000Z"); const cooldownUntil = new Date("2026-08-16T09:30:00.000Z"); const receivedAt = new Date("2026-07-17T10:00:00.000Z"); const { claim, domain } = createPortalDomainState({ status: "cooldown", deprovisionedAt: completedAt, cooldownUntil, controllerResultContentHash: "result_2", controllerResultAttempt: 1, controllerResultStatus: "deprovisioned", }); claim.releasedAt = completedAt; claim.cooldownUntil = cooldownUntil; const client = createFakeClient({ products: [{ id: "product_domain", code: "customer_portal_domain_setup", kind: "one_time_setup" }], subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), acquisitions: new Map([ [ "acquisition_domain_1", { id: "acquisition_domain_1", tenantId: "tenant_1", subscriptionProductId: "product_domain", subscriptionPriceId: "price_domain", productKind: "one_time_setup", scopeKey: "portal-domain:claim_1", status: "payment_pending", version: 1, quantity: 1, invoiceExternalId: "invoice_domain_recovery_1", tenantSubscriptionProductId: null, lagoSubscriptionId: null, }, ], ]), portalClaims: new Map([[claim.id, claim]]), portalDomains: new Map([[domain.id, domain]]), }); await applyMolliePaymentSync( { tenantId: "tenant_1", eventKey: "mollie:portal-domain:paid-after-ack", productKind: "one_time_setup", productAcquisitionId: "acquisition_domain_1", productScopeKey: "portal-domain:claim_1", subscriptionProductId: "product_domain", subscriptionPriceId: "price_domain", ...productPaymentSyncFields("acquisition_domain_1"), invoiceExternalId: "invoice_domain_recovery_1", status: "paid", receivedAt, }, client ); const state = getFakeState(client); expect(state.sequence).toContain("domain-cas"); expect(state.portalClaims.get("claim_1")).toMatchObject({ generation: 3, releasedAt: null, cooldownUntil: null }); expect(state.portalDomains.get("domain_1")).toMatchObject({ generation: 3, status: "provisioning", deprovisionedAt: null, cooldownUntil: null, disabledReason: null, }); expect(state.outboxEvents).toContainEqual(expect.objectContaining({ dispatchKey: "portal-domain:claim_1:3:provision" })); }); it("fences a base subscription downgrade before changing portal entitlement", async () => { const { claim, domain } = createPortalDomainState({ status: "active", disabledReason: null, deprovisioningStartedAt: null }); const client = createFakeClient({ subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "business" }]]), portalClaims: new Map([[claim.id, claim]]), portalDomains: new Map([[domain.id, domain]]), }); await applyLagoSubscriptionSync({ tenantId: "tenant_1", eventKey: "lago:tenant_1:cancelled", status: "cancelled" }, client); const state = getFakeState(client); expect(state.sequence.indexOf("advisory:claim_1")).toBeLessThan(state.sequence.indexOf("domain-lock:claim_1")); expect(state.sequence.indexOf("domain-lock:claim_1")).toBeLessThan(state.sequence.indexOf("claim-lock:claim_1")); expect(state.sequence.indexOf("claim-lock:claim_1")).toBeLessThan(state.sequence.indexOf("subscription-upsert")); expect(state.subscriptions.get("tenant_1")).toMatchObject({ status: "cancelled" }); }); });