512 lines
19 KiB
TypeScript
512 lines
19 KiB
TypeScript
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
|
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
|
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
|
|
import { SubscriptionProductDto } from "../../../application/dtos/subscriptions/SubscriptionProductDto";
|
|
import {
|
|
createSubscriptionProduct,
|
|
createSubscriptionPrice,
|
|
createSubscriptionFeature,
|
|
updateSubscriptionProductBillingProviderId,
|
|
updateSubscriptionPriceBillingProviderId,
|
|
deleteSubscriptionPrice,
|
|
deleteSubscriptionProduct,
|
|
updateSubscriptionProduct,
|
|
deleteSubscriptionFeatures,
|
|
deleteSubscriptionUsageBasedTier,
|
|
deleteSubscriptionUsageBasedPrice,
|
|
createSubscriptionUsageBasedPrice,
|
|
createSubscriptionUsageBasedTier,
|
|
getSubscriptionProduct,
|
|
getAllSubscriptionProducts,
|
|
} from "../../db/subscriptionProducts.db.server";
|
|
import { CheckoutSessionStatus, SubscriptionPrice, SubscriptionUsageBasedPrice } from "@hivegrid/db/prisma-browser";
|
|
import { getOrPersistTenantSubscription } from "../../db/tenantSubscriptions.db.server";
|
|
import { getTenant } from "../../db/tenants.db.server";
|
|
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
|
|
import { TFunction } from "i18next";
|
|
import { TenantTypesApi } from "../../api/.server/TenantTypesApi";
|
|
import { addTenantSubscriptionProduct } from "../../db/subscriptions/tenantSubscriptionProducts.db.server";
|
|
import EventsService from "../../../modules/events/services/.server/EventsService";
|
|
import { SubscriptionSubscribedDto } from "~/modules/events/dtos/SubscriptionSubscribedDto";
|
|
import { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
|
|
import { getUser } from "../../db/users.db.server";
|
|
import { cancelTenantSubscription, clearAllSubscriptionsCache, clearTenantSubscriptionCache, getActiveTenantSubscriptions } from "./subscriptionService";
|
|
import currencies from "~/application/pricing/currencies";
|
|
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
|
import { createScopedLogger } from "~/utils/logger.server";
|
|
import { completeSelfServiceCheckout } from "~/services/billing/self-service-checkout.server";
|
|
|
|
const pricingLogger = createScopedLogger("pricing");
|
|
|
|
function localBillingProviderId(prefix: string, seed: string) {
|
|
return `local_${prefix}_${seed.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 72)}`;
|
|
}
|
|
|
|
export async function createPlans(plans: SubscriptionProductDto[]) {
|
|
for (const plan of plans.sort((a, b) => a.order - b.order)) {
|
|
await createPlan(
|
|
plan,
|
|
plan.prices.map((price) => {
|
|
return {
|
|
billingPeriod: price.billingPeriod,
|
|
currency: price.currency,
|
|
price: Number(price.price),
|
|
};
|
|
}),
|
|
plan.features,
|
|
plan.usageBasedPrices
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function createPlan(
|
|
plan: SubscriptionProductDto,
|
|
prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[],
|
|
features: SubscriptionFeatureDto[],
|
|
usageBasedPrices?: SubscriptionUsageBasedPriceDto[],
|
|
t?: TFunction
|
|
) {
|
|
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
|
|
const product = await createSubscriptionProduct({
|
|
billingProviderId: productBillingProviderId,
|
|
order: plan.order,
|
|
title: plan.title,
|
|
model: plan.model,
|
|
description: plan.description ?? null,
|
|
badge: plan.badge ?? null,
|
|
groupTitle: plan.groupTitle ?? null,
|
|
groupDescription: plan.groupDescription ?? null,
|
|
active: plan.active,
|
|
public: plan.public,
|
|
billingAddressCollection: plan.billingAddressCollection ?? "auto",
|
|
hasQuantity: plan.hasQuantity ?? false,
|
|
canBuyAgain: plan.canBuyAgain ?? false,
|
|
});
|
|
|
|
if (!product) {
|
|
throw new Error("Could not create subscription product");
|
|
}
|
|
|
|
await Promise.all(
|
|
prices.map(async (price) => {
|
|
return await createSubscriptionPrice({
|
|
...price,
|
|
subscriptionProductId: product.id,
|
|
billingProviderId: localBillingProviderId("price", `${product.id}_${price.billingPeriod}_${price.currency}_${price.price}`),
|
|
type: SubscriptionPriceType.RECURRING,
|
|
billingPeriod: price.billingPeriod,
|
|
price: price.price,
|
|
currency: price.currency,
|
|
trialDays: price.trialDays ?? 0,
|
|
active: true,
|
|
});
|
|
})
|
|
);
|
|
|
|
await Promise.all(
|
|
features
|
|
.sort((a, b) => a.order - b.order)
|
|
.map(async (feature) => {
|
|
// Save to db
|
|
return await createSubscriptionFeature(product.id, feature);
|
|
})
|
|
);
|
|
|
|
if (usageBasedPrices) {
|
|
await Promise.all(
|
|
usageBasedPrices.map(async (usageBasedPrice) => {
|
|
pricingLogger.info(
|
|
{ op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit },
|
|
"Creating usage-based price",
|
|
);
|
|
const createdPrice = await createSubscriptionUsageBasedPrice({
|
|
subscriptionProductId: product.id,
|
|
billingProviderId: localBillingProviderId(
|
|
"usage",
|
|
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`,
|
|
),
|
|
billingPeriod: usageBasedPrice.billingPeriod,
|
|
currency: usageBasedPrice.currency,
|
|
unit: usageBasedPrice.unit,
|
|
unitTitle: usageBasedPrice.unitTitle,
|
|
unitTitlePlural: usageBasedPrice.unitTitlePlural,
|
|
usageType: usageBasedPrice.usageType,
|
|
aggregateUsage: usageBasedPrice.aggregateUsage,
|
|
tiersMode: usageBasedPrice.tiersMode,
|
|
billingScheme: usageBasedPrice.billingScheme,
|
|
});
|
|
await Promise.all(
|
|
usageBasedPrice.tiers.map(async (tierPrice) => {
|
|
await createSubscriptionUsageBasedTier({
|
|
subscriptionUsageBasedPriceId: createdPrice.id,
|
|
from: tierPrice.from,
|
|
to: tierPrice.to !== null && tierPrice.to !== undefined ? Number(tierPrice.to) : null,
|
|
perUnitPrice: tierPrice.perUnitPrice !== null && tierPrice.perUnitPrice !== undefined ? Number(tierPrice.perUnitPrice) : null,
|
|
flatFeePrice: tierPrice.flatFeePrice !== null && tierPrice.flatFeePrice !== undefined ? Number(tierPrice.flatFeePrice) : null,
|
|
});
|
|
})
|
|
);
|
|
})
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function syncPlan(
|
|
plan: SubscriptionProductDto,
|
|
prices: { id?: string; billingPeriod: SubscriptionBillingPeriod; price: number; currency: string }[]
|
|
) {
|
|
if (!plan.id) {
|
|
throw new Error(`Plan ${plan.title} not found on database`);
|
|
}
|
|
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
|
|
await updateSubscriptionProductBillingProviderId(plan.id, {
|
|
billingProviderId: productBillingProviderId,
|
|
});
|
|
|
|
prices.map(async (price) => {
|
|
await updateSubscriptionPriceBillingProviderId(price.id ?? "", {
|
|
billingProviderId: localBillingProviderId("price", `${plan.id}_${price.billingPeriod}_${price.currency}_${price.price}`),
|
|
});
|
|
});
|
|
}
|
|
|
|
export async function updatePlan(plan: SubscriptionProductDto, features: SubscriptionFeatureDto[]) {
|
|
if (!plan.id) {
|
|
throw new Error(`Plan ${plan.title} not found on database`);
|
|
}
|
|
|
|
await updateSubscriptionProduct(plan.id, {
|
|
order: plan.order,
|
|
title: plan.title,
|
|
model: plan.model,
|
|
description: plan.description ?? null,
|
|
badge: plan.badge ?? null,
|
|
groupTitle: plan.groupTitle ?? null,
|
|
groupDescription: plan.groupDescription ?? null,
|
|
public: plan.public,
|
|
billingAddressCollection: plan.billingAddressCollection ?? "auto",
|
|
hasQuantity: plan.hasQuantity === undefined ? undefined : plan.hasQuantity,
|
|
canBuyAgain: plan.canBuyAgain === undefined ? undefined : plan.canBuyAgain,
|
|
});
|
|
|
|
await deleteSubscriptionFeatures(plan.id ?? "");
|
|
await clearAllSubscriptionsCache();
|
|
|
|
return await Promise.all(
|
|
features
|
|
.sort((a, b) => a.order - b.order)
|
|
.map(async (feature) => {
|
|
return await createSubscriptionFeature(plan.id ?? "", feature);
|
|
})
|
|
);
|
|
}
|
|
|
|
export async function deletePlan(plan: SubscriptionProductDto) {
|
|
await clearAllSubscriptionsCache();
|
|
pricingLogger.info({ op: "deletePlan.flatPrices", planId: plan.id, count: plan.prices?.length ?? 0 }, "Deleting flat-rate prices");
|
|
|
|
await Promise.all(
|
|
plan.prices
|
|
.map(async (price) => {
|
|
if (price.id) {
|
|
await deleteSubscriptionPrice(price.id);
|
|
}
|
|
|
|
return null;
|
|
})
|
|
);
|
|
|
|
pricingLogger.info(
|
|
{ op: "deletePlan.usageBasedPrices", planId: plan.id, count: plan.usageBasedPrices?.length ?? 0 },
|
|
"Deleting usage-based prices",
|
|
);
|
|
if (plan.usageBasedPrices) {
|
|
await Promise.all(
|
|
plan.usageBasedPrices?.map(async (price) => {
|
|
await Promise.all(
|
|
price.tiers.map(async (tier) => {
|
|
return deleteSubscriptionUsageBasedTier(tier.id);
|
|
})
|
|
);
|
|
await deleteSubscriptionUsageBasedPrice(price.id);
|
|
|
|
return null;
|
|
})
|
|
);
|
|
}
|
|
|
|
if (plan.id) {
|
|
await deleteSubscriptionProduct(plan.id);
|
|
}
|
|
}
|
|
|
|
export type CheckoutSessionResponse = {
|
|
id: string;
|
|
customer: {
|
|
id: string;
|
|
email: string;
|
|
name: string;
|
|
};
|
|
products: {
|
|
id: string;
|
|
title: string;
|
|
quantity: number;
|
|
subscription: string | undefined;
|
|
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
|
|
}[];
|
|
status: CheckoutSessionStatus | null;
|
|
source?: "self-service" | "legacy";
|
|
};
|
|
export async function getAcquiredItemsFromCheckoutSession(
|
|
session_id: string | null,
|
|
options?: { tenantId?: string | null }
|
|
): Promise<CheckoutSessionResponse | null> {
|
|
if (!session_id || !options?.tenantId) {
|
|
pricingLogger.warn({ op: "getAcquiredItemsFromCheckoutSession", sessionId: session_id }, "Checkout session context is missing");
|
|
return null;
|
|
}
|
|
return await completeSelfServiceCheckout({ sessionId: session_id, tenantId: options.tenantId });
|
|
}
|
|
|
|
export async function addTenantProductsFromCheckoutSession({
|
|
request,
|
|
tenantId,
|
|
user,
|
|
checkoutSession,
|
|
createdUserId,
|
|
createdTenantId,
|
|
t,
|
|
}: {
|
|
request: Request;
|
|
tenantId: string;
|
|
user: { id: string; email: string };
|
|
checkoutSession: CheckoutSessionResponse;
|
|
createdUserId?: string | null;
|
|
createdTenantId?: string | null;
|
|
t: TFunction;
|
|
}) {
|
|
if (checkoutSession.source === "self-service") {
|
|
return;
|
|
}
|
|
clearTenantSubscriptionCache(tenantId);
|
|
const appConfiguration = await getAppConfiguration({ request });
|
|
const tenant = await getTenant(tenantId);
|
|
if (!tenant) {
|
|
throw new Error("Tenant not found");
|
|
}
|
|
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
|
|
if (!checkoutSession) {
|
|
throw new Error(t("settings.subscription.checkout.invalid"));
|
|
} else {
|
|
if (!appConfiguration.subscription.multiple) {
|
|
const hasSubscribed = checkoutSession.products.some((product) => product.subscription);
|
|
const activeSubscriptions = await getActiveTenantSubscriptions(tenant.id);
|
|
const recurringSubscriptions = activeSubscriptions?.products.filter((f) => f.billingProviderSubscriptionId) || [];
|
|
pricingLogger.info(
|
|
{
|
|
op: "cancelExistingSubscriptions",
|
|
tenantId: tenant.id,
|
|
hasSubscribed,
|
|
recurringCount: recurringSubscriptions.length,
|
|
},
|
|
"Cancelling existing subscriptions before new subscribe",
|
|
);
|
|
if (hasSubscribed && recurringSubscriptions.length > 0) {
|
|
await Promise.all(
|
|
recurringSubscriptions.map(async (recurringSubscription) => {
|
|
pricingLogger.info(
|
|
{
|
|
op: "cancelSubscription",
|
|
tenantId: tenant.id,
|
|
subscriptionId: recurringSubscription.id,
|
|
productId: recurringSubscription.subscriptionProductId,
|
|
},
|
|
"Cancelling tenant subscription",
|
|
);
|
|
return await cancelTenantSubscription(recurringSubscription.id, { tenantId, userId: user.id, t });
|
|
})
|
|
);
|
|
}
|
|
}
|
|
await Promise.all(
|
|
checkoutSession.products.map(async (product) => {
|
|
// const existingProduct = await getTenantSubscriptionProduct(tenant.id, product.id);
|
|
// if (!existingProduct) {
|
|
await addTenantSubscriptionProduct({
|
|
tenantSubscriptionId: tenantSubscription.id,
|
|
subscriptionProductId: product.id ?? "",
|
|
quantity: product.quantity,
|
|
billingProviderSubscriptionId: product.subscription ?? "",
|
|
fromCheckoutSessionId: checkoutSession.id,
|
|
prices: product.prices.map((price) => {
|
|
return {
|
|
subscriptionPriceId: price.flatPrice?.id,
|
|
subscriptionUsageBasedPriceId: price.usageBasedPrice?.id,
|
|
};
|
|
}),
|
|
});
|
|
// } else {
|
|
// // is active
|
|
// if (!existingProduct.endsAt) {
|
|
// await updateTenantSubscriptionProduct(existingProduct.id, {
|
|
// quantity: (existingProduct.quantity ?? 1) + 1,
|
|
// });
|
|
// } else {
|
|
// await updateTenantSubscriptionProduct(existingProduct.id, {
|
|
// quantity: product.quantity,
|
|
// endsAt: null,
|
|
// cancelledAt: null,
|
|
// });
|
|
// }
|
|
// }
|
|
const subscriptionProduct = await getSubscriptionProduct(product.id);
|
|
if (subscriptionProduct) {
|
|
function checkUpgradeDowngrade(plan: SubscriptionProductDto) {
|
|
const existing = tenantSubscription?.products.find((f) => f)?.subscriptionProduct;
|
|
if (existing) {
|
|
if (plan.order > existing.order) {
|
|
return { upgrade: true };
|
|
} else {
|
|
return { downgrade: true };
|
|
}
|
|
}
|
|
}
|
|
|
|
let event: "subscription.subscribed" | "subscription.upgraded" | "subscription.downgraded" = "subscription.subscribed";
|
|
if (tenantSubscription.products.length > 0) {
|
|
const upgradeDowngrade = checkUpgradeDowngrade(subscriptionProduct);
|
|
if (upgradeDowngrade?.upgrade) {
|
|
event = "subscription.upgraded";
|
|
} else if (upgradeDowngrade?.downgrade) {
|
|
event = "subscription.downgraded";
|
|
}
|
|
}
|
|
await EventsService.create({
|
|
request,
|
|
event,
|
|
tenantId: tenant.id,
|
|
userId: user.id,
|
|
data: {
|
|
user: { id: user.id, email: user.email },
|
|
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
|
|
subscription: {
|
|
product: { id: product.id, title: t(subscriptionProduct.title) || subscriptionProduct.title },
|
|
session: checkoutSession.id,
|
|
},
|
|
} satisfies SubscriptionSubscribedDto,
|
|
});
|
|
|
|
await TenantTypesApi.setTenantTypes({ tenantId, subscriptionProduct });
|
|
}
|
|
})
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function autosubscribeToTrialOrFreePlan({
|
|
request,
|
|
t,
|
|
tenantId,
|
|
userId,
|
|
}: {
|
|
request: Request;
|
|
t: TFunction;
|
|
tenantId: string;
|
|
userId: string | null;
|
|
}) {
|
|
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Starting auto-subscribe to trial/free plan");
|
|
const tenant = await getTenant(tenantId);
|
|
if (!tenant) {
|
|
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant not found; skipping");
|
|
return;
|
|
}
|
|
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
|
|
const defaultCurrency = currencies.find((f) => f.default)?.value;
|
|
if (!defaultCurrency) {
|
|
return;
|
|
}
|
|
const allProducts = await getAllSubscriptionProducts(true);
|
|
const productsFree: SubscriptionPriceDto[] = [];
|
|
const productsWithTrialDays: SubscriptionPriceDto[] = [];
|
|
|
|
pricingLogger.debug(
|
|
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
|
|
"Auto-subscribe candidate products loaded",
|
|
);
|
|
|
|
allProducts.forEach((product) => {
|
|
if (product.prices.length === 0) {
|
|
return;
|
|
}
|
|
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
|
|
if (allPricesAreZero) {
|
|
productsFree.push(product.prices[0]);
|
|
}
|
|
const firstPriceWithTrialDays = product.prices.find(
|
|
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
|
|
);
|
|
if (firstPriceWithTrialDays) {
|
|
productsWithTrialDays.push(firstPriceWithTrialDays);
|
|
}
|
|
});
|
|
|
|
try {
|
|
if (productsWithTrialDays.length > 0) {
|
|
pricingLogger.info(
|
|
{
|
|
op: "autosubscribeToTrialOrFreePlan",
|
|
tenantId: tenant.id,
|
|
productCount: productsWithTrialDays.length,
|
|
productIds: productsWithTrialDays.map((p) => p.subscriptionProductId),
|
|
},
|
|
"Autosubscribing tenant to trial/free plan",
|
|
);
|
|
const price = productsWithTrialDays[0];
|
|
await addTenantSubscriptionProduct({
|
|
tenantSubscriptionId: tenantSubscription.id,
|
|
subscriptionProductId: price.subscriptionProductId,
|
|
quantity: 1,
|
|
billingProviderSubscriptionId: "",
|
|
fromCheckoutSessionId: null,
|
|
prices: [
|
|
{
|
|
subscriptionPriceId: price.id,
|
|
},
|
|
],
|
|
});
|
|
const user = userId ? await getUser(userId) : null;
|
|
await EventsService.create({
|
|
request,
|
|
event: "subscription.subscribed",
|
|
tenantId: tenant.id,
|
|
userId: user?.id ?? null,
|
|
data: {
|
|
user: !user ? null : { id: user.id, email: user.email },
|
|
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
|
|
subscription: {
|
|
product: {
|
|
id: price.subscriptionProductId,
|
|
title: t(price.subscriptionProduct?.title ?? "") || price.subscriptionProduct?.title || "",
|
|
},
|
|
},
|
|
} satisfies SubscriptionSubscribedDto,
|
|
});
|
|
} else if (productsFree.length > 0) {
|
|
// TODO(pricing): implement free-plan auto-subscribe. Free plans are planned for
|
|
// HiveGrid, so this branch must mirror the trial path above (create the free
|
|
// subscription + emit "subscription.subscribed") instead of only logging.
|
|
pricingLogger.info(
|
|
{ op: "autosubscribeToTrialOrFreePlan.free", tenantId, count: productsFree.length },
|
|
"Free products available but auto-subscribe-free path not implemented yet",
|
|
);
|
|
} else {
|
|
pricingLogger.info(
|
|
{ op: "autosubscribeToTrialOrFreePlan.none", tenantId },
|
|
"No auto-subscription products/plans found",
|
|
);
|
|
}
|
|
} catch (e: any) {
|
|
pricingLogger.error({ err: e, op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
|
|
}
|
|
}
|