Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+2
-24
@@ -13,8 +13,6 @@ vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
updateTenant: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ createLog: vi.fn() }));
|
||||
vi.mock("~/utils/db/entities/entities.db.server", () => ({ findEntityByName: vi.fn() }));
|
||||
vi.mock("~/utils/api/.server/RowsApi", () => ({ RowsApi: { createCustom: vi.fn() } }));
|
||||
vi.mock("~/utils/integrations/storageService", () => ({ storeFile: vi.fn() }));
|
||||
vi.mock("~/utils/integrations/storageAudit.server", () => ({ auditRejectedUpload: vi.fn(() => vi.fn()) }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
|
||||
@@ -25,15 +23,13 @@ vi.mock("~/utils/services/tenantService", () => ({
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({ getActiveTenantSubscriptions: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getTenantTypeOptions: vi.fn() }));
|
||||
vi.mock("@toolctrl/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: { mode: "path" } })) }));
|
||||
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: { mode: "path" } })) }));
|
||||
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createLog } from "~/utils/db/logs.db.server";
|
||||
import { getTenant, getTenantBySlug, updateTenant } from "~/utils/db/tenants.db.server";
|
||||
import { findEntityByName } from "~/utils/db/entities/entities.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { deleteAndCancelTenant, isReservedTenantSlug } from "~/utils/services/tenantService";
|
||||
import { getActiveTenantSubscriptions } from "~/utils/services/.server/subscriptionService";
|
||||
@@ -100,13 +96,11 @@ describe("tenant account settings action", () => {
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
||||
vi.mocked(getTenantBySlug).mockResolvedValue(null as never);
|
||||
vi.mocked(findEntityByName).mockResolvedValue(null as never);
|
||||
vi.mocked(updateTenant).mockResolvedValue({ ...tenant, name: "Acme GmbH" } as never);
|
||||
vi.mocked(EventsService.create).mockResolvedValue(undefined as never);
|
||||
vi.mocked(createLog).mockResolvedValue({} as never);
|
||||
vi.mocked(storeFile).mockImplementation(async ({ content }) => String(content));
|
||||
vi.mocked(isReservedTenantSlug).mockReturnValue(false);
|
||||
vi.mocked(RowsApi.createCustom).mockResolvedValue({} as never);
|
||||
vi.mocked(getActiveTenantSubscriptions).mockResolvedValue({ products: [] } as never);
|
||||
vi.mocked(deleteAndCancelTenant).mockResolvedValue(undefined as never);
|
||||
});
|
||||
@@ -151,7 +145,7 @@ describe("tenant account settings action", () => {
|
||||
expect(EventsService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects reserved slugs before logs, row properties, storage, and tenant mutation", async () => {
|
||||
it("rejects reserved slugs before logs, storage, and tenant mutation", async () => {
|
||||
vi.mocked(isReservedTenantSlug).mockReturnValueOnce(true);
|
||||
|
||||
const response = await callAction(createEditForm({ slug: "admin" }));
|
||||
@@ -160,27 +154,11 @@ describe("tenant account settings action", () => {
|
||||
expect(response.status).toBe(400);
|
||||
expect(data).toEqual({ updateDetailsError: "settings.tenant.errors.reservedSlug:admin" });
|
||||
expect(createLog).not.toHaveBeenCalled();
|
||||
expect(RowsApi.createCustom).not.toHaveBeenCalled();
|
||||
expect(storeFile).not.toHaveBeenCalled();
|
||||
expect(updateTenant).not.toHaveBeenCalled();
|
||||
expect(EventsService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps tenant settings row internals out of update errors", async () => {
|
||||
vi.mocked(findEntityByName).mockResolvedValueOnce({ id: "entity_1" } as never);
|
||||
vi.mocked(RowsApi.createCustom).mockRejectedValueOnce(new Error("raw row settings failure"));
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
|
||||
const response = await callAction(createEditForm());
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(data).toEqual({ updateDetailsError: "shared.unexpectedError" });
|
||||
expect(JSON.stringify(data)).not.toContain("raw row settings failure");
|
||||
expect(consoleError).toHaveBeenCalledWith(expect.any(Error));
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("stops on CSRF failure before permission checks and mutations", async () => {
|
||||
const csrfError = new Response("csrf", { status: 403 });
|
||||
vi.mocked(validateCSRFToken).mockRejectedValueOnce(csrfError as never);
|
||||
|
||||
+3
-30
@@ -17,8 +17,6 @@ import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getActiveTenantSubscriptions } from "~/utils/services/.server/subscriptionService";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { findEntityByName, type EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server";
|
||||
import { getTenantTypeOptions } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
@@ -29,12 +27,11 @@ import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import toast from "react-hot-toast";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
tenant: TenantWithDetails;
|
||||
tenantTypes: Awaited<ReturnType<typeof getTenantTypeOptions>>;
|
||||
};
|
||||
@@ -43,17 +40,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
|
||||
const { t } = await getTranslations(request);
|
||||
const [tenantSettingsEntity, tenant, tenantTypes] = await Promise.all([
|
||||
findEntityByName({ tenantId, name: "tenantSettings" }),
|
||||
getTenant(tenantId),
|
||||
getTenantTypeOptions(),
|
||||
]);
|
||||
const [tenant, tenantTypes] = await Promise.all([getTenant(tenantId), getTenantTypeOptions()]);
|
||||
if (!tenant) {
|
||||
throw Error(t("shared.notFound"));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
|
||||
tenantSettingsEntity,
|
||||
tenant,
|
||||
tenantTypes,
|
||||
};
|
||||
@@ -113,24 +105,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
await createLog(request, tenantId, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
||||
|
||||
const tenantSettingsEntity = await findEntityByName({ tenantId, name: "tenantSettings" });
|
||||
if (tenantSettingsEntity) {
|
||||
try {
|
||||
await RowsApi.createCustom({
|
||||
entity: tenantSettingsEntity,
|
||||
tenantId,
|
||||
t,
|
||||
form,
|
||||
row: existing?.tenantSettingsRow?.row as Parameters<typeof RowsApi.createCustom>[0]["row"],
|
||||
rowCreateInput: { tenantSettingsRow: { create: { tenantId } } },
|
||||
request,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return badRequest({ updateDetailsError: t("shared.unexpectedError") });
|
||||
}
|
||||
}
|
||||
|
||||
if (existing?.slug !== slug) {
|
||||
const existingSlug = await getTenantBySlug(slug);
|
||||
if (existingSlug) {
|
||||
@@ -252,7 +226,6 @@ export default function TenantRoute() {
|
||||
<UpdateTenantDetailsForm
|
||||
disabled={!getUserHasPermission(appData, "app.settings.account.update")}
|
||||
tenant={data.tenant}
|
||||
tenantSettingsEntity={data.tenantSettingsEntity}
|
||||
tenantTypes={data.tenantTypes}
|
||||
options={{
|
||||
canChangeType: false,
|
||||
@@ -268,7 +241,7 @@ export default function TenantRoute() {
|
||||
</div>
|
||||
|
||||
{/*Danger */}
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")}>
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/modules/api/services/ApiSpecsService", () => ({
|
||||
default: {
|
||||
generateSpecs: vi.fn(async () => ({
|
||||
openApi: { openapi: "3.1.0" },
|
||||
postmanCollection: { info: {}, item: [] },
|
||||
apiDocsUrl: "https://api.example.com/v1/docs",
|
||||
})),
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(async () => ({ app: { features: { tenantApiKeys: true } } })),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn(async () => undefined) }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant-1") }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string) => (key === "settings.api.errors.tenantApiKeysNotEnabled" ? "API keys are not enabled" : key),
|
||||
})),
|
||||
}));
|
||||
|
||||
import ApiSpecsService from "~/modules/api/services/ApiSpecsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { loader } from "./docs";
|
||||
|
||||
describe("tenant API docs route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(getAppConfiguration).mockResolvedValue({ app: { features: { tenantApiKeys: true } } } as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
});
|
||||
|
||||
it("checks tenant permission and feature gate before generating docs", async () => {
|
||||
const request = new Request("https://app.example.com/acme/settings/api/docs");
|
||||
|
||||
const data = await loader({ request, params: { tenant: "acme" }, context: {} } as unknown as LoaderFunctionArgs);
|
||||
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith({ tenant: "acme" });
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(request, "app.settings.apiKeys.view", "tenant-1");
|
||||
expect(getAppConfiguration).toHaveBeenCalledWith({ request });
|
||||
expect(ApiSpecsService.generateSpecs).toHaveBeenCalledWith({ request });
|
||||
expect(data).toMatchObject({ apiSpecs: { apiDocsUrl: "https://api.example.com/v1/docs" } });
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
vi.mocked(ApiSpecsService.generateSpecs).mock.invocationCallOrder[0]
|
||||
);
|
||||
});
|
||||
|
||||
it("does not generate docs when tenant API keys are disabled", async () => {
|
||||
vi.mocked(getAppConfiguration).mockResolvedValue({ app: { features: { tenantApiKeys: false } } } as never);
|
||||
|
||||
try {
|
||||
await loader({ request: new Request("https://app.example.com/acme/settings/api/docs"), params: { tenant: "acme" }, context: {} } as never);
|
||||
throw new Error("Expected loader to throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(Response);
|
||||
const response = error as Response;
|
||||
expect(response.status).toBe(404);
|
||||
await expect(response.json()).resolves.toEqual({ error: "API keys are not enabled" });
|
||||
}
|
||||
|
||||
expect(getTranslations).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(ApiSpecsService.generateSpecs).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import ApiSpecs from "~/modules/api/components/ApiSpecs";
|
||||
import ApiSpecsService, { ApiSpecsDto } from "~/modules/api/services/ApiSpecsService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
type LoaderData = {
|
||||
apiSpecs: ApiSpecsDto;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.apiKeys.view", tenantId);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (!appConfiguration.app.features.tenantApiKeys) {
|
||||
throw Response.json({ error: t("settings.api.errors.tenantApiKeysNotEnabled") }, { status: 404 });
|
||||
}
|
||||
const apiSpecs = await ApiSpecsService.generateSpecs({ request });
|
||||
const data: LoaderData = {
|
||||
apiSpecs,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function AdminApiDocsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: UrlUtils.getModulePath(params, "api"),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: UrlUtils.getModulePath(params, "api/logs"),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: UrlUtils.getModulePath(params, "api/keys"),
|
||||
},
|
||||
{
|
||||
name: t("docs.title"),
|
||||
routePath: UrlUtils.getModulePath(params, "api/docs"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ApiSpecs item={data.apiSpecs} postmanCollectionUrl={null} showPostmanCollection={false} />
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-1
@@ -39,7 +39,6 @@ export default function ApiKeysRoute() {
|
||||
>
|
||||
<ApiKeysTable
|
||||
canCreate={getUserHasPermission(appData, "app.settings.apiKeys.create")}
|
||||
entities={appData.entities}
|
||||
items={data.apiKeys}
|
||||
/>
|
||||
<Outlet />
|
||||
|
||||
+10
-22
@@ -32,9 +32,6 @@ vi.mock("~/utils/db/apiKeys.db.server", () => ({
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({
|
||||
createLog: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/ApiKeyHelperService", () => ({
|
||||
getApiKeyEntityPermissions: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
||||
default: { create: vi.fn() },
|
||||
}));
|
||||
@@ -53,7 +50,6 @@ import { countApiKeyLogsForKey, deleteApiKey, getApiKeys, getTenantApiKeyById, r
|
||||
import { createLog } from "~/utils/db/logs.db.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getApiKeyEntityPermissions } from "~/utils/helpers/.server/ApiKeyHelperService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
@@ -62,14 +58,12 @@ import { action } from "./$id";
|
||||
const params = { tenant: "acme", id: "api-key-1" };
|
||||
const tenant = { id: "tenant-1", name: "Acme", slug: "acme" };
|
||||
const user = { id: "user-1", email: "ada@example.test" };
|
||||
const entityPermission = { entityId: "entity-1", create: true, read: true, update: false, delete: false };
|
||||
const existingApiKey = {
|
||||
id: "api-key-1",
|
||||
tenantId: "tenant-1",
|
||||
alias: "Primary integration",
|
||||
expires: null,
|
||||
active: true,
|
||||
entities: [entityPermission],
|
||||
};
|
||||
const rotatedApiKey = { ...existingApiKey, key: "tc_live_rotated_plaintext_once" };
|
||||
|
||||
@@ -86,7 +80,6 @@ function createForm(actionName: "edit" | "delete" | "rotate" = "edit", overrides
|
||||
form.set("action", actionName);
|
||||
form.set("alias", "Primary integration updated");
|
||||
form.set("active", "on");
|
||||
form.append("entities[]", JSON.stringify(entityPermission));
|
||||
Object.entries(overrides).forEach(([key, value]) => form.set(key, value));
|
||||
return form;
|
||||
}
|
||||
@@ -120,7 +113,6 @@ describe("tenant API key edit route", () => {
|
||||
vi.mocked(rotateApiKey).mockResolvedValue(rotatedApiKey as never);
|
||||
vi.mocked(deleteApiKey).mockResolvedValue(existingApiKey as never);
|
||||
vi.mocked(countApiKeyLogsForKey).mockResolvedValue(0 as never);
|
||||
vi.mocked(getApiKeyEntityPermissions).mockImplementation(async (permissions) => permissions as never);
|
||||
vi.mocked(EventsService.create).mockResolvedValue(undefined as never);
|
||||
vi.mocked(createLog).mockResolvedValue({} as never);
|
||||
});
|
||||
@@ -191,33 +183,29 @@ describe("tenant API key edit route", () => {
|
||||
expect(createLog).toHaveBeenCalledWith(expect.any(Request), "tenant-1", "settings.apiKeys.deleted", "");
|
||||
});
|
||||
|
||||
it("preserves edited scope changes in logs and events", async () => {
|
||||
it("preserves edited details in logs and events", async () => {
|
||||
const response = await callAction(createForm("edit", { alias: "Primary integration updated" }));
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(updateApiKey).toHaveBeenCalledWith(
|
||||
"api-key-1",
|
||||
{
|
||||
tenantId: "tenant-1",
|
||||
alias: "Primary integration updated",
|
||||
expires: null,
|
||||
active: true,
|
||||
},
|
||||
[entityPermission]
|
||||
);
|
||||
expect(updateApiKey).toHaveBeenCalledWith("api-key-1", {
|
||||
tenantId: "tenant-1",
|
||||
alias: "Primary integration updated",
|
||||
expires: null,
|
||||
active: true,
|
||||
});
|
||||
expect(createLog).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"tenant-1",
|
||||
"settings.apiKeys.updated",
|
||||
expect.stringContaining('"entities":[{"entityId":"entity-1","create":true,"read":true,"update":false,"delete":false}]')
|
||||
expect.stringContaining('"alias":"Primary integration updated"')
|
||||
);
|
||||
expect(createLog).toHaveBeenCalledTimes(1);
|
||||
expect(EventsService.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
event: "api_key.updated",
|
||||
data: expect.objectContaining({
|
||||
new: expect.objectContaining({ entities: [entityPermission] }),
|
||||
old: expect.objectContaining({ entities: [entityPermission] }),
|
||||
new: expect.objectContaining({ alias: "Primary integration updated", active: true }),
|
||||
old: expect.objectContaining({ alias: "Primary integration" }),
|
||||
}),
|
||||
})
|
||||
);
|
||||
|
||||
+7
-23
@@ -17,7 +17,6 @@ import {
|
||||
} from "~/utils/db/apiKeys.db.server";
|
||||
import { createLog } from "~/utils/db/logs.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getApiKeyEntityPermissions } from "~/utils/helpers/.server/ApiKeyHelperService";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
@@ -69,11 +68,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
if (action === "edit") {
|
||||
const entities: { entityId: string; create: boolean; read: boolean; update: boolean; delete: boolean }[] = form
|
||||
.getAll("entities[]")
|
||||
.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
let expirationDate: Date | null = null;
|
||||
let expires = form.get("expires")?.toString();
|
||||
if (expires) {
|
||||
@@ -85,17 +79,13 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
await updateApiKey(
|
||||
params.id ?? "",
|
||||
{
|
||||
tenantId: tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
},
|
||||
entities
|
||||
);
|
||||
await createLog(request, tenantId, "settings.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active, entities }));
|
||||
await updateApiKey(params.id ?? "", {
|
||||
tenantId: tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createLog(request, tenantId, "settings.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
@@ -107,13 +97,11 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
alias: alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
entities: await getApiKeyEntityPermissions(entities),
|
||||
},
|
||||
old: {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
entities: await getApiKeyEntityPermissions(existing.entities),
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
@@ -133,13 +121,11 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
entities: await getApiKeyEntityPermissions(existing.entities),
|
||||
},
|
||||
old: {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
entities: await getApiKeyEntityPermissions(existing.entities),
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
@@ -163,7 +149,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
entities: await getApiKeyEntityPermissions(existing.entities),
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
@@ -183,7 +168,6 @@ export default function ApiEditKeyRoute() {
|
||||
<>
|
||||
<OpenModal className="sm:max-w-xl" onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/api/keys"))}>
|
||||
<ApiKeyForm
|
||||
entities={appData.entities}
|
||||
item={data.item}
|
||||
canUpdate={getUserHasPermission(appData, "app.settings.apiKeys.update")}
|
||||
canDelete={getUserHasPermission(appData, "app.settings.apiKeys.delete")}
|
||||
|
||||
+9
-22
@@ -5,11 +5,9 @@ import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
|
||||
import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { createApiKey, getApiKeyByAlias } from "~/utils/db/apiKeys.db.server";
|
||||
import { createLog } from "~/utils/db/logs.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getApiKeyEntityPermissions } from "~/utils/helpers/.server/ApiKeyHelperService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
@@ -47,12 +45,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "create") {
|
||||
const entities: { entityId: string; create: boolean; read: boolean; update: boolean; delete: boolean }[] = form
|
||||
.getAll("entities[]")
|
||||
.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
let expirationDate: Date | null = null;
|
||||
let expires = form.get("expires")?.toString();
|
||||
if (expires) {
|
||||
@@ -64,16 +56,13 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
const apiKey = await createApiKey(
|
||||
{
|
||||
tenantId: tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
},
|
||||
entities
|
||||
);
|
||||
const apiKey = await createApiKey({
|
||||
tenantId: tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
@@ -84,11 +73,10 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
alias: apiKey.alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
entities: await getApiKeyEntityPermissions(entities),
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
});
|
||||
await createLog(request, tenantId, "settings.apiKeys.created", JSON.stringify({ id: apiKey.id, alias, expirationDate, active, entities }));
|
||||
await createLog(request, tenantId, "settings.apiKeys.created", JSON.stringify({ id: apiKey.id, alias, expirationDate, active }));
|
||||
return Response.json({ apiKey: { key: apiKey.key, alias: apiKey.alias } } satisfies ActionData);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
@@ -99,11 +87,10 @@ export default function ApiNewKeyRoute() {
|
||||
const navigate = useNavigate();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
const appData = useAppData();
|
||||
return (
|
||||
<>
|
||||
<OpenModal className="sm:max-w-xl" onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/api/keys"))}>
|
||||
<ApiKeyForm entities={appData.entities} />
|
||||
<ApiKeyForm />
|
||||
{actionData?.apiKey !== undefined && (
|
||||
<ApiKeyCreatedModal apiKey={actionData?.apiKey} redirectTo={UrlUtils.currentTenantUrl(params, "settings/api/keys")} />
|
||||
)}
|
||||
|
||||
+4
-4
@@ -2,12 +2,12 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./audit-export";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
vi.mock("@toolctrl/db/client.server", () => ({
|
||||
vi.mock("@hivegrid/db/client.server", () => ({
|
||||
getDbClient: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -34,7 +34,7 @@ function callLoader(url: string) {
|
||||
describe("tenant audit export route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
@@ -50,7 +50,7 @@ describe("tenant audit export route", () => {
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.auditTrails.view", "tenant-1");
|
||||
expect(findMany).not.toHaveBeenCalled();
|
||||
expect(data).toMatchObject({
|
||||
title: "translated:models.log.plural | ToolCTRL",
|
||||
title: "translated:models.log.plural | HiveGrid",
|
||||
tenantSlug: "acme",
|
||||
maxRows: expect.any(Number),
|
||||
});
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
+5
-70
@@ -1,78 +1,13 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CreditsList from "~/modules/usage/components/CreditsList";
|
||||
import { CreditWithDetails, getAllCredits } from "~/modules/usage/db/credits.db.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { CreditTypes } from "~/modules/usage/dtos/CreditType";
|
||||
import { LoaderFunctionArgs, redirect } from "react-router";
|
||||
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
items: CreditWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
canDelete: boolean;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.view", tenantId);
|
||||
if (CreditTypes.length === 0) {
|
||||
return redirect(UrlUtils.currentTenantUrl(params, "settings/subscription"));
|
||||
}
|
||||
const tenantUsers = await getTenantUsers(tenantId);
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "userId",
|
||||
title: "models.user.object",
|
||||
options: [
|
||||
{ value: "null", name: t("models.credit.filters.noUser") },
|
||||
...tenantUsers.map((item) => {
|
||||
return {
|
||||
value: item.user.id,
|
||||
name: item.user.email,
|
||||
};
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "type",
|
||||
title: "models.credit.type",
|
||||
options: CreditTypes.map((item) => {
|
||||
return {
|
||||
value: item.value,
|
||||
name: t(item.name),
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const { items, pagination } = await getAllCredits({ tenantId, filters, filterableProperties, pagination: currentPagination });
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
filterableProperties,
|
||||
pagination,
|
||||
canDelete: false,
|
||||
};
|
||||
return data;
|
||||
return redirect(UrlUtils.currentTenantUrl(params, "settings/subscription"));
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<EditPageLayout title={t("models.credit.plural")}>
|
||||
<CreditsList data={data} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
export default function RemovedCreditsRoute() {
|
||||
return null;
|
||||
}
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityTemplate } from "@toolctrl/db/prisma-browser";
|
||||
import { getEntityTemplates } from "~/utils/db/entities/entityTemplates.db.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
items: EntityTemplate[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const items = await getEntityTemplates(entity.id, { tenantId });
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function EntityTemplatesIndex() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
|
||||
function getConfig(item: EntityTemplate) {
|
||||
try {
|
||||
const config = JSON.parse(item.config);
|
||||
const values: string[] = [];
|
||||
data.entity.properties
|
||||
.filter((f) => !f.isDefault)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.forEach((property) => {
|
||||
let value = config[property.name];
|
||||
if (value) {
|
||||
if (property.type === PropertyType.SELECT) {
|
||||
const option = property.options.find((f) => f.value === value);
|
||||
if (option) {
|
||||
value = option.name || option.value;
|
||||
}
|
||||
}
|
||||
values.push(t(property.title) + ": " + value);
|
||||
}
|
||||
});
|
||||
return values.join(", ");
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t(data.entity.titlePlural) + " - " + t("models.entity.templates")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: t("models.entity.plural"),
|
||||
routePath: UrlUtils.getModulePath(params, `entities`),
|
||||
},
|
||||
{
|
||||
title: data.entity.titlePlural,
|
||||
routePath: UrlUtils.getModulePath(params, `entities/${data.entity.slug}/templates`),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<TableSimple
|
||||
headers={[
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.entityTemplate.title"),
|
||||
value: (item) => item.title,
|
||||
},
|
||||
{
|
||||
title: t("models.entityTemplate.object"),
|
||||
name: "template",
|
||||
className: "max-w-xs",
|
||||
value: (item) => <ShowPayloadModalButton title={t("models.entityTemplate.templateWithTitle", { title: item.title })} payload={getConfig(item)} />,
|
||||
},
|
||||
]}
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (idx, item) => item.id,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
<div className="w-fu flex justify-start">
|
||||
<ButtonTertiary to="new">
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
<span className="font-medium uppercase">{t("shared.add")}</span>
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
import { EntityTemplate } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityTemplateForm from "~/components/entities/entityTemplates/EntityTemplateForm";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { deleteScopedEntityTemplate, getEntityTemplate, updateScopedEntityTemplate } from "~/utils/db/entities/entityTemplates.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
item: EntityTemplate;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const templateScope = { id: params.id ?? "", tenantId, entityId: entity.id };
|
||||
const item = await getEntityTemplate(templateScope.id, { tenantId, entityId: entity.id });
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const templateScope = { id: params.id ?? "", tenantId, entityId: entity.id };
|
||||
const existing = await getEntityTemplate(templateScope.id, { tenantId, entityId: entity.id });
|
||||
if (!existing) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const config = form.get("config")?.toString() ?? "";
|
||||
|
||||
if (action === "edit") {
|
||||
try {
|
||||
await updateScopedEntityTemplate(templateScope, {
|
||||
title,
|
||||
config,
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
} catch {
|
||||
return badRequest({ error: t("models.entityTemplate.errors.updateFailed") });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await deleteScopedEntityTemplate(templateScope);
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityTemplateRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
const navigate = useNavigate();
|
||||
function close() {
|
||||
navigate(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
}
|
||||
return (
|
||||
<SlideOverWideEmpty title={t("models.entityTemplate.edit")} open={true} className="sm:max-w-lg" onClose={close}>
|
||||
<EntityTemplateForm entity={data.entity} item={data.item} />
|
||||
</SlideOverWideEmpty>
|
||||
);
|
||||
}
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityTemplateForm from "~/components/entities/entityTemplates/EntityTemplateForm";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { createEntityTemplate } from "~/utils/db/entities/entityTemplates.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
entity: EntityWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const data: LoaderData = {
|
||||
title: t("models.entityTemplate.metaTitle", { appName: process.env.APP_NAME }),
|
||||
entity,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity! });
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const config = form.get("config")?.toString() ?? "";
|
||||
|
||||
if (action === "create") {
|
||||
try {
|
||||
await createEntityTemplate({
|
||||
entityId: entity.id,
|
||||
tenantId,
|
||||
title,
|
||||
config,
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
} catch {
|
||||
return badRequest({ error: t("models.entityTemplate.errors.createFailed") });
|
||||
}
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function NewEntityTemplateRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
const navigate = useNavigate();
|
||||
function close() {
|
||||
navigate(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
}
|
||||
return (
|
||||
<SlideOverWideEmpty title={t("models.entityTemplate.new")} open={true} className="sm:max-w-lg" onClose={close}>
|
||||
<EntityTemplateForm entity={data.entity} />
|
||||
</SlideOverWideEmpty>
|
||||
);
|
||||
}
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData, useNavigate, useOutlet } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import TenantPropertiesList from "~/components/entities/properties/TenantPropertiesList";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { PropertiesApi } from "~/utils/api/.server/PropertiesApi";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { PropertyWithDetails, getEntityBySlug, EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { deleteScopedProperty, getScopedProperty, updateScopedProperty, updateScopedPropertyOrder } from "~/utils/db/entities/properties.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
properties: PropertyWithDetails[];
|
||||
allEntities: EntityWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await requireAuth({ request, params });
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (!appConfiguration.app.features.tenantEntityCustomization) {
|
||||
throw Error(t("settings.entities.errors.tenantEntityCustomizationNotEnabled"));
|
||||
}
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
properties: entity.properties,
|
||||
allEntities: await getAllEntities({ tenantId }),
|
||||
};
|
||||
return success(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
properties?: PropertyWithDetails[];
|
||||
created?: boolean;
|
||||
updated?: boolean;
|
||||
deleted?: boolean;
|
||||
};
|
||||
const success = (data: ActionData) => Response.json(data, { status: 200 });
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
const allowedPropertyIds = new Set(entity.properties.map((property) => property.id));
|
||||
if (items.some(({ id }) => !allowedPropertyIds.has(id))) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
items.map(async ({ id, order }) => {
|
||||
await updateScopedPropertyOrder({ id, tenantId, entityId: entity.id }, Number(order));
|
||||
})
|
||||
);
|
||||
return Response.json({ updated: true });
|
||||
} else if (action === "delete") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const propertyScope = { id, tenantId, entityId: entity.id };
|
||||
const existingProperty = await getScopedProperty(propertyScope);
|
||||
if (!existingProperty) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
await deleteScopedProperty(propertyScope);
|
||||
return success({
|
||||
properties: (await getEntityBySlug({ tenantId, slug: params.entity ?? "" }))?.properties,
|
||||
deleted: true,
|
||||
});
|
||||
// return redirect(adminPath(`entities/${params.entity}/properties`, { mode: "host-aware" }));
|
||||
} else if (action === "toggle-display") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const propertyScope = { id, tenantId, entityId: entity.id };
|
||||
const existingProperty = await getScopedProperty(propertyScope);
|
||||
if (!existingProperty) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
await updateScopedProperty(propertyScope, {
|
||||
isDisplay: !existingProperty.isDisplay,
|
||||
});
|
||||
return Response.json({});
|
||||
// return redirect(adminPath(`entities/${params.entity}/properties`, { mode: "host-aware" }));
|
||||
} else if (action === "duplicate") {
|
||||
try {
|
||||
const propertyId = form.get("id")?.toString() ?? "";
|
||||
const existingProperty = await getScopedProperty({ id: propertyId, tenantId, entityId: entity.id });
|
||||
if (!existingProperty) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
await PropertiesApi.duplicate({ entity, propertyId });
|
||||
return Response.json({ created: true });
|
||||
} catch {
|
||||
return badRequest({ error: t("models.property.errors.duplicateFailed") });
|
||||
}
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const appData = useAppData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={`${t(data.entity.title)} - ${t("models.property.plural")}`}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: t("models.entity.plural"),
|
||||
routePath: UrlUtils.getModulePath(params, `entities`),
|
||||
},
|
||||
{
|
||||
title: data.entity.titlePlural,
|
||||
routePath: UrlUtils.getModulePath(params, `entities/${data.entity.slug}`),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<TenantPropertiesList tenantId={appData.currentTenant.id} items={data.properties} />
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("shared.edit") : t("shared.new")}
|
||||
open={!!outlet}
|
||||
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>
|
||||
);
|
||||
}
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import PropertyForm from "~/components/entities/properties/PropertyForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllFormulas } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import FormulaHelpers from "~/modules/formulas/utils/FormulaHelpers";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { PropertyWithDetails, EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import {
|
||||
deleteScopedProperty,
|
||||
getScopedProperty,
|
||||
updateScopedProperty,
|
||||
updateScopedPropertyAttributes,
|
||||
updateScopedPropertyOptions,
|
||||
} from "~/utils/db/entities/properties.db.server";
|
||||
import { validateProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
item: PropertyWithDetails;
|
||||
formulas: FormulaDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const propertyScope = { id: params.id ?? "", tenantId, entityId: entity.id };
|
||||
const item = await getScopedProperty(propertyScope);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}`));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
item,
|
||||
formulas: (await getAllFormulas()).map((formula) => FormulaHelpers.getFormulaDto(formula)),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
|
||||
const propertyScope = { id: params.id ?? "", tenantId, entityId: entity.id };
|
||||
const existing = await getScopedProperty(propertyScope);
|
||||
if (!existing) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const type = Number(form.get("type")) as PropertyType;
|
||||
const subtype = form.get("subtype")?.toString() ?? null;
|
||||
const order = Number(form.get("order"));
|
||||
let isRequired = Boolean(form.get("is-required"));
|
||||
const isHidden = Boolean(form.get("is-hidden"));
|
||||
const isDisplay = Boolean(form.get("is-display"));
|
||||
const isReadOnly = Boolean(form.get("is-read-only"));
|
||||
const canUpdate = Boolean(form.get("can-update"));
|
||||
let showInCreate = Boolean(form.get("show-in-create"));
|
||||
let formulaId = form.get("formula-id")?.toString() ?? null;
|
||||
|
||||
if (["id", "folio", "createdAt", "createdByUser", "sort", "page", "q", "v", "redirect", "tags"].includes(name)) {
|
||||
return badRequest({ error: t("models.property.errors.reservedName", { name }) });
|
||||
}
|
||||
|
||||
const options: { order: number; value: string; name?: string; color?: Colors }[] = form.getAll("options[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
const attributes: { name: string; value: string }[] = form.getAll("attributes[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if ([PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(type) && options.length === 0) {
|
||||
// return badRequest({ error: "Add at least one option" });
|
||||
}
|
||||
|
||||
if (type !== PropertyType.FORMULA) {
|
||||
formulaId = null;
|
||||
} else {
|
||||
isRequired = false;
|
||||
}
|
||||
if ([PropertyType.FORMULA].includes(type) && !formulaId) {
|
||||
return badRequest({ error: t("models.property.errors.selectFormula") });
|
||||
}
|
||||
|
||||
const errors = await validateProperty(name, title, entity.properties, existing, t);
|
||||
if (errors.length > 0) {
|
||||
return badRequest({ error: errors.join(", ") });
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
if (name?.includes(" ")) {
|
||||
return badRequest({ error: t("models.property.errors.nameNoSpaces") });
|
||||
}
|
||||
if (name?.includes("-")) {
|
||||
return badRequest({ error: t("models.property.errors.nameNoHyphen") });
|
||||
}
|
||||
try {
|
||||
await updateScopedProperty(propertyScope, {
|
||||
name,
|
||||
title,
|
||||
type,
|
||||
subtype,
|
||||
order,
|
||||
isDefault: existing?.isDefault ?? false,
|
||||
isRequired,
|
||||
isHidden,
|
||||
isDisplay,
|
||||
isReadOnly,
|
||||
canUpdate,
|
||||
showInCreate,
|
||||
formulaId,
|
||||
});
|
||||
await updateScopedPropertyOptions(propertyScope, options);
|
||||
await updateScopedPropertyAttributes(propertyScope, attributes);
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}`));
|
||||
} catch {
|
||||
return badRequest({ error: t("models.property.errors.updateFailed") });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await deleteScopedProperty(propertyScope);
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}`));
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityPropertyRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return <PropertyForm item={data.item} properties={[]} entities={appOrAdminData.entities} formulas={data.formulas} />;
|
||||
}
|
||||
-132
@@ -1,132 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import PropertyForm from "~/components/entities/properties/PropertyForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllFormulas } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import FormulaHelpers from "~/modules/formulas/utils/FormulaHelpers";
|
||||
import { PropertiesApi } from "~/utils/api/.server/PropertiesApi";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { PropertyWithDetails, getEntityBySlug, EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { validateProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
properties: PropertyWithDetails[];
|
||||
formulas: FormulaDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
properties: entity?.properties ?? [],
|
||||
formulas: (await getAllFormulas()).map((formula) => FormulaHelpers.getFormulaDto(formula)),
|
||||
};
|
||||
return success(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
properties?: PropertyWithDetails[];
|
||||
};
|
||||
const success = (data: ActionData) => Response.json(data, { status: 200 });
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const type = Number(form.get("type")) as PropertyType;
|
||||
const subtype = form.get("subtype")?.toString() ?? null;
|
||||
const order = Number(form.get("order"));
|
||||
const isDefault = Boolean(form.get("is-default"));
|
||||
let isRequired = Boolean(form.get("is-required"));
|
||||
const isHidden = Boolean(form.get("is-hidden"));
|
||||
const isDisplay = Boolean(form.get("is-display"));
|
||||
const isReadOnly = Boolean(form.get("is-read-only"));
|
||||
const canUpdate = Boolean(form.get("can-update"));
|
||||
let showInCreate = Boolean(form.get("show-in-create"));
|
||||
let formulaId = form.get("formula-id")?.toString() ?? null;
|
||||
|
||||
if (["id", "folio", "createdAt", "createdByUser", "sort", "page", "q", "v", "redirect", "tags"].includes(name)) {
|
||||
return badRequest({ error: t("models.property.errors.reservedName", { name }) });
|
||||
}
|
||||
|
||||
const options: { order: number; value: string; name?: string; color?: Colors }[] = form.getAll("options[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
const attributes: { name: string; value: string }[] = form.getAll("attributes[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if ([PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(type) && options.length === 0) {
|
||||
// return badRequest({ error: "Add at least one option" });
|
||||
}
|
||||
|
||||
if (type !== PropertyType.FORMULA) {
|
||||
formulaId = null;
|
||||
} else {
|
||||
isRequired = false;
|
||||
showInCreate = false;
|
||||
}
|
||||
if ([PropertyType.FORMULA].includes(type) && !formulaId) {
|
||||
return badRequest({ error: t("models.property.errors.selectFormula") });
|
||||
}
|
||||
|
||||
const errors = await validateProperty(name, title, entity.properties, null, t);
|
||||
if (errors.length > 0) {
|
||||
return badRequest({ error: errors.join(", ") });
|
||||
}
|
||||
|
||||
if (action === "create") {
|
||||
try {
|
||||
await PropertiesApi.create({
|
||||
entityId: entity.id,
|
||||
name,
|
||||
title,
|
||||
type,
|
||||
subtype,
|
||||
order,
|
||||
isDefault,
|
||||
isRequired,
|
||||
isHidden,
|
||||
isDisplay,
|
||||
isReadOnly,
|
||||
canUpdate,
|
||||
showInCreate,
|
||||
formulaId,
|
||||
options,
|
||||
attributes,
|
||||
tenantId,
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}`));
|
||||
} catch {
|
||||
return badRequest({ error: t("models.property.errors.createFailed") });
|
||||
}
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function NewEntityPropertyRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return <PropertyForm properties={data.properties} entities={appOrAdminData.entities} formulas={data.formulas} />;
|
||||
}
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
|
||||
type LoaderData = {
|
||||
allEntities: EntityWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await requireAuth({ request, params });
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (!appConfiguration.app.features.tenantEntityCustomization) {
|
||||
throw Error(t("settings.entities.errors.tenantEntityCustomizationNotEnabled"));
|
||||
}
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const allEntities = await getAllEntities({ tenantId, active: true, types: [DefaultEntityTypes.All, DefaultEntityTypes.AppOnly] });
|
||||
const data: LoaderData = {
|
||||
allEntities,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<EditPageLayout title={t("models.entity.plural")}>
|
||||
<div className="space-y-2">
|
||||
<TableSimple
|
||||
items={data.allEntities}
|
||||
actions={[
|
||||
{
|
||||
title: t("models.entity.templates"),
|
||||
onClickRoute: (_, item) => item.slug + "/templates",
|
||||
},
|
||||
{
|
||||
title: t("models.property.plural"),
|
||||
onClickRoute: (_, item) => item.slug,
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.entity.title"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<div className="flex items-center space-x-1">
|
||||
<Link to={item.slug} className="font-medium hover:underline">
|
||||
{t(item.titlePlural)}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "properties",
|
||||
title: t("models.property.plural"),
|
||||
className: "w-full text-xs",
|
||||
value: (item) => (
|
||||
<div className="max-w-xs truncate">
|
||||
{item.properties.filter((f) => !f.isDefault).length > 0 ? (
|
||||
<Link className="truncate pb-1 hover:underline" to={item.slug}>
|
||||
{item.properties
|
||||
.filter((f) => !f.isDefault)
|
||||
.map((f) => t(f.title) + (f.isRequired ? "*" : ""))
|
||||
.join(", ")}
|
||||
</Link>
|
||||
) : (
|
||||
<Link className="text-muted-foreground truncate pb-1 hover:underline" to={item.slug}>
|
||||
{t("shared.setCustomProperties")}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+79
-4
@@ -1,22 +1,35 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { LoaderFunctionArgs, MetaFunction, useFetcher, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Outlet } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import toast from "react-hot-toast";
|
||||
import { buildGroupsDetailVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getUserPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getAllGroups, getMyGroups, GroupWithDetails } from "~/utils/db/permissions/groups.db.server";
|
||||
import { getTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import GroupsListView from "~/modules/users/components/GroupsListView";
|
||||
import { GroupMembersDialog, type GroupMembersActions } from "~/components/screens/users/GroupMembersDialog";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import InfoBanner from "~/components/ui/banners/InfoBanner";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
|
||||
// R-P2b — groups bulk add/remove (interim UI per AD-28, David parked groups
|
||||
// for RBAC V2): the list gains a "manage members" row action opening the bulk
|
||||
// dialog, which posts bulk-add/bulk-remove to the existing groups/$id action.
|
||||
|
||||
type TenantUserRow = { userId: string; firstName: string | null; lastName: string | null; email: string };
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: GroupWithDetails[];
|
||||
tenantUsers: TenantUserRow[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
@@ -37,28 +50,90 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
items = await getMyGroups(userInfo.userId, tenantId);
|
||||
}
|
||||
|
||||
// Bulk-add candidates: active tenant members (minimal fields only).
|
||||
const tenantUsers = (await getTenantUsers(tenantId)).map((member) => ({
|
||||
userId: member.userId,
|
||||
firstName: member.user.firstName,
|
||||
lastName: member.user.lastName,
|
||||
email: member.user.email,
|
||||
}));
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.group.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
tenantUsers,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function RolesRoute() {
|
||||
type MutationResponse = { error?: string; success?: string };
|
||||
|
||||
export default function GroupsRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const rootData = useRootData();
|
||||
const appData = useAppData();
|
||||
const params = useParams();
|
||||
const { t } = useTranslation();
|
||||
const fetcher = useFetcher<MutationResponse>();
|
||||
const [openGroupId, setOpenGroupId] = useState<string | null>(null);
|
||||
const hadSubmission = useRef(false);
|
||||
|
||||
const canManage = getUserHasPermission(appData, "app.settings.groups.full");
|
||||
const submitting = fetcher.state !== "idle";
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.state !== "idle") {
|
||||
hadSubmission.current = true;
|
||||
return;
|
||||
}
|
||||
if (hadSubmission.current) {
|
||||
hadSubmission.current = false;
|
||||
if (fetcher.data?.error) toast.error(fetcher.data.error);
|
||||
else if (fetcher.data?.success) toast.success(fetcher.data.success);
|
||||
}
|
||||
}, [fetcher.state, fetcher.data]);
|
||||
|
||||
const openGroup = openGroupId ? (data.items.find((group) => group.id === openGroupId) ?? null) : null;
|
||||
const groupVM = openGroup
|
||||
? buildGroupsDetailVM({
|
||||
group: { id: openGroup.id, name: openGroup.name, description: openGroup.description },
|
||||
memberUsers: openGroup.users.map((entry) => ({
|
||||
userId: entry.user.id,
|
||||
firstName: entry.user.firstName,
|
||||
lastName: entry.user.lastName,
|
||||
email: entry.user.email,
|
||||
})),
|
||||
tenantUsers: data.tenantUsers,
|
||||
canManage,
|
||||
})
|
||||
: null;
|
||||
|
||||
function postBulk(intent: "bulk-add" | "bulk-remove", userIds: string[]) {
|
||||
if (!openGroupId) return;
|
||||
const formData = new FormData();
|
||||
if (rootData.csrf) formData.set("csrf", rootData.csrf);
|
||||
formData.set("action", intent);
|
||||
for (const userId of userIds) {
|
||||
formData.append("user-ids", userId);
|
||||
}
|
||||
fetcher.submit(formData, { method: "post", action: UrlUtils.currentTenantUrl(params, `settings/groups/${openGroupId}`) });
|
||||
}
|
||||
|
||||
const bulkActions: GroupMembersActions = {
|
||||
onAdd: (userIds) => postBulk("bulk-add", userIds),
|
||||
onRemove: (userIds) => postBulk("bulk-remove", userIds),
|
||||
};
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
{rootData.featureFlags?.includes("row-groups") ? (
|
||||
<GroupsListView items={data.items} canManage={getUserHasPermission(appData, "app.settings.groups.full")} />
|
||||
<GroupsListView items={data.items} canManage={canManage} onManageMembers={canManage ? setOpenGroupId : undefined} />
|
||||
) : (
|
||||
<InfoBanner title={t("settings.groups.disabled.title")} text={t("settings.groups.disabled.description")} />
|
||||
)}
|
||||
{groupVM ? <GroupMembersDialog vm={groupVM} actions={bulkActions} submitting={submitting} onClose={() => setOpenGroupId(null)} /> : null}
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
);
|
||||
|
||||
+17
-1
@@ -7,7 +7,7 @@ import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { createLog } from "~/utils/db/logs.db.server";
|
||||
import { deleteGroup, getGroup, GroupWithDetails, updateGroup } from "~/utils/db/permissions/groups.db.server";
|
||||
import { addUsersToGroup, deleteGroup, getGroup, GroupWithDetails, removeUsersFromGroup, updateGroup } from "~/utils/db/permissions/groups.db.server";
|
||||
import { replaceGroupUsers } from "~/utils/db/permissions/userGroups.db.server";
|
||||
import { getTenantUsers, TenantUserWithUser } from "~/utils/db/tenants.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
@@ -96,6 +96,22 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
users.map((user) => user.id)
|
||||
);
|
||||
await createLog(request, tenantId, "settings.groups.updated", `${existing.name}: ${JSON.stringify({ ...data, users: users.map((f) => f.email) })}`);
|
||||
} else if (action === "bulk-add" || action === "bulk-remove") {
|
||||
// R-P2b — bulk member ops for the interim group members dialog (AD-28).
|
||||
// Only tenant members are accepted; the ops themselves are idempotent.
|
||||
const userIds = form.getAll("user-ids").map((value) => value.toString());
|
||||
const tenantUserIds = new Set((await getTenantUsers(tenantId)).map((tenantUser) => tenantUser.userId));
|
||||
if (userIds.length === 0 || !userIds.every((userId) => tenantUserIds.has(userId))) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
if (action === "bulk-add") {
|
||||
await addUsersToGroup(existing.id, userIds);
|
||||
await createLog(request, tenantId, "settings.groups.membersAdded", `${existing.name}: +${userIds.length}`);
|
||||
return Response.json({ success: t("settings.members.groups.bulk.added", { count: userIds.length }) });
|
||||
}
|
||||
await removeUsersFromGroup(existing.id, userIds);
|
||||
await createLog(request, tenantId, "settings.groups.membersRemoved", `${existing.name}: -${userIds.length}`);
|
||||
return Response.json({ success: t("settings.members.groups.bulk.removed", { count: userIds.length }) });
|
||||
} else if (action === "delete") {
|
||||
const deleted = await deleteGroup(existing.id, tenantId);
|
||||
if ("count" in deleted && deleted.count !== 1) {
|
||||
|
||||
+2
-2
@@ -74,7 +74,7 @@ function callLoader(url: string) {
|
||||
describe("tenant settings event list route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({
|
||||
@@ -115,7 +115,7 @@ describe("tenant settings event list route", () => {
|
||||
"tenant-1",
|
||||
);
|
||||
expect(data).toMatchObject({
|
||||
title: "translated:models.event.plural | ToolCTRL",
|
||||
title: "translated:models.event.plural | HiveGrid",
|
||||
items: events,
|
||||
pagination: { page: 2, pageSize: 25, totalItems: 1, totalPages: 1 },
|
||||
});
|
||||
|
||||
+5
-5
@@ -2,7 +2,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./index";
|
||||
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@toolctrl/db/logs.server";
|
||||
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
@@ -39,7 +39,7 @@ vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@toolctrl/db/logs.server", () => ({
|
||||
vi.mock("@hivegrid/db/logs.server", () => ({
|
||||
getTenantAuditLogList: vi.fn(),
|
||||
serializeAdminAuditLogsCsv: vi.fn(),
|
||||
}));
|
||||
@@ -76,7 +76,7 @@ function readTenantLogsRoute() {
|
||||
describe("tenant settings logs route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
@@ -104,7 +104,7 @@ describe("tenant settings logs route", () => {
|
||||
});
|
||||
expect(JSON.stringify(vi.mocked(getTenantAuditLogList).mock.calls[0]?.[1])).not.toContain("other-tenant");
|
||||
expect(data).toMatchObject({
|
||||
title: "translated:models.log.plural | ToolCTRL",
|
||||
title: "translated:models.log.plural | HiveGrid",
|
||||
items: auditRows,
|
||||
pagination: { page: 2, pageSize: 25, totalItems: 1, totalPages: 1 },
|
||||
});
|
||||
@@ -165,7 +165,7 @@ describe("tenant settings logs route", () => {
|
||||
it("uses the package audit-log boundary instead of the legacy app DB helper", () => {
|
||||
const source = readTenantLogsRoute();
|
||||
|
||||
expect(source).toContain('from "@toolctrl/db/logs.server"');
|
||||
expect(source).toContain('from "@hivegrid/db/logs.server"');
|
||||
expect(source).toContain("getTenantAuditLogList");
|
||||
expect(source).toContain("serializeAdminAuditLogsCsv");
|
||||
expect(source).toContain("TenantActivityLogToolbar");
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
import type { AdminAuditLogFilters, AdminAuditLogRow } from "@toolctrl/db/logs.server";
|
||||
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@toolctrl/db/logs.server";
|
||||
import type { AdminAuditLogFilters, AdminAuditLogRow } from "@hivegrid/db/logs.server";
|
||||
import { getTenantAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
+113
-82
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
@@ -12,43 +12,31 @@ vi.mock("react-router", async () => {
|
||||
useActionData: () => undefined,
|
||||
useLoaderData: () => ({}),
|
||||
useNavigate: () => vi.fn(),
|
||||
useNavigation: () => ({ state: "idle" }),
|
||||
useOutlet: () => null,
|
||||
useParams: () => ({}),
|
||||
useSubmit: () => vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("~/components/core/roles/GroupsTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/roles/RoleBadge", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/roles/RolesAndPermissionsMatrix", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/roles/UserRolesTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/settings/members/MemberInvitationsListAndTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputSearch", () => ({ default: () => null }));
|
||||
vi.mock("react-hot-toast", () => ({ default: { success: vi.fn(), error: vi.fn() } }));
|
||||
vi.mock("~/components/screens/users/MembersPage", () => ({ MembersPage: () => null }));
|
||||
vi.mock("~/ui/components/Dialog", () => ({ Dialog: Object.assign(() => null, { Content: () => null }) }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/ActionResultModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/ConfirmModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/ErrorModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/Modal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/sections/SettingSection", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/tables/TableSimple", () => ({ default: () => null }));
|
||||
vi.mock("~/utils/app/UrlUtils", () => ({ default: { currentTenantUrl: vi.fn(() => "/acme/settings/subscription") } }));
|
||||
vi.mock("~/utils/data/useAppData", () => ({ useAppData: () => ({}) }));
|
||||
vi.mock("~/utils/app/UrlUtils", () => ({ default: { currentTenantUrl: vi.fn(() => "/acme/settings/members") } }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({}) }));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ createAdminLog: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/groups.db.server", () => ({ getAllGroups: vi.fn(), getMyGroups: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/permissions.db.server", () => ({ getAllPermissions: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRoles: vi.fn(), getTenantAssignableAppRole: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getTenantAssignableAppRole: vi.fn(), getTenantAssignableAppRoles: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ createUserRole: vi.fn(), deleteUserRole: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenantUserInvitations.db.server", () => ({ deleteUserInvitation: vi.fn(), getUserInvitation: vi.fn(), getUserInvitations: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: vi.fn(), getTenantMember: vi.fn(), getTenantUsers: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ getUserPermission: vi.fn(), verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn() }));
|
||||
vi.mock("~/utils/services/tenantUserLifecycle.server", () => ({ deactivateTenantUser: vi.fn(), reactivateTenantUser: vi.fn() }));
|
||||
vi.mock("~/utils/auth/mfa/enforcement.server", () => ({ enforceAdminMfa: vi.fn() }));
|
||||
vi.mock("~/utils/auth/mfa/step-up.server", () => ({ checkMfaStepUpState: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn(), getUserTotpStatus: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn(), getUserTotpStatus: vi.fn(), getEnabledTotpUserIds: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
createImpersonationStartedAt: vi.fn(() => "2026-05-08T17:00:00.000Z"),
|
||||
createUserSession: vi.fn(),
|
||||
@@ -57,7 +45,7 @@ vi.mock("~/utils/session.server", () => ({
|
||||
setLoggedUser: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({
|
||||
routing: {
|
||||
protocol: "https",
|
||||
@@ -71,15 +59,14 @@ vi.mock("@toolctrl/config", () => ({
|
||||
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { getAllRoles, getTenantAssignableAppRole } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getAllGroups, getMyGroups } from "~/utils/db/permissions/groups.db.server";
|
||||
import { getAllPermissions } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { getTenantAssignableAppRole, getTenantAssignableAppRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { createUserRole } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { deleteUserInvitation, getUserInvitation, getUserInvitations } from "~/utils/db/tenantUserInvitations.db.server";
|
||||
import { getTenant, getTenantMember, getTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
import { getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
|
||||
import { getEnabledTotpUserIds, getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
|
||||
import { getUserPermission, verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { deactivateTenantUser, reactivateTenantUser } from "~/utils/services/tenantUserLifecycle.server";
|
||||
import { createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { action, loader } from "./members";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
@@ -122,7 +109,7 @@ async function callLoader() {
|
||||
request: new Request("https://app.example.test/acme/settings/members"),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
});
|
||||
} as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("workspace members impersonation MFA guard", () => {
|
||||
@@ -233,7 +220,7 @@ describe("workspace members impersonation MFA guard", () => {
|
||||
await expect(result.response.json()).resolves.toEqual({ success: "settings.members.success.invitationDeleted" });
|
||||
});
|
||||
|
||||
it("localizes the last-super-admin removal guard response", async () => {
|
||||
it("localizes the last-super-admin removal guard response with the V01 code", async () => {
|
||||
vi.mocked(getTenantMember).mockResolvedValue({ user: targetUser } as never);
|
||||
vi.mocked(getTenantAssignableAppRole).mockResolvedValue({ id: "role-super", name: "SuperUser", description: "Super User", type: "app" } as never);
|
||||
vi.mocked(getTenantUsers).mockResolvedValue([
|
||||
@@ -247,7 +234,7 @@ describe("workspace members impersonation MFA guard", () => {
|
||||
|
||||
expect(result.thrown).toBe(false);
|
||||
expect(result.response.status).toBe(400);
|
||||
await expect(result.response.json()).resolves.toEqual({ error: "settings.members.errors.atLeastOneSuperAdmin" });
|
||||
await expect(result.response.json()).resolves.toEqual({ error: "settings.members.errors.atLeastOneSuperAdmin", code: "last-admin" });
|
||||
});
|
||||
|
||||
it("localizes the own super-admin role removal guard response", async () => {
|
||||
@@ -284,67 +271,111 @@ describe("workspace members impersonation MFA guard", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace members loader", () => {
|
||||
describe("workspace member lifecycle intents (R-P2b M03/V01)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1" as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue(actorInfo as never);
|
||||
vi.mocked(getUser).mockResolvedValue(actor as never);
|
||||
vi.mocked(getTenant).mockResolvedValue({ id: "tenant-1", name: "Acme", slug: "acme" } as never);
|
||||
vi.mocked(getTenantMember).mockResolvedValue({ user: targetUser } as never);
|
||||
});
|
||||
|
||||
it("deactivates a member through the lifecycle service without reassign", async () => {
|
||||
vi.mocked(deactivateTenantUser).mockResolvedValue({ ok: true } as never);
|
||||
|
||||
const result = await callAction({ action: "deactivate", "user-id": targetUser.id });
|
||||
|
||||
expect(result.thrown).toBe(false);
|
||||
expect(deactivateTenantUser).toHaveBeenCalledWith({ tenantId: "tenant-1", targetUserId: targetUser.id });
|
||||
await expect(result.response.json()).resolves.toEqual({ success: "settings.members.success.deactivated" });
|
||||
});
|
||||
|
||||
it("maps the last-admin guard to the V01 blocker code", async () => {
|
||||
vi.mocked(deactivateTenantUser).mockResolvedValue({ ok: false, reason: "last-admin" } as never);
|
||||
|
||||
const result = await callAction({ action: "deactivate", "user-id": targetUser.id });
|
||||
|
||||
expect(result.thrown).toBe(false);
|
||||
expect(result.response.status).toBe(400);
|
||||
await expect(result.response.json()).resolves.toEqual({ error: "settings.members.errors.lastAdminBody", code: "last-admin" });
|
||||
});
|
||||
|
||||
it("rejects other deactivation failures with a plain error", async () => {
|
||||
vi.mocked(deactivateTenantUser).mockResolvedValue({ ok: false, reason: "already-inactive" } as never);
|
||||
|
||||
const result = await callAction({ action: "deactivate", "user-id": targetUser.id });
|
||||
|
||||
expect(result.response.status).toBe(400);
|
||||
await expect(result.response.json()).resolves.toEqual({ error: "shared.invalidForm" });
|
||||
});
|
||||
|
||||
it("reactivates a member through the lifecycle service", async () => {
|
||||
vi.mocked(reactivateTenantUser).mockResolvedValue({ ok: true } as never);
|
||||
|
||||
const result = await callAction({ action: "reactivate", "user-id": targetUser.id });
|
||||
|
||||
expect(result.thrown).toBe(false);
|
||||
expect(reactivateTenantUser).toHaveBeenCalledWith({ tenantId: "tenant-1", targetUserId: targetUser.id });
|
||||
await expect(result.response.json()).resolves.toEqual({ success: "settings.members.success.reactivated" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace members loader (MembersListVM)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant-1" as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue(actorInfo as never);
|
||||
vi.mocked(getTenantUsers).mockResolvedValue([{ id: "member-1", user: { id: "user-1" } }] as never);
|
||||
vi.mocked(getUserInvitations).mockResolvedValue([{ id: "invite-1" }] as never);
|
||||
vi.mocked(getAllRoles).mockResolvedValue([{ id: "role-1" }] as never);
|
||||
vi.mocked(getAllPermissions).mockResolvedValue([{ name: "app.settings.members.view" }] as never);
|
||||
vi.mocked(getUserPermission).mockResolvedValue({ permission: null, userPermission: null } as never);
|
||||
vi.mocked(getAllGroups).mockResolvedValue([{ id: "group-1" }] as never);
|
||||
vi.mocked(getMyGroups).mockResolvedValue([{ id: "my-group-1" }] as never);
|
||||
vi.mocked(getEnabledTotpUserIds).mockResolvedValue(["user-1"] as never);
|
||||
vi.mocked(getUserInvitations).mockResolvedValue([{ id: "invite-1", email: "new@example.test", firstName: "New", lastName: "Person" }] as never);
|
||||
// The helper already scopes to assignable defaults + the tenant's own roles.
|
||||
vi.mocked(getTenantAssignableAppRoles).mockResolvedValue([
|
||||
{ id: "role-1", name: "SuperUser", description: "", tenantId: null },
|
||||
{ id: "role-shk", name: "Monteur", description: "", tenantId: "tenant-1" },
|
||||
] as never);
|
||||
vi.mocked(getTenantUsers).mockResolvedValue([
|
||||
{
|
||||
id: "member-1",
|
||||
userId: "user-1",
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
user: {
|
||||
id: "user-1",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
email: "ada@example.test",
|
||||
phone: "+49 1",
|
||||
roles: [{ tenantId: "tenant-1", role: { id: "role-1", name: "SuperUser", description: "" } }],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "member-2",
|
||||
userId: "user-2",
|
||||
status: TenantUserStatus.INACTIVE,
|
||||
user: { id: "user-2", firstName: "Grace", lastName: "Hopper", email: "grace@example.test", phone: null, roles: [] },
|
||||
},
|
||||
] as never);
|
||||
});
|
||||
|
||||
it("loads independent members settings data in parallel before resolving groups", async () => {
|
||||
const started: string[] = [];
|
||||
vi.mocked(getTenantUsers).mockImplementation(async () => {
|
||||
started.push("users");
|
||||
return [{ id: "member-1", user: { id: "user-1" } }] as never;
|
||||
});
|
||||
vi.mocked(getUserInvitations).mockImplementation(async () => {
|
||||
started.push("invitations");
|
||||
return [{ id: "invite-1" }] as never;
|
||||
});
|
||||
vi.mocked(getAllRoles).mockImplementation(async () => {
|
||||
started.push("roles");
|
||||
return [{ id: "role-1" }] as never;
|
||||
});
|
||||
vi.mocked(getAllPermissions).mockImplementation(async () => {
|
||||
started.push("permissions");
|
||||
return [{ name: "app.settings.members.view" }] as never;
|
||||
});
|
||||
vi.mocked(getUserPermission).mockImplementation(async () => {
|
||||
started.push("group-access");
|
||||
return { permission: null, userPermission: null } as never;
|
||||
});
|
||||
it("builds the VM including deactivated members and the tenant's assignable roles", async () => {
|
||||
const data = (await callLoader()) as { vm: { status: string; data?: any }; canViewRoles: boolean };
|
||||
|
||||
const data = await callLoader();
|
||||
|
||||
expect(started).toEqual(["users", "invitations", "roles", "permissions", "group-access"]);
|
||||
expect(getAllGroups).toHaveBeenCalledWith("tenant-1");
|
||||
expect(getMyGroups).not.toHaveBeenCalled();
|
||||
expect(data).toEqual(
|
||||
expect.objectContaining({
|
||||
users: [{ id: "member-1", user: { id: "user-1" } }],
|
||||
pendingInvitations: [{ id: "invite-1" }],
|
||||
roles: [{ id: "role-1" }],
|
||||
permissions: [{ name: "app.settings.members.view" }],
|
||||
groups: [{ id: "group-1" }],
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("loads only my groups when the current user lacks full group access", async () => {
|
||||
vi.mocked(getUserPermission).mockResolvedValue({ permission: { name: "app.settings.groups.full" }, userPermission: null } as never);
|
||||
|
||||
const data = await callLoader();
|
||||
|
||||
expect(getAllGroups).not.toHaveBeenCalled();
|
||||
expect(getMyGroups).toHaveBeenCalledWith(actor.id, "tenant-1");
|
||||
expect(data).toEqual(expect.objectContaining({ groups: [{ id: "my-group-1" }] }));
|
||||
expect(getTenantUsers).toHaveBeenCalledWith("tenant-1", { includeInactive: true });
|
||||
expect(getTenantAssignableAppRoles).toHaveBeenCalledWith("tenant-1");
|
||||
expect(data.vm.status).toBe("ready");
|
||||
const rows = data.vm.data.rows;
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]).toMatchObject({ name: "Ada Lovelace", status: "active", mfaEnabled: true, roles: [{ id: "role-1" }] });
|
||||
expect(rows[1]).toMatchObject({ name: "Grace Hopper", status: "inactive", mfaEnabled: false, canReactivate: true });
|
||||
// Defaults AND the tenant's own custom/SHK roles feed the D01 dropdown.
|
||||
expect(data.vm.data.assignableRoles).toEqual([
|
||||
{ id: "role-1", name: "SuperUser", description: "" },
|
||||
{ id: "role-shk", name: "Monteur", description: "" },
|
||||
]);
|
||||
expect(data.vm.data.pendingInvitations).toEqual([{ id: "invite-1", email: "new@example.test", name: "New Person", createdAtIso: null }]);
|
||||
expect(data.canViewRoles).toBe(true);
|
||||
});
|
||||
});
|
||||
+135
-216
@@ -1,40 +1,25 @@
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import { Fragment, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { getTenant, getTenantMember, getTenantUsers, TenantUserWithUser } from "~/utils/db/tenants.db.server";
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { useNavigate, useNavigation, useOutlet, useParams, useSubmit } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import toast from "react-hot-toast";
|
||||
import { buildMembersListVM, type MembersListVM, type MemberStatus } from "@hivegrid/view-models";
|
||||
import { getTenant, getTenantMember, getTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
import { deleteUserInvitation, getUserInvitation, getUserInvitations } from "~/utils/db/tenantUserInvitations.db.server";
|
||||
import MemberInvitationsListAndTable from "~/components/core/settings/members/MemberInvitationsListAndTable";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { getUserPermission, verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { RoleWithPermissions, getAllRoles, getTenantAssignableAppRole } from "~/utils/db/permissions/roles.db.server";
|
||||
import { Permission } from "@toolctrl/db/prisma-browser";
|
||||
import { getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTenantAssignableAppRole, getTenantAssignableAppRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getEnabledTotpUserIds, getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { createUserRole, deleteUserRole } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { createImpersonationStartedAt, createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import MembersListView from "~/modules/users/components/MembersListView";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import RoleBadge from "~/components/core/roles/RoleBadge";
|
||||
import { permissionDisplayDescription, permissionDisplayName, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import RolesAndPermissionsMatrix from "~/components/core/roles/RolesAndPermissionsMatrix";
|
||||
import { getAllPermissions } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { GroupWithDetails, getAllGroups, getMyGroups } from "~/utils/db/permissions/groups.db.server";
|
||||
import GroupsTable from "~/components/core/roles/GroupsTable";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { deactivateTenantUser, reactivateTenantUser } from "~/utils/services/tenantUserLifecycle.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { MembersPage, type MembersActions } from "~/components/screens/users/MembersPage";
|
||||
import { Dialog } from "~/ui/components/Dialog";
|
||||
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { RoleAssignedDto } from "~/modules/events/dtos/RoleAssignedDto";
|
||||
@@ -42,57 +27,77 @@ import { RoleUnassignedDto } from "~/modules/events/dtos/RoleUnassignedDto";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAdminPath, absoluteAppPath } from "~/utils/app/CrossHostUrls";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
users: TenantUserWithUser[];
|
||||
mfaEnabledUserIds: string[];
|
||||
pendingInvitations: Awaited<ReturnType<typeof getUserInvitations>>;
|
||||
roles: RoleWithPermissions[];
|
||||
permissions: Permission[];
|
||||
groups: GroupWithDetails[];
|
||||
vm: MembersListVM;
|
||||
canViewRoles: boolean;
|
||||
};
|
||||
|
||||
function toMemberStatus(status: TenantUserStatus): MemberStatus {
|
||||
if (status === TenantUserStatus.ACTIVE) return "active";
|
||||
if (status === TenantUserStatus.INACTIVE) return "inactive";
|
||||
return "invited";
|
||||
}
|
||||
|
||||
async function hasPermission(userId: string, permissionName: string, tenantId: string): Promise<boolean> {
|
||||
const { permission, userPermission } = await getUserPermission({ userId, permissionName, tenantId });
|
||||
return !permission || Boolean(userPermission);
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const userInfo = await getUserInfo(request);
|
||||
await verifyUserHasPermission(request, "app.settings.members.view", tenantId);
|
||||
|
||||
const [users, pendingInvitations, roles, permissions, groupAccess] = await Promise.all([
|
||||
getTenantUsers(tenantId),
|
||||
// Deactivated members stay visible with status "Deaktiviert" (David's S01/M03).
|
||||
const [users, pendingInvitations, roles, canInvite, canEditRoles, canManageMembers, canViewRoles] = await Promise.all([
|
||||
getTenantUsers(tenantId, { includeInactive: true }),
|
||||
getUserInvitations(tenantId),
|
||||
getAllRoles("app"),
|
||||
getAllPermissions("app"),
|
||||
getUserPermission({
|
||||
userId: userInfo.userId,
|
||||
permissionName: "app.settings.groups.full",
|
||||
tenantId: tenantId,
|
||||
}),
|
||||
// Assignable defaults + the tenant's own custom/SHK roles (D01 dropdown).
|
||||
getTenantAssignableAppRoles(tenantId),
|
||||
hasPermission(userInfo.userId, "app.settings.members.create", tenantId),
|
||||
hasPermission(userInfo.userId, "app.settings.roles.set", tenantId),
|
||||
hasPermission(userInfo.userId, "app.settings.members.update", tenantId),
|
||||
hasPermission(userInfo.userId, "app.settings.roles.view", tenantId),
|
||||
]);
|
||||
const { permission, userPermission } = groupAccess;
|
||||
let groups: GroupWithDetails[];
|
||||
if (!permission || userPermission) {
|
||||
groups = await getAllGroups(tenantId);
|
||||
} else {
|
||||
groups = await getMyGroups(userInfo.userId, tenantId);
|
||||
}
|
||||
const mfaEnabledUserIds = new Set(await getEnabledTotpUserIds(users.map((member) => member.user.id)));
|
||||
|
||||
const mfaEnabledUserIds = (
|
||||
await Promise.all(users.map(async (member) => ((await getUserTotpStatus(member.user.id))?.enabled ? member.user.id : null)))
|
||||
).filter((id): id is string => id !== null);
|
||||
const vm = buildMembersListVM({
|
||||
rows: users.map((member) => ({
|
||||
tenantUserId: member.id,
|
||||
userId: member.userId,
|
||||
firstName: member.user.firstName,
|
||||
lastName: member.user.lastName,
|
||||
email: member.user.email,
|
||||
phone: member.user.phone,
|
||||
status: toMemberStatus(member.status),
|
||||
mfaEnabled: mfaEnabledUserIds.has(member.user.id),
|
||||
roles: member.user.roles
|
||||
.filter((userRole) => userRole.tenantId === tenantId)
|
||||
.map((userRole) => ({ id: userRole.role.id, name: userRole.role.name, description: userRole.role.description })),
|
||||
})),
|
||||
pendingInvitations: pendingInvitations.map((invitation) => ({
|
||||
id: invitation.id,
|
||||
email: invitation.email,
|
||||
name: [invitation.firstName, invitation.lastName].filter(Boolean).join(" "),
|
||||
createdAtIso: null,
|
||||
})),
|
||||
assignableRoles: roles.map((role) => ({ id: role.id, name: role.name, description: role.description })),
|
||||
currentUserId: userInfo.userId,
|
||||
canInvite,
|
||||
canEditRoles,
|
||||
canManageMembers,
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.members.title")} | ${process.env.APP_NAME}`,
|
||||
users,
|
||||
mfaEnabledUserIds,
|
||||
pendingInvitations,
|
||||
roles,
|
||||
permissions,
|
||||
groups,
|
||||
vm,
|
||||
canViewRoles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
@@ -100,6 +105,8 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
/** Machine-readable guard code — "last-admin" opens the V01 blocker dialog. */
|
||||
code?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
@@ -127,6 +134,33 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
await deleteUserInvitation(invitation.id, tenantId);
|
||||
return Response.json({ success: t("settings.members.success.invitationDeleted") });
|
||||
}
|
||||
if (action === "deactivate" || action === "reactivate") {
|
||||
// R-P2b user lifecycle (M03/V01): soft-deactivation via the lifecycle service.
|
||||
// Reassign-on-deactivate stays Backlog/V2 (David) — the service keeps the option.
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
const tenant = await getTenant(tenantId);
|
||||
const tenantMember = await getTenantMember(userId, tenantId);
|
||||
if (!tenant || !tenantMember) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
if (action === "deactivate") {
|
||||
const result = await deactivateTenantUser({ tenantId, targetUserId: userId });
|
||||
if (!result.ok) {
|
||||
if (result.reason === "last-admin") {
|
||||
return badRequest({ error: t("settings.members.errors.lastAdminBody"), code: "last-admin" });
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
createAdminLog(request, "settings.members.deactivated", `[${tenant.name}] ${tenantMember.user.email}`);
|
||||
return Response.json({ success: t("settings.members.success.deactivated") });
|
||||
}
|
||||
const result = await reactivateTenantUser({ tenantId, targetUserId: userId });
|
||||
if (!result.ok) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
createAdminLog(request, "settings.members.reactivated", `[${tenant.name}] ${tenantMember.user.email}`);
|
||||
return Response.json({ success: t("settings.members.success.reactivated") });
|
||||
}
|
||||
if (action === "edit") {
|
||||
await verifyUserHasPermission(request, "app.settings.roles.set", tenantId);
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
@@ -147,8 +181,10 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
const activeMembers = allMembers.filter((member) => member.status === TenantUserStatus.ACTIVE);
|
||||
const superAdmins = activeMembers.filter((m) => m.user.roles.some((r) => r.tenantId === tenantId && r.role.name === DefaultAppRoles.SuperUser));
|
||||
if (superAdmins.length === 1 && !add) {
|
||||
// Same guard family as deactivation: the workspace must keep an admin (V01).
|
||||
return badRequest({
|
||||
error: t("settings.members.errors.atLeastOneSuperAdmin"),
|
||||
code: "last-admin",
|
||||
});
|
||||
}
|
||||
if (userId === userInfo.userId) {
|
||||
@@ -239,184 +275,67 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
export default function MembersSettingsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
const appData = useAppData();
|
||||
const navigate = useNavigate();
|
||||
const navigation = useNavigation();
|
||||
const outlet = useOutlet();
|
||||
const submit = useSubmit();
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
const confirmUpgrade = useRef<RefConfirmModal>(null);
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
const [permissionsModalOpen, setPermissionsModalOpen] = useState(false);
|
||||
const [selectedRole, setSelectedRole] = useState<RoleWithPermissions>();
|
||||
const [showRolesAndPermissions, setShowRolesAndPermissions] = useState(false);
|
||||
const formatPermissionCount = (count: number | undefined) => {
|
||||
const value = count ?? 0;
|
||||
return t("models.permission.count", { count: value, formattedCount: formatters.number(value) });
|
||||
};
|
||||
const submitting = navigation.state === "submitting";
|
||||
const lastAdminBlocked = actionData?.code === "last-admin";
|
||||
|
||||
useEffect(() => {
|
||||
setPermissionsModalOpen(selectedRole !== undefined);
|
||||
}, [selectedRole]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!permissionsModalOpen) {
|
||||
setSelectedRole(undefined);
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error && actionData.code !== "last-admin") {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [permissionsModalOpen]);
|
||||
}, [actionData]);
|
||||
|
||||
function yesUpdateSubscription() {
|
||||
navigate(UrlUtils.currentTenantUrl(params, `settings/subscription`));
|
||||
function post(fields: Record<string, string>) {
|
||||
const formData = new FormData();
|
||||
if (rootData.csrf) formData.set("csrf", rootData.csrf);
|
||||
for (const [name, value] of Object.entries(fields)) {
|
||||
formData.set(name, value);
|
||||
}
|
||||
submit(formData, { method: "post" });
|
||||
}
|
||||
const sortedItems = useMemo(() => {
|
||||
if (!data.users) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const normalizedSearch = searchInput.toUpperCase();
|
||||
return data.users
|
||||
.filter(
|
||||
(f) =>
|
||||
f.user.firstName?.toString().toUpperCase().includes(normalizedSearch) ||
|
||||
f.user.lastName?.toString().toUpperCase().includes(normalizedSearch) ||
|
||||
f.user.email?.toString().toUpperCase().includes(normalizedSearch) ||
|
||||
f.user.phone?.toString().toUpperCase().includes(normalizedSearch)
|
||||
)
|
||||
.slice()
|
||||
.sort((x, y) => {
|
||||
return x.type > y.type ? 1 : -1;
|
||||
});
|
||||
}, [data.users, searchInput]);
|
||||
|
||||
const actions: MembersActions = {
|
||||
onToggleRole: ({ userId, roleId, add }) => post({ action: "edit", "user-id": userId, "role-id": roleId, add: String(add) }),
|
||||
onDeactivate: ({ userId }) => post({ action: "deactivate", "user-id": userId }),
|
||||
onReactivate: ({ userId }) => post({ action: "reactivate", "user-id": userId }),
|
||||
onDeleteInvitation: ({ invitationId }) => post({ action: "delete-invitation", "invitation-id": invitationId }),
|
||||
onInvite: () => navigate(UrlUtils.currentTenantUrl(params, "settings/members/new")),
|
||||
};
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
<div data-ui-id="ui.settings.members.page" className="contents">
|
||||
<SettingSection
|
||||
size="lg"
|
||||
title={t("settings.members.title")}
|
||||
description={
|
||||
<div className="flex flex-col space-y-1">
|
||||
<div>{t("settings.members.description")}</div>
|
||||
<div>
|
||||
<button type="button" className="text-left underline" onClick={() => setShowRolesAndPermissions(true)}>
|
||||
{t("settings.members.viewRolesAndPermissions")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
className="p-1"
|
||||
>
|
||||
<div className="grid grid-cols-1 space-y-2">
|
||||
<div data-ui-id="ui.settings.members.search">
|
||||
<InputSearch
|
||||
value={searchInput}
|
||||
setValue={setSearchInput}
|
||||
onNewRoute={!getUserHasPermission(appData, "app.settings.members.create") ? "" : UrlUtils.currentTenantUrl(params, "settings/members/new")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div data-ui-id="ui.settings.members.table">
|
||||
<MembersListView
|
||||
items={sortedItems}
|
||||
mfaEnabledUserIds={data.mfaEnabledUserIds}
|
||||
tenantId={appData.currentTenant.id}
|
||||
canEdit={getUserHasPermission(appData, "app.settings.roles.set")}
|
||||
editRouteFor={(tenantUserId) => UrlUtils.currentTenantUrl(params, `settings/members/edit/${tenantUserId}`)}
|
||||
rolesUrl={UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/users")}
|
||||
/>
|
||||
</div>
|
||||
<MembersPage
|
||||
vm={data.vm}
|
||||
actions={actions}
|
||||
rolesTabHref={data.canViewRoles ? UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/roles") : null}
|
||||
editRouteFor={(tenantUserId) => UrlUtils.currentTenantUrl(params, `settings/members/edit/${tenantUserId}`)}
|
||||
submitting={submitting}
|
||||
lastAdminBlocked={lastAdminBlocked}
|
||||
/>
|
||||
|
||||
<Modal open={permissionsModalOpen} setOpen={setPermissionsModalOpen}>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-baseline justify-between space-x-2">
|
||||
<h4 className="text-lg font-bold">{selectedRole ? roleDisplayName(selectedRole, t) : undefined}</h4>
|
||||
<p className="text-muted-foreground text-sm">{formatPermissionCount(selectedRole?.permissions.length)}</p>
|
||||
</div>
|
||||
<div className="h-96 max-h-96 overflow-y-scroll p-1">
|
||||
<TableSimple
|
||||
headers={[
|
||||
{
|
||||
name: "name",
|
||||
title: t("models.permission.name"),
|
||||
value: (i) => permissionDisplayName(i.permission, t),
|
||||
formattedValue: (i) => <RoleBadge item={i.permission} kind="permission" />,
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("models.permission.description"),
|
||||
value: (i) => permissionDisplayDescription(i.permission, t) ?? "",
|
||||
},
|
||||
]}
|
||||
items={selectedRole?.permissions ?? []}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<Modal size="4xl" open={showRolesAndPermissions} setOpen={setShowRolesAndPermissions}>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-baseline justify-between space-x-2">
|
||||
<h4 className="text-lg font-bold">{t("app.sidebar.rolesAndPermissions")}</h4>
|
||||
<p className="text-muted-foreground text-sm">{formatPermissionCount(data.permissions.length)}</p>
|
||||
</div>
|
||||
<div className="p-1">
|
||||
<RolesAndPermissionsMatrix roles={data.roles} permissions={data.permissions} className="h-96 max-h-96 overflow-y-scroll" />
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{data.pendingInvitations.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<label className="text-foreground/80 block text-sm font-medium">{t("settings.members.pendingInvitations")}</label>
|
||||
<MemberInvitationsListAndTable items={data.pendingInvitations} canDelete={getUserHasPermission(appData, "app.settings.members.delete")} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{rootData.featureFlags?.includes("row-groups") && (
|
||||
<Fragment>
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>{" "}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection size="lg" title={t("settings.members.groups.title")} description={t("settings.members.groups.description")} className="p-1">
|
||||
<GroupsTable items={data.groups} onNewRoute="groups/new" />
|
||||
</SettingSection>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("settings.members.form.editTitle") : t("settings.members.form.newTitle")}
|
||||
{/* Child routes (M01 invite, member edit, group forms) render in a real Dialog (S 560). */}
|
||||
<Dialog
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
onOpenChange={(open: boolean) => {
|
||||
if (!open) 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>
|
||||
|
||||
<ActionResultModal actionData={actionData} showSuccess={false} />
|
||||
<ErrorModal ref={errorModal} />
|
||||
<ConfirmModal ref={confirmUpgrade} onYes={yesUpdateSubscription} />
|
||||
</div>
|
||||
<Dialog.Content className="w-[560px] max-w-[90vw] p-6" aria-label={t("settings.members.form.newTitle")}>
|
||||
<div className="w-full">{outlet}</div>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+1
-1
@@ -5,7 +5,7 @@ import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmMod
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessModal";
|
||||
import { useEscapeKeypress } from "~/utils/shared/KeypressUtils";
|
||||
import type { TenantUser, User } from "@toolctrl/db/prisma-browser";
|
||||
import type { TenantUser, User } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { Form, useActionData, useParams, useSubmit, useNavigation, useNavigate } from "react-router";
|
||||
import { deleteTenantUser, getTenantUser, getTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
|
||||
+17
-7
@@ -1,12 +1,14 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, MetaFunction, useLoaderData } from "react-router";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, MetaFunction, useLoaderData, useNavigate, useParams } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant, getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { getUser, getUserByEmail } from "~/utils/db/users.db.server";
|
||||
import { createWorkspaceInvite, WorkspaceInviteError } from "@toolctrl/db/workspace-invites.server";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@toolctrl/db/outbox";
|
||||
import type { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import NewMember from "~/components/core/settings/members/NewMember";
|
||||
import { createWorkspaceInvite, WorkspaceInviteError } from "@hivegrid/db/workspace-invites.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import CheckPlanFeatureLimit from "~/components/core/settings/subscription/CheckPlanFeatureLimit";
|
||||
import { InviteMemberForm } from "~/components/screens/users/InviteMemberForm";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
|
||||
import { getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
|
||||
@@ -159,8 +161,16 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function NewMemberRoute() {
|
||||
// D-P2 M01 "Mitarbeiter einladen": David-style form, rendered inside the
|
||||
// members route's Dialog outlet (real Dialog instead of the old slide-over).
|
||||
const data = useLoaderData<NewMemberLoaderData>();
|
||||
return <NewMember featurePlanUsage={data.featurePlanUsage} />;
|
||||
const navigate = useNavigate();
|
||||
const params = useParams();
|
||||
return (
|
||||
<CheckPlanFeatureLimit item={data.featurePlanUsage}>
|
||||
<InviteMemberForm onClose={() => navigate(UrlUtils.currentTenantUrl(params, "settings/members"), { replace: true })} />
|
||||
</CheckPlanFeatureLimit>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
|
||||
+100
-29
@@ -3,7 +3,7 @@ import { render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MemoryRouter } from "react-router";
|
||||
|
||||
vi.mock("@toolctrl/db/notifications.server", () => ({
|
||||
vi.mock("@hivegrid/db/notifications.server", () => ({
|
||||
getUserNotificationPreferences: vi.fn(),
|
||||
upsertUserNotificationPreference: vi.fn(),
|
||||
}));
|
||||
@@ -27,6 +27,13 @@ const routeTranslations: Record<string, string> = {
|
||||
"settings.notifications.categories.default": "Default",
|
||||
"settings.notifications.categories.billing": "Billing",
|
||||
"settings.notifications.categories.team": "Team",
|
||||
"settings.notifications.modules.general": "General",
|
||||
"settings.notifications.modules.billing": "Billing module",
|
||||
"settings.notifications.modules.team": "Team module",
|
||||
"settings.notifications.master.heading": "Email master switch",
|
||||
"settings.notifications.master.description": "Turns off all email notifications at once.",
|
||||
"settings.notifications.master.disableAllEmails": "Disable all emails",
|
||||
"settings.notifications.master.save": "Save all",
|
||||
"settings.notifications.channels.inApp": "In-app",
|
||||
"settings.notifications.channels.email": "Email",
|
||||
"settings.notifications.errors.invalidPreferenceAction": "Invalid notification preference action.",
|
||||
@@ -55,10 +62,12 @@ vi.mock("react-router", async () => {
|
||||
...actual,
|
||||
useActionData: () => routeActionData,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
useFetcher: () => ({ submit: vi.fn(), data: routeActionData, state: "idle" }),
|
||||
};
|
||||
});
|
||||
|
||||
import { getUserNotificationPreferences, upsertUserNotificationPreference } from "@toolctrl/db/notifications.server";
|
||||
import { buildNotificationSettingsVM } from "@hivegrid/view-models";
|
||||
import { getUserNotificationPreferences, upsertUserNotificationPreference } from "@hivegrid/db/notifications.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
@@ -100,11 +109,10 @@ describe("workspace notification settings route", () => {
|
||||
vi.mocked(getUserNotificationPreferences).mockResolvedValue([]);
|
||||
vi.mocked(upsertUserNotificationPreference).mockResolvedValue({ id: "pref_1" });
|
||||
routeLoaderData = {
|
||||
preferences: {
|
||||
default: { IN_APP: true, EMAIL: true },
|
||||
billing: { IN_APP: true, EMAIL: false },
|
||||
team: { IN_APP: false, EMAIL: true },
|
||||
},
|
||||
vm: buildNotificationSettingsVM([
|
||||
{ category: "billing", channel: "EMAIL", enabled: false },
|
||||
{ category: "team", channel: "IN_APP", enabled: false },
|
||||
]),
|
||||
};
|
||||
routeActionData = undefined;
|
||||
});
|
||||
@@ -123,12 +131,16 @@ describe("workspace notification settings route", () => {
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(getUserInfo).toHaveBeenCalledWith(request);
|
||||
expect(getUserNotificationPreferences).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" });
|
||||
expect(body).toEqual({
|
||||
preferences: {
|
||||
default: { IN_APP: true, EMAIL: true },
|
||||
billing: { IN_APP: true, EMAIL: false },
|
||||
team: { IN_APP: false, EMAIL: true },
|
||||
},
|
||||
expect(body.vm.status).toBe("ready");
|
||||
const channels = Object.fromEntries(
|
||||
body.vm.data.groups.flatMap((group: { categories: { category: string; channels: Record<string, boolean> }[] }) =>
|
||||
group.categories.map((category) => [category.category, category.channels]),
|
||||
),
|
||||
);
|
||||
expect(channels).toEqual({
|
||||
default: { IN_APP: true, EMAIL: true },
|
||||
billing: { IN_APP: true, EMAIL: false },
|
||||
team: { IN_APP: false, EMAIL: true },
|
||||
});
|
||||
expect(JSON.stringify(body)).not.toContain("unknown");
|
||||
});
|
||||
@@ -139,12 +151,16 @@ describe("workspace notification settings route", () => {
|
||||
const response = (await loader(routeArgs())) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(body).toEqual({
|
||||
preferences: {
|
||||
default: { IN_APP: true, EMAIL: false },
|
||||
billing: { IN_APP: true, EMAIL: false },
|
||||
team: { IN_APP: true, EMAIL: false },
|
||||
},
|
||||
expect(body.vm.data.allEmailsDisabled).toBe(true);
|
||||
const channels = Object.fromEntries(
|
||||
body.vm.data.groups.flatMap((group: { categories: { category: string; channels: Record<string, boolean> }[] }) =>
|
||||
group.categories.map((category) => [category.category, category.channels]),
|
||||
),
|
||||
);
|
||||
expect(channels).toEqual({
|
||||
default: { IN_APP: true, EMAIL: false },
|
||||
billing: { IN_APP: true, EMAIL: false },
|
||||
team: { IN_APP: true, EMAIL: false },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -200,21 +216,76 @@ describe("workspace notification settings route", () => {
|
||||
expect(body).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it("renders compact controls for default, billing, and team notification preferences", () => {
|
||||
render(
|
||||
it("disables email for every registered category when the master switch is turned on", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "set-email-master");
|
||||
form.set("disableAllEmails", "on");
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(body).toEqual({ ok: true });
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledTimes(3);
|
||||
for (const category of ["default", "billing", "team"]) {
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "EMAIL",
|
||||
category,
|
||||
enabled: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("re-enables email for every registered category when the master switch is cleared", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "set-email-master");
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(body).toEqual({ ok: true });
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledTimes(3);
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ channel: "EMAIL", category: "default", enabled: true }),
|
||||
);
|
||||
});
|
||||
|
||||
it("renders the email master switch alongside the per-category controls", () => {
|
||||
const { container } = render(
|
||||
<MemoryRouter>
|
||||
<WorkspaceNotificationSettingsRoute />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("heading", { name: "Notification preferences" })).toBeInTheDocument();
|
||||
expect(container.querySelector('[data-ui-id="ui.settings.notifications.master.email"]')).toBeInTheDocument();
|
||||
expect(screen.getAllByText("In-app")).toHaveLength(3);
|
||||
expect(screen.getAllByText("Email")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("renders compact controls for default, billing, and team notification preferences", () => {
|
||||
const { container } = render(
|
||||
<MemoryRouter>
|
||||
<WorkspaceNotificationSettingsRoute />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("Notification preferences")).toBeInTheDocument();
|
||||
expect(screen.getByText("Preferences are scoped to your current workspace and user account.", { exact: false })).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "Default" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "Billing" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: "Team" })).toBeInTheDocument();
|
||||
expect(screen.getAllByLabelText("In-app")).toHaveLength(3);
|
||||
expect(screen.getAllByLabelText("Email")).toHaveLength(3);
|
||||
expect(screen.getByLabelText("Email", { selector: "input#notification-billing-EMAIL" })).not.toBeChecked();
|
||||
expect(screen.getByLabelText("In-app", { selector: "input#notification-team-IN_APP" })).not.toBeChecked();
|
||||
expect(screen.getByText("Default")).toBeInTheDocument();
|
||||
expect(screen.getByText("Billing")).toBeInTheDocument();
|
||||
expect(screen.getByText("Team")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("In-app")).toHaveLength(3);
|
||||
expect(screen.getAllByText("Email")).toHaveLength(3);
|
||||
|
||||
// Switch state mirrors the VM: billing EMAIL off, team IN_APP off.
|
||||
const billingEmail = container
|
||||
.querySelector('[data-ui-id="ui.settings.notifications.preference.billing.email"]')
|
||||
?.querySelector('[role="switch"]');
|
||||
const teamInApp = container
|
||||
.querySelector('[data-ui-id="ui.settings.notifications.preference.team.in_app"]')
|
||||
?.querySelector('[role="switch"]');
|
||||
expect(billingEmail).toHaveAttribute("aria-checked", "false");
|
||||
expect(teamInApp).toHaveAttribute("aria-checked", "false");
|
||||
});
|
||||
});
|
||||
+62
-117
@@ -1,30 +1,28 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
// AK-P3 — Notification-Settings route (`/app/:tenant/settings/notifications`).
|
||||
// The category registry + default-inheritance merge live in the pure
|
||||
// notification-settings VM (@hivegrid/view-models); the loader builds the VM
|
||||
// once and the route injects it plus fetcher-backed action callbacks into the
|
||||
// interim <NotificationSettingsPage /> screen (AD-28).
|
||||
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
|
||||
import { upsertUserNotificationPreference, getUserNotificationPreferences } from "@hivegrid/db/notifications.server";
|
||||
import {
|
||||
getUserNotificationPreferences,
|
||||
upsertUserNotificationPreference,
|
||||
type NotificationPreferenceChannel,
|
||||
} from "@toolctrl/db/notifications.server";
|
||||
buildNotificationSettingsVM,
|
||||
isAllowedNotificationCategory,
|
||||
isAllowedNotificationChannel,
|
||||
NOTIFICATION_SETTING_CATEGORIES,
|
||||
type NotificationPreferenceInput,
|
||||
type NotificationSettingsVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { NotificationSettingsPage } from "~/components/screens/notifications/NotificationSettingsPage";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const NOTIFICATION_SETTING_CATEGORIES = ["default", "billing", "team"] as const;
|
||||
const NOTIFICATION_SETTING_CHANNELS = ["IN_APP", "EMAIL"] as const;
|
||||
|
||||
type NotificationSettingCategory = (typeof NOTIFICATION_SETTING_CATEGORIES)[number];
|
||||
type NotificationSettingChannel = (typeof NOTIFICATION_SETTING_CHANNELS)[number];
|
||||
|
||||
type NotificationPreferenceRecord = {
|
||||
channel: NotificationPreferenceChannel | string;
|
||||
category: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
preferences: Record<NotificationSettingCategory, Record<NotificationSettingChannel, boolean>>;
|
||||
vm: NotificationSettingsVM;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
@@ -32,14 +30,6 @@ type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function isAllowedCategory(value: string): value is NotificationSettingCategory {
|
||||
return NOTIFICATION_SETTING_CATEGORIES.includes(value as NotificationSettingCategory);
|
||||
}
|
||||
|
||||
function isAllowedChannel(value: string): value is NotificationSettingChannel {
|
||||
return NOTIFICATION_SETTING_CHANNELS.includes(value as NotificationSettingChannel);
|
||||
}
|
||||
|
||||
function getRequiredFormValue(formData: FormData, key: string): string | null {
|
||||
const value = formData.get(key);
|
||||
|
||||
@@ -51,41 +41,9 @@ function getRequiredFormValue(formData: FormData, key: string): string | null {
|
||||
return normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function createDefaultPreferences(): LoaderData["preferences"] {
|
||||
return {
|
||||
default: { IN_APP: true, EMAIL: true },
|
||||
billing: { IN_APP: true, EMAIL: true },
|
||||
team: { IN_APP: true, EMAIL: true },
|
||||
};
|
||||
}
|
||||
|
||||
function toLoaderData(records: NotificationPreferenceRecord[]): LoaderData {
|
||||
const preferences = createDefaultPreferences();
|
||||
const explicitPreferences = new Set<string>();
|
||||
|
||||
for (const record of records) {
|
||||
const category = record.category.trim().toLowerCase();
|
||||
const channel = record.channel.trim().replace(/-/g, "_").toUpperCase();
|
||||
|
||||
if (isAllowedCategory(category) && isAllowedChannel(channel)) {
|
||||
preferences[category][channel] = record.enabled;
|
||||
explicitPreferences.add(`${category}:${channel}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const category of NOTIFICATION_SETTING_CATEGORIES) {
|
||||
if (category === "default") {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const channel of NOTIFICATION_SETTING_CHANNELS) {
|
||||
if (!explicitPreferences.has(`${category}:${channel}`)) {
|
||||
preferences[category][channel] = preferences.default[channel];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { preferences };
|
||||
function isCheckboxOn(formData: FormData, key: string): boolean {
|
||||
const value = formData.get(key);
|
||||
return value === "on" || value === "true";
|
||||
}
|
||||
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
@@ -94,9 +52,10 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const records = (await getUserNotificationPreferences({ tenantId, userId: userInfo.userId })) as NotificationPreferenceRecord[];
|
||||
const records = (await getUserNotificationPreferences({ tenantId, userId: userInfo.userId })) as NotificationPreferenceInput[];
|
||||
|
||||
return Response.json(toLoaderData(records));
|
||||
const data: LoaderData = { vm: buildNotificationSettingsVM(records) };
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
@@ -108,6 +67,24 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const formData = await request.formData();
|
||||
const actionName = getRequiredFormValue(formData, "action");
|
||||
|
||||
// Master "turn all emails off" switch: write the EMAIL preference for every
|
||||
// known category so explicit per-category overrides cannot leak emails back in.
|
||||
if (actionName === "set-email-master") {
|
||||
const emailsEnabled = !isCheckboxOn(formData, "disableAllEmails");
|
||||
|
||||
for (const category of NOTIFICATION_SETTING_CATEGORIES) {
|
||||
await upsertUserNotificationPreference({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
channel: "EMAIL",
|
||||
category,
|
||||
enabled: emailsEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
if (actionName !== "update-preference") {
|
||||
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceAction") });
|
||||
}
|
||||
@@ -115,11 +92,11 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const category = getRequiredFormValue(formData, "category")?.toLowerCase() ?? "";
|
||||
const channel = getRequiredFormValue(formData, "channel")?.replace(/-/g, "_").toUpperCase() ?? "";
|
||||
|
||||
if (!isAllowedCategory(category)) {
|
||||
if (!isAllowedNotificationCategory(category)) {
|
||||
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceCategory") });
|
||||
}
|
||||
|
||||
if (!isAllowedChannel(channel)) {
|
||||
if (!isAllowedNotificationChannel(channel)) {
|
||||
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceChannel") });
|
||||
}
|
||||
|
||||
@@ -128,67 +105,35 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
userId: userInfo.userId,
|
||||
channel,
|
||||
category,
|
||||
enabled: formData.get("enabled") === "on" || formData.get("enabled") === "true",
|
||||
enabled: isCheckboxOn(formData, "enabled"),
|
||||
});
|
||||
|
||||
return Response.json({ ok: true });
|
||||
};
|
||||
|
||||
export default function WorkspaceNotificationSettingsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
|
||||
const saveState = fetcher.data ? { ok: fetcher.data.ok === true, errorText: fetcher.data.error } : null;
|
||||
|
||||
function submit(form: Record<string, string>) {
|
||||
fetcher.submit({ ...form, ...(rootData.csrf ? { csrf: rootData.csrf } : {}) }, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<main data-ui-id="ui.settings.notifications.page" className="mx-auto grid max-w-3xl gap-5 px-4 py-5 sm:px-8">
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-semibold text-foreground">{t("settings.notifications.heading")}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t("settings.notifications.description")}</p>
|
||||
</div>
|
||||
|
||||
{actionData?.error ? <p className="rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">{actionData.error}</p> : null}
|
||||
{actionData?.ok ? <p className="rounded-md border border-emerald-500/40 bg-emerald-500/10 p-3 text-sm text-emerald-700">{t("settings.notifications.saved")}</p> : null}
|
||||
|
||||
<div className="divide-y rounded-lg border bg-card">
|
||||
{NOTIFICATION_SETTING_CATEGORIES.map((category) => (
|
||||
<section
|
||||
key={category}
|
||||
data-ui-id={`ui.settings.notifications.category.${category}`}
|
||||
className="grid gap-3 p-4 sm:grid-cols-[1fr_auto] sm:items-center"
|
||||
>
|
||||
<div>
|
||||
<h2 className="text-sm font-medium text-foreground">{t(`settings.notifications.categories.${category}`)}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("settings.notifications.categoryDescription", { category: t(`settings.notifications.categories.${category}`).toLowerCase() })}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{NOTIFICATION_SETTING_CHANNELS.map((channel) => {
|
||||
const inputId = `notification-${category}-${channel}`;
|
||||
return (
|
||||
<form
|
||||
key={channel}
|
||||
method="post"
|
||||
data-ui-id={`ui.settings.notifications.preference.${category}.${channel.toLowerCase()}`}
|
||||
className="flex items-center gap-2 rounded-md border px-3 py-2"
|
||||
>
|
||||
<input type="hidden" name="action" value="update-preference" />
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="category" value={category} />
|
||||
<input type="hidden" name="channel" value={channel} />
|
||||
<input id={inputId} name="enabled" type="checkbox" defaultChecked={data.preferences[category][channel]} />
|
||||
<label htmlFor={inputId} className="text-sm font-medium">
|
||||
{t(channel === "IN_APP" ? "settings.notifications.channels.inApp" : "settings.notifications.channels.email")}
|
||||
</label>
|
||||
<button type="submit" className="text-sm text-primary underline-offset-2 hover:underline">
|
||||
{t("shared.save")}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
<main className="relative z-0 flex-1 pb-8">
|
||||
<NotificationSettingsPage
|
||||
vm={data.vm}
|
||||
saveState={saveState}
|
||||
actions={{
|
||||
onTogglePreference: ({ category, channel, enabled }) =>
|
||||
submit({ action: "update-preference", category, channel, enabled: enabled ? "true" : "false" }),
|
||||
onSetEmailMaster: (disableAllEmails) =>
|
||||
submit({ action: "set-email-master", ...(disableAllEmails ? { disableAllEmails: "true" } : {}) }),
|
||||
}}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
import { ActionFunctionArgs, Form, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { deleteShkDemoData, getDemoDataStatus, provisionShkDemoData } from "~/utils/services/.server/akP20OnboardingService";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
type LoaderData = {
|
||||
provisioning: Awaited<ReturnType<typeof getDemoDataStatus>>;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.onboarding.demoData.manage", tenantId);
|
||||
return { provisioning: await getDemoDataStatus(tenantId) } satisfies LoaderData;
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.onboarding.demoData.manage", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "create-demo-data") {
|
||||
await provisionShkDemoData({ tenantId, userId: userInfo.userId });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
if (action === "delete-demo-data") {
|
||||
await deleteShkDemoData({ tenantId, provisioningId: form.get("provisioningId")?.toString() ?? "" });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
return Response.json({ error: "shared.invalidAction" }, { status: 400 });
|
||||
};
|
||||
|
||||
export default function DemoDataSettingsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { csrf } = useRootData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const hasDemoData = Boolean(data.provisioning);
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("onboarding.demoData.title")}>
|
||||
<SettingSection title={t("onboarding.demoData.title")} description={t("onboarding.demoData.description")}>
|
||||
<Form method="post" className="flex flex-wrap gap-3">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
{hasDemoData ? (
|
||||
<>
|
||||
<input type="hidden" name="action" value="delete-demo-data" />
|
||||
<input type="hidden" name="provisioningId" value={data.provisioning?.id ?? ""} />
|
||||
<button type="submit" className="bg-destructive text-destructive-foreground rounded-md px-3 py-2 text-sm font-medium">
|
||||
{t("onboarding.demoData.delete")}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<input type="hidden" name="action" value="create-demo-data" />
|
||||
<button type="submit" className="bg-primary text-primary-foreground rounded-md px-3 py-2 text-sm font-medium">
|
||||
{t("onboarding.demoData.create")}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</Form>
|
||||
</SettingSection>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+1
-1
@@ -26,7 +26,7 @@ vi.mock("~/utils/db/users.db.server", () => ({
|
||||
vi.mock("~/shared-store.server", () => ({
|
||||
getSharedStore: vi.fn(() => ({ kind: "test-store" })),
|
||||
}));
|
||||
vi.mock("@toolctrl/shared-store", () => ({
|
||||
vi.mock("@hivegrid/shared-store", () => ({
|
||||
createSlidingWindowRateLimiter: vi.fn(() => ({
|
||||
consume: (...args: unknown[]) => consumeRateLimitMock(...args),
|
||||
})),
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from "react-router";
|
||||
import { Link, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { createSlidingWindowRateLimiter } from "@toolctrl/shared-store";
|
||||
import { createSlidingWindowRateLimiter } from "@hivegrid/shared-store";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { PluginSettingsFrame } from "~/modules/plugins/components/PluginSettingsFrame";
|
||||
import {
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test, vi, beforeEach } from "vitest";
|
||||
import { PLUGIN_CAPABILITY_NAMES } from "@toolctrl/plugin-runtime/capabilities";
|
||||
import { PLUGIN_CAPABILITY_NAMES } from "@hivegrid/plugin-runtime/capabilities";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const listMock = vi.fn();
|
||||
|
||||
+5
-5
@@ -17,9 +17,9 @@ import {
|
||||
isPluginCapabilityName,
|
||||
type PluginCapabilityMetadata,
|
||||
type PluginCapabilityRisk,
|
||||
} from "@toolctrl/plugin-runtime/capabilities";
|
||||
import { isPluginHookProductionAvailable } from "@toolctrl/plugin-runtime/hooks/registry";
|
||||
import type { PluginCapability } from "@toolctrl/plugin-runtime/manifest";
|
||||
} from "@hivegrid/plugin-runtime/capabilities";
|
||||
import { isPluginHookProductionAvailable } from "@hivegrid/plugin-runtime/hooks/registry";
|
||||
import type { PluginCapability } from "@hivegrid/plugin-runtime/manifest";
|
||||
import { Form, Link, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useState } from "react";
|
||||
@@ -351,8 +351,8 @@ export default function TenantPluginsRoute() {
|
||||
return (
|
||||
<div className="space-y-6 p-6" data-ui-id="ui.plugins.page">
|
||||
<header>
|
||||
<h1 className="text-xl font-semibold">{t("settings.plugins.title")}</h1>
|
||||
<p className="text-sm text-gray-500">{t("settings.plugins.description", { tenantSlug: data.tenantSlug })}</p>
|
||||
<h1 className="text-heading- font-heading- text-text-neutral-primary">{t("settings.plugins.title")}</h1>
|
||||
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{t("settings.plugins.description", { tenantSlug: data.tenantSlug })}</p>
|
||||
</header>
|
||||
{actionData?.message ? (
|
||||
<div
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { FormHTMLAttributes, ReactNode } from "react";
|
||||
import { MemoryRouter, useActionData, useLoaderData } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { expectNoAxeViolations, runAxe } from "@toolctrl/ui-app/test-setup/axe";
|
||||
import { expectNoAxeViolations, runAxe } from "@hivegrid/ui-app/test-setup/axe";
|
||||
|
||||
import TenantPluginsRoute from "./plugins";
|
||||
|
||||
|
||||
+3
-3
@@ -65,10 +65,10 @@ function routeArgs(): LoaderFunctionArgs {
|
||||
describe("workspace policies settings route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
routeLoaderData = { title: "settings.policies.title | ToolCTRL", workspaceSlug: "acme" };
|
||||
routeLoaderData = { title: "settings.policies.title | HiveGrid", workspaceSlug: "acme" };
|
||||
});
|
||||
|
||||
it("requires account settings permission for the resolved tenant before rendering policy data", async () => {
|
||||
@@ -77,7 +77,7 @@ describe("workspace policies settings route", () => {
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(request, "app.settings.account.view", "tenant_1");
|
||||
expect(vi.mocked(getTenantIdFromUrl).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]);
|
||||
expect(data).toEqual({ title: "settings.policies.title | ToolCTRL", workspaceSlug: "acme" });
|
||||
expect(data).toEqual({ title: "settings.policies.title | HiveGrid", workspaceSlug: "acme" });
|
||||
});
|
||||
|
||||
it("propagates permission rejection after tenant resolution", async () => {
|
||||
|
||||
+2
-2
@@ -19,8 +19,8 @@ const mocks = vi.hoisted(() => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({ createAuditEvent: (...args: unknown[]) => mocks.createAuditEvent(...args) }));
|
||||
vi.mock("@toolctrl/db/client.server", () => ({ getDbClient: () => mocks.db }));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: (...args: unknown[]) => mocks.createAuditEvent(...args) }));
|
||||
vi.mock("@hivegrid/db/client.server", () => ({ getDbClient: () => mocks.db }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
|
||||
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: (...args: unknown[]) => mocks.requireAuth(...args) }));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
|
||||
+2
-2
@@ -26,8 +26,8 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { Form, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
+19
-5
@@ -25,8 +25,9 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { createGdprExportJob } from "@hivegrid/db/privacy-gdpr.server";
|
||||
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
@@ -35,6 +36,7 @@ import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { DeletionTokenSecretMissingError, signDeletionToken } from "~/utils/dsgvo/deletionToken.server";
|
||||
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
|
||||
import { enqueueGdprExport } from "~/utils/privacy/gdprExportQueue.server";
|
||||
|
||||
const DSGVO_GRACE_PERIOD_DAYS = Number(process.env.DSGVO_GRACE_PERIOD_DAYS ?? "30") || 30;
|
||||
|
||||
@@ -113,8 +115,20 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const requestId = randomUUID();
|
||||
|
||||
if (intent === "export") {
|
||||
// Record the request as an AuditEvent — the worker job picks it up
|
||||
// out-of-band (queue glue lives in apps/worker/src/index.ts).
|
||||
const exportJob = await createGdprExportJob({
|
||||
tenantId,
|
||||
requestedByUserId: userInfo.userId,
|
||||
targetUserId: userInfo.userId,
|
||||
scope: "user_self",
|
||||
});
|
||||
const enqueueResult = await enqueueGdprExport({
|
||||
exportJobId: exportJob.id,
|
||||
tenantId,
|
||||
requestedByUserId: userInfo.userId,
|
||||
targetUserId: userInfo.userId,
|
||||
scope: "user_self",
|
||||
requestId,
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
@@ -125,7 +139,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "export", source: "self-service" },
|
||||
metadata: { requestId, intent: "export", source: "self-service", gdprExportJobId: exportJob.id, enqueueResult },
|
||||
});
|
||||
const data: ActionData = {
|
||||
intent: "export",
|
||||
|
||||
+3
-3
@@ -183,7 +183,7 @@ describe("profile MFA route actions", () => {
|
||||
vi.mocked(requireAuth).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: user.id } as never);
|
||||
vi.mocked(getUserSession).mockResolvedValue({ id: "session_1", get: vi.fn(), set: vi.fn(), unset: vi.fn() } as never);
|
||||
vi.mocked(storage.destroySession).mockResolvedValue("RJ_session=; Max-Age=0; Path=/; HttpOnly" as never);
|
||||
vi.mocked(storage.destroySession).mockResolvedValue("hivegrid_session=; Max-Age=0; Path=/; HttpOnly" as never);
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue(tenant.id);
|
||||
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
||||
vi.mocked(db.user.findUnique).mockResolvedValue(user as never);
|
||||
@@ -196,8 +196,8 @@ describe("profile MFA route actions", () => {
|
||||
vi.mocked(startTotpEnrollment).mockReturnValue({
|
||||
secret: "RAWSECRET",
|
||||
encryptedSecret: "encrypted-secret",
|
||||
otpauthUri: "otpauth://totp/ToolCTRL:ada@example.com?secret=RAWSECRET&issuer=ToolCTRL",
|
||||
qrValue: "otpauth://totp/ToolCTRL:ada@example.com?secret=RAWSECRET&issuer=ToolCTRL",
|
||||
otpauthUri: "otpauth://totp/HiveGrid:ada@example.com?secret=RAWSECRET&issuer=HiveGrid",
|
||||
qrValue: "otpauth://totp/HiveGrid:ada@example.com?secret=RAWSECRET&issuer=HiveGrid",
|
||||
});
|
||||
vi.mocked(verifyTotpCode).mockReturnValue(true);
|
||||
vi.mocked(getUserTotpPendingEnrollment).mockResolvedValue({
|
||||
|
||||
+3
-3
@@ -107,7 +107,7 @@ async function callAction(actionName: string) {
|
||||
|
||||
function expectNoSessionLeak(payload: unknown) {
|
||||
const serialized = JSON.stringify(payload);
|
||||
expect(serialized).not.toContain("RJ_session");
|
||||
expect(serialized).not.toContain("hivegrid_session");
|
||||
expect(serialized).not.toContain("raw-cookie-value");
|
||||
expect(serialized).not.toContain("csrf-secret");
|
||||
expect(serialized).not.toContain("adminMfaStepUp");
|
||||
@@ -144,7 +144,7 @@ describe("profile current-session settings", () => {
|
||||
state: { userId: user.id, method: "totp", verifiedAt: "2026-05-08T12:00:00.000Z", redirectTo: "/admin" },
|
||||
ageMs: 10_000,
|
||||
});
|
||||
vi.mocked(commitSession).mockResolvedValue("RJ_session=updated-cookie; Path=/; HttpOnly" as never);
|
||||
vi.mocked(commitSession).mockResolvedValue("hivegrid_session=updated-cookie; Path=/; HttpOnly" as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
@@ -205,7 +205,7 @@ describe("profile current-session settings", () => {
|
||||
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(clearMfaStepUpState).toHaveBeenCalledWith(session);
|
||||
expect(commitSession).toHaveBeenCalledWith(session);
|
||||
expect(response.headers.get("Set-Cookie")).toBe("RJ_session=updated-cookie; Path=/; HttpOnly");
|
||||
expect(response.headers.get("Set-Cookie")).toBe("hivegrid_session=updated-cookie; Path=/; HttpOnly");
|
||||
expect(body).toMatchObject({ success: "Session MFA verification cleared", currentSession: { mfaStepUp: { present: true, verified: true } } });
|
||||
expectNoSessionLeak(body);
|
||||
});
|
||||
|
||||
+6
-1
@@ -30,6 +30,7 @@ import { UserPasswordUpdatedDto } from "~/modules/events/dtos/UserPasswordUpdate
|
||||
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import { UserProfileDeletedDto } from "~/modules/events/dtos/UserProfileDeletedDto";
|
||||
import MyProfileScreen from "~/modules/users/components/MyProfileScreen";
|
||||
import { LanguageSettingsNotice } from "~/components/settings/LanguageSettingsNotice";
|
||||
import toast from "react-hot-toast";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { generateRecoveryCodes } from "~/utils/auth/mfa/recovery-codes.server";
|
||||
@@ -74,7 +75,7 @@ function getCurrentSessionSettings(
|
||||
const cookies = Array.isArray(userInfo.cookies) ? userInfo.cookies : [];
|
||||
return {
|
||||
locale: userInfo.lng,
|
||||
lightOrDarkMode: userInfo.lightOrDarkMode || "system",
|
||||
lightOrDarkMode: userInfo.lightOrDarkMode === "dark" ? "dark" : "light",
|
||||
theme: typeof userInfo.theme === "string" && userInfo.theme.length > 0 ? userInfo.theme : null,
|
||||
cookieConsentCount: cookies.filter((cookie) => cookie?.allowed).length,
|
||||
impersonationActive: Boolean(userInfo.impersonatingFromUserId),
|
||||
@@ -423,11 +424,15 @@ export default function ProfileRoute() {
|
||||
<EditPageLayout className="pb-20">
|
||||
<MyProfileScreen
|
||||
user={appData.user}
|
||||
role={appData.currentRole}
|
||||
mfaStatus={actionData?.mfaStatus ?? loaderData.mfaStatus}
|
||||
otpauthUri={actionData?.otpauthUri}
|
||||
recoveryCodes={actionData?.recoveryCodes}
|
||||
mfaError={actionData?.mfaError}
|
||||
/>
|
||||
<div className="mt-6 w-full">
|
||||
<LanguageSettingsNotice />
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+9
-32
@@ -4,10 +4,12 @@ import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useEffect } from "react";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import TabsVertical from "~/components/ui/tabs/TabsVertical";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
// R-P2b — D-P2 restructure: one merged "Rollen und Berechtigungen" tab (S02).
|
||||
// The old users/permissions sub-tabs redirect (matrix → members D01 dropdown,
|
||||
// permissions → role editor M02); the tab bar lives in MembersPage/RolesPage.
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
@@ -20,7 +22,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "app.settings.roles.view", tenantId);
|
||||
|
||||
if (UrlUtils.stripTrailingSlash(new URL(request.url).pathname) === UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions")) {
|
||||
throw redirect(UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/users"));
|
||||
throw redirect(UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/roles"));
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
@@ -29,46 +31,21 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function AdminAccountUsersFromTenant() {
|
||||
const { t } = useTranslation();
|
||||
export default function RolesAndPermissionsShell() {
|
||||
const params = useParams();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (UrlUtils.stripTrailingSlash(location.pathname) === UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions")) {
|
||||
navigate(UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/users"));
|
||||
navigate(UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/roles"));
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [location.pathname]);
|
||||
|
||||
return (
|
||||
<div data-ui-id="ui.settings.rolesAndPermissions.page" className="mx-auto max-w-5xl space-y-2 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-12">
|
||||
<div data-ui-id="ui.settings.rolesAndPermissions.tabs" className="lg:col-span-2">
|
||||
<TabsVertical
|
||||
tabs={[
|
||||
{
|
||||
name: t("models.user.plural"),
|
||||
routePath: UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/users"),
|
||||
},
|
||||
{
|
||||
name: t("models.role.plural"),
|
||||
routePath: UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/roles"),
|
||||
},
|
||||
{
|
||||
name: t("models.permission.plural"),
|
||||
routePath: UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/permissions"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="lg:col-span-10">
|
||||
<div className="w-full">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div data-ui-id="ui.settings.rolesAndPermissions.page" className="w-full">
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+7
-34
@@ -1,41 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllPermissions, PermissionWithRoles } from "~/utils/db/permissions/permissions.db.server";
|
||||
import PermissionsTable from "~/components/core/roles/PermissionsTable";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { LoaderFunctionArgs, redirect } from "react-router";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: PermissionWithRoles[];
|
||||
};
|
||||
|
||||
// R-P2b — D-P2 restructure: permissions live inside the merged
|
||||
// "Rollen und Berechtigungen" tab (S02/M02). The route stays for old links.
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.roles.view", tenantId);
|
||||
|
||||
const items = await getAllPermissions("app");
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.permission.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
throw redirect(UrlUtils.currentTenantUrl(params, "settings/roles-and-permissions/roles"));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function PermissionsRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appData = useAppData();
|
||||
|
||||
return (
|
||||
<div data-ui-id="ui.settings.rolesAndPermissions.permissions">
|
||||
<PermissionsTable items={data.items} canCreate={false} canUpdate={false} tenantId={appData.currentTenant.id} />
|
||||
</div>
|
||||
);
|
||||
export default function RolesAndPermissionsPermissionsRedirect() {
|
||||
return null;
|
||||
}
|
||||
+12
-4
@@ -75,6 +75,7 @@ const role = {
|
||||
order: 1,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
tenantId: "tenant_1",
|
||||
permissions: [{ id: "role_perm_1", roleId: "role_1", permissionId: "perm_1", permission: appPermission }],
|
||||
users: [],
|
||||
};
|
||||
@@ -143,15 +144,22 @@ describe("tenant workspace role routes", () => {
|
||||
expect(getAllRolesWithUsers).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses global default and tenant-owned app roles for the list loader after requiring builder access", async () => {
|
||||
const defaultRole = { ...role, id: "role_default", isDefault: true };
|
||||
it("builds the roles VM from default and tenant-owned app roles after requiring builder access", async () => {
|
||||
const defaultRole = { ...role, id: "role_default", isDefault: true, tenantId: null };
|
||||
vi.mocked(getAllRolesWithUsers).mockResolvedValueOnce([role, defaultRole] as Awaited<ReturnType<typeof getAllRolesWithUsers>>);
|
||||
|
||||
const data = await callListLoader();
|
||||
const data = (await callListLoader()) as { vm: { status: string; data?: { rows: { id: string; typeKey: string }[] } }; editorCatalog: unknown; rolePermissionNames: Record<string, string[]> };
|
||||
|
||||
expect(requireWorkspaceRolesBuilderAccess).toHaveBeenCalledWith({ request, params, tenantId: "tenant_1" });
|
||||
expect(getAllRolesWithUsers).toHaveBeenCalledWith("app", undefined, "tenant_1");
|
||||
expect(data).toMatchObject({ items: [role, defaultRole] });
|
||||
expect(data.vm.status).toBe("ready");
|
||||
expect(data.vm.data?.rows.map((row) => ({ id: row.id, typeKey: row.typeKey }))).toEqual([
|
||||
{ id: "role_1", typeKey: "custom" },
|
||||
{ id: "role_default", typeKey: "system" },
|
||||
]);
|
||||
// Editor prefill data: catalog is app-only, per-role permission names are exposed by id.
|
||||
expect(data.editorCatalog).toEqual([{ name: "app.settings.members.view", description: "View members" }]);
|
||||
expect(data.rolePermissionNames).toEqual({ role_1: ["app.settings.members.view"], role_default: ["app.settings.members.view"] });
|
||||
});
|
||||
|
||||
it("new role loader exposes only app permissions", async () => {
|
||||
|
||||
+88
-31
@@ -1,17 +1,25 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { t } from "i18next";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { LoaderFunctionArgs, MetaFunction, useFetcher, useLoaderData, useParams } from "react-router";
|
||||
import toast from "react-hot-toast";
|
||||
import { buildRolesListVM, type RoleEditorInputPermission, type RolesListVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import RolesListView from "~/modules/users/components/RolesListView";
|
||||
import { getAllRolesWithUsers, RoleWithPermissionsAndUsers } from "~/utils/db/permissions/roles.db.server";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { getAllRolesWithUsers } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getAllPermissions } from "~/utils/db/permissions/permissions.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { requireWorkspaceRolesBuilderAccess } from "~/utils/services/workspaceRoles.server";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { RolesPage, type RolesActions, type RoleMutationInput } from "~/components/screens/users/RolesPage";
|
||||
|
||||
// R-P2b — D-P2 S02 "Rollen und Berechtigungen": the list route builds the VM,
|
||||
// the RolesPage dialogs (M04A/M04B/M02/D03) post to the existing new/$id
|
||||
// actions via fetcher — the create/update/delete contracts stay untouched.
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: RoleWithPermissionsAndUsers[];
|
||||
vm: RolesListVM;
|
||||
editorCatalog: RoleEditorInputPermission[];
|
||||
rolePermissionNames: Record<string, string[]>;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
@@ -19,42 +27,91 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireWorkspaceRolesBuilderAccess({ request, params, tenantId });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const items = await getAllRolesWithUsers("app", undefined, tenantId);
|
||||
const [items, permissions] = await Promise.all([getAllRolesWithUsers("app", undefined, tenantId), getAllPermissions("app")]);
|
||||
|
||||
const vm = buildRolesListVM({
|
||||
rows: items.map((role) => ({
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
description: role.description,
|
||||
isDefault: role.isDefault,
|
||||
tenantId: role.tenantId ?? null,
|
||||
memberCount: role.users.filter((user) => user.tenantId === tenantId).length,
|
||||
permissionCount: role.permissions.length,
|
||||
})),
|
||||
tenantId,
|
||||
// The builder gate (app.settings.roles.set) already passed above.
|
||||
canManageRoles: true,
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.role.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
vm,
|
||||
editorCatalog: permissions.filter((permission) => permission.type === "app").map(({ name, description }) => ({ name, description })),
|
||||
rolePermissionNames: Object.fromEntries(items.map((role) => [role.id, role.permissions.map((entry) => entry.permission.name)])),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type MutationResponse = { error?: string; success?: string };
|
||||
|
||||
export default function RolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appData = useAppData();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
const canUpdate = getUserHasPermission(appData, "app.settings.roles.set");
|
||||
const fetcher = useFetcher<MutationResponse>();
|
||||
const rootData = useRootData();
|
||||
const [closeSignal, setCloseSignal] = useState(0);
|
||||
const hadSubmission = useRef(false);
|
||||
|
||||
const submitting = fetcher.state !== "idle";
|
||||
const errorMessage = fetcher.data?.error ?? null;
|
||||
|
||||
// Close the dialogs (and toast) once a mutation went through without an error.
|
||||
useEffect(() => {
|
||||
if (fetcher.state !== "idle") {
|
||||
hadSubmission.current = true;
|
||||
return;
|
||||
}
|
||||
if (hadSubmission.current) {
|
||||
hadSubmission.current = false;
|
||||
if (!fetcher.data?.error) {
|
||||
setCloseSignal((value) => value + 1);
|
||||
if (fetcher.data?.success) toast.success(fetcher.data.success);
|
||||
}
|
||||
}
|
||||
}, [fetcher.state, fetcher.data]);
|
||||
|
||||
function post(target: string, fields: Record<string, string>, permissionNames?: string[]) {
|
||||
const formData = new FormData();
|
||||
if (rootData.csrf) formData.set("csrf", rootData.csrf);
|
||||
for (const [name, value] of Object.entries(fields)) {
|
||||
formData.set(name, value);
|
||||
}
|
||||
for (const permissionName of permissionNames ?? []) {
|
||||
formData.append("permissions[]", permissionName);
|
||||
}
|
||||
fetcher.submit(formData, { method: "post", action: UrlUtils.currentTenantUrl(params, `settings/roles-and-permissions/roles/${target}`) });
|
||||
}
|
||||
|
||||
const actions: RolesActions = {
|
||||
onCreate: (input: RoleMutationInput) => post("new", { action: "create", name: input.name, description: input.description, type: "app" }, input.permissionNames),
|
||||
onUpdate: (roleId: string, input: RoleMutationInput) =>
|
||||
post(roleId, { action: "edit", name: input.name, description: input.description, type: "app" }, input.permissionNames),
|
||||
onDelete: (roleId: string) => post(roleId, { action: "delete" }),
|
||||
};
|
||||
|
||||
return (
|
||||
<div data-ui-id="ui.settings.rolesAndPermissions.roles" className="space-y-2">
|
||||
<RolesListView items={data.items} canUpdate={canUpdate} tenantId={appData.currentTenant.id} />
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("shared.edit") : t("shared.new")}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-lg"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</div>
|
||||
<RolesPage
|
||||
vm={data.vm}
|
||||
editorCatalog={data.editorCatalog}
|
||||
rolePermissionNames={data.rolePermissionNames}
|
||||
membersTabHref={UrlUtils.currentTenantUrl(params, "settings/members")}
|
||||
actions={actions}
|
||||
submitting={submitting}
|
||||
errorMessage={errorMessage}
|
||||
closeSignal={closeSignal}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+8
-173
@@ -1,180 +1,15 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllRoles, getTenantAssignableAppRole, RoleWithPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getTenantScopedUsersWithDetails, getUser, UserWithDetails, UserWithRoles } from "~/utils/db/users.db.server";
|
||||
import UserRolesTable from "~/components/core/roles/UserRolesTable";
|
||||
import { useEffect, useState } from "react";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { createUserRole, deleteUserRole } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenant, getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { RoleAssignedDto } from "~/modules/events/dtos/RoleAssignedDto";
|
||||
import { RoleUnassignedDto } from "~/modules/events/dtos/RoleUnassignedDto";
|
||||
import { LoaderFunctionArgs, redirect } from "react-router";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: UserWithRoles[];
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
// R-P2b — D-P2 restructure: the user↔role matrix is superseded by the inline
|
||||
// role dropdown in the members list (D01). The route stays for old links and
|
||||
// forwards to Settings → Mitarbeiter.
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.roles.view", tenantId);
|
||||
|
||||
const tenantUsers = await getTenantScopedUsersWithDetails(tenantId);
|
||||
const roles = await getAllRoles("app");
|
||||
|
||||
const items: UserWithDetails[] = [];
|
||||
tenantUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.permission.userRoles")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
throw redirect(UrlUtils.currentTenantUrl(params, "settings/members"));
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.roles.set", tenantId);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const fromUser = await getUser(userInfo.userId);
|
||||
if (!fromUser) {
|
||||
return badRequest({ error: t("shared.invalidUser") });
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
const roleId = form.get("role-id")?.toString() ?? "";
|
||||
const add = form.get("add") === "true";
|
||||
|
||||
const tenant = await getTenant(tenantId);
|
||||
const tenantMember = await getTenantMember(userId, tenantId);
|
||||
const user = tenantMember?.user ?? null;
|
||||
const role = await getTenantAssignableAppRole(roleId, tenantId);
|
||||
|
||||
if (!tenant || !tenantMember || !user || !role || role.type !== "app") {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId, tenantId);
|
||||
if (fromUser && user && role) {
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "role.assigned",
|
||||
tenantId: tenant?.id ?? null,
|
||||
userId: fromUser.id,
|
||||
data: {
|
||||
fromUser: { id: fromUser.id, email: fromUser.email },
|
||||
toUser: { id: user.id, email: user.email },
|
||||
role: { id: role.id, name: role.name, description: role.description },
|
||||
} satisfies RoleAssignedDto,
|
||||
});
|
||||
}
|
||||
createAdminLog(request, "settings.rolesAndPermissions.userRoles.created", `[${tenant?.name}] ${user?.email} - ${role?.name}`);
|
||||
} else {
|
||||
if (fromUser && user && role) {
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "role.unassigned",
|
||||
tenantId: tenant?.id ?? null,
|
||||
userId: fromUser.id,
|
||||
data: {
|
||||
fromUser: { id: fromUser.id, email: fromUser.email },
|
||||
toUser: { id: user.id, email: user.email },
|
||||
role: { id: role.id, name: role.name, description: role.description },
|
||||
} satisfies RoleUnassignedDto,
|
||||
});
|
||||
}
|
||||
await deleteUserRole(userId, roleId, tenantId);
|
||||
createAdminLog(request, "settings.rolesAndPermissions.userRoles.deleted", `[${tenant?.name}] ${user?.email} - ${role?.name}`);
|
||||
}
|
||||
|
||||
return Response.json({});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminAccountUsersFromTenant() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appData = useAppData();
|
||||
const rootData = useRootData();
|
||||
const [items, setItems] = useState(data.items);
|
||||
const submit = useSubmit();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setItems(data.items);
|
||||
}, [data]);
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!items) {
|
||||
return [];
|
||||
}
|
||||
return items.filter(
|
||||
(f) =>
|
||||
f.email?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.firstName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.lastName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.roles.find(
|
||||
(f) => f.role.name.toUpperCase().includes(searchInput.toUpperCase()) || f.role.description.toUpperCase().includes(searchInput.toUpperCase())
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
function onChange(item: UserWithRoles, role: RoleWithPermissions, add: any) {
|
||||
const form = new FormData();
|
||||
form.set("action", "edit");
|
||||
form.set("user-id", item.id);
|
||||
form.set("role-id", role.id);
|
||||
form.set("add", add ? "true" : "false");
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div data-ui-id="ui.settings.rolesAndPermissions.users" className="space-y-2">
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
|
||||
<UserRolesTable
|
||||
items={filteredItems()}
|
||||
roles={data.roles}
|
||||
onChange={onChange}
|
||||
tenantId={appData.currentTenant.id}
|
||||
disabled={!getUserHasPermission(appData, "app.settings.roles.set")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
export default function RolesAndPermissionsUsersRedirect() {
|
||||
return null;
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { redirect, useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction } from "react-router";
|
||||
|
||||
import { buildSessionListVM, type SessionListVM } from "@toolctrl/view-models";
|
||||
import { buildSessionListVM, type SessionListVM } from "@hivegrid/view-models";
|
||||
import SecuritySessionsScreen from "~/modules/users/components/SecuritySessionsScreen";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
|
||||
+114
-44
@@ -11,15 +11,13 @@ const mocks = vi.hoisted(() => ({
|
||||
getTenant: vi.fn(),
|
||||
getOrPersistTenantSubscription: vi.fn(),
|
||||
getTenantSubscription: vi.fn(),
|
||||
getStripeCustomer: vi.fn(),
|
||||
getStripeInvoices: vi.fn(),
|
||||
getStripePaymentIntents: vi.fn(),
|
||||
getStripeUpcomingInvoices: vi.fn(),
|
||||
getStripePaymentMethods: vi.fn(),
|
||||
createCustomerPortalSession: vi.fn(),
|
||||
cancelTenantSubscription: vi.fn(),
|
||||
getPlanFeaturesUsage: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
tenantHasModule: vi.fn(),
|
||||
listCustomerBillingInvoices: vi.fn(),
|
||||
getAllSubscriptionProducts: vi.fn(),
|
||||
createSelfServiceCheckout: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
@@ -52,25 +50,39 @@ vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
||||
cancelTenantSubscription: (...args: unknown[]) => mocks.cancelTenantSubscription(...args),
|
||||
getPlanFeaturesUsage: (...args: unknown[]) => mocks.getPlanFeaturesUsage(...args),
|
||||
}));
|
||||
vi.mock("~/utils/stripe.server", () => ({
|
||||
createCustomerPortalSession: (...args: unknown[]) => mocks.createCustomerPortalSession(...args),
|
||||
createStripeSetupSession: vi.fn(),
|
||||
deleteStripePaymentMethod: vi.fn(),
|
||||
getStripeCustomer: (...args: unknown[]) => mocks.getStripeCustomer(...args),
|
||||
getStripeInvoices: (...args: unknown[]) => mocks.getStripeInvoices(...args),
|
||||
getStripePaymentIntents: (...args: unknown[]) => mocks.getStripePaymentIntents(...args),
|
||||
getStripeUpcomingInvoices: (...args: unknown[]) => mocks.getStripeUpcomingInvoices(...args),
|
||||
getStripePaymentMethods: (...args: unknown[]) => mocks.getStripePaymentMethods(...args),
|
||||
vi.mock("~/utils/connector/tenantConnector.server", () => ({
|
||||
tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args),
|
||||
}));
|
||||
vi.mock("~/services/billing/customer-invoices.server", () => ({
|
||||
CustomerBillingInvoiceError: class CustomerBillingInvoiceError extends Error {
|
||||
readonly i18nKey = "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE";
|
||||
},
|
||||
listCustomerBillingInvoices: (...args: unknown[]) => mocks.listCustomerBillingInvoices(...args),
|
||||
}));
|
||||
vi.mock("~/utils/db/subscriptionProducts.db.server", () => ({
|
||||
getAllSubscriptionProducts: (...args: unknown[]) => mocks.getAllSubscriptionProducts(...args),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/PricingHelper", () => ({
|
||||
getCurrenciesAndPeriods: (prices: unknown[]) => ({
|
||||
currencies: { value: "eur", options: ["eur"] },
|
||||
billingPeriods: { value: 3, options: [3] },
|
||||
prices,
|
||||
}),
|
||||
}));
|
||||
vi.mock("~/services/billing/self-service-checkout.server", () => ({
|
||||
SelfServiceCheckoutError: class SelfServiceCheckoutError extends Error {
|
||||
readonly i18nKey = "settings.subscription.errors.CHECKOUT_URL_MISSING";
|
||||
},
|
||||
createSelfServiceCheckout: (...args: unknown[]) => mocks.createSelfServiceCheckout(...args),
|
||||
}));
|
||||
|
||||
import { action, loader } from "./subscription";
|
||||
|
||||
const tenantId = "tenant-1";
|
||||
const userId = "user-1";
|
||||
const params = { tenant: "acme" };
|
||||
const tenantSubscription = {
|
||||
stripeCustomerId: "cus_123",
|
||||
products: [{ stripeSubscriptionId: "sub_123" }],
|
||||
billingProviderCustomerId: "cus_123",
|
||||
products: [{ billingProviderSubscriptionId: "sub_123" }],
|
||||
};
|
||||
|
||||
function formRequest(form: FormData) {
|
||||
@@ -83,7 +95,7 @@ function formRequest(form: FormData) {
|
||||
|
||||
function createForm(overrides: Record<string, string> = {}) {
|
||||
const form = new FormData();
|
||||
form.set("action", "open-customer-portal");
|
||||
form.set("action", "cancel");
|
||||
form.set("csrf", "csrf-token");
|
||||
Object.entries(overrides).forEach(([key, value]) => form.set(key, value));
|
||||
return form;
|
||||
@@ -109,18 +121,42 @@ describe("tenant subscription settings route", () => {
|
||||
mocks.getTenant.mockResolvedValue({ id: tenantId, name: "Acme", slug: "acme" });
|
||||
mocks.getOrPersistTenantSubscription.mockResolvedValue(tenantSubscription);
|
||||
mocks.getTenantSubscription.mockResolvedValue(tenantSubscription);
|
||||
mocks.getStripeCustomer.mockResolvedValue({ id: "cus_123" });
|
||||
mocks.getStripeInvoices.mockResolvedValue([{ id: "in_1" }]);
|
||||
mocks.getStripePaymentIntents.mockResolvedValue([{ id: "pi_1" }]);
|
||||
mocks.getStripeUpcomingInvoices.mockResolvedValue([{ id: "in_upcoming" }]);
|
||||
mocks.getStripePaymentMethods.mockResolvedValue([{ id: "pm_1" }]);
|
||||
mocks.getPlanFeaturesUsage.mockResolvedValue([{ name: "seats" }]);
|
||||
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
||||
mocks.createCustomerPortalSession.mockResolvedValue({ url: "https://billing.stripe.test/session" });
|
||||
mocks.tenantHasModule.mockResolvedValue(true);
|
||||
mocks.listCustomerBillingInvoices.mockResolvedValue([
|
||||
{
|
||||
id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
issuingDate: "2026-07-04",
|
||||
amountCents: 4900,
|
||||
currency: "EUR",
|
||||
status: "finalized",
|
||||
paymentStatus: "succeeded",
|
||||
invoiceType: "subscription",
|
||||
downloadHref: "/acme/settings/subscription/invoices/invoice_1/download",
|
||||
},
|
||||
]);
|
||||
mocks.getAllSubscriptionProducts.mockResolvedValue([
|
||||
{
|
||||
id: "plan_grow",
|
||||
billingProviderId: "local_product_grow",
|
||||
order: 1,
|
||||
title: "Grow",
|
||||
description: null,
|
||||
badge: null,
|
||||
active: true,
|
||||
model: 2,
|
||||
public: true,
|
||||
prices: [{ id: "price_grow_month", price: 49, currency: "eur", billingPeriod: 3 }],
|
||||
features: [],
|
||||
},
|
||||
]);
|
||||
mocks.createSelfServiceCheckout.mockResolvedValue({ checkoutUrl: "https://www.mollie.com/checkout/test" });
|
||||
mocks.cancelTenantSubscription.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("does not call Stripe invoice APIs when invoice permission is denied", async () => {
|
||||
it("loads local subscription feature usage", async () => {
|
||||
mocks.verifyUserHasPermission.mockImplementation(async (_request: Request, permission: string) => {
|
||||
if (permission === "app.settings.subscription.invoices.view") throw new Response("Forbidden", { status: 403 });
|
||||
});
|
||||
@@ -133,27 +169,32 @@ describe("tenant subscription settings route", () => {
|
||||
} as LoaderFunctionArgs);
|
||||
const data = await response.json();
|
||||
|
||||
expect(data.customer).toBeNull();
|
||||
expect(data.myInvoices).toEqual([]);
|
||||
expect(data.myPayments).toEqual([]);
|
||||
expect(data.myUpcomingInvoices).toEqual([]);
|
||||
expect(data.myPaymentMethods).toEqual([]);
|
||||
expect(data.myFeatures).toEqual([{ name: "seats" }]);
|
||||
expect(mocks.getStripeCustomer).not.toHaveBeenCalled();
|
||||
expect(mocks.getStripeInvoices).not.toHaveBeenCalled();
|
||||
expect(mocks.getStripePaymentIntents).not.toHaveBeenCalled();
|
||||
expect(mocks.getStripeUpcomingInvoices).not.toHaveBeenCalled();
|
||||
expect(mocks.getStripePaymentMethods).not.toHaveBeenCalled();
|
||||
expect(data.canViewInvoices).toBe(false);
|
||||
expect(data.availablePlans).toHaveLength(1);
|
||||
expect(data.canManageSubscription).toBe(true);
|
||||
expect(data.myInvoices).toEqual([]);
|
||||
expect(mocks.listCustomerBillingInvoices).not.toHaveBeenCalled();
|
||||
expect(mocks.getAllSubscriptionProducts).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it("returns 400 instead of redirecting to an empty customer portal URL", async () => {
|
||||
mocks.createCustomerPortalSession.mockResolvedValueOnce({ url: "" });
|
||||
|
||||
const response = await callAction(createForm());
|
||||
it("loads Lago invoices when the user may view subscription invoices", async () => {
|
||||
const response = await loader({
|
||||
request: new Request("https://app.example.test/app/acme/settings/subscription"),
|
||||
params,
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/subscription",
|
||||
} as LoaderFunctionArgs);
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(data).toEqual({ error: "settings.subscription.errors.customerPortalUnavailable" });
|
||||
expect(data.canViewInvoices).toBe(true);
|
||||
expect(data.myInvoices).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
}),
|
||||
]);
|
||||
expect(mocks.listCustomerBillingInvoices).toHaveBeenCalledWith({ tenantId, tenantSlug: "acme" });
|
||||
});
|
||||
|
||||
it("checks delete permission before cancelling a subscription product", async () => {
|
||||
@@ -165,8 +206,37 @@ describe("tenant subscription settings route", () => {
|
||||
expect(mocks.cancelTenantSubscription).toHaveBeenCalledWith("tsp_1", expect.objectContaining({ tenantId, userId }));
|
||||
});
|
||||
|
||||
it("starts a self-service checkout and redirects to Mollie when a plan is selected", async () => {
|
||||
const form = createForm({
|
||||
action: "subscribe",
|
||||
"product-id": "plan_grow",
|
||||
"billing-period": "3",
|
||||
currency: "eur",
|
||||
quantity: "4",
|
||||
"tenant-slug-context": "acme",
|
||||
});
|
||||
|
||||
const response = await callAction(form);
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toBe("https://www.mollie.com/checkout/test");
|
||||
expect(mocks.createSelfServiceCheckout).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId,
|
||||
tenantSlug: "acme",
|
||||
tenantName: "Acme",
|
||||
userId,
|
||||
userEmail: "user@example.test",
|
||||
productId: "plan_grow",
|
||||
billingPeriod: 3,
|
||||
currency: "eur",
|
||||
quantity: 4,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps cancel internals out of tenant-facing errors", async () => {
|
||||
mocks.cancelTenantSubscription.mockRejectedValueOnce(new Error("Stripe raw failure"));
|
||||
mocks.cancelTenantSubscription.mockRejectedValueOnce(new Error("Payment provider raw failure"));
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
|
||||
const response = await callAction(createForm({ action: "cancel", "tenant-subscription-product-id": "tsp_1" }));
|
||||
@@ -174,7 +244,7 @@ describe("tenant subscription settings route", () => {
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(data).toEqual({ error: "shared.unexpectedError" });
|
||||
expect(JSON.stringify(data)).not.toContain("Stripe raw failure");
|
||||
expect(JSON.stringify(data)).not.toContain("Payment provider raw failure");
|
||||
expect(consoleError).toHaveBeenCalledWith(expect.any(Error));
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
+114
-61
@@ -1,20 +1,9 @@
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData } from "react-router";
|
||||
import {
|
||||
createCustomerPortalSession,
|
||||
createStripeSetupSession,
|
||||
deleteStripePaymentMethod,
|
||||
getStripeCustomer,
|
||||
getStripeInvoices,
|
||||
getStripePaymentIntents,
|
||||
getStripePaymentMethods,
|
||||
getStripeUpcomingInvoices,
|
||||
} from "~/utils/stripe.server";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import type Stripe from "stripe";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getOrPersistTenantSubscription, getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
@@ -22,7 +11,6 @@ import { cancelTenantSubscription, getPlanFeaturesUsage } from "~/utils/services
|
||||
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SubscriptionSettings from "~/modules/users/components/SubscriptionSettings";
|
||||
@@ -30,17 +18,52 @@ import toast from "react-hot-toast";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { BILLING_MODULE_KEY } from "~/utils/services/.server/billingStatusService";
|
||||
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
import { CustomerBillingInvoiceError, listCustomerBillingInvoices } from "~/services/billing/customer-invoices.server";
|
||||
import type { CustomerBillingInvoiceDto } from "~/application/dtos/billing/CustomerBillingInvoiceDto";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { getCurrenciesAndPeriods } from "~/utils/helpers/PricingHelper";
|
||||
import type { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { createSelfServiceCheckout, SelfServiceCheckoutError } from "~/services/billing/self-service-checkout.server";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
customer: Stripe.Customer | Stripe.DeletedCustomer | null;
|
||||
myInvoices: Stripe.Invoice[];
|
||||
myPayments: Stripe.PaymentIntent[];
|
||||
myFeatures: PlanFeatureUsageDto[];
|
||||
myUpcomingInvoices: Stripe.Invoice[];
|
||||
myPaymentMethods: Stripe.PaymentMethod[];
|
||||
myInvoices: CustomerBillingInvoiceDto[];
|
||||
availablePlans: SubscriptionProductDto[];
|
||||
currenciesAndPeriod: ReturnType<typeof getCurrenciesAndPeriods>;
|
||||
canViewInvoices: boolean;
|
||||
canManageSubscription: boolean;
|
||||
invoiceErrorKey: string | null;
|
||||
};
|
||||
|
||||
async function canViewSubscriptionInvoices(request: Request, tenantId: string): Promise<boolean> {
|
||||
try {
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.invoices.view", tenantId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof Response && (error.status === 403 || error.status === 404)) {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function canManageSubscription(request: Request, tenantId: string): Promise<boolean> {
|
||||
try {
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.update", tenantId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof Response && (error.status === 403 || error.status === 404)) {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "app.$tenant.settings.subscription");
|
||||
let { t } = await getTranslations(request);
|
||||
@@ -50,15 +73,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const userInfoPromise = time(getUserInfo(request), "getUserInfo");
|
||||
const userPromise = userInfoPromise.then((userInfo) => time(getUser(userInfo.userId), "getUser"));
|
||||
const tenantPromise = time(getTenant(tenantId), "getTenant");
|
||||
const canViewInvoicesPromise = time(
|
||||
verifyUserHasPermission(request, "app.settings.subscription.invoices.view", tenantId).then(
|
||||
() => true,
|
||||
() => false
|
||||
),
|
||||
"verifyInvoicePermission"
|
||||
);
|
||||
|
||||
const [user, tenant, canViewInvoices] = await Promise.all([userPromise, tenantPromise, canViewInvoicesPromise]);
|
||||
const [user, tenant] = await Promise.all([userPromise, tenantPromise]);
|
||||
const userInfo = await userInfoPromise;
|
||||
const hasBillingModule = await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BILLING_MODULE_KEY });
|
||||
if (!hasBillingModule) {
|
||||
throw redirect(appTenantPlanRequiredPath(params));
|
||||
}
|
||||
if (!user) {
|
||||
return badRequest({ error: t("shared.invalidUser") });
|
||||
}
|
||||
@@ -67,29 +87,34 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
}
|
||||
|
||||
const tenantSubscription = await time(getOrPersistTenantSubscription(tenantId), "getOrPersistTenantSubscription");
|
||||
const { customer, myInvoices, myPayments, myUpcomingInvoices, myPaymentMethods, myFeatures } = await time(
|
||||
promiseHash({
|
||||
customer: canViewInvoices ? getStripeCustomer(tenantSubscription.stripeCustomerId) : Promise.resolve(null),
|
||||
myInvoices: canViewInvoices ? (getStripeInvoices(tenantSubscription.stripeCustomerId) ?? []) : Promise.resolve([] as Stripe.Invoice[]),
|
||||
myPayments: canViewInvoices
|
||||
? (getStripePaymentIntents(tenantSubscription.stripeCustomerId, "succeeded") ?? [])
|
||||
: Promise.resolve([] as Stripe.PaymentIntent[]),
|
||||
myUpcomingInvoices: canViewInvoices
|
||||
? getStripeUpcomingInvoices(tenantSubscription.products.filter((f) => f.stripeSubscriptionId).flatMap((p) => p.stripeSubscriptionId!))
|
||||
: Promise.resolve([] as Stripe.Invoice[]),
|
||||
myPaymentMethods: canViewInvoices ? getStripePaymentMethods(tenantSubscription.stripeCustomerId) : Promise.resolve([] as Stripe.PaymentMethod[]),
|
||||
myFeatures: getPlanFeaturesUsage(tenantId, tenantSubscription),
|
||||
}),
|
||||
"subscription[getStripeData]"
|
||||
);
|
||||
const [canViewInvoices, canUpdateSubscription, availablePlans] = await Promise.all([
|
||||
time(canViewSubscriptionInvoices(request, tenantId), "verifyInvoicePermission"),
|
||||
time(canManageSubscription(request, tenantId), "verifySubscriptionUpdatePermission"),
|
||||
time(getAllSubscriptionProducts(true), "subscription[getPublicProducts]"),
|
||||
]);
|
||||
const [myFeatures, invoiceResult] = await Promise.all([
|
||||
time(getPlanFeaturesUsage(tenantId, tenantSubscription), "subscription[getPlanFeaturesUsage]"),
|
||||
canViewInvoices
|
||||
? time(
|
||||
listCustomerBillingInvoices({ tenantId, tenantSlug: tenant.slug })
|
||||
.then((invoices) => ({ invoices, errorKey: null }))
|
||||
.catch((error) => ({
|
||||
invoices: [],
|
||||
errorKey: error instanceof CustomerBillingInvoiceError ? error.i18nKey : "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE",
|
||||
})),
|
||||
"billing[listCustomerInvoices]"
|
||||
)
|
||||
: Promise.resolve({ invoices: [], errorKey: null }),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
title: `${t("app.navbar.subscription")} | ${process.env.APP_NAME}`,
|
||||
customer,
|
||||
myFeatures,
|
||||
myInvoices,
|
||||
myPayments,
|
||||
myUpcomingInvoices,
|
||||
myPaymentMethods,
|
||||
myInvoices: invoiceResult.invoices,
|
||||
availablePlans: availablePlans as SubscriptionProductDto[],
|
||||
currenciesAndPeriod: getCurrenciesAndPeriods(availablePlans.flatMap((plan) => plan.prices)),
|
||||
canViewInvoices,
|
||||
canManageSubscription: canUpdateSubscription,
|
||||
invoiceErrorKey: invoiceResult.errorKey,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
@@ -110,9 +135,9 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (!tenantSubscription || !tenantSubscription?.stripeCustomerId) {
|
||||
if (!tenantSubscription) {
|
||||
return badRequest({
|
||||
error: t("settings.subscription.errors.invalidStripeCustomer"),
|
||||
error: t("settings.subscription.errors.invalidSubscription"),
|
||||
});
|
||||
} else if (action === "cancel") {
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.delete", tenantId);
|
||||
@@ -125,18 +150,46 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
console.error(error);
|
||||
return Response.json({ error: t("shared.unexpectedError") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "add-payment-method") {
|
||||
const session = await createStripeSetupSession(request, tenantSubscription.stripeCustomerId);
|
||||
return redirect(session?.url ?? "");
|
||||
} else if (action === "delete-payment-method") {
|
||||
await deleteStripePaymentMethod(form.get("id")?.toString() ?? "", tenantSubscription.stripeCustomerId);
|
||||
return Response.json({});
|
||||
} else if (action === "open-customer-portal") {
|
||||
const session = await createCustomerPortalSession(request, tenantSubscription.stripeCustomerId);
|
||||
if (!session?.url) {
|
||||
return badRequest({ error: t("settings.subscription.errors.customerPortalUnavailable") });
|
||||
} else if (action === "subscribe") {
|
||||
const tenant = await getTenant(tenantId);
|
||||
const user = await getUser(userInfo.userId);
|
||||
if (!tenant) {
|
||||
return badRequest({ error: t("settings.subscription.errors.invalidTenant", { tenantId }) });
|
||||
}
|
||||
if (!user) {
|
||||
return badRequest({ error: t("shared.invalidUser") });
|
||||
}
|
||||
const tenantSlugContext = form.get("tenant-slug-context")?.toString();
|
||||
if (tenantSlugContext && tenantSlugContext !== tenant.slug) {
|
||||
return badRequest({ error: t("settings.subscription.checkout.invalid") });
|
||||
}
|
||||
|
||||
try {
|
||||
const checkout = await createSelfServiceCheckout({
|
||||
request,
|
||||
tenantId,
|
||||
tenantSlug: tenant.slug,
|
||||
tenantName: tenant.name,
|
||||
userId: user.id,
|
||||
userEmail: user.email,
|
||||
userName: `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim() || user.email,
|
||||
productId: form.get("product-id")?.toString() ?? "",
|
||||
billingPeriod: Number(form.get("billing-period")?.toString()),
|
||||
currency: form.get("currency")?.toString() ?? "",
|
||||
quantity: Number(form.get("quantity")?.toString() ?? "1"),
|
||||
});
|
||||
return redirect(checkout.checkoutUrl);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof SelfServiceCheckoutError) {
|
||||
return Response.json({ error: t(error.i18nKey) }, { status: 400 });
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return Response.json({ error: t("shared.unexpectedError") }, { status: 400 });
|
||||
}
|
||||
return redirect(session.url);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -160,9 +213,9 @@ export default function SubscriptionRoute() {
|
||||
<SubscriptionSettings
|
||||
{...data}
|
||||
mySubscription={appData.mySubscription}
|
||||
currentTenant={appData.currentTenant}
|
||||
permissions={{
|
||||
viewInvoices: getUserHasPermission(appData, "app.settings.subscription.invoices.view") && data.myInvoices.length > 0,
|
||||
viewInvoices: data.canViewInvoices && getUserHasPermission(appData, "app.settings.subscription.invoices.view"),
|
||||
manageSubscription: data.canManageSubscription && getUserHasPermission(appData, "app.settings.subscription.update"),
|
||||
}}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getTranslations: vi.fn(),
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
getCustomerBillingInvoiceDownloadTarget: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: (...args: unknown[]) => mocks.verifyUserHasPermission(...args) }));
|
||||
vi.mock("~/services/billing/customer-invoices.server", () => ({
|
||||
CustomerBillingInvoiceError: class CustomerBillingInvoiceError extends Error {
|
||||
override readonly name = "CustomerBillingInvoiceError";
|
||||
readonly i18nKey: string;
|
||||
constructor(readonly code: "CONFIGURATION_MISSING" | "INVOICE_NOT_FOUND" | "DOWNLOAD_UNAVAILABLE") {
|
||||
super(code);
|
||||
this.i18nKey = `settings.subscription.errors.${code}`;
|
||||
}
|
||||
},
|
||||
getCustomerBillingInvoiceDownloadTarget: (...args: unknown[]) => mocks.getCustomerBillingInvoiceDownloadTarget(...args),
|
||||
}));
|
||||
|
||||
import { loader } from "./invoices.$invoiceId.download";
|
||||
|
||||
function callLoader(params: Record<string, string | undefined> = { tenant: "acme", invoiceId: "invoice_1" }) {
|
||||
return loader({
|
||||
request: new Request("https://app.example.test/acme/settings/subscription/invoices/invoice_1/download"),
|
||||
params,
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/subscription/invoices.$invoiceId.download",
|
||||
} as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("customer invoice download route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
|
||||
mocks.getTenantIdFromUrl.mockResolvedValue("tenant_1");
|
||||
mocks.verifyUserHasPermission.mockResolvedValue(undefined);
|
||||
mocks.getCustomerBillingInvoiceDownloadTarget.mockResolvedValue({
|
||||
fileUrl: "https://files.example.test/invoice_1.pdf",
|
||||
filename: "invoice_1.pdf",
|
||||
});
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response("pdf", { headers: { "content-type": "application/pdf" } }))
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("checks invoice permission before streaming the generated Lago PDF", async () => {
|
||||
const response = (await callLoader()) as Response;
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
await expect(response.text()).resolves.toBe("pdf");
|
||||
expect(response.headers.get("Content-Type")).toContain("application/pdf");
|
||||
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="invoice_1.pdf"');
|
||||
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.invoices.view", "tenant_1");
|
||||
expect(mocks.getCustomerBillingInvoiceDownloadTarget).toHaveBeenCalledWith({ tenantId: "tenant_1", invoiceId: "invoice_1" });
|
||||
expect(fetch).toHaveBeenCalledWith("https://files.example.test/invoice_1.pdf", { headers: { accept: "application/pdf,*/*" } });
|
||||
});
|
||||
|
||||
it("returns a localized 404 when the invoice does not belong to the tenant", async () => {
|
||||
const { CustomerBillingInvoiceError } = await import("~/services/billing/customer-invoices.server");
|
||||
mocks.getCustomerBillingInvoiceDownloadTarget.mockRejectedValueOnce(new CustomerBillingInvoiceError("INVOICE_NOT_FOUND"));
|
||||
|
||||
await expect(callLoader()).rejects.toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a localized 404 when the upstream PDF cannot be loaded", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("missing", { status: 404 })));
|
||||
|
||||
await expect(callLoader()).rejects.toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
});
|
||||
});
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { type LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getCustomerBillingInvoiceDownloadTarget, CustomerBillingInvoiceError } from "~/services/billing/customer-invoices.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
function invoiceErrorStatus(error: unknown): number {
|
||||
if (error instanceof CustomerBillingInvoiceError) {
|
||||
return error.code === "CONFIGURATION_MISSING" ? 503 : 404;
|
||||
}
|
||||
return 503;
|
||||
}
|
||||
|
||||
function invoiceErrorKey(error: unknown): string {
|
||||
if (error instanceof CustomerBillingInvoiceError) return error.i18nKey;
|
||||
return "settings.subscription.errors.DOWNLOAD_UNAVAILABLE";
|
||||
}
|
||||
|
||||
function contentDispositionFilename(filename: string): string {
|
||||
return filename.replace(/["\\\r\n]/gu, "_");
|
||||
}
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.invoices.view", tenantId);
|
||||
|
||||
const invoiceId = params.invoiceId?.trim();
|
||||
if (!invoiceId) {
|
||||
const { t } = await getTranslations(request);
|
||||
throw new Response(t("settings.subscription.errors.INVOICE_NOT_FOUND"), { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
const target = await getCustomerBillingInvoiceDownloadTarget({ tenantId, invoiceId });
|
||||
const upstream = await fetch(target.fileUrl, { headers: { accept: "application/pdf,*/*" } });
|
||||
if (!upstream.ok || !upstream.body) {
|
||||
throw new CustomerBillingInvoiceError("DOWNLOAD_UNAVAILABLE");
|
||||
}
|
||||
return new Response(upstream.body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": upstream.headers.get("content-type") || "application/pdf",
|
||||
"Content-Disposition": `attachment; filename="${contentDispositionFilename(target.filename)}"`,
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
const { t } = await getTranslations(request);
|
||||
throw new Response(t(invoiceErrorKey(error)), { status: invoiceErrorStatus(error) });
|
||||
}
|
||||
}
|
||||
+4
-5
@@ -7,9 +7,12 @@ const sourceFiles = [
|
||||
"apps/web/app/components/core/tenants/UpdateTenantDetailsForm.tsx",
|
||||
"apps/web/app/components/core/tenants/DeactivateTenantModal.tsx",
|
||||
"apps/web/app/components/core/tenants/TenantsTable.tsx",
|
||||
// R-P2b: members settings render through the D-P2 screens (VM as prop).
|
||||
"apps/web/app/components/screens/users/MembersPage.tsx",
|
||||
"apps/web/app/components/screens/users/InviteMemberForm.tsx",
|
||||
"apps/web/app/components/core/roles/RolesTable.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/groups.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/account.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/api/docs.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/api/index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/api/keys.tsx",
|
||||
"apps/web/app/routes/app.$tenant/settings/api/keys/$id.tsx",
|
||||
@@ -48,18 +51,15 @@ const sourceFiles = [
|
||||
describe("tenant settings i18n", () => {
|
||||
it("uses semantic translation keys for visible tenant settings labels", () => {
|
||||
const source = sourceFiles.map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
|
||||
const roleUsersSource = fs.readFileSync(path.join(repoRoot, "apps/web/app/routes/app.$tenant/settings/roles-and-permissions/users.tsx"), "utf8");
|
||||
|
||||
expect(source).toContain("settings.tenant.iconAlt");
|
||||
expect(source).toContain("settings.tenant.deactivation.title");
|
||||
expect(source).toContain("settings.tenant.billing.lastInvoice");
|
||||
expect(source).toContain("models.event.plural");
|
||||
expect(source).toContain("settings.groups.disabled.title");
|
||||
expect(source).toContain("settings.members.groups.createTitle");
|
||||
expect(source).toContain("settings.members.errors.createInvitationFailed");
|
||||
expect(source).toContain('settings.members.actions.removeConfirm", { email:');
|
||||
expect(source).toContain("models.permission.count");
|
||||
expect(roleUsersSource).toContain('title: `${t("models.permission.userRoles")} | ${process.env.APP_NAME}`');
|
||||
expect(source).toContain("createLocaleFormatters");
|
||||
expect(source).toContain("formatters.currency");
|
||||
expect(source).toContain("formatters.number");
|
||||
@@ -69,7 +69,6 @@ describe("tenant settings i18n", () => {
|
||||
expect(source).not.toContain("NumberUtils");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('process.env.APP_NAME ?? "App"');
|
||||
expect(roleUsersSource).not.toContain('title: `${t("models.role.adminRoles")} | ${process.env.APP_NAME}`');
|
||||
expect(source).not.toContain("i.types.map((f) => f.title).join");
|
||||
expect(source).not.toContain("name: f.title");
|
||||
expect(source).not.toContain("Could not create invitation");
|
||||
|
||||
+24
-2
@@ -1,11 +1,14 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenantWithProfile, updateTenantTheme, TenantWithProfile } from "~/utils/db/tenants.db.server";
|
||||
import { getTenantWithProfile, updateTenantTheme, updateTenantAnrede, TenantWithProfile } from "~/utils/db/tenants.db.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import UpdateTenantFormTheme from "~/components/core/tenants/forms/UpdateTenantFormTheme";
|
||||
import UpdateTenantFormAnrede from "~/components/core/tenants/forms/UpdateTenantFormAnrede";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { isAnrede } from "@hivegrid/i18n";
|
||||
import { anredeCookie } from "~/locale/anrede.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
@@ -55,6 +58,22 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (action === "update-anrede") {
|
||||
const anrede = form.get("anrede")?.toString();
|
||||
if (!isAnrede(anrede)) {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
try {
|
||||
// Persist the tenant-wide default and pin the choice for this browser via
|
||||
// the `_anrede` cookie so it takes effect immediately on revalidation.
|
||||
await updateTenantAnrede(tenantId, anrede);
|
||||
return Response.json({ success: t("shared.updated") }, { headers: { "Set-Cookie": await anredeCookie.serialize(anrede) } });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return badRequest({ error: t("shared.unexpectedError") });
|
||||
}
|
||||
}
|
||||
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
@@ -65,7 +84,10 @@ export default function ThemeSettingsRoute() {
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
<UpdateTenantFormTheme tenant={data.tenant} />
|
||||
<div className="space-y-6">
|
||||
<UpdateTenantFormAnrede tenant={data.tenant} />
|
||||
<UpdateTenantFormTheme tenant={data.tenant} />
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
import { BILLING_MODULE_KEY, getBillingUsageSummary } from "~/utils/services/.server/billingStatusService";
|
||||
|
||||
type LoaderData = Awaited<ReturnType<typeof getBillingUsageSummary>>;
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.view", tenantId);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const hasBillingModule = await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BILLING_MODULE_KEY });
|
||||
if (!hasBillingModule) {
|
||||
throw redirect(appTenantPlanRequiredPath(params));
|
||||
}
|
||||
return await getBillingUsageSummary(tenantId);
|
||||
};
|
||||
|
||||
export default function BillingUsageRoute() {
|
||||
const { t } = useTranslation("billing");
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("usage.title")}>
|
||||
<SettingSection title={t("usage.currentPeriod")} description={t("usage.description")}>
|
||||
<dl className="grid gap-3 sm:grid-cols-2">
|
||||
{data.metrics.length === 0 ? (
|
||||
<div className="text-muted-foreground rounded-md border p-4 text-sm">{t("usage.empty")}</div>
|
||||
) : (
|
||||
data.metrics.map((metric) => (
|
||||
<div key={metric.metricCode} className="rounded-md border p-4">
|
||||
<dt className="text-muted-foreground text-sm">{t(`usage.metrics.${metric.metricCode}`)}</dt>
|
||||
<dd className="text-2xl font-semibold">{metric.quantity}</dd>
|
||||
{metric.quota === null ? (
|
||||
<p className="text-muted-foreground mt-2 text-sm">{t("usage.unlimited")}</p>
|
||||
) : (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="text-muted-foreground flex items-center justify-between text-xs">
|
||||
<span>{t("usage.quota", { quota: metric.quota })}</span>
|
||||
<span>{t("usage.remaining", { remaining: metric.remaining })}</span>
|
||||
</div>
|
||||
<div className="bg-muted h-2 overflow-hidden rounded">
|
||||
<div className={metric.exceeded ? "h-full bg-destructive" : "bg-primary h-full"} style={{ width: `${metric.percentUsed ?? 0}%` }} />
|
||||
</div>
|
||||
{metric.exceeded ? <p className="text-destructive text-sm">{t("usage.limitExceeded")}</p> : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</dl>
|
||||
</SettingSection>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user