Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,43 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
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 AdminSettingsAnalytics, { action } from "./analytics";
|
||||
import { getOrCreateAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
// EU-Sterilisation (R-P1a): Google-Analytics-Feld aus den Admin-Analytics-Settings entfernt.
|
||||
// Verbleibend sind die datenschutzfreundlichen EU-Tracker SimpleAnalytics + Plausible.
|
||||
let routeLoaderData = {
|
||||
title: "Analytics Settings",
|
||||
appConfiguration: {
|
||||
analytics: {
|
||||
enabled: true,
|
||||
simpleAnalytics: false,
|
||||
plausibleAnalytics: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
let routeActionData: { success?: string; error?: string; fieldErrors?: Record<string, string[]> } | undefined;
|
||||
let canUpdate = true;
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Form: ({ children, ...props }: React.ComponentProps<"form">) => <form {...props}>{children}</form>,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
useActionData: () => routeActionData,
|
||||
};
|
||||
});
|
||||
|
||||
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.analytics.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: ({ children }: { children: React.ReactNode }) => <main>{children}</main>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/BackButtonWithTitle", () => ({
|
||||
default: ({ children }: { children: React.ReactNode }) => <h1>{children}</h1>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/sections/SettingSection", () => ({
|
||||
default: ({ title, children }: { title: React.ReactNode; children: React.ReactNode }) => (
|
||||
<section>
|
||||
{title}
|
||||
{children}
|
||||
</section>
|
||||
),
|
||||
}));
|
||||
|
||||
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/button", () => ({
|
||||
Button: ({ children, ...props }: React.ComponentProps<"button">) => <button {...props}>{children}</button>,
|
||||
}));
|
||||
|
||||
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/analytics?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", "on");
|
||||
form.set("simpleAnalytics", "on");
|
||||
return form;
|
||||
}
|
||||
|
||||
describe("admin analytics settings route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
routeActionData = undefined;
|
||||
canUpdate = 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/analytics" });
|
||||
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("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/analytics" })).rejects.toBe(rejection);
|
||||
|
||||
expect(verifyUserHasPermissionMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.analytics.update");
|
||||
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(createAdminLogMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates valid settings and writes an audit payload", async () => {
|
||||
const response = await action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/analytics" });
|
||||
const body = await (response as Response).json();
|
||||
|
||||
expect((response as Response).status).toBe(200);
|
||||
expect(body.success).toBe("shared.updated");
|
||||
expect(updateAppConfigurationMock).toHaveBeenCalledWith({
|
||||
analyticsEnabled: true,
|
||||
analyticsSimpleAnalytics: true,
|
||||
analyticsPlausibleAnalytics: false,
|
||||
});
|
||||
expect(createAdminLogMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.updated", expect.any(String));
|
||||
const auditPayload = createAdminLogMock.mock.calls[0][2];
|
||||
expect(auditPayload).toContain("analytics");
|
||||
expect(auditPayload).toContain("analyticsEnabled");
|
||||
expect(auditPayload).toContain('"analyticsEnabled":true');
|
||||
expect(auditPayload).not.toContain("token=secret");
|
||||
});
|
||||
|
||||
it("renders accessible action and field errors", () => {
|
||||
routeActionData = { error: "shared.invalidForm", fieldErrors: { action: ["Invalid action."] } };
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsAnalytics />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const alert = screen.getByRole("alert");
|
||||
expect(alert).toHaveTextContent("shared.invalidForm");
|
||||
expect(alert).toHaveTextContent("action: Invalid action.");
|
||||
});
|
||||
|
||||
it("preserves save button and checkbox disabled state when the admin lacks update permission", () => {
|
||||
canUpdate = false;
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsAnalytics />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("shared.enabled")).toBeDisabled();
|
||||
expect(screen.getByLabelText("analytics.configuration.simpleAnalyticsEnabled")).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "shared.save" })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useActionData } from "react-router";
|
||||
import { Form, useLoaderData } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
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 { toast } from "sonner";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
appConfiguration: AppConfiguration;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
fieldErrors?: Record<string, string[]>;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await verifyUserHasPermission(request, "admin.settings.analytics.view");
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.admin.analytics.title")} | ${process.env.APP_NAME}`,
|
||||
appConfiguration,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const parsed = parseAdminSettingsForm("analytics", form);
|
||||
if (!parsed.ok) {
|
||||
return Response.json({ error: t("shared.invalidForm"), fieldErrors: parsed.errors }, { status: parsed.status });
|
||||
}
|
||||
|
||||
await verifyUserHasPermission(request, "admin.settings.analytics.update");
|
||||
await getOrCreateAppConfiguration({ request });
|
||||
await updateAppConfiguration(parsed.data);
|
||||
await createAdminLog(request, "admin.settings.updated", redactSettingsAuditDetails("analytics", parsed.data));
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
};
|
||||
|
||||
export default function AdminSettingsAnalytics() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
|
||||
const [enabled, setEnabled] = useState(data.appConfiguration.analytics.enabled);
|
||||
const [simpleAnalytics, setSimpleAnalytics] = useState(data.appConfiguration.analytics.simpleAnalytics);
|
||||
const [plausibleAnalytics, setPlausibleAnalytics] = useState(data.appConfiguration.analytics.plausibleAnalytics);
|
||||
|
||||
const [canUpdate] = useState(getUserHasPermission(adminData, "admin.settings.analytics.update"));
|
||||
const fieldErrors = actionData?.fieldErrors ?? {};
|
||||
const fieldErrorEntries = Object.entries(fieldErrors);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout title={""}>
|
||||
<SettingSection
|
||||
title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.analytics.title")}</BackButtonWithTitle>}
|
||||
description={t("analytics.configuration.description")}
|
||||
>
|
||||
<Form method="post" className="space-y-8">
|
||||
{rootData.csrf && <input hidden readOnly name="csrf" value={rootData.csrf} />}
|
||||
{(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">
|
||||
{actionData?.error && <p className="font-medium">{actionData.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>
|
||||
)}
|
||||
<input name="action" value="update" hidden readOnly />
|
||||
<div className="grid grid-cols-1 gap-y-6 sm:grid-cols-6 sm:gap-x-6">
|
||||
<div className="sm:col-span-6">
|
||||
<InputCheckboxWithDescription
|
||||
name="enabled"
|
||||
value={enabled}
|
||||
setValue={setEnabled}
|
||||
title={t("shared.enabled")}
|
||||
description={t("analytics.configuration.builtInDescription")}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="simpleAnalytics"
|
||||
value={simpleAnalytics}
|
||||
setValue={setSimpleAnalytics}
|
||||
title={t("analytics.configuration.simpleAnalyticsEnabled")}
|
||||
description={
|
||||
<a href="https://www.simpleanalytics.com/?referral=hesef" target="_blank" rel="noreferrer">
|
||||
{t("shared.clickHereToTryLearnMore")}
|
||||
</a>
|
||||
}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="plausibleAnalytics"
|
||||
value={plausibleAnalytics}
|
||||
setValue={setPlausibleAnalytics}
|
||||
title={t("analytics.configuration.plausibleAnalyticsEnabled")}
|
||||
description={
|
||||
<a href="https://plausible.io/" target="_blank" rel="noreferrer">
|
||||
{t("shared.clickHereToTryLearnMore")}
|
||||
</a>
|
||||
}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" variant="outline" disabled={!canUpdate}>
|
||||
{t("shared.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
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 AdminSettingsAuthentication, { action } from "./authentication";
|
||||
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: "Authentication Settings",
|
||||
appConfiguration: {
|
||||
auth: {
|
||||
requireEmailVerification: false,
|
||||
requireOrganization: true,
|
||||
requireName: true,
|
||||
captcha: { enabled: false, instanceUrl: "", loginSiteKey: "" },
|
||||
},
|
||||
subscription: {
|
||||
required: false,
|
||||
allowSubscribeBeforeSignUp: true,
|
||||
allowSignUpBeforeSubscribe: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
let routeActionData: { success?: string; error?: string; fieldErrors?: Record<string, string[]> } | undefined;
|
||||
let canUpdate = true;
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Form: ({ children, ...props }: React.ComponentProps<"form">) => <form {...props}>{children}</form>,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
useActionData: () => routeActionData,
|
||||
};
|
||||
});
|
||||
|
||||
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.authentication.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: ({ children }: { children: React.ReactNode }) => <main>{children}</main>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/BackButtonWithTitle", () => ({
|
||||
default: ({ children }: { children: React.ReactNode }) => <h1>{children}</h1>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/LoadingButton", () => ({
|
||||
default: ({ children, ...props }: React.ComponentProps<"button">) => <button {...props}>{children}</button>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/sections/SettingSection", () => ({
|
||||
default: ({ title, children }: { title: React.ReactNode; children: React.ReactNode }) => (
|
||||
<section>
|
||||
{title}
|
||||
{children}
|
||||
</section>
|
||||
),
|
||||
}));
|
||||
|
||||
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/input/InputText", () => ({
|
||||
default: ({ name, title, value, disabled, type }: { name: string; title: string; value?: string; disabled?: boolean; type?: string }) => (
|
||||
<label>
|
||||
{title}
|
||||
<input name={name} type={type} defaultValue={value} disabled={disabled} />
|
||||
</label>
|
||||
),
|
||||
}));
|
||||
|
||||
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/authentication?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("requireEmailVerification", "on");
|
||||
form.set("requireName", "on");
|
||||
form.set("required", "on");
|
||||
form.set("allowSubscribeBeforeSignUp", "on");
|
||||
return form;
|
||||
}
|
||||
|
||||
describe("admin authentication settings route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
routeActionData = undefined;
|
||||
canUpdate = 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/authentication" });
|
||||
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("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/authentication" })).rejects.toBe(rejection);
|
||||
|
||||
expect(verifyUserHasPermissionMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.authentication.update");
|
||||
expect(getOrCreateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(updateAppConfigurationMock).not.toHaveBeenCalled();
|
||||
expect(createAdminLogMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates valid settings and writes a redacted audit payload", async () => {
|
||||
const response = await action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/authentication" });
|
||||
const body = await (response as Response).json();
|
||||
|
||||
expect((response as Response).status).toBe(200);
|
||||
expect(body.success).toBe("shared.updated");
|
||||
expect(updateAppConfigurationMock).toHaveBeenCalledWith({
|
||||
authRequireEmailVerification: true,
|
||||
authRequireOrganization: false,
|
||||
authRequireName: true,
|
||||
subscriptionRequired: true,
|
||||
subscriptionAllowSubscribeBeforeSignUp: true,
|
||||
subscriptionAllowSignUpBeforeSubscribe: false,
|
||||
});
|
||||
expect(createAdminLogMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.updated", expect.any(String));
|
||||
const auditPayload = createAdminLogMock.mock.calls[0][2];
|
||||
expect(auditPayload).toContain("authentication");
|
||||
expect(auditPayload).toContain("authRequireEmailVerification");
|
||||
expect(auditPayload).toContain('"authRequireEmailVerification":true');
|
||||
expect(auditPayload).not.toContain("token=secret");
|
||||
});
|
||||
|
||||
it("renders accessible action and field errors", () => {
|
||||
routeActionData = { error: "shared.invalidForm", fieldErrors: { action: ["Invalid action."] } };
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsAuthentication />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const alert = screen.getByRole("alert");
|
||||
expect(alert).toHaveTextContent("shared.invalidForm");
|
||||
expect(alert).toHaveTextContent("action: Invalid action.");
|
||||
});
|
||||
|
||||
it("preserves save button and input disabled state when the admin lacks update permission", () => {
|
||||
canUpdate = false;
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsAuthentication />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("settings.admin.authentication.fields.requireEmailVerification.title")).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "shared.save" })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useActionData } from "react-router";
|
||||
import { Form, useLoaderData } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
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 { 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";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
appConfiguration: AppConfiguration;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
fieldErrors?: Record<string, string[]>;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await verifyUserHasPermission(request, "admin.settings.authentication.view");
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.admin.authentication.title")} | ${process.env.APP_NAME}`,
|
||||
appConfiguration,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const parsed = parseAdminSettingsForm("authentication", form);
|
||||
if (!parsed.ok) {
|
||||
return Response.json({ error: t("shared.invalidForm"), fieldErrors: parsed.errors }, { status: parsed.status });
|
||||
}
|
||||
|
||||
await verifyUserHasPermission(request, "admin.settings.authentication.update");
|
||||
await getOrCreateAppConfiguration({ request });
|
||||
await updateAppConfiguration(parsed.data);
|
||||
await createAdminLog(request, "admin.settings.updated", redactSettingsAuditDetails("authentication", parsed.data));
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
};
|
||||
|
||||
export default function AdminSettingsAuthentication() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const rootData = useRootData();
|
||||
const adminData = useAdminData();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const [requireEmailVerification, setRequireEmailVerification] = useState(data.appConfiguration.auth.requireEmailVerification);
|
||||
const [requireOrganization, setRequireOrganization] = useState(data.appConfiguration.auth.requireOrganization);
|
||||
const [requireName, setRequireName] = useState(data.appConfiguration.auth.requireName);
|
||||
|
||||
const [required, setRequired] = useState(data.appConfiguration.subscription.required);
|
||||
const [allowSubscribeBeforeSignUp, setAllowSubscribeBeforeSignUp] = useState(data.appConfiguration.subscription.allowSubscribeBeforeSignUp);
|
||||
const [allowSignUpBeforeSubscribe, setAllowSignUpBeforeSubscribe] = useState(data.appConfiguration.subscription.allowSignUpBeforeSubscribe);
|
||||
|
||||
const [canUpdate] = useState(getUserHasPermission(adminData, "admin.settings.authentication.update"));
|
||||
const fieldErrors = actionData?.fieldErrors ?? {};
|
||||
const fieldErrorEntries = Object.entries(fieldErrors);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
<SettingSection title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.authentication.title")}</BackButtonWithTitle>}>
|
||||
<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">
|
||||
{actionData?.error && <p className="font-medium">{actionData.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>
|
||||
)}
|
||||
<input name="action" value="update" hidden readOnly />
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<div className="grid grid-cols-1 gap-y-6 sm:grid-cols-6 sm:gap-x-6">
|
||||
<div className="sm:col-span-6">
|
||||
<InputCheckboxWithDescription
|
||||
name="requireEmailVerification"
|
||||
value={requireEmailVerification}
|
||||
setValue={setRequireEmailVerification}
|
||||
title={t("settings.admin.authentication.fields.requireEmailVerification.title")}
|
||||
description={t("settings.admin.authentication.fields.requireEmailVerification.description")}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="requireOrganization"
|
||||
value={requireOrganization}
|
||||
setValue={setRequireOrganization}
|
||||
title={t("settings.admin.authentication.fields.requireOrganization.title")}
|
||||
description={t("settings.admin.authentication.fields.requireOrganization.description")}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="requireName"
|
||||
value={requireName}
|
||||
setValue={setRequireName}
|
||||
title={t("settings.admin.authentication.fields.requireName.title")}
|
||||
description={t("settings.admin.authentication.fields.requireName.description")}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="required"
|
||||
value={required}
|
||||
setValue={setRequired}
|
||||
title={t("settings.admin.authentication.fields.subscriptionRequired.title")}
|
||||
description={t("settings.admin.authentication.fields.subscriptionRequired.description")}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="allowSubscribeBeforeSignUp"
|
||||
value={allowSubscribeBeforeSignUp}
|
||||
setValue={setAllowSubscribeBeforeSignUp}
|
||||
title={t("settings.admin.authentication.fields.allowSubscribeBeforeSignUp.title")}
|
||||
description={t("settings.admin.authentication.fields.allowSubscribeBeforeSignUp.description")}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="allowSignUpBeforeSubscribe"
|
||||
value={allowSignUpBeforeSubscribe}
|
||||
setValue={setAllowSignUpBeforeSubscribe}
|
||||
title={t("settings.admin.authentication.fields.allowSignUpBeforeSubscribe.title")}
|
||||
description={t("settings.admin.authentication.fields.allowSignUpBeforeSubscribe.description")}
|
||||
disabled={!canUpdate}
|
||||
/>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-8">
|
||||
<LoadingButton type="submit" disabled={!canUpdate}>
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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 { 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";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await verifyUserHasPermission(request, "admin.settings.danger.reset");
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.admin.danger.title")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.settings.danger.reset");
|
||||
await deleteAppConfiguration();
|
||||
return Response.json({ success: t("settings.admin.danger.resetSuccess") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminSettingsDanger() {
|
||||
const { t } = useTranslation();
|
||||
useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
return (
|
||||
<EditPageLayout title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.danger.title")}</BackButtonWithTitle>}>
|
||||
<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 />
|
||||
<div className="grid grid-cols-1 gap-y-6 sm:grid-cols-6 sm:gap-x-6">
|
||||
<div className="sm:col-span-6">
|
||||
<h2 className="text-foreground text-xl font-medium">{t("settings.admin.danger.resetTitle")}</h2>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("settings.admin.danger.resetDescription")}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-8">
|
||||
<ButtonPrimary destructive type="submit">
|
||||
{t("settings.reset")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</Form>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
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 AdminSettingsGeneral, { action } from "./general";
|
||||
import { getOrCreateAppConfiguration, 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";
|
||||
|
||||
let routeLoaderData = {
|
||||
title: "General Settings",
|
||||
appConfiguration: {
|
||||
app: { name: "ToolCTRL", url: "https://example.com", theme: "light" },
|
||||
branding: { logo: "", logoDarkMode: "", icon: "", iconDarkMode: "", favicon: "" },
|
||||
scripts: { head: "", body: "" },
|
||||
},
|
||||
};
|
||||
let routeActionData: { success?: string; error?: string; fieldErrors?: Record<string, string[]> } | undefined;
|
||||
let canUpdate = true;
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Form: ({ children, ...props }: React.ComponentProps<"form">) => <form {...props}>{children}</form>,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
useActionData: () => routeActionData,
|
||||
};
|
||||
});
|
||||
|
||||
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.general.update"] : [] }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({
|
||||
getUserHasPermission: vi.fn(() => canUpdate),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
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("~/utils/integrations/storageService", () => ({
|
||||
storeFile: vi.fn(async ({ id }: { id: string }) => `stored:${id}`),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: vi.fn(async () => ({ userId: "user-1", theme: "light" })),
|
||||
createUserSession: vi.fn(async () => new Response(null, { status: 204 })),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ csrf: "csrf-test-token" }),
|
||||
}));
|
||||
|
||||
vi.mock("react-hot-toast", () => ({
|
||||
default: { success: vi.fn(), error: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({
|
||||
default: ({ title, children }: { title: React.ReactNode; children: React.ReactNode }) => (
|
||||
<main>
|
||||
<header>{title}</header>
|
||||
{children}
|
||||
</main>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/BackButtonWithTitle", () => ({
|
||||
default: ({ children }: { children: React.ReactNode }) => <h1>{children}</h1>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/LoadingButton", () => ({
|
||||
default: ({ children, ...props }: React.ComponentProps<"button">) => <button {...props}>{children}</button>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/forms/InputGroup", () => ({
|
||||
default: ({ title, children }: { title: string; children: React.ReactNode }) => (
|
||||
<section>
|
||||
<h2>{title}</h2>
|
||||
{children}
|
||||
</section>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputText", () => ({
|
||||
default: ({ name, title, defaultValue, disabled, required }: { name: string; title: string; defaultValue?: string; disabled?: boolean; required?: boolean }) => (
|
||||
<label>
|
||||
{title}
|
||||
<input name={name} defaultValue={defaultValue} disabled={disabled} required={required} />
|
||||
</label>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputImage", () => ({
|
||||
default: ({ name, title, value, disabled }: { name: string; title: string; value?: string; disabled?: boolean }) => (
|
||||
<label>
|
||||
{title}
|
||||
<input name={name} defaultValue={value} disabled={disabled} />
|
||||
</label>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputSelect", () => ({
|
||||
default: ({ name, title, defaultValue, options }: { name: string; title: string; defaultValue?: string; options: { name: string; value: string }[] }) => (
|
||||
<label>
|
||||
{title}
|
||||
<select name={name} defaultValue={defaultValue}>
|
||||
{options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
),
|
||||
}));
|
||||
|
||||
const getOrCreateAppConfigurationMock = vi.mocked(getOrCreateAppConfiguration);
|
||||
const updateAppConfigurationMock = vi.mocked(updateAppConfiguration);
|
||||
const createAdminLogMock = vi.mocked(createAdminLog);
|
||||
const storeFileMock = vi.mocked(storeFile);
|
||||
const createUserSessionMock = vi.mocked(createUserSession);
|
||||
|
||||
function postRequest(form: FormData) {
|
||||
return new Request("https://admin.example.com/settings/general?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("name", "ToolCTRL Cloud");
|
||||
form.set("theme", "dark");
|
||||
form.set("logo", "data:image/png;base64,logo-secret");
|
||||
form.set("logoDarkMode", "");
|
||||
form.set("icon", "https://cdn.example.com/icon.png?token=secret");
|
||||
form.set("iconDarkMode", "");
|
||||
form.set("favicon", "");
|
||||
form.set("headScripts", "<script>window.secret='abc'</script>");
|
||||
form.set("bodyScripts", "<script>window.token='def'</script>");
|
||||
return form;
|
||||
}
|
||||
|
||||
describe("admin general settings route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
routeActionData = undefined;
|
||||
canUpdate = true;
|
||||
routeLoaderData = {
|
||||
title: "General Settings",
|
||||
appConfiguration: {
|
||||
app: { name: "ToolCTRL", url: "https://example.com", theme: "light" },
|
||||
branding: { logo: "", logoDarkMode: "", icon: "", iconDarkMode: "", favicon: "" },
|
||||
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);
|
||||
});
|
||||
|
||||
it("rejects invalid actions before database, storage, 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/general" });
|
||||
const body = await (response as Response).json();
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
it("rejects an empty application name before database, storage, or audit side effects", async () => {
|
||||
const form = validForm();
|
||||
form.set("name", " ");
|
||||
|
||||
const response = await action({ request: postRequest(form), params: {}, context: {}, unstable_pattern: "admin/settings/general" });
|
||||
const body = await (response as Response).json();
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
it("updates valid settings and writes a redacted audit payload without raw scripts or query strings", async () => {
|
||||
const response = await action({ request: postRequest(validForm()), params: {}, context: {}, unstable_pattern: "admin/settings/general" });
|
||||
|
||||
expect((response as Response).status).toBe(204);
|
||||
expect(storeFileMock).toHaveBeenCalledWith(expect.objectContaining({ bucket: "branding", content: "data:image/png;base64,logo-secret", id: "logo", scan: expect.objectContaining({ context: "mediaLibrary", filename: "logo" }) }));
|
||||
expect(storeFileMock).toHaveBeenCalledWith(expect.objectContaining({ bucket: "branding", content: "https://cdn.example.com/icon.png?token=secret", id: "icon", scan: expect.objectContaining({ context: "mediaLibrary", filename: "icon" }) }));
|
||||
expect(updateAppConfigurationMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "ToolCTRL Cloud",
|
||||
brandingLogo: "stored:logo",
|
||||
brandingIcon: "stored:icon",
|
||||
headScripts: "<script>window.secret='abc'</script>",
|
||||
bodyScripts: "<script>window.token='def'</script>",
|
||||
})
|
||||
);
|
||||
expect(createAdminLogMock).toHaveBeenCalledWith(expect.any(Request), "admin.settings.updated", expect.any(String));
|
||||
const auditPayload = createAdminLogMock.mock.calls[0][2];
|
||||
expect(auditPayload).toContain("general");
|
||||
expect(auditPayload).toContain("headScripts");
|
||||
expect(auditPayload).toContain("brandingLogo");
|
||||
expect(auditPayload).not.toContain("window.secret");
|
||||
expect(auditPayload).not.toContain("window.token");
|
||||
expect(auditPayload).not.toContain("logo-secret");
|
||||
expect(auditPayload).not.toContain("token=secret");
|
||||
});
|
||||
|
||||
it("renders accessible action and field errors", () => {
|
||||
routeActionData = { error: "settings.admin.invalid", fieldErrors: { name: ["This field is required."], action: ["Invalid action."] } };
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsGeneral />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const alert = screen.getByRole("alert");
|
||||
expect(alert).toHaveTextContent("settings.admin.invalid");
|
||||
expect(alert).toHaveTextContent("name: This field is required.");
|
||||
expect(alert).toHaveTextContent("action: Invalid action.");
|
||||
});
|
||||
|
||||
it("disables editable controls when the admin lacks update permission", () => {
|
||||
canUpdate = false;
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsGeneral />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByLabelText("settings.admin.general.fields.applicationName")).toBeDisabled();
|
||||
expect(screen.getByLabelText("settings.admin.general.fields.logoLightMode")).toBeDisabled();
|
||||
expect(screen.getByLabelText("settings.admin.general.fields.headScripts")).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "shared.save" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("renders theme preset choices through translation keys", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<AdminSettingsGeneral />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("option", { name: "settings:tenant.theme.presets.emerald" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("option", { name: "settings:tenant.theme.presets.blue" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useActionData } from "react-router";
|
||||
import { Form, useLoaderData } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
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 { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { parseAdminSettingsForm, redactSettingsAuditDetails } from "~/utils/services/adminSettingsValidation.server";
|
||||
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 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 }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
appConfiguration: AppConfiguration;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
fieldErrors?: Record<string, string[]>;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await verifyUserHasPermission(request, "admin.settings.general.view");
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.admin.general.title")} | ${process.env.APP_NAME}`,
|
||||
appConfiguration,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.settings.general.update");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const form = await request.formData();
|
||||
const parsed = parseAdminSettingsForm("general", form);
|
||||
if (!parsed.ok) {
|
||||
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() ?? "";
|
||||
const iconDarkMode = parsed.data.brandingIconDarkMode?.toString() ?? "";
|
||||
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(""),
|
||||
});
|
||||
|
||||
const updateData = {
|
||||
...parsed.data,
|
||||
brandingLogo: storedLogo,
|
||||
brandingLogoDarkMode: storedLogoDarkMode,
|
||||
brandingIcon: storedIcon,
|
||||
brandingIconDarkMode: storedIconDarkMode,
|
||||
brandingFavicon: storedFavicon,
|
||||
};
|
||||
|
||||
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 Response.json({ success: t("shared.updated") });
|
||||
};
|
||||
|
||||
export default function AdminSettingsGeneral() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const [logoLight, setLogoLight] = useState(data.appConfiguration.branding.logo ?? "");
|
||||
const [logoDarkMode, setLogoDarkMode] = useState(data.appConfiguration.branding.logoDarkMode ?? "");
|
||||
const [iconLight, setIconLight] = useState(data.appConfiguration.branding.icon ?? "");
|
||||
const [iconDarkMode, setIconDarkMode] = useState(data.appConfiguration.branding.iconDarkMode ?? "");
|
||||
const [favicon, setFavicon] = useState(data.appConfiguration.branding.favicon ?? "");
|
||||
|
||||
const [canUpdate] = useState(getUserHasPermission(adminData, "admin.settings.general.update"));
|
||||
const fieldErrors = actionData?.fieldErrors ?? {};
|
||||
const fieldErrorEntries = Object.entries(fieldErrors);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
return (
|
||||
<EditPageLayout title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.general.title")}</BackButtonWithTitle>}>
|
||||
<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">
|
||||
{actionData?.error && <p className="font-medium">{actionData.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>
|
||||
)}
|
||||
<input name="action" value="update" hidden readOnly />
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<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 />
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<InputText name="url" title={t("settings.admin.general.fields.url")} defaultValue={data.appConfiguration.app.url ?? ""} disabled required />
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<div className="w-full">
|
||||
<InputSelect
|
||||
name="theme"
|
||||
title={t("settings.admin.general.fields.theme")}
|
||||
defaultValue={data.appConfiguration.app.theme ?? ""}
|
||||
options={defaultThemes.map((item) => {
|
||||
const label = t(item.labelKey, { defaultValue: item.name });
|
||||
return {
|
||||
name: label,
|
||||
value: item.value,
|
||||
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")}
|
||||
>
|
||||
<svg className={clsx("h-2 w-2")} fill="currentColor" viewBox="0 0 8 8">
|
||||
<circle cx={4} cy={4} r={3} />
|
||||
</svg>
|
||||
</div>
|
||||
<div>{label}</div>
|
||||
</div>
|
||||
),
|
||||
};
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<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} />
|
||||
</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" />
|
||||
</div>
|
||||
{/* <div className="sm:col-span-6">
|
||||
<PreviewLogo />
|
||||
</div> */}
|
||||
<div className="sm:col-span-3">
|
||||
<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" />
|
||||
</div>
|
||||
{/* <div className="sm:col-span-6">
|
||||
<PreviewIcon />
|
||||
</div> */}
|
||||
<div className="sm:col-span-6">
|
||||
<InputImage name="favicon" title={t("settings.admin.general.fields.favicon")} value={favicon} setValue={setFavicon} disabled={!canUpdate} />
|
||||
</div>
|
||||
{/* <div className="sm:col-span-6">
|
||||
<PreviewFavicon />
|
||||
</div> */}
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<InputGroup title={t("settings.admin.general.sections.scripts")}>
|
||||
<div className="grid grid-cols-1 gap-y-6 sm:grid-cols-6 sm:gap-x-6">
|
||||
<div className="sm:col-span-3">
|
||||
<InputText
|
||||
name="headScripts"
|
||||
title={t("settings.admin.general.fields.headScripts")}
|
||||
defaultValue={data.appConfiguration.scripts.head ?? ""}
|
||||
disabled={!canUpdate}
|
||||
rows={10}
|
||||
placeholder={t("settings.admin.general.placeholders.headScripts")}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputText
|
||||
name="bodyScripts"
|
||||
title={t("settings.admin.general.fields.bodyScripts")}
|
||||
defaultValue={data.appConfiguration.scripts.body ?? ""}
|
||||
disabled={!canUpdate}
|
||||
rows={10}
|
||||
placeholder={t("settings.admin.general.placeholders.bodyScripts")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<LoadingButton type="submit" disabled={!getUserHasPermission(adminData, "admin.settings.general.update")}>
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import UnderConstruction from "~/components/ui/misc/UnderConstruction";
|
||||
import { getTranslations } from "~/locale/i18next.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";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.settings.internationalization.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.admin.internationalization.title")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function AdminSettingsInternationalization() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<EditPageLayout title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("settings.admin.internationalization.title")}</BackButtonWithTitle>}>
|
||||
<div>
|
||||
<UnderConstruction title={t("settings.admin.internationalization.title")} description={t("settings.admin.internationalization.description")} />
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
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 { getTranslations } from "~/locale/i18next.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { deletePlan, updatePlan } from "~/utils/services/.server/pricingService";
|
||||
import PricingPlanForm from "~/components/core/pricing/PricingPlanForm";
|
||||
import { getAllSubscriptionProducts, getSubscriptionProduct } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
||||
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";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { toast } from "sonner";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
item: SubscriptionProductDto;
|
||||
plans: SubscriptionProductDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const item = await getSubscriptionProduct(params.id ?? "");
|
||||
if (!item) {
|
||||
throw redirect(adminPath("settings/pricing", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: `${t("admin.pricing.edit")} | ${process.env.APP_NAME}` }],
|
||||
item,
|
||||
plans: await getAllSubscriptionProducts(),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const item = await getSubscriptionProduct(params.id ?? "");
|
||||
if (!item) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
if (action === "edit") {
|
||||
const order = Number(form.get("order"));
|
||||
const title = form.get("title")?.toString();
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const badge = form.get("badge")?.toString() ?? "";
|
||||
const groupTitle = form.get("group-title")?.toString() ?? "";
|
||||
const groupDescription = form.get("group-description")?.toString() ?? "";
|
||||
const isPublic = Boolean(form.get("is-public"));
|
||||
const isBillingRequired = Boolean(form.get("is-billing-required"));
|
||||
const hasQuantity = Boolean(form.get("has-quantity"));
|
||||
const canBuyAgain = Boolean(form.get("can-buy-again"));
|
||||
|
||||
const featuresArr = form.getAll("features[]");
|
||||
const features: SubscriptionFeatureDto[] = featuresArr.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!title) {
|
||||
return badRequest({ error: t("admin.pricing.errors.titleRequired") });
|
||||
}
|
||||
|
||||
const plan: SubscriptionProductDto = {
|
||||
id: params.id,
|
||||
stripeId: "",
|
||||
order,
|
||||
title,
|
||||
description,
|
||||
badge,
|
||||
groupTitle,
|
||||
groupDescription,
|
||||
active: true,
|
||||
model: item.model,
|
||||
public: isPublic,
|
||||
prices: [],
|
||||
usageBasedPrices: [],
|
||||
features: [],
|
||||
billingAddressCollection: isBillingRequired ? "required" : "auto",
|
||||
hasQuantity,
|
||||
canBuyAgain,
|
||||
};
|
||||
|
||||
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() });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.pricing.delete");
|
||||
if (!item) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planNotFound") });
|
||||
}
|
||||
try {
|
||||
await deletePlan(item);
|
||||
return redirect(adminPath("settings/pricing", { mode: "host-aware" }));
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
}
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function EditPricinPlanRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={
|
||||
<BackButtonWithTitle href={adminPath("settings/pricing", { mode: "host-aware" })}>
|
||||
{t("admin.pricing.editTitle", { name: t(data.item.title) })}
|
||||
</BackButtonWithTitle>
|
||||
}
|
||||
>
|
||||
<PricingPlanForm
|
||||
item={data.item}
|
||||
plans={data.plans}
|
||||
canUpdate={getUserHasPermission(adminData, "admin.pricing.update")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.pricing.delete")}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const sourcePaths = [
|
||||
"apps/web/app/routes/admin/settings/pricing.features.tsx",
|
||||
"apps/web/app/components/core/pricing/FlatPrices.tsx",
|
||||
"apps/web/app/components/core/pricing/PricingFeaturesForm.tsx",
|
||||
"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/utils/services/setupService.ts",
|
||||
].map((sourcePath) => path.resolve(process.cwd(), sourcePath));
|
||||
|
||||
describe("pricing features route i18n", () => {
|
||||
it("uses semantic translation keys for visible feature-management copy", () => {
|
||||
const source = sourcePaths.map((sourcePath) => fs.readFileSync(sourcePath, "utf8")).join("\n");
|
||||
|
||||
expect(source).toContain("admin.pricing.features.metaTitle");
|
||||
expect(source).toContain("admin.pricing.features.fields.badge");
|
||||
expect(source).toContain("admin.pricing.features.placeholders.badge");
|
||||
expect(source).toContain("admin.pricing.features.limitTypes.notIncluded");
|
||||
expect(source).toContain("admin.pricing.features.editor.featureDetails");
|
||||
expect(source).toContain("admin.pricing.features.help.internalId");
|
||||
expect(source).toContain("admin.pricing.features.actions.copyFromProduct");
|
||||
expect(source).toContain("admin.pricing.features.actions.setFeatures");
|
||||
expect(source).toContain("admin.pricing.features.actions.setFeaturesForSelection");
|
||||
expect(source).toContain("admin.pricing.prices.fields.currency");
|
||||
expect(source).toContain("admin.pricing.prices.fields.monthlyPrice");
|
||||
expect(source).toContain("admin.pricing.prices.fields.quarterlyPrice");
|
||||
expect(source).toContain("admin.pricing.prices.fields.semiAnnualPrice");
|
||||
expect(source).toContain("admin.pricing.prices.fields.yearlyPrice");
|
||||
expect(source).toContain("admin.pricing.prices.fields.yearlyDiscount");
|
||||
expect(source).toContain("admin.pricing.prices.fields.oneTimePrice");
|
||||
expect(source).toContain("admin.pricing.prices.fields.billingPeriods");
|
||||
expect(source).toContain("admin.pricing.prices.fields.trialPeriodDays");
|
||||
expect(source).toContain("admin.pricing.prices.discountOff");
|
||||
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(product.features.length)");
|
||||
expect(source).toContain("formatters.number(item.value)");
|
||||
expect(source).toContain('t("shared.notSet")');
|
||||
expect(source).toContain("setup.pricing.title");
|
||||
expect(source).toContain("admin.pricing.features.errors.invalidFeatureTitleInPlan");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('"Currency"');
|
||||
expect(source).not.toContain('"NA"');
|
||||
expect(source).not.toContain("% off");
|
||||
expect(source).not.toContain('"Internal ID"');
|
||||
expect(source).not.toContain('"Features"');
|
||||
expect(source).not.toContain('"Not included"');
|
||||
expect(source).not.toContain('"Included"');
|
||||
expect(source).not.toContain('"Monthly"');
|
||||
expect(source).not.toContain('"Max"');
|
||||
expect(source).not.toContain('"Unlimited"');
|
||||
expect(source).not.toContain('"Move up"');
|
||||
expect(source).not.toContain('"Value"');
|
||||
expect(source).not.toContain('"Link"');
|
||||
expect(source).not.toContain('"Badge"');
|
||||
expect(source).not.toContain("Set features for ");
|
||||
expect(source).not.toContain("Duplicated name");
|
||||
expect(source).not.toContain("Invalid feature title");
|
||||
expect(source).not.toContain("(accumulates)");
|
||||
expect(source).not.toContain(".e.g. New!");
|
||||
expect(source).not.toContain("toFixed(0)");
|
||||
expect(source).not.toContain('{item.tenantProducts?.length ?? 0} {t("shared.active")}');
|
||||
expect(source).not.toContain("({product.features.length})");
|
||||
expect(source).not.toContain("item.value.toString()");
|
||||
expect(source).not.toContain('t("shared.undefined")');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,591 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useSubmit } from "react-router";
|
||||
import { EyeIcon, PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import { SubscriptionFeatureInPlansDto } from "~/application/dtos/subscriptions/SubscriptionFeatureInPlansDto";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import {
|
||||
createSubscriptionFeature,
|
||||
deleteSubscriptionFeatures,
|
||||
getAllSubscriptionProductsWithTenants,
|
||||
getSubscriptionProductsInIds,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
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 SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import InputCombobox from "~/components/ui/input/InputCombobox";
|
||||
import PlansGrouped from "~/components/core/settings/subscription/plans/PlansGrouped";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import { getCurrenciesAndPeriods } from "~/utils/helpers/PricingHelper";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import { clearAllSubscriptionsCache } from "~/utils/services/.server/subscriptionService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: SubscriptionProductDto[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const ids = searchParams.getAll("id");
|
||||
const items: SubscriptionProductDto[] = ids.length > 0 ? await getSubscriptionProductsInIds(ids) : await getAllSubscriptionProductsWithTenants();
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: t("admin.pricing.features.metaTitle", { appName: process.env.APP_NAME }) }],
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "update-features") {
|
||||
const planIds = JSON.parse(form.get("planIds")?.toString() ?? "[]") as string[];
|
||||
const plans = await getSubscriptionProductsInIds(planIds);
|
||||
if (plans.length === 0) {
|
||||
return Response.json({ error: t("admin.pricing.features.errors.noPlansFound") }, { status: 400 });
|
||||
}
|
||||
const featuresInPlans = JSON.parse(form.get("features")?.toString() ?? "[]") as SubscriptionFeatureInPlansDto[];
|
||||
await Promise.all(
|
||||
plans.map(async (plan) => {
|
||||
await deleteSubscriptionFeatures(plan.id ?? "");
|
||||
const features = featuresInPlans.filter((f) => f.plans.find((p) => p.id === plan.id));
|
||||
await Promise.all(
|
||||
features
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map(async ({ order, name, href, badge, plans, accumulate }) => {
|
||||
const feature = plans.find((p) => p.id === plan.id);
|
||||
if (!feature) {
|
||||
return;
|
||||
}
|
||||
return await createSubscriptionFeature(plan.id ?? "", {
|
||||
order,
|
||||
name,
|
||||
title: feature.title,
|
||||
type: feature.type,
|
||||
value: feature.value,
|
||||
href: href ?? null,
|
||||
badge: badge ?? null,
|
||||
accumulate: accumulate ?? false,
|
||||
});
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
await clearAllSubscriptionsCache();
|
||||
return Response.json({ success: t("admin.pricing.features.actions.updated") });
|
||||
}
|
||||
return Response.json({ error: t("shared.invalidRequest") }, { status: 400 });
|
||||
};
|
||||
|
||||
function getInitialItems(plans: SubscriptionProductDto[]) {
|
||||
const items: SubscriptionFeatureInPlansDto[] = [];
|
||||
plans.forEach((plan) => {
|
||||
plan.features.forEach((feature) => {
|
||||
if (!feature.name) {
|
||||
feature.name = feature.title;
|
||||
}
|
||||
const existing = items.find((f) => f.name === feature.name);
|
||||
if (existing) {
|
||||
existing.plans.push({
|
||||
id: plan.id!,
|
||||
title: feature.title,
|
||||
type: feature.type,
|
||||
value: feature.value,
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
id: crypto.randomUUID(),
|
||||
...feature,
|
||||
plans: [
|
||||
{
|
||||
id: plan.id!,
|
||||
title: feature.title,
|
||||
type: feature.type,
|
||||
value: feature.value,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
plans.forEach((plan) => {
|
||||
items.forEach((feature) => {
|
||||
if (!feature.plans.find((p) => p.id === plan.id)) {
|
||||
feature.plans.push({
|
||||
id: plan.id!,
|
||||
title: "?",
|
||||
type: SubscriptionFeatureLimitType.NOT_INCLUDED,
|
||||
value: 0,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const submit = useSubmit();
|
||||
|
||||
const [showPreview, setShowPreview] = useState(false);
|
||||
|
||||
const [items, setItems] = useState<SubscriptionFeatureInPlansDto[]>([]);
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<SubscriptionFeatureInPlansDto>[]>([]);
|
||||
|
||||
const [selectedPlans, setSelectedPlans] = useState<SubscriptionProductDto[]>(data.items);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
useEffect(() => {
|
||||
setItems(getInitialItems(selectedPlans));
|
||||
}, [selectedPlans]);
|
||||
|
||||
useEffect(() => {
|
||||
const headers: RowHeaderDisplayDto<SubscriptionFeatureInPlansDto>[] = [
|
||||
{
|
||||
title: t("shared.order"),
|
||||
name: "order",
|
||||
value: (item) => item.order,
|
||||
formattedValue: (_, idx) => (
|
||||
<OrderListButtons
|
||||
index={idx}
|
||||
items={items}
|
||||
onChange={(items) => {
|
||||
setItems(items as SubscriptionFeatureInPlansDto[]);
|
||||
}}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("admin.pricing.features.table.feature"),
|
||||
name: "feature-title",
|
||||
value: (item) => (
|
||||
<ClosedOpenedValue
|
||||
closed={
|
||||
<div className="flex flex-col space-y-2 px-1 py-2">
|
||||
{/* <div className="font-medium">{t(item.title)}</div> */}
|
||||
<div className="font-bold">
|
||||
{item.name ? (
|
||||
<span>
|
||||
{item.name} {item.accumulate ? <span className="text-muted-foreground text-xs font-light italic">{t("admin.pricing.features.badges.accumulates")}</span> : null}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-red-600 underline">{t("admin.pricing.features.empty.clickToSet")}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
opened={
|
||||
<div className="flex flex-col space-y-2 px-1 py-2">
|
||||
<div>
|
||||
<InputText
|
||||
name="name"
|
||||
title={t("admin.pricing.features.fields.name")}
|
||||
placeholder={t("admin.pricing.features.placeholders.name")}
|
||||
value={item.name}
|
||||
required
|
||||
setValue={(e) => {
|
||||
item.name = e?.toString() ?? "";
|
||||
setItems([...items]);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<InputText
|
||||
name="href"
|
||||
title={t("admin.pricing.features.fields.url")}
|
||||
placeholder={t("admin.pricing.features.placeholders.url")}
|
||||
value={item.href ?? undefined}
|
||||
setValue={(e) => {
|
||||
item.href = e?.toString() ?? "";
|
||||
setItems([...items]);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<InputText
|
||||
name="badge"
|
||||
title={t("admin.pricing.features.fields.badge")}
|
||||
placeholder={t("admin.pricing.features.placeholders.badge")}
|
||||
value={item.badge ?? undefined}
|
||||
setValue={(e) => {
|
||||
item.badge = e?.toString() ?? "";
|
||||
setItems([...items]);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<InputCheckboxWithDescription
|
||||
name="accumulate"
|
||||
title={t("admin.pricing.features.fields.accumulate")}
|
||||
value={item.accumulate}
|
||||
setValue={(e) => {
|
||||
item.accumulate = Boolean(e);
|
||||
setItems([...items]);
|
||||
}}
|
||||
description={t("admin.pricing.features.descriptions.accumulate")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
selectedPlans.forEach((plan) => {
|
||||
headers.push({
|
||||
title: t(plan.title),
|
||||
name: "feature-in-" + plan.id,
|
||||
value: (item) => {
|
||||
const existing = item.plans.find((p) => p.id === plan.id);
|
||||
return (
|
||||
<ClosedOpenedValue
|
||||
closed={
|
||||
<div>
|
||||
{!item.name || !existing || !existing.title.trim() || existing.title === "?" ? (
|
||||
<div className="text-red-600 underline">{t("admin.pricing.features.empty.clickToSet")}</div>
|
||||
) : (
|
||||
<PlanFeatureDescription
|
||||
feature={{
|
||||
...item,
|
||||
title: existing?.title ?? "",
|
||||
value: existing?.value ?? 0,
|
||||
type: existing?.type ?? SubscriptionFeatureLimitType.NOT_INCLUDED,
|
||||
}}
|
||||
editing={true}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
opened={
|
||||
<div className="flex flex-col space-y-2 px-1 py-2">
|
||||
{!existing ? (
|
||||
<div>-</div>
|
||||
) : (
|
||||
<Fragment>
|
||||
<div>
|
||||
<InputText
|
||||
withTranslation={true}
|
||||
name="title"
|
||||
title={t("admin.pricing.features.fields.title")}
|
||||
placeholder={t("admin.pricing.features.placeholders.title")}
|
||||
value={existing?.title}
|
||||
required
|
||||
setValue={(e) => {
|
||||
existing.title = e?.toString() ?? "";
|
||||
setItems([...items]);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<InputSelect
|
||||
name="type"
|
||||
title={t("admin.pricing.features.fields.type")}
|
||||
value={existing?.type}
|
||||
setValue={(e) => {
|
||||
let type = Number(e) as SubscriptionFeatureLimitType;
|
||||
if (existing) {
|
||||
existing.type = type;
|
||||
if (![SubscriptionFeatureLimitType.MAX, SubscriptionFeatureLimitType.MONTHLY].includes(type)) {
|
||||
existing.value = 0;
|
||||
}
|
||||
} else {
|
||||
item.plans.push({
|
||||
id: plan.id!,
|
||||
title: "?",
|
||||
type,
|
||||
value: 0,
|
||||
});
|
||||
}
|
||||
setItems([...items]);
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
name: t("admin.pricing.features.limitTypes.notIncluded"),
|
||||
value: SubscriptionFeatureLimitType.NOT_INCLUDED,
|
||||
},
|
||||
{
|
||||
name: t("admin.pricing.features.limitTypes.included"),
|
||||
value: SubscriptionFeatureLimitType.INCLUDED,
|
||||
},
|
||||
{
|
||||
name: t("admin.pricing.features.limitTypes.monthly"),
|
||||
value: SubscriptionFeatureLimitType.MONTHLY,
|
||||
},
|
||||
{
|
||||
name: t("admin.pricing.features.limitTypes.max"),
|
||||
value: SubscriptionFeatureLimitType.MAX,
|
||||
},
|
||||
{
|
||||
name: t("admin.pricing.features.limitTypes.unlimited"),
|
||||
value: SubscriptionFeatureLimitType.UNLIMITED,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<InputNumber
|
||||
name="value"
|
||||
title={t("admin.pricing.features.fields.limit")}
|
||||
value={existing?.value}
|
||||
setValue={(e) => {
|
||||
let value = e as number;
|
||||
if (existing) {
|
||||
existing.value = value;
|
||||
} else {
|
||||
item.plans.push({
|
||||
id: plan.id!,
|
||||
title: "?",
|
||||
type: SubscriptionFeatureLimitType.MAX,
|
||||
value,
|
||||
});
|
||||
}
|
||||
setItems([...items]);
|
||||
}}
|
||||
disabled={![SubscriptionFeatureLimitType.MONTHLY, SubscriptionFeatureLimitType.MAX].includes(existing?.type ?? 0)}
|
||||
/>
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
setHeaders(headers);
|
||||
}, [selectedPlans, items, t]);
|
||||
|
||||
function sortedItems() {
|
||||
return items.sort((a, b) => a.order - b.order);
|
||||
}
|
||||
|
||||
function onAdd() {
|
||||
const lastItem = items.length > 0 ? sortedItems()[items.length - 1] : undefined;
|
||||
const item: SubscriptionFeatureInPlansDto = {
|
||||
id: crypto.randomUUID(),
|
||||
name: "untitled-feature",
|
||||
order: items.length + 1,
|
||||
accumulate: false,
|
||||
plans: selectedPlans.map((p) => {
|
||||
const lastPlanFeature = lastItem?.plans.find((f) => f.id === p.id);
|
||||
return {
|
||||
id: p.id!,
|
||||
title: lastPlanFeature?.title ?? "",
|
||||
type: lastPlanFeature?.type ?? SubscriptionFeatureLimitType.NOT_INCLUDED,
|
||||
value: lastPlanFeature?.value ?? 0,
|
||||
};
|
||||
}),
|
||||
};
|
||||
setItems([...items, item]);
|
||||
}
|
||||
|
||||
function getErrors() {
|
||||
let errors: string[] = [];
|
||||
const duplicatedNames = items.filter((item, index) => items.findIndex((i) => i.name === item.name) !== index);
|
||||
if (duplicatedNames.length > 0) {
|
||||
errors = [...errors, ...duplicatedNames.map((item) => t("admin.pricing.features.errors.duplicatedName", { name: item.name }))];
|
||||
}
|
||||
items.forEach((item) => {
|
||||
item.plans.forEach(({ id, title }) => {
|
||||
const plan = selectedPlans.find((p) => p.id === id);
|
||||
if (!plan) {
|
||||
return;
|
||||
}
|
||||
if (!title.trim() || title === "?") {
|
||||
errors.push(t("admin.pricing.features.errors.invalidFeatureTitleInPlan", { title, plan: t(plan.title) }));
|
||||
}
|
||||
});
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
function onSave() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "update-features");
|
||||
form.set("planIds", JSON.stringify(selectedPlans.map((p) => p.id)));
|
||||
form.set("features", JSON.stringify(items));
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<EditPageLayout
|
||||
title={t("admin.pricing.features.title")}
|
||||
menu={[
|
||||
{ title: t("admin.pricing.title"), routePath: adminPath("settings/pricing", { mode: "host-aware" }) },
|
||||
{ title: t("models.subscriptionFeature.plural"), routePath: adminPath("settings/pricing/features", { mode: "host-aware" }) },
|
||||
]}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonSecondary onClick={() => setShowPreview(true)}>
|
||||
<EyeIcon className="h-4 w-4" />
|
||||
<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}>
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="flex space-x-1">
|
||||
<InputCombobox
|
||||
className="w-72"
|
||||
withSearch={false}
|
||||
title={t("admin.pricing.features.fields.plans")}
|
||||
value={selectedPlans.map((p) => p.id) as string[]}
|
||||
onChange={(e) => {
|
||||
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 }))}
|
||||
minDisplayCount={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{getErrors().length > 0 && (
|
||||
<div>
|
||||
<ErrorBanner title={t("admin.pricing.features.errors.title")}>
|
||||
<div>
|
||||
{getErrors().map((error) => {
|
||||
return <div key={error}>{error}</div>;
|
||||
})}
|
||||
</div>
|
||||
</ErrorBanner>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<TableSimple
|
||||
headers={headers}
|
||||
items={sortedItems()}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.pricing.features.actions.remove"),
|
||||
destructive: true,
|
||||
onClick: (idx) => {
|
||||
const item = items[idx];
|
||||
if (item) {
|
||||
setItems(items.filter((i) => i.id !== item.id));
|
||||
}
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAdd}
|
||||
className="border-border text-muted-foreground focus:text-foreground bg-background hover:bg-secondary/90 mt-2 flex items-center space-x-1 rounded-md border px-2 py-1 text-xs focus:ring-3 focus:ring-gray-300 focus:ring-offset-1"
|
||||
>
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
<span className="font-medium uppercase">{t("shared.add")}</span>
|
||||
</button>
|
||||
|
||||
<Modal open={showPreview} setOpen={() => setShowPreview(false)} size="7xl">
|
||||
<PlansGrouped
|
||||
items={selectedPlans.map((f) => {
|
||||
return {
|
||||
...f,
|
||||
features: items.map((item) => {
|
||||
const feature = item.plans.find((p) => p.id === f.id);
|
||||
return {
|
||||
...item,
|
||||
title: feature?.title ?? "",
|
||||
type: feature?.type ?? SubscriptionFeatureLimitType.NOT_INCLUDED,
|
||||
value: feature?.value ?? 0,
|
||||
};
|
||||
}),
|
||||
};
|
||||
})}
|
||||
stripeCoupon={null}
|
||||
canSubmit={false}
|
||||
currenciesAndPeriod={getCurrenciesAndPeriods(selectedPlans.flatMap((f) => f.prices))}
|
||||
/>
|
||||
</Modal>
|
||||
</EditPageLayout>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function ClosedOpenedValue({ closed, opened }: { closed: React.ReactNode; opened: React.ReactNode }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button type="button" className="hover:underline" onClick={() => setOpen(true)}>
|
||||
{closed}
|
||||
</button>
|
||||
<SlideOverWideEmpty
|
||||
withTitle={false}
|
||||
withClose={false}
|
||||
title={""}
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
className="sm:max-w-sm"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<Form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setOpen(false);
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
{opened}
|
||||
</Form>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useRef } from "react";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { createPlan } from "~/utils/services/.server/pricingService";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import PricingPlanForm from "~/components/core/pricing/PricingPlanForm";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
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";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
plans: SubscriptionProductDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.pricing.new")} | ${process.env.APP_NAME}`,
|
||||
plans: await getAllSubscriptionProducts(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.create");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action !== "create") {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
const order = Number(form.get("order"));
|
||||
const title = form.get("title")?.toString();
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const model = Number(form.get("model"));
|
||||
const badge = form.get("badge")?.toString() ?? "";
|
||||
const groupTitle = form.get("group-title")?.toString() ?? "";
|
||||
const groupDescription = form.get("group-description")?.toString() ?? "";
|
||||
const isPublic = Boolean(form.get("is-public"));
|
||||
const isBillingRequired = Boolean(form.get("is-billing-required"));
|
||||
const hasQuantity = Boolean(form.get("has-quantity"));
|
||||
const canBuyAgain = Boolean(form.get("can-buy-again"));
|
||||
|
||||
const featuresArr = form.getAll("features[]");
|
||||
const features: SubscriptionFeatureDto[] = featuresArr.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
const prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[] = form
|
||||
.getAll("prices[]")
|
||||
.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
const oneTimePricesWithZero = prices.filter((p) => p.billingPeriod === SubscriptionBillingPeriod.ONCE && p.price === 0);
|
||||
if (oneTimePricesWithZero.length > 0) {
|
||||
return badRequest({ error: t("admin.pricing.errors.oneTimePriceCannotBeZero") });
|
||||
}
|
||||
|
||||
const usageBasedPrices: SubscriptionUsageBasedPriceDto[] = form.getAll("usage-based-prices[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!title) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planTitleRequired") });
|
||||
}
|
||||
|
||||
const plan: SubscriptionProductDto = {
|
||||
stripeId: "",
|
||||
order,
|
||||
title,
|
||||
model,
|
||||
description,
|
||||
badge,
|
||||
groupTitle,
|
||||
groupDescription,
|
||||
active: true,
|
||||
public: isPublic,
|
||||
prices: [],
|
||||
features: [],
|
||||
usageBasedPrices,
|
||||
billingAddressCollection: isBillingRequired ? "required" : "auto",
|
||||
hasQuantity,
|
||||
canBuyAgain,
|
||||
};
|
||||
|
||||
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() });
|
||||
}
|
||||
};
|
||||
|
||||
export default function NewPricingPlanRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout title={<BackButtonWithTitle href={adminPath("settings/pricing", { mode: "host-aware" })}>{t("admin.pricing.new")}</BackButtonWithTitle>}>
|
||||
<PricingPlanForm plans={data.plans} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
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,
|
||||
getSubscriptionProduct,
|
||||
updateSubscriptionProduct,
|
||||
} from "@toolctrl/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 ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
||||
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 { isStripeTestMode } from "~/utils/stripe.server";
|
||||
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 { 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";
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
isStripeTest: boolean;
|
||||
items: SubscriptionProductDto[];
|
||||
};
|
||||
|
||||
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}`,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
items: await getAllSubscriptionProductsWithTenants(),
|
||||
};
|
||||
|
||||
if (data.items.length === 0) {
|
||||
data.items = plans;
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export type PricingPlansActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
items?: Awaited<ReturnType<typeof getAllSubscriptionProducts>>;
|
||||
};
|
||||
const badRequest = (data: PricingPlansActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.update");
|
||||
const { t } = await getTranslations(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;
|
||||
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") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const item = await getSubscriptionProduct(id);
|
||||
if (!item) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planNotFound") });
|
||||
}
|
||||
try {
|
||||
item.translatedTitle = t(item.title);
|
||||
await syncPlan(
|
||||
item,
|
||||
item.prices.map((price) => {
|
||||
return {
|
||||
id: price.id,
|
||||
billingPeriod: price.billingPeriod,
|
||||
currency: price.currency,
|
||||
price: Number(price.price),
|
||||
};
|
||||
})
|
||||
);
|
||||
return Response.json({
|
||||
items: await getAllSubscriptionProducts(),
|
||||
});
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
}
|
||||
} else if (action === "toggle") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const item = await getSubscriptionProduct(id);
|
||||
if (!item) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planNotFound") });
|
||||
}
|
||||
try {
|
||||
await updateSubscriptionProduct(id, {
|
||||
public: !item.public,
|
||||
});
|
||||
return Response.json({
|
||||
success: t("admin.pricing.actions.visibilityChanged", {
|
||||
status: t(!item.public ? "admin.pricing.status.public" : "admin.pricing.status.private"),
|
||||
}),
|
||||
});
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
}
|
||||
} else if (action === "bulk-delete") {
|
||||
await verifyUserHasPermission(request, "admin.pricing.delete");
|
||||
const ids = form.getAll("ids[]");
|
||||
const items = await getAllSubscriptionProducts();
|
||||
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) => {
|
||||
await deletePlan(item);
|
||||
})
|
||||
);
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminPricingRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<PricingPlansActionData>();
|
||||
const adminData = useAdminData();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const loading = navigation.state === "submitting";
|
||||
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
}
|
||||
updateItems(actionData?.items ?? data.items);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [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));
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const allFeatures: SubscriptionFeatureDto[] = [];
|
||||
items.forEach((item) => {
|
||||
item.features.forEach((feature) => {
|
||||
const existing = allFeatures.find((f) => f.name === feature.name);
|
||||
if (!existing) {
|
||||
allFeatures.push({
|
||||
order: feature.order,
|
||||
name: feature.name,
|
||||
title: feature.title,
|
||||
type: feature.type,
|
||||
value: feature.value,
|
||||
accumulate: feature.accumulate,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
setAllFeatures(allFeatures.sort((a, b) => a.order - b.order));
|
||||
}, [items]);
|
||||
|
||||
// const sortedItems = () => {
|
||||
// return items.sort((x, y) => {
|
||||
// return x?.order > y?.order ? 1 : -1;
|
||||
// });
|
||||
// };
|
||||
|
||||
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");
|
||||
// form.set("id", item.id?.toString() ?? "");
|
||||
// submit(form, {
|
||||
// method: "post",
|
||||
// });
|
||||
// }
|
||||
// function createPlan(item: SubscriptionProductDto) {
|
||||
// const form = new FormData();
|
||||
// form.set("action", "create");
|
||||
// form.set("order", item.order);
|
||||
// form.set("order", item.description);
|
||||
// employees.forEach((item) => {
|
||||
// form.append("employees[]", JSON.stringify(item));
|
||||
// });
|
||||
// submit(form, {
|
||||
// method: "post",
|
||||
// });
|
||||
// }
|
||||
|
||||
function createdPlans() {
|
||||
return data.items.filter((f) => f.id).length;
|
||||
}
|
||||
|
||||
// function getFeatureValue(item: SubscriptionProductDto, name: string) {
|
||||
// return item.features.find((f) => f.name === name);
|
||||
// }
|
||||
|
||||
function onToggle(item: SubscriptionProductDto) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "toggle");
|
||||
form.set("id", item.id?.toString() ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
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">
|
||||
{selectedItems.length > 0 && (
|
||||
<DeleteIconButton
|
||||
items={selectedItems}
|
||||
onClick={() => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "bulk-delete");
|
||||
selectedItems.forEach((item) => {
|
||||
form.append("ids[]", item.id?.toString() ?? "");
|
||||
});
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<ButtonSecondary
|
||||
disabled={data.items.length === 0}
|
||||
to={adminPath("settings/pricing/features?" + selectedItems.map((f) => "id=" + f.id).join("&"), { mode: "host-aware" })}
|
||||
>
|
||||
{selectedItems.length === 0 ? (
|
||||
<span>{t("admin.pricing.features.actions.setFeatures")}</span>
|
||||
) : (
|
||||
<span>{t("admin.pricing.features.actions.setFeaturesForSelection", { count: selectedItems.length })}</span>
|
||||
)}
|
||||
</ButtonSecondary>
|
||||
{selectedItems.length === 0 && (
|
||||
<Fragment>
|
||||
{/* <ButtonSecondary disabled={loading} to=".">
|
||||
{t("shared.reload")}
|
||||
</ButtonSecondary> */}
|
||||
|
||||
<ButtonPrimary to="new" disabled={loading || !getUserHasPermission(adminData, "admin.pricing.create")}>
|
||||
{t("shared.new")}
|
||||
</ButtonPrimary>
|
||||
</Fragment>
|
||||
)}
|
||||
</Form>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<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={[
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.FLAT_RATE]),
|
||||
value: PricingModel.FLAT_RATE,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.PER_SEAT]),
|
||||
value: PricingModel.PER_SEAT,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.USAGE_BASED]),
|
||||
value: PricingModel.USAGE_BASED,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.FLAT_RATE_USAGE_BASED]),
|
||||
value: PricingModel.FLAT_RATE_USAGE_BASED,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.ONCE]),
|
||||
value: PricingModel.ONCE,
|
||||
},
|
||||
{
|
||||
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>
|
||||
)}
|
||||
|
||||
<TableSimple
|
||||
selectedRows={selectedItems}
|
||||
onSelected={(items) => setSelectedItems(items)}
|
||||
items={items}
|
||||
headers={[
|
||||
{
|
||||
name: "level",
|
||||
title: t("models.subscriptionProduct.level"),
|
||||
value: (i) => <div className="text-muted-foreground text-xs">{i.order}</div>,
|
||||
},
|
||||
{
|
||||
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>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "model",
|
||||
title: t("models.subscriptionProduct.model"),
|
||||
value: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{t("pricing." + PricingModel[item.model])} </div>
|
||||
{item.model !== PricingModel.ONCE && (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{getPossibleBillingPeriods(item.prices)
|
||||
.map((billingPeriod) => t("pricing." + SubscriptionBillingPeriod[billingPeriod]).toLowerCase())
|
||||
.join(", ")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
// ...allFeatures.map((feature) => {
|
||||
// return {
|
||||
// name: feature.name,
|
||||
// title: feature.name,
|
||||
// value: (item: SubscriptionProductDto) => <PlanFeatureValue item={getFeatureValue(item, feature.name)} />,
|
||||
// };
|
||||
// }),
|
||||
{
|
||||
name: "subscriptions",
|
||||
title: t("models.subscriptionProduct.plural"),
|
||||
value: (item) => (
|
||||
<div className="text-muted-foreground lowercase">
|
||||
{t("admin.pricing.subscriptionCount", {
|
||||
count: item.tenantProducts?.length ?? 0,
|
||||
formattedCount: formatters.number(item.tenantProducts?.length ?? 0),
|
||||
})}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
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} />
|
||||
)}
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
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>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function DeleteIconButton({ onClick, items }: { onClick: () => void; items: SubscriptionProductDto[] }) {
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const confirmModal = useRef<RefConfirmModal>(null);
|
||||
function onDeleting() {
|
||||
const hasWithSub = items.some((f) => (f.tenantProducts?.length ?? 0) > 0);
|
||||
if (hasWithSub) {
|
||||
toast.error(t("admin.pricing.errors.activeSubscriptions", { plans: items.map((f) => t(f.title ?? "")).join(", ") }));
|
||||
} else {
|
||||
confirmModal.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Fragment>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(
|
||||
"hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent px-4 py-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden",
|
||||
navigation.state === "submitting" && navigation.formData?.get("action") === "bulk-delete" && "base-spinner"
|
||||
)}
|
||||
disabled={navigation.state !== "idle"}
|
||||
onClick={onDeleting}
|
||||
>
|
||||
<TrashIcon className="group-hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</button>
|
||||
<ConfirmModal ref={confirmModal} onYes={onClick} destructive />
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
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";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
mfaStatus: UserTotpStatus | null;
|
||||
currentSession: CurrentSessionSettings;
|
||||
};
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
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 || "system",
|
||||
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>
|
||||
);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
const settingsDir = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const protectedRoutes = [
|
||||
{ name: "general", file: "general.tsx", parserScope: "general" },
|
||||
{ name: "authentication", file: "authentication.tsx", parserScope: "authentication" },
|
||||
{ name: "analytics", file: "analytics.tsx", parserScope: "analytics" },
|
||||
{ name: "cookies", file: "cookies.tsx", parserScope: "cookies" },
|
||||
] as const;
|
||||
|
||||
const transactionalEmailException = {
|
||||
routeFile: "transactional-emails.tsx",
|
||||
testFile: "transactional-emails.test.tsx",
|
||||
serviceImport: "~/modules/emails/services/TransactionalEmailSettings.server",
|
||||
};
|
||||
|
||||
const secretAuditFieldNames = [
|
||||
"headScripts",
|
||||
"bodyScripts",
|
||||
"apiKey",
|
||||
"token",
|
||||
"password",
|
||||
"secret",
|
||||
];
|
||||
|
||||
function readSettingsRoute(file: string) {
|
||||
return readFileSync(join(settingsDir, file), "utf8");
|
||||
}
|
||||
|
||||
function extractActionBody(source: string) {
|
||||
const actionStart = source.indexOf("export const action");
|
||||
expect(actionStart, "route must export an action").toBeGreaterThanOrEqual(0);
|
||||
const componentStart = source.indexOf("export default", actionStart);
|
||||
expect(componentStart, "route must define action before default component").toBeGreaterThan(actionStart);
|
||||
return source.slice(actionStart, componentStart);
|
||||
}
|
||||
|
||||
function removeRedactionHelperCalls(source: string) {
|
||||
return source.replace(/redactSettingsAuditDetails\([^)]*\)/gs, "redactSettingsAuditDetails(<redacted>)");
|
||||
}
|
||||
|
||||
describe("admin settings validation/audit contract", () => {
|
||||
it.each(protectedRoutes)("$name route uses the shared validation service before mutating settings", ({ file, parserScope }) => {
|
||||
const source = readSettingsRoute(file);
|
||||
const actionBody = extractActionBody(source);
|
||||
|
||||
expect(source).toContain('from "~/utils/services/adminSettingsValidation.server"');
|
||||
expect(source).toContain("parseAdminSettingsForm");
|
||||
expect(source).toContain("redactSettingsAuditDetails");
|
||||
expect(actionBody).toContain(`parseAdminSettingsForm("${parserScope}", form)`);
|
||||
expect(actionBody).toContain("if (!parsed.ok)");
|
||||
expect(actionBody).toContain("Response.json({ error: t(\"shared.invalidForm\"), fieldErrors: parsed.errors }, { status: parsed.status })");
|
||||
expect(actionBody).toContain("updateAppConfiguration");
|
||||
expect(actionBody).toContain("createAdminLog");
|
||||
expect(actionBody.indexOf("if (!parsed.ok)")).toBeLessThan(actionBody.indexOf("updateAppConfiguration"));
|
||||
expect(actionBody.indexOf("updateAppConfiguration")).toBeLessThan(actionBody.indexOf("createAdminLog"));
|
||||
});
|
||||
|
||||
it.each(protectedRoutes)("$name route writes audit details only through the redaction helper", ({ file, parserScope }) => {
|
||||
const source = readSettingsRoute(file);
|
||||
const actionBody = extractActionBody(source);
|
||||
const redactionCall = `redactSettingsAuditDetails("${parserScope}"`;
|
||||
|
||||
expect(actionBody).toContain("createAdminLog(request, \"admin.settings.updated\"");
|
||||
expect(actionBody).toContain(redactionCall);
|
||||
|
||||
const unredactedActionBody = removeRedactionHelperCalls(actionBody);
|
||||
for (const fieldName of secretAuditFieldNames) {
|
||||
expect(unredactedActionBody, `${file} must not reference raw audit-sensitive field ${fieldName} outside redactSettingsAuditDetails`).not.toContain(fieldName);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps transactional emails as an explicit provider-settings-service exception", () => {
|
||||
const routeSource = readSettingsRoute(transactionalEmailException.routeFile);
|
||||
const testSource = readSettingsRoute(transactionalEmailException.testFile);
|
||||
|
||||
expect(routeSource).toContain(transactionalEmailException.serviceImport);
|
||||
expect(routeSource).toContain("updateMailjetSettings(form)");
|
||||
expect(testSource).toContain("updateMailjetSettings");
|
||||
expect(testSource).toContain("action rejects provider tampering through the Mailjet update helper");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
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";
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
useActionData: () => undefined,
|
||||
useFetcher: () => ({
|
||||
data: undefined,
|
||||
state: "idle",
|
||||
formData: undefined,
|
||||
submit: vi.fn(),
|
||||
Form: ({ children, ...props }: React.ComponentProps<"form">) => <form {...props}>{children}</form>,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, args?: Record<string, string>) => {
|
||||
if (key === "settings.admin.transactionalEmails.providerStatus") {
|
||||
return `${args?.provider} ${args?.status}`;
|
||||
}
|
||||
if (key === "settings.admin.transactionalEmails.sources.summary") {
|
||||
return `API key source: ${args?.apiKeySource}; From email source: ${args?.fromEmailSource}`;
|
||||
}
|
||||
if (key === "settings.admin.transactionalEmails.workerEnvNotice") {
|
||||
return `This page can only verify web-visible environment keys. The worker must use ${args?.providerEnvName}, MAILJET_SECRET_KEY, MAILJET_FROM_EMAIL, and MAILJET_FROM_NAME to deliver queued mail.`;
|
||||
}
|
||||
const labels: Record<string, string> = {
|
||||
"settings.admin.transactionalEmails.providers.mailjet": "Mailjet",
|
||||
"settings.admin.transactionalEmails.status.configured": "Configured",
|
||||
"settings.admin.transactionalEmails.status.missingConfiguration": "Missing configuration",
|
||||
};
|
||||
return labels[key] ?? key;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/mail-translator.server", () => ({
|
||||
getMailTranslator: vi.fn(async () => ({ t: (key: string) => key, locale: "en" })),
|
||||
getMailTranslatorFromRequest: vi.fn(async () => ({ t: (key: string) => (key === "registry.welcomeDescription" ? "Localized welcome email" : key), locale: "en" })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
requireUser: vi.fn(async () => ({ firstName: "Ada", email: "ada@example.com" })),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAdminData", () => ({
|
||||
useAdminData: () => ({ user: { email: "admin@example.com" } }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/emails/services/TransactionalEmailSettings.server", () => ({
|
||||
getMailjetProviderStatus: vi.fn(),
|
||||
updateMailjetSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/emails/services/EmailService", () => ({
|
||||
sendEmail: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({
|
||||
default: {
|
||||
allTemplates: [
|
||||
{
|
||||
name: "welcome",
|
||||
description: "Welcome email",
|
||||
describe: (t?: (key: string) => string) => t?.("registry.welcomeDescription") ?? "Welcome email",
|
||||
parse: vi.fn(() => ({ subject: "Welcome", body: "Hello" })),
|
||||
},
|
||||
],
|
||||
},
|
||||
}));
|
||||
|
||||
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/tables/TableSimple", () => ({
|
||||
default: ({ items }: { items: { name: string; description: string }[] }) => (
|
||||
<table>
|
||||
<tbody>
|
||||
{items.map((item) => (
|
||||
<tr key={item.name}>
|
||||
<td>{item.name}</td>
|
||||
<td>{item.description}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/modals/ModalOrSlide", () => ({
|
||||
default: ({ open, children }: { open: boolean; children: React.ReactNode }) => (open ? <section aria-label="Email Settings">{children}</section> : null),
|
||||
}));
|
||||
|
||||
const appConfiguration = {
|
||||
email: {
|
||||
provider: "mailjet",
|
||||
fromEmail: "sender@example.com",
|
||||
fromName: "Support",
|
||||
supportEmail: "support@example.com",
|
||||
},
|
||||
};
|
||||
|
||||
const mailjetStatus = {
|
||||
id: "mailjet" as const,
|
||||
name: "Mailjet" as const,
|
||||
configured: true,
|
||||
source: { apiKey: "environment" as const, secretKey: "environment" as const, fromEmail: "environment" as const },
|
||||
missing: [],
|
||||
};
|
||||
|
||||
let routeLoaderData = {
|
||||
title: "Transactional Emails",
|
||||
items: [{ name: "welcome", description: "Welcome email" }],
|
||||
appConfiguration,
|
||||
provider: mailjetStatus,
|
||||
providers: [mailjetStatus],
|
||||
};
|
||||
|
||||
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
|
||||
const getMailjetProviderStatusMock = vi.mocked(getMailjetProviderStatus);
|
||||
const updateMailjetSettingsMock = vi.mocked(updateMailjetSettings);
|
||||
|
||||
describe("admin transactional email route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
routeLoaderData = {
|
||||
title: "Transactional Emails",
|
||||
items: [{ name: "welcome", description: "Welcome email" }],
|
||||
appConfiguration,
|
||||
provider: mailjetStatus,
|
||||
providers: [mailjetStatus],
|
||||
};
|
||||
getAppConfigurationMock.mockResolvedValue(appConfiguration as Awaited<ReturnType<typeof getAppConfiguration>>);
|
||||
getMailjetProviderStatusMock.mockResolvedValue(mailjetStatus);
|
||||
updateMailjetSettingsMock.mockResolvedValue({ success: true });
|
||||
});
|
||||
|
||||
it("loader exposes Mailjet as the only provider status without secrets", async () => {
|
||||
const result = await loader({ request: new Request("https://admin.example.com/settings/transactional-emails"), params: {}, context: {}, unstable_pattern: "admin/settings/transactional-emails" });
|
||||
|
||||
expect(result.providers).toEqual([mailjetStatus]);
|
||||
expect(result.provider).toEqual(mailjetStatus);
|
||||
expect(result.items).toEqual([{ name: "welcome", description: "Localized welcome email" }]);
|
||||
// The provider status must only carry redaction markers, never raw key material.
|
||||
expect(Object.values(result.provider.source).every((value) => value === "environment" || value === "missing")).toBe(true);
|
||||
});
|
||||
|
||||
it("action rejects provider tampering through the Mailjet update helper", async () => {
|
||||
updateMailjetSettingsMock.mockResolvedValue({ success: false, error: "Only Mailjet is supported for transactional email." });
|
||||
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." });
|
||||
const submittedForm = updateMailjetSettingsMock.mock.calls[0]?.[0];
|
||||
expect(submittedForm?.get("emailProvider")).toBe("sendgrid");
|
||||
});
|
||||
|
||||
it("renders Mailjet-only settings without a generic provider selector", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<TransactionalEmailsRoute />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button"));
|
||||
|
||||
expect(screen.getByText("Mailjet")).toBeInTheDocument();
|
||||
expect(screen.getByText("API key source: environment; From email source: environment")).toBeInTheDocument();
|
||||
expect(screen.getByText(/This page can only verify web-visible environment keys/)).toBeInTheDocument();
|
||||
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
|
||||
expect(document.querySelector('input[name="emailFromEmail"]')).toBeNull();
|
||||
expect(document.querySelector('input[name="emailFromName"]')).toBeNull();
|
||||
expect(document.querySelector('input[name="emailProvider"]')).toHaveValue("mailjet");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useFetcher } from "react-router";
|
||||
import { useActionData, useLoaderData } from "react-router";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
|
||||
import { getMailTranslator, getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { AppConfiguration, getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import { sendEmail } from "~/modules/emails/services/EmailService";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { toast } from "sonner";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { cn } from "~/lib/utils";
|
||||
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";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: { name: string; description: string }[];
|
||||
appConfiguration: AppConfiguration;
|
||||
provider: MailjetProviderStatus;
|
||||
providers: MailjetProviderStatus[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
await verifyUserHasPermission(request, "admin.emails.view");
|
||||
const items = EmailTemplates.allTemplates;
|
||||
const { t } = await getTranslations(request);
|
||||
const mailTranslator = await getMailTranslatorFromRequest(request);
|
||||
const provider = await getMailjetProviderStatus({ request });
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.admin.transactionalEmails.title")} | ${process.env.APP_NAME}`,
|
||||
items: items.map((template) => ({ name: template.name, description: template.describe(mailTranslator.t) })),
|
||||
appConfiguration,
|
||||
provider,
|
||||
providers: [provider],
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
await verifyUserHasPermission(request, "admin.emails.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const user = await requireUser({ request });
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "send-test") {
|
||||
const email = form.get("email")?.toString();
|
||||
const templateName = form.get("template")?.toString();
|
||||
if (!email) {
|
||||
return { error: t("settings.admin.transactionalEmails.errors.invalidEmail") };
|
||||
}
|
||||
const template = EmailTemplates.allTemplates.find((f) => f.name === templateName);
|
||||
if (!template) {
|
||||
return { error: t("settings.admin.transactionalEmails.errors.invalidTemplate") };
|
||||
}
|
||||
// await sendEmail({ request, to: email, alias: template, data: {} });
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const mailTranslator = await getMailTranslator(user?.locale);
|
||||
try {
|
||||
await sendEmail({
|
||||
request,
|
||||
to: email,
|
||||
alias: template.name,
|
||||
...template.parse({
|
||||
appConfiguration,
|
||||
data: {
|
||||
name: user?.firstName,
|
||||
invite_sender_name: user?.firstName,
|
||||
invite_sender_organization: "{Account Name}",
|
||||
email,
|
||||
plan: "{Plan Name}",
|
||||
action_url: "https://example.com/action",
|
||||
},
|
||||
t: mailTranslator.t,
|
||||
locale: mailTranslator.locale,
|
||||
}),
|
||||
});
|
||||
return { success: t("settings.admin.transactionalEmails.testEmailQueued") };
|
||||
} catch (e: any) {
|
||||
return { error: e?.toString() };
|
||||
}
|
||||
} else if (action === "update-app-configuration") {
|
||||
const result = await updateMailjetSettings(form);
|
||||
if (!result.success) {
|
||||
return { error: result.error };
|
||||
}
|
||||
return { success: t("shared.updated") };
|
||||
}
|
||||
return { error: t("shared.invalidForm") };
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const adminData = useAdminData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const fetcher = useFetcher<{ success?: string; error?: string }>();
|
||||
|
||||
const [openSettings, setOpenSettings] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.success) {
|
||||
toast.success(fetcher.data.success);
|
||||
setOpenSettings(false);
|
||||
} else if (fetcher.data?.error) {
|
||||
toast.error(fetcher.data.error);
|
||||
}
|
||||
}, [fetcher.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function sendTest(templateName: string): void {
|
||||
let to = adminData.user?.email;
|
||||
if (to === "admin@email.com") {
|
||||
to = data.appConfiguration.email.supportEmail;
|
||||
}
|
||||
const email = window.prompt(t("settings.admin.transactionalEmails.promptEmail"), to);
|
||||
if (!email || email.trim() === "") {
|
||||
return;
|
||||
}
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "send-test");
|
||||
form.set("template", templateName);
|
||||
form.set("email", email);
|
||||
fetcher.submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function getProviderEnvName() {
|
||||
return "MAILJET_API_KEY";
|
||||
}
|
||||
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">
|
||||
<Button variant="ghost" onClick={() => setOpenSettings(true)}>
|
||||
<GearIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
headers={[
|
||||
{
|
||||
name: "name",
|
||||
title: t("admin.emails.name"),
|
||||
value: (i) => i.name,
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("shared.description"),
|
||||
value: (i) => i.description,
|
||||
},
|
||||
]}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.emails.sendTest"),
|
||||
onClick: (_, item) => sendTest(item.name),
|
||||
disabled: () => fetcher.state === "submitting",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<ModalOrSlide
|
||||
type="slide"
|
||||
title={t("settings.admin.transactionalEmails.settingsTitle")}
|
||||
open={openSettings}
|
||||
setOpen={() => {
|
||||
setOpenSettings(false);
|
||||
}}
|
||||
size="lg"
|
||||
>
|
||||
<fetcher.Form method="post">
|
||||
<input type="hidden" name="action" value="update-app-configuration" readOnly hidden />
|
||||
<input type="hidden" name="emailProvider" value="mailjet" readOnly hidden />
|
||||
<div className="grid gap-2 sm:grid-cols-12">
|
||||
<div className="rounded-md border bg-muted/30 p-3 sm:col-span-12">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<Label className="mb-1 block text-xs">{t("settings.admin.transactionalEmails.provider")}</Label>
|
||||
<div className="font-medium">{t("settings.admin.transactionalEmails.providers.mailjet")}</div>
|
||||
</div>
|
||||
<Badge variant={data.provider.configured ? "secondary" : "destructive"}>
|
||||
{data.provider.configured
|
||||
? t("settings.admin.transactionalEmails.status.configured")
|
||||
: t("settings.admin.transactionalEmails.status.missingConfiguration")}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="mt-2 text-xs text-muted-foreground">
|
||||
{t("settings.admin.transactionalEmails.sources.summary", {
|
||||
apiKeySource: data.provider.source.apiKey,
|
||||
fromEmailSource: data.provider.source.fromEmail,
|
||||
})}
|
||||
{data.provider.missing.length > 0
|
||||
? t("settings.admin.transactionalEmails.sources.missing", { missing: data.provider.missing.join(", ") })
|
||||
: ""}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-12">
|
||||
<Label className="mb-1 block text-xs">{t("settings.admin.transactionalEmails.supportEmail")}</Label>
|
||||
<Input type="email" name="emailSupportEmail" defaultValue={data.appConfiguration.email.supportEmail} placeholder="" className="bg-background" />
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-12 rounded-md border border-dashed p-3 text-xs text-muted-foreground">
|
||||
{t("settings.admin.transactionalEmails.workerEnvNotice", { providerEnvName: getProviderEnvName() })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 flex justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="submit"
|
||||
disabled={fetcher.state === "submitting"}
|
||||
className={cn(fetcher.state === "submitting" && fetcher.formData?.get("action") === "update-app-configuration" && "base-spinner")}
|
||||
>
|
||||
{t("shared.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</fetcher.Form>
|
||||
</ModalOrSlide>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user