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
-43
@@ -1,43 +0,0 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
return {
|
||||
metadata: [{ title: `${t("models.tenant.plural")} | ${process.env.APP_NAME}` }],
|
||||
};
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metadata || [];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("settings.admin.tenants.settingsTitle")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: t("settings.admin.tenants.settingsTitle"),
|
||||
routePath: adminPath("settings/accounts", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Link
|
||||
to={`types`}
|
||||
className="focus:ring-ring border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center focus:outline-hidden focus:ring-2 focus:ring-offset-2"
|
||||
>
|
||||
<span className="text-foreground mt-2 block text-sm font-medium">{t("settings.admin.tenants.types.title")}</span>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-185
@@ -1,185 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useNavigate, useOutlet, useParams, useSubmit } from "react-router";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { getAllTenantTypes, deleteTenantType } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { TenantTypeDto } from "~/application/dtos/tenants/TenantTypeDto";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { getAllTenantsWithoutTypes } from "~/utils/db/tenants.db.server";
|
||||
import clsx from "clsx";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import LockClosedIcon from "~/components/ui/icons/LockClosedIcon";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
types: TenantTypeDto[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accountTypes.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const types: TenantTypeDto[] = await getAllTenantTypes();
|
||||
const subscriptionProducts = await getAllSubscriptionProducts();
|
||||
const allTenants = await getAllTenantsWithoutTypes();
|
||||
types.unshift({
|
||||
title: t("settings.admin.tenants.types.default"),
|
||||
titlePlural: t("settings.admin.tenants.types.default"),
|
||||
description: null,
|
||||
isDefault: true,
|
||||
subscriptionProducts: subscriptionProducts
|
||||
.filter((f) => !f.assignsTenantTypes || f.assignsTenantTypes?.length === 0)
|
||||
.map((f) => ({ id: f.id, title: f.title })),
|
||||
_count: { tenants: allTenants.length },
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: t("settings.admin.tenants.types.metaTitle", { appName: process.env.APP_NAME }),
|
||||
types,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accountTypes.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.accountTypes.delete");
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
await deleteTenantType(id);
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const rootData = useRootData();
|
||||
const submit = useSubmit();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
const params = useParams();
|
||||
|
||||
const [open, setOpen] = useState(!!outlet);
|
||||
useEffect(() => {
|
||||
setOpen(!!outlet);
|
||||
}, [outlet]);
|
||||
|
||||
function onToggleTypeEntity(typeId: string, entityId: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "toggle-entity");
|
||||
form.set("typeId", typeId);
|
||||
form.set("entityId", entityId);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("models.tenantType.plural")}</BackButtonWithTitle>}
|
||||
buttons={
|
||||
<>
|
||||
<Button type="button" variant="default" size="sm" asChild>
|
||||
<Link to="new">{t("shared.new")}</Link>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
{!rootData.appConfiguration.app.features.tenantTypes && (
|
||||
<WarningBanner title={t("shared.warning")} text={t("settings.admin.tenants.types.disabledWarning")} />
|
||||
)}
|
||||
<TableSimple
|
||||
items={data.types}
|
||||
onClickRoute={(idx, item) => item.id ?? undefined}
|
||||
headers={[
|
||||
{
|
||||
name: "name",
|
||||
title: t("shared.title"),
|
||||
value: (item) => (
|
||||
<div className={clsx("flex max-w-xs flex-col truncate", item.id && "cursor-pointer hover:underline")}>
|
||||
<div className="flex items-center space-x-2">
|
||||
{!item.id && <LockClosedIcon className="text-muted-foreground h-4 w-4" />}
|
||||
<div>
|
||||
{item.title} <span className="text-muted-foreground text-xs font-normal">({item.titlePlural})</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-muted-foreground truncate text-sm">{item.description}</div>
|
||||
</div>
|
||||
),
|
||||
href: (item) => item.id ?? undefined,
|
||||
},
|
||||
{
|
||||
name: "inProducts",
|
||||
title: t("models.subscriptionProduct.plural"),
|
||||
className: "w-full",
|
||||
value: (item) => <div className="max-w-md truncate">{item.subscriptionProducts?.map((f) => t(f.title)).join(", ") || t("shared.none")}</div>,
|
||||
},
|
||||
{
|
||||
name: "inTenants",
|
||||
title: t("models.tenant.plural"),
|
||||
value: (item) => item._count?.tenants,
|
||||
href(item) {
|
||||
return item.id ? adminPath(`accounts?typeId=${item.id}`, { mode: "host-aware" }) : "null";
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "isDefault",
|
||||
title: t("shared.default"),
|
||||
value: (item) => (item.isDefault ? <CheckIcon className="h-4 w-4 text-green-500" /> : <XIcon className="text-muted-foreground h-4 w-4" />),
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: "",
|
||||
value: (item) => (
|
||||
<Fragment>
|
||||
{item.id && (
|
||||
<Link to={item.id} className="hover:underline">
|
||||
{t("shared.edit")}
|
||||
</Link>
|
||||
)}
|
||||
</Fragment>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("settings.admin.tenants.types.editTitle") : t("settings.admin.tenants.types.newTitle")}
|
||||
open={open}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-sm"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { TenantTypeForm } from "~/components/core/tenants/types/TenantTypeForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { TenantTypeWithDetails, getTenantType, updateTenantType, deleteTenantType, getTenantTypeByTitle } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: TenantTypeWithDetails;
|
||||
allSubscriptionProducts: SubscriptionProductDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accountTypes.update");
|
||||
const item = await getTenantType(params.id!);
|
||||
if (!item) {
|
||||
return redirect(adminPath("settings/accounts/types", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
allSubscriptionProducts: await getAllSubscriptionProducts(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accountTypes.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
const item = await getTenantType(params.id!);
|
||||
if (!item) {
|
||||
return redirect(adminPath("settings/accounts/types", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
const title = form.get("title")?.toString().trim();
|
||||
const titlePlural = form.get("titlePlural")?.toString().trim();
|
||||
const description = form.get("description")?.toString() || null;
|
||||
const isDefault = Boolean(form.get("isDefault"));
|
||||
const subscriptionProducts = form.getAll("subscriptionProducts[]").map((f) => f.toString());
|
||||
|
||||
if (!title || !titlePlural) {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
const existing = await getTenantTypeByTitle(title);
|
||||
if (existing && existing.id !== item.id) {
|
||||
return Response.json({ error: t("shared.alreadyExists") }, { status: 400 });
|
||||
}
|
||||
|
||||
await updateTenantType(params.id!, {
|
||||
title,
|
||||
titlePlural,
|
||||
description,
|
||||
isDefault,
|
||||
subscriptionProducts,
|
||||
});
|
||||
return redirect(adminPath("settings/accounts/types", { mode: "host-aware" }));
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.accountTypes.delete");
|
||||
await deleteTenantType(params.id!);
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<TenantTypeForm item={data.item} allSubscriptionProducts={data.allSubscriptionProducts} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { TenantTypeForm } from "~/components/core/tenants/types/TenantTypeForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { createTenantType, getTenantTypeByTitle } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
allSubscriptionProducts: SubscriptionProductDto[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accountTypes.create");
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (!appConfiguration.app.features.tenantTypes) {
|
||||
throw Error(t("settings.admin.tenants.types.disabledWarning"));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
allSubscriptionProducts: await getAllSubscriptionProducts(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accountTypes.create");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "create") {
|
||||
const title = form.get("title")?.toString().trim();
|
||||
const titlePlural = form.get("titlePlural")?.toString().trim();
|
||||
const description = form.get("description")?.toString() || null;
|
||||
const isDefault = Boolean(form.get("isDefault"));
|
||||
const subscriptionProducts = form.getAll("subscriptionProducts[]").map((f) => f.toString());
|
||||
|
||||
if (!title || !titlePlural) {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
const existing = await getTenantTypeByTitle(title);
|
||||
if (existing) {
|
||||
return Response.json({ error: t("shared.alreadyExists") }, { status: 400 });
|
||||
}
|
||||
await createTenantType({
|
||||
title,
|
||||
titlePlural,
|
||||
description,
|
||||
isDefault,
|
||||
subscriptionProducts,
|
||||
});
|
||||
return redirect(adminPath("settings/accounts/types", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div>
|
||||
<TenantTypeForm allSubscriptionProducts={data.allSubscriptionProducts} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { adminSession, transaction } = vi.hoisted(() => ({
|
||||
adminSession: {
|
||||
adminUserId: "admin-1",
|
||||
adminUser: { id: "admin-1", email: "admin@example.test" },
|
||||
},
|
||||
transaction: {
|
||||
adminRole: { findUnique: vi.fn() },
|
||||
adminPermission: { findMany: vi.fn() },
|
||||
adminRolePermission: { deleteMany: vi.fn(), createMany: vi.fn() },
|
||||
adminSession: { updateMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/rls-context.server", () => ({
|
||||
runWithRlsTransaction: vi.fn(async (_transaction, operation: () => Promise<unknown>) => operation()),
|
||||
}));
|
||||
vi.mock("~/components/screens/admin/sales/security/AdminRolesPage", () => ({ AdminRolesPage: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: 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/admin-identity.server", () => ({
|
||||
runAsAdminIdentity: vi.fn(async (_request, _permission, operation) => operation(adminSession)),
|
||||
}));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: { $transaction: vi.fn(async (operation) => operation(transaction)) },
|
||||
}));
|
||||
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { action } from "./admin-roles";
|
||||
|
||||
function callAction(values: Array<[string, string]>) {
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of values) body.append(key, value);
|
||||
return action({
|
||||
request: new Request("https://admin.example.test/settings/admin-roles", { method: "POST", body }),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/settings/admin-roles",
|
||||
} as ActionFunctionArgs);
|
||||
}
|
||||
|
||||
describe("admin role editor action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
transaction.adminRole.findUnique.mockResolvedValue({ id: "role-sales", systemKey: "sales" });
|
||||
transaction.adminPermission.findMany.mockResolvedValue([
|
||||
{ id: "permission-read", name: "admin_sales.crm.read" },
|
||||
{ id: "permission-write", name: "admin_sales.crm.write" },
|
||||
]);
|
||||
transaction.adminRolePermission.deleteMany.mockResolvedValue({ count: 2 });
|
||||
transaction.adminRolePermission.createMany.mockResolvedValue({ count: 2 });
|
||||
transaction.adminSession.updateMany.mockResolvedValue({ count: 3 });
|
||||
});
|
||||
|
||||
it("persists a typed bundle transactionally with reasoned audit", async () => {
|
||||
const response = await callAction([
|
||||
["intent", "save-role"],
|
||||
["roleId", "role-sales"],
|
||||
["reason", "Sales-Rolle auf Kernzugriff begrenzen"],
|
||||
["permission", "admin_sales.crm.read"],
|
||||
["permission", "admin_sales.crm.write"],
|
||||
["permission", "not.allowed"],
|
||||
]);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(runAsAdminIdentity).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin_identity.roles.manage",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(transaction.adminRolePermission.deleteMany).toHaveBeenCalledWith({
|
||||
where: { adminRoleId: "role-sales" },
|
||||
});
|
||||
expect(transaction.adminRolePermission.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
{ adminRoleId: "role-sales", adminPermissionId: "permission-read" },
|
||||
{ adminRoleId: "role-sales", adminPermissionId: "permission-write" },
|
||||
],
|
||||
});
|
||||
expect(transaction.adminSession.updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
revokedAt: null,
|
||||
adminUser: { roles: { some: { adminRoleId: "role-sales" } } },
|
||||
},
|
||||
data: { revokedAt: expect.any(Date) },
|
||||
});
|
||||
expect(recordAdminAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "security.adminRolePermissionsChanged",
|
||||
targetId: "role-sales",
|
||||
reason: "Sales-Rolle auf Kernzugriff begrenzen",
|
||||
after: {
|
||||
permissions: ["admin_sales.crm.read", "admin_sales.crm.write"],
|
||||
revokedSessions: 3,
|
||||
},
|
||||
}),
|
||||
transaction
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the SuperAdmin bundle immutable", async () => {
|
||||
transaction.adminRole.findUnique.mockResolvedValueOnce({ id: "role-super", systemKey: "super_admin" });
|
||||
|
||||
const response = await callAction([
|
||||
["intent", "save-role"],
|
||||
["roleId", "role-super"],
|
||||
["reason", "Superadmin-Rolle ändern"],
|
||||
["permission", "admin_sales.crm.read"],
|
||||
]);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(transaction.adminRolePermission.deleteMany).not.toHaveBeenCalled();
|
||||
expect(recordAdminAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects legacy or freely created roles", async () => {
|
||||
transaction.adminRole.findUnique.mockResolvedValueOnce({ id: "role-custom", systemKey: null });
|
||||
|
||||
const response = await callAction([
|
||||
["intent", "save-role"],
|
||||
["roleId", "role-custom"],
|
||||
["reason", "Freie Rolle ändern"],
|
||||
["permission", "admin_sales.crm.read"],
|
||||
]);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(transaction.adminRolePermission.deleteMany).not.toHaveBeenCalled();
|
||||
expect(transaction.adminSession.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useFetcher, useLoaderData } from "react-router";
|
||||
|
||||
import type { AuditEventWriterClient } from "@hivegrid/db/audit-events.server";
|
||||
import { ADMIN_EDITABLE_ROLE_KEYS, ADMIN_ROLE_KEYS, isAdminPermissionName } from "@hivegrid/db/admin-permissions";
|
||||
import { runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
|
||||
import { buildAdminRoleEditorVM } from "@hivegrid/view-models";
|
||||
|
||||
import { AdminRolesPage } from "~/components/screens/admin/sales/security/AdminRolesPage";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { assertAdminActionReason, recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type ActionData = { ok: true; messageKey: string } | { ok: false; errorKey: string };
|
||||
const editableRoleKeySet = new Set<string>(ADMIN_EDITABLE_ROLE_KEYS);
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
const vm = await runAsAdminIdentity(request, "admin_identity.roles.read", async () => {
|
||||
const [roles, permissions] = await Promise.all([
|
||||
db.adminRole.findMany({
|
||||
where: { active: true, systemKey: { in: [...ADMIN_ROLE_KEYS] } },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
systemKey: true,
|
||||
isSystem: true,
|
||||
permissions: { select: { permission: { select: { name: true } } } },
|
||||
_count: { select: { users: true } },
|
||||
},
|
||||
}),
|
||||
db.adminPermission.findMany({ select: { name: true, description: true } }),
|
||||
]);
|
||||
return buildAdminRoleEditorVM({ roles, permissions });
|
||||
});
|
||||
return { title: `${t("admin.sales.adminRoles.title")} | ${process.env.APP_NAME}`, vm };
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("intent") !== "save-role") {
|
||||
return Response.json({ ok: false, errorKey: "admin.sales.adminRoles.errors.updateFailed" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
let reason: string;
|
||||
try {
|
||||
reason = assertAdminActionReason(String(form.get("reason") ?? ""));
|
||||
} catch {
|
||||
return Response.json({ ok: false, errorKey: "admin.audit.errors.reasonTooShort" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const roleId = String(form.get("roleId") ?? "");
|
||||
const permissions = [...new Set(form.getAll("permission").map(String).filter(isAdminPermissionName))];
|
||||
try {
|
||||
await runAsAdminIdentity(request, "admin_identity.roles.manage", async (session) =>
|
||||
db.$transaction((transaction) =>
|
||||
runWithRlsTransaction(transaction, async () => {
|
||||
const role = await transaction.adminRole.findUnique({ where: { id: roleId }, select: { id: true, systemKey: true } });
|
||||
if (!role?.systemKey || !editableRoleKeySet.has(role.systemKey)) {
|
||||
throw new Error("Only editable system role bundles may be changed");
|
||||
}
|
||||
const permissionRows = await transaction.adminPermission.findMany({
|
||||
where: { name: { in: permissions } },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
if (permissionRows.length !== permissions.length) throw new Error("Unknown permission");
|
||||
await transaction.adminRolePermission.deleteMany({ where: { adminRoleId: roleId } });
|
||||
await transaction.adminRolePermission.createMany({
|
||||
data: permissionRows.map((permission) => ({ adminRoleId: roleId, adminPermissionId: permission.id })),
|
||||
});
|
||||
const revokedSessions = await transaction.adminSession.updateMany({
|
||||
where: {
|
||||
revokedAt: null,
|
||||
adminUser: { roles: { some: { adminRoleId: roleId } } },
|
||||
},
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
await recordAdminAction(
|
||||
{
|
||||
action: "security.adminRolePermissionsChanged",
|
||||
actorUserId: session.adminUserId,
|
||||
actorEmail: session.adminUser.email,
|
||||
targetKind: "admin-role",
|
||||
targetId: roleId,
|
||||
reason,
|
||||
request,
|
||||
after: { permissions, revokedSessions: revokedSessions.count },
|
||||
},
|
||||
transaction as unknown as AuditEventWriterClient
|
||||
);
|
||||
})
|
||||
)
|
||||
);
|
||||
return Response.json({ ok: true, messageKey: "admin.sales.adminRoles.toast.saved" } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
return Response.json({ ok: false, errorKey: "admin.sales.adminRoles.errors.updateFailed" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export default function AdminRolesRoute() {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const root = useRootData();
|
||||
useSaveToast(fetcher.data?.ok ? fetcher.data : undefined);
|
||||
return (
|
||||
<AdminRolesPage
|
||||
vm={vm}
|
||||
busy={fetcher.state !== "idle"}
|
||||
errorKey={fetcher.data && !fetcher.data.ok ? fetcher.data.errorKey : undefined}
|
||||
actions={{
|
||||
onSaveRole: ({ roleId, permissions, reason }) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "save-role");
|
||||
form.set("roleId", roleId);
|
||||
form.set("reason", reason);
|
||||
for (const permission of permissions) form.append("permission", permission);
|
||||
if (root.csrf) form.set("csrf", root.csrf);
|
||||
fetcher.submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import type { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
await requireAdminIdentityPermission(request, "admin_identity.users.read");
|
||||
const { t } = await getTranslations(request);
|
||||
return { title: `${t("admin.sales.adminUsers.title")} | ${process.env.APP_NAME}` };
|
||||
}
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminUsersLayout() {
|
||||
return <Outlet />;
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { adminSession, transaction } = vi.hoisted(() => ({
|
||||
adminSession: {
|
||||
id: "session-current",
|
||||
adminUserId: "admin-1",
|
||||
adminUser: { id: "admin-1", email: "admin@example.test" },
|
||||
},
|
||||
transaction: {
|
||||
adminSession: { updateMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/admin-rbac.server", () => ({
|
||||
disableAdminUserInTransaction: vi.fn(),
|
||||
replaceAdminSystemRolesInTransaction: vi.fn(),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/admin-permissions", () => ({
|
||||
ADMIN_ROLE_KEYS: ["super_admin", "support", "sales", "sales_manager", "engineering", "executive", "viewer"],
|
||||
}));
|
||||
vi.mock("@hivegrid/db/rls-context.server", () => ({
|
||||
runWithRlsTransaction: vi.fn(async (_transaction, operation: () => Promise<unknown>) => operation()),
|
||||
}));
|
||||
vi.mock("~/components/screens/admin/sales/security/AdminUserDetailPage", () => ({ AdminUserDetailPage: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: 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/admin-identity.server", () => ({
|
||||
runAsAdminIdentity: vi.fn(async (_request, _permission, operation) => operation(adminSession)),
|
||||
}));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: { $transaction: vi.fn(async (operation) => operation(transaction)) },
|
||||
}));
|
||||
|
||||
import { disableAdminUserInTransaction, replaceAdminSystemRolesInTransaction } from "@hivegrid/db/admin-rbac.server";
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { action } from "./$id";
|
||||
|
||||
function callAction(values: Array<[string, string]>, id = "admin-2") {
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of values) body.append(key, value);
|
||||
return action({
|
||||
request: new Request(`https://admin.example.test/settings/admin-users/${id}`, { method: "POST", body }),
|
||||
params: { id },
|
||||
context: {},
|
||||
unstable_pattern: "admin/settings/admin-users/$id",
|
||||
} as ActionFunctionArgs);
|
||||
}
|
||||
|
||||
describe("admin user detail actions", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(replaceAdminSystemRolesInTransaction).mockResolvedValue(true);
|
||||
vi.mocked(disableAdminUserInTransaction).mockResolvedValue(true);
|
||||
transaction.adminSession.updateMany.mockResolvedValue({ count: 1 });
|
||||
});
|
||||
|
||||
it("replaces typed roles through the smallest permission and audits the change", async () => {
|
||||
const response = await callAction([
|
||||
["intent", "save-roles"],
|
||||
["reason", "Verantwortung im Sales-Team geändert"],
|
||||
["roleKey", "sales"],
|
||||
["roleKey", "viewer"],
|
||||
["roleKey", "unknown"],
|
||||
]);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(runAsAdminIdentity).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin_identity.users.manage",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(replaceAdminSystemRolesInTransaction).toHaveBeenCalledWith({
|
||||
adminUserId: "admin-2",
|
||||
roleKeys: ["sales", "viewer"],
|
||||
grantedByAdminUserId: "admin-1",
|
||||
client: transaction,
|
||||
});
|
||||
expect(recordAdminAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "security.adminRolesChanged",
|
||||
targetId: "admin-2",
|
||||
reason: "Verantwortung im Sales-Team geändert",
|
||||
}),
|
||||
transaction
|
||||
);
|
||||
});
|
||||
|
||||
it("maps last-superadmin protection to a stable user-facing failure", async () => {
|
||||
vi.mocked(replaceAdminSystemRolesInTransaction).mockRejectedValueOnce(
|
||||
Object.assign(new Error("protected"), { code: "ADMIN_LAST_SUPER_ADMIN" })
|
||||
);
|
||||
|
||||
const response = await callAction([
|
||||
["intent", "save-roles"],
|
||||
["reason", "Rollenbereinigung im Admin-Team"],
|
||||
["roleKey", "viewer"],
|
||||
]);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
ok: false,
|
||||
errorKey: "admin.sales.adminUserDetail.errors.lastSuperAdmin",
|
||||
});
|
||||
});
|
||||
|
||||
it("prevents self-disable before calling the domain mutation", async () => {
|
||||
const response = await callAction(
|
||||
[
|
||||
["intent", "disable"],
|
||||
["reason", "Admin-Zugang wird deaktiviert"],
|
||||
],
|
||||
adminSession.adminUserId
|
||||
);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(disableAdminUserInTransaction).not.toHaveBeenCalled();
|
||||
expect(recordAdminAction).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useFetcher, useLoaderData, useNavigate } from "react-router";
|
||||
|
||||
import type { AuditEventWriterClient } from "@hivegrid/db/audit-events.server";
|
||||
import { disableAdminUserInTransaction, replaceAdminSystemRolesInTransaction } from "@hivegrid/db/admin-rbac.server";
|
||||
import type { AdminRoleKey } from "@hivegrid/db/admin-permissions";
|
||||
import { ADMIN_ROLE_KEYS } from "@hivegrid/db/admin-permissions";
|
||||
import { runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
|
||||
import { buildAdminUserDetailVM } from "@hivegrid/view-models";
|
||||
|
||||
import { AdminUserDetailPage } from "~/components/screens/admin/sales/security/AdminUserDetailPage";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { assertAdminActionReason, recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type ActionData = { ok: true; intent: string; messageKey: string } | { ok: false; errorKey: string };
|
||||
const roleKeySet = new Set<string>(ADMIN_ROLE_KEYS);
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const targetId = params.id;
|
||||
if (!targetId) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
const { t } = await getTranslations(request);
|
||||
const vm = await runAsAdminIdentity(request, "admin_identity.users.read", async (session) => {
|
||||
const [user, availableRoles, audit] = await Promise.all([
|
||||
db.adminUser.findUnique({
|
||||
where: { id: targetId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
status: true,
|
||||
authentikSubject: true,
|
||||
lastSsoLoginAt: true,
|
||||
roles: {
|
||||
select: {
|
||||
role: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
systemKey: true,
|
||||
permissions: { select: { permission: { select: { name: true } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
sessions: {
|
||||
where: { revokedAt: null, expiresAt: { gt: new Date() } },
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
lastSeenAt: true,
|
||||
expiresAt: true,
|
||||
approxLocation: true,
|
||||
userAgent: true,
|
||||
mfaAssuredAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
db.adminRole.findMany({ where: { active: true, systemKey: { not: null } }, select: { id: true, name: true, systemKey: true } }),
|
||||
db.auditEvent.findMany({
|
||||
where: { tenantId: null, targetType: "admin-user", targetId },
|
||||
select: { id: true, action: true, createdAt: true, summaryText: true },
|
||||
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
||||
take: 25,
|
||||
}),
|
||||
]);
|
||||
if (!user) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
return buildAdminUserDetailVM({
|
||||
user,
|
||||
sessions: user.sessions,
|
||||
availableRoles,
|
||||
audit,
|
||||
currentAdminUserId: session.adminUserId,
|
||||
currentSessionId: session.id,
|
||||
});
|
||||
});
|
||||
return { title: `${vm.user.displayName} | ${t("admin.sales.adminUsers.title")}`, vm };
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const targetId = params.id;
|
||||
if (!targetId) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
let reason: string;
|
||||
try {
|
||||
reason = assertAdminActionReason(String(form.get("reason") ?? ""));
|
||||
} catch {
|
||||
return Response.json({ ok: false, errorKey: "admin.audit.errors.reasonTooShort" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await runAsAdminIdentity(request, intent === "revoke-session" ? "admin_identity.sessions.revoke" : "admin_identity.users.manage", async (session) =>
|
||||
db.$transaction((transaction) =>
|
||||
runWithRlsTransaction(transaction, async () => {
|
||||
if (intent === "save-roles") {
|
||||
const requested = form
|
||||
.getAll("roleKey")
|
||||
.map(String)
|
||||
.filter((key): key is AdminRoleKey => roleKeySet.has(key));
|
||||
if (requested.length === 0) throw new Error("At least one role is required");
|
||||
const updated = await replaceAdminSystemRolesInTransaction({
|
||||
adminUserId: targetId,
|
||||
roleKeys: requested,
|
||||
grantedByAdminUserId: session.adminUserId,
|
||||
client: transaction,
|
||||
});
|
||||
if (!updated) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
await recordAdminAction(
|
||||
{
|
||||
action: "security.adminRolesChanged",
|
||||
actorUserId: session.adminUserId,
|
||||
actorEmail: session.adminUser.email,
|
||||
targetKind: "admin-user",
|
||||
targetId,
|
||||
reason,
|
||||
request,
|
||||
after: { roleKeys: requested },
|
||||
},
|
||||
transaction as unknown as AuditEventWriterClient
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (intent === "disable") {
|
||||
if (targetId === session.adminUserId) throw new Error("Self-disable is not allowed");
|
||||
const disabled = await disableAdminUserInTransaction({ adminUserId: targetId, reason, client: transaction });
|
||||
if (!disabled) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
await recordAdminAction(
|
||||
{
|
||||
action: "security.adminUserDisabled",
|
||||
actorUserId: session.adminUserId,
|
||||
actorEmail: session.adminUser.email,
|
||||
targetKind: "admin-user",
|
||||
targetId,
|
||||
reason,
|
||||
request,
|
||||
},
|
||||
transaction as unknown as AuditEventWriterClient
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (intent === "revoke-session") {
|
||||
const sessionId = String(form.get("sessionId") ?? "");
|
||||
if (!sessionId || sessionId === session.id) throw new Error("Current session cannot be revoked here");
|
||||
const result = await transaction.adminSession.updateMany({
|
||||
where: { id: sessionId, adminUserId: targetId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
if (result.count !== 1) throw new Error("Session not found");
|
||||
await recordAdminAction(
|
||||
{
|
||||
action: "security.sessionRevoked",
|
||||
actorUserId: session.adminUserId,
|
||||
actorEmail: session.adminUser.email,
|
||||
targetKind: "admin-user",
|
||||
targetId,
|
||||
reason,
|
||||
request,
|
||||
extraMeta: { sessionId },
|
||||
},
|
||||
transaction as unknown as AuditEventWriterClient
|
||||
);
|
||||
return;
|
||||
}
|
||||
throw new Error("Unsupported action");
|
||||
})
|
||||
)
|
||||
);
|
||||
const messageKeyByIntent: Record<string, string> = {
|
||||
"save-roles": "admin.sales.adminUserDetail.toast.rolesSaved",
|
||||
disable: "admin.sales.adminUserDetail.toast.disabled",
|
||||
"revoke-session": "admin.sales.adminUserDetail.toast.sessionRevoked",
|
||||
};
|
||||
return Response.json({
|
||||
ok: true,
|
||||
intent,
|
||||
messageKey: messageKeyByIntent[intent] ?? "admin.sales.adminUserDetail.toast.saved",
|
||||
} satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
const errorKey =
|
||||
error instanceof Error && "code" in error && error.code === "ADMIN_LAST_SUPER_ADMIN"
|
||||
? "admin.sales.adminUserDetail.errors.lastSuperAdmin"
|
||||
: "admin.sales.adminUserDetail.errors.updateFailed";
|
||||
return Response.json({ ok: false, errorKey } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export default function AdminUserDetailRoute() {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const root = useRootData();
|
||||
useSaveToast(fetcher.data?.ok ? fetcher.data : undefined);
|
||||
const submit = (entries: Array<[string, string]>) => {
|
||||
const form = new FormData();
|
||||
for (const [key, value] of entries) form.append(key, value);
|
||||
if (root.csrf) form.set("csrf", root.csrf);
|
||||
fetcher.submit(form, { method: "post" });
|
||||
};
|
||||
return (
|
||||
<AdminUserDetailPage
|
||||
vm={vm}
|
||||
busy={fetcher.state !== "idle"}
|
||||
errorKey={fetcher.data && !fetcher.data.ok ? fetcher.data.errorKey : undefined}
|
||||
actions={{
|
||||
onBack: () => navigate(".."),
|
||||
onSaveRoles: ({ roleKeys, reason }) =>
|
||||
submit([["intent", "save-roles"], ["reason", reason], ...roleKeys.map((roleKey): [string, string] => ["roleKey", roleKey])]),
|
||||
onDisable: (reason) =>
|
||||
submit([
|
||||
["intent", "disable"],
|
||||
["reason", reason],
|
||||
]),
|
||||
onRevokeSession: ({ sessionId, reason }) =>
|
||||
submit([
|
||||
["intent", "revoke-session"],
|
||||
["sessionId", sessionId],
|
||||
["reason", reason],
|
||||
]),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { adminSession, transaction } = vi.hoisted(() => ({
|
||||
adminSession: {
|
||||
id: "session-1",
|
||||
adminUserId: "admin-1",
|
||||
adminUser: { id: "admin-1", email: "admin@example.test" },
|
||||
},
|
||||
transaction: {
|
||||
adminRole: { findMany: vi.fn() },
|
||||
adminUser: { create: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/rls-context.server", () => ({
|
||||
runWithRlsTransaction: vi.fn(async (_transaction, operation: () => Promise<unknown>) => operation()),
|
||||
}));
|
||||
vi.mock("~/components/screens/admin/sales/security/AdminUsersPage", () => ({ AdminUsersPage: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: 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/admin-identity.server", () => ({
|
||||
runAsAdminIdentity: vi.fn(async (_request, _permission, operation) => operation(adminSession)),
|
||||
}));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: { $transaction: vi.fn(async (operation) => operation(transaction)) },
|
||||
}));
|
||||
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { action } from "./index";
|
||||
|
||||
function callAction(values: Record<string, string | string[]>) {
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
for (const item of Array.isArray(value) ? value : [value]) body.append(key, item);
|
||||
}
|
||||
const request = new Request("https://admin.example.test/settings/admin-users", {
|
||||
method: "POST",
|
||||
body,
|
||||
});
|
||||
return action({
|
||||
request,
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/settings/admin-users/index",
|
||||
} as ActionFunctionArgs);
|
||||
}
|
||||
|
||||
describe("admin user preparation action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
transaction.adminRole.findMany.mockResolvedValue([
|
||||
{ id: "role-sales", systemKey: "sales" },
|
||||
{ id: "role-viewer", systemKey: "viewer" },
|
||||
]);
|
||||
transaction.adminUser.create.mockResolvedValue({ id: "admin-prepared" });
|
||||
});
|
||||
|
||||
it("prepares an Authentik identity with additive selected roles and mandatory audit", async () => {
|
||||
const response = await callAction({
|
||||
intent: "prepare-admin",
|
||||
email: "NEW.ADMIN@EXAMPLE.TEST",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
reason: "Neue Kollegin im Vertrieb",
|
||||
roleKey: ["sales", "viewer"],
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.json()).resolves.toEqual({ ok: true, adminUserId: "admin-prepared" });
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(runAsAdminIdentity).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin_identity.users.manage",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(transaction.adminUser.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
email: "new.admin@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
roles: {
|
||||
create: [
|
||||
{ adminRoleId: "role-sales", grantedByAdminUserId: "admin-1" },
|
||||
{ adminRoleId: "role-viewer", grantedByAdminUserId: "admin-1" },
|
||||
],
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(recordAdminAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "security.adminUserPrepared",
|
||||
actorUserId: "admin-1",
|
||||
targetId: "admin-prepared",
|
||||
reason: "Neue Kollegin im Vertrieb",
|
||||
after: { email: "new.admin@example.test", roleKeys: ["sales", "viewer"] },
|
||||
}),
|
||||
transaction
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects invalid identity input before opening the permission-gated mutation", async () => {
|
||||
const response = await callAction({
|
||||
intent: "prepare-admin",
|
||||
email: "invalid",
|
||||
firstName: "",
|
||||
reason: "Neue Kollegin im Vertrieb",
|
||||
roleKey: "viewer",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(runAsAdminIdentity).not.toHaveBeenCalled();
|
||||
expect(transaction.adminUser.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
import { useEffect } from "react";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useFetcher, useLoaderData, useNavigate } from "react-router";
|
||||
|
||||
import type { AuditEventWriterClient } from "@hivegrid/db/audit-events.server";
|
||||
import type { AdminRoleKey } from "@hivegrid/db/admin-permissions";
|
||||
import { ADMIN_ROLE_KEYS } from "@hivegrid/db/admin-permissions";
|
||||
import { runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
|
||||
import { buildAdminUserListVM } from "@hivegrid/view-models";
|
||||
|
||||
import { AdminUsersPage } from "~/components/screens/admin/sales/security/AdminUsersPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { assertAdminActionReason, recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type ActionData = { ok: true; adminUserId: string } | { ok: false; errorKey: string };
|
||||
const roleKeySet = new Set<string>(ADMIN_ROLE_KEYS);
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
const vm = await runAsAdminIdentity(request, "admin_identity.users.read", async () => {
|
||||
const [users, availableRoles] = await Promise.all([
|
||||
db.adminUser.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
status: true,
|
||||
authentikSubject: true,
|
||||
lastSsoLoginAt: true,
|
||||
roles: { select: { role: { select: { id: true, name: true, systemKey: true } } } },
|
||||
sessions: {
|
||||
where: { revokedAt: null },
|
||||
select: { lastSeenAt: true },
|
||||
orderBy: { lastSeenAt: "desc" },
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
}),
|
||||
db.adminRole.findMany({
|
||||
where: { active: true, systemKey: { not: null } },
|
||||
select: { id: true, name: true, systemKey: true },
|
||||
}),
|
||||
]);
|
||||
return buildAdminUserListVM(users, availableRoles);
|
||||
});
|
||||
return { title: `${t("admin.sales.adminUsers.title")} | ${process.env.APP_NAME}`, vm };
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("intent") !== "prepare-admin") {
|
||||
return Response.json({ ok: false, errorKey: "admin.sales.adminUsers.errors.invalid" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const email = String(form.get("email") ?? "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const firstName = String(form.get("firstName") ?? "").trim();
|
||||
const lastName = String(form.get("lastName") ?? "").trim();
|
||||
const rawRoleKeys = form.getAll("roleKey").map(String);
|
||||
const roleKeys = [...new Set(rawRoleKeys)] as AdminRoleKey[];
|
||||
let reason: string;
|
||||
try {
|
||||
reason = assertAdminActionReason(String(form.get("reason") ?? ""));
|
||||
} catch {
|
||||
return Response.json({ ok: false, errorKey: "admin.audit.errors.reasonTooShort" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
if (
|
||||
!email.includes("@") ||
|
||||
firstName.length === 0 ||
|
||||
email.length > 320 ||
|
||||
firstName.length > 200 ||
|
||||
lastName.length > 200 ||
|
||||
roleKeys.length === 0 ||
|
||||
rawRoleKeys.some((key) => !roleKeySet.has(key))
|
||||
) {
|
||||
return Response.json({ ok: false, errorKey: "admin.sales.adminUsers.errors.invalid" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const adminUserId = await runAsAdminIdentity(request, "admin_identity.users.manage", async (session) =>
|
||||
db.$transaction((transaction) =>
|
||||
runWithRlsTransaction(transaction, async () => {
|
||||
const roles = await transaction.adminRole.findMany({
|
||||
where: { systemKey: { in: roleKeys }, active: true },
|
||||
select: { id: true, systemKey: true },
|
||||
});
|
||||
if (roles.length !== roleKeys.length) throw new Error("Admin role catalog is not synchronized");
|
||||
const prepared = await transaction.adminUser.create({
|
||||
data: {
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
roles: {
|
||||
create: roles.map((role) => ({
|
||||
adminRoleId: role.id,
|
||||
grantedByAdminUserId: session.adminUserId,
|
||||
})),
|
||||
},
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
await recordAdminAction(
|
||||
{
|
||||
action: "security.adminUserPrepared",
|
||||
actorUserId: session.adminUserId,
|
||||
actorEmail: session.adminUser.email,
|
||||
targetKind: "admin-user",
|
||||
targetId: prepared.id,
|
||||
reason,
|
||||
request,
|
||||
after: { email, roleKeys },
|
||||
},
|
||||
transaction as unknown as AuditEventWriterClient
|
||||
);
|
||||
return prepared.id;
|
||||
})
|
||||
)
|
||||
);
|
||||
return Response.json({ ok: true, adminUserId } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
const duplicate = error instanceof Error && "code" in error && error.code === "P2002";
|
||||
return Response.json(
|
||||
{ ok: false, errorKey: duplicate ? "admin.sales.adminUsers.errors.duplicate" : "admin.sales.adminUsers.errors.createFailed" } satisfies ActionData,
|
||||
{ status: duplicate ? 409 : 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default function AdminUsersRoute() {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const root = useRootData();
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.ok) {
|
||||
navigate(`${fetcher.data.adminUserId}?toast=${encodeURIComponent("admin.sales.adminUsers.toast.created")}`);
|
||||
}
|
||||
}, [fetcher.data, navigate]);
|
||||
return (
|
||||
<AdminUsersPage
|
||||
vm={vm}
|
||||
busy={fetcher.state !== "idle"}
|
||||
errorKey={fetcher.data && !fetcher.data.ok ? fetcher.data.errorKey : undefined}
|
||||
actions={{
|
||||
onOpenUser: (userId) => navigate(userId),
|
||||
onCreateUser: ({ email, firstName, lastName, roleKeys, reason }) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "prepare-admin");
|
||||
form.set("email", email);
|
||||
form.set("firstName", firstName);
|
||||
form.set("lastName", lastName);
|
||||
form.set("reason", reason);
|
||||
for (const roleKey of roleKeys) form.append("roleKey", roleKey);
|
||||
if (root.csrf) form.set("csrf", root.csrf);
|
||||
fetcher.submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+1
-3
@@ -13,9 +13,7 @@ import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsServ
|
||||
import { parseAdminSettingsForm, redactSettingsAuditDetails } from "~/utils/services/adminSettingsValidation.server";
|
||||
import { toast } from "sonner";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
@@ -87,7 +85,7 @@ export default function AdminSettingsAuthentication() {
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
<SettingSection title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.authentication.title")}</BackButtonWithTitle>}>
|
||||
<SettingSection title={t("settings.admin.authentication.sectionTitle")}>
|
||||
<Form method="post" className="space-y-8">
|
||||
{(actionData?.error || fieldErrorEntries.length > 0) && (
|
||||
<div role="alert" className="rounded-md border border-red-200 bg-red-50 p-4 text-sm text-red-800">
|
||||
|
||||
-459
@@ -1,459 +0,0 @@
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { useLocation, useNavigation, useSearchParams, useSubmit } from "react-router";
|
||||
import { cache } from "~/utils/cache.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import InputCombobox from "~/components/ui/input/InputCombobox";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsersNames, UserWithNames } from "~/utils/db/users.db.server";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { LucideRefreshCcw } from "~/components/ui/icons/vendor";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createLocaleFormatters, useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type CachedValue = {
|
||||
key: string;
|
||||
value: any;
|
||||
sizeMb: number;
|
||||
createdAt: Date;
|
||||
createdTime: number;
|
||||
};
|
||||
type LoaderData = {
|
||||
cachedValues: CachedValue[];
|
||||
allTenants: { id: string; name: string; slug: string }[];
|
||||
allUsers: UserWithNames[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.settings.general.update");
|
||||
const cachedValues: CachedValue[] = [];
|
||||
|
||||
for (const key of cache.keys()) {
|
||||
if (cachedValues.find((x) => x.key === key)) {
|
||||
continue;
|
||||
}
|
||||
const value = cache.get(key);
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
const sizeBytes = new TextEncoder().encode(JSON.stringify(value)).length;
|
||||
const sizeMb = sizeBytes / 1024 / 1024;
|
||||
const createdTime = value.metadata.createdTime;
|
||||
const createdAt = new Date(createdTime);
|
||||
const cachedValue = { key, value: value.value, sizeMb, createdAt, createdTime };
|
||||
cachedValues.push(cachedValue);
|
||||
}
|
||||
|
||||
const allTenants = await adminGetAllTenantsIdsAndNames();
|
||||
const allUsers = await adminGetAllUsersNames();
|
||||
|
||||
const data: LoaderData = {
|
||||
cachedValues,
|
||||
allTenants,
|
||||
allUsers,
|
||||
};
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.settings.general.update");
|
||||
await validateCSRFToken(request);
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const formatters = createLocaleFormatters(locale);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "delete-key") {
|
||||
const key = form.get("key")?.toString() ?? "";
|
||||
cache.delete(key);
|
||||
return Response.json({ success: t("settings.admin.cache.keyDeleted") });
|
||||
} else if (action === "delete-all") {
|
||||
let keyCount = cache.size;
|
||||
cache.clear();
|
||||
return Response.json({ success: t("settings.admin.cache.cacheCleared", { count: keyCount, formattedCount: formatters.number(keyCount) }) });
|
||||
} else if (action === "delete-keys") {
|
||||
const keys = form.get("keys")?.toString() ?? "";
|
||||
const keysArray = keys.split(",");
|
||||
let keyCount = 0;
|
||||
for (const key of keysArray) {
|
||||
cache.delete(key);
|
||||
keyCount++;
|
||||
}
|
||||
return Response.json({ success: t("settings.admin.cache.keysDeleted", { count: keyCount, formattedCount: formatters.number(keyCount) }) });
|
||||
}
|
||||
return Response.json({ error: t("settings.admin.cache.invalidAction") }, { status: 400 });
|
||||
};
|
||||
|
||||
export default function AdminCacheRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ success?: string; error?: string }>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
|
||||
const [selectedTenants, setSelectedTenants] = useState<string[]>([]);
|
||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||
const [keyGroups, setKeyGroups] = useState<{ value: string; count: number }[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const keyGroups: { [key: string]: number } = {};
|
||||
for (const key of data.cachedValues.map((f) => f.key)) {
|
||||
const keyGroup = key.split(":")[0];
|
||||
if (!keyGroups[keyGroup]) {
|
||||
keyGroups[keyGroup] = 0;
|
||||
}
|
||||
keyGroups[keyGroup]++;
|
||||
}
|
||||
const keyGroupsArray = Object.keys(keyGroups).map((key) => ({ value: key, count: keyGroups[key] }));
|
||||
setKeyGroups(keyGroupsArray);
|
||||
}, [data.cachedValues]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
const filteredItems = () => {
|
||||
let items = data.cachedValues;
|
||||
if (selectedKeys.length) {
|
||||
items = items.filter((item) => selectedKeys.includes(item.key.split(":")[0]));
|
||||
}
|
||||
if (selectedTenants.length) {
|
||||
items = items.filter((item) => {
|
||||
const tenantIds = selectedTenants;
|
||||
for (const tenantId of tenantIds) {
|
||||
const tenant = data.allTenants.find((f) => f.id === tenantId);
|
||||
if (!tenant) {
|
||||
return false;
|
||||
}
|
||||
const { id, slug } = tenant;
|
||||
if (item.key.includes(":" + id) || item.key.includes(":" + slug)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
if (selectedUsers.length) {
|
||||
items = items.filter((item) => {
|
||||
const userIds = selectedUsers;
|
||||
for (const userId of userIds) {
|
||||
const user = data.allUsers.find((f) => f.id === userId);
|
||||
if (!user) {
|
||||
return false;
|
||||
}
|
||||
const { id } = user;
|
||||
if (item.key.includes(":" + id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
if (searchInput) {
|
||||
items = items.filter(
|
||||
(item) =>
|
||||
item.key.toLowerCase().includes(searchInput.toLowerCase()) ||
|
||||
JSON.stringify(item.value ?? "")
|
||||
?.toLowerCase()
|
||||
.includes(searchInput.toLowerCase())
|
||||
);
|
||||
}
|
||||
return items;
|
||||
};
|
||||
|
||||
const sortedItems = () => {
|
||||
const items = filteredItems();
|
||||
const sortBy = searchParams.get("sort") ?? "-createdTime";
|
||||
const sortAsc = sortBy.startsWith("-");
|
||||
const sortKey = sortBy.replace("-", "");
|
||||
const sorted = items.sort((a, b) => {
|
||||
if (sortKey === "key") {
|
||||
return sortAsc ? a.key.localeCompare(b.key) : b.key.localeCompare(a.key);
|
||||
} else if (sortKey === "sizeMb") {
|
||||
return sortAsc ? a.sizeMb - b.sizeMb : b.sizeMb - a.sizeMb;
|
||||
} else if (sortKey === "createdTime") {
|
||||
return sortAsc ? a.createdTime - b.createdTime : b.createdTime - a.createdTime;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
return sorted;
|
||||
};
|
||||
|
||||
const availableUsers = () => {
|
||||
let users = data.allUsers.filter((f) => {
|
||||
if (!data.cachedValues.find((item) => item.key.includes(":" + f.id))) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return users;
|
||||
};
|
||||
|
||||
const availableTenants = () => {
|
||||
let tenants = data.allTenants.filter((f) => {
|
||||
if (!data.cachedValues.find((item) => item.key.includes(":" + f.id) || item.key.includes(":" + f.slug))) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return tenants;
|
||||
};
|
||||
|
||||
function onDeleteAll() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-all");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function onDelete(key: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-key");
|
||||
form.set("key", key);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function onDeleteSelected(keys: string[]) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-keys");
|
||||
form.set("keys", keys.join(","));
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function getValue(item: CachedValue) {
|
||||
try {
|
||||
// if is array, count
|
||||
if (Array.isArray(item.value)) {
|
||||
return t("settings.admin.cache.valuePreview.arrayItems", { count: item.value.length });
|
||||
} else if (typeof item.value === "object") {
|
||||
return t("settings.admin.cache.valuePreview.objectKeys", { count: Object.keys(item.value).length });
|
||||
}
|
||||
} catch {}
|
||||
return item.value;
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={
|
||||
<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>
|
||||
{t("settings.admin.cache.summary", {
|
||||
keys: formatters.number(data.cachedValues.length),
|
||||
size: formatters.number(data.cachedValues.reduce((a, b) => a + b.sizeMb, 0), {
|
||||
style: "unit",
|
||||
unit: "megabyte",
|
||||
unitDisplay: "short",
|
||||
maximumFractionDigits: 2,
|
||||
}),
|
||||
})}
|
||||
</BackButtonWithTitle>
|
||||
}
|
||||
buttons={
|
||||
<>
|
||||
<div className="flex justify-between space-x-2">
|
||||
<InputSearch size="sm" className="w-full grow" value={searchInput} setValue={setSearchInput} />
|
||||
<Button size="sm" asChild type="button" variant="secondary" isLoading={navigation.state !== "idle"}>
|
||||
<Link to={location.pathname + location.search}>
|
||||
<LucideRefreshCcw className="size-3" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start space-x-4">
|
||||
<div className="w-52 shrink-0 space-y-2 p-1">
|
||||
<InputCombobox
|
||||
title={t("settings.admin.cache.filters.group")}
|
||||
name="keyGroupBy"
|
||||
// prefix="Key group"
|
||||
selectPlaceholder={t("settings.admin.cache.filters.selectGroup")}
|
||||
options={keyGroups.map((f) => ({ name: `${f.value} (${formatters.number(f.count)})`, value: f.value }))}
|
||||
value={selectedKeys}
|
||||
onChange={(value) => {
|
||||
setSelectedKeys(value as string[]);
|
||||
}}
|
||||
onClear={() => setSelectedKeys([])}
|
||||
disabled={keyGroups.length === 0}
|
||||
minDisplayCount={2}
|
||||
className="bg-background"
|
||||
/>
|
||||
<InputCombobox
|
||||
title={t("settings.admin.cache.filters.tenant")}
|
||||
name="tenants"
|
||||
// prefix="Tenant"
|
||||
selectPlaceholder={t("settings.admin.cache.filters.selectTenant")}
|
||||
options={availableTenants().map((f) => ({ name: f.name + " (" + f.slug + ")", value: f.id }))}
|
||||
value={selectedTenants}
|
||||
onChange={(value) => {
|
||||
setSelectedTenants(value as string[]);
|
||||
}}
|
||||
onClear={() => setSelectedTenants([])}
|
||||
disabled={availableTenants().length === 0}
|
||||
minDisplayCount={1}
|
||||
className="bg-background"
|
||||
/>
|
||||
<InputCombobox
|
||||
title={t("settings.admin.cache.filters.user")}
|
||||
name="users"
|
||||
// prefix="User"
|
||||
selectPlaceholder={t("settings.admin.cache.filters.selectUser")}
|
||||
options={availableUsers().map((f) => ({ name: f.email, value: f.id }))}
|
||||
value={selectedUsers}
|
||||
onChange={(value) => {
|
||||
setSelectedUsers(value as string[]);
|
||||
}}
|
||||
onClear={() => setSelectedUsers([])}
|
||||
disabled={availableUsers().length === 0}
|
||||
minDisplayCount={1}
|
||||
className="bg-background"
|
||||
/>
|
||||
<div className="border-border border-t pt-2">
|
||||
<DeleteButton items={sortedItems()} searchInput={searchInput} onDeleteAll={onDeleteAll} onDeleteSelected={onDeleteSelected} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grow space-y-2 overflow-auto p-1">
|
||||
<div>
|
||||
<label className="text-muted-foreground mb-1 block text-xs font-medium">{t("settings.admin.cache.cachedValues")}</label>
|
||||
<TableSimple
|
||||
items={sortedItems()}
|
||||
noRecords={
|
||||
<div className="flex flex-col space-y-1 py-4 text-sm">
|
||||
<div>{t("shared.noRecords")}</div>
|
||||
{searchInput && (
|
||||
<div>
|
||||
<button type="button" className="text-blue-500 underline" onClick={() => setSearchInput("")}>
|
||||
{t("settings.admin.cache.clearSearch")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
headers={[
|
||||
{
|
||||
name: "key",
|
||||
title: t("settings.admin.cache.columns.key"),
|
||||
value: (item) => <div className="max-w-xs truncate">{item.key}</div>,
|
||||
sortBy: "key",
|
||||
sortable: true,
|
||||
},
|
||||
{
|
||||
name: "type",
|
||||
title: t("settings.admin.cache.columns.type"),
|
||||
value: (item) => (Array.isArray(item.value) ? "array" : typeof item.value),
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: t("settings.admin.cache.columns.value"),
|
||||
value: (item) => (
|
||||
<div className="flex justify-end">
|
||||
<ShowPayloadModalButton description={getValue(item)} payload={item.value} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "size",
|
||||
title: t("settings.admin.cache.columns.size"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
{formatters.number(item.sizeMb, {
|
||||
style: "unit",
|
||||
unit: "megabyte",
|
||||
unitDisplay: "short",
|
||||
maximumFractionDigits: 4,
|
||||
})}
|
||||
</div>
|
||||
),
|
||||
sortBy: "sizeMb",
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => item.createdAt,
|
||||
formattedValue: (item) => <DateCell date={item.createdAt} displays={["ymdhmsms"]} />,
|
||||
sortBy: "createdTime",
|
||||
},
|
||||
]}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.delete"),
|
||||
onClick: (_, item) => onDelete(item.key),
|
||||
disabled: (item) => navigation.formData?.get("action") === "delete-key" && navigation.formData?.get("key") === item.key,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function DeleteButton({
|
||||
items,
|
||||
searchInput,
|
||||
onDeleteAll,
|
||||
onDeleteSelected,
|
||||
}: {
|
||||
items: CachedValue[];
|
||||
searchInput: string;
|
||||
onDeleteAll: () => void;
|
||||
onDeleteSelected: (keys: string[]) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const formattedCount = formatters.number(items.length);
|
||||
return (
|
||||
<Fragment>
|
||||
{searchInput ? (
|
||||
<ButtonSecondary
|
||||
className="w-full"
|
||||
disabled={items.length === 0}
|
||||
destructive
|
||||
onClick={() => onDeleteSelected(items.map((f) => f.key))}
|
||||
isLoading={navigation.formData?.get("action") === "delete-selected"}
|
||||
>
|
||||
{t("settings.admin.cache.clearKeys", { count: items.length, formattedCount })}
|
||||
</ButtonSecondary>
|
||||
) : (
|
||||
<ButtonSecondary
|
||||
disabled={items.length === 0}
|
||||
className="w-full"
|
||||
destructive
|
||||
onClick={() => onDeleteAll()}
|
||||
isLoading={navigation.formData?.get("action") === "delete-all"}
|
||||
>
|
||||
{t("settings.admin.cache.clearKeys", { count: items.length, formattedCount })}
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
-237
@@ -1,237 +0,0 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import AdminSettingsCookies, { action } from "./cookies";
|
||||
import { getOrCreateAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
let routeLoaderData = {
|
||||
title: "Cookie Settings",
|
||||
appConfiguration: {
|
||||
cookies: {
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
let fetcherData: { success?: string; error?: string; fieldErrors?: Record<string, string[]> } | undefined;
|
||||
let fetcherSubmit = vi.fn();
|
||||
let canUpdate = true;
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
useFetcher: () => ({
|
||||
data: fetcherData,
|
||||
state: "idle",
|
||||
submit: fetcherSubmit,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAdminData", () => ({
|
||||
useAdminData: () => ({ permissions: canUpdate ? ["admin.settings.cookies.update"] : [] }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({
|
||||
getUserHasPermission: vi.fn(() => canUpdate),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ csrf: "csrf-test-token" }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(),
|
||||
getOrCreateAppConfiguration: vi.fn(),
|
||||
updateAppConfiguration: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({
|
||||
createAdminLog: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: { success: vi.fn(), error: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({
|
||||
default: ({ title, buttons, children }: { title?: React.ReactNode; buttons?: React.ReactNode; children: React.ReactNode }) => (
|
||||
<main>
|
||||
<header>{title}</header>
|
||||
<div>{buttons}</div>
|
||||
{children}
|
||||
</main>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/BackButtonWithTitle", () => ({
|
||||
default: ({ children }: { children: React.ReactNode }) => <h1>{children}</h1>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({
|
||||
default: ({ children, ...props }: React.ComponentProps<"button">) => <button {...props}>{children}</button>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/icons/PreviewIcon", () => ({
|
||||
default: () => <span aria-hidden="true" />,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputCheckboxWithDescription", () => ({
|
||||
default: ({ name, title, value, disabled }: { name: string; title: string; value?: boolean; disabled?: boolean }) => (
|
||||
<label>
|
||||
{title}
|
||||
<input name={name} type="checkbox" defaultChecked={value} disabled={disabled} />
|
||||
</label>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/modals/Modal", () => ({
|
||||
default: ({ open, children }: { open: boolean; children: React.ReactNode }) => (open ? <section aria-label="Cookie preview">{children}</section> : null),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/cookies/CookieConsentSettings", () => ({
|
||||
default: () => <div>Cookie consent preview</div>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/cookies/CookiesList", () => ({
|
||||
default: () => <div>Cookies list</div>,
|
||||
}));
|
||||
|
||||
const verifyUserHasPermissionMock = vi.mocked(verifyUserHasPermission);
|
||||
const getOrCreateAppConfigurationMock = vi.mocked(getOrCreateAppConfiguration);
|
||||
const updateAppConfigurationMock = vi.mocked(updateAppConfiguration);
|
||||
const createAdminLogMock = vi.mocked(createAdminLog);
|
||||
|
||||
function postRequest(form: FormData) {
|
||||
return new Request("https://admin.example.com/settings/cookies?token=secret", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(form as unknown as Record<string, string>),
|
||||
});
|
||||
}
|
||||
|
||||
function validForm() {
|
||||
const form = new FormData();
|
||||
form.set("action", "update");
|
||||
form.set("enabled", "true");
|
||||
return form;
|
||||
}
|
||||
|
||||
describe("admin cookie settings route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
fetcherData = undefined;
|
||||
fetcherSubmit = vi.fn();
|
||||
canUpdate = true;
|
||||
routeLoaderData = { title: "Cookie Settings", appConfiguration: { cookies: { enabled: true } } };
|
||||
verifyUserHasPermissionMock.mockResolvedValue(undefined as never);
|
||||
getOrCreateAppConfigurationMock.mockResolvedValue(undefined as never);
|
||||
updateAppConfigurationMock.mockResolvedValue(undefined as never);
|
||||
createAdminLogMock.mockResolvedValue(undefined as never);
|
||||
});
|
||||
|
||||
it("rejects invalid actions before permission, database, or audit side effects", async () => {
|
||||
const form = validForm();
|
||||
form.set("action", "delete");
|
||||
|
||||
const response = await action({ request: postRequest(form), params: {}, context: {}, unstable_pattern: "admin/settings/cookies" });
|
||||
const body = await (response as Response).json();
|
||||
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(body.fieldErrors.action).toEqual(["Invalid action."]);
|
||||
expect(verifyUserHasPermissionMock).not.toHaveBeenCalled();
|
||||
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(createAdminLogMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects tampered enabled values before permission, database, or audit side effects", async () => {
|
||||
const form = validForm();
|
||||
form.set("enabled", "maybe");
|
||||
|
||||
const response = await action({ request: postRequest(form), params: {}, context: {}, unstable_pattern: "admin/settings/cookies" });
|
||||
const body = await (response as Response).json();
|
||||
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(body.fieldErrors.enabled).toEqual(["Boolean value is invalid."]);
|
||||
expect(verifyUserHasPermissionMock).not.toHaveBeenCalled();
|
||||
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(createAdminLogMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("propagates permission rejection for valid mutations without database or audit side effects", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
verifyUserHasPermissionMock.mockRejectedValue(rejection);
|
||||
|
||||
await expect(action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/cookies" })).rejects.toBe(rejection);
|
||||
|
||||
expect(verifyUserHasPermissionMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.cookies.update");
|
||||
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(createAdminLogMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates valid cookie settings and writes a redacted audit payload without URL query secrets", async () => {
|
||||
const response = await action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/cookies" });
|
||||
const body = await (response as Response).json();
|
||||
|
||||
expect((response as Response).status).toBe(200);
|
||||
expect(body.success).toBe("shared.updated");
|
||||
expect(updateAppConfigurationMock).toHaveBeenCalledWith({ cookiesEnabled: true });
|
||||
expect(createAdminLogMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.updated", expect.any(String));
|
||||
const auditPayload = createAdminLogMock.mock.calls[0][2];
|
||||
expect(auditPayload).toContain("cookies");
|
||||
expect(auditPayload).toContain("cookiesEnabled");
|
||||
expect(auditPayload).toContain('"cookiesEnabled":true');
|
||||
expect(auditPayload).not.toContain("token=secret");
|
||||
});
|
||||
|
||||
it("renders accessible fetcher action and field errors", () => {
|
||||
fetcherData = { error: "shared.invalidForm", fieldErrors: { enabled: ["Boolean value is invalid."], action: ["Invalid action."] } };
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsCookies />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const alert = screen.getByRole("alert");
|
||||
expect(alert).toHaveTextContent("shared.invalidForm");
|
||||
expect(alert).toHaveTextContent("enabled: Boolean value is invalid.");
|
||||
expect(alert).toHaveTextContent("action: Invalid action.");
|
||||
});
|
||||
|
||||
it("preserves the preview modal path and disables updates without permission", () => {
|
||||
canUpdate = false;
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsCookies />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("settings.admin.cookies.fields.enabled.title")).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "shared.preview" })).toBeEnabled();
|
||||
});
|
||||
});
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useFetcher } from "react-router";
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CookieConsentSettings from "~/components/cookies/CookieConsentSettings";
|
||||
import CookiesList from "~/components/cookies/CookiesList";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import PreviewIcon from "~/components/ui/icons/PreviewIcon";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { AppConfiguration, getAppConfiguration, getOrCreateAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { parseAdminSettingsForm, redactSettingsAuditDetails } from "~/utils/services/adminSettingsValidation.server";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { toast } from "sonner";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
appConfiguration: AppConfiguration;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await verifyUserHasPermission(request, "admin.settings.cookies.view");
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.admin.cookies.title")} | ${process.env.APP_NAME}`,
|
||||
appConfiguration,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
fieldErrors?: Record<string, string[]>;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const parsed = parseAdminSettingsForm("cookies", form);
|
||||
if (!parsed.ok) {
|
||||
return Response.json({ error: t("shared.invalidForm"), fieldErrors: parsed.errors }, { status: parsed.status });
|
||||
}
|
||||
|
||||
await verifyUserHasPermission(request, "admin.settings.cookies.update");
|
||||
await getOrCreateAppConfiguration({ request });
|
||||
await updateAppConfiguration(parsed.data);
|
||||
await createAdminLog(request, "admin.settings.updated", redactSettingsAuditDetails("cookies", parsed.data));
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
};
|
||||
|
||||
export default function AdminSettingsCookies() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
|
||||
const [canUpdate] = useState(getUserHasPermission(adminData, "admin.settings.cookies.update"));
|
||||
const [enabled, setEnabled] = useState(data.appConfiguration.cookies.enabled);
|
||||
|
||||
const [showCookieSettingsModal, setShowCookieSettingsModal] = useState(false);
|
||||
const fieldErrors = fetcher.data?.fieldErrors ?? {};
|
||||
const fieldErrorEntries = Object.entries(fieldErrors);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.success) {
|
||||
toast.success(fetcher.data.success);
|
||||
} else if (fetcher.data?.error) {
|
||||
toast.error(fetcher.data.error);
|
||||
}
|
||||
}, [fetcher.data]);
|
||||
|
||||
function onChangeEnabled(value: boolean) {
|
||||
setEnabled(value);
|
||||
const form = new FormData();
|
||||
form.set("action", "update");
|
||||
form.set("enabled", value.toString());
|
||||
if (rootData.csrf) {
|
||||
form.set("csrf", rootData.csrf);
|
||||
}
|
||||
fetcher.submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.cookies.title")}</BackButtonWithTitle>}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonSecondary onClick={() => setShowCookieSettingsModal(true)}>
|
||||
<PreviewIcon className="h-4 w-4" />
|
||||
<div>{t("shared.preview")}</div>
|
||||
</ButtonSecondary>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Modal open={showCookieSettingsModal} setOpen={setShowCookieSettingsModal}>
|
||||
<CookieConsentSettings onUpdated={() => setShowCookieSettingsModal(false)} />
|
||||
</Modal>
|
||||
|
||||
<div>
|
||||
{(fetcher.data?.error || fieldErrorEntries.length > 0) && (
|
||||
<div role="alert" className="mb-4 rounded-md border border-red-200 bg-red-50 p-4 text-sm text-red-800">
|
||||
{fetcher.data?.error && <p className="font-medium">{fetcher.data.error}</p>}
|
||||
{fieldErrorEntries.length > 0 && (
|
||||
<ul className="mt-2 list-disc space-y-1 pl-5">
|
||||
{fieldErrorEntries.flatMap(([field, messages]) =>
|
||||
messages.map((message) => (
|
||||
<li key={`${field}-${message}`}>
|
||||
<span className="font-medium">{field}</span>: {message}
|
||||
</li>
|
||||
))
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="enabled"
|
||||
value={enabled}
|
||||
setValue={(e) => onChangeEnabled(Boolean(e))}
|
||||
title={t("settings.admin.cookies.fields.enabled.title")}
|
||||
description={t("settings.admin.cookies.fields.enabled.description")}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
<CookiesList editing={true} />
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+2
-4
@@ -1,15 +1,13 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Form, useActionData, useLoaderData } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { deleteAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
@@ -59,7 +57,7 @@ export default function AdminSettingsDanger() {
|
||||
}
|
||||
}, [actionData]);
|
||||
return (
|
||||
<EditPageLayout title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.danger.title")}</BackButtonWithTitle>}>
|
||||
<EditPageLayout>
|
||||
<Form method="post" className="divide-y-gray-200 mt-6 space-y-8 divide-y">
|
||||
{rootData.csrf && <input hidden readOnly name="csrf" value={rootData.csrf} />}
|
||||
<input name="action" value="delete" hidden readOnly />
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
useActionData,
|
||||
useLoaderData,
|
||||
useNavigation,
|
||||
useSubmit,
|
||||
} from "react-router";
|
||||
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { AdminSalesContactsPage } from "~/components/screens/admin/sales/data/AdminSalesContactsPage";
|
||||
import {
|
||||
loadAdminSalesDataRoute,
|
||||
mutateAdminSalesDataRoute,
|
||||
type AdminSalesDataActionData,
|
||||
} from "~/services/admin/admin-sales-data-route.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
export const loader = loadAdminSalesDataRoute;
|
||||
export const action = mutateAdminSalesDataRoute;
|
||||
|
||||
export function HydrateFallback(): React.JSX.Element {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminSalesFieldsTagsRoute(): React.JSX.Element {
|
||||
const { t } = useTranslation();
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData() as AdminSalesDataActionData | undefined;
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const submitIntent = (
|
||||
intent: string,
|
||||
values: Record<string, string | readonly string[] | number | boolean>
|
||||
) => {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("intent", intent);
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
form.set(key, Array.isArray(value) ? JSON.stringify(value) : String(value));
|
||||
}
|
||||
submit(form, { method: "post" });
|
||||
};
|
||||
|
||||
return (
|
||||
<AdminSalesContactsPage
|
||||
vm={vm}
|
||||
view="fields-tags"
|
||||
preview={null}
|
||||
submitting={navigation.state === "submitting"}
|
||||
successMessage={actionData?.success ?? null}
|
||||
errorMessage={actionData?.error ?? null}
|
||||
actions={{
|
||||
onPreviewImport: () => undefined,
|
||||
onConfirmImport: () => undefined,
|
||||
onExport: () => undefined,
|
||||
onCreateTag: (input) =>
|
||||
submitIntent("create-tag", {
|
||||
name: input.name,
|
||||
color: input.color ?? "",
|
||||
reason: t("admin.sales.data.audit.tagCreated"),
|
||||
}),
|
||||
onCreateCustomField: (input) =>
|
||||
submitIntent("create-field", {
|
||||
...input,
|
||||
options: input.options,
|
||||
reason: t("admin.sales.data.audit.fieldCreated"),
|
||||
}),
|
||||
onBulkUpdate: () => undefined,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+10
-8
@@ -3,7 +3,7 @@ import { render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import AdminSettingsGeneral, { action } from "./general";
|
||||
import { getOrCreateAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { createUserSession } from "~/utils/session.server";
|
||||
@@ -51,7 +51,6 @@ vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(),
|
||||
getOrCreateAppConfiguration: vi.fn(),
|
||||
updateAppConfiguration: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -73,8 +72,8 @@ vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ csrf: "csrf-test-token" }),
|
||||
}));
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
default: { success: vi.fn(), error: vi.fn() },
|
||||
vi.mock("sonner", () => ({
|
||||
toast: { success: vi.fn(), error: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({
|
||||
@@ -136,7 +135,6 @@ vi.mock("~/components/ui/input/InputSelect", () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
const getOrCreateAppConfigurationMock = vi.mocked(getOrCreateAppConfiguration);
|
||||
const updateAppConfigurationMock = vi.mocked(updateAppConfiguration);
|
||||
const createAdminLogMock = vi.mocked(createAdminLog);
|
||||
const storeFileMock = vi.mocked(storeFile);
|
||||
@@ -178,7 +176,6 @@ describe("admin general settings route", () => {
|
||||
scripts: { head: "", body: "" },
|
||||
},
|
||||
};
|
||||
getOrCreateAppConfigurationMock.mockResolvedValue(undefined as never);
|
||||
updateAppConfigurationMock.mockResolvedValue(undefined as never);
|
||||
createAdminLogMock.mockResolvedValue(undefined as never);
|
||||
createUserSessionMock.mockResolvedValue(new Response(null, { status: 204 }) as never);
|
||||
@@ -193,7 +190,6 @@ describe("admin general settings route", () => {
|
||||
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(body.fieldErrors.action).toEqual(["Invalid action."]);
|
||||
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(storeFileMock).not.toHaveBeenCalled();
|
||||
expect(createAdminLogMock).not.toHaveBeenCalled();
|
||||
@@ -208,7 +204,6 @@ describe("admin general settings route", () => {
|
||||
|
||||
expect((response as Response).status).toBe(400);
|
||||
expect(body.fieldErrors.name).toEqual(["This field is required."]);
|
||||
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(storeFileMock).not.toHaveBeenCalled();
|
||||
expect(createAdminLogMock).not.toHaveBeenCalled();
|
||||
@@ -240,6 +235,13 @@ describe("admin general settings route", () => {
|
||||
expect(auditPayload).not.toContain("token=secret");
|
||||
});
|
||||
|
||||
it("uses the already MFA-assured AdminSession instead of a second HiveGrid TOTP stack", async () => {
|
||||
const response = await action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/general" });
|
||||
|
||||
expect((response as Response).status).toBe(204);
|
||||
expect(updateAppConfigurationMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renders accessible action and field errors", () => {
|
||||
routeActionData = { error: "settings.admin.invalid", fieldErrors: { name: ["This field is required."], action: ["Invalid action."] } };
|
||||
|
||||
|
||||
+88
-18
@@ -8,7 +8,7 @@ import InputImage from "~/components/ui/input/InputImage";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { AppConfiguration, getAppConfiguration, getOrCreateAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { AppConfiguration, getAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
@@ -20,10 +20,8 @@ import { defaultThemes } from "~/utils/theme/defaultThemes";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import clsx from "clsx";
|
||||
import { createUserSession, getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
@@ -60,8 +58,6 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
return Response.json({ error: t("shared.invalidForm"), fieldErrors: parsed.errors }, { status: parsed.status });
|
||||
}
|
||||
|
||||
await getOrCreateAppConfiguration({ request });
|
||||
|
||||
const logo = parsed.data.brandingLogo?.toString() ?? "";
|
||||
const logoDarkMode = parsed.data.brandingLogoDarkMode?.toString() ?? "";
|
||||
const icon = parsed.data.brandingIcon?.toString() ?? "";
|
||||
@@ -69,11 +65,56 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
const favicon = parsed.data.brandingFavicon?.toString() ?? "";
|
||||
|
||||
const { storedLogo, storedLogoDarkMode, storedIcon, storedIconDarkMode, storedFavicon } = await promiseHash({
|
||||
storedLogo: logo ? storeFile({ bucket: "branding", content: logo, id: "logo", scan: { context: "mediaLibrary", enqueuePostScan: true, onReject: auditRejectedUpload(request, "admin.general.branding"), filename: "logo" } }) : Promise.resolve(""),
|
||||
storedLogoDarkMode: logoDarkMode ? storeFile({ bucket: "branding", content: logoDarkMode, id: "logo-dark-mode", scan: { context: "mediaLibrary", enqueuePostScan: true, onReject: auditRejectedUpload(request, "admin.general.branding"), filename: "logo-dark-mode" } }) : Promise.resolve(""),
|
||||
storedIcon: icon ? storeFile({ bucket: "branding", content: icon, id: "icon", scan: { context: "mediaLibrary", enqueuePostScan: true, onReject: auditRejectedUpload(request, "admin.general.branding"), filename: "icon" } }) : Promise.resolve(""),
|
||||
storedIconDarkMode: iconDarkMode ? storeFile({ bucket: "branding", content: iconDarkMode, id: "icon-dark-mode", scan: { context: "mediaLibrary", enqueuePostScan: true, onReject: auditRejectedUpload(request, "admin.general.branding"), filename: "icon-dark-mode" } }) : Promise.resolve(""),
|
||||
storedFavicon: favicon ? storeFile({ bucket: "branding", content: favicon, id: "favicon", scan: { context: "mediaLibrary", enqueuePostScan: true, onReject: auditRejectedUpload(request, "admin.general.branding"), filename: "favicon" } }) : Promise.resolve(""),
|
||||
storedLogo: logo
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: logo,
|
||||
id: "logo",
|
||||
scan: { context: "mediaLibrary", requireMalwareScan: true, onReject: auditRejectedUpload(request, "admin.general.branding"), filename: "logo" },
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedLogoDarkMode: logoDarkMode
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: logoDarkMode,
|
||||
id: "logo-dark-mode",
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
requireMalwareScan: true,
|
||||
onReject: auditRejectedUpload(request, "admin.general.branding"),
|
||||
filename: "logo-dark-mode",
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedIcon: icon
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: icon,
|
||||
id: "icon",
|
||||
scan: { context: "mediaLibrary", requireMalwareScan: true, onReject: auditRejectedUpload(request, "admin.general.branding"), filename: "icon" },
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedIconDarkMode: iconDarkMode
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: iconDarkMode,
|
||||
id: "icon-dark-mode",
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
requireMalwareScan: true,
|
||||
onReject: auditRejectedUpload(request, "admin.general.branding"),
|
||||
filename: "icon-dark-mode",
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedFavicon: favicon
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: favicon,
|
||||
id: "favicon",
|
||||
scan: { context: "mediaLibrary", requireMalwareScan: true, onReject: auditRejectedUpload(request, "admin.general.branding"), filename: "favicon" },
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
});
|
||||
|
||||
const updateData = {
|
||||
@@ -88,7 +129,7 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
await updateAppConfiguration(updateData);
|
||||
await createAdminLog(request, "admin.settings.updated", redactSettingsAuditDetails("general", updateData));
|
||||
if (updateData.theme !== userInfo.theme) {
|
||||
return createUserSession({ ...userInfo, theme: updateData.theme?.toString() });
|
||||
return createUserSession({ ...userInfo, theme: updateData.theme?.toString() }, "", { request });
|
||||
}
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
};
|
||||
@@ -118,7 +159,7 @@ export default function AdminSettingsGeneral() {
|
||||
}
|
||||
}, [actionData]);
|
||||
return (
|
||||
<EditPageLayout title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.general.title")}</BackButtonWithTitle>}>
|
||||
<EditPageLayout>
|
||||
<Form method="post" className="mt-6 space-y-8">
|
||||
{(actionData?.error || fieldErrorEntries.length > 0) && (
|
||||
<div role="alert" className="rounded-md border border-red-200 bg-red-50 p-4 text-sm text-red-800">
|
||||
@@ -141,7 +182,13 @@ export default function AdminSettingsGeneral() {
|
||||
<InputGroup title={t("settings.admin.general.sections.general")}>
|
||||
<div className="grid grid-cols-1 gap-y-6 sm:grid-cols-6 sm:gap-x-6">
|
||||
<div className="sm:col-span-2">
|
||||
<InputText name="name" title={t("settings.admin.general.fields.applicationName")} defaultValue={data.appConfiguration.app.name ?? ""} disabled={!canUpdate} required />
|
||||
<InputText
|
||||
name="name"
|
||||
title={t("settings.admin.general.fields.applicationName")}
|
||||
defaultValue={data.appConfiguration.app.name ?? ""}
|
||||
disabled={!canUpdate}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<InputText name="url" title={t("settings.admin.general.fields.url")} defaultValue={data.appConfiguration.app.url ?? ""} disabled required />
|
||||
@@ -160,7 +207,10 @@ export default function AdminSettingsGeneral() {
|
||||
component: (
|
||||
<div className="flex items-center space-x-2">
|
||||
<div
|
||||
className={clsx(`theme-${item.value}`, "bg-primary text-primary inline-flex shrink-0 items-center rounded-full text-xs font-medium")}
|
||||
className={clsx(
|
||||
`theme-${item.value}`,
|
||||
"bg-primary text-primary inline-flex shrink-0 items-center rounded-full text-xs font-medium"
|
||||
)}
|
||||
>
|
||||
<svg className={clsx("h-2 w-2")} fill="currentColor" viewBox="0 0 8 8">
|
||||
<circle cx={4} cy={4} r={3} />
|
||||
@@ -180,10 +230,23 @@ export default function AdminSettingsGeneral() {
|
||||
<InputGroup title={t("settings.admin.general.sections.branding")}>
|
||||
<div className="grid grid-cols-1 gap-y-6 sm:grid-cols-6 sm:gap-x-6">
|
||||
<div className="sm:col-span-3">
|
||||
<InputImage name="logo" title={t("settings.admin.general.fields.logoLightMode")} value={logoLight} setValue={setLogoLight} disabled={!canUpdate} />
|
||||
<InputImage
|
||||
name="logo"
|
||||
title={t("settings.admin.general.fields.logoLightMode")}
|
||||
value={logoLight}
|
||||
setValue={setLogoLight}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputImage name="logoDarkMode" title={t("settings.admin.general.fields.logoDarkMode")} value={logoDarkMode} setValue={setLogoDarkMode} disabled={!canUpdate} className="dark" />
|
||||
<InputImage
|
||||
name="logoDarkMode"
|
||||
title={t("settings.admin.general.fields.logoDarkMode")}
|
||||
value={logoDarkMode}
|
||||
setValue={setLogoDarkMode}
|
||||
disabled={!canUpdate}
|
||||
className="dark"
|
||||
/>
|
||||
</div>
|
||||
{/* <div className="sm:col-span-6">
|
||||
<PreviewLogo />
|
||||
@@ -192,7 +255,14 @@ export default function AdminSettingsGeneral() {
|
||||
<InputImage name="icon" title={t("settings.admin.general.fields.icon")} value={iconLight} setValue={setIconLight} disabled={!canUpdate} />
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputImage name="iconDarkMode" title={t("settings.admin.general.fields.iconDarkMode")} value={iconDarkMode} setValue={setIconDarkMode} disabled={!canUpdate} className="dark" />
|
||||
<InputImage
|
||||
name="iconDarkMode"
|
||||
title={t("settings.admin.general.fields.iconDarkMode")}
|
||||
value={iconDarkMode}
|
||||
setValue={setIconDarkMode}
|
||||
disabled={!canUpdate}
|
||||
className="dark"
|
||||
/>
|
||||
</div>
|
||||
{/* <div className="sm:col-span-6">
|
||||
<PreviewIcon />
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import { adminLeadAutomationFormSchema, buildAdminLeadAutomationVM } from "@hivegrid/view-models";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminSalesLeadSettingsPage } from "~/components/screens/admin/sales/leads/AdminSalesLeadSettingsPage";
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { listPlatformLeadAssignees, requirePlatformLeadAdmin, runAsPlatformLeadOperator } from "~/services/admin/platform-leads.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
return runAsPlatformLeadOperator(request, async ({ access, service, advancedService }) => {
|
||||
requirePlatformLeadAdmin(access);
|
||||
const [config, sources, assignees] = await Promise.all([advancedService.listAutomationConfig(), service.listSources(), listPlatformLeadAssignees()]);
|
||||
return {
|
||||
vm: buildAdminLeadAutomationVM({
|
||||
assignmentRules: config.assignmentRules,
|
||||
scoreRules: config.scoreRules,
|
||||
sourceOptions: sources.map((source) => ({ id: source.id, label: source.displayName })),
|
||||
assigneeOptions: assignees,
|
||||
canConfigure: access.canAdmin,
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = JSON.parse(String(form.get("payload") ?? "{}"));
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.sales.leadSettings.errors.invalid") }, { status: 400 });
|
||||
}
|
||||
const parsed = adminLeadAutomationFormSchema.safeParse(payload);
|
||||
if (!parsed.success) {
|
||||
return Response.json({ error: t("admin.sales.leadSettings.errors.invalid") }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await runAsPlatformLeadOperator(request, async ({ access, advancedService }) => {
|
||||
requirePlatformLeadAdmin(access);
|
||||
const audit = access.audit(t("admin.sales.leadSettings.audit.created"));
|
||||
const actor = {
|
||||
adminUserId: audit.actorAdminUserId,
|
||||
email: audit.actorEmail,
|
||||
reason: audit.reason,
|
||||
requestId: audit.requestId,
|
||||
ip: audit.actorIp,
|
||||
userAgent: audit.actorUserAgent,
|
||||
};
|
||||
if (parsed.data.intent === "create-assignment-rule") {
|
||||
await advancedService.createAssignmentRule({ ...parsed.data, actor });
|
||||
} else {
|
||||
await advancedService.createScoreRule({ ...parsed.data, actor });
|
||||
}
|
||||
});
|
||||
const target = new URL(adminPath("settings/leads", { mode: "host-aware" }), request.url);
|
||||
target.searchParams.set(
|
||||
"toast",
|
||||
parsed.data.intent === "create-assignment-rule"
|
||||
? "admin.sales.leadSettings.toast.assignmentRuleCreated"
|
||||
: "admin.sales.leadSettings.toast.scoreRuleCreated"
|
||||
);
|
||||
return Response.redirect(target, 303);
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.sales.leadSettings.errors.createFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export function HydrateFallback(): React.JSX.Element {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminSalesLeadSettingsRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData() as { readonly error?: string } | undefined;
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
|
||||
function submitPayload(payload: Record<string, unknown>) {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("payload", JSON.stringify(payload));
|
||||
submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminSalesLeadSettingsPage
|
||||
vm={vm}
|
||||
backHref={adminPath("leads", { mode: "host-aware" })}
|
||||
submitting={navigation.state === "submitting"}
|
||||
errorMessage={actionData?.error ?? null}
|
||||
actions={{
|
||||
onCreateAssignmentRule: (input) => submitPayload({ intent: "create-assignment-rule", ...input }),
|
||||
onCreateScoreRule: (input) => submitPayload({ intent: "create-score-rule", ...input }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { adminPipelineCreateActionSchema } from "@hivegrid/view-models";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
|
||||
import { AdminSalesPipelineSettingsPage } from "~/components/screens/admin/sales/deals/AdminSalesPipelineSettingsPage";
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { runAsAdminSalesPipelineOperator } from "~/services/admin/admin-sales-pipeline.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
return runAsAdminSalesPipelineOperator(request, "admin_sales.crm.assign", async ({ service }) => ({
|
||||
pipelines: await service.listPipelines(),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("intent") !== "create") return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
|
||||
try {
|
||||
const command = adminPipelineCreateActionSchema.parse(JSON.parse(String(form.get("payload") ?? "{}")));
|
||||
await runAsAdminSalesPipelineOperator(request, "admin_sales.crm.assign", ({ service, actor }) =>
|
||||
service.createPipeline({
|
||||
name: command.name,
|
||||
description: command.description,
|
||||
isDefault: command.isDefault,
|
||||
stages: command.stages,
|
||||
lossReasons: command.lossReasons,
|
||||
actor: actor(command.reason),
|
||||
})
|
||||
);
|
||||
const target = new URL(adminPath("sales/deals", { mode: "host-aware" }), request.url);
|
||||
target.searchParams.set("toast", "admin.sales.pipelineSettings.toast.created");
|
||||
return Response.redirect(target, 303);
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.sales.pipelineSettings.errors.createFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export function HydrateFallback(): React.JSX.Element {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminSalesPipelineSettingsRoute(): React.JSX.Element {
|
||||
const { pipelines } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData() as { readonly error?: string } | undefined;
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
return (
|
||||
<AdminSalesPipelineSettingsPage
|
||||
existingPipelines={pipelines}
|
||||
backHref={adminPath("sales/deals", { mode: "host-aware" })}
|
||||
submitting={navigation.state === "submitting"}
|
||||
errorMessage={actionData?.error ?? null}
|
||||
actions={{
|
||||
onCreate: (input) => {
|
||||
const form = appendCSRFToken(new FormData());
|
||||
form.set("intent", "create");
|
||||
form.set("payload", JSON.stringify(input));
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+21
-10
@@ -1,7 +1,6 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useRef } from "react";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { deletePlan, updatePlan } from "~/utils/services/.server/pricingService";
|
||||
@@ -12,7 +11,6 @@ import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/Subscri
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import BreadcrumbSimple from "~/components/ui/breadcrumbs/BreadcrumbSimple";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
@@ -21,6 +19,11 @@ import { toast } from "sonner";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { isHiveGridSubscriptionPricingModel } from "~/application/pricing/pricingModelPolicy";
|
||||
import { isManagedBillingCatalogProduct } from "~/application/pricing/adminCatalogPolicy";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
|
||||
const logger = createScopedLogger("admin.pricing.edit");
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
|
||||
|
||||
@@ -63,6 +66,9 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
if (!item) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
if (isManagedBillingCatalogProduct(item)) {
|
||||
return badRequest({ error: t("admin.pricing.errors.managedCatalogProduct") });
|
||||
}
|
||||
if (action === "edit") {
|
||||
if (!isHiveGridSubscriptionPricingModel(item.model)) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
@@ -105,15 +111,19 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
billingAddressCollection: isBillingRequired ? "required" : "auto",
|
||||
hasQuantity,
|
||||
canBuyAgain,
|
||||
kind: item.kind,
|
||||
code: item.code,
|
||||
lagoPlanCode: item.lagoPlanCode,
|
||||
};
|
||||
|
||||
try {
|
||||
await updatePlan(plan, features);
|
||||
await createAdminLog(request, "Updated pricing plan", plan.translatedTitle ?? plan.title);
|
||||
|
||||
return redirect(adminPath("settings/pricing", { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e?.toString() });
|
||||
return redirect(`${adminPath("settings/pricing", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.pricing.toast.updated")}`);
|
||||
} catch (error) {
|
||||
logger.error({ event: "admin.pricing.update_failed", ...toSafeErrorLog(error) }, "Admin pricing plan update failed");
|
||||
return badRequest({ error: t("admin.pricing.errors.updateFailed") });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.pricing.delete");
|
||||
@@ -122,9 +132,10 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
try {
|
||||
await deletePlan(item);
|
||||
return redirect(adminPath("settings/pricing", { mode: "host-aware" }));
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
return redirect(`${adminPath("settings/pricing", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.pricing.toast.deleted")}`);
|
||||
} catch (error) {
|
||||
logger.error({ event: "admin.pricing.delete_failed", ...toSafeErrorLog(error) }, "Admin pricing plan delete failed");
|
||||
return badRequest({ error: t("admin.pricing.errors.deleteFailed") });
|
||||
}
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
|
||||
+8
-1
@@ -10,6 +10,7 @@ const sourcePaths = [
|
||||
"apps/web/app/components/core/pricing/PricingFeaturesTable.tsx",
|
||||
"apps/web/app/routes/admin/settings/pricing.tsx",
|
||||
"apps/web/app/routes/admin/settings/pricing.new.tsx",
|
||||
"apps/web/app/routes/admin/settings/pricing.edit.$id.tsx",
|
||||
].map((sourcePath) => path.resolve(process.cwd(), sourcePath));
|
||||
|
||||
describe("pricing features route i18n", () => {
|
||||
@@ -38,11 +39,17 @@ describe("pricing features route i18n", () => {
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.percent");
|
||||
expect(source).toContain("admin.pricing.subscriptionCount");
|
||||
expect(source).toContain("formatters.number(item.tenantProducts?.length ?? 0)");
|
||||
expect(source).toContain("formatters.number(item.tenantProductCount ?? 0)");
|
||||
expect(source).toContain("formatters.number(product.features.length)");
|
||||
expect(source).toContain("formatters.number(item.value)");
|
||||
expect(source).toContain('t("shared.notSet")');
|
||||
expect(source).toContain("admin.pricing.features.errors.invalidFeatureTitleInPlan");
|
||||
expect(source).toContain("admin.pricing.errors.syncFailed");
|
||||
expect(source).toContain("admin.pricing.errors.visibilityUpdateFailed");
|
||||
expect(source).toContain("admin.pricing.errors.createFailed");
|
||||
expect(source).toContain("admin.pricing.errors.updateFailed");
|
||||
expect(source).toContain("admin.pricing.errors.deleteFailed");
|
||||
expect(source).not.toMatch(/badRequest\(\{ error: (?:error|e)\.(?:message|toString\(\))/u);
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('"Currency"');
|
||||
expect(source).not.toContain('"NA"');
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const {
|
||||
clearAllSubscriptionsCache,
|
||||
createSubscriptionFeature,
|
||||
deleteSubscriptionFeatures,
|
||||
getSubscriptionProductsInIds,
|
||||
} = vi.hoisted(() => ({
|
||||
clearAllSubscriptionsCache: vi.fn(),
|
||||
createSubscriptionFeature: vi.fn(),
|
||||
deleteSubscriptionFeatures: vi.fn(),
|
||||
getSubscriptionProductsInIds: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/subscriptions.server", () => ({
|
||||
createSubscriptionFeature,
|
||||
deleteSubscriptionFeatures,
|
||||
getAllSubscriptionProductsWithTenants: vi.fn(),
|
||||
getSubscriptionProductsInIds,
|
||||
}));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
||||
clearAllSubscriptionsCache,
|
||||
}));
|
||||
|
||||
import { action } from "./pricing.features";
|
||||
|
||||
function updateFeaturesRequest(planIds: string[]): Request {
|
||||
return new Request("http://admin.localhost:3000/admin/settings/pricing/features", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({
|
||||
action: "update-features",
|
||||
planIds: JSON.stringify(planIds),
|
||||
features: "[]",
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
describe("admin pricing feature mutations", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("rejects feature changes for canonical base plans before deleting features", async () => {
|
||||
getSubscriptionProductsInIds.mockResolvedValue([
|
||||
{ id: "starter", kind: "base_plan", code: "starter" },
|
||||
]);
|
||||
|
||||
const response = await action({
|
||||
request: updateFeaturesRequest(["starter"]),
|
||||
params: {},
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
error: "admin.pricing.errors.managedCatalogProduct",
|
||||
});
|
||||
expect(deleteSubscriptionFeatures).not.toHaveBeenCalled();
|
||||
expect(createSubscriptionFeature).not.toHaveBeenCalled();
|
||||
expect(clearAllSubscriptionsCache).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("continues to update explicitly editable add-ons", async () => {
|
||||
getSubscriptionProductsInIds.mockResolvedValue([
|
||||
{ id: "portal-monthly", kind: "recurring_add_on", code: "customer_portal_monthly" },
|
||||
]);
|
||||
|
||||
const response = await action({
|
||||
request: updateFeaturesRequest(["portal-monthly"]),
|
||||
params: {},
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
success: "admin.pricing.features.actions.updated",
|
||||
});
|
||||
expect(deleteSubscriptionFeatures).toHaveBeenCalledWith("portal-monthly");
|
||||
expect(createSubscriptionFeature).not.toHaveBeenCalled();
|
||||
expect(clearAllSubscriptionsCache).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
+12
-4
@@ -24,7 +24,7 @@ import OrderListButtons from "~/components/ui/sort/OrderListButtons";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import PlanFeatureDescription from "~/components/core/settings/subscription/PlanFeatureDescription";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import InputCombobox from "~/components/ui/input/InputCombobox";
|
||||
@@ -39,6 +39,7 @@ import { clearAllSubscriptionsCache } from "~/utils/services/.server/subscriptio
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { isManagedBillingCatalogProduct } from "~/application/pricing/adminCatalogPolicy";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
@@ -76,6 +77,9 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
if (plans.length === 0) {
|
||||
return Response.json({ error: t("admin.pricing.features.errors.noPlansFound") }, { status: 400 });
|
||||
}
|
||||
if (plans.some(isManagedBillingCatalogProduct)) {
|
||||
return Response.json({ error: t("admin.pricing.errors.managedCatalogProduct") }, { status: 400 });
|
||||
}
|
||||
const featuresInPlans = JSON.parse(form.get("features")?.toString() ?? "[]") as SubscriptionFeatureInPlansDto[];
|
||||
await Promise.all(
|
||||
plans.map(async (plan) => {
|
||||
@@ -169,7 +173,8 @@ export default function () {
|
||||
const [items, setItems] = useState<SubscriptionFeatureInPlansDto[]>([]);
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<SubscriptionFeatureInPlansDto>[]>([]);
|
||||
|
||||
const [selectedPlans, setSelectedPlans] = useState<SubscriptionProductDto[]>(data.items);
|
||||
const editablePlans = data.items.filter((plan) => !isManagedBillingCatalogProduct(plan));
|
||||
const [selectedPlans, setSelectedPlans] = useState<SubscriptionProductDto[]>(editablePlans);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
@@ -472,7 +477,10 @@ export default function () {
|
||||
<div>{t("shared.preview")}</div>
|
||||
</ButtonSecondary>
|
||||
<ButtonSecondary onClick={() => setItems(getInitialItems(selectedPlans))}>{t("shared.reset")}</ButtonSecondary>
|
||||
<LoadingButton disabled={getErrors().length > 0 || !getUserHasPermission(adminData, "admin.pricing.update")} onClick={onSave}>
|
||||
<LoadingButton
|
||||
disabled={selectedPlans.length === 0 || getErrors().length > 0 || !getUserHasPermission(adminData, "admin.pricing.update")}
|
||||
onClick={onSave}
|
||||
>
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</>
|
||||
@@ -488,7 +496,7 @@ export default function () {
|
||||
const ids = e as string[];
|
||||
setSelectedPlans(data.items.filter((p) => ids.includes(p.id ?? "")));
|
||||
}}
|
||||
options={data.items.map((p) => ({ name: t(p.title), value: p.id }))}
|
||||
options={editablePlans.map((p) => ({ name: t(p.title), value: p.id }))}
|
||||
minDisplayCount={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
+15
-6
@@ -1,6 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useRef } from "react";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
@@ -13,7 +12,6 @@ import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/Sub
|
||||
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
|
||||
import BreadcrumbSimple from "~/components/ui/breadcrumbs/BreadcrumbSimple";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { toast } from "sonner";
|
||||
@@ -21,6 +19,11 @@ import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { isHiveGridSubscriptionPricingModel } from "~/application/pricing/pricingModelPolicy";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import { deriveAdminCatalogProductKind } from "~/application/pricing/adminCatalogPolicy";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
|
||||
const logger = createScopedLogger("admin.pricing.create");
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
@@ -94,6 +97,10 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
if (!title) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planTitleRequired") });
|
||||
}
|
||||
const productKind = deriveAdminCatalogProductKind(prices);
|
||||
if (!productKind) {
|
||||
return badRequest({ error: t("admin.pricing.errors.invalidProductKind") });
|
||||
}
|
||||
|
||||
const plan: SubscriptionProductDto = {
|
||||
billingProviderId: "",
|
||||
@@ -112,15 +119,17 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
billingAddressCollection: isBillingRequired ? "required" : "auto",
|
||||
hasQuantity,
|
||||
canBuyAgain,
|
||||
kind: productKind,
|
||||
};
|
||||
|
||||
try {
|
||||
await createPlan(plan, prices, features, usageBasedPrices, t);
|
||||
await createAdminLog(request, "admin.pricing.plan.created", plan.title);
|
||||
|
||||
return redirect(adminPath("settings/pricing", { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e?.toString() });
|
||||
return redirect(`${adminPath("settings/pricing", { mode: "host-aware" })}?toast=${encodeURIComponent("admin.pricing.toast.created")}`);
|
||||
} catch (error) {
|
||||
logger.error({ event: "admin.pricing.create_failed", ...toSafeErrorLog(error) }, "Admin pricing plan creation failed");
|
||||
return badRequest({ error: t("admin.pricing.errors.createFailed") });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+98
-159
@@ -1,18 +1,17 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Fragment, useEffect, useRef, useState } from "react";
|
||||
import plans from "~/application/pricing/plans.server";
|
||||
import { ActionFunction, Link, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, Outlet, useSubmit, useNavigation } from "react-router";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import {
|
||||
getAllSubscriptionProducts,
|
||||
getAllSubscriptionProductsWithTenants,
|
||||
getSubscriptionProductTenantUsageCounts,
|
||||
getSubscriptionProduct,
|
||||
updateSubscriptionProduct,
|
||||
} from "@hivegrid/db/subscriptions.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { createPlans, deletePlan, syncPlan } from "~/utils/services/.server/pricingService";
|
||||
import { deletePlan, syncPlan } from "~/utils/services/.server/pricingService";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
@@ -21,24 +20,26 @@ import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/Subscri
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { getPossibleBillingPeriods } from "~/utils/helpers/PricingHelper";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import clsx from "clsx";
|
||||
import TrashIcon from "~/components/ui/icons/TrashIcon";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { HIVEGRID_SUBSCRIPTION_PRICING_MODELS, isHiveGridSubscriptionPricingModel } from "~/application/pricing/pricingModelPolicy";
|
||||
import { isManagedBillingCatalogProduct } from "~/application/pricing/adminCatalogPolicy";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
|
||||
const logger = createScopedLogger("admin.pricing");
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
@@ -46,25 +47,29 @@ type LoaderData = {
|
||||
items: SubscriptionProductDto[];
|
||||
};
|
||||
|
||||
async function getAdminSubscriptionProducts(): Promise<SubscriptionProductDto[]> {
|
||||
const [items, usageCounts] = await Promise.all([getAllSubscriptionProductsWithTenants(), getSubscriptionProductTenantUsageCounts()]);
|
||||
return items.map((item) => ({
|
||||
...item,
|
||||
tenantProductCount: item.id ? (usageCounts[item.id] ?? 0) : 0,
|
||||
}));
|
||||
}
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.pricing.title")} | ${process.env.APP_NAME}`,
|
||||
items: await getAllSubscriptionProductsWithTenants(),
|
||||
items: await getAdminSubscriptionProducts(),
|
||||
};
|
||||
|
||||
if (data.items.length === 0) {
|
||||
data.items = plans;
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export type PricingPlansActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
items?: Awaited<ReturnType<typeof getAllSubscriptionProducts>>;
|
||||
items?: SubscriptionProductDto[];
|
||||
};
|
||||
const badRequest = (data: PricingPlansActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
@@ -74,47 +79,15 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "create-all-plans") {
|
||||
await verifyUserHasPermission(request, "admin.pricing.create");
|
||||
const model = Number(form.get("model")) as PricingModel;
|
||||
if (model !== PricingModel.ALL && !isHiveGridSubscriptionPricingModel(model)) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
const items = await getAllSubscriptionProducts();
|
||||
if (items.length > 0) {
|
||||
return Response.json({
|
||||
items,
|
||||
});
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
plans
|
||||
.filter((f) => f.model === model || model === PricingModel.ALL)
|
||||
.map(async (plan) => {
|
||||
plan.translatedTitle = t(plan.title);
|
||||
plan.usageBasedPrices?.forEach((usageBasedPrice) => {
|
||||
usageBasedPrice.unitTitle = t(usageBasedPrice.unitTitle);
|
||||
usageBasedPrice.unitTitlePlural = t(usageBasedPrice.unitTitlePlural);
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
try {
|
||||
await createPlans(plans.filter((f) => f.model === model || model === PricingModel.ALL));
|
||||
await createAdminLog(request, "admin.pricing.createdPlans", plans.map((f) => t(f.title)).join(", "));
|
||||
|
||||
return Response.json({
|
||||
items: await getAllSubscriptionProducts(),
|
||||
});
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e?.toString() });
|
||||
}
|
||||
} else if (action === "sync-plan-with-payment-provider") {
|
||||
if (action === "sync-plan-with-payment-provider") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const item = await getSubscriptionProduct(id);
|
||||
if (!item) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planNotFound") });
|
||||
}
|
||||
if (isManagedBillingCatalogProduct(item)) {
|
||||
return badRequest({ error: t("admin.pricing.errors.managedCatalogProduct") });
|
||||
}
|
||||
try {
|
||||
item.translatedTitle = t(item.title);
|
||||
await syncPlan(
|
||||
@@ -129,10 +102,11 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
})
|
||||
);
|
||||
return Response.json({
|
||||
items: await getAllSubscriptionProducts(),
|
||||
items: await getAdminSubscriptionProducts(),
|
||||
});
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
} catch (error) {
|
||||
logger.error({ event: "admin.pricing.sync_failed", ...toSafeErrorLog(error) }, "Admin pricing plan sync failed");
|
||||
return badRequest({ error: t("admin.pricing.errors.syncFailed") });
|
||||
}
|
||||
} else if (action === "toggle") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
@@ -140,6 +114,9 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
if (!item) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planNotFound") });
|
||||
}
|
||||
if (isManagedBillingCatalogProduct(item)) {
|
||||
return badRequest({ error: t("admin.pricing.errors.managedCatalogProduct") });
|
||||
}
|
||||
try {
|
||||
await updateSubscriptionProduct(id, {
|
||||
public: !item.public,
|
||||
@@ -149,27 +126,34 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
status: t(!item.public ? "admin.pricing.status.public" : "admin.pricing.status.private"),
|
||||
}),
|
||||
});
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
} catch (error) {
|
||||
logger.error({ event: "admin.pricing.visibility_update_failed", ...toSafeErrorLog(error) }, "Admin pricing visibility update failed");
|
||||
return badRequest({ error: t("admin.pricing.errors.visibilityUpdateFailed") });
|
||||
}
|
||||
} else if (action === "bulk-delete") {
|
||||
await verifyUserHasPermission(request, "admin.pricing.delete");
|
||||
const ids = form.getAll("ids[]");
|
||||
const items = await getAllSubscriptionProducts();
|
||||
const items = await getAdminSubscriptionProducts();
|
||||
const itemsToDelete = items.filter((f) => ids.includes(f.id?.toString() ?? ""));
|
||||
await Promise.all(
|
||||
itemsToDelete.map(async (item) => {
|
||||
if (item.tenantProducts && item.tenantProducts.length > 0) {
|
||||
throw new Error(t("admin.pricing.errors.activeSubscriptions", { plans: t(item.title) }));
|
||||
}
|
||||
await createAdminLog(request, "admin.pricing.deletedPlan", item.id!);
|
||||
})
|
||||
);
|
||||
await Promise.all(
|
||||
itemsToDelete.map(async (item) => {
|
||||
if (itemsToDelete.some(isManagedBillingCatalogProduct)) {
|
||||
return badRequest({ error: t("admin.pricing.errors.managedCatalogProduct") });
|
||||
}
|
||||
const usedItem = itemsToDelete.find((item) => (item.tenantProductCount ?? 0) > 0);
|
||||
if (usedItem) {
|
||||
return badRequest({ error: t("admin.pricing.errors.activeSubscriptions", { plans: t(usedItem.title) }) });
|
||||
}
|
||||
try {
|
||||
for (const item of itemsToDelete) {
|
||||
await deletePlan(item);
|
||||
})
|
||||
);
|
||||
await createAdminLog(request, "admin.pricing.deletedPlan", item.id!);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error && typeof error === "object" && "code" in error && error.code === "P2003") {
|
||||
return badRequest({ error: t("admin.pricing.errors.activeSubscriptions", { plans: itemsToDelete.map((item) => t(item.title)).join(", ") }) });
|
||||
}
|
||||
logger.error({ event: "admin.pricing.bulk_delete_failed", ...toSafeErrorLog(error) }, "Admin pricing bulk delete failed");
|
||||
return badRequest({ error: t("admin.pricing.errors.deleteFailed") });
|
||||
}
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
}
|
||||
};
|
||||
@@ -186,13 +170,12 @@ export default function AdminPricingRoute() {
|
||||
|
||||
const [selectedItems, setSelectedItems] = useState<SubscriptionProductDto[]>([]);
|
||||
|
||||
const [model, setModel] = useState<PricingModel>(PricingModel.FLAT_RATE);
|
||||
const [items, setItems] = useState<SubscriptionProductDto[]>([]);
|
||||
const [, setAllFeatures] = useState<SubscriptionFeatureDto[]>([]);
|
||||
useEffect(() => {
|
||||
updateItems(data.items);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data.items, model]);
|
||||
}, [data.items]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
@@ -206,11 +189,7 @@ export default function AdminPricingRoute() {
|
||||
}, [actionData]);
|
||||
|
||||
function updateItems(items: SubscriptionProductDto[]) {
|
||||
if (items.filter((f) => f.id).length > 0) {
|
||||
setItems(items);
|
||||
} else {
|
||||
setItems(items.filter((f) => f.model === model || model === PricingModel.ALL));
|
||||
}
|
||||
setItems(items);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -239,15 +218,6 @@ export default function AdminPricingRoute() {
|
||||
// });
|
||||
// };
|
||||
|
||||
function createAllPlans() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "create-all-plans");
|
||||
form.set("model", model.toString());
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
// function syncPlanWithPaymentProvider(item: SubscriptionProductDto) {
|
||||
// const form = new FormData();
|
||||
// form.set("action", "sync-plan-with-payment-provider");
|
||||
@@ -269,10 +239,6 @@ export default function AdminPricingRoute() {
|
||||
// });
|
||||
// }
|
||||
|
||||
function createdPlans() {
|
||||
return data.items.filter((f) => f.id).length;
|
||||
}
|
||||
|
||||
// function getFeatureValue(item: SubscriptionProductDto, name: string) {
|
||||
// return item.features.find((f) => f.name === name);
|
||||
// }
|
||||
@@ -289,7 +255,6 @@ export default function AdminPricingRoute() {
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("admin.pricing.title")}</BackButtonWithTitle>}
|
||||
buttons={
|
||||
<>
|
||||
<Form method="post" className="flex h-9 items-center space-x-2">
|
||||
@@ -335,45 +300,13 @@ export default function AdminPricingRoute() {
|
||||
}
|
||||
>
|
||||
<div className="space-y-6">
|
||||
{createdPlans() === 0 && (
|
||||
<WarningBanner title={t("shared.warning")} text={t("admin.pricing.thesePricesAreFromFiles")}>
|
||||
<div className="mt-2 flex items-center space-x-2">
|
||||
<div className="w-44">
|
||||
<InputSelect
|
||||
name="model"
|
||||
title={t("models.subscriptionProduct.model")}
|
||||
withLabel={false}
|
||||
value={model}
|
||||
setValue={(e) => {
|
||||
setModel(Number(e));
|
||||
}}
|
||||
options={[
|
||||
...HIVEGRID_SUBSCRIPTION_PRICING_MODELS.map((value) => ({
|
||||
name: t("pricing." + PricingModel[value]),
|
||||
value,
|
||||
})),
|
||||
{
|
||||
name: t("shared.all"),
|
||||
value: PricingModel.ALL,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<ButtonSecondary
|
||||
type="button"
|
||||
onClick={createAllPlans}
|
||||
disabled={loading || createdPlans() > 0 || !getUserHasPermission(adminData, "admin.pricing.create")}
|
||||
className="bg-yellow-500 text-yellow-900 hover:bg-yellow-400"
|
||||
>
|
||||
{t("admin.pricing.generateFromFiles")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</WarningBanner>
|
||||
)}
|
||||
{data.items.some(isManagedBillingCatalogProduct) ? (
|
||||
<WarningBanner title={t("admin.pricing.managedBadge")} text={t("admin.pricing.catalogManaged")} />
|
||||
) : null}
|
||||
|
||||
<TableSimple
|
||||
selectedRows={selectedItems}
|
||||
onSelected={(items) => setSelectedItems(items)}
|
||||
onSelected={(items) => setSelectedItems(items.filter((item) => !isManagedBillingCatalogProduct(item)))}
|
||||
items={items}
|
||||
headers={[
|
||||
{
|
||||
@@ -384,14 +317,22 @@ export default function AdminPricingRoute() {
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.subscriptionProduct.title"),
|
||||
value: (item) => (
|
||||
<div className="group flex items-center gap-1">
|
||||
<Link to={"edit/" + item.id} className="group-hover:underline">
|
||||
{t(item.title)}
|
||||
</Link>
|
||||
{item.badge && <div className="border-border bg-theme-50 text-theme-800 ml-1 rounded-md border px-1 py-0.5 text-xs">{t(item.badge)}</div>}
|
||||
</div>
|
||||
),
|
||||
value: (item) => {
|
||||
const managed = isManagedBillingCatalogProduct(item);
|
||||
return (
|
||||
<div className="group flex items-center gap-1">
|
||||
{managed ? (
|
||||
<span>{t(item.title)}</span>
|
||||
) : (
|
||||
<Link to={"edit/" + item.id} className="group-hover:underline">
|
||||
{t(item.title)}
|
||||
</Link>
|
||||
)}
|
||||
{managed ? <SimpleBadge title={t("admin.pricing.managedBadge")} color={Colors.BLUE} /> : null}
|
||||
{item.badge && <div className="border-border bg-theme-50 text-theme-800 ml-1 rounded-md border px-1 py-0.5 text-xs">{t(item.badge)}</div>}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "model",
|
||||
@@ -422,8 +363,8 @@ export default function AdminPricingRoute() {
|
||||
value: (item) => (
|
||||
<div className="text-muted-foreground lowercase">
|
||||
{t("admin.pricing.subscriptionCount", {
|
||||
count: item.tenantProducts?.length ?? 0,
|
||||
formattedCount: formatters.number(item.tenantProducts?.length ?? 0),
|
||||
count: item.tenantProductCount ?? 0,
|
||||
formattedCount: formatters.number(item.tenantProductCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
),
|
||||
@@ -431,34 +372,32 @@ export default function AdminPricingRoute() {
|
||||
{
|
||||
name: "active",
|
||||
title: t("models.subscriptionProduct.status"),
|
||||
value: (item) => (
|
||||
<>
|
||||
{item.active ? (
|
||||
<>
|
||||
<button type="button" onClick={() => onToggle(item)} className="hover:underline">
|
||||
{item.public ? (
|
||||
<SimpleBadge title={t("models.subscriptionProduct.public")} color={Colors.TEAL} underline />
|
||||
) : (
|
||||
<SimpleBadge title={t("models.subscriptionProduct.custom")} color={Colors.ORANGE} underline />
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<SimpleBadge title={t("shared.inactive")} color={Colors.RED} />
|
||||
)}
|
||||
</>
|
||||
),
|
||||
value: (item) => {
|
||||
const status = item.public
|
||||
? <SimpleBadge title={t("models.subscriptionProduct.public")} color={Colors.TEAL} underline={!isManagedBillingCatalogProduct(item)} />
|
||||
: <SimpleBadge title={t("models.subscriptionProduct.custom")} color={Colors.ORANGE} underline={!isManagedBillingCatalogProduct(item)} />;
|
||||
if (!item.active) return <SimpleBadge title={t("shared.inactive")} color={Colors.RED} />;
|
||||
if (isManagedBillingCatalogProduct(item)) return status;
|
||||
return (
|
||||
<button type="button" onClick={() => onToggle(item)} className="hover:underline">
|
||||
{status}
|
||||
</button>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: t("shared.actions"),
|
||||
value: (item) => (
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonTertiary disabled={!item.id} to={"edit/" + item.id}>
|
||||
{t("shared.edit")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
),
|
||||
value: (item) =>
|
||||
isManagedBillingCatalogProduct(item) ? (
|
||||
<span className="text-muted-foreground text-xs">{t("admin.pricing.managedReadOnly")}</span>
|
||||
) : (
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonTertiary disabled={!item.id} to={"edit/" + item.id}>
|
||||
{t("shared.edit")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
@@ -474,7 +413,7 @@ function DeleteIconButton({ onClick, items }: { onClick: () => void; items: Subs
|
||||
const navigation = useNavigation();
|
||||
const confirmModal = useRef<RefConfirmModal>(null);
|
||||
function onDeleting() {
|
||||
const hasWithSub = items.some((f) => (f.tenantProducts?.length ?? 0) > 0);
|
||||
const hasWithSub = items.some((f) => (f.tenantProductCount ?? 0) > 0);
|
||||
if (hasWithSub) {
|
||||
toast.error(t("admin.pricing.errors.activeSubscriptions", { plans: items.map((f) => t(f.title ?? "")).join(", ") }));
|
||||
} else {
|
||||
|
||||
+7
-333
@@ -1,338 +1,12 @@
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { hashPassword, verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import toast from "react-hot-toast";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UserProfileSettings from "~/modules/users/components/UserProfileSettings";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { UserProfileUpdatedDto } from "~/modules/events/dtos/UserProfileUpdatedDto";
|
||||
import { UserPasswordUpdatedDto } from "~/modules/events/dtos/UserPasswordUpdatedDto";
|
||||
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import { UserProfileDeletedDto } from "~/modules/events/dtos/UserProfileDeletedDto";
|
||||
import { generateRecoveryCodes } from "~/utils/auth/mfa/recovery-codes.server";
|
||||
import { checkMfaStepUpState, clearMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { startTotpEnrollment, verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import {
|
||||
activateUserTotpPendingSecret,
|
||||
disableUserTotp,
|
||||
getUserTotpPendingEnrollment,
|
||||
getUserTotpStatus,
|
||||
setUserMfaRecoveryCodes,
|
||||
setUserTotpPendingSecret,
|
||||
updateUserPassword,
|
||||
updateUserProfile,
|
||||
type UserTotpStatus,
|
||||
} from "~/utils/db/users.db.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { commitSession, getUserInfo, getUserSession, storage, validateCSRFToken } from "~/utils/session.server";
|
||||
import type { CurrentSessionSettings } from "~/routes/app.$tenant/settings/profile";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
mfaStatus: UserTotpStatus | null;
|
||||
currentSession: CurrentSessionSettings;
|
||||
};
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
mfaError?: string;
|
||||
mfaStatus?: UserTotpStatus | null;
|
||||
otpauthUri?: string;
|
||||
recoveryCodes?: string[];
|
||||
currentSession?: CurrentSessionSettings;
|
||||
};
|
||||
|
||||
type CurrentSessionMfaStepUp = CurrentSessionSettings["mfaStepUp"];
|
||||
|
||||
function getCurrentSessionMfaStepUp(stepUp: ReturnType<typeof checkMfaStepUpState>): CurrentSessionMfaStepUp {
|
||||
if (stepUp.verified) {
|
||||
return { present: true, verified: true, stale: false, method: stepUp.state.method };
|
||||
}
|
||||
if (stepUp.reason === "missing") {
|
||||
return { present: false, verified: false, stale: false, reason: "missing" };
|
||||
}
|
||||
return { present: true, verified: false, stale: stepUp.reason === "stale", reason: stepUp.reason };
|
||||
export async function loader(_args: LoaderFunctionArgs) {
|
||||
throw redirect(adminPath("settings/security", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
function getCurrentSessionSettings(userInfo: Awaited<ReturnType<typeof getUserInfo>>, session: Awaited<ReturnType<typeof getUserSession>>): CurrentSessionSettings {
|
||||
const stepUp = checkMfaStepUpState(session, userInfo.userId);
|
||||
const cookies = Array.isArray(userInfo.cookies) ? userInfo.cookies : [];
|
||||
return {
|
||||
locale: userInfo.lng,
|
||||
lightOrDarkMode: userInfo.lightOrDarkMode === "dark" ? "dark" : "light",
|
||||
theme: typeof userInfo.theme === "string" && userInfo.theme.length > 0 ? userInfo.theme : null,
|
||||
cookieConsentCount: cookies.filter((cookie) => cookie?.allowed).length,
|
||||
impersonationActive: Boolean(userInfo.impersonatingFromUserId),
|
||||
mfaStepUp: getCurrentSessionMfaStepUp(stepUp),
|
||||
};
|
||||
}
|
||||
|
||||
function mfaJson(
|
||||
body: { mfaStatus: UserTotpStatus | null; mfaError?: string; otpauthUri?: string; recoveryCodes?: string[]; success?: string },
|
||||
init?: ResponseInit
|
||||
) {
|
||||
return Response.json(body, init);
|
||||
}
|
||||
|
||||
function isSixDigitTotpCode(code: FormDataEntryValue | null): code is string {
|
||||
return typeof code === "string" && /^\d{6}$/.test(code);
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const session = await getUserSession(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.profile.profileTitle")} | ${process.env.APP_NAME}`,
|
||||
mfaStatus: await getUserTotpStatus(userInfo.userId),
|
||||
currentSession: getCurrentSessionSettings(userInfo, session),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
|
||||
if (typeof action !== "string") {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userInfo.userId },
|
||||
include: { admin: true },
|
||||
});
|
||||
if (!user) {
|
||||
return Response.json({ error: t("settings.profile.errors.userNotFound") }, { status: 400 });
|
||||
}
|
||||
|
||||
const passwordCurrent = form.get("passwordCurrent")?.toString();
|
||||
|
||||
switch (action) {
|
||||
case "startTotpEnrollment": {
|
||||
const mfaStatus = await getUserTotpStatus(user.id);
|
||||
if (typeof passwordCurrent !== "string") {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.errors.currentPasswordRequired") }, { status: 400 });
|
||||
}
|
||||
const isCorrectPassword = (await verifyPassword(passwordCurrent, user.passwordHash)).valid;
|
||||
if (!isCorrectPassword) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
|
||||
const enrollment = startTotpEnrollment(user.email);
|
||||
await setUserTotpPendingSecret(user.id, enrollment.encryptedSecret);
|
||||
const updatedMfaStatus = await getUserTotpStatus(user.id);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.mfa.totp.enrollment.started",
|
||||
tenantId: null,
|
||||
userId: user.id,
|
||||
data: { user: { id: user.id, email: user.email }, mfaStatus: updatedMfaStatus },
|
||||
});
|
||||
return mfaJson({ success: t("settings.profile.mfa.enrollmentStarted"), mfaStatus: updatedMfaStatus, otpauthUri: enrollment.otpauthUri });
|
||||
}
|
||||
case "confirmTotpEnrollment": {
|
||||
const mfaStatus = await getUserTotpStatus(user.id);
|
||||
const code = form.get("code");
|
||||
if (!isSixDigitTotpCode(code)) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.mfa.enterCode") }, { status: 400 });
|
||||
}
|
||||
const pending = await getUserTotpPendingEnrollment(user.id);
|
||||
if (!pending?.totpPendingSecretEncrypted || !pending.totpPendingCreatedAt) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.mfa.noPendingEnrollment") }, { status: 400 });
|
||||
}
|
||||
if (!verifyTotpCode(pending.totpPendingSecretEncrypted, code)) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.mfa.invalidCode") }, { status: 400 });
|
||||
}
|
||||
await activateUserTotpPendingSecret(user.id, pending.totpPendingSecretEncrypted);
|
||||
const recoveryCodeGeneration = generateRecoveryCodes();
|
||||
await setUserMfaRecoveryCodes(user.id, recoveryCodeGeneration.entries, recoveryCodeGeneration.generatedAt);
|
||||
const updatedMfaStatus = await getUserTotpStatus(user.id);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.mfa.totp.enabled",
|
||||
tenantId: null,
|
||||
userId: user.id,
|
||||
data: {
|
||||
user: { id: user.id, email: user.email },
|
||||
mfaStatus: updatedMfaStatus,
|
||||
recoveryCodes: {
|
||||
generatedCount: recoveryCodeGeneration.codes.length,
|
||||
remainingCount: recoveryCodeGeneration.entries.filter((entry) => !entry.usedAt).length,
|
||||
generatedAt: recoveryCodeGeneration.generatedAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
return mfaJson({ success: t("settings.profile.mfa.enabled"), mfaStatus: updatedMfaStatus, recoveryCodes: recoveryCodeGeneration.codes });
|
||||
}
|
||||
case "disableTotpEnrollment": {
|
||||
const mfaStatus = await getUserTotpStatus(user.id);
|
||||
if (typeof passwordCurrent !== "string") {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.errors.currentPasswordRequired") }, { status: 400 });
|
||||
}
|
||||
const isCorrectPassword = (await verifyPassword(passwordCurrent, user.passwordHash)).valid;
|
||||
if (!isCorrectPassword) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
await disableUserTotp(user.id);
|
||||
const updatedMfaStatus = await getUserTotpStatus(user.id);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.mfa.totp.disabled",
|
||||
tenantId: null,
|
||||
userId: user.id,
|
||||
data: { user: { id: user.id, email: user.email }, mfaStatus: updatedMfaStatus },
|
||||
});
|
||||
return mfaJson({ success: t("settings.profile.mfa.disabled"), mfaStatus: updatedMfaStatus });
|
||||
}
|
||||
case "clearMfaStepUp": {
|
||||
const session = await getUserSession(request);
|
||||
clearMfaStepUpState(session);
|
||||
return Response.json(
|
||||
{ success: t("settings.profile.mfa.sessionCleared"), currentSession: getCurrentSessionSettings(userInfo, session) },
|
||||
{ headers: { "Set-Cookie": await commitSession(session) } }
|
||||
);
|
||||
}
|
||||
case "profile": {
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString() ?? "";
|
||||
const avatar = form.get("avatar")?.toString() ?? "";
|
||||
if (typeof firstName !== "string" || firstName.length < 2) {
|
||||
return Response.json({ error: t("settings.profile.errors.firstNameRequired") }, { status: 400 });
|
||||
}
|
||||
const avatarStored = avatar ? await storeFile({ bucket: "users-icons", content: avatar, id: userInfo.userId, scan: { context: "avatar", enqueuePostScan: true, onReject: auditRejectedUpload(request, "admin.profile.avatar"), filename: `${userInfo.userId}.avatar` } }) : avatar;
|
||||
const profile = await updateUserProfile({ firstName, lastName, avatar: avatarStored }, userInfo.userId);
|
||||
if (!profile) {
|
||||
return Response.json({ error: t("settings.profile.errors.profileUpdateFailed") }, { status: 400 });
|
||||
}
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.profile.updated",
|
||||
tenantId: null,
|
||||
userId: user.id,
|
||||
data: {
|
||||
email: user.email,
|
||||
new: { firstName, lastName },
|
||||
old: { firstName: user.firstName, lastName: user.lastName },
|
||||
userId: userInfo.userId,
|
||||
} satisfies UserProfileUpdatedDto,
|
||||
});
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
}
|
||||
case "password": {
|
||||
const passwordNew = form.get("passwordNew")?.toString();
|
||||
const passwordNewConfirm = form.get("passwordNewConfirm")?.toString();
|
||||
if (typeof passwordCurrent !== "string" || typeof passwordNew !== "string" || typeof passwordNewConfirm !== "string") {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
if (passwordNew !== passwordNewConfirm) {
|
||||
return Response.json({ error: t("account.shared.passwordMismatch") }, { status: 400 });
|
||||
}
|
||||
const policyResult = await validatePolicyPassword(passwordNew, { email: user.email });
|
||||
if (!policyResult.valid) {
|
||||
const first = policyResult.errors[0];
|
||||
return Response.json({ error: first ? t(first.code, first.args ?? {}) : t("settings.profile.errors.passwordMinLength") }, { status: 400 });
|
||||
}
|
||||
const isCorrectPassword = (await verifyPassword(passwordCurrent, user.passwordHash)).valid;
|
||||
if (!isCorrectPassword) {
|
||||
return Response.json({ error: t("settings.profile.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
const passwordHash = await hashPassword(passwordNew);
|
||||
await updateUserPassword({ passwordHash }, userInfo.userId);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.password.updated",
|
||||
tenantId: null,
|
||||
userId: user.id,
|
||||
data: { user: { id: user.id, email: user.email } } satisfies UserPasswordUpdatedDto,
|
||||
});
|
||||
return Response.json({ success: t("settings.profile.passwordUpdated") });
|
||||
}
|
||||
case "deleteAccount": {
|
||||
if (user.admin !== null) {
|
||||
return Response.json({ error: t("settings.profile.errors.cannotDeleteAdmin") }, { status: 400 });
|
||||
}
|
||||
if (typeof passwordCurrent !== "string" || passwordCurrent.length === 0) {
|
||||
return Response.json({ error: t("settings.profile.errors.currentPasswordRequired") }, { status: 400 });
|
||||
}
|
||||
const isCorrectPassword = (await verifyPassword(passwordCurrent, user.passwordHash)).valid;
|
||||
if (!isCorrectPassword) {
|
||||
return Response.json({ error: t("settings.profile.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
const { deletedTenants } = await deleteUserWithItsTenants(user.id);
|
||||
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({
|
||||
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,
|
||||
});
|
||||
const session = await getUserSession(request);
|
||||
return redirect("/login", { headers: { "Set-Cookie": await storage.destroySession(session) } });
|
||||
}
|
||||
}
|
||||
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function ProfileRoute() {
|
||||
const adminData = useAdminData();
|
||||
const loaderData = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout className="pb-20">
|
||||
<UserProfileSettings
|
||||
user={{
|
||||
...adminData.user,
|
||||
firstName: adminData.user.firstName ?? "",
|
||||
lastName: adminData.user.lastName ?? "",
|
||||
}}
|
||||
mfaStatus={actionData?.mfaStatus ?? loaderData.mfaStatus}
|
||||
otpauthUri={actionData?.otpauthUri}
|
||||
mfaError={actionData?.mfaError}
|
||||
recoveryCodes={actionData?.recoveryCodes}
|
||||
currentSession={actionData?.currentSession ?? loaderData.currentSession}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
export default function AdminProfileRedirect() {
|
||||
return null;
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
// @vitest-environment node
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { adminSession, transaction } = vi.hoisted(() => ({
|
||||
adminSession: {
|
||||
id: "session-current",
|
||||
adminUserId: "admin-1",
|
||||
adminUser: { id: "admin-1", email: "admin@example.test" },
|
||||
},
|
||||
transaction: {
|
||||
adminSession: { updateMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/rls-context.server", () => ({
|
||||
runWithRlsTransaction: vi.fn(async (_transaction, operation: () => Promise<unknown>) => operation()),
|
||||
}));
|
||||
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/admin-identity.server", () => ({
|
||||
requireAdminIdentityPermission: vi.fn(),
|
||||
runAsAdminIdentity: vi.fn(async (_request, _permission, operation) => operation(adminSession)),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: { $transaction: vi.fn(async (operation) => operation(transaction)) },
|
||||
}));
|
||||
|
||||
import { recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { requireAdminIdentityPermission, runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { action } from "./security";
|
||||
|
||||
function request(values: Record<string, string>) {
|
||||
return new Request("https://admin.example.test/settings/security", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams(values),
|
||||
});
|
||||
}
|
||||
|
||||
function callAction(values: Record<string, string>) {
|
||||
return action({
|
||||
request: request(values),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/settings/security",
|
||||
} as ActionFunctionArgs);
|
||||
}
|
||||
|
||||
describe("admin security settings action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(requireAdminIdentityPermission).mockResolvedValue(adminSession as never);
|
||||
transaction.adminSession.updateMany.mockResolvedValue({ count: 1 });
|
||||
});
|
||||
|
||||
it("revokes another own session and writes the mandatory audit in the same transaction", async () => {
|
||||
const response = await callAction({
|
||||
intent: "revoke-session",
|
||||
sessionId: "session-other",
|
||||
reason: "Verlorenes Arbeitsgerät",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
ok: true,
|
||||
messageKey: "admin.sales.security.toast.sessionRevoked",
|
||||
});
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin_identity.sessions.revoke");
|
||||
expect(runAsAdminIdentity).toHaveBeenCalledWith(expect.any(Request), "admin_identity.sessions.revoke", expect.any(Function));
|
||||
expect(transaction.adminSession.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: "session-other", adminUserId: adminSession.adminUserId, revokedAt: null },
|
||||
data: { revokedAt: expect.any(Date) },
|
||||
});
|
||||
expect(recordAdminAction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "security.sessionRevoked",
|
||||
actorUserId: adminSession.adminUserId,
|
||||
targetId: "session-other",
|
||||
reason: "Verlorenes Arbeitsgerät",
|
||||
}),
|
||||
transaction
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects revoking the current session before any mutation", async () => {
|
||||
const response = await callAction({
|
||||
intent: "revoke-session",
|
||||
sessionId: adminSession.id,
|
||||
reason: "Sitzung schließen",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(transaction.adminSession.updateMany).not.toHaveBeenCalled();
|
||||
expect(recordAdminAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the selected session no longer exists", async () => {
|
||||
transaction.adminSession.updateMany.mockResolvedValueOnce({ count: 0 });
|
||||
|
||||
const response = await callAction({
|
||||
intent: "revoke-session",
|
||||
sessionId: "session-missing",
|
||||
reason: "Verlorenes Arbeitsgerät",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(recordAdminAction).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useFetcher, useLoaderData } from "react-router";
|
||||
|
||||
import type { AuditEventWriterClient } from "@hivegrid/db/audit-events.server";
|
||||
import { runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
|
||||
import { buildAdminSecurityProfileVM } from "@hivegrid/view-models";
|
||||
|
||||
import { AdminSecurityProfilePage } from "~/components/screens/admin/sales/security/AdminSecurityProfilePage";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { assertAdminActionReason, recordAdminAction } from "~/services/admin/admin-action-audit.server";
|
||||
import { requireAdminIdentityPermission, runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type ActionData = { ok: true; messageKey: string } | { ok: false; errorKey: string };
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const session = await requireAdminIdentityPermission(request, "admin_identity.sessions.read");
|
||||
const admin = await runAsAdminIdentity(request, "admin_identity.sessions.read", () =>
|
||||
db.adminUser.findUnique({
|
||||
where: { id: session.adminUserId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
status: true,
|
||||
authentikSubject: true,
|
||||
lastSsoLoginAt: true,
|
||||
roles: {
|
||||
where: { role: { active: true } },
|
||||
select: { role: { select: { id: true, name: true, systemKey: true } } },
|
||||
},
|
||||
sessions: {
|
||||
where: { revokedAt: null, expiresAt: { gt: new Date() } },
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
lastSeenAt: true,
|
||||
expiresAt: true,
|
||||
approxLocation: true,
|
||||
userAgent: true,
|
||||
mfaAssuredAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
if (!admin) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
const { t } = await getTranslations(request);
|
||||
return {
|
||||
title: `${t("admin.sales.security.title")} | ${process.env.APP_NAME}`,
|
||||
vm: buildAdminSecurityProfileVM({
|
||||
identity: admin,
|
||||
roles: admin.roles.map((assignment) => assignment.role),
|
||||
sessions: admin.sessions,
|
||||
currentSessionId: session.id,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs): Promise<Response> {
|
||||
await validateCSRFToken(request);
|
||||
const currentSession = await requireAdminIdentityPermission(request, "admin_identity.sessions.revoke");
|
||||
const form = await request.formData();
|
||||
if (form.get("intent") !== "revoke-session") {
|
||||
return Response.json({ ok: false, errorKey: "admin.sales.security.errors.revokeFailed" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const sessionId = String(form.get("sessionId") ?? "").trim();
|
||||
if (!sessionId || sessionId === currentSession.id) {
|
||||
return Response.json({ ok: false, errorKey: "admin.sales.security.errors.revokeFailed" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
let reason: string;
|
||||
try {
|
||||
reason = assertAdminActionReason(String(form.get("reason") ?? ""));
|
||||
} catch {
|
||||
return Response.json({ ok: false, errorKey: "admin.audit.errors.reasonTooShort" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await runAsAdminIdentity(request, "admin_identity.sessions.revoke", () =>
|
||||
db.$transaction(async (transaction) =>
|
||||
runWithRlsTransaction(transaction, async () => {
|
||||
const revoked = await transaction.adminSession.updateMany({
|
||||
where: {
|
||||
id: sessionId,
|
||||
adminUserId: currentSession.adminUserId,
|
||||
revokedAt: null,
|
||||
},
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
if (revoked.count !== 1) return "missing" as const;
|
||||
await recordAdminAction(
|
||||
{
|
||||
action: "security.sessionRevoked",
|
||||
actorUserId: currentSession.adminUserId,
|
||||
actorEmail: currentSession.adminUser.email,
|
||||
targetKind: "admin-session",
|
||||
targetId: sessionId,
|
||||
reason,
|
||||
request,
|
||||
},
|
||||
transaction as unknown as AuditEventWriterClient
|
||||
);
|
||||
return "revoked" as const;
|
||||
})
|
||||
)
|
||||
);
|
||||
if (result !== "revoked") {
|
||||
return Response.json({ ok: false, errorKey: "admin.sales.security.errors.revokeFailed" } satisfies ActionData, { status: 404 });
|
||||
}
|
||||
return Response.json({ ok: true, messageKey: "admin.sales.security.toast.sessionRevoked" } satisfies ActionData);
|
||||
}
|
||||
|
||||
export default function AdminSecurityProfileRoute() {
|
||||
const data = useLoaderData<typeof loader>();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const rootData = useRootData();
|
||||
useSaveToast(fetcher.data?.ok ? fetcher.data : undefined);
|
||||
return (
|
||||
<AdminSecurityProfilePage
|
||||
vm={data.vm}
|
||||
busy={fetcher.state !== "idle"}
|
||||
errorKey={fetcher.data && !fetcher.data.ok ? fetcher.data.errorKey : undefined}
|
||||
actions={{
|
||||
onRevokeSession: ({ sessionId, reason }) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "revoke-session");
|
||||
form.set("sessionId", sessionId);
|
||||
form.set("reason", reason);
|
||||
if (rootData.csrf) form.set("csrf", rootData.csrf);
|
||||
fetcher.submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
-1
@@ -8,7 +8,6 @@ const settingsDir = dirname(fileURLToPath(import.meta.url));
|
||||
const protectedRoutes = [
|
||||
{ name: "general", file: "general.tsx", parserScope: "general" },
|
||||
{ name: "authentication", file: "authentication.tsx", parserScope: "authentication" },
|
||||
{ name: "cookies", file: "cookies.tsx", parserScope: "cookies" },
|
||||
] as const;
|
||||
|
||||
const transactionalEmailException = {
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
buildAdminTelephonySettingsVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import {
|
||||
resolveAircallOAuthConfig,
|
||||
} from "@hivegrid/integrations";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { useLoaderData } from "react-router";
|
||||
|
||||
import { AdminSalesLoadingPage } from "~/components/screens/admin/sales/AdminSalesLoadingPage";
|
||||
import { AdminTelephonySettingsPage } from "~/components/screens/admin/sales/telephony/AdminTelephonySettingsPage";
|
||||
import {
|
||||
listAdminTelephonyConnectionSettings,
|
||||
runAsAdminTelephonyOperator,
|
||||
} from "~/services/admin/admin-telephony-connections.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
return runAsAdminTelephonyOperator(
|
||||
request,
|
||||
"admin_sales.integrations.manage",
|
||||
async (context) => ({
|
||||
vm: buildAdminTelephonySettingsVM({
|
||||
providerConfigured: Boolean(
|
||||
resolveAircallOAuthConfig() &&
|
||||
process.env.ADMIN_AIRCALL_WEBHOOK_URL?.trim()
|
||||
),
|
||||
connections:
|
||||
await listAdminTelephonyConnectionSettings(context),
|
||||
}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function HydrateFallback(): React.JSX.Element {
|
||||
return <AdminSalesLoadingPage />;
|
||||
}
|
||||
|
||||
export default function AdminTelephonySettingsRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
return (
|
||||
<AdminTelephonySettingsPage
|
||||
vm={vm}
|
||||
salesHref={adminPath("sales/deals", { mode: "host-aware" })}
|
||||
connectHref={adminPath(
|
||||
"settings/telephony/connect/aircall",
|
||||
{ mode: "host-aware" }
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import {
|
||||
completeAdminAircallConnection,
|
||||
runAsAdminTelephonyOperator,
|
||||
} from "~/services/admin/admin-telephony-connections.server";
|
||||
import { consumeAdminTelephonyOAuthState } from "~/services/admin/admin-telephony-oauth-state.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const url = new URL(request.url);
|
||||
const code = url.searchParams.get("code") ?? "";
|
||||
const state = url.searchParams.get("state") ?? "";
|
||||
return runAsAdminTelephonyOperator(
|
||||
request,
|
||||
"admin_sales.integrations.manage",
|
||||
async (context) => {
|
||||
const challenge = consumeAdminTelephonyOAuthState(request, {
|
||||
expectedState: state,
|
||||
expectedAdminUserId: context.adminUserId,
|
||||
});
|
||||
if (!challenge.ok || !code) {
|
||||
return redirect("oauth-error", challenge.clearCookie, request.url);
|
||||
}
|
||||
try {
|
||||
await completeAdminAircallConnection({ context, code });
|
||||
return redirect("connected", challenge.clearCookie, request.url);
|
||||
} catch {
|
||||
return redirect("connection-error", challenge.clearCookie, request.url);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function redirect(status: string, cookie: string, requestUrl: string) {
|
||||
const location = new URL(
|
||||
`${adminPath("settings/telephony", { mode: "host-aware" })}?status=${status}`,
|
||||
requestUrl
|
||||
);
|
||||
return new Response(null, {
|
||||
status: 303,
|
||||
headers: {
|
||||
Location: location.toString(),
|
||||
"Set-Cookie": cookie,
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import {
|
||||
getAdminAircallAuthorizationUrl,
|
||||
runAsAdminTelephonyOperator,
|
||||
} from "~/services/admin/admin-telephony-connections.server";
|
||||
import { createAdminTelephonyOAuthState } from "~/services/admin/admin-telephony-oauth-state.server";
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
return runAsAdminTelephonyOperator(
|
||||
request,
|
||||
"admin_sales.integrations.manage",
|
||||
async (context) => {
|
||||
const challenge = createAdminTelephonyOAuthState({
|
||||
adminUserId: context.adminUserId,
|
||||
});
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: getAdminAircallAuthorizationUrl(challenge.state),
|
||||
"Set-Cookie": challenge.cookie,
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
+29
-2
@@ -5,6 +5,7 @@ import { MemoryRouter } from "react-router";
|
||||
import TransactionalEmailsRoute, { action, loader } from "./transactional-emails";
|
||||
import { getMailjetProviderStatus, updateMailjetSettings } from "~/modules/emails/services/TransactionalEmailSettings.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { sendEmail } from "~/modules/emails/services/EmailService";
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
@@ -153,6 +154,7 @@ let routeLoaderData = {
|
||||
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
|
||||
const getMailjetProviderStatusMock = vi.mocked(getMailjetProviderStatus);
|
||||
const updateMailjetSettingsMock = vi.mocked(updateMailjetSettings);
|
||||
const sendEmailMock = vi.mocked(sendEmail);
|
||||
|
||||
describe("admin transactional email route", () => {
|
||||
beforeEach(() => {
|
||||
@@ -180,18 +182,43 @@ describe("admin transactional email route", () => {
|
||||
});
|
||||
|
||||
it("action rejects provider tampering through the Mailjet update helper", async () => {
|
||||
updateMailjetSettingsMock.mockResolvedValue({ success: false, error: "Only Mailjet is supported for transactional email." });
|
||||
updateMailjetSettingsMock.mockResolvedValue({
|
||||
success: false,
|
||||
errorKey: "settings.admin.transactionalEmails.errors.unsupportedProvider",
|
||||
});
|
||||
const form = new FormData();
|
||||
form.set("action", "update-app-configuration");
|
||||
form.set("emailProvider", "sendgrid");
|
||||
|
||||
const result = await action({ request: new Request("https://admin.example.com/settings/transactional-emails", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form as unknown as Record<string, string>) }), params: {}, context: {}, unstable_pattern: "admin/settings/transactional-emails" });
|
||||
|
||||
expect(result).toEqual({ error: "Only Mailjet is supported for transactional email." });
|
||||
expect(result).toEqual({ error: "settings.admin.transactionalEmails.errors.unsupportedProvider" });
|
||||
const submittedForm = updateMailjetSettingsMock.mock.calls[0]?.[0];
|
||||
expect(submittedForm?.get("emailProvider")).toBe("sendgrid");
|
||||
});
|
||||
|
||||
it("returns a localized error instead of exposing mail provider failures", async () => {
|
||||
sendEmailMock.mockRejectedValueOnce(new Error("provider secret: upstream refused request"));
|
||||
const form = new FormData();
|
||||
form.set("action", "send-test");
|
||||
form.set("template", "welcome");
|
||||
form.set("email", "admin@example.com");
|
||||
|
||||
const result = await action({
|
||||
request: new Request("https://admin.example.com/settings/transactional-emails", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(form as unknown as Record<string, string>),
|
||||
}),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/settings/transactional-emails",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ error: "settings.admin.transactionalEmails.errors.testSendFailed" });
|
||||
expect(JSON.stringify(result)).not.toContain("provider secret");
|
||||
});
|
||||
|
||||
it("renders Mailjet-only settings without a generic provider selector", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
|
||||
+27
-23
@@ -21,10 +21,12 @@ import ModalOrSlide from "~/components/ui/modals/ModalOrSlide";
|
||||
import { GearIcon } from "~/components/ui/icons/vendor";
|
||||
import { requireUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { getMailjetProviderStatus, updateMailjetSettings, type MailjetProviderStatus } from "~/modules/emails/services/TransactionalEmailSettings.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
|
||||
const logger = createScopedLogger("admin.transactional-emails");
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
@@ -99,15 +101,21 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}),
|
||||
});
|
||||
return { success: t("settings.admin.transactionalEmails.testEmailQueued") };
|
||||
} catch (e: any) {
|
||||
return { error: e?.toString() };
|
||||
} catch (error: unknown) {
|
||||
logger.error({ event: "admin.transactional_emails.test_send_failed", ...toSafeErrorLog(error) }, "Transactional test email failed");
|
||||
return { error: t("settings.admin.transactionalEmails.errors.testSendFailed") };
|
||||
}
|
||||
} else if (action === "update-app-configuration") {
|
||||
const result = await updateMailjetSettings(form);
|
||||
if (!result.success) {
|
||||
return { error: result.error };
|
||||
try {
|
||||
const result = await updateMailjetSettings(form);
|
||||
if (!result.success) {
|
||||
return { error: t(result.errorKey) };
|
||||
}
|
||||
return { success: t("shared.updated") };
|
||||
} catch (error: unknown) {
|
||||
logger.error({ event: "admin.transactional_emails.settings_update_failed", ...toSafeErrorLog(error) }, "Transactional email settings update failed");
|
||||
return { error: t("settings.admin.transactionalEmails.errors.settingsUpdateFailed") };
|
||||
}
|
||||
return { success: t("shared.updated") };
|
||||
}
|
||||
return { error: t("shared.invalidForm") };
|
||||
};
|
||||
@@ -161,23 +169,19 @@ export default function () {
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={
|
||||
<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div>{t("settings.admin.transactionalEmails.title")}</div>
|
||||
<Badge variant={data.provider.configured ? "secondary" : "destructive"} className={data.provider.configured ? "border border-blue-300 bg-blue-50 text-blue-800" : undefined}>
|
||||
{t("settings.admin.transactionalEmails.providerStatus", {
|
||||
provider: t("settings.admin.transactionalEmails.providers.mailjet"),
|
||||
status: data.provider.configured
|
||||
? t("settings.admin.transactionalEmails.status.configured")
|
||||
: t("settings.admin.transactionalEmails.status.missingConfiguration"),
|
||||
})}
|
||||
</Badge>
|
||||
</div>
|
||||
</BackButtonWithTitle>
|
||||
}
|
||||
buttons={
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant={data.provider.configured ? "secondary" : "destructive"}
|
||||
className={data.provider.configured ? "border border-blue-300 bg-blue-50 text-blue-800" : undefined}
|
||||
>
|
||||
{t("settings.admin.transactionalEmails.providerStatus", {
|
||||
provider: t("settings.admin.transactionalEmails.providers.mailjet"),
|
||||
status: data.provider.configured
|
||||
? t("settings.admin.transactionalEmails.status.configured")
|
||||
: t("settings.admin.transactionalEmails.status.missingConfiguration"),
|
||||
})}
|
||||
</Badge>
|
||||
<Button variant="ghost" onClick={() => setOpenSettings(true)}>
|
||||
<GearIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
Reference in new issue
Block a user