Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,9 +1,35 @@
import { z } from "zod";
import type { PaymentGateway, PaymentGatewayCreatePaymentInput, PaymentGatewayPayment, PaymentGatewayPaymentStatus } from "./types.js";
import { readBillingJsonResponse } from "./provider-http.js";
import {
mollieLocales,
mollieMandatePaymentMethods,
molliePaymentMethodIds,
mollieSepaFirstPaymentMethods,
paymentBillingFlows,
subscriptionProductKinds,
} from "./types.js";
import type {
ExhaustiveCustomerPaymentGateway,
MollieLocale,
MolliePaymentMethodId,
MollieSepaFirstPaymentMethod,
PaymentGateway,
PaymentGatewayCreateCustomerInput,
PaymentGatewayCreatePaymentInput,
PaymentGatewayCustomer,
PaymentGatewayListMethodsInput,
PaymentGatewayMandate,
PaymentGatewayPayment,
PaymentGatewayPaymentMethod,
PaymentGatewayPaymentStatus,
PaymentBillingFlow,
SubscriptionProductKind,
} from "./types.js";
const DEFAULT_MOLLIE_API_URL = "https://api.mollie.com";
const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000;
const MAX_EXHAUSTIVE_CUSTOMER_PAYMENT_PAGES = 1_000;
export type MolliePaymentGatewayConfig = {
apiKey: string;
@@ -39,16 +65,34 @@ const metadataSchema = z
tenantId: z.string().nullable().optional(),
invoiceExternalId: z.string().nullable().optional(),
paymentExternalId: z.string().nullable().optional(),
mollieCustomerId: z.string().nullable().optional(),
lagoCustomerId: z.string().nullable().optional(),
lagoSubscriptionId: z.string().nullable().optional(),
lagoProviderSubscriptionId: z.string().nullable().optional(),
lagoPlanCode: z.string().nullable().optional(),
planCode: z.string().nullable().optional(),
subscriptionPriceId: z.string().nullable().optional(),
seatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
officeSeatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
fieldSeatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
billingCadence: z.string().nullable().optional(),
commitmentEndsAt: z.string().nullable().optional(),
storageAddOnCodes: z.array(z.string()).nullable().optional(),
trialEndsAt: z.string().nullable().optional(),
changeEffectiveAt: z.string().nullable().optional(),
changeEffectiveAtDate: z.string().nullable().optional(),
billingFlow: z.string().nullable().optional(),
productAcquisitionId: z.string().nullable().optional(),
productKind: z.string().nullable().optional(),
productScopeKey: z.string().nullable().optional(),
subscriptionProductId: z.string().nullable().optional(),
})
.nullable()
.optional();
const molliePaymentSchema = z.object({
id: z.string(),
customerId: z.string().nullable().optional(),
status: z.string().nullable().optional(),
amount: amountSchema.nullable().optional(),
amountRefunded: amountSchema.nullable().optional(),
@@ -69,9 +113,63 @@ const molliePaymentSchema = z.object({
.optional(),
});
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
const mollieCustomerSchema = z.object({
id: z.string(),
name: z.string().nullable().optional(),
email: z.string().nullable().optional(),
locale: z.string().nullable().optional(),
metadata: z
.object({
tenantId: z.string().nullable().optional(),
})
.nullable()
.optional(),
createdAt: z.string().nullable().optional(),
});
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): PaymentGateway {
const mollieCustomerPaymentsSchema = z.object({
_embedded: z.object({ payments: z.array(molliePaymentSchema) }),
_links: z
.object({
next: z
.object({
href: z.string(),
})
.nullable()
.optional(),
})
.nullable()
.optional(),
});
const mollieMethodSchema = z.object({
id: z.enum(molliePaymentMethodIds),
description: z.string(),
});
const mollieMethodsSchema = z.object({
_embedded: z.object({
methods: z.array(mollieMethodSchema),
}),
});
const mollieMandateSchema = z.object({
id: z.string(),
status: z.enum(["valid", "pending", "invalid"]),
method: z.enum(mollieMandatePaymentMethods),
createdAt: z.string().nullable().optional(),
});
const mollieMandatesSchema = z.object({
_embedded: z.object({
mandates: z.array(mollieMandateSchema),
}),
});
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
type MollieCustomerResponse = z.infer<typeof mollieCustomerSchema>;
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): ExhaustiveCustomerPaymentGateway {
return new MolliePaymentGateway(config);
}
@@ -104,7 +202,10 @@ export function parseMollieWebhookEvent(input: URLSearchParams | FormData | Reco
return { providerPaymentId: id };
}
export async function resolveMollieWebhookPayment(gateway: PaymentGateway, input: URLSearchParams | FormData | Record<string, unknown>): Promise<PaymentGatewayPayment> {
export async function resolveMollieWebhookPayment(
gateway: PaymentGateway,
input: URLSearchParams | FormData | Record<string, unknown>
): Promise<PaymentGatewayPayment> {
const event = parseMollieWebhookEvent(input);
const payment = await gateway.getPayment(event.providerPaymentId);
if (!payment) {
@@ -113,7 +214,7 @@ export async function resolveMollieWebhookPayment(gateway: PaymentGateway, input
return payment;
}
class MolliePaymentGateway implements PaymentGateway {
class MolliePaymentGateway implements ExhaustiveCustomerPaymentGateway {
private readonly apiUrl: string;
private readonly apiKey: string;
private readonly profileId: string | null;
@@ -131,34 +232,167 @@ class MolliePaymentGateway implements PaymentGateway {
this.fetchImpl = config.fetchImpl ?? fetch;
}
async createCustomer(input: PaymentGatewayCreateCustomerInput): Promise<PaymentGatewayCustomer> {
const normalizedInput = validateCreateCustomerInput(input);
const response = await this.request("/customers", {
method: "POST",
idempotencyKey: normalizeIdempotencyKey(input.idempotencyKey),
body: {
name: normalizedInput.name,
email: normalizedInput.email,
...(normalizedInput.locale ? { locale: normalizedInput.locale } : {}),
metadata: {
tenantId: normalizedInput.tenantId,
},
},
});
return toCustomer(parseMollieCustomerResponse(response));
}
async createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment> {
validateCreatePaymentInput(input);
const normalizedInput = validateCreatePaymentInput(input);
const response = await this.request("/payments", {
method: "POST",
idempotencyKey: normalizeIdempotencyKey(input.idempotencyKey),
body: {
amount: {
currency: input.currency.toUpperCase(),
value: centsToMollieValue(input.amountCents),
},
description: input.description?.trim() || `Invoice ${input.invoiceExternalId}`,
redirectUrl: input.redirectUrl,
...(input.redirectUrl ? { redirectUrl: input.redirectUrl } : {}),
webhookUrl: input.webhookUrl,
sequenceType: normalizedInput.sequenceType,
...(normalizedInput.method ? { method: normalizedInput.method } : {}),
...(normalizedInput.mandateId ? { mandateId: normalizedInput.mandateId } : {}),
...(normalizedInput.locale ? { locale: normalizedInput.locale } : {}),
...(this.profileId ? { profileId: this.profileId } : {}),
...(input.mollieCustomerId ? { customerId: input.mollieCustomerId } : {}),
...(normalizedInput.mollieCustomerId ? { customerId: normalizedInput.mollieCustomerId } : {}),
metadata: {
tenantId: input.tenantId,
invoiceExternalId: input.invoiceExternalId,
...(input.paymentExternalId ? { paymentExternalId: input.paymentExternalId } : {}),
...(normalizedInput.mollieCustomerId ? { mollieCustomerId: normalizedInput.mollieCustomerId } : {}),
...(input.lagoCustomerId ? { lagoCustomerId: input.lagoCustomerId } : {}),
...(input.lagoSubscriptionId ? { lagoSubscriptionId: input.lagoSubscriptionId } : {}),
...(normalizedInput.lagoProviderSubscriptionId ? { lagoProviderSubscriptionId: normalizedInput.lagoProviderSubscriptionId } : {}),
...(normalizedInput.lagoPlanCode ? { lagoPlanCode: normalizedInput.lagoPlanCode } : {}),
...(input.planCode ? { planCode: input.planCode } : {}),
...(input.subscriptionPriceId ? { subscriptionPriceId: input.subscriptionPriceId } : {}),
...(input.seatQuantity ? { seatQuantity: input.seatQuantity } : {}),
...(input.officeSeatQuantity !== null && input.officeSeatQuantity !== undefined ? { officeSeatQuantity: input.officeSeatQuantity } : {}),
...(input.fieldSeatQuantity !== null && input.fieldSeatQuantity !== undefined ? { fieldSeatQuantity: input.fieldSeatQuantity } : {}),
...(input.billingCadence ? { billingCadence: input.billingCadence } : {}),
...(normalizedInput.commitmentEndsAt ? { commitmentEndsAt: normalizedInput.commitmentEndsAt } : {}),
...(normalizedInput.storageAddOnCodes.length > 0 ? { storageAddOnCodes: normalizedInput.storageAddOnCodes } : {}),
...(normalizedInput.trialEndsAt ? { trialEndsAt: normalizedInput.trialEndsAt } : {}),
...(normalizedInput.changeEffectiveAt ? { changeEffectiveAt: normalizedInput.changeEffectiveAt } : {}),
...(normalizedInput.changeEffectiveAtDate ? { changeEffectiveAtDate: normalizedInput.changeEffectiveAtDate } : {}),
...(normalizedInput.billingFlow ? { billingFlow: normalizedInput.billingFlow } : {}),
...(normalizedInput.productAcquisitionId ? { productAcquisitionId: normalizedInput.productAcquisitionId } : {}),
...(normalizedInput.productKind ? { productKind: normalizedInput.productKind } : {}),
...(normalizedInput.productScopeKey ? { productScopeKey: normalizedInput.productScopeKey } : {}),
...(normalizedInput.subscriptionProductId ? { subscriptionProductId: normalizedInput.subscriptionProductId } : {}),
},
},
});
return toPayment(parseMollieResponse(response));
}
async listPaymentMethods(input: PaymentGatewayListMethodsInput): Promise<PaymentGatewayPaymentMethod[]> {
const normalized = validateListPaymentMethodsInput(input);
const query = new URLSearchParams({ sequenceType: normalized.sequenceType });
if (normalized.locale) query.set("locale", normalized.locale);
if (normalized.amountCents !== null) {
query.set("amount[value]", centsToMollieValue(normalized.amountCents));
query.set("amount[currency]", normalized.currency);
}
if (this.profileId) query.set("profileId", this.profileId);
const response = await this.request(`/methods?${query.toString()}`, { method: "GET" });
const parsed = mollieMethodsSchema.safeParse(response);
if (!parsed.success) {
throw new MolliePaymentGatewayError("Mollie payment methods response shape is invalid.", "RESPONSE_INVALID");
}
const ids = parsed.data._embedded.methods.map((method) => method.id);
if (new Set(ids).size !== ids.length || parsed.data._embedded.methods.some((method) => !method.description.trim())) {
throw new MolliePaymentGatewayError("Mollie payment methods response is ambiguous.", "RESPONSE_INVALID");
}
return parsed.data._embedded.methods.map((method) => ({
provider: "mollie",
id: method.id,
description: method.description.trim(),
}));
}
async listCustomerMandates(mollieCustomerId: string): Promise<PaymentGatewayMandate[]> {
const customerId = mollieCustomerId.trim();
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
const response = await this.request(`/customers/${encodeURIComponent(customerId)}/mandates?limit=250`, { method: "GET" });
const parsed = mollieMandatesSchema.safeParse(response);
if (!parsed.success) {
throw new MolliePaymentGatewayError("Mollie mandates response shape is invalid.", "RESPONSE_INVALID");
}
const ids = parsed.data._embedded.mandates.map((mandate) => mandate.id);
if (new Set(ids).size !== ids.length || ids.some((id) => !/^mdt_.+/u.test(id))) {
throw new MolliePaymentGatewayError("Mollie mandates response is ambiguous.", "RESPONSE_INVALID");
}
return parsed.data._embedded.mandates.map((mandate) => ({
provider: "mollie",
providerMandateId: mandate.id,
status: mandate.status,
method: mandate.method,
createdAt: normalizeProviderTimestamp(mandate.createdAt),
}));
}
async findCustomerPaymentByExternalId(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null> {
const customerId = mollieCustomerId.trim();
const externalId = paymentExternalId.trim();
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
if (!externalId) throw new MolliePaymentGatewayError("Payment external id is required.", "CONFIG_INVALID");
const response = await this.request(`/customers/${encodeURIComponent(customerId)}/payments?limit=250&sort=desc`, { method: "GET" });
const parsed = mollieCustomerPaymentsSchema.safeParse(response);
if (!parsed.success) throw new MolliePaymentGatewayError("Mollie customer payments response shape is invalid.", "RESPONSE_INVALID");
const payment = parsed.data._embedded.payments.find((candidate) => {
const metadata = candidate.metadata ?? {};
return metadata.paymentExternalId === externalId || metadata.productAcquisitionId === externalId;
});
return payment ? toPayment(payment) : null;
}
async findCustomerPaymentByExternalIdExhaustive(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null> {
const customerId = mollieCustomerId.trim();
const externalId = paymentExternalId.trim();
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
if (!externalId) throw new MolliePaymentGatewayError("Payment external id is required.", "CONFIG_INVALID");
const expectedPathPrefix = `/customers/${encodeURIComponent(customerId)}/payments`;
let path = `${expectedPathPrefix}?limit=250&sort=desc`;
const visited = new Set<string>();
for (let page = 0; page < MAX_EXHAUSTIVE_CUSTOMER_PAYMENT_PAGES; page += 1) {
if (visited.has(path)) {
throw new MolliePaymentGatewayError("Mollie customer payments pagination looped.", "RESPONSE_INVALID");
}
visited.add(path);
const response = await this.request(path, { method: "GET" });
const parsed = mollieCustomerPaymentsSchema.safeParse(response);
if (!parsed.success) {
throw new MolliePaymentGatewayError("Mollie customer payments response shape is invalid.", "RESPONSE_INVALID");
}
const payment = parsed.data._embedded.payments.find((candidate) => {
const metadata = candidate.metadata ?? {};
return metadata.paymentExternalId === externalId || metadata.productAcquisitionId === externalId;
});
if (payment) return toPayment(payment);
const nextHref = parsed.data._links?.next?.href;
if (!nextHref) return null;
path = normalizeMollieCustomerPaymentsNextPath(nextHref, this.apiUrl, expectedPathPrefix);
}
throw new MolliePaymentGatewayError("Mollie customer payments pagination exceeded its safety bound.", "RESPONSE_INVALID");
}
async getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null> {
const id = providerPaymentId.trim();
if (!id) {
@@ -168,7 +402,10 @@ class MolliePaymentGateway implements PaymentGateway {
return response === null ? null : toPayment(parseMollieResponse(response));
}
private async request(path: string, options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
private async request(
path: string,
options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean; idempotencyKey?: string | null }
): Promise<unknown | null> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
try {
@@ -178,8 +415,10 @@ class MolliePaymentGateway implements PaymentGateway {
authorization: `Bearer ${this.apiKey}`,
accept: "application/json",
...(options.body ? { "content-type": "application/json" } : {}),
...(options.method === "POST" && options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}),
},
body: options.body ? JSON.stringify(options.body) : undefined,
redirect: "error",
signal: controller.signal,
});
if (response.status === 404 && options.allowNotFound) {
@@ -188,7 +427,7 @@ class MolliePaymentGateway implements PaymentGateway {
if (!response.ok) {
throw new MolliePaymentGatewayError(`Mollie request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
}
return await response.json();
return await readBillingJsonResponse(response);
} catch (error) {
if (error instanceof MolliePaymentGatewayError) throw error;
throw new MolliePaymentGatewayError("Mollie request failed.", "REQUEST_FAILED");
@@ -198,6 +437,21 @@ class MolliePaymentGateway implements PaymentGateway {
}
}
function normalizeMollieCustomerPaymentsNextPath(href: string, apiUrl: string, expectedPathPrefix: string): string {
let next: URL;
try {
next = new URL(href, `${apiUrl}/v2/`);
} catch {
throw new MolliePaymentGatewayError("Mollie customer payments next link is invalid.", "RESPONSE_INVALID");
}
const base = new URL(apiUrl);
const expectedPath = `/v2${expectedPathPrefix}`;
if (next.origin !== base.origin || next.pathname !== expectedPath) {
throw new MolliePaymentGatewayError("Mollie customer payments next link is outside the requested collection.", "RESPONSE_INVALID");
}
return `${expectedPathPrefix}${next.search}`;
}
function parseMollieResponse(response: unknown): MolliePaymentResponse {
const result = molliePaymentSchema.safeParse(response);
if (!result.success) {
@@ -206,13 +460,33 @@ function parseMollieResponse(response: unknown): MolliePaymentResponse {
return result.data;
}
function parseMollieCustomerResponse(response: unknown): MollieCustomerResponse {
const result = mollieCustomerSchema.safeParse(response);
if (!result.success) {
throw new MolliePaymentGatewayError("Mollie customer response shape is invalid.", "RESPONSE_INVALID");
}
return result.data;
}
function toCustomer(customer: MollieCustomerResponse): PaymentGatewayCustomer {
return {
provider: "mollie",
providerCustomerId: customer.id,
tenantId: customer.metadata?.tenantId ?? null,
name: customer.name ?? null,
email: customer.email ?? null,
locale: customer.locale ?? null,
createdAt: customer.createdAt ?? null,
};
}
function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment {
const metadata = payment.metadata ?? {};
return {
provider: "mollie",
providerPaymentId: payment.id,
externalId: metadata.paymentExternalId ?? null,
status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value),
status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value, payment.amount?.value),
amountCents: mollieValueToCents(payment.amount?.value),
amountRefundedCents: mollieValueToCents(payment.amountRefunded?.value),
amountRemainingCents: mollieValueToCents(payment.amountRemaining?.value),
@@ -224,10 +498,27 @@ function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment {
tenantId: metadata.tenantId ?? null,
invoiceExternalId: metadata.invoiceExternalId ?? null,
paymentExternalId: metadata.paymentExternalId ?? null,
mollieCustomerId: normalizeMetadataString(payment.customerId) ?? normalizeMetadataString(metadata.mollieCustomerId),
lagoCustomerId: metadata.lagoCustomerId ?? null,
lagoSubscriptionId: metadata.lagoSubscriptionId ?? null,
lagoProviderSubscriptionId: normalizeMetadataString(metadata.lagoProviderSubscriptionId),
lagoPlanCode: normalizeMetadataString(metadata.lagoPlanCode),
planCode: metadata.planCode ?? null,
subscriptionPriceId: normalizeMetadataString(metadata.subscriptionPriceId),
seatQuantity: normalizeMetadataSeatQuantity(metadata.seatQuantity),
officeSeatQuantity: normalizeMetadataNonNegativeSeatQuantity(metadata.officeSeatQuantity),
fieldSeatQuantity: normalizeMetadataNonNegativeSeatQuantity(metadata.fieldSeatQuantity),
billingCadence: normalizeMetadataString(metadata.billingCadence),
commitmentEndsAt: normalizeMetadataIsoTimestamp(metadata.commitmentEndsAt),
storageAddOnCodes: [...new Set((metadata.storageAddOnCodes ?? []).map((code) => code.trim()).filter(Boolean))],
trialEndsAt: normalizeMetadataIsoTimestamp(metadata.trialEndsAt),
changeEffectiveAt: normalizeChangeEffectiveAt(metadata.changeEffectiveAt),
changeEffectiveAtDate: normalizeMetadataIsoTimestamp(metadata.changeEffectiveAtDate),
billingFlow: normalizeBillingFlow(metadata.billingFlow),
productAcquisitionId: normalizeMetadataString(metadata.productAcquisitionId),
productKind: normalizeProductKind(metadata.productKind),
productScopeKey: normalizeMetadataString(metadata.productScopeKey),
subscriptionProductId: normalizeMetadataString(metadata.subscriptionProductId),
},
};
}
@@ -244,17 +535,236 @@ function normalizeMetadataSeatQuantity(value: string | number | null | undefined
return null;
}
function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): void {
function normalizeMetadataNonNegativeSeatQuantity(value: string | number | null | undefined): number | null {
if (typeof value === "number" && Number.isFinite(value)) {
const normalized = Math.trunc(value);
return normalized >= 0 ? normalized : null;
}
if (typeof value === "string" && value.trim()) {
const normalized = Number.parseInt(value, 10);
return Number.isFinite(normalized) && normalized >= 0 ? normalized : null;
}
return null;
}
function validateCreateCustomerInput(input: PaymentGatewayCreateCustomerInput): {
tenantId: string;
name: string;
email: string;
locale: string | null;
} {
const tenantId = input.tenantId.trim();
const name = input.name.trim();
const email = input.email.trim();
const locale = input.locale?.trim() || null;
if (!tenantId) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID");
if (!name) throw new MolliePaymentGatewayError("Customer name is required.", "CONFIG_INVALID");
if (!z.string().email().safeParse(email).success) {
throw new MolliePaymentGatewayError("Customer email must be valid.", "CONFIG_INVALID");
}
return { tenantId, name, email, locale };
}
function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): {
sequenceType: "oneoff" | "first" | "recurring";
method: MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null;
locale: MollieLocale | null;
mollieCustomerId: string | null;
mandateId: string | null;
trialEndsAt: string | null;
commitmentEndsAt: string | null;
storageAddOnCodes: readonly string[];
changeEffectiveAt: "immediate" | "period_end" | null;
changeEffectiveAtDate: string | null;
billingFlow: PaymentBillingFlow | null;
productAcquisitionId: string | null;
productKind: SubscriptionProductKind | null;
productScopeKey: string | null;
subscriptionProductId: string | null;
lagoProviderSubscriptionId: string | null;
lagoPlanCode: string | null;
} {
if (!input.tenantId.trim()) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID");
if (!input.invoiceExternalId.trim()) throw new MolliePaymentGatewayError("Invoice reference is required.", "CONFIG_INVALID");
if (!Number.isInteger(input.amountCents) || input.amountCents < 1) {
throw new MolliePaymentGatewayError("Amount must be a positive cent integer.", "CONFIG_INVALID");
const sequenceType = input.sequenceType ?? "oneoff";
if (sequenceType !== "oneoff" && sequenceType !== "first" && sequenceType !== "recurring") {
throw new MolliePaymentGatewayError("Payment sequence type is invalid.", "CONFIG_INVALID");
}
if (!Number.isInteger(input.amountCents) || input.amountCents < 0 || (input.amountCents === 0 && sequenceType !== "first")) {
throw new MolliePaymentGatewayError(
sequenceType === "first" ? "Amount must be a non-negative cent integer." : "Amount must be a positive cent integer.",
"CONFIG_INVALID"
);
}
if (!/^[A-Za-z]{3}$/u.test(input.currency)) {
throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID");
}
assertHttpUrl(input.redirectUrl, "Redirect URL");
const mollieCustomerId = input.mollieCustomerId?.trim() || null;
if ((sequenceType === "first" || sequenceType === "recurring") && !mollieCustomerId) {
throw new MolliePaymentGatewayError("Mollie customer id is required for first and recurring payments.", "CONFIG_INVALID");
}
const changeEffectiveAt = input.changeEffectiveAt ?? null;
if (changeEffectiveAt !== null && changeEffectiveAt !== "immediate" && changeEffectiveAt !== "period_end") {
throw new MolliePaymentGatewayError("Change effective mode is invalid.", "CONFIG_INVALID");
}
if (sequenceType === "recurring") {
if (input.redirectUrl) assertHttpUrl(input.redirectUrl, "Redirect URL");
} else {
if (!input.redirectUrl) {
throw new MolliePaymentGatewayError("Redirect URL is required.", "CONFIG_INVALID");
}
assertHttpUrl(input.redirectUrl, "Redirect URL");
}
assertHttpUrl(input.webhookUrl, "Webhook URL");
const billingFlow = normalizeBillingFlow(input.billingFlow);
const productAcquisitionId = normalizeMetadataString(input.productAcquisitionId);
const productKind = normalizeProductKind(input.productKind);
const productScopeKey = normalizeMetadataString(input.productScopeKey);
const subscriptionProductId = normalizeMetadataString(input.subscriptionProductId);
const lagoProviderSubscriptionId = normalizeMetadataString(input.lagoProviderSubscriptionId);
const lagoPlanCode = normalizeMetadataString(input.lagoPlanCode);
const method = normalizePaymentMethod(input.method, sequenceType);
const mandateId = normalizeMandateId(input.mandateId, sequenceType);
if (sequenceType === "recurring" && !mandateId) {
throw new MolliePaymentGatewayError("Mollie mandate id is required for recurring payments.", "CONFIG_INVALID");
}
const storageAddOnCodes = (input.storageAddOnCodes ?? []).map((code) => normalizeMetadataString(code));
if (storageAddOnCodes.some((code) => code === null) || new Set(storageAddOnCodes).size !== storageAddOnCodes.length) {
throw new MolliePaymentGatewayError("Storage add-on metadata is invalid.", "CONFIG_INVALID");
}
if (billingFlow === "product_acquisition") {
if (!productAcquisitionId || !productKind || !productScopeKey || !subscriptionProductId || !input.subscriptionPriceId?.trim()) {
throw new MolliePaymentGatewayError("Product acquisition metadata is incomplete.", "CONFIG_INVALID");
}
if (productKind === "base_plan" || productKind === "contract_override") {
throw new MolliePaymentGatewayError("Product acquisition kind is not payable.", "CONFIG_INVALID");
}
}
return {
sequenceType,
method,
locale: normalizeLocale(input.locale),
mollieCustomerId,
mandateId,
trialEndsAt: normalizeIsoTimestamp(input.trialEndsAt, "Trial end"),
commitmentEndsAt: normalizeIsoTimestamp(input.commitmentEndsAt, "Commitment end"),
storageAddOnCodes: storageAddOnCodes as string[],
changeEffectiveAt,
changeEffectiveAtDate: normalizeIsoTimestamp(input.changeEffectiveAtDate, "Change effective date"),
billingFlow,
productAcquisitionId,
productKind,
productScopeKey,
subscriptionProductId,
lagoProviderSubscriptionId,
lagoPlanCode,
};
}
function normalizePaymentMethod(
value: PaymentGatewayCreatePaymentInput["method"],
sequenceType: "oneoff" | "first" | "recurring"
): MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null {
if (value === null || value === undefined) return null;
if (typeof value === "string") {
if (!molliePaymentMethodIds.includes(value as MolliePaymentMethodId)) {
throw new MolliePaymentGatewayError("Payment method is invalid.", "CONFIG_INVALID");
}
if (sequenceType === "recurring" && value !== "directdebit" && value !== "creditcard" && value !== "paypal") {
throw new MolliePaymentGatewayError("Recurring collection method is invalid.", "CONFIG_INVALID");
}
if (sequenceType !== "recurring" && value === "directdebit") {
throw new MolliePaymentGatewayError("Direct debit is valid only for recurring collection payments.", "CONFIG_INVALID");
}
return value as MolliePaymentMethodId;
}
if (sequenceType !== "first" || value.length === 0) {
throw new MolliePaymentGatewayError("SEPA authorization methods are valid only for first payments.", "CONFIG_INVALID");
}
const allowed = new Set<string>(mollieSepaFirstPaymentMethods);
if (value.some((method) => !allowed.has(method)) || new Set(value).size !== value.length) {
throw new MolliePaymentGatewayError("SEPA authorization payment methods are invalid.", "CONFIG_INVALID");
}
return [...value];
}
function normalizeMandateId(value: string | null | undefined, sequenceType: "oneoff" | "first" | "recurring"): string | null {
if (value === null || value === undefined) return null;
const mandateId = value.trim();
if (sequenceType !== "recurring" || !/^mdt_[A-Za-z0-9]+$/u.test(mandateId)) {
throw new MolliePaymentGatewayError("Mollie mandate id is invalid.", "CONFIG_INVALID");
}
return mandateId;
}
function normalizeProviderTimestamp(value: string | null | undefined): string | null {
if (!value) return null;
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
}
function normalizeLocale(value: MollieLocale | null | undefined): MollieLocale | null {
if (value === null || value === undefined) return null;
if (!mollieLocales.includes(value)) {
throw new MolliePaymentGatewayError("Mollie locale is invalid.", "CONFIG_INVALID");
}
return value;
}
function validateListPaymentMethodsInput(input: PaymentGatewayListMethodsInput): {
amountCents: number | null;
currency: string;
sequenceType: "oneoff" | "first" | "recurring";
locale: MollieLocale | null;
} {
const currency = input.currency.trim().toUpperCase();
if (!/^[A-Z]{3}$/u.test(currency)) {
throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID");
}
if (input.sequenceType !== "oneoff" && input.sequenceType !== "first" && input.sequenceType !== "recurring") {
throw new MolliePaymentGatewayError("Payment sequence type is invalid.", "CONFIG_INVALID");
}
const amountCents = input.amountCents === null || input.amountCents === undefined ? null : input.amountCents;
if (amountCents !== null && (!Number.isSafeInteger(amountCents) || amountCents < 0)) {
throw new MolliePaymentGatewayError("Amount must be a non-negative cent integer.", "CONFIG_INVALID");
}
return {
amountCents,
currency,
sequenceType: input.sequenceType,
locale: normalizeLocale(input.locale),
};
}
function normalizeBillingFlow(value: string | null | undefined): PaymentBillingFlow | null {
return paymentBillingFlows.includes(value as PaymentBillingFlow) ? (value as PaymentBillingFlow) : null;
}
function normalizeProductKind(value: string | null | undefined): SubscriptionProductKind | null {
return subscriptionProductKinds.includes(value as SubscriptionProductKind) ? (value as SubscriptionProductKind) : null;
}
function normalizeIsoTimestamp(value: string | null | undefined, label: string): string | null {
if (value === null || value === undefined) return null;
const normalized = value.trim();
if (!z.string().datetime({ offset: true }).safeParse(normalized).success) {
throw new MolliePaymentGatewayError(`${label} must be an ISO timestamp with timezone.`, "CONFIG_INVALID");
}
return new Date(normalized).toISOString();
}
function normalizeChangeEffectiveAt(value: string | null | undefined): "immediate" | "period_end" | null {
return value === "immediate" || value === "period_end" ? value : null;
}
function normalizeMetadataString(value: string | null | undefined): string | null {
return value?.trim() || null;
}
function normalizeMetadataIsoTimestamp(value: string | null | undefined): string | null {
const normalized = normalizeMetadataString(value);
if (!normalized || !z.string().datetime({ offset: true }).safeParse(normalized).success) return null;
return new Date(normalized).toISOString();
}
function assertHttpUrl(value: string, label: string): void {
@@ -273,6 +783,15 @@ function normalizeTimeout(timeoutMs: number | undefined): number {
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_MOLLIE_TIMEOUT_MS;
}
function normalizeIdempotencyKey(value: string | null | undefined): string | null {
if (value === null || value === undefined) return null;
const key = value.trim();
if (!key || key.length > 255 || !/^[\x21-\x7e]+$/u.test(key)) {
throw new MolliePaymentGatewayError("Idempotency key must contain 1 to 255 visible ASCII characters.", "CONFIG_INVALID");
}
return key;
}
function centsToMollieValue(amountCents: number): string {
return (amountCents / 100).toFixed(2);
}
@@ -284,9 +803,21 @@ function mollieValueToCents(value: string | null | undefined): number | null {
return Math.round(Number(normalized) * 100);
}
function normalizePaymentStatus(status: string | null | undefined, refundedValue: string | null | undefined): PaymentGatewayPaymentStatus {
function normalizePaymentStatus(
status: string | null | undefined,
refundedValue: string | null | undefined,
originalValue: string | null | undefined
): PaymentGatewayPaymentStatus {
const refundedCents = mollieValueToCents(refundedValue);
if (typeof refundedCents === "number" && refundedCents > 0) return "refunded";
const originalCents = mollieValueToCents(originalValue);
// Mollie exposes partial and full refunds through the same amountRefunded
// field. Only a full refund is a terminal payment state; a partial refund
// keeps the provider status (normally `paid`) so the product ledger can
// quarantine it for operator reconciliation without revoking the complete
// entitlement.
if (typeof refundedCents === "number" && typeof originalCents === "number" && originalCents > 0 && refundedCents >= originalCents) {
return "refunded";
}
if (
status === "open" ||
status === "pending" ||