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
@@ -1,9 +0,0 @@
|
||||
import Page404 from "~/components/pages/Page404";
|
||||
|
||||
export default function AdminRoute404() {
|
||||
return (
|
||||
<>
|
||||
<Page404 withLogo={false} withFooter={false} withGoBack={false} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -3,20 +3,16 @@ import { Outlet } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import UserIcon from "~/components/ui/icons/UserIcon";
|
||||
import CustomerIcon from "~/components/ui/icons/settings/CustomerIcon";
|
||||
import CustomerIconFilled from "~/components/ui/icons/settings/CustomerIconFilled";
|
||||
import CompanyIcon from "~/components/ui/icons/crm/CompanyIcon";
|
||||
import CompanyIconFilled from "~/components/ui/icons/crm/CompanyIconFilled";
|
||||
import { LinkIcon, LockIcon, NoSymbolIcon, ServerStackIcon } from "~/components/ui/icons/vendor";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { LockIcon, NoSymbolIcon, ServerStackIcon } from "~/components/ui/icons/vendor";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const loader = async ({ request: _request, params: _params }: LoaderFunctionArgs) => {
|
||||
const data: LoaderData = {
|
||||
title: "",
|
||||
};
|
||||
@@ -27,7 +23,6 @@ export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.t
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration } = useRootData();
|
||||
return <Outlet />;
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
@@ -55,14 +50,6 @@ export default () => {
|
||||
icon: <LockIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <LockIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.navigation.relationships"),
|
||||
href: adminPath("accounts/relationships", { mode: "host-aware" }),
|
||||
// permission: "admin.relationships.view",
|
||||
hidden: !appConfiguration.app.features.tenantTypes,
|
||||
icon: <LinkIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <LinkIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.navigation.subscriptions"),
|
||||
href: adminPath("accounts/subscriptions", { mode: "host-aware" }),
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllTenantUsers } from "~/utils/db/users.db.server";
|
||||
import { getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantConnectorRows } from "~/services/admin/subscription-assembly.server";
|
||||
import { getTenantNoteRows } from "~/services/admin/tenant-notes.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { loader } from "./$id";
|
||||
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/services/admin/subscription-assembly.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/subscription-assembly.server")>("~/services/admin/subscription-assembly.server");
|
||||
return { ...actual, getTenantConnectorRows: vi.fn(), setTenantFeatureConnector: vi.fn() };
|
||||
});
|
||||
vi.mock("~/services/admin/tenant-notes.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/tenant-notes.server")>("~/services/admin/tenant-notes.server");
|
||||
return { ...actual, getTenantNoteRows: vi.fn(), createTenantNote: vi.fn(), deleteTenantNote: vi.fn() };
|
||||
});
|
||||
vi.mock("~/utils/db.server", () => ({ db: { tenantSubscription: { findUnique: vi.fn() } } }));
|
||||
vi.mock("~/utils/db/tenants.db.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/utils/db/tenants.db.server")>("~/utils/db/tenants.db.server");
|
||||
return { ...actual, getTenant: vi.fn() };
|
||||
});
|
||||
vi.mock("~/utils/db/users.db.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/utils/db/users.db.server")>("~/utils/db/users.db.server");
|
||||
return { ...actual, adminGetAllTenantUsers: vi.fn() };
|
||||
});
|
||||
vi.mock("~/utils/db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn() }));
|
||||
vi.mock("~/utils/db/subscriptionProducts.db.server", () => ({ getAllSubscriptionProducts: vi.fn() }));
|
||||
|
||||
describe("admin account tenant RLS context", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
|
||||
vi.mocked(getTenant).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return {
|
||||
id: "tenant_1",
|
||||
name: "Acme",
|
||||
slug: "acme",
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
users: [],
|
||||
} as never;
|
||||
});
|
||||
vi.mocked(adminGetAllTenantUsers).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return [];
|
||||
});
|
||||
vi.mocked(getTenantSubscription).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return null;
|
||||
});
|
||||
vi.mocked(getAllSubscriptionProducts).mockResolvedValue([]);
|
||||
vi.mocked(getTenantConnectorRows).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return [];
|
||||
});
|
||||
vi.mocked(getTenantNoteRows).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return [];
|
||||
});
|
||||
vi.mocked(db.tenantSubscription.findUnique).mockImplementation((async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return null;
|
||||
}) as never);
|
||||
});
|
||||
|
||||
it("binds the target tenant only after the admin permission check", async () => {
|
||||
const data = await loader({
|
||||
request: new Request("https://admin.example.test/accounts/tenant_1"),
|
||||
params: { id: "tenant_1" },
|
||||
context: {},
|
||||
} as LoaderFunctionArgs);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.view");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getTenant).mock.invocationCallOrder[0]);
|
||||
expect(data.tenant.id).toBe("tenant_1");
|
||||
});
|
||||
});
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import {
|
||||
forgetTenantTrustedDevice,
|
||||
getTenantSecuritySnapshot,
|
||||
revokeTenantUserSession,
|
||||
TenantSecurityError,
|
||||
} from "~/services/admin/tenant-security.server";
|
||||
import { action, loader } from "./$id.security";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({ default: () => null }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
||||
vi.mock("~/locale/format", () => ({
|
||||
useLocaleFormatters: () => ({
|
||||
dateTime: (value: string) => value,
|
||||
}),
|
||||
}));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/services/admin/tenant-security.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/tenant-security.server")>("~/services/admin/tenant-security.server");
|
||||
return {
|
||||
...actual,
|
||||
getTenantSecuritySnapshot: vi.fn(),
|
||||
revokeTenantUserSession: vi.fn(),
|
||||
forgetTenantTrustedDevice: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
function callLoader(id = "tenant_1") {
|
||||
return loader({ request: new Request("https://admin.example.test/accounts/tenant_1/security"), params: { id }, context: {} } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
function callAction(form: Record<string, string>, id = "tenant_1") {
|
||||
return action({
|
||||
request: new Request("https://admin.example.test/accounts/tenant_1/security", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams(form),
|
||||
}),
|
||||
params: { id },
|
||||
context: {},
|
||||
} as ActionFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant security route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "admin_1" } as never);
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "admin_1", email: "admin@hivegrid.de" } as never);
|
||||
vi.mocked(getTenantSecuritySnapshot).mockResolvedValue({
|
||||
now: "2026-07-09T10:00:00.000Z",
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", active: true },
|
||||
users: [
|
||||
{
|
||||
id: "user_1",
|
||||
email: "owner@example.test",
|
||||
name: "Owner Example",
|
||||
active: true,
|
||||
membershipStatus: "active",
|
||||
mfaEnabled: true,
|
||||
mfaPending: false,
|
||||
recoveryCodesConfigured: true,
|
||||
},
|
||||
],
|
||||
sessions: [],
|
||||
trustedDevices: [],
|
||||
magicLinks: [],
|
||||
ipLogs: [],
|
||||
auditEvents: [],
|
||||
});
|
||||
vi.mocked(revokeTenantUserSession).mockResolvedValue(undefined);
|
||||
vi.mocked(forgetTenantTrustedDevice).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("checks the tenant view permission and builds the security VM", async () => {
|
||||
vi.mocked(getTenantSecuritySnapshot).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
return {
|
||||
now: "2026-07-09T10:00:00.000Z",
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", active: true },
|
||||
users: [
|
||||
{
|
||||
id: "user_1",
|
||||
email: "owner@example.test",
|
||||
name: "Owner Example",
|
||||
active: true,
|
||||
membershipStatus: "active",
|
||||
mfaEnabled: true,
|
||||
mfaPending: false,
|
||||
recoveryCodesConfigured: true,
|
||||
},
|
||||
],
|
||||
sessions: [],
|
||||
trustedDevices: [],
|
||||
magicLinks: [],
|
||||
ipLogs: [],
|
||||
auditEvents: [],
|
||||
};
|
||||
});
|
||||
const data = await callLoader();
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.view");
|
||||
expect(getTenantSecuritySnapshot).toHaveBeenCalledWith("tenant_1");
|
||||
expect(data.vm.status).toBe("ready");
|
||||
});
|
||||
|
||||
it("redirects to account list when the tenant is missing", async () => {
|
||||
vi.mocked(getTenantSecuritySnapshot).mockRejectedValueOnce(new TenantSecurityError("TENANT_NOT_FOUND"));
|
||||
|
||||
await expect(callLoader("missing")).rejects.toMatchObject({ status: 302 });
|
||||
});
|
||||
|
||||
it("revokes a user session through the audited service", async () => {
|
||||
vi.mocked(revokeTenantUserSession).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
});
|
||||
const response = (await callAction({
|
||||
csrf: "csrf",
|
||||
action: "revoke-session",
|
||||
sessionId: "session_1",
|
||||
reason: "Supportfall MFA Reset",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.tenantSecurity.actions.sessionRevoked" });
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.settings.update");
|
||||
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(revokeTenantUserSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
sessionId: "session_1",
|
||||
reason: "Supportfall MFA Reset",
|
||||
actorUserId: "admin_1",
|
||||
actorEmail: "admin@hivegrid.de",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("forgets a trusted device through the audited service", async () => {
|
||||
vi.mocked(forgetTenantTrustedDevice).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
|
||||
});
|
||||
const response = (await callAction({
|
||||
csrf: "csrf",
|
||||
action: "forget-device",
|
||||
trustedDeviceId: "device_1",
|
||||
reason: "Geraet verloren",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.tenantSecurity.actions.deviceForgotten" });
|
||||
expect(forgetTenantTrustedDevice).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", trustedDeviceId: "device_1" }));
|
||||
});
|
||||
});
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
import {
|
||||
buildTenantSecurityVM,
|
||||
type TenantSecurityMetric,
|
||||
type TenantSecurityData,
|
||||
type TenantSecurityRisk,
|
||||
type TenantSecuritySessionRow,
|
||||
type TenantSecurityTone,
|
||||
type TenantSecurityTrustedDeviceRow,
|
||||
} from "@hivegrid/view-models";
|
||||
import { AlertTriangle, ArrowLeft, KeyRound, LinkIcon, MonitorSmartphone, ShieldCheck, ShieldX, UserRoundCheck } from "lucide-react";
|
||||
import type React from "react";
|
||||
import { Form, Link, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData, useNavigation, type ActionFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { Badge, type BadgeColor } from "~/components/ui/badge";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import {
|
||||
forgetTenantTrustedDevice,
|
||||
getTenantSecuritySnapshot,
|
||||
revokeTenantUserSession,
|
||||
TenantSecurityError,
|
||||
} from "~/services/admin/tenant-security.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildTenantSecurityVM>;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = params.id;
|
||||
if (!tenantId) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
try {
|
||||
const snapshot = await runWithRlsContext({ tenantId }, () => getTenantSecuritySnapshot(tenantId));
|
||||
return {
|
||||
title: `${t("admin.tenantSecurity.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildTenantSecurityVM(snapshot),
|
||||
} satisfies LoaderData;
|
||||
} catch (error) {
|
||||
if (error instanceof TenantSecurityError && error.code === "TENANT_NOT_FOUND") {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
function badRequest(data: ActionData) {
|
||||
return Response.json(data, { status: 400 });
|
||||
}
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.settings.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const userInfo = await getUserInfo(request);
|
||||
const actor = await getUser(userInfo.userId);
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const reason = form.get("reason")?.toString() ?? "";
|
||||
const tenantId = params.id ?? "";
|
||||
|
||||
try {
|
||||
if (action === "revoke-session") {
|
||||
await runWithRlsContext({ tenantId }, () =>
|
||||
revokeTenantUserSession({
|
||||
tenantId,
|
||||
sessionId: form.get("sessionId")?.toString() ?? "",
|
||||
reason,
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
})
|
||||
);
|
||||
return Response.json({ success: t("admin.tenantSecurity.actions.sessionRevoked") } satisfies ActionData);
|
||||
}
|
||||
if (action === "forget-device") {
|
||||
await runWithRlsContext({ tenantId }, () =>
|
||||
forgetTenantTrustedDevice({
|
||||
tenantId,
|
||||
trustedDeviceId: form.get("trustedDeviceId")?.toString() ?? "",
|
||||
reason,
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
})
|
||||
);
|
||||
return Response.json({ success: t("admin.tenantSecurity.actions.deviceForgotten") } satisfies ActionData);
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
} catch (error) {
|
||||
if (error && typeof error === "object" && "i18nKey" in error && typeof error.i18nKey === "string") {
|
||||
return badRequest({ error: t(error.i18nKey) });
|
||||
}
|
||||
if (error instanceof TenantSecurityError) {
|
||||
return badRequest({ error: t(`admin.tenantSecurity.errors.${error.code}`) });
|
||||
}
|
||||
return badRequest({ error: t("admin.tenantSecurity.errors.actionFailed") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function TenantSecurityRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const loading = navigation.state === "submitting";
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.tenantSecurity.title")} fullWidth>
|
||||
{data.vm.status === "ready" ? (
|
||||
<TenantSecurityPage data={data.vm.data} actionData={actionData} loading={loading} />
|
||||
) : (
|
||||
<div className="border-border bg-background rounded-md border p-6">
|
||||
<div className="font-medium">{t("admin.tenantSecurity.empty.title")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.tenantSecurity.empty.body")}</div>
|
||||
</div>
|
||||
)}
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function TenantSecurityPage({
|
||||
data,
|
||||
actionData,
|
||||
loading,
|
||||
}: {
|
||||
data: TenantSecurityData;
|
||||
actionData: ActionData | undefined;
|
||||
loading: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="border-border bg-surface-neutral-primary rounded-md border p-4">
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div className="min-w-0">
|
||||
<Link to={adminPath(`accounts/${data.tenant.id}`, { mode: "host-aware" })} className="text-primary inline-flex items-center gap-1 text-sm font-medium hover:underline">
|
||||
<ArrowLeft className="size-4" aria-hidden="true" />
|
||||
{t("admin.tenantSecurity.backToTenant")}
|
||||
</Link>
|
||||
<div className="text-muted-foreground mt-2 text-sm">
|
||||
{t("admin.tenantSecurity.description", { tenant: data.tenant.name, slug: data.tenant.slug })}
|
||||
</div>
|
||||
</div>
|
||||
<Badge color={riskBadgeColor(data.risk)} withColorDot>
|
||||
{t(data.riskLabelKey)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-3 text-sm">{t(data.riskDetailKey)}</div>
|
||||
{actionData?.success ? <div className="mt-3 rounded-md bg-green-50 px-3 py-2 text-sm text-green-800">{actionData.success}</div> : null}
|
||||
{actionData?.error ? <div className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-800">{actionData.error}</div> : null}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
|
||||
{data.metrics.map((metric) => (
|
||||
<MetricCard key={metric.id} metric={metric} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{data.issues.length > 0 ? (
|
||||
<Card className="gap-4 rounded-lg border-yellow-200 bg-yellow-50 py-5">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base text-yellow-950">
|
||||
<AlertTriangle className="size-5" aria-hidden="true" />
|
||||
{t("admin.tenantSecurity.issues.title")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ul className="grid gap-2 text-sm text-yellow-900 md:grid-cols-2">
|
||||
{data.issues.map((issue) => (
|
||||
<li key={issue}>{t(issue)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.users.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.users.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[760px] text-sm">
|
||||
<thead className="text-muted-foreground border-b text-left">
|
||||
<tr>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.user")}</th>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.status")}</th>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.mfa")}</th>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.recovery")}</th>
|
||||
<th className="py-2 pr-4 font-medium">{t("admin.tenantSecurity.users.columns.risk")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{data.users.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<td className="py-3 pr-4">
|
||||
<div className="font-medium">{user.name}</div>
|
||||
<div className="text-muted-foreground">{user.email}</div>
|
||||
</td>
|
||||
<td className="py-3 pr-4">{t(user.statusLabelKey)}</td>
|
||||
<td className="py-3 pr-4">{t(user.mfaLabelKey)}</td>
|
||||
<td className="py-3 pr-4">{user.recoveryCodesConfigured ? t("shared.yes") : t("shared.no")}</td>
|
||||
<td className="py-3 pr-4">
|
||||
<Badge color={riskBadgeColor(user.risk)} withColorDot>
|
||||
{t(user.riskLabelKey)}
|
||||
</Badge>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
<SessionsCard rows={data.sessions} loading={loading} />
|
||||
<TrustedDevicesCard rows={data.trustedDevices} loading={loading} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.magicLinks.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.magicLinks.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CompactRows
|
||||
emptyKey="admin.tenantSecurity.magicLinks.empty"
|
||||
rows={data.magicLinks.map((link) => ({
|
||||
id: link.id,
|
||||
title: link.userEmail,
|
||||
detail: `${t(link.statusLabelKey)} · ${link.expiresAt}`,
|
||||
tone: link.tone,
|
||||
}))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.ipLogs.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.ipLogs.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CompactRows
|
||||
emptyKey="admin.tenantSecurity.ipLogs.empty"
|
||||
rows={data.ipLogs.map((log) => ({
|
||||
id: log.id,
|
||||
title: `${log.maskedIp} · ${log.actorLabel}`,
|
||||
detail: `${log.fromUrl} · ${log.createdAt}`,
|
||||
tone: "neutral",
|
||||
}))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.audit.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.audit.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CompactRows
|
||||
emptyKey="admin.tenantSecurity.audit.empty"
|
||||
rows={data.auditEvents.map((event) => ({
|
||||
id: event.id,
|
||||
title: event.displaySummary,
|
||||
detail: `${event.actorEmail ?? event.actorId ?? "system"} · ${event.createdAt}`,
|
||||
tone: event.tone,
|
||||
}))}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCard({ metric }: { metric: TenantSecurityMetric }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<CardTitle className="text-sm leading-5">{t(metric.labelKey)}</CardTitle>
|
||||
<CardDescription className="mt-1 leading-5">{t(metric.detailKey)}</CardDescription>
|
||||
</div>
|
||||
<div className={`flex size-10 shrink-0 items-center justify-center rounded-md border ${toneIconClasses(metric.tone)}`}>{metricIcon(metric.id)}</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-semibold leading-7">{metric.value}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function SessionsCard({ rows, loading }: { rows: readonly TenantSecuritySessionRow[]; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
return (
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.sessions.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.sessions.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{rows.length === 0 ? <div className="text-muted-foreground text-sm">{t("admin.tenantSecurity.sessions.empty")}</div> : null}
|
||||
{rows.map((session) => (
|
||||
<div key={session.id} className="rounded-md border p-3">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="font-medium">{session.displayDevice}</div>
|
||||
<Badge color={toneBadgeColor(session.tone)} withColorDot>
|
||||
{t(session.statusLabelKey)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{session.userEmail}</div>
|
||||
<div className="text-muted-foreground mt-1 text-xs">
|
||||
{t("admin.tenantSecurity.sessions.lastSeen", { value: format.dateTime(session.lastSeenAt) })}
|
||||
</div>
|
||||
</div>
|
||||
{session.status === "active" || session.status === "trusted" ? (
|
||||
<SecurityActionForm action="revoke-session" idName="sessionId" idValue={session.id} buttonKey="admin.tenantSecurity.actions.revokeSession" loading={loading} />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function TrustedDevicesCard({ rows, loading }: { rows: readonly TenantSecurityTrustedDeviceRow[]; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
return (
|
||||
<Card className="gap-4 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("admin.tenantSecurity.devices.title")}</CardTitle>
|
||||
<CardDescription>{t("admin.tenantSecurity.devices.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{rows.length === 0 ? <div className="text-muted-foreground text-sm">{t("admin.tenantSecurity.devices.empty")}</div> : null}
|
||||
{rows.map((device) => (
|
||||
<div key={device.id} className="rounded-md border p-3">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="font-medium">{device.displayDevice}</div>
|
||||
<Badge color={toneBadgeColor(device.tone)} withColorDot>
|
||||
{t(device.statusLabelKey)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{device.userEmail}</div>
|
||||
<div className="text-muted-foreground mt-1 text-xs">
|
||||
{t("admin.tenantSecurity.devices.lastUsed", { value: format.dateTime(device.lastUsedAt) })}
|
||||
</div>
|
||||
</div>
|
||||
{device.status === "active" ? (
|
||||
<SecurityActionForm action="forget-device" idName="trustedDeviceId" idValue={device.id} buttonKey="admin.tenantSecurity.actions.forgetDevice" loading={loading} />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function SecurityActionForm({
|
||||
action,
|
||||
idName,
|
||||
idValue,
|
||||
buttonKey,
|
||||
loading,
|
||||
}: {
|
||||
action: string;
|
||||
idName: string;
|
||||
idValue: string;
|
||||
buttonKey: string;
|
||||
loading: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
return (
|
||||
<Form method="post" className="flex w-full flex-col gap-2 md:w-72">
|
||||
<input type="hidden" name="action" value={action} />
|
||||
<input type="hidden" name={idName} value={idValue} />
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} />
|
||||
<input
|
||||
name="reason"
|
||||
required
|
||||
minLength={5}
|
||||
placeholder={t("admin.tenantSecurity.actions.reasonPlaceholder")}
|
||||
className="border-border bg-background h-9 rounded-md border px-3 text-sm focus-visible:outline-none focus-visible:shadow-focus"
|
||||
/>
|
||||
<ButtonSecondary disabled={loading} type="submit">
|
||||
{t(buttonKey)}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function CompactRows({
|
||||
rows,
|
||||
emptyKey,
|
||||
}: {
|
||||
rows: readonly { readonly id: string; readonly title: string; readonly detail: string; readonly tone: TenantSecurityTone }[];
|
||||
emptyKey: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (rows.length === 0) return <div className="text-muted-foreground text-sm">{t(emptyKey)}</div>;
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{rows.map((row) => (
|
||||
<div key={row.id} className="flex items-start justify-between gap-3 rounded-md border p-3 text-sm">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-medium">{row.title}</div>
|
||||
<div className="text-muted-foreground mt-1 truncate">{row.detail}</div>
|
||||
</div>
|
||||
<span className={`mt-1 size-2 shrink-0 rounded-full ${toneDotClass(row.tone)}`} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function metricIcon(id: string): React.ReactNode {
|
||||
if (id === "mfa") return <ShieldCheck className="size-5" aria-hidden="true" />;
|
||||
if (id === "sessions") return <MonitorSmartphone className="size-5" aria-hidden="true" />;
|
||||
if (id === "devices") return <KeyRound className="size-5" aria-hidden="true" />;
|
||||
if (id === "magicLinks") return <LinkIcon className="size-5" aria-hidden="true" />;
|
||||
if (id === "loginFailures") return <ShieldX className="size-5" aria-hidden="true" />;
|
||||
return <UserRoundCheck className="size-5" aria-hidden="true" />;
|
||||
}
|
||||
|
||||
function riskBadgeColor(risk: TenantSecurityRisk): BadgeColor {
|
||||
if (risk === "high") return "red";
|
||||
if (risk === "medium") return "yellow";
|
||||
return "green";
|
||||
}
|
||||
|
||||
function toneBadgeColor(tone: TenantSecurityTone): BadgeColor {
|
||||
if (tone === "danger") return "red";
|
||||
if (tone === "warning") return "yellow";
|
||||
if (tone === "success") return "green";
|
||||
return "gray";
|
||||
}
|
||||
|
||||
function toneIconClasses(tone: TenantSecurityTone): string {
|
||||
if (tone === "danger") return "border-red-200 bg-red-50 text-red-700";
|
||||
if (tone === "warning") return "border-yellow-200 bg-yellow-50 text-yellow-700";
|
||||
if (tone === "success") return "border-green-200 bg-green-50 text-green-700";
|
||||
return "border-border bg-surface-neutral-primary text-muted-foreground";
|
||||
}
|
||||
|
||||
function toneDotClass(tone: TenantSecurityTone): string {
|
||||
if (tone === "danger") return "bg-red-500";
|
||||
if (tone === "warning") return "bg-yellow-500";
|
||||
if (tone === "success") return "bg-green-500";
|
||||
return "bg-gray-300";
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { buildTenantSupportSummary } from "./$id";
|
||||
|
||||
describe("admin tenant support console", () => {
|
||||
it("builds tenant-specific support metrics and deep links", () => {
|
||||
const summary = buildTenantSupportSummary({
|
||||
tenant: {
|
||||
id: "tenant_1",
|
||||
slug: "acme",
|
||||
name: "Acme",
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
users: [
|
||||
{
|
||||
type: TenantUserType.OWNER,
|
||||
user: { email: "owner@example.test" },
|
||||
},
|
||||
],
|
||||
} as never,
|
||||
users: [
|
||||
{
|
||||
email: "owner@example.test",
|
||||
tenants: [{ tenantId: "tenant_1", status: TenantUserStatus.ACTIVE }],
|
||||
},
|
||||
{
|
||||
email: "inactive@example.test",
|
||||
tenants: [{ tenantId: "tenant_1", status: TenantUserStatus.INACTIVE }],
|
||||
},
|
||||
] as never,
|
||||
subscription: {
|
||||
status: "past_due",
|
||||
planCode: "business",
|
||||
seatQuantity: 7,
|
||||
lagoCustomerId: "lago_1",
|
||||
mollieCustomerId: null,
|
||||
pastDueSince: new Date("2026-07-01T00:00:00.000Z"),
|
||||
frozenAt: null,
|
||||
} as never,
|
||||
});
|
||||
|
||||
expect(summary).toMatchObject({
|
||||
status: "warning",
|
||||
ownerEmail: "owner@example.test",
|
||||
planCode: "business",
|
||||
seatQuantity: 7,
|
||||
billingStatus: "past_due",
|
||||
providerSummaryKey: "admin.accounts.supportConsole.providers.partial",
|
||||
});
|
||||
expect(summary.metrics).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: "users", value: "1", href: "/accounts/users?tenantId=tenant_1" }),
|
||||
expect.objectContaining({ id: "billing", value: "past_due", tone: "warning", href: "/system/billing" }),
|
||||
expect.objectContaining({ id: "providers", value: "Lago", tone: "warning", href: "/system/billing" }),
|
||||
])
|
||||
);
|
||||
expect(summary.actions).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: "users", href: "/accounts/users?tenantId=tenant_1" }),
|
||||
expect.objectContaining({ id: "audit", href: "/audit?tenantId=tenant_1" }),
|
||||
expect.objectContaining({ id: "events", href: "/events?tenantId=tenant_1" }),
|
||||
])
|
||||
);
|
||||
});
|
||||
});
|
||||
+564
-165
@@ -1,6 +1,7 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { ActionFunction, Link, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData, useNavigation } from "react-router";
|
||||
import { useActionData, useParams, useSubmit } from "react-router";
|
||||
import { Activity, ArrowRight, CreditCard, ExternalLink, KeyRound, ShieldAlert, Users } from "lucide-react";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant, getTenantBySlug, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import UpdateTenantDetailsForm from "~/components/core/tenants/UpdateTenantDetailsForm";
|
||||
@@ -22,53 +23,128 @@ import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsServ
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { getAllTenantTypes, getTenantTypeOptions } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import { AccountUpdatedDto } from "~/modules/events/dtos/AccountUpdatedDto";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
|
||||
import { Badge, type BadgeColor } from "~/components/ui/badge";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import {
|
||||
ADMIN_TENANT_NOTE_CATEGORIES,
|
||||
buildAdminConnectorListVM,
|
||||
buildAdminTenantNoteListVM,
|
||||
type AdminConnectorListVM,
|
||||
type AdminTenantNoteListVM,
|
||||
type ConnectorOverrideState,
|
||||
} from "@hivegrid/view-models";
|
||||
import { AdminTenantOperationsPanel } from "~/components/screens/admin/AdminTenantOperationsPanel";
|
||||
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
|
||||
import { AdminBillingError, extendTenantTrial } from "~/services/admin/billing-admin.server";
|
||||
import { AdminConnectorError, getTenantConnectorRows, setTenantFeatureConnector } from "~/services/admin/subscription-assembly.server";
|
||||
import { createTenantNote, deleteTenantNote, getTenantNoteRows, TenantNoteError } from "~/services/admin/tenant-notes.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type TenantSupportTone = "success" | "warning" | "danger" | "neutral";
|
||||
|
||||
type TenantSupportMetric = {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
value: string;
|
||||
detailKey: string;
|
||||
tone: TenantSupportTone;
|
||||
href?: string;
|
||||
};
|
||||
|
||||
type TenantSupportAction = {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
detailKey: string;
|
||||
href: string;
|
||||
external?: boolean;
|
||||
};
|
||||
|
||||
type TenantSupportSummary = {
|
||||
status: TenantSupportTone;
|
||||
statusLabelKey: string;
|
||||
statusDetail: string | null;
|
||||
ownerEmail: string | null;
|
||||
planCode: string | null;
|
||||
seatQuantity: number | null;
|
||||
billingStatus: string | null;
|
||||
providerSummaryKey: string;
|
||||
metrics: TenantSupportMetric[];
|
||||
actions: TenantSupportAction[];
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenant: TenantWithDetails;
|
||||
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
tenantTypes: Awaited<ReturnType<typeof getTenantTypeOptions>>;
|
||||
supportSummary: TenantSupportSummary;
|
||||
connectors: AdminConnectorListVM;
|
||||
notes: AdminTenantNoteListVM;
|
||||
trial: { status: string | null; trialEndsAtIso: string | null };
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenant = await getTenant(params.id!);
|
||||
if (!tenant) {
|
||||
const tenantId = params.id;
|
||||
if (!tenantId) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
const [users, subscription, subscriptionProducts, tenantTypes] = await Promise.all([
|
||||
adminGetAllTenantUsers(tenant.id),
|
||||
getTenantSubscription(params.id ?? ""),
|
||||
getAllSubscriptionProducts(),
|
||||
getTenantTypeOptions(),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
|
||||
tenant,
|
||||
users,
|
||||
subscription,
|
||||
subscriptionProducts,
|
||||
tenantTypes,
|
||||
};
|
||||
return data;
|
||||
|
||||
return runWithRlsContext({ tenantId }, async () => {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!tenant) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
const [users, subscription, subscriptionProducts, connectorRows, noteRows, trialSubscription] = await Promise.all([
|
||||
adminGetAllTenantUsers(tenant.id),
|
||||
getTenantSubscription(tenantId),
|
||||
getAllSubscriptionProducts(),
|
||||
getTenantConnectorRows(tenantId),
|
||||
getTenantNoteRows(tenantId),
|
||||
db.tenantSubscription.findUnique({ where: { tenantId }, select: { status: true, trialEndsAt: true } }),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
|
||||
tenant,
|
||||
users,
|
||||
subscription,
|
||||
subscriptionProducts,
|
||||
supportSummary: buildTenantSupportSummary({ tenant, users, subscription }),
|
||||
connectors: buildAdminConnectorListVM({ rows: connectorRows }),
|
||||
notes: buildAdminTenantNoteListVM({ rows: noteRows }),
|
||||
trial: {
|
||||
status: trialSubscription?.status ?? null,
|
||||
trialEndsAtIso: trialSubscription?.trialEndsAt?.toISOString() ?? null,
|
||||
},
|
||||
};
|
||||
return data;
|
||||
});
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
updateSubscriptionSuccess?: string;
|
||||
updateDetailsError?: string;
|
||||
updateSubscriptionError?: string;
|
||||
opsSuccess?: string;
|
||||
opsError?: string;
|
||||
};
|
||||
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
@@ -83,91 +159,146 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
const tenant = await getTenant(params.id ?? "");
|
||||
if (!tenant) {
|
||||
const tenantId = params.id;
|
||||
if (!tenantId) {
|
||||
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const icon = form.get("icon")?.toString() ?? "";
|
||||
const typeIds = form.getAll("typeIds[]").map((t) => t.toString());
|
||||
|
||||
if ((name?.length ?? 0) < 1) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.nameRequired"),
|
||||
});
|
||||
}
|
||||
if (!slug || slug.length < 1) {
|
||||
return badRequest({ updateDetailsError: t("settings.tenant.errors.slugRequired") });
|
||||
return runWithRlsContext({ tenantId }, async () => {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!tenant) {
|
||||
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
let tenantTypes = await getAllTenantTypes();
|
||||
typeIds.forEach((type) => {
|
||||
if (!tenantTypes.find((t) => t.id === type)) {
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const icon = form.get("icon")?.toString() ?? "";
|
||||
|
||||
if ((name?.length ?? 0) < 1) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("admin.accounts.errors.invalidTenantType"),
|
||||
updateDetailsError: t("settings.tenant.errors.nameRequired"),
|
||||
});
|
||||
}
|
||||
});
|
||||
if (!slug || slug.length < 1) {
|
||||
return badRequest({ updateDetailsError: t("settings.tenant.errors.slugRequired") });
|
||||
}
|
||||
|
||||
if (isReservedTenantSlug(slug)) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.reservedSlug", { slug }),
|
||||
});
|
||||
}
|
||||
if (slug.includes(" ")) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugWhitespace"),
|
||||
});
|
||||
}
|
||||
|
||||
const existing = await getTenant(params.id!);
|
||||
if (!existing) {
|
||||
return badRequest({ updateDetailsError: t("admin.accounts.errors.invalidTenant") });
|
||||
}
|
||||
|
||||
if (existing.slug !== slug) {
|
||||
const existingSlug = await getTenantBySlug(slug);
|
||||
if (existingSlug) {
|
||||
if (isReservedTenantSlug(slug)) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugTaken"),
|
||||
updateDetailsError: t("settings.tenant.errors.reservedSlug", { slug }),
|
||||
});
|
||||
}
|
||||
if (slug.includes(" ")) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugWhitespace"),
|
||||
});
|
||||
}
|
||||
}
|
||||
await createAdminLog(request, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
||||
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.updated",
|
||||
tenantId: tenant.id,
|
||||
userId: currentUser.id,
|
||||
data: {
|
||||
id: tenant.id,
|
||||
new: { name, slug },
|
||||
old: { name: tenant.name, slug: tenant.slug },
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies AccountUpdatedDto,
|
||||
});
|
||||
await updateTenant(existing, { name, icon, slug, typeIds });
|
||||
return Response.json({
|
||||
success: t("settings.tenant.updated"),
|
||||
});
|
||||
} else if (action === "delete-tenant") {
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.deleted",
|
||||
tenantId: null,
|
||||
userId: userInfo.userId,
|
||||
data: { tenant: { id: tenant.id, name: tenant.name }, user: { id: currentUser.id, email: currentUser.email } } satisfies AccountDeletedDto,
|
||||
});
|
||||
await deleteAndCancelTenant({ tenantId: tenant.id, userId: currentUser.id });
|
||||
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
} else {
|
||||
return badRequest({ updateDetailsError: t("shared.invalidForm") });
|
||||
}
|
||||
const existing = await getTenant(tenantId);
|
||||
if (!existing) {
|
||||
return badRequest({ updateDetailsError: t("admin.accounts.errors.invalidTenant") });
|
||||
}
|
||||
|
||||
if (existing.slug !== slug) {
|
||||
const existingSlug = await getTenantBySlug(slug);
|
||||
if (existingSlug) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugTaken"),
|
||||
});
|
||||
}
|
||||
}
|
||||
await createAdminLog(request, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
||||
|
||||
await EventsService.createTenantEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "account.updated",
|
||||
tenantId: tenant.id,
|
||||
userId: currentUser.id,
|
||||
data: {
|
||||
id: tenant.id,
|
||||
new: { name, slug },
|
||||
old: { name: tenant.name, slug: tenant.slug },
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies AccountUpdatedDto,
|
||||
},
|
||||
() => updateTenant(existing, { name, icon, slug })
|
||||
);
|
||||
return Response.json({
|
||||
intent: "edit",
|
||||
ok: true,
|
||||
messageKey: "admin.accounts.toast.updated",
|
||||
} satisfies ActionData);
|
||||
} else if (action === "trial-extend" || action === "connector-set" || action === "note-create" || action === "note-delete") {
|
||||
const actor = { actorUserId: currentUser.id, actorEmail: currentUser.email, request };
|
||||
try {
|
||||
if (action === "trial-extend") {
|
||||
await extendTenantTrial({
|
||||
tenantId: tenant.id,
|
||||
days: form.get("days")?.toString() ?? "",
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
...actor,
|
||||
});
|
||||
return Response.json({ opsSuccess: t("admin.tenantOps.trial.extended") } satisfies ActionData);
|
||||
}
|
||||
if (action === "connector-set") {
|
||||
const state = form.get("state")?.toString() ?? "";
|
||||
if (state !== "enabled" && state !== "disabled" && state !== "inherit") {
|
||||
return badRequest({ opsError: t("shared.invalidForm") });
|
||||
}
|
||||
await setTenantFeatureConnector({
|
||||
tenantId: tenant.id,
|
||||
featureKey: form.get("featureKey")?.toString() ?? "",
|
||||
state: state satisfies ConnectorOverrideState,
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
...actor,
|
||||
});
|
||||
return Response.json({ opsSuccess: t("admin.connectors.updated") } satisfies ActionData);
|
||||
}
|
||||
if (action === "note-create") {
|
||||
await createTenantNote({
|
||||
tenantId: tenant.id,
|
||||
noteText: form.get("noteText")?.toString() ?? "",
|
||||
category: form.get("category")?.toString() ?? null,
|
||||
pinned: form.get("pinned")?.toString() === "true",
|
||||
authorUserId: currentUser.id,
|
||||
actorEmail: currentUser.email,
|
||||
request,
|
||||
});
|
||||
return Response.json({ opsSuccess: t("admin.tenantNotes.created") } satisfies ActionData);
|
||||
}
|
||||
await deleteTenantNote({
|
||||
noteId: form.get("noteId")?.toString() ?? "",
|
||||
tenantId: tenant.id,
|
||||
...actor,
|
||||
});
|
||||
return Response.json({ opsSuccess: t("admin.tenantNotes.deleted") } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminActionInputError || error instanceof AdminConnectorError || error instanceof TenantNoteError) {
|
||||
return badRequest({ opsError: t(error.i18nKey) });
|
||||
}
|
||||
if (error instanceof AdminBillingError) {
|
||||
return badRequest({ opsError: t(error.i18nKey) });
|
||||
}
|
||||
// Unexpected failures (e.g. the audit writer refusing an unauditable
|
||||
// action) surface as a Klartext banner instead of a naked 500 page.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("admin tenant-ops action failed", { action, tenantId }, error);
|
||||
return badRequest({ opsError: t("admin.tenantOps.errors.actionFailed") });
|
||||
}
|
||||
} else if (action === "delete-tenant") {
|
||||
await deleteAndCancelTenant({
|
||||
request,
|
||||
tenantId: tenant.id,
|
||||
userId: currentUser.id,
|
||||
eventData: { tenant: { id: tenant.id, name: tenant.name }, user: { id: currentUser.id, email: currentUser.email } } satisfies AccountDeletedDto,
|
||||
});
|
||||
return redirect(`${adminPath("accounts", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.toast.deleted")}`);
|
||||
} else {
|
||||
return badRequest({ updateDetailsError: t("shared.invalidForm") });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export default function TenantRoute() {
|
||||
@@ -178,6 +309,8 @@ export default function TenantRoute() {
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
useSaveToast(actionData, { intents: ["edit"] });
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
const successModal = useRef<RefSuccessModal>(null);
|
||||
@@ -204,59 +337,83 @@ export default function TenantRoute() {
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={data.tenant.name}
|
||||
menu={[
|
||||
{ title: t("models.tenant.plural"), routePath: adminPath("accounts", { mode: "host-aware" }) },
|
||||
{ title: data.tenant?.name ?? "", routePath: adminPath(`accounts/${params.id ?? ""}`, { mode: "host-aware" }) },
|
||||
]}
|
||||
>
|
||||
<SettingSection title={t("settings.tenant.general")} description={t("settings.tenant.generalDescription")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UpdateTenantDetailsForm
|
||||
tenant={data.tenant}
|
||||
disabled={!getUserHasPermission(adminData, "admin.account.settings.update")}
|
||||
tenantTypes={data.tenantTypes}
|
||||
options={{
|
||||
canChangeType: true,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</SettingSection>
|
||||
<div className="flex w-full flex-col">
|
||||
<AdminPageHeader title={data.tenant.name} description={t("admin.accounts.detailPageDescription", { slug: data.tenant.slug })} />
|
||||
<EditPageLayout
|
||||
fullWidth
|
||||
menu={[
|
||||
{ title: t("models.tenant.plural"), routePath: adminPath("accounts", { mode: "host-aware" }) },
|
||||
{ title: data.tenant?.name ?? "", routePath: adminPath(`accounts/${params.id ?? ""}`, { mode: "host-aware" }) },
|
||||
]}
|
||||
>
|
||||
<TenantSupportConsole data={data} />
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tenant Users */}
|
||||
{getUserHasPermission(adminData, "admin.account.users") && (
|
||||
<Fragment>
|
||||
<SettingSection title={t("models.user.plural")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UsersTable
|
||||
items={data.users}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canSetUserRoles={false}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
/>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tenant Subscription */}
|
||||
{/* {getUserHasPermission(adminData, "admin.account.subscription") && (
|
||||
{/* AK-P19 DoD #3: trial extension, connector assembly, operator notes */}
|
||||
{getUserHasPermission(adminData, "admin.account.settings.update") && (
|
||||
<Fragment>
|
||||
<AdminTenantOperationsPanel
|
||||
connectors={data.connectors}
|
||||
notes={data.notes}
|
||||
trial={data.trial}
|
||||
noteCategories={ADMIN_TENANT_NOTE_CATEGORIES}
|
||||
csrf={rootData.csrf ?? ""}
|
||||
submitting={navigation.state === "submitting"}
|
||||
feedback={{ success: actionData?.opsSuccess, error: actionData?.opsError }}
|
||||
/>
|
||||
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
<SettingSection title={t("settings.tenant.general")} description={t("settings.tenant.generalDescription")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UpdateTenantDetailsForm tenant={data.tenant} disabled={!getUserHasPermission(adminData, "admin.account.settings.update")} />
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tenant Users */}
|
||||
{getUserHasPermission(adminData, "admin.account.users") && (
|
||||
<Fragment>
|
||||
<SettingSection title={t("models.user.plural")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UsersTable
|
||||
items={data.users}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canSetUserRoles={false}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
/>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
{/* Tenant Subscription */}
|
||||
{/* {getUserHasPermission(adminData, "admin.account.subscription") && (
|
||||
<>
|
||||
<div className="md:grid lg:grid-cols-3 md:gap-2">
|
||||
<div className="md:col-span-1">
|
||||
@@ -281,33 +438,275 @@ export default function TenantRoute() {
|
||||
</>
|
||||
)} */}
|
||||
|
||||
{/*Danger */}
|
||||
{getUserHasPermission(adminData, "admin.account.delete") && (
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
<div className="">
|
||||
{/*Danger */}
|
||||
{getUserHasPermission(adminData, "admin.account.delete") && (
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
<div className="">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("admin.accounts.danger.deleteAccountTitle")}</h3>
|
||||
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
||||
<p>{t("admin.accounts.danger.deleteAccountDescription")}</p>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<ButtonPrimary destructive={true} onClick={deleteAccount}>
|
||||
{t("settings.danger.deleteAccount")}
|
||||
</ButtonPrimary>
|
||||
<div className="">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("admin.accounts.danger.deleteAccountTitle")}</h3>
|
||||
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
||||
<p>{t("admin.accounts.danger.deleteAccountDescription")}</p>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<ButtonPrimary destructive={true} onClick={deleteAccount}>
|
||||
{t("settings.danger.deleteAccount")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
)}
|
||||
</SettingSection>
|
||||
)}
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteTenant} />
|
||||
<SuccessModal ref={successModal} />
|
||||
<ErrorModal ref={errorModal} />
|
||||
</EditPageLayout>
|
||||
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteTenant} />
|
||||
<SuccessModal ref={successModal} />
|
||||
<ErrorModal ref={errorModal} />
|
||||
</EditPageLayout>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function buildTenantSupportSummary({
|
||||
tenant,
|
||||
users,
|
||||
subscription,
|
||||
}: {
|
||||
tenant: TenantWithDetails;
|
||||
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
}): TenantSupportSummary {
|
||||
const owner = tenant.users.find((item) => item.type === TenantUserType.OWNER)?.user ?? users[0] ?? null;
|
||||
const activeUsers = users.filter((user) =>
|
||||
user.tenants.some((membership) => membership.tenantId === tenant.id && membership.status === TenantUserStatus.ACTIVE)
|
||||
).length;
|
||||
const hasLago = Boolean(subscription?.lagoCustomerId);
|
||||
const hasMollie = Boolean(subscription?.mollieCustomerId);
|
||||
const billingAttention = Boolean(
|
||||
subscription?.status === "past_due" || subscription?.status === "frozen" || subscription?.pastDueSince || subscription?.frozenAt
|
||||
);
|
||||
const status: TenantSupportTone = !tenant.active || tenant.deactivatedReason ? "danger" : billingAttention ? "warning" : "success";
|
||||
|
||||
return {
|
||||
status,
|
||||
statusLabelKey:
|
||||
tenant.active && !tenant.deactivatedReason ? "admin.accounts.supportConsole.status.active" : "admin.accounts.supportConsole.status.inactive",
|
||||
statusDetail: tenant.deactivatedReason,
|
||||
ownerEmail: owner?.email ?? null,
|
||||
planCode: subscription?.planCode ?? null,
|
||||
seatQuantity: subscription?.seatQuantity ?? null,
|
||||
billingStatus: subscription?.status ?? null,
|
||||
providerSummaryKey:
|
||||
hasLago && hasMollie
|
||||
? "admin.accounts.supportConsole.providers.complete"
|
||||
: hasLago || hasMollie
|
||||
? "admin.accounts.supportConsole.providers.partial"
|
||||
: "admin.accounts.supportConsole.providers.missing",
|
||||
metrics: [
|
||||
{
|
||||
id: "users",
|
||||
labelKey: "admin.accounts.supportConsole.metrics.users.label",
|
||||
value: String(activeUsers),
|
||||
detailKey: "admin.accounts.supportConsole.metrics.users.detail",
|
||||
tone: activeUsers > 0 ? "success" : "warning",
|
||||
href: adminPath(`accounts/users?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "billing",
|
||||
labelKey: "admin.accounts.supportConsole.metrics.billing.label",
|
||||
value: subscription?.status ?? "-",
|
||||
detailKey: billingAttention
|
||||
? "admin.accounts.supportConsole.metrics.billing.detailAttention"
|
||||
: "admin.accounts.supportConsole.metrics.billing.detailOk",
|
||||
tone: billingAttention ? "warning" : subscription ? "success" : "neutral",
|
||||
href: adminPath("system/billing", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "providers",
|
||||
labelKey: "admin.accounts.supportConsole.metrics.providers.label",
|
||||
value: [hasLago ? "Lago" : null, hasMollie ? "Mollie" : null].filter(Boolean).join(" / ") || "-",
|
||||
detailKey:
|
||||
hasLago && hasMollie ? "admin.accounts.supportConsole.metrics.providers.detailOk" : "admin.accounts.supportConsole.metrics.providers.detailMissing",
|
||||
tone: hasLago && hasMollie ? "success" : "warning",
|
||||
href: adminPath("system/billing", { mode: "host-aware" }),
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
id: "open-tenant",
|
||||
labelKey: "admin.accounts.supportConsole.actions.openTenant.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.openTenant.detail",
|
||||
href: "",
|
||||
external: true,
|
||||
},
|
||||
{
|
||||
id: "users",
|
||||
labelKey: "admin.accounts.supportConsole.actions.users.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.users.detail",
|
||||
href: adminPath(`accounts/users?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "audit",
|
||||
labelKey: "admin.accounts.supportConsole.actions.audit.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.audit.detail",
|
||||
href: adminPath(`audit?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "security",
|
||||
labelKey: "admin.accounts.supportConsole.actions.security.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.security.detail",
|
||||
href: adminPath(`accounts/${tenant.id}/security`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
id: "events",
|
||||
labelKey: "admin.accounts.supportConsole.actions.events.label",
|
||||
detailKey: "admin.accounts.supportConsole.actions.events.detail",
|
||||
href: adminPath(`events?tenantId=${tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function TenantSupportConsole({ data }: { data: LoaderData }) {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const summary = data.supportSummary;
|
||||
const appHref = absoluteAppPath(rootData.routing, data.tenant.slug, "dashboard");
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Card className="gap-5 rounded-lg py-5">
|
||||
<CardHeader>
|
||||
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div className="min-w-0 space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge color={toneToBadgeColor(summary.status)} withColorDot>
|
||||
{t(summary.statusLabelKey)}
|
||||
</Badge>
|
||||
<Badge color={summary.billingStatus === "past_due" || summary.billingStatus === "frozen" ? "yellow" : "gray"} withColorDot>
|
||||
{summary.billingStatus ?? t("admin.accounts.supportConsole.billing.noSubscription")}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-xl leading-7">{t("admin.accounts.supportConsole.title")}</CardTitle>
|
||||
<CardDescription className="mt-1 max-w-3xl leading-5">{t("admin.accounts.supportConsole.description")}</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Link
|
||||
to={appHref}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="border-border bg-background hover:bg-surface-neutral-secondary inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium"
|
||||
>
|
||||
{t("admin.accounts.supportConsole.openInApp")}
|
||||
<ExternalLink className="size-4" aria-hidden="true" />
|
||||
</Link>
|
||||
<Link
|
||||
to={adminPath(`audit?tenantId=${data.tenant.id}`, { mode: "host-aware" })}
|
||||
className="border-border bg-background hover:bg-surface-neutral-secondary inline-flex items-center gap-2 rounded-md border px-3 py-2 text-sm font-medium"
|
||||
>
|
||||
{t("admin.accounts.supportConsole.openAudit")}
|
||||
<Activity className="size-4" aria-hidden="true" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,0.45fr)]">
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
{summary.metrics.map((metric) => (
|
||||
<SupportMetricCard key={metric.id} metric={metric} />
|
||||
))}
|
||||
</div>
|
||||
<dl className="bg-background grid gap-3 rounded-md border p-4 text-sm">
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.slug")} value={`/${data.tenant.slug}`} />
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.owner")} value={summary.ownerEmail ?? t("shared.none")} />
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.plan")} value={summary.planCode ?? t("shared.none")} />
|
||||
<SupportDetail
|
||||
label={t("admin.accounts.supportConsole.fields.seats")}
|
||||
value={summary.seatQuantity ? String(summary.seatQuantity) : t("shared.none")}
|
||||
/>
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.providers")} value={t(summary.providerSummaryKey)} />
|
||||
{summary.statusDetail ? (
|
||||
<SupportDetail label={t("admin.accounts.supportConsole.fields.reason")} value={summary.statusDetail} tone="danger" />
|
||||
) : null}
|
||||
</dl>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
|
||||
{summary.actions.map((action) => (
|
||||
<SupportActionCard key={action.id} action={{ ...action, href: action.id === "open-tenant" ? appHref : action.href }} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportMetricCard({ metric }: { metric: TenantSupportMetric }) {
|
||||
const { t } = useTranslation();
|
||||
const content = (
|
||||
<div className="bg-background hover:bg-surface-neutral-secondary/60 flex h-full min-h-28 flex-col justify-between gap-3 rounded-md border p-4 transition-colors">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm leading-5 font-medium">{t(metric.labelKey)}</p>
|
||||
<p className="text-text-neutral-tertiary mt-1 text-xs leading-4">{t(metric.detailKey)}</p>
|
||||
</div>
|
||||
<MetricIcon id={metric.id} tone={metric.tone} />
|
||||
</div>
|
||||
<p className="truncate text-2xl leading-7 font-semibold">{metric.value}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!metric.href) return content;
|
||||
return (
|
||||
<Link to={metric.href} className="focus-visible:shadow-focus block focus-visible:outline-none">
|
||||
{content}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportActionCard({ action }: { action: TenantSupportAction }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Link
|
||||
to={action.href}
|
||||
target={action.external ? "_blank" : undefined}
|
||||
rel={action.external ? "noreferrer" : undefined}
|
||||
className="border-border bg-background hover:bg-surface-neutral-secondary/60 focus-visible:shadow-focus flex min-h-24 items-start justify-between gap-3 rounded-lg border p-4 transition-colors focus-visible:outline-none"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm leading-5 font-medium">{t(action.labelKey)}</p>
|
||||
<p className="text-text-neutral-tertiary mt-1 text-xs leading-4">{t(action.detailKey)}</p>
|
||||
</div>
|
||||
<ArrowRight className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function SupportDetail({ label, value, tone = "neutral" }: { label: string; value: string; tone?: TenantSupportTone }) {
|
||||
return (
|
||||
<div className="grid grid-cols-[7rem_minmax(0,1fr)] gap-3">
|
||||
<dt className="text-text-neutral-tertiary">{label}</dt>
|
||||
<dd className={tone === "danger" ? "text-red-700" : "text-foreground truncate font-medium"}>{value}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricIcon({ id, tone }: { id: string; tone: TenantSupportTone }) {
|
||||
const className = tone === "danger" ? "text-red-600" : tone === "warning" ? "text-yellow-600" : tone === "success" ? "text-green-600" : "text-gray-500";
|
||||
if (id === "users") return <Users className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
||||
if (id === "billing") return <CreditCard className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
||||
if (id === "providers") return <KeyRound className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
||||
return <ShieldAlert className={`size-4 shrink-0 ${className}`} aria-hidden="true" />;
|
||||
}
|
||||
|
||||
function toneToBadgeColor(tone: TenantSupportTone): BadgeColor {
|
||||
if (tone === "success") return "green";
|
||||
if (tone === "danger") return "red";
|
||||
if (tone === "warning") return "yellow";
|
||||
return "gray";
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@ import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { addToBlacklist, findInBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { useSubmit } from "react-router";
|
||||
import { db } from "~/utils/db.server";
|
||||
import DropdownSimple from "~/components/ui/dropdowns/DropdownSimple";
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { findInBlacklist, addToBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { useSubmit } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { db } from "~/utils/db.server";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
|
||||
-9
@@ -74,7 +74,6 @@ const sourceFiles = [
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users/$user.roles.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/$id.tsx",
|
||||
"apps/web/app/utils/helpers/PermissionsHelper.ts",
|
||||
"apps/web/app/components/core/roles/RolesAndPermissionsMatrix.tsx",
|
||||
@@ -101,14 +100,10 @@ describe("admin account security i18n", () => {
|
||||
expect(source).toContain("admin.accounts.ipAddresses.actions.deleteSelectedLogs");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.roles");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.permissions");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.adminUsers");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.accountUsers");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.permissions.errors.existingPermission");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.existingRole");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.updateFailed");
|
||||
expect(source).toContain("settings.tenant.errors.nameRequired");
|
||||
expect(source).toContain("settings.tenant.errors.slugRequired");
|
||||
expect(source).toContain("models.blacklist.types.");
|
||||
expect(source).toContain("admin.accounts.users.filters.hasLoggedIn");
|
||||
expect(source).toContain('app.shared.periods.LAST_N_MONTHS", { count: 6, formattedCount: "6" }');
|
||||
@@ -116,16 +111,12 @@ describe("admin account security i18n", () => {
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.relativeDate");
|
||||
expect(source).toContain("models.permission.matrix.rolePermissionCount");
|
||||
expect(source).toContain("translateLabel(t, i18n, f.title)");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).toContain(
|
||||
'title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`'
|
||||
);
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).toContain(
|
||||
'title: t("admin.accounts.rolesAndPermissions.tabs.accountUsers")'
|
||||
);
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/admin-users.tsx")).toContain(
|
||||
'title: `${t("admin.accounts.rolesAndPermissions.tabs.adminUsers")} | ${process.env.APP_NAME}`'
|
||||
);
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).not.toContain("i18nT");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/roles.tsx")).not.toContain('from "i18next"');
|
||||
|
||||
+6
-242
@@ -1,245 +1,9 @@
|
||||
import { buildAdminBillingVM, type AdminBillingRow } from "@hivegrid/view-models";
|
||||
import { ActionFunctionArgs, Form, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData, useNavigation } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import {
|
||||
listAdminBillingRows,
|
||||
requestManualBillingSync,
|
||||
setTenantBillingPlanSeats,
|
||||
AdminBillingError,
|
||||
type BillingSyncProvider,
|
||||
} from "~/services/admin/billing-admin.server";
|
||||
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildAdminBillingVM>;
|
||||
};
|
||||
import { redirectLegacyAdminRoute } from "~/utils/navigation/legacyAdminRouteRedirect.server";
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const loader = ({ request }: LoaderFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "system/billing");
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
const vm = buildAdminBillingVM({ rows: await listAdminBillingRows() });
|
||||
return {
|
||||
title: `${t("admin.billing.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
function badRequest(data: ActionData) {
|
||||
return Response.json(data, { status: 400 });
|
||||
}
|
||||
|
||||
function billingErrorKey(error: unknown): string {
|
||||
if (error instanceof AdminBillingError || error instanceof AdminActionInputError) return error.i18nKey;
|
||||
return "admin.billing.errors.UNKNOWN";
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const tenantId = form.get("tenantId")?.toString() ?? "";
|
||||
const userInfo = await getUserInfo(request);
|
||||
const actor = await getUser(userInfo.userId);
|
||||
|
||||
try {
|
||||
if (action === "set-plan-seats") {
|
||||
await setTenantBillingPlanSeats({
|
||||
tenantId,
|
||||
planCode: form.get("planCode")?.toString() ?? "",
|
||||
seatQuantity: form.get("seatQuantity")?.toString() ?? "",
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.billing.actions.planSeatsUpdated") } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (action === "request-sync") {
|
||||
const provider = form.get("provider")?.toString() as BillingSyncProvider;
|
||||
if (provider !== "lago" && provider !== "mollie") {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
await requestManualBillingSync({
|
||||
tenantId,
|
||||
provider,
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.billing.actions.syncRequested", { provider: t(`admin.billing.providers.${provider}`) }) } satisfies ActionData);
|
||||
}
|
||||
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
} catch (error) {
|
||||
return badRequest({ error: t(billingErrorKey(error)) });
|
||||
}
|
||||
};
|
||||
|
||||
function FieldValue({ label, value }: { label: string; value: string | number | null }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="text-muted-foreground text-xs font-medium uppercase">{label}</div>
|
||||
<div className="text-foreground text-sm break-all">{value || "-"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SyncButtons({ row, csrf }: { row: AdminBillingRow; csrf?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(["lago", "mollie"] as const).map((provider) => (
|
||||
<Form key={provider} method="post">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="request-sync" />
|
||||
<input type="hidden" name="tenantId" value={row.tenantId} />
|
||||
<input type="hidden" name="provider" value={provider} />
|
||||
<ButtonSecondary type="submit" className="h-8 px-3 text-xs">
|
||||
{t("admin.billing.actions.requestProviderSync", { provider: t(`admin.billing.providers.${provider}`) })}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PlanSeatForm({ row, csrf, loading }: { row: AdminBillingRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Form method="post" className="grid gap-2 md:grid-cols-[minmax(120px,1fr)_96px_minmax(180px,1.5fr)_auto]">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="set-plan-seats" />
|
||||
<input type="hidden" name="tenantId" value={row.tenantId} />
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.planCode")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="planCode"
|
||||
defaultValue={row.planCode ?? ""}
|
||||
placeholder={t("admin.billing.placeholders.planCode")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.seats")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="seatQuantity"
|
||||
type="number"
|
||||
min={1}
|
||||
defaultValue={row.seatQuantity ?? 1}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.reason")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="reason"
|
||||
placeholder={t("admin.billing.placeholders.reason")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end">
|
||||
<ButtonPrimary type="submit" disabled={loading} className="h-9 px-3 text-xs">
|
||||
{t("admin.billing.actions.saveOverride")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function BillingRowCard({ row, csrf, loading }: { row: AdminBillingRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="border-border bg-background rounded-md border p-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-foreground text-base font-semibold">{row.tenantName}</div>
|
||||
<div className="text-muted-foreground text-sm">{row.tenantSlug}</div>
|
||||
</div>
|
||||
<div className="bg-muted text-foreground rounded-full px-3 py-1 text-xs font-medium">{t(row.statusLabelKey)}</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-4">
|
||||
<FieldValue label={t("admin.billing.fields.planCode")} value={row.planCode} />
|
||||
<FieldValue label={t("admin.billing.fields.seats")} value={row.seatQuantity} />
|
||||
<FieldValue label={t("admin.billing.fields.lastInvoice")} value={row.lastInvoiceExternalId} />
|
||||
<FieldValue label={t("admin.billing.fields.lastPayment")} value={row.lastPaymentExternalId} />
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-3">
|
||||
<FieldValue label={t("admin.billing.fields.readOnlyReason")} value={t(row.readOnlyReasonKey)} />
|
||||
<FieldValue label={t("admin.billing.fields.recoveryHint")} value={t(row.recoveryHintKey)} />
|
||||
<FieldValue label={t("admin.billing.fields.providers")} value={t(row.providerSummaryKey)} />
|
||||
</div>
|
||||
|
||||
<div className="border-border mt-4 border-t pt-4">
|
||||
<PlanSeatForm row={row} csrf={csrf} loading={loading} />
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<SyncButtons row={row} csrf={csrf} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminBillingRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const rootData = useRootData();
|
||||
const loading = navigation.state === "submitting";
|
||||
const rows = data.vm.status === "ready" ? data.vm.data.rows : [];
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.billing.title")} fullWidth>
|
||||
<div className="space-y-4">
|
||||
<div className="border-border bg-surface-neutral-primary rounded-md border p-4">
|
||||
<div className="text-muted-foreground text-sm">{t("admin.billing.description")}</div>
|
||||
{actionData?.success && <div className="mt-3 rounded-md bg-green-50 px-3 py-2 text-sm text-green-800">{actionData.success}</div>}
|
||||
{actionData?.error && <div className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-800">{actionData.error}</div>}
|
||||
</div>
|
||||
|
||||
{data.vm.status === "empty" ? (
|
||||
<div className="border-border bg-background rounded-md border p-6">
|
||||
<div className="font-medium">{t("admin.billing.empty.headline")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.billing.empty.body")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => (
|
||||
<BillingRowCard key={row.tenantId} row={row} csrf={rootData.csrf} loading={loading} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
export const action = ({ request }: ActionFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "system/billing");
|
||||
+11
-7
@@ -1,5 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigation, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
@@ -19,6 +19,7 @@ import Modal from "~/components/ui/modals/Modal";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
@@ -45,13 +46,14 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
@@ -61,25 +63,27 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
type: form.get("type")?.toString() ?? "",
|
||||
value: form.get("value")?.toString() ?? "",
|
||||
});
|
||||
return Response.json({});
|
||||
return Response.json({ intent: action, ok: true, messageKey: "models.blacklist.toast.created" } satisfies ActionData);
|
||||
} else if (action === "delete") {
|
||||
await deleteFromBlacklist({
|
||||
type: form.get("type")?.toString() ?? "",
|
||||
value: form.get("value")?.toString() ?? "",
|
||||
});
|
||||
return Response.json({});
|
||||
return Response.json({ intent: action, ok: true, messageKey: "models.blacklist.toast.deleted" } satisfies ActionData);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
return badRequest({ intent: action, errorKey: "shared.invalidForm" });
|
||||
}
|
||||
};
|
||||
|
||||
export default function BlacklistRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const formatters = useLocaleFormatters();
|
||||
const navigation = useNavigation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "create";
|
||||
useSaveToast(actionData);
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
|
||||
+308
-14
@@ -1,13 +1,20 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./index";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { action, loader } from "./index";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminGetAllTenantsWithUsage } from "~/utils/db/tenants.db.server";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { adminGetAllTenantsWithUsage, getTenantSimple, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsersNames, getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
|
||||
import { requireUserId } from "~/utils/session.server";
|
||||
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
||||
import { getReservedOwnerInvitationReissueTarget, reissueReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationReissue.server";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
@@ -29,7 +36,6 @@ vi.mock("~/components/core/tenants/DeactivateTenantModal", () => ({ default: ()
|
||||
vi.mock("~/components/core/tenants/TenantsTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/button", () => ({ Button: () => null }));
|
||||
vi.mock("~/components/ui/forms/FormGroup", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputCheckboxWithDescription", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputText", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
@@ -45,26 +51,44 @@ vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders:
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/api/.server/TenantsApi", () => ({ TenantsApi: { create: vi.fn() } }));
|
||||
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
|
||||
reserveTenantWithoutOwner: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/domain/tenant-bootstrap/ownerInvitationIssuance.server", () => ({
|
||||
prepareReservedOwnerInvitation: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/domain/tenant-bootstrap/ownerInvitationReissue.server", () => ({
|
||||
getReservedOwnerInvitationReissueTarget: vi.fn(),
|
||||
reissueReservedOwnerInvitation: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/domain/tenant-bootstrap/tenantBootstrap.constants", () => ({ TENANT_PENDING_OWNER_REASON: "pending_owner" }));
|
||||
vi.mock("~/utils/app/UrlUtils", () => ({ default: { slugify: (value: string) => value.toLowerCase() } }));
|
||||
vi.mock("~/utils/csrf", () => ({ appendCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({ useAppOrAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRoles: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsWithUsage: vi.fn(),
|
||||
createTenantUser: vi.fn(),
|
||||
getTenantSimple: vi.fn(),
|
||||
updateTenantDeactivated: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsersNames: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsersNames: vi.fn(), getUser: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
getFiltersFromCurrentUrl: vi.fn(),
|
||||
getPaginationFromCurrentUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/tenantService", () => ({ getExistingSlug: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn(), requireUserId: vi.fn() }));
|
||||
vi.mock("~/utils/app/UserValidationUtils", () => ({ default: { validateEmail: vi.fn() } }));
|
||||
|
||||
const OWNER_INVITATION = {
|
||||
issuanceKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
||||
email: "owner@heizkraft.de",
|
||||
firstName: "Anna",
|
||||
lastName: "Berger",
|
||||
fromUserId: "operator_1",
|
||||
token: "o".repeat(43),
|
||||
mail: { subject: "Einladung", html: `https://app.example.test/invitation/${"o".repeat(43)}` },
|
||||
};
|
||||
const tenants = [
|
||||
{
|
||||
id: "tenant-1",
|
||||
@@ -94,13 +118,25 @@ describe("admin accounts invoice hydration", () => {
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([] as never);
|
||||
vi.mocked(getAllTenantTypes).mockResolvedValue([] as never);
|
||||
vi.mocked(getFiltersFromCurrentUrl).mockReturnValue(undefined as never);
|
||||
vi.mocked(getPaginationFromCurrentUrl).mockReturnValue({ page: 1, pageSize: 10 } as never);
|
||||
vi.mocked(adminGetAllTenantsWithUsage).mockResolvedValue({
|
||||
items: tenants,
|
||||
pagination: { page: 1, pageSize: 10, totalItems: tenants.length, totalPages: 1 },
|
||||
} as never);
|
||||
vi.mocked(requireUserId).mockResolvedValue("operator_1");
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "operator_1", firstName: "Olivia", locale: "de" } as never);
|
||||
vi.mocked(UserValidationUtils.validateEmail).mockReturnValue(true);
|
||||
vi.mocked(prepareReservedOwnerInvitation).mockResolvedValue(OWNER_INVITATION);
|
||||
vi.mocked(getReservedOwnerInvitationReissueTarget).mockResolvedValue({
|
||||
tenantName: "Heizkraft GmbH",
|
||||
invitationId: "invite-old",
|
||||
email: "owner@heizkraft.de",
|
||||
firstName: "Anna",
|
||||
lastName: "Berger",
|
||||
});
|
||||
vi.mocked(reissueReservedOwnerInvitation).mockResolvedValue({ invitationId: "invite-new", replayed: false });
|
||||
vi.mocked(getTenantSimple).mockResolvedValue({ deactivatedReason: null } as never);
|
||||
});
|
||||
|
||||
it("loads the default tenant list without processor invoice hydration", async () => {
|
||||
@@ -110,5 +146,263 @@ describe("admin accounts invoice hydration", () => {
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.accounts.view");
|
||||
expect(body.tenantInvoices).toBeUndefined();
|
||||
expect(body).not.toHaveProperty("includeInvoices");
|
||||
expect(body.reservationRequestKey).toMatch(/^[0-9a-f-]{36}$/i);
|
||||
expect(body.ownerInvitationReissueKey).toMatch(/^[0-9a-f-]{36}$/i);
|
||||
expect(body.ownerInvitationReissueKey).not.toBe(body.reservationRequestKey);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["deactivate", false, "billing"],
|
||||
["activate", true, ""],
|
||||
] as const)("runs the %s mutation inside the selected tenant RLS context", async (operation, active, reason) => {
|
||||
vi.mocked(updateTenantDeactivated).mockImplementationOnce(async (tenantId) => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
|
||||
return { id: tenantId } as never;
|
||||
});
|
||||
const form = new FormData();
|
||||
form.set("action", operation);
|
||||
form.set("id", "tenant-1");
|
||||
form.set("reason", reason);
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
||||
);
|
||||
|
||||
expect(updateTenantDeactivated).toHaveBeenCalledWith("tenant-1", {
|
||||
active,
|
||||
deactivatedReason: active ? null : "billing",
|
||||
});
|
||||
expect(getRlsExecutionContext()).toBeNull();
|
||||
});
|
||||
|
||||
it("atomically reserves an inactive tenant and queues its OWNER invitation", async () => {
|
||||
vi.mocked(reserveTenantWithoutOwner).mockResolvedValue({
|
||||
id: "tenant-reserved",
|
||||
name: "Heizkraft GmbH",
|
||||
slug: "heizkraft",
|
||||
active: false,
|
||||
deactivatedReason: TENANT_PENDING_OWNER_REASON,
|
||||
} as never);
|
||||
const form = new FormData();
|
||||
form.set("action", "create");
|
||||
form.set("name", "Heizkraft GmbH");
|
||||
form.set("slug", "heizkraft");
|
||||
form.set("reservationRequestKey", "d7077797-054b-497a-b1ce-8e4f36257a96");
|
||||
form.set("ownerEmail", "OWNER@HEIZKRAFT.DE");
|
||||
form.set("ownerFirstName", "Anna");
|
||||
form.set("ownerLastName", "Berger");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const result = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(prepareReservedOwnerInvitation).toHaveBeenCalledWith({
|
||||
request,
|
||||
issuanceKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
||||
tenantName: "Heizkraft GmbH",
|
||||
email: "owner@heizkraft.de",
|
||||
firstName: "Anna",
|
||||
lastName: "Berger",
|
||||
issuer: { id: "operator_1", firstName: "Olivia", locale: "de" },
|
||||
});
|
||||
expect(reserveTenantWithoutOwner).toHaveBeenCalledWith({
|
||||
name: "Heizkraft GmbH",
|
||||
slug: "heizkraft",
|
||||
operatorUserId: "operator_1",
|
||||
reservationRequestKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
||||
ownerInvitation: OWNER_INVITATION,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
intent: "create",
|
||||
ok: true,
|
||||
createdTenantId: "tenant-reserved",
|
||||
messageKey: "admin.accounts.toast.ownerInvitationSent",
|
||||
});
|
||||
});
|
||||
|
||||
it("rotates an owner invitation with a page-stable idempotency key", async () => {
|
||||
const issuanceKey = "93923898-e834-41e9-9e2c-0c03080e91df";
|
||||
const reissuedDraft = { ...OWNER_INVITATION, issuanceKey };
|
||||
vi.mocked(prepareReservedOwnerInvitation).mockResolvedValueOnce(reissuedDraft);
|
||||
const form = new FormData();
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("issuanceKey", issuanceKey);
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(getReservedOwnerInvitationReissueTarget).toHaveBeenCalledWith({
|
||||
tenantId: "tenant-reserved",
|
||||
operatorUserId: "operator_1",
|
||||
});
|
||||
expect(prepareReservedOwnerInvitation).toHaveBeenCalledWith({
|
||||
request,
|
||||
issuanceKey,
|
||||
tenantName: "Heizkraft GmbH",
|
||||
email: "owner@heizkraft.de",
|
||||
firstName: "Anna",
|
||||
lastName: "Berger",
|
||||
issuer: { id: "operator_1", firstName: "Olivia", locale: "de" },
|
||||
});
|
||||
expect(reissueReservedOwnerInvitation).toHaveBeenCalledWith({
|
||||
tenantId: "tenant-reserved",
|
||||
operatorUserId: "operator_1",
|
||||
sourceInvitationId: "invite-old",
|
||||
ownerInvitation: reissuedDraft,
|
||||
});
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
await expect((response as Response).json()).resolves.toEqual({
|
||||
intent: "resend-owner-invitation",
|
||||
ok: true,
|
||||
messageKey: "admin.accounts.toast.ownerInvitationResent",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a malformed owner-invitation reissue key before loading the reservation", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("issuanceKey", "not-a-uuid");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(getReservedOwnerInvitationReissueTarget).not.toHaveBeenCalled();
|
||||
expect(prepareReservedOwnerInvitation).not.toHaveBeenCalled();
|
||||
expect(reissueReservedOwnerInvitation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the ownerless reservation changed before invitation rotation", async () => {
|
||||
vi.mocked(reissueReservedOwnerInvitation).mockRejectedValueOnce(
|
||||
new CatalogError(foundationErrors.idempotencyConflict, { scope: "tenant-owner-invitation-reissue", key: "fixture" })
|
||||
);
|
||||
const form = new FormData();
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("issuanceKey", "93923898-e834-41e9-9e2c-0c03080e91df");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(409);
|
||||
await expect((response as Response).json()).resolves.toEqual({
|
||||
intent: "resend-owner-invitation",
|
||||
errorKey: "admin.accounts.actions.ownerInvitationResendFailed",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not hide an infrastructure failure as a user conflict", async () => {
|
||||
vi.mocked(reissueReservedOwnerInvitation).mockRejectedValueOnce(new Error("database unavailable"));
|
||||
const form = new FormData();
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("issuanceKey", "93923898-e834-41e9-9e2c-0c03080e91df");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
await expect(action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)).rejects.toThrow(
|
||||
"database unavailable"
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects invalid owner identity before preparing a capability or creating a tenant", async () => {
|
||||
vi.mocked(UserValidationUtils.validateEmail).mockReturnValueOnce(false);
|
||||
const form = new FormData();
|
||||
form.set("action", "create");
|
||||
form.set("name", "Heizkraft GmbH");
|
||||
form.set("slug", "heizkraft");
|
||||
form.set("reservationRequestKey", "d7077797-054b-497a-b1ce-8e4f36257a96");
|
||||
form.set("ownerEmail", "not-an-email");
|
||||
form.set("ownerFirstName", "Anna");
|
||||
form.set("ownerLastName", "Berger");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(prepareReservedOwnerInvitation).not.toHaveBeenCalled();
|
||||
expect(reserveTenantWithoutOwner).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a malformed reservation request key before creating a tenant", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "create");
|
||||
form.set("name", "Heizkraft GmbH");
|
||||
form.set("slug", "heizkraft");
|
||||
form.set("reservationRequestKey", "attacker-controlled");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(reserveTenantWithoutOwner).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["activate", ""],
|
||||
["deactivate", "billing"],
|
||||
] as const)("rejects forged %s of an ownerless reservation without changing its marker", async (operation, reason) => {
|
||||
vi.mocked(getTenantSimple).mockImplementationOnce(async (tenantId) => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
|
||||
return { id: tenantId, active: false, deactivatedReason: TENANT_PENDING_OWNER_REASON } as never;
|
||||
});
|
||||
const form = new FormData();
|
||||
form.set("action", operation);
|
||||
form.set("id", "tenant-reserved");
|
||||
form.set("reason", reason);
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
||||
);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(409);
|
||||
await expect((response as Response).json()).resolves.toEqual({
|
||||
intent: operation,
|
||||
errorKey: "admin.accounts.actions.reservationRequiresOwner",
|
||||
});
|
||||
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
||||
expect(getRlsExecutionContext()).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["activate", "deactivate"] as const)("fails closed when the %s target is not visible through RLS", async (operation) => {
|
||||
vi.mocked(getTenantSimple).mockResolvedValueOnce(null);
|
||||
const form = new FormData();
|
||||
form.set("action", operation);
|
||||
form.set("id", "tenant-hidden");
|
||||
form.set("reason", "billing");
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
||||
);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(409);
|
||||
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
||||
expect(getRlsExecutionContext()).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects a forged pending_owner reason on a normal tenant", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "deactivate");
|
||||
form.set("id", "tenant-normal");
|
||||
form.set("reason", TENANT_PENDING_OWNER_REASON);
|
||||
const request = new Request("https://admin.example.test/accounts", { method: "POST", body: form });
|
||||
|
||||
const response = await runWithRlsContext({ userId: "operator_1" }, () =>
|
||||
action({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as ActionFunctionArgs)
|
||||
);
|
||||
|
||||
expect(response).toBeInstanceOf(Response);
|
||||
expect((response as Response).status).toBe(409);
|
||||
expect(getTenantSimple).not.toHaveBeenCalled();
|
||||
expect(updateTenantDeactivated).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+198
-99
@@ -1,37 +1,41 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { adminGetAllTenantsWithUsage, createTenantUser, TenantSimple, TenantWithUsage, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { adminGetAllTenantsWithUsage, getTenantSimple, TenantSimple, TenantWithUsage, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import TenantsTable from "~/components/core/tenants/TenantsTable";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { adminGetAllUsersNames, getUser } from "~/utils/db/users.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useActionData, useNavigation, useSubmit } from "react-router";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { TenantsApi } from "~/utils/api/.server/TenantsApi";
|
||||
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getExistingSlug } from "~/utils/services/tenantService";
|
||||
import DeactivateTenantModal from "~/components/core/tenants/DeactivateTenantModal";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requireUserId, validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
|
||||
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
||||
import { getReservedOwnerInvitationReissueTarget, reissueReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationReissue.server";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
@@ -41,16 +45,17 @@ type LoaderData = {
|
||||
items: TenantWithUsage[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
reservationRequestKey: string;
|
||||
ownerInvitationReissueKey: string;
|
||||
};
|
||||
|
||||
const RESERVATION_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 const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.accounts");
|
||||
await time(verifyUserHasPermission(request, "admin.accounts.view"), "verifyUserHasPermission");
|
||||
let { t } = await time(getTranslations(request), "getTranslations");
|
||||
const [userOptions, tenantTypes] = await Promise.all([
|
||||
time(adminGetAllUsersNames(), "adminGetAllUsersNames"),
|
||||
time(getAllTenantTypes(), "getAllTenantTypes"),
|
||||
]);
|
||||
const userOptions = await time(adminGetAllUsersNames(), "adminGetAllUsersNames");
|
||||
|
||||
const filterableProperties = [
|
||||
{ name: "name", title: "models.tenant.name" },
|
||||
@@ -66,20 +71,6 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "typeId",
|
||||
title: t("shared.type"),
|
||||
manual: true,
|
||||
options: [
|
||||
{ value: "null", name: t("admin.accounts.filters.defaultType") },
|
||||
...tenantTypes.map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: t(item.title),
|
||||
};
|
||||
}),
|
||||
],
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
@@ -90,18 +81,21 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
items: items.sort((a, b) => (a.createdAt > b.createdAt ? -1 : 1)),
|
||||
filterableProperties,
|
||||
pagination,
|
||||
reservationRequestKey: randomUUID(),
|
||||
ownerInvitationReissueKey: randomUUID(),
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
createdTenantId?: string;
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
@@ -110,46 +104,119 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
if (action === "deactivate" && id) {
|
||||
const deactivatedReason = form.get("reason")?.toString();
|
||||
if (!deactivatedReason) {
|
||||
return Response.json({ error: t("admin.accounts.actions.missingDeactivationReason") }, { status: 400 });
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.missingDeactivationReason" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
await updateTenantDeactivated(id, {
|
||||
active: false,
|
||||
deactivatedReason,
|
||||
if (deactivatedReason === TENANT_PENDING_OWNER_REASON) {
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.reservationRequiresOwner" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
const deactivationBlocked = await runWithRlsContext({ tenantId: id }, async () => {
|
||||
const tenant = await getTenantSimple(id);
|
||||
if (!tenant || tenant.deactivatedReason === TENANT_PENDING_OWNER_REASON) {
|
||||
return true;
|
||||
}
|
||||
await updateTenantDeactivated(id, {
|
||||
active: false,
|
||||
deactivatedReason,
|
||||
});
|
||||
return false;
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.actions.tenantDeactivated") });
|
||||
if (deactivationBlocked) {
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.reservationRequiresOwner" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
return Response.json({ intent: action, ok: true, messageKey: "admin.accounts.toast.deactivated" } satisfies ActionData);
|
||||
} else if (action === "activate" && id) {
|
||||
await updateTenantDeactivated(id, {
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
const activationBlocked = await runWithRlsContext({ tenantId: id }, async () => {
|
||||
const tenant = await getTenantSimple(id);
|
||||
if (!tenant || tenant.deactivatedReason === TENANT_PENDING_OWNER_REASON) {
|
||||
return true;
|
||||
}
|
||||
await updateTenantDeactivated(id, {
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
});
|
||||
return false;
|
||||
});
|
||||
return Response.json({});
|
||||
if (activationBlocked) {
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.reservationRequiresOwner" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
return Response.json({ intent: action, ok: true, messageKey: "admin.accounts.toast.activated" } satisfies ActionData);
|
||||
} else if (action === "resend-owner-invitation" && id) {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const issuanceKey = form.get("issuanceKey")?.toString() ?? "";
|
||||
if (!RESERVATION_REQUEST_KEY_PATTERN.test(issuanceKey)) {
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const operatorUserId = await requireUserId(request);
|
||||
const operator = await getUser(operatorUserId);
|
||||
if (!operator) {
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const target = await getReservedOwnerInvitationReissueTarget({ tenantId: id, operatorUserId });
|
||||
const ownerInvitation = await prepareReservedOwnerInvitation({
|
||||
request,
|
||||
issuanceKey,
|
||||
tenantName: target.tenantName,
|
||||
email: target.email,
|
||||
firstName: target.firstName,
|
||||
lastName: target.lastName,
|
||||
issuer: { id: operator.id, firstName: operator.firstName, locale: operator.locale },
|
||||
});
|
||||
await reissueReservedOwnerInvitation({
|
||||
tenantId: id,
|
||||
operatorUserId,
|
||||
sourceInvitationId: target.invitationId,
|
||||
ownerInvitation,
|
||||
});
|
||||
return Response.json({ intent: action, ok: true, messageKey: "admin.accounts.toast.ownerInvitationResent" } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ intent: action, errorKey: "admin.accounts.actions.ownerInvitationResendFailed" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} else if (action === "create") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const name = form.get("name")?.toString().trim() ?? "";
|
||||
const slug = form.get("slug")?.toString() ?? "";
|
||||
const existingSlug = await getExistingSlug(slug);
|
||||
if (!slug || existingSlug) {
|
||||
return Response.json({ error: t("shared.slugTaken") }, { status: 400 });
|
||||
const reservationRequestKey = form.get("reservationRequestKey")?.toString() ?? "";
|
||||
const ownerEmail = form.get("ownerEmail")?.toString().trim().toLowerCase() ?? "";
|
||||
const ownerFirstName = form.get("ownerFirstName")?.toString().trim() ?? "";
|
||||
const ownerLastName = form.get("ownerLastName")?.toString().trim() ?? "";
|
||||
if (
|
||||
!name ||
|
||||
!slug ||
|
||||
!RESERVATION_REQUEST_KEY_PATTERN.test(reservationRequestKey) ||
|
||||
!UserValidationUtils.validateEmail(ownerEmail) ||
|
||||
!ownerFirstName ||
|
||||
!ownerLastName
|
||||
) {
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const { tenant, user } = await TenantsApi.create({ request, name, slug });
|
||||
const addMySelf = Boolean(form.get("addMySelf"));
|
||||
if (addMySelf) {
|
||||
const roles = await getAllRoles("app");
|
||||
await createTenantUser(
|
||||
{
|
||||
tenantId: tenant.id,
|
||||
userId: user.id,
|
||||
type: TenantUserType.OWNER,
|
||||
},
|
||||
roles
|
||||
);
|
||||
const operatorUserId = await requireUserId(request);
|
||||
const operator = await getUser(operatorUserId);
|
||||
if (!operator) {
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const ownerInvitation = await prepareReservedOwnerInvitation({
|
||||
request,
|
||||
issuanceKey: reservationRequestKey,
|
||||
tenantName: name,
|
||||
email: ownerEmail,
|
||||
firstName: ownerFirstName,
|
||||
lastName: ownerLastName,
|
||||
issuer: { id: operator.id, firstName: operator.firstName, locale: operator.locale },
|
||||
});
|
||||
const tenant = await reserveTenantWithoutOwner({ name, slug, operatorUserId, reservationRequestKey, ownerInvitation });
|
||||
const data: ActionData = {
|
||||
intent: action,
|
||||
ok: true,
|
||||
createdTenantId: tenant.id,
|
||||
messageKey: "admin.accounts.toast.ownerInvitationSent",
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -160,6 +227,7 @@ export default function AdminTenantsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
useSaveToast(actionData);
|
||||
|
||||
const [deactivatingTenant, setDeactivatingTenant] = useState<TenantWithUsage>();
|
||||
const [creatingNewAccount, setCreatingNewAccount] = useState(false);
|
||||
@@ -191,36 +259,62 @@ export default function AdminTenantsRoute() {
|
||||
setDeactivatingTenant(undefined);
|
||||
}
|
||||
|
||||
function onResendOwnerInvitation(item: TenantWithUsage) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "resend-owner-invitation");
|
||||
form.set("id", item.id);
|
||||
form.set("issuanceKey", data.ownerInvitationReissueKey);
|
||||
submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.tenant.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
size="sm"
|
||||
disabled={!getUserHasPermission(appOrAdminData, "admin.accounts.create")}
|
||||
onClick={() => setCreatingNewAccount(true)}
|
||||
>
|
||||
{t("shared.new")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TenantsTable
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
actions={[
|
||||
{
|
||||
renderTitle: (i) => (!i.deactivatedReason ? t("shared.deactivate") : t("shared.activate")),
|
||||
onClick: (_idx, item) => onToggleActive(item),
|
||||
disabled: () => navigation.state === "submitting",
|
||||
renderIsDestructive: (i) => !i.deactivatedReason,
|
||||
},
|
||||
]}
|
||||
<div className="flex w-full flex-col">
|
||||
<AdminPageHeader
|
||||
title={t("models.tenant.plural")}
|
||||
description={t("admin.accounts.pageDescription")}
|
||||
actions={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button type="button" variant="outline" size="sm" disabled={!getUserHasPermission(appOrAdminData, "admin.accounts.create")} asChild>
|
||||
<Link to={adminPath("accounts/new", { mode: "host-aware" })}>{t("admin.accounts.create.fullCreateLink")}</Link>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
size="sm"
|
||||
disabled={!getUserHasPermission(appOrAdminData, "admin.accounts.create")}
|
||||
onClick={() => setCreatingNewAccount(true)}
|
||||
>
|
||||
{t("shared.new")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<div className="mobile:px-4 flex w-full flex-col gap-3 px-6 py-6">
|
||||
<TenantsTable
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
actions={[
|
||||
{
|
||||
renderTitle: (i) => (!i.deactivatedReason ? t("shared.deactivate") : t("shared.activate")),
|
||||
onClick: (_idx, item) => onToggleActive(item),
|
||||
disabled: (item) => navigation.state === "submitting" || item.deactivatedReason === TENANT_PENDING_OWNER_REASON,
|
||||
renderIsDestructive: (i) => !i.deactivatedReason,
|
||||
},
|
||||
{
|
||||
title: t("admin.accounts.actions.resendOwnerInvitation"),
|
||||
onClick: (_idx, item) => onResendOwnerInvitation(item),
|
||||
hidden: (item) => item.deactivatedReason !== TENANT_PENDING_OWNER_REASON || !getUserHasPermission(appOrAdminData, "admin.accounts.create"),
|
||||
disabled: () => navigation.state === "submitting",
|
||||
confirmation: () => ({
|
||||
title: t("admin.accounts.actions.resendOwnerInvitation"),
|
||||
description: t("admin.accounts.actions.resendOwnerInvitationConfirmation"),
|
||||
}),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DeactivateTenantModal
|
||||
open={!!deactivatingTenant}
|
||||
@@ -240,22 +334,22 @@ export default function AdminTenantsRoute() {
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">
|
||||
<CreateTenantForm />
|
||||
<CreateTenantForm reservationRequestKey={data.reservationRequestKey} />
|
||||
</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
|
||||
<ActionResultModal actionData={actionData} />
|
||||
</EditPageLayout>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateTenantForm() {
|
||||
function CreateTenantForm({ reservationRequestKey }: { reservationRequestKey: string }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const [addMySelf, setAddMySelf] = useState(true);
|
||||
const [ownerEmail, setOwnerEmail] = useState("");
|
||||
const [ownerFirstName, setOwnerFirstName] = useState("");
|
||||
const [ownerLastName, setOwnerLastName] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setSlug(UrlUtils.slugify(name));
|
||||
@@ -275,16 +369,21 @@ function CreateTenantForm() {
|
||||
}}
|
||||
withErrorModal={false}
|
||||
>
|
||||
<input type="hidden" name="reservationRequestKey" value={reservationRequestKey} readOnly />
|
||||
<div className="space-y-3">
|
||||
<InputText ref={firstInput} autoFocus name="name" title={t("shared.name")} value={name} setValue={setName} required />
|
||||
<InputText name="slug" title={t("shared.slug")} value={slug} setValue={setSlug} required onBlur={() => setSlug(UrlUtils.slugify(slug))} />
|
||||
<InputCheckboxWithDescription
|
||||
name="addMySelf"
|
||||
title={t("admin.accounts.create.addMyselfAsOwner")}
|
||||
description={t("admin.accounts.create.addMyselfAsOwnerDescription")}
|
||||
value={addMySelf}
|
||||
setValue={setAddMySelf}
|
||||
<InputText
|
||||
type="email"
|
||||
name="ownerEmail"
|
||||
title={t("models.user.email")}
|
||||
help={t("admin.accounts.create.ownerInvitationDescription")}
|
||||
value={ownerEmail}
|
||||
setValue={setOwnerEmail}
|
||||
required
|
||||
/>
|
||||
<InputText name="ownerFirstName" title={t("models.user.firstName")} value={ownerFirstName} setValue={setOwnerFirstName} required />
|
||||
<InputText name="ownerLastName" title={t("models.user.lastName")} value={ownerLastName} setValue={setOwnerLastName} required />
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/components/screens/admin/AdminTenantCreatePage", () => ({ AdminTenantCreatePage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ requireUserId: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/domain/tenant-bootstrap/ownerInvitationIssuance.server", () => ({ prepareReservedOwnerInvitation: vi.fn() }));
|
||||
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({ reserveTenantWithoutOwner: vi.fn() }));
|
||||
vi.mock("~/services/admin/admin-action-audit.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/admin-action-audit.server")>("~/services/admin/admin-action-audit.server");
|
||||
return { ...actual, recordAdminAction: vi.fn() };
|
||||
});
|
||||
vi.mock("~/services/admin/billing-admin.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/billing-admin.server")>("~/services/admin/billing-admin.server");
|
||||
return { ...actual, extendTenantTrial: vi.fn(), setTenantBillingPlanSeats: vi.fn() };
|
||||
});
|
||||
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireUserId, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
||||
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { extendTenantTrial, setTenantBillingPlanSeats } from "~/services/admin/billing-admin.server";
|
||||
import { action } from "./new";
|
||||
|
||||
const RESERVATION_KEY = "3f2504e0-4f89-41d3-9a0c-0305e82c3301";
|
||||
|
||||
function makeForm(overrides: Record<string, string> = {}): URLSearchParams {
|
||||
return new URLSearchParams({
|
||||
name: "Acme GmbH",
|
||||
slug: "acme-gmbh",
|
||||
reservationRequestKey: RESERVATION_KEY,
|
||||
ownerEmail: "owner@example.test",
|
||||
ownerFirstName: "Owa",
|
||||
ownerLastName: "Ner",
|
||||
planCode: "",
|
||||
seatQuantity: "1",
|
||||
trialDays: "0",
|
||||
reason: "Neukunde aus dem Vertrieb",
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
function makeActionArgs(body: URLSearchParams): ActionFunctionArgs {
|
||||
return {
|
||||
request: new Request("https://admin.example.test/accounts/new", { method: "POST", body }),
|
||||
params: {},
|
||||
context: {},
|
||||
} as ActionFunctionArgs;
|
||||
}
|
||||
|
||||
describe("admin accounts new action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(requireUserId).mockResolvedValue("operator_1");
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "operator_1", email: "op@example.test", firstName: "Op", locale: "de" } as never);
|
||||
vi.mocked(prepareReservedOwnerInvitation).mockResolvedValue({ issuanceKey: RESERVATION_KEY } as never);
|
||||
vi.mocked(reserveTenantWithoutOwner).mockResolvedValue({ id: "tenant_new", slug: "acme-gmbh" } as never);
|
||||
});
|
||||
|
||||
it("requires the create permission and a reason", async () => {
|
||||
const response = (await action(makeActionArgs(makeForm({ reason: "" })))) as Response;
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.accounts.create");
|
||||
expect(response.status).toBe(400);
|
||||
expect(reserveTenantWithoutOwner).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates the reservation, audits tenant.created, and redirects to the detail", async () => {
|
||||
const response = (await action(makeActionArgs(makeForm()))) as Response;
|
||||
|
||||
expect(reserveTenantWithoutOwner).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: "Acme GmbH", slug: "acme-gmbh", operatorUserId: "operator_1", reservationRequestKey: RESERVATION_KEY })
|
||||
);
|
||||
expect(setTenantBillingPlanSeats).not.toHaveBeenCalled();
|
||||
expect(extendTenantTrial).not.toHaveBeenCalled();
|
||||
expect(recordAdminAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: "tenant.created", targetId: "tenant_new", reason: "Neukunde aus dem Vertrieb" })
|
||||
);
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toContain("accounts/tenant_new");
|
||||
expect(response.headers.get("Location")).toContain(`toast=${encodeURIComponent("admin.accounts.toast.created")}`);
|
||||
});
|
||||
|
||||
it("applies optional plan/seats and trial with the same audited reason", async () => {
|
||||
await action(makeActionArgs(makeForm({ planCode: "starter", seatQuantity: "5", trialDays: "30" })));
|
||||
|
||||
expect(setTenantBillingPlanSeats).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tenantId: "tenant_new", planCode: "starter", seatQuantity: "5", reason: "Neukunde aus dem Vertrieb" })
|
||||
);
|
||||
expect(extendTenantTrial).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_new", days: 30, reason: "Neukunde aus dem Vertrieb" }));
|
||||
});
|
||||
|
||||
it("rejects an invalid owner email before touching the bootstrap service", async () => {
|
||||
const response = (await action(makeActionArgs(makeForm({ ownerEmail: "not-an-email" })))) as Response;
|
||||
expect(response.status).toBe(400);
|
||||
expect(prepareReservedOwnerInvitation).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData, useNavigation } from "react-router";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { AdminTenantCreatePage } from "~/components/screens/admin/AdminTenantCreatePage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { AdminActionInputError, assertAdminActionReason, recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { AdminBillingError, extendTenantTrial, setTenantBillingPlanSeats } from "~/services/admin/billing-admin.server";
|
||||
import { prepareReservedOwnerInvitation } from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
|
||||
import { reserveTenantWithoutOwner } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { isReservedTenantSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
|
||||
import { requireUserId, validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
const RESERVATION_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;
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
reservationRequestKey: string;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const { t } = await getTranslations(request);
|
||||
return {
|
||||
title: `${t("admin.accounts.create.title")} | ${process.env.APP_NAME}`,
|
||||
reservationRequestKey: randomUUID(),
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function badRequest(data: ActionData, status = 400) {
|
||||
return Response.json(data, { status });
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const name = form.get("name")?.toString().trim() ?? "";
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const reservationRequestKey = form.get("reservationRequestKey")?.toString() ?? "";
|
||||
const ownerEmail = form.get("ownerEmail")?.toString().trim().toLowerCase() ?? "";
|
||||
const ownerFirstName = form.get("ownerFirstName")?.toString().trim() ?? "";
|
||||
const ownerLastName = form.get("ownerLastName")?.toString().trim() ?? "";
|
||||
const planCode = form.get("planCode")?.toString().trim() ?? "";
|
||||
const seatQuantity = form.get("seatQuantity")?.toString() ?? "1";
|
||||
const trialDays = Number.parseInt(form.get("trialDays")?.toString() ?? "0", 10) || 0;
|
||||
|
||||
if (
|
||||
!name ||
|
||||
!slug ||
|
||||
!RESERVATION_REQUEST_KEY_PATTERN.test(reservationRequestKey) ||
|
||||
!UserValidationUtils.validateEmail(ownerEmail) ||
|
||||
!ownerFirstName ||
|
||||
!ownerLastName
|
||||
) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
if (slug !== UrlUtils.slugify(slug) || isReservedTenantSlug(slug)) {
|
||||
return badRequest({ error: t("settings.tenant.errors.reservedSlug", { slug }) });
|
||||
}
|
||||
|
||||
const operatorUserId = await requireUserId(request);
|
||||
const operator = await getUser(operatorUserId);
|
||||
if (!operator) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
let reason: string;
|
||||
try {
|
||||
reason = assertAdminActionReason(form.get("reason")?.toString());
|
||||
} catch (error) {
|
||||
if (error instanceof AdminActionInputError) return badRequest({ error: t(error.i18nKey) });
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
const ownerInvitation = await prepareReservedOwnerInvitation({
|
||||
request,
|
||||
issuanceKey: reservationRequestKey,
|
||||
tenantName: name,
|
||||
email: ownerEmail,
|
||||
firstName: ownerFirstName,
|
||||
lastName: ownerLastName,
|
||||
issuer: { id: operator.id, firstName: operator.firstName, locale: operator.locale },
|
||||
});
|
||||
const tenant = await reserveTenantWithoutOwner({ name, slug, operatorUserId, reservationRequestKey, ownerInvitation });
|
||||
|
||||
const actor = { actorUserId: operator.id, actorEmail: operator.email, request };
|
||||
if (planCode) {
|
||||
await setTenantBillingPlanSeats({ tenantId: tenant.id, planCode, seatQuantity, reason, ...actor });
|
||||
}
|
||||
if (trialDays > 0) {
|
||||
await extendTenantTrial({ tenantId: tenant.id, days: trialDays, reason, ...actor });
|
||||
}
|
||||
|
||||
await recordAdminAction({
|
||||
action: "tenant.created",
|
||||
targetKind: "tenant",
|
||||
targetId: tenant.id,
|
||||
reason,
|
||||
after: {
|
||||
name,
|
||||
slug,
|
||||
ownerEmail,
|
||||
planCode: planCode || null,
|
||||
trialDays: trialDays || null,
|
||||
},
|
||||
...actor,
|
||||
});
|
||||
|
||||
return redirect(`${adminPath(`accounts/${tenant.id}`, { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.toast.created")}`);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminActionInputError || error instanceof AdminBillingError) {
|
||||
return badRequest({ error: t(error.i18nKey) });
|
||||
}
|
||||
if (error instanceof CatalogError) {
|
||||
return badRequest({ error: t("admin.accounts.create.failed") }, 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminTenantCreateRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const rootData = useRootData();
|
||||
return (
|
||||
<AdminTenantCreatePage
|
||||
reservationRequestKey={data.reservationRequestKey}
|
||||
csrf={rootData.csrf ?? ""}
|
||||
submitting={navigation.state === "submitting"}
|
||||
feedback={{ error: actionData?.error }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-4
@@ -61,10 +61,6 @@ export default function AdminRolesRoute() {
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.permissions"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.adminUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/admin-users", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.accountUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }),
|
||||
|
||||
+63
-42
@@ -18,6 +18,8 @@ import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsServ
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
@@ -31,44 +33,52 @@ type LoaderData = {
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenant = await getTenant(params.account!);
|
||||
if (!tenant) {
|
||||
const tenantId = params.account;
|
||||
if (!tenantId) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const adminUsers = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const tenantUsers = await adminGetAllTenantUsers(params.account ?? "");
|
||||
const roles = await getAllRoles("app");
|
||||
|
||||
const items: UserWithRoles[] = [];
|
||||
adminUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
return runWithRlsContext({ tenantId }, async () => {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!tenant) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }));
|
||||
}
|
||||
});
|
||||
tenantUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
tenant,
|
||||
};
|
||||
return data;
|
||||
const adminUsers = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const tenantUsers = await adminGetAllTenantUsers(tenantId);
|
||||
const roles = await getAllRoles("app");
|
||||
|
||||
const items: UserWithRoles[] = [];
|
||||
adminUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
tenantUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
tenant,
|
||||
};
|
||||
return data;
|
||||
});
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
@@ -77,27 +87,37 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
const roleId = form.get("role-id")?.toString() ?? "";
|
||||
const add = form.get("add") === "true";
|
||||
const tenantId = params.account;
|
||||
if (!tenantId) return badRequest({ intent: action, errorKey: "shared.notFound" });
|
||||
|
||||
const tenant = await getTenant(params.account ?? "");
|
||||
const user = await getUser(userId);
|
||||
const role = await getRole(roleId);
|
||||
const tenantMember = await getTenantMember(userId, tenant?.id);
|
||||
return runWithRlsContext({ tenantId }, async () => {
|
||||
const tenant = await getTenant(tenantId);
|
||||
const user = await getUser(userId);
|
||||
const role = await getRole(roleId);
|
||||
const tenantMember = await getTenantMember(userId, tenant?.id);
|
||||
|
||||
if (!tenant || !user || !role || role.type !== "app" || (!user.admin && !tenantMember)) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
if (!tenant || !user || !role || role.type !== "app" || (!user.admin && !tenantMember)) {
|
||||
return badRequest({ intent: action, errorKey: "shared.notFound" });
|
||||
}
|
||||
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.created", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
} else {
|
||||
await deleteUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.deleted", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
}
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.created", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
} else {
|
||||
await deleteUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.deleted", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
}
|
||||
|
||||
return Response.json({});
|
||||
return Response.json({
|
||||
intent: action,
|
||||
ok: true,
|
||||
messageKey: add
|
||||
? "admin.accounts.rolesAndPermissions.accountUsers.toast.roleAssigned"
|
||||
: "admin.accounts.rolesAndPermissions.accountUsers.toast.roleRemoved",
|
||||
} satisfies ActionData);
|
||||
});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
return badRequest({ intent: action, errorKey: "shared.invalidForm" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -110,6 +130,7 @@ export default function AdminAccountUsersFromTenant() {
|
||||
const [items, setItems] = useState(data.items);
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
useSaveToast(actionData);
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
|
||||
+1
-12
@@ -9,7 +9,6 @@ import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
@@ -32,7 +31,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesAndPermissionsAccountUsersRoute() {
|
||||
const { i18n, t } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
@@ -73,16 +72,6 @@ export default function AdminRolesAndPermissionsAccountUsersRoute() {
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "types",
|
||||
title: t("shared.types"),
|
||||
value: (i) =>
|
||||
i.types.length === 0 ? (
|
||||
<span className="text-muted-foreground">{t("shared.default")}</span>
|
||||
) : (
|
||||
i.types.map((f) => translateLabel(t, i18n, f.title)).join(", ")
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "users",
|
||||
title: t("models.user.plural"),
|
||||
|
||||
+16
-117
@@ -1,123 +1,22 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllRoles, getRole, RoleWithPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { adminGetAllUsers, getUser, UserWithDetails, UserWithRoles } from "~/utils/db/users.db.server";
|
||||
import UserRolesTable from "~/components/core/roles/UserRolesTable";
|
||||
import { useEffect, useState } from "react";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { createUserRole, deleteUserRole } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: UserWithDetails[];
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
async function redirectToAdminRoleBundles(request: Request) {
|
||||
await requireAdminIdentityPermission(request, "admin_identity.roles.read");
|
||||
throw redirect(adminPath("settings/admin-roles", { mode: "host-aware" }), 303);
|
||||
}
|
||||
|
||||
const items = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const roles = await getAllRoles("admin");
|
||||
export function loader({ request }: LoaderFunctionArgs) {
|
||||
return redirectToAdminRoleBundles(request);
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.adminUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
export function action({ request }: ActionFunctionArgs) {
|
||||
return redirectToAdminRoleBundles(request);
|
||||
}
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
const roleId = form.get("role-id")?.toString() ?? "";
|
||||
const add = form.get("add") === "true";
|
||||
|
||||
const user = await getUser(userId);
|
||||
const role = await getRole(roleId);
|
||||
|
||||
if (!user || !user.admin || !role || role.type !== "admin") {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId);
|
||||
await createAdminLog(request, "admin.adminUserRoles.created", `${user.email} - ${role.name}`);
|
||||
} else {
|
||||
await deleteUserRole(userId, roleId);
|
||||
await createAdminLog(request, "admin.adminUserRoles.deleted", `${user.email} - ${role.name}`);
|
||||
}
|
||||
return Response.json({});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesAndPermissionsAdminUsersRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const [items, setItems] = useState(data.items);
|
||||
const submit = useSubmit();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setItems(data.items);
|
||||
}, [data]);
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!items) {
|
||||
return [];
|
||||
}
|
||||
return items.filter(
|
||||
(f) =>
|
||||
f.email?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.firstName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.lastName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.tenants.find((f) => f.tenant.name.toUpperCase().includes(searchInput.toUpperCase())) ||
|
||||
f.roles.find(
|
||||
(f) => f.role.name.toUpperCase().includes(searchInput.toUpperCase()) || f.role.description.toUpperCase().includes(searchInput.toUpperCase())
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
function onChange(item: UserWithRoles, role: RoleWithPermissions, add: any) {
|
||||
const form = new FormData();
|
||||
form.set("action", "edit");
|
||||
form.set("user-id", item.id);
|
||||
form.set("role-id", role.id);
|
||||
form.set("add", add ? "true" : "false");
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<UserRolesTable items={filteredItems()} roles={data.roles} onChange={onChange} disabled={!getUserHasPermission(adminData, "admin.roles.set")} />
|
||||
</div>
|
||||
);
|
||||
export default function LegacyAdminRoleAssignmentRedirect() {
|
||||
return null;
|
||||
}
|
||||
+15
-5
@@ -1,4 +1,4 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useActionData, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllPermissions, PermissionWithRoles, updatePermission } from "~/utils/db/permissions/permissions.db.server";
|
||||
import PermissionsTable from "~/components/core/roles/PermissionsTable";
|
||||
@@ -17,6 +17,7 @@ import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
@@ -60,10 +61,13 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
|
||||
type ActionData = {
|
||||
items?: PermissionWithRoles[];
|
||||
intent?: string;
|
||||
ok?: boolean;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
@@ -78,20 +82,26 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await updatePermission(id, { order: Number(order) });
|
||||
})
|
||||
);
|
||||
return Response.json({ items: await getAllPermissions() });
|
||||
return Response.json({
|
||||
items: await getAllPermissions(),
|
||||
intent: action,
|
||||
ok: true,
|
||||
messageKey: "admin.accounts.rolesAndPermissions.permissions.toast.orderSaved",
|
||||
} satisfies ActionData);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
return Response.json({ intent: action, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useLoaderData<ActionData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
const { t } = useTranslation();
|
||||
useSaveToast(actionData);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
|
||||
+3
-1
@@ -78,7 +78,9 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
const toastKey =
|
||||
action === "delete" ? "admin.accounts.rolesAndPermissions.permissions.toast.deleted" : "admin.accounts.rolesAndPermissions.permissions.toast.updated";
|
||||
return redirect(`${adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" })}?toast=${encodeURIComponent(toastKey)}`);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
+4
-2
@@ -15,7 +15,7 @@ type LoaderData = {
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const loader = async ({ request, params: _params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
@@ -70,7 +70,9 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.rolesAndPermissions.permissions.toast.created")}`
|
||||
);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
+6
-11
@@ -21,13 +21,13 @@ describe("admin role assignment scoping", () => {
|
||||
expect(source).not.toContain("deleteUserRole(userId, roleId, params.account)");
|
||||
});
|
||||
|
||||
it("restricts admin user assignments to admin users and admin roles", () => {
|
||||
it("retires legacy UserRole-based admin assignments in favor of AdminRBAC", () => {
|
||||
const source = readRoute("admin-users.tsx");
|
||||
|
||||
expect(source).toContain("!user.admin");
|
||||
expect(source).toContain('role.type !== "admin"');
|
||||
expect(source).toContain("createUserRole(userId, roleId)");
|
||||
expect(source).toContain("deleteUserRole(userId, roleId)");
|
||||
expect(source).toContain("admin_identity.roles.read");
|
||||
expect(source).toContain('adminPath("settings/admin-roles"');
|
||||
expect(source).not.toContain("createUserRole");
|
||||
expect(source).not.toContain("deleteUserRole");
|
||||
});
|
||||
|
||||
it("writes clean role assignment audit details", () => {
|
||||
@@ -36,13 +36,12 @@ describe("admin role assignment scoping", () => {
|
||||
|
||||
expect(adminUsersSource).not.toContain("${role.name}}");
|
||||
expect(accountUsersSource).not.toContain("${role.name}}");
|
||||
expect(adminUsersSource).toContain("`${user.email} - ${role.name}`");
|
||||
expect(adminUsersSource).not.toContain("createAdminLog");
|
||||
expect(accountUsersSource).toContain("`[${tenant.name}] ${user.email} - ${role.name}`");
|
||||
});
|
||||
|
||||
it("uses render-translated stable audit action values", () => {
|
||||
const routeFiles = [
|
||||
"admin-users.tsx",
|
||||
"account-users.$account.tsx",
|
||||
"permissions/new.tsx",
|
||||
"permissions/$id.tsx",
|
||||
@@ -57,8 +56,6 @@ describe("admin role assignment scoping", () => {
|
||||
.filter((action): action is string => typeof action === "string");
|
||||
});
|
||||
|
||||
expect(actions).toContain("admin.adminUserRoles.created");
|
||||
expect(actions).toContain("admin.adminUserRoles.deleted");
|
||||
expect(actions).toContain("admin.accountUserRoles.created");
|
||||
expect(actions).toContain("admin.accountUserRoles.deleted");
|
||||
expect(actions).toContain("admin.roles.updated");
|
||||
@@ -73,8 +70,6 @@ describe("admin role assignment scoping", () => {
|
||||
expect(actions).not.toContain("Deleted");
|
||||
expect(new Set(actions)).toEqual(
|
||||
new Set([
|
||||
"admin.adminUserRoles.created",
|
||||
"admin.adminUserRoles.deleted",
|
||||
"admin.accountUserRoles.created",
|
||||
"admin.accountUserRoles.deleted",
|
||||
"admin.permissions.created",
|
||||
|
||||
-1
@@ -1,5 +1,4 @@
|
||||
import { LoaderFunctionArgs, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import RolesTable from "~/components/core/roles/RolesTable";
|
||||
import { getAllRolesWithUsers, RoleWithPermissionsAndUsers } from "~/utils/db/permissions/roles.db.server";
|
||||
|
||||
+5
-3
@@ -10,7 +10,7 @@ import { deleteRole, getRole, RoleWithPermissions, updateRole } from "~/utils/db
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
@@ -78,7 +78,7 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
permissions,
|
||||
})}`
|
||||
);
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
return Response.json({ success: t("admin.accounts.rolesAndPermissions.roles.toast.updated") });
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.updateFailed") }, { status: 400 });
|
||||
}
|
||||
@@ -89,7 +89,9 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.rolesAndPermissions.roles.toast.deleted")}`
|
||||
);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
+4
-2
@@ -15,7 +15,7 @@ type LoaderData = {
|
||||
permissions: PermissionWithRoles[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const loader = async ({ request, params: _params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
@@ -72,7 +72,9 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.accounts.rolesAndPermissions.roles.toast.created")}`
|
||||
);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
+45
-16
@@ -20,13 +20,30 @@ import {
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { MISSING_NUMBER_PLACEHOLDER, toFiniteNumber, useLocaleFormatters } from "~/locale/format";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
// Prisma `Decimal` columns do not reach the browser as numbers: the loader
|
||||
// serialization keeps their structural shape, so a client-side `Number(price)`
|
||||
// evaluates to `NaN` and the tier column renders "NaN €". Normalize the amount
|
||||
// server-side, which is also where every other price surface converts it.
|
||||
function toSerializableSubscriptionProduct(item: TenantSubscriptionProductWithTenant) {
|
||||
return {
|
||||
...item,
|
||||
prices: item.prices.map((price) => ({
|
||||
...price,
|
||||
subscriptionPrice: price.subscriptionPrice ? { ...price.subscriptionPrice, price: Number(price.subscriptionPrice.price) } : null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
type SubscriptionListItem = ReturnType<typeof toSerializableSubscriptionProduct>;
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: TenantSubscriptionProductWithTenant[];
|
||||
items: SubscriptionListItem[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
@@ -74,14 +91,27 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const getFilterValue = (name: string) => filters.properties.find((property) => property.name === name)?.value?.toString();
|
||||
const { items, pagination } = await getAllTenantSubscriptionProducts(
|
||||
{
|
||||
status: getFilterValue("status"),
|
||||
subscriptionProductId: getFilterValue("subscriptionProductId"),
|
||||
tenantId: getFilterValue("tenantId"),
|
||||
},
|
||||
currentPagination
|
||||
const requestedTenantId = getFilterValue("tenantId");
|
||||
const targetTenants = requestedTenantId ? tenantOptions.filter((tenant) => tenant.id === requestedTenantId) : tenantOptions;
|
||||
const tenantPages = await Promise.all(
|
||||
targetTenants.map((tenant) =>
|
||||
runWithRlsContext({ tenantId: tenant.id }, () =>
|
||||
getAllTenantSubscriptionProducts({
|
||||
status: getFilterValue("status"),
|
||||
subscriptionProductId: getFilterValue("subscriptionProductId"),
|
||||
tenantId: tenant.id,
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
const allItems = tenantPages.flatMap((page) => page.items).sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime());
|
||||
const offset = currentPagination.pageSize * (currentPagination.page - 1);
|
||||
const items = allItems.slice(offset, offset + currentPagination.pageSize).map(toSerializableSubscriptionProduct);
|
||||
const pagination: PaginationDto = {
|
||||
...currentPagination,
|
||||
totalItems: allItems.length,
|
||||
totalPages: Math.ceil(allItems.length / currentPagination.pageSize),
|
||||
};
|
||||
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: `${t("models.subscription.plural")} | ${process.env.APP_NAME}` }],
|
||||
@@ -129,13 +159,12 @@ export default function () {
|
||||
<div>
|
||||
{t(product.subscriptionProduct.title)}{" "}
|
||||
{product.prices
|
||||
.map(
|
||||
(f) =>
|
||||
`${formatters.currency(Number(f.subscriptionPrice?.price ?? 0), f.subscriptionPrice?.currency || "USD")} - ${SubscriptionUtils.getBillingPeriodDescription(
|
||||
t,
|
||||
f.subscriptionPrice?.billingPeriod ?? 0
|
||||
)}`
|
||||
)
|
||||
.map((f) => {
|
||||
const amount = toFiniteNumber(f.subscriptionPrice?.price);
|
||||
const amountLabel =
|
||||
amount === null ? MISSING_NUMBER_PLACEHOLDER : formatters.currency(amount, f.subscriptionPrice?.currency || "USD");
|
||||
return `${amountLabel} - ${SubscriptionUtils.getBillingPeriodDescription(t, f.subscriptionPrice?.billingPeriod ?? 0)}`;
|
||||
})
|
||||
.join(", ")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+12
-1
@@ -8,6 +8,8 @@ import { adminGetTenantSubscriptionProductById, type TenantSubscriptionProductWi
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: TenantSubscriptionProductWithTenant;
|
||||
@@ -15,7 +17,16 @@ type LoaderData = {
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.settings.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const item = await adminGetTenantSubscriptionProductById(params.id!);
|
||||
const subscriptionProductId = params.id;
|
||||
if (!subscriptionProductId) {
|
||||
return Response.json({ error: t("admin.accounts.subscriptions.errors.notFound") }, { status: 404 });
|
||||
}
|
||||
const tenantOptions = await adminGetAllTenantsIdsAndNames();
|
||||
let item: TenantSubscriptionProductWithTenant | null = null;
|
||||
for (const tenant of tenantOptions) {
|
||||
item = await runWithRlsContext({ tenantId: tenant.id }, () => adminGetTenantSubscriptionProductById(subscriptionProductId));
|
||||
if (item) break;
|
||||
}
|
||||
if (!item) {
|
||||
return Response.json({ error: t("admin.accounts.subscriptions.errors.notFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
+113
-144
@@ -1,10 +1,8 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
@@ -16,47 +14,41 @@ vi.mock("react-router", async () => {
|
||||
useOutlet: () => null,
|
||||
};
|
||||
});
|
||||
vi.mock("react-hot-toast", () => ({ default: { success: vi.fn() } }));
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
||||
appPath: ({ tenantSlug, path }: { tenantSlug: string; path?: string }) => (path ? `/${tenantSlug}/${path}` : `/${tenantSlug}`),
|
||||
adminPath: (path?: string | { mode?: string; path?: string }, options?: { mode?: string }) => {
|
||||
const inputPath = typeof path === "object" ? path.path : path;
|
||||
const mode = typeof path === "object" ? path.mode : options?.mode;
|
||||
const normalizedPath = inputPath ? `/${inputPath.replace(/^\/+/, "")}` : "";
|
||||
return mode === "legacy" ? `/admin${normalizedPath}` : normalizedPath || "/";
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/app/HostRouting.server", () => ({
|
||||
getHostRoutingContextFromRequest: vi.fn(() => "admin"),
|
||||
}));
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({ routing: undefined }),
|
||||
}));
|
||||
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
vi.mock("~/components/core/users/UsersTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/button", () => ({ Button: () => null }));
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
|
||||
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({ createMetrics: vi.fn() }));
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() }));
|
||||
vi.mock("~/utils/data/useAdminData", () => ({ useAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ getLastUserLog: vi.fn() }));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ getLastUserLogsByUserIds: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
getFiltersFromCurrentUrl: vi.fn(),
|
||||
getPaginationFromCurrentUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/enforcement.server", () => ({
|
||||
enforceAdminMfa: vi.fn(),
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({
|
||||
routing: {
|
||||
appBaseDomain: "example.test",
|
||||
protocol: "https",
|
||||
webAppHost: "app.example.test",
|
||||
adminAppHost: "admin.example.test",
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/step-up.server", () => ({
|
||||
checkMfaStepUpState: vi.fn(),
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
||||
appPath: ({ tenantSlug, path }: { tenantSlug: string; path?: string }) => `/${tenantSlug}${path ? `/${path}` : ""}`,
|
||||
adminPath: (path?: string) => (path ? `/${path}` : "/"),
|
||||
}));
|
||||
vi.mock("~/utils/auth/passwordHasher.server", () => ({ hashPassword: vi.fn(async () => "new-password-hash") }));
|
||||
vi.mock("~/services/auth/password-policy.server", () => ({ validatePassword: vi.fn(async () => ({ valid: true, errors: [] })) }));
|
||||
vi.mock("~/services/auth/sessionStore.server", () => ({ revokeAllUserSessionsForUser: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsIdsAndNames: vi.fn(),
|
||||
getTenant: vi.fn(),
|
||||
@@ -64,163 +56,140 @@ vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
adminGetAllUsers: vi.fn(),
|
||||
getUser: vi.fn(),
|
||||
getUserTotpStatus: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
createImpersonationStartedAt: vi.fn(() => "2026-05-08T17:00:00.000Z"),
|
||||
createUserSession: vi.fn(),
|
||||
createImpersonationStartedAt: vi.fn(() => "2026-07-24T17:00:00.000Z"),
|
||||
getUserInfo: vi.fn(),
|
||||
getUserSession: vi.fn(),
|
||||
setLoggedUser: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/impersonation-audit.server", () => ({
|
||||
createImpersonationAudit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
vi.mock("~/services/auth/session-handoff.server", () => ({ createSessionHandoffRedirect: vi.fn() }));
|
||||
vi.mock("~/services/admin/admin-action-audit.server", () => ({ recordAdminAction: vi.fn() }));
|
||||
vi.mock("~/services/admin/admin-identity.server", () => ({ requireAdminIdentityPermission: vi.fn() }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
||||
default: { createUserEventWithMutation: vi.fn(async (_args, mutation) => mutation()) },
|
||||
}));
|
||||
|
||||
import { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { createSessionHandoffRedirect } from "~/services/auth/session-handoff.server";
|
||||
import { revokeAllUserSessionsForUser } from "~/services/auth/sessionStore.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getUser, getUserTotpStatus, updateUserPassword } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUser, updateUserPassword } from "~/utils/db/users.db.server";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { action } from "./users";
|
||||
|
||||
const actor = { id: "admin-1", admin: true, email: "admin@example.test" };
|
||||
const targetUser = { id: "user-1", admin: false, email: "user@example.test", defaultTenantId: "tenant-1" };
|
||||
const actorInfo = {
|
||||
userId: actor.id,
|
||||
lightOrDarkMode: "light",
|
||||
lng: "en",
|
||||
cookies: [],
|
||||
const adminSession = {
|
||||
id: "admin-session-1",
|
||||
adminUserId: "admin-1",
|
||||
adminUser: { id: "admin-1", email: "admin@example.test" },
|
||||
};
|
||||
const targetUser = {
|
||||
id: "user-1",
|
||||
email: "user@example.test",
|
||||
firstName: "Target",
|
||||
lastName: "User",
|
||||
defaultTenantId: "tenant-1",
|
||||
};
|
||||
const enabledTotpStatus = { enabled: true, pending: false, enabledAt: new Date("2026-05-08T12:00:00.000Z"), pendingCreatedAt: null };
|
||||
const freshStepUp = { verified: true, state: { userId: actor.id, method: "totp", verifiedAt: "2026-05-08T16:59:00.000Z" }, ageMs: 60_000 };
|
||||
|
||||
function postRequest(actionName = "impersonate", extra: Record<string, string> = {}) {
|
||||
return new Request("https://admin.example.test/accounts/users?filter=active", {
|
||||
return new Request("https://admin.example.test/accounts/users", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: actionName, "user-id": targetUser.id, ...extra }),
|
||||
body: new URLSearchParams({
|
||||
action: actionName,
|
||||
"user-id": targetUser.id,
|
||||
reason: "Supportfall HG-1234 prüfen",
|
||||
...extra,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async function callAction(actionName = "impersonate", extra: Record<string, string> = {}) {
|
||||
try {
|
||||
const response = await action({ request: postRequest(actionName, extra), params: {}, context: {}, unstable_pattern: "admin/accounts/users" } as ActionFunctionArgs);
|
||||
return { thrown: false, response: response as Response };
|
||||
} catch (error) {
|
||||
return { thrown: true, response: await (error as Promise<Response>) };
|
||||
}
|
||||
return action({
|
||||
request: postRequest(actionName, extra),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/accounts/users",
|
||||
} as ActionFunctionArgs);
|
||||
}
|
||||
|
||||
describe("admin accounts user impersonation MFA guard", () => {
|
||||
describe("separated AdminUser tenant impersonation", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(requireAdminIdentityPermission).mockResolvedValue(adminSession as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue(actorInfo as never);
|
||||
vi.mocked(getUserSession).mockResolvedValue({ get: vi.fn() } as never);
|
||||
vi.mocked(getUser).mockImplementation(async (id?: string) => (id === actor.id || id === undefined ? actor : id === targetUser.id ? targetUser : null) as never);
|
||||
vi.mocked(getUserTotpStatus).mockResolvedValue(enabledTotpStatus as never);
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue(freshStepUp as never);
|
||||
vi.mocked(enforceAdminMfa).mockImplementation(() => ({ allowed: true, reason: "allowed", redirectTo: "/accounts/users" }) as never);
|
||||
vi.mocked(setLoggedUser).mockResolvedValue({ userId: targetUser.id, defaultTenantId: "tenant-1" } as never);
|
||||
vi.mocked(getUser).mockResolvedValue(targetUser as never);
|
||||
vi.mocked(setLoggedUser).mockResolvedValue({
|
||||
userId: targetUser.id,
|
||||
defaultTenantId: "tenant-1",
|
||||
defaultTenant: { id: "tenant-1", slug: "acme" },
|
||||
} as never);
|
||||
vi.mocked(getTenant).mockResolvedValue({ id: "tenant-1", slug: "acme" } as never);
|
||||
vi.mocked(createSessionHandoffRedirect).mockResolvedValue(
|
||||
new Response(null, { status: 302, headers: { Location: "https://app.example.test/auth/session-handoff?code=opaque" } }) as never
|
||||
);
|
||||
vi.mocked(updateUserPassword).mockResolvedValue({} as never);
|
||||
vi.mocked(deleteUserWithItsTenants).mockResolvedValue({ deletedTenants: [] } as never);
|
||||
vi.mocked(createImpersonationAudit).mockResolvedValue({
|
||||
id: "audit-1",
|
||||
createdAt: new Date("2026-05-08T17:00:00.000Z"),
|
||||
actorUserId: actor.id,
|
||||
targetUserId: targetUser.id,
|
||||
tenantId: "tenant-1",
|
||||
action: "start",
|
||||
reason: "admin.users.impersonate",
|
||||
requestPath: "/accounts/users",
|
||||
metadata: null,
|
||||
} as never);
|
||||
vi.mocked(createUserSession).mockResolvedValue(new Response(null, { status: 302, headers: { Location: "/acme/dashboard" } }) as never);
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA step-up before creating an impersonation session", async () => {
|
||||
const result = await callAction();
|
||||
it("uses the smallest permission, reasoned platform audit and a bounded banner marker", async () => {
|
||||
const response = await callAction();
|
||||
|
||||
expect(result.thrown).toBe(false);
|
||||
expect(result.response).toBeDefined();
|
||||
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.impersonate");
|
||||
expect(getUserTotpStatus).toHaveBeenCalledWith(actor.id);
|
||||
expect(checkMfaStepUpState).toHaveBeenCalledWith(expect.anything(), actor.id);
|
||||
expect(enforceAdminMfa).toHaveBeenCalledWith(expect.objectContaining({
|
||||
requestUrl: "https://admin.example.test/accounts/users?filter=active",
|
||||
userId: actor.id,
|
||||
isAdmin: true,
|
||||
totpStatus: enabledTotpStatus,
|
||||
stepUp: freshStepUp,
|
||||
redirectMode: "host-aware",
|
||||
}));
|
||||
expect(setLoggedUser).toHaveBeenCalledWith(targetUser);
|
||||
expect(getTenant).toHaveBeenCalledWith("tenant-1");
|
||||
expect(result.response.headers.get("Location")).toBe("/acme/dashboard");
|
||||
expect(response.status).toBe(302);
|
||||
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin_identity.impersonation.start");
|
||||
expect(recordAdminAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "impersonation.started",
|
||||
actorUserId: adminSession.adminUserId,
|
||||
targetId: targetUser.id,
|
||||
reason: "Supportfall HG-1234 prüfen",
|
||||
})
|
||||
);
|
||||
expect(createSessionHandoffRedirect).toHaveBeenCalledWith({
|
||||
request: expect.any(Request),
|
||||
session: expect.objectContaining({
|
||||
userId: targetUser.id,
|
||||
impersonatingFromAdminUserId: adminSession.adminUserId,
|
||||
impersonatingFromAdminEmail: adminSession.adminUser.email,
|
||||
impersonatingStartedAt: "2026-07-24T17:00:00.000Z",
|
||||
}),
|
||||
redirectTo: "https://app.example.test/acme/dashboard",
|
||||
});
|
||||
});
|
||||
|
||||
it("redirects to the MFA challenge and does not switch sessions when step-up is missing", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
|
||||
const result = await callAction();
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
it("rejects an impersonation without a meaningful operator reason before switching", async () => {
|
||||
const response = await callAction("impersonate", { reason: "x" });
|
||||
expect(response.status).toBe(400);
|
||||
expect(setLoggedUser).not.toHaveBeenCalled();
|
||||
expect(createImpersonationAudit).not.toHaveBeenCalled();
|
||||
expect(createUserSession).not.toHaveBeenCalled();
|
||||
expect(recordAdminAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA before changing a user password", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
|
||||
const result = await callAction("change-password", { "password-new": "new-password-123" });
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
expect(updateUserPassword).not.toHaveBeenCalled();
|
||||
it("uses dedicated AdminRBAC for password reset and revokes the target sessions first", async () => {
|
||||
const response = await callAction("change-password", { "password-new": "new-password-123" });
|
||||
expect(response.status).toBe(200);
|
||||
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.changePassword");
|
||||
expect(revokeAllUserSessionsForUser).toHaveBeenCalledWith(targetUser.id);
|
||||
expect(updateUserPassword).toHaveBeenCalledWith({ passwordHash: "new-password-hash" }, targetUser.id);
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA before deleting a user", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
it("uses dedicated AdminRBAC for tenant-user deletion", async () => {
|
||||
const response = await callAction("delete-user");
|
||||
expect(response.status).toBe(200);
|
||||
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.delete");
|
||||
expect(deleteUserWithItsTenants).toHaveBeenCalledWith({
|
||||
actorUserId: adminSession.adminUserId,
|
||||
targetUser,
|
||||
request: expect.any(Request),
|
||||
});
|
||||
});
|
||||
|
||||
const result = await callAction("delete-user");
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
||||
it("propagates permission denial as 404 without touching the tenant target", async () => {
|
||||
vi.mocked(requireAdminIdentityPermission).mockRejectedValueOnce(Response.json({}, { status: 404 }));
|
||||
await expect(callAction()).rejects.toMatchObject({ status: 404 });
|
||||
expect(setLoggedUser).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+59
-150
@@ -1,17 +1,13 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { adminGetAllUsers, getUser, getUserTotpStatus, updateUserPassword, UserWithDetails } from "~/utils/db/users.db.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { createImpersonationStartedAt, createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { adminGetAllUsers, getUser, updateUserPassword, UserWithDetails } from "~/utils/db/users.db.server";
|
||||
import { createImpersonationStartedAt, getUserInfo, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import { requireAdminMfaForAction } from "~/services/auth/admin-mfa-gate.server";
|
||||
import UsersTable from "~/components/core/users/UsersTable";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
@@ -19,25 +15,23 @@ import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropert
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { adminGetAllTenantsIdsAndNames, getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import type { Log } from "@hivegrid/db/prisma-browser";
|
||||
import { getLastUserLogsByUserIds } from "~/utils/db/logs.db.server";
|
||||
import { getLastUserLogsByUserIds, type AdminUserLastActivity } from "~/utils/db/logs.db.server";
|
||||
import { useNavigate, useOutlet } from "react-router";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import { UserPasswordUpdatedDto } from "~/modules/events/dtos/UserPasswordUpdatedDto";
|
||||
import { UserProfileDeletedDto } from "~/modules/events/dtos/UserProfileDeletedDto";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { extractWebActorIp, extractWebActorUserAgent } from "~/utils/audit/withAuditContext";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAppPath, absoluteAppRootPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { revokeAllUserSessionsForUser } from "~/services/auth/sessionStore.server";
|
||||
import { createSessionHandoffRedirect } from "~/services/auth/session-handoff.server";
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
// export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
@@ -48,7 +42,7 @@ type LoaderData = {
|
||||
items: UserWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
lastLogs: { userId: string; log: Log }[];
|
||||
lastLogs: { userId: string; log: AdminUserLastActivity }[];
|
||||
};
|
||||
|
||||
export function adminImpersonationRedirectTarget(
|
||||
@@ -60,7 +54,7 @@ export function adminImpersonationRedirectTarget(
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.users");
|
||||
await time(verifyUserHasPermission(request, "admin.users.view"), "verifyUserHasPermission");
|
||||
await time(requireAdminIdentityPermission(request, "admin.users.view"), "requireAdminIdentityPermission");
|
||||
let { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
@@ -123,12 +117,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { items, pagination } = await time(adminGetAllUsers(filters, currentPagination), "adminGetAllUsers");
|
||||
|
||||
const lastLogsByUserId = await time(getLastUserLogsByUserIds(items.map((user) => user.id)), "getLastUserLogsByUserIds");
|
||||
const lastLogs: { userId: string; log: Log }[] = items
|
||||
const lastLogs: { userId: string; log: AdminUserLastActivity }[] = items
|
||||
.map((user) => {
|
||||
const log = lastLogsByUserId.get(user.id);
|
||||
return log ? { userId: user.id, log } : null;
|
||||
})
|
||||
.filter((entry): entry is { userId: string; log: Log } => entry !== null);
|
||||
.filter((entry): entry is { userId: string; log: AdminUserLastActivity } => entry !== null);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.user.plural")} | ${process.env.APP_NAME}`,
|
||||
@@ -147,9 +141,7 @@ type ActionData = {
|
||||
const success = (data: ActionData) => Response.json(data, { status: 200 });
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
await validateCSRFToken(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const form = await request.formData();
|
||||
@@ -162,165 +154,82 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
}
|
||||
switch (action) {
|
||||
case "impersonate": {
|
||||
await verifyUserHasPermission(request, "admin.users.impersonate");
|
||||
// Phase 09 #82 — sensitive-action MFA gate (otpauth from #26).
|
||||
// requireAdminMfaForAction wraps the existing enforceAdminMfa /
|
||||
// step-up plumbing under a typed action taxonomy so future audit
|
||||
// events tag the gate consistently.
|
||||
await requireAdminMfaForAction(request, "impersonation.start", userInfo.userId);
|
||||
await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
|
||||
const userSession = await setLoggedUser(user);
|
||||
if (!userSession) {
|
||||
return badRequest({
|
||||
error: t("shared.notFound"),
|
||||
});
|
||||
const adminSession = await requireAdminIdentityPermission(request, "admin_identity.impersonation.start");
|
||||
const userInfo = await getUserInfo(request);
|
||||
const reason = form.get("reason")?.toString().trim() ?? "";
|
||||
if (reason.length < 10) {
|
||||
return badRequest({ error: t("admin.users.errors.impersonationReasonRequired") });
|
||||
}
|
||||
// Reuse the tenant resolved inside setLoggedUser to avoid a duplicate
|
||||
// getTenant() round-trip on every impersonation start.
|
||||
const userSession = await setLoggedUser(user);
|
||||
const tenant = userSession.defaultTenant ?? (userSession.defaultTenantId ? await getTenant(userSession.defaultTenantId) : null);
|
||||
await createImpersonationAudit({
|
||||
actorUserId: userInfo.userId,
|
||||
targetUserId: user.id,
|
||||
tenantId: tenant?.id ?? userSession.defaultTenantId ?? null,
|
||||
action: "start",
|
||||
reason: "admin.users.impersonate",
|
||||
requestPath: new URL(request.url).pathname,
|
||||
});
|
||||
// Phase 10 Task #67: also emit the consolidated AuditEvent so the
|
||||
// compliance export picks up admin impersonations without joining
|
||||
// the legacy ImpersonationAudit table. ImpersonationAudit remains
|
||||
// for backwards-compat; a future task will retire it.
|
||||
await createAuditEvent({
|
||||
tenantId: tenant?.id ?? userSession.defaultTenantId ?? null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
actorIp: extractWebActorIp(request),
|
||||
actorUserAgent: extractWebActorUserAgent(request),
|
||||
action: "admin.impersonation.start",
|
||||
targetType: "user",
|
||||
await recordAdminAction({
|
||||
action: "impersonation.started",
|
||||
actorUserId: adminSession.adminUserId,
|
||||
actorEmail: adminSession.adminUser.email,
|
||||
targetKind: "tenant-user",
|
||||
targetId: user.id,
|
||||
sourceModule: "admin",
|
||||
outcome: "success",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: { requestPath: new URL(request.url).pathname, reason: "admin.users.impersonate" },
|
||||
reason,
|
||||
request,
|
||||
extraMeta: { tenantId: tenant?.id ?? userSession.defaultTenantId ?? null },
|
||||
});
|
||||
return createUserSession(
|
||||
{
|
||||
return createSessionHandoffRedirect({
|
||||
request,
|
||||
session: {
|
||||
...userInfo,
|
||||
...userSession,
|
||||
impersonatingFromUserId: userInfo.userId,
|
||||
impersonatingFromAdminUserId: adminSession.adminUserId,
|
||||
impersonatingFromAdminEmail: adminSession.adminUser.email,
|
||||
impersonatingStartedAt: createImpersonationStartedAt(),
|
||||
},
|
||||
adminImpersonationRedirectTarget(tenant)
|
||||
);
|
||||
redirectTo: adminImpersonationRedirectTarget(tenant),
|
||||
});
|
||||
}
|
||||
case "change-password": {
|
||||
await verifyUserHasPermission(request, "admin.users.changePassword");
|
||||
const actor = await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
const adminSession = await requireAdminIdentityPermission(request, "admin.users.changePassword");
|
||||
const passwordNew = form.get("password-new")?.toString();
|
||||
if (!passwordNew) {
|
||||
return badRequest({ error: t("admin.users.errors.passwordMinLength") });
|
||||
}
|
||||
if (user?.admin) {
|
||||
return badRequest({ error: t("admin.users.errors.cannotChangeAdminPassword") });
|
||||
}
|
||||
const policyResult = await validatePolicyPassword(passwordNew, user?.email ? { email: user.email } : {});
|
||||
const policyResult = await validatePolicyPassword(passwordNew, user.email ? { email: user.email } : {});
|
||||
if (!policyResult.valid) {
|
||||
const first = policyResult.errors[0];
|
||||
return badRequest({ error: first ? t(first.code, first.args ?? {}) : t("admin.users.errors.passwordMinLength") });
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(passwordNew);
|
||||
await updateUserPassword({ passwordHash }, user?.id);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.password.updated",
|
||||
tenantId: null,
|
||||
userId: user.id,
|
||||
data: {
|
||||
user: { id: user.id, email: user.email },
|
||||
fromUser: { id: actor?.id ?? "", email: actor?.email ?? "" },
|
||||
} satisfies UserPasswordUpdatedDto,
|
||||
});
|
||||
|
||||
await revokeAllUserSessionsForUser(user.id);
|
||||
await EventsService.createUserEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "user.password.updated",
|
||||
userId: adminSession.adminUserId,
|
||||
data: {
|
||||
user: { id: user.id, email: user.email },
|
||||
fromUser: { id: adminSession.adminUserId, email: adminSession.adminUser.email },
|
||||
} satisfies UserPasswordUpdatedDto,
|
||||
},
|
||||
() => updateUserPassword({ passwordHash }, user.id)
|
||||
);
|
||||
return success({ success: t("shared.updated") });
|
||||
}
|
||||
case "delete-user": {
|
||||
await verifyUserHasPermission(request, "admin.users.delete");
|
||||
// Phase 09 #82 — destructive admin action (delete user + cascading
|
||||
// tenants) goes through the sensitive-action gate before the existing
|
||||
// step-up enforcement.
|
||||
await requireAdminMfaForAction(request, "tenant.delete", userInfo.userId);
|
||||
await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
const adminSession = await requireAdminIdentityPermission(request, "admin.users.delete");
|
||||
try {
|
||||
const { deletedTenants } = await deleteUserWithItsTenants(userId);
|
||||
const deletedAccounts = await Promise.all(
|
||||
deletedTenants.map(async (tenant) => {
|
||||
const data = {
|
||||
tenant: { id: tenant.id, name: tenant.name },
|
||||
user: { id: user.id, email: user.email },
|
||||
} satisfies AccountDeletedDto;
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.deleted",
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
data,
|
||||
});
|
||||
return data;
|
||||
})
|
||||
);
|
||||
await EventsService.create({
|
||||
await deleteUserWithItsTenants({
|
||||
actorUserId: adminSession.adminUserId,
|
||||
targetUser: user,
|
||||
request,
|
||||
event: "user.profile.deleted",
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
data: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
deletedAccounts,
|
||||
} satisfies UserProfileDeletedDto,
|
||||
});
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return badRequest({
|
||||
error: t("shared.unexpectedError"),
|
||||
});
|
||||
return badRequest({ error: t("shared.unexpectedError") });
|
||||
}
|
||||
return success({ success: t("shared.deleted") });
|
||||
}
|
||||
default: {
|
||||
default:
|
||||
return badRequest({ error: t("admin.users.errors.invalidForm") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
async function requireAdminUsersActionMfa(request: Request, actorUserId: string) {
|
||||
const session = await getUserSession(request);
|
||||
const actor = await getUser(actorUserId);
|
||||
const mfaEnforcement = enforceAdminMfa({
|
||||
requestUrl: request.url,
|
||||
userId: actor?.id,
|
||||
isAdmin: Boolean(actor?.admin),
|
||||
totpStatus: actor ? await getUserTotpStatus(actor.id) : null,
|
||||
stepUp: actor ? checkMfaStepUpState(session, actor.id) : { verified: false, reason: "missing" },
|
||||
redirectMode: "host-aware",
|
||||
appFallbackPath: absoluteAppRootPath(loadRequiredWebConfig().routing),
|
||||
});
|
||||
if (mfaEnforcement instanceof Response) {
|
||||
throw mfaEnforcement;
|
||||
}
|
||||
if (!mfaEnforcement.allowed) {
|
||||
throw redirect(mfaEnforcement.redirectTo);
|
||||
}
|
||||
return actor;
|
||||
}
|
||||
|
||||
export default function AdminUsersRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
@@ -344,17 +253,17 @@ export default function AdminUsersRoute() {
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button asChild type="button" variant="default" size="sm">
|
||||
<Link to="new">{t("shared.new")}</Link>
|
||||
<Link to={adminPath("settings/admin-users", { mode: "host-aware" })}>{t("admin.sales.adminUsers.title")}</Link>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<UsersTable
|
||||
items={data.items}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin_identity.impersonation.start")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
canSetUserRoles={adminData.isSuperAdmin}
|
||||
canSetUserRoles={false}
|
||||
pagination={data.pagination}
|
||||
lastLogs={data.lastLogs}
|
||||
/>
|
||||
|
||||
+30
-164
@@ -1,168 +1,34 @@
|
||||
import { Role } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { UserWithDetails, getUserByEmail, getUserByEmailWithDetails } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
type LoaderData = {
|
||||
user: UserWithDetails;
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const user = await getUserByEmailWithDetails(params.user!);
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
user,
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const user = await getUserByEmail(params.user);
|
||||
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "set-user-roles") {
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
let setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
setRoles = setRoles.filter((v, i, a) => a.findIndex((t) => t.role.id === v.role.id) === i);
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const countAdmins = await db.adminUser.count();
|
||||
if (!isAdmin && countAdmins === 1) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveLastAdmin") }, { status: 400 });
|
||||
}
|
||||
const hasSuperAdmin = setRoles.some((r) => r.role.name === DefaultAdminRoles.SuperAdmin);
|
||||
if (user.id === userInfo.userId && !hasSuperAdmin) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveOwnSuperAdmin") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
// return Response.json({ success: t("shared.updated") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>(data.user.roles?.filter((f) => f.role.type === "admin").map((r) => r.role.id));
|
||||
|
||||
function hasSomeAdminRoles() {
|
||||
return data.adminRoles.some((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
function hasAllAdminRoles() {
|
||||
return data.adminRoles.every((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="set-user-roles" hidden readOnly />
|
||||
{selectedRoles?.map((role, idx) => {
|
||||
return (
|
||||
<input
|
||||
key={idx}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="border-border flex items-center justify-between space-x-2 border-b pb-2">
|
||||
<div className="text-foreground/80 text-lg font-medium">{t("models.role.plural")}</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonSecondary disabled={!hasSomeAdminRoles()} onClick={() => setSelectedRoles([])}>
|
||||
{t("shared.clear")}
|
||||
</ButtonSecondary>
|
||||
|
||||
<ButtonSecondary disabled={hasAllAdminRoles()} onClick={() => setSelectedRoles(data.adminRoles.map((r) => r.id))}>
|
||||
{t("shared.selectAll")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-1 rounded-md shadow-2xs">
|
||||
{data.adminRoles?.map((role, idx) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={idx}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
<ActionResultModal actionData={actionData ?? undefined} />
|
||||
</div>
|
||||
async function redirectToDedicatedAdminIdentity(request: Request, email: string | undefined) {
|
||||
const adminUser = email
|
||||
? await runAsAdminIdentity(request, "admin_identity.users.manage", () =>
|
||||
db.adminUser.findFirst({
|
||||
where: { email: { equals: email, mode: "insensitive" } },
|
||||
select: { id: true },
|
||||
})
|
||||
)
|
||||
: null;
|
||||
throw redirect(
|
||||
adminPath(adminUser ? `settings/admin-users/${adminUser.id}` : "accounts/users", {
|
||||
mode: "host-aware",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return redirectToDedicatedAdminIdentity(request, params.user);
|
||||
}
|
||||
|
||||
export function action({ request, params }: ActionFunctionArgs) {
|
||||
return redirectToDedicatedAdminIdentity(request, params.user);
|
||||
}
|
||||
|
||||
export default function LegacyAdminUserRolesRedirect() {
|
||||
return null;
|
||||
}
|
||||
+16
-173
@@ -1,179 +1,22 @@
|
||||
import { Role } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const data: LoaderData = {
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
async function redirectToAuthentikAdminUsers(request: Request) {
|
||||
await requireAdminIdentityPermission(request, "admin_identity.users.manage");
|
||||
throw redirect(adminPath("settings/admin-users", { mode: "host-aware" }), 303);
|
||||
}
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
export function loader({ request }: LoaderFunctionArgs) {
|
||||
return redirectToAuthentikAdminUsers(request);
|
||||
}
|
||||
|
||||
if (action === "new-user") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const email = form.get("email")?.toString();
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString();
|
||||
const password = form.get("password")?.toString();
|
||||
export function action({ request }: ActionFunctionArgs) {
|
||||
return redirectToAuthentikAdminUsers(request);
|
||||
}
|
||||
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!email || !password || !firstName) {
|
||||
return Response.json({ error: t("admin.users.create.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
// if (arrRoles.length === 0) {
|
||||
// return Response.json({ error: "You must select at least one role." }, { status: 400 });
|
||||
// }
|
||||
|
||||
const existingUser = await getUserByEmail(email);
|
||||
if (existingUser) {
|
||||
return Response.json({ error: t("admin.users.create.errors.userAlreadyExists") }, { status: 400 });
|
||||
}
|
||||
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
const setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const { id } = await register({
|
||||
email,
|
||||
firstName,
|
||||
lastName: lastName ?? "",
|
||||
password,
|
||||
request,
|
||||
});
|
||||
const user = await getUser(id);
|
||||
if (!user) {
|
||||
return Response.json({ error: t("admin.users.create.errors.unexpectedCreateError") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [email, setEmail] = useState<string>("");
|
||||
const [password, setPassword] = useState<string>("");
|
||||
const [firstName, setFirstName] = useState<string>("");
|
||||
const [lastName, setLastName] = useState<string>("");
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="new-user" hidden readOnly />
|
||||
{selectedRoles?.map((role) => {
|
||||
return (
|
||||
<input
|
||||
key={role}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputText autoFocus type="email" name="email" title={t("models.user.email")} value={email} setValue={setEmail} required />
|
||||
|
||||
<InputText type="password" name="password" title={t("account.shared.password")} value={password} setValue={setPassword} required />
|
||||
|
||||
<InputText name="firstName" title={t("models.user.firstName")} value={firstName} setValue={setFirstName} required />
|
||||
|
||||
<InputText name="lastName" title={t("models.user.lastName")} value={lastName} setValue={setLastName} />
|
||||
|
||||
<div>
|
||||
<label className="mb-1 flex justify-between space-x-2 truncate text-xs font-medium">{t("models.role.plural")}</label>
|
||||
<div className="border-border bg-background divide-border divide-y rounded-md border px-2 py-1">
|
||||
{data.adminRoles?.map((role) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={role.name}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
export default function LegacyAdminUserCreationRedirect() {
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { Outlet } from "react-router";
|
||||
|
||||
export default function LegacyAdminUsersLayout() {
|
||||
return <Outlet />;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import { redirectLegacyAdminRoute } from "~/utils/navigation/legacyAdminRouteRedirect.server";
|
||||
|
||||
function canonicalPath(id: string | undefined) {
|
||||
return `settings/admin-users/${encodeURIComponent(id ?? "")}`;
|
||||
}
|
||||
|
||||
export const loader = ({ request, params }: LoaderFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, canonicalPath(params.id));
|
||||
|
||||
export const action = ({ request, params }: ActionFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, canonicalPath(params.id));
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import { redirectLegacyAdminRoute } from "~/utils/navigation/legacyAdminRouteRedirect.server";
|
||||
|
||||
export const loader = ({ request }: LoaderFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "settings/admin-users");
|
||||
|
||||
export const action = ({ request }: ActionFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "settings/admin-users");
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import { redirectLegacyAdminRoute } from "~/utils/navigation/legacyAdminRouteRedirect.server";
|
||||
|
||||
export const loader = ({ request }: LoaderFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "settings/admin-roles");
|
||||
|
||||
export const action = ({ request }: ActionFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "settings/admin-roles");
|
||||
@@ -1,6 +1,8 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
@@ -15,4 +17,12 @@ export const loader = async (_: LoaderFunctionArgs) => {
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => <Outlet />;
|
||||
export default function AdminApiShell() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex w-full flex-col">
|
||||
<AdminPageHeader title={t("admin.apiAdmin.title")} description={t("admin.apiAdmin.description")} />
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { buildApiAdminVM } from "@hivegrid/view-models";
|
||||
import { Link, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getApiAdminSnapshot } from "~/services/admin/api-admin.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { apiTabs } from "./index";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildApiAdminVM>;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const { t } = await getTranslations(request);
|
||||
return {
|
||||
title: `${t("admin.apiAdmin.clients.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildApiAdminVM(await getApiAdminSnapshot({ platformLeadVisibility: null })),
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
export default function ApiClientsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const rows = data.vm.status === "ready" ? data.vm.data.consumers : [];
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.apiAdmin.clients.title")} tabs={apiTabs(t)} fullWidth>
|
||||
<div className="overflow-hidden rounded-md border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/40 text-muted-foreground text-xs uppercase">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left">{t("models.tenant.object")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.apiAdmin.consumers.keys")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.apiAdmin.consumers.activeKeys")}</th>
|
||||
<th className="px-3 py-2 text-left">{t("admin.apiAdmin.consumers.lastKey")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-muted-foreground px-3 py-6 text-center">
|
||||
{t("admin.apiAdmin.clients.empty")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
rows.map((row) => (
|
||||
<tr key={row.id} className="border-border hover:bg-muted/30 border-t">
|
||||
<td className="px-3 py-2">
|
||||
<Link className="text-primary font-medium hover:underline" to={adminPath(`accounts/${row.id}`, { mode: "host-aware" })}>
|
||||
{row.name}
|
||||
</Link>
|
||||
<div className="text-muted-foreground text-xs">/{row.slug}</div>
|
||||
</td>
|
||||
<td className="px-3 py-2">{format.number(row.keyCount)}</td>
|
||||
<td className="px-3 py-2">{format.number(row.activeKeyCount)}</td>
|
||||
<td className="text-muted-foreground px-3 py-2">{row.lastKeyCreatedAt ? format.dateTime(row.lastKeyCreatedAt) : t("shared.notSet")}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { buildApiAdminVM } from "@hivegrid/view-models";
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getApiAdminSnapshot } from "~/services/admin/api-admin.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { apiTabs } from "./index";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildApiAdminVM>;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const { t } = await getTranslations(request);
|
||||
return {
|
||||
title: `${t("admin.apiAdmin.inbound.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildApiAdminVM(await getApiAdminSnapshot({ platformLeadVisibility: null })),
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
export default function ApiInboundRegistrationsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const ready = data.vm.status === "ready" ? data.vm.data.inbound : null;
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.apiAdmin.inbound.title")} tabs={apiTabs(t)} fullWidth>
|
||||
<div className="grid gap-4">
|
||||
<div className="rounded-md border">
|
||||
<div className="border-border border-b p-4">
|
||||
<div className="font-medium">{t("admin.apiAdmin.inbound.registrationsTitle")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.apiAdmin.inbound.registrationsDescription")}</div>
|
||||
</div>
|
||||
<div className="divide-y">
|
||||
{!ready || ready.recentRegistrations.length === 0 ? (
|
||||
<div className="text-muted-foreground p-4 text-sm">{t("admin.apiAdmin.inbound.emptyRegistrations")}</div>
|
||||
) : (
|
||||
ready.recentRegistrations.map((registration) => (
|
||||
<div key={registration.id} className="flex items-start justify-between gap-3 p-4 text-sm">
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium">{registration.email}</div>
|
||||
<div className="text-muted-foreground mt-1 truncate">{registration.company ?? t("shared.notSet")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-xs">{format.dateTime(registration.createdAt)}</div>
|
||||
</div>
|
||||
<Badge color={registration.createdTenantId ? "green" : "yellow"} withColorDot>
|
||||
{registration.createdTenantId ? t("admin.apiAdmin.inbound.converted") : t("admin.apiAdmin.inbound.pending")}
|
||||
</Badge>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -1,74 +1,218 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { Fragment } from "react";
|
||||
import { buildApiAdminVM, type ApiAdminMetricInput, type ApiAdminData } from "@hivegrid/view-models";
|
||||
import { FeatherActivity, FeatherArrowRight, FeatherKey, FeatherRadioTower, FeatherShieldAlert, FeatherUsers } from "@subframe/core";
|
||||
import type React from "react";
|
||||
import { Link, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ApiKeyLogsSummary from "~/modules/api/components/ApiKeyLogsSummary";
|
||||
import { ApiCallSummaryDto } from "~/modules/api/dtos/ApiCallSummaryDto";
|
||||
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getApiAdminSnapshot } from "~/services/admin/api-admin.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
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 { StatsCard } from "~/ui/components/StatsCard";
|
||||
import { Table } from "~/ui/components/Table";
|
||||
|
||||
type LoaderData =
|
||||
| { error: string }
|
||||
| {
|
||||
items: ApiCallSummaryDto[];
|
||||
allTenants: { id: string; name: string; slug: string }[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
try {
|
||||
const { items, allTenants, filterableProperties } = await ApiKeyLogService.getSummary({ request, params });
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
allTenants,
|
||||
filterableProperties,
|
||||
};
|
||||
return data;
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildApiAdminVM>;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const snapshot = await getApiAdminSnapshot({ platformLeadVisibility: null });
|
||||
return {
|
||||
title: `${t("admin.apiAdmin.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildApiAdminVM(snapshot),
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
export default function AdminApiIndexRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
{"error" in data ? (
|
||||
<ErrorBanner title={t(data.error)}>
|
||||
<Link to="." className="underline">
|
||||
{t("shared.clickHereToTryAgain")}
|
||||
</Link>
|
||||
</ErrorBanner>
|
||||
) : (
|
||||
<Fragment>
|
||||
<ApiKeyLogsSummary data={data} />
|
||||
</Fragment>
|
||||
)}
|
||||
<EditPageLayout title={t("shared.overview")} tabs={apiTabs(t)} fullWidth>
|
||||
{data.vm.status === "ready" ? <ApiAdminPage data={data.vm.data} /> : <EmptyApiAdmin />}
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function apiTabs(t: (key: string) => string) {
|
||||
return [
|
||||
{ name: t("shared.overview"), routePath: adminPath("api", { mode: "host-aware" }) },
|
||||
{ name: t("models.apiCall.plural"), routePath: adminPath("api/logs", { mode: "host-aware" }) },
|
||||
{ name: t("models.apiKey.plural"), routePath: adminPath("api/keys", { mode: "host-aware" }) },
|
||||
{ name: t("admin.apiAdmin.tabs.clients"), routePath: adminPath("api/clients", { mode: "host-aware" }) },
|
||||
{ name: t("admin.apiAdmin.tabs.inbound"), routePath: adminPath("api/inbound-registrations", { mode: "host-aware" }) },
|
||||
];
|
||||
}
|
||||
|
||||
function ApiAdminPage({ data }: { data: ApiAdminData }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col items-start gap-4">
|
||||
<Card variant="neutral">
|
||||
<div className="flex w-full flex-wrap items-center justify-between gap-3">
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t("admin.apiAdmin.publicApiHint")}</span>
|
||||
{data.hasInboundAttention ? (
|
||||
<BadgeFeedback farbe="subtle-warning">{t("admin.apiAdmin.inboundAttention")}</BadgeFeedback>
|
||||
) : (
|
||||
<BadgeFeedback farbe="subtle-positive">{t("admin.apiAdmin.inboundHealthy")}</BadgeFeedback>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<div className="mobile:grid-cols-1 grid w-full gap-4 md:grid-cols-2 xl:grid-cols-5">
|
||||
{data.metrics.map((metric) => (
|
||||
<MetricCard key={metric.id} metric={metric} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mobile:grid-cols-1 grid w-full gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]">
|
||||
<Card>
|
||||
<div className="flex w-full items-start justify-between gap-4">
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("admin.apiAdmin.consumers.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("admin.apiAdmin.consumers.description")}
|
||||
</span>
|
||||
</div>
|
||||
<Link to={adminPath("api/clients", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("shared.viewAll")}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<Table
|
||||
header={
|
||||
<Table.HeaderRow>
|
||||
<Table.HeaderCell>{t("models.tenant.object")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("admin.apiAdmin.consumers.keys")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("admin.apiAdmin.consumers.activeKeys")}</Table.HeaderCell>
|
||||
<Table.HeaderCell>{t("admin.apiAdmin.consumers.lastKey")}</Table.HeaderCell>
|
||||
</Table.HeaderRow>
|
||||
}
|
||||
>
|
||||
{data.consumers.slice(0, 8).map((consumer) => (
|
||||
<Table.Row key={consumer.id}>
|
||||
<Table.Cell>
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<Link
|
||||
className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate hover:underline"
|
||||
to={adminPath(`accounts/${consumer.id}`, { mode: "host-aware" })}
|
||||
>
|
||||
{consumer.name}
|
||||
</Link>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">/{consumer.slug}</span>
|
||||
</div>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-primary">{format.number(consumer.keyCount)}</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-primary">
|
||||
{format.number(consumer.activeKeyCount)}
|
||||
</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{consumer.lastKeyCreatedAt ? format.dateTime(consumer.lastKeyCreatedAt) : t("shared.notSet")}
|
||||
</span>
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
))}
|
||||
</Table>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<div className="flex w-full items-start justify-between gap-4">
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("admin.apiAdmin.inbound.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("admin.apiAdmin.inbound.description")}
|
||||
</span>
|
||||
</div>
|
||||
<Link to={adminPath("api/inbound-registrations", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("shared.viewAll")}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="grid w-full grid-cols-3 gap-2">
|
||||
<MiniStat label={t("admin.apiAdmin.inbound.pending")} value={data.inbound.registrationsPending} />
|
||||
<MiniStat label={t("admin.apiAdmin.inbound.newLeads")} value={data.inbound.leadsNew} />
|
||||
<MiniStat label={t("admin.apiAdmin.inbound.qualified")} value={data.inbound.leadsQualified} />
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
{data.inbound.recentLeads.slice(0, 5).map((lead) => (
|
||||
<Link
|
||||
key={lead.id}
|
||||
to={adminPath(`leads/${lead.id}`, { mode: "host-aware" })}
|
||||
className="border-border-default bg-surface-neutral-primary hover:bg-surface-neutral-secondary/60 flex w-full flex-col items-start rounded-md border border-solid px-4 py-3 transition-colors"
|
||||
>
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate">
|
||||
{lead.email ?? lead.company ?? t("shared.notSet")}
|
||||
</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary w-full truncate">
|
||||
{[lead.company, lead.source, t(`admin.platformLeads.status.${lead.status}`)].filter(Boolean).join(" · ")}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCard({ metric }: { metric: ApiAdminMetricInput }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useLocaleFormatters();
|
||||
return (
|
||||
<StatsCard
|
||||
label={t(metric.labelKey)}
|
||||
value={format.number(metric.value)}
|
||||
trend={metric.tone === "success" ? "positive" : metric.tone === "danger" || metric.tone === "warning" ? "negative" : "neutral"}
|
||||
percentage=""
|
||||
comparisonText={t(metric.detailKey)}
|
||||
icon={metricIcon(metric.id)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MiniStat({ label, value }: { label: string; value: number }) {
|
||||
const format = useLocaleFormatters();
|
||||
return (
|
||||
<div className="border-border-default bg-surface-neutral-primary flex flex-col items-center rounded-md border border-solid px-3 py-3">
|
||||
<span className="text-subtitle-0 font-subtitle-0 text-text-neutral-primary">{format.number(value)}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary text-center">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyApiAdmin() {
|
||||
const { t } = useTranslation();
|
||||
return <EmptyState outlined title={t("admin.apiAdmin.empty.title")} body={t("admin.apiAdmin.empty.body")} />;
|
||||
}
|
||||
|
||||
function metricIcon(id: string): React.ReactNode {
|
||||
if (id === "keys") return <FeatherKey />;
|
||||
if (id === "activeKeys") return <FeatherShieldAlert />;
|
||||
if (id === "expiredKeys") return <FeatherActivity />;
|
||||
if (id === "failedLogs") return <FeatherRadioTower />;
|
||||
return <FeatherUsers />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { RedactedApiKeyWithDetails, getAllApiKeys } from "~/utils/db/apiKeys.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { apiTabs } from "./index";
|
||||
|
||||
type LoaderData = {
|
||||
apiKeys: RedactedApiKeyWithDetails[];
|
||||
@@ -27,28 +27,8 @@ export default function AdminApiKeysRoute() {
|
||||
const adminData = useAdminData();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
title={t("models.apiKey.plural")}
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ApiKeysTable
|
||||
canCreate={getUserHasPermission(adminData, "admin.apiKeys.create")}
|
||||
items={data.apiKeys}
|
||||
withTenant={true}
|
||||
/>
|
||||
<EditPageLayout title={t("models.apiKey.plural")} tabs={apiTabs(t)} fullWidth>
|
||||
<ApiKeysTable canCreate={getUserHasPermission(adminData, "admin.apiKeys.create")} items={data.apiKeys} withTenant={true} />
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
</>
|
||||
|
||||
+57
-49
@@ -1,4 +1,5 @@
|
||||
import { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import type { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
|
||||
@@ -7,7 +8,7 @@ import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { RedactedApiKeyWithDetails, adminGetApiKeyById, deleteApiKey, getApiKeys, updateApiKey } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
@@ -18,7 +19,7 @@ import { ApiKeyUpdatedDto } from "~/modules/events/dtos/ApiKeyUpdatedDto";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
tenants: Tenant[];
|
||||
tenants: Pick<Tenant, "id" | "name">[];
|
||||
item: RedactedApiKeyWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
@@ -27,7 +28,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
if (!item) {
|
||||
return redirect(adminPath("api", { mode: "host-aware" }));
|
||||
}
|
||||
const tenants = await adminGetAllTenants();
|
||||
const tenants = await adminGetAllTenantsIdsAndNames();
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
tenants,
|
||||
@@ -60,58 +61,65 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
expirationDate = new Date(expires);
|
||||
}
|
||||
const tenantId = form.get("tenant-id")?.toString() ?? "";
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const existingAlias = await getApiKeys(tenantId);
|
||||
if (existingAlias.filter((f) => f.id !== existing.id && f.alias === alias).length > 0) {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
if (tenantId !== existing.tenantId) {
|
||||
return badRequest({ error: t("models.apiKey.errors.tenantChangeNotAllowed") });
|
||||
}
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const active = Boolean(form.get("active"));
|
||||
await updateApiKey(params.id ?? "", {
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
await runWithRlsContext({ tenantId }, async () => {
|
||||
const existingAlias = await getApiKeys(tenantId);
|
||||
if (existingAlias.some((item) => item.id !== existing.id && item.alias === alias)) {
|
||||
throw badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
await updateApiKey(params.id ?? "", {
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
new: {
|
||||
alias: alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
},
|
||||
old: {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
});
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
new: {
|
||||
alias: alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
},
|
||||
old: {
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.saved")}`);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
await runWithRlsContext({ tenantId: existing.tenantId }, async () => {
|
||||
await deleteApiKey(params.id ?? "", existing.tenantId);
|
||||
await createAdminLog(request, "admin.apiKeys.deleted", "");
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.deleted",
|
||||
tenantId: existing.tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
});
|
||||
return redirect(adminPath(`api/keys`, { mode: "host-aware" }));
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
await deleteApiKey(params.id ?? "", existing.tenantId);
|
||||
await createAdminLog(request, "admin.apiKeys.deleted", "");
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.deleted",
|
||||
tenantId: existing.tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
return redirect(adminPath(`api/keys`, { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.deleted")}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ adminGetAllTenantsIdsAndNames: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/utils/db/apiKeys.db.server", () => ({
|
||||
adminGetApiKeyById: vi.fn(),
|
||||
createApiKey: vi.fn(),
|
||||
deleteApiKey: vi.fn(),
|
||||
getApiKeyByAlias: vi.fn(),
|
||||
getApiKeys: vi.fn(),
|
||||
updateApiKey: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ createAdminLog: vi.fn() }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ adminPath: (path = "") => `/admin/${path}` }));
|
||||
vi.mock("~/components/core/apiKeys/ApiKeyCreatedModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/apiKeys/ApiKeyForm", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/OpenModal", () => ({ default: ({ children }: { children: React.ReactNode }) => children }));
|
||||
vi.mock("~/utils/data/useAdminData", () => ({ useAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: () => true }));
|
||||
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminGetApiKeyById, createApiKey, deleteApiKey, getApiKeyByAlias, getApiKeys, updateApiKey } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { action as createAction } from "./new";
|
||||
import { action as editAction } from "./$id";
|
||||
|
||||
const operator = { id: "operator_1", email: "operator@example.test" };
|
||||
const tenants = [
|
||||
{ id: "tenant_a", name: "Tenant A", slug: "tenant-a" },
|
||||
{ id: "tenant_b", name: "Tenant B", slug: "tenant-b" },
|
||||
];
|
||||
const existing = { id: "key_a", tenantId: "tenant_a", alias: "Primary", expires: null, active: true };
|
||||
|
||||
function requestFor(path: string, values: Record<string, string>) {
|
||||
return new Request(`https://admin.example.test${path}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(values),
|
||||
});
|
||||
}
|
||||
|
||||
function callCreate(values: Record<string, string>) {
|
||||
return runWithRlsContext({ userId: operator.id }, () =>
|
||||
createAction({
|
||||
request: requestFor("/api/keys/new", values),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/api/keys/new",
|
||||
} as ActionFunctionArgs)
|
||||
) as Promise<Response>;
|
||||
}
|
||||
|
||||
function callEdit(values: Record<string, string>) {
|
||||
return runWithRlsContext({ userId: operator.id }, () =>
|
||||
editAction({
|
||||
request: requestFor("/api/keys/key_a", values),
|
||||
params: { id: "key_a" },
|
||||
context: {},
|
||||
unstable_pattern: "admin/api/keys/$id",
|
||||
} as ActionFunctionArgs)
|
||||
) as Promise<Response>;
|
||||
}
|
||||
|
||||
describe("admin API key route RLS contexts", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: operator.id } as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUser).mockResolvedValue(operator as never);
|
||||
vi.mocked(adminGetAllTenantsIdsAndNames).mockResolvedValue(tenants);
|
||||
vi.mocked(adminGetApiKeyById).mockResolvedValue(existing as never);
|
||||
vi.mocked(getApiKeyByAlias).mockResolvedValue(null as never);
|
||||
vi.mocked(getApiKeys).mockResolvedValue([existing] as never);
|
||||
vi.mocked(createApiKey).mockResolvedValue({ ...existing, id: "key_b", tenantId: "tenant_b" } as never);
|
||||
vi.mocked(updateApiKey).mockResolvedValue(existing as never);
|
||||
vi.mocked(deleteApiKey).mockResolvedValue(existing as never);
|
||||
vi.mocked(EventsService.create).mockResolvedValue(undefined as never);
|
||||
vi.mocked(createAdminLog).mockResolvedValue({} as never);
|
||||
});
|
||||
|
||||
it("creates a key and its event only inside the selected tenant context", async () => {
|
||||
vi.mocked(getApiKeyByAlias).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
return null;
|
||||
});
|
||||
vi.mocked(createApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
return { ...existing, id: "key_b", tenantId: "tenant_b" } as never;
|
||||
});
|
||||
vi.mocked(EventsService.create).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_b" });
|
||||
});
|
||||
|
||||
const response = await callCreate({ action: "create", "tenant-id": "tenant_b", alias: "Primary", active: "on" });
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.created")}`);
|
||||
expect(createApiKey).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_b", createdByUserId: operator.id }));
|
||||
});
|
||||
|
||||
it("rejects a forged tenant before probing aliases or creating a key", async () => {
|
||||
const response = await callCreate({ action: "create", "tenant-id": "tenant_forged", alias: "Primary" });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(getApiKeyByAlias).not.toHaveBeenCalled();
|
||||
expect(createApiKey).not.toHaveBeenCalled();
|
||||
expect(EventsService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects moving an existing key to another tenant", async () => {
|
||||
const response = await callEdit({ action: "edit", "tenant-id": "tenant_b", alias: "Moved", active: "on" });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: "translated:models.apiKey.errors.tenantChangeNotAllowed" });
|
||||
expect(getApiKeys).not.toHaveBeenCalled();
|
||||
expect(updateApiKey).not.toHaveBeenCalled();
|
||||
expect(EventsService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates and deletes only inside the key's owning tenant context", async () => {
|
||||
vi.mocked(updateApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_a" });
|
||||
return existing as never;
|
||||
});
|
||||
vi.mocked(deleteApiKey).mockImplementation(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ userId: operator.id, tenantId: "tenant_a" });
|
||||
return existing as never;
|
||||
});
|
||||
|
||||
const editResponse = await callEdit({ action: "edit", "tenant-id": "tenant_a", alias: "Updated", active: "on" });
|
||||
const deleteResponse = await callEdit({ action: "delete" });
|
||||
|
||||
expect(editResponse.status).toBe(302);
|
||||
expect(deleteResponse.status).toBe(302);
|
||||
expect(editResponse.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.saved")}`);
|
||||
expect(deleteResponse.headers.get("Location")).toContain(`toast=${encodeURIComponent("models.apiKey.toast.deleted")}`);
|
||||
expect(updateApiKey).toHaveBeenCalledWith("key_a", expect.objectContaining({ tenantId: "tenant_a", alias: "Updated" }));
|
||||
expect(deleteApiKey).toHaveBeenCalledWith("key_a", "tenant_a");
|
||||
});
|
||||
});
|
||||
+35
-28
@@ -1,4 +1,5 @@
|
||||
import { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import type { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData, useNavigate } from "react-router";
|
||||
import ApiKeyCreatedModal from "~/components/core/apiKeys/ApiKeyCreatedModal";
|
||||
@@ -7,7 +8,7 @@ import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createApiKey, getApiKeyByAlias } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
@@ -16,11 +17,11 @@ import { ApiKeyCreatedDto } from "~/modules/events/dtos/ApiKeyCreatedDto";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
tenants: Tenant[];
|
||||
tenants: Pick<Tenant, "id" | "name">[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.create");
|
||||
const tenants = await adminGetAllTenants();
|
||||
const tenants = await adminGetAllTenantsIdsAndNames();
|
||||
const data: LoaderData = {
|
||||
tenants,
|
||||
};
|
||||
@@ -35,7 +36,7 @@ type ActionData = {
|
||||
};
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
export const action: ActionFunction = async ({ request, params: _params }) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.create");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
@@ -52,34 +53,40 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
const tenantId = form.get("tenant-id")?.toString() ?? "";
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const existingAlias = await getApiKeyByAlias(tenantId, alias);
|
||||
if (existingAlias) {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
const tenantExists = (await adminGetAllTenantsIdsAndNames()).some((tenant) => tenant.id === tenantId);
|
||||
if (!tenantExists) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
const apiKey = await createApiKey({
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? "",
|
||||
data: {
|
||||
id: apiKey.id,
|
||||
alias: apiKey.alias,
|
||||
await runWithRlsContext({ tenantId }, async () => {
|
||||
const existingAlias = await getApiKeyByAlias(tenantId, alias);
|
||||
if (existingAlias) {
|
||||
throw badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const apiKey = await createApiKey({
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? "",
|
||||
data: {
|
||||
id: apiKey.id,
|
||||
alias: apiKey.alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
});
|
||||
});
|
||||
// return success({ apiKey });
|
||||
return redirect(adminPath("api/keys", { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("api/keys", { mode: "host-aware" })}?toast=${encodeURIComponent("models.apiKey.toast.created")}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
|
||||
import { ApiKeyLogDto } from "~/modules/api/dtos/ApiKeyLogDto";
|
||||
@@ -9,14 +8,16 @@ import ApiKeyLogsDetails from "~/modules/api/components/ApiKeyLogsDetails";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { apiTabs } from "./index";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
items: ApiKeyLogDto[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
type ActionData = { intent: "delete"; ok?: true; messageKey?: string; messageValues?: { count: number }; errorKey?: string };
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params, adminOnly: true });
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
@@ -32,39 +33,29 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params, adminOnly: true });
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("action") === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
const ids = (form.get("ids")?.toString().split(",") ?? []).map((x) => x.toString() ?? "");
|
||||
await ApiKeyLogService.adminDeleteMany(ids);
|
||||
return Response.json({ success: true });
|
||||
const result = await ApiKeyLogService.adminDeleteMany(ids);
|
||||
if (result.rejectedTenantlessIds.length > 0) {
|
||||
return Response.json({ intent: "delete", errorKey: "admin.apiAdmin.logs.tenantlessDeleteDenied" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
return Response.json({ intent: "delete", ok: true, messageKey: "admin.apiAdmin.logs.deleted", messageValues: { count: ids.length } } satisfies ActionData);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm"), success: false }, { status: 400 });
|
||||
return Response.json({ intent: "delete", errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
useSaveToast(actionData);
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<EditPageLayout title={t("models.apiCall.plural")} tabs={apiTabs(t)} fullWidth>
|
||||
<ApiKeyLogsDetails data={data} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
|
||||
+48
-43
@@ -3,9 +3,12 @@
|
||||
* import them without dragging in the route module's server-only deps
|
||||
* (PrismaClient, getDbClient, session secret env vars).
|
||||
*/
|
||||
import { computeAuditHash } from "@hivegrid/db/audit-hash";
|
||||
import { verifyAuditChain } from "@hivegrid/db/audit-hash";
|
||||
import { auditChainKey, type AuditVerificationContext } from "@hivegrid/db/audit-chain-checkpoint.server";
|
||||
import { neutralizeSpreadsheetFormula } from "@hivegrid/foundation/spreadsheet-safety";
|
||||
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const FILTER_ALL = "__all__";
|
||||
|
||||
export const AUDIT_EXPORT_MAX_ROWS = 50_000;
|
||||
|
||||
@@ -69,6 +72,16 @@ export type AuditIntegritySummary = {
|
||||
reason: string | null;
|
||||
};
|
||||
|
||||
export function stripAuditExportFilterSentinels(url: URL): URL {
|
||||
const cleaned = new URL(url.toString());
|
||||
for (const key of Array.from(cleaned.searchParams.keys())) {
|
||||
const values = cleaned.searchParams.getAll(key).filter((value) => value.trim() !== FILTER_ALL);
|
||||
cleaned.searchParams.delete(key);
|
||||
for (const value of values) cleaned.searchParams.append(key, value);
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
export function parseAuditExportFilters(url: URL): AuditExportFilters {
|
||||
return {
|
||||
from: parseIsoDate(url.searchParams.get("from")),
|
||||
@@ -105,7 +118,19 @@ export function buildAuditExportWhere(filters: AuditExportFilters): Record<strin
|
||||
return where;
|
||||
}
|
||||
|
||||
export function computeAuditIntegritySummary(rows: ReadonlyArray<AuditExportRow>): AuditIntegritySummary {
|
||||
export function hasAuditExportPrefixFilters(filters: AuditExportFilters): boolean {
|
||||
return Boolean(
|
||||
filters.from
|
||||
|| filters.actorType
|
||||
|| filters.outcome
|
||||
|| filters.regulatoryScope.length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
export function computeAuditIntegritySummary(
|
||||
rows: ReadonlyArray<AuditExportRow>,
|
||||
context?: AuditVerificationContext,
|
||||
): AuditIntegritySummary {
|
||||
const chains = new Map<string, AuditExportRow[]>();
|
||||
for (const row of rows) {
|
||||
const key = row.tenantId ?? "__platform__";
|
||||
@@ -114,44 +139,24 @@ export function computeAuditIntegritySummary(rows: ReadonlyArray<AuditExportRow>
|
||||
chains.set(key, list);
|
||||
}
|
||||
let inspected = 0;
|
||||
for (const [, list] of chains) {
|
||||
list.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
||||
let lastHash: string | null = null;
|
||||
for (const row of list) {
|
||||
if (row.eventHash === null) {
|
||||
lastHash = null;
|
||||
continue;
|
||||
}
|
||||
inspected += 1;
|
||||
if (row.previousHash !== lastHash) {
|
||||
return { ok: false, inspected, firstBreakId: row.id, reason: "previous-hash-mismatch" };
|
||||
}
|
||||
const recomputed = computeAuditHash({
|
||||
previousHash: row.previousHash,
|
||||
payload: {
|
||||
id: "",
|
||||
createdAt: "",
|
||||
tenantId: row.tenantId,
|
||||
actorType: row.actorType,
|
||||
actorId: row.actorId,
|
||||
actorEmail: row.actorEmail,
|
||||
actorIp: row.actorIp,
|
||||
actorUserAgent: row.actorUserAgent,
|
||||
action: row.action,
|
||||
targetType: row.targetType,
|
||||
targetId: row.targetId,
|
||||
requestId: row.requestId,
|
||||
sourceModule: row.sourceModule,
|
||||
outcome: row.outcome,
|
||||
dataSensitivity: row.dataSensitivity,
|
||||
regulatoryScope: row.regulatoryScope,
|
||||
metadata: row.metadata,
|
||||
},
|
||||
});
|
||||
if (recomputed !== row.eventHash) {
|
||||
return { ok: false, inspected, firstBreakId: row.id, reason: "hash-mismatch" };
|
||||
}
|
||||
lastHash = row.eventHash;
|
||||
for (const [key, list] of chains) {
|
||||
list.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id));
|
||||
const chainKey = auditChainKey(key === "__platform__" ? null : key);
|
||||
if (context?.invalidCheckpointChains.has(chainKey)) {
|
||||
return { ok: false, inspected, firstBreakId: list[0]?.id ?? null, reason: "checkpoint-authentication-failed" };
|
||||
}
|
||||
const result = verifyAuditChain(
|
||||
list.map((row) => ({ ...row, createdAt: row.createdAt.toISOString() })),
|
||||
{ initialPreviousHash: context?.initialPreviousHashes.get(chainKey) ?? null },
|
||||
);
|
||||
inspected += result.inspected;
|
||||
if (!result.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
inspected,
|
||||
firstBreakId: result.firstBreak?.eventId ?? null,
|
||||
reason: result.firstBreak?.reason ?? "unknown",
|
||||
};
|
||||
}
|
||||
}
|
||||
return { ok: true, inspected, firstBreakId: null, reason: null };
|
||||
@@ -196,7 +201,7 @@ export function csvCell(value: unknown): string {
|
||||
if (Array.isArray(value)) return csvCell(value.join("|"));
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
if (typeof value === "object") return csvCell(JSON.stringify(value));
|
||||
const s = String(value);
|
||||
if (/[",\n\r]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
|
||||
return s;
|
||||
const safeValue = neutralizeSpreadsheetFormula(String(value));
|
||||
if (/[",\n\r]/.test(safeValue)) return `"${safeValue.replace(/"/g, '""')}"`;
|
||||
return safeValue;
|
||||
}
|
||||
+12
@@ -7,6 +7,7 @@ import {
|
||||
buildAuditExportWhere,
|
||||
computeAuditIntegritySummary,
|
||||
csvCell,
|
||||
hasAuditExportPrefixFilters,
|
||||
parseAuditExportFilters,
|
||||
renderAuditExportCsv,
|
||||
type AuditExportRow,
|
||||
@@ -35,6 +36,13 @@ describe("admin audit-export filters", () => {
|
||||
it("AUDIT_EXPORT_MAX_ROWS is set", () => {
|
||||
expect(AUDIT_EXPORT_MAX_ROWS).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("only treats filters that remove the chain prefix as partial verification", () => {
|
||||
const base = { from: null, to: null, regulatoryScope: [], actorType: null, outcome: null, tenantId: null };
|
||||
expect(hasAuditExportPrefixFilters({ ...base, to: new Date("2026-01-01T00:00:00.000Z") })).toBe(false);
|
||||
expect(hasAuditExportPrefixFilters({ ...base, from: new Date("2025-01-01T00:00:00.000Z") })).toBe(true);
|
||||
expect(hasAuditExportPrefixFilters({ ...base, actorType: "admin" })).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin audit-export csv rendering", () => {
|
||||
@@ -48,6 +56,10 @@ describe("admin audit-export csv rendering", () => {
|
||||
expect(csvCell({ a: 1 })).toBe('"{""a"":1}"');
|
||||
});
|
||||
|
||||
it.each(["=1+1", "+cmd", "-2+3", "@SUM(A1:A2)", " =1+1", "\tformula"])("neutralizes formula value %j", (value) => {
|
||||
expect(csvCell(value)).toBe(`'${value}`);
|
||||
});
|
||||
|
||||
it("renders integrity header line and column row", () => {
|
||||
const csv = renderAuditExportCsv([], { ok: true, inspected: 0, firstBreakId: null, reason: null });
|
||||
const lines = csv.trim().split("\n");
|
||||
|
||||
+16
-17
@@ -11,21 +11,23 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData } from "react-router";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { loadAuditVerificationContext } from "@hivegrid/db/audit-chain-checkpoint.server";
|
||||
import { buildAuditExportVM, toAuditExportResultVM, type AuditExportVM } from "@hivegrid/view-models";
|
||||
import { AuditExportPage } from "~/components/screens/audit/AuditExportPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
AUDIT_EXPORT_MAX_ROWS,
|
||||
buildAuditExportWhere,
|
||||
computeAuditIntegritySummary,
|
||||
hasAuditExportPrefixFilters,
|
||||
parseAuditExportFilters,
|
||||
renderAuditExportCsv,
|
||||
stripAuditExportFilterSentinels,
|
||||
type AuditExportRow,
|
||||
} from "./audit-export.helpers.server";
|
||||
import { buildAuditPdfLabels, renderAuditExportPdfResponse } from "~/utils/audit/pdfRender";
|
||||
import {
|
||||
AuditExportPurposeRequiredError,
|
||||
AuditExportStorageUnavailableError,
|
||||
@@ -54,18 +56,8 @@ function filtersFromForm(form: FormData): URL {
|
||||
return new URL(`https://audit.local/?${params.toString()}`);
|
||||
}
|
||||
|
||||
function stripFilterSentinels(url: URL): URL {
|
||||
const cleaned = new URL(url.toString());
|
||||
for (const key of Array.from(cleaned.searchParams.keys())) {
|
||||
const values = cleaned.searchParams.getAll(key).filter((value) => value.trim() !== FILTER_ALL);
|
||||
cleaned.searchParams.delete(key);
|
||||
for (const value of values) cleaned.searchParams.append(key, value);
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs): Promise<ActionData> => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
await requireAdminIdentityPermission(request, "admin_identity.audit.export");
|
||||
const [userInfo, form] = await Promise.all([getUserInfo(request), request.formData()]);
|
||||
const filters = parseAuditExportFilters(filtersFromForm(form));
|
||||
try {
|
||||
@@ -90,9 +82,9 @@ type LoaderData = {
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
await requireAdminIdentityPermission(request, "admin_identity.audit.export");
|
||||
const { t } = await getTranslations(request);
|
||||
const url = stripFilterSentinels(new URL(request.url));
|
||||
const url = stripAuditExportFilterSentinels(new URL(request.url));
|
||||
|
||||
if (url.searchParams.get("export") === "csv") {
|
||||
return streamAdminAuditExport(url);
|
||||
@@ -124,7 +116,10 @@ async function streamAdminAuditExport(url: URL): Promise<Response> {
|
||||
take: AUDIT_EXPORT_MAX_ROWS,
|
||||
})) as unknown as AuditExportRow[];
|
||||
|
||||
const integrity = computeAuditIntegritySummary(rows);
|
||||
const verification = await loadAuditVerificationContext(db as never, rows, {
|
||||
allowPartialPrefix: hasAuditExportPrefixFilters(filters),
|
||||
});
|
||||
const integrity = computeAuditIntegritySummary(rows, verification);
|
||||
const csv = renderAuditExportCsv(rows, integrity);
|
||||
return new Response(csv, {
|
||||
headers: {
|
||||
@@ -136,6 +131,7 @@ async function streamAdminAuditExport(url: URL): Promise<Response> {
|
||||
}
|
||||
|
||||
async function streamAdminAuditPdfExport(url: URL, t: Awaited<ReturnType<typeof getTranslations>>["t"]): Promise<Response> {
|
||||
const { buildAuditPdfLabels, renderAuditExportPdfResponse } = await import("~/utils/audit/pdfRender");
|
||||
const filters = parseAuditExportFilters(url);
|
||||
const db = getDbClient();
|
||||
const rows = (await db.auditEvent.findMany({
|
||||
@@ -143,7 +139,10 @@ async function streamAdminAuditPdfExport(url: URL, t: Awaited<ReturnType<typeof
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: AUDIT_EXPORT_MAX_ROWS,
|
||||
})) as unknown as AuditExportRow[];
|
||||
const integrity = computeAuditIntegritySummary(rows);
|
||||
const verification = await loadAuditVerificationContext(db as never, rows, {
|
||||
allowPartialPrefix: hasAuditExportPrefixFilters(filters),
|
||||
});
|
||||
const integrity = computeAuditIntegritySummary(rows, verification);
|
||||
return renderAuditExportPdfResponse(
|
||||
{
|
||||
tenantId: filters.tenantId,
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./audit-trails-export";
|
||||
import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
vi.mock("@hivegrid/db/logs.server", () => ({
|
||||
getAdminAuditLogList: vi.fn(),
|
||||
serializeAdminAuditLogsCsv: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
const auditRows = [{ id: "log-1" }];
|
||||
|
||||
function callLoader(url: string) {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params: {}, context: {}, unstable_pattern: "admin/audit-trails-export" } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("admin audit-trails CSV export route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getAdminAuditLogList).mockResolvedValue({ rows: auditRows, total: 1, take: 500, skip: 0 } as never);
|
||||
vi.mocked(serializeAdminAuditLogsCsv).mockReturnValue("csv-body\n");
|
||||
});
|
||||
|
||||
it("exports CSV with the same admin filters and a capped export window", async () => {
|
||||
const response = await callLoader(
|
||||
"https://admin.example.test/audit-trails-export?q=login&action=auth&url=%2Flogin&tenantId=tenant-9&userId=user-2&createdAtFrom=2026-05-01&createdAtTo=2026-05-08&page=9&pageSize=5",
|
||||
);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]);
|
||||
expect(getAdminAuditLogList).toHaveBeenCalledWith({
|
||||
q: "login",
|
||||
action: "auth",
|
||||
url: "/login",
|
||||
tenantId: "tenant-9",
|
||||
userId: "user-2",
|
||||
createdAtFrom: "2026-05-01",
|
||||
createdAtTo: "2026-05-08",
|
||||
take: 500,
|
||||
skip: 0,
|
||||
});
|
||||
expect(serializeAdminAuditLogsCsv).toHaveBeenCalledWith(auditRows);
|
||||
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
|
||||
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="admin-audit-logs.csv"');
|
||||
expect(await response.text()).toBe("csv-body\n");
|
||||
});
|
||||
|
||||
it("rejects CSV reads without permission before helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(callLoader("https://admin.example.test/audit-trails-export")).rejects.toBe(rejection);
|
||||
|
||||
expect(getAdminAuditLogList).not.toHaveBeenCalled();
|
||||
expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
// CSV export for the admin audit log. Resource route on purpose: raw Response
|
||||
// bodies only pass through routes without a component.
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { CSV_EXPORT_TAKE, getAdminAuditLogFiltersFromUrl } from "./audit-trails.helpers.server";
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const auditLogFilters = getAdminAuditLogFiltersFromUrl(urlSearchParams);
|
||||
const { rows } = await getAdminAuditLogList({ ...auditLogFilters, take: CSV_EXPORT_TAKE, skip: 0 });
|
||||
|
||||
return new Response(serializeAdminAuditLogsCsv(rows), {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": 'attachment; filename="admin-audit-logs.csv"',
|
||||
},
|
||||
});
|
||||
};
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
// Shared between the admin audit-trails list route and its CSV export
|
||||
// resource route (raw Response bodies only pass through component-less routes).
|
||||
import type { AdminAuditLogFilters } from "@hivegrid/db/logs.server";
|
||||
|
||||
export const CSV_EXPORT_TAKE = 500;
|
||||
|
||||
export function getAdminAuditLogFiltersFromUrl(urlSearchParams: URLSearchParams): AdminAuditLogFilters {
|
||||
return {
|
||||
q: urlSearchParams.get("q"),
|
||||
action: urlSearchParams.get("action"),
|
||||
url: urlSearchParams.get("url"),
|
||||
tenantId: urlSearchParams.get("tenantId"),
|
||||
userId: urlSearchParams.get("userId"),
|
||||
createdAtFrom: urlSearchParams.get("createdAtFrom"),
|
||||
createdAtTo: urlSearchParams.get("createdAtTo"),
|
||||
};
|
||||
}
|
||||
+1
-45
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loader } from "./audit-trails";
|
||||
import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import { getAdminAuditLogList } from "@hivegrid/db/logs.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
@@ -33,7 +33,6 @@ vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
|
||||
vi.mock("@hivegrid/db/logs.server", () => ({
|
||||
getAdminAuditLogList: vi.fn(),
|
||||
serializeAdminAuditLogsCsv: vi.fn(),
|
||||
}));
|
||||
|
||||
const auditRows = [
|
||||
@@ -71,7 +70,6 @@ describe("admin audit trails route", () => {
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(getAdminAuditLogList).mockResolvedValue({ rows: auditRows, total: 1, take: 25, skip: 25 } as never);
|
||||
vi.mocked(serializeAdminAuditLogsCsv).mockReturnValue("csv-body\n");
|
||||
});
|
||||
|
||||
it("checks permission before reading the filtered table data", async () => {
|
||||
@@ -99,31 +97,6 @@ describe("admin audit trails route", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("exports CSV with the same filters and a capped export window after permission passes", async () => {
|
||||
const response = (await callLoader(
|
||||
"https://admin.example.test/audit-trails?export=csv&q=login&action=auth&url=%2Flogin&tenantId=tenant-2&userId=user-2&createdAtFrom=bad-date&createdAtTo=2026-05-08",
|
||||
)) as Response;
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]);
|
||||
expect(getAdminAuditLogList).toHaveBeenCalledWith({
|
||||
q: "login",
|
||||
action: "auth",
|
||||
url: "/login",
|
||||
tenantId: "tenant-2",
|
||||
userId: "user-2",
|
||||
createdAtFrom: "bad-date",
|
||||
createdAtTo: "2026-05-08",
|
||||
take: 500,
|
||||
skip: 0,
|
||||
});
|
||||
expect(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(serializeAdminAuditLogsCsv).mock.invocationCallOrder[0]);
|
||||
expect(serializeAdminAuditLogsCsv).toHaveBeenCalledWith(auditRows);
|
||||
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
|
||||
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="admin-audit-logs.csv"');
|
||||
expect(await response.text()).toBe("csv-body\n");
|
||||
});
|
||||
|
||||
it("rejects table loads without permission before helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
@@ -136,22 +109,6 @@ describe("admin audit trails route", () => {
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view");
|
||||
expect(getAdminAuditLogList).not.toHaveBeenCalled();
|
||||
expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects CSV export without permission before helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(
|
||||
callLoader(
|
||||
"https://admin.example.test/audit-trails?export=csv&q=login&action=auth&url=%2Flogin&tenantId=tenant-2&userId=user-2&createdAtFrom=2026-05-01&createdAtTo=2026-05-08",
|
||||
),
|
||||
).rejects.toBe(rejection);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view");
|
||||
expect(getAdminAuditLogList).not.toHaveBeenCalled();
|
||||
expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not crash on malformed numeric and date filters", async () => {
|
||||
@@ -178,7 +135,6 @@ describe("admin audit trails route", () => {
|
||||
|
||||
expect(source).toContain('from "@hivegrid/db/logs.server"');
|
||||
expect(source).toContain("getAdminAuditLogList");
|
||||
expect(source).toContain("serializeAdminAuditLogsCsv");
|
||||
expect(source).not.toContain("getAllLogs");
|
||||
expect(source).not.toContain('from "~/utils/db/logs.db.server"');
|
||||
});
|
||||
|
||||
+15
-31
@@ -1,17 +1,16 @@
|
||||
import type { AdminAuditLogFilters, AdminAuditLogRow } from "@hivegrid/db/logs.server";
|
||||
import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import type { AdminAuditLogRow } from "@hivegrid/db/logs.server";
|
||||
import { getAdminAuditLogList } from "@hivegrid/db/logs.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import AdminAuditLogToolbar from "~/components/audit/AdminAuditLogToolbar";
|
||||
import LogsTable from "~/components/app/events/LogsTable";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
|
||||
const CSV_EXPORT_TAKE = 500;
|
||||
import { getAdminAuditLogFiltersFromUrl } from "./audit-trails.helpers.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
@@ -27,17 +26,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const filterableProperties = getAuditLogFilterableProperties();
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const auditLogFilters = getAuditLogFiltersFromUrl(urlSearchParams);
|
||||
|
||||
if (urlSearchParams.get("export") === "csv") {
|
||||
const { rows } = await getAdminAuditLogList({ ...auditLogFilters, take: CSV_EXPORT_TAKE, skip: 0 });
|
||||
return new Response(serializeAdminAuditLogsCsv(rows), {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": 'attachment; filename="admin-audit-logs.csv"',
|
||||
},
|
||||
});
|
||||
}
|
||||
const auditLogFilters = getAdminAuditLogFiltersFromUrl(urlSearchParams);
|
||||
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const pageSize = normalizePositiveInteger(currentPagination.pageSize, 10);
|
||||
@@ -93,18 +82,6 @@ function getAuditLogFilterableProperties(): FilterablePropertyDto[] {
|
||||
];
|
||||
}
|
||||
|
||||
function getAuditLogFiltersFromUrl(urlSearchParams: URLSearchParams): AdminAuditLogFilters {
|
||||
return {
|
||||
q: urlSearchParams.get("q"),
|
||||
action: urlSearchParams.get("action"),
|
||||
url: urlSearchParams.get("url"),
|
||||
tenantId: urlSearchParams.get("tenantId"),
|
||||
userId: urlSearchParams.get("userId"),
|
||||
createdAtFrom: urlSearchParams.get("createdAtFrom"),
|
||||
createdAtTo: urlSearchParams.get("createdAtTo"),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePositiveInteger(value: number | null | undefined, fallback: number): number {
|
||||
if (!Number.isFinite(value) || !value || value < 1) return fallback;
|
||||
return Math.trunc(value);
|
||||
@@ -117,8 +94,15 @@ export default function Events() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<IndexPageLayout title={t("models.log.plural")} buttons={<AdminAuditLogToolbar filters={data.filterableProperties} />}>
|
||||
<LogsTable withTenant={true} items={data.items} pagination={data.pagination} />
|
||||
</IndexPageLayout>
|
||||
<div className="flex w-full flex-col">
|
||||
<AdminPageHeader
|
||||
title={t("models.log.plural")}
|
||||
description={t("admin.auditTrails.pageDescription")}
|
||||
actions={<AdminAuditLogToolbar filters={data.filterableProperties} />}
|
||||
/>
|
||||
<div className="mobile:px-4 w-full space-y-2 px-6 py-6">
|
||||
<LogsTable withTenant={true} items={data.items} pagination={data.pagination} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { listAuditEvents } from "@hivegrid/db/audit-events-query.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { buildWhere, loader, parseFilters } from "./audit";
|
||||
|
||||
vi.mock("~/components/screens/audit/AuditListPage", () => ({ AuditListPage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/services/admin/admin-identity.server", () => ({
|
||||
runAsAdminIdentity: vi.fn(async (_request, _permission, operation) => operation({ adminUserId: "admin_1" })),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events-query.server", () => ({
|
||||
AUDIT_VIEWER_DEFAULT_PAGE_SIZE: 25,
|
||||
listAuditEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
function callLoader(url: string) {
|
||||
return loader({ request: new Request(url), params: {}, context: {} } as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("admin audit route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
|
||||
vi.mocked(listAuditEvents).mockResolvedValue({ rows: [], total: 0, take: 25, skip: 0 } as never);
|
||||
});
|
||||
|
||||
it("parses the extended investigation filters", () => {
|
||||
const filters = parseFilters(
|
||||
new URL(
|
||||
"https://admin.example.test/audit?from=2026-07-01&tenantId=t1&actorType=admin&actorId=u1&action=admin&outcome=failure&targetType=Tenant&targetId=t1"
|
||||
)
|
||||
);
|
||||
|
||||
expect(filters).toMatchObject({
|
||||
from: "2026-07-01",
|
||||
tenantId: "t1",
|
||||
actorType: "admin",
|
||||
actorId: "u1",
|
||||
action: "admin",
|
||||
outcome: "failure",
|
||||
targetType: "Tenant",
|
||||
targetId: "t1",
|
||||
});
|
||||
});
|
||||
|
||||
it("builds a Prisma where shape for tenant/user/action/entity/time filters", () => {
|
||||
const where = buildWhere({
|
||||
from: "2026-07-01",
|
||||
to: "2026-07-02",
|
||||
tenantId: "t1",
|
||||
actorType: "admin",
|
||||
actorId: "u1",
|
||||
action: "tenant",
|
||||
outcome: "success",
|
||||
targetType: "Tenant",
|
||||
targetId: "t1",
|
||||
});
|
||||
|
||||
expect(where).toMatchObject({
|
||||
tenantId: "t1",
|
||||
actorType: "admin",
|
||||
actorId: "u1",
|
||||
action: { contains: "tenant", mode: "insensitive" },
|
||||
outcome: "success",
|
||||
targetType: "Tenant",
|
||||
targetId: "t1",
|
||||
});
|
||||
expect((where.createdAt as { gte: Date; lt: Date }).lt.toISOString()).toBe("2026-07-03T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("passes the extended filters to listAuditEvents and into the VM", async () => {
|
||||
const data = await callLoader("https://admin.example.test/audit?tenantId=t1&actorId=u1&targetId=target_1&page=2");
|
||||
|
||||
expect(runAsAdminIdentity).toHaveBeenCalledWith(expect.any(Request), "admin_identity.audit.read", expect.any(Function));
|
||||
expect(listAuditEvents).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ tenantId: "t1", actorId: "u1", targetId: "target_1" }),
|
||||
take: 25,
|
||||
skip: 25,
|
||||
})
|
||||
);
|
||||
expect(data.vm.status).toBe("ready");
|
||||
if (data.vm.status !== "ready") return;
|
||||
expect(data.vm.data.filter).toMatchObject({ tenantId: "t1", actorId: "u1", targetId: "target_1" });
|
||||
});
|
||||
|
||||
it("passes the resolved actor name into the view model", async () => {
|
||||
vi.mocked(listAuditEvents).mockResolvedValue({
|
||||
rows: [
|
||||
{
|
||||
id: "audit_1",
|
||||
createdAt: new Date("2026-07-27T08:00:00.000Z"),
|
||||
tenantId: null,
|
||||
actorType: "admin",
|
||||
actorId: "cms2q01t70000zz4ymxuk5hba",
|
||||
actorEmail: "admin@email.com",
|
||||
actorDisplayName: "Raffael Sheikh",
|
||||
action: "admin.login.fallback.success",
|
||||
targetType: null,
|
||||
targetId: null,
|
||||
outcome: "success",
|
||||
metadata: null,
|
||||
beforeDiff: null,
|
||||
afterDiff: null,
|
||||
summaryText: "cms2q01t70000zz4ymxuk5hba: admin.login.fallback.success",
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
take: 25,
|
||||
skip: 0,
|
||||
} as never);
|
||||
|
||||
const data = await callLoader("https://admin.example.test/audit");
|
||||
|
||||
expect(data.vm.status).toBe("ready");
|
||||
if (data.vm.status !== "ready") return;
|
||||
expect(data.vm.data.rows[0]).toMatchObject({
|
||||
actorLabel: "Raffael Sheikh",
|
||||
actionLabelKey: "audit.action.adminFallbackLoginSuccess",
|
||||
summaryText: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* AK-P3 — Audit-Viewer (`/admin/audit`).
|
||||
*
|
||||
* Permission-gated (`admin.auditTrails.view`), server-side filtered list over the
|
||||
* Permission-gated (`admin_identity.audit.read`), server-side filtered list over the
|
||||
* tamper-evident `AuditEvent` table (NOT the legacy `Log` model used by
|
||||
* `/admin/audit-trails`). The loader builds the AuditListVM once (persisted
|
||||
* summaryText + field-by-field beforeDiff/afterDiff since the AK-P3 core schema
|
||||
@@ -12,11 +12,14 @@ import type { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useLoaderData, useNavigate } from "react-router";
|
||||
import { listAuditEvents, AUDIT_VIEWER_DEFAULT_PAGE_SIZE } from "@hivegrid/db/audit-events-query.server";
|
||||
import { buildAuditListVM, type AuditListVM, type AuditListFilterState } from "@hivegrid/view-models";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AuditListPage, type AuditListQuery } from "~/components/screens/audit/AuditListPage";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
@@ -25,26 +28,31 @@ type LoaderData = {
|
||||
vm: AuditListVM;
|
||||
};
|
||||
|
||||
function parseFilters(url: URL): AuditListFilterState {
|
||||
export function parseFilters(url: URL): AuditListFilterState {
|
||||
const get = (k: string) => url.searchParams.get(k)?.trim() || null;
|
||||
const from = get("from");
|
||||
const to = get("to");
|
||||
return {
|
||||
from: from && ISO_DATE.test(from) ? from : null,
|
||||
to: to && ISO_DATE.test(to) ? to : null,
|
||||
tenantId: get("tenantId"),
|
||||
actorType: get("actorType"),
|
||||
actorId: get("actorId"),
|
||||
action: get("action"),
|
||||
outcome: get("outcome"),
|
||||
targetType: get("targetType"),
|
||||
targetId: get("targetId"),
|
||||
};
|
||||
}
|
||||
|
||||
function buildWhere(filters: AuditListFilterState, tenantId: string | null): Record<string, unknown> {
|
||||
export function buildWhere(filters: AuditListFilterState): Record<string, unknown> {
|
||||
const where: Record<string, unknown> = {};
|
||||
if (tenantId) where.tenantId = tenantId;
|
||||
if (filters.tenantId) where.tenantId = filters.tenantId;
|
||||
if (filters.actorType) where.actorType = filters.actorType;
|
||||
if (filters.actorId) where.actorId = filters.actorId;
|
||||
if (filters.outcome) where.outcome = filters.outcome;
|
||||
if (filters.targetType) where.targetType = filters.targetType;
|
||||
if (filters.targetId) where.targetId = filters.targetId;
|
||||
if (filters.action) where.action = { contains: filters.action, mode: "insensitive" };
|
||||
if (filters.from || filters.to) {
|
||||
const range: Record<string, Date> = {};
|
||||
@@ -60,28 +68,30 @@ function buildWhere(filters: AuditListFilterState, tenantId: string | null): Rec
|
||||
}
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const url = new URL(request.url);
|
||||
|
||||
const filters = parseFilters(url);
|
||||
const tenantId = url.searchParams.get("tenantId")?.trim() || null;
|
||||
const pageRaw = Number.parseInt(url.searchParams.get("page") ?? "1", 10);
|
||||
const page = Number.isFinite(pageRaw) && pageRaw > 0 ? pageRaw : 1;
|
||||
const pageSize = AUDIT_VIEWER_DEFAULT_PAGE_SIZE;
|
||||
|
||||
// listAuditEvents lives in @hivegrid/db so the route stays free of findMany.
|
||||
const { rows, total, take } = await listAuditEvents({
|
||||
where: buildWhere(filters, tenantId),
|
||||
take: pageSize,
|
||||
skip: pageSize * (page - 1),
|
||||
});
|
||||
const { rows, total, take } = await runAsAdminIdentity(request, "admin_identity.audit.read", () =>
|
||||
listAuditEvents({
|
||||
where: buildWhere(filters),
|
||||
take: pageSize,
|
||||
skip: pageSize * (page - 1),
|
||||
})
|
||||
);
|
||||
|
||||
const vm = buildAuditListVM({
|
||||
rows: rows.map((row) => ({
|
||||
id: row.id,
|
||||
createdAtIso: row.createdAt.toISOString(),
|
||||
tenantId: row.tenantId,
|
||||
actorType: row.actorType,
|
||||
actorName: row.actorDisplayName ?? null,
|
||||
actorEmail: row.actorEmail,
|
||||
actorId: row.actorId,
|
||||
action: row.action,
|
||||
@@ -111,22 +121,43 @@ export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.t
|
||||
export default function AuditViewerRoute() {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation(["settings", "translations"]);
|
||||
|
||||
function onApply(query: AuditListQuery) {
|
||||
const params = new URLSearchParams();
|
||||
if (query.from) params.set("from", query.from);
|
||||
if (query.to) params.set("to", query.to);
|
||||
if (query.tenantId) params.set("tenantId", query.tenantId);
|
||||
if (query.actorType) params.set("actorType", query.actorType);
|
||||
if (query.actorId) params.set("actorId", query.actorId);
|
||||
if (query.action) params.set("action", query.action);
|
||||
if (query.outcome) params.set("outcome", query.outcome);
|
||||
if (query.targetType) params.set("targetType", query.targetType);
|
||||
if (query.targetId) params.set("targetId", query.targetId);
|
||||
if (query.page > 1) params.set("page", String(query.page));
|
||||
navigate({ search: params.toString() ? `?${params.toString()}` : "" });
|
||||
}
|
||||
|
||||
// Canonical admin-host link (host-aware alias, e.g. /audit-export) — matches
|
||||
// how every other admin surface links internally.
|
||||
return <AuditListPage vm={vm} exportHref={adminPath("audit-export", { mode: "host-aware" })} actions={{ onApply }} />;
|
||||
const exportHref = adminPath("audit-export", { mode: "host-aware" });
|
||||
const canExport = vm.status === "ready" && Boolean(vm.data?.canExport);
|
||||
return (
|
||||
<div className="flex w-full flex-col">
|
||||
<AdminPageHeader
|
||||
title={t("settings:audit.viewer.title")}
|
||||
description={t("settings:audit.viewer.subtitle")}
|
||||
actions={
|
||||
canExport ? (
|
||||
<a href={exportHref} className="no-underline" data-ui-id="ui.audit.list.export">
|
||||
<Button variant="secondary">{t("settings:audit.viewer.exportLink")}</Button>
|
||||
</a>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
<AuditListPage vm={vm} exportHref={exportHref} actions={{ onApply }} hideHeader />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
|
||||
+118
-99
@@ -1,128 +1,147 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loader } from "./dashboard";
|
||||
import { loadAdminDashboardRouteData } from "~/utils/data/.server/adminDashboardRouteData";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAdminDashboardStats } from "~/utils/services/adminDashboardService";
|
||||
import { adminGetAllTenantsWithUsage } from "~/utils/db/tenants.db.server";
|
||||
import PeriodHelper from "~/utils/helpers/PeriodHelper";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const translatedT = vi.fn((key: string) => `translated:${key}`);
|
||||
const computedGte = new Date("2026-02-03T04:05:06.000Z");
|
||||
const stats = [{ name: "Translated accounts", stat: "10" }];
|
||||
const tenants = { items: [{ id: "tenant-1" }], pagination: { page: 1, pageSize: 10, totalItems: 1, totalPages: 1 } };
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/adminDashboardService", () => ({
|
||||
getAdminDashboardStats: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsWithUsage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PeriodHelper", () => ({
|
||||
default: { getGreaterThanOrEqualsFromRequest: vi.fn() },
|
||||
defaultPeriodFilter: "30d",
|
||||
PeriodFilters: [],
|
||||
}));
|
||||
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { loadPersonalizedAdminDashboard } from "~/services/admin/admin-dashboard-personalization.server";
|
||||
import { getAdminDashboardOverview, getAdminDashboardStats } from "~/utils/services/adminDashboardService";
|
||||
import { adminGetAllTenantsWithUsage } from "~/utils/db/tenants.db.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
|
||||
createMetrics: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
requireAuth: vi.fn(),
|
||||
vi.mock("@hivegrid/db/admin-rbac.server", () => ({
|
||||
listAdminPermissionNames: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-identity.server", () => ({
|
||||
runAsAdminIdentity: vi.fn(async (_request, _permission, operation) =>
|
||||
operation({ adminUserId: "admin_1" })
|
||||
),
|
||||
}));
|
||||
vi.mock("~/services/admin/admin-dashboard-personalization.server", () => ({
|
||||
loadPersonalizedAdminDashboard: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/adminDashboardService", () => ({
|
||||
getAdminDashboardOverview: vi.fn(),
|
||||
getAdminDashboardStats: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsWithUsage: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: { adminUserRole: { findMany: vi.fn() } },
|
||||
}));
|
||||
vi.mock("~/utils/helpers/PeriodHelper", () => ({
|
||||
default: { getGreaterThanOrEqualsFromRequest: vi.fn(() => new Date("2026-07-01T00:00:00.000Z")) },
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
getPaginationFromCurrentUrl: vi.fn(() => ({ page: 1, pageSize: 10 })),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({
|
||||
serverTimingHeaders: vi.fn(),
|
||||
}));
|
||||
const dashboard = {
|
||||
roles: ["sales"],
|
||||
widgets: [
|
||||
{
|
||||
id: "sales_today",
|
||||
group: "sales",
|
||||
titleKey: "title",
|
||||
descriptionKey: "description",
|
||||
value: "2",
|
||||
href: "/sales/tasks/today",
|
||||
tone: "neutral",
|
||||
},
|
||||
],
|
||||
};
|
||||
const overview = {
|
||||
billing: { openIssueCount: 0, pastDueCount: 0, frozenCount: 0, missingProviderCount: 0, signals: [] },
|
||||
system: { signals: [] },
|
||||
deploy: { environment: "test", release: "abc", signals: [] },
|
||||
recentEvents: [],
|
||||
};
|
||||
|
||||
vi.mock("~/components/ui/stats/DashboardStats", () => ({
|
||||
DashboardStats: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/app/ProfileBanner", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/core/tenants/TenantsTable", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputSelect", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({
|
||||
useAppOrAdminData: vi.fn(() => ({ user: {}, permissions: ["admin.dashboard.view"] })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({
|
||||
getUserHasPermission: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
|
||||
}));
|
||||
|
||||
function readDashboardRoute() {
|
||||
return readRepoFile("apps/web/app/utils/data/.server/adminDashboardRouteData.ts");
|
||||
}
|
||||
|
||||
describe("admin dashboard KPI route contract", () => {
|
||||
describe("personalized admin dashboard loader", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: translatedT } as never);
|
||||
vi.mocked(getAdminDashboardStats).mockResolvedValue(stats as never);
|
||||
vi.mocked(adminGetAllTenantsWithUsage).mockResolvedValue(tenants as never);
|
||||
vi.mocked(PeriodHelper.getGreaterThanOrEqualsFromRequest).mockReturnValue(computedGte);
|
||||
vi.mocked(getTranslations).mockResolvedValue({
|
||||
t: (key: string) => `translated:${key}`,
|
||||
} as never);
|
||||
vi.mocked(createMetrics).mockResolvedValue({
|
||||
time: async <T,>(value: T | Promise<T>) => value,
|
||||
getServerTimingHeader: () => ({ "Server-Timing": "admin.dashboard;dur=1" }),
|
||||
getServerTimingHeader: () => ({ "Server-Timing": "dashboard;dur=1" }),
|
||||
} as never);
|
||||
vi.mocked(listAdminPermissionNames).mockResolvedValue([
|
||||
"admin.dashboard.view",
|
||||
"admin_sales.crm.read",
|
||||
] as never);
|
||||
vi.mocked(db.adminUserRole.findMany).mockResolvedValue([
|
||||
{ role: { systemKey: "sales" } },
|
||||
] as never);
|
||||
vi.mocked(loadPersonalizedAdminDashboard).mockResolvedValue(
|
||||
dashboard as never
|
||||
);
|
||||
vi.mocked(getAdminDashboardStats).mockResolvedValue([
|
||||
{ name: "MRR", stat: "10 €", hint: "" },
|
||||
] as never);
|
||||
vi.mocked(getAdminDashboardOverview).mockResolvedValue(overview as never);
|
||||
vi.mocked(adminGetAllTenantsWithUsage).mockResolvedValue({
|
||||
items: [],
|
||||
pagination: { page: 1, pageSize: 10, totalItems: 0, totalPages: 0 },
|
||||
} as never);
|
||||
});
|
||||
|
||||
it("passes translations and the computed period boundary into the KPI service while preserving loader data", async () => {
|
||||
const request = new Request("https://admin.example.com/dashboard?period=month&page=2");
|
||||
it("guards the route and never loads platform data for a sales persona", async () => {
|
||||
const request = new Request("https://admin.example.test/dashboard");
|
||||
const result = await loadAdminDashboardRouteData({ request, params: {} });
|
||||
|
||||
const response = (await loader({ request, params: {}, context: {}, unstable_pattern: "admin/dashboard" })) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(requireAuth).toHaveBeenCalledWith({ request, params: {} });
|
||||
expect(getTranslations).toHaveBeenCalledWith(request);
|
||||
expect(PeriodHelper.getGreaterThanOrEqualsFromRequest).toHaveBeenCalledWith({ request });
|
||||
expect(getAdminDashboardStats).toHaveBeenCalledWith({ t: translatedT, gte: computedGte });
|
||||
expect(adminGetAllTenantsWithUsage).toHaveBeenCalledWith(undefined, { page: 1, pageSize: 10 });
|
||||
expect(body).toMatchObject({
|
||||
expect(runAsAdminIdentity).toHaveBeenCalledWith(
|
||||
request,
|
||||
"admin.dashboard.view",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(loadPersonalizedAdminDashboard).toHaveBeenCalledWith({
|
||||
adminUserId: "admin_1",
|
||||
roleKeys: ["sales"],
|
||||
permissions: ["admin.dashboard.view", "admin_sales.crm.read"],
|
||||
});
|
||||
expect(getAdminDashboardStats).not.toHaveBeenCalled();
|
||||
expect(getAdminDashboardOverview).not.toHaveBeenCalled();
|
||||
expect(adminGetAllTenantsWithUsage).not.toHaveBeenCalled();
|
||||
expect(result.data).toEqual({
|
||||
title: "translated:app.sidebar.dashboard | HiveGrid",
|
||||
stats,
|
||||
tenants,
|
||||
dashboard,
|
||||
superOverview: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps KPI labels behind the translated dashboard service boundary", () => {
|
||||
const source = readDashboardRoute();
|
||||
it("loads the legacy full platform overview only for Super Admin", async () => {
|
||||
vi.mocked(db.adminUserRole.findMany).mockResolvedValue([
|
||||
{ role: { systemKey: "super_admin" } },
|
||||
] as never);
|
||||
vi.mocked(listAdminPermissionNames).mockResolvedValue([
|
||||
"admin.dashboard.view",
|
||||
"admin_identity.roles.manage",
|
||||
] as never);
|
||||
vi.mocked(loadPersonalizedAdminDashboard).mockResolvedValue({
|
||||
roles: ["super_admin"],
|
||||
widgets: [],
|
||||
} as never);
|
||||
|
||||
expect(source).toContain('import { getAdminDashboardStats } from "~/utils/services/adminDashboardService";');
|
||||
expect(source).toContain("getAdminDashboardStats({ t, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) })");
|
||||
expect(source).not.toContain("admin.kpi.accounts.name");
|
||||
expect(source).not.toContain("admin.kpi.mrr.name");
|
||||
expect(source).not.toContain("admin.kpi.activeUsers.name");
|
||||
expect(source).not.toContain("Translated accounts");
|
||||
const result = await loadAdminDashboardRouteData({
|
||||
request: new Request("https://admin.example.test/dashboard?period=month"),
|
||||
params: {},
|
||||
});
|
||||
|
||||
expect(getAdminDashboardStats).toHaveBeenCalledOnce();
|
||||
expect(getAdminDashboardOverview).toHaveBeenCalledOnce();
|
||||
expect(adminGetAllTenantsWithUsage).toHaveBeenCalledOnce();
|
||||
expect(result.data.superOverview).toMatchObject({
|
||||
overview,
|
||||
tenants: { items: [] },
|
||||
});
|
||||
});
|
||||
});
|
||||
+5
-3
@@ -8,11 +8,13 @@ function readRoute() {
|
||||
}
|
||||
|
||||
describe("admin dashboard KPI route contract", () => {
|
||||
it("passes the route translations and period filter to the dashboard stats service", () => {
|
||||
it("keeps the legacy platform KPI load behind the explicit super-admin branch", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain('const { t } = await time(getTranslations(request), "getTranslations");');
|
||||
expect(source).toContain("getAdminDashboardStats({ t, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) })");
|
||||
expect(source).toContain('const { t, locale } = await time(getTranslations(request), "getTranslations");');
|
||||
expect(source).toContain('roleKeys.includes("super_admin")');
|
||||
expect(source).toContain("loadSuperAdminOverview(request, t, time)");
|
||||
expect(source).toContain("PeriodHelper.getGreaterThanOrEqualsFromRequest({ request })");
|
||||
expect(source).toContain("admin.dashboard.details.getAdminDashboardStats");
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,33 @@
|
||||
import { useLoaderData } from "react-router";
|
||||
import { Link, useLoaderData } from "react-router";
|
||||
import { useSearchParams } from "react-router";
|
||||
import {
|
||||
FeatherActivity,
|
||||
FeatherAlertTriangle,
|
||||
FeatherArrowRight,
|
||||
FeatherCheckCircle,
|
||||
FeatherCreditCard,
|
||||
FeatherRocket,
|
||||
FeatherServer,
|
||||
FeatherShieldCheck,
|
||||
} from "@subframe/core";
|
||||
import type React from "react";
|
||||
import { DashboardStats } from "~/components/ui/stats/DashboardStats";
|
||||
import ProfileBanner from "~/components/app/ProfileBanner";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import { AdminPersonalizedDashboard } from "~/components/screens/admin/AdminPersonalizedDashboard";
|
||||
import TenantsTable from "~/components/core/tenants/TenantsTable";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { defaultPeriodFilter, PeriodFilters } from "~/utils/helpers/PeriodHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import type { AdminDashboardLoaderData } from "~/routeModules/admin/dashboard.impl";
|
||||
import type { AdminDashboardActivity, AdminDashboardSignal, AdminDashboardSignalTone } from "~/utils/services/adminDashboardService";
|
||||
import { formatDate } from "~/locale/format";
|
||||
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
export { serverTimingHeaders as headers };
|
||||
export { loader } from "~/routeModules/admin/dashboard.impl";
|
||||
|
||||
@@ -26,20 +41,23 @@ export default function AdminNavigationRoute() {
|
||||
|
||||
return (
|
||||
<main className="relative z-0 flex-1 pb-8">
|
||||
{/*Page header */}
|
||||
<div className="bg-background lg:border-border hidden shadow-xs md:block lg:border-t">
|
||||
<ProfileBanner user={appOrAdminData.user} />
|
||||
</div>
|
||||
<AdminPageHeader title={t("app.sidebar.dashboard")} description={t("admin.dashboard.pageDescription")} />
|
||||
|
||||
<div className="mx-auto grid max-w-5xl gap-5 px-4 py-5 sm:px-8">
|
||||
{getUserHasPermission(appOrAdminData, "admin.dashboard.view") ? (
|
||||
<div className="space-y-5 overflow-hidden">
|
||||
<div className="space-y-3 truncate p-1">
|
||||
<div className="mobile:px-4 grid w-full gap-5 px-6 py-6">
|
||||
<div className="space-y-5 overflow-hidden">
|
||||
<GreetingTile firstName={appOrAdminData.user?.firstName} email={appOrAdminData.user?.email} />
|
||||
<AdminPersonalizedDashboard vm={data.dashboard} />
|
||||
{data.superOverview ? (
|
||||
<>
|
||||
<div className="space-y-3 p-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground grow font-medium leading-4">{t("app.dashboard.summary")}</h3>
|
||||
<h3 className="text-body-large-0 font-body-large-0 text-text-neutral-primary grow">
|
||||
{t("admin.dashboard.personalized.platformDetails")}
|
||||
</h3>
|
||||
<div>
|
||||
{/* Subframe Select has a fixed 192px min-width — the wrapper must match or the chevron gets clipped. */}
|
||||
<InputSelect
|
||||
className="w-44"
|
||||
className="w-48"
|
||||
name="period"
|
||||
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
|
||||
options={PeriodFilters.map((f) => {
|
||||
@@ -59,21 +77,275 @@ export default function AdminNavigationRoute() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DashboardStats items={data.stats} />
|
||||
<DashboardStats items={data.superOverview.stats} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.7fr)]">
|
||||
<OperatorPanel
|
||||
title={t("admin.dashboard.billing.title")}
|
||||
description={t("admin.dashboard.billing.description")}
|
||||
icon={<FeatherCreditCard aria-hidden="true" />}
|
||||
signals={data.superOverview.overview.billing.signals}
|
||||
ctaHref={adminPath("system/billing", { mode: "host-aware" })}
|
||||
ctaLabel={t("admin.dashboard.billing.cta")}
|
||||
/>
|
||||
<DeployPanel
|
||||
title={t("admin.dashboard.deploy.title")}
|
||||
description={t("admin.dashboard.deploy.description")}
|
||||
environment={data.superOverview.overview.deploy.environment}
|
||||
release={data.superOverview.overview.deploy.release}
|
||||
signals={data.superOverview.overview.deploy.signals}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(320px,0.85fr)]">
|
||||
<OperatorPanel
|
||||
title={t("admin.dashboard.system.title")}
|
||||
description={t("admin.dashboard.system.description")}
|
||||
icon={<FeatherServer aria-hidden="true" />}
|
||||
signals={data.superOverview.overview.system.signals}
|
||||
ctaHref={adminPath("events", { mode: "host-aware" })}
|
||||
ctaLabel={t("admin.dashboard.system.cta")}
|
||||
/>
|
||||
<RecentActivityPanel
|
||||
title={t("admin.dashboard.recentActivity.title")}
|
||||
description={t("admin.dashboard.recentActivity.description")}
|
||||
emptyLabel={t("admin.dashboard.recentActivity.empty")}
|
||||
items={data.superOverview.overview.recentEvents}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 overflow-x-auto p-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground font-medium leading-4">{t("models.tenant.plural")}</h3>
|
||||
<ButtonSecondary to={adminPath("accounts", { mode: "host-aware" })}>{t("shared.viewAll")}</ButtonSecondary>
|
||||
<h3 className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("models.tenant.plural")}</h3>
|
||||
<Link to={adminPath("accounts", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("shared.viewAll")}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<TenantsTable items={data.tenants.items} pagination={data.tenants.pagination} />
|
||||
<TenantsTable
|
||||
items={data.superOverview.tenants.items}
|
||||
pagination={data.superOverview.tenants.pagination}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="font-medium">{t("app.dashboard.noPermission")}</div>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function GreetingTile({ firstName, email }: { firstName?: string | null; email?: string | null }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Card variant="neutral">
|
||||
<div className="flex w-full flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">
|
||||
{t("shared.hi")} {firstName ? <span>{firstName} 👋</span> : null}
|
||||
</span>
|
||||
{email ? <span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{email}</span> : null}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function OperatorPanel({
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
signals,
|
||||
ctaHref,
|
||||
ctaLabel,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
icon: React.ReactNode;
|
||||
signals: AdminDashboardSignal[];
|
||||
ctaHref: string;
|
||||
ctaLabel: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex w-full items-start justify-between gap-4">
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<span className="text-heading- font-heading- text-icon-neutral-tertiary">{icon}</span>
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{title}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{description}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Link to={ctaHref}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{ctaLabel}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="grid w-full gap-3 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{signals.map((signal) => (
|
||||
<SignalCard key={signal.id} signal={signal} label={t(signal.labelKey)} detail={t(signal.detailKey)} />
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function DeployPanel({
|
||||
title,
|
||||
description,
|
||||
environment,
|
||||
release,
|
||||
signals,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
environment: string;
|
||||
release: string;
|
||||
signals: AdminDashboardSignal[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<span className="text-heading- font-heading- text-icon-neutral-tertiary">
|
||||
<FeatherRocket />
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{title}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{description}</span>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="grid w-full grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-2">
|
||||
<dt className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("admin.dashboard.deploy.environment")}</dt>
|
||||
<dd className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate">{environment}</dd>
|
||||
<dt className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("admin.dashboard.deploy.release")}</dt>
|
||||
<dd className="text-text-neutral-primary truncate font-mono text-xs">{release}</dd>
|
||||
</dl>
|
||||
<div className="grid w-full gap-3">
|
||||
{signals.map((signal) => (
|
||||
<SignalCard key={signal.id} signal={signal} label={t(signal.labelKey)} detail={t(signal.detailKey)} compact />
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function SignalCard({ signal, label, detail, compact = false }: { signal: AdminDashboardSignal; label: string; detail: string; compact?: boolean }) {
|
||||
const content = (
|
||||
<div className="border-border-default bg-surface-neutral-primary hover:bg-surface-neutral-secondary/60 flex h-full min-h-20 w-full flex-col justify-between gap-3 rounded-md border border-solid px-4 py-3 transition-colors">
|
||||
<div className="flex w-full items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate">{label}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{detail}</span>
|
||||
</div>
|
||||
<StatusBadge tone={signal.tone} />
|
||||
</div>
|
||||
<span className={compact ? "text-body-large-0 font-body-large-0 text-text-neutral-primary" : "text-subtitle-0 font-subtitle-0 text-text-neutral-primary"}>
|
||||
{signal.value}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!signal.href) {
|
||||
return content;
|
||||
}
|
||||
|
||||
return (
|
||||
<Link className="focus-visible:shadow-focus block focus-visible:outline-none" to={signal.href}>
|
||||
{content}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function RecentActivityPanel({
|
||||
title,
|
||||
description,
|
||||
emptyLabel,
|
||||
items,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
emptyLabel: string;
|
||||
items: AdminDashboardActivity[];
|
||||
}) {
|
||||
const { i18n } = useTranslation();
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<span className="text-heading- font-heading- text-icon-neutral-tertiary">
|
||||
<FeatherActivity />
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{title}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{description}</span>
|
||||
</div>
|
||||
</div>
|
||||
{items.length === 0 ? (
|
||||
<span className="border-border-default text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full rounded-md border border-dashed p-4">
|
||||
{emptyLabel}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
{items.map((item) => (
|
||||
<Link
|
||||
key={item.id}
|
||||
to={item.href}
|
||||
className="border-border-default bg-surface-neutral-primary hover:bg-surface-neutral-secondary/60 flex w-full items-start gap-3 rounded-md border border-solid px-4 py-3 transition-colors"
|
||||
>
|
||||
<StatusIcon tone={item.tone} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate">{item.label}</p>
|
||||
<p className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary truncate">{item.detail}</p>
|
||||
</div>
|
||||
<time
|
||||
className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary shrink-0"
|
||||
dateTime={item.timestamp}
|
||||
>
|
||||
{formatTimestamp(item.timestamp, i18n.language)}
|
||||
</time>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusBadge({ tone }: { tone: AdminDashboardSignalTone }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<BadgeFeedback farbe={toneToBadgeTone(tone)} size="small">
|
||||
{t(`admin.dashboard.tones.${tone}`)}
|
||||
</BadgeFeedback>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusIcon({ tone }: { tone: AdminDashboardSignalTone }) {
|
||||
if (tone === "success") {
|
||||
return <FeatherCheckCircle className="text-icon-feedback-positive mt-0.5 size-4 shrink-0" aria-hidden="true" />;
|
||||
}
|
||||
if (tone === "danger" || tone === "warning") {
|
||||
return <FeatherAlertTriangle className="text-icon-feedback-warning mt-0.5 size-4 shrink-0" aria-hidden="true" />;
|
||||
}
|
||||
return <FeatherShieldCheck className="text-icon-neutral-tertiary mt-0.5 size-4 shrink-0" aria-hidden="true" />;
|
||||
}
|
||||
|
||||
function toneToBadgeTone(tone: AdminDashboardSignalTone): "subtle-positive" | "subtle-negative" | "subtle-warning" | "subtle-neutral" {
|
||||
if (tone === "success") return "subtle-positive";
|
||||
if (tone === "danger") return "subtle-negative";
|
||||
if (tone === "warning") return "subtle-warning";
|
||||
return "subtle-neutral";
|
||||
}
|
||||
|
||||
function formatTimestamp(value: string, locale: string) {
|
||||
try {
|
||||
// Explicit locale + fixed time zone keep SSR and client output identical (React #418).
|
||||
return formatDate(value, locale, { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import { redirectLegacyAdminRoute } from "~/utils/navigation/legacyAdminRouteRedirect.server";
|
||||
|
||||
export const loader = ({ request }: LoaderFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "system/deploys");
|
||||
+1
-1
@@ -17,7 +17,7 @@ type LoaderData = {
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.marketing.leads.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const title = (t("admin.emailSequences.title") as string) || "Email Sequences";
|
||||
const title = t("admin.emailSequences.title");
|
||||
const data: LoaderData = {
|
||||
title: `${title} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
* the home for periodic snapshots).
|
||||
*/
|
||||
import { Link, type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { dbRead } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
+43
-2
@@ -37,9 +37,9 @@ vi.mock("i18next", () => ({
|
||||
t: (key: string) => key,
|
||||
}));
|
||||
|
||||
async function callAction(values: Record<string, string>) {
|
||||
async function callActionResponse(values: Record<string, string>) {
|
||||
const body = new URLSearchParams(values);
|
||||
const response = (await action({
|
||||
return (await action({
|
||||
request: new Request("https://admin.example.test/email-sequences/seq-1", {
|
||||
method: "POST",
|
||||
body,
|
||||
@@ -49,6 +49,10 @@ async function callAction(values: Record<string, string>) {
|
||||
context: {},
|
||||
unstable_pattern: "admin/email-sequences/:id",
|
||||
} as ActionFunctionArgs)) as Response;
|
||||
}
|
||||
|
||||
async function callAction(values: Record<string, string>) {
|
||||
const response = await callActionResponse(values);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
@@ -94,4 +98,41 @@ describe("admin email sequence detail action", () => {
|
||||
});
|
||||
expect(db.emailSequence.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not expose the email-sequence engine error in validation feedback", async () => {
|
||||
const result = await callAction({
|
||||
name: "Welcome",
|
||||
triggerEvent: "lead.captured",
|
||||
stepsJson: "{}",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
error: "translated:admin.emailSequences.errors.stepsJsonValidationFailed",
|
||||
field: "stepsJson",
|
||||
});
|
||||
expect(db.emailSequence.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("redirects with an action-specific toast after enabling a sequence", async () => {
|
||||
const response = await callActionResponse({ intent: "toggle" });
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toContain(
|
||||
`toast=${encodeURIComponent("admin.emailSequences.toast.enabled")}`
|
||||
);
|
||||
});
|
||||
|
||||
it("redirects with the saved toast after updating a sequence", async () => {
|
||||
const response = await callActionResponse({
|
||||
name: "Welcome",
|
||||
triggerEvent: "lead.captured",
|
||||
stepsJson: "[]",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toContain(
|
||||
`toast=${encodeURIComponent("admin.emailSequences.toast.saved")}`
|
||||
);
|
||||
});
|
||||
});
|
||||
+12
-5
@@ -12,7 +12,7 @@
|
||||
* engine package before save so bad JSON cannot corrupt a run.
|
||||
*/
|
||||
import { Form, Link, type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { db, dbRead } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
@@ -63,7 +63,12 @@ export const action = async ({ params, request }: ActionFunctionArgs) => {
|
||||
|
||||
if (intent === "toggle") {
|
||||
await db.emailSequence.update({ where: { id }, data: { isEnabled: !existing.isEnabled } });
|
||||
return redirect(`${adminPath("email-sequences", { mode: "host-aware" })}/${id}`);
|
||||
const messageKey = existing.isEnabled
|
||||
? "admin.emailSequences.toast.disabled"
|
||||
: "admin.emailSequences.toast.enabled";
|
||||
return redirect(
|
||||
`${adminPath("email-sequences", { mode: "host-aware" })}/${id}?toast=${encodeURIComponent(messageKey)}`
|
||||
);
|
||||
}
|
||||
|
||||
const name = String(formData.get("name") ?? "").trim();
|
||||
@@ -84,10 +89,10 @@ export const action = async ({ params, request }: ActionFunctionArgs) => {
|
||||
const { parseSequenceSteps } = await import("@hivegrid/email-sequences");
|
||||
try {
|
||||
parseSequenceSteps(stepsJson);
|
||||
} catch (error) {
|
||||
} catch {
|
||||
return Response.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : t("admin.emailSequences.errors.stepsJsonValidationFailed"),
|
||||
error: t("admin.emailSequences.errors.stepsJsonValidationFailed"),
|
||||
field: "stepsJson",
|
||||
} satisfies ActionResponse);
|
||||
}
|
||||
@@ -113,7 +118,9 @@ export const action = async ({ params, request }: ActionFunctionArgs) => {
|
||||
conditionsJson: conditionsJson as never,
|
||||
},
|
||||
});
|
||||
return redirect(`${adminPath("email-sequences", { mode: "host-aware" })}/${id}`);
|
||||
return redirect(
|
||||
`${adminPath("email-sequences", { mode: "host-aware" })}/${id}?toast=${encodeURIComponent("admin.emailSequences.toast.saved")}`
|
||||
);
|
||||
};
|
||||
|
||||
export default function EmailSequenceDetail() {
|
||||
|
||||
+13
@@ -25,12 +25,20 @@ function readTranslations(locale: "en" | "de") {
|
||||
form: Record<string, string>;
|
||||
placeholders: Record<string, string>;
|
||||
stats: Record<string, string>;
|
||||
toast: Record<string, string>;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
describe("admin email sequence route i18n", () => {
|
||||
it("uses the localized title key without an English meta fallback", () => {
|
||||
const source = readRoute("../email-sequences.tsx");
|
||||
|
||||
expect(source).toContain('t("admin.emailSequences.title")');
|
||||
expect(source).not.toContain('|| "Email Sequences"');
|
||||
});
|
||||
|
||||
it("uses namespaced email sequence keys for create and edit form chrome", () => {
|
||||
const source = `${readRoute("new.tsx")}\n${readRoute("$id.tsx")}`;
|
||||
|
||||
@@ -51,6 +59,10 @@ describe("admin email sequence route i18n", () => {
|
||||
"admin.emailSequences.form.triggerEvent",
|
||||
"admin.emailSequences.form.triggerHint",
|
||||
"admin.emailSequences.placeholders.triggerEvent",
|
||||
"admin.emailSequences.toast.created",
|
||||
"admin.emailSequences.toast.disabled",
|
||||
"admin.emailSequences.toast.enabled",
|
||||
"admin.emailSequences.toast.saved",
|
||||
]) {
|
||||
expect(source).toContain(key);
|
||||
}
|
||||
@@ -81,6 +93,7 @@ describe("admin email sequence route i18n", () => {
|
||||
expect(Object.keys(de.form).sort()).toEqual(Object.keys(en.form).sort());
|
||||
expect(Object.keys(de.placeholders).sort()).toEqual(Object.keys(en.placeholders).sort());
|
||||
expect(Object.keys(de.stats).sort()).toEqual(Object.keys(en.stats).sort());
|
||||
expect(Object.keys(de.toast).sort()).toEqual(Object.keys(en.toast).sort());
|
||||
});
|
||||
|
||||
it("keeps trigger event terminology coherent across email sequence locales", () => {
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { loader } from "./new";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({ db: { emailSequence: { create: vi.fn() } } }));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("i18next", () => ({
|
||||
t: (key: string) => key,
|
||||
}));
|
||||
|
||||
describe("admin email sequence create loader", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
});
|
||||
|
||||
it("builds the starter subject with the request-local translator", async () => {
|
||||
vi.mocked(getTranslations).mockResolvedValue({
|
||||
t: ((key: string, values?: { productName?: string }) => `${key}:${values?.productName ?? ""}`) as never,
|
||||
} as never);
|
||||
|
||||
const response = (await loader({
|
||||
request: new Request("https://admin.example.test/email-sequences/new"),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/email-sequences/new",
|
||||
} as LoaderFunctionArgs)) as Response;
|
||||
const data = (await response.json()) as { defaultSteps: string };
|
||||
const steps = JSON.parse(data.defaultSteps) as Array<{ subject: string }>;
|
||||
|
||||
expect(steps[0]?.subject).toBe(`admin.emailSequences.defaults.welcomeSubject:${process.env.APP_NAME ?? "HiveGrid"}`);
|
||||
expect(getTranslations).toHaveBeenCalledWith(expect.any(Request));
|
||||
});
|
||||
});
|
||||
+25
-21
@@ -6,8 +6,8 @@
|
||||
* before inserting so the row is always renderable by the trigger
|
||||
* handler.
|
||||
*/
|
||||
import { Form, Link, redirect, useActionData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { Form, Link, redirect, useActionData, useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
@@ -15,23 +15,24 @@ import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type ActionResponse = { ok: true } | { ok: false; error: string };
|
||||
|
||||
const DEFAULT_STEPS = JSON.stringify(
|
||||
[
|
||||
{
|
||||
stepIndex: 0,
|
||||
delayHours: 0,
|
||||
template: "welcome",
|
||||
subject: i18nT("admin.emailSequences.defaults.welcomeSubject"),
|
||||
variables: { productName: "HiveGrid" },
|
||||
},
|
||||
],
|
||||
null,
|
||||
2
|
||||
);
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.marketing.leads.view");
|
||||
return Response.json({});
|
||||
const { t } = await getTranslations(request);
|
||||
const productName = process.env.APP_NAME ?? "HiveGrid";
|
||||
const defaultSteps = JSON.stringify(
|
||||
[
|
||||
{
|
||||
stepIndex: 0,
|
||||
delayHours: 0,
|
||||
template: "welcome",
|
||||
subject: t("admin.emailSequences.defaults.welcomeSubject", { productName }),
|
||||
variables: { productName },
|
||||
},
|
||||
],
|
||||
null,
|
||||
2
|
||||
);
|
||||
return Response.json({ defaultSteps });
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
@@ -54,10 +55,10 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const { parseSequenceSteps } = await import("@hivegrid/email-sequences");
|
||||
try {
|
||||
parseSequenceSteps(stepsJson);
|
||||
} catch (error) {
|
||||
} catch {
|
||||
return Response.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : t("admin.emailSequences.errors.stepsJsonValidationFailed"),
|
||||
error: t("admin.emailSequences.errors.stepsJsonValidationFailed"),
|
||||
} satisfies ActionResponse);
|
||||
}
|
||||
let conditionsJson: unknown = null;
|
||||
@@ -78,10 +79,13 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
isEnabled: false,
|
||||
},
|
||||
});
|
||||
return redirect(`${adminPath("email-sequences", { mode: "host-aware" })}/${created.id}`);
|
||||
return redirect(
|
||||
`${adminPath("email-sequences", { mode: "host-aware" })}/${created.id}?toast=${encodeURIComponent("admin.emailSequences.toast.created")}`
|
||||
);
|
||||
};
|
||||
|
||||
export default function EmailSequenceNew() {
|
||||
const { defaultSteps } = useLoaderData<typeof loader>();
|
||||
const action = useActionData<ActionResponse>();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8">
|
||||
@@ -126,7 +130,7 @@ export default function EmailSequenceNew() {
|
||||
<textarea
|
||||
id="stepsJson"
|
||||
name="stepsJson"
|
||||
defaultValue={DEFAULT_STEPS}
|
||||
defaultValue={defaultSteps}
|
||||
rows={14}
|
||||
spellCheck={false}
|
||||
className="border-border w-full rounded-md border px-3 py-1.5 font-mono text-xs"
|
||||
|
||||
+39
-28
@@ -1,5 +1,6 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, Outlet } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
|
||||
import IncreaseIcon from "~/components/ui/icons/crm/IncreaseIcon";
|
||||
import IncreaseIconFilled from "~/components/ui/icons/crm/IncreaseIconFilled";
|
||||
import SettingsIcon from "~/components/ui/icons/crm/SettingsIcon";
|
||||
@@ -9,6 +10,7 @@ import ToggleOnIcon from "~/components/ui/icons/featureFlags/ToggleOnIcon";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
type LoaderData = {
|
||||
@@ -16,7 +18,7 @@ type LoaderData = {
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
await verifyUserHasPermission(request, ADMIN_AREA_ACCESS.featureFlags);
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("featureFlags.title")} | ${process.env.APP_NAME}`,
|
||||
@@ -29,32 +31,41 @@ export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.t
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
href: adminPath("feature-flags", { mode: "host-aware" }),
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
exact: true,
|
||||
},
|
||||
{
|
||||
name: t("featureFlags.plural"),
|
||||
href: adminPath("feature-flags/flags", { mode: "host-aware" }),
|
||||
icon: <ToggleOffIcon className="h-5 w-5" />,
|
||||
iconSelected: <ToggleOnIcon className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("shared.settings"),
|
||||
href: adminPath("feature-flags/settings", { mode: "host-aware" }),
|
||||
icon: <SettingsIcon className="h-5 w-5" />,
|
||||
iconSelected: <SettingsIconFilled className="h-5 w-5" />,
|
||||
bottom: true,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
<div className="flex w-full flex-col">
|
||||
<AdminPageHeader title={t("app.sidebar.featureFlags")} description={t("featureFlags.pageDescription")} />
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
href: adminPath("feature-flags", { mode: "host-aware" }),
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
exact: true,
|
||||
},
|
||||
{
|
||||
name: t("featureFlags.plural"),
|
||||
href: adminPath("feature-flags/flags", { mode: "host-aware" }),
|
||||
icon: <ToggleOffIcon className="h-5 w-5" />,
|
||||
iconSelected: <ToggleOnIcon className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("featureFlags.engine.nav"),
|
||||
href: adminPath("feature-flags/engine", { mode: "host-aware" }),
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("shared.settings"),
|
||||
href: adminPath("feature-flags/settings", { mode: "host-aware" }),
|
||||
icon: <SettingsIcon className="h-5 w-5" />,
|
||||
iconSelected: <SettingsIconFilled className="h-5 w-5" />,
|
||||
bottom: true,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import {
|
||||
applyAdminFeatureFlagBulkOverride,
|
||||
getAdminFeatureFlagRolloutView,
|
||||
} from "~/services/admin/feature-flag-rollout.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
import { action, loader } from "./$key.bulk";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/admin/admin-identity.server", () => ({
|
||||
runAsAdminIdentity: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/admin/feature-flag-rollout.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/feature-flag-rollout.server")>(
|
||||
"~/services/admin/feature-flag-rollout.server"
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
applyAdminFeatureFlagBulkOverride: vi.fn(),
|
||||
getAdminFeatureFlagRolloutView: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
const runAsAdminIdentityMock = vi.mocked(runAsAdminIdentity);
|
||||
const getRolloutViewMock = vi.mocked(getAdminFeatureFlagRolloutView);
|
||||
const applyBulkOverrideMock = vi.mocked(applyAdminFeatureFlagBulkOverride);
|
||||
|
||||
describe("admin feature flag bulk route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
runAsAdminIdentityMock.mockImplementation(async (_request, _permission, operation) =>
|
||||
operation({
|
||||
adminUserId: "admin-raffael",
|
||||
sessionId: "session-1",
|
||||
assurance: "mfa",
|
||||
} as never)
|
||||
);
|
||||
});
|
||||
|
||||
it("builds the effective rollout VM behind the read permission", async () => {
|
||||
getRolloutViewMock.mockResolvedValue({
|
||||
flag: {
|
||||
id: "flag-1",
|
||||
key: "sales_workspace",
|
||||
label: "Sales Workspace",
|
||||
defaultValue: false,
|
||||
lifecycleStage: "rollout",
|
||||
},
|
||||
tenants: [
|
||||
{
|
||||
id: "tenant-1",
|
||||
name: "Muster SHK",
|
||||
slug: "muster",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
size: "11-25",
|
||||
industry: "shk",
|
||||
status: "active",
|
||||
subscriptionProductIds: [],
|
||||
},
|
||||
],
|
||||
preview: {
|
||||
enabled: 1,
|
||||
disabled: 0,
|
||||
overrides: 1,
|
||||
filtered: 0,
|
||||
defaulted: 0,
|
||||
rows: [{ tenantId: "tenant-1", decision: { value: true, source: "override", filterId: null } }],
|
||||
},
|
||||
});
|
||||
|
||||
const response = await loader({
|
||||
request: new Request("https://admin.hivegrid.de/feature-flags/sales_workspace/bulk"),
|
||||
params: { key: "sales_workspace" },
|
||||
context: {},
|
||||
} as never);
|
||||
const body = await response.json();
|
||||
|
||||
expect(runAsAdminIdentityMock).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin.featureFlags.view",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(body.vm.tenants[0]).toMatchObject({
|
||||
id: "tenant-1",
|
||||
effectiveValue: true,
|
||||
source: "override",
|
||||
});
|
||||
});
|
||||
|
||||
it("validates CSRF and uses the smallest manage permission for a bulk override", async () => {
|
||||
applyBulkOverrideMock.mockResolvedValue({ updated: 2 });
|
||||
const form = new FormData();
|
||||
form.set("action", "bulk-override");
|
||||
form.set("value", "true");
|
||||
form.set("reason", "Pilotgruppe freigegeben");
|
||||
form.append("tenantId", "tenant-1");
|
||||
form.append("tenantId", "tenant-2");
|
||||
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of form.entries()) {
|
||||
if (typeof value === "string") body.append(key, value);
|
||||
}
|
||||
const response = await action({
|
||||
request: new Request("https://admin.hivegrid.de/feature-flags/sales_workspace/bulk", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
}),
|
||||
params: { key: "sales_workspace" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(runAsAdminIdentityMock).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin.featureFlags.manage",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(applyBulkOverrideMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
flagKey: "sales_workspace",
|
||||
tenantIds: ["tenant-1", "tenant-2"],
|
||||
actorAdminUserId: "admin-raffael",
|
||||
})
|
||||
);
|
||||
expect(response.status).toBe(303);
|
||||
});
|
||||
});
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { useActionData, useLoaderData, useSubmit } from "react-router";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { buildAdminFeatureFlagRolloutVM } from "@hivegrid/view-models";
|
||||
|
||||
import { AdminFeatureFlagBulkPage } from "~/components/screens/admin/sales/feature-flags/AdminFeatureFlagBulkPage";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import {
|
||||
AdminFeatureFlagRolloutError,
|
||||
applyAdminFeatureFlagBulkOverride,
|
||||
getAdminFeatureFlagRolloutView,
|
||||
} from "~/services/admin/feature-flag-rollout.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type ActionData = { errorKey?: string };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const flagKey = params.key ?? "";
|
||||
const view = await runAsAdminIdentity(request, "admin.featureFlags.view", () => getAdminFeatureFlagRolloutView(flagKey));
|
||||
if (!view) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
const updatedValue = Number(new URL(request.url).searchParams.get("updated"));
|
||||
const updatedCount = Number.isSafeInteger(updatedValue) && updatedValue > 0 ? updatedValue : null;
|
||||
const vm = buildAdminFeatureFlagRolloutVM({ ...view, updatedCount });
|
||||
if (vm.status !== "ready") throw new Error("Feature flag rollout view model is not ready.");
|
||||
return Response.json({ vm: vm.data });
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const actionName = form.get("action");
|
||||
if (actionName !== "bulk-override") {
|
||||
return Response.json({ errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const value = form.get("value");
|
||||
if (value !== "true" && value !== "false") {
|
||||
return Response.json({ errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await runAsAdminIdentity(request, "admin.featureFlags.manage", (session) =>
|
||||
applyAdminFeatureFlagBulkOverride({
|
||||
flagKey: params.key ?? "",
|
||||
tenantIds: form.getAll("tenantId").map(String),
|
||||
value: value === "true",
|
||||
reason: String(form.get("reason") ?? ""),
|
||||
note: String(form.get("note") ?? ""),
|
||||
expiresAt: parseOptionalDate(form.get("expiresAt")),
|
||||
actorAdminUserId: session.adminUserId,
|
||||
request,
|
||||
})
|
||||
);
|
||||
return Response.redirect(
|
||||
new URL(adminPath(`feature-flags/${encodeURIComponent(params.key ?? "")}/bulk`, { mode: "host-aware" }) + `?updated=${result.updated}`, request.url),
|
||||
303
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminFeatureFlagRolloutError) {
|
||||
return Response.json({ errorKey: `featureFlags.rollout.errors.${error.code}` } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export default function AdminFeatureFlagBulkRoute() {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
useSaveToast(actionData);
|
||||
return (
|
||||
<AdminFeatureFlagBulkPage
|
||||
vm={vm}
|
||||
actions={{
|
||||
onApplyOverride(input) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "bulk-override");
|
||||
form.set("value", String(input.value));
|
||||
form.set("reason", input.reason);
|
||||
form.set("note", input.note);
|
||||
form.set("expiresAt", input.expiresAt);
|
||||
input.tenantIds.forEach((tenantId) => form.append("tenantId", tenantId));
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function parseOptionalDate(value: FormDataEntryValue | null): Date | null {
|
||||
const text = typeof value === "string" ? value.trim() : "";
|
||||
if (!text) return null;
|
||||
const date = new Date(text);
|
||||
if (!Number.isFinite(date.getTime())) throw new AdminFeatureFlagRolloutError("INVALID_INPUT");
|
||||
return date;
|
||||
}
|
||||
+34
-23
@@ -18,8 +18,8 @@ import { validateCSRFToken, getUserInfo } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { evaluateRule, type TargetingRule } from "@hivegrid/feature-flags";
|
||||
import { invalidateFlagCache } from "~/utils/services/.server/featureFlagEvaluator.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type V2Flag = {
|
||||
id: string;
|
||||
@@ -47,6 +47,14 @@ type LoaderData = {
|
||||
audits: AuditRow[];
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
intent: string;
|
||||
ok?: true;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
errorValues?: Record<string, string | number>;
|
||||
};
|
||||
|
||||
type RuleValidationError = {
|
||||
key: string;
|
||||
options?: Record<string, string | number>;
|
||||
@@ -168,7 +176,6 @@ export const loader: LoaderFunction = async ({ request }) => {
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.manage");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent")?.toString() ?? "";
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
@@ -176,13 +183,13 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const actorUserId = userInfo.userId || null;
|
||||
|
||||
const existing = await db.featureFlag.findUnique({ where: { id } });
|
||||
if (!existing) return Response.json({ error: t("featureFlags.engine.errors.notFound") }, { status: 404 });
|
||||
if (!existing) return Response.json({ intent, errorKey: "featureFlags.engine.errors.notFound" } satisfies ActionData, { status: 404 });
|
||||
|
||||
if (intent === "toggle") {
|
||||
const newEnabled = !existing.enabled;
|
||||
await db.$transaction([
|
||||
db.featureFlag.update({ where: { id }, data: { enabled: newEnabled } }),
|
||||
db.featureFlagAudit.create({
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.featureFlag.update({ where: { id }, data: { enabled: newEnabled } });
|
||||
await tx.featureFlagAudit.create({
|
||||
data: {
|
||||
flagId: id,
|
||||
actorUserId,
|
||||
@@ -190,10 +197,10 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
oldValue: { enabled: existing.enabled },
|
||||
newValue: { enabled: newEnabled },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
await invalidateFlagCache(existing.name);
|
||||
return Response.json({ ok: true });
|
||||
return Response.json({ intent } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "save-rules") {
|
||||
@@ -203,11 +210,14 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const value = JSON.parse(rulesRaw);
|
||||
parsed = value === null ? null : (value as TargetingRule);
|
||||
} catch {
|
||||
return Response.json({ error: t("featureFlags.engine.errors.invalidRulesJson") }, { status: 400 });
|
||||
return Response.json({ intent, errorKey: "featureFlags.engine.errors.invalidRulesJson" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const validationError = parsed ? validateTargetingRuleShape(parsed) : null;
|
||||
if (validationError) {
|
||||
return Response.json({ error: t(validationError.key, validationError.options) }, { status: 400 });
|
||||
return Response.json(
|
||||
{ intent, errorKey: validationError.key, errorValues: validationError.options } satisfies ActionData,
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
// Validation: evaluate against a representative context to ensure
|
||||
// the rule does not throw (it never does — see evaluator.ts — but
|
||||
@@ -216,9 +226,8 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
if (parsed) {
|
||||
try {
|
||||
evaluateRule(parsed, { flagName: existing.name, tenantId: "ctx_probe", userId: "ctx_probe" });
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : t("featureFlags.engine.errors.invalidRule");
|
||||
return Response.json({ error: message }, { status: 400 });
|
||||
} catch {
|
||||
return Response.json({ intent, errorKey: "featureFlags.engine.errors.invalidRule" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
}
|
||||
// Prisma's JsonValue type rejects our typed TargetingRule narrowing — cast
|
||||
@@ -227,9 +236,9 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const rulesForDb = (parsed ?? null) as unknown as never;
|
||||
const auditOldRules = (existing.rules ?? null) as unknown as never;
|
||||
const auditNewRules = (parsed ?? null) as unknown as never;
|
||||
await db.$transaction([
|
||||
db.featureFlag.update({ where: { id }, data: { rules: rulesForDb } }),
|
||||
db.featureFlagAudit.create({
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.featureFlag.update({ where: { id }, data: { rules: rulesForDb } });
|
||||
await tx.featureFlagAudit.create({
|
||||
data: {
|
||||
flagId: id,
|
||||
actorUserId,
|
||||
@@ -237,21 +246,23 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
oldValue: { rules: auditOldRules } as unknown as never,
|
||||
newValue: { rules: auditNewRules } as unknown as never,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
await invalidateFlagCache(existing.name);
|
||||
return Response.json({ ok: true });
|
||||
return Response.json({ intent, ok: true, messageKey: "featureFlags.engine.toast.rulesSaved" } satisfies ActionData);
|
||||
}
|
||||
|
||||
return Response.json({ error: t("featureFlags.engine.errors.unknownIntent") }, { status: 400 });
|
||||
return Response.json({ intent, errorKey: "featureFlags.engine.errors.unknownIntent" } satisfies ActionData, { status: 400 });
|
||||
};
|
||||
|
||||
export default function FeatureFlagsEngineRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
useSaveToast(fetcher.data);
|
||||
|
||||
function submitToggle(flagId: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
@@ -270,7 +281,7 @@ export default function FeatureFlagsEngineRoute() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="mb-12 w-full space-y-5 px-6 py-6 mobile:px-4">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-lg leading-6 font-medium">{t("featureFlags.engine.title")}</h3>
|
||||
<p className="text-muted-foreground text-sm">{t("featureFlags.engine.description")}</p>
|
||||
|
||||
+5
-1
@@ -85,7 +85,11 @@ describe("admin feature flag engine rule validation", () => {
|
||||
})) as Response;
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: "rule.op must be AND, OR, or NOT." });
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
intent: "save-rules",
|
||||
errorKey: "featureFlags.engine.errors.invalidCompositeOperator",
|
||||
errorValues: { path: "rule" },
|
||||
});
|
||||
expect(mocks.transaction).not.toHaveBeenCalled();
|
||||
expect(mocks.invalidateFlagCache).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
+11
@@ -7,6 +7,8 @@ const repoRoot = process.cwd();
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/feature-flags/index.tsx",
|
||||
"apps/web/app/routes/admin/feature-flags/flags.tsx",
|
||||
"apps/web/app/routes/admin/feature-flags/flags/new.tsx",
|
||||
"apps/web/app/routes/admin/feature-flags/flags/$id.tsx",
|
||||
"apps/web/app/routes/admin/feature-flags/engine.tsx",
|
||||
"apps/web/app/modules/featureFlags/components/FeatureFlagForm.tsx",
|
||||
];
|
||||
@@ -30,6 +32,15 @@ describe("feature flags i18n", () => {
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
});
|
||||
|
||||
it("does not expose persistence errors to administrators", () => {
|
||||
const sources = sourceFiles.map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
|
||||
|
||||
expect(sources).toContain("featureFlags.errors.createFailed");
|
||||
expect(sources).toContain("featureFlags.errors.updateFailed");
|
||||
expect(sources).toContain("featureFlags.errors.deleteFailed");
|
||||
expect(sources).not.toContain("error: e.message");
|
||||
});
|
||||
|
||||
it("does not keep raw visible admin labels in source", () => {
|
||||
const forbidden = [
|
||||
"`All ",
|
||||
|
||||
+47
-4
@@ -3,11 +3,44 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn(async () => undefined) }));
|
||||
vi.mock("~/modules/featureFlags/db/featureFlags.db.server", () => ({ getAllFeatureFlags: vi.fn(async () => [{ enabled: true }, { enabled: false }]) }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: { analyticsEvent: { count: vi.fn(async () => 2) } } }));
|
||||
vi.mock("~/modules/featureFlags/db/featureFlags.db.server", () => ({
|
||||
getAllFeatureFlags: vi.fn(async () => [
|
||||
{
|
||||
id: "flag_1",
|
||||
name: "maintenance",
|
||||
description: "Maintenance",
|
||||
enabled: true,
|
||||
scope: "global",
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
filters: [],
|
||||
_count: { events: 2 },
|
||||
rules: null,
|
||||
variants: [],
|
||||
parentFlagId: null,
|
||||
enabledFrom: null,
|
||||
enabledUntil: null,
|
||||
},
|
||||
{
|
||||
id: "flag_2",
|
||||
name: "tenant-api",
|
||||
description: "Tenant API",
|
||||
enabled: false,
|
||||
scope: "tenant",
|
||||
tenantId: "tenant_1",
|
||||
userId: null,
|
||||
filters: [{ id: "filter_1" }],
|
||||
_count: { events: 0 },
|
||||
rules: { type: "boolean", value: true },
|
||||
variants: [],
|
||||
parentFlagId: null,
|
||||
enabledFrom: null,
|
||||
enabledUntil: null,
|
||||
},
|
||||
]),
|
||||
}));
|
||||
|
||||
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
describe("admin feature flag route permissions", () => {
|
||||
@@ -37,6 +70,16 @@ describe("admin feature flag route permissions", () => {
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(request, "admin.featureFlags.view");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getAllFeatureFlags).mock.invocationCallOrder[0]);
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(db.analyticsEvent.count).mock.invocationCallOrder[0]);
|
||||
});
|
||||
|
||||
it("returns the feature flag studio summary VM", async () => {
|
||||
const request = new Request("https://admin.example.com/feature-flags");
|
||||
const { loader } = await import("./index");
|
||||
|
||||
const response = await loader({ request, params: {}, context: {} } as never);
|
||||
const data = await response.json();
|
||||
|
||||
expect(data.vm.status).toBe("ready");
|
||||
expect(data.vm.data.summary).toMatchObject({ flagsTotal: 2, flagsEnabled: 1, triggersTotal: 2, highRiskFlags: 1 });
|
||||
});
|
||||
});
|
||||
+21
-13
@@ -1,10 +1,15 @@
|
||||
import { ActionFunctionArgs, LoaderFunction, MetaFunction, useLoaderData } from "react-router";
|
||||
import { ActionFunctionArgs, LoaderFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { FeatureFlag } from "@hivegrid/db/prisma-browser";
|
||||
import { FeatureFlagWithEvents, getFeatureFlag, getFeatureFlagsWithEvents, updateFeatureFlag } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import {
|
||||
FeatureFlagWithEventCount,
|
||||
getFeatureFlag,
|
||||
getLegacyFeatureFlagsWithEventCounts,
|
||||
updateFeatureFlag,
|
||||
} from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, Outlet, useSearchParams, useSubmit } from "react-router";
|
||||
import { Outlet, useSearchParams, useSubmit } from "react-router";
|
||||
import TabsWithIcons from "~/components/ui/tabs/TabsWithIcons";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
@@ -14,28 +19,28 @@ import InputCheckbox from "~/components/ui/input/InputCheckbox";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: FeatureFlagWithEvents[];
|
||||
items: FeatureFlagWithEventCount[];
|
||||
};
|
||||
type ActionData = { intent: "toggle"; errorKey?: string };
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("featureFlags.title")} | ${process.env.APP_NAME}`,
|
||||
items: await getFeatureFlagsWithEvents({ enabled: undefined }),
|
||||
items: await getLegacyFeatureFlagsWithEventCounts({ enabled: undefined }),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
export const action = async ({ request, params: _params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
@@ -46,16 +51,16 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
const flag = await getFeatureFlag({ id });
|
||||
if (!flag) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 400 });
|
||||
return Response.json({ intent: "toggle", errorKey: "shared.notFound" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
await updateFeatureFlag(id, {
|
||||
enabled,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.success") });
|
||||
return Response.json({ intent: "toggle" } satisfies ActionData);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
return Response.json({ intent: "toggle", errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -64,8 +69,11 @@ export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.ti
|
||||
export default function CampaignsListRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
useSaveToast(actionData);
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
function countStatus(enabled?: boolean) {
|
||||
@@ -94,7 +102,7 @@ export default function CampaignsListRoute() {
|
||||
return data.items;
|
||||
}
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="mb-12 w-full space-y-5 px-6 py-6 mobile:px-4">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex-grow">
|
||||
<TabsWithIcons
|
||||
@@ -155,7 +163,7 @@ export default function CampaignsListRoute() {
|
||||
</div>
|
||||
<div className="text-muted-foreground flex items-center space-x-2 text-sm">
|
||||
<span className="lowercase">
|
||||
{i.events.length} {t("featureFlags.triggers")}
|
||||
{i._count.events} {t("featureFlags.triggers")}
|
||||
</span>
|
||||
<div>•</div>
|
||||
<div>
|
||||
|
||||
+26
-8
@@ -1,8 +1,9 @@
|
||||
import { FeatureFlag, FeatureFlagFilter, Role, Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useSubmit } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { groupUniqueVisitorsBy } from "~/modules/analytics/db/analyticsUniqueVisitors.db.server";
|
||||
@@ -17,6 +18,11 @@ import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
|
||||
const logger = createScopedLogger("admin.feature-flags.edit");
|
||||
|
||||
type LoaderData = {
|
||||
item: FeatureFlag & { filters: FeatureFlagFilter[] };
|
||||
@@ -99,20 +105,27 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
try {
|
||||
await updateFeatureFlag(item.id, { name, description, filters });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
} catch (error: unknown) {
|
||||
logger.error({ event: "admin.feature_flags.update_failed", ...toSafeErrorLog(error) }, "Admin feature flag update failed");
|
||||
return Response.json({ error: t("featureFlags.errors.updateFailed") }, { status: 500 });
|
||||
}
|
||||
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("feature-flags/flags", { mode: "host-aware" })}?toast=${encodeURIComponent("featureFlags.toast.updated")}`);
|
||||
} else if (action === "delete") {
|
||||
await deleteFeatureFlag(item.id);
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
try {
|
||||
await deleteFeatureFlag(item.id);
|
||||
} catch (error: unknown) {
|
||||
logger.error({ event: "admin.feature_flags.delete_failed", ...toSafeErrorLog(error) }, "Admin feature flag deletion failed");
|
||||
return Response.json({ error: t("featureFlags.errors.deleteFailed") }, { status: 500 });
|
||||
}
|
||||
return redirect(`${adminPath("feature-flags/flags", { mode: "host-aware" })}?toast=${encodeURIComponent("featureFlags.toast.deleted")}`);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
@@ -134,7 +147,12 @@ export default function () {
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Link to={adminPath(`feature-flags/${encodeURIComponent(data.item.key ?? data.item.name)}/bulk`, { mode: "host-aware" })}>
|
||||
<Button variant="tertiary">{t("featureFlags.rollout.openBulk")}</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<FeatureFlagForm item={data.item} metadata={data.metadata} onDelete={onDelete} />
|
||||
</div>
|
||||
);
|
||||
|
||||
+11
-6
@@ -1,7 +1,7 @@
|
||||
import { Role, Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { groupUniqueVisitorsBy } from "~/modules/analytics/db/analyticsUniqueVisitors.db.server";
|
||||
@@ -15,6 +15,10 @@ import { UserSimple, adminGetAllUsers } from "~/utils/db/users.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
|
||||
const logger = createScopedLogger("admin.feature-flags.create");
|
||||
|
||||
type LoaderData = {
|
||||
metadata: {
|
||||
@@ -33,7 +37,7 @@ type LoaderData = {
|
||||
};
|
||||
};
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const loader = async ({ request, params: _params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const metadata = {
|
||||
users: (await adminGetAllUsers()).items,
|
||||
@@ -60,7 +64,7 @@ type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
export const action = async ({ request, params: _params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
@@ -90,11 +94,12 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
try {
|
||||
await createFeatureFlag({ name, description, enabled: false, filters });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
} catch (error: unknown) {
|
||||
logger.error({ event: "admin.feature_flags.create_failed", ...toSafeErrorLog(error) }, "Admin feature flag creation failed");
|
||||
return Response.json({ error: t("featureFlags.errors.createFailed") }, { status: 500 });
|
||||
}
|
||||
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("feature-flags/flags", { mode: "host-aware" })}?toast=${encodeURIComponent("featureFlags.toast.created")}`);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
+188
-40
@@ -1,31 +1,43 @@
|
||||
import { useLoaderData } from "react-router";
|
||||
import { Link, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { FeatherAlertTriangle, FeatherArrowRight, FeatherGitBranch, FeatherShieldCheck, FeatherToggleLeft, FeatherZap } from "@subframe/core";
|
||||
import { buildFeatureFlagStudioVM, type FeatureFlagStudioData, type FeatureFlagStudioFlag, type FeatureFlagStudioRisk } from "@hivegrid/view-models";
|
||||
import type React from "react";
|
||||
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
|
||||
import { BannerAlert } from "~/ui/components/BannerAlert";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
import { StatsCard } from "~/ui/components/StatsCard";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
type LoaderData = {
|
||||
summary: {
|
||||
flagsTotal: number;
|
||||
flagsEnabled: number;
|
||||
triggersTotal: number;
|
||||
};
|
||||
vm: ReturnType<typeof buildFeatureFlagStudioVM>;
|
||||
};
|
||||
export const loader = async ({ request }: { request: Request }) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const items = await getAllFeatureFlags();
|
||||
const triggersTotal = await db.analyticsEvent.count({
|
||||
where: { featureFlagId: { not: null } },
|
||||
});
|
||||
const data: LoaderData = {
|
||||
summary: {
|
||||
flagsTotal: items.length,
|
||||
flagsEnabled: items.filter((f) => f.enabled).length,
|
||||
triggersTotal,
|
||||
},
|
||||
vm: buildFeatureFlagStudioVM({
|
||||
flags: items.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
enabled: item.enabled,
|
||||
scope: item.scope,
|
||||
tenantId: item.tenantId,
|
||||
userId: item.userId,
|
||||
filtersCount: item.filters.length,
|
||||
eventsCount: item._count.events,
|
||||
rulesConfigured: item.rules !== null,
|
||||
variantsCount: Array.isArray(item.variants) ? item.variants.length : 0,
|
||||
parentFlagId: item.parentFlagId,
|
||||
enabledFrom: item.enabledFrom?.toISOString() ?? null,
|
||||
enabledUntil: item.enabledUntil?.toISOString() ?? null,
|
||||
})),
|
||||
}),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
@@ -34,31 +46,167 @@ export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const vm = data.vm.status === "ready" ? data.vm.data : null;
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-lg font-medium leading-6">{t("shared.overview")}</h3>
|
||||
<div className="mobile:px-4 mb-12 w-full space-y-5 px-6 py-6">
|
||||
<div className="border-border-default flex flex-wrap items-start justify-between gap-3 border-b pb-5">
|
||||
<div className="flex flex-col items-start">
|
||||
<h3 className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("featureFlags.studio.title")}</h3>
|
||||
<p className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("featureFlags.studio.description")}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Link to={adminPath("feature-flags/flags", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("featureFlags.studio.actions.openFlags")}
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to={adminPath("feature-flags/engine", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("featureFlags.studio.actions.openEngine")}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-2">
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow ">
|
||||
<dt className="text-muted-foreground flex items-center space-x-2 truncate text-xs font-medium uppercase">
|
||||
<ColorBadge color={Colors.GREEN} />
|
||||
<div>{t("featureFlags.plural")}</div>
|
||||
</dt>
|
||||
<dd className="mt-1 flex items-baseline space-x-1 truncate text-2xl font-semibold">
|
||||
<div>
|
||||
{formatters.number(data.summary.flagsEnabled)}/{formatters.number(data.summary.flagsTotal)}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs font-normal lowercase">{t("featureFlags.enabled")}</div>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow ">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("featureFlags.triggers")}</div>
|
||||
</dt>
|
||||
<dd className="mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.triggersTotal)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
{vm ? <FeatureFlagStudio data={vm} formatNumber={formatters.number} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FeatureFlagStudio({ data, formatNumber }: { data: FeatureFlagStudioData; formatNumber: (value: number) => string }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="mobile:grid-cols-1 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<StudioKpi
|
||||
title={t("featureFlags.studio.summary.enabled")}
|
||||
value={`${formatNumber(data.summary.flagsEnabled)}/${formatNumber(data.summary.flagsTotal)}`}
|
||||
icon={<FeatherToggleLeft />}
|
||||
tone={data.summary.flagsEnabled > 0 ? "success" : "neutral"}
|
||||
/>
|
||||
<StudioKpi
|
||||
title={t("featureFlags.studio.summary.targeted")}
|
||||
value={formatNumber(data.summary.targetedFlags)}
|
||||
icon={<FeatherGitBranch />}
|
||||
tone={data.summary.targetedFlags > 0 ? "success" : "warning"}
|
||||
/>
|
||||
<StudioKpi title={t("featureFlags.studio.summary.triggers")} value={formatNumber(data.summary.triggersTotal)} icon={<FeatherZap />} tone="neutral" />
|
||||
<StudioKpi
|
||||
title={t("featureFlags.studio.summary.highRisk")}
|
||||
value={formatNumber(data.summary.highRiskFlags)}
|
||||
icon={<FeatherAlertTriangle />}
|
||||
tone={data.summary.highRiskFlags > 0 ? "danger" : "success"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{data.summary.highRiskFlags > 0 ? (
|
||||
<BannerAlert type="warning" fillContainer>
|
||||
{t("featureFlags.studio.riskBanner.title")} — {t("featureFlags.studio.riskBanner.body")}
|
||||
</BannerAlert>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(320px,0.7fr)]">
|
||||
<TopFlagsCard flags={data.topFlags} />
|
||||
<RolloutReadinessCard data={data} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StudioKpi({ title, value, icon, tone }: { title: string; value: string; icon: React.ReactNode; tone: "success" | "warning" | "danger" | "neutral" }) {
|
||||
return (
|
||||
<StatsCard
|
||||
label={title}
|
||||
value={value}
|
||||
trend={tone === "success" ? "positive" : tone === "danger" || tone === "warning" ? "negative" : "neutral"}
|
||||
percentage=""
|
||||
comparisonText=""
|
||||
icon={icon}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TopFlagsCard({ flags }: { flags: readonly FeatureFlagStudioFlag[] }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex w-full flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("featureFlags.studio.topFlags.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("featureFlags.studio.topFlags.description")}
|
||||
</span>
|
||||
</div>
|
||||
{flags.length === 0 ? (
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("featureFlags.empty.description")}</span>
|
||||
) : (
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
{flags.map((flag) => (
|
||||
<div
|
||||
key={flag.id}
|
||||
className="border-border-default bg-surface-neutral-primary flex w-full flex-col items-start gap-2 rounded-md border border-solid px-4 py-3"
|
||||
>
|
||||
<div className="flex w-full flex-wrap items-start justify-between gap-2">
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate">{flag.description}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary truncate">{flag.name}</span>
|
||||
</div>
|
||||
<BadgeFeedback farbe={riskTone(flag.risk)} size="small">
|
||||
{t(flag.riskLabelKey)}
|
||||
</BadgeFeedback>
|
||||
</div>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("featureFlags.studio.topFlags.meta", {
|
||||
triggers: flag.eventsCount,
|
||||
filters: flag.filtersCount,
|
||||
scope: flag.scope ?? "global",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function RolloutReadinessCard({ data }: { data: FeatureFlagStudioData }) {
|
||||
const { t } = useTranslation();
|
||||
const items = [
|
||||
{ label: t("featureFlags.studio.readiness.scoped"), value: data.summary.scopedFlags },
|
||||
{ label: t("featureFlags.studio.readiness.scheduled"), value: data.summary.scheduledFlags },
|
||||
{ label: t("featureFlags.studio.readiness.disabled"), value: data.summary.flagsDisabled },
|
||||
];
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<span className="text-heading- font-heading- text-icon-neutral-tertiary">
|
||||
<FeatherShieldCheck />
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("featureFlags.studio.readiness.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("featureFlags.studio.readiness.description")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
{items.map((item) => (
|
||||
<div
|
||||
key={item.label}
|
||||
className="border-border-default bg-surface-neutral-primary flex w-full items-center justify-between gap-3 rounded-md border border-solid px-4 py-2"
|
||||
>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{item.label}</span>
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">{item.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function riskTone(risk: FeatureFlagStudioRisk): "subtle-negative" | "subtle-warning" | "subtle-positive" {
|
||||
if (risk === "high") return "subtle-negative";
|
||||
if (risk === "medium") return "subtle-warning";
|
||||
return "subtle-positive";
|
||||
}
|
||||
+15
-25
@@ -4,33 +4,32 @@ import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { deleteAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type ActionData = {
|
||||
deleteError?: string;
|
||||
deleteSuccess?: boolean;
|
||||
intent: "delete-all";
|
||||
ok?: true;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "delete-all") {
|
||||
await db.analyticsEvent.deleteMany({ where: { featureFlagId: { not: null } } });
|
||||
await db.featureFlag.deleteMany({});
|
||||
return Response.json({
|
||||
deleteSuccess: true,
|
||||
});
|
||||
try {
|
||||
await deleteAllFeatureFlags();
|
||||
return Response.json({ intent: "delete-all", ok: true, messageKey: "featureFlags.danger.toast.reset" } satisfies ActionData);
|
||||
} catch {
|
||||
return Response.json({ intent: "delete-all", errorKey: "featureFlags.danger.errors.resetFailed" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({
|
||||
error: t("shared.invalidForm"),
|
||||
});
|
||||
return Response.json({ intent: "delete-all", errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -38,6 +37,8 @@ export default function AdminAnalyticsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
|
||||
useSaveToast(actionData);
|
||||
return (
|
||||
<>
|
||||
<IndexPageLayout>
|
||||
@@ -55,17 +56,6 @@ export default function AdminAnalyticsOverviewRoute() {
|
||||
{t("featureFlags.danger.reset.title")}
|
||||
</ButtonPrimary>
|
||||
|
||||
{actionData?.deleteSuccess ? (
|
||||
<p className="py-2 text-xs text-green-500" role="alert">
|
||||
{t("analytics.deleted")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{actionData?.deleteError ? (
|
||||
<p className="py-2 text-xs text-rose-500" role="alert">
|
||||
{actionData.deleteError}
|
||||
</p>
|
||||
) : null}
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import { redirectLegacyAdminRoute } from "~/utils/navigation/legacyAdminRouteRedirect.server";
|
||||
|
||||
export const loader = ({ request }: LoaderFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "system");
|
||||
@@ -1,54 +0,0 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, Outlet } from "react-router";
|
||||
import FeedbackIcon from "~/components/ui/icons/FeedbackIcon";
|
||||
import FeedbackIconFilled from "~/components/ui/icons/FeedbackIconFilled";
|
||||
import IncreaseIcon from "~/components/ui/icons/crm/IncreaseIcon";
|
||||
import IncreaseIconFilled from "~/components/ui/icons/crm/IncreaseIconFilled";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const data: LoaderData = {
|
||||
title: i18nT("helpDesk.metaTitle", { appName: process.env.APP_NAME }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
href: adminPath("help-desk", { mode: "host-aware" }),
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
exact: true,
|
||||
},
|
||||
{
|
||||
name: t("helpDesk.tickets.plural"),
|
||||
href: adminPath("help-desk/tickets", { mode: "host-aware" }),
|
||||
icon: <FeedbackIcon className="h-5 w-5" />,
|
||||
iconSelected: <FeedbackIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("feedback.object"),
|
||||
href: adminPath("help-desk/feedback", { mode: "host-aware" }),
|
||||
icon: <FeedbackIcon className="h-5 w-5" />,
|
||||
iconSelected: <FeedbackIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
summary: {
|
||||
feedbackTotal: number;
|
||||
ticketsTotal: number;
|
||||
};
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params, adminOnly: true });
|
||||
const data: LoaderData = {
|
||||
summary: {
|
||||
feedbackTotal: await db.feedback.count(),
|
||||
ticketsTotal: await db.supportTicket.count(),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-lg font-medium leading-6">{t("shared.overview")}</h3>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-2">
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("feedback.plural")}</div>
|
||||
</dt>
|
||||
<dd className="mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.feedbackTotal, { maximumFractionDigits: 0 })}</dd>
|
||||
</div>
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("helpDesk.tickets.plural")}</div>
|
||||
</dt>
|
||||
<dd className="mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.ticketsTotal, { maximumFractionDigits: 0 })}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getAllSupportTickets, SupportTicketWithDetails } from "~/modules/helpDesk/db/supportTickets.db.server";
|
||||
import { redactFeedbackText } from "~/modules/helpDesk/services/FeedbackRedaction";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
items: SupportTicketWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params, adminOnly: true });
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "tenantId",
|
||||
title: "models.tenant.object",
|
||||
options: [
|
||||
{ value: "null", name: "{null}" },
|
||||
...(await adminGetAllTenantsIdsAndNames()).map((item) => ({ value: item.id, name: item.name })),
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: "models.user.object",
|
||||
options: [
|
||||
{ value: "null", name: "{null}" },
|
||||
...(await adminGetAllUsersNames()).map((item) => ({ value: item.id, name: item.email })),
|
||||
],
|
||||
},
|
||||
];
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
return Response.json({
|
||||
...(await getAllSupportTickets({ filters, filterableProperties, pagination })),
|
||||
filterableProperties,
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export default function HelpDeskTicketsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<EditPageLayout title={t("helpDesk.tickets.plural")}>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.dateTime(item.createdAt, { timeStyle: "medium" }),
|
||||
},
|
||||
{
|
||||
name: "subject",
|
||||
title: t("helpDesk.tickets.subject"),
|
||||
value: (item) => redactFeedbackText(item.subject),
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
title: t("helpDesk.tickets.status"),
|
||||
value: (item) => item.status,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: t("helpDesk.tickets.source"),
|
||||
value: (item) => item.source,
|
||||
},
|
||||
{
|
||||
name: "message",
|
||||
title: t("feedback.message"),
|
||||
value: (item) => <div className="max-w-xl truncate">{redactFeedbackText(item.message)}</div>,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
/** R-LEADS compatibility redirect for the retired legacy lead board. */
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export const loader = (_args: LoaderFunctionArgs) => redirect(adminPath("leads", { mode: "host-aware" }));
|
||||
|
||||
export default function RetiredIncomingLeadsBoard(): null {
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import { redirectLegacyAdminRoute } from "~/utils/navigation/legacyAdminRouteRedirect.server";
|
||||
|
||||
export const loader = ({ request }: LoaderFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "system/jobs");
|
||||
|
||||
export const action = ({ request }: ActionFunctionArgs) =>
|
||||
redirectLegacyAdminRoute(request, "system/jobs");
|
||||
+2
-2
@@ -8,13 +8,13 @@ import DocsIcon from "~/components/ui/icons/entities/DocsIcon";
|
||||
import DocsIconFilled from "~/components/ui/icons/entities/DocsIconFilled";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const loader = async ({ request: _request, params: _params }: LoaderFunctionArgs) => {
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: i18nT("knowledgeBase.authoring.metaTitle") }],
|
||||
};
|
||||
|
||||
+3
-1
@@ -136,7 +136,9 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
userId: userInfo.userId,
|
||||
position: "last",
|
||||
});
|
||||
return redirect(adminPath(`knowledge-base/bases/${kb.slug}/articles/${KnowledgeBaseUtils.defaultLanguage}/${created.id}/edit`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${kb.slug}/articles/${KnowledgeBaseUtils.defaultLanguage}/${created.id}/edit`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminArticles.toast.created")}`
|
||||
);
|
||||
} else if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
|
||||
+4
-2
@@ -1,5 +1,5 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
|
||||
import { Form, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
@@ -83,7 +83,9 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.articleNotFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
return redirect(adminPath(`knowledge-base/bases/${params.slug}/articles/${params.lang}/${params.id}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${params.slug}/articles/${params.lang}/${params.id}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminArticles.toast.draftSaved")}`
|
||||
);
|
||||
}
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.invalidAction") }, { status: 400 });
|
||||
};
|
||||
|
||||
+16
-14
@@ -13,11 +13,10 @@ import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsServ
|
||||
import KnowledgeBaseUtils from "~/modules/knowledgeBase/utils/KnowledgeBaseUtils";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
type LoaderData = {
|
||||
@@ -53,12 +52,14 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
intent?: "publish" | "unpublish";
|
||||
ok?: true;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.kb.update");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
@@ -68,13 +69,14 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
});
|
||||
const item = await getKbArticleByIdInKnowledgeBase({ id: params.id!, knowledgeBaseId: knowledgeBase.id, language: params.lang! });
|
||||
if (!item) {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.articleNotFound") }, { status: 400 });
|
||||
return Response.json({ errorKey: "knowledgeBase.admin.errors.articleNotFound" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
if (action === "togglePublish") {
|
||||
if (!item.categoryId) {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.articleCategoryRequired") }, { status: 400 });
|
||||
return Response.json({ errorKey: "knowledgeBase.admin.errors.articleCategoryRequired" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const intent = item.publishedAt ? "unpublish" : "publish";
|
||||
let publishedAt = item.publishedAt;
|
||||
let contentPublished = item.contentPublished;
|
||||
if (item.publishedAt) {
|
||||
@@ -94,12 +96,16 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
}
|
||||
);
|
||||
if (result.count !== 1) {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.articleNotFound") }, { status: 404 });
|
||||
return Response.json({ intent, errorKey: "knowledgeBase.admin.errors.articleNotFound" } satisfies ActionData, { status: 404 });
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
return Response.json({
|
||||
intent,
|
||||
ok: true,
|
||||
messageKey: intent === "publish" ? "knowledgeBase.adminArticles.toast.published" : "knowledgeBase.adminArticles.toast.unpublished",
|
||||
} satisfies ActionData);
|
||||
}
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.invalidAction") }, { status: 400 });
|
||||
return Response.json({ errorKey: "knowledgeBase.admin.errors.invalidAction" } satisfies ActionData, { status: 400 });
|
||||
};
|
||||
|
||||
export default function () {
|
||||
@@ -110,11 +116,7 @@ export default function () {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
useSaveToast(actionData);
|
||||
|
||||
return (
|
||||
<Form method="post" className="space-y-6">
|
||||
|
||||
+6
-2
@@ -172,14 +172,18 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return Response.json({ error: t("knowledgeBase.articleSettings.errors.articleNotFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
return redirect(adminPath(`knowledge-base/bases/${knowledgeBase.slug}/articles/${language}/${item.id}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${knowledgeBase.slug}/articles/${language}/${item.id}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminArticles.toast.settingsSaved")}`
|
||||
);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.kb.delete");
|
||||
const result = await deleteKnowledgeBaseArticleInKnowledgeBase({ id: item.id, knowledgeBaseId: routeKnowledgeBase.id, language: params.lang! });
|
||||
if (result.count !== 1) {
|
||||
return Response.json({ error: t("knowledgeBase.articleSettings.errors.articleNotFound") }, { status: 404 });
|
||||
}
|
||||
return redirect(adminPath(`knowledge-base/bases/${routeKnowledgeBase.slug}/articles/${params.lang}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${routeKnowledgeBase.slug}/articles/${params.lang}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminArticles.toast.deleted")}`
|
||||
);
|
||||
}
|
||||
return Response.json({ error: t("knowledgeBase.articleSettings.errors.invalidAction") }, { status: 400 });
|
||||
};
|
||||
|
||||
+6
-2
@@ -136,7 +136,9 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
userId: userInfo.userId,
|
||||
position: "last",
|
||||
});
|
||||
return redirect(adminPath(`knowledge-base/bases/${kb.slug}/articles/${params.lang}/${created.id}/edit`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${kb.slug}/articles/${params.lang}/${created.id}/edit`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminArticles.toast.created")}`
|
||||
);
|
||||
} else if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
@@ -164,7 +166,9 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
try {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const item = await KnowledgeBaseService.duplicateArticle({ kb, language: params.lang!, articleId: id });
|
||||
return redirect(adminPath(`knowledge-base/bases/${kb.slug}/articles/${params.lang}/${item.id}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${kb.slug}/articles/${params.lang}/${item.id}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminArticles.toast.duplicated")}`
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
|
||||
+11
-5
@@ -45,6 +45,7 @@ import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsServ
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
knowledgeBase: KnowledgeBaseDto;
|
||||
@@ -71,6 +72,9 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
intent?: string;
|
||||
ok?: true;
|
||||
messageKey?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
@@ -127,7 +131,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
if (result.count !== 1) {
|
||||
return Response.json({ error: t("knowledgeBase.adminCategories.errors.categoryNotFound") }, { status: 404 });
|
||||
}
|
||||
return Response.json({ deleted: true });
|
||||
return Response.json({ intent: "delete-category", ok: true, messageKey: "knowledgeBase.adminCategories.toast.deleted" } satisfies ActionData);
|
||||
} else if (action === "delete-section") {
|
||||
await verifyUserHasPermission(request, "admin.kb.delete");
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
@@ -144,7 +148,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
if (result.count !== 1) {
|
||||
return Response.json({ error: t("knowledgeBase.adminCategories.errors.sectionNotFound") }, { status: 404 });
|
||||
}
|
||||
return Response.json({ deleted: true });
|
||||
return Response.json({ intent: "delete-section", ok: true, messageKey: "knowledgeBase.adminCategories.toast.sectionDeleted" } satisfies ActionData);
|
||||
} else if (action === "delete-article") {
|
||||
await verifyUserHasPermission(request, "admin.kb.delete");
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
@@ -156,13 +160,13 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
if (result.count !== 1) {
|
||||
return Response.json({ error: t("knowledgeBase.adminCategories.errors.articleNotFound") }, { status: 404 });
|
||||
}
|
||||
return Response.json({ deleted: true });
|
||||
return Response.json({ intent: "delete-article", ok: true, messageKey: "knowledgeBase.adminArticles.toast.deleted" } satisfies ActionData);
|
||||
} else if (action === "duplicate") {
|
||||
await verifyUserHasPermission(request, "admin.kb.create");
|
||||
try {
|
||||
const categoryId = form.get("id")?.toString() ?? "";
|
||||
await KnowledgeBaseService.duplicateCategory({ kb, language: params.lang!, categoryId });
|
||||
return Response.json({ duplicated: true });
|
||||
return Response.json({ intent: "duplicate-category", ok: true, messageKey: "knowledgeBase.adminCategories.toast.duplicated" } satisfies ActionData);
|
||||
} catch (e: unknown) {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
@@ -192,7 +196,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
initialSlug: slug.length > 0 ? slug : undefined,
|
||||
position: position as any,
|
||||
});
|
||||
return Response.json({ created: true });
|
||||
return Response.json({ intent: "create-article", ok: true, messageKey: "knowledgeBase.adminArticles.toast.created" } satisfies ActionData);
|
||||
} catch (e: unknown) {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
@@ -242,6 +246,8 @@ export default function () {
|
||||
const submit = useSubmit();
|
||||
const location = useLocation();
|
||||
|
||||
useSaveToast(actionData?.ok ? actionData : undefined);
|
||||
|
||||
const [toggledCategories, setToggledCategories] = useState<string[]>([]);
|
||||
|
||||
const confirmDeleteCategory = useRef<RefConfirmModal>(null);
|
||||
|
||||
+6
-2
@@ -90,14 +90,18 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
|
||||
return redirect(adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminCategories.toast.sectionSaved")}`
|
||||
);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.kb.delete");
|
||||
const result = await deleteKnowledgeBaseCategorySectionInCategory({ id: item.id, categoryId: category.id });
|
||||
if (result.count !== 1) {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.sectionNotFound") }, { status: 404 });
|
||||
}
|
||||
return redirect(adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminCategories.toast.sectionDeleted")}`
|
||||
);
|
||||
} else if (action === "set-orders") {
|
||||
await verifyUserHasPermission(request, "admin.kb.update");
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
|
||||
+3
-1
@@ -69,7 +69,9 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
|
||||
return redirect(adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminCategories.toast.sectionCreated")}`
|
||||
);
|
||||
} else {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
+6
-2
@@ -93,14 +93,18 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
|
||||
return redirect(adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminCategories.toast.saved")}`
|
||||
);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.kb.delete");
|
||||
const result = await deleteKnowledgeBaseCategoryInKnowledgeBase({ id: item.id, knowledgeBaseId: knowledgeBase.id, language: params.lang! });
|
||||
if (result.count !== 1) {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.categoryNotFound") }, { status: 404 });
|
||||
}
|
||||
return redirect(adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminCategories.toast.deleted")}`
|
||||
);
|
||||
} else if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
|
||||
+3
-1
@@ -77,7 +77,9 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
|
||||
return redirect(adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath(`knowledge-base/bases/${params.slug}/categories/${params.lang}`, { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminCategories.toast.created")}`
|
||||
);
|
||||
} else {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
+28
-17
@@ -1,4 +1,4 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Link, useNavigate, useOutlet, useParams, useSearchParams, useSubmit } from "react-router";
|
||||
import TabsWithIcons from "~/components/ui/tabs/TabsWithIcons";
|
||||
@@ -25,12 +25,14 @@ import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { absoluteAppRootPath, isAbsoluteHttpUrl, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { useSaveToast, type SaveActionResult } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: KnowledgeBaseDto[];
|
||||
template: KnowledgeBasesTemplateDto;
|
||||
};
|
||||
type ActionData = { intent: "toggle"; errorKey?: string };
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.kb.view");
|
||||
const { t } = await getTranslations(request);
|
||||
@@ -44,10 +46,9 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
export const action = async ({ request, params: _params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.kb.view");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "toggle") {
|
||||
@@ -57,16 +58,16 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
const item = await KnowledgeBaseService.getById({ id, request });
|
||||
if (!item) {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.notFound") }, { status: 404 });
|
||||
return Response.json({ intent: "toggle", errorKey: "knowledgeBase.admin.errors.notFound" } satisfies ActionData, { status: 404 });
|
||||
}
|
||||
|
||||
await updateKnowledgeBase(id, {
|
||||
enabled,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("knowledgeBase.admin.success.updated") });
|
||||
return Response.json({ intent: "toggle" } satisfies ActionData);
|
||||
} else {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.invalidForm") }, { status: 400 });
|
||||
return Response.json({ intent: "toggle", errorKey: "knowledgeBase.admin.errors.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -74,6 +75,7 @@ export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
@@ -81,6 +83,10 @@ export default function () {
|
||||
const rootData = useRootData();
|
||||
|
||||
const [selected, setSelected] = useState<KnowledgeBaseDto[]>([]);
|
||||
const [exportResult, setExportResult] = useState<SaveActionResult>();
|
||||
|
||||
useSaveToast(actionData);
|
||||
useSaveToast(exportResult);
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
@@ -114,18 +120,23 @@ export default function () {
|
||||
}
|
||||
|
||||
function onExport() {
|
||||
if (selected.length > 0) {
|
||||
data.template.knowledgeBases = data.template.knowledgeBases.filter((item) => selected.find((i) => i.slug === item.slug));
|
||||
data.template.categories = data.template.categories.filter((item) => selected.find((i) => i.slug === item.knowledgeBaseSlug));
|
||||
data.template.articles = data.template.articles.filter((item) => selected.find((i) => i.slug === item.knowledgeBaseSlug));
|
||||
try {
|
||||
if (selected.length > 0) {
|
||||
data.template.knowledgeBases = data.template.knowledgeBases.filter((item) => selected.find((i) => i.slug === item.slug));
|
||||
data.template.categories = data.template.categories.filter((item) => selected.find((i) => i.slug === item.knowledgeBaseSlug));
|
||||
data.template.articles = data.template.articles.filter((item) => selected.find((i) => i.slug === item.knowledgeBaseSlug));
|
||||
}
|
||||
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data.template, null, "\t"));
|
||||
const downloadAnchorNode = document.createElement("a");
|
||||
downloadAnchorNode.setAttribute("href", dataStr);
|
||||
downloadAnchorNode.setAttribute("download", "kbs.json");
|
||||
document.body.appendChild(downloadAnchorNode);
|
||||
downloadAnchorNode.click();
|
||||
downloadAnchorNode.remove();
|
||||
setExportResult({ ok: true, messageKey: "knowledgeBase.adminBases.toast.exported" });
|
||||
} catch {
|
||||
setExportResult({ errorKey: "knowledgeBase.adminBases.errors.exportFailed" });
|
||||
}
|
||||
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data.template, null, "\t"));
|
||||
const downloadAnchorNode = document.createElement("a");
|
||||
downloadAnchorNode.setAttribute("href", dataStr);
|
||||
downloadAnchorNode.setAttribute("download", "kbs.json");
|
||||
document.body.appendChild(downloadAnchorNode); // required for firefox
|
||||
downloadAnchorNode.click();
|
||||
downloadAnchorNode.remove();
|
||||
}
|
||||
function publicKbUrl(item: KnowledgeBaseDto) {
|
||||
return absolutePublicAppPath(rootData.routing, KnowledgeBaseUtils.getKbUrl({ kb: item, params }));
|
||||
|
||||
+6
-2
@@ -96,12 +96,16 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
|
||||
return redirect(adminPath("knowledge-base/bases", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("knowledge-base/bases", { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminBases.toast.saved")}`
|
||||
);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.kb.delete");
|
||||
try {
|
||||
await KnowledgeBaseService.del(item);
|
||||
return redirect(adminPath("knowledge-base/bases", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("knowledge-base/bases", { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminBases.toast.deleted")}`
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
|
||||
+3
-1
@@ -70,7 +70,9 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
return Response.json({ error: t(getKnowledgeBaseActionErrorKey(e)) }, { status: 400 });
|
||||
}
|
||||
|
||||
return redirect(adminPath("knowledge-base/bases", { mode: "host-aware" }));
|
||||
return redirect(
|
||||
`${adminPath("knowledge-base/bases", { mode: "host-aware" })}?toast=${encodeURIComponent("knowledgeBase.adminBases.toast.created")}`
|
||||
);
|
||||
} else {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
+16
-10
@@ -3,13 +3,13 @@ import { Form, useActionData, useSubmit } from "react-router";
|
||||
import { FormEvent, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
@@ -24,23 +24,28 @@ export const loader = async ({ request }: LoaderFunctionArgs): Promise<LoaderDat
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
intent: "reset-all-data";
|
||||
ok?: true;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.kb.view");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "reset-all-data") {
|
||||
await verifyUserHasPermission(request, "admin.kb.delete");
|
||||
await db.knowledgeBaseCategory.deleteMany({});
|
||||
await db.knowledgeBaseArticle.deleteMany({});
|
||||
await db.knowledgeBase.deleteMany({});
|
||||
return Response.json({ success: t("knowledgeBase.admin.success.resetSuccessful") });
|
||||
try {
|
||||
await db.knowledgeBaseCategory.deleteMany({});
|
||||
await db.knowledgeBaseArticle.deleteMany({});
|
||||
await db.knowledgeBase.deleteMany({});
|
||||
return Response.json({ intent: "reset-all-data", ok: true, messageKey: "knowledgeBase.adminDanger.toast.reset" } satisfies ActionData);
|
||||
} catch {
|
||||
return Response.json({ intent: "reset-all-data", errorKey: "knowledgeBase.admin.errors.actionFailed" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({ error: t("knowledgeBase.admin.errors.invalidForm") }, { status: 400 });
|
||||
return Response.json({ intent: "reset-all-data", errorKey: "knowledgeBase.admin.errors.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -48,6 +53,8 @@ export default function () {
|
||||
const { t } = useTranslation();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
useSaveToast(actionData);
|
||||
|
||||
const submit = useSubmit();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
@@ -89,7 +96,6 @@ export default function () {
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
<ActionResultModal actionData={actionData} showSuccess={false} />
|
||||
<ConfirmModal ref={confirmDelete} onYes={onConfirmedDelete} destructive />
|
||||
</div>
|
||||
);
|
||||
|
||||
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user