Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+40
-181
@@ -6,8 +6,8 @@ import {
|
||||
createSubscriptionProduct,
|
||||
createSubscriptionPrice,
|
||||
createSubscriptionFeature,
|
||||
updateSubscriptionProductStripeId,
|
||||
updateSubscriptionPriceStripeId,
|
||||
updateSubscriptionProductBillingProviderId,
|
||||
updateSubscriptionPriceBillingProviderId,
|
||||
deleteSubscriptionPrice,
|
||||
deleteSubscriptionProduct,
|
||||
updateSubscriptionProduct,
|
||||
@@ -16,28 +16,12 @@ import {
|
||||
deleteSubscriptionUsageBasedPrice,
|
||||
createSubscriptionUsageBasedPrice,
|
||||
createSubscriptionUsageBasedTier,
|
||||
getSubscriptionPriceByStripeId,
|
||||
getSubscriptionUsageBasedPriceByStripeId,
|
||||
getSubscriptionProduct,
|
||||
getAllSubscriptionProducts,
|
||||
} from "../../db/subscriptionProducts.db.server";
|
||||
import {
|
||||
createStripeProduct,
|
||||
createStripePrice,
|
||||
archiveStripePrice,
|
||||
deleteStripeProduct,
|
||||
updateStripeProduct,
|
||||
createStripeUsageBasedPrice,
|
||||
archiveStripeProduct,
|
||||
getStripeSession,
|
||||
createStripeCustomer,
|
||||
createStripeSubscription,
|
||||
} from "../../stripe.server";
|
||||
import { CheckoutSessionStatus, SubscriptionPrice, SubscriptionUsageBasedPrice } from "@toolctrl/db/prisma-browser";
|
||||
import Stripe from "stripe";
|
||||
import { getOrPersistTenantSubscription, updateTenantSubscriptionCustomerId } from "../../db/tenantSubscriptions.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 { getCheckoutSessionStatus, updateCheckoutSessionStatus } from "../../db/stripe/checkoutSessions.db.server";
|
||||
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
|
||||
import { TFunction } from "i18next";
|
||||
import { TenantTypesApi } from "../../api/.server/TenantTypesApi";
|
||||
@@ -50,9 +34,14 @@ import { cancelTenantSubscription, clearAllSubscriptionsCache, clearTenantSubscr
|
||||
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(
|
||||
@@ -77,11 +66,9 @@ export async function createPlan(
|
||||
usageBasedPrices?: SubscriptionUsageBasedPriceDto[],
|
||||
t?: TFunction
|
||||
) {
|
||||
// Create stripe product
|
||||
const stripeProduct = await createStripeProduct({ title: plan.translatedTitle ?? plan.title });
|
||||
// Save to db
|
||||
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
|
||||
const product = await createSubscriptionProduct({
|
||||
stripeId: stripeProduct?.id ?? "",
|
||||
billingProviderId: productBillingProviderId,
|
||||
order: plan.order,
|
||||
title: plan.title,
|
||||
model: plan.model,
|
||||
@@ -102,13 +89,10 @@ export async function createPlan(
|
||||
|
||||
await Promise.all(
|
||||
prices.map(async (price) => {
|
||||
// Create stripe price
|
||||
const stripePrice = await createStripePrice(stripeProduct?.id ?? "", price);
|
||||
// Save to db
|
||||
return await createSubscriptionPrice({
|
||||
...price,
|
||||
subscriptionProductId: product.id,
|
||||
stripeId: stripePrice?.id ?? "",
|
||||
billingProviderId: localBillingProviderId("price", `${product.id}_${price.billingPeriod}_${price.currency}_${price.price}`),
|
||||
type: SubscriptionPriceType.RECURRING,
|
||||
billingPeriod: price.billingPeriod,
|
||||
price: price.price,
|
||||
@@ -135,13 +119,12 @@ export async function createPlan(
|
||||
{ op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit },
|
||||
"Creating usage-based price",
|
||||
);
|
||||
const stripePrice = await createStripeUsageBasedPrice(stripeProduct?.id ?? "", {
|
||||
...usageBasedPrice,
|
||||
unitTitle: t ? t(usageBasedPrice.unitTitle) : usageBasedPrice.unitTitle,
|
||||
});
|
||||
const createdPrice = await createSubscriptionUsageBasedPrice({
|
||||
subscriptionProductId: product.id,
|
||||
stripeId: stripePrice?.id ?? "",
|
||||
billingProviderId: localBillingProviderId(
|
||||
"usage",
|
||||
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`,
|
||||
),
|
||||
billingPeriod: usageBasedPrice.billingPeriod,
|
||||
currency: usageBasedPrice.currency,
|
||||
unit: usageBasedPrice.unit,
|
||||
@@ -175,23 +158,14 @@ export async function syncPlan(
|
||||
if (!plan.id) {
|
||||
throw new Error(`Plan ${plan.title} not found on database`);
|
||||
}
|
||||
const stripeProduct = await createStripeProduct({ title: plan.translatedTitle ?? plan.title });
|
||||
if (!stripeProduct) {
|
||||
throw new Error("Could not create product");
|
||||
}
|
||||
await updateSubscriptionProductStripeId(plan.id, {
|
||||
stripeId: stripeProduct.id,
|
||||
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
|
||||
await updateSubscriptionProductBillingProviderId(plan.id, {
|
||||
billingProviderId: productBillingProviderId,
|
||||
});
|
||||
|
||||
prices.map(async (price) => {
|
||||
// Create stripe price
|
||||
const stripePrice = await createStripePrice(stripeProduct?.id ?? "", price);
|
||||
if (!stripePrice) {
|
||||
throw new Error(`Could not create price ${plan.title} - ${price.price}`);
|
||||
}
|
||||
// Save to db
|
||||
await updateSubscriptionPriceStripeId(price.id ?? "", {
|
||||
stripeId: stripePrice?.id ?? "",
|
||||
await updateSubscriptionPriceBillingProviderId(price.id ?? "", {
|
||||
billingProviderId: localBillingProviderId("price", `${plan.id}_${price.billingPeriod}_${price.currency}_${price.price}`),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -201,8 +175,6 @@ export async function updatePlan(plan: SubscriptionProductDto, features: Subscri
|
||||
throw new Error(`Plan ${plan.title} not found on database`);
|
||||
}
|
||||
|
||||
await updateStripeProduct(plan.stripeId, { title: plan.translatedTitle ?? plan.title });
|
||||
|
||||
await updateSubscriptionProduct(plan.id, {
|
||||
order: plan.order,
|
||||
title: plan.title,
|
||||
@@ -235,10 +207,7 @@ export async function deletePlan(plan: SubscriptionProductDto) {
|
||||
|
||||
await Promise.all(
|
||||
plan.prices
|
||||
.filter((f) => f.stripeId)
|
||||
.map(async (price) => {
|
||||
await archiveStripePrice(price.stripeId);
|
||||
|
||||
if (price.id) {
|
||||
await deleteSubscriptionPrice(price.id);
|
||||
}
|
||||
@@ -254,8 +223,6 @@ export async function deletePlan(plan: SubscriptionProductDto) {
|
||||
if (plan.usageBasedPrices) {
|
||||
await Promise.all(
|
||||
plan.usageBasedPrices?.map(async (price) => {
|
||||
await archiveStripePrice(price.stripeId);
|
||||
|
||||
await Promise.all(
|
||||
price.tiers.map(async (tier) => {
|
||||
return deleteSubscriptionUsageBasedTier(tier.id);
|
||||
@@ -268,19 +235,6 @@ export async function deletePlan(plan: SubscriptionProductDto) {
|
||||
);
|
||||
}
|
||||
|
||||
pricingLogger.info({ op: "deletePlan.product", planId: plan.id, stripeId: plan.stripeId }, "Deleting Stripe product");
|
||||
if (plan.stripeId) {
|
||||
try {
|
||||
await deleteStripeProduct(plan.stripeId);
|
||||
} catch (e: any) {
|
||||
pricingLogger.warn(
|
||||
{ err: e, op: "deletePlan.product.archive", planId: plan.id, stripeId: plan.stripeId },
|
||||
"Could not delete Stripe product; archiving instead",
|
||||
);
|
||||
await archiveStripeProduct(plan.stripeId);
|
||||
}
|
||||
}
|
||||
|
||||
if (plan.id) {
|
||||
await deleteSubscriptionProduct(plan.id);
|
||||
}
|
||||
@@ -301,91 +255,17 @@ export type CheckoutSessionResponse = {
|
||||
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
|
||||
}[];
|
||||
status: CheckoutSessionStatus | null;
|
||||
source?: "self-service" | "legacy";
|
||||
};
|
||||
export async function getAcquiredItemsFromCheckoutSession(session_id: string | null): Promise<CheckoutSessionResponse | null> {
|
||||
const session = await getStripeSession(session_id ?? "");
|
||||
if (!session || session.status !== "complete") {
|
||||
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;
|
||||
}
|
||||
const prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[] = [];
|
||||
try {
|
||||
let line_items: { price: Stripe.Price; quantity: number | undefined }[] = [];
|
||||
if (session.line_items) {
|
||||
session.line_items.data.forEach((item) => {
|
||||
if (item.price) {
|
||||
line_items.push({
|
||||
price: item.price,
|
||||
quantity: item.quantity ?? undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
line_items.map(async (line_item) => {
|
||||
const flatPrice = await getSubscriptionPriceByStripeId(line_item.price.id);
|
||||
const usageBasedPrice = await getSubscriptionUsageBasedPriceByStripeId(line_item.price.id);
|
||||
const quantity = line_item.quantity ?? undefined;
|
||||
if (!flatPrice && !usageBasedPrice) {
|
||||
throw new Error("Price not found: " + line_item.price.id);
|
||||
}
|
||||
prices.push({
|
||||
flatPrice: flatPrice ?? undefined,
|
||||
usageBasedPrice: usageBasedPrice ?? undefined,
|
||||
quantity,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (e: any) {
|
||||
pricingLogger.error({ err: e, op: "getAcquiredItemsFromCheckoutSession" }, "Failed to load acquired items from checkout session");
|
||||
}
|
||||
|
||||
const products: {
|
||||
id: string;
|
||||
title: string;
|
||||
quantity: number;
|
||||
subscription: string | undefined;
|
||||
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
|
||||
}[] = [];
|
||||
|
||||
prices.forEach((item) => {
|
||||
const productId = item.flatPrice?.subscriptionProductId ?? item.usageBasedPrice?.subscriptionProductId ?? "";
|
||||
if (!productId) {
|
||||
return;
|
||||
}
|
||||
const product = products.find((p) => p.id === productId);
|
||||
if (!product) {
|
||||
products.push({
|
||||
id: productId,
|
||||
title: "",
|
||||
quantity: item.quantity ?? 1,
|
||||
prices: [item],
|
||||
subscription: session.subscription?.toString(),
|
||||
});
|
||||
} else {
|
||||
product?.prices.push(item);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
products.map(async (product) => {
|
||||
const subscriptionProduct = await getSubscriptionProduct(product.id);
|
||||
product.title = subscriptionProduct?.title ?? "";
|
||||
})
|
||||
);
|
||||
|
||||
const status = await getCheckoutSessionStatus(session.id);
|
||||
|
||||
return {
|
||||
id: session.id,
|
||||
customer: {
|
||||
id: session.customer?.toString() ?? "",
|
||||
name: session.customer_details?.name ?? "",
|
||||
email: session.customer_details?.email ?? "",
|
||||
},
|
||||
products,
|
||||
status,
|
||||
};
|
||||
return await completeSelfServiceCheckout({ sessionId: session_id, tenantId: options.tenantId });
|
||||
}
|
||||
|
||||
export async function addTenantProductsFromCheckoutSession({
|
||||
@@ -405,6 +285,9 @@ export async function addTenantProductsFromCheckoutSession({
|
||||
createdTenantId?: string | null;
|
||||
t: TFunction;
|
||||
}) {
|
||||
if (checkoutSession.source === "self-service") {
|
||||
return;
|
||||
}
|
||||
clearTenantSubscriptionCache(tenantId);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const tenant = await getTenant(tenantId);
|
||||
@@ -412,34 +295,13 @@ export async function addTenantProductsFromCheckoutSession({
|
||||
throw new Error("Tenant not found");
|
||||
}
|
||||
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
|
||||
if (!tenantSubscription.stripeCustomerId) {
|
||||
const customer = await createStripeCustomer(user.email, tenant.name);
|
||||
if (customer) {
|
||||
tenantSubscription.stripeCustomerId = customer.id;
|
||||
await updateTenantSubscriptionCustomerId(tenant.id, {
|
||||
stripeCustomerId: customer.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
const existingSessionStatus = await getCheckoutSessionStatus(checkoutSession.id);
|
||||
if (!checkoutSession) {
|
||||
throw new Error(t("settings.subscription.checkout.invalid"));
|
||||
} else if (checkoutSession.customer.id !== tenantSubscription.stripeCustomerId) {
|
||||
throw new Error(t("settings.subscription.checkout.invalidCustomer"));
|
||||
} else if (!existingSessionStatus) {
|
||||
throw new Error(t("settings.subscription.checkout.invalid"));
|
||||
} else if (!existingSessionStatus.pending) {
|
||||
throw new Error(t("settings.subscription.checkout.alreadyProcessed"));
|
||||
} else {
|
||||
await updateCheckoutSessionStatus(checkoutSession.id, {
|
||||
pending: false,
|
||||
createdUserId,
|
||||
createdTenantId,
|
||||
});
|
||||
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.stripeSubscriptionId) || [];
|
||||
const recurringSubscriptions = activeSubscriptions?.products.filter((f) => f.billingProviderSubscriptionId) || [];
|
||||
pricingLogger.info(
|
||||
{
|
||||
op: "cancelExistingSubscriptions",
|
||||
@@ -474,7 +336,7 @@ export async function addTenantProductsFromCheckoutSession({
|
||||
tenantSubscriptionId: tenantSubscription.id,
|
||||
subscriptionProductId: product.id ?? "",
|
||||
quantity: product.quantity,
|
||||
stripeSubscriptionId: product.subscription ?? "",
|
||||
billingProviderSubscriptionId: product.subscription ?? "",
|
||||
fromCheckoutSessionId: checkoutSession.id,
|
||||
prices: product.prices.map((price) => {
|
||||
return {
|
||||
@@ -558,10 +420,7 @@ export async function autosubscribeToTrialOrFreePlan({
|
||||
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant not found; skipping");
|
||||
return;
|
||||
}
|
||||
if (!tenant.subscription?.stripeCustomerId) {
|
||||
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant has no Stripe customer id; skipping");
|
||||
return;
|
||||
}
|
||||
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
|
||||
const defaultCurrency = currencies.find((f) => f.default)?.value;
|
||||
if (!defaultCurrency) {
|
||||
return;
|
||||
@@ -603,13 +462,11 @@ export async function autosubscribeToTrialOrFreePlan({
|
||||
"Autosubscribing tenant to trial/free plan",
|
||||
);
|
||||
const price = productsWithTrialDays[0];
|
||||
const trial_end = Math.floor(Date.now() / 1000) + (price.trialDays || 30) * 24 * 60 * 60;
|
||||
const stripeSubscription = await createStripeSubscription(tenant.subscription.stripeCustomerId, price.stripeId, trial_end);
|
||||
await addTenantSubscriptionProduct({
|
||||
tenantSubscriptionId: tenant.subscription.id,
|
||||
tenantSubscriptionId: tenantSubscription.id,
|
||||
subscriptionProductId: price.subscriptionProductId,
|
||||
quantity: 1,
|
||||
stripeSubscriptionId: stripeSubscription.id,
|
||||
billingProviderSubscriptionId: "",
|
||||
fromCheckoutSessionId: null,
|
||||
prices: [
|
||||
{
|
||||
@@ -635,7 +492,9 @@ export async function autosubscribeToTrialOrFreePlan({
|
||||
} satisfies SubscriptionSubscribedDto,
|
||||
});
|
||||
} else if (productsFree.length > 0) {
|
||||
// TODO: IMPLEMENT
|
||||
// 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",
|
||||
|
||||
Reference in new issue
Block a user