118 lines
4.3 KiB
TypeScript
118 lines
4.3 KiB
TypeScript
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),
|
|
};
|
|
}
|