302 lines
13 KiB
TypeScript
302 lines
13 KiB
TypeScript
import { useEffect, useRef } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
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";
|
|
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 "@hivegrid/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";
|
|
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";
|
|
|
|
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";
|
|
if (period === SubscriptionBillingPeriod.SEMI_ANNUAL) return "settings.subscription.checkout.success.intervals.halfYear";
|
|
return null;
|
|
}
|
|
|
|
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;
|
|
};
|
|
|
|
export function subscribeTenantHomePath(tenantSlug: string) {
|
|
return appPath({ tenantSlug, 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 user = await time(
|
|
runWithRlsContext({ userId: userInfo.userId }, () => getUser(userInfo.userId)),
|
|
"getUser"
|
|
);
|
|
if (!user) {
|
|
throw redirect(`/login`);
|
|
}
|
|
|
|
return runWithRlsContext({ tenantId, userId: user.id }, async () => {
|
|
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,
|
|
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() {
|
|
const { t } = useTranslation();
|
|
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 billingHref = subscribeTenantSubscriptionSettingsPath(tenantSlug);
|
|
|
|
useEffect(() => {
|
|
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));
|
|
}
|
|
};
|
|
timer = window.setTimeout(poll, checkoutStatusPollDelay(cycle));
|
|
return () => {
|
|
stopped = true;
|
|
if (timer !== undefined) window.clearTimeout(timer);
|
|
};
|
|
}, [data.checkoutState]);
|
|
|
|
useEffect(() => {
|
|
if (data.checkoutState !== "cancelled" && data.checkoutState !== "failed" && data.checkoutState !== "expired") return;
|
|
clearPersistedCheckoutRequest(billingHref);
|
|
}, [billingHref, data.checkoutState]);
|
|
|
|
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 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 =
|
|
displayGrossTotalCents !== null
|
|
? formatters.currency(displayGrossTotalCents / 100, data.checkoutReceipt?.currency ?? priceCurrency.toUpperCase(), {
|
|
minimumFractionDigits: 2,
|
|
})
|
|
: null;
|
|
const intervalKey = intervalTranslationKey(period, data.checkoutReceipt?.billingCadence);
|
|
const interval = intervalKey ? t(intervalKey) : "";
|
|
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 (
|
|
<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,
|
|
}}
|
|
/>
|
|
);
|
|
}
|