Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

9.0 KB
Raw Blame
import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
import type { ReactNode } from "react";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MantineProvider } from "@mantine/core";
import { MemoryRouter, useLocation } from "react-router-dom";
import { PortalTestProviders } from "@processor/test/TestQueryProvider";
import type { ServerPlan } from "@editor/billing/serverPlan";
import { qk } from "@processor/queries/keys";

/**
 * The unlinked usage page renders the shared billing screen from the instance's own ledger and
 * nothing else — no wallet, so no claim about linkage — and it has to survive its endpoints being
 * admin-only, since a non-admin can hold a portal grant and reach this page.
 */
const { fetchFreeTier, fetchFleetStats, fetchUsers, openLinkModal, auth } =
  vi.hoisted(() => ({
    fetchFreeTier: vi.fn(),
    fetchFleetStats: vi.fn(),
    fetchUsers: vi.fn(),
    openLinkModal: vi.fn(),
    auth: { isAdmin: true },
  }));

vi.mock("@editor/auth", () => ({ useAuth: () => auth }));

vi.mock("@processor/api/link", () => ({ fetchFreeTier }));
vi.mock("@processor/queries/infrastructure", () => ({
  useFleetStats: () => ({ data: null, loading: false, error: null }),
}));
vi.mock("@editor/portal/usersBackend", () => ({
  usersBackend: { fetchUsers },
}));
vi.mock("@processor/contexts/UIContext", () => ({
  useUI: () => ({ openLinkModal }),
}));
vi.mock("react-i18next", () => ({
  useTranslation: () => ({
    // Interpolated so the figures themselves are what the assertions read.
    t: (_key: string, fallback: string, vars?: Record<string, unknown>) =>
      typeof fallback === "string" && vars
        ? fallback.replace(/\{\{(\w+)\}\}/g, (_m, n) => String(vars[n] ?? ""))
        : fallback,
    i18n: { changeLanguage: vi.fn() },
  }),
}));

import { HttpError } from "@processor/api/http";
import { FreeTierPlanView } from "@processor/components/billing/FreeTierPlanView";

const BALANCE = {
  grantUnits: 500,
  usedUnits: 120,
  remainingUnits: 380,
  periodStart: "2026-09-01T00:00:00",
  periodEnd: "2026-10-01T00:00:00",
};

function Location() {
  const location = useLocation();
  return (
    <output data-testid="location">
      {location.pathname}
      {location.search}
    </output>
  );
}

const renderView = (
  serverPlan?: ServerPlan,
  licenseSection?: ReactNode,
  entry = "/settings/billing",
) =>
  render(
    <PortalTestProviders>
      <MemoryRouter initialEntries={[entry]}>
        <Location />
        <FreeTierPlanView
          serverPlan={serverPlan}
          licenseSection={licenseSection}
        />
      </MemoryRouter>
    </PortalTestProviders>,
  );

