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; readonly onPreview: ( selection: SelfServiceSubscriptionSelection ) => Promise<{ preview: SelfServiceSubscriptionPricePreviewVM; paymentMethods: SelfServiceCheckoutPaymentMethodsVM }>; readonly onCheckout: (selection: SelfServiceSubscriptionSelection, paymentMethod: string | null, checkoutRequestKey: string) => void | Promise; readonly onCancel: (productId: string) => void | Promise; readonly onEmailMarketingPreview: (addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number]) => Promise<{ addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number]; paymentMethods: SelfServiceCheckoutPaymentMethodsVM; }>; readonly onEmailMarketingCheckout: ( addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number], paymentMethod: string | null ) => void | Promise; 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> = { 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 ; return ( ); } 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("team"); const initialSelection = useMemo(() => initialActivationSubscriptionSelection(data, initialPlanAdvice), [data, initialPlanAdvice]); const [selection, setSelection] = useState(initialSelection); const initialManualPlanSelection = Boolean( data.currentSelection || (data.preferredSelection && initialSelection && initialPlanAdvice && initialSelection.priceId !== initialPlanAdvice.recommendedPriceId) ); const [planAdvice, setPlanAdvice] = useState(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(null); const [preview, setPreview] = useState(null); const [paymentMethods, setPaymentMethods] = useState(null); const [selectedPaymentMethod, setSelectedPaymentMethod] = useState(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(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 { 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 ( {t("billing:states.retry")} } /> ); } return (
{ACTIVATION_STEPS.map((candidate, index) => ( ))}

{t(`billing:selfServiceSubscription.activation.wizard.${step}.title`)}

{t(`billing:selfServiceSubscription.activation.wizard.${step}.description`)}

{step === "team" && selection ? (
} 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)} /> } 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)} />
{planAdviceLoading ? : null} {planAdviceError ? (
) : null}
) : null} {step === "plan" && selection ? (
{ 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 (
{catalogText(t, plan.titleKey)} {recommended ? ( {t("billing:selfServiceSubscription.activation.wizard.plan.recommended")} ) : null}
{price ? ( {formatters.currencyFromCents(advisedPlan?.amountCents ?? price.unitAmountCents, advisedPlan?.currency ?? price.currency)}{" "} {t("billing:selfServiceSubscription.price.netSuffix")} / {t(periodLabelKey(advisedPlan?.billingPeriod ?? price.billingPeriod))} ) : null} {plan.packageTerms ? (
{t("billing:selfServiceSubscription.packageTerms.seats", { office: plan.packageTerms.officeSeatsIncluded, field: plan.packageTerms.fieldSeatsIncluded, })} {t("billing:selfServiceSubscription.packageTerms.storage", { storage: plan.packageTerms.storageIncludedGb })} {t("billing:selfServiceSubscription.packageTerms.storageGrowth", { storage: plan.packageTerms.storagePerAdditionalSeatGb, })}
) : null}
); })}
{selectedPlan && selectedPlan.prices.length > 1 ? ( { const price = selectedPlan.prices.find((candidate) => candidate.id === priceId); if (price) choosePrice(price); }} > {selectedPlan.prices.map((price) => ( {formatters.currencyFromCents(price.unitAmountCents, price.currency)} {t("billing:selfServiceSubscription.price.netSuffix")} /{" "} {t(periodLabelKey(price.billingPeriod))} {price.billingPeriod === 4 ? t("billing:selfServiceSubscription.price.annualCommitmentHint") : price.trialDays > 0 ? t("billing:selfServiceSubscription.price.trialDays", { count: price.trialDays }) : t("billing:selfServiceSubscription.price.noTrial")} ))} ) : null}
) : null} {step === "storage" && selection ? (
{selectedPlan?.packageTerms ? ( ) : null} { replaceSelection({ ...selection, storageAddOnCodes: value === "none" ? [] : [value] }); }} > {t("billing:selfServiceSubscription.activation.wizard.storage.noExtra")} {t("billing:selfServiceSubscription.activation.wizard.storage.noExtraDescription")} {data.storageAddOns.map((addOn) => (
{addOn.title}
+{formatters.currencyFromCents(addOn.amountCents, addOn.currency)} {t("billing:selfServiceSubscription.price.netSuffix")} /{" "} {t(periodLabelKey(3))}
))}
) : null} {step === "email" ? (
{ const choice = value === "yes" ? "yes" : "no"; setEmailChoice(choice); if (choice === "no") setEmailAddOnCode(null); }} > {t("billing:selfServiceSubscription.activation.wizard.email.no")} {t("billing:selfServiceSubscription.activation.wizard.email.noDescription")}
{t("billing:selfServiceSubscription.activation.wizard.email.yes")}
{t("billing:selfServiceSubscription.activation.wizard.email.yesDescription")}
{emailChoice === "yes" && data.emailMarketingAddOns.length > 0 ? ( {data.emailMarketingAddOns.map((addOn) => ( {catalogText(t, addOn.title)} {t("billing:selfServiceSubscription.emailMarketing.allowance", { count: addOn.monthlyEmailLimit, formattedCount: formatters.number(addOn.monthlyEmailLimit), })} {formatters.currencyFromCents(addOn.amountCents, addOn.currency)} {t("billing:selfServiceSubscription.price.netSuffix")} /{" "} {t(periodLabelKey(3))} ))} ) : null} {emailChoice === "yes" ? ( ) : null}
) : null} {step === "payment" ? (
} />
{t("billing:selfServiceSubscription.paymentMethods.title")} {t( usesCardOnly(paymentMethods) ? "billing:selfServiceSubscription.paymentMethods.cardDescription" : "billing:selfServiceSubscription.paymentMethods.description" )}
{paymentMethods?.status === "ready" ? ( {paymentMethods.methods.map((method) => (
{method.id === "creditcard" ? ( ) : ( )} {method.label}
))}
) : paymentMethods?.status === "required_card_unavailable" ? ( ) : paymentMethods?.status === "fallback" ? ( ) : ( )}
} /> {t("billing:selfServiceSubscription.activation.wizard.payment.summaryTitle")}
{preview ? ( ) : ( )} {preview ? ( 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 ? ( ) : null} {checkoutError ? ( ) : null}
) : null} {previewError && step !== "plan" && step !== "storage" ? ( ) : null}
{step !== "payment" ? ( ) : null}
); } 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 (
{label} {description}
onChange(values[0] ?? minimum)} aria-label={label} /> { const nextValue = event.currentTarget.valueAsNumber; if (Number.isFinite(nextValue)) { onChange(Math.min(10_000, Math.max(minimum, nextValue))); } }} />
); } function ActivationPriceRows({ preview }: { preview: SelfServiceSubscriptionPricePreviewVM }): React.JSX.Element { const { t } = useTranslation(); const formatters = useLocaleFormatters(); return (
{preview.officeSeatAmountCents > 0 ? ( ) : null} {preview.fieldSeatAmountCents > 0 ? ( ) : null} {preview.storageAmountCents > 0 ? ( ) : null}
); } function ActivationLivePrice({ preview, loading, error, }: { preview: SelfServiceSubscriptionPricePreviewVM | null; loading: boolean; error: boolean; }): React.JSX.Element { const { t } = useTranslation(); return (
{t("billing:selfServiceSubscription.activation.wizard.livePrice.title")} {t("billing:selfServiceSubscription.activation.wizard.livePrice.description")}
{loading ? : null}
{preview ? : null} {error ? ( ) : null}
); } function LoadingMessage({ label }: { label: string }): React.JSX.Element { return (
{label}
); } 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(() => initialSelfServiceSubscriptionSelection(data)); const [preview, setPreview] = useState(null); const [paymentMethods, setPaymentMethods] = useState(null); const [selectedPaymentMethod, setSelectedPaymentMethod] = useState(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(null); const [cancellingProductId, setCancellingProductId] = useState(null); const [emailMarketingPreview, setEmailMarketingPreview] = useState(null); const [emailMarketingPaymentMethods, setEmailMarketingPaymentMethods] = useState(null); const [selectedEmailMarketingPaymentMethod, setSelectedEmailMarketingPaymentMethod] = useState(null); const [emailMarketingPreviewingCode, setEmailMarketingPreviewingCode] = useState(null); const [emailMarketingCheckingOut, setEmailMarketingCheckingOut] = useState(false); const [emailMarketingError, setEmailMarketingError] = useState(false); const [managementSection, setManagementSection] = useState("overview"); const [pendingEmailMarketingAddOnCode, setPendingEmailMarketingAddOnCode] = useState(initialEmailMarketingAddOnCode); const checkoutRequestRef = useRef(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 { 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 { 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 { if (cancellingProductId) return; setCancellingProductId(productId); try { await actions.onCancel(productId); setCancelProductId(null); } finally { setCancellingProductId(null); } } async function requestEmailMarketingPreview(addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number]): Promise { 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 { 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 = ( ); return ( {activationMode ? (

{t("billing:selfServiceSubscription.activation.title")}

{t("billing:selfServiceSubscription.activation.description")}

) : embedded ? null : ( } title={t("billing:selfServiceSubscription.title")} subtitle={t("billing:selfServiceSubscription.description")} actions={openBillingButton} /> )} {activationMode ? ( ) : embedded ? ( // No billing-portal button here: inside the hub its target is the // Rechnungen tab, which the tab bar already offers one row above. {t("billing:selfServiceSubscription.description")} ) : null} {!data.canManage ? ( ) : null} {!activationMode && managementSection === "overview" ? (
{data.usage ? : null}
} 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" /> } 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" />
) : null} {activationMode || managementSection === "plan" ? (
{t(activationMode ? "billing:selfServiceSubscription.activation.builder.title" : "billing:selfServiceSubscription.builder.title")} {t(activationMode ? "billing:selfServiceSubscription.activation.builder.description" : "billing:selfServiceSubscription.builder.description")}
{!activationMode ? ( ) : null}
{data.catalog.plans.length === 0 ? ( ) : ( <>
{t("billing:selfServiceSubscription.catalog.title")} { 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 (
{catalogText(t, plan.titleKey)} {plan.descriptionKey ? ( {catalogText(t, plan.descriptionKey)} ) : null}
{plan.badge ? ( {catalogText(t, plan.badge)} ) : null}
{displayPrice ? ( {formatters.currencyFromCents(displayPrice.unitAmountCents, displayPrice.currency)} /{" "} {t(periodLabelKey(displayPrice.billingPeriod))} ) : ( {t("billing:selfServiceSubscription.catalog.noPrice")} )} {plan.packageTerms ? (
{t("billing:selfServiceSubscription.packageTerms.core")}
{t("billing:selfServiceSubscription.packageTerms.seats", { office: plan.packageTerms.officeSeatsIncluded, field: plan.packageTerms.fieldSeatsIncluded, })} {t("billing:selfServiceSubscription.packageTerms.storage", { storage: plan.packageTerms.storageIncludedGb })} {t("billing:selfServiceSubscription.packageTerms.storageGrowth", { storage: plan.packageTerms.storagePerAdditionalSeatGb, })} {!activationMode ? ( <> {t("billing:selfServiceSubscription.packageTerms.annualSepa", { price: formatters.currencyFromCents(plan.packageTerms.annualSepaMonthlyEquivalentCents, "EUR"), })} {t("billing:selfServiceSubscription.packageTerms.extraSeatsMonthly", { office: formatters.currencyFromCents(plan.packageTerms.officeExtraMonthlyCents, "EUR"), field: formatters.currencyFromCents(plan.packageTerms.fieldExtraMonthlyCents, "EUR"), })} {t("billing:selfServiceSubscription.packageTerms.extraSeatsAnnualSepa", { office: formatters.currencyFromCents(plan.packageTerms.officeExtraAnnualSepaCents, "EUR"), field: formatters.currencyFromCents(plan.packageTerms.fieldExtraAnnualSepaCents, "EUR"), })} ) : null}
) : null}
); })}
{selectedPlan && selectedPlan.prices.length > 0 ? (
{t("billing:selfServiceSubscription.price.title")} { const price = selectedPlan.prices.find((candidate) => candidate.id === priceId); if (price) selectPrice(price); }} disabled={!data.canManage} > {selectedPlan.prices.map((price) => ( {formatters.currencyFromCents(price.unitAmountCents, price.currency)} {t("billing:selfServiceSubscription.price.netSuffix")} /{" "} {t(periodLabelKey(price.billingPeriod))} {price.billingPeriod === 4 ? t("billing:selfServiceSubscription.price.annualCommitmentHint") : price.trialDays > 0 ? t("billing:selfServiceSubscription.price.trialDays", { count: price.trialDays }) : t("billing:selfServiceSubscription.price.noTrial")} ))}
) : null}
selectSeatQuantity("office", event.currentTarget.valueAsNumber)} disabled={!data.canManage || !selection} aria-label={t("billing:selfServiceSubscription.seats.officeLabel")} data-ui-id="ui.billing.selfServiceSubscription.officeSeats" /> selectSeatQuantity("field", event.currentTarget.valueAsNumber)} disabled={!data.canManage || !selection} aria-label={t("billing:selfServiceSubscription.seats.fieldLabel")} data-ui-id="ui.billing.selfServiceSubscription.fieldSeats" />
{activationMode && data.storageAddOns.length > 0 ? (
{t("billing:selfServiceSubscription.storage.title")} {t("billing:selfServiceSubscription.storage.description")}
{data.storageAddOns.map((addOn) => ( 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}`} /> ))}
) : null} {previewError ? ( ) : null} {activationMode && selectedPlan && selectedPrice && selection ? (
{t("billing:selfServiceSubscription.activation.summary.title")} {t("billing:selfServiceSubscription.activation.summary.description")}
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" />
) : (
)} )}
) : null} {!activationMode && managementSection === "addons" ? (

{t("billing:selfServiceSubscription.management.overview.addons.title")}

{t("billing:selfServiceSubscription.management.overview.addons.description")}

{data.storageAddOns.length > 0 ? (
} />
{t("billing:selfServiceSubscription.storage.title")} {t("billing:selfServiceSubscription.storage.description")}
{data.storageAddOns.map((addOn) => ( 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}`} /> ))}
{previewError ? ( ) : null}
) : null} {data.emailMarketingAddOns.length > 0 ? (
{t("billing:selfServiceSubscription.emailMarketing.title")} {t("billing:selfServiceSubscription.emailMarketing.description")}
{data.emailMarketingAddOns.some((addOn) => addOn.active) ? ( ) : null} {emailMarketingError && emailMarketingPreview === null ? ( ) : null}
{data.emailMarketingAddOns.map((addOn) => (
{catalogText(t, addOn.title)} {addOn.active ? ( {t("billing:selfServiceSubscription.emailMarketing.active.badge")} ) : null}
{formatters.currencyFromCents(addOn.grossAmountCents, addOn.currency)} / {t(periodLabelKey(3))} {t("billing:selfServiceSubscription.emailMarketing.grossPriceDetail", { net: formatters.currencyFromCents(addOn.amountCents, addOn.currency), rate: addOn.vatRateBasisPoints / 100, })} {t("billing:selfServiceSubscription.emailMarketing.allowance", { count: addOn.monthlyEmailLimit, formattedCount: formatters.number(addOn.monthlyEmailLimit), })}
))}
) : null} {actions.onOpenCustomerPortal ? (
} />
{t("billing:selfServiceSubscription.customerPortal.title")} {t("billing:selfServiceSubscription.customerPortal.description")}
) : null} {data.storageAddOns.length === 0 && data.emailMarketingAddOns.length === 0 && !actions.onOpenCustomerPortal ? ( ) : null}
) : null}
setPreviewOpen(open)}> {preview ? ( <>
{t("billing:selfServiceSubscription.preview.dialog.title")} {t("billing:selfServiceSubscription.preview.dialog.description")}
{preview.officeSeatAmountCents > 0 ? ( ) : null} {preview.fieldSeatAmountCents > 0 ? ( ) : null} {preview.storageAmountCents > 0 ? ( ) : null}
{paymentMethods?.status === "ready" ? (
{t("billing:selfServiceSubscription.paymentMethods.title")} {t( usesCardOnly(paymentMethods) ? "billing:selfServiceSubscription.paymentMethods.cardDescription" : preview.selectedPrice.billingPeriod === 4 ? "billing:selfServiceSubscription.paymentMethods.sepaDescription" : "billing:selfServiceSubscription.paymentMethods.description" )}
{paymentMethods.methods.map((method) => (
{method.label}
))}
) : paymentMethods?.status === "fallback" ? ( ) : paymentMethods?.status === "required_card_unavailable" ? ( ) : null} {checkoutError ? ( ) : null}
) : null}
{ if (!open && !emailMarketingCheckingOut) { setEmailMarketingPreview(null); setEmailMarketingPaymentMethods(null); setSelectedEmailMarketingPaymentMethod(null); setEmailMarketingError(false); } }} > {emailMarketingPreview ? ( <>
{t("billing:selfServiceSubscription.emailMarketing.dialog.title")} {t("billing:selfServiceSubscription.emailMarketing.dialog.description")}
{data.emailMarketingAddOns.some((addOn) => addOn.active) ? ( ) : null} {emailMarketingPaymentMethods?.status === "ready" ? (
{t("billing:selfServiceSubscription.paymentMethods.title")} {t( usesCardOnly(emailMarketingPaymentMethods) ? "billing:selfServiceSubscription.paymentMethods.cardDescription" : "billing:selfServiceSubscription.paymentMethods.description" )}
{emailMarketingPaymentMethods.methods.map((method) => (
{method.label}
))}
) : emailMarketingPaymentMethods?.status === "fallback" ? ( ) : emailMarketingPaymentMethods?.status === "required_card_unavailable" ? ( ) : null} {emailMarketingError ? ( ) : null}
) : null}
(open ? undefined : setCancelProductId(null))}>
{t("billing:subscriptionOverview.cancel.title")} {t("billing:subscriptionOverview.cancel.description", { product: cancelProduct ? catalogText(t, cancelProduct.titleKey) : "", })}
); } 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 (
{title} {description}
); } function SubscriptionUsageCard({ usage }: { usage: NonNullable }): React.JSX.Element { const { t } = useTranslation(); const formatters = useLocaleFormatters(); const storage = usage.storage; return (
{t("billing:selfServiceSubscription.usage.title")} {t("billing:selfServiceSubscription.usage.description")}
{t("billing:selfServiceSubscription.usage.storage.title")} {storage.status === "ready" ? ( {formatBytes(storage.storedBytes + storage.reservedBytes, formatters.number)} ) : null}
{storage.status === "ready" ? ( <> = 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 ? ( {t("billing:selfServiceSubscription.usage.storage.reserved", { value: formatBytes(storage.reservedBytes, formatters.number), })} ) : null} ) : ( {t(`billing:selfServiceSubscription.usage.unavailable.${storage.reason}`)} )}
{t("billing:selfServiceSubscription.usage.emailMarketing.title")} {usage.emailMarketing.status === "ready" ? ( {formatters.number(usage.emailMarketing.used)} ) : null}
{usage.emailMarketing.status === "ready" ? ( <> {usage.emailMarketing.limit === null ? ( {t("billing:selfServiceSubscription.usage.emailMarketing.unlimited")} ) : ( = 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), })} /> )} {t("billing:selfServiceSubscription.usage.emailMarketing.period", { start: formatters.date(usage.emailMarketing.periodStart, { dateStyle: "medium" }), end: formatters.date(usage.emailMarketing.periodEnd, { dateStyle: "medium" }), })} ) : ( {t(`billing:selfServiceSubscription.usage.unavailable.${usage.emailMarketing.reason}`)} )}
); } 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 (
{t("billing:selfServiceSubscription.current.loading")}
); } if (overview.status === "error") { return ( {t("billing:selfServiceSubscription.error.retry")} } /> ); } if (overview.status === "empty") { return (
{t("billing:selfServiceSubscription.current.empty.title")} {t("billing:selfServiceSubscription.current.empty.description")}
); } const cancellableProducts = overview.data.products.filter((product) => product.canCancel); return (
{t("billing:selfServiceSubscription.current.title")} {overview.data.planLabel ? catalogText(t, overview.data.planLabel) : t("billing:selfServiceSubscription.current.noPlan")}
{t(`billing:selfServiceSubscription.current.status.${overview.data.status}`)}
{t("billing:selfServiceSubscription.current.seats")} {seats === null ? t("billing:selfServiceSubscription.current.unknown") : formatters.number(seats)}
{t("billing:selfServiceSubscription.current.effectiveUntil")} {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")}
{cancellableProducts.length > 0 ? (
{cancellableProducts.map((product) => ( ))}
) : null}
); } function PreviewRow({ label, value, strong = false }: { label: string; value: string; strong?: boolean }): React.JSX.Element { return (
{label} {value}
); }