326 lines
16 KiB
TypeScript
326 lines
16 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { LoaderFunctionArgs, redirect, useNavigate } from "react-router";
|
|
import { Link, useLoaderData } from "react-router";
|
|
import Logo from "~/components/brand/Logo";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { getTenant } from "~/utils/db/tenants.db.server";
|
|
import { getUser } from "~/utils/db/users.db.server";
|
|
import { getUserInfo } from "~/utils/session.server";
|
|
import { AppLoaderData } from "~/utils/data/useAppData";
|
|
import { loadAppData } from "~/utils/data/.server/appData";
|
|
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
|
import { addTenantProductsFromCheckoutSession, CheckoutSessionResponse, getAcquiredItemsFromCheckoutSession } from "~/utils/services/.server/pricingService";
|
|
import { createLog } from "~/utils/db/logs.db.server";
|
|
import { persistCheckoutSessionStatus } from "~/utils/services/.server/subscriptionService";
|
|
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
|
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
|
import { loadRequiredWebConfig } from "@toolctrl/config";
|
|
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
|
import { useLocaleFormatters } from "~/locale/format";
|
|
|
|
const AUTO_REDIRECT_SECONDS = 10;
|
|
|
|
function intervalTranslationKey(period: number | undefined) {
|
|
if (period === SubscriptionBillingPeriod.MONTHLY) return "settings.subscription.checkout.success.intervals.month";
|
|
if (period === SubscriptionBillingPeriod.YEARLY) return "settings.subscription.checkout.success.intervals.year";
|
|
if (period === SubscriptionBillingPeriod.QUARTERLY) return "settings.subscription.checkout.success.intervals.quarter";
|
|
if (period === SubscriptionBillingPeriod.SEMI_ANNUAL) return "settings.subscription.checkout.success.intervals.halfYear";
|
|
return null;
|
|
}
|
|
|
|
function nextBillingDate(period: number | undefined) {
|
|
const d = new Date();
|
|
if (period === SubscriptionBillingPeriod.MONTHLY) d.setMonth(d.getMonth() + 1);
|
|
else if (period === SubscriptionBillingPeriod.YEARLY) d.setFullYear(d.getFullYear() + 1);
|
|
else if (period === SubscriptionBillingPeriod.QUARTERLY) d.setMonth(d.getMonth() + 3);
|
|
else if (period === SubscriptionBillingPeriod.SEMI_ANNUAL) d.setMonth(d.getMonth() + 6);
|
|
else return null;
|
|
return d;
|
|
}
|
|
|
|
type LoaderData = AppLoaderData & {
|
|
title: string;
|
|
checkoutSession: CheckoutSessionResponse | null;
|
|
error?: string;
|
|
};
|
|
|
|
export function subscribeTenantHomePath(tenantSlug: string) {
|
|
return appPath({ tenantSlug, mode: "host-aware" });
|
|
}
|
|
|
|
export function subscribeTenantSubscriptionSettingsPath(tenantSlug: string) {
|
|
return appPath({ tenantSlug, path: "settings/subscription", mode: "host-aware" });
|
|
}
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "subscribe.$tenant.$session.success");
|
|
let { t } = await getTranslations(request);
|
|
const [tenantId, userInfo] = await Promise.all([
|
|
time(getTenantIdFromUrl(params), "getTenantIdFromUrl"),
|
|
time(getUserInfo(request), "getUserInfo"),
|
|
]);
|
|
|
|
const user = await time(getUser(userInfo.userId), "getUser");
|
|
if (!user) {
|
|
throw redirect(`/login`);
|
|
}
|
|
const tenant = await time(getTenant(tenantId), "getTenant");
|
|
if (!tenant) {
|
|
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
|
|
}
|
|
await time(verifyUserHasPermission(request, "app.settings.subscription.update", tenantId), "verifyUserHasPermission");
|
|
|
|
await time(
|
|
persistCheckoutSessionStatus({
|
|
request,
|
|
id: params.session ?? "",
|
|
fromUrl: new URL(request.url).pathname,
|
|
fromUserId: user.id,
|
|
fromTenantId: tenant.id,
|
|
}),
|
|
"persistCheckoutSessionStatus"
|
|
);
|
|
const checkoutSession = await time(getAcquiredItemsFromCheckoutSession(params.session ?? ""), "getAcquiredItemsFromCheckoutSession");
|
|
|
|
const appData = await time(loadAppData({ request, params, t, time }), "loadAppData");
|
|
const data: LoaderData = {
|
|
title: `${t("pricing.subscribe")} | ${process.env.APP_NAME}`,
|
|
...appData,
|
|
checkoutSession,
|
|
};
|
|
|
|
if (checkoutSession) {
|
|
try {
|
|
await time(
|
|
addTenantProductsFromCheckoutSession({
|
|
request,
|
|
tenantId: tenantId,
|
|
user,
|
|
checkoutSession,
|
|
createdUserId: null,
|
|
createdTenantId: null,
|
|
t,
|
|
}),
|
|
"addTenantProductsFromCheckoutSession"
|
|
);
|
|
await Promise.all(
|
|
checkoutSession.products.map(async (product) => {
|
|
await createLog(request, tenantId, "Subscribed", t(product.title ?? ""));
|
|
})
|
|
);
|
|
return Response.json(data, { headers: getServerTimingHeader() });
|
|
} catch (e: any) {
|
|
return Response.json({ ...data, error: t("shared.unexpectedError") }, { status: 500, headers: getServerTimingHeader() });
|
|
}
|
|
}
|
|
return data;
|
|
};
|
|
|
|
export default function SubscribeTenantSuccessRoute() {
|
|
const { t } = useTranslation();
|
|
const formatters = useLocaleFormatters();
|
|
const data = useLoaderData<LoaderData>();
|
|
const navigate = useNavigate();
|
|
|
|
const tenantSlug = data.currentTenant.slug;
|
|
const dashboardPath = appPath({ tenantSlug, path: "dashboard", mode: "host-aware" });
|
|
const profilePath = appPath({ tenantSlug, path: "settings/profile", mode: "host-aware" });
|
|
const membersPath = appPath({ tenantSlug, path: "settings/members", mode: "host-aware" });
|
|
|
|
const showSuccess = !!data.checkoutSession && !data.error;
|
|
|
|
// Confetti burst on mount — client-only, dynamic import keeps SSR + bundle clean.
|
|
useEffect(() => {
|
|
if (!showSuccess) return;
|
|
let cancelled = false;
|
|
void import("canvas-confetti").then((mod) => {
|
|
if (cancelled) return;
|
|
const confetti = mod.default;
|
|
const colors = ["#6366F1", "#22C55E", "#F59E0B", "#EC4899", "#3B82F6"];
|
|
confetti({ particleCount: 120, spread: 70, origin: { y: 0.55 }, colors });
|
|
setTimeout(() => !cancelled && confetti({ particleCount: 50, angle: 60, spread: 55, origin: { x: 0, y: 0.6 }, colors }), 250);
|
|
setTimeout(() => !cancelled && confetti({ particleCount: 50, angle: 120, spread: 55, origin: { x: 1, y: 0.6 }, colors }), 400);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [showSuccess]);
|
|
|
|
// Auto-redirect countdown — pauses on hover so user can read.
|
|
const [secondsLeft, setSecondsLeft] = useState(AUTO_REDIRECT_SECONDS);
|
|
const [paused, setPaused] = useState(false);
|
|
useEffect(() => {
|
|
if (!showSuccess || paused) return;
|
|
if (secondsLeft <= 0) {
|
|
navigate(dashboardPath);
|
|
return;
|
|
}
|
|
const timer = setTimeout(() => setSecondsLeft((s) => s - 1), 1000);
|
|
return () => clearTimeout(timer);
|
|
}, [secondsLeft, paused, showSuccess, navigate, dashboardPath]);
|
|
|
|
if (!showSuccess) {
|
|
return (
|
|
<div data-ui-id={data.error ? "ui.subscription.checkout.success.error" : "ui.subscription.checkout.success.invalid"}>
|
|
<div className="pt-20">
|
|
<div className="mx-auto max-w-7xl px-4 pt-2 sm:px-6 lg:px-8">
|
|
<div className="flex shrink-0 justify-center">
|
|
<Logo to={subscribeTenantHomePath(data.currentTenant.slug)} />
|
|
</div>
|
|
<div className="sm:align-center sm:flex sm:flex-col">
|
|
<div className="relative mx-auto w-full max-w-xl overflow-hidden px-2 py-12 sm:py-6">
|
|
<div className="text-center">
|
|
{data.error ? (
|
|
<>
|
|
<h1 className="text-3xl font-extrabold tracking-tight sm:text-4xl">{t("shared.unexpectedError")}</h1>
|
|
<p className="mt-4 text-lg leading-6 text-red-500">{data.error}</p>
|
|
</>
|
|
) : (
|
|
<>
|
|
<h1 className="text-3xl font-extrabold tracking-tight sm:text-4xl">{t("shared.error")}</h1>
|
|
<p className="mt-4 text-lg leading-6 text-red-500">{t("settings.subscription.checkout.invalid")}</p>
|
|
</>
|
|
)}
|
|
<div className="mt-4">
|
|
<Link
|
|
data-ui-id="ui.subscription.checkout.success.subscriptionLink"
|
|
className="focus:border-accent-300 hover:bg-secondary border-border text-foreground bg-background inline-flex items-center space-x-2 rounded-full border px-3 py-2 text-sm font-medium shadow-2xs focus:ring-2 focus:outline-hidden dark:border-gray-800 dark:bg-gray-800 dark:text-white dark:hover:bg-gray-700"
|
|
to={subscribeTenantSubscriptionSettingsPath(data.currentTenant.slug)}
|
|
>
|
|
← {t("settings.subscription.checkout.success.goToSubscription")}
|
|
</Link>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// Success variant — confetti, receipt, next-steps, auto-redirect.
|
|
const session = data.checkoutSession!;
|
|
const firstProduct = session.products[0];
|
|
const firstPriceWrap = firstProduct?.prices?.[0];
|
|
const flatPrice = firstPriceWrap?.flatPrice;
|
|
const productTitle = firstProduct ? t(firstProduct.title ?? "") : "";
|
|
const priceAmount = flatPrice ? Number(flatPrice.price ?? 0) : 0;
|
|
const priceCurrency = flatPrice?.currency ?? "eur";
|
|
const period = flatPrice?.billingPeriod;
|
|
const formattedPrice =
|
|
priceAmount > 0
|
|
? formatters.currency(priceAmount, priceCurrency.toUpperCase(), {
|
|
minimumFractionDigits: priceAmount % 1 === 0 ? 0 : 2,
|
|
})
|
|
: null;
|
|
const intervalKey = intervalTranslationKey(period);
|
|
const interval = intervalKey ? t(intervalKey) : "";
|
|
const nextDate = nextBillingDate(period);
|
|
const progressPct = Math.max(0, Math.min(100, (secondsLeft / AUTO_REDIRECT_SECONDS) * 100));
|
|
|
|
return (
|
|
<div className="min-h-screen" data-ui-id="ui.subscription.checkout.success.page" onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
|
|
<div className="pt-16">
|
|
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
|
|
<div className="flex shrink-0 justify-center">
|
|
<Logo to={subscribeTenantHomePath(tenantSlug)} />
|
|
</div>
|
|
|
|
<div className="mx-auto mt-10 w-full max-w-xl space-y-6 px-2">
|
|
<div className="text-center" data-ui-id="ui.subscription.checkout.success.hero">
|
|
<div className="text-5xl">🎉</div>
|
|
<h1 className="mt-4 text-3xl font-extrabold tracking-tight sm:text-4xl">{t("settings.subscription.checkout.success.title")}</h1>
|
|
<p className="text-muted-foreground mt-3 text-lg leading-6">{t("settings.subscription.checkout.success.description", { 0: productTitle })}</p>
|
|
</div>
|
|
|
|
{/* Receipt card */}
|
|
<div className="border-border bg-card rounded-xl border p-6 shadow-sm" data-ui-id="ui.subscription.checkout.success.receipt">
|
|
<div className="text-muted-foreground text-xs font-medium tracking-wider uppercase">{t("settings.subscription.checkout.success.orderSummary")}</div>
|
|
<div className="mt-4 space-y-3 text-sm">
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-muted-foreground">{t("settings.subscription.checkout.success.fields.plan")}</span>
|
|
<span className="text-foreground font-semibold">{productTitle}</span>
|
|
</div>
|
|
{formattedPrice && (
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-muted-foreground">{t("settings.subscription.checkout.success.fields.price")}</span>
|
|
<span className="text-foreground font-semibold">
|
|
{formattedPrice}
|
|
{interval ? ` / ${interval}` : ""}
|
|
</span>
|
|
</div>
|
|
)}
|
|
{nextDate && (
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-muted-foreground">{t("settings.subscription.checkout.success.fields.nextInvoice")}</span>
|
|
<span className="text-foreground font-semibold">{formatters.date(nextDate, { dateStyle: "long" })}</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Next steps */}
|
|
<div data-ui-id="ui.subscription.checkout.success.nextSteps">
|
|
<div className="text-muted-foreground mb-3 text-xs font-medium tracking-wider uppercase">
|
|
{t("settings.subscription.checkout.success.nextSteps.title")}
|
|
</div>
|
|
<div className="grid gap-3 sm:grid-cols-3">
|
|
<Link
|
|
data-ui-id="ui.subscription.checkout.success.profileLink"
|
|
to={profilePath}
|
|
className="border-border bg-card hover:border-accent-400 hover:bg-secondary group rounded-lg border p-4 text-left transition-colors"
|
|
>
|
|
<div className="text-2xl">👤</div>
|
|
<div className="mt-2 text-sm font-semibold">{t("settings.subscription.checkout.success.nextSteps.profile.title")}</div>
|
|
<div className="text-muted-foreground mt-1 text-xs">{t("settings.subscription.checkout.success.nextSteps.profile.description")}</div>
|
|
</Link>
|
|
<Link
|
|
data-ui-id="ui.subscription.checkout.success.membersLink"
|
|
to={membersPath}
|
|
className="border-border bg-card hover:border-accent-400 hover:bg-secondary group rounded-lg border p-4 text-left transition-colors"
|
|
>
|
|
<div className="text-2xl">👥</div>
|
|
<div className="mt-2 text-sm font-semibold">{t("settings.subscription.checkout.success.nextSteps.inviteTeam.title")}</div>
|
|
<div className="text-muted-foreground mt-1 text-xs">{t("settings.subscription.checkout.success.nextSteps.inviteTeam.description")}</div>
|
|
</Link>
|
|
<Link
|
|
data-ui-id="ui.subscription.checkout.success.dashboardLink"
|
|
to={dashboardPath}
|
|
className="border-border bg-card hover:border-accent-400 hover:bg-secondary group rounded-lg border p-4 text-left transition-colors"
|
|
>
|
|
<div className="text-2xl">🚀</div>
|
|
<div className="mt-2 text-sm font-semibold">{t("settings.subscription.checkout.success.nextSteps.dashboard.title")}</div>
|
|
<div className="text-muted-foreground mt-1 text-xs">{t("settings.subscription.checkout.success.nextSteps.dashboard.description")}</div>
|
|
</Link>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Auto-redirect indicator */}
|
|
<div className="text-center" data-ui-id="ui.subscription.checkout.success.autoRedirect">
|
|
<div className="bg-secondary mx-auto h-1 max-w-xs overflow-hidden rounded-full">
|
|
<div className="bg-foreground h-full transition-[width] duration-1000 ease-linear" style={{ width: `${progressPct}%` }} />
|
|
</div>
|
|
<div className="text-muted-foreground mt-2 text-xs">
|
|
{paused
|
|
? t("settings.subscription.checkout.success.autoRedirect.paused")
|
|
: t("settings.subscription.checkout.success.autoRedirect.countdown", { seconds: secondsLeft })}
|
|
</div>
|
|
<Link
|
|
data-ui-id="ui.subscription.checkout.success.subscriptionLink"
|
|
className="text-muted-foreground hover:text-foreground mt-3 inline-block text-xs underline-offset-2 hover:underline"
|
|
to={subscribeTenantSubscriptionSettingsPath(tenantSlug)}
|
|
>
|
|
{t("settings.subscription.checkout.success.goToSubscription")}
|
|
</Link>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|