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; }; const CUSTOMER_INVOICE_PAGE_SIZE = 50; const CUSTOMER_INVOICE_MAX_PAGES = 100; 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 { const gateway = resolveGateway(deps); if (!gateway) throw new CustomerBillingInvoiceError("CONFIGURATION_MISSING"); const ownedInvoices: BillingGatewayInvoice[] = []; const seenInvoiceIds = new Set(); for (let page = 1; page <= CUSTOMER_INVOICE_MAX_PAGES; page += 1) { const invoices = await gateway.listInvoices({ tenantId: input.tenantId, page, perPage: CUSTOMER_INVOICE_PAGE_SIZE }); let addedInvoice = false; for (const invoice of invoices) { if (invoice.externalCustomerId !== input.tenantId || seenInvoiceIds.has(invoice.providerInvoiceId)) continue; seenInvoiceIds.add(invoice.providerInvoiceId); ownedInvoices.push(invoice); addedInvoice = true; } if (invoices.length < CUSTOMER_INVOICE_PAGE_SIZE || !addedInvoice) break; } return ownedInvoices.map((invoice) => toCustomerInvoice(invoice, input.tenantSlug)); } export async function getCustomerBillingInvoiceDownloadUrl( input: { tenantId: string; invoiceId: string }, deps: CustomerInvoiceDeps = {} ): Promise { return (await getCustomerBillingInvoiceDownloadTarget(input, deps)).fileUrl; } export async function getCustomerBillingInvoiceDownloadTarget( input: { tenantId: string; invoiceId: string }, deps: CustomerInvoiceDeps = {} ): Promise { const gateway = resolveGateway(deps); if (!gateway) throw new CustomerBillingInvoiceError("CONFIGURATION_MISSING"); const ownedInvoice = await gateway.getInvoice(input.invoiceId); if (!ownedInvoice || ownedInvoice.externalCustomerId !== input.tenantId) { 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), }; }