Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/billing/SelfServiceSubscriptionPage.tsx
T

2482 lines
122 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import {
FeatherArrowLeft,
FeatherArrowRight,
FeatherBriefcase,
FeatherCheck,
FeatherClock,
FeatherCreditCard,
FeatherExternalLink,
FeatherHardDrive,
FeatherHardHat,
FeatherGlobe,
FeatherLock,
FeatherMail,
FeatherPackage,
FeatherSparkles,
FeatherUsers,
FeatherWallet,
} from "@subframe/core";
import type { SelfServiceCheckoutPaymentMethodsVM, SelfServiceSubscriptionPageVM, SelfServiceSubscriptionPricePreviewVM } from "@hivegrid/view-models";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageIntro, PageShell } from "../shared/PageShell";
import { useLocaleFormatters } from "~/locale/format";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Checkbox } from "~/ui/components/Checkbox";
import { Dialog } from "~/ui/components/Dialog";
import { EmptyState } from "~/ui/components/EmptyState";
import { Loader } from "~/ui/components/Loader";
import { Progress } from "~/ui/components/Progress";
import { RadioCardGroup } from "~/ui/components/RadioCardGroup";
import { Logo } from "~/ui/components/Logo";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { StepperHorizontal } from "~/ui/components/StepperHorizontal";
import { Slider } from "~/ui/components/Slider";
import { TextInput } from "~/ui/components/TextInput";
import {
browserCheckoutRequestOptions,
stableCheckoutRequestKey,
type CheckoutRequest,
type SelfServiceSubscriptionSelection,
} from "./checkout-request";
export type { SelfServiceSubscriptionSelection } from "./checkout-request";
export type SelfServiceSubscriptionPlanAdvice = {
readonly plans: readonly {
readonly planId: string;
readonly priceId: string;
readonly amountCents: number;
readonly currency: string;
readonly billingPeriod: number;
readonly recommended: boolean;
}[];
readonly selectedPriceId: string;
readonly recommendedPriceId: string;
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
};
export type SelfServiceSubscriptionActions = {
readonly onPlanAdvice: (seatQuantities: {
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
}) => Promise<SelfServiceSubscriptionPlanAdvice>;
readonly onPreview: (
selection: SelfServiceSubscriptionSelection
) => Promise<{ preview: SelfServiceSubscriptionPricePreviewVM; paymentMethods: SelfServiceCheckoutPaymentMethodsVM }>;
readonly onCheckout: (selection: SelfServiceSubscriptionSelection, paymentMethod: string | null, checkoutRequestKey: string) => void | Promise<void>;
readonly onCancel: (productId: string) => void | Promise<void>;
readonly onEmailMarketingPreview: (addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number]) => Promise<{
addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number];
paymentMethods: SelfServiceCheckoutPaymentMethodsVM;
}>;
readonly onEmailMarketingCheckout: (
addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number],
paymentMethod: string | null
) => void | Promise<void>;
readonly onOpenBilling: () => void;
readonly onOpenCustomerPortal?: () => void;
readonly onRetry: () => void;
};
type ReadySelfServiceData = SelfServiceSubscriptionPageVM;
type CatalogPlan = ReadySelfServiceData["catalog"]["plans"][number];
type CatalogPrice = CatalogPlan["prices"][number];
type ManagementSection = "overview" | "plan" | "addons";
const PERIOD_SEGMENTS: Readonly<Record<number, string>> = {
0: "once",
1: "daily",
2: "weekly",
3: "monthly",
4: "annualCommitment",
5: "quarterly",
6: "semiAnnual",
};
function catalogText(t: TFunction, value: string): string {
return value.startsWith("settings.subscription.checkout.plans.packages.") || value.startsWith("billing:selfServiceSubscription.") ? t(value) : value;
}
function periodLabelKey(period: number): string {
return `billing:selfServiceSubscription.period.${PERIOD_SEGMENTS[period] ?? "unknown"}`;
}
function usesCardOnly(methods: SelfServiceCheckoutPaymentMethodsVM | null): boolean {
return methods?.status === "ready" && methods.methods.length > 0 && methods.methods.every((method) => method.id === "creditcard");
}
function formatBytes(bytes: number, number: (value: number, options?: Intl.NumberFormatOptions) => string): string {
const units = ["B", "KB", "MB", "GB", "TB"] as const;
let value = bytes;
let unitIndex = 0;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex += 1;
}
return `${number(value, { maximumFractionDigits: unitIndex === 0 ? 0 : 1 })} ${units[unitIndex]}`;
}
export function initialSelfServiceSubscriptionSelection(data: ReadySelfServiceData): SelfServiceSubscriptionSelection | null {
const currentPlanCode = data.currentSelection?.planCode ?? (data.overview.status === "ready" ? data.overview.data.planCode : null);
const preferredPlan =
!data.currentSelection && !currentPlanCode ? data.catalog.plans.find((candidate) => candidate.id === data.preferredSelection?.planId) : undefined;
const plan =
data.catalog.plans.find((candidate) => candidate.id === data.currentSelection?.planId || candidate.code === currentPlanCode) ??
preferredPlan ??
data.catalog.plans[0];
const preferredPriceId = plan?.id === preferredPlan?.id ? data.preferredSelection?.priceId : undefined;
const price =
plan?.prices.find((candidate) => candidate.id === data.currentSelection?.priceId) ??
plan?.prices.find((candidate) => candidate.id === preferredPriceId) ??
plan?.prices[0];
if (!plan || !price) return null;
return {
productId: plan.id,
priceId: price.id,
billingPeriod: price.billingPeriod,
currency: price.currency,
officeSeatQuantity: Math.max(
data.minimumSeatQuantities.office,
data.currentSelection?.officeSeatQuantity ?? data.preferredSelection?.officeSeatQuantity ?? data.minimumSeatQuantities.office
),
fieldSeatQuantity: Math.max(
data.minimumSeatQuantities.field,
data.currentSelection?.fieldSeatQuantity ?? data.preferredSelection?.fieldSeatQuantity ?? data.minimumSeatQuantities.field
),
storageAddOnCodes: data.currentSelection?.storageAddOnCodes ?? [],
};
}
export function applyRecommendedSubscriptionPlan(
selection: SelfServiceSubscriptionSelection,
advice: SelfServiceSubscriptionPlanAdvice,
preserveManualSelection: boolean
): SelfServiceSubscriptionSelection {
if (preserveManualSelection) return selection;
const recommendedPlan = advice.plans.find((plan) => plan.priceId === advice.recommendedPriceId && plan.recommended);
if (!recommendedPlan) return selection;
return {
...selection,
productId: recommendedPlan.planId,
priceId: recommendedPlan.priceId,
billingPeriod: recommendedPlan.billingPeriod,
currency: recommendedPlan.currency,
};
}
export function initialActivationSubscriptionSelection(
data: SelfServiceSubscriptionPageVM,
advice: SelfServiceSubscriptionPlanAdvice | null
): SelfServiceSubscriptionSelection | null {
const selection = initialSelfServiceSubscriptionSelection(data);
return selection && advice && !data.currentSelection && !data.preferredSelection ? applyRecommendedSubscriptionPlan(selection, advice, false) : selection;
}
function isSelectionAvailable(data: ReadySelfServiceData, selection: SelfServiceSubscriptionSelection): boolean {
const plan = data.catalog.plans.find((candidate) => candidate.id === selection.productId);
return Boolean(plan?.prices.some((price) => price.id === selection.priceId));
}
function currentSeatCount(overview: ReadySelfServiceData["overview"]): number | null {
if (overview.status !== "ready") return null;
if (overview.data.seatUsage.status === "ready") {
return overview.data.seatUsage.data.categories.reduce((total, category) => total + category.used, 0);
}
return overview.data.products.find((product) => product.state === "active")?.quantity ?? null;
}
function sameCodes(left: readonly string[], right: readonly string[]): boolean {
if (left.length !== right.length) return false;
const rightCodes = new Set(right);
return left.every((code) => rightCodes.has(code));
}
/**
* VA-P24a interim screen (AD-28). The server owns catalog and price-preview
* calculations; this component only keeps the user's selection and renders the
* preview returned by actions.onPreview.
*/
export function SelfServiceSubscriptionPage({
vm,
actions,
embedded = false,
activationMode = false,
initialPlanAdvice = null,
initialEmailMarketingAddOnCode = null,
}: {
vm: SelfServiceSubscriptionPageVM;
actions: SelfServiceSubscriptionActions;
/** Inside the Abrechnung hub (AK-SET-01) the hub owns the header — see PageIntro. */
embedded?: boolean;
/** First checkout after registration: no app chrome, usage or optional product upsells before the base plan is active. */
activationMode?: boolean;
/** Initial server-calculated recommendation for the activation team's persisted seat quantities. */
initialPlanAdvice?: SelfServiceSubscriptionPlanAdvice | null;
/** Validated follow-up selection from the base-checkout success page. */
initialEmailMarketingAddOnCode?: string | null;
}): React.JSX.Element {
if (activationMode) return <ActivationSubscriptionWizard data={vm} actions={actions} initialPlanAdvice={initialPlanAdvice} />;
return (
<ReadySelfServiceSubscriptionPage
data={vm}
actions={actions}
embedded={embedded}
activationMode={activationMode}
initialEmailMarketingAddOnCode={initialEmailMarketingAddOnCode}
/>
);
}
type ActivationStep = "team" | "plan" | "storage" | "email" | "payment";
const ACTIVATION_STEPS: readonly ActivationStep[] = ["team", "plan", "storage", "email", "payment"];
function activationStepVariant(current: ActivationStep, candidate: ActivationStep): "active" | "completed" | "default" {
const currentIndex = ACTIVATION_STEPS.indexOf(current);
const candidateIndex = ACTIVATION_STEPS.indexOf(candidate);
if (candidateIndex === currentIndex) return "active";
return candidateIndex < currentIndex ? "completed" : "default";
}
function ActivationSubscriptionWizard({
data,
actions,
initialPlanAdvice,
}: {
data: ReadySelfServiceData;
actions: SelfServiceSubscriptionActions;
initialPlanAdvice: SelfServiceSubscriptionPlanAdvice | null;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [step, setStep] = useState<ActivationStep>("team");
const initialSelection = useMemo(() => initialActivationSubscriptionSelection(data, initialPlanAdvice), [data, initialPlanAdvice]);
const [selection, setSelection] = useState<SelfServiceSubscriptionSelection | null>(initialSelection);
const initialManualPlanSelection = Boolean(
data.currentSelection ||
(data.preferredSelection && initialSelection && initialPlanAdvice && initialSelection.priceId !== initialPlanAdvice.recommendedPriceId)
);
const [planAdvice, setPlanAdvice] = useState<SelfServiceSubscriptionPlanAdvice | null>(initialPlanAdvice);
const [planAdviceLoading, setPlanAdviceLoading] = useState(false);
const [planAdviceError, setPlanAdviceError] = useState(false);
const [planAdviceAttempt, setPlanAdviceAttempt] = useState(0);
const planManuallyOverriddenRef = useRef(initialManualPlanSelection);
const onPlanAdviceRef = useRef(actions.onPlanAdvice);
const onPreviewRef = useRef(actions.onPreview);
const checkoutRequestRef = useRef<CheckoutRequest | null>(null);
const [preview, setPreview] = useState<SelfServiceSubscriptionPricePreviewVM | null>(null);
const [paymentMethods, setPaymentMethods] = useState<SelfServiceCheckoutPaymentMethodsVM | null>(null);
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string | null>(null);
const [previewing, setPreviewing] = useState(false);
const [previewError, setPreviewError] = useState(false);
const [checkingOut, setCheckingOut] = useState(false);
const [checkoutError, setCheckoutError] = useState(false);
const [emailChoice, setEmailChoice] = useState<"yes" | "no" | null>(null);
const [emailAddOnCode, setEmailAddOnCode] = useState<string | null>(null);
const selectedPlan = data.catalog.plans.find((candidate) => candidate.id === selection?.productId) ?? null;
const selectedEmailAddOn = data.emailMarketingAddOns.find((candidate) => candidate.code === emailAddOnCode) ?? null;
const recommendedPlanId = planAdvice?.plans.find((candidate) => candidate.priceId === planAdvice.recommendedPriceId)?.planId ?? null;
const adviceMatchesSelection = Boolean(
selection && planAdvice && planAdvice.officeSeatQuantity === selection.officeSeatQuantity && planAdvice.fieldSeatQuantity === selection.fieldSeatQuantity
);
useEffect(() => {
onPlanAdviceRef.current = actions.onPlanAdvice;
}, [actions.onPlanAdvice]);
useEffect(() => {
onPreviewRef.current = actions.onPreview;
}, [actions.onPreview]);
function replaceSelection(next: SelfServiceSubscriptionSelection): void {
setSelection(next);
setPreview(null);
setPaymentMethods(null);
setSelectedPaymentMethod(null);
setPreviewError(false);
setCheckoutError(false);
}
function setSeat(role: "office" | "field", value: number): void {
if (!selection || !Number.isFinite(value)) return;
replaceSelection({
...selection,
[`${role}SeatQuantity`]: Math.max(data.minimumSeatQuantities[role], Math.min(10_000, Math.trunc(value))),
});
}
function choosePlan(plan: CatalogPlan): void {
if (!selection) return;
const advisedPlan = planAdvice?.plans.find((candidate) => candidate.planId === plan.id);
const price =
plan.prices.find((candidate) => candidate.id === advisedPlan?.priceId) ??
plan.prices.find((candidate) => candidate.billingPeriod === selection.billingPeriod) ??
plan.prices[0];
if (!price) return;
const preserveManualSelection = plan.id !== recommendedPlanId;
planManuallyOverriddenRef.current = preserveManualSelection;
replaceSelection({ ...selection, productId: plan.id, priceId: price.id, billingPeriod: price.billingPeriod, currency: price.currency });
}
function choosePrice(price: CatalogPrice): void {
if (!selection) return;
const preserveManualSelection = price.id !== planAdvice?.recommendedPriceId;
planManuallyOverriddenRef.current = preserveManualSelection;
replaceSelection({ ...selection, priceId: price.id, billingPeriod: price.billingPeriod, currency: price.currency });
}
useEffect(() => {
if (!selection || adviceMatchesSelection) return;
let cancelled = false;
setPlanAdviceLoading(true);
setPlanAdviceError(false);
const timeout = window.setTimeout(async () => {
try {
const advice = await onPlanAdviceRef.current({
officeSeatQuantity: selection.officeSeatQuantity,
fieldSeatQuantity: selection.fieldSeatQuantity,
});
if (cancelled) return;
setPlanAdvice(advice);
setSelection((current) => (current ? applyRecommendedSubscriptionPlan(current, advice, planManuallyOverriddenRef.current) : current));
} catch {
if (!cancelled) setPlanAdviceError(true);
} finally {
if (!cancelled) setPlanAdviceLoading(false);
}
}, 250);
return () => {
cancelled = true;
window.clearTimeout(timeout);
};
}, [adviceMatchesSelection, planAdviceAttempt, selection?.fieldSeatQuantity, selection?.officeSeatQuantity]);
useEffect(() => {
if (!selection || step === "team" || step === "email") return;
let cancelled = false;
const timeout = window.setTimeout(async () => {
setPreviewing(true);
setPreviewError(false);
try {
const result = await onPreviewRef.current(selection);
if (cancelled) return;
setPreview(result.preview);
setPaymentMethods(result.paymentMethods);
setSelectedPaymentMethod((current) =>
result.paymentMethods.status === "ready" && result.paymentMethods.methods.some((method) => method.id === current)
? current
: result.paymentMethods.status === "ready"
? (result.paymentMethods.methods[0]?.id ?? null)
: null
);
} catch {
if (!cancelled) setPreviewError(true);
} finally {
if (!cancelled) setPreviewing(false);
}
}, 300);
return () => {
cancelled = true;
window.clearTimeout(timeout);
};
}, [
selection?.billingPeriod,
selection?.currency,
selection?.fieldSeatQuantity,
selection?.officeSeatQuantity,
selection?.priceId,
selection?.productId,
selection?.storageAddOnCodes,
step,
]);
async function checkout(): Promise<void> {
if (!preview || checkingOut) return;
setCheckingOut(true);
setCheckoutError(false);
try {
const checkoutSelection = {
productId: preview.selectedPlan.id,
priceId: preview.selectedPrice.id,
billingPeriod: preview.selectedPrice.billingPeriod,
currency: preview.selectedPrice.currency,
officeSeatQuantity: preview.selectedOfficeSeatQuantity,
fieldSeatQuantity: preview.selectedFieldSeatQuantity,
storageAddOnCodes: preview.selectedStorageAddOnCodes,
emailMarketingAddOnCode: selectedEmailAddOn?.code ?? null,
} satisfies SelfServiceSubscriptionSelection;
checkoutRequestRef.current = stableCheckoutRequestKey(
checkoutRequestRef.current,
checkoutSelection,
selectedPaymentMethod,
browserCheckoutRequestOptions(data.billingHref)
);
await actions.onCheckout(checkoutSelection, selectedPaymentMethod, checkoutRequestRef.current.key);
} catch {
setCheckoutError(true);
} finally {
setCheckingOut(false);
}
}
function goBack(): void {
const index = ACTIVATION_STEPS.indexOf(step);
if (index > 0) setStep(ACTIVATION_STEPS[index - 1]!);
}
function goNext(): void {
const index = ACTIVATION_STEPS.indexOf(step);
if (index < ACTIVATION_STEPS.length - 1) setStep(ACTIVATION_STEPS[index + 1]!);
}
const canContinue =
selection !== null &&
(step !== "team" || (adviceMatchesSelection && !planAdviceLoading && !planAdviceError)) &&
(step !== "email" || emailChoice !== null) &&
(step !== "email" || emailChoice !== "yes" || data.emailMarketingAddOns.length === 0 || emailAddOnCode !== null) &&
(step === "team" || step === "email" || (preview !== null && !previewing));
if (!selection || data.catalog.plans.length === 0) {
return (
<PageShell uiId="ui.billing.activation.page" className="bg-surface-neutral-secondary min-h-screen">
<PageBody className="mx-auto max-w-[720px] py-12">
<EmptyState
outlined
variant="error"
title={t("billing:selfServiceSubscription.catalog.empty.title")}
body={t("billing:selfServiceSubscription.catalog.empty.description")}
action={
<Button variant="tertiary" onClick={actions.onRetry}>
{t("billing:states.retry")}
</Button>
}
/>
</PageBody>
</PageShell>
);
}
return (
<PageShell uiId="ui.billing.activation.page" className="bg-surface-neutral-secondary min-h-screen">
<div className="border-border-default bg-surface-neutral-primary mobile:px-4 mobile:py-6 flex w-full flex-col items-center gap-5 border-b px-6 py-8">
<Logo size="32" />
<div className="w-full max-w-[920px] overflow-x-auto pb-1">
<StepperHorizontal data-ui-id="ui.billing.activation.steps">
{ACTIVATION_STEPS.map((candidate, index) => (
<StepperHorizontal.Step
key={candidate}
firstStep={index === 0}
lastStep={index === ACTIVATION_STEPS.length - 1}
variant={activationStepVariant(step, candidate)}
stepNumber={String(index + 1)}
label={t(`billing:selfServiceSubscription.activation.wizard.steps.${candidate}`)}
/>
))}
</StepperHorizontal>
</div>
<div className="flex max-w-[720px] flex-col items-center gap-2 text-center">
<h1 className="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">
{t(`billing:selfServiceSubscription.activation.wizard.${step}.title`)}
</h1>
<p className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t(`billing:selfServiceSubscription.activation.wizard.${step}.description`)}
</p>
</div>
</div>
<PageBody className="mx-auto max-w-[1040px] items-start">
<Alert
notDismissible
variant="warning"
title={t("billing:selfServiceSubscription.activation.locked.title")}
description={t("billing:selfServiceSubscription.activation.locked.description")}
data-ui-id="ui.billing.activation.locked"
/>
{step === "team" && selection ? (
<div className="flex w-full flex-col gap-5" data-ui-id="ui.billing.activation.team">
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-5">
<ActivationSeatCard
icon={<FeatherBriefcase />}
label={t("billing:selfServiceSubscription.seats.officeLabel")}
description={t("billing:selfServiceSubscription.activation.wizard.team.officeDescription")}
value={selection.officeSeatQuantity}
minimum={data.minimumSeatQuantities.office}
sliderMax={50}
onChange={(value) => setSeat("office", value)}
/>
<ActivationSeatCard
icon={<FeatherHardHat />}
label={t("billing:selfServiceSubscription.seats.fieldLabel")}
description={t("billing:selfServiceSubscription.activation.wizard.team.fieldDescription")}
value={selection.fieldSeatQuantity}
minimum={data.minimumSeatQuantities.field}
sliderMax={100}
onChange={(value) => setSeat("field", value)}
/>
</div>
{planAdviceLoading ? <LoadingMessage label={t("account.register.recommendationLoading")} /> : null}
{planAdviceError ? (
<div className="flex flex-col items-start gap-3">
<Alert
notDismissible
variant="error"
title={t("account.register.recommendationErrorTitle")}
description={t("account.register.recommendationErrorBody")}
/>
<Button variant="tertiary" onClick={() => setPlanAdviceAttempt((attempt) => attempt + 1)}>
{t("billing:states.retry")}
</Button>
</div>
) : null}
</div>
) : null}
{step === "plan" && selection ? (
<div className="flex w-full flex-col gap-5" data-ui-id="ui.billing.activation.plan">
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.catalog.title")}
className="mobile:grid-cols-1 grid w-full grid-cols-3"
value={selection.productId}
onValueChange={(productId) => {
const plan = data.catalog.plans.find((candidate) => candidate.id === productId);
if (plan) choosePlan(plan);
}}
>
{data.catalog.plans.map((plan) => {
const advisedPlan = planAdvice?.plans.find((candidate) => candidate.planId === plan.id);
const price =
plan.prices.find((candidate) => candidate.id === advisedPlan?.priceId) ??
plan.prices.find((candidate) => candidate.billingPeriod === selection.billingPeriod) ??
plan.prices[0];
const recommended = plan.id === recommendedPlanId;
return (
<RadioCardGroup.RadioCard key={plan.id} value={plan.id} disabled={!price} className="h-full">
<div className="flex w-full flex-wrap items-center gap-2">
<span className="text-heading- font-heading- text-text-neutral-primary">{catalogText(t, plan.titleKey)}</span>
{recommended ? (
<BadgeFeedback farbe="subtle-brand-primary" size="small">
{t("billing:selfServiceSubscription.activation.wizard.plan.recommended")}
</BadgeFeedback>
) : null}
</div>
{price ? (
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
{formatters.currencyFromCents(advisedPlan?.amountCents ?? price.unitAmountCents, advisedPlan?.currency ?? price.currency)}{" "}
{t("billing:selfServiceSubscription.price.netSuffix")} / {t(periodLabelKey(advisedPlan?.billingPeriod ?? price.billingPeriod))}
</span>
) : null}
{plan.packageTerms ? (
<div className="border-border-default flex w-full flex-col gap-2 border-0 border-t border-solid pt-3">
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.seats", {
office: plan.packageTerms.officeSeatsIncluded,
field: plan.packageTerms.fieldSeatsIncluded,
})}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.storage", { storage: plan.packageTerms.storageIncludedGb })}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.storageGrowth", {
storage: plan.packageTerms.storagePerAdditionalSeatGb,
})}
</span>
</div>
) : null}
</RadioCardGroup.RadioCard>
);
})}
</RadioCardGroup>
{selectedPlan && selectedPlan.prices.length > 1 ? (
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.price.title")}
className="mobile:grid-cols-1 grid w-full grid-cols-2"
value={selection.priceId}
onValueChange={(priceId) => {
const price = selectedPlan.prices.find((candidate) => candidate.id === priceId);
if (price) choosePrice(price);
}}
>
{selectedPlan.prices.map((price) => (
<RadioCardGroup.RadioCard key={price.id} value={price.id}>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{formatters.currencyFromCents(price.unitAmountCents, price.currency)} {t("billing:selfServiceSubscription.price.netSuffix")} /{" "}
{t(periodLabelKey(price.billingPeriod))}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{price.billingPeriod === 4
? t("billing:selfServiceSubscription.price.annualCommitmentHint")
: price.trialDays > 0
? t("billing:selfServiceSubscription.price.trialDays", { count: price.trialDays })
: t("billing:selfServiceSubscription.price.noTrial")}
</span>
</RadioCardGroup.RadioCard>
))}
</RadioCardGroup>
) : null}
<ActivationLivePrice preview={preview} loading={previewing} error={previewError} />
</div>
) : null}
{step === "storage" && selection ? (
<div className="flex w-full flex-col gap-5" data-ui-id="ui.billing.activation.storage">
{selectedPlan?.packageTerms ? (
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.activation.wizard.storage.includedTitle", {
storage: preview?.totalStorageGb ?? selectedPlan.packageTerms.storageIncludedGb,
})}
description={
preview
? t("billing:selfServiceSubscription.activation.wizard.storage.poolDescription", {
included: preview.includedStorageGb,
additional: preview.additionalSeatStorageGb,
addOn: preview.addOnStorageGb,
perUser: selectedPlan.packageTerms.storagePerAdditionalSeatGb,
})
: t("billing:selfServiceSubscription.activation.wizard.storage.includedDescription", {
perUser: selectedPlan.packageTerms.storagePerAdditionalSeatGb,
})
}
/>
) : null}
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.storage.title")}
className="mobile:grid-cols-1 grid w-full grid-cols-2"
value={selection.storageAddOnCodes[0] ?? "none"}
onValueChange={(value) => {
replaceSelection({ ...selection, storageAddOnCodes: value === "none" ? [] : [value] });
}}
>
<RadioCardGroup.RadioCard value="none">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.activation.wizard.storage.noExtra")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.activation.wizard.storage.noExtraDescription")}
</span>
</RadioCardGroup.RadioCard>
{data.storageAddOns.map((addOn) => (
<RadioCardGroup.RadioCard key={addOn.code} value={addOn.code}>
<div className="flex w-full items-center gap-3">
<FeatherHardDrive className="text-heading-0 font-heading-0 text-icon-neutral-secondary" />
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{addOn.title}</span>
</div>
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
+{formatters.currencyFromCents(addOn.amountCents, addOn.currency)} {t("billing:selfServiceSubscription.price.netSuffix")} /{" "}
{t(periodLabelKey(3))}
</span>
</RadioCardGroup.RadioCard>
))}
</RadioCardGroup>
<ActivationLivePrice preview={preview} loading={previewing} error={previewError} />
</div>
) : null}
{step === "email" ? (
<div className="flex w-full flex-col gap-5" data-ui-id="ui.billing.activation.emailMarketing">
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.activation.wizard.email.question")}
className="mobile:grid-cols-1 grid w-full grid-cols-2"
value={emailChoice ?? ""}
onValueChange={(value) => {
const choice = value === "yes" ? "yes" : "no";
setEmailChoice(choice);
if (choice === "no") setEmailAddOnCode(null);
}}
>
<RadioCardGroup.RadioCard value="no">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.activation.wizard.email.no")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.activation.wizard.email.noDescription")}
</span>
</RadioCardGroup.RadioCard>
<RadioCardGroup.RadioCard value="yes">
<div className="flex w-full items-center gap-3">
<FeatherMail className="text-heading-0 font-heading-0 text-icon-neutral-secondary" />
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.activation.wizard.email.yes")}
</span>
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.activation.wizard.email.yesDescription")}
</span>
</RadioCardGroup.RadioCard>
</RadioCardGroup>
{emailChoice === "yes" && data.emailMarketingAddOns.length > 0 ? (
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.emailMarketing.title")}
className="mobile:grid-cols-1 grid w-full grid-cols-3"
value={emailAddOnCode ?? ""}
onValueChange={setEmailAddOnCode}
>
{data.emailMarketingAddOns.map((addOn) => (
<RadioCardGroup.RadioCard key={addOn.code} value={addOn.code}>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{catalogText(t, addOn.title)}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.emailMarketing.allowance", {
count: addOn.monthlyEmailLimit,
formattedCount: formatters.number(addOn.monthlyEmailLimit),
})}
</span>
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
{formatters.currencyFromCents(addOn.amountCents, addOn.currency)} {t("billing:selfServiceSubscription.price.netSuffix")} /{" "}
{t(periodLabelKey(3))}
</span>
</RadioCardGroup.RadioCard>
))}
</RadioCardGroup>
) : null}
{emailChoice === "yes" ? (
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.activation.wizard.email.separateTitle")}
description={t("billing:selfServiceSubscription.activation.wizard.email.separateDescription")}
/>
) : null}
</div>
) : null}
{step === "payment" ? (
<div className="mobile:grid-cols-1 grid w-full grid-cols-[minmax(0,1.1fr)_minmax(320px,0.9fr)] gap-5" data-ui-id="ui.billing.activation.payment">
<Card>
<div className="flex w-full items-start gap-3">
<IconWithBackground variant="information" size="medium" icon={<FeatherWallet />} />
<div className="flex min-w-0 flex-col gap-1">
<span className="text-body-large font-body-large text-text-neutral-primary">{t("billing:selfServiceSubscription.paymentMethods.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(
usesCardOnly(paymentMethods)
? "billing:selfServiceSubscription.paymentMethods.cardDescription"
: "billing:selfServiceSubscription.paymentMethods.description"
)}
</span>
</div>
</div>
{paymentMethods?.status === "ready" ? (
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.paymentMethods.title")}
className="flex w-full flex-col"
value={selectedPaymentMethod ?? ""}
onValueChange={setSelectedPaymentMethod}
disabled={checkingOut}
>
{paymentMethods.methods.map((method) => (
<RadioCardGroup.RadioCard key={method.id} value={method.id} disabled={checkingOut}>
<div className="flex w-full items-center gap-3">
{method.id === "creditcard" ? (
<FeatherCreditCard className="text-heading-0 font-heading-0 text-icon-neutral-secondary" />
) : (
<FeatherWallet className="text-heading-0 font-heading-0 text-icon-neutral-secondary" />
)}
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{method.label}</span>
</div>
</RadioCardGroup.RadioCard>
))}
</RadioCardGroup>
) : paymentMethods?.status === "required_card_unavailable" ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.paymentMethods.cardUnavailableTitle")}
description={t("billing:selfServiceSubscription.paymentMethods.cardUnavailableDescription")}
/>
) : paymentMethods?.status === "fallback" ? (
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.paymentMethods.fallbackTitle")}
description={t("billing:selfServiceSubscription.paymentMethods.fallbackDescription")}
/>
) : (
<LoadingMessage label={t("billing:selfServiceSubscription.activation.wizard.payment.loadingMethods")} />
)}
<Alert
notDismissible
variant="neutral"
title={t("billing:selfServiceSubscription.activation.wizard.payment.hostedTitle")}
description={t("billing:selfServiceSubscription.activation.wizard.payment.hostedDescription")}
/>
</Card>
<Card variant="neutral">
<div className="flex w-full items-center gap-3">
<IconWithBackground variant="neutral" size="medium" icon={<FeatherSparkles />} />
<span className="text-body-large font-body-large text-text-neutral-primary">
{t("billing:selfServiceSubscription.activation.wizard.payment.summaryTitle")}
</span>
</div>
{preview ? (
<ActivationPriceRows preview={preview} />
) : (
<LoadingMessage label={t("billing:selfServiceSubscription.activation.wizard.payment.loadingPrice")} />
)}
{preview ? (
<Alert
notDismissible
variant="information"
title={t(
preview.trialDays > 0
? "billing:selfServiceSubscription.activation.trial.title"
: "billing:selfServiceSubscription.activation.immediate.title",
{ count: preview.trialDays }
)}
description={t(
preview.trialDays > 0
? "billing:selfServiceSubscription.activation.trial.description"
: "billing:selfServiceSubscription.activation.immediate.description",
{ count: preview.trialDays }
)}
/>
) : null}
{selectedEmailAddOn ? (
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.activation.wizard.email.followUpTitle")}
description={t("billing:selfServiceSubscription.activation.wizard.email.followUpDescription", {
package: catalogText(t, selectedEmailAddOn.title),
})}
/>
) : null}
{checkoutError ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.checkout.error.title")}
description={t("billing:selfServiceSubscription.checkout.error.description")}
/>
) : null}
<Button
size="large"
className="w-full"
icon={<FeatherCreditCard />}
loading={checkingOut}
disabled={
!data.canManage ||
!preview ||
checkingOut ||
paymentMethods?.status === "required_card_unavailable" ||
(paymentMethods?.status === "ready" && selectedPaymentMethod === null)
}
onClick={() => void checkout()}
data-ui-id="ui.billing.activation.checkout"
>
{t("billing:selfServiceSubscription.checkout.action")}
</Button>
</Card>
</div>
) : null}
{previewError && step !== "plan" && step !== "storage" ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.preview.error.title")}
description={t("billing:selfServiceSubscription.preview.error.description")}
/>
) : null}
<div className="flex w-full items-center justify-between gap-3">
<Button variant="tertiary" icon={<FeatherArrowLeft />} disabled={step === "team" || checkingOut} onClick={goBack}>
{t("billing:selfServiceSubscription.activation.wizard.back")}
</Button>
{step !== "payment" ? (
<Button icon={<FeatherArrowRight />} disabled={!canContinue} onClick={goNext} data-ui-id="ui.billing.activation.next">
{t("billing:selfServiceSubscription.activation.wizard.next")}
</Button>
) : null}
</div>
</PageBody>
</PageShell>
);
}
function ActivationSeatCard({
icon,
label,
description,
value,
minimum,
sliderMax,
onChange,
}: {
icon: React.ReactNode;
label: string;
description: string;
value: number;
minimum: number;
sliderMax: number;
onChange: (value: number) => void;
}): React.JSX.Element {
return (
<Card className="h-full">
<div className="flex w-full items-start gap-3">
<IconWithBackground variant="information" size="medium" icon={icon} />
<div className="flex min-w-0 flex-col gap-1">
<span className="text-body-large font-body-large text-text-neutral-primary">{label}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{description}</span>
</div>
</div>
<Slider
min={minimum}
max={sliderMax}
step={1}
value={[Math.min(value, sliderMax)]}
valueText={value}
disabled={false}
onValueChange={(values) => onChange(values[0] ?? minimum)}
aria-label={label}
/>
<TextInput showLabel label={label} fillContainer type="number">
<TextInput.Input
type="number"
min={minimum}
max={10_000}
step={1}
value={value}
onChange={(event) => {
const nextValue = event.currentTarget.valueAsNumber;
if (Number.isFinite(nextValue)) {
onChange(Math.min(10_000, Math.max(minimum, nextValue)));
}
}}
/>
</TextInput>
</Card>
);
}
function ActivationPriceRows({ preview }: { preview: SelfServiceSubscriptionPricePreviewVM }): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<div className="flex w-full flex-col gap-3" aria-live="polite">
<PreviewRow label={t("billing:selfServiceSubscription.preview.plan")} value={catalogText(t, preview.selectedPlan.titleKey)} />
<PreviewRow
label={t("billing:selfServiceSubscription.preview.baseAmount")}
value={formatters.currencyFromCents(preview.baseAmountCents, preview.selectedPrice.currency)}
/>
{preview.officeSeatAmountCents > 0 ? (
<PreviewRow
label={t("billing:selfServiceSubscription.preview.officeSeatAmount")}
value={formatters.currencyFromCents(preview.officeSeatAmountCents, preview.selectedPrice.currency)}
/>
) : null}
{preview.fieldSeatAmountCents > 0 ? (
<PreviewRow
label={t("billing:selfServiceSubscription.preview.fieldSeatAmount")}
value={formatters.currencyFromCents(preview.fieldSeatAmountCents, preview.selectedPrice.currency)}
/>
) : null}
{preview.storageAmountCents > 0 ? (
<PreviewRow
label={t("billing:selfServiceSubscription.preview.storageAmount")}
value={formatters.currencyFromCents(preview.storageAmountCents, preview.selectedPrice.currency)}
/>
) : null}
<div className="bg-border-default h-px w-full" />
<PreviewRow
label={t("billing:selfServiceSubscription.preview.recurringNetTotal")}
value={formatters.currencyFromCents(preview.recurringNetTotalCents, preview.selectedPrice.currency)}
/>
<PreviewRow
label={t("billing:selfServiceSubscription.preview.vat", { rate: preview.vatRateBasisPoints / 100 })}
value={formatters.currencyFromCents(preview.vatAmountCents, preview.selectedPrice.currency)}
/>
<PreviewRow
strong
label={t("billing:selfServiceSubscription.preview.recurringGrossTotal")}
value={formatters.currencyFromCents(preview.recurringGrossTotalCents, preview.selectedPrice.currency)}
/>
</div>
);
}
function ActivationLivePrice({
preview,
loading,
error,
}: {
preview: SelfServiceSubscriptionPricePreviewVM | null;
loading: boolean;
error: boolean;
}): React.JSX.Element {
const { t } = useTranslation();
return (
<Card variant="neutral" data-ui-id="ui.billing.activation.livePrice">
<div className="flex w-full items-center justify-between gap-3">
<div className="flex flex-col gap-1">
<span className="text-body-large font-body-large text-text-neutral-primary">
{t("billing:selfServiceSubscription.activation.wizard.livePrice.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.activation.wizard.livePrice.description")}
</span>
</div>
{loading ? <LoadingMessage label={t("billing:selfServiceSubscription.activation.wizard.livePrice.loading")} /> : null}
</div>
{preview ? <ActivationPriceRows preview={preview} /> : null}
{error ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.preview.error.title")}
description={t("billing:selfServiceSubscription.preview.error.description")}
/>
) : null}
</Card>
);
}
function LoadingMessage({ label }: { label: string }): React.JSX.Element {
return (
<div className="flex items-center gap-2" role="status">
<Loader size="small" aria-hidden />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{label}</span>
</div>
);
}
function ReadySelfServiceSubscriptionPage({
data,
actions,
embedded,
activationMode,
initialEmailMarketingAddOnCode,
}: {
data: ReadySelfServiceData;
actions: SelfServiceSubscriptionActions;
embedded: boolean;
activationMode: boolean;
initialEmailMarketingAddOnCode: string | null;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [selection, setSelection] = useState<SelfServiceSubscriptionSelection | null>(() => initialSelfServiceSubscriptionSelection(data));
const [preview, setPreview] = useState<SelfServiceSubscriptionPricePreviewVM | null>(null);
const [paymentMethods, setPaymentMethods] = useState<SelfServiceCheckoutPaymentMethodsVM | null>(null);
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string | null>(null);
const [previewOpen, setPreviewOpen] = useState(false);
const [previewing, setPreviewing] = useState(false);
const [checkingOut, setCheckingOut] = useState(false);
const [previewError, setPreviewError] = useState(false);
const [checkoutError, setCheckoutError] = useState(false);
const [cancelProductId, setCancelProductId] = useState<string | null>(null);
const [cancellingProductId, setCancellingProductId] = useState<string | null>(null);
const [emailMarketingPreview, setEmailMarketingPreview] = useState<SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number] | null>(null);
const [emailMarketingPaymentMethods, setEmailMarketingPaymentMethods] = useState<SelfServiceCheckoutPaymentMethodsVM | null>(null);
const [selectedEmailMarketingPaymentMethod, setSelectedEmailMarketingPaymentMethod] = useState<string | null>(null);
const [emailMarketingPreviewingCode, setEmailMarketingPreviewingCode] = useState<string | null>(null);
const [emailMarketingCheckingOut, setEmailMarketingCheckingOut] = useState(false);
const [emailMarketingError, setEmailMarketingError] = useState(false);
const [managementSection, setManagementSection] = useState<ManagementSection>("overview");
const [pendingEmailMarketingAddOnCode, setPendingEmailMarketingAddOnCode] = useState(initialEmailMarketingAddOnCode);
const checkoutRequestRef = useRef<CheckoutRequest | null>(null);
useEffect(() => {
setSelection((current) => {
if (!current || !isSelectionAvailable(data, current)) return initialSelfServiceSubscriptionSelection(data);
if (current.officeSeatQuantity >= data.minimumSeatQuantities.office && current.fieldSeatQuantity >= data.minimumSeatQuantities.field) {
return current;
}
return {
...current,
officeSeatQuantity: Math.max(current.officeSeatQuantity, data.minimumSeatQuantities.office),
fieldSeatQuantity: Math.max(current.fieldSeatQuantity, data.minimumSeatQuantities.field),
};
});
}, [data]);
const selectedPlan = useMemo(() => data.catalog.plans.find((plan) => plan.id === selection?.productId) ?? null, [data.catalog.plans, selection?.productId]);
const selectedPrice = useMemo(() => selectedPlan?.prices.find((price) => price.id === selection?.priceId) ?? null, [selectedPlan, selection?.priceId]);
const seats = data.currentSelection?.seatQuantity ?? currentSeatCount(data.overview);
const cancelProduct = data.overview.status === "ready" ? (data.overview.data.products.find((product) => product.id === cancelProductId) ?? null) : null;
const storageSelectionChanged = Boolean(selection && !sameCodes(selection.storageAddOnCodes, data.currentSelection?.storageAddOnCodes ?? []));
function invalidatePreview(): void {
setPreview(null);
setPaymentMethods(null);
setSelectedPaymentMethod(null);
setPreviewOpen(false);
setPreviewError(false);
setCheckoutError(false);
}
function openManagementSection(section: ManagementSection): void {
invalidatePreview();
setSelection(initialSelfServiceSubscriptionSelection(data));
setManagementSection(section);
}
function selectPlan(plan: CatalogPlan): void {
const price = plan.prices[0];
if (!price) return;
invalidatePreview();
setSelection((current) => ({
productId: plan.id,
priceId: price.id,
billingPeriod: price.billingPeriod,
currency: price.currency,
officeSeatQuantity: current?.officeSeatQuantity ?? data.minimumSeatQuantities.office,
fieldSeatQuantity: current?.fieldSeatQuantity ?? data.minimumSeatQuantities.field,
storageAddOnCodes: current?.storageAddOnCodes ?? [],
}));
}
function selectPrice(price: CatalogPrice): void {
if (!selection) return;
invalidatePreview();
setSelection({
...selection,
priceId: price.id,
billingPeriod: price.billingPeriod,
currency: price.currency,
});
}
function selectSeatQuantity(role: "office" | "field", value: number): void {
if (!selection || !Number.isFinite(value)) return;
invalidatePreview();
const minimum = data.minimumSeatQuantities[role];
setSelection({ ...selection, [`${role}SeatQuantity`]: Math.max(minimum, Math.trunc(value)) });
}
function toggleStorageAddOn(code: string, selected: boolean): void {
if (!selection) return;
invalidatePreview();
const nextCodes = selected ? [...new Set([...selection.storageAddOnCodes, code])] : selection.storageAddOnCodes.filter((candidate) => candidate !== code);
setSelection({ ...selection, storageAddOnCodes: nextCodes.sort() });
}
async function requestPreview(): Promise<void> {
if (!selection || previewing) return;
setPreviewing(true);
setPreviewError(false);
try {
const result = await actions.onPreview(selection);
setPreview(result.preview);
setPaymentMethods(result.paymentMethods);
setSelectedPaymentMethod(result.paymentMethods.status === "ready" ? (result.paymentMethods.methods[0]?.id ?? null) : null);
setPreviewOpen(true);
} catch {
setPreviewError(true);
} finally {
setPreviewing(false);
}
}
async function startCheckout(): Promise<void> {
if (!preview || checkingOut) return;
setCheckingOut(true);
setCheckoutError(false);
try {
const checkoutSelection = {
productId: preview.selectedPlan.id,
priceId: preview.selectedPrice.id,
billingPeriod: preview.selectedPrice.billingPeriod,
currency: preview.selectedPrice.currency,
officeSeatQuantity: preview.selectedOfficeSeatQuantity,
fieldSeatQuantity: preview.selectedFieldSeatQuantity,
storageAddOnCodes: preview.selectedStorageAddOnCodes,
} satisfies SelfServiceSubscriptionSelection;
checkoutRequestRef.current = stableCheckoutRequestKey(
checkoutRequestRef.current,
checkoutSelection,
selectedPaymentMethod,
browserCheckoutRequestOptions(data.billingHref)
);
await actions.onCheckout(checkoutSelection, selectedPaymentMethod, checkoutRequestRef.current.key);
} catch {
setCheckoutError(true);
} finally {
setCheckingOut(false);
}
}
async function confirmCancellation(productId: string): Promise<void> {
if (cancellingProductId) return;
setCancellingProductId(productId);
try {
await actions.onCancel(productId);
setCancelProductId(null);
} finally {
setCancellingProductId(null);
}
}
async function requestEmailMarketingPreview(addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number]): Promise<void> {
if (emailMarketingPreviewingCode || emailMarketingCheckingOut) return;
setEmailMarketingPreviewingCode(addOn.code);
setEmailMarketingError(false);
try {
const result = await actions.onEmailMarketingPreview(addOn);
setEmailMarketingPreview(result.addOn);
setEmailMarketingPaymentMethods(result.paymentMethods);
setSelectedEmailMarketingPaymentMethod(result.paymentMethods.status === "ready" ? (result.paymentMethods.methods[0]?.id ?? null) : null);
} catch {
setEmailMarketingError(true);
} finally {
setEmailMarketingPreviewingCode(null);
}
}
async function startEmailMarketingCheckout(): Promise<void> {
if (!emailMarketingPreview || emailMarketingCheckingOut) return;
setEmailMarketingCheckingOut(true);
setEmailMarketingError(false);
try {
await actions.onEmailMarketingCheckout(emailMarketingPreview, selectedEmailMarketingPaymentMethod);
} catch {
setEmailMarketingError(true);
} finally {
setEmailMarketingCheckingOut(false);
}
}
useEffect(() => {
if (!pendingEmailMarketingAddOnCode) return;
const addOn = data.emailMarketingAddOns.find((candidate) => candidate.code === pendingEmailMarketingAddOnCode && !candidate.active);
setPendingEmailMarketingAddOnCode(null);
if (!addOn || !data.canManage) return;
setManagementSection("addons");
void requestEmailMarketingPreview(addOn);
}, [data.canManage, data.emailMarketingAddOns, pendingEmailMarketingAddOnCode]);
const openBillingButton = (
<Button variant="secondary" icon={<FeatherExternalLink />} onClick={actions.onOpenBilling} data-ui-id="ui.billing.selfServiceSubscription.openBilling">
{t("billing:selfServiceSubscription.openBilling")}
</Button>
);
return (
<PageShell
uiId={activationMode ? "ui.billing.activation.page" : "ui.billing.selfServiceSubscription.page"}
className={activationMode ? "bg-surface-neutral-secondary min-h-screen" : "bg-surface-neutral-primary"}
>
{activationMode ? (
<div className="border-border-default bg-surface-neutral-primary mobile:px-4 mobile:py-6 flex w-full flex-col items-center gap-5 border-b px-6 py-8">
<Logo size="32" />
<div className="w-full max-w-[720px]">
<StepperHorizontal data-ui-id="ui.billing.activation.steps">
<StepperHorizontal.Step firstStep variant="completed" stepNumber="1" label={t("billing:selfServiceSubscription.activation.steps.account")} />
<StepperHorizontal.Step variant="completed" stepNumber="2" label={t("billing:selfServiceSubscription.activation.steps.plan")} />
<StepperHorizontal.Step lastStep variant="active" stepNumber="3" label={t("billing:selfServiceSubscription.activation.steps.payment")} />
</StepperHorizontal>
</div>
<div className="flex max-w-[720px] flex-col items-center gap-2 text-center">
<div className="bg-surface-neutral-secondary rounded-round flex h-9 w-9 items-center justify-center">
<FeatherLock className="text-heading- font-heading- text-icon-neutral-tertiary" />
</div>
<h1 className="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">
{t("billing:selfServiceSubscription.activation.title")}
</h1>
<p className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.activation.description")}
</p>
</div>
</div>
) : embedded ? null : (
<PageHeader
icon={<FeatherCreditCard className={PAGE_HEADER_ICON_CLASS} />}
title={t("billing:selfServiceSubscription.title")}
subtitle={t("billing:selfServiceSubscription.description")}
actions={openBillingButton}
/>
)}
<PageBody className={activationMode ? "mx-auto max-w-[1120px] items-start" : "items-start"}>
{activationMode ? (
<Alert
notDismissible
variant="warning"
title={t("billing:selfServiceSubscription.activation.locked.title")}
description={t("billing:selfServiceSubscription.activation.locked.description")}
data-ui-id="ui.billing.activation.locked"
/>
) : embedded ? (
// No billing-portal button here: inside the hub its target is the
// Rechnungen tab, which the tab bar already offers one row above.
<PageIntro uiId="ui.billing.selfServiceSubscription.intro">{t("billing:selfServiceSubscription.description")}</PageIntro>
) : null}
{!data.canManage ? (
<Alert
notDismissible
variant="warning"
title={t("billing:selfServiceSubscription.permission.title")}
description={t("billing:selfServiceSubscription.permission.description")}
data-ui-id="ui.billing.selfServiceSubscription.permission"
/>
) : null}
{!activationMode && managementSection === "overview" ? (
<div
id="billing-management-overview"
role="region"
aria-label={t("billing:selfServiceSubscription.management.tabs.overview")}
className="flex w-full flex-col gap-6"
>
<CurrentSubscriptionCard
overview={data.overview}
seats={seats}
cancellingProductId={cancellingProductId}
onCancel={setCancelProductId}
onRetry={actions.onRetry}
/>
{data.usage ? <SubscriptionUsageCard usage={data.usage} /> : null}
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4" data-ui-id="ui.billing.selfServiceSubscription.managementActions">
<ManagementActionCard
icon={<FeatherUsers />}
title={t("billing:selfServiceSubscription.management.overview.plan.title")}
description={t("billing:selfServiceSubscription.management.overview.plan.description")}
actionLabel={t("billing:selfServiceSubscription.management.overview.plan.action")}
onAction={() => openManagementSection("plan")}
uiId="ui.billing.selfServiceSubscription.openPlan"
/>
<ManagementActionCard
icon={<FeatherPackage />}
title={t("billing:selfServiceSubscription.management.overview.addons.title")}
description={t("billing:selfServiceSubscription.management.overview.addons.description")}
actionLabel={t("billing:selfServiceSubscription.management.overview.addons.action")}
onAction={() => openManagementSection("addons")}
uiId="ui.billing.selfServiceSubscription.openAddons"
/>
</div>
</div>
) : null}
{activationMode || managementSection === "plan" ? (
<Card
id={activationMode ? undefined : "billing-management-plan"}
role={activationMode ? undefined : "region"}
aria-label={activationMode ? undefined : t("billing:selfServiceSubscription.management.tabs.plan")}
data-ui-id="ui.billing.selfServiceSubscription.builder"
>
<div className="mobile:flex-col flex w-full items-start justify-between gap-4">
<div className="flex flex-col items-start">
<span className="text-body-large font-body-large text-text-neutral-primary">
{t(activationMode ? "billing:selfServiceSubscription.activation.builder.title" : "billing:selfServiceSubscription.builder.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(activationMode ? "billing:selfServiceSubscription.activation.builder.description" : "billing:selfServiceSubscription.builder.description")}
</span>
</div>
{!activationMode ? (
<Button
className="mobile:w-full"
variant="tertiary"
icon={<FeatherArrowLeft />}
onClick={() => openManagementSection("overview")}
data-ui-id="ui.billing.selfServiceSubscription.backToOverview"
>
{t("billing:selfServiceSubscription.management.back")}
</Button>
) : null}
</div>
{data.catalog.plans.length === 0 ? (
<EmptyState
title={t("billing:selfServiceSubscription.catalog.empty.title")}
body={t("billing:selfServiceSubscription.catalog.empty.description")}
/>
) : (
<>
<div className="flex w-full flex-col items-start gap-3">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.catalog.title")}
</span>
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.catalog.title")}
className="mobile:grid-cols-1 grid w-full grid-cols-3"
value={selection?.productId ?? ""}
onValueChange={(productId) => {
const plan = data.catalog.plans.find((candidate) => candidate.id === productId);
if (plan) selectPlan(plan);
}}
disabled={!data.canManage}
>
{data.catalog.plans.map((plan) => {
const displayPrice = plan.prices[0];
return (
<RadioCardGroup.RadioCard key={plan.id} value={plan.id} disabled={!data.canManage || plan.prices.length === 0}>
<div className="flex w-full items-start justify-between gap-3">
<div className="flex flex-col items-start">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{catalogText(t, plan.titleKey)}
</span>
{plan.descriptionKey ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{catalogText(t, plan.descriptionKey)}
</span>
) : null}
</div>
{plan.badge ? (
<BadgeFeedback farbe="subtle-brand-primary" size="small">
{catalogText(t, plan.badge)}
</BadgeFeedback>
) : null}
</div>
{displayPrice ? (
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
{formatters.currencyFromCents(displayPrice.unitAmountCents, displayPrice.currency)} /{" "}
{t(periodLabelKey(displayPrice.billingPeriod))}
</span>
) : (
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.catalog.noPrice")}
</span>
)}
{plan.packageTerms ? (
<div className="border-border flex w-full flex-col items-start gap-2 border-t pt-3">
<div className="flex items-start gap-2">
<FeatherCheck className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-positive" />
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{t("billing:selfServiceSubscription.packageTerms.core")}
</span>
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.seats", {
office: plan.packageTerms.officeSeatsIncluded,
field: plan.packageTerms.fieldSeatsIncluded,
})}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.storage", { storage: plan.packageTerms.storageIncludedGb })}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.storageGrowth", {
storage: plan.packageTerms.storagePerAdditionalSeatGb,
})}
</span>
{!activationMode ? (
<>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.annualSepa", {
price: formatters.currencyFromCents(plan.packageTerms.annualSepaMonthlyEquivalentCents, "EUR"),
})}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.extraSeatsMonthly", {
office: formatters.currencyFromCents(plan.packageTerms.officeExtraMonthlyCents, "EUR"),
field: formatters.currencyFromCents(plan.packageTerms.fieldExtraMonthlyCents, "EUR"),
})}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.packageTerms.extraSeatsAnnualSepa", {
office: formatters.currencyFromCents(plan.packageTerms.officeExtraAnnualSepaCents, "EUR"),
field: formatters.currencyFromCents(plan.packageTerms.fieldExtraAnnualSepaCents, "EUR"),
})}
</span>
</>
) : null}
</div>
) : null}
</RadioCardGroup.RadioCard>
);
})}
</RadioCardGroup>
</div>
{selectedPlan && selectedPlan.prices.length > 0 ? (
<div className="flex w-full flex-col items-start gap-3">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.price.title")}
</span>
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.price.title")}
className="mobile:grid-cols-1 grid w-full grid-cols-2"
value={selection?.priceId ?? ""}
onValueChange={(priceId) => {
const price = selectedPlan.prices.find((candidate) => candidate.id === priceId);
if (price) selectPrice(price);
}}
disabled={!data.canManage}
>
{selectedPlan.prices.map((price) => (
<RadioCardGroup.RadioCard key={price.id} value={price.id} disabled={!data.canManage}>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{formatters.currencyFromCents(price.unitAmountCents, price.currency)} {t("billing:selfServiceSubscription.price.netSuffix")} /{" "}
{t(periodLabelKey(price.billingPeriod))}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{price.billingPeriod === 4
? t("billing:selfServiceSubscription.price.annualCommitmentHint")
: price.trialDays > 0
? t("billing:selfServiceSubscription.price.trialDays", { count: price.trialDays })
: t("billing:selfServiceSubscription.price.noTrial")}
</span>
</RadioCardGroup.RadioCard>
))}
</RadioCardGroup>
</div>
) : null}
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-3">
<TextInput
showLabel
label={t("billing:selfServiceSubscription.seats.officeLabel")}
helpText={t("billing:selfServiceSubscription.seats.roleDescription", { count: data.minimumSeatQuantities.office })}
fillContainer
disabled={!data.canManage || !selection}
type="number"
>
<TextInput.Input
type="number"
min={data.minimumSeatQuantities.office}
step={1}
value={selection?.officeSeatQuantity ?? data.minimumSeatQuantities.office}
onChange={(event) => selectSeatQuantity("office", event.currentTarget.valueAsNumber)}
disabled={!data.canManage || !selection}
aria-label={t("billing:selfServiceSubscription.seats.officeLabel")}
data-ui-id="ui.billing.selfServiceSubscription.officeSeats"
/>
</TextInput>
<TextInput
showLabel
label={t("billing:selfServiceSubscription.seats.fieldLabel")}
helpText={t("billing:selfServiceSubscription.seats.roleDescription", { count: data.minimumSeatQuantities.field })}
fillContainer
disabled={!data.canManage || !selection}
type="number"
>
<TextInput.Input
type="number"
min={data.minimumSeatQuantities.field}
step={1}
value={selection?.fieldSeatQuantity ?? data.minimumSeatQuantities.field}
onChange={(event) => selectSeatQuantity("field", event.currentTarget.valueAsNumber)}
disabled={!data.canManage || !selection}
aria-label={t("billing:selfServiceSubscription.seats.fieldLabel")}
data-ui-id="ui.billing.selfServiceSubscription.fieldSeats"
/>
</TextInput>
</div>
{activationMode && data.storageAddOns.length > 0 ? (
<div className="flex w-full flex-col items-start gap-3">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.storage.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.storage.description")}
</span>
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-3">
{data.storageAddOns.map((addOn) => (
<Card key={addOn.code} variant="neutral">
<Checkbox
checked={selection?.storageAddOnCodes.includes(addOn.code) ?? false}
disabled={!data.canManage || !selection}
onCheckedChange={(checked) => toggleStorageAddOn(addOn.code, checked)}
label={`${addOn.title} · ${formatters.currencyFromCents(addOn.amountCents, addOn.currency)} / ${t(
periodLabelKey(3)
)} ${t("billing:selfServiceSubscription.price.netSuffix")}`}
data-ui-id={`ui.billing.selfServiceSubscription.storage.${addOn.code}`}
/>
</Card>
))}
</div>
</div>
) : null}
{previewError ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.preview.error.title")}
description={t("billing:selfServiceSubscription.preview.error.description")}
data-ui-id="ui.billing.selfServiceSubscription.previewError"
/>
) : null}
{activationMode && selectedPlan && selectedPrice && selection ? (
<Card variant="neutral" data-ui-id="ui.billing.activation.summary">
<div className="flex w-full flex-col items-start gap-1">
<span className="text-body-large font-body-large text-text-neutral-primary">
{t("billing:selfServiceSubscription.activation.summary.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.activation.summary.description")}
</span>
</div>
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-x-8 gap-y-3">
<PreviewRow label={t("billing:selfServiceSubscription.preview.plan")} value={catalogText(t, selectedPlan.titleKey)} />
<PreviewRow label={t("billing:selfServiceSubscription.preview.period")} value={t(periodLabelKey(selectedPrice.billingPeriod))} />
<PreviewRow label={t("billing:selfServiceSubscription.preview.officeSeats")} value={formatters.number(selection.officeSeatQuantity)} />
<PreviewRow label={t("billing:selfServiceSubscription.preview.fieldSeats")} value={formatters.number(selection.fieldSeatQuantity)} />
</div>
<Alert
notDismissible
variant="information"
title={t(
selectedPrice.trialDays > 0
? "billing:selfServiceSubscription.activation.trial.title"
: "billing:selfServiceSubscription.activation.immediate.title"
)}
description={t(
selectedPrice.trialDays > 0
? "billing:selfServiceSubscription.activation.trial.description"
: "billing:selfServiceSubscription.activation.immediate.description",
{ count: selectedPrice.trialDays }
)}
data-ui-id="ui.billing.activation.paymentTiming"
/>
<Button
className="w-full"
icon={<FeatherArrowRight />}
loading={previewing}
disabled={!data.canManage || previewing}
aria-label={t("billing:selfServiceSubscription.activation.previewAction")}
onClick={() => void requestPreview()}
data-ui-id="ui.billing.activation.preview"
>
{t("billing:selfServiceSubscription.activation.previewAction")}
</Button>
</Card>
) : (
<div className="flex w-full items-center justify-end gap-2">
<Button
loading={previewing}
disabled={!data.canManage || !selection || !selectedPrice || previewing}
aria-label={t("billing:selfServiceSubscription.preview.action")}
onClick={() => void requestPreview()}
data-ui-id="ui.billing.selfServiceSubscription.preview"
>
{t("billing:selfServiceSubscription.preview.action")}
</Button>
</div>
)}
</>
)}
</Card>
) : null}
{!activationMode && managementSection === "addons" ? (
<div
id="billing-management-addons"
role="region"
aria-label={t("billing:selfServiceSubscription.management.tabs.addons")}
className="flex w-full flex-col gap-6"
>
<div className="mobile:flex-col flex w-full items-start justify-between gap-4">
<div className="flex flex-col items-start gap-1">
<h2 className="text-heading-3 font-heading-3 text-text-neutral-primary">
{t("billing:selfServiceSubscription.management.overview.addons.title")}
</h2>
<p className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.management.overview.addons.description")}
</p>
</div>
<Button
className="mobile:w-full"
variant="tertiary"
icon={<FeatherArrowLeft />}
onClick={() => openManagementSection("overview")}
data-ui-id="ui.billing.selfServiceSubscription.backToOverview"
>
{t("billing:selfServiceSubscription.management.back")}
</Button>
</div>
{data.storageAddOns.length > 0 ? (
<Card data-ui-id="ui.billing.selfServiceSubscription.storageAddOns">
<div className="flex w-full items-start gap-3">
<IconWithBackground variant="neutral" icon={<FeatherHardDrive />} />
<div className="flex flex-col items-start gap-1">
<span className="text-body-large font-body-large text-text-neutral-primary">{t("billing:selfServiceSubscription.storage.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.storage.description")}
</span>
</div>
</div>
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-3">
{data.storageAddOns.map((addOn) => (
<Card key={addOn.code} variant="neutral">
<Checkbox
checked={selection?.storageAddOnCodes.includes(addOn.code) ?? false}
disabled={!data.canManage || !selection}
onCheckedChange={(checked) => toggleStorageAddOn(addOn.code, checked)}
label={`${addOn.title} · ${formatters.currencyFromCents(addOn.amountCents, addOn.currency)} / ${t(periodLabelKey(3))} ${t(
"billing:selfServiceSubscription.price.netSuffix"
)}`}
data-ui-id={`ui.billing.selfServiceSubscription.storage.${addOn.code}`}
/>
</Card>
))}
</div>
{previewError ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.preview.error.title")}
description={t("billing:selfServiceSubscription.preview.error.description")}
data-ui-id="ui.billing.selfServiceSubscription.storagePreviewError"
/>
) : null}
<div className="flex w-full justify-end">
<Button
loading={previewing}
disabled={!data.canManage || !selection || !selectedPrice || !storageSelectionChanged || previewing}
onClick={() => void requestPreview()}
data-ui-id="ui.billing.selfServiceSubscription.storagePreview"
>
{t("billing:selfServiceSubscription.storage.previewAction")}
</Button>
</div>
</Card>
) : null}
{data.emailMarketingAddOns.length > 0 ? (
<Card data-ui-id="ui.billing.selfServiceSubscription.emailMarketing">
<div className="flex w-full flex-col items-start">
<span className="text-body-large font-body-large text-text-neutral-primary">{t("billing:selfServiceSubscription.emailMarketing.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.emailMarketing.description")}
</span>
</div>
{data.emailMarketingAddOns.some((addOn) => addOn.active) ? (
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.emailMarketing.active.title")}
description={t("billing:selfServiceSubscription.emailMarketing.active.description")}
/>
) : null}
{emailMarketingError && emailMarketingPreview === null ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.emailMarketing.errors.checkoutTitle")}
description={t("billing:selfServiceSubscription.emailMarketing.errors.checkoutDescription")}
data-ui-id="ui.billing.selfServiceSubscription.emailMarketing.previewError"
/>
) : null}
<div className="mobile:grid-cols-1 grid w-full grid-cols-3 gap-3">
{data.emailMarketingAddOns.map((addOn) => (
<Card key={addOn.code} variant="neutral">
<div className="flex w-full items-start justify-between gap-3">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{catalogText(t, addOn.title)}</span>
{addOn.active ? (
<BadgeFeedback farbe="subtle-positive" size="small">
{t("billing:selfServiceSubscription.emailMarketing.active.badge")}
</BadgeFeedback>
) : null}
</div>
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
{formatters.currencyFromCents(addOn.grossAmountCents, addOn.currency)} / {t(periodLabelKey(3))}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.emailMarketing.grossPriceDetail", {
net: formatters.currencyFromCents(addOn.amountCents, addOn.currency),
rate: addOn.vatRateBasisPoints / 100,
})}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.emailMarketing.allowance", {
count: addOn.monthlyEmailLimit,
formattedCount: formatters.number(addOn.monthlyEmailLimit),
})}
</span>
<Button
variant="secondary"
loading={emailMarketingPreviewingCode === addOn.code}
disabled={!data.canManage || addOn.active || emailMarketingPreviewingCode !== null || emailMarketingCheckingOut}
onClick={() => void requestEmailMarketingPreview(addOn)}
data-ui-id={`ui.billing.selfServiceSubscription.emailMarketing.${addOn.code}`}
>
{t(
addOn.active
? "billing:selfServiceSubscription.emailMarketing.active.badge"
: data.emailMarketingAddOns.some((candidate) => candidate.active)
? "billing:selfServiceSubscription.emailMarketing.switch"
: "billing:selfServiceSubscription.emailMarketing.checkout"
)}
</Button>
</Card>
))}
</div>
</Card>
) : null}
{actions.onOpenCustomerPortal ? (
<Card data-ui-id="ui.billing.selfServiceSubscription.customerPortal">
<div className="mobile:flex-col flex w-full items-center justify-between gap-4">
<div className="flex min-w-0 items-start gap-3">
<IconWithBackground variant="neutral" icon={<FeatherGlobe />} />
<div className="flex min-w-0 flex-col items-start gap-1">
<span className="text-body-large font-body-large text-text-neutral-primary">
{t("billing:selfServiceSubscription.customerPortal.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.customerPortal.description")}
</span>
</div>
</div>
<Button
className="mobile:w-full"
variant="tertiary"
iconRight={<FeatherArrowRight />}
onClick={actions.onOpenCustomerPortal}
data-ui-id="ui.billing.selfServiceSubscription.customerPortal.open"
>
{t("billing:selfServiceSubscription.customerPortal.action")}
</Button>
</div>
</Card>
) : null}
{data.storageAddOns.length === 0 && data.emailMarketingAddOns.length === 0 && !actions.onOpenCustomerPortal ? (
<EmptyState
title={t("billing:selfServiceSubscription.management.addons.empty.title")}
body={t("billing:selfServiceSubscription.management.addons.empty.description")}
/>
) : null}
</div>
) : null}
</PageBody>
<Dialog open={previewOpen && preview !== null} onOpenChange={(open: boolean) => setPreviewOpen(open)}>
<Dialog.Content
className="w-[560px] max-w-[90vw] p-4"
aria-label={t("billing:selfServiceSubscription.preview.dialog.title")}
data-ui-id="ui.billing.selfServiceSubscription.previewDialog"
>
{preview ? (
<>
<div className="flex w-full flex-col items-start gap-2">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("billing:selfServiceSubscription.preview.dialog.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.preview.dialog.description")}
</span>
</div>
<div className="bg-surface-neutral-secondary flex w-full flex-col items-start gap-3 rounded-md p-4">
<PreviewRow label={t("billing:selfServiceSubscription.preview.plan")} value={catalogText(t, preview.selectedPlan.titleKey)} />
<PreviewRow
label={t("billing:selfServiceSubscription.preview.changeKind.label")}
value={t(`billing:selfServiceSubscription.preview.changeKind.${preview.changeKind}`)}
/>
<PreviewRow label={t("billing:selfServiceSubscription.preview.officeSeats")} value={formatters.number(preview.selectedOfficeSeatQuantity)} />
<PreviewRow label={t("billing:selfServiceSubscription.preview.fieldSeats")} value={formatters.number(preview.selectedFieldSeatQuantity)} />
<PreviewRow label={t("billing:selfServiceSubscription.preview.period")} value={t(periodLabelKey(preview.selectedPrice.billingPeriod))} />
<PreviewRow
label={t("billing:selfServiceSubscription.preview.effectiveAtLabel")}
value={
preview.effectiveAtDate
? formatters.date(preview.effectiveAtDate, { dateStyle: "medium" })
: t(`billing:selfServiceSubscription.preview.effectiveAt.${preview.effectiveAt}`)
}
/>
<PreviewRow
label={t(
preview.selectedPlan.quantityMode === "per_seat"
? "billing:selfServiceSubscription.preview.unitAmount"
: "billing:selfServiceSubscription.preview.baseAmount"
)}
value={formatters.currencyFromCents(preview.selectedPrice.unitAmountCents, preview.selectedPrice.currency)}
/>
{preview.officeSeatAmountCents > 0 ? (
<PreviewRow
label={t("billing:selfServiceSubscription.preview.officeSeatAmount")}
value={formatters.currencyFromCents(preview.officeSeatAmountCents, preview.selectedPrice.currency)}
/>
) : null}
{preview.fieldSeatAmountCents > 0 ? (
<PreviewRow
label={t("billing:selfServiceSubscription.preview.fieldSeatAmount")}
value={formatters.currencyFromCents(preview.fieldSeatAmountCents, preview.selectedPrice.currency)}
/>
) : null}
{preview.storageAmountCents > 0 ? (
<PreviewRow
label={t("billing:selfServiceSubscription.preview.storageAmount")}
value={formatters.currencyFromCents(preview.storageAmountCents, preview.selectedPrice.currency)}
/>
) : null}
<div className="bg-border-default h-px w-full" />
<PreviewRow
label={t("billing:selfServiceSubscription.preview.recurringNetTotal")}
value={`${formatters.currencyFromCents(preview.recurringNetTotalCents, preview.selectedPrice.currency)} / ${t(
periodLabelKey(preview.selectedPrice.billingPeriod)
)}`}
/>
<PreviewRow
label={t("billing:selfServiceSubscription.preview.vat", {
rate: preview.vatRateBasisPoints / 100,
})}
value={formatters.currencyFromCents(preview.vatAmountCents, preview.selectedPrice.currency)}
/>
<PreviewRow
strong
label={t("billing:selfServiceSubscription.preview.recurringGrossTotal")}
value={`${formatters.currencyFromCents(preview.recurringGrossTotalCents, preview.selectedPrice.currency)} / ${t(
periodLabelKey(preview.selectedPrice.billingPeriod)
)}`}
/>
</div>
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.preview.payment.title")}
description={t("billing:selfServiceSubscription.preview.payment.description")}
/>
{paymentMethods?.status === "ready" ? (
<div className="flex w-full flex-col items-start gap-3" data-ui-id="ui.billing.selfServiceSubscription.paymentMethods">
<div className="flex w-full flex-col items-start">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.paymentMethods.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(
usesCardOnly(paymentMethods)
? "billing:selfServiceSubscription.paymentMethods.cardDescription"
: preview.selectedPrice.billingPeriod === 4
? "billing:selfServiceSubscription.paymentMethods.sepaDescription"
: "billing:selfServiceSubscription.paymentMethods.description"
)}
</span>
</div>
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.paymentMethods.title")}
className="mobile:grid-cols-1 grid w-full grid-cols-2"
value={selectedPaymentMethod ?? ""}
onValueChange={setSelectedPaymentMethod}
disabled={checkingOut}
>
{paymentMethods.methods.map((method) => (
<RadioCardGroup.RadioCard key={method.id} value={method.id} disabled={checkingOut}>
<div className="flex w-full items-center gap-3">
<FeatherCreditCard className="text-heading-0 font-heading-0 text-icon-neutral-secondary" />
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{method.label}</span>
</div>
</RadioCardGroup.RadioCard>
))}
</RadioCardGroup>
</div>
) : paymentMethods?.status === "fallback" ? (
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.paymentMethods.fallbackTitle")}
description={t("billing:selfServiceSubscription.paymentMethods.fallbackDescription")}
data-ui-id="ui.billing.selfServiceSubscription.paymentMethodsFallback"
/>
) : paymentMethods?.status === "required_card_unavailable" ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.paymentMethods.cardUnavailableTitle")}
description={t("billing:selfServiceSubscription.paymentMethods.cardUnavailableDescription")}
data-ui-id="ui.billing.selfServiceSubscription.paymentMethodsCardUnavailable"
/>
) : null}
{checkoutError ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.checkout.error.title")}
description={t("billing:selfServiceSubscription.checkout.error.description")}
/>
) : null}
<div className="flex w-full items-center justify-end gap-2 pt-2">
<Button variant="tertiary" disabled={checkingOut} onClick={() => setPreviewOpen(false)}>
{t("billing:selfServiceSubscription.preview.close")}
</Button>
<Button
loading={checkingOut}
disabled={
!data.canManage ||
checkingOut ||
paymentMethods?.status === "required_card_unavailable" ||
(paymentMethods?.status === "ready" && selectedPaymentMethod === null)
}
aria-label={t("billing:selfServiceSubscription.checkout.action")}
onClick={() => void startCheckout()}
data-ui-id="ui.billing.selfServiceSubscription.checkout"
>
{t("billing:selfServiceSubscription.checkout.action")}
</Button>
</div>
</>
) : null}
</Dialog.Content>
</Dialog>
<Dialog
open={emailMarketingPreview !== null}
onOpenChange={(open: boolean) => {
if (!open && !emailMarketingCheckingOut) {
setEmailMarketingPreview(null);
setEmailMarketingPaymentMethods(null);
setSelectedEmailMarketingPaymentMethod(null);
setEmailMarketingError(false);
}
}}
>
<Dialog.Content
className="w-[520px] max-w-[90vw] p-4"
aria-labelledby="email-marketing-checkout-title"
data-ui-id="ui.billing.selfServiceSubscription.emailMarketing.dialog"
>
{emailMarketingPreview ? (
<>
<div className="flex w-full flex-col items-start gap-2">
<span id="email-marketing-checkout-title" className="text-heading-0 font-heading-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.emailMarketing.dialog.title")}
</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.emailMarketing.dialog.description")}
</span>
</div>
<div className="bg-surface-neutral-secondary flex w-full flex-col items-start gap-3 rounded-md p-4">
<PreviewRow label={t("billing:selfServiceSubscription.emailMarketing.dialog.package")} value={catalogText(t, emailMarketingPreview.title)} />
<PreviewRow
label={t("billing:selfServiceSubscription.emailMarketing.dialog.allowance")}
value={t("billing:selfServiceSubscription.emailMarketing.allowance", {
count: emailMarketingPreview.monthlyEmailLimit,
formattedCount: formatters.number(emailMarketingPreview.monthlyEmailLimit),
})}
/>
<PreviewRow
label={t("billing:selfServiceSubscription.emailMarketing.dialog.netPrice")}
value={formatters.currencyFromCents(emailMarketingPreview.amountCents, emailMarketingPreview.currency)}
/>
<PreviewRow
label={t("billing:selfServiceSubscription.emailMarketing.dialog.vat", {
rate: emailMarketingPreview.vatRateBasisPoints / 100,
})}
value={formatters.currencyFromCents(emailMarketingPreview.vatAmountCents, emailMarketingPreview.currency)}
/>
<PreviewRow
strong
label={t("billing:selfServiceSubscription.emailMarketing.dialog.grossPrice")}
value={`${formatters.currencyFromCents(emailMarketingPreview.grossAmountCents, emailMarketingPreview.currency)} / ${t(periodLabelKey(3))}`}
/>
</div>
{data.emailMarketingAddOns.some((addOn) => addOn.active) ? (
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.emailMarketing.dialog.replacement.title")}
description={t("billing:selfServiceSubscription.emailMarketing.dialog.replacement.description")}
/>
) : null}
{emailMarketingPaymentMethods?.status === "ready" ? (
<div className="flex w-full flex-col items-start gap-3">
<div className="flex w-full flex-col items-start">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("billing:selfServiceSubscription.paymentMethods.title")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(
usesCardOnly(emailMarketingPaymentMethods)
? "billing:selfServiceSubscription.paymentMethods.cardDescription"
: "billing:selfServiceSubscription.paymentMethods.description"
)}
</span>
</div>
<RadioCardGroup
aria-label={t("billing:selfServiceSubscription.paymentMethods.title")}
className="mobile:grid-cols-1 grid w-full grid-cols-2"
value={selectedEmailMarketingPaymentMethod ?? ""}
onValueChange={setSelectedEmailMarketingPaymentMethod}
disabled={emailMarketingCheckingOut}
>
{emailMarketingPaymentMethods.methods.map((method) => (
<RadioCardGroup.RadioCard key={method.id} value={method.id} disabled={emailMarketingCheckingOut}>
<div className="flex w-full items-center gap-3">
<FeatherCreditCard className="text-heading-0 font-heading-0 text-icon-neutral-secondary" />
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{method.label}</span>
</div>
</RadioCardGroup.RadioCard>
))}
</RadioCardGroup>
</div>
) : emailMarketingPaymentMethods?.status === "fallback" ? (
<Alert
notDismissible
variant="information"
title={t("billing:selfServiceSubscription.paymentMethods.fallbackTitle")}
description={t("billing:selfServiceSubscription.paymentMethods.fallbackDescription")}
/>
) : emailMarketingPaymentMethods?.status === "required_card_unavailable" ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.paymentMethods.cardUnavailableTitle")}
description={t("billing:selfServiceSubscription.paymentMethods.cardUnavailableDescription")}
/>
) : null}
{emailMarketingError ? (
<Alert
notDismissible
variant="error"
title={t("billing:selfServiceSubscription.emailMarketing.errors.checkoutTitle")}
description={t("billing:selfServiceSubscription.emailMarketing.errors.checkoutDescription")}
/>
) : null}
<div className="flex w-full items-center justify-end gap-2">
<Button
variant="secondary"
disabled={emailMarketingCheckingOut}
onClick={() => setEmailMarketingPreview(null)}
data-ui-id="ui.billing.selfServiceSubscription.emailMarketing.dialog.cancel"
>
{t("shared.cancel")}
</Button>
<Button
loading={emailMarketingCheckingOut}
disabled={
emailMarketingCheckingOut ||
emailMarketingPaymentMethods?.status === "required_card_unavailable" ||
(emailMarketingPaymentMethods?.status === "ready" && selectedEmailMarketingPaymentMethod === null)
}
onClick={() => void startEmailMarketingCheckout()}
data-ui-id="ui.billing.selfServiceSubscription.emailMarketing.dialog.checkout"
>
{t("billing:selfServiceSubscription.emailMarketing.dialog.checkout")}
</Button>
</div>
</>
) : null}
</Dialog.Content>
</Dialog>
<Dialog open={cancelProduct !== null} onOpenChange={(open: boolean) => (open ? undefined : setCancelProductId(null))}>
<Dialog.Content
className="w-[420px] max-w-[90vw] p-4"
aria-label={t("billing:subscriptionOverview.cancel.title")}
data-ui-id="ui.billing.selfServiceSubscription.cancelDialog"
>
<div className="flex w-full flex-col items-start gap-2">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("billing:subscriptionOverview.cancel.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("billing:subscriptionOverview.cancel.description", {
product: cancelProduct ? catalogText(t, cancelProduct.titleKey) : "",
})}
</span>
</div>
<div className="flex w-full items-center justify-end gap-2 pt-4">
<Button variant="tertiary" disabled={cancellingProductId !== null} onClick={() => setCancelProductId(null)}>
{t("shared.cancel")}
</Button>
<Button
variant="destructive"
loading={cancellingProductId !== null}
disabled={cancellingProductId !== null}
aria-label={t("billing:subscriptionOverview.cancel.confirm")}
onClick={() => (cancelProduct ? void confirmCancellation(cancelProduct.id) : undefined)}
data-ui-id="ui.billing.selfServiceSubscription.cancelConfirm"
>
{t("billing:subscriptionOverview.cancel.confirm")}
</Button>
</div>
</Dialog.Content>
</Dialog>
</PageShell>
);
}
function ManagementActionCard({
icon,
title,
description,
actionLabel,
onAction,
uiId,
}: {
readonly icon: React.ReactNode;
readonly title: string;
readonly description: string;
readonly actionLabel: string;
readonly onAction: () => void;
readonly uiId: string;
}): React.JSX.Element {
return (
<Card>
<div className="flex items-start gap-3">
<IconWithBackground variant="neutral" icon={icon} />
<div className="flex min-w-0 flex-col items-start gap-1">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{title}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{description}</span>
</div>
</div>
<Button className="mobile:w-full" variant="tertiary" iconRight={<FeatherArrowRight />} onClick={onAction} data-ui-id={uiId}>
{actionLabel}
</Button>
</Card>
);
}
function SubscriptionUsageCard({ usage }: { usage: NonNullable<ReadySelfServiceData["usage"]> }): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const storage = usage.storage;
return (
<Card data-ui-id="ui.billing.selfServiceSubscription.usage">
<div className="flex w-full flex-col items-start">
<span className="text-body-large font-body-large text-text-neutral-primary">{t("billing:selfServiceSubscription.usage.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.usage.description")}
</span>
</div>
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4">
<Card variant="neutral" data-ui-id="ui.billing.selfServiceSubscription.usage.storage">
<div className="flex w-full items-start justify-between gap-4">
<div className="flex flex-col items-start">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.usage.storage.title")}
</span>
{storage.status === "ready" ? (
<span className="text-subtitle-0 font-subtitle-0 text-text-neutral-primary">
{formatBytes(storage.storedBytes + storage.reservedBytes, formatters.number)}
</span>
) : null}
</div>
<FeatherHardDrive className="text-heading-0 font-heading-0 text-icon-neutral-tertiary" />
</div>
{storage.status === "ready" ? (
<>
<Progress
className="w-full"
state={storage.percentUsed >= 100 ? "error" : "uploading"}
value={storage.percentUsed}
label={t("billing:selfServiceSubscription.usage.storage.limit", {
value: formatBytes(storage.capacityBytes, formatters.number),
})}
statusText={t("billing:selfServiceSubscription.usage.storage.remaining", {
value: formatBytes(storage.remainingBytes, formatters.number),
})}
/>
{storage.reservedBytes > 0 ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.usage.storage.reserved", {
value: formatBytes(storage.reservedBytes, formatters.number),
})}
</span>
) : null}
</>
) : (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(`billing:selfServiceSubscription.usage.unavailable.${storage.reason}`)}
</span>
)}
</Card>
<Card variant="neutral" data-ui-id="ui.billing.selfServiceSubscription.usage.emailMarketing">
<div className="flex w-full items-start justify-between gap-4">
<div className="flex flex-col items-start">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.usage.emailMarketing.title")}
</span>
{usage.emailMarketing.status === "ready" ? (
<span className="text-subtitle-0 font-subtitle-0 text-text-neutral-primary">{formatters.number(usage.emailMarketing.used)}</span>
) : null}
</div>
<FeatherMail className="text-heading-0 font-heading-0 text-icon-neutral-tertiary" />
</div>
{usage.emailMarketing.status === "ready" ? (
<>
{usage.emailMarketing.limit === null ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.usage.emailMarketing.unlimited")}
</span>
) : (
<Progress
className="w-full"
state={(usage.emailMarketing.percentUsed ?? 0) >= 100 ? "error" : "uploading"}
value={usage.emailMarketing.percentUsed ?? 0}
label={t("billing:selfServiceSubscription.usage.emailMarketing.limit", {
value: formatters.number(usage.emailMarketing.limit),
})}
statusText={t("billing:selfServiceSubscription.usage.emailMarketing.remaining", {
value: formatters.number(usage.emailMarketing.remaining ?? 0),
})}
/>
)}
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.usage.emailMarketing.period", {
start: formatters.date(usage.emailMarketing.periodStart, { dateStyle: "medium" }),
end: formatters.date(usage.emailMarketing.periodEnd, { dateStyle: "medium" }),
})}
</span>
</>
) : (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t(`billing:selfServiceSubscription.usage.unavailable.${usage.emailMarketing.reason}`)}
</span>
)}
</Card>
</div>
</Card>
);
}
function CurrentSubscriptionCard({
overview,
seats,
cancellingProductId,
onCancel,
onRetry,
}: {
overview: ReadySelfServiceData["overview"];
seats: number | null;
cancellingProductId: string | null;
onCancel: (productId: string) => void;
onRetry: () => void;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
if (overview.status === "idle" || overview.status === "loading") {
return (
<Card data-ui-id="ui.billing.selfServiceSubscription.current.loading">
<div className="flex w-full items-center gap-3">
<Loader />
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("billing:selfServiceSubscription.current.loading")}
</span>
</div>
</Card>
);
}
if (overview.status === "error") {
return (
<EmptyState
outlined
variant="error"
title={t("billing:selfServiceSubscription.current.error.title")}
body={t(overview.error.messageKey)}
action={
<Button variant="tertiary" onClick={onRetry}>
{t("billing:selfServiceSubscription.error.retry")}
</Button>
}
/>
);
}
if (overview.status === "empty") {
return (
<Card data-ui-id="ui.billing.selfServiceSubscription.current.empty">
<div className="flex w-full flex-col items-start">
<span className="text-body-large font-body-large text-text-neutral-primary">{t("billing:selfServiceSubscription.current.empty.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.current.empty.description")}
</span>
</div>
</Card>
);
}
const cancellableProducts = overview.data.products.filter((product) => product.canCancel);
return (
<Card data-ui-id="ui.billing.selfServiceSubscription.current">
<div className="mobile:flex-col flex w-full items-start justify-between gap-4">
<div className="flex flex-col items-start">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.current.title")}
</span>
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
{overview.data.planLabel ? catalogText(t, overview.data.planLabel) : t("billing:selfServiceSubscription.current.noPlan")}
</span>
</div>
<BadgeFeedback farbe={overview.data.status === "active" || overview.data.status === "trial" ? "subtle-positive" : "subtle-warning"} size="small">
{t(`billing:selfServiceSubscription.current.status.${overview.data.status}`)}
</BadgeFeedback>
</div>
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4">
<Card variant="neutral">
<div className="flex items-center gap-3">
<FeatherUsers className="text-heading-0 font-heading-0 text-icon-neutral-secondary" />
<div className="flex flex-col items-start">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.current.seats")}
</span>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{seats === null ? t("billing:selfServiceSubscription.current.unknown") : formatters.number(seats)}
</span>
</div>
</div>
</Card>
<Card variant="neutral">
<div className="flex items-center gap-3">
<FeatherClock className="text-heading-0 font-heading-0 text-icon-neutral-secondary" />
<div className="flex flex-col items-start">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("billing:selfServiceSubscription.current.effectiveUntil")}
</span>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{overview.data.products.find((product) => product.state === "active")?.currentPeriodEnd
? formatters.date(overview.data.products.find((product) => product.state === "active")!.currentPeriodEnd!, { dateStyle: "medium" })
: t("billing:selfServiceSubscription.current.openEnded")}
</span>
</div>
</div>
</Card>
</div>
{cancellableProducts.length > 0 ? (
<div className="flex w-full flex-wrap items-center justify-end gap-2">
{cancellableProducts.map((product) => (
<Button
key={product.id}
variant="tertiary"
size="small"
loading={cancellingProductId === product.id}
disabled={cancellingProductId !== null}
onClick={() => onCancel(product.id)}
data-ui-id="ui.billing.selfServiceSubscription.cancel"
>
{t("billing:selfServiceSubscription.current.cancel", {
product: catalogText(t, product.titleKey),
})}
</Button>
))}
</div>
) : null}
</Card>
);
}
function PreviewRow({ label, value, strong = false }: { label: string; value: string; strong?: boolean }): React.JSX.Element {
return (
<div className="flex w-full items-start justify-between gap-4">
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{label}</span>
<span
className={
strong
? "text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary text-right"
: "text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary text-right"
}
>
{value}
</span>
</div>
);
}