Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@hivegrid/billing",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./lago": "./src/lago.ts",
|
||||
"./mollie": "./src/mollie.ts",
|
||||
"./sandbox-flow": "./src/sandbox-flow.ts",
|
||||
"./sync-outbox": "./src/sync-outbox.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "pnpm run typecheck",
|
||||
"test": "vitest run src",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hivegrid/db": "workspace:*",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.0.0",
|
||||
"typescript": "^5.3.2",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from "./types.js";
|
||||
export * from "./lago.js";
|
||||
export * from "./mollie.js";
|
||||
export * from "./sync-outbox.js";
|
||||
export * from "./sandbox-flow.js";
|
||||
export * from "./webhook.js";
|
||||
@@ -0,0 +1,276 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createLagoBillingGateway, LagoBillingGatewayError, normalizeLagoApiUrl, redactLagoValue } from "./lago.js";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("LagoBillingGateway", () => {
|
||||
it("creates customers through the Lago API and maps the response", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
customer: {
|
||||
lago_id: "lago_customer_1",
|
||||
external_id: "tenant_1",
|
||||
name: "ACME GmbH",
|
||||
email: "billing@example.test",
|
||||
currency: "EUR",
|
||||
created_at: "2026-07-04T00:00:00Z",
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test/",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(
|
||||
gateway.createCustomer({
|
||||
tenantId: "tenant_1",
|
||||
name: "ACME GmbH",
|
||||
email: "billing@example.test",
|
||||
currency: "EUR",
|
||||
})
|
||||
).resolves.toEqual({
|
||||
provider: "lago",
|
||||
externalId: "tenant_1",
|
||||
providerCustomerId: "lago_customer_1",
|
||||
name: "ACME GmbH",
|
||||
email: "billing@example.test",
|
||||
currency: "EUR",
|
||||
createdAt: "2026-07-04T00:00:00Z",
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://lago.example.test/api/v1/customers",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.objectContaining({
|
||||
authorization: "Bearer secret_lago_key",
|
||||
"content-type": "application/json",
|
||||
}),
|
||||
body: JSON.stringify({
|
||||
customer: {
|
||||
external_id: "tenant_1",
|
||||
name: "ACME GmbH",
|
||||
email: "billing@example.test",
|
||||
currency: "EUR",
|
||||
},
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("creates plan subscriptions without storing seat count as unsupported Lago usage", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
subscription: {
|
||||
lago_id: "lago_subscription_1",
|
||||
external_id: "sub_tenant_1_business",
|
||||
external_customer_id: "tenant_1",
|
||||
plan_code: "business",
|
||||
status: "active",
|
||||
name: "business (5 seats)",
|
||||
current_billing_period_started_at: "2026-07-01T00:00:00Z",
|
||||
current_billing_period_ending_at: "2026-08-01T00:00:00Z",
|
||||
created_at: "2026-07-04T00:00:00Z",
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
const subscription = await gateway.createSubscription({
|
||||
tenantId: "tenant_1",
|
||||
subscriptionExternalId: "sub_tenant_1_business",
|
||||
planCode: "business",
|
||||
seatQuantity: 5,
|
||||
subscriptionAt: new Date("2026-07-04T00:00:00Z"),
|
||||
});
|
||||
|
||||
expect(subscription).toMatchObject({
|
||||
provider: "lago",
|
||||
externalId: "sub_tenant_1_business",
|
||||
providerSubscriptionId: "lago_subscription_1",
|
||||
externalCustomerId: "tenant_1",
|
||||
planCode: "business",
|
||||
status: "active",
|
||||
});
|
||||
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
|
||||
expect(request.subscription).toMatchObject({
|
||||
external_customer_id: "tenant_1",
|
||||
external_id: "sub_tenant_1_business",
|
||||
plan_code: "business",
|
||||
billing_time: "anniversary",
|
||||
subscription_at: "2026-07-04T00:00:00.000Z",
|
||||
});
|
||||
expect(request.subscription).not.toHaveProperty("seatQuantity");
|
||||
});
|
||||
|
||||
it("reads invoice status with optional tenant filter", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
invoices: [
|
||||
{
|
||||
lago_id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
external_customer_id: "tenant_1",
|
||||
status: "finalized",
|
||||
payment_status: "succeeded",
|
||||
invoice_type: "subscription",
|
||||
currency: "EUR",
|
||||
total_amount_cents: 4900,
|
||||
issuing_date: "2026-07-04",
|
||||
file_url: "https://files.example.test/invoice_1.pdf",
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(gateway.listInvoices({ tenantId: "tenant_1", page: 2, perPage: 10 })).resolves.toEqual([
|
||||
{
|
||||
provider: "lago",
|
||||
providerInvoiceId: "invoice_1",
|
||||
number: "LAG-001",
|
||||
externalCustomerId: "tenant_1",
|
||||
status: "finalized",
|
||||
paymentStatus: "succeeded",
|
||||
invoiceType: "subscription",
|
||||
currency: "EUR",
|
||||
totalAmountCents: 4900,
|
||||
issuingDate: "2026-07-04",
|
||||
fileUrl: "https://files.example.test/invoice_1.pdf",
|
||||
},
|
||||
]);
|
||||
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices?external_customer_id=tenant_1&page=2&per_page=10");
|
||||
});
|
||||
|
||||
it("downloads an invoice and maps the generated file url", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
invoice: {
|
||||
lago_id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
status: "finalized",
|
||||
payment_status: "succeeded",
|
||||
invoice_type: "subscription",
|
||||
currency: "EUR",
|
||||
total_amount_cents: 4900,
|
||||
issuing_date: "2026-07-04",
|
||||
file_url: "https://files.example.test/invoice_1.pdf",
|
||||
customer: {
|
||||
external_id: "tenant_1",
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(gateway.downloadInvoice("invoice_1")).resolves.toMatchObject({
|
||||
providerInvoiceId: "invoice_1",
|
||||
externalCustomerId: "tenant_1",
|
||||
fileUrl: "https://files.example.test/invoice_1.pdf",
|
||||
});
|
||||
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices/invoice_1/download");
|
||||
expect(fetchImpl.mock.calls[0]?.[1]).toMatchObject({ method: "POST" });
|
||||
});
|
||||
|
||||
it("updates an invoice payment status", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse({
|
||||
invoice: {
|
||||
lago_id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
external_customer_id: "tenant_1",
|
||||
status: "finalized",
|
||||
payment_status: "succeeded",
|
||||
invoice_type: "subscription",
|
||||
currency: "EUR",
|
||||
total_amount_cents: 99900,
|
||||
issuing_date: "2026-07-06",
|
||||
file_url: "https://files.example.test/invoice_1.pdf",
|
||||
},
|
||||
})
|
||||
);
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(gateway.updateInvoicePaymentStatus("invoice_1", "succeeded")).resolves.toMatchObject({
|
||||
providerInvoiceId: "invoice_1",
|
||||
paymentStatus: "succeeded",
|
||||
});
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://lago.example.test/api/v1/invoices/invoice_1",
|
||||
expect.objectContaining({
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
invoice: {
|
||||
payment_status: "succeeded",
|
||||
},
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null on 404 reads and throws clear errors for failed calls", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => new Response("{}", { status: 404 }));
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(gateway.getCustomer("tenant_missing")).resolves.toBeNull();
|
||||
|
||||
fetchImpl.mockResolvedValueOnce(new Response("{}", { status: 500 }));
|
||||
await expect(gateway.listInvoices()).rejects.toMatchObject({
|
||||
name: "LagoBillingGatewayError",
|
||||
code: "REQUEST_FAILED",
|
||||
status: 500,
|
||||
message: "Lago request failed with status 500.",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects invalid configuration and invalid response shapes", async () => {
|
||||
expect(() => normalizeLagoApiUrl("file:///tmp/lago")).toThrow(LagoBillingGatewayError);
|
||||
expect(() => createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: " " })).toThrow(LagoBillingGatewayError);
|
||||
|
||||
const gateway = createLagoBillingGateway({
|
||||
apiUrl: "https://lago.example.test",
|
||||
apiKey: "secret_lago_key",
|
||||
fetchImpl: vi.fn<typeof fetch>(async () => jsonResponse({ customer: { external_id: "tenant_1" } })),
|
||||
});
|
||||
await expect(gateway.createCustomer({ tenantId: "tenant_1", name: "Tenant" })).rejects.toMatchObject({
|
||||
code: "RESPONSE_INVALID",
|
||||
message: "Lago response shape is invalid.",
|
||||
});
|
||||
});
|
||||
|
||||
it("redacts Lago IDs and tokens for diagnostics", () => {
|
||||
expect(redactLagoValue("secret_lago_key_123456")).toBe("secr…3456");
|
||||
expect(redactLagoValue("short")).toBe("[redacted]");
|
||||
expect(redactLagoValue(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,319 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type {
|
||||
BillingGateway,
|
||||
BillingGatewayCustomer,
|
||||
BillingGatewayCustomerInput,
|
||||
BillingGatewayInvoice,
|
||||
BillingGatewayInvoiceListInput,
|
||||
BillingGatewaySubscription,
|
||||
BillingGatewaySubscriptionInput,
|
||||
} from "./types.js";
|
||||
|
||||
const DEFAULT_LAGO_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_LAGO_PER_PAGE = 20;
|
||||
|
||||
export type LagoBillingGatewayConfig = {
|
||||
apiUrl: string;
|
||||
apiKey: string;
|
||||
timeoutMs?: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
};
|
||||
|
||||
export class LagoBillingGatewayError extends Error {
|
||||
readonly code: "CONFIG_INVALID" | "REQUEST_FAILED" | "RESPONSE_INVALID";
|
||||
readonly status?: number;
|
||||
|
||||
constructor(message: string, code: LagoBillingGatewayError["code"], status?: number) {
|
||||
super(message);
|
||||
this.name = "LagoBillingGatewayError";
|
||||
this.code = code;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
const nullableString = z.string().nullable().optional();
|
||||
|
||||
const lagoCustomerSchema = z.object({
|
||||
lago_id: z.string(),
|
||||
external_id: z.string(),
|
||||
name: nullableString,
|
||||
email: nullableString,
|
||||
currency: nullableString,
|
||||
created_at: nullableString,
|
||||
});
|
||||
|
||||
const lagoSubscriptionSchema = z.object({
|
||||
lago_id: z.string(),
|
||||
external_id: z.string(),
|
||||
external_customer_id: z.string(),
|
||||
plan_code: z.string(),
|
||||
status: z.string().nullable().optional(),
|
||||
name: nullableString,
|
||||
current_billing_period_started_at: nullableString,
|
||||
current_billing_period_ending_at: nullableString,
|
||||
created_at: nullableString,
|
||||
});
|
||||
|
||||
const lagoInvoiceSchema = z.object({
|
||||
lago_id: z.string(),
|
||||
number: nullableString,
|
||||
external_customer_id: nullableString,
|
||||
customer: z
|
||||
.object({
|
||||
external_id: nullableString,
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
status: z.string().nullable().optional(),
|
||||
payment_status: z.string().nullable().optional(),
|
||||
invoice_type: nullableString,
|
||||
currency: nullableString,
|
||||
total_amount_cents: z.number().nullable().optional(),
|
||||
issuing_date: nullableString,
|
||||
file_url: nullableString,
|
||||
});
|
||||
|
||||
const customerResponseSchema = z.object({ customer: lagoCustomerSchema });
|
||||
const subscriptionResponseSchema = z.object({ subscription: lagoSubscriptionSchema });
|
||||
const invoiceResponseSchema = z.object({ invoice: lagoInvoiceSchema });
|
||||
const invoicesResponseSchema = z.object({ invoices: z.array(lagoInvoiceSchema) });
|
||||
|
||||
type LagoCustomer = z.infer<typeof lagoCustomerSchema>;
|
||||
type LagoSubscription = z.infer<typeof lagoSubscriptionSchema>;
|
||||
type LagoInvoice = z.infer<typeof lagoInvoiceSchema>;
|
||||
|
||||
export function createLagoBillingGateway(config: LagoBillingGatewayConfig): BillingGateway {
|
||||
return new LagoBillingGateway(config);
|
||||
}
|
||||
|
||||
export function normalizeLagoApiUrl(apiUrl: string): string {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(apiUrl);
|
||||
} catch {
|
||||
throw new LagoBillingGatewayError("Lago API URL must be an absolute URL.", "CONFIG_INVALID");
|
||||
}
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
throw new LagoBillingGatewayError("Lago API URL must use http or https.", "CONFIG_INVALID");
|
||||
}
|
||||
url.pathname = url.pathname.replace(/\/+$/u, "");
|
||||
return url.toString().replace(/\/$/u, "");
|
||||
}
|
||||
|
||||
export function redactLagoValue(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
if (value.length <= 8) return "[redacted]";
|
||||
return `${value.slice(0, 4)}…${value.slice(-4)}`;
|
||||
}
|
||||
|
||||
class LagoBillingGateway implements BillingGateway {
|
||||
private readonly apiUrl: string;
|
||||
private readonly apiKey: string;
|
||||
private readonly timeoutMs: number;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
|
||||
constructor(config: LagoBillingGatewayConfig) {
|
||||
this.apiUrl = normalizeLagoApiUrl(config.apiUrl);
|
||||
this.apiKey = config.apiKey.trim();
|
||||
if (!this.apiKey) {
|
||||
throw new LagoBillingGatewayError("Lago API key is required.", "CONFIG_INVALID");
|
||||
}
|
||||
this.timeoutMs = normalizeTimeout(config.timeoutMs);
|
||||
this.fetchImpl = config.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
async createCustomer(input: BillingGatewayCustomerInput): Promise<BillingGatewayCustomer> {
|
||||
const response = await this.request("/customers", {
|
||||
method: "POST",
|
||||
body: {
|
||||
customer: {
|
||||
external_id: input.tenantId,
|
||||
name: input.name,
|
||||
...(input.email ? { email: input.email } : {}),
|
||||
...(input.currency ? { currency: input.currency } : {}),
|
||||
...(input.country ? { country: input.country } : {}),
|
||||
...(input.timezone ? { timezone: input.timezone } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return toCustomer(parseLagoResponse(customerResponseSchema, response));
|
||||
}
|
||||
|
||||
async getCustomer(tenantId: string): Promise<BillingGatewayCustomer | null> {
|
||||
const response = await this.request(`/customers/${encodeURIComponent(tenantId)}`, { method: "GET", allowNotFound: true });
|
||||
return response === null ? null : toCustomer(parseLagoResponse(customerResponseSchema, response));
|
||||
}
|
||||
|
||||
async createSubscription(input: BillingGatewaySubscriptionInput): Promise<BillingGatewaySubscription> {
|
||||
assertPositiveSeatQuantity(input.seatQuantity);
|
||||
const response = await this.request("/subscriptions", {
|
||||
method: "POST",
|
||||
body: {
|
||||
subscription: {
|
||||
external_customer_id: input.tenantId,
|
||||
external_id: input.subscriptionExternalId,
|
||||
plan_code: input.planCode,
|
||||
name: input.name ?? `${input.planCode} (${input.seatQuantity} seats)`,
|
||||
billing_time: "anniversary",
|
||||
...(input.subscriptionAt ? { subscription_at: toIsoString(input.subscriptionAt) } : {}),
|
||||
...(input.endingAt ? { ending_at: toIsoString(input.endingAt) } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
|
||||
}
|
||||
|
||||
async getSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null> {
|
||||
const response = await this.request(`/subscriptions/${encodeURIComponent(subscriptionExternalId)}`, { method: "GET", allowNotFound: true });
|
||||
return response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
|
||||
}
|
||||
|
||||
async listInvoices(input: BillingGatewayInvoiceListInput = {}): Promise<BillingGatewayInvoice[]> {
|
||||
const query = new URLSearchParams();
|
||||
if (input.tenantId) query.set("external_customer_id", input.tenantId);
|
||||
query.set("page", String(input.page ?? 1));
|
||||
query.set("per_page", String(input.perPage ?? DEFAULT_LAGO_PER_PAGE));
|
||||
const response = await this.request(`/invoices?${query.toString()}`, { method: "GET" });
|
||||
return parseLagoResponse(invoicesResponseSchema, response).invoices.map(toInvoice);
|
||||
}
|
||||
|
||||
async downloadInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null> {
|
||||
const id = providerInvoiceId.trim();
|
||||
if (!id) {
|
||||
throw new LagoBillingGatewayError("Invoice id is required.", "CONFIG_INVALID");
|
||||
}
|
||||
const response = await this.request(`/invoices/${encodeURIComponent(id)}/download`, { method: "POST", allowNotFound: true });
|
||||
return response === null ? null : toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
|
||||
}
|
||||
|
||||
async updateInvoicePaymentStatus(providerInvoiceId: string, paymentStatus: BillingGatewayInvoice["paymentStatus"]): Promise<BillingGatewayInvoice> {
|
||||
const id = providerInvoiceId.trim();
|
||||
if (!id) {
|
||||
throw new LagoBillingGatewayError("Invoice id is required.", "CONFIG_INVALID");
|
||||
}
|
||||
if (paymentStatus !== "pending" && paymentStatus !== "succeeded" && paymentStatus !== "failed") {
|
||||
throw new LagoBillingGatewayError("Invoice payment status is invalid.", "CONFIG_INVALID");
|
||||
}
|
||||
const response = await this.request(`/invoices/${encodeURIComponent(id)}`, {
|
||||
method: "PUT",
|
||||
body: {
|
||||
invoice: {
|
||||
payment_status: paymentStatus,
|
||||
},
|
||||
},
|
||||
});
|
||||
return toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
|
||||
}
|
||||
|
||||
private async request(path: string, options: { method: "GET" | "POST" | "PUT"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.apiUrl}/api/v1${path}`, {
|
||||
method: options.method,
|
||||
headers: {
|
||||
authorization: `Bearer ${this.apiKey}`,
|
||||
accept: "application/json",
|
||||
...(options.body ? { "content-type": "application/json" } : {}),
|
||||
},
|
||||
body: options.body ? JSON.stringify(options.body) : undefined,
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.status === 404 && options.allowNotFound) {
|
||||
return null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new LagoBillingGatewayError(`Lago request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
if (error instanceof LagoBillingGatewayError) throw error;
|
||||
throw new LagoBillingGatewayError("Lago request failed.", "REQUEST_FAILED");
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseLagoResponse<T>(schema: z.ZodType<T>, response: unknown): T {
|
||||
const result = schema.safeParse(response);
|
||||
if (!result.success) {
|
||||
throw new LagoBillingGatewayError("Lago response shape is invalid.", "RESPONSE_INVALID");
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
function toCustomer(response: { customer: LagoCustomer }): BillingGatewayCustomer {
|
||||
const customer = response.customer;
|
||||
return {
|
||||
provider: "lago",
|
||||
externalId: customer.external_id,
|
||||
providerCustomerId: customer.lago_id,
|
||||
name: customer.name ?? null,
|
||||
email: customer.email ?? null,
|
||||
currency: customer.currency ?? null,
|
||||
createdAt: customer.created_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function toSubscription(response: { subscription: LagoSubscription }): BillingGatewaySubscription {
|
||||
const subscription = response.subscription;
|
||||
return {
|
||||
provider: "lago",
|
||||
externalId: subscription.external_id,
|
||||
providerSubscriptionId: subscription.lago_id,
|
||||
externalCustomerId: subscription.external_customer_id,
|
||||
planCode: subscription.plan_code,
|
||||
status: normalizeSubscriptionStatus(subscription.status),
|
||||
name: subscription.name ?? null,
|
||||
currentBillingPeriodStartedAt: subscription.current_billing_period_started_at ?? null,
|
||||
currentBillingPeriodEndingAt: subscription.current_billing_period_ending_at ?? null,
|
||||
createdAt: subscription.created_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function toInvoice(invoice: LagoInvoice): BillingGatewayInvoice {
|
||||
return {
|
||||
provider: "lago",
|
||||
providerInvoiceId: invoice.lago_id,
|
||||
number: invoice.number ?? null,
|
||||
externalCustomerId: invoice.external_customer_id ?? invoice.customer?.external_id ?? null,
|
||||
status: normalizeInvoiceStatus(invoice.status),
|
||||
paymentStatus: normalizePaymentStatus(invoice.payment_status),
|
||||
invoiceType: invoice.invoice_type ?? null,
|
||||
currency: invoice.currency ?? null,
|
||||
totalAmountCents: invoice.total_amount_cents ?? null,
|
||||
issuingDate: invoice.issuing_date ?? null,
|
||||
fileUrl: invoice.file_url ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeTimeout(timeoutMs: number | undefined): number {
|
||||
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_LAGO_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
function assertPositiveSeatQuantity(seatQuantity: number): void {
|
||||
if (!Number.isInteger(seatQuantity) || seatQuantity < 1) {
|
||||
throw new LagoBillingGatewayError("Seat quantity must be a positive integer.", "CONFIG_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function toIsoString(value: Date | string): string {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
|
||||
function normalizeSubscriptionStatus(value: string | null | undefined): BillingGatewaySubscription["status"] {
|
||||
if (value === "pending" || value === "active" || value === "terminated" || value === "canceled" || value === "cancelled") return value;
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizeInvoiceStatus(value: string | null | undefined): BillingGatewayInvoice["status"] {
|
||||
if (value === "draft" || value === "finalized" || value === "voided" || value === "failed" || value === "pending") return value;
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizePaymentStatus(value: string | null | undefined): BillingGatewayInvoice["paymentStatus"] {
|
||||
if (value === "pending" || value === "succeeded" || value === "failed") return value;
|
||||
return "unknown";
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createMolliePaymentGateway,
|
||||
MolliePaymentGatewayError,
|
||||
normalizeMollieApiUrl,
|
||||
parseMollieWebhookEvent,
|
||||
redactMollieValue,
|
||||
resolveMollieWebhookPayment,
|
||||
} from "./mollie.js";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function molliePayment(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "tr_123",
|
||||
status: "open",
|
||||
amount: { currency: "EUR", value: "49.00" },
|
||||
amountRefunded: { currency: "EUR", value: "0.00" },
|
||||
amountRemaining: { currency: "EUR", value: "49.00" },
|
||||
paidAt: null,
|
||||
expiresAt: "2026-07-05T00:00:00+00:00",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
paymentExternalId: "payment_1",
|
||||
lagoCustomerId: null,
|
||||
lagoSubscriptionId: null,
|
||||
planCode: null,
|
||||
seatQuantity: null,
|
||||
},
|
||||
_links: {
|
||||
checkout: { href: "https://www.mollie.com/checkout/select-method/tr_123" },
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("MolliePaymentGateway", () => {
|
||||
it("creates checkout payments without HiveGrid domain data in the Mollie payload", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment()));
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
profileId: "pfl_123",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
paymentExternalId: "payment_1",
|
||||
amountCents: 4900,
|
||||
currency: "eur",
|
||||
redirectUrl: "https://app.hivegrid.de/admin/billing/return?invoice=invoice_1",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
mollieCustomerId: "cst_123",
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
provider: "mollie",
|
||||
providerPaymentId: "tr_123",
|
||||
externalId: "payment_1",
|
||||
status: "open",
|
||||
amountCents: 4900,
|
||||
currency: "EUR",
|
||||
checkoutUrl: "https://www.mollie.com/checkout/select-method/tr_123",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
},
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledWith(
|
||||
"https://api.mollie.com/v2/payments",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.objectContaining({
|
||||
authorization: "Bearer test_mollie_key",
|
||||
"content-type": "application/json",
|
||||
}),
|
||||
})
|
||||
);
|
||||
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
|
||||
expect(request).toMatchObject({
|
||||
amount: { currency: "EUR", value: "49.00" },
|
||||
description: "Invoice invoice_1",
|
||||
redirectUrl: "https://app.hivegrid.de/admin/billing/return?invoice=invoice_1",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
profileId: "pfl_123",
|
||||
customerId: "cst_123",
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
paymentExternalId: "payment_1",
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(request)).not.toContain("business");
|
||||
expect(JSON.stringify(request)).not.toContain("seat");
|
||||
expect(JSON.stringify(request)).not.toContain("billing@example.test");
|
||||
});
|
||||
|
||||
it("verifies classic Mollie webhooks by parsing the id and refetching payment status", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse(
|
||||
molliePayment({
|
||||
status: "paid",
|
||||
paidAt: "2026-07-04T12:00:00+00:00",
|
||||
})
|
||||
)
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
const payment = await resolveMollieWebhookPayment(gateway, new URLSearchParams({ id: "tr_123" }));
|
||||
|
||||
expect(payment).toMatchObject({
|
||||
providerPaymentId: "tr_123",
|
||||
status: "paid",
|
||||
paidAt: "2026-07-04T12:00:00+00:00",
|
||||
});
|
||||
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://api.mollie.com/v2/payments/tr_123");
|
||||
});
|
||||
|
||||
it("maps refunded amounts to refunded payment status", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () =>
|
||||
jsonResponse(
|
||||
molliePayment({
|
||||
status: "paid",
|
||||
amountRefunded: { currency: "EUR", value: "49.00" },
|
||||
amountRemaining: { currency: "EUR", value: "0.00" },
|
||||
})
|
||||
)
|
||||
);
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(gateway.getPayment("tr_123")).resolves.toMatchObject({
|
||||
status: "refunded",
|
||||
amountRefundedCents: 4900,
|
||||
amountRemainingCents: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null on 404 reads and throws clear errors for failed calls", async () => {
|
||||
const fetchImpl = vi.fn<typeof fetch>(async () => new Response("{}", { status: 404 }));
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl,
|
||||
});
|
||||
|
||||
await expect(gateway.getPayment("tr_missing")).resolves.toBeNull();
|
||||
|
||||
fetchImpl.mockResolvedValueOnce(new Response("{}", { status: 500 }));
|
||||
await expect(
|
||||
gateway.createPayment({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
amountCents: 4900,
|
||||
currency: "EUR",
|
||||
redirectUrl: "https://app.hivegrid.de/return",
|
||||
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
name: "MolliePaymentGatewayError",
|
||||
code: "REQUEST_FAILED",
|
||||
status: 500,
|
||||
message: "Mollie request failed with status 500.",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects invalid config, invalid webhook payloads and invalid response shapes", async () => {
|
||||
expect(() => normalizeMollieApiUrl("file:///tmp/mollie")).toThrow(MolliePaymentGatewayError);
|
||||
expect(() => createMolliePaymentGateway({ apiKey: " " })).toThrow(MolliePaymentGatewayError);
|
||||
expect(() => parseMollieWebhookEvent({})).toThrow(MolliePaymentGatewayError);
|
||||
|
||||
const gateway = createMolliePaymentGateway({
|
||||
apiKey: "test_mollie_key",
|
||||
fetchImpl: vi.fn<typeof fetch>(async () => jsonResponse({ status: "paid" })),
|
||||
});
|
||||
await expect(gateway.getPayment("tr_123")).rejects.toMatchObject({
|
||||
code: "RESPONSE_INVALID",
|
||||
message: "Mollie response shape is invalid.",
|
||||
});
|
||||
});
|
||||
|
||||
it("redacts Mollie IDs and tokens for diagnostics", () => {
|
||||
expect(redactMollieValue("test_mollie_key_123456")).toBe("test…3456");
|
||||
expect(redactMollieValue("short")).toBe("[redacted]");
|
||||
expect(redactMollieValue(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { PaymentGateway, PaymentGatewayCreatePaymentInput, PaymentGatewayPayment, PaymentGatewayPaymentStatus } from "./types.js";
|
||||
|
||||
const DEFAULT_MOLLIE_API_URL = "https://api.mollie.com";
|
||||
const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000;
|
||||
|
||||
export type MolliePaymentGatewayConfig = {
|
||||
apiKey: string;
|
||||
apiUrl?: string;
|
||||
profileId?: string | null;
|
||||
timeoutMs?: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
};
|
||||
|
||||
export type MollieWebhookEvent = {
|
||||
providerPaymentId: string;
|
||||
};
|
||||
|
||||
export class MolliePaymentGatewayError extends Error {
|
||||
readonly code: "CONFIG_INVALID" | "REQUEST_FAILED" | "RESPONSE_INVALID" | "WEBHOOK_INVALID" | "WEBHOOK_PAYMENT_NOT_FOUND";
|
||||
readonly status?: number;
|
||||
|
||||
constructor(message: string, code: MolliePaymentGatewayError["code"], status?: number) {
|
||||
super(message);
|
||||
this.name = "MolliePaymentGatewayError";
|
||||
this.code = code;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
const amountSchema = z.object({
|
||||
currency: z.string().nullable().optional(),
|
||||
value: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
const metadataSchema = z
|
||||
.object({
|
||||
tenantId: z.string().nullable().optional(),
|
||||
invoiceExternalId: z.string().nullable().optional(),
|
||||
paymentExternalId: z.string().nullable().optional(),
|
||||
lagoCustomerId: z.string().nullable().optional(),
|
||||
lagoSubscriptionId: z.string().nullable().optional(),
|
||||
planCode: z.string().nullable().optional(),
|
||||
seatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional();
|
||||
|
||||
const molliePaymentSchema = z.object({
|
||||
id: z.string(),
|
||||
status: z.string().nullable().optional(),
|
||||
amount: amountSchema.nullable().optional(),
|
||||
amountRefunded: amountSchema.nullable().optional(),
|
||||
amountRemaining: amountSchema.nullable().optional(),
|
||||
paidAt: z.string().nullable().optional(),
|
||||
expiresAt: z.string().nullable().optional(),
|
||||
metadata: metadataSchema,
|
||||
_links: z
|
||||
.object({
|
||||
checkout: z
|
||||
.object({
|
||||
href: z.string().nullable().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
|
||||
|
||||
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): PaymentGateway {
|
||||
return new MolliePaymentGateway(config);
|
||||
}
|
||||
|
||||
export function normalizeMollieApiUrl(apiUrl: string | undefined): string {
|
||||
const rawUrl = apiUrl?.trim() || DEFAULT_MOLLIE_API_URL;
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(rawUrl);
|
||||
} catch {
|
||||
throw new MolliePaymentGatewayError("Mollie API URL must be an absolute URL.", "CONFIG_INVALID");
|
||||
}
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
throw new MolliePaymentGatewayError("Mollie API URL must use http or https.", "CONFIG_INVALID");
|
||||
}
|
||||
url.pathname = url.pathname.replace(/\/+$/u, "");
|
||||
return url.toString().replace(/\/$/u, "");
|
||||
}
|
||||
|
||||
export function redactMollieValue(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
if (value.length <= 8) return "[redacted]";
|
||||
return `${value.slice(0, 4)}…${value.slice(-4)}`;
|
||||
}
|
||||
|
||||
export function parseMollieWebhookEvent(input: URLSearchParams | FormData | Record<string, unknown>): MollieWebhookEvent {
|
||||
const id = getWebhookValue(input, "id")?.trim();
|
||||
if (!id) {
|
||||
throw new MolliePaymentGatewayError("Mollie webhook is missing payment id.", "WEBHOOK_INVALID");
|
||||
}
|
||||
return { providerPaymentId: id };
|
||||
}
|
||||
|
||||
export async function resolveMollieWebhookPayment(gateway: PaymentGateway, input: URLSearchParams | FormData | Record<string, unknown>): Promise<PaymentGatewayPayment> {
|
||||
const event = parseMollieWebhookEvent(input);
|
||||
const payment = await gateway.getPayment(event.providerPaymentId);
|
||||
if (!payment) {
|
||||
throw new MolliePaymentGatewayError("Mollie webhook payment could not be verified.", "WEBHOOK_PAYMENT_NOT_FOUND", 404);
|
||||
}
|
||||
return payment;
|
||||
}
|
||||
|
||||
class MolliePaymentGateway implements PaymentGateway {
|
||||
private readonly apiUrl: string;
|
||||
private readonly apiKey: string;
|
||||
private readonly profileId: string | null;
|
||||
private readonly timeoutMs: number;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
|
||||
constructor(config: MolliePaymentGatewayConfig) {
|
||||
this.apiUrl = normalizeMollieApiUrl(config.apiUrl);
|
||||
this.apiKey = config.apiKey.trim();
|
||||
if (!this.apiKey) {
|
||||
throw new MolliePaymentGatewayError("Mollie API key is required.", "CONFIG_INVALID");
|
||||
}
|
||||
this.profileId = config.profileId?.trim() || null;
|
||||
this.timeoutMs = normalizeTimeout(config.timeoutMs);
|
||||
this.fetchImpl = config.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
async createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment> {
|
||||
validateCreatePaymentInput(input);
|
||||
const response = await this.request("/payments", {
|
||||
method: "POST",
|
||||
body: {
|
||||
amount: {
|
||||
currency: input.currency.toUpperCase(),
|
||||
value: centsToMollieValue(input.amountCents),
|
||||
},
|
||||
description: input.description?.trim() || `Invoice ${input.invoiceExternalId}`,
|
||||
redirectUrl: input.redirectUrl,
|
||||
webhookUrl: input.webhookUrl,
|
||||
...(this.profileId ? { profileId: this.profileId } : {}),
|
||||
...(input.mollieCustomerId ? { customerId: input.mollieCustomerId } : {}),
|
||||
metadata: {
|
||||
tenantId: input.tenantId,
|
||||
invoiceExternalId: input.invoiceExternalId,
|
||||
...(input.paymentExternalId ? { paymentExternalId: input.paymentExternalId } : {}),
|
||||
...(input.lagoCustomerId ? { lagoCustomerId: input.lagoCustomerId } : {}),
|
||||
...(input.lagoSubscriptionId ? { lagoSubscriptionId: input.lagoSubscriptionId } : {}),
|
||||
...(input.planCode ? { planCode: input.planCode } : {}),
|
||||
...(input.seatQuantity ? { seatQuantity: input.seatQuantity } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return toPayment(parseMollieResponse(response));
|
||||
}
|
||||
|
||||
async getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null> {
|
||||
const id = providerPaymentId.trim();
|
||||
if (!id) {
|
||||
throw new MolliePaymentGatewayError("Mollie payment id is required.", "CONFIG_INVALID");
|
||||
}
|
||||
const response = await this.request(`/payments/${encodeURIComponent(id)}`, { method: "GET", allowNotFound: true });
|
||||
return response === null ? null : toPayment(parseMollieResponse(response));
|
||||
}
|
||||
|
||||
private async request(path: string, options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.apiUrl}/v2${path}`, {
|
||||
method: options.method,
|
||||
headers: {
|
||||
authorization: `Bearer ${this.apiKey}`,
|
||||
accept: "application/json",
|
||||
...(options.body ? { "content-type": "application/json" } : {}),
|
||||
},
|
||||
body: options.body ? JSON.stringify(options.body) : undefined,
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.status === 404 && options.allowNotFound) {
|
||||
return null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new MolliePaymentGatewayError(`Mollie request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
if (error instanceof MolliePaymentGatewayError) throw error;
|
||||
throw new MolliePaymentGatewayError("Mollie request failed.", "REQUEST_FAILED");
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseMollieResponse(response: unknown): MolliePaymentResponse {
|
||||
const result = molliePaymentSchema.safeParse(response);
|
||||
if (!result.success) {
|
||||
throw new MolliePaymentGatewayError("Mollie response shape is invalid.", "RESPONSE_INVALID");
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment {
|
||||
const metadata = payment.metadata ?? {};
|
||||
return {
|
||||
provider: "mollie",
|
||||
providerPaymentId: payment.id,
|
||||
externalId: metadata.paymentExternalId ?? null,
|
||||
status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value),
|
||||
amountCents: mollieValueToCents(payment.amount?.value),
|
||||
amountRefundedCents: mollieValueToCents(payment.amountRefunded?.value),
|
||||
amountRemainingCents: mollieValueToCents(payment.amountRemaining?.value),
|
||||
currency: payment.amount?.currency ?? null,
|
||||
checkoutUrl: payment._links?.checkout?.href ?? null,
|
||||
paidAt: payment.paidAt ?? null,
|
||||
expiresAt: payment.expiresAt ?? null,
|
||||
metadata: {
|
||||
tenantId: metadata.tenantId ?? null,
|
||||
invoiceExternalId: metadata.invoiceExternalId ?? null,
|
||||
paymentExternalId: metadata.paymentExternalId ?? null,
|
||||
lagoCustomerId: metadata.lagoCustomerId ?? null,
|
||||
lagoSubscriptionId: metadata.lagoSubscriptionId ?? null,
|
||||
planCode: metadata.planCode ?? null,
|
||||
seatQuantity: normalizeMetadataSeatQuantity(metadata.seatQuantity),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeMetadataSeatQuantity(value: string | number | null | undefined): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
const normalized = Math.trunc(value);
|
||||
return normalized > 0 ? normalized : null;
|
||||
}
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const normalized = Number.parseInt(value, 10);
|
||||
return Number.isFinite(normalized) && normalized > 0 ? normalized : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): void {
|
||||
if (!input.tenantId.trim()) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID");
|
||||
if (!input.invoiceExternalId.trim()) throw new MolliePaymentGatewayError("Invoice reference is required.", "CONFIG_INVALID");
|
||||
if (!Number.isInteger(input.amountCents) || input.amountCents < 1) {
|
||||
throw new MolliePaymentGatewayError("Amount must be a positive cent integer.", "CONFIG_INVALID");
|
||||
}
|
||||
if (!/^[A-Za-z]{3}$/u.test(input.currency)) {
|
||||
throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID");
|
||||
}
|
||||
assertHttpUrl(input.redirectUrl, "Redirect URL");
|
||||
assertHttpUrl(input.webhookUrl, "Webhook URL");
|
||||
}
|
||||
|
||||
function assertHttpUrl(value: string, label: string): void {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new MolliePaymentGatewayError(`${label} must be an absolute URL.`, "CONFIG_INVALID");
|
||||
}
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
throw new MolliePaymentGatewayError(`${label} must use http or https.`, "CONFIG_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTimeout(timeoutMs: number | undefined): number {
|
||||
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_MOLLIE_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
function centsToMollieValue(amountCents: number): string {
|
||||
return (amountCents / 100).toFixed(2);
|
||||
}
|
||||
|
||||
function mollieValueToCents(value: string | null | undefined): number | null {
|
||||
if (!value) return null;
|
||||
const normalized = value.trim();
|
||||
if (!/^-?\d+(\.\d{1,2})?$/u.test(normalized)) return null;
|
||||
return Math.round(Number(normalized) * 100);
|
||||
}
|
||||
|
||||
function normalizePaymentStatus(status: string | null | undefined, refundedValue: string | null | undefined): PaymentGatewayPaymentStatus {
|
||||
const refundedCents = mollieValueToCents(refundedValue);
|
||||
if (typeof refundedCents === "number" && refundedCents > 0) return "refunded";
|
||||
if (
|
||||
status === "open" ||
|
||||
status === "pending" ||
|
||||
status === "authorized" ||
|
||||
status === "paid" ||
|
||||
status === "failed" ||
|
||||
status === "expired" ||
|
||||
status === "canceled"
|
||||
) {
|
||||
return status;
|
||||
}
|
||||
if (status === "charged_back") return "charged_back";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function getWebhookValue(input: URLSearchParams | FormData | Record<string, unknown>, key: string): string | null {
|
||||
if (input instanceof URLSearchParams || input instanceof FormData) {
|
||||
const value = input.get(key);
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
const value = input[key];
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runBillingSandboxFlow } from "./sandbox-flow.js";
|
||||
|
||||
describe("runBillingSandboxFlow", () => {
|
||||
it("proves the BILL-07 Lago/Mollie billing core with deterministic sandbox stubs", async () => {
|
||||
const result = await runBillingSandboxFlow({
|
||||
runId: "unit",
|
||||
now: new Date("2026-07-04T10:00:00.000Z"),
|
||||
moduleKey: "crm-basic",
|
||||
seatQuantity: 5,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.tenantId).toBe("hg-stg-bill-07-unit");
|
||||
expect(result.customer.providerCustomerId).toBe("lago_customer_hg-stg-bill-07-unit");
|
||||
expect(result.subscription.planCode).toBe("hg-stg-plan-bill-07-unit");
|
||||
expect(result.invoice.providerInvoiceId).toBe("lago_invoice_subscription-unit");
|
||||
expect(result.payment.status).toBe("paid");
|
||||
expect(result.activeState).toMatchObject({
|
||||
status: "active",
|
||||
readOnly: false,
|
||||
planCode: "hg-stg-plan-bill-07-unit",
|
||||
seatQuantity: 5,
|
||||
lastInvoiceExternalId: "lago_invoice_subscription-unit",
|
||||
lastPaymentExternalId: "tr_payment-unit",
|
||||
});
|
||||
expect(result.gate).toMatchObject({
|
||||
moduleKey: "crm-basic",
|
||||
activeAllowed: true,
|
||||
activeReadOnly: false,
|
||||
failedReadOnly: true,
|
||||
pastDueReadOnly: true,
|
||||
frozenReadOnly: true,
|
||||
});
|
||||
expect(result.failedState.status).toBe("past_due");
|
||||
expect(result.pastDueState.status).toBe("past_due");
|
||||
expect(result.frozenState.status).toBe("frozen");
|
||||
expect(result.referencesVisible).toBe(true);
|
||||
expect(result.audit.auditEvents).toBeGreaterThanOrEqual(5);
|
||||
expect(result.audit.activities).toBeGreaterThanOrEqual(5);
|
||||
expect(result.steps.map((step) => [step.key, step.ok])).toEqual([
|
||||
["lago.customer", true],
|
||||
["lago.subscription", true],
|
||||
["mollie.payment", true],
|
||||
["local.sync", true],
|
||||
["module.gate", true],
|
||||
["references.audit", true],
|
||||
["negative.failed-expired", true],
|
||||
["negative.frozen", true],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,595 @@
|
||||
import {
|
||||
applyLagoSubscriptionSync,
|
||||
applyMolliePaymentSync,
|
||||
type BillingSyncClient,
|
||||
type BillingSyncResult,
|
||||
} from "@hivegrid/db/billing-sync.server";
|
||||
import {
|
||||
resolveTenantBillingState,
|
||||
type TenantBillingState,
|
||||
type TenantBillingStateClient,
|
||||
} from "@hivegrid/db/billing-domain.server";
|
||||
|
||||
import type {
|
||||
BillingGateway,
|
||||
BillingGatewayCustomer,
|
||||
BillingGatewayInvoice,
|
||||
BillingGatewaySubscription,
|
||||
PaymentGateway,
|
||||
PaymentGatewayCreatePaymentInput,
|
||||
PaymentGatewayPayment,
|
||||
PaymentGatewayPaymentStatus,
|
||||
} from "./types.js";
|
||||
|
||||
export type BillingSandboxFlowInput = {
|
||||
runId?: string;
|
||||
tenantId?: string;
|
||||
tenantName?: string;
|
||||
planCode?: string;
|
||||
seatQuantity?: number;
|
||||
moduleKey?: string;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type BillingSandboxFlowStep = {
|
||||
key: string;
|
||||
ok: boolean;
|
||||
detail: string;
|
||||
};
|
||||
|
||||
export type BillingSandboxFlowResult = {
|
||||
ok: boolean;
|
||||
mode: "stub";
|
||||
runId: string;
|
||||
tenantId: string;
|
||||
planCode: string;
|
||||
seatQuantity: number;
|
||||
customer: BillingGatewayCustomer;
|
||||
subscription: BillingGatewaySubscription;
|
||||
invoice: BillingGatewayInvoice;
|
||||
payment: PaymentGatewayPayment;
|
||||
activeState: TenantBillingState;
|
||||
failedState: TenantBillingState;
|
||||
pastDueState: TenantBillingState;
|
||||
frozenState: TenantBillingState;
|
||||
syncResults: {
|
||||
lagoActive: BillingSyncResult;
|
||||
molliePaid: BillingSyncResult;
|
||||
mollieFailed: BillingSyncResult;
|
||||
mollieExpired: BillingSyncResult;
|
||||
lagoFrozen: BillingSyncResult;
|
||||
};
|
||||
gate: {
|
||||
moduleKey: string;
|
||||
activeAllowed: boolean;
|
||||
activeReadOnly: boolean;
|
||||
failedReadOnly: boolean;
|
||||
pastDueReadOnly: boolean;
|
||||
frozenReadOnly: boolean;
|
||||
};
|
||||
audit: {
|
||||
auditEvents: number;
|
||||
activities: number;
|
||||
};
|
||||
referencesVisible: boolean;
|
||||
steps: BillingSandboxFlowStep[];
|
||||
};
|
||||
|
||||
type SandboxProduct = {
|
||||
id: string;
|
||||
code: string;
|
||||
lagoPlanCode: string;
|
||||
title: string;
|
||||
features: Array<{
|
||||
code: string;
|
||||
name: string;
|
||||
order: number;
|
||||
title: string;
|
||||
type: number;
|
||||
value: number;
|
||||
quotaValue: unknown | null;
|
||||
accumulate: boolean;
|
||||
}>;
|
||||
};
|
||||
|
||||
type SandboxState = {
|
||||
idempotency: Map<string, { responseBody: unknown }>;
|
||||
subscriptions: Map<string, Record<string, unknown> & { id: string; tenantId: string }>;
|
||||
products: SandboxProduct[];
|
||||
tenantProducts: Array<Record<string, unknown> & { id: string; tenantSubscriptionId: string }>;
|
||||
auditEvents: unknown[];
|
||||
activities: unknown[];
|
||||
customers: Map<string, BillingGatewayCustomer>;
|
||||
providerSubscriptions: Map<string, BillingGatewaySubscription>;
|
||||
invoices: Map<string, BillingGatewayInvoice[]>;
|
||||
payments: Map<string, PaymentGatewayPayment>;
|
||||
};
|
||||
|
||||
const INCLUDED_LIMIT_TYPE = 1;
|
||||
|
||||
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 TenantSubscriptionFindUniqueArgs = Parameters<TenantBillingStateClient["tenantSubscription"]["findUnique"]>[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 normalizeRunId(value: string | undefined): string {
|
||||
const fallback = `bill-07-${Date.now().toString(36)}`;
|
||||
return (value ?? fallback).trim().toLowerCase().replace(/[^a-z0-9-]+/gu, "-").replace(/^-+|-+$/gu, "") || fallback;
|
||||
}
|
||||
|
||||
function positiveSeatQuantity(value: number | undefined): number {
|
||||
return Number.isInteger(value) && value && value > 0 ? value : 3;
|
||||
}
|
||||
|
||||
function createSandboxState(input: Required<Pick<BillingSandboxFlowInput, "planCode" | "moduleKey">>): SandboxState {
|
||||
return {
|
||||
idempotency: new Map(),
|
||||
subscriptions: new Map(),
|
||||
products: [
|
||||
{
|
||||
id: `product_${input.planCode}`,
|
||||
code: input.planCode,
|
||||
lagoPlanCode: input.planCode,
|
||||
title: `Sandbox ${input.planCode}`,
|
||||
features: [
|
||||
{
|
||||
code: input.moduleKey,
|
||||
name: input.moduleKey,
|
||||
order: 1,
|
||||
title: "Sandbox module",
|
||||
type: INCLUDED_LIMIT_TYPE,
|
||||
value: 0,
|
||||
quotaValue: null,
|
||||
accumulate: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
tenantProducts: [],
|
||||
auditEvents: [],
|
||||
activities: [],
|
||||
customers: new Map(),
|
||||
providerSubscriptions: new Map(),
|
||||
invoices: new Map(),
|
||||
payments: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBillingStateClient {
|
||||
return {
|
||||
idempotencyKey: {
|
||||
async findUnique({ where }: IdempotencyFindUniqueArgs) {
|
||||
const row = state.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: "sandbox",
|
||||
responseStatus: 200,
|
||||
responseBody: row.responseBody,
|
||||
responseHeaders: null,
|
||||
} as never)
|
||||
: null;
|
||||
},
|
||||
async create({ data }: IdempotencyCreateArgs) {
|
||||
state.idempotency.set(`${data.scope}:${data.key}`, { responseBody: data.responseBody });
|
||||
return { id: `idem_${state.idempotency.size}`, createdAt: new Date(), updatedAt: new Date(), ...data } as never;
|
||||
},
|
||||
},
|
||||
auditEvent: {
|
||||
async findFirst() {
|
||||
return null;
|
||||
},
|
||||
async create({ data }: AuditCreateArgs) {
|
||||
state.auditEvents.push(data);
|
||||
return { id: `audit_${state.auditEvents.length}`, createdAt: new Date(), ...data } as never;
|
||||
},
|
||||
},
|
||||
activity: {
|
||||
async create({ data }: ActivityCreateArgs) {
|
||||
state.activities.push(data);
|
||||
return { id: `activity_${state.activities.length}` };
|
||||
},
|
||||
},
|
||||
tenantSubscription: {
|
||||
async upsert({ where, create, update }: TenantSubscriptionUpsertArgs) {
|
||||
const current = state.subscriptions.get(where.tenantId);
|
||||
const next = {
|
||||
...(current ?? { id: `tenant_subscription_${state.subscriptions.size + 1}` }),
|
||||
...(current ? update : create),
|
||||
tenantId: where.tenantId,
|
||||
};
|
||||
state.subscriptions.set(where.tenantId, next as Record<string, unknown> & { id: string; tenantId: string });
|
||||
return next as never;
|
||||
},
|
||||
async findUnique({ where }: TenantSubscriptionFindUniqueArgs) {
|
||||
const subscription = state.subscriptions.get(where.tenantId);
|
||||
if (!subscription) return null;
|
||||
const products = state.tenantProducts
|
||||
.filter((tenantProduct) => tenantProduct.tenantSubscriptionId === subscription.id)
|
||||
.map((tenantProduct) => {
|
||||
const product = state.products.find((item) => item.id === tenantProduct.subscriptionProductId);
|
||||
if (!product) return null;
|
||||
return {
|
||||
...tenantProduct,
|
||||
createdAt: tenantProduct.createdAt instanceof Date ? tenantProduct.createdAt : new Date("2026-07-04T00:00:00.000Z"),
|
||||
subscriptionProduct: product,
|
||||
};
|
||||
})
|
||||
.filter((product): product is NonNullable<typeof product> => Boolean(product));
|
||||
return { ...subscription, products } as never;
|
||||
},
|
||||
},
|
||||
subscriptionProduct: {
|
||||
async findFirst({ where }: SubscriptionProductFindFirstArgs) {
|
||||
return (
|
||||
state.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 (
|
||||
state.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_${state.tenantProducts.length + 1}`, createdAt: new Date("2026-07-04T00:00:00.000Z"), ...data };
|
||||
state.tenantProducts.push(row as unknown as Record<string, unknown> & { id: string; tenantSubscriptionId: string });
|
||||
return row;
|
||||
},
|
||||
async update({ where, data }: TenantSubscriptionProductUpdateArgs) {
|
||||
const index = state.tenantProducts.findIndex((row) => row.id === where.id);
|
||||
state.tenantProducts[index] = { ...state.tenantProducts[index], ...data };
|
||||
return state.tenantProducts[index];
|
||||
},
|
||||
async updateMany({ where, data }: TenantSubscriptionProductUpdateManyArgs) {
|
||||
// Mirrors endOtherActivePlanProducts' where shape: scalar tenantSubscriptionId,
|
||||
// id:{not}, cancelledAt:null and an OR over endsAt (null | { gt }).
|
||||
const w = where as {
|
||||
tenantSubscriptionId?: string;
|
||||
id?: { not?: string };
|
||||
cancelledAt?: unknown;
|
||||
OR?: Array<{ endsAt?: unknown }>;
|
||||
};
|
||||
let count = 0;
|
||||
state.tenantProducts = state.tenantProducts.map((row) => {
|
||||
const current = row as Record<string, unknown>;
|
||||
if (w.tenantSubscriptionId !== undefined && current.tenantSubscriptionId !== w.tenantSubscriptionId) return row;
|
||||
if (w.id && "not" in w.id && current.id === w.id.not) return row;
|
||||
if (w.cancelledAt === null && current.cancelledAt != null) return row;
|
||||
if (Array.isArray(w.OR)) {
|
||||
const endsAt = current.endsAt as Date | null | undefined;
|
||||
const matchesOr = w.OR.some((condition) => {
|
||||
const value = condition.endsAt as unknown;
|
||||
if (value === null) return endsAt == null;
|
||||
if (value && typeof value === "object" && "gt" in (value as Record<string, unknown>)) {
|
||||
return endsAt != null && endsAt > (value as { gt: Date }).gt;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (!matchesOr) return row;
|
||||
}
|
||||
count += 1;
|
||||
return { ...current, ...(data as Record<string, unknown>) } as (typeof state.tenantProducts)[number];
|
||||
});
|
||||
return { count };
|
||||
},
|
||||
},
|
||||
} as unknown as BillingSyncClient & TenantBillingStateClient;
|
||||
}
|
||||
|
||||
function createSandboxBillingGateway(state: SandboxState, now: Date): BillingGateway {
|
||||
return {
|
||||
async createCustomer(input) {
|
||||
const customer: BillingGatewayCustomer = {
|
||||
provider: "lago",
|
||||
externalId: input.tenantId,
|
||||
providerCustomerId: `lago_customer_${input.tenantId}`,
|
||||
name: input.name,
|
||||
email: input.email ?? null,
|
||||
currency: input.currency ?? "EUR",
|
||||
createdAt: now.toISOString(),
|
||||
};
|
||||
state.customers.set(input.tenantId, customer);
|
||||
return customer;
|
||||
},
|
||||
async getCustomer(tenantId) {
|
||||
return state.customers.get(tenantId) ?? null;
|
||||
},
|
||||
async createSubscription(input) {
|
||||
const subscription: BillingGatewaySubscription = {
|
||||
provider: "lago",
|
||||
externalId: input.subscriptionExternalId,
|
||||
providerSubscriptionId: `lago_subscription_${input.subscriptionExternalId}`,
|
||||
externalCustomerId: input.tenantId,
|
||||
planCode: input.planCode,
|
||||
status: "active",
|
||||
name: input.name ?? `${input.planCode} (${input.seatQuantity} seats)`,
|
||||
currentBillingPeriodStartedAt: now.toISOString(),
|
||||
currentBillingPeriodEndingAt: new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
createdAt: now.toISOString(),
|
||||
};
|
||||
const invoice: BillingGatewayInvoice = {
|
||||
provider: "lago",
|
||||
providerInvoiceId: `lago_invoice_${input.subscriptionExternalId}`,
|
||||
number: `HG-${input.subscriptionExternalId}`,
|
||||
externalCustomerId: input.tenantId,
|
||||
status: "finalized",
|
||||
paymentStatus: "pending",
|
||||
invoiceType: "subscription",
|
||||
currency: "EUR",
|
||||
totalAmountCents: input.seatQuantity * 2_900,
|
||||
issuingDate: now.toISOString(),
|
||||
fileUrl: `https://lago.test/invoices/lago_invoice_${input.subscriptionExternalId}.pdf`,
|
||||
};
|
||||
state.providerSubscriptions.set(input.subscriptionExternalId, subscription);
|
||||
state.invoices.set(input.tenantId, [invoice]);
|
||||
return subscription;
|
||||
},
|
||||
async getSubscription(subscriptionExternalId) {
|
||||
return state.providerSubscriptions.get(subscriptionExternalId) ?? null;
|
||||
},
|
||||
async listInvoices(input = {}) {
|
||||
return input.tenantId ? state.invoices.get(input.tenantId) ?? [] : [...state.invoices.values()].flat();
|
||||
},
|
||||
async downloadInvoice(providerInvoiceId) {
|
||||
return [...state.invoices.values()].flat().find((invoice) => invoice.providerInvoiceId === providerInvoiceId) ?? null;
|
||||
},
|
||||
async updateInvoicePaymentStatus(providerInvoiceId, paymentStatus) {
|
||||
const invoice = [...state.invoices.values()].flat().find((item) => item.providerInvoiceId === providerInvoiceId);
|
||||
if (!invoice) {
|
||||
throw new Error(`Sandbox invoice ${providerInvoiceId} not found.`);
|
||||
}
|
||||
invoice.paymentStatus = paymentStatus;
|
||||
return invoice;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createSandboxPaymentGateway(state: SandboxState): PaymentGateway {
|
||||
return {
|
||||
async createPayment(input: PaymentGatewayCreatePaymentInput) {
|
||||
const providerPaymentId = `tr_${input.paymentExternalId ?? input.invoiceExternalId}`;
|
||||
const payment: PaymentGatewayPayment = {
|
||||
provider: "mollie",
|
||||
providerPaymentId,
|
||||
externalId: input.paymentExternalId ?? null,
|
||||
status: "open",
|
||||
amountCents: input.amountCents,
|
||||
amountRefundedCents: 0,
|
||||
amountRemainingCents: input.amountCents,
|
||||
currency: input.currency,
|
||||
checkoutUrl: `https://mollie.test/checkout/${providerPaymentId}`,
|
||||
paidAt: null,
|
||||
expiresAt: null,
|
||||
metadata: {
|
||||
tenantId: input.tenantId,
|
||||
invoiceExternalId: input.invoiceExternalId,
|
||||
paymentExternalId: input.paymentExternalId ?? null,
|
||||
lagoCustomerId: input.lagoCustomerId ?? null,
|
||||
lagoSubscriptionId: input.lagoSubscriptionId ?? null,
|
||||
planCode: input.planCode ?? null,
|
||||
seatQuantity: input.seatQuantity ?? null,
|
||||
},
|
||||
};
|
||||
state.payments.set(providerPaymentId, payment);
|
||||
return payment;
|
||||
},
|
||||
async getPayment(providerPaymentId) {
|
||||
return state.payments.get(providerPaymentId) ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function setSandboxPaymentStatus(state: SandboxState, providerPaymentId: string, status: PaymentGatewayPaymentStatus, at: Date): PaymentGatewayPayment {
|
||||
const current = state.payments.get(providerPaymentId);
|
||||
if (!current) throw new Error(`Sandbox payment ${providerPaymentId} not found.`);
|
||||
const next: PaymentGatewayPayment = {
|
||||
...current,
|
||||
status,
|
||||
paidAt: status === "paid" ? at.toISOString() : current.paidAt,
|
||||
expiresAt: status === "expired" ? at.toISOString() : current.expiresAt,
|
||||
amountRemainingCents: status === "paid" ? 0 : current.amountRemainingCents,
|
||||
};
|
||||
state.payments.set(providerPaymentId, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function moduleAllowed(state: TenantBillingState, moduleKey: string): boolean {
|
||||
return !state.readOnly && state.entitlements.some((entitlement) => entitlement.featureKey === moduleKey && entitlement.enabled);
|
||||
}
|
||||
|
||||
function buildStep(key: string, ok: boolean, detail: string): BillingSandboxFlowStep {
|
||||
return { key, ok, detail };
|
||||
}
|
||||
|
||||
export async function runBillingSandboxFlow(input: BillingSandboxFlowInput = {}): Promise<BillingSandboxFlowResult> {
|
||||
const runId = normalizeRunId(input.runId);
|
||||
const tenantId = input.tenantId ?? `hg-stg-bill-07-${runId}`;
|
||||
const tenantName = input.tenantName ?? `BILL-07 Sandbox ${runId}`;
|
||||
const planCode = input.planCode ?? `hg-stg-plan-bill-07-${runId}`;
|
||||
const seatQuantity = positiveSeatQuantity(input.seatQuantity);
|
||||
const moduleKey = input.moduleKey ?? "billing-sandbox";
|
||||
const now = input.now ?? new Date();
|
||||
const state = createSandboxState({ planCode, moduleKey });
|
||||
const client = createSandboxClient(state);
|
||||
const billingGateway = createSandboxBillingGateway(state, now);
|
||||
const paymentGateway = createSandboxPaymentGateway(state);
|
||||
|
||||
const customer = await billingGateway.createCustomer({
|
||||
tenantId,
|
||||
name: tenantName,
|
||||
email: `${runId}@sandbox.hivegrid.test`,
|
||||
currency: "EUR",
|
||||
country: "DE",
|
||||
timezone: "Europe/Berlin",
|
||||
});
|
||||
const subscription = await billingGateway.createSubscription({
|
||||
tenantId,
|
||||
subscriptionExternalId: `subscription-${runId}`,
|
||||
planCode,
|
||||
seatQuantity,
|
||||
subscriptionAt: now,
|
||||
});
|
||||
const [invoice] = await billingGateway.listInvoices({ tenantId, perPage: 1 });
|
||||
if (!invoice) throw new Error("Sandbox Lago invoice was not created.");
|
||||
|
||||
const payment = await paymentGateway.createPayment({
|
||||
tenantId,
|
||||
invoiceExternalId: invoice.providerInvoiceId,
|
||||
amountCents: invoice.totalAmountCents ?? 8_700,
|
||||
currency: invoice.currency ?? "EUR",
|
||||
redirectUrl: "https://app.hivegrid.test/billing/return",
|
||||
webhookUrl: "https://api.hivegrid.test/v1/billing/mollie/webhooks",
|
||||
paymentExternalId: `payment-${runId}`,
|
||||
mollieCustomerId: `mollie_customer_${tenantId}`,
|
||||
});
|
||||
const paidPayment = setSandboxPaymentStatus(state, payment.providerPaymentId, "paid", now);
|
||||
|
||||
const lagoActive = await applyLagoSubscriptionSync(
|
||||
{
|
||||
tenantId,
|
||||
eventKey: `sandbox:lago:active:${runId}`,
|
||||
lagoCustomerId: customer.providerCustomerId,
|
||||
lagoSubscriptionId: subscription.providerSubscriptionId,
|
||||
status: "active",
|
||||
planCode,
|
||||
seatQuantity,
|
||||
currentPeriodStart: new Date(subscription.currentBillingPeriodStartedAt ?? now),
|
||||
currentPeriodEnd: new Date(subscription.currentBillingPeriodEndingAt ?? now),
|
||||
invoiceExternalId: invoice.providerInvoiceId,
|
||||
receivedAt: now,
|
||||
},
|
||||
client
|
||||
);
|
||||
const molliePaid = await applyMolliePaymentSync(
|
||||
{
|
||||
tenantId,
|
||||
eventKey: `sandbox:mollie:paid:${runId}`,
|
||||
mollieCustomerId: `mollie_customer_${tenantId}`,
|
||||
paymentExternalId: paidPayment.providerPaymentId,
|
||||
invoiceExternalId: invoice.providerInvoiceId,
|
||||
status: paidPayment.status,
|
||||
receivedAt: now,
|
||||
},
|
||||
client
|
||||
);
|
||||
const activeState = await resolveTenantBillingState(tenantId, { client, now });
|
||||
const activeAllowed = moduleAllowed(activeState, moduleKey);
|
||||
|
||||
const failedPayment = setSandboxPaymentStatus(state, payment.providerPaymentId, "failed", new Date(now.getTime() + 30_000));
|
||||
const mollieFailed = await applyMolliePaymentSync(
|
||||
{
|
||||
tenantId,
|
||||
eventKey: `sandbox:mollie:failed:${runId}`,
|
||||
mollieCustomerId: `mollie_customer_${tenantId}`,
|
||||
paymentExternalId: failedPayment.providerPaymentId,
|
||||
invoiceExternalId: invoice.providerInvoiceId,
|
||||
status: failedPayment.status,
|
||||
receivedAt: new Date(now.getTime() + 30_000),
|
||||
},
|
||||
client
|
||||
);
|
||||
const failedState = await resolveTenantBillingState(tenantId, { client, now: new Date(now.getTime() + 30_000) });
|
||||
|
||||
const expiredPayment = setSandboxPaymentStatus(state, payment.providerPaymentId, "expired", new Date(now.getTime() + 60_000));
|
||||
const mollieExpired = await applyMolliePaymentSync(
|
||||
{
|
||||
tenantId,
|
||||
eventKey: `sandbox:mollie:expired:${runId}`,
|
||||
mollieCustomerId: `mollie_customer_${tenantId}`,
|
||||
paymentExternalId: expiredPayment.providerPaymentId,
|
||||
invoiceExternalId: invoice.providerInvoiceId,
|
||||
status: expiredPayment.status,
|
||||
receivedAt: new Date(now.getTime() + 60_000),
|
||||
},
|
||||
client
|
||||
);
|
||||
const pastDueState = await resolveTenantBillingState(tenantId, { client, now: new Date(now.getTime() + 60_000) });
|
||||
const lagoFrozen = await applyLagoSubscriptionSync(
|
||||
{
|
||||
tenantId,
|
||||
eventKey: `sandbox:lago:frozen:${runId}`,
|
||||
lagoCustomerId: customer.providerCustomerId,
|
||||
lagoSubscriptionId: subscription.providerSubscriptionId,
|
||||
status: "paused",
|
||||
planCode,
|
||||
seatQuantity,
|
||||
invoiceExternalId: invoice.providerInvoiceId,
|
||||
receivedAt: new Date(now.getTime() + 120_000),
|
||||
},
|
||||
client
|
||||
);
|
||||
const frozenState = await resolveTenantBillingState(tenantId, { client, now: new Date(now.getTime() + 120_000) });
|
||||
|
||||
const referencesVisible = Boolean(activeState.lastInvoiceExternalId && activeState.lastPaymentExternalId);
|
||||
const steps = [
|
||||
buildStep("lago.customer", customer.externalId === tenantId, `Customer ${customer.providerCustomerId} created for ${tenantId}.`),
|
||||
buildStep("lago.subscription", subscription.planCode === planCode && subscription.status === "active", `Subscription ${subscription.providerSubscriptionId} uses ${planCode}.`),
|
||||
buildStep("mollie.payment", payment.status === "open" && paidPayment.status === "paid", `Payment ${payment.providerPaymentId} was created and simulated as paid.`),
|
||||
buildStep("local.sync", activeState.status === "active" && activeState.lastInvoiceExternalId === invoice.providerInvoiceId, "Provider sync updated the local subscription."),
|
||||
buildStep("module.gate", activeAllowed && !activeState.readOnly, `${moduleKey} is allowed while the subscription is active.`),
|
||||
buildStep("references.audit", referencesVisible && state.auditEvents.length >= 2, "Invoice/payment references are visible and syncs are audited."),
|
||||
buildStep(
|
||||
"negative.failed-expired",
|
||||
failedState.status === "past_due" && failedState.readOnly && pastDueState.status === "past_due" && pastDueState.readOnly,
|
||||
"Failed and expired Mollie payments mark the subscription past_due/read-only."
|
||||
),
|
||||
buildStep("negative.frozen", frozenState.status === "frozen" && frozenState.readOnly, "Paused Lago subscription marks the tenant frozen/read-only."),
|
||||
];
|
||||
|
||||
return {
|
||||
ok: steps.every((step) => step.ok),
|
||||
mode: "stub",
|
||||
runId,
|
||||
tenantId,
|
||||
planCode,
|
||||
seatQuantity,
|
||||
customer,
|
||||
subscription,
|
||||
invoice,
|
||||
payment: paidPayment,
|
||||
activeState,
|
||||
failedState,
|
||||
pastDueState,
|
||||
frozenState,
|
||||
syncResults: { lagoActive, molliePaid, mollieFailed, mollieExpired, lagoFrozen },
|
||||
gate: {
|
||||
moduleKey,
|
||||
activeAllowed,
|
||||
activeReadOnly: activeState.readOnly,
|
||||
failedReadOnly: failedState.readOnly,
|
||||
pastDueReadOnly: pastDueState.readOnly,
|
||||
frozenReadOnly: frozenState.readOnly,
|
||||
},
|
||||
audit: {
|
||||
auditEvents: state.auditEvents.length,
|
||||
activities: state.activities.length,
|
||||
},
|
||||
referencesVisible,
|
||||
steps,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildLagoBillingSyncDispatchKey,
|
||||
buildLagoBillingSyncOutboxArgs,
|
||||
buildMolliePaymentSyncDispatchKey,
|
||||
buildMolliePaymentSyncOutboxArgs,
|
||||
buildMolliePaymentSyncOutboxArgsFromPayment,
|
||||
LAGO_BILLING_SYNC_EVENT_TYPE,
|
||||
MOLLIE_PAYMENT_SYNC_EVENT_TYPE,
|
||||
} from "./sync-outbox.js";
|
||||
import { buildLagoWebhookSyncOutboxArgs, parseLagoWebhookEvent } from "./webhook.js";
|
||||
|
||||
describe("Lago billing sync outbox", () => {
|
||||
it("builds idempotent outbox args for Lago pull sync actions", () => {
|
||||
const args = buildLagoBillingSyncOutboxArgs({
|
||||
tenantId: "tenant_1",
|
||||
action: "subscription.upsert",
|
||||
externalId: "sub_1",
|
||||
source: "pull",
|
||||
receivedAt: new Date("2026-07-04T00:00:00Z"),
|
||||
});
|
||||
|
||||
expect(args).toEqual({
|
||||
tenantId: "tenant_1",
|
||||
type: LAGO_BILLING_SYNC_EVENT_TYPE,
|
||||
dispatchKey: "lago:subscription.upsert:tenant_1:sub_1",
|
||||
payload: {
|
||||
provider: "lago",
|
||||
action: "subscription.upsert",
|
||||
tenantId: "tenant_1",
|
||||
externalId: "sub_1",
|
||||
source: "pull",
|
||||
receivedAt: "2026-07-04T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("sanitizes dispatch keys to the outbox-safe character set", () => {
|
||||
expect(
|
||||
buildLagoBillingSyncDispatchKey({
|
||||
tenantId: "tenant/with/slashes",
|
||||
action: "invoice.refresh",
|
||||
externalId: "invoice 123",
|
||||
})
|
||||
).toBe("lago:invoice.refresh:tenant_with_slashes:invoice_123");
|
||||
});
|
||||
|
||||
it("maps Lago webhook events to idempotent sync events", () => {
|
||||
const event = parseLagoWebhookEvent({
|
||||
event_type: "invoice.finalized",
|
||||
lago_id: "invoice_1",
|
||||
external_customer_id: "tenant_1",
|
||||
data: { status: "finalized" },
|
||||
});
|
||||
|
||||
expect(
|
||||
buildLagoWebhookSyncOutboxArgs({
|
||||
tenantId: "tenant_1",
|
||||
event,
|
||||
receivedAt: new Date("2026-07-04T00:00:00Z"),
|
||||
})
|
||||
).toMatchObject({
|
||||
tenantId: "tenant_1",
|
||||
type: LAGO_BILLING_SYNC_EVENT_TYPE,
|
||||
dispatchKey: "lago:invoice.refresh:tenant_1:invoice_1",
|
||||
payload: {
|
||||
action: "invoice.refresh",
|
||||
externalId: "invoice_1",
|
||||
source: "webhook",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mollie payment sync outbox", () => {
|
||||
it("builds idempotent outbox args for paid payment events", () => {
|
||||
const args = buildMolliePaymentSyncOutboxArgs({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
providerPaymentId: "tr_123",
|
||||
paymentExternalId: "payment_1",
|
||||
status: "paid",
|
||||
amountCents: 4900,
|
||||
amountRefundedCents: 0,
|
||||
amountRemainingCents: 0,
|
||||
source: "webhook",
|
||||
receivedAt: new Date("2026-07-04T00:00:00Z"),
|
||||
});
|
||||
|
||||
expect(args).toEqual({
|
||||
tenantId: "tenant_1",
|
||||
type: MOLLIE_PAYMENT_SYNC_EVENT_TYPE,
|
||||
dispatchKey: "mollie:payment.paid:tenant_1:tr_123:paid:0",
|
||||
payload: {
|
||||
provider: "mollie",
|
||||
action: "payment.paid",
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
providerPaymentId: "tr_123",
|
||||
paymentExternalId: "payment_1",
|
||||
status: "paid",
|
||||
amountCents: 4900,
|
||||
amountRefundedCents: 0,
|
||||
amountRemainingCents: 0,
|
||||
source: "webhook",
|
||||
receivedAt: "2026-07-04T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("records failure, expired and refund statuses as distinct billing events", () => {
|
||||
expect(
|
||||
buildMolliePaymentSyncOutboxArgs({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
providerPaymentId: "tr_123",
|
||||
paymentExternalId: null,
|
||||
status: "failed",
|
||||
amountCents: 4900,
|
||||
amountRefundedCents: 0,
|
||||
amountRemainingCents: 4900,
|
||||
source: "webhook",
|
||||
}).payload
|
||||
).toMatchObject({ action: "payment.failed" });
|
||||
|
||||
expect(
|
||||
buildMolliePaymentSyncOutboxArgs({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
providerPaymentId: "tr_123",
|
||||
paymentExternalId: null,
|
||||
status: "expired",
|
||||
amountCents: 4900,
|
||||
amountRefundedCents: 0,
|
||||
amountRemainingCents: 4900,
|
||||
source: "webhook",
|
||||
}).payload
|
||||
).toMatchObject({ action: "payment.expired" });
|
||||
|
||||
expect(
|
||||
buildMolliePaymentSyncOutboxArgs({
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
providerPaymentId: "tr_123",
|
||||
paymentExternalId: null,
|
||||
status: "refunded",
|
||||
amountCents: 4900,
|
||||
amountRefundedCents: 4900,
|
||||
amountRemainingCents: 0,
|
||||
source: "webhook",
|
||||
}).payload
|
||||
).toMatchObject({ action: "payment.refunded" });
|
||||
});
|
||||
|
||||
it("sanitizes Mollie dispatch keys and can build them from verified payments", () => {
|
||||
expect(
|
||||
buildMolliePaymentSyncDispatchKey({
|
||||
tenantId: "tenant/with/slashes",
|
||||
providerPaymentId: "tr 123",
|
||||
status: "refunded",
|
||||
amountRefundedCents: 4900,
|
||||
})
|
||||
).toBe("mollie:payment.refunded:tenant_with_slashes:tr_123:refunded:4900");
|
||||
|
||||
expect(
|
||||
buildMolliePaymentSyncOutboxArgsFromPayment(
|
||||
{
|
||||
provider: "mollie",
|
||||
providerPaymentId: "tr_123",
|
||||
externalId: "payment_1",
|
||||
status: "refunded",
|
||||
amountCents: 4900,
|
||||
amountRefundedCents: 4900,
|
||||
amountRemainingCents: 0,
|
||||
currency: "EUR",
|
||||
checkoutUrl: null,
|
||||
paidAt: null,
|
||||
expiresAt: null,
|
||||
metadata: {
|
||||
tenantId: "tenant_1",
|
||||
invoiceExternalId: "invoice_1",
|
||||
paymentExternalId: "payment_1",
|
||||
lagoCustomerId: null,
|
||||
lagoSubscriptionId: null,
|
||||
planCode: null,
|
||||
seatQuantity: null,
|
||||
},
|
||||
},
|
||||
{ source: "webhook", receivedAt: new Date("2026-07-04T00:00:00Z") }
|
||||
)
|
||||
).toMatchObject({
|
||||
tenantId: "tenant_1",
|
||||
dispatchKey: "mollie:payment.refunded:tenant_1:tr_123:refunded:4900",
|
||||
payload: {
|
||||
action: "payment.refunded",
|
||||
invoiceExternalId: "invoice_1",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { publishOutboxEvent, type OutboxPublishArgs, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import type { PaymentGatewayPayment, PaymentGatewayPaymentStatus } from "./types.js";
|
||||
|
||||
export const LAGO_BILLING_SYNC_EVENT_TYPE = "billing.lago.sync";
|
||||
export const MOLLIE_PAYMENT_SYNC_EVENT_TYPE = "billing.mollie.payment";
|
||||
|
||||
export type LagoBillingSyncAction = "customer.upsert" | "subscription.upsert" | "invoice.refresh" | "webhook.received";
|
||||
export type MolliePaymentSyncAction = "payment.refresh" | "payment.paid" | "payment.failed" | "payment.expired" | "payment.refunded" | "payment.cancelled";
|
||||
|
||||
export type LagoBillingSyncPayload = {
|
||||
provider: "lago";
|
||||
action: LagoBillingSyncAction;
|
||||
tenantId: string;
|
||||
externalId: string;
|
||||
receivedAt: string;
|
||||
source: "api" | "webhook" | "pull";
|
||||
};
|
||||
|
||||
export type LagoBillingSyncInput = Omit<LagoBillingSyncPayload, "provider" | "receivedAt"> & {
|
||||
receivedAt?: Date;
|
||||
};
|
||||
|
||||
export function buildLagoBillingSyncOutboxArgs(input: LagoBillingSyncInput): OutboxPublishArgs {
|
||||
return {
|
||||
tenantId: input.tenantId,
|
||||
type: LAGO_BILLING_SYNC_EVENT_TYPE,
|
||||
dispatchKey: buildLagoBillingSyncDispatchKey(input),
|
||||
payload: {
|
||||
provider: "lago",
|
||||
action: input.action,
|
||||
tenantId: input.tenantId,
|
||||
externalId: input.externalId,
|
||||
source: input.source,
|
||||
receivedAt: (input.receivedAt ?? new Date()).toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function publishLagoBillingSync(tx: OutboxPublisherTransaction, input: LagoBillingSyncInput) {
|
||||
return await publishOutboxEvent(tx, buildLagoBillingSyncOutboxArgs(input));
|
||||
}
|
||||
|
||||
export function buildLagoBillingSyncDispatchKey(input: Pick<LagoBillingSyncInput, "action" | "tenantId" | "externalId">): string {
|
||||
return `lago:${input.action}:${input.tenantId}:${input.externalId}`.replace(/[^A-Za-z0-9._:-]/gu, "_").slice(0, 256);
|
||||
}
|
||||
|
||||
export type MolliePaymentSyncPayload = {
|
||||
provider: "mollie";
|
||||
action: MolliePaymentSyncAction;
|
||||
tenantId: string;
|
||||
invoiceExternalId: string;
|
||||
providerPaymentId: string;
|
||||
paymentExternalId: string | null;
|
||||
status: PaymentGatewayPaymentStatus;
|
||||
amountCents: number | null;
|
||||
amountRefundedCents: number | null;
|
||||
amountRemainingCents: number | null;
|
||||
receivedAt: string;
|
||||
source: "api" | "webhook" | "pull";
|
||||
};
|
||||
|
||||
export type MolliePaymentSyncInput = Omit<MolliePaymentSyncPayload, "provider" | "receivedAt" | "action"> & {
|
||||
action?: MolliePaymentSyncAction;
|
||||
receivedAt?: Date;
|
||||
};
|
||||
|
||||
export function buildMolliePaymentSyncOutboxArgs(input: MolliePaymentSyncInput): OutboxPublishArgs {
|
||||
const action = input.action ?? actionForMolliePaymentStatus(input.status);
|
||||
return {
|
||||
tenantId: input.tenantId,
|
||||
type: MOLLIE_PAYMENT_SYNC_EVENT_TYPE,
|
||||
dispatchKey: buildMolliePaymentSyncDispatchKey({ ...input, action }),
|
||||
payload: {
|
||||
provider: "mollie",
|
||||
action,
|
||||
tenantId: input.tenantId,
|
||||
invoiceExternalId: input.invoiceExternalId,
|
||||
providerPaymentId: input.providerPaymentId,
|
||||
paymentExternalId: input.paymentExternalId,
|
||||
status: input.status,
|
||||
amountCents: input.amountCents,
|
||||
amountRefundedCents: input.amountRefundedCents,
|
||||
amountRemainingCents: input.amountRemainingCents,
|
||||
source: input.source,
|
||||
receivedAt: (input.receivedAt ?? new Date()).toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildMolliePaymentSyncOutboxArgsFromPayment(payment: PaymentGatewayPayment, options: { source: "api" | "webhook" | "pull"; receivedAt?: Date }): OutboxPublishArgs {
|
||||
const tenantId = payment.metadata.tenantId;
|
||||
const invoiceExternalId = payment.metadata.invoiceExternalId;
|
||||
if (!tenantId || !invoiceExternalId) {
|
||||
throw new Error("Mollie payment metadata must include tenantId and invoiceExternalId.");
|
||||
}
|
||||
return buildMolliePaymentSyncOutboxArgs({
|
||||
tenantId,
|
||||
invoiceExternalId,
|
||||
providerPaymentId: payment.providerPaymentId,
|
||||
paymentExternalId: payment.externalId ?? payment.metadata.paymentExternalId,
|
||||
status: payment.status,
|
||||
amountCents: payment.amountCents,
|
||||
amountRefundedCents: payment.amountRefundedCents,
|
||||
amountRemainingCents: payment.amountRemainingCents,
|
||||
source: options.source,
|
||||
receivedAt: options.receivedAt,
|
||||
});
|
||||
}
|
||||
|
||||
export async function publishMolliePaymentSync(tx: OutboxPublisherTransaction, input: MolliePaymentSyncInput) {
|
||||
return await publishOutboxEvent(tx, buildMolliePaymentSyncOutboxArgs(input));
|
||||
}
|
||||
|
||||
export function actionForMolliePaymentStatus(status: PaymentGatewayPaymentStatus): MolliePaymentSyncAction {
|
||||
if (status === "paid" || status === "authorized") return "payment.paid";
|
||||
if (status === "failed" || status === "charged_back") return "payment.failed";
|
||||
if (status === "expired") return "payment.expired";
|
||||
if (status === "refunded") return "payment.refunded";
|
||||
if (status === "canceled") return "payment.cancelled";
|
||||
return "payment.refresh";
|
||||
}
|
||||
|
||||
export function buildMolliePaymentSyncDispatchKey(input: Pick<MolliePaymentSyncInput, "tenantId" | "providerPaymentId" | "status" | "amountRefundedCents"> & { action?: MolliePaymentSyncAction }): string {
|
||||
const refundPart = typeof input.amountRefundedCents === "number" ? input.amountRefundedCents : "none";
|
||||
return `mollie:${input.action ?? actionForMolliePaymentStatus(input.status)}:${input.tenantId}:${input.providerPaymentId}:${input.status}:${refundPart}`
|
||||
.replace(/[^A-Za-z0-9._:-]/gu, "_")
|
||||
.slice(0, 256);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
export type BillingGatewayCustomerInput = {
|
||||
tenantId: string;
|
||||
name: string;
|
||||
email?: string | null;
|
||||
currency?: string | null;
|
||||
country?: string | null;
|
||||
timezone?: string | null;
|
||||
};
|
||||
|
||||
export type BillingGatewayCustomer = {
|
||||
provider: "lago";
|
||||
externalId: string;
|
||||
providerCustomerId: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
currency: string | null;
|
||||
createdAt: string | null;
|
||||
};
|
||||
|
||||
export type BillingGatewaySubscriptionInput = {
|
||||
tenantId: string;
|
||||
subscriptionExternalId: string;
|
||||
planCode: string;
|
||||
seatQuantity: number;
|
||||
name?: string | null;
|
||||
subscriptionAt?: Date | string | null;
|
||||
endingAt?: Date | string | null;
|
||||
};
|
||||
|
||||
export type BillingGatewaySubscription = {
|
||||
provider: "lago";
|
||||
externalId: string;
|
||||
providerSubscriptionId: string;
|
||||
externalCustomerId: string;
|
||||
planCode: string;
|
||||
status: "pending" | "active" | "terminated" | "canceled" | "cancelled" | "unknown";
|
||||
name: string | null;
|
||||
currentBillingPeriodStartedAt: string | null;
|
||||
currentBillingPeriodEndingAt: string | null;
|
||||
createdAt: string | null;
|
||||
};
|
||||
|
||||
export type BillingGatewayInvoice = {
|
||||
provider: "lago";
|
||||
providerInvoiceId: string;
|
||||
number: string | null;
|
||||
externalCustomerId: string | null;
|
||||
status: "draft" | "finalized" | "voided" | "failed" | "pending" | "unknown";
|
||||
paymentStatus: "pending" | "succeeded" | "failed" | "unknown";
|
||||
invoiceType: string | null;
|
||||
currency: string | null;
|
||||
totalAmountCents: number | null;
|
||||
issuingDate: string | null;
|
||||
fileUrl: string | null;
|
||||
};
|
||||
|
||||
export type BillingGatewayInvoiceListInput = {
|
||||
tenantId?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
};
|
||||
|
||||
export type BillingGateway = {
|
||||
createCustomer(input: BillingGatewayCustomerInput): Promise<BillingGatewayCustomer>;
|
||||
getCustomer(tenantId: string): Promise<BillingGatewayCustomer | null>;
|
||||
createSubscription(input: BillingGatewaySubscriptionInput): Promise<BillingGatewaySubscription>;
|
||||
getSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null>;
|
||||
listInvoices(input?: BillingGatewayInvoiceListInput): Promise<BillingGatewayInvoice[]>;
|
||||
downloadInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null>;
|
||||
updateInvoicePaymentStatus(providerInvoiceId: string, paymentStatus: BillingGatewayInvoice["paymentStatus"]): Promise<BillingGatewayInvoice>;
|
||||
};
|
||||
|
||||
export type PaymentGatewayCreatePaymentInput = {
|
||||
tenantId: string;
|
||||
invoiceExternalId: string;
|
||||
amountCents: number;
|
||||
currency: string;
|
||||
redirectUrl: string;
|
||||
webhookUrl: string;
|
||||
paymentExternalId?: string | null;
|
||||
mollieCustomerId?: string | null;
|
||||
lagoCustomerId?: string | null;
|
||||
lagoSubscriptionId?: string | null;
|
||||
planCode?: string | null;
|
||||
seatQuantity?: number | null;
|
||||
description?: string | null;
|
||||
};
|
||||
|
||||
export type PaymentGatewayPaymentStatus =
|
||||
| "open"
|
||||
| "pending"
|
||||
| "authorized"
|
||||
| "paid"
|
||||
| "failed"
|
||||
| "expired"
|
||||
| "canceled"
|
||||
| "refunded"
|
||||
| "charged_back"
|
||||
| "unknown";
|
||||
|
||||
export type PaymentGatewayPaymentMetadata = {
|
||||
tenantId: string | null;
|
||||
invoiceExternalId: string | null;
|
||||
paymentExternalId: string | null;
|
||||
lagoCustomerId: string | null;
|
||||
lagoSubscriptionId: string | null;
|
||||
planCode: string | null;
|
||||
seatQuantity: number | null;
|
||||
};
|
||||
|
||||
export type PaymentGatewayPayment = {
|
||||
provider: "mollie";
|
||||
providerPaymentId: string;
|
||||
externalId: string | null;
|
||||
status: PaymentGatewayPaymentStatus;
|
||||
amountCents: number | null;
|
||||
amountRefundedCents: number | null;
|
||||
amountRemainingCents: number | null;
|
||||
currency: string | null;
|
||||
checkoutUrl: string | null;
|
||||
paidAt: string | null;
|
||||
expiresAt: string | null;
|
||||
metadata: PaymentGatewayPaymentMetadata;
|
||||
};
|
||||
|
||||
export type PaymentGateway = {
|
||||
createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment>;
|
||||
getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null>;
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { buildLagoBillingSyncOutboxArgs, type LagoBillingSyncAction } from "./sync-outbox.js";
|
||||
|
||||
export const lagoWebhookEventSchema = z
|
||||
.object({
|
||||
event_type: z.string().optional(),
|
||||
webhook_type: z.string().optional(),
|
||||
object_type: z.string().optional(),
|
||||
lago_id: z.string().optional(),
|
||||
external_id: z.string().optional(),
|
||||
external_customer_id: z.string().optional(),
|
||||
data: z.unknown().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type LagoWebhookEvent = z.infer<typeof lagoWebhookEventSchema>;
|
||||
|
||||
export function parseLagoWebhookEvent(value: unknown): LagoWebhookEvent {
|
||||
return lagoWebhookEventSchema.parse(value);
|
||||
}
|
||||
|
||||
export function buildLagoWebhookSyncOutboxArgs(input: { tenantId: string; event: LagoWebhookEvent; receivedAt?: Date }) {
|
||||
const action = resolveWebhookAction(input.event);
|
||||
const externalId = input.event.external_id ?? input.event.lago_id ?? `${action}:${input.tenantId}`;
|
||||
return buildLagoBillingSyncOutboxArgs({
|
||||
tenantId: input.tenantId,
|
||||
action,
|
||||
externalId,
|
||||
source: "webhook",
|
||||
receivedAt: input.receivedAt,
|
||||
});
|
||||
}
|
||||
|
||||
function resolveWebhookAction(event: LagoWebhookEvent): LagoBillingSyncAction {
|
||||
const type = [event.event_type, event.webhook_type, event.object_type].filter(Boolean).join(":").toLowerCase();
|
||||
if (type.includes("invoice")) return "invoice.refresh";
|
||||
if (type.includes("subscription")) return "subscription.upsert";
|
||||
if (type.includes("customer")) return "customer.upsert";
|
||||
return "webhook.received";
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": false,
|
||||
"allowImportingTsExtensions": false,
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"noEmit": true,
|
||||
"types": ["node", "vitest/globals"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user