import { useTranslation } from "react-i18next"; import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router"; import { Link, useActionData, useSearchParams } from "react-router"; import { getTranslations } from "~/locale/i18next.server"; import { getTenant } from "~/utils/db/tenants.db.server"; import { getUser } from "~/utils/db/users.db.server"; import { requireUserId, validateCSRFToken } from "~/utils/session.server"; import { getTenantIdFromUrl } from "~/utils/services/.server/urlService"; import { AppLoaderData } from "~/utils/data/useAppData"; import { loadAppData } from "~/utils/data/.server/appData"; import PlansGrouped from "~/components/core/settings/subscription/plans/PlansGrouped"; import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto"; import { getAllSubscriptionProducts, getSubscriptionProductsInIds } from "@toolctrl/db/subscriptions.server"; import { createTenantSubscription, getTenantSubscription, updateTenantSubscriptionCustomerId } from "~/utils/db/tenantSubscriptions.db.server"; import { createStripeCheckoutSession, createStripeCustomer, getStripeCoupon } from "~/utils/stripe.server"; import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal"; import { useEffect, useRef } from "react"; import SubscriptionHelper from "~/utils/helpers/SubscriptionHelper"; import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper"; import type Stripe from "stripe"; import { getAbsoluteCurrentUrl, getAbsoluteUrl } from "~/utils/url.server"; import { getCurrenciesAndPeriods, getDefaultBillingPeriod, getDefaultCurrency } from "~/utils/helpers/PricingHelper"; import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod"; import { v2MetaFunction } from "~/utils/compat/v2MetaFunction"; import { appPath } from "~/utils/app/CanonicalUrlUtils"; import { loadRequiredWebConfig } from "@toolctrl/config"; import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls"; import { subscriptionCheckoutPath } from "~/utils/app/SubscriptionUrlUtils"; import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService"; export const meta: v2MetaFunction = ({ data }) => [{ title: data?.title }]; export function subscriptionSettingsPath(tenantSlug: string) { return appPath({ tenantSlug, path: "settings/subscription", mode: "host-aware" }); } type LoaderData = AppLoaderData & { title: string; items: SubscriptionProductDto[]; coupon?: { error?: string; stripeCoupon?: Stripe.Coupon | null }; currenciesAndPeriod: { currencies: { value: string; options: string[] }; billingPeriods: { value: SubscriptionBillingPeriod; options: SubscriptionBillingPeriod[] }; }; }; export const loader = async ({ request, params }: LoaderFunctionArgs) => { const { t } = await getTranslations(request); const requestUrl = new URL(request.url); const userId = await requireUserId(request, `${requestUrl.pathname}${requestUrl.search}`); const tenantId = await getTenantIdFromUrl(params); const user = await getUser(userId); if (!user) { throw redirect(`/login`); } const tenant = await getTenant(tenantId); if (!tenant) { throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing)); } await verifyUserHasPermission(request, "app.settings.subscription.view", tenantId); const appData = await loadAppData({ request, params, t }); let items = await getAllSubscriptionProducts(true); const searchParams = new URL(request.url).searchParams; const planParam = searchParams.get("plan")?.toString(); if (planParam) { items = await getSubscriptionProductsInIds([planParam]); } const couponParam = searchParams.get("coupon"); let coupon: { error?: string; stripeCoupon?: Stripe.Coupon | null } | undefined = undefined; if (couponParam) { try { const stripeCoupon = await getStripeCoupon(couponParam); if (!stripeCoupon) { throw Error(t("pricing.coupons.invalid")); } if (stripeCoupon.max_redemptions && stripeCoupon.times_redeemed > stripeCoupon.max_redemptions) { throw Error(t("pricing.coupons.expired")); } if (!stripeCoupon.valid) { throw Error(t("pricing.coupons.invalid")); } coupon = { stripeCoupon }; } catch (e: any) { coupon = { error: e.message }; } } const defaultCurrency = getDefaultCurrency(request); const defaultBillingPeriod = getDefaultBillingPeriod(request); const data: LoaderData = { title: `${t("pricing.subscribe")} | ${process.env.APP_NAME}`, ...appData, items, coupon, currenciesAndPeriod: getCurrenciesAndPeriods( items.flatMap((f) => f.prices), defaultCurrency, defaultBillingPeriod ), }; return Response.json(data); }; type ActionData = { error?: string; success?: string; }; const badRequest = (data: ActionData) => Response.json(data, { status: 400 }); export const action: ActionFunction = async ({ request, params }) => { const { t } = await getTranslations(request); const userId = await requireUserId(request); const tenantId = await getTenantIdFromUrl(params); await validateCSRFToken(request); await verifyUserHasPermission(request, "app.settings.subscription.update", tenantId); const form = await request.formData(); // Tenant-mismatch guard: the subscribe form embeds the slug of the tenant // it was rendered for. Refuse if the form was posted to a different // tenant's action — protects against stale-form replay and the rare case // of a user opening multiple tabs on different tenants and clicking the // wrong one (we hit this exact case during staging shake-down). const formTenantSlug = form.get("tenant-slug-context")?.toString().trim(); if (formTenantSlug && params.tenant && formTenantSlug !== params.tenant) { return badRequest({ error: t("settings.subscription.checkout.tenantMismatch", { formTenantSlug, submittedTenantSlug: params.tenant, }), }); } const tenantSubscription = (await getTenantSubscription(tenantId)) ?? (await createTenantSubscription(tenantId, "")); const user = await getUser(userId); const tenant = await getTenant(tenantId); if (!tenantSubscription.stripeCustomerId && user && tenant) { const customer = await createStripeCustomer(user.email, tenant.name); if (customer) { tenantSubscription.stripeCustomerId = customer.id; await updateTenantSubscriptionCustomerId(tenant.id, { stripeCustomerId: customer.id, }); } } const action = form.get("action")?.toString(); if (!tenantSubscription || !tenantSubscription?.stripeCustomerId) { return badRequest({ error: t("settings.subscription.errors.invalidStripeCustomer"), }); } if (action === "subscribe") { try { const selectedPlan = await SubscriptionHelper.getPlanFromForm(form); const session = await createStripeCheckoutSession({ subscriptionProduct: selectedPlan.product, customer: tenantSubscription.stripeCustomerId, line_items: selectedPlan.line_items, mode: selectedPlan.mode, // Stripe's success_url placeholder must stay literal `{CHECKOUT_SESSION_ID}`. // `new URL()` (inside getAbsoluteUrl) encodes `{` and `}` to %7B/%7D, // which Stripe does NOT substitute. Decode back after the URL is built. success_url: getAbsoluteUrl(request, subscriptionCheckoutPath(params.tenant ?? "", "{CHECKOUT_SESSION_ID}/success")).replace( /%7BCHECKOUT_SESSION_ID%7D/gi, "{CHECKOUT_SESSION_ID}", ), cancel_url: getAbsoluteCurrentUrl(request), freeTrialDays: selectedPlan.freeTrialDays, coupon: selectedPlan.coupon, referral: selectedPlan.referral, }); if (!session || !session.url) { return badRequest({ error: t("settings.subscription.checkout.updateFailed"), }); } return redirect(session.url); } catch (e: any) { return badRequest({ error: t(e.message) }); } } }; export default function AppSubscriptionRoute() { const { t } = useTranslation(); const data = useLoaderData(); const actionData = useActionData(); const [searchParams] = useSearchParams(); const errorModal = useRef(null); useEffect(() => { if (actionData?.error) { errorModal.current?.show(actionData.error); } }, [actionData]); function canSubscribe() { return getUserHasPermission(data, "app.settings.subscription.update"); } return (
{t("settings.subscription.goToSubscription")}

{t("pricing.title")}

{searchParams.get("error")?.toString() === "subscription_required" ? ( {t("pricing.required")} ) : ( {t("pricing.headline")} )}

{data?.items && ( )}
); }