describe("FreeTierPlanView", () => {
  beforeEach(() => {
    auth.isAdmin = true;
    fetchFreeTier.mockReset();
    fetchFleetStats.mockReset().mockRejectedValue(new Error("no stats"));
    fetchUsers.mockReset().mockRejectedValue(new Error("not admin"));
    openLinkModal.mockReset();
  });

  it.each(["ready", "failed"])(
    "retains license management at the end of the shared card when the ledger is %s",
    async (state) => {
      if (state === "ready") fetchFreeTier.mockResolvedValue(BALANCE);
      else
        fetchFreeTier.mockRejectedValue(
          new HttpError(500, "Server Error", null),
        );
      renderView(undefined, <button>Manage local license</button>);
      await screen.findByText(
        state === "ready" ? "120 of 500 used" : "Couldn't load credit usage",
      );
      const section = screen
        .getByRole("button", { name: "Manage local license" })
        .closest("section");
      expect(section).toHaveAttribute("id", "ub-license");
      expect(section?.parentElement?.lastElementChild).toBe(section);
    },
  );

  it("meters the local ledger on the shared screen", async () => {
    fetchFreeTier.mockResolvedValue(BALANCE);
    renderView();

    expect(await screen.findByText("120 of 500 used")).toBeInTheDocument();
    // No rate is known locally, so the row quotes the allowance rather than a price.
    expect(screen.getByText("500 included every month")).toBeInTheDocument();
  });

  it("reads only the instance's own ledger for the meter", async () => {
    fetchFreeTier.mockResolvedValue(BALANCE);
    renderView();

    await screen.findByText("120 of 500 used");
    expect(fetchFreeTier).toHaveBeenCalledTimes(1);
  });

  it("keeps cached usage visible when a background refetch fails", async () => {
    fetchFreeTier.mockResolvedValue(BALANCE);
    const client = new QueryClient();
    render(
      <QueryClientProvider client={client}>
        <MantineProvider>
          <MemoryRouter>
            <FreeTierPlanView />
          </MemoryRouter>
        </MantineProvider>
      </QueryClientProvider>,
    );
    await screen.findByText("120 of 500 used");
    fetchFreeTier.mockRejectedValue(new HttpError(500, "Server Error", null));
    await act(async () => {
      await client.refetchQueries({ queryKey: qk.freeTier() });
    });
    expect(client.getQueryState(qk.freeTier())?.status).toBe("error");
    expect(screen.getByText("120 of 500 used")).toBeInTheDocument();
    expect(screen.queryByText("Couldn't load credit usage")).toBeNull();
  });

  it("shows the users this server may have when the admin endpoint answers", async () => {
    fetchFreeTier.mockResolvedValue(BALANCE);
    fetchUsers.mockResolvedValue({ summary: { seatsUsed: 3, seatLimit: 5 } });
    renderView();

    expect(await screen.findByText("3 of 5 users")).toBeInTheDocument();
  });

  it("drops the users row rather than claiming zero when it does not", async () => {
    fetchFreeTier.mockResolvedValue(BALANCE);
    renderView();

    await screen.findByText("120 of 500 used");
    expect(screen.queryByText(/of 0 users/)).toBeNull();
    expect(screen.queryByText("Users")).toBeNull();
  });

  it("offers the account as more allowance, and asks for it only on request", async () => {
    fetchFreeTier.mockResolvedValue(BALANCE);
    renderView();

    await screen.findByText("120 of 500 used");
    expect(openLinkModal).not.toHaveBeenCalled();
    expect(screen.getByText("Connect a Stirling account")).toBeInTheDocument();
  });

  it.each(["Get an enterprise quote", "Explore Enterprise"])(
    "opens the hosted Enterprise page from %s, with no account to connect first",
    async (button) => {
      const open = vi.spyOn(window, "open").mockReturnValue(null);
      onTestFinished(() => open.mockRestore());
      fetchFreeTier.mockResolvedValue(BALANCE);
      renderView();
      await screen.findByText("120 of 500 used");
      if (button === "Explore Enterprise") {
        fireEvent.click(screen.getByRole("button", { name: "Compare plans" }));
      }

      fireEvent.click(screen.getByRole("button", { name: button }));

      expect(openLinkModal).not.toHaveBeenCalled();
      expect(open).toHaveBeenCalledWith(
        expect.stringMatching(/^https:\/\/.+\/enterprise$/),
        "_blank",
        "noopener,noreferrer",
      );
    },
  );

  it("tells a non-admin the figures are not theirs to see, rather than failing", async () => {
    fetchFreeTier.mockRejectedValue(new HttpError(403, "Forbidden", null));
    renderView();

    expect(
      await screen.findByText(/only an administrator/),
    ).toBeInTheDocument();
    expect(screen.queryByText("Couldn't load credit usage")).toBeNull();
  });

  it("reports a real failure as one", async () => {
    fetchFreeTier.mockRejectedValue(new HttpError(500, "Server Error", null));
    renderView();

    expect(
      await screen.findByText("Couldn't load credit usage"),
    ).toBeInTheDocument();
  });

  it("does not offer linking or fetch admin figures for a member", async () => {
    auth.isAdmin = false;
    renderView();

    expect(
      await screen.findByText(/only an administrator/),
    ).toBeInTheDocument();
    expect(fetchFreeTier).not.toHaveBeenCalled();
    expect(fetchUsers).not.toHaveBeenCalled();
    expect(
      screen.queryByRole("button", {
        name: /Connect a Stirling account|Link account for more credits/,
      }),
    ).toBeNull();
  });

  it("puts a recovery CTA beside an exhausted meter", async () => {
    fetchFreeTier.mockResolvedValue({
      ...BALANCE,
      remainingUnits: 0,
      usedUnits: 500,
    });
    renderView();
    fireEvent.click(
      await screen.findByRole("button", {
        name: "Link account for more credits",
      }),
    );
    expect(openLinkModal).toHaveBeenCalledWith("exhausted");
  });

  it("keeps Enterprise linking optional when the local ledger is empty", async () => {
    fetchFreeTier.mockResolvedValue({
      ...BALANCE,
      remainingUnits: 0,
      usedUnits: 500,
    });
    renderView({ licenseType: "ENTERPRISE", maxUsers: 10, usersInUse: 3 });

    expect(
      await screen.findByText(/Your Enterprise license includes processing/),
    ).toBeInTheDocument();
    fireEvent.click(
      screen.getByRole("button", { name: "Connect a Stirling account" }),
    );
    expect(openLinkModal).toHaveBeenCalledWith("link");
    expect(
      screen.queryByRole("button", { name: "Link account for more credits" }),
    ).toBeNull();
  });
});