Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,301 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
applyLagoSubscriptionSync,
applyMolliePaymentSync,
BILLING_SYNC_IDEMPOTENCY_SCOPE,
normalizeLagoSubscriptionStatus,
normalizeMolliePaymentStatus,
type BillingSyncClient,
} from "./billing-sync.server.js";
type FakeState = {
idempotency: Map<string, { responseBody: unknown }>;
subscriptions: Map<string, Record<string, unknown>>;
products: Array<{ id: string; code?: string | null; lagoPlanCode?: string | null }>;
tenantProducts: Array<Record<string, unknown> & { id: string }>;
auditEvents: unknown[];
activities: unknown[];
};
type IdempotencyFindUniqueArgs = Parameters<BillingSyncClient["idempotencyKey"]["findUnique"]>[0];
type IdempotencyCreateArgs = Parameters<BillingSyncClient["idempotencyKey"]["create"]>[0];
type AuditCreateArgs = Parameters<BillingSyncClient["auditEvent"]["create"]>[0];
type ActivityCreateArgs = Parameters<BillingSyncClient["activity"]["create"]>[0];
type TenantSubscriptionUpsertArgs = Parameters<BillingSyncClient["tenantSubscription"]["upsert"]>[0];
type SubscriptionProductFindFirstArgs = Parameters<BillingSyncClient["subscriptionProduct"]["findFirst"]>[0];
type TenantSubscriptionProductFindFirstArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["findFirst"]>[0];
type TenantSubscriptionProductCreateArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["create"]>[0];
type TenantSubscriptionProductUpdateArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["update"]>[0];
type TenantSubscriptionProductUpdateManyArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["updateMany"]>[0];
function createFakeClient(state: Partial<FakeState> = {}): BillingSyncClient {
const fake: FakeState = {
idempotency: state.idempotency ?? new Map(),
subscriptions: state.subscriptions ?? new Map(),
products: state.products ?? [],
tenantProducts: state.tenantProducts ?? [],
auditEvents: state.auditEvents ?? [],
activities: state.activities ?? [],
};
return {
idempotencyKey: {
async findUnique({ where }: IdempotencyFindUniqueArgs) {
const row = fake.idempotency.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.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,
scope: where.idempotency_key_scope_key.scope,
key: where.idempotency_key_scope_key.key,
requestHash: "hash",
responseStatus: 200,
responseBody: row.responseBody,
responseHeaders: null,
} as never)
: null;
},
async create({ data }: IdempotencyCreateArgs) {
fake.idempotency.set(`${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 { id: `audit_${fake.auditEvents.length}`, createdAt: new Date(), ...data } as never;
},
},
activity: {
async create({ data }: ActivityCreateArgs) {
fake.activities.push(data);
return { id: `activity_${fake.activities.length}` };
},
},
tenantSubscription: {
async upsert({ where, create, update }: TenantSubscriptionUpsertArgs) {
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) {
return (
fake.products.find((product) =>
where.OR.some((condition) => condition.id === product.id || condition.code === product.code || condition.lagoPlanCode === product.lagoPlanCode)
) ?? null
);
},
},
tenantSubscriptionProduct: {
async findFirst({ where }: TenantSubscriptionProductFindFirstArgs) {
return (
fake.tenantProducts.find(
(product) =>
product.tenantSubscriptionId === where.tenantSubscriptionId &&
where.OR.some(
(condition) =>
condition.lagoSubscriptionId === product.lagoSubscriptionId ||
condition.subscriptionProductId === product.subscriptionProductId ||
condition.planCode === product.planCode
)
) ?? 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 (row.tenantSubscriptionId !== where.tenantSubscriptionId) 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 };
},
},
__state: fake,
} as unknown as BillingSyncClient;
}
function getFakeState(client: BillingSyncClient): FakeState {
return (client as unknown as { __state: FakeState }).__state;
}
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", "active"],
["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("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 result = await applyLagoSubscriptionSync(
{
tenantId: "tenant_1",
eventKey: "lago:sub_1:active",
lagoCustomerId: "cus_1",
lagoSubscriptionId: "sub_1",
status: "active",
planCode: "lago_pro",
seatQuantity: 7,
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,
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", planCode: "lago_pro", quantity: 7 });
expect(state.idempotency.has(`${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" });
});
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("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,
});
});
});