251 lines
10 KiB
TypeScript
251 lines
10 KiB
TypeScript
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<LoaderData> = ({ 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<LoaderData>();
|
|
const actionData = useActionData<ActionData>();
|
|
const [searchParams] = useSearchParams();
|
|
|
|
const errorModal = useRef<RefErrorModal>(null);
|
|
|
|
useEffect(() => {
|
|
if (actionData?.error) {
|
|
errorModal.current?.show(actionData.error);
|
|
}
|
|
}, [actionData]);
|
|
|
|
function canSubscribe() {
|
|
return getUserHasPermission(data, "app.settings.subscription.update");
|
|
}
|
|
return (
|
|
<div data-ui-id="ui.subscription.checkout.page">
|
|
<div className="pt-4">
|
|
<div className="mx-auto max-w-7xl px-4 pt-2 sm:px-6 lg:px-8">
|
|
<div className="flex shrink-0 justify-center">
|
|
<div className="mt-4 flex">
|
|
<Link
|
|
to={subscriptionSettingsPath(data.currentTenant.slug)}
|
|
className="w-full text-center text-sm font-medium hover:underline"
|
|
data-ui-id="ui.subscription.checkout.backLink"
|
|
>
|
|
<span aria-hidden="true"> ←</span> {t("settings.subscription.goToSubscription")}
|
|
</Link>
|
|
</div>
|
|
</div>
|
|
<div className="sm:align-center sm:flex sm:flex-col">
|
|
<div className="relative mx-auto w-full max-w-7xl space-y-4 overflow-hidden px-2 py-12 sm:py-6">
|
|
<div className="text-center">
|
|
<h1 className="text-3xl font-extrabold tracking-tight sm:text-4xl">{t("pricing.title")}</h1>
|
|
<p className="text-muted-foreground mt-4 text-lg leading-6">
|
|
{searchParams.get("error")?.toString() === "subscription_required" ? (
|
|
<span className="text-red-500">{t("pricing.required")}</span>
|
|
) : (
|
|
<span>{t("pricing.headline")}</span>
|
|
)}
|
|
</p>
|
|
</div>
|
|
{data?.items && (
|
|
<PlansGrouped
|
|
items={data.items}
|
|
canSubmit={canSubscribe()}
|
|
tenantSubscription={data.mySubscription}
|
|
stripeCoupon={data.coupon?.stripeCoupon || null}
|
|
currenciesAndPeriod={data.currenciesAndPeriod}
|
|
/>
|
|
)}
|
|
<ErrorModal ref={errorModal} />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|