400 lines
14 KiB
TypeScript
400 lines
14 KiB
TypeScript
import {
|
|
billingCadences,
|
|
calculateBillingCatalogPrice,
|
|
calculateHiveGridGrossAmountCents,
|
|
} from "@hivegrid/entitlements";
|
|
import {
|
|
getTenantSubscription,
|
|
type TenantSubscriptionReaderClient,
|
|
type TenantSubscriptionWithDetails,
|
|
} from "@hivegrid/db/subscriptions.server";
|
|
|
|
import {
|
|
ProductAcquisitionError,
|
|
reserveProductAcquisitionLedger,
|
|
type CreateProductAcquisitionInput,
|
|
type ProductAcquisitionClient,
|
|
type ProductAcquisitionResult,
|
|
} from "./product-acquisition.server";
|
|
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
|
|
|
export const BASE_CHECKOUT_SCOPE_PREFIX = "base_checkout:v1:" as const;
|
|
|
|
type QueryClient = {
|
|
$queryRaw<T = unknown>(query: TemplateStringsArray, ...values: unknown[]): Promise<T>;
|
|
};
|
|
|
|
export type RecurringCheckoutPolicyClient = QueryClient & ProductAcquisitionClient;
|
|
|
|
type OpenRecurringAcquisition = {
|
|
readonly id: string;
|
|
readonly status: "pending" | "provider_pending" | "payment_pending";
|
|
readonly subscriptionProductId: string;
|
|
readonly scopeKey: string;
|
|
readonly amountCents: number | null;
|
|
readonly currency: string | null;
|
|
readonly reservationExpiresAt: Date | null;
|
|
readonly productCode: string | null;
|
|
};
|
|
|
|
type SelectedRecurringProduct = {
|
|
readonly productId: string;
|
|
readonly priceId: string;
|
|
readonly productCode: string | null;
|
|
readonly kind: string;
|
|
readonly productActive: boolean;
|
|
readonly productPublic: boolean;
|
|
readonly hasQuantity: boolean;
|
|
readonly priceActive: boolean;
|
|
readonly priceType: number;
|
|
readonly price: number | string | { toString(): string };
|
|
readonly currency: string;
|
|
};
|
|
|
|
type WithTenantPolicyClient = <T>(
|
|
tenantId: string,
|
|
operation: (client: RecurringCheckoutPolicyClient) => Promise<T>,
|
|
) => Promise<T>;
|
|
|
|
export type RecurringCheckoutReplacement = {
|
|
/** Base plan checkouts replace the current base price instead of adding to it. */
|
|
readonly replacesBasePlan?: boolean;
|
|
/** Product families such as e-mail tiers replace an active/open sibling tier. */
|
|
readonly replacedProductCodes?: readonly string[];
|
|
};
|
|
|
|
export type ReservedRecurringProductCheckout = {
|
|
readonly reservation: ProductAcquisitionResult;
|
|
readonly paymentPolicyAmountCents: number;
|
|
};
|
|
|
|
type ReservePolicyDependencies = {
|
|
readonly withTenant?: WithTenantPolicyClient;
|
|
readonly reserveLedger?: typeof reserveProductAcquisitionLedger;
|
|
readonly now?: () => Date;
|
|
};
|
|
|
|
function failClosed(): never {
|
|
throw new ProductAcquisitionError("PAYMENT_METHOD_UNAVAILABLE");
|
|
}
|
|
|
|
function safeAdd(...amounts: readonly number[]): number {
|
|
let total = 0;
|
|
for (const amount of amounts) {
|
|
if (!Number.isSafeInteger(amount) || amount < 0 || !Number.isSafeInteger(total + amount)) failClosed();
|
|
total += amount;
|
|
}
|
|
return total;
|
|
}
|
|
|
|
function activeAt(
|
|
product: TenantSubscriptionWithDetails["products"][number],
|
|
now: Date,
|
|
): boolean {
|
|
return !product.cancelledAt
|
|
&& (!product.currentPeriodStart || product.currentPeriodStart <= now)
|
|
&& (!product.endsAt || product.endsAt > now);
|
|
}
|
|
|
|
function fixedRecurringGrossAmountCents(
|
|
product: TenantSubscriptionWithDetails["products"][number],
|
|
): number {
|
|
const fixedPrices = product.prices.filter((candidate) => !candidate.isMetered && candidate.subscriptionPrice);
|
|
if (fixedPrices.length !== 1) failClosed();
|
|
const fixed = fixedPrices[0]!;
|
|
const currency = fixed.subscriptionPrice!.currency.trim().toUpperCase();
|
|
const quantity = fixed.quantity;
|
|
const numericPrice = Number(fixed.subscriptionPrice!.price);
|
|
const unitNetAmountCents = Math.round(numericPrice * 100);
|
|
if (
|
|
currency !== "EUR"
|
|
|| !Number.isSafeInteger(quantity)
|
|
|| quantity < 1
|
|
|| !Number.isFinite(numericPrice)
|
|
|| numericPrice < 0
|
|
|| !Number.isSafeInteger(unitNetAmountCents)
|
|
|| Math.abs(numericPrice * 100 - unitNetAmountCents) > 0.000_001
|
|
) {
|
|
failClosed();
|
|
}
|
|
const netAmountCents = unitNetAmountCents * quantity;
|
|
if (!Number.isSafeInteger(netAmountCents)) failClosed();
|
|
return calculateHiveGridGrossAmountCents(netAmountCents);
|
|
}
|
|
|
|
function currentBaseGrossAmountCents(
|
|
subscription: TenantSubscriptionWithDetails,
|
|
now: Date,
|
|
): number {
|
|
const activeBaseProducts = subscription.products.filter(
|
|
(product) => product.subscriptionProduct.kind === "base_plan" && activeAt(product, now),
|
|
);
|
|
const matchingBaseProducts = activeBaseProducts.filter((product) => {
|
|
const subscriptionPlanCode = subscription.planCode?.trim() ?? "";
|
|
return Boolean(
|
|
subscriptionPlanCode
|
|
&& (product.planCode?.trim() === subscriptionPlanCode || product.subscriptionProduct.code?.trim() === subscriptionPlanCode),
|
|
);
|
|
});
|
|
const baseProduct = matchingBaseProducts.length === 1
|
|
? matchingBaseProducts[0]
|
|
: activeBaseProducts.length === 1
|
|
? activeBaseProducts[0]
|
|
: null;
|
|
if (!baseProduct) failClosed();
|
|
const planCode = baseProduct.subscriptionProduct.code?.trim()
|
|
|| baseProduct.planCode?.trim()
|
|
|| subscription.planCode?.trim()
|
|
|| "";
|
|
const billingCadence = baseProduct.billingCadence?.trim() || subscription.billingCadence?.trim();
|
|
const cadence = billingCadence === billingCadences.monthly
|
|
? billingCadences.monthly
|
|
: billingCadence === billingCadences.annualSepa
|
|
? billingCadences.annualSepa
|
|
: null;
|
|
if (!planCode || !cadence) failClosed();
|
|
const officeSeatQuantity = baseProduct.officeSeatQuantity ?? subscription.officeSeatQuantity;
|
|
const fieldSeatQuantity = baseProduct.fieldSeatQuantity ?? subscription.fieldSeatQuantity;
|
|
if (
|
|
!Number.isSafeInteger(officeSeatQuantity)
|
|
|| officeSeatQuantity < 0
|
|
|| !Number.isSafeInteger(fieldSeatQuantity)
|
|
|| fieldSeatQuantity < 0
|
|
) {
|
|
failClosed();
|
|
}
|
|
const storageAddOnCodes = [...new Set([
|
|
...(baseProduct.storageAddOnCodes ?? subscription.storageAddOnCodes ?? []),
|
|
...subscription.products
|
|
.filter(
|
|
(product) => product.subscriptionProduct.kind === "recurring_add_on"
|
|
&& product.subscriptionProduct.code?.startsWith("storage_")
|
|
&& activeAt(product, now),
|
|
)
|
|
.map((product) => product.subscriptionProduct.code!),
|
|
])].sort();
|
|
try {
|
|
return calculateBillingCatalogPrice({
|
|
planCode,
|
|
cadence,
|
|
officeSeatQuantity,
|
|
fieldSeatQuantity,
|
|
storageAddOnCodes,
|
|
}).recurringGrossAmountCents;
|
|
} catch {
|
|
failClosed();
|
|
}
|
|
}
|
|
|
|
function currentOtherRecurringGrossAmountCents(
|
|
subscription: TenantSubscriptionWithDetails,
|
|
now: Date,
|
|
replacedProductCodes: ReadonlySet<string>,
|
|
): number {
|
|
let total = 0;
|
|
for (const product of subscription.products) {
|
|
const code = product.subscriptionProduct.code?.trim() ?? "";
|
|
if (
|
|
product.subscriptionProduct.kind !== "recurring_add_on"
|
|
|| code.startsWith("storage_")
|
|
|| replacedProductCodes.has(code)
|
|
|| !activeAt(product, now)
|
|
) {
|
|
continue;
|
|
}
|
|
total = safeAdd(total, fixedRecurringGrossAmountCents(product));
|
|
}
|
|
return total;
|
|
}
|
|
|
|
async function loadOpenRecurringAcquisitions(
|
|
client: QueryClient,
|
|
tenantId: string,
|
|
): Promise<readonly OpenRecurringAcquisition[]> {
|
|
return client.$queryRaw<OpenRecurringAcquisition[]>`
|
|
SELECT
|
|
acquisition."id",
|
|
acquisition."status"::text AS "status",
|
|
acquisition."subscriptionProductId",
|
|
acquisition."scopeKey",
|
|
acquisition."amountCents",
|
|
acquisition."currency",
|
|
acquisition."reservationExpiresAt",
|
|
product."code" AS "productCode"
|
|
FROM "TenantProductAcquisition" acquisition
|
|
INNER JOIN "SubscriptionProduct" product ON product."id" = acquisition."subscriptionProductId"
|
|
WHERE acquisition."tenantId" = ${tenantId}
|
|
AND acquisition."productKind"::text = 'recurring_add_on'
|
|
AND acquisition."status"::text IN ('pending', 'provider_pending', 'payment_pending')
|
|
`;
|
|
}
|
|
|
|
async function assertNoOpenBaseCheckout(client: QueryClient, tenantId: string): Promise<void> {
|
|
const rows = await client.$queryRaw<Array<{ readonly id: string }>>`
|
|
SELECT "id"
|
|
FROM "CheckoutSessionStatus"
|
|
WHERE "tenantId" = ${tenantId}
|
|
AND "productKind" = 'base_plan'
|
|
AND "scopeKey" LIKE ${`${BASE_CHECKOUT_SCOPE_PREFIX}%`}
|
|
AND "pending" = TRUE
|
|
AND "status" NOT IN ('canceled', 'failed', 'expired')
|
|
LIMIT 1
|
|
`;
|
|
if (rows.length > 0) throw new ProductAcquisitionError("IDEMPOTENCY_CONFLICT");
|
|
}
|
|
|
|
async function selectedRecurringGrossAmountCents(
|
|
client: QueryClient,
|
|
input: Pick<CreateProductAcquisitionInput, "productId" | "priceId" | "quantity">,
|
|
): Promise<number> {
|
|
const rows = await client.$queryRaw<SelectedRecurringProduct[]>`
|
|
SELECT
|
|
product."id" AS "productId",
|
|
price."id" AS "priceId",
|
|
product."code" AS "productCode",
|
|
product."kind"::text AS "kind",
|
|
product."active" AS "productActive",
|
|
product."public" AS "productPublic",
|
|
product."hasQuantity",
|
|
price."active" AS "priceActive",
|
|
price."type" AS "priceType",
|
|
price."price",
|
|
price."currency"
|
|
FROM "SubscriptionProduct" product
|
|
INNER JOIN "SubscriptionPrice" price ON price."subscriptionProductId" = product."id"
|
|
WHERE product."id" = ${input.productId}
|
|
AND price."id" = ${input.priceId}
|
|
`;
|
|
if (rows.length !== 1) failClosed();
|
|
const selected = rows[0]!;
|
|
const quantity = input.quantity ?? 1;
|
|
const numericPrice = Number(selected.price);
|
|
const unitNetAmountCents = Math.round(numericPrice * 100);
|
|
if (
|
|
selected.kind !== "recurring_add_on"
|
|
|| !selected.productActive
|
|
|| !selected.productPublic
|
|
|| !selected.priceActive
|
|
|| selected.priceType !== 1
|
|
|| selected.currency.trim().toUpperCase() !== "EUR"
|
|
|| !Number.isSafeInteger(quantity)
|
|
|| quantity < 1
|
|
|| (!selected.hasQuantity && quantity !== 1)
|
|
|| !Number.isFinite(numericPrice)
|
|
|| numericPrice <= 0
|
|
|| !Number.isSafeInteger(unitNetAmountCents)
|
|
|| Math.abs(numericPrice * 100 - unitNetAmountCents) > 0.000_001
|
|
) {
|
|
failClosed();
|
|
}
|
|
const netAmountCents = unitNetAmountCents * quantity;
|
|
if (!Number.isSafeInteger(netAmountCents)) failClosed();
|
|
return calculateHiveGridGrossAmountCents(netAmountCents);
|
|
}
|
|
|
|
export async function acquireTenantRecurringCheckoutPolicyLock(
|
|
client: QueryClient,
|
|
tenantId: string,
|
|
): Promise<void> {
|
|
await client.$queryRaw`
|
|
SELECT pg_catalog.pg_advisory_xact_lock(
|
|
pg_catalog.hashtextextended('recurring-checkout-policy:' || ${tenantId}, 26030)
|
|
)::text AS "lock"
|
|
`;
|
|
}
|
|
|
|
export async function resolveLockedRecurringCheckoutPolicyAmount(
|
|
client: QueryClient,
|
|
input: {
|
|
readonly tenantId: string;
|
|
readonly now: Date;
|
|
readonly selectedRecurringGrossAmountCents: number;
|
|
readonly targetProductId?: string;
|
|
readonly targetScopeKey?: string;
|
|
readonly replacement?: RecurringCheckoutReplacement;
|
|
readonly allowOpenBaseCheckout?: boolean;
|
|
},
|
|
): Promise<number> {
|
|
if (!input.allowOpenBaseCheckout) await assertNoOpenBaseCheckout(client, input.tenantId);
|
|
const subscription = await getTenantSubscription(
|
|
input.tenantId,
|
|
client as unknown as TenantSubscriptionReaderClient,
|
|
);
|
|
const activeSubscription = Boolean(
|
|
subscription
|
|
&& subscription.status === "active"
|
|
&& subscription.frozenAt === null
|
|
&& subscription.cancelledAt === null,
|
|
);
|
|
if (!activeSubscription && !input.replacement?.replacesBasePlan) {
|
|
throw new ProductAcquisitionError("BASE_SUBSCRIPTION_REQUIRED");
|
|
}
|
|
const replacedProductCodes = new Set(input.replacement?.replacedProductCodes ?? []);
|
|
let total = activeSubscription && !input.replacement?.replacesBasePlan
|
|
? currentBaseGrossAmountCents(subscription!, input.now)
|
|
: 0;
|
|
if (activeSubscription) {
|
|
total = safeAdd(total, currentOtherRecurringGrossAmountCents(subscription!, input.now, replacedProductCodes));
|
|
}
|
|
|
|
const openAcquisitions = await loadOpenRecurringAcquisitions(client, input.tenantId);
|
|
for (const acquisition of openAcquisitions) {
|
|
const reservationExpiresAt = acquisition.reservationExpiresAt;
|
|
if (!reservationExpiresAt) failClosed();
|
|
if (reservationExpiresAt <= input.now) {
|
|
if (acquisition.status === "pending") continue;
|
|
failClosed();
|
|
}
|
|
const productCode = acquisition.productCode?.trim() ?? "";
|
|
const exactTarget = acquisition.subscriptionProductId === input.targetProductId
|
|
&& acquisition.scopeKey === input.targetScopeKey;
|
|
if (!exactTarget && replacedProductCodes.has(productCode)) {
|
|
throw new ProductAcquisitionError("IDEMPOTENCY_CONFLICT");
|
|
}
|
|
if (exactTarget) continue;
|
|
if (
|
|
acquisition.currency?.trim().toUpperCase() !== "EUR"
|
|
|| !Number.isSafeInteger(acquisition.amountCents)
|
|
|| (acquisition.amountCents ?? 0) <= 0
|
|
) {
|
|
failClosed();
|
|
}
|
|
total = safeAdd(total, acquisition.amountCents!);
|
|
}
|
|
return safeAdd(total, input.selectedRecurringGrossAmountCents);
|
|
}
|
|
|
|
export async function reserveRecurringProductCheckoutLedgerWithClient(
|
|
client: RecurringCheckoutPolicyClient,
|
|
input: CreateProductAcquisitionInput,
|
|
replacement: RecurringCheckoutReplacement = {},
|
|
dependencies: Pick<ReservePolicyDependencies, "reserveLedger" | "now"> = {},
|
|
): Promise<ReservedRecurringProductCheckout> {
|
|
const now = dependencies.now?.() ?? new Date();
|
|
await acquireTenantRecurringCheckoutPolicyLock(client, input.tenantId);
|
|
const selectedGrossAmountCents = await selectedRecurringGrossAmountCents(client, input);
|
|
const paymentPolicyAmountCents = await resolveLockedRecurringCheckoutPolicyAmount(client, {
|
|
tenantId: input.tenantId,
|
|
now,
|
|
selectedRecurringGrossAmountCents: selectedGrossAmountCents,
|
|
targetProductId: input.productId,
|
|
targetScopeKey: input.scopeKey,
|
|
replacement,
|
|
});
|
|
const lockedInput = { ...input, paymentPolicyAmountCents };
|
|
const reservation = await (dependencies.reserveLedger ?? reserveProductAcquisitionLedger)(lockedInput, { client });
|
|
return { reservation, paymentPolicyAmountCents };
|
|
}
|
|
|
|
export async function reserveRecurringProductCheckoutLedger(
|
|
input: CreateProductAcquisitionInput,
|
|
replacement: RecurringCheckoutReplacement = {},
|
|
dependencies: ReservePolicyDependencies = {},
|
|
): Promise<ReservedRecurringProductCheckout> {
|
|
const withTenant = dependencies.withTenant
|
|
?? (<T>(tenantId: string, operation: (client: RecurringCheckoutPolicyClient) => Promise<T>) =>
|
|
withTenantRLS(tenantId, (tx) => operation(tx as unknown as RecurringCheckoutPolicyClient)));
|
|
return withTenant(input.tenantId, (client) =>
|
|
reserveRecurringProductCheckoutLedgerWithClient(client, input, replacement, dependencies));
|
|
}
|