Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,8 +1,9 @@
import { useEffect, useState } from "react";
import { useEffect, useRef } 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 { LoaderFunctionArgs, redirect, useNavigate, useRevalidator } from "react-router";
import { useLoaderData } from "react-router";
import { CheckoutSuccessPage } from "~/components/screens/billing/CheckoutSuccessPage";
import { clearPersistedCheckoutRequest } from "~/components/screens/billing/checkout-request";
import { getTranslations } from "~/locale/i18next.server";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
@@ -20,10 +21,23 @@ 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";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveTenantBillingState, type BillingSubscriptionStatus } from "@hivegrid/db/billing-domain.server";
import {
billingCadences,
calculateBillingCatalogPrice,
getBillingCatalogPlan,
getEmailMarketingCommercialProduct,
hiveGridBasePlans,
type BillingCadence,
} from "@hivegrid/entitlements";
import {
projectSelfServiceCheckoutReturnState,
type SelfServiceCheckoutReturnState,
} from "~/services/billing/self-service-checkout.server";
const AUTO_REDIRECT_SECONDS = 10;
function intervalTranslationKey(period: number | undefined) {
function intervalTranslationKey(period: number | undefined, cadence: string | null | undefined) {
if (cadence === billingCadences.annualSepa) return "settings.subscription.checkout.success.intervals.annualCommitment";
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";
@@ -31,19 +45,49 @@ function intervalTranslationKey(period: number | undefined) {
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 CheckoutReceipt = {
subscriptionStatus: BillingSubscriptionStatus;
trialEndsAt: string | null;
currentPeriodEnd: string | null;
amountCents: number | null;
recurringGrossTotalCents: number | null;
currency: string | null;
billingCadence: string | null;
};
function checkoutRecurringGrossTotal(checkoutSession: CheckoutSessionResponse): number | null {
const status = checkoutSession.status;
if (!status?.planCode) return null;
const cadence: BillingCadence | null =
status.billingCadence === billingCadences.annualSepa
? billingCadences.annualSepa
: status.billingCadence === billingCadences.monthly
? billingCadences.monthly
: null;
if (!cadence) return null;
const planCode =
getBillingCatalogPlan(status.planCode)?.technicalCode ??
hiveGridBasePlans.find((plan) => plan.variants.some((variant) => variant.code === status.planCode))?.technicalCode;
if (!planCode) return null;
try {
return calculateBillingCatalogPrice({
planCode,
cadence,
officeSeatQuantity: status.officeSeatQuantity,
fieldSeatQuantity: status.fieldSeatQuantity,
storageAddOnCodes: status.storageAddOnCodes,
}).recurringGrossAmountCents;
} catch {
return null;
}
}
type LoaderData = AppLoaderData & {
title: string;
checkoutSession: CheckoutSessionResponse | null;
checkoutState: SelfServiceCheckoutReturnState | "invalid";
checkoutReceipt: CheckoutReceipt | null;
emailMarketingFollowUp: { code: string; titleKey: string } | null;
error?: string;
};
@@ -51,75 +95,113 @@ 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 function subscribeTenantSubscriptionSettingsPath(tenantSlug: string, emailMarketingAddOnCode?: string | null) {
const path = appPath({ tenantSlug, path: "settings/billing", mode: "host-aware" });
if (!emailMarketingAddOnCode) return path;
const searchParams = new URLSearchParams({ email_add_on: emailMarketingAddOnCode });
return `${path}?${searchParams}`;
}
export function subscribeTenantWelcomePath(tenantSlug: string) {
return appPath({ tenantSlug, path: "onboarding/welcome", mode: "host-aware" });
}
const CHECKOUT_STATUS_AUTO_POLL_LIMIT = 12;
const CHECKOUT_STATUS_INITIAL_POLL_MS = 2_500;
const CHECKOUT_STATUS_MAX_POLL_MS = 30_000;
function checkoutStatusPollDelay(cycle: number): number {
return Math.min(CHECKOUT_STATUS_INITIAL_POLL_MS * 2 ** cycle, CHECKOUT_STATUS_MAX_POLL_MS);
}
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 [tenantId, userInfo] = await Promise.all([time(getTenantIdFromUrl(params), "getTenantIdFromUrl"), time(getUserInfo(request), "getUserInfo")]);
const user = await time(getUser(userInfo.userId), "getUser");
const user = await time(
runWithRlsContext({ userId: userInfo.userId }, () => 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 ?? "", { tenantId }),
"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 runWithRlsContext({ tenantId, userId: user.id }, async () => {
const tenant = await time(getTenant(tenantId), "getTenant");
if (!tenant) {
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
}
return data;
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,
tenantId: tenant.id,
}),
"persistCheckoutSessionStatus"
);
const checkoutSession = await time(getAcquiredItemsFromCheckoutSession(params.session ?? "", { tenantId }), "getAcquiredItemsFromCheckoutSession");
const checkoutState = checkoutSession ? projectSelfServiceCheckoutReturnState(checkoutSession.status?.status) : "invalid";
const appData = await time(loadAppData({ request, params, t, time }), "loadAppData");
const data: LoaderData = {
title: `${t("pricing.subscribe")} | ${process.env.APP_NAME}`,
...appData,
checkoutSession,
checkoutState,
checkoutReceipt: null,
emailMarketingFollowUp: (() => {
const code = new URL(request.url).searchParams.get("email_add_on")?.trim() ?? "";
const product = getEmailMarketingCommercialProduct(code);
return product ? { code: product.code, titleKey: product.title } : null;
})(),
};
if (checkoutSession && checkoutState === "paid") {
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 ?? ""));
})
);
const billingState = await time(resolveTenantBillingState(tenantId), "resolveTenantBillingState");
return Response.json(
{
...data,
checkoutReceipt: {
subscriptionStatus: billingState.status,
trialEndsAt: billingState.trialEndsAt?.toISOString() ?? null,
currentPeriodEnd: billingState.currentPeriodEnd?.toISOString() ?? null,
amountCents: checkoutSession.status?.amountCents ?? null,
recurringGrossTotalCents: checkoutRecurringGrossTotal(checkoutSession),
currency: checkoutSession.status?.currency ?? null,
billingCadence: checkoutSession.status?.billingCadence ?? null,
},
} satisfies LoaderData,
{ headers: getServerTimingHeader() }
);
} catch (_e: any) {
return Response.json({ ...data, error: t("shared.unexpectedError") }, { status: 500, headers: getServerTimingHeader() });
}
}
return Response.json(data, { headers: getServerTimingHeader() });
});
};
export default function SubscribeTenantSuccessRoute() {
@@ -127,202 +209,93 @@ export default function SubscribeTenantSuccessRoute() {
const formatters = useLocaleFormatters();
const data = useLoaderData<LoaderData>();
const navigate = useNavigate();
const revalidator = useRevalidator();
const revalidatorStateRef = useRef(revalidator.state);
const revalidateRef = useRef(revalidator.revalidate);
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 billingHref = subscribeTenantSubscriptionSettingsPath(tenantSlug);
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;
revalidatorStateRef.current = revalidator.state;
revalidateRef.current = revalidator.revalidate;
}, [revalidator.revalidate, revalidator.state]);
useEffect(() => {
if (data.checkoutState !== "processing") return;
let stopped = false;
let timer: number | undefined;
let cycle = 0;
const poll = () => {
if (stopped || cycle >= CHECKOUT_STATUS_AUTO_POLL_LIMIT) return;
cycle += 1;
if (revalidatorStateRef.current === "idle") revalidateRef.current();
if (cycle < CHECKOUT_STATUS_AUTO_POLL_LIMIT) {
timer = window.setTimeout(poll, checkoutStatusPollDelay(cycle));
}
};
}, [showSuccess]);
timer = window.setTimeout(poll, checkoutStatusPollDelay(cycle));
return () => {
stopped = true;
if (timer !== undefined) window.clearTimeout(timer);
};
}, [data.checkoutState]);
// 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 (data.checkoutState !== "cancelled" && data.checkoutState !== "failed" && data.checkoutState !== "expired") return;
clearPersistedCheckoutRequest(billingHref);
}, [billingHref, data.checkoutState]);
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)}
>
&larr; {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 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 recurringGrossTotalCents = data.checkoutReceipt?.recurringGrossTotalCents;
const paidAmountCents = data.checkoutReceipt?.amountCents;
const displayGrossTotalCents =
recurringGrossTotalCents !== null && recurringGrossTotalCents !== undefined
? recurringGrossTotalCents
: paidAmountCents !== null && paidAmountCents !== undefined && paidAmountCents > 0
? paidAmountCents
: null;
const formattedPrice =
priceAmount > 0
? formatters.currency(priceAmount, priceCurrency.toUpperCase(), {
minimumFractionDigits: priceAmount % 1 === 0 ? 0 : 2,
displayGrossTotalCents !== null
? formatters.currency(displayGrossTotalCents / 100, data.checkoutReceipt?.currency ?? priceCurrency.toUpperCase(), {
minimumFractionDigits: 2,
})
: null;
const intervalKey = intervalTranslationKey(period);
const intervalKey = intervalTranslationKey(period, data.checkoutReceipt?.billingCadence);
const interval = intervalKey ? t(intervalKey) : "";
const nextDate = nextBillingDate(period);
const progressPct = Math.max(0, Math.min(100, (secondsLeft / AUTO_REDIRECT_SECONDS) * 100));
const activationKind =
data.checkoutReceipt?.subscriptionStatus === "trial" && data.checkoutReceipt.trialEndsAt
? "trial"
: (data.checkoutReceipt?.amountCents ?? 0) > 0
? "paid"
: "confirmed";
const nextBillingAt = activationKind === "trial" ? data.checkoutReceipt?.trialEndsAt : data.checkoutReceipt?.currentPeriodEnd;
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>
<CheckoutSuccessPage
state={data.error ? "error" : data.checkoutState === "paid" ? "success" : data.checkoutState}
activationKind={activationKind}
homeHref={subscribeTenantHomePath(tenantSlug)}
workspaceName={data.currentTenant.name}
planTitle={productTitle}
formattedPrice={formattedPrice}
interval={interval}
nextInvoice={nextBillingAt ? formatters.date(new Date(nextBillingAt), { dateStyle: "long" }) : null}
emailMarketingFollowUpTitle={data.emailMarketingFollowUp ? t(data.emailMarketingFollowUp.titleKey) : null}
errorMessage={data.error}
actions={{
onStartSetup: () => navigate(subscribeTenantWelcomePath(tenantSlug)),
onOpenBilling: () => navigate(subscribeTenantSubscriptionSettingsPath(tenantSlug)),
onRetry: () => revalidator.revalidate(),
onRestartCheckout: () => navigate(subscribeTenantSubscriptionSettingsPath(tenantSlug)),
onOpenEmailMarketingFollowUp: data.emailMarketingFollowUp
? () => navigate(subscribeTenantSubscriptionSettingsPath(tenantSlug, data.emailMarketingFollowUp?.code))
: undefined,
}}
/>
);
}