1519 lines
63 KiB
TypeScript
1519 lines
63 KiB
TypeScript
import { createHash, randomUUID } from "node:crypto";
|
|
import {
|
|
createLagoBillingGateway,
|
|
createMolliePaymentGateway,
|
|
defaultMollieFirstPaymentMethod,
|
|
ensureActiveLagoSubscription,
|
|
mollieSepaFirstPaymentMethods,
|
|
resolveMollieCheckoutPaymentMethodRequirement,
|
|
type BillingGateway,
|
|
type BillingGatewayInvoice,
|
|
type BillingGatewaySubscription,
|
|
type CustomerPaymentGateway,
|
|
type ExhaustiveCustomerPaymentGateway,
|
|
type MolliePaymentMethodId,
|
|
type PaymentGatewayPayment,
|
|
} from "@hivegrid/billing";
|
|
import { loadWebConfig } from "@hivegrid/config";
|
|
import { applyLagoSubscriptionSync, applyMolliePaymentSync } from "@hivegrid/db/billing-sync.server";
|
|
import { reserveRecurringInvoiceCollection } from "@hivegrid/db/recurring-invoice-collection.server";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import type { CheckoutSessionStatus, SubscriptionPrice, SubscriptionProduct } from "@hivegrid/db/prisma-browser";
|
|
import { getBillingCatalogStorageAddOn, hiveGridBillingCatalogVersion, hiveGridVat } from "@hivegrid/entitlements";
|
|
import {
|
|
correlateCheckoutSessionProviderInvoice,
|
|
claimCheckoutSessionStatus,
|
|
getCheckoutSessionStatus,
|
|
getSubscriptionProduct,
|
|
getTenantSubscription,
|
|
updateCheckoutSessionStatus,
|
|
transitionClaimedCheckoutSessionStatus,
|
|
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 { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
|
import { clearTenantSubscriptionCache } from "~/utils/services/.server/subscriptionService";
|
|
import { assertCheckoutPaymentMethodAvailable, CheckoutPaymentMethodError, toMollieLocale } from "./payment-methods.server";
|
|
import {
|
|
acquireTenantRecurringCheckoutPolicyLock,
|
|
BASE_CHECKOUT_SCOPE_PREFIX,
|
|
resolveLockedRecurringCheckoutPolicyAmount,
|
|
} from "./recurring-checkout-policy.server";
|
|
import {
|
|
previewSelfServiceSubscription,
|
|
resolveOtherActiveRecurringGrossTotalCents,
|
|
SelfServiceSubscriptionValidationError,
|
|
type SelfServiceSubscriptionSelection,
|
|
} from "./self-service-subscription.server";
|
|
|
|
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"
|
|
| "SEAT_QUANTITY_INVALID"
|
|
| "SEAT_QUANTITY_BELOW_USAGE"
|
|
| "CURRENT_PERIOD_END_MISSING"
|
|
| "NO_CHANGE"
|
|
| "SESSION_NOT_FOUND"
|
|
| "PAYMENT_NOT_FOUND"
|
|
| "PAYMENT_METHOD_INVALID"
|
|
| "PAYMENT_METHOD_UNAVAILABLE"
|
|
| "DEFERRED_SEPA_PAYMENT_UNAVAILABLE"
|
|
| "CHECKOUT_IN_PROGRESS"
|
|
| "PAYMENT_METADATA_MISMATCH"
|
|
| "SUBSCRIPTION_ACTIVATION_FAILED"
|
|
) {
|
|
super(code);
|
|
this.i18nKey = `billing:selfServiceSubscription.errors.${
|
|
code === "CHECKOUT_IN_PROGRESS" ? "CHECKOUT_NOT_PAYABLE" : code === "PAYMENT_METADATA_MISMATCH" ? "SUBSCRIPTION_ACTIVATION_FAILED" : code
|
|
}`;
|
|
}
|
|
}
|
|
|
|
type TenantCheckoutContext = {
|
|
tenantId: string;
|
|
tenantSlug: string;
|
|
tenantName: string;
|
|
userId: string;
|
|
userEmail: string;
|
|
userName: string;
|
|
};
|
|
|
|
export type CreateSelfServiceCheckoutInput = TenantCheckoutContext & {
|
|
request: Request;
|
|
checkoutRequestKey: string;
|
|
productId: string;
|
|
priceId?: string;
|
|
billingPeriod: number;
|
|
currency: string;
|
|
quantity?: number;
|
|
officeSeatQuantity?: number;
|
|
fieldSeatQuantity?: number;
|
|
storageAddOnCodes?: readonly string[];
|
|
paymentMethod?: string | null;
|
|
paymentLocale?: string;
|
|
postActivationEmailMarketingAddOnCode?: string | null;
|
|
};
|
|
|
|
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";
|
|
};
|
|
|
|
export type SelfServiceCheckoutReturnState = "paid" | "processing" | "cancelled" | "failed" | "expired";
|
|
|
|
type SelfServiceCheckoutDeps = {
|
|
lagoGateway?: BillingGateway | null;
|
|
mollieGateway?: ExhaustiveCustomerPaymentGateway | null;
|
|
now?: () => Date;
|
|
reserveCheckoutSession?: ReserveCanonicalBaseCheckoutSession;
|
|
};
|
|
|
|
const CHECKOUT_REQUEST_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/u;
|
|
const CHECKOUT_CREATION_STALE_MS = 2 * 60 * 1000;
|
|
const RETRYABLE_TERMINAL_PAYMENT_STATUSES = ["canceled", "failed", "expired"] as const;
|
|
|
|
type CheckoutResult = { sessionId: string; checkoutUrl: string; providerPaymentId: 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 createConfiguredMollieGateway(): ExhaustiveCustomerPaymentGateway | 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 normalizeStorageCodes(codes: readonly string[] | null | undefined): string[] {
|
|
return [...new Set(codes ?? [])].sort();
|
|
}
|
|
|
|
function checkoutSessionId(tenantId: string, requestKey: string): string {
|
|
const digest = createHash("sha256").update(`${tenantId}:${requestKey}`).digest("hex").slice(0, 32);
|
|
return `hgco_${digest}`;
|
|
}
|
|
|
|
function canonicalCheckoutScopeKey(businessFingerprint: string): string {
|
|
return `${BASE_CHECKOUT_SCOPE_PREFIX}${businessFingerprint}`;
|
|
}
|
|
|
|
function checkoutAttemptSessionId(tenantId: string, businessFingerprint: string): string {
|
|
const digest = createHash("sha256").update(`${tenantId}:${businessFingerprint}:${randomUUID()}`).digest("hex").slice(0, 32);
|
|
return `hgco_${digest}`;
|
|
}
|
|
|
|
function providerIdempotencyKey(operation: "customer" | "payment", reference: string): string {
|
|
return `hivegrid-checkout-${operation}-${createHash("sha256").update(reference).digest("hex").slice(0, 40)}`;
|
|
}
|
|
|
|
function sameStringArray(left: readonly string[] | null | undefined, right: readonly string[] | null | undefined): boolean {
|
|
return JSON.stringify(normalizeStorageCodes(left)) === JSON.stringify(normalizeStorageCodes(right));
|
|
}
|
|
|
|
type StoredCheckoutIntent = {
|
|
v: 1 | 2;
|
|
path: string;
|
|
requestFingerprint: string;
|
|
businessFingerprint: string | null;
|
|
trialEndsAt: string | null;
|
|
commitmentEndsAt: string | null;
|
|
changeEffectiveAt: "immediate" | "period_end";
|
|
changeEffectiveAtDate: string | null;
|
|
managedPlanCode: string;
|
|
managedPlanAmountCents: number;
|
|
paymentPolicyAmountCents: number;
|
|
billingFlow: "self_service_new" | "self_service_change";
|
|
lagoCustomerId: string | null;
|
|
mollieCustomerId: string | null;
|
|
lagoProviderSubscriptionId: string | null;
|
|
};
|
|
|
|
type CheckoutPaymentIntent = Pick<
|
|
StoredCheckoutIntent,
|
|
| "commitmentEndsAt"
|
|
| "trialEndsAt"
|
|
| "changeEffectiveAt"
|
|
| "changeEffectiveAtDate"
|
|
| "managedPlanCode"
|
|
| "billingFlow"
|
|
| "lagoCustomerId"
|
|
| "mollieCustomerId"
|
|
| "lagoProviderSubscriptionId"
|
|
>;
|
|
|
|
const CHECKOUT_INTENT_MARKER = "#hivegrid-checkout-v1=";
|
|
|
|
function encodeCheckoutIntent(intent: StoredCheckoutIntent): string {
|
|
return `${intent.path}${CHECKOUT_INTENT_MARKER}${Buffer.from(JSON.stringify(intent), "utf8").toString("base64url")}`;
|
|
}
|
|
|
|
function decodeCheckoutIntent(fromUrl: string): StoredCheckoutIntent {
|
|
const markerIndex = fromUrl.indexOf(CHECKOUT_INTENT_MARKER);
|
|
if (markerIndex <= 0) throw new SelfServiceCheckoutError("PAYMENT_METADATA_MISMATCH");
|
|
try {
|
|
const parsed = JSON.parse(
|
|
Buffer.from(fromUrl.slice(markerIndex + CHECKOUT_INTENT_MARKER.length), "base64url").toString("utf8")
|
|
) as Partial<StoredCheckoutIntent>;
|
|
if (
|
|
(parsed.v !== 1 && parsed.v !== 2) ||
|
|
typeof parsed.path !== "string" ||
|
|
parsed.path !== fromUrl.slice(0, markerIndex) ||
|
|
typeof parsed.requestFingerprint !== "string" ||
|
|
!/^[a-f0-9]{64}$/u.test(parsed.requestFingerprint) ||
|
|
(parsed.v === 2 && (typeof parsed.businessFingerprint !== "string" || !/^[a-f0-9]{64}$/u.test(parsed.businessFingerprint))) ||
|
|
!isNullableIsoDate(parsed.trialEndsAt) ||
|
|
!isNullableIsoDate(parsed.commitmentEndsAt) ||
|
|
(parsed.changeEffectiveAt !== "immediate" && parsed.changeEffectiveAt !== "period_end") ||
|
|
!isNullableIsoDate(parsed.changeEffectiveAtDate) ||
|
|
typeof parsed.managedPlanCode !== "string" ||
|
|
!parsed.managedPlanCode ||
|
|
!Number.isSafeInteger(parsed.managedPlanAmountCents) ||
|
|
(parsed.managedPlanAmountCents ?? -1) < 0 ||
|
|
!Number.isSafeInteger(parsed.paymentPolicyAmountCents) ||
|
|
(parsed.paymentPolicyAmountCents ?? -1) < 0 ||
|
|
(parsed.billingFlow !== "self_service_new" && parsed.billingFlow !== "self_service_change") ||
|
|
!isNullableProviderId(parsed.lagoCustomerId) ||
|
|
!isNullableProviderId(parsed.mollieCustomerId) ||
|
|
!isNullableProviderId(parsed.lagoProviderSubscriptionId)
|
|
) {
|
|
throw new Error("invalid checkout intent");
|
|
}
|
|
return {
|
|
...(parsed as StoredCheckoutIntent),
|
|
businessFingerprint: parsed.v === 2 ? parsed.businessFingerprint! : null,
|
|
};
|
|
} catch (error) {
|
|
if (error instanceof SelfServiceCheckoutError) throw error;
|
|
throw new SelfServiceCheckoutError("PAYMENT_METADATA_MISMATCH");
|
|
}
|
|
}
|
|
|
|
function resolveCompletionCheckoutIntent(session: CheckoutSessionStatus & { tenantId: string }, payment: PaymentGatewayPayment): CheckoutPaymentIntent {
|
|
if (session.fromUrl.includes(CHECKOUT_INTENT_MARKER)) {
|
|
return decodeCheckoutIntent(session.fromUrl);
|
|
}
|
|
return decodeLegacyPaidCheckoutIntent(session, payment);
|
|
}
|
|
|
|
function decodeLegacyPaidCheckoutIntent(session: CheckoutSessionStatus & { tenantId: string }, payment: PaymentGatewayPayment): CheckoutPaymentIntent {
|
|
const metadata = payment.metadata;
|
|
const trialEndsAt = nullableText(metadata.trialEndsAt);
|
|
const commitmentEndsAt = nullableText(metadata.commitmentEndsAt);
|
|
const changeEffectiveAtDate = nullableText(metadata.changeEffectiveAtDate);
|
|
const lagoCustomerId = nullableText(metadata.lagoCustomerId);
|
|
const mollieCustomerId = nullableText(metadata.mollieCustomerId);
|
|
const lagoProviderSubscriptionId = nullableText(metadata.lagoProviderSubscriptionId);
|
|
const managedPlanCode = nullableText(metadata.lagoPlanCode);
|
|
|
|
if (
|
|
payment.status !== "paid" ||
|
|
!payment.paidAt ||
|
|
Number.isNaN(new Date(payment.paidAt).getTime()) ||
|
|
session.provider !== "mollie" ||
|
|
!isLegacyCheckoutPath(session.fromUrl) ||
|
|
!isNullableIsoDate(trialEndsAt) ||
|
|
!isNullableIsoDate(commitmentEndsAt) ||
|
|
!isNullableIsoDate(changeEffectiveAtDate) ||
|
|
nullableDateIso(session.commitmentEndsAt) !== commitmentEndsAt ||
|
|
(metadata.changeEffectiveAt !== "immediate" && metadata.changeEffectiveAt !== "period_end") ||
|
|
(metadata.billingFlow !== "self_service_new" && metadata.billingFlow !== "self_service_change") ||
|
|
!lagoCustomerId ||
|
|
!mollieCustomerId ||
|
|
!managedPlanCode ||
|
|
!isNullableProviderId(lagoProviderSubscriptionId)
|
|
) {
|
|
throw new SelfServiceCheckoutError("PAYMENT_METADATA_MISMATCH");
|
|
}
|
|
|
|
return {
|
|
trialEndsAt,
|
|
commitmentEndsAt,
|
|
changeEffectiveAt: metadata.changeEffectiveAt,
|
|
changeEffectiveAtDate,
|
|
managedPlanCode,
|
|
billingFlow: metadata.billingFlow,
|
|
lagoCustomerId,
|
|
mollieCustomerId,
|
|
lagoProviderSubscriptionId,
|
|
};
|
|
}
|
|
|
|
function isLegacyCheckoutPath(value: string): boolean {
|
|
if (
|
|
!value.startsWith("/") ||
|
|
value.startsWith("//") ||
|
|
value.length > 2_048 ||
|
|
value.includes("?") ||
|
|
value.includes("#") ||
|
|
/[\u0000-\u001F\u007F]/u.test(value)
|
|
) {
|
|
return false;
|
|
}
|
|
try {
|
|
const base = new URL("https://legacy-checkout.invalid");
|
|
const parsed = new URL(value, base);
|
|
return parsed.origin === base.origin && parsed.pathname === value;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function isNullableIsoDate(value: unknown): value is string | null {
|
|
return value === null || (typeof value === "string" && !Number.isNaN(new Date(value).getTime()));
|
|
}
|
|
|
|
function isNullableProviderId(value: unknown): value is string | null {
|
|
return value === null || (typeof value === "string" && value.trim().length > 0);
|
|
}
|
|
|
|
function nullableText(value: string | null | undefined): string | null {
|
|
return value?.trim() || null;
|
|
}
|
|
|
|
function nullableDateIso(value: Date | null | undefined): string | null {
|
|
return value ? value.toISOString() : null;
|
|
}
|
|
|
|
function checkoutRequestFingerprint(value: Record<string, unknown>): string {
|
|
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
}
|
|
|
|
function checkoutClaimStatus(): string {
|
|
return `provider_claimed_${randomUUID().replaceAll("-", "")}`;
|
|
}
|
|
|
|
function isCheckoutClaimStatus(status: string): boolean {
|
|
return status === "creating" || status.startsWith("provider_claimed_");
|
|
}
|
|
|
|
function isReusableCheckoutPayment(payment: PaymentGatewayPayment): boolean {
|
|
return payment.status === "open" || payment.status === "pending" || payment.status === "authorized";
|
|
}
|
|
|
|
function isRetryableTerminalPaymentStatus(
|
|
status: PaymentGatewayPayment["status"] | string
|
|
): status is (typeof RETRYABLE_TERMINAL_PAYMENT_STATUSES)[number] {
|
|
return RETRYABLE_TERMINAL_PAYMENT_STATUSES.some((candidate) => candidate === status);
|
|
}
|
|
|
|
type CanonicalBaseCheckoutSessionCreate = {
|
|
id: string;
|
|
tenantId: string;
|
|
pending: true;
|
|
email: string;
|
|
fromUrl: string;
|
|
fromUserId: string;
|
|
provider: "mollie";
|
|
providerPaymentId: null;
|
|
invoiceExternalId: string;
|
|
subscriptionProductId: string;
|
|
subscriptionPriceId: string;
|
|
lagoSubscriptionId: string;
|
|
planCode: string;
|
|
productKind: "base_plan";
|
|
scopeKey: string;
|
|
quantity: number;
|
|
officeSeatQuantity: number;
|
|
fieldSeatQuantity: number;
|
|
billingCadence: string;
|
|
commitmentEndsAt: Date | null;
|
|
storageAddOnCodes: string[];
|
|
amountCents: number;
|
|
currency: string;
|
|
checkoutUrl: null;
|
|
status: string;
|
|
};
|
|
|
|
type CanonicalBaseCheckoutReservationInput = {
|
|
tenantId: string;
|
|
businessFingerprint: string;
|
|
selectedRecurringGrossAmountCents: number;
|
|
now: Date;
|
|
createSession: (sessionId: string, paymentPolicyAmountCents?: number) => CanonicalBaseCheckoutSessionCreate;
|
|
};
|
|
|
|
type CanonicalBaseCheckoutReservation = {
|
|
session: CheckoutSessionStatus & { tenantId: string };
|
|
created: boolean;
|
|
};
|
|
|
|
type ReserveCanonicalBaseCheckoutSession = (
|
|
input: CanonicalBaseCheckoutReservationInput
|
|
) => Promise<CanonicalBaseCheckoutReservation>;
|
|
|
|
/**
|
|
* Serializes all open base-checkout reservations for a tenant in PostgreSQL.
|
|
* The browser request UUID is deliberately not part of the commercial scope:
|
|
* two tabs or two authorized tenant users therefore converge on one durable
|
|
* attempt. Only a provider-terminal attempt releases the scope for a new row.
|
|
*/
|
|
export const reserveCanonicalBaseCheckoutSession: ReserveCanonicalBaseCheckoutSession = async (input) => {
|
|
const scopeKey = canonicalCheckoutScopeKey(input.businessFingerprint);
|
|
return withTenantRLS(input.tenantId, async (tx) => {
|
|
await acquireTenantRecurringCheckoutPolicyLock(tx, input.tenantId);
|
|
const active = await tx.checkoutSessionStatus.findMany({
|
|
where: {
|
|
tenantId: input.tenantId,
|
|
productKind: "base_plan",
|
|
scopeKey: { startsWith: BASE_CHECKOUT_SCOPE_PREFIX },
|
|
pending: true,
|
|
status: { notIn: [...RETRYABLE_TERMINAL_PAYMENT_STATUSES] },
|
|
},
|
|
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
|
take: 2,
|
|
});
|
|
if (active.length > 1) throw new SelfServiceCheckoutError("CHECKOUT_IN_PROGRESS");
|
|
const existing = active[0];
|
|
if (existing) {
|
|
if (existing.scopeKey !== scopeKey) throw new SelfServiceCheckoutError("CHECKOUT_IN_PROGRESS");
|
|
return { session: existing, created: false };
|
|
}
|
|
|
|
const paymentPolicyAmountCents = await resolveLockedRecurringCheckoutPolicyAmount(tx, {
|
|
tenantId: input.tenantId,
|
|
now: input.now,
|
|
selectedRecurringGrossAmountCents: input.selectedRecurringGrossAmountCents,
|
|
replacement: { replacesBasePlan: true },
|
|
allowOpenBaseCheckout: true,
|
|
});
|
|
const sessionId = checkoutAttemptSessionId(input.tenantId, input.businessFingerprint);
|
|
const session = await tx.checkoutSessionStatus.create({ data: input.createSession(sessionId, paymentPolicyAmountCents) });
|
|
return { session, created: true };
|
|
});
|
|
};
|
|
|
|
function assertProviderBinding(expected: string | null, actual: string | null): void {
|
|
if (expected !== null && expected !== actual) throw new SelfServiceCheckoutError("PAYMENT_METADATA_MISMATCH");
|
|
}
|
|
|
|
function assertMatchingReservedSession(
|
|
session: CheckoutSessionStatus & { tenantId: string },
|
|
expected: {
|
|
tenantId: string;
|
|
userId: string;
|
|
email: string;
|
|
productId: string;
|
|
priceId: string;
|
|
planCode: string;
|
|
quantity: number;
|
|
officeSeatQuantity: number;
|
|
fieldSeatQuantity: number;
|
|
billingCadence: string;
|
|
storageAddOnCodes: readonly string[];
|
|
amountCents: number;
|
|
currency: string;
|
|
lagoSubscriptionId: string;
|
|
path: string;
|
|
requestFingerprint: string;
|
|
businessFingerprint: string;
|
|
}
|
|
): void {
|
|
const intent = decodeCheckoutIntent(session.fromUrl);
|
|
const canonicalScope = canonicalCheckoutScopeKey(expected.businessFingerprint);
|
|
const canonicalReservation = session.scopeKey != null || intent.businessFingerprint !== null;
|
|
if (
|
|
session.tenantId !== expected.tenantId ||
|
|
session.subscriptionProductId !== expected.productId ||
|
|
session.subscriptionPriceId !== expected.priceId ||
|
|
session.planCode !== expected.planCode ||
|
|
session.quantity !== expected.quantity ||
|
|
session.officeSeatQuantity !== expected.officeSeatQuantity ||
|
|
session.fieldSeatQuantity !== expected.fieldSeatQuantity ||
|
|
session.billingCadence !== expected.billingCadence ||
|
|
!sameStringArray(session.storageAddOnCodes, expected.storageAddOnCodes) ||
|
|
session.amountCents !== expected.amountCents ||
|
|
session.currency?.toUpperCase() !== expected.currency.toUpperCase() ||
|
|
(session.invoiceExternalId !== session.id && session.providerPaymentId === null) ||
|
|
session.lagoSubscriptionId !== expected.lagoSubscriptionId
|
|
) {
|
|
throw new SelfServiceCheckoutError("PAYMENT_METADATA_MISMATCH");
|
|
}
|
|
if (
|
|
(canonicalReservation
|
|
? session.scopeKey !== canonicalScope || intent.businessFingerprint !== expected.businessFingerprint
|
|
: session.fromUserId !== expected.userId ||
|
|
session.email !== expected.email ||
|
|
intent.path !== expected.path ||
|
|
intent.requestFingerprint !== expected.requestFingerprint) ||
|
|
nullableDateIso(session.commitmentEndsAt) !== intent.commitmentEndsAt
|
|
) {
|
|
throw new SelfServiceCheckoutError("PAYMENT_METADATA_MISMATCH");
|
|
}
|
|
}
|
|
|
|
async function replayPersistedCheckout(
|
|
session: CheckoutSessionStatus & { tenantId: string },
|
|
gateway: ExhaustiveCustomerPaymentGateway,
|
|
intent: StoredCheckoutIntent
|
|
): Promise<CheckoutResult | { terminalStatus: (typeof RETRYABLE_TERMINAL_PAYMENT_STATUSES)[number] }> {
|
|
if (!session.providerPaymentId) throw new SelfServiceCheckoutError("PAYMENT_NOT_FOUND");
|
|
const payment = await gateway.getPayment(session.providerPaymentId);
|
|
if (!payment) throw new SelfServiceCheckoutError("PAYMENT_NOT_FOUND");
|
|
assertMatchingSelfServicePayment(session, payment, intent);
|
|
if (isReusableCheckoutPayment(payment) && payment.checkoutUrl) {
|
|
return { sessionId: session.id, checkoutUrl: payment.checkoutUrl, providerPaymentId: payment.providerPaymentId };
|
|
}
|
|
if (payment.status === "paid") throw new SelfServiceCheckoutError("NO_CHANGE");
|
|
if (isRetryableTerminalPaymentStatus(payment.status)) return { terminalStatus: payment.status };
|
|
throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
|
|
}
|
|
|
|
function assertMatchingSelfServicePayment(
|
|
session: CheckoutSessionStatus & { tenantId: string },
|
|
payment: PaymentGatewayPayment,
|
|
intent: CheckoutPaymentIntent
|
|
): void {
|
|
const metadata = payment.metadata;
|
|
const refundedAmountCents = payment.amountRefundedCents ?? 0;
|
|
if (
|
|
payment.externalId !== session.id ||
|
|
(session.providerPaymentId !== null && session.providerPaymentId !== payment.providerPaymentId) ||
|
|
metadata.paymentExternalId !== session.id ||
|
|
metadata.invoiceExternalId !== session.id ||
|
|
metadata.tenantId !== session.tenantId ||
|
|
metadata.lagoSubscriptionId !== session.lagoSubscriptionId ||
|
|
metadata.planCode !== session.planCode ||
|
|
metadata.subscriptionPriceId !== session.subscriptionPriceId ||
|
|
metadata.seatQuantity !== session.quantity ||
|
|
metadata.officeSeatQuantity !== session.officeSeatQuantity ||
|
|
metadata.fieldSeatQuantity !== session.fieldSeatQuantity ||
|
|
metadata.billingCadence !== session.billingCadence ||
|
|
!sameStringArray(metadata.storageAddOnCodes, session.storageAddOnCodes) ||
|
|
nullableText(metadata.commitmentEndsAt) !== intent.commitmentEndsAt ||
|
|
nullableText(metadata.trialEndsAt) !== intent.trialEndsAt ||
|
|
metadata.changeEffectiveAt !== intent.changeEffectiveAt ||
|
|
nullableText(metadata.changeEffectiveAtDate) !== intent.changeEffectiveAtDate ||
|
|
nullableText(metadata.lagoPlanCode) !== intent.managedPlanCode ||
|
|
nullableText(metadata.lagoProviderSubscriptionId) !== intent.lagoProviderSubscriptionId ||
|
|
nullableText(metadata.lagoCustomerId) !== intent.lagoCustomerId ||
|
|
nullableText(metadata.mollieCustomerId) !== intent.mollieCustomerId ||
|
|
payment.amountCents !== session.amountCents ||
|
|
payment.currency?.toUpperCase() !== session.currency?.toUpperCase() ||
|
|
metadata.billingFlow !== intent.billingFlow ||
|
|
refundedAmountCents !== 0
|
|
) {
|
|
throw new SelfServiceCheckoutError("PAYMENT_METADATA_MISMATCH");
|
|
}
|
|
}
|
|
|
|
function resolvePlanCode(product: Pick<SubscriptionProduct, "id" | "code" | "lagoPlanCode">, price: Pick<SubscriptionPrice, "lagoPlanCode">): string {
|
|
return price.lagoPlanCode?.trim() || product.lagoPlanCode?.trim() || product.code?.trim() || product.id;
|
|
}
|
|
|
|
function buildManagedPlanCode(input: {
|
|
planCode: string;
|
|
amountCents: number;
|
|
currency: string;
|
|
officeSeatQuantity: number;
|
|
fieldSeatQuantity: number;
|
|
storageAddOnCodes: readonly string[];
|
|
}): string {
|
|
const fingerprint = JSON.stringify({
|
|
catalogVersion: hiveGridBillingCatalogVersion,
|
|
planCode: input.planCode,
|
|
amountCents: input.amountCents,
|
|
currency: input.currency,
|
|
officeSeatQuantity: input.officeSeatQuantity,
|
|
fieldSeatQuantity: input.fieldSeatQuantity,
|
|
storageAddOnCodes: [...input.storageAddOnCodes].sort(),
|
|
});
|
|
const digest = createHash("sha256").update(fingerprint).digest("hex").slice(0, 16);
|
|
const version = hiveGridBillingCatalogVersion.replace(/[^A-Za-z0-9]+/gu, "_");
|
|
const baseCode = input.planCode.replace(/[^A-Za-z0-9_-]+/gu, "_").slice(0, 60);
|
|
return `hg_price_${version}_${baseCode}_${digest}`;
|
|
}
|
|
|
|
function buildManagedPlanDisplayName(
|
|
productTitle: string,
|
|
officeSeatQuantity: number,
|
|
fieldSeatQuantity: number,
|
|
storageAddOnCodes: readonly string[]
|
|
): string {
|
|
const storageLabels = storageAddOnCodes.map((code) => getBillingCatalogStorageAddOn(code)?.publicName ?? code);
|
|
return [
|
|
`${productTitle} · ${officeSeatQuantity} Büro · ${fieldSeatQuantity} Baustelle`,
|
|
...(storageLabels.length > 0 ? [`Speicher: ${storageLabels.join(", ")}`] : []),
|
|
].join(" · ");
|
|
}
|
|
|
|
function findCheckoutPrice(product: SubscriptionProductWithDetails, billingPeriod: number, currency: string, priceId?: string) {
|
|
return product.prices.find(
|
|
(price) =>
|
|
price.active &&
|
|
price.type === SubscriptionPriceType.RECURRING &&
|
|
(!priceId || price.id === priceId) &&
|
|
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 buildRedirectUrl(tenantSlug: string, sessionId: string, emailMarketingAddOnCode?: string | null) {
|
|
const routing = loadWebConfig().config.routing;
|
|
const path = `/subscribe/${encodeURIComponent(tenantSlug)}/${encodeURIComponent(sessionId)}/success`;
|
|
const redirectUrl = new URL(absolutePublicAppPath(routing, path));
|
|
if (emailMarketingAddOnCode) redirectUrl.searchParams.set("email_add_on", emailMarketingAddOnCode);
|
|
return redirectUrl.toString();
|
|
}
|
|
|
|
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(),
|
|
});
|
|
}
|
|
|
|
async function ensureMollieCustomer(
|
|
gateway: CustomerPaymentGateway,
|
|
input: TenantCheckoutContext,
|
|
existingCustomerId: string | null | undefined
|
|
): Promise<string> {
|
|
const existing = existingCustomerId?.trim();
|
|
if (existing) return existing;
|
|
const customer = await gateway.createCustomer({
|
|
tenantId: input.tenantId,
|
|
name: input.tenantName,
|
|
email: input.userEmail,
|
|
idempotencyKey: providerIdempotencyKey("customer", input.tenantId),
|
|
});
|
|
return customer.providerCustomerId;
|
|
}
|
|
|
|
function isPaidPayment(payment: PaymentGatewayPayment | null): payment is PaymentGatewayPayment {
|
|
return payment?.status === "paid";
|
|
}
|
|
|
|
export function projectSelfServiceCheckoutReturnState(status: PaymentGatewayPayment["status"] | string | null | undefined): SelfServiceCheckoutReturnState {
|
|
if (status === "paid") return "paid";
|
|
if (status === "open" || status === "pending" || status === "authorized") return "processing";
|
|
if (status === "canceled") return "cancelled";
|
|
if (status === "expired") return "expired";
|
|
return "failed";
|
|
}
|
|
|
|
async function buildSelfServiceCheckoutResponse(session: CheckoutSessionStatus & { tenantId: string }): Promise<SelfServiceCheckoutResponse> {
|
|
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.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: session,
|
|
source: "self-service",
|
|
};
|
|
}
|
|
|
|
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 & { tenantId: string },
|
|
providerInvoiceExternalId?: string,
|
|
activatedSubscription?: BillingGatewaySubscription | null
|
|
) {
|
|
const tenantId = payment.metadata.tenantId ?? session.tenantId;
|
|
const invoiceExternalId = session.invoiceExternalId ?? payment.metadata.invoiceExternalId;
|
|
if (!tenantId || !invoiceExternalId) return;
|
|
|
|
await applyMolliePaymentSync({
|
|
tenantId,
|
|
eventKey: mollieEventKey(payment),
|
|
paymentExternalId: payment.externalId ?? payment.providerPaymentId,
|
|
providerPaymentId: payment.providerPaymentId,
|
|
invoiceExternalId,
|
|
lagoSubscriptionId: payment.metadata.lagoSubscriptionId ?? session.lagoSubscriptionId,
|
|
mollieCustomerId: payment.metadata.mollieCustomerId,
|
|
status: payment.status,
|
|
selfServiceCheckout: true,
|
|
preserveSubscriptionStatus:
|
|
payment.status === "paid" ||
|
|
(payment.metadata.billingFlow === "self_service_change" &&
|
|
(payment.status === "failed" || payment.status === "expired" || payment.status === "canceled")),
|
|
receivedAt: new Date(),
|
|
});
|
|
|
|
const planCode = payment.metadata.planCode ?? session.planCode;
|
|
const lagoSubscriptionId = payment.metadata.lagoSubscriptionId ?? session.lagoSubscriptionId;
|
|
const receivedAt = new Date();
|
|
const effectiveAtDate = parseProviderDate(payment.metadata.changeEffectiveAtDate);
|
|
const trialEndsAt = parseProviderDate(payment.metadata.trialEndsAt);
|
|
const isTrial = Boolean(trialEndsAt && trialEndsAt > receivedAt);
|
|
if (planCode && lagoSubscriptionId) {
|
|
await applyLagoSubscriptionSync({
|
|
tenantId,
|
|
eventKey: lagoEventKey(payment),
|
|
lagoCustomerId: payment.metadata.lagoCustomerId,
|
|
lagoSubscriptionId,
|
|
billingProviderSubscriptionId: activatedSubscription?.providerSubscriptionId ?? payment.metadata.lagoProviderSubscriptionId,
|
|
fromCheckoutSessionId: payment.metadata.paymentExternalId ?? session.id,
|
|
planCode,
|
|
subscriptionPriceId: payment.metadata.subscriptionPriceId ?? session.subscriptionPriceId,
|
|
seatQuantity: payment.metadata.seatQuantity ?? session.quantity,
|
|
officeSeatQuantity: payment.metadata.officeSeatQuantity ?? session.officeSeatQuantity,
|
|
fieldSeatQuantity: payment.metadata.fieldSeatQuantity ?? session.fieldSeatQuantity,
|
|
billingCadence: payment.metadata.billingCadence ?? session.billingCadence,
|
|
commitmentEndsAt: parseProviderDate(payment.metadata.commitmentEndsAt) ?? session.commitmentEndsAt,
|
|
storageAddOnCodes: payment.metadata.storageAddOnCodes ?? session.storageAddOnCodes,
|
|
invoiceExternalId: providerInvoiceExternalId ?? invoiceExternalId,
|
|
status: isTrial ? "trial" : "active",
|
|
deferredUntil: payment.metadata.changeEffectiveAt === "period_end" && effectiveAtDate && effectiveAtDate > receivedAt ? effectiveAtDate : undefined,
|
|
trialStartsAt: isTrial ? receivedAt : undefined,
|
|
trialEndsAt: isTrial ? trialEndsAt : undefined,
|
|
receivedAt,
|
|
});
|
|
}
|
|
|
|
clearTenantSubscriptionCache(tenantId);
|
|
invalidateTenantModuleAccessCache(tenantId);
|
|
}
|
|
|
|
async function settlePaidInitialLagoInvoice(
|
|
payment: PaymentGatewayPayment,
|
|
tenantId: string,
|
|
gateway: BillingGateway,
|
|
subscription: BillingGatewaySubscription,
|
|
persistedProviderInvoiceId?: string
|
|
): Promise<BillingGatewayInvoice | null> {
|
|
const lagoSubscriptionId = subscription.externalId.trim();
|
|
const lagoProviderSubscriptionId = subscription.providerSubscriptionId.trim();
|
|
if (!lagoSubscriptionId || !lagoProviderSubscriptionId || !payment.amountCents || payment.amountCents <= 0) return null;
|
|
|
|
const isExactInitialInvoice = (invoice: BillingGatewayInvoice | null): invoice is BillingGatewayInvoice =>
|
|
Boolean(
|
|
invoice?.subscriptionExternalIds?.includes(lagoSubscriptionId) &&
|
|
invoice.subscriptionProviderIds?.includes(lagoProviderSubscriptionId) &&
|
|
invoice.totalAmountCents === payment.amountCents &&
|
|
(invoice.paymentStatus === "pending" || invoice.paymentStatus === "succeeded")
|
|
);
|
|
const settleExactInvoice = (invoice: BillingGatewayInvoice): Promise<BillingGatewayInvoice> =>
|
|
invoice.paymentStatus === "succeeded" ? Promise.resolve(invoice) : gateway.updateInvoicePaymentStatus(invoice.providerInvoiceId, "succeeded");
|
|
|
|
if (persistedProviderInvoiceId) {
|
|
const persistedInvoice = await gateway.getInvoice(persistedProviderInvoiceId);
|
|
return isExactInitialInvoice(persistedInvoice) ? settleExactInvoice(persistedInvoice) : null;
|
|
}
|
|
|
|
for (let attempt = 0; attempt < 12; attempt += 1) {
|
|
const invoices = await gateway.listInvoices({ tenantId, perPage: 50 });
|
|
const candidates = invoices
|
|
.filter(
|
|
(candidate) => candidate.totalAmountCents === payment.amountCents && (candidate.paymentStatus === "pending" || candidate.paymentStatus === "succeeded")
|
|
)
|
|
.sort((left, right) => (right.issuingDate ?? "").localeCompare(left.issuingDate ?? ""));
|
|
for (const candidate of candidates) {
|
|
const hasExactSubscription =
|
|
candidate.subscriptionExternalIds?.includes(lagoSubscriptionId) && candidate.subscriptionProviderIds?.includes(lagoProviderSubscriptionId);
|
|
const invoice = hasExactSubscription ? candidate : await gateway.getInvoice(candidate.providerInvoiceId);
|
|
if (!isExactInitialInvoice(invoice)) continue;
|
|
return settleExactInvoice(invoice);
|
|
}
|
|
if (attempt < 11) await new Promise((resolve) => setTimeout(resolve, 100 * (attempt + 1)));
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function parseProviderDate(value: string | null | undefined): Date | null {
|
|
if (!value) return null;
|
|
const parsed = new Date(value);
|
|
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
}
|
|
|
|
function hasConsumedTrial(subscription: Awaited<ReturnType<typeof getTenantSubscription>>): boolean {
|
|
if (!subscription) return false;
|
|
if (subscription.trialStartsAt || subscription.trialEndsAt) return true;
|
|
return subscription.products.some((product) => product.prices.some((price) => (price.subscriptionPrice?.trialDays ?? 0) > 0));
|
|
}
|
|
|
|
function toCheckoutSelection(input: CreateSelfServiceCheckoutInput, priceId: string): SelfServiceSubscriptionSelection {
|
|
return {
|
|
productId: input.productId,
|
|
priceId,
|
|
...(input.officeSeatQuantity === undefined && input.fieldSeatQuantity === undefined
|
|
? { seatQuantity: input.quantity }
|
|
: {
|
|
officeSeatQuantity: input.officeSeatQuantity,
|
|
fieldSeatQuantity: input.fieldSeatQuantity,
|
|
}),
|
|
storageAddOnCodes: input.storageAddOnCodes,
|
|
};
|
|
}
|
|
|
|
function addCalendarMonths(value: Date, months: number): Date {
|
|
const result = new Date(value);
|
|
const day = result.getUTCDate();
|
|
result.setUTCDate(1);
|
|
result.setUTCMonth(result.getUTCMonth() + months);
|
|
const lastDay = new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate();
|
|
result.setUTCDate(Math.min(day, lastDay));
|
|
return result;
|
|
}
|
|
|
|
function requiresPaymentConfirmedProviderActivation(input: { trialEndsAt: Date | null; effectiveAt: "immediate" | "period_end" }): boolean {
|
|
return input.trialEndsAt === null && input.effectiveAt === "immediate";
|
|
}
|
|
|
|
async function ensurePaidLagoSubscription(
|
|
payment: PaymentGatewayPayment,
|
|
tenantId: string,
|
|
gateway: BillingGateway
|
|
): Promise<BillingGatewaySubscription | null> {
|
|
const activatedAt = parseProviderDate(payment.paidAt) ?? new Date();
|
|
const trialEndsAt = parseProviderDate(payment.metadata.trialEndsAt);
|
|
if (trialEndsAt && trialEndsAt > activatedAt) return null;
|
|
const effectiveAtDate = parseProviderDate(payment.metadata.changeEffectiveAtDate);
|
|
if (payment.metadata.changeEffectiveAt === "period_end" && effectiveAtDate && effectiveAtDate > activatedAt) return null;
|
|
|
|
const subscriptionExternalId = payment.metadata.lagoSubscriptionId?.trim();
|
|
const lagoPlanCode = payment.metadata.lagoPlanCode?.trim();
|
|
const seatQuantity = payment.metadata.seatQuantity;
|
|
if (!subscriptionExternalId || !lagoPlanCode || !seatQuantity) {
|
|
throw new SelfServiceCheckoutError("SUBSCRIPTION_ACTIVATION_FAILED");
|
|
}
|
|
try {
|
|
return await ensureActiveLagoSubscription(gateway, {
|
|
tenantId,
|
|
subscriptionExternalId,
|
|
planCode: lagoPlanCode,
|
|
seatQuantity,
|
|
name: `${payment.metadata.planCode ?? "base-plan"} (${seatQuantity} seats)`,
|
|
endingAt: parseProviderDate(payment.metadata.commitmentEndsAt) ?? undefined,
|
|
paymentMethodType: "manual",
|
|
consolidateInvoice: false,
|
|
});
|
|
} catch {
|
|
throw new SelfServiceCheckoutError("SUBSCRIPTION_ACTIVATION_FAILED");
|
|
}
|
|
}
|
|
|
|
function rethrowSelectionError(error: unknown): never {
|
|
if (error instanceof SelfServiceSubscriptionValidationError) {
|
|
if (error.code === "SEAT_QUANTITY_INVALID" || error.code === "SEAT_QUANTITY_BELOW_USAGE" || error.code === "CURRENT_PERIOD_END_MISSING") {
|
|
throw new SelfServiceCheckoutError(error.code);
|
|
}
|
|
if (error.code === "PRICE_NOT_FOUND") throw new SelfServiceCheckoutError("PRICE_NOT_FOUND");
|
|
throw new SelfServiceCheckoutError("PLAN_NOT_PURCHASABLE");
|
|
}
|
|
throw error;
|
|
}
|
|
|
|
export async function createSelfServiceCheckout(input: CreateSelfServiceCheckoutInput, deps: SelfServiceCheckoutDeps = {}): Promise<CheckoutResult> {
|
|
return runWithRlsContext({ tenantId: input.tenantId, userId: input.userId }, () => createSelfServiceCheckoutInContext(input, deps));
|
|
}
|
|
|
|
async function createSelfServiceCheckoutInContext(input: CreateSelfServiceCheckoutInput, deps: SelfServiceCheckoutDeps): Promise<CheckoutResult> {
|
|
const requestKey = input.checkoutRequestKey.trim();
|
|
if (!CHECKOUT_REQUEST_KEY_PATTERN.test(requestKey)) throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
|
|
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, input.priceId);
|
|
if (!price) throw new SelfServiceCheckoutError("PRICE_NOT_FOUND");
|
|
const priceId = requireRecordId(price.id, "PRICE_NOT_FOUND");
|
|
|
|
let preview;
|
|
try {
|
|
preview = await previewSelfServiceSubscription(input.tenantId, toCheckoutSelection(input, priceId), deps.now?.() ?? new Date());
|
|
} catch (error) {
|
|
rethrowSelectionError(error);
|
|
}
|
|
if (preview.changeKind === "unchanged") throw new SelfServiceCheckoutError("NO_CHANGE");
|
|
const selectedOfficeSeatQuantity = preview.selectedOfficeSeatQuantity ?? preview.selectedSeatQuantity;
|
|
const selectedFieldSeatQuantity = preview.selectedFieldSeatQuantity ?? 0;
|
|
const selectedStorageAddOnCodes = normalizeStorageCodes(preview.selectedStorageAddOnCodes);
|
|
const quantity = normalizeQuantity(selectedOfficeSeatQuantity + selectedFieldSeatQuantity);
|
|
|
|
const now = deps.now?.() ?? new Date();
|
|
const tenantSubscription = await getTenantSubscription(input.tenantId);
|
|
const trialDays = preview.changeKind === "new" && !hasConsumedTrial(tenantSubscription) ? preview.trialDays : 0;
|
|
const trialEndsAt = trialDays > 0 ? new Date(now.getTime() + trialDays * 86_400_000) : null;
|
|
const amountCents = trialEndsAt || preview.effectiveAt === "period_end" ? 0 : (preview.recurringGrossTotalCents ?? preview.recurringTotalCents);
|
|
if (amountCents < 0) throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
|
|
const selectedRecurringGrossAmountCents = preview.recurringGrossTotalCents ?? preview.recurringTotalCents;
|
|
if (!Number.isSafeInteger(selectedRecurringGrossAmountCents) || selectedRecurringGrossAmountCents < 0) {
|
|
throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
|
|
}
|
|
const planCode = resolvePlanCode({ id: productId, code: product.code, lagoPlanCode: product.lagoPlanCode }, price);
|
|
const currentLagoSubscriptionId = tenantSubscription?.products.find(
|
|
(item) => item.subscriptionProduct.kind === "base_plan" && item.lagoSubscriptionId && !item.cancelledAt && (!item.endsAt || item.endsAt > now)
|
|
)?.lagoSubscriptionId;
|
|
const effectiveAtDate = parseProviderDate(preview.effectiveAtDate);
|
|
const subscriptionStartsAt = trialEndsAt ?? effectiveAtDate ?? now;
|
|
const contractMonths = price.contractMonths ?? (price.billingPeriod === 4 ? 12 : 1);
|
|
const billingCadence = price.billingCadence ?? (price.billingPeriod === 4 ? "annual_sepa" : "monthly");
|
|
const commitmentEndsAt = contractMonths > 1 ? addCalendarMonths(subscriptionStartsAt, contractMonths) : null;
|
|
const currency = price.currency.toUpperCase();
|
|
const managedPlanCode = buildManagedPlanCode({
|
|
planCode,
|
|
amountCents: preview.recurringTotalCents,
|
|
currency,
|
|
officeSeatQuantity: selectedOfficeSeatQuantity,
|
|
fieldSeatQuantity: selectedFieldSeatQuantity,
|
|
storageAddOnCodes: selectedStorageAddOnCodes,
|
|
});
|
|
const path = new URL(input.request.url).pathname;
|
|
const businessFingerprint = checkoutRequestFingerprint({
|
|
v: 1,
|
|
tenantId: input.tenantId,
|
|
productId,
|
|
priceId,
|
|
planCode,
|
|
quantity,
|
|
officeSeatQuantity: selectedOfficeSeatQuantity,
|
|
fieldSeatQuantity: selectedFieldSeatQuantity,
|
|
billingCadence,
|
|
storageAddOnCodes: selectedStorageAddOnCodes,
|
|
amountCents,
|
|
currency,
|
|
managedPlanAmountCents: preview.recurringTotalCents,
|
|
changeKind: preview.changeKind,
|
|
changeEffectiveAt: preview.effectiveAt,
|
|
changeEffectiveAtDate: preview.effectiveAtDate ?? null,
|
|
contractMonths,
|
|
trialDays,
|
|
currentSubscription: tenantSubscription
|
|
? {
|
|
id: tenantSubscription.id,
|
|
status: tenantSubscription.status,
|
|
planCode: tenantSubscription.planCode,
|
|
seatQuantity: tenantSubscription.seatQuantity,
|
|
officeSeatQuantity: tenantSubscription.officeSeatQuantity,
|
|
fieldSeatQuantity: tenantSubscription.fieldSeatQuantity,
|
|
billingCadence: tenantSubscription.billingCadence,
|
|
commitmentEndsAt: nullableDateIso(tenantSubscription.commitmentEndsAt),
|
|
trialStartsAt: nullableDateIso(tenantSubscription.trialStartsAt),
|
|
trialEndsAt: nullableDateIso(tenantSubscription.trialEndsAt),
|
|
cancelledAt: nullableDateIso(tenantSubscription.cancelledAt),
|
|
activeBaseProducts: tenantSubscription.products
|
|
.filter(
|
|
(item) =>
|
|
item.subscriptionProduct.kind === "base_plan" && !item.cancelledAt && (!item.endsAt || item.endsAt > now)
|
|
)
|
|
.map((item) => ({
|
|
id: item.id,
|
|
subscriptionProductId: item.subscriptionProductId,
|
|
lagoSubscriptionId: item.lagoSubscriptionId,
|
|
planCode: item.planCode,
|
|
officeSeatQuantity: item.officeSeatQuantity,
|
|
fieldSeatQuantity: item.fieldSeatQuantity,
|
|
billingCadence: item.billingCadence,
|
|
commitmentEndsAt: nullableDateIso(item.commitmentEndsAt),
|
|
currentPeriodEnd: nullableDateIso(item.currentPeriodEnd),
|
|
}))
|
|
.sort((left, right) => left.id.localeCompare(right.id)),
|
|
}
|
|
: null,
|
|
});
|
|
const claimStatus = checkoutClaimStatus();
|
|
const buildReservation = (sessionId: string, lockedPaymentPolicyAmountCents?: number) => {
|
|
if (lockedPaymentPolicyAmountCents === undefined) {
|
|
const legacyOtherRecurringGrossAmountCents = resolveOtherActiveRecurringGrossTotalCents(tenantSubscription, { now });
|
|
if (
|
|
legacyOtherRecurringGrossAmountCents === null
|
|
|| !Number.isSafeInteger(selectedRecurringGrossAmountCents + legacyOtherRecurringGrossAmountCents)
|
|
) {
|
|
throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
|
|
}
|
|
lockedPaymentPolicyAmountCents = selectedRecurringGrossAmountCents + legacyOtherRecurringGrossAmountCents;
|
|
}
|
|
const subscriptionExternalId = currentLagoSubscriptionId ?? sessionId;
|
|
const requestFingerprint = checkoutRequestFingerprint({
|
|
tenantId: input.tenantId,
|
|
userId: input.userId,
|
|
email: input.userEmail,
|
|
productId,
|
|
priceId,
|
|
planCode,
|
|
quantity,
|
|
officeSeatQuantity: selectedOfficeSeatQuantity,
|
|
fieldSeatQuantity: selectedFieldSeatQuantity,
|
|
billingCadence,
|
|
storageAddOnCodes: selectedStorageAddOnCodes,
|
|
amountCents,
|
|
currency,
|
|
lagoSubscriptionId: subscriptionExternalId,
|
|
managedPlanAmountCents: preview.recurringTotalCents,
|
|
paymentPolicyAmountCents: lockedPaymentPolicyAmountCents,
|
|
changeKind: preview.changeKind,
|
|
changeEffectiveAt: preview.effectiveAt,
|
|
changeEffectiveAtDate: preview.effectiveAtDate ?? null,
|
|
paymentMethod: input.paymentMethod?.trim() || null,
|
|
paymentLocale: input.paymentLocale?.trim().toLowerCase() || "de",
|
|
postActivationEmailMarketingAddOnCode: input.postActivationEmailMarketingAddOnCode?.trim() || null,
|
|
});
|
|
const initialIntent: StoredCheckoutIntent = {
|
|
v: 2,
|
|
path,
|
|
requestFingerprint,
|
|
businessFingerprint,
|
|
trialEndsAt: nullableDateIso(trialEndsAt),
|
|
commitmentEndsAt: nullableDateIso(commitmentEndsAt),
|
|
changeEffectiveAt: preview.effectiveAt,
|
|
changeEffectiveAtDate: nullableText(preview.effectiveAtDate),
|
|
managedPlanCode,
|
|
managedPlanAmountCents: preview.recurringTotalCents,
|
|
paymentPolicyAmountCents: lockedPaymentPolicyAmountCents,
|
|
billingFlow: preview.changeKind === "new" ? "self_service_new" : "self_service_change",
|
|
lagoCustomerId: null,
|
|
mollieCustomerId: null,
|
|
lagoProviderSubscriptionId: null,
|
|
};
|
|
const session: CanonicalBaseCheckoutSessionCreate = {
|
|
id: sessionId,
|
|
tenantId: input.tenantId,
|
|
pending: true,
|
|
email: input.userEmail,
|
|
fromUrl: encodeCheckoutIntent(initialIntent),
|
|
fromUserId: input.userId,
|
|
provider: "mollie",
|
|
providerPaymentId: null,
|
|
invoiceExternalId: sessionId,
|
|
subscriptionProductId: productId,
|
|
subscriptionPriceId: priceId,
|
|
lagoSubscriptionId: subscriptionExternalId,
|
|
planCode,
|
|
quantity,
|
|
officeSeatQuantity: selectedOfficeSeatQuantity,
|
|
fieldSeatQuantity: selectedFieldSeatQuantity,
|
|
billingCadence,
|
|
commitmentEndsAt,
|
|
storageAddOnCodes: [...selectedStorageAddOnCodes],
|
|
amountCents,
|
|
currency,
|
|
checkoutUrl: null,
|
|
productKind: "base_plan",
|
|
scopeKey: canonicalCheckoutScopeKey(businessFingerprint),
|
|
status: claimStatus,
|
|
};
|
|
return {
|
|
session,
|
|
expected: {
|
|
tenantId: input.tenantId,
|
|
userId: input.userId,
|
|
email: input.userEmail,
|
|
productId,
|
|
priceId,
|
|
planCode,
|
|
quantity,
|
|
officeSeatQuantity: selectedOfficeSeatQuantity,
|
|
fieldSeatQuantity: selectedFieldSeatQuantity,
|
|
billingCadence,
|
|
storageAddOnCodes: selectedStorageAddOnCodes,
|
|
amountCents,
|
|
currency,
|
|
lagoSubscriptionId: subscriptionExternalId,
|
|
path,
|
|
requestFingerprint,
|
|
businessFingerprint,
|
|
},
|
|
};
|
|
};
|
|
|
|
const reserveCheckoutSession = deps.reserveCheckoutSession ?? reserveCanonicalBaseCheckoutSession;
|
|
const legacySessionId = checkoutSessionId(input.tenantId, requestKey);
|
|
const legacySession = await getCheckoutSessionStatus({ id: legacySessionId, tenantId: input.tenantId });
|
|
let reservation: CanonicalBaseCheckoutReservation = legacySession
|
|
? { session: legacySession, created: false }
|
|
: await reserveCheckoutSession({
|
|
tenantId: input.tenantId,
|
|
businessFingerprint,
|
|
selectedRecurringGrossAmountCents,
|
|
now,
|
|
createSession: (sessionId, lockedPaymentPolicyAmountCents) =>
|
|
buildReservation(sessionId, lockedPaymentPolicyAmountCents).session,
|
|
});
|
|
let reservedSession: CheckoutSessionStatus & { tenantId: string } = reservation.session;
|
|
let intent = decodeCheckoutIntent(reservedSession.fromUrl);
|
|
let ownsReservation = reservation.created;
|
|
|
|
for (let attempt = 0; !ownsReservation && attempt < 3; attempt += 1) {
|
|
const expectedReservation = buildReservation(reservedSession.id, intent.paymentPolicyAmountCents).expected;
|
|
assertMatchingReservedSession(reservedSession, expectedReservation);
|
|
if (reservedSession.providerPaymentId) {
|
|
const replay = await replayPersistedCheckout(reservedSession, mollieGateway, intent);
|
|
if (!("terminalStatus" in replay)) return replay;
|
|
await transitionClaimedCheckoutSessionStatus({
|
|
id: reservedSession.id,
|
|
tenantId: input.tenantId,
|
|
claimedStatus: reservedSession.status,
|
|
data: { pending: true, status: replay.terminalStatus },
|
|
});
|
|
reservation = await reserveCheckoutSession({
|
|
tenantId: input.tenantId,
|
|
businessFingerprint,
|
|
selectedRecurringGrossAmountCents,
|
|
now,
|
|
createSession: (sessionId, lockedPaymentPolicyAmountCents) =>
|
|
buildReservation(sessionId, lockedPaymentPolicyAmountCents).session,
|
|
});
|
|
reservedSession = reservation.session;
|
|
intent = decodeCheckoutIntent(reservedSession.fromUrl);
|
|
ownsReservation = reservation.created;
|
|
continue;
|
|
}
|
|
const reservationAgeMs = now.getTime() - reservedSession.updatedAt.getTime();
|
|
const staleClaim = isCheckoutClaimStatus(reservedSession.status) && reservationAgeMs >= CHECKOUT_CREATION_STALE_MS;
|
|
if (isCheckoutClaimStatus(reservedSession.status) && !staleClaim) {
|
|
throw new SelfServiceCheckoutError("CHECKOUT_IN_PROGRESS");
|
|
}
|
|
if (reservedSession.status !== "provider_recovery_pending" && reservedSession.status !== "failed" && !staleClaim) {
|
|
throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
|
|
}
|
|
const claimed = await claimCheckoutSessionStatus({
|
|
id: reservedSession.id,
|
|
tenantId: input.tenantId,
|
|
expectedStatus: reservedSession.status,
|
|
claimedStatus: claimStatus,
|
|
...(staleClaim ? { updatedBefore: new Date(now.getTime() - CHECKOUT_CREATION_STALE_MS) } : {}),
|
|
});
|
|
if (!claimed) throw new SelfServiceCheckoutError("CHECKOUT_IN_PROGRESS");
|
|
reservedSession = claimed;
|
|
intent = decodeCheckoutIntent(claimed.fromUrl);
|
|
ownsReservation = true;
|
|
}
|
|
if (!ownsReservation) throw new SelfServiceCheckoutError("CHECKOUT_IN_PROGRESS");
|
|
const sessionId = reservedSession.id;
|
|
const subscriptionExternalId = currentLagoSubscriptionId ?? sessionId;
|
|
assertMatchingReservedSession(reservedSession, buildReservation(sessionId, intent.paymentPolicyAmountCents).expected);
|
|
|
|
const persistedTrialEndsAt = parseProviderDate(intent.trialEndsAt);
|
|
const persistedEffectiveAtDate = parseProviderDate(intent.changeEffectiveAtDate);
|
|
const persistedCommitmentEndsAt = parseProviderDate(intent.commitmentEndsAt);
|
|
const paymentConfirmedActivationRequired = requiresPaymentConfirmedProviderActivation({
|
|
trialEndsAt: persistedTrialEndsAt,
|
|
effectiveAt: intent.changeEffectiveAt,
|
|
});
|
|
const providerSubscriptionAt = paymentConfirmedActivationRequired ? null : (persistedTrialEndsAt ?? persistedEffectiveAtDate);
|
|
const checkoutPaymentMethodRequirement = resolveMollieCheckoutPaymentMethodRequirement({
|
|
amountCents: intent.paymentPolicyAmountCents,
|
|
currency,
|
|
configuredRequirement: "any",
|
|
});
|
|
let selectedPaymentMethod: MolliePaymentMethodId | null;
|
|
try {
|
|
selectedPaymentMethod = await assertCheckoutPaymentMethodAvailable(
|
|
input.paymentMethod,
|
|
{
|
|
amountCents,
|
|
policyAmountCents: intent.paymentPolicyAmountCents,
|
|
currency: price.currency,
|
|
sequenceType: "first",
|
|
locale: input.paymentLocale ?? "de",
|
|
requirement: checkoutPaymentMethodRequirement,
|
|
},
|
|
{ gateway: mollieGateway }
|
|
);
|
|
} catch (error) {
|
|
await transitionClaimedCheckoutSessionStatus({
|
|
id: sessionId,
|
|
tenantId: input.tenantId,
|
|
claimedStatus: claimStatus,
|
|
data: { pending: true, status: "failed" },
|
|
});
|
|
if (error instanceof CheckoutPaymentMethodError) throw new SelfServiceCheckoutError(error.code);
|
|
throw error;
|
|
}
|
|
|
|
let payment: PaymentGatewayPayment | null = null;
|
|
try {
|
|
const lagoCustomer = await ensureLagoCustomer(lagoGateway, input, price.currency);
|
|
const mollieCustomerId = await ensureMollieCustomer(mollieGateway, input, intent.mollieCustomerId ?? tenantSubscription?.mollieCustomerId);
|
|
assertProviderBinding(intent.lagoCustomerId, lagoCustomer.providerCustomerId);
|
|
assertProviderBinding(intent.mollieCustomerId, mollieCustomerId);
|
|
let lagoSubscription: BillingGatewaySubscription | null = null;
|
|
const managedPlanDisplayName = buildManagedPlanDisplayName(product.title, selectedOfficeSeatQuantity, selectedFieldSeatQuantity, selectedStorageAddOnCodes);
|
|
const managedPlan = {
|
|
code: intent.managedPlanCode,
|
|
name: managedPlanDisplayName,
|
|
invoiceDisplayName: managedPlanDisplayName,
|
|
description: `${product.title} · Katalog ${hiveGridBillingCatalogVersion}`,
|
|
interval: "monthly",
|
|
amountCents: intent.managedPlanAmountCents,
|
|
currency,
|
|
payInAdvance: true,
|
|
taxCodes: [hiveGridVat.code],
|
|
metadata: {
|
|
hivegrid_resource_kind: "selected_price",
|
|
hivegrid_catalog_version: hiveGridBillingCatalogVersion,
|
|
hivegrid_base_plan_code: planCode,
|
|
hivegrid_billing_cadence: billingCadence,
|
|
hivegrid_office_seats: String(selectedOfficeSeatQuantity),
|
|
hivegrid_field_seats: String(selectedFieldSeatQuantity),
|
|
hivegrid_storage_add_ons: selectedStorageAddOnCodes.join(",") || "none",
|
|
},
|
|
} as const;
|
|
if (paymentConfirmedActivationRequired) {
|
|
if (!lagoGateway.ensureManagedPlan) throw new SelfServiceCheckoutError("PROVIDER_CONFIGURATION_MISSING");
|
|
await lagoGateway.ensureManagedPlan(managedPlan);
|
|
} else {
|
|
lagoSubscription = (await lagoGateway.getSubscription(subscriptionExternalId)) ?? (await lagoGateway.getSubscription(subscriptionExternalId, "pending"));
|
|
if (!lagoSubscription) {
|
|
lagoSubscription = await lagoGateway.createSubscription({
|
|
tenantId: input.tenantId,
|
|
subscriptionExternalId,
|
|
planCode,
|
|
seatQuantity: quantity,
|
|
name: `${input.tenantName} · ${product.title}`,
|
|
subscriptionAt: providerSubscriptionAt,
|
|
endingAt: persistedCommitmentEndsAt,
|
|
paymentMethodType: "manual",
|
|
consolidateInvoice: false,
|
|
managedPlan,
|
|
});
|
|
}
|
|
if (
|
|
lagoSubscription.externalId !== subscriptionExternalId ||
|
|
lagoSubscription.externalCustomerId !== input.tenantId ||
|
|
lagoSubscription.planCode !== intent.managedPlanCode
|
|
) {
|
|
throw new SelfServiceCheckoutError("PAYMENT_METADATA_MISMATCH");
|
|
}
|
|
}
|
|
const lagoProviderSubscriptionId = lagoSubscription?.providerSubscriptionId ?? null;
|
|
assertProviderBinding(intent.lagoProviderSubscriptionId, lagoProviderSubscriptionId);
|
|
const boundIntent: StoredCheckoutIntent = {
|
|
...intent,
|
|
lagoCustomerId: lagoCustomer.providerCustomerId,
|
|
mollieCustomerId,
|
|
lagoProviderSubscriptionId,
|
|
};
|
|
const boundSession = await transitionClaimedCheckoutSessionStatus({
|
|
id: sessionId,
|
|
tenantId: input.tenantId,
|
|
claimedStatus: claimStatus,
|
|
data: { pending: true, status: claimStatus, fromUrl: encodeCheckoutIntent(boundIntent) },
|
|
});
|
|
if (!boundSession) throw new SelfServiceCheckoutError("CHECKOUT_IN_PROGRESS");
|
|
reservedSession = boundSession;
|
|
intent = boundIntent;
|
|
const redirectUrl = buildRedirectUrl(input.tenantSlug, sessionId, input.postActivationEmailMarketingAddOnCode);
|
|
payment = await mollieGateway.findCustomerPaymentByExternalIdExhaustive(mollieCustomerId, sessionId);
|
|
if (payment) assertMatchingSelfServicePayment(reservedSession, payment, intent);
|
|
payment ??= await mollieGateway.createPayment({
|
|
tenantId: input.tenantId,
|
|
invoiceExternalId: sessionId,
|
|
paymentExternalId: sessionId,
|
|
amountCents,
|
|
currency,
|
|
redirectUrl,
|
|
webhookUrl: buildWebhookUrl(),
|
|
sequenceType: "first",
|
|
method: selectedPaymentMethod ?? defaultMollieFirstPaymentMethod(checkoutPaymentMethodRequirement, mollieSepaFirstPaymentMethods),
|
|
locale: toMollieLocale(input.paymentLocale ?? "de"),
|
|
mollieCustomerId,
|
|
lagoCustomerId: lagoCustomer.providerCustomerId,
|
|
lagoSubscriptionId: subscriptionExternalId,
|
|
lagoProviderSubscriptionId: intent.lagoProviderSubscriptionId ?? undefined,
|
|
lagoPlanCode: intent.managedPlanCode,
|
|
planCode,
|
|
subscriptionPriceId: priceId,
|
|
seatQuantity: quantity,
|
|
officeSeatQuantity: selectedOfficeSeatQuantity,
|
|
fieldSeatQuantity: selectedFieldSeatQuantity,
|
|
billingCadence,
|
|
commitmentEndsAt: intent.commitmentEndsAt ?? undefined,
|
|
storageAddOnCodes: selectedStorageAddOnCodes,
|
|
trialEndsAt: intent.trialEndsAt ?? undefined,
|
|
changeEffectiveAt: intent.changeEffectiveAt,
|
|
changeEffectiveAtDate: intent.changeEffectiveAtDate,
|
|
billingFlow: intent.billingFlow,
|
|
description: `${loadWebConfig().config.appName} ${product.title}`,
|
|
idempotencyKey: providerIdempotencyKey("payment", sessionId),
|
|
});
|
|
assertMatchingSelfServicePayment(reservedSession, payment, intent);
|
|
const transitioned = await transitionClaimedCheckoutSessionStatus({
|
|
id: sessionId,
|
|
tenantId: input.tenantId,
|
|
claimedStatus: claimStatus,
|
|
data: {
|
|
pending: true,
|
|
providerPaymentId: payment.providerPaymentId,
|
|
invoiceExternalId: sessionId,
|
|
lagoSubscriptionId: subscriptionExternalId,
|
|
checkoutUrl: payment.checkoutUrl,
|
|
status: payment.status,
|
|
fromUrl: encodeCheckoutIntent(intent),
|
|
},
|
|
});
|
|
if (!transitioned) {
|
|
const current = await getCheckoutSessionStatus({ id: sessionId, tenantId: input.tenantId });
|
|
if (current?.providerPaymentId) {
|
|
const replay = await replayPersistedCheckout(current, mollieGateway, decodeCheckoutIntent(current.fromUrl));
|
|
if (!("terminalStatus" in replay)) return replay;
|
|
}
|
|
throw new SelfServiceCheckoutError("CHECKOUT_IN_PROGRESS");
|
|
}
|
|
if (payment.status === "paid") throw new SelfServiceCheckoutError("NO_CHANGE");
|
|
if (!isReusableCheckoutPayment(payment)) throw new SelfServiceCheckoutError("CHECKOUT_NOT_PAYABLE");
|
|
if (!payment.checkoutUrl) throw new SelfServiceCheckoutError("CHECKOUT_URL_MISSING");
|
|
return { sessionId, checkoutUrl: payment.checkoutUrl, providerPaymentId: payment.providerPaymentId };
|
|
} catch (error) {
|
|
await transitionClaimedCheckoutSessionStatus({
|
|
id: sessionId,
|
|
tenantId: input.tenantId,
|
|
claimedStatus: claimStatus,
|
|
data: {
|
|
pending: true,
|
|
providerPaymentId: payment?.providerPaymentId,
|
|
invoiceExternalId: sessionId,
|
|
lagoSubscriptionId: subscriptionExternalId,
|
|
checkoutUrl: payment?.checkoutUrl ?? undefined,
|
|
status: "provider_recovery_pending",
|
|
fromUrl: encodeCheckoutIntent(intent),
|
|
},
|
|
});
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function completeSelfServiceCheckout(
|
|
input: CompleteSelfServiceCheckoutInput,
|
|
deps: SelfServiceCheckoutDeps = {}
|
|
): Promise<SelfServiceCheckoutResponse | null> {
|
|
return runWithRlsContext({ tenantId: input.tenantId }, () => completeSelfServiceCheckoutInContext(input, deps));
|
|
}
|
|
|
|
async function completeSelfServiceCheckoutInContext(
|
|
input: CompleteSelfServiceCheckoutInput,
|
|
deps: SelfServiceCheckoutDeps
|
|
): Promise<SelfServiceCheckoutResponse | null> {
|
|
const session = await getCheckoutSessionStatus({ id: input.sessionId, tenantId: input.tenantId });
|
|
if (!session) {
|
|
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");
|
|
const intent = resolveCompletionCheckoutIntent(session, payment);
|
|
assertMatchingSelfServicePayment(session, payment, intent);
|
|
|
|
const updatedSession = await updateCheckoutSessionStatus(
|
|
{ id: session.id, tenantId: input.tenantId },
|
|
{
|
|
pending: !isPaidPayment(payment),
|
|
status: payment.status,
|
|
providerPaymentId: payment.providerPaymentId,
|
|
invoiceExternalId: session.invoiceExternalId ?? payment.metadata.invoiceExternalId,
|
|
lagoSubscriptionId: payment.metadata.lagoSubscriptionId ?? session.lagoSubscriptionId,
|
|
}
|
|
);
|
|
|
|
if (!isPaidPayment(payment)) {
|
|
return buildSelfServiceCheckoutResponse(updatedSession);
|
|
}
|
|
|
|
const lagoGateway = getLagoGateway(deps);
|
|
if (!lagoGateway) throw new SelfServiceCheckoutError("PROVIDER_CONFIGURATION_MISSING");
|
|
const activatedSubscription = await ensurePaidLagoSubscription(payment, input.tenantId, lagoGateway);
|
|
const receivedAt = new Date();
|
|
const paidChangeEffectiveAt = parseProviderDate(payment.metadata.changeEffectiveAtDate);
|
|
const requiresInitialInvoice =
|
|
typeof payment.amountCents === "number" &&
|
|
payment.amountCents > 0 &&
|
|
requiresPaymentConfirmedProviderActivation({
|
|
trialEndsAt: parseProviderDate(payment.metadata.trialEndsAt),
|
|
effectiveAt:
|
|
payment.metadata.changeEffectiveAt === "period_end" && paidChangeEffectiveAt && paidChangeEffectiveAt > receivedAt ? "period_end" : "immediate",
|
|
});
|
|
if (requiresInitialInvoice && !activatedSubscription) throw new SelfServiceCheckoutError("SUBSCRIPTION_ACTIVATION_FAILED");
|
|
const settledInvoice =
|
|
requiresInitialInvoice && activatedSubscription
|
|
? await settlePaidInitialLagoInvoice(
|
|
payment,
|
|
input.tenantId,
|
|
lagoGateway,
|
|
activatedSubscription,
|
|
session.invoiceExternalId && session.invoiceExternalId !== session.id ? session.invoiceExternalId : undefined
|
|
)
|
|
: null;
|
|
if (requiresInitialInvoice && !settledInvoice) throw new SelfServiceCheckoutError("SUBSCRIPTION_ACTIVATION_FAILED");
|
|
await syncPaidCheckoutSession(payment, session, settledInvoice?.providerInvoiceId, activatedSubscription);
|
|
if (settledInvoice && activatedSubscription) {
|
|
await correlateCheckoutSessionProviderInvoice({
|
|
id: session.id,
|
|
tenantId: input.tenantId,
|
|
providerPaymentId: payment.providerPaymentId,
|
|
lagoSubscriptionId: activatedSubscription.externalId,
|
|
sourceInvoiceExternalId: session.invoiceExternalId ?? payment.metadata.invoiceExternalId ?? session.id,
|
|
providerInvoiceExternalId: settledInvoice.providerInvoiceId,
|
|
});
|
|
}
|
|
if (settledInvoice) {
|
|
const lagoSubscriptionId = payment.metadata.lagoSubscriptionId?.trim();
|
|
const billingProviderSubscriptionId = activatedSubscription?.providerSubscriptionId.trim();
|
|
if (!lagoSubscriptionId || !billingProviderSubscriptionId || !payment.amountCents || !payment.currency) {
|
|
throw new SelfServiceCheckoutError("SUBSCRIPTION_ACTIVATION_FAILED");
|
|
}
|
|
const collection = await reserveRecurringInvoiceCollection({
|
|
tenantId: input.tenantId,
|
|
invoiceExternalId: settledInvoice.providerInvoiceId,
|
|
lagoSubscriptionId,
|
|
billingProviderSubscriptionId,
|
|
invoicingReason: "subscription_starting",
|
|
invoiceCreatedAt: parseProviderDate(settledInvoice.issuingDate) ?? receivedAt,
|
|
amountCents: payment.amountCents,
|
|
currency: payment.currency,
|
|
receivedAt,
|
|
});
|
|
if (collection.disposition === "not_ready" || collection.disposition === "queued") {
|
|
throw new SelfServiceCheckoutError("SUBSCRIPTION_ACTIVATION_FAILED");
|
|
}
|
|
}
|
|
|
|
return buildSelfServiceCheckoutResponse(updatedSession);
|
|
}
|