361 lines
12 KiB
TypeScript
361 lines
12 KiB
TypeScript
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",
|
|
};
|
|
}
|