Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,64 @@
// Guards how the loader's FilterablePropertyDto list becomes facets:
// option-bearing properties become dropdowns, and a property without options
// still shows up as a removable chip while it is active — otherwise a filter
// arriving through a row link would be invisible and unclearable.
import { fireEvent, render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import { describe, expect, it, vi } from "vitest";
import type { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { ApiFilterBar } from "./ApiFilterBar";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
const METHOD: FilterablePropertyDto = {
name: "method",
title: "models.apiKeyLog.method",
options: [
{ name: "GET", value: "GET" },
{ name: "POST", value: "POST" },
],
};
function renderBar(properties: FilterablePropertyDto[]) {
const onToggleProperty = vi.fn();
const onSearchChange = vi.fn();
render(
<ApiFilterBar
uiId="ui.test.filter"
properties={properties}
search=""
onSearchChange={onSearchChange}
onToggleProperty={onToggleProperty}
onReset={vi.fn()}
/>
);
return { onToggleProperty, onSearchChange };
}
describe("ApiFilterBar", () => {
it("turns an option-bearing property into a facet button", () => {
renderBar([{ ...METHOD }]);
// The options live in a Radix portal that only mounts once opened; the chip
// test below covers the reporting path.
expect(document.querySelector("[data-ui-id='ui.test.filter.method']")).not.toBeNull();
expect(screen.getByText("models.apiKeyLog.method")).toBeInTheDocument();
});
it("shows an active option-less filter as a removable chip", () => {
const { onToggleProperty } = renderBar([{ name: "endpoint", title: "models.apiKeyLog.endpoint", value: "/api/kontakte" }]);
expect(screen.getByText("/api/kontakte")).toBeInTheDocument();
fireEvent.click(document.querySelector("[data-ui-id='ui.test.filter.chip.endpoint./api/kontakte.remove']")!);
expect(onToggleProperty).toHaveBeenCalledWith("endpoint", "/api/kontakte");
});
it("leaves out an option-less property that is not filtering", () => {
renderBar([{ name: "params", title: "models.apiKeyLog.params" }]);
expect(document.querySelector("[data-ui-id='ui.test.filter.params']")).toBeNull();
});
});
@@ -0,0 +1,75 @@
// The shared facet strip for the API tabs, driven by the loader's
// FilterablePropertyDto list.
//
// The tabs used to carry the boilerplate InputSearchWithURL plus an InputFilters
// popover button, which looked nothing like the bar every list screen wears. The
// URL contract is untouched: the free-text box still writes `q`, and every facet
// still writes its property name as a single query parameter, so the loader-side
// filtering in ApiKeyLogService keeps working unchanged.
//
// Properties without a fixed option list (endpoint, params, status …) cannot be
// offered as a dropdown, but they are still reachable — the row links write
// their parameter. Whenever such a filter is active it renders as a one-option
// facet so it appears as a removable chip rather than an invisible filter.
import { useTranslation } from "react-i18next";
import { FeatherFilter } from "@subframe/core";
import type { ReactNode } from "react";
import type { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar";
/** Chip colours, so two active filters are told apart at a glance. */
const FACET_TONE = ["violet-subtle", "blue-subtle", "sky-subtle", "yellow-subtle", "neutral-subtle"] as const;
export type ApiFilterBarProps = {
properties: readonly FilterablePropertyDto[];
/** Current `q` value. */
search: string;
onSearchChange: (value: string) => void;
/** Sets a property filter, or clears it when the active value is picked again. */
onToggleProperty: (name: string, value: string) => void;
onReset: () => void;
uiId: string;
hideSearch?: boolean;
afterFacets?: ReactNode;
};
export function ApiFilterBar({ properties, search, onSearchChange, onToggleProperty, onReset, uiId, hideSearch, afterFacets }: ApiFilterBarProps) {
const { t } = useTranslation();
const facets: ClientFacet[] = properties
.map((property, index): ClientFacet | null => {
const active = property.value ?? null;
const options = property.options?.length
? property.options.map((option) => ({ value: option.value, label: option.name }))
: active
? [{ value: active, label: active }]
: [];
if (options.length === 0) return null;
return {
key: property.name,
label: t(property.title),
icon: <FeatherFilter />,
tone: FACET_TONE[index % FACET_TONE.length],
options,
selected: new Set(active ? [active] : []),
};
})
.filter((facet): facet is ClientFacet => facet !== null);
return (
<FacetFilterBar
variant="inline"
uiId={uiId}
facets={facets}
onToggle={onToggleProperty}
search={search}
onSearchChange={onSearchChange}
searchPlaceholder={t("shared.searchDot")}
onReset={onReset}
hideSearch={hideSearch}
afterFacets={afterFacets}
labels={{ reset: t("shared.reset"), removeChip: t("settings.members.filters.removeChip") }}
/>
);
}
@@ -0,0 +1,72 @@
// Guards the contract the edit route relies on after "Bearbeiten" moved from the
// boilerplate ApiKeyForm onto the shared FormDialog: saving reports the trimmed
// fields, and rotate and delete both ask before they run — the old FormGroup
// wired its delete straight to a submit.
import { fireEvent, render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import { describe, expect, it, vi } from "vitest";
import { ApiKeyEditDialog, type ApiKeyEditData } from "./ApiKeyEditDialog";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
const DATA: ApiKeyEditData = {
redactedKey: "hgd_demo…••••auth",
alias: "Website Lead Intake",
expires: "",
active: true,
canUpdate: true,
canDelete: true,
canRotate: true,
};
function renderDialog(overrides: Partial<ApiKeyEditData> = {}) {
const handlers = { onSave: vi.fn(), onRotate: vi.fn(), onDelete: vi.fn(), onClose: vi.fn() };
render(<ApiKeyEditDialog data={{ ...DATA, ...overrides }} submitting={false} errorMessage={null} {...handlers} />);
return handlers;
}
const byId = (id: string) => document.querySelector(`[data-ui-id='${id}']`) as HTMLButtonElement;
describe("ApiKeyEditDialog", () => {
it("prefills the key and reports the trimmed save", () => {
const { onSave } = renderDialog({ expires: "2027-01-31" });
expect(screen.getByLabelText("models.apiKey.alias")).toHaveValue("Website Lead Intake");
fireEvent.change(screen.getByLabelText("models.apiKey.alias"), { target: { value: " Intake " } });
fireEvent.click(byId("ui.settings.apiKeys.editDialog.submit"));
expect(onSave).toHaveBeenCalledWith({ alias: "Intake", expires: "2027-01-31", active: true });
});
it("asks before rotating and only then reports it", () => {
const { onRotate } = renderDialog();
fireEvent.click(byId("ui.settings.apiKeys.editDialog.rotate"));
expect(onRotate).not.toHaveBeenCalled();
expect(screen.getByText("models.apiKey.rotateBody")).toBeInTheDocument();
fireEvent.click(byId("ui.settings.apiKeys.editDialog.rotateSubmit"));
expect(onRotate).toHaveBeenCalledTimes(1);
});
it("asks before deleting and only then reports it", () => {
const { onDelete } = renderDialog();
fireEvent.click(byId("ui.settings.apiKeys.editDialog.delete"));
expect(onDelete).not.toHaveBeenCalled();
fireEvent.click(byId("ui.settings.apiKeys.editDialog.deleteSubmit"));
expect(onDelete).toHaveBeenCalledTimes(1);
});
it("hides the actions a viewer is not allowed to run", () => {
renderDialog({ canDelete: false, canRotate: false, canUpdate: false });
expect(byId("ui.settings.apiKeys.editDialog.delete")).toBeNull();
expect(byId("ui.settings.apiKeys.editDialog.rotate")).toBeNull();
expect(byId("ui.settings.apiKeys.editDialog.submit")).toBeDisabled();
expect(screen.getByLabelText("models.apiKey.alias")).toBeDisabled();
});
});
@@ -0,0 +1,180 @@
// "API-Schluessel bearbeiten" on the shared FormDialog chrome.
//
// The edit route rendered the boilerplate ApiKeyForm inside an OpenModal, so it
// wore the same odd popup shape the create route did — plus a FormGroup footer
// whose delete button raised its own confirm. The fields are the same three the
// action already accepts; rotate and delete sit in their own section below them,
// because both are irreversible in a way that saving a new alias is not.
//
// Presentational: the route owns the submits. The admin API-key routes keep the
// shared ApiKeyForm for now.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherRefreshCw, FeatherSave, FeatherTrash2 } from "@subframe/core";
import { Alert } from "~/ui/components/Alert";
import { Button } from "~/ui/components/Button";
import { Checkbox } from "~/ui/components/Checkbox";
import { TextInput } from "~/ui/components/TextInput";
import { DateField } from "../tasks/DateField";
import { FormDialog } from "../shared/FormDialog";
export type ApiKeyEditInput = {
alias: string;
/** ISO date (yyyy-mm-dd) or "" for a key that does not expire. */
expires: string;
active: boolean;
};
export type ApiKeyEditData = {
/** Redacted key (prefix…last four) — the raw secret never reaches the client. */
redactedKey: string;
alias: string;
expires: string;
active: boolean;
canUpdate: boolean;
canDelete: boolean;
canRotate: boolean;
};
export function ApiKeyEditDialog({
data,
submitting,
errorMessage,
onSave,
onRotate,
onDelete,
onClose,
}: {
data: ApiKeyEditData;
submitting: boolean;
errorMessage: string | null;
onSave: (input: ApiKeyEditInput) => void;
onRotate: () => void;
onDelete: () => void;
onClose: () => void;
}): React.JSX.Element {
const { t } = useTranslation();
const [alias, setAlias] = useState(data.alias);
const [expires, setExpires] = useState(data.expires);
const [active, setActive] = useState(data.active);
const [confirm, setConfirm] = useState<"rotate" | "delete" | null>(null);
const disabled = !data.canUpdate;
const canSubmit = !disabled && alias.trim().length > 0 && !submitting;
if (confirm) {
const isDelete = confirm === "delete";
return (
<FormDialog
open
onOpenChange={(open: boolean) => (open ? undefined : setConfirm(null))}
size="xs"
uiId={`ui.settings.apiKeys.editDialog.${confirm}Confirm`}
title={isDelete ? t("models.apiKey.deleteTitle") : t("models.apiKey.rotateTitle")}
footer={
<>
<Button className="mobile:w-full" type="button" variant="tertiary" onClick={() => setConfirm(null)}>
{t("shared.cancel")}
</Button>
<Button
className="mobile:w-full"
variant={isDelete ? "destructive" : "primary"}
icon={isDelete ? <FeatherTrash2 /> : <FeatherRefreshCw />}
loading={submitting}
disabled={submitting}
onClick={() => (isDelete ? onDelete() : onRotate())}
data-ui-id={`ui.settings.apiKeys.editDialog.${confirm}Submit`}
>
{isDelete ? t("shared.delete") : t("models.apiKey.rotate")}
</Button>
</>
}
>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{isDelete ? t("models.apiKey.deleteBody", { alias: data.alias }) : t("models.apiKey.rotateBody", { alias: data.alias })}
</span>
</FormDialog>
);
}
return (
<FormDialog
open
onOpenChange={(open: boolean) => (open ? undefined : onClose())}
title={t("models.apiKey.editTitle")}
subtitle={data.redactedKey}
uiId="ui.settings.apiKeys.editDialog"
footer={
<>
<Button type="button" variant="tertiary" onClick={onClose} disabled={submitting}>
{t("shared.cancel")}
</Button>
<Button
icon={<FeatherSave />}
loading={submitting}
disabled={!canSubmit}
onClick={() => onSave({ alias: alias.trim(), expires, active })}
data-ui-id="ui.settings.apiKeys.editDialog.submit"
>
{t("shared.save")}
</Button>
</>
}
>
{errorMessage ? <Alert variant="error" title={errorMessage} /> : null}
<TextInput className="w-full max-w-full" label={t("models.apiKey.alias")} showLabel>
<TextInput.Input
value={alias}
onChange={(event) => setAlias(event.target.value)}
disabled={disabled}
autoComplete="off"
required
data-ui-id="ui.settings.apiKeys.editDialog.alias"
/>
</TextInput>
<div className="flex w-full flex-col gap-1">
<DateField label={t("models.apiKey.expires")} name="expires" value={expires} onChange={setExpires} />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("models.apiKey.expiresHint")}</span>
</div>
<Checkbox className="w-fit" label={t("models.apiKey.active")} checked={active} disabled={disabled} onCheckedChange={(checked: boolean) => setActive(checked)} />
{data.canRotate || data.canDelete ? (
<div className="flex w-full flex-col gap-3 border-t border-solid border-border-default pt-4">
{/* Both are irreversible in a way that renaming a key is not, so they
stand apart from the save action and ask before they run. */}
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">{t("models.apiKey.dangerSection")}</span>
<div className="flex flex-wrap items-center gap-2">
{data.canRotate ? (
<Button
type="button"
variant="secondary"
icon={<FeatherRefreshCw />}
disabled={submitting}
onClick={() => setConfirm("rotate")}
data-ui-id="ui.settings.apiKeys.editDialog.rotate"
>
{t("models.apiKey.rotate")}
</Button>
) : null}
{data.canDelete ? (
<Button
type="button"
variant="destructive"
icon={<FeatherTrash2 />}
disabled={submitting}
onClick={() => setConfirm("delete")}
data-ui-id="ui.settings.apiKeys.editDialog.delete"
>
{t("shared.delete")}
</Button>
) : null}
</div>
</div>
) : null}
</FormDialog>
);
}
@@ -0,0 +1,56 @@
// Guards the contract the create route relies on after "Neuer API-Schluessel"
// moved from the boilerplate OpenModal onto the shared FormDialog: the dialog
// reports the trimmed alias, the expiry and the active flag, and it refuses to
// submit without an alias (the action rejects an empty one server-side).
import { fireEvent, render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import { describe, expect, it, vi } from "vitest";
import { ApiKeyNewDialog, type ApiKeyNewInput } from "./ApiKeyNewDialog";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
vi.mock("~/hooks/use-copy-toast", () => ({ useCopyToast: () => async () => true }));
function renderDialog() {
const onCreate = vi.fn<(input: ApiKeyNewInput) => void>();
render(<ApiKeyNewDialog open onOpenChange={() => undefined} submitting={false} errorMessage={null} onCreate={onCreate} />);
return { onCreate };
}
function submitButton(): HTMLButtonElement {
return document.querySelector("[data-ui-id='ui.settings.apiKeys.newDialog.submit']") as HTMLButtonElement;
}
describe("ApiKeyNewDialog", () => {
it("reports the trimmed alias, the expiry and the active flag", () => {
const { onCreate } = renderDialog();
fireEvent.change(screen.getByLabelText("models.apiKey.alias"), { target: { value: " Website Lead Intake " } });
fireEvent.change(screen.getByLabelText("models.apiKey.expires"), { target: { value: "2027-01-31" } });
fireEvent.click(submitButton());
expect(onCreate).toHaveBeenCalledWith({ alias: "Website Lead Intake", expires: "2027-01-31", active: true });
});
it("keeps the submit disabled until an alias is set", () => {
renderDialog();
expect(submitButton()).toBeDisabled();
fireEvent.change(screen.getByLabelText("models.apiKey.alias"), { target: { value: "Intake" } });
expect(submitButton()).not.toBeDisabled();
});
it("shows the server-side rejection", () => {
render(
<ApiKeyNewDialog
open
onOpenChange={() => undefined}
submitting={false}
errorMessage="models.apiKey.errors.aliasExists"
onCreate={vi.fn()}
/>
);
expect(screen.getByText("models.apiKey.errors.aliasExists")).toBeInTheDocument();
});
});
@@ -0,0 +1,153 @@
// "Neuer API-Schluessel" as a popup on the shared FormDialog chrome, plus the
// one-time reveal that follows a successful create.
//
// The create route used to stack two OpenModal overlays with the boilerplate
// FormGroup/InputText/InputDate controls inside — a different popup shape from
// every other form in the app. Both steps now wear the same header/body/footer
// bar the task, role, group and member popups wear.
//
// Presentational: the route owns the submit and the navigation back to the list.
// The admin API-key routes keep the shared ApiKeyForm for now.
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherCheck, FeatherCopy, FeatherKey } from "@subframe/core";
import { Alert } from "~/ui/components/Alert";
import { Button } from "~/ui/components/Button";
import { Checkbox } from "~/ui/components/Checkbox";
import { TextInput } from "~/ui/components/TextInput";
import { useCopyToast } from "~/hooks/use-copy-toast";
import { DateField } from "../tasks/DateField";
import { FormDialog } from "../shared/FormDialog";
export type ApiKeyNewInput = {
/** Free-text name the list shows next to the redacted key. */
alias: string;
/** ISO date (yyyy-mm-dd) or "" for a key that does not expire. */
expires: string;
active: boolean;
};
export function ApiKeyNewDialog({
open,
onOpenChange,
submitting,
errorMessage,
onCreate,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
submitting: boolean;
/** Server-side rejection (e.g. the alias is already taken). */
errorMessage: string | null;
onCreate: (input: ApiKeyNewInput) => void;
}): React.JSX.Element {
const { t } = useTranslation();
const [alias, setAlias] = useState("");
const [expires, setExpires] = useState("");
const [active, setActive] = useState(true);
const canSubmit = alias.trim().length > 0 && !submitting;
return (
<FormDialog
open={open}
onOpenChange={onOpenChange}
title={t("models.apiKey.newTitle")}
subtitle={t("models.apiKey.newDescription")}
uiId="ui.settings.apiKeys.newDialog"
footer={
<>
<Button type="button" variant="tertiary" onClick={() => onOpenChange(false)} disabled={submitting}>
{t("shared.cancel")}
</Button>
<Button
icon={<FeatherKey />}
loading={submitting}
disabled={!canSubmit}
onClick={() => onCreate({ alias: alias.trim(), expires, active })}
data-ui-id="ui.settings.apiKeys.newDialog.submit"
>
{t("shared.create")}
</Button>
</>
}
>
{errorMessage ? <Alert variant="error" title={errorMessage} /> : null}
<TextInput className="w-full max-w-full" label={t("models.apiKey.alias")} showLabel>
<TextInput.Input
value={alias}
onChange={(event) => setAlias(event.target.value)}
autoFocus
autoComplete="off"
required
data-ui-id="ui.settings.apiKeys.newDialog.alias"
/>
</TextInput>
<div className="flex w-full flex-col gap-1">
<DateField label={t("models.apiKey.expires")} name="expires" value={expires} onChange={setExpires} />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("models.apiKey.expiresHint")}</span>
</div>
<Checkbox className="w-fit" label={t("models.apiKey.active")} checked={active} onCheckedChange={(checked: boolean) => setActive(checked)} />
</FormDialog>
);
}
/**
* One-time reveal. The raw key exists only in this response, so the dialog does
* not offer a way to dismiss it without the user having seen the copy button.
*/
export function ApiKeyCreatedDialog({
apiKey,
onClose,
action = "created",
}: {
apiKey: { key: string; alias: string };
onClose: () => void;
/** A rotated key replaces a live one, so it says so. */
action?: "created" | "rotated";
}): React.JSX.Element {
const { t } = useTranslation();
const copyText = useCopyToast();
const [copied, setCopied] = useState(false);
async function copyApiKey() {
const didCopy = await copyText(apiKey.key, { successKey: "models.apiKey.copied", errorKey: "models.apiKey.copyFailed" });
if (didCopy) setCopied(true);
}
return (
<FormDialog
open
onOpenChange={(next: boolean) => {
if (!next) onClose();
}}
title={t(action === "rotated" ? "models.apiKey.rotatedTitle" : "models.apiKey.createdTitle")}
subtitle={t("models.apiKey.aliasWithValue", { alias: apiKey.alias })}
uiId="ui.settings.apiKeys.createdDialog"
footer={
<>
<Button
variant="tertiary"
icon={copied ? <FeatherCheck /> : <FeatherCopy />}
onClick={copyApiKey}
data-ui-id="ui.settings.apiKeys.createdDialog.copy"
>
{copied ? t("shared.copied") : t("shared.copy")}
</Button>
<Button onClick={onClose} data-ui-id="ui.settings.apiKeys.createdDialog.done">
{t("shared.acceptAndContinue")}
</Button>
</>
}
>
<Alert variant="warning" title={t(action === "rotated" ? "models.apiKey.oneTimeDescriptionRotated" : "models.apiKey.oneTimeDescriptionCreated")} />
<TextInput className="w-full max-w-full" label={t("models.apiKey.oneTimeLabel")} showLabel>
<TextInput.Input className="select-all font-mono" value={apiKey.key} readOnly data-ui-id="ui.settings.apiKeys.createdDialog.value" />
</TextInput>
</FormDialog>
);
}
@@ -0,0 +1,82 @@
// Guards the rebuilt "API-Aufrufe" table: rows render with the badge buckets the
// old SimpleBadge stack used, the empty state replaces the bare "no records"
// line, and the pagination footer only offers the steps that exist.
import { fireEvent, render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import { describe, expect, it, vi } from "vitest";
import type { ApiKeyLogDto } from "~/modules/api/dtos/ApiKeyLogDto";
import { ApiLogsPage, methodTone, speedLabelKey, statusTone } from "./ApiLogsPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (s: string) => s, i18n: { language: "de" } }),
}));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({
number: (value: number) => String(value),
dateTime: (value: string | Date) => String(value),
}),
}));
const LOG = {
id: "log_1",
createdAt: "2026-08-02T10:00:00.000Z",
apiKey: { alias: "Website Lead Intake" },
ip: "192.0.2.10",
endpoint: "/api/leads",
method: "POST",
params: "{}",
status: 201,
duration: 42,
error: null,
} as unknown as ApiKeyLogDto;
function renderPage(items: ApiKeyLogDto[], pagination = { page: 1, pageSize: 10, totalItems: items.length, totalPages: 1 }) {
const actions = { onSearchChange: vi.fn(), onToggleProperty: vi.fn(), onReset: vi.fn(), onPage: vi.fn() };
render(<ApiLogsPage items={items} properties={[]} pagination={pagination} search="" actions={actions} />);
return actions;
}
describe("ApiLogsPage", () => {
it("renders a call row", () => {
renderPage([LOG]);
expect(screen.getByText("/api/leads")).toBeInTheDocument();
expect(screen.getByText("POST")).toBeInTheDocument();
expect(screen.getByText("201")).toBeInTheDocument();
expect(screen.getByText("metrics.speed.fast")).toBeInTheDocument();
});
it("shows the empty state instead of a bare table", () => {
renderPage([]);
expect(screen.getByText("models.apiKeyLog.empty.title")).toBeInTheDocument();
expect(document.querySelector("[data-ui-id='ui.settings.apiLogs.table']")).toBeNull();
});
it("offers both page steps in the middle of the result set", () => {
const actions = renderPage([LOG], { page: 2, pageSize: 10, totalItems: 30, totalPages: 3 });
fireEvent.click(document.querySelector("[data-ui-id='ui.settings.apiLogs.prev']")!);
expect(actions.onPage).toHaveBeenCalledWith(1);
fireEvent.click(document.querySelector("[data-ui-id='ui.settings.apiLogs.next']")!);
expect(actions.onPage).toHaveBeenCalledWith(3);
});
it("offers no page step on a single-page result set", () => {
renderPage([LOG], { page: 1, pageSize: 10, totalItems: 5, totalPages: 1 });
expect(document.querySelector("[data-ui-id='ui.settings.apiLogs.prev']")).toBeNull();
expect(document.querySelector("[data-ui-id='ui.settings.apiLogs.next']")).toBeNull();
});
it("keeps the badge buckets of the replaced SimpleBadge stack", () => {
expect(methodTone("DELETE")).toBe("subtle-negative");
expect(methodTone("HEAD")).toBe("subtle-neutral");
expect(statusTone(204)).toBe("subtle-positive");
expect(statusTone(500)).toBe("subtle-negative");
expect(statusTone(null)).toBe("subtle-warning");
expect(speedLabelKey(5)).toBe("metrics.speed.lightningFast");
expect(speedLabelKey(2500)).toBe("metrics.speed.verySlow");
});
});
@@ -0,0 +1,197 @@
// "API-Aufrufe" on the list chrome the rest of the product wears: the shared
// facet filter bar, a ~/ui Table and the same server-side pagination footer the
// audit viewer uses.
//
// It replaces the boilerplate TableSimple/InputFilters/InputSearchWithURL stack
// for the tenant tab only — the admin log route keeps ApiKeyLogsDetails, which
// also carries row selection and bulk delete. Filtering is server-side, so every
// interaction is reported to the route, which turns it into query parameters.
import { useTranslation } from "react-i18next";
import type { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import type { PaginationDto } from "~/application/dtos/data/PaginationDto";
import type { ApiKeyLogDto } from "~/modules/api/dtos/ApiKeyLogDto";
import { useLocaleFormatters } from "~/locale/format";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { EmptyState } from "~/ui/components/EmptyState";
import { Table } from "~/ui/components/Table";
import { ApiFilterBar } from "./ApiFilterBar";
export type ApiLogsActions = {
onSearchChange: (value: string) => void;
onToggleProperty: (name: string, value: string) => void;
onReset: () => void;
onPage: (page: number) => void;
};
type BadgeTone = React.ComponentProps<typeof BadgeFeedback>["farbe"];
/** Same buckets the old SimpleBadge used, mapped onto the kit's feedback tones. */
export function methodTone(method: string): BadgeTone {
if (method === "POST") return "subtle-positive";
if (method === "GET") return "subtle-information";
if (method === "PUT" || method === "PATCH") return "subtle-warning";
if (method === "DELETE") return "subtle-negative";
return "subtle-neutral";
}
export function statusTone(status: number | null): BadgeTone {
if (status === null) return "subtle-warning";
if (status >= 200 && status < 300) return "subtle-positive";
if (status >= 300 && status < 400) return "subtle-warning";
if (status >= 400) return "subtle-negative";
return "subtle-neutral";
}
/** Duration buckets of the old ApiCallSpeedBadge, unchanged. */
export function speedLabelKey(duration: number): string {
if (duration < 10) return "metrics.speed.lightningFast";
if (duration < 100) return "metrics.speed.fast";
if (duration < 1000) return "metrics.speed.average";
if (duration < 2000) return "metrics.speed.slow";
return "metrics.speed.verySlow";
}
export function speedTone(duration: number): BadgeTone {
if (duration < 100) return "subtle-positive";
if (duration < 1000) return "subtle-warning";
return "subtle-negative";
}
const CELL_CLASS = "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary";
const MUTED_CLASS = "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary";
export function ApiLogsPage({
items,
properties,
pagination,
search,
actions,
}: {
items: readonly ApiKeyLogDto[];
properties: readonly FilterablePropertyDto[];
pagination: PaginationDto;
search: string;
actions: ApiLogsActions;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const duration = (value: number | null) =>
value === null ? (
<span className={MUTED_CLASS}>{t("shared.notSet")}</span>
) : (
<span className={CELL_CLASS}>{formatters.number(Number(value), { style: "unit", unit: "millisecond", unitDisplay: "short", maximumFractionDigits: 3 })}</span>
);
return (
<div className="flex w-full flex-col gap-4" data-ui-id="ui.settings.apiLogs">
<ApiFilterBar
uiId="ui.settings.apiLogs.filter"
properties={properties}
search={search}
onSearchChange={actions.onSearchChange}
onToggleProperty={actions.onToggleProperty}
onReset={actions.onReset}
/>
{items.length === 0 ? (
<div data-ui-id="ui.settings.apiLogs.empty">
<EmptyState outlined title={t("models.apiKeyLog.empty.title")} body={t("models.apiKeyLog.empty.description")} />
</div>
) : (
<div className="w-full overflow-x-auto" data-ui-id="ui.settings.apiLogs.table">
<Table
header={
<Table.HeaderRow>
<Table.HeaderCell>{t("shared.createdAt")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKey.alias")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.ip")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.endpoint")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.method")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.duration")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.speed")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.error")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{items.map((item) => (
<Table.Row key={item.id} data-row-id={item.id}>
<Table.Cell>
<span className={CELL_CLASS}>
<time dateTime={new Date(item.createdAt).toISOString()}>{formatters.dateTime(item.createdAt)}</time>
</span>
</Table.Cell>
<Table.Cell>
<span className={CELL_CLASS}>{item.apiKey?.alias ?? t("shared.notSet")}</span>
</Table.Cell>
<Table.Cell>
<span className={item.ip.length > 0 ? CELL_CLASS : MUTED_CLASS}>{item.ip.length > 0 ? item.ip : t("shared.notSet")}</span>
</Table.Cell>
<Table.Cell>
<span className="font-mono text-body-small-regular-0 text-text-neutral-primary">{item.endpoint}</span>
</Table.Cell>
<Table.Cell>
<BadgeFeedback farbe={methodTone(item.method)} size="small">
{item.method}
</BadgeFeedback>
</Table.Cell>
<Table.Cell>
{item.status === null ? (
<span className={MUTED_CLASS}>{t("shared.notSet")}</span>
) : (
<BadgeFeedback farbe={statusTone(item.status)} size="small">
{String(item.status)}
</BadgeFeedback>
)}
</Table.Cell>
<Table.Cell>{duration(item.duration)}</Table.Cell>
<Table.Cell>
{item.duration === null ? (
<span className={MUTED_CLASS}>{t("shared.notSet")}</span>
) : (
<BadgeFeedback farbe={speedTone(Number(item.duration))} size="small">
{t(speedLabelKey(Number(item.duration)))}
</BadgeFeedback>
)}
</Table.Cell>
<Table.Cell>
{/* An empty error column is the normal case — a dash reads
quieter there than a spelled-out "not set". */}
<span className={item.error ? "text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" : MUTED_CLASS}>
{item.error || "—"}
</span>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
)}
{/* Server-side pagination, same shape as the audit viewer's footer. */}
<div className="flex items-center justify-between" data-ui-id="ui.settings.apiLogs.pagination">
<span className={CELL_CLASS}>
{t("shared.pageInfo", {
page: pagination.page,
totalPages: Math.max(pagination.totalPages, 1),
total: formatters.number(pagination.totalItems),
})}
</span>
<div className="flex gap-2">
{pagination.page > 1 ? (
<Button variant="tertiary" onClick={() => actions.onPage(pagination.page - 1)} data-ui-id="ui.settings.apiLogs.prev">
{t("shared.previous")}
</Button>
) : null}
{pagination.page < pagination.totalPages ? (
<Button variant="tertiary" onClick={() => actions.onPage(pagination.page + 1)} data-ui-id="ui.settings.apiLogs.next">
{t("shared.next")}
</Button>
) : null}
</div>
</div>
</div>
);
}
@@ -0,0 +1,184 @@
// "Übersicht" — API calls grouped by method/endpoint/status, on the same list
// chrome as the neighbouring tabs.
//
// Replaces the boilerplate InputCombobox + InputFilters + TableSimple stack of
// ApiKeyLogsSummary for the tenant tab. The grouping control keeps its URL
// contract (repeated `groupBy` parameters) and sits inside the filter bar, next
// to the facets it orders. The row link into "API-Aufrufe" carries the group's
// values as filters, exactly as before.
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { FeatherLayers } from "@subframe/core";
import type { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import type { ApiCallSummaryDto } from "~/modules/api/dtos/ApiCallSummaryDto";
import { useLocaleFormatters } from "~/locale/format";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { DropdownMenuMultiSelect } from "~/ui/components/DropdownMenuMultiSelect";
import { EmptyState } from "~/ui/components/EmptyState";
import { FilterBar } from "~/ui/components/FilterBar";
import { Table } from "~/ui/components/Table";
import { ApiFilterBar } from "./ApiFilterBar";
import { methodTone, speedLabelKey, speedTone, statusTone } from "./ApiLogsPage";
/** Group-by keys the service accepts; the tenant tab has no tenant grouping. */
export const GROUP_BY_KEYS = ["method", "endpoint", "params", "status"] as const;
export type GroupByKey = (typeof GROUP_BY_KEYS)[number];
export type ApiSummaryActions = {
onSearchChange: (value: string) => void;
onToggleProperty: (name: string, value: string) => void;
onToggleGroupBy: (key: GroupByKey) => void;
onReset: () => void;
};
const CELL_CLASS = "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary";
const MUTED_CLASS = "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary";
const GROUP_LABEL_KEY: Record<GroupByKey, string> = {
method: "models.apiKeyLog.method",
endpoint: "models.apiKeyLog.endpoint",
params: "models.apiKeyLog.params",
status: "models.apiKeyLog.status",
};
export function ApiSummaryPage({
items,
properties,
groupBy,
search,
detailHrefFor,
actions,
}: {
items: readonly ApiCallSummaryDto[];
properties: readonly FilterablePropertyDto[];
groupBy: readonly GroupByKey[];
search: string;
/** Link into the calls tab, pre-filtered with this row's group values. */
detailHrefFor: (item: ApiCallSummaryDto) => string;
actions: ApiSummaryActions;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<div className="flex w-full flex-col gap-4" data-ui-id="ui.settings.apiSummary">
<ApiFilterBar
uiId="ui.settings.apiSummary.filter"
properties={properties}
search={search}
onSearchChange={actions.onSearchChange}
onToggleProperty={actions.onToggleProperty}
onReset={actions.onReset}
afterFacets={
<FilterBar.StatusFilterButton
icon={<FeatherLayers />}
label={t("models.apiKeyLog.groupBy.prefix")}
showCount={groupBy.length > 0}
count={groupBy.length > 0 ? String(groupBy.length) : ""}
data-ui-id="ui.settings.apiSummary.groupBy"
dropdown={
<DropdownMenuMultiSelect>
{GROUP_BY_KEYS.map((key) => (
<DropdownMenuMultiSelect.DropdownItem
key={key}
showCheckbox
selected={groupBy.includes(key)}
onClick={() => actions.onToggleGroupBy(key)}
data-ui-id={`ui.settings.apiSummary.groupBy.${key}`}
>
{t(GROUP_LABEL_KEY[key])}
</DropdownMenuMultiSelect.DropdownItem>
))}
</DropdownMenuMultiSelect>
}
/>
}
/>
{groupBy.length === 0 ? (
<Alert variant="warning" title={t("models.apiKeyLog.groupBy.title")} description={t("models.apiKeyLog.groupBy.required")} />
) : items.length === 0 ? (
<div data-ui-id="ui.settings.apiSummary.empty">
<EmptyState outlined title={t("models.apiKeyLog.empty.title")} body={t("models.apiKeyLog.empty.description")} />
</div>
) : (
<div className="w-full overflow-x-auto" data-ui-id="ui.settings.apiSummary.table">
<Table
header={
<Table.HeaderRow>
{groupBy.map((key) => (
<Table.HeaderCell key={key}>{t(GROUP_LABEL_KEY[key])}</Table.HeaderCell>
))}
<Table.HeaderCell>{t("models.apiKeyLog.apiCalls")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.avgDuration")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKeyLog.speed")}</Table.HeaderCell>
<Table.HeaderCell />
</Table.HeaderRow>
}
>
{items.map((item, index) => {
const average = item._avg.duration === null ? null : Number(item._avg.duration);
return (
<Table.Row key={`${index}-${item.method}-${item.endpoint}`}>
{groupBy.map((key) => (
<Table.Cell key={key}>{groupCell(key, item)}</Table.Cell>
))}
<Table.Cell>
<span className={CELL_CLASS}>
{t("models.apiKeyLog.calls", { count: Number(item._count._all), formattedCount: formatters.number(Number(item._count._all)) })}
</span>
</Table.Cell>
<Table.Cell>
{average === null ? (
<span className={MUTED_CLASS}>{t("shared.notAvailable")}</span>
) : (
<span className={CELL_CLASS}>
{formatters.number(average, { style: "unit", unit: "millisecond", unitDisplay: "short", maximumFractionDigits: 3 })}
</span>
)}
</Table.Cell>
<Table.Cell>
{average === null ? (
<span className={MUTED_CLASS}>{t("shared.notAvailable")}</span>
) : (
<BadgeFeedback farbe={speedTone(average)} size="small">
{t(speedLabelKey(average))}
</BadgeFeedback>
)}
</Table.Cell>
<Table.Cell variant="align-right">
<Link to={detailHrefFor(item)} className="text-body-small-regular-0 text-text-feedback-link-default underline">
{t("shared.details")}
</Link>
</Table.Cell>
</Table.Row>
);
})}
</Table>
</div>
)}
</div>
);
function groupCell(key: GroupByKey, item: ApiCallSummaryDto) {
if (key === "method") {
return (
<BadgeFeedback farbe={methodTone(item.method)} size="small">
{item.method}
</BadgeFeedback>
);
}
if (key === "status") {
return item.status === null ? (
<span className={MUTED_CLASS}>{t("shared.unknown")}</span>
) : (
<BadgeFeedback farbe={statusTone(item.status)} size="small">
{String(item.status)}
</BadgeFeedback>
);
}
return <span className="font-mono text-body-small-regular-0 text-text-neutral-primary">{key === "endpoint" ? item.endpoint : item.params}</span>;
}
}