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,117 @@
// @vitest-environment node
import { describe, expect, it, vi } from "vitest";
import type { BillingGateway, BillingGatewayInvoice } from "@hivegrid/billing";
import {
CustomerBillingInvoiceError,
getCustomerBillingInvoiceDownloadTarget,
getCustomerBillingInvoiceDownloadUrl,
listCustomerBillingInvoices,
} from "./customer-invoices.server";
function invoice(overrides: Partial<BillingGatewayInvoice> = {}): BillingGatewayInvoice {
return {
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",
...overrides,
};
}
function gateway(overrides: Partial<BillingGateway> = {}): BillingGateway {
return {
createCustomer: vi.fn(),
getCustomer: vi.fn(),
createSubscription: vi.fn(),
getSubscription: vi.fn(),
listInvoices: vi.fn(async () => [invoice(), invoice({ providerInvoiceId: "foreign_invoice", externalCustomerId: "tenant_2" })]),
downloadInvoice: vi.fn(async () => invoice()),
...overrides,
} as BillingGateway;
}
describe("customer billing invoices", () => {
it("lists only invoices that belong to the current tenant", async () => {
const deps = { gateway: gateway() };
await expect(listCustomerBillingInvoices({ tenantId: "tenant_1", tenantSlug: "acme" }, deps)).resolves.toEqual([
{
id: "invoice_1",
number: "LAG-001",
issuingDate: "2026-07-04",
amountCents: 4900,
currency: "EUR",
status: "finalized",
paymentStatus: "succeeded",
invoiceType: "subscription",
downloadHref: "/acme/settings/subscription/invoices/invoice_1/download",
},
]);
expect(deps.gateway.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", perPage: 50 });
});
it("returns an empty customer invoice list when Lago is not configured", async () => {
await expect(listCustomerBillingInvoices({ tenantId: "tenant_1", tenantSlug: "acme" }, { gateway: null })).resolves.toEqual([]);
});
it("keeps voided invoices visible but not downloadable", async () => {
await expect(
listCustomerBillingInvoices(
{ tenantId: "tenant_1", tenantSlug: "acme" },
{ gateway: gateway({ listInvoices: vi.fn(async () => [invoice({ status: "voided" })]) }) }
)
).resolves.toMatchObject([{ id: "invoice_1", status: "voided", downloadHref: null }]);
});
it("returns a generated download URL after tenant ownership is verified", async () => {
const deps = { gateway: gateway() };
await expect(getCustomerBillingInvoiceDownloadUrl({ tenantId: "tenant_1", invoiceId: "invoice_1" }, deps)).resolves.toBe(
"https://files.example.test/invoice_1.pdf"
);
expect(deps.gateway.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", perPage: 50 });
expect(deps.gateway.downloadInvoice).toHaveBeenCalledWith("invoice_1");
});
it("accepts Lago download responses without customer data after list ownership check", async () => {
await expect(
getCustomerBillingInvoiceDownloadTarget(
{ tenantId: "tenant_1", invoiceId: "invoice_1" },
{ gateway: gateway({ downloadInvoice: vi.fn(async () => invoice({ externalCustomerId: null })) }) }
)
).resolves.toEqual({
fileUrl: "https://files.example.test/invoice_1.pdf",
filename: "LAG-001.pdf",
});
});
it("rejects downloads for invoices from another tenant", async () => {
await expect(
getCustomerBillingInvoiceDownloadUrl(
{ tenantId: "tenant_1", invoiceId: "foreign_invoice" },
{ gateway: gateway({ downloadInvoice: vi.fn(async () => invoice({ providerInvoiceId: "foreign_invoice", externalCustomerId: "tenant_2" })) }) }
)
).rejects.toMatchObject({ name: "CustomerBillingInvoiceError", code: "INVOICE_NOT_FOUND" });
});
it("rejects downloads when Lago has not generated a file URL", async () => {
await expect(
getCustomerBillingInvoiceDownloadUrl(
{ tenantId: "tenant_1", invoiceId: "invoice_1" },
{
gateway: gateway({
listInvoices: vi.fn(async () => [invoice({ fileUrl: null })]),
downloadInvoice: vi.fn(async () => invoice({ fileUrl: null })),
}),
}
)
).rejects.toBeInstanceOf(CustomerBillingInvoiceError);
});
});
@@ -0,0 +1,117 @@
import { createLagoBillingGateway, type BillingGateway, type BillingGatewayInvoice } from "@hivegrid/billing";
import { loadWebConfig } from "@hivegrid/config";
import type { CustomerBillingInvoiceDto } from "~/application/dtos/billing/CustomerBillingInvoiceDto";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
export class CustomerBillingInvoiceError extends Error {
override readonly name = "CustomerBillingInvoiceError";
readonly i18nKey: string;
constructor(readonly code: "CONFIGURATION_MISSING" | "INVOICE_NOT_FOUND" | "DOWNLOAD_UNAVAILABLE") {
super(code);
this.i18nKey = `settings.subscription.errors.${code}`;
}
}
type CustomerInvoiceDeps = {
gateway?: BillingGateway | null;
loadGateway?: () => BillingGateway | null;
};
export type CustomerBillingInvoiceDownloadTarget = {
fileUrl: string;
filename: string;
};
function createConfiguredLagoGateway(): BillingGateway | null {
const config = loadWebConfig().config.lago;
if (!config.apiUrl || !config.apiKey) {
return null;
}
return createLagoBillingGateway({
apiUrl: config.apiUrl,
apiKey: config.apiKey,
timeoutMs: config.timeoutMs,
});
}
function resolveGateway(deps: CustomerInvoiceDeps = {}): BillingGateway | null {
if ("gateway" in deps) return deps.gateway ?? null;
return (deps.loadGateway ?? createConfiguredLagoGateway)();
}
function toCustomerInvoice(invoice: BillingGatewayInvoice, tenantSlug: string): CustomerBillingInvoiceDto {
const isDownloadable = invoice.status !== "voided";
return {
id: invoice.providerInvoiceId,
number: invoice.number,
issuingDate: invoice.issuingDate,
amountCents: invoice.totalAmountCents,
currency: invoice.currency,
status: invoice.status,
paymentStatus: invoice.paymentStatus,
invoiceType: invoice.invoiceType,
downloadHref: isDownloadable
? appPath({ tenantSlug, path: `settings/subscription/invoices/${encodeURIComponent(invoice.providerInvoiceId)}/download`, mode: "host-aware" })
: null,
};
}
function filenameForInvoice(invoice: BillingGatewayInvoice): string {
return `${(invoice.number || invoice.providerInvoiceId).replace(/[^a-zA-Z0-9._-]+/g, "-")}.pdf`;
}
function toServerReachableLagoFileUrl(fileUrl: string): string {
const config = loadWebConfig().config.lago;
if (!config.apiUrl) return fileUrl;
try {
const original = new URL(fileUrl);
if (!original.pathname.startsWith("/rails/active_storage/")) return fileUrl;
const apiUrl = new URL(config.apiUrl);
return `${apiUrl.toString().replace(/\/$/u, "")}${original.pathname}${original.search}`;
} catch {
return fileUrl;
}
}
export async function listCustomerBillingInvoices(input: { tenantId: string; tenantSlug: string }, deps: CustomerInvoiceDeps = {}): Promise<CustomerBillingInvoiceDto[]> {
const gateway = resolveGateway(deps);
if (!gateway) return [];
const invoices = await gateway.listInvoices({ tenantId: input.tenantId, perPage: 50 });
return invoices
.filter((invoice) => invoice.externalCustomerId === input.tenantId)
.map((invoice) => toCustomerInvoice(invoice, input.tenantSlug));
}
export async function getCustomerBillingInvoiceDownloadUrl(
input: { tenantId: string; invoiceId: string },
deps: CustomerInvoiceDeps = {}
): Promise<string> {
return (await getCustomerBillingInvoiceDownloadTarget(input, deps)).fileUrl;
}
export async function getCustomerBillingInvoiceDownloadTarget(
input: { tenantId: string; invoiceId: string },
deps: CustomerInvoiceDeps = {}
): Promise<CustomerBillingInvoiceDownloadTarget> {
const gateway = resolveGateway(deps);
if (!gateway) throw new CustomerBillingInvoiceError("CONFIGURATION_MISSING");
const ownedInvoice = (await gateway.listInvoices({ tenantId: input.tenantId, perPage: 50 })).find(
(invoice) => invoice.providerInvoiceId === input.invoiceId && invoice.externalCustomerId === input.tenantId
);
if (!ownedInvoice) {
throw new CustomerBillingInvoiceError("INVOICE_NOT_FOUND");
}
const downloadedInvoice = await gateway.downloadInvoice(input.invoiceId);
const fileUrl = downloadedInvoice?.fileUrl ?? ownedInvoice.fileUrl;
if (!fileUrl) {
throw new CustomerBillingInvoiceError("DOWNLOAD_UNAVAILABLE");
}
return {
fileUrl: toServerReachableLagoFileUrl(fileUrl),
filename: filenameForInvoice(downloadedInvoice ?? ownedInvoice),
};
}
@@ -0,0 +1,360 @@
import { randomUUID } from "node:crypto";
import {
createLagoBillingGateway,
createMolliePaymentGateway,
type BillingGateway,
type BillingGatewaySubscription,
type PaymentGateway,
type PaymentGatewayPayment,
} from "@hivegrid/billing";
import { loadWebConfig } from "@hivegrid/config";
import { applyLagoSubscriptionSync, applyMolliePaymentSync } from "@hivegrid/db/billing-sync.server";
import type { CheckoutSessionStatus, SubscriptionPrice, SubscriptionProduct } from "@hivegrid/db/prisma-browser";
import {
createCheckoutSessionStatus,
getCheckoutSessionStatus,
getSubscriptionProduct,
updateCheckoutSessionStatus,
type SubscriptionProductPriceWithDetails,
type SubscriptionProductWithDetails,
} from "@hivegrid/db/subscriptions.server";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import { apiUrl } from "~/utils/app/CanonicalUrlUtils";
import { absolutePublicAppPath } from "~/utils/app/CrossHostUrls";
import { invalidateTenantModuleAccessCache } from "~/utils/connector/tenantConnector.server";
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
export class SelfServiceCheckoutError extends Error {
override readonly name = "SelfServiceCheckoutError";
readonly i18nKey: string;
constructor(
readonly code:
| "PROVIDER_CONFIGURATION_MISSING"
| "PLAN_NOT_FOUND"
| "PRICE_NOT_FOUND"
| "PLAN_NOT_PURCHASABLE"
| "CHECKOUT_NOT_PAYABLE"
| "CHECKOUT_URL_MISSING"
| "SESSION_NOT_FOUND"
| "PAYMENT_NOT_FOUND"
) {
super(code);
this.i18nKey = `settings.subscription.errors.${code}`;
}
}
type TenantCheckoutContext = {
tenantId: string;
tenantSlug: string;
tenantName: string;
userId: string;
userEmail: string;
userName: string;
};
export type CreateSelfServiceCheckoutInput = TenantCheckoutContext & {
request: Request;
productId: string;
billingPeriod: number;
currency: string;
quantity: number;
};
export type CompleteSelfServiceCheckoutInput = {
sessionId: string;
tenantId: string;
};
export type SelfServiceCheckoutResponse = {
id: string;
customer: {
id: string;
email: string;
name: string;
};
products: {
id: string;
title: string;
quantity: number;
subscription: string | undefined;
prices: { flatPrice?: SubscriptionPrice; quantity?: number }[];
}[];
status: CheckoutSessionStatus | null;
source: "self-service";
};
type SelfServiceCheckoutDeps = {
lagoGateway?: BillingGateway | null;
mollieGateway?: PaymentGateway | null;
};
function createConfiguredLagoGateway(): BillingGateway | null {
const config = loadWebConfig().config.lago;
if (!config.apiUrl || !config.apiKey) return null;
return createLagoBillingGateway({
apiUrl: config.apiUrl,
apiKey: config.apiKey,
timeoutMs: config.timeoutMs,
});
}
function createConfiguredMollieGateway(): PaymentGateway | null {
const config = loadWebConfig().config.mollie;
if (!config.apiKey) return null;
return createMolliePaymentGateway({
apiKey: config.apiKey,
profileId: config.profileId,
timeoutMs: config.timeoutMs,
});
}
function getLagoGateway(deps: SelfServiceCheckoutDeps = {}) {
if ("lagoGateway" in deps) return deps.lagoGateway ?? null;
return createConfiguredLagoGateway();
}
function getMollieGateway(deps: SelfServiceCheckoutDeps = {}) {
if ("mollieGateway" in deps) return deps.mollieGateway ?? null;
return createConfiguredMollieGateway();
}
function normalizeQuantity(value: number): number {
if (!Number.isFinite(value)) return 1;
return Math.min(10_000, Math.max(1, Math.trunc(value)));
}
function resolvePlanCode(product: Pick<SubscriptionProduct, "id" | "code" | "lagoPlanCode">): string {
return product.lagoPlanCode?.trim() || product.code?.trim() || product.id;
}
function findCheckoutPrice(product: SubscriptionProductWithDetails, billingPeriod: number, currency: string) {
return product.prices.find(
(price) =>
price.active &&
price.type === SubscriptionPriceType.RECURRING &&
price.billingPeriod === billingPeriod &&
price.currency.toLowerCase() === currency.toLowerCase()
);
}
function requireRecordId(id: string | undefined, code: "PLAN_NOT_FOUND" | "PRICE_NOT_FOUND"): string {
if (!id) throw new SelfServiceCheckoutError(code);
return id;
}
function centsForPrice(price: SubscriptionProductPriceWithDetails, quantity: number): number {
return Math.round(Number(price.price ?? 0) * 100 * quantity);
}
function buildRedirectUrl(tenantSlug: string, sessionId: string) {
const routing = loadWebConfig().config.routing;
return absolutePublicAppPath(routing, `/subscribe/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(sessionId)}/success`);
}
function buildWebhookUrl() {
const routing = loadWebConfig().config.routing;
return apiUrl({
rootDomain: routing.apiHost,
protocol: routing.protocol,
path: "billing/mollie/webhooks",
version: "v1",
mode: "host-aware",
});
}
async function ensureLagoCustomer(gateway: BillingGateway, input: TenantCheckoutContext, currency: string) {
const existing = await gateway.getCustomer(input.tenantId);
if (existing) return existing;
return gateway.createCustomer({
tenantId: input.tenantId,
name: input.tenantName,
email: input.userEmail,
currency: currency.toUpperCase(),
});
}
function isPaidPayment(payment: PaymentGatewayPayment | null): payment is PaymentGatewayPayment {
return payment?.status === "paid" || payment?.status === "authorized";
}
function mollieEventKey(payment: PaymentGatewayPayment) {
const refundPart = typeof payment.amountRefundedCents === "number" ? payment.amountRefundedCents : "none";
return `mollie:webhook:${payment.providerPaymentId}:${payment.status}:${refundPart}`.replace(/[^A-Za-z0-9._:-]/gu, "_").slice(0, 256);
}
function lagoEventKey(payment: PaymentGatewayPayment) {
return `mollie:lago:${payment.providerPaymentId}:${payment.status}`.replace(/[^A-Za-z0-9._:-]/gu, "_").slice(0, 256);
}
async function syncPaidCheckoutSession(payment: PaymentGatewayPayment, session: CheckoutSessionStatus) {
const tenantId = payment.metadata.tenantId ?? session.fromTenantId;
const invoiceExternalId = payment.metadata.invoiceExternalId ?? session.invoiceExternalId;
if (!tenantId || !invoiceExternalId) return;
await applyMolliePaymentSync({
tenantId,
eventKey: mollieEventKey(payment),
paymentExternalId: payment.externalId ?? payment.providerPaymentId,
invoiceExternalId,
status: payment.status,
receivedAt: new Date(),
});
const planCode = payment.metadata.planCode ?? session.planCode;
const lagoSubscriptionId = payment.metadata.lagoSubscriptionId ?? session.lagoSubscriptionId;
if (planCode && lagoSubscriptionId) {
await applyLagoSubscriptionSync({
tenantId,
eventKey: lagoEventKey(payment),
lagoCustomerId: payment.metadata.lagoCustomerId,
lagoSubscriptionId,
planCode,
seatQuantity: payment.metadata.seatQuantity ?? session.quantity,
invoiceExternalId,
status: "active",
receivedAt: new Date(),
});
}
clearTenantSubscriptionCache(tenantId);
invalidateTenantModuleAccessCache(tenantId);
}
export async function createSelfServiceCheckout(
input: CreateSelfServiceCheckoutInput,
deps: SelfServiceCheckoutDeps = {}
): Promise<{ sessionId: string; checkoutUrl: string; providerPaymentId: string }> {
const [lagoGateway, mollieGateway] = [getLagoGateway(deps), getMollieGateway(deps)];
if (!lagoGateway || !mollieGateway) {
throw new SelfServiceCheckoutError("PROVIDER_CONFIGURATION_MISSING");
}
const product = await getSubscriptionProduct(input.productId);
if (!product) throw new SelfServiceCheckoutError("PLAN_NOT_FOUND");
if (!product.active || !product.public) throw new SelfServiceCheckoutError("PLAN_NOT_PURCHASABLE");
const productId = requireRecordId(product.id, "PLAN_NOT_FOUND");
const price = findCheckoutPrice(product, input.billingPeriod, input.currency);
if (!price) throw new SelfServiceCheckoutError("PRICE_NOT_FOUND");
const priceId = requireRecordId(price.id, "PRICE_NOT_FOUND");
const quantity = normalizeQuantity(input.quantity);
const amountCents = centsForPrice(price, quantity);
if (amountCents <= 0) throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
const sessionId = `hgco_${randomUUID().replaceAll("-", "")}`;
const planCode = resolvePlanCode({ id: productId, code: product.code, lagoPlanCode: product.lagoPlanCode });
const lagoCustomer = await ensureLagoCustomer(lagoGateway, input, price.currency);
const lagoSubscription: BillingGatewaySubscription = await lagoGateway.createSubscription({
tenantId: input.tenantId,
subscriptionExternalId: sessionId,
planCode,
seatQuantity: quantity,
name: `${input.tenantName} · ${product.title}`,
});
const redirectUrl = buildRedirectUrl(input.tenantSlug, sessionId);
const payment = await mollieGateway.createPayment({
tenantId: input.tenantId,
invoiceExternalId: sessionId,
paymentExternalId: sessionId,
amountCents,
currency: price.currency.toUpperCase(),
redirectUrl,
webhookUrl: buildWebhookUrl(),
lagoCustomerId: lagoCustomer.providerCustomerId,
lagoSubscriptionId: lagoSubscription.externalId,
planCode,
seatQuantity: quantity,
description: `${loadWebConfig().config.appName} ${product.title}`,
});
if (!payment.checkoutUrl) {
throw new SelfServiceCheckoutError("CHECKOUT_URL_MISSING");
}
await createCheckoutSessionStatus({
id: sessionId,
email: input.userEmail,
fromUrl: new URL(input.request.url).pathname,
fromUserId: input.userId,
fromTenantId: input.tenantId,
provider: "mollie",
providerPaymentId: payment.providerPaymentId,
invoiceExternalId: sessionId,
subscriptionProductId: productId,
subscriptionPriceId: priceId,
lagoSubscriptionId: lagoSubscription.externalId,
planCode,
quantity,
amountCents,
currency: price.currency.toUpperCase(),
checkoutUrl: payment.checkoutUrl,
status: payment.status,
});
return { sessionId, checkoutUrl: payment.checkoutUrl, providerPaymentId: payment.providerPaymentId };
}
export async function completeSelfServiceCheckout(
input: CompleteSelfServiceCheckoutInput,
deps: SelfServiceCheckoutDeps = {}
): Promise<SelfServiceCheckoutResponse | null> {
const session = await getCheckoutSessionStatus(input.sessionId);
if (!session || session.fromTenantId !== input.tenantId) {
throw new SelfServiceCheckoutError("SESSION_NOT_FOUND");
}
if (!session.providerPaymentId) {
throw new SelfServiceCheckoutError("PAYMENT_NOT_FOUND");
}
const gateway = getMollieGateway(deps);
if (!gateway) throw new SelfServiceCheckoutError("PROVIDER_CONFIGURATION_MISSING");
const payment = await gateway.getPayment(session.providerPaymentId);
if (!payment) throw new SelfServiceCheckoutError("PAYMENT_NOT_FOUND");
await updateCheckoutSessionStatus(session.id, {
pending: !isPaidPayment(payment),
status: payment.status,
providerPaymentId: payment.providerPaymentId,
invoiceExternalId: payment.metadata.invoiceExternalId ?? session.invoiceExternalId,
lagoSubscriptionId: payment.metadata.lagoSubscriptionId ?? session.lagoSubscriptionId,
});
if (!isPaidPayment(payment)) {
return null;
}
await syncPaidCheckoutSession(payment, session);
const product = session.subscriptionProductId ? await getSubscriptionProduct(session.subscriptionProductId) : null;
const flatPrice = product?.prices.find((price) => price.id === session.subscriptionPriceId) ?? undefined;
const responseFlatPrice: SubscriptionPrice | undefined =
flatPrice && flatPrice.id
? {
...flatPrice,
id: flatPrice.id,
}
: undefined;
return {
id: session.id,
customer: {
id: session.fromTenantId ?? input.tenantId,
email: session.email,
name: session.email,
},
products: product
? [
{
id: requireRecordId(product.id, "PLAN_NOT_FOUND"),
title: product.title,
quantity: session.quantity,
subscription: session.lagoSubscriptionId ?? undefined,
prices: [{ flatPrice: responseFlatPrice, quantity: session.quantity }],
},
]
: [],
status: await getCheckoutSessionStatus(session.id),
source: "self-service",
};
}