Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+68
@@ -0,0 +1,68 @@
|
||||
// @vitest-environment node
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const billingScreenDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
function source(file: string): string {
|
||||
return fs.readFileSync(path.join(billingScreenDir, file), "utf8");
|
||||
}
|
||||
|
||||
/** A ui id is either written on the element (`data-ui-id`) or handed to a shared screen primitive (`uiId`). */
|
||||
function hasUiId(content: string, id: string): boolean {
|
||||
return content.includes(`data-ui-id="${id}"`) || content.includes(`uiId="${id}"`);
|
||||
}
|
||||
|
||||
function uiIdIndex(content: string, id: string): number {
|
||||
const dataIndex = content.indexOf(`data-ui-id="${id}"`);
|
||||
const propIndex = content.indexOf(`uiId="${id}"`);
|
||||
return [dataIndex, propIndex].filter((index) => index >= 0).sort((a, b) => a - b)[0] ?? -1;
|
||||
}
|
||||
|
||||
describe("AK-P20 billing interim screen contracts", () => {
|
||||
const screens = ["SubscriptionOverviewPage.tsx", "BillingUsagePage.tsx", "BillingPaymentPage.tsx"];
|
||||
|
||||
it.each(screens)("%s separates loading, error, empty, and ready states", (file) => {
|
||||
const content = source(file);
|
||||
expect(content).toContain('vm.status === "idle" || vm.status === "loading"');
|
||||
expect(content).toContain('vm.status === "error"');
|
||||
expect(content).toContain('vm.status === "empty"');
|
||||
expect(content.includes('vm.status === "ready"') || hasUiId(content, "ui.billing.subscriptionOverview.page")).toBe(true);
|
||||
expect(content).toContain("actions.onRetry");
|
||||
expect(content).toContain("billing:states.retry");
|
||||
});
|
||||
|
||||
it.each(screens)("%s stays app-chrome-free and uses synchronized UI components", (file) => {
|
||||
const content = source(file);
|
||||
expect(content).toContain('from "~/ui/components/');
|
||||
expect(content).not.toContain("DefaultPageLayout");
|
||||
expect(content).not.toContain("EditPageLayout");
|
||||
expect(content).not.toContain("Sidebar");
|
||||
});
|
||||
|
||||
// The heading comes from the shared PageHeader (screens/shared/PageShell.tsx), which renders the single <h1>.
|
||||
it.each(screens)("%s exposes a semantic main heading", (file) => {
|
||||
const content = source(file);
|
||||
expect(content).toContain("<PageHeader");
|
||||
expect(content).toContain("shared/PageShell");
|
||||
});
|
||||
|
||||
it("exposes stable selectors for customer-facing billing actions", () => {
|
||||
const subscription = source("SubscriptionOverviewPage.tsx");
|
||||
const payment = source("BillingPaymentPage.tsx");
|
||||
expect(subscription).toContain('data-ui-id="ui.billing.subscriptionOverview.contact"');
|
||||
expect(subscription).toContain("actions.onOpenContact");
|
||||
expect(uiIdIndex(subscription, "ui.billing.subscriptionOverview.contact")).toBeLessThan(
|
||||
uiIdIndex(subscription, "ui.billing.subscriptionOverview.page")
|
||||
);
|
||||
expect(subscription).not.toContain("<a ");
|
||||
expect(subscription).toContain('data-ui-id="ui.billing.subscriptionOverview.cancel"');
|
||||
expect(subscription).toContain('data-ui-id="ui.billing.subscriptionOverview.cancelConfirm"');
|
||||
expect(subscription).toContain('aria-label={t("billing:subscriptionOverview.cancel.title")}');
|
||||
expect(payment).toContain('data-ui-id="ui.billing.payment.invoiceDownload"');
|
||||
expect(payment).toContain("actions.onDownloadInvoice");
|
||||
expect(payment).not.toContain("<a ");
|
||||
});
|
||||
});
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
// Guards the in-app invoice preview: every row opens its own PDF below the
|
||||
// table, the row button toggles it shut again, and the panel's close button
|
||||
// does the same. The frame points at the inline variant of the download route,
|
||||
// so the preview never bypasses the permission check the download runs.
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { buildBillingPaymentVM } from "@hivegrid/view-models";
|
||||
import { BillingPaymentPage } from "./BillingPaymentPage";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string, options?: Record<string, unknown>) => (options?.invoice ? `${key}:${String(options.invoice)}` : key), i18n: { language: "de" } }),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/format", () => ({
|
||||
useLocaleFormatters: () => ({
|
||||
number: (value: number) => String(value),
|
||||
date: (value: string) => value,
|
||||
currencyFromCents: (cents: number) => String(cents),
|
||||
}),
|
||||
}));
|
||||
|
||||
function invoice(id: string, number: string, overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id,
|
||||
number,
|
||||
issuingDate: "2026-07-10",
|
||||
amountCents: 4_900,
|
||||
currency: "eur",
|
||||
status: "finalized",
|
||||
paymentStatus: "succeeded",
|
||||
invoiceType: "subscription",
|
||||
downloadHref: `/acme/settings/subscription/invoices/${id}/download`,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function renderPage(invoices = [invoice("invoice_1", "LAG-001"), invoice("invoice_2", "LAG-002", { issuingDate: "2026-06-10" })]) {
|
||||
const onDownloadInvoice = vi.fn();
|
||||
render(<BillingPaymentPage vm={buildBillingPaymentVM({ invoices })} actions={{ onDownloadInvoice, onRetry: vi.fn() }} embedded />);
|
||||
return { onDownloadInvoice };
|
||||
}
|
||||
|
||||
function previewButtons(): HTMLElement[] {
|
||||
return Array.from(document.querySelectorAll("[data-ui-id='ui.billing.payment.invoicePreview']"));
|
||||
}
|
||||
|
||||
function previewFrame(): HTMLIFrameElement | null {
|
||||
return document.querySelector("[data-ui-id='ui.billing.payment.invoicePreviewFrame']");
|
||||
}
|
||||
|
||||
describe("BillingPaymentPage invoice preview", () => {
|
||||
it("opens the picked invoice inline below the table", () => {
|
||||
renderPage();
|
||||
expect(previewFrame()).toBeNull();
|
||||
|
||||
fireEvent.click(previewButtons()[1]!);
|
||||
|
||||
expect(previewFrame()?.getAttribute("src")).toBe("/acme/settings/subscription/invoices/invoice_2/download?disposition=inline");
|
||||
expect(screen.getByText("billing:billingPayment.invoices.previewTitle:LAG-002")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("switches the frame to another invoice without closing it", () => {
|
||||
renderPage();
|
||||
fireEvent.click(previewButtons()[1]!);
|
||||
fireEvent.click(previewButtons()[0]!);
|
||||
|
||||
expect(previewFrame()?.getAttribute("src")).toBe("/acme/settings/subscription/invoices/invoice_1/download?disposition=inline");
|
||||
});
|
||||
|
||||
it("closes from the row button that opened it and from the panel", () => {
|
||||
renderPage();
|
||||
fireEvent.click(previewButtons()[0]!);
|
||||
fireEvent.click(previewButtons()[0]!);
|
||||
expect(previewFrame()).toBeNull();
|
||||
|
||||
fireEvent.click(previewButtons()[0]!);
|
||||
fireEvent.click(document.querySelector("[data-ui-id='ui.billing.payment.invoicePreviewClose']")!);
|
||||
expect(previewFrame()).toBeNull();
|
||||
});
|
||||
|
||||
it("offers neither preview nor download for a voided invoice", () => {
|
||||
renderPage([invoice("voided", "LAG-003", { status: "voided", downloadHref: null })]);
|
||||
|
||||
expect(previewButtons()).toHaveLength(0);
|
||||
expect(screen.getByText("billing:billingPayment.invoices.unavailable")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FeatherCreditCard, FeatherDownload, FeatherEye, FeatherFileText, FeatherReceipt, FeatherX } from "@subframe/core";
|
||||
import type { BillingPaymentInvoiceVM, BillingPaymentVM } 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 { EmptyState } from "~/ui/components/EmptyState";
|
||||
import { Loader } from "~/ui/components/Loader";
|
||||
import { StatsCard } from "~/ui/components/StatsCard";
|
||||
import { Table } from "~/ui/components/Table";
|
||||
|
||||
export type BillingPaymentActions = {
|
||||
readonly onDownloadInvoice: (href: string) => void;
|
||||
readonly onRetry: () => void;
|
||||
};
|
||||
|
||||
function invoiceTone(tone: BillingPaymentInvoiceVM["tone"]): React.ComponentProps<typeof BadgeFeedback>["farbe"] {
|
||||
if (tone === "positive") return "subtle-positive";
|
||||
if (tone === "negative") return "subtle-negative";
|
||||
if (tone === "warning") return "subtle-warning";
|
||||
return "subtle-neutral";
|
||||
}
|
||||
|
||||
/** D-P20 S03 interim: Lago invoices and their Mollie payment result. */
|
||||
export function BillingPaymentPage({
|
||||
vm,
|
||||
actions,
|
||||
embedded = false,
|
||||
}: {
|
||||
vm: BillingPaymentVM;
|
||||
actions: BillingPaymentActions;
|
||||
/** Inside the Abrechnung hub (AK-SET-01) the hub owns the header — see PageIntro. */
|
||||
embedded?: boolean;
|
||||
}): React.JSX.Element {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
// Which invoice is open in the preview frame below the table. Local view
|
||||
// state: the frame streams the same route the download button opens, so the
|
||||
// route has nothing to prepare for it.
|
||||
const [previewInvoiceId, setPreviewInvoiceId] = useState<string | null>(null);
|
||||
const previewInvoice = vm.status === "ready" ? (vm.data.invoices.find((invoice) => invoice.id === previewInvoiceId) ?? null) : null;
|
||||
|
||||
return (
|
||||
<PageShell uiId="ui.billing.payment.page" className="bg-surface-neutral-primary">
|
||||
{embedded ? null : (
|
||||
<PageHeader
|
||||
icon={<FeatherReceipt className={PAGE_HEADER_ICON_CLASS} />}
|
||||
title={t("billing:billingPayment.title")}
|
||||
subtitle={t("billing:billingPayment.description")}
|
||||
/>
|
||||
)}
|
||||
<PageBody className="items-start">
|
||||
{embedded ? <PageIntro uiId="ui.billing.payment.intro">{t("billing:billingPayment.description")}</PageIntro> : null}
|
||||
{vm.status === "idle" || vm.status === "loading" ? (
|
||||
<Card>
|
||||
<div className="flex w-full items-center gap-3" data-ui-id="ui.billing.payment.loading">
|
||||
<Loader />
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
|
||||
{t("billing:billingPayment.loading.title")}
|
||||
</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("billing:billingPayment.loading.description")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
) : vm.status === "error" ? (
|
||||
<EmptyState
|
||||
outlined
|
||||
variant="error"
|
||||
title={t("billing:billingPayment.error.title")}
|
||||
body={t(vm.error.messageKey)}
|
||||
action={
|
||||
<Button variant="tertiary" onClick={actions.onRetry} data-ui-id="ui.billing.payment.retry">
|
||||
{t("billing:states.retry")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : vm.status === "empty" ? (
|
||||
<EmptyState
|
||||
outlined
|
||||
title={t("billing:billingPayment.empty.title")}
|
||||
body={t("billing:billingPayment.empty.description")}
|
||||
action={
|
||||
<Button variant="tertiary" onClick={actions.onRetry}>
|
||||
{t("billing:states.refresh")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : vm.status === "ready" ? (
|
||||
<>
|
||||
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4">
|
||||
<StatsCard
|
||||
trend="neutral"
|
||||
icon={<FeatherFileText />}
|
||||
label={t("billing:billingPayment.summary.invoices")}
|
||||
value={formatters.number(vm.data.invoices.length)}
|
||||
percentage={t("billing:billingPayment.summary.lago")}
|
||||
/>
|
||||
<StatsCard
|
||||
trend={vm.data.latestPaymentStatus === "succeeded" || vm.data.latestPaymentStatus === "paid" ? "positive" : "neutral"}
|
||||
icon={<FeatherCreditCard />}
|
||||
label={t("billing:billingPayment.summary.latestPayment")}
|
||||
value={t(vm.data.latestPaymentStatusLabelKey)}
|
||||
percentage={t(
|
||||
vm.data.hasMollieReference ? "billing:billingPayment.summary.mollieConnected" : "billing:billingPayment.summary.noPaymentReference"
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Alert notDismissible variant="information" title={t(vm.data.helpTitleKey)} description={t(vm.data.helpDescriptionKey)} />
|
||||
|
||||
<Card data-ui-id="ui.billing.payment.invoices">
|
||||
<div className="flex w-full flex-col items-start">
|
||||
<span className="text-body-large font-body-large text-text-neutral-primary">{t("billing:billingPayment.invoices.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("billing:billingPayment.invoices.description")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-full overflow-x-auto">
|
||||
<Table
|
||||
header={
|
||||
<Table.HeaderRow>
|
||||
<Table.HeaderCell>{t("billing:billingPayment.invoices.columns.invoice")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:billingPayment.invoices.columns.date")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:billingPayment.invoices.columns.amount")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:billingPayment.invoices.columns.invoiceStatus")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:billingPayment.invoices.columns.paymentStatus")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:billingPayment.invoices.columns.download")}</Table.HeaderCell>
|
||||
</Table.HeaderRow>
|
||||
}
|
||||
>
|
||||
{vm.data.invoices.map((invoice) => (
|
||||
<Table.Row key={invoice.id}>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">{invoice.number ?? invoice.id}</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
|
||||
{invoice.issuingDate ? formatters.date(invoice.issuingDate, { dateStyle: "medium" }) : t("shared.unknown")}
|
||||
</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
|
||||
{invoice.amountCents !== null && invoice.currency
|
||||
? formatters.currencyFromCents(invoice.amountCents, invoice.currency)
|
||||
: t("shared.unknown")}
|
||||
</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<BadgeFeedback farbe="subtle-neutral" size="small">
|
||||
{t(invoice.statusLabelKey)}
|
||||
</BadgeFeedback>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<BadgeFeedback farbe={invoiceTone(invoice.tone)} size="small">
|
||||
{t(invoice.paymentStatusLabelKey)}
|
||||
</BadgeFeedback>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
{invoice.downloadHref ? (
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Preview toggles: the same button closes the frame again. */}
|
||||
<Button
|
||||
variant={previewInvoiceId === invoice.id ? "secondary" : "tertiary"}
|
||||
size="small"
|
||||
icon={<FeatherEye />}
|
||||
onClick={() => setPreviewInvoiceId(previewInvoiceId === invoice.id ? null : invoice.id)}
|
||||
data-ui-id="ui.billing.payment.invoicePreview"
|
||||
>
|
||||
{t("billing:billingPayment.invoices.preview")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="tertiary"
|
||||
size="small"
|
||||
icon={<FeatherDownload />}
|
||||
onClick={() => actions.onDownloadInvoice(invoice.downloadHref!)}
|
||||
data-ui-id="ui.billing.payment.invoiceDownload"
|
||||
>
|
||||
{t("billing:billingPayment.invoices.download")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
|
||||
{t("billing:billingPayment.invoices.unavailable")}
|
||||
</span>
|
||||
)}
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
))}
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{/* Preview opens below the list and closes from its own header or
|
||||
from the row button that opened it. The frame streams the
|
||||
invoice route with ?disposition=inline — same permission check
|
||||
and same bytes as the download. */}
|
||||
{previewInvoice?.previewHref ? (
|
||||
<div
|
||||
className="flex w-full flex-col gap-3 border-t border-solid border-border-default pt-4"
|
||||
data-ui-id="ui.billing.payment.invoicePreviewPanel"
|
||||
>
|
||||
<div className="flex w-full flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
|
||||
{t("billing:billingPayment.invoices.previewTitle", { invoice: previewInvoice.number ?? previewInvoice.id })}
|
||||
</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("billing:billingPayment.invoices.previewHint")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="tertiary"
|
||||
size="small"
|
||||
icon={<FeatherDownload />}
|
||||
onClick={() => actions.onDownloadInvoice(previewInvoice.downloadHref!)}
|
||||
>
|
||||
{t("billing:billingPayment.invoices.download")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="tertiary"
|
||||
size="small"
|
||||
icon={<FeatherX />}
|
||||
onClick={() => setPreviewInvoiceId(null)}
|
||||
data-ui-id="ui.billing.payment.invoicePreviewClose"
|
||||
>
|
||||
{t("billing:billingPayment.invoices.previewClose")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<iframe
|
||||
key={previewInvoice.id}
|
||||
src={previewInvoice.previewHref}
|
||||
title={t("billing:billingPayment.invoices.previewTitle", { invoice: previewInvoice.number ?? previewInvoice.id })}
|
||||
className="h-[720px] max-h-[70vh] w-full rounded-md border border-solid border-border-default bg-surface-neutral-secondary"
|
||||
data-ui-id="ui.billing.payment.invoicePreviewFrame"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</Card>
|
||||
</>
|
||||
) : null}
|
||||
</PageBody>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FeatherActivity, FeatherGauge, FeatherHardDrive } from "@subframe/core";
|
||||
import type { BillingUsageMetricVM, BillingUsageVM } 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 { Card } from "~/ui/components/Card";
|
||||
import { EmptyState } from "~/ui/components/EmptyState";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Loader } from "~/ui/components/Loader";
|
||||
import { Progress } from "~/ui/components/Progress";
|
||||
|
||||
export type BillingUsageActions = { readonly onRetry: () => void };
|
||||
|
||||
function formatMetric(metric: BillingUsageMetricVM, number: (value: number, options?: Intl.NumberFormatOptions) => string): string {
|
||||
if (metric.valueFormat === "number") return number(metric.quantity);
|
||||
const units = ["bytes", "kb", "mb", "gb", "tb"] as const;
|
||||
let value = metric.quantity;
|
||||
let unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
return `${number(value, { maximumFractionDigits: unitIndex === 0 ? 0 : 1 })} ${units[unitIndex].toUpperCase()}`;
|
||||
}
|
||||
|
||||
/** D-P20 S02 interim: v1 counters only, with no usage-billing affordance. */
|
||||
export function BillingUsagePage({
|
||||
vm,
|
||||
actions,
|
||||
embedded = false,
|
||||
}: {
|
||||
vm: BillingUsageVM;
|
||||
actions: BillingUsageActions;
|
||||
/** Inside the Abrechnung hub (AK-SET-01) the hub owns the header — see PageIntro. */
|
||||
embedded?: boolean;
|
||||
}): React.JSX.Element {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
return (
|
||||
<PageShell uiId="ui.billing.usage.page" className="bg-surface-neutral-primary">
|
||||
{embedded ? null : (
|
||||
<PageHeader
|
||||
icon={<FeatherGauge className={PAGE_HEADER_ICON_CLASS} />}
|
||||
title={t("billing:usage.title")}
|
||||
subtitle={t("billing:usage.description")}
|
||||
/>
|
||||
)}
|
||||
<PageBody className="items-start">
|
||||
{embedded ? <PageIntro uiId="ui.billing.usage.intro">{t("billing:usage.description")}</PageIntro> : null}
|
||||
{vm.status === "idle" || vm.status === "loading" ? (
|
||||
<Card>
|
||||
<div className="flex w-full items-center gap-3" data-ui-id="ui.billing.usage.loading">
|
||||
<Loader />
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("billing:usage.loading.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("billing:usage.loading.description")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
) : vm.status === "error" ? (
|
||||
<EmptyState
|
||||
outlined
|
||||
variant="error"
|
||||
title={t("billing:usage.error.title")}
|
||||
body={t(vm.error.messageKey)}
|
||||
action={
|
||||
<Button variant="tertiary" onClick={actions.onRetry} data-ui-id="ui.billing.usage.retry">
|
||||
{t("billing:states.retry")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : vm.status === "empty" ? (
|
||||
<EmptyState
|
||||
outlined
|
||||
title={t("billing:usage.emptyTitle")}
|
||||
body={t("billing:usage.empty")}
|
||||
action={
|
||||
<Button variant="tertiary" onClick={actions.onRetry}>
|
||||
{t("billing:states.refresh")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : vm.status === "ready" ? (
|
||||
<>
|
||||
{vm.data.unavailableMetrics.includes("storage_bytes") ? (
|
||||
<div className="flex w-full flex-col items-start gap-3" data-ui-id="ui.billing.usage.storageUnavailable">
|
||||
<Alert
|
||||
notDismissible
|
||||
variant="warning"
|
||||
title={t("billing:usage.error.title")}
|
||||
description={t("billing:usage.error.description")}
|
||||
/>
|
||||
<Button variant="tertiary" onClick={actions.onRetry} data-ui-id="ui.billing.usage.retryStorage">
|
||||
{t("billing:states.retry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<Card variant="neutral">
|
||||
<div className="mobile:flex-col mobile:items-start flex w-full items-center justify-between gap-4">
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="text-body-large font-body-large text-text-neutral-primary">{t("billing:usage.currentPeriod")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("billing:usage.periodDescription")}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-secondary">
|
||||
{formatters.date(vm.data.periodStart, { dateStyle: "medium" })} – {formatters.date(vm.data.periodEnd, { dateStyle: "medium" })}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{vm.data.hasExceeded ? (
|
||||
<Alert
|
||||
notDismissible
|
||||
variant="error"
|
||||
title={t("billing:usage.alert.exceeded.title")}
|
||||
description={t("billing:usage.alert.exceeded.description")}
|
||||
/>
|
||||
) : vm.data.hasWarning ? (
|
||||
<Alert
|
||||
notDismissible
|
||||
variant="warning"
|
||||
title={t("billing:usage.alert.warning.title")}
|
||||
description={t("billing:usage.alert.warning.description")}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4">
|
||||
{vm.data.metrics.map((metric) => {
|
||||
const Icon = metric.metricCode === "storage_bytes" ? FeatherHardDrive : FeatherActivity;
|
||||
return (
|
||||
<Card key={metric.metricCode} variant={metric.tone === "danger" ? "negative" : metric.tone === "warning" ? "warning" : "default"}>
|
||||
<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(metric.labelKey)}</span>
|
||||
<span className="text-subtitle-0 font-subtitle-0 text-text-neutral-primary">{formatMetric(metric, formatters.number)}</span>
|
||||
</div>
|
||||
<Icon className="text-heading- font-heading- text-icon-neutral-tertiary" />
|
||||
</div>
|
||||
{metric.quota === null ? (
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("billing:usage.unlimited")}</span>
|
||||
) : (
|
||||
<Progress
|
||||
className="w-full"
|
||||
state={metric.exceeded ? "error" : "uploading"}
|
||||
value={metric.percentUsed ?? 0}
|
||||
label={t("billing:usage.quota", { quota: formatMetric({ ...metric, quantity: metric.quota }, formatters.number) })}
|
||||
statusText={t("billing:usage.remaining", {
|
||||
remaining: formatMetric({ ...metric, quantity: metric.remaining ?? 0 }, formatters.number),
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</PageBody>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FeatherArrowRight, FeatherCheckCircle, FeatherCreditCard, FeatherMail, FeatherRefreshCw, FeatherShieldCheck } from "@subframe/core";
|
||||
|
||||
import Logo from "~/components/brand/Logo";
|
||||
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
import { EmptyState } from "~/ui/components/EmptyState";
|
||||
import { IconWithBackground } from "~/ui/components/IconWithBackground";
|
||||
import { Loader } from "~/ui/components/Loader";
|
||||
import { StepperHorizontal } from "~/ui/components/StepperHorizontal";
|
||||
|
||||
export type CheckoutSuccessPageProps = {
|
||||
readonly state: "success" | "processing" | "cancelled" | "failed" | "expired" | "error" | "invalid";
|
||||
readonly activationKind: "paid" | "trial" | "confirmed";
|
||||
readonly homeHref: string;
|
||||
readonly workspaceName: string;
|
||||
readonly planTitle?: string;
|
||||
readonly formattedPrice?: string | null;
|
||||
readonly interval?: string | null;
|
||||
readonly nextInvoice?: string | null;
|
||||
readonly emailMarketingFollowUpTitle?: string | null;
|
||||
readonly errorMessage?: string;
|
||||
readonly actions: {
|
||||
readonly onStartSetup: () => void;
|
||||
readonly onOpenBilling: () => void;
|
||||
readonly onRetry: () => void;
|
||||
readonly onRestartCheckout: () => void;
|
||||
readonly onOpenEmailMarketingFollowUp?: () => void;
|
||||
};
|
||||
};
|
||||
|
||||
export function CheckoutSuccessPage({
|
||||
state,
|
||||
activationKind,
|
||||
homeHref,
|
||||
workspaceName,
|
||||
planTitle,
|
||||
formattedPrice,
|
||||
interval,
|
||||
nextInvoice,
|
||||
emailMarketingFollowUpTitle,
|
||||
errorMessage,
|
||||
actions,
|
||||
}: CheckoutSuccessPageProps) {
|
||||
const { t } = useTranslation();
|
||||
const copyKey = `settings.subscription.checkout.success.${activationKind}`;
|
||||
|
||||
if (state !== "success") {
|
||||
const stateCopyKey = `settings.subscription.checkout.success.${state}`;
|
||||
const canRetry = state !== "invalid";
|
||||
const requiresNewCheckout = state === "cancelled" || state === "failed" || state === "expired";
|
||||
return (
|
||||
<main
|
||||
className="bg-surface-neutral-secondary flex min-h-screen flex-col items-center gap-8 px-4 py-10"
|
||||
data-ui-id={`ui.subscription.checkout.success.${state}`}
|
||||
>
|
||||
<Logo to={homeHref} size="h-12" />
|
||||
<div className="w-full max-w-xl">
|
||||
{state === "processing" ? (
|
||||
<Card className="items-center gap-5 py-10 text-center" data-ui-id="ui.subscription.checkout.success.processing.status">
|
||||
<Loader size="large" />
|
||||
<div className="flex flex-col items-center gap-2" role="status" aria-live="polite">
|
||||
<span className="text-heading-2 font-heading-2 text-text-neutral-primary" role="heading" aria-level={1}>
|
||||
{t(`${stateCopyKey}.title`)}
|
||||
</span>
|
||||
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
|
||||
{t(`${stateCopyKey}.body`)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap justify-center gap-2">
|
||||
<Button variant="secondary" icon={<FeatherRefreshCw />} onClick={actions.onRetry}>
|
||||
{t("settings.subscription.checkout.success.retry")}
|
||||
</Button>
|
||||
<Button variant="tertiary" onClick={actions.onOpenBilling}>
|
||||
{t("settings.subscription.checkout.success.goToSubscription")}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
<EmptyState
|
||||
outlined
|
||||
variant="error"
|
||||
title={
|
||||
<span role="heading" aria-level={1}>
|
||||
{t(`${stateCopyKey}.title`)}
|
||||
</span>
|
||||
}
|
||||
body={errorMessage || t(`${stateCopyKey}.body`)}
|
||||
action={
|
||||
<div className="flex flex-wrap justify-center gap-2">
|
||||
{canRetry ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={requiresNewCheckout ? <FeatherArrowRight /> : <FeatherRefreshCw />}
|
||||
onClick={requiresNewCheckout ? actions.onRestartCheckout : actions.onRetry}
|
||||
>
|
||||
{t(
|
||||
requiresNewCheckout
|
||||
? "settings.subscription.checkout.success.restartCheckout"
|
||||
: "settings.subscription.checkout.success.retry"
|
||||
)}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="tertiary" onClick={actions.onOpenBilling}>
|
||||
{t("settings.subscription.checkout.success.goToSubscription")}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="bg-surface-neutral-secondary min-h-screen px-4 py-8 sm:px-6 sm:py-10" data-ui-id="ui.subscription.checkout.success.page">
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col items-center gap-8">
|
||||
<Logo to={homeHref} size="h-12" />
|
||||
<StepperHorizontal aria-label={t("settings.subscription.checkout.success.stepper.label")}>
|
||||
<StepperHorizontal.Step variant="completed" firstStep stepNumber="1" label={t("settings.subscription.checkout.success.stepper.account")} />
|
||||
<StepperHorizontal.Step variant="completed" stepNumber="2" label={t("settings.subscription.checkout.success.stepper.payment")} />
|
||||
<StepperHorizontal.Step variant="active" lastStep stepNumber="3" label={t("settings.subscription.checkout.success.stepper.setup")} />
|
||||
</StepperHorizontal>
|
||||
|
||||
<div className="flex flex-col items-center gap-3 text-center" data-ui-id="ui.subscription.checkout.success.hero">
|
||||
<IconWithBackground variant="success" size="extra-large" round icon={<FeatherCheckCircle />} />
|
||||
<BadgeFeedback farbe="subtle-positive">{t(`${copyKey}.badge`)}</BadgeFeedback>
|
||||
<h1 className="text-heading-1 font-heading-1 text-text-neutral-primary">{t(`${copyKey}.title`)}</h1>
|
||||
<p className="text-body-large-0 font-body-large-0 text-text-neutral-secondary max-w-xl">{t(`${copyKey}.description`, { workspaceName })}</p>
|
||||
</div>
|
||||
|
||||
<Card size="large" className="gap-5" data-ui-id="ui.subscription.checkout.success.receipt">
|
||||
<div className="flex w-full items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<IconWithBackground variant="neutral" icon={<FeatherCreditCard />} />
|
||||
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">{t("settings.subscription.checkout.success.orderSummary")}</span>
|
||||
</div>
|
||||
<BadgeFeedback farbe="subtle-positive">{t(`${copyKey}.status`)}</BadgeFeedback>
|
||||
</div>
|
||||
<div className="bg-surface-neutral-primary flex w-full flex-col gap-3 rounded-md px-4 py-4">
|
||||
<ReceiptRow
|
||||
label={t("settings.subscription.checkout.success.fields.plan")}
|
||||
value={planTitle || t("settings.subscription.checkout.success.fields.planFallback")}
|
||||
/>
|
||||
{formattedPrice ? <ReceiptRow label={t(`${copyKey}.priceLabel`)} value={`${formattedPrice}${interval ? ` / ${interval}` : ""}`} /> : null}
|
||||
{nextInvoice ? <ReceiptRow label={t(`${copyKey}.nextBillingLabel`)} value={nextInvoice} /> : null}
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<IconWithBackground variant="success" size="small" icon={<FeatherShieldCheck />} />
|
||||
<p className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t(`${copyKey}.secureNote`)}</p>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{emailMarketingFollowUpTitle && actions.onOpenEmailMarketingFollowUp ? (
|
||||
<Card variant="neutral" data-ui-id="ui.subscription.checkout.success.emailMarketingFollowUp">
|
||||
<div className="flex w-full flex-col gap-4 sm:flex-row sm:items-start">
|
||||
<div className="flex min-w-0 grow items-start gap-3">
|
||||
<IconWithBackground variant="information" icon={<FeatherMail />} />
|
||||
<div className="flex min-w-0 grow basis-0 flex-col gap-1">
|
||||
<span className="text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary">
|
||||
{t("settings.subscription.checkout.success.emailMarketingFollowUp.title")}
|
||||
</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
|
||||
{t("settings.subscription.checkout.success.emailMarketingFollowUp.description", { package: emailMarketingFollowUpTitle })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button className="w-full sm:w-auto sm:shrink-0" variant="secondary" onClick={actions.onOpenEmailMarketingFollowUp}>
|
||||
{t("settings.subscription.checkout.success.emailMarketingFollowUp.action")}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<div className="flex w-full flex-col items-stretch gap-3 sm:flex-row sm:justify-center">
|
||||
<Button size="large" iconRight={<FeatherArrowRight />} onClick={actions.onStartSetup} data-ui-id="ui.subscription.checkout.success.setupAction">
|
||||
{t("settings.subscription.checkout.success.setupAction")}
|
||||
</Button>
|
||||
<Button size="large" variant="tertiary" onClick={actions.onOpenBilling} data-ui-id="ui.subscription.checkout.success.subscriptionLink">
|
||||
{t("settings.subscription.checkout.success.goToSubscription")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function ReceiptRow({ label, value }: { readonly label: string; readonly value: string }) {
|
||||
return (
|
||||
<div className="flex w-full flex-wrap items-baseline justify-between gap-2">
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{label}</span>
|
||||
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSelfServiceSubscriptionPageVM } from "@hivegrid/view-models";
|
||||
|
||||
import {
|
||||
applyRecommendedSubscriptionPlan,
|
||||
initialActivationSubscriptionSelection,
|
||||
initialSelfServiceSubscriptionSelection,
|
||||
type SelfServiceSubscriptionPlanAdvice,
|
||||
} from "./SelfServiceSubscriptionPage";
|
||||
import { clearPersistedCheckoutRequest, stableCheckoutRequestKey, type SelfServiceSubscriptionSelection } from "./checkout-request";
|
||||
|
||||
const plans = [
|
||||
{
|
||||
id: "product_starter",
|
||||
code: "starter",
|
||||
titleKey: "Core",
|
||||
descriptionKey: "Core plan",
|
||||
badge: null,
|
||||
quantityMode: "flat" as const,
|
||||
features: [],
|
||||
prices: [{ id: "price_starter", billingPeriod: 3, currency: "EUR", unitAmountCents: 19_900, trialDays: 0 }],
|
||||
},
|
||||
{
|
||||
id: "product_pro",
|
||||
code: "pro",
|
||||
titleKey: "Swarm",
|
||||
descriptionKey: "Swarm plan",
|
||||
badge: null,
|
||||
quantityMode: "flat" as const,
|
||||
features: [],
|
||||
prices: [{ id: "price_pro", billingPeriod: 3, currency: "EUR", unitAmountCents: 49_900, trialDays: 0 }],
|
||||
},
|
||||
] as const;
|
||||
|
||||
const effectiveAtByChangeKind = {
|
||||
new: "immediate",
|
||||
upgrade: "immediate",
|
||||
downgrade: "period_end",
|
||||
billing_period_change: "period_end",
|
||||
seat_increase: "immediate",
|
||||
seat_decrease: "period_end",
|
||||
configuration_increase: "immediate",
|
||||
configuration_decrease: "period_end",
|
||||
configuration_change: "period_end",
|
||||
unchanged: "immediate",
|
||||
} as const;
|
||||
|
||||
describe("registration billing preference", () => {
|
||||
it("preselects the persisted registration price for a tenant without a subscription", () => {
|
||||
const vm = buildSelfServiceSubscriptionPageVM({
|
||||
overview: { status: "empty" },
|
||||
catalog: { plans },
|
||||
managementPolicy: { planOrder: ["starter", "pro"], effectiveAtByChangeKind },
|
||||
minimumSeatQuantity: 1,
|
||||
minimumSeatQuantities: { office: 1, field: 0 },
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
preferredSelection: {
|
||||
planId: "product_pro",
|
||||
priceId: "price_pro",
|
||||
officeSeatQuantity: 5,
|
||||
fieldSeatQuantity: 15,
|
||||
},
|
||||
});
|
||||
|
||||
expect(initialSelfServiceSubscriptionSelection(vm)).toMatchObject({
|
||||
productId: "product_pro",
|
||||
priceId: "price_pro",
|
||||
officeSeatQuantity: 5,
|
||||
fieldSeatQuantity: 15,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an active subscription selection ahead of a stale registration preference", () => {
|
||||
const vm = buildSelfServiceSubscriptionPageVM({
|
||||
overview: { status: "empty" },
|
||||
catalog: { plans },
|
||||
managementPolicy: { planOrder: ["starter", "pro"], effectiveAtByChangeKind },
|
||||
minimumSeatQuantity: 1,
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
currentSelection: {
|
||||
planId: "product_starter",
|
||||
planCode: "starter",
|
||||
priceId: "price_starter",
|
||||
seatQuantity: 1,
|
||||
},
|
||||
preferredSelection: { planId: "product_pro", priceId: "price_pro" },
|
||||
});
|
||||
|
||||
expect(initialSelfServiceSubscriptionSelection(vm)).toMatchObject({
|
||||
productId: "product_starter",
|
||||
priceId: "price_starter",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const coreSelection: SelfServiceSubscriptionSelection = {
|
||||
productId: "product_starter",
|
||||
priceId: "price_starter",
|
||||
billingPeriod: 3,
|
||||
currency: "EUR",
|
||||
officeSeatQuantity: 5,
|
||||
fieldSeatQuantity: 15,
|
||||
storageAddOnCodes: ["storage_100"],
|
||||
};
|
||||
|
||||
const swarmAdvice: SelfServiceSubscriptionPlanAdvice = {
|
||||
plans: [
|
||||
{
|
||||
planId: "product_starter",
|
||||
priceId: "price_starter",
|
||||
amountCents: 62_600,
|
||||
currency: "EUR",
|
||||
billingPeriod: 3,
|
||||
recommended: false,
|
||||
},
|
||||
{
|
||||
planId: "product_pro",
|
||||
priceId: "price_pro",
|
||||
amountCents: 49_900,
|
||||
currency: "EUR",
|
||||
billingPeriod: 3,
|
||||
recommended: true,
|
||||
},
|
||||
],
|
||||
selectedPriceId: "price_pro",
|
||||
recommendedPriceId: "price_pro",
|
||||
officeSeatQuantity: 5,
|
||||
fieldSeatQuantity: 15,
|
||||
};
|
||||
|
||||
describe("activation plan advice", () => {
|
||||
it("starts with the server recommendation when no plan was selected explicitly", () => {
|
||||
const vm = buildSelfServiceSubscriptionPageVM({
|
||||
overview: { status: "empty" },
|
||||
catalog: { plans },
|
||||
managementPolicy: { planOrder: ["starter", "pro"], effectiveAtByChangeKind },
|
||||
minimumSeatQuantity: 20,
|
||||
minimumSeatQuantities: { office: 5, field: 15 },
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
});
|
||||
|
||||
expect(initialActivationSubscriptionSelection(vm, swarmAdvice)).toMatchObject({
|
||||
productId: "product_pro",
|
||||
priceId: "price_pro",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not replace an explicitly persisted plan during activation initialization", () => {
|
||||
const vm = buildSelfServiceSubscriptionPageVM({
|
||||
overview: { status: "empty" },
|
||||
catalog: { plans },
|
||||
managementPolicy: { planOrder: ["starter", "pro"], effectiveAtByChangeKind },
|
||||
minimumSeatQuantity: 1,
|
||||
minimumSeatQuantities: { office: 1, field: 0 },
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
preferredSelection: {
|
||||
planId: "product_starter",
|
||||
priceId: "price_starter",
|
||||
officeSeatQuantity: 5,
|
||||
fieldSeatQuantity: 15,
|
||||
},
|
||||
});
|
||||
|
||||
expect(initialActivationSubscriptionSelection(vm, swarmAdvice)).toMatchObject({
|
||||
productId: "product_starter",
|
||||
priceId: "price_starter",
|
||||
});
|
||||
});
|
||||
|
||||
it("applies the server-recommended plan while retaining seats and add-ons", () => {
|
||||
expect(applyRecommendedSubscriptionPlan(coreSelection, swarmAdvice, false)).toEqual({
|
||||
...coreSelection,
|
||||
productId: "product_pro",
|
||||
priceId: "price_pro",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a deliberately selected different plan when fresh advice arrives", () => {
|
||||
expect(applyRecommendedSubscriptionPlan(coreSelection, swarmAdvice, true)).toBe(coreSelection);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkout request recovery", () => {
|
||||
function memoryStorage() {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key: string) => values.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => void values.set(key, value),
|
||||
removeItem: (key: string) => void values.delete(key),
|
||||
};
|
||||
}
|
||||
|
||||
it("reuses the same request after a reload for the same tenant selection", () => {
|
||||
const storage = memoryStorage();
|
||||
const options = { storage, namespace: "/acme/settings/billing", now: 1_000, createKey: () => "00000000-0000-4000-8000-000000000001" };
|
||||
const first = stableCheckoutRequestKey(null, coreSelection, "creditcard", options);
|
||||
const afterReload = stableCheckoutRequestKey(null, coreSelection, "creditcard", {
|
||||
...options,
|
||||
now: 2_000,
|
||||
createKey: () => "00000000-0000-4000-8000-000000000002",
|
||||
});
|
||||
|
||||
expect(afterReload).toEqual(first);
|
||||
});
|
||||
|
||||
it("creates a fresh request for a changed selection, tenant, or expired attempt", () => {
|
||||
const storage = memoryStorage();
|
||||
const first = stableCheckoutRequestKey(null, coreSelection, "creditcard", {
|
||||
storage,
|
||||
namespace: "/acme/settings/billing",
|
||||
now: 1_000,
|
||||
createKey: () => "00000000-0000-4000-8000-000000000001",
|
||||
});
|
||||
const changed = stableCheckoutRequestKey(first, { ...coreSelection, fieldSeatQuantity: 16 }, "creditcard", {
|
||||
storage,
|
||||
namespace: "/acme/settings/billing",
|
||||
now: 2_000,
|
||||
createKey: () => "00000000-0000-4000-8000-000000000002",
|
||||
});
|
||||
const otherTenant = stableCheckoutRequestKey(null, coreSelection, "creditcard", {
|
||||
storage,
|
||||
namespace: "/other/settings/billing",
|
||||
now: 2_000,
|
||||
createKey: () => "00000000-0000-4000-8000-000000000003",
|
||||
});
|
||||
const expired = stableCheckoutRequestKey(null, coreSelection, "creditcard", {
|
||||
storage,
|
||||
namespace: "/acme/settings/billing",
|
||||
now: 30 * 60 * 1000 + 3_000,
|
||||
createKey: () => "00000000-0000-4000-8000-000000000004",
|
||||
});
|
||||
|
||||
expect(changed.key).toBe("00000000-0000-4000-8000-000000000002");
|
||||
expect(otherTenant.key).toBe("00000000-0000-4000-8000-000000000003");
|
||||
expect(expired.key).toBe("00000000-0000-4000-8000-000000000004");
|
||||
});
|
||||
|
||||
it("clears a terminal checkout request so the identical selection can retry immediately", () => {
|
||||
const storage = memoryStorage();
|
||||
const namespace = "/acme/settings/billing";
|
||||
const first = stableCheckoutRequestKey(null, coreSelection, "creditcard", {
|
||||
storage,
|
||||
namespace,
|
||||
now: 1_000,
|
||||
createKey: () => "00000000-0000-4000-8000-000000000001",
|
||||
});
|
||||
|
||||
clearPersistedCheckoutRequest(namespace, storage);
|
||||
const retry = stableCheckoutRequestKey(null, coreSelection, "creditcard", {
|
||||
storage,
|
||||
namespace,
|
||||
now: 2_000,
|
||||
createKey: () => "00000000-0000-4000-8000-000000000002",
|
||||
});
|
||||
|
||||
expect(first.key).not.toBe(retry.key);
|
||||
expect(retry.key).toBe("00000000-0000-4000-8000-000000000002");
|
||||
});
|
||||
});
|
||||
+2481
File diff suppressed because it is too large.
Load diff
+333
@@ -0,0 +1,333 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FeatherClock, FeatherCreditCard, FeatherExternalLink, FeatherPackage, FeatherUsers } from "@subframe/core";
|
||||
import type { TFunction } from "i18next";
|
||||
import type { SubscriptionBannerTone, SubscriptionOverviewProductVM, SubscriptionOverviewVM } from "@hivegrid/view-models";
|
||||
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, 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 { Dialog } from "~/ui/components/Dialog";
|
||||
import { EmptyState } from "~/ui/components/EmptyState";
|
||||
import { Loader } from "~/ui/components/Loader";
|
||||
import { Progress } from "~/ui/components/Progress";
|
||||
import { StatsCard } from "~/ui/components/StatsCard";
|
||||
import { Table } from "~/ui/components/Table";
|
||||
|
||||
export type SubscriptionOverviewActions = {
|
||||
readonly onCancel: (productId: string) => void | Promise<void>;
|
||||
readonly onOpenContact: () => void;
|
||||
readonly onRetry: () => void;
|
||||
};
|
||||
|
||||
function productTitle(t: TFunction, value: string): string {
|
||||
return value.startsWith("settings.subscription.checkout.plans.packages.") ? t(value) : value;
|
||||
}
|
||||
|
||||
function alertVariant(tone: SubscriptionBannerTone): "success" | "warning" | "error" {
|
||||
if (tone === "success") return "success";
|
||||
if (tone === "warning") return "warning";
|
||||
return "error";
|
||||
}
|
||||
|
||||
function productTone(state: SubscriptionOverviewProductVM["state"]): React.ComponentProps<typeof BadgeFeedback>["farbe"] {
|
||||
if (state === "active") return "subtle-positive";
|
||||
if (state === "cancelled") return "subtle-warning";
|
||||
return "subtle-neutral";
|
||||
}
|
||||
|
||||
/** D-P20 S01 interim: tenant subscription overview, deliberately read-only except cancellation. */
|
||||
export function SubscriptionOverviewPage({ vm, actions }: { vm: SubscriptionOverviewVM; actions: SubscriptionOverviewActions }): React.JSX.Element {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const [cancelProduct, setCancelProduct] = useState<SubscriptionOverviewProductVM | null>(null);
|
||||
const [cancelling, setCancelling] = useState(false);
|
||||
|
||||
if (vm.status === "idle" || vm.status === "loading") {
|
||||
return (
|
||||
<div className="flex w-full flex-col items-start gap-6 px-6 py-6" data-ui-id="ui.billing.subscriptionOverview.loading">
|
||||
<Card>
|
||||
<div className="flex w-full items-center gap-3">
|
||||
<Loader />
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
|
||||
{t("billing:subscriptionOverview.loading.title")}
|
||||
</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("billing:subscriptionOverview.loading.description")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (vm.status === "error") {
|
||||
return (
|
||||
<div className="flex w-full flex-col items-start gap-6 px-6 py-6" data-ui-id="ui.billing.subscriptionOverview.error">
|
||||
<EmptyState
|
||||
outlined
|
||||
variant="error"
|
||||
title={t("billing:subscriptionOverview.error.title")}
|
||||
body={t(vm.error.messageKey)}
|
||||
action={
|
||||
<Button variant="tertiary" onClick={actions.onRetry} data-ui-id="ui.billing.subscriptionOverview.retry">
|
||||
{t("billing:states.retry")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (vm.status === "empty") {
|
||||
return (
|
||||
<div className="flex w-full flex-col items-start gap-6 px-6 py-6" data-ui-id="ui.billing.subscriptionOverview.empty">
|
||||
<EmptyState
|
||||
outlined
|
||||
title={t("billing:subscriptionOverview.empty.title")}
|
||||
body={t("billing:subscriptionOverview.empty.description")}
|
||||
action={
|
||||
<Button
|
||||
variant="tertiary"
|
||||
icon={<FeatherExternalLink />}
|
||||
onClick={actions.onOpenContact}
|
||||
data-ui-id="ui.billing.subscriptionOverview.contact"
|
||||
>
|
||||
{t("billing:subscriptionOverview.contact")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { data } = vm;
|
||||
const totalSeats = data.seatUsage.status === "ready" ? data.seatUsage.data.categories.reduce((sum, category) => sum + category.used, 0) : 0;
|
||||
|
||||
async function confirmCancellation(): Promise<void> {
|
||||
if (!cancelProduct) return;
|
||||
setCancelling(true);
|
||||
try {
|
||||
await actions.onCancel(cancelProduct.id);
|
||||
setCancelProduct(null);
|
||||
} finally {
|
||||
setCancelling(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PageShell uiId="ui.billing.subscriptionOverview.page" className="bg-surface-neutral-primary">
|
||||
<PageHeader
|
||||
icon={<FeatherCreditCard className={PAGE_HEADER_ICON_CLASS} />}
|
||||
title={t("billing:subscriptionOverview.title")}
|
||||
subtitle={t("billing:subscriptionOverview.description")}
|
||||
actions={
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<FeatherExternalLink />}
|
||||
onClick={actions.onOpenContact}
|
||||
data-ui-id="ui.billing.subscriptionOverview.contact"
|
||||
>
|
||||
{t("billing:subscriptionOverview.contact")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<PageBody className="items-start">
|
||||
{data.banner.status === "ready" ? (
|
||||
<Alert
|
||||
notDismissible
|
||||
variant={alertVariant(data.banner.data.tone)}
|
||||
title={t(data.banner.data.titleKey)}
|
||||
description={t(data.banner.data.descriptionKey, { count: data.banner.data.trialDaysRemaining ?? undefined })}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className={data.trialDaysRemaining === null ? "mobile:grid-cols-1 grid w-full grid-cols-3 gap-4" : "mobile:grid-cols-1 grid w-full grid-cols-4 gap-4"}
|
||||
>
|
||||
<StatsCard
|
||||
trend="neutral"
|
||||
icon={<FeatherPackage />}
|
||||
label={t("billing:subscriptionOverview.summary.plan")}
|
||||
value={data.planLabel ? productTitle(t, data.planLabel) : t("billing:subscriptionOverview.summary.noPlan")}
|
||||
percentage={t("billing:subscriptionOverview.summary.readOnly")}
|
||||
/>
|
||||
<StatsCard
|
||||
trend={data.status === "active" || data.status === "trial" ? "positive" : "negative"}
|
||||
icon={<FeatherCreditCard />}
|
||||
label={t("billing:subscriptionOverview.summary.status")}
|
||||
value={t(data.statusLabelKey)}
|
||||
percentage={t("billing:subscriptionOverview.summary.synced")}
|
||||
/>
|
||||
<StatsCard
|
||||
trend="neutral"
|
||||
icon={<FeatherUsers />}
|
||||
label={t("billing:subscriptionOverview.summary.seats")}
|
||||
value={formatters.number(totalSeats)}
|
||||
percentage={t("billing:subscriptionOverview.summary.activeSeats")}
|
||||
/>
|
||||
{data.trialDaysRemaining !== null && data.trialEndsAt ? (
|
||||
<StatsCard
|
||||
trend={data.trialDaysRemaining <= 3 ? "negative" : "neutral"}
|
||||
icon={<FeatherClock />}
|
||||
label={t("billing:subscriptionOverview.summary.trial")}
|
||||
value={t("billing:subscriptionOverview.summary.trialDays", { count: data.trialDaysRemaining })}
|
||||
percentage={formatters.date(data.trialEndsAt, { dateStyle: "medium" })}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<Card data-ui-id="ui.billing.subscriptionOverview.products">
|
||||
<div className="flex w-full flex-col items-start">
|
||||
<span className="text-body-large font-body-large text-text-neutral-primary">{t("billing:subscriptionOverview.products.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("billing:subscriptionOverview.products.description")}
|
||||
</span>
|
||||
</div>
|
||||
{data.products.length === 0 ? (
|
||||
<EmptyState title={t(data.emptyTitleKey)} body={t(data.emptyDescriptionKey)} />
|
||||
) : (
|
||||
<div className="w-full overflow-x-auto">
|
||||
<Table
|
||||
header={
|
||||
<Table.HeaderRow>
|
||||
<Table.HeaderCell>{t("billing:subscriptionOverview.products.columns.position")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:subscriptionOverview.products.columns.price")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:subscriptionOverview.products.columns.periodEnd")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:subscriptionOverview.products.columns.status")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("billing:subscriptionOverview.products.columns.action")}</Table.HeaderCell>
|
||||
</Table.HeaderRow>
|
||||
}
|
||||
>
|
||||
{data.products.map((product) => (
|
||||
<Table.Row key={product.id}>
|
||||
<Table.Cell>
|
||||
<div className="flex flex-col items-start">
|
||||
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
|
||||
{product.quantity > 1 ? `${formatters.number(product.quantity)} × ` : ""}
|
||||
{productTitle(t, product.titleKey)}
|
||||
</span>
|
||||
{product.code ? (
|
||||
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{product.code}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<div className="flex flex-col items-start gap-1">
|
||||
{product.prices.length === 0 ? (
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
|
||||
{t("billing:subscriptionOverview.products.noPrice")}
|
||||
</span>
|
||||
) : (
|
||||
product.prices.map((price, index) => (
|
||||
<span key={`${product.id}-${index}`} className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
|
||||
{price.amount !== null && price.currency
|
||||
? `${formatters.currency(price.amount * price.quantity, price.currency)} / ${t(price.periodLabelKey)}`
|
||||
: t("billing:subscriptionOverview.products.noPrice")}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
|
||||
{product.currentPeriodEnd
|
||||
? formatters.date(product.currentPeriodEnd, { dateStyle: "medium" })
|
||||
: t("billing:subscriptionOverview.products.openEnded")}
|
||||
</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<BadgeFeedback farbe={productTone(product.state)} size="small">
|
||||
{t(product.stateLabelKey)}
|
||||
</BadgeFeedback>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
{product.canCancel ? (
|
||||
<Button variant="tertiary" size="small" onClick={() => setCancelProduct(product)} data-ui-id="ui.billing.subscriptionOverview.cancel">
|
||||
{t("billing:subscriptionOverview.cancel.action")}
|
||||
</Button>
|
||||
) : null}
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
))}
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{data.seatUsage.status === "ready" ? (
|
||||
<Card data-ui-id="ui.billing.subscriptionOverview.seats">
|
||||
<div className="flex w-full flex-col items-start">
|
||||
<span className="text-body-large font-body-large text-text-neutral-primary">{t(data.seatUsage.data.titleKey)}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t(data.seatUsage.data.descriptionKey)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4">
|
||||
{data.seatUsage.data.categories.map((category) => {
|
||||
const percent = category.included ? Math.min(100, Math.round((category.used / category.included) * 100)) : 0;
|
||||
return (
|
||||
<Card key={category.seatType} variant={category.overLimit ? "warning" : "neutral"}>
|
||||
<Progress
|
||||
className="w-full"
|
||||
state={category.overLimit ? "error" : "uploading"}
|
||||
value={percent}
|
||||
label={t(category.labelKey)}
|
||||
statusText={
|
||||
category.included === null
|
||||
? formatters.number(category.used)
|
||||
: t("billing:subscriptionOverview.seats.used", { used: category.used, included: category.included })
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<Alert
|
||||
notDismissible
|
||||
variant="information"
|
||||
title={t("billing:subscriptionOverview.externalManagement.title")}
|
||||
description={t("billing:subscriptionOverview.externalManagement.description")}
|
||||
/>
|
||||
</PageBody>
|
||||
|
||||
<Dialog open={cancelProduct !== null} onOpenChange={(open: boolean) => (open ? undefined : setCancelProduct(null))}>
|
||||
<Dialog.Content
|
||||
className="w-[420px] max-w-[90vw] p-4"
|
||||
aria-label={t("billing:subscriptionOverview.cancel.title")}
|
||||
data-ui-id="ui.billing.subscriptionOverview.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 ? productTitle(t, cancelProduct.titleKey) : "",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex w-full items-center justify-end gap-2 pt-4">
|
||||
<Button variant="tertiary" disabled={cancelling} onClick={() => setCancelProduct(null)}>
|
||||
{t("shared.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
loading={cancelling}
|
||||
onClick={() => void confirmCancellation()}
|
||||
data-ui-id="ui.billing.subscriptionOverview.cancelConfirm"
|
||||
>
|
||||
{t("billing:subscriptionOverview.cancel.confirm")}
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
// @vitest-environment jsdom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { SubscriptionBannerStatus, SubscriptionBannerVM } from "@hivegrid/view-models";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { SubscriptionStatusBanner } from "./SubscriptionStatusBanner";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
function bannerVm(status: SubscriptionBannerStatus): SubscriptionBannerVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
status,
|
||||
tone: status === "frozen" ? "danger" : status === "past_due" || status === "cancelled" ? "warning" : "success",
|
||||
titleKey: `settings.subscription.banner.${status}.title`,
|
||||
descriptionKey: `settings.subscription.banner.${status}.description`,
|
||||
trialDaysRemaining: status === "trial" ? 2 : null,
|
||||
readOnly: status === "past_due" || status === "cancelled" || status === "frozen",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("SubscriptionStatusBanner", () => {
|
||||
it("keeps empty and active states out of the app shell", () => {
|
||||
const { container, rerender } = render(<SubscriptionStatusBanner vm={{ status: "empty" }} actions={{ onOpenSubscription: vi.fn() }} />);
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.statusBanner"]')).not.toBeInTheDocument();
|
||||
|
||||
rerender(<SubscriptionStatusBanner vm={bannerVm("active")} actions={{ onOpenSubscription: vi.fn() }} />);
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.statusBanner"]')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(["trial", "past_due", "frozen", "cancelled"] as const)("renders %s with localized content", (status) => {
|
||||
const { container } = render(<SubscriptionStatusBanner vm={bannerVm(status)} actions={{ onOpenSubscription: vi.fn() }} />);
|
||||
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.statusBanner"]')).toBeInTheDocument();
|
||||
expect(screen.getByText(`settings.subscription.banner.${status}.title`)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "billing:status.openSubscriptionSettings" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("delegates navigation through the injected action callback", () => {
|
||||
const onOpenSubscription = vi.fn();
|
||||
render(<SubscriptionStatusBanner vm={bannerVm("past_due")} actions={{ onOpenSubscription }} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:status.openSubscriptionSettings" }));
|
||||
expect(onOpenSubscription).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps the status visible but hides the CTA without subscription view permission", () => {
|
||||
const { container } = render(<SubscriptionStatusBanner vm={bannerVm("frozen")} actions={{}} />);
|
||||
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.statusBanner"]')).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "billing:status.openSubscriptionSettings" })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import type { SubscriptionBannerTone, SubscriptionBannerVM } from "@hivegrid/view-models";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Alert } from "~/ui/components/Alert";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
|
||||
export type SubscriptionStatusBannerActions = {
|
||||
readonly onOpenSubscription?: () => void;
|
||||
};
|
||||
|
||||
function alertVariant(tone: SubscriptionBannerTone): "success" | "warning" | "error" {
|
||||
if (tone === "success") return "success";
|
||||
if (tone === "warning") return "warning";
|
||||
return "error";
|
||||
}
|
||||
|
||||
export function SubscriptionStatusBanner({ vm, actions }: { vm: SubscriptionBannerVM; actions: SubscriptionStatusBannerActions }): React.JSX.Element | null {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (vm.status !== "ready" || vm.data.status === "active") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Alert
|
||||
variant={alertVariant(vm.data.tone)}
|
||||
role={vm.data.readOnly ? "alert" : "status"}
|
||||
title={t(vm.data.titleKey)}
|
||||
description={t(vm.data.descriptionKey, { count: vm.data.trialDaysRemaining ?? undefined })}
|
||||
actions={
|
||||
actions.onOpenSubscription ? (
|
||||
<Button type="button" variant="tertiary" size="small" onClick={actions.onOpenSubscription} data-ui-id="ui.billing.statusBanner.openSubscription">
|
||||
{t("billing:status.openSubscriptionSettings")}
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
data-ui-id="ui.billing.statusBanner"
|
||||
/>
|
||||
);
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`VA-P24a interim visual baseline > opens active billing with a calm overview and keeps plan editing one explicit action away 1`] = `"<main data-ui-id="ui.vaP24a.interim.visualBaseline"><div class="flex w-full flex-col items-start bg-surface-neutral-primary" data-ui-id="ui.billing.selfServiceSubscription.page"><div class="flex w-full items-start gap-4 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:flex-col mobile:px-4"><div class="flex grow shrink-0 basis-0 flex-col items-start gap-1"><div class="flex items-center gap-2"><span class="text-heading- font-heading- text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><h1 class="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">billing:selfServiceSubscription.title</h1></div><p class="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">billing:selfServiceSubscription.description</p></div><div class="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-wrap"><button class="group/3b777358 flex h-9 cursor-pointer items-center justify-center gap-3 rounded-md border-none px-4 py-2.5 text-left focus-within:shadow-focus disabled:cursor-default disabled:bg-surface-neutral-disabled disabled:pointer-events-none hover:disabled:cursor-default hover:disabled:bg-surface-neutral-disabled active:disabled:cursor-default active:disabled:bg-surface-neutral-disabled bg-brand-brand-secondary-surface-subtle-default hover:bg-brand-brand-secondary-surface-subtle-hover active:bg-brand-brand-secondary-surface-subtle-active" type="button" data-ui-id="ui.billing.selfServiceSubscription.openBilling"><span class="text-body-default-regular-0 font-body-default-regular-0 group-disabled/3b777358:text-icon-neutral-disabled text-icon-neutral-primary icon-wrapper-module_root__-l6uP"><span class="icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></span><div class="hidden h-4 w-4 flex-none items-center justify-center gap-2"><div class="text-body-extra-small-regular-150 font-body-extra-small-regular-150 group-disabled/3b777358:text-icon-neutral-disabled group-hover/3b777358:group-disabled/3b777358:text-icon-neutral-on-solid group-active/3b777358:group-disabled/3b777358:text-icon-neutral-disabled text-icon-neutral-primary loader-module_root__-0Kak"></div></div><span class="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 group-disabled/3b777358:text-text-neutral-disabled text-text-neutral-primary">billing:selfServiceSubscription.openBilling</span></button></div></div><div class="flex w-full flex-col gap-6 p-6 mobile:p-4 items-start"><div id="billing-management-overview" role="region" aria-label="billing:selfServiceSubscription.management.tabs.overview" class="flex w-full flex-col gap-6"><div class="group/56067c50 flex w-full flex-col items-start gap-4 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-4 shadow-sm" data-ui-id="ui.billing.selfServiceSubscription.current"><div class="mobile:flex-col flex w-full items-start justify-between gap-4"><div class="flex flex-col items-start"><span class="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">billing:selfServiceSubscription.current.title</span><span class="text-heading-0 font-heading-0 text-text-neutral-primary">billing:selfServiceSubscription.fixture.starter.title</span></div><div class="group/896531e4 flex items-center gap-2 rounded-round px-2.5 h-5 py-0.5 bg-surface-feedback-subtle-positive"><div class="flex h-1 w-1 flex-none flex-col items-start gap-2 rounded-round bg-icon-feedback-positive"></div><span class="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-feedback-positive">billing:selfServiceSubscription.current.status.active</span></div></div><div class="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4"><div class="group/56067c50 flex w-full flex-col items-start gap-4 rounded-md px-4 py-4 shadow-sm border border-solid border-surface-feedback-subtle-neutral bg-surface-feedback-subtle-neutral"><div class="flex items-center gap-3"><span class="text-heading-0 font-heading-0 text-icon-neutral-secondary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><div class="flex flex-col items-start"><span class="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">billing:selfServiceSubscription.current.seats</span><span class="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">3</span></div></div></div><div class="group/56067c50 flex w-full flex-col items-start gap-4 rounded-md px-4 py-4 shadow-sm border border-solid border-surface-feedback-subtle-neutral bg-surface-feedback-subtle-neutral"><div class="flex items-center gap-3"><span class="text-heading-0 font-heading-0 text-icon-neutral-secondary icon-wrapper-module_root__-l6uP"><svg data-visLine truncated
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { FeatherCreditCard } from "@subframe/core";
|
||||
import { buildSettingsHubVM } from "@hivegrid/view-models";
|
||||
import { createMemoryRouter, RouterProvider } from "react-router";
|
||||
|
||||
import { SettingsHubShell } from "~/components/screens/settings/SettingsHubShell";
|
||||
import { VaP24aInterimVisualFixture } from "./va-p24a-interim.visual-fixture";
|
||||
|
||||
export function Bill20BillingHubVisualFixture(): React.JSX.Element {
|
||||
const currentPath = "/analytical-engines/settings/billing";
|
||||
const vm = buildSettingsHubVM({
|
||||
hubId: "billing",
|
||||
titleKey: "settings.hubs.billing.title",
|
||||
subtitleKey: "settings.hubs.billing.subtitle",
|
||||
currentPath,
|
||||
tabs: [
|
||||
{
|
||||
id: "plan",
|
||||
labelKey: "billing:selfServiceSubscription.management.tabs.overview",
|
||||
href: currentPath,
|
||||
exact: true,
|
||||
},
|
||||
{
|
||||
id: "usage",
|
||||
labelKey: "billing:usage.title",
|
||||
href: `${currentPath}/usage`,
|
||||
},
|
||||
{
|
||||
id: "invoices",
|
||||
labelKey: "app.subscription.invoices.title",
|
||||
href: `${currentPath}/invoices`,
|
||||
},
|
||||
],
|
||||
});
|
||||
const router = createMemoryRouter(
|
||||
[
|
||||
{
|
||||
path: "*",
|
||||
element: (
|
||||
<SettingsHubShell vm={vm} icon={<FeatherCreditCard />}>
|
||||
<VaP24aInterimVisualFixture embedded canonicalPlans />
|
||||
</SettingsHubShell>
|
||||
),
|
||||
},
|
||||
],
|
||||
{ initialEntries: [currentPath] }
|
||||
);
|
||||
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
export type SelfServiceSubscriptionSelection = {
|
||||
readonly productId: string;
|
||||
readonly priceId: string;
|
||||
readonly billingPeriod: number;
|
||||
readonly currency: string;
|
||||
readonly officeSeatQuantity: number;
|
||||
readonly fieldSeatQuantity: number;
|
||||
readonly storageAddOnCodes: readonly string[];
|
||||
readonly emailMarketingAddOnCode?: string | null;
|
||||
};
|
||||
|
||||
export type CheckoutRequest = { readonly fingerprint: string; readonly key: string; readonly createdAt: number };
|
||||
|
||||
type CheckoutRequestStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;
|
||||
|
||||
const CHECKOUT_REQUEST_STORAGE_PREFIX = "hivegrid.billing.checkout-request.v1";
|
||||
const CHECKOUT_REQUEST_MAX_AGE_MS = 30 * 60 * 1000;
|
||||
const CHECKOUT_REQUEST_KEY_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function clearPersistedCheckoutRequest(namespace: string, storage?: Pick<Storage, "removeItem">): void {
|
||||
const checkoutStorage = storage ?? (typeof window === "undefined" ? null : window.sessionStorage);
|
||||
if (!checkoutStorage) return;
|
||||
try {
|
||||
checkoutStorage.removeItem(`${CHECKOUT_REQUEST_STORAGE_PREFIX}:${namespace}`);
|
||||
} catch {
|
||||
// Storage can be unavailable in hardened/private browser contexts.
|
||||
}
|
||||
}
|
||||
|
||||
function checkoutRequestFingerprint(selection: SelfServiceSubscriptionSelection, paymentMethod: string | null): string {
|
||||
return JSON.stringify({
|
||||
...selection,
|
||||
storageAddOnCodes: [...selection.storageAddOnCodes].sort(),
|
||||
paymentMethod,
|
||||
});
|
||||
}
|
||||
|
||||
function persistedCheckoutRequest(storage: CheckoutRequestStorage, storageKey: string, fingerprint: string, now: number): CheckoutRequest | null {
|
||||
try {
|
||||
const parsed = JSON.parse(storage.getItem(storageKey) ?? "null") as Partial<CheckoutRequest> | null;
|
||||
if (
|
||||
!parsed ||
|
||||
parsed.fingerprint !== fingerprint ||
|
||||
typeof parsed.key !== "string" ||
|
||||
!CHECKOUT_REQUEST_KEY_PATTERN.test(parsed.key) ||
|
||||
typeof parsed.createdAt !== "number" ||
|
||||
!Number.isFinite(parsed.createdAt) ||
|
||||
parsed.createdAt > now ||
|
||||
now - parsed.createdAt > CHECKOUT_REQUEST_MAX_AGE_MS
|
||||
) {
|
||||
storage.removeItem(storageKey);
|
||||
return null;
|
||||
}
|
||||
return { fingerprint, key: parsed.key, createdAt: parsed.createdAt };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function stableCheckoutRequestKey(
|
||||
current: CheckoutRequest | null,
|
||||
selection: SelfServiceSubscriptionSelection,
|
||||
paymentMethod: string | null,
|
||||
options?: {
|
||||
readonly storage: CheckoutRequestStorage;
|
||||
readonly namespace: string;
|
||||
readonly now?: number;
|
||||
readonly createKey?: () => string;
|
||||
}
|
||||
): CheckoutRequest {
|
||||
const fingerprint = checkoutRequestFingerprint(selection, paymentMethod);
|
||||
const now = options?.now ?? Date.now();
|
||||
if (current?.fingerprint === fingerprint && current.createdAt <= now && now - current.createdAt <= CHECKOUT_REQUEST_MAX_AGE_MS) return current;
|
||||
const storageKey = options ? `${CHECKOUT_REQUEST_STORAGE_PREFIX}:${options.namespace}` : null;
|
||||
const persisted = options && storageKey ? persistedCheckoutRequest(options.storage, storageKey, fingerprint, now) : null;
|
||||
if (persisted) return persisted;
|
||||
const next = { fingerprint, key: options?.createKey?.() ?? globalThis.crypto.randomUUID(), createdAt: now };
|
||||
if (options && storageKey) {
|
||||
try {
|
||||
options.storage.setItem(storageKey, JSON.stringify(next));
|
||||
} catch {
|
||||
// Storage can be unavailable in hardened/private browser contexts. The in-memory key still protects retries in this render.
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function browserCheckoutRequestOptions(namespace: string): Parameters<typeof stableCheckoutRequestKey>[3] {
|
||||
try {
|
||||
return { storage: window.sessionStorage, namespace };
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
import { createVaP24aInterimFixtureViewModel } from "@hivegrid/ui-mock";
|
||||
import {
|
||||
buildSelfServiceSubscriptionPricePreviewVM,
|
||||
type SelfServiceCheckoutPaymentMethodsVM,
|
||||
type SelfServiceSubscriptionPageVM,
|
||||
} from "@hivegrid/view-models";
|
||||
|
||||
import {
|
||||
SelfServiceSubscriptionPage,
|
||||
type SelfServiceSubscriptionActions,
|
||||
type SelfServiceSubscriptionPlanAdvice,
|
||||
type SelfServiceSubscriptionSelection,
|
||||
} from "./SelfServiceSubscriptionPage";
|
||||
|
||||
const noOp = (): void => undefined;
|
||||
|
||||
/** Shared ready-state fixture for VA-P24a markup and Chromium baselines. */
|
||||
export function VaP24aInterimVisualFixture({
|
||||
onCheckout = noOp,
|
||||
onPlanAdvice,
|
||||
onPreview,
|
||||
onEmailMarketingPreview,
|
||||
onEmailMarketingCheckout = noOp,
|
||||
activationMode = false,
|
||||
activationTrialDays,
|
||||
embedded = false,
|
||||
canonicalPlans = false,
|
||||
previewPaymentMethods,
|
||||
initialEmailMarketingAddOnCode,
|
||||
emptyCatalog = false,
|
||||
onRetry = noOp,
|
||||
}: {
|
||||
onCheckout?: SelfServiceSubscriptionActions["onCheckout"];
|
||||
onPlanAdvice?: SelfServiceSubscriptionActions["onPlanAdvice"];
|
||||
onPreview?: SelfServiceSubscriptionActions["onPreview"];
|
||||
onEmailMarketingPreview?: SelfServiceSubscriptionActions["onEmailMarketingPreview"];
|
||||
onEmailMarketingCheckout?: SelfServiceSubscriptionActions["onEmailMarketingCheckout"];
|
||||
activationMode?: boolean;
|
||||
activationTrialDays?: number;
|
||||
embedded?: boolean;
|
||||
canonicalPlans?: boolean;
|
||||
previewPaymentMethods?: SelfServiceCheckoutPaymentMethodsVM;
|
||||
initialEmailMarketingAddOnCode?: string | null;
|
||||
emptyCatalog?: boolean;
|
||||
onRetry?: SelfServiceSubscriptionActions["onRetry"];
|
||||
} = {}): React.JSX.Element {
|
||||
const readyVm = createVaP24aInterimFixtureViewModel();
|
||||
const [starterFixture, businessFixture] = readyVm.catalog.plans;
|
||||
const fixtureTrialDays = activationTrialDays ?? 14;
|
||||
const activationCatalog: SelfServiceSubscriptionPageVM["catalog"] = {
|
||||
plans:
|
||||
starterFixture && businessFixture
|
||||
? [
|
||||
{
|
||||
...starterFixture,
|
||||
id: "plan-core",
|
||||
code: "core",
|
||||
titleKey: "settings.subscription.checkout.plans.packages.starter.title",
|
||||
descriptionKey: "settings.subscription.checkout.plans.packages.starter.description",
|
||||
badge: "billing:selfServiceSubscription.fixture.business.badge",
|
||||
packageTerms: {
|
||||
packageId: "starter",
|
||||
monthlyCents: 19_900,
|
||||
annualSepaMonthlyEquivalentCents: 17_900,
|
||||
officeSeatsIncluded: 2,
|
||||
fieldSeatsIncluded: 5,
|
||||
storageIncludedGb: 100,
|
||||
storagePerAdditionalSeatGb: 10,
|
||||
officeExtraMonthlyCents: 5_900,
|
||||
fieldExtraMonthlyCents: 2_500,
|
||||
officeExtraAnnualSepaCents: 5_310,
|
||||
fieldExtraAnnualSepaCents: 2_250,
|
||||
},
|
||||
prices: starterFixture.prices.map((price, index) => ({
|
||||
...price,
|
||||
id: index === 0 ? "price-core-monthly" : "price-core-annual",
|
||||
unitAmountCents: 19_900,
|
||||
trialDays: fixtureTrialDays,
|
||||
})),
|
||||
},
|
||||
{
|
||||
...businessFixture,
|
||||
id: "plan-swarm",
|
||||
code: "swarm",
|
||||
titleKey: "settings.subscription.checkout.plans.packages.team.title",
|
||||
descriptionKey: "settings.subscription.checkout.plans.packages.team.description",
|
||||
badge: null,
|
||||
packageTerms: {
|
||||
packageId: "team",
|
||||
monthlyCents: 49_900,
|
||||
annualSepaMonthlyEquivalentCents: 44_900,
|
||||
officeSeatsIncluded: 5,
|
||||
fieldSeatsIncluded: 15,
|
||||
storageIncludedGb: 500,
|
||||
storagePerAdditionalSeatGb: 20,
|
||||
officeExtraMonthlyCents: 3_900,
|
||||
fieldExtraMonthlyCents: 1_900,
|
||||
officeExtraAnnualSepaCents: 3_510,
|
||||
fieldExtraAnnualSepaCents: 1_710,
|
||||
},
|
||||
prices: businessFixture.prices.map((price, index) => ({
|
||||
...price,
|
||||
id: index === 0 ? "price-swarm-monthly" : "price-swarm-annual",
|
||||
unitAmountCents: 49_900,
|
||||
trialDays: fixtureTrialDays,
|
||||
})),
|
||||
},
|
||||
{
|
||||
...businessFixture,
|
||||
id: "plan-colony",
|
||||
code: "colony",
|
||||
titleKey: "settings.subscription.checkout.plans.packages.business.title",
|
||||
descriptionKey: "settings.subscription.checkout.plans.packages.business.description",
|
||||
badge: null,
|
||||
packageTerms: {
|
||||
packageId: "business",
|
||||
monthlyCents: 99_900,
|
||||
annualSepaMonthlyEquivalentCents: 89_900,
|
||||
officeSeatsIncluded: 10,
|
||||
fieldSeatsIncluded: 30,
|
||||
storageIncludedGb: 2_000,
|
||||
storagePerAdditionalSeatGb: 40,
|
||||
officeExtraMonthlyCents: 3_500,
|
||||
fieldExtraMonthlyCents: 1_500,
|
||||
officeExtraAnnualSepaCents: 3_150,
|
||||
fieldExtraAnnualSepaCents: 1_350,
|
||||
},
|
||||
prices: businessFixture.prices.map((price, index) => ({
|
||||
...price,
|
||||
id: index === 0 ? "price-colony-monthly" : "price-colony-annual",
|
||||
unitAmountCents: 99_900,
|
||||
trialDays: fixtureTrialDays,
|
||||
})),
|
||||
},
|
||||
]
|
||||
: readyVm.catalog.plans,
|
||||
};
|
||||
let vm: SelfServiceSubscriptionPageVM = activationMode
|
||||
? {
|
||||
...readyVm,
|
||||
catalog: activationCatalog,
|
||||
overview: { status: "empty" },
|
||||
currentSelection: null,
|
||||
minimumSeatQuantity: 1,
|
||||
minimumSeatQuantities: { office: 1, field: 0 },
|
||||
preferredSelection: {
|
||||
planId: "plan-core",
|
||||
priceId: "price-core-monthly",
|
||||
officeSeatQuantity: 2,
|
||||
fieldSeatQuantity: 5,
|
||||
},
|
||||
storageAddOns: [
|
||||
{ code: "storage_500gb", title: "Cloud-Speicher Plus · 500 GB", storageGb: 500, amountCents: 699, currency: "EUR" },
|
||||
{ code: "storage_1tb", title: "Cloud-Speicher Plus · 1 TB", storageGb: 1_000, amountCents: 1_299, currency: "EUR" },
|
||||
{ code: "storage_5tb", title: "Cloud-Speicher Plus · 5 TB", storageGb: 5_000, amountCents: 6_099, currency: "EUR" },
|
||||
],
|
||||
emailMarketingAddOns: readyVm.emailMarketingAddOns.map((addOn) => ({ ...addOn, active: false })),
|
||||
usage: null,
|
||||
}
|
||||
: canonicalPlans
|
||||
? {
|
||||
...readyVm,
|
||||
catalog: activationCatalog,
|
||||
currentSelection: readyVm.currentSelection
|
||||
? {
|
||||
...readyVm.currentSelection,
|
||||
planId: "plan-core",
|
||||
priceId: "price-core-monthly",
|
||||
planCode: "core",
|
||||
}
|
||||
: null,
|
||||
storageAddOns: [
|
||||
{ code: "storage_500gb", title: "Cloud-Speicher Plus · 500 GB", storageGb: 500, amountCents: 699, currency: "EUR" },
|
||||
{ code: "storage_1tb", title: "Cloud-Speicher Plus · 1 TB", storageGb: 1_000, amountCents: 1_299, currency: "EUR" },
|
||||
{ code: "storage_5tb", title: "Cloud-Speicher Plus · 5 TB", storageGb: 5_000, amountCents: 6_099, currency: "EUR" },
|
||||
],
|
||||
overview:
|
||||
readyVm.overview.status === "ready"
|
||||
? {
|
||||
status: "ready",
|
||||
data: {
|
||||
...readyVm.overview.data,
|
||||
planCode: "core",
|
||||
},
|
||||
}
|
||||
: readyVm.overview,
|
||||
}
|
||||
: readyVm;
|
||||
if (emptyCatalog) vm = { ...vm, catalog: { plans: [] }, preferredSelection: null };
|
||||
|
||||
const fixturePlanAdvice = ({
|
||||
officeSeatQuantity,
|
||||
fieldSeatQuantity,
|
||||
}: {
|
||||
officeSeatQuantity: number;
|
||||
fieldSeatQuantity: number;
|
||||
}): SelfServiceSubscriptionPlanAdvice => {
|
||||
const plans = vm.catalog.plans.flatMap((plan) => {
|
||||
const price = plan.prices.find((candidate) => candidate.billingPeriod === 3);
|
||||
return price
|
||||
? [
|
||||
{
|
||||
planId: plan.id,
|
||||
priceId: price.id,
|
||||
amountCents: price.unitAmountCents,
|
||||
currency: price.currency,
|
||||
billingPeriod: price.billingPeriod,
|
||||
recommended: plan === vm.catalog.plans[0],
|
||||
},
|
||||
]
|
||||
: [];
|
||||
});
|
||||
const recommended = plans.find((plan) => plan.recommended);
|
||||
if (!recommended) throw new Error("Visual fixture has no monthly plan recommendation");
|
||||
return {
|
||||
plans,
|
||||
selectedPriceId: recommended.priceId,
|
||||
recommendedPriceId: recommended.priceId,
|
||||
officeSeatQuantity,
|
||||
fieldSeatQuantity,
|
||||
};
|
||||
};
|
||||
const initialPlanAdvice =
|
||||
activationMode && vm.catalog.plans.length > 0
|
||||
? fixturePlanAdvice({
|
||||
officeSeatQuantity: vm.preferredSelection?.officeSeatQuantity ?? vm.minimumSeatQuantities.office,
|
||||
fieldSeatQuantity: vm.preferredSelection?.fieldSeatQuantity ?? vm.minimumSeatQuantities.field,
|
||||
})
|
||||
: null;
|
||||
|
||||
const actions: SelfServiceSubscriptionActions = {
|
||||
onPlanAdvice: onPlanAdvice ?? (async (seatQuantities) => fixturePlanAdvice(seatQuantities)),
|
||||
onPreview:
|
||||
onPreview ??
|
||||
((selection: SelfServiceSubscriptionSelection) => {
|
||||
const selectedPlan = vm.catalog.plans.find((plan) => plan.id === selection.productId);
|
||||
const selectedPrice = selectedPlan?.prices.find((price) => price.id === selection.priceId);
|
||||
const currentPlanCode = vm.overview.status === "ready" ? vm.overview.data.planCode : null;
|
||||
const currentPlan = vm.catalog.plans.find((plan) => plan.code === currentPlanCode) ?? null;
|
||||
const currentPrice = currentPlan?.prices.find((price) => price.id === vm.currentSelection?.priceId) ?? null;
|
||||
if (!selectedPlan || !selectedPrice) return Promise.reject(new Error("Visual fixture selection is not in the catalog"));
|
||||
|
||||
return Promise.resolve({
|
||||
preview: buildSelfServiceSubscriptionPricePreviewVM({
|
||||
currentPlan,
|
||||
currentPrice,
|
||||
currentSeatQuantity: 3,
|
||||
currentPeriodEnd: "2026-08-15T00:00:00.000Z",
|
||||
selectedPlan,
|
||||
selectedPrice,
|
||||
selectedSeatQuantity: Math.max(1, selection.officeSeatQuantity + selection.fieldSeatQuantity),
|
||||
selectedOfficeSeatQuantity: selection.officeSeatQuantity,
|
||||
selectedFieldSeatQuantity: selection.fieldSeatQuantity,
|
||||
selectedStorageAddOnCodes: selection.storageAddOnCodes,
|
||||
vatRateBasisPoints: 1_900,
|
||||
policy: vm.managementPolicy,
|
||||
}),
|
||||
paymentMethods:
|
||||
previewPaymentMethods ??
|
||||
({
|
||||
status: "ready",
|
||||
methods: [
|
||||
{ id: "ideal", label: "iDEAL" },
|
||||
{ id: "creditcard", label: "Kreditkarte" },
|
||||
],
|
||||
} as const),
|
||||
});
|
||||
}),
|
||||
onCheckout,
|
||||
onCancel: noOp,
|
||||
onEmailMarketingPreview:
|
||||
onEmailMarketingPreview ??
|
||||
((addOn) =>
|
||||
Promise.resolve({
|
||||
addOn,
|
||||
paymentMethods: {
|
||||
status: "ready",
|
||||
methods: [
|
||||
{ id: "ideal", label: "iDEAL" },
|
||||
{ id: "creditcard", label: "Kreditkarte" },
|
||||
],
|
||||
},
|
||||
})),
|
||||
onEmailMarketingCheckout,
|
||||
onOpenBilling: noOp,
|
||||
onOpenCustomerPortal: noOp,
|
||||
onRetry,
|
||||
};
|
||||
|
||||
return (
|
||||
<SelfServiceSubscriptionPage
|
||||
vm={vm}
|
||||
actions={actions}
|
||||
activationMode={activationMode}
|
||||
initialPlanAdvice={initialPlanAdvice}
|
||||
embedded={embedded}
|
||||
initialEmailMarketingAddOnCode={initialEmailMarketingAddOnCode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+324
@@ -0,0 +1,324 @@
|
||||
// @vitest-environment jsdom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import React from "react";
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { assertNoA11yViolations } from "~/utils/test/a11y";
|
||||
|
||||
import { VaP24aInterimVisualFixture } from "./va-p24a-interim.visual-fixture";
|
||||
|
||||
globalThis.ResizeObserver =
|
||||
globalThis.ResizeObserver ??
|
||||
class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
};
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${Object.values(values).join("/")}` : key),
|
||||
i18n: { language: "de" },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/format", () => ({
|
||||
useLocaleFormatters: () => ({
|
||||
number: (value: number) => String(value),
|
||||
currency: (value: number, currency: string) => `${value.toFixed(2)} ${currency}`,
|
||||
currencyFromCents: (value: number, currency: string) => `${(value / 100).toFixed(2)} ${currency}`,
|
||||
date: (value: string) => value,
|
||||
dateTime: (value: string) => value,
|
||||
}),
|
||||
}));
|
||||
|
||||
async function advanceActivationToPayment(): Promise<void> {
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" }));
|
||||
await waitFor(() => expect(document.querySelector('[data-ui-id="ui.billing.activation.livePrice"]')).toBeVisible());
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" })).toBeEnabled());
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" }));
|
||||
await waitFor(() => expect(document.querySelector('[data-ui-id="ui.billing.activation.storage"]')).toBeVisible());
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: /activation\.wizard\.email\.no/u }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" }));
|
||||
await waitFor(() => expect(document.querySelector('[data-ui-id="ui.billing.activation.payment"]')).toBeVisible());
|
||||
}
|
||||
|
||||
describe("VA-P24a interim visual baseline", () => {
|
||||
it("opens active billing with a calm overview and keeps plan editing one explicit action away", () => {
|
||||
const { container } = render(
|
||||
<main data-ui-id="ui.vaP24a.interim.visualBaseline">
|
||||
<VaP24aInterimVisualFixture />
|
||||
</main>
|
||||
);
|
||||
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.page']")).toHaveLength(1);
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.current']")).toHaveLength(1);
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.usage']")).toHaveLength(1);
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.builder']")).toHaveLength(0);
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.emailMarketing']")).toHaveLength(0);
|
||||
|
||||
const stableMarkup = container.innerHTML.replace(/<svg\b[^>]*>[\s\S]*?<\/svg>/gu, '<svg data-visual-icon="true"></svg>');
|
||||
expect(stableMarkup).toMatchSnapshot();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.plan.action" }));
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.builder']")).toHaveLength(1);
|
||||
expect(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.back" })).toBeVisible();
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.officeSeats']")).toHaveLength(1);
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.fieldSeats']")).toHaveLength(1);
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.preview']")).toHaveLength(1);
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.back" }));
|
||||
expect(container.querySelectorAll("[data-ui-id='ui.billing.selfServiceSubscription.current']")).toHaveLength(1);
|
||||
assertNoA11yViolations(container);
|
||||
});
|
||||
|
||||
it("renders first activation as a focused locked-workspace checkout without app billing clutter", async () => {
|
||||
const onCheckout = vi.fn(() => new Promise<void>(() => undefined));
|
||||
const { container } = render(<VaP24aInterimVisualFixture activationMode onCheckout={onCheckout} />);
|
||||
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.activation.page"]')).toBeInTheDocument();
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.activation.locked"]')).toBeInTheDocument();
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.selfServiceSubscription.usage"]')).not.toBeInTheDocument();
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.selfServiceSubscription.emailMarketing"]')).not.toBeInTheDocument();
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.selfServiceSubscription.current"]')).not.toBeInTheDocument();
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.activation.team"]')).toBeVisible();
|
||||
expect(screen.getByRole("slider", { name: "billing:selfServiceSubscription.seats.officeLabel" })).toBeVisible();
|
||||
expect(screen.getByRole("spinbutton", { name: "billing:selfServiceSubscription.seats.officeLabel" })).toBeVisible();
|
||||
|
||||
await advanceActivationToPayment();
|
||||
expect(screen.getByText("billing:selfServiceSubscription.preview.recurringNetTotal")).toBeVisible();
|
||||
expect(screen.getByText("billing:selfServiceSubscription.preview.recurringGrossTotal")).toBeVisible();
|
||||
expect(screen.getByText(/billing:selfServiceSubscription\.activation\.trial\.title/u)).toBeVisible();
|
||||
expect(screen.getByRole("radio", { name: /iDEAL/u })).toBeChecked();
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.checkout.action" }));
|
||||
|
||||
expect(onCheckout).toHaveBeenCalledTimes(1);
|
||||
assertNoA11yViolations(container);
|
||||
});
|
||||
|
||||
it("does not restart an activation preview when the route recreates its actions object", async () => {
|
||||
const onPreview = vi.fn(async () => {
|
||||
throw new Error("expected single probe");
|
||||
});
|
||||
const { rerender } = render(<VaP24aInterimVisualFixture activationMode onPreview={onPreview} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" }));
|
||||
await waitFor(() => expect(onPreview).toHaveBeenCalledTimes(1));
|
||||
|
||||
rerender(<VaP24aInterimVisualFixture activationMode onPreview={onPreview} />);
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 400));
|
||||
|
||||
expect(onPreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("offers an explicit retry when live plan advice fails", async () => {
|
||||
const onPlanAdvice = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error("advisor unavailable"))
|
||||
.mockResolvedValueOnce({
|
||||
plans: [{ planId: "plan-core", priceId: "price-core-monthly", amountCents: 19_900, currency: "EUR", billingPeriod: 3, recommended: true }],
|
||||
selectedPriceId: "price-core-monthly",
|
||||
recommendedPriceId: "price-core-monthly",
|
||||
officeSeatQuantity: 3,
|
||||
fieldSeatQuantity: 5,
|
||||
});
|
||||
render(<VaP24aInterimVisualFixture activationMode onPlanAdvice={onPlanAdvice} />);
|
||||
|
||||
fireEvent.change(screen.getByRole("spinbutton", { name: "billing:selfServiceSubscription.seats.officeLabel" }), { target: { value: "3" } });
|
||||
const retry = await screen.findByRole("button", { name: "billing:states.retry" });
|
||||
fireEvent.click(retry);
|
||||
|
||||
await waitFor(() => expect(onPlanAdvice).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "billing:states.retry" })).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows a recoverable empty state when activation has no purchasable catalog", () => {
|
||||
const onRetry = vi.fn();
|
||||
const { container } = render(<VaP24aInterimVisualFixture activationMode emptyCatalog onRetry={onRetry} />);
|
||||
|
||||
expect(screen.getByText("billing:selfServiceSubscription.catalog.empty.title")).toBeVisible();
|
||||
expect(screen.getByText("billing:selfServiceSubscription.catalog.empty.description")).toBeVisible();
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:states.retry" }));
|
||||
expect(onRetry).toHaveBeenCalledTimes(1);
|
||||
assertNoA11yViolations(container);
|
||||
});
|
||||
|
||||
it("explains the license-grown workspace pool before offering fair fixed storage", async () => {
|
||||
const { container } = render(<VaP24aInterimVisualFixture activationMode />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" }));
|
||||
await waitFor(() => expect(document.querySelector('[data-ui-id="ui.billing.activation.livePrice"]')).toBeVisible());
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" })).toBeEnabled());
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.activation.wizard.next" }));
|
||||
await waitFor(() => expect(document.querySelector('[data-ui-id="ui.billing.activation.storage"]')).toBeVisible());
|
||||
|
||||
expect(screen.getByText("billing:selfServiceSubscription.activation.wizard.storage.includedTitle:100")).toBeVisible();
|
||||
expect(screen.getByText("billing:selfServiceSubscription.activation.wizard.storage.poolDescription:100/0/0/10")).toBeVisible();
|
||||
expect(screen.getByText(/6\.99 EUR/u)).toBeVisible();
|
||||
expect(screen.getByText(/^\+12\.99 EUR/u)).toBeVisible();
|
||||
expect(screen.getByText(/60\.99 EUR/u)).toBeVisible();
|
||||
expect(screen.queryByText(/1\.25 EUR/u)).not.toBeInTheDocument();
|
||||
assertNoA11yViolations(container);
|
||||
});
|
||||
|
||||
it("states explicitly when the selected activation price has no trial", async () => {
|
||||
render(<VaP24aInterimVisualFixture activationMode activationTrialDays={0} />);
|
||||
|
||||
await advanceActivationToPayment();
|
||||
|
||||
expect(screen.getByText(/billing:selfServiceSubscription\.activation\.immediate\.title/u)).toBeVisible();
|
||||
expect(screen.getByText("billing:selfServiceSubscription.activation.immediate.description:0")).toBeVisible();
|
||||
expect(screen.queryByText(/billing:selfServiceSubscription\.activation\.trial\.title/u)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("explains the high-value card requirement and blocks checkout when Mollie has no card", async () => {
|
||||
const { container } = render(<VaP24aInterimVisualFixture activationMode previewPaymentMethods={{ status: "required_card_unavailable", methods: [] }} />);
|
||||
|
||||
await advanceActivationToPayment();
|
||||
|
||||
expect(await screen.findByText("billing:selfServiceSubscription.paymentMethods.cardUnavailableTitle")).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "billing:selfServiceSubscription.checkout.action" })).toBeDisabled();
|
||||
assertNoA11yViolations(container);
|
||||
});
|
||||
|
||||
it("labels a card-only high-value checkout before redirecting to Mollie", async () => {
|
||||
render(<VaP24aInterimVisualFixture activationMode previewPaymentMethods={{ status: "ready", methods: [{ id: "creditcard", label: "Kreditkarte" }] }} />);
|
||||
|
||||
await advanceActivationToPayment();
|
||||
|
||||
expect(await screen.findByText("billing:selfServiceSubscription.paymentMethods.cardDescription")).toBeVisible();
|
||||
expect(screen.getByRole("radio", { name: /Kreditkarte/u })).toBeChecked();
|
||||
});
|
||||
|
||||
it("classifies a monthly-to-yearly selection as a period-end billing change", async () => {
|
||||
render(<VaP24aInterimVisualFixture />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.plan.action" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: /290\.00 EUR/u }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.preview.action" }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("billing:selfServiceSubscription.preview.changeKind.billing_period_change")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("names the selection groups and prevents duplicate checkout submissions while loading", async () => {
|
||||
const onCheckout = vi.fn(() => new Promise<void>(() => undefined));
|
||||
render(<VaP24aInterimVisualFixture onCheckout={onCheckout} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.plan.action" }));
|
||||
expect(screen.getByRole("radiogroup", { name: "billing:selfServiceSubscription.catalog.title" })).toBeVisible();
|
||||
expect(screen.getByRole("radiogroup", { name: "billing:selfServiceSubscription.price.title" })).toBeVisible();
|
||||
expect(screen.getByRole("spinbutton", { name: "billing:selfServiceSubscription.seats.officeLabel" })).toBeVisible();
|
||||
expect(screen.getByRole("spinbutton", { name: "billing:selfServiceSubscription.seats.fieldLabel" })).toBeVisible();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.preview.action" }));
|
||||
expect(await screen.findByRole("radiogroup", { name: "billing:selfServiceSubscription.paymentMethods.title" })).toBeVisible();
|
||||
expect(screen.getByRole("radio", { name: /iDEAL/u })).toBeChecked();
|
||||
const checkout = await screen.findByRole("button", { name: "billing:selfServiceSubscription.checkout.action" });
|
||||
fireEvent.click(checkout);
|
||||
fireEvent.click(checkout);
|
||||
|
||||
expect(onCheckout).toHaveBeenCalledTimes(1);
|
||||
expect(onCheckout).toHaveBeenCalledWith(expect.any(Object), "ideal", expect.stringMatching(/^[0-9a-f-]{36}$/u));
|
||||
expect(checkout).toBeDisabled();
|
||||
});
|
||||
|
||||
it("releases the checkout lock when a handled action error returns without redirecting", async () => {
|
||||
const onCheckout = vi.fn().mockResolvedValue(undefined);
|
||||
render(<VaP24aInterimVisualFixture onCheckout={onCheckout} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.plan.action" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.preview.action" }));
|
||||
|
||||
const checkout = await screen.findByRole("button", { name: "billing:selfServiceSubscription.checkout.action" });
|
||||
fireEvent.click(checkout);
|
||||
|
||||
await waitFor(() => expect(checkout).toBeEnabled());
|
||||
fireEvent.click(checkout);
|
||||
await waitFor(() => expect(onCheckout).toHaveBeenCalledTimes(2));
|
||||
expect(onCheckout.mock.calls[1]?.[2]).toBe(onCheckout.mock.calls[0]?.[2]);
|
||||
});
|
||||
|
||||
it("previews an email tier switch, keeps the current tier visible, and pins the chosen method", async () => {
|
||||
const onEmailMarketingCheckout = vi.fn(() => new Promise<void>(() => undefined));
|
||||
const { container } = render(<VaP24aInterimVisualFixture onEmailMarketingCheckout={onEmailMarketingCheckout} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.addons.action" }));
|
||||
expect(screen.getByText("billing:selfServiceSubscription.emailMarketing.active.description")).toBeVisible();
|
||||
expect(container.querySelector('[data-ui-id="ui.billing.selfServiceSubscription.customerPortal"]')).toBeVisible();
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.emailMarketing.switch" }));
|
||||
|
||||
const dialog = await screen.findByRole("dialog", { name: "billing:selfServiceSubscription.emailMarketing.dialog.title" });
|
||||
expect(dialog).toBeVisible();
|
||||
expect(screen.getByText("billing:selfServiceSubscription.emailMarketing.dialog.replacement.description")).toBeVisible();
|
||||
expect(screen.getByRole("radio", { name: /iDEAL/u })).toBeChecked();
|
||||
|
||||
const checkout = screen.getByRole("button", { name: "billing:selfServiceSubscription.emailMarketing.dialog.checkout" });
|
||||
fireEvent.click(checkout);
|
||||
fireEvent.click(checkout);
|
||||
|
||||
expect(onEmailMarketingCheckout).toHaveBeenCalledTimes(1);
|
||||
expect(onEmailMarketingCheckout).toHaveBeenCalledWith(expect.objectContaining({ code: "email_marketing_m" }), "ideal");
|
||||
expect(checkout).toBeDisabled();
|
||||
assertNoA11yViolations(container);
|
||||
});
|
||||
|
||||
it("releases the email package checkout lock when the action returns an inline error", async () => {
|
||||
const onEmailMarketingCheckout = vi.fn().mockResolvedValue(undefined);
|
||||
render(<VaP24aInterimVisualFixture onEmailMarketingCheckout={onEmailMarketingCheckout} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.addons.action" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.emailMarketing.switch" }));
|
||||
|
||||
const checkout = await screen.findByRole("button", { name: "billing:selfServiceSubscription.emailMarketing.dialog.checkout" });
|
||||
fireEvent.click(checkout);
|
||||
|
||||
await waitFor(() => expect(checkout).toBeEnabled());
|
||||
expect(onEmailMarketingCheckout).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("opens the validated post-activation email package directly as a separate checkout", async () => {
|
||||
render(<VaP24aInterimVisualFixture initialEmailMarketingAddOnCode="email_marketing_m" />);
|
||||
|
||||
const dialog = await screen.findByRole("dialog", { name: "billing:selfServiceSubscription.emailMarketing.dialog.title" });
|
||||
expect(dialog).toBeVisible();
|
||||
expect(within(dialog).getByText("billing:selfServiceSubscription.emailMarketing.fixture.m")).toBeVisible();
|
||||
expect(screen.getByRole("radio", { name: /iDEAL/u })).toBeChecked();
|
||||
});
|
||||
|
||||
it("keeps plan and storage edits isolated and requires a real storage change", async () => {
|
||||
render(<VaP24aInterimVisualFixture canonicalPlans />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.plan.action" }));
|
||||
const planOptions = screen.getByRole("radiogroup", { name: "billing:selfServiceSubscription.catalog.title" });
|
||||
fireEvent.click(planOptions.querySelectorAll('[role="radio"]')[1]!);
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.back" }));
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.plan.action" }));
|
||||
const resetPlanOptions = screen.getByRole("radiogroup", { name: "billing:selfServiceSubscription.catalog.title" });
|
||||
expect(within(resetPlanOptions).getAllByRole("radio")[0]).toBeChecked();
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.back" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.addons.action" }));
|
||||
|
||||
const storagePreview = screen.getByRole("button", { name: "billing:selfServiceSubscription.storage.previewAction" });
|
||||
expect(storagePreview).toBeDisabled();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: /500 GB/u }));
|
||||
expect(storagePreview).toBeEnabled();
|
||||
fireEvent.click(storagePreview);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('[data-ui-id="ui.billing.selfServiceSubscription.previewDialog"]')).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a failed email package preview visible in the billing surface", async () => {
|
||||
render(<VaP24aInterimVisualFixture onEmailMarketingPreview={() => Promise.reject(new Error("provider unavailable"))} />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.management.overview.addons.action" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "billing:selfServiceSubscription.emailMarketing.switch" }));
|
||||
|
||||
expect(await screen.findByText("billing:selfServiceSubscription.emailMarketing.errors.checkoutDescription")).toBeVisible();
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user