Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,9 @@
|
||||
import Page404 from "~/components/pages/Page404";
|
||||
|
||||
export default function AdminRoute404() {
|
||||
return (
|
||||
<>
|
||||
<Page404 withLogo={false} withFooter={false} withGoBack={false} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowEngineApi } from "~/modules/workflowEngine/routes/workflow-engine.api.server";
|
||||
import WorkflowEngineView from "~/modules/workflowEngine/routes/workflow-engine.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowEngineApi.loader(args);
|
||||
// export const action = (args: ActionFunctionArgs) => WorkflowEngineApi.action(args);
|
||||
|
||||
export default () => <WorkflowEngineView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdExecutionsApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.executions.api.server";
|
||||
import WorkflowsIdExecutionsView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.executions.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdExecutionsApi.loader(args);
|
||||
// export const action = (args: ActionFunctionArgs) => WorkflowsIdExecutionsApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdExecutionsView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdRunApiApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.api.server";
|
||||
import WorkflowsIdRunApiApiView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.api.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdRunApiApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIdRunApiApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdRunApiApiView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdRunManualApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.manual.api.server";
|
||||
import WorkflowsIdRunManualView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.manual.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdRunManualApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIdRunManualApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdRunManualView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { workflowExecutionStreamLoader } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.stream.$executionId.server";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => workflowExecutionStreamLoader(args);
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdRunStreamApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.stream.api.server";
|
||||
import WorkflowsIdRunStreamView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.stream.view";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
|
||||
export const meta: v2MetaFunction<WorkflowsIdRunStreamApi.LoaderData> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdRunStreamApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIdRunStreamApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdRunStreamView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdIndexApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.index.api.server";
|
||||
import WorkflowsIdIndexView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.index.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdIndexApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIdIndexApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdIndexView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsCredentialsApi } from "~/modules/workflowEngine/routes/workflow-engine/credentials.api.server";
|
||||
import WorkflowsCredentialsView from "~/modules/workflowEngine/routes/workflow-engine/credentials.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsCredentialsApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsCredentialsApi.action(args);
|
||||
|
||||
export default () => <WorkflowsCredentialsView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsCredentialsNewApi } from "~/modules/workflowEngine/routes/workflow-engine/credentials/credentials.new.api.server";
|
||||
import WorkflowsCredentialsNewView from "~/modules/workflowEngine/routes/workflow-engine/credentials/credentials.new.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsCredentialsNewApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsCredentialsNewApi.action(args);
|
||||
|
||||
export default () => <WorkflowsCredentialsNewView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsDangerApi } from "~/modules/workflowEngine/routes/workflow-engine/danger.api.server";
|
||||
import WorkflowsDangerView from "~/modules/workflowEngine/routes/workflow-engine/danger.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsDangerApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsDangerApi.action(args);
|
||||
|
||||
export default () => <WorkflowsDangerView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsExecutionsApi } from "~/modules/workflowEngine/routes/workflow-engine/executions.api.server";
|
||||
import WorkflowsExecutionsView from "~/modules/workflowEngine/routes/workflow-engine/executions.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsExecutionsApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsExecutionsApi.action(args);
|
||||
|
||||
export default () => <WorkflowsExecutionsView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowEngineIndexApi } from "~/modules/workflowEngine/routes/workflow-engine/index.api.server";
|
||||
import WorkflowEngineIndexView from "~/modules/workflowEngine/routes/workflow-engine/index.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowEngineIndexApi.loader(args);
|
||||
// export const action = (args: ActionFunctionArgs) => WorkflowEngineIndexApi.action(args);
|
||||
|
||||
export default () => <WorkflowEngineIndexView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsTemplatesApi } from "~/modules/workflowEngine/routes/workflow-engine/templates.api.server";
|
||||
import WorkflowsTemplatesView from "~/modules/workflowEngine/routes/workflow-engine/templates.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsTemplatesApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsTemplatesApi.action(args);
|
||||
|
||||
export default () => <WorkflowsTemplatesView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsVariablesApi } from "~/modules/workflowEngine/routes/workflow-engine/variables.api.server";
|
||||
import WorkflowsVariablesView from "~/modules/workflowEngine/routes/workflow-engine/variables.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsVariablesApi.loader(args);
|
||||
// export const action = (args: ActionFunctionArgs) => WorkflowsVariablesApi.action(args);
|
||||
|
||||
export default () => <WorkflowsVariablesView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsVariablesIdApi } from "~/modules/workflowEngine/routes/workflow-engine/variables/variables.$id.api.server";
|
||||
import WorkflowsVariablesIdView from "~/modules/workflowEngine/routes/workflow-engine/variables/variables.$id.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsVariablesIdApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsVariablesIdApi.action(args);
|
||||
|
||||
export default () => <WorkflowsVariablesIdView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsVariablesNewApi } from "~/modules/workflowEngine/routes/workflow-engine/variables/variables.new.api.server";
|
||||
import WorkflowsVariablesNewView from "~/modules/workflowEngine/routes/workflow-engine/variables/variables.new.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsVariablesNewApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsVariablesNewApi.action(args);
|
||||
|
||||
export default () => <WorkflowsVariablesNewView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIndexApi } from "~/modules/workflowEngine/routes/workflow-engine/workflows.index.api.server";
|
||||
import WorkflowsIndexView from "~/modules/workflowEngine/routes/workflow-engine/workflows.index.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIndexApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIndexApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIndexView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import UserIcon from "~/components/ui/icons/UserIcon";
|
||||
import CustomerIcon from "~/components/ui/icons/settings/CustomerIcon";
|
||||
import CustomerIconFilled from "~/components/ui/icons/settings/CustomerIconFilled";
|
||||
import CompanyIcon from "~/components/ui/icons/crm/CompanyIcon";
|
||||
import CompanyIconFilled from "~/components/ui/icons/crm/CompanyIconFilled";
|
||||
import { LinkIcon, LockIcon, NoSymbolIcon, ServerStackIcon } from "~/components/ui/icons/vendor";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const data: LoaderData = {
|
||||
title: "",
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration } = useRootData();
|
||||
return <Outlet />;
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("admin.tenants.title"),
|
||||
href: adminPath("accounts", { mode: "host-aware" }),
|
||||
exact: true,
|
||||
// permission: "admin.accounts.view",
|
||||
icon: <CompanyIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <CompanyIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
name: t("models.user.plural"),
|
||||
href: adminPath("accounts/users", { mode: "host-aware" }),
|
||||
// permission: "admin.users.view",
|
||||
icon: <CustomerIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <CustomerIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
name: t("app.sidebar.rolesAndPermissions"),
|
||||
href: adminPath("accounts/roles-and-permissions", { mode: "host-aware" }),
|
||||
// permission: "admin.roles.view",
|
||||
icon: <LockIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <LockIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.navigation.relationships"),
|
||||
href: adminPath("accounts/relationships", { mode: "host-aware" }),
|
||||
// permission: "admin.relationships.view",
|
||||
hidden: !appConfiguration.app.features.tenantTypes,
|
||||
icon: <LinkIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <LinkIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.navigation.subscriptions"),
|
||||
href: adminPath("accounts/subscriptions", { mode: "host-aware" }),
|
||||
// permission: "admin.relationships.view",
|
||||
hidden: true,
|
||||
},
|
||||
{
|
||||
name: t("models.blacklist.object"),
|
||||
href: adminPath("accounts/blacklist", { mode: "host-aware" }),
|
||||
// permission: "admin.blacklist.view",
|
||||
icon: <NoSymbolIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <NoSymbolIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
name: t("models.tenantIpAddress.plural"),
|
||||
href: adminPath("accounts/ip-addresses", { mode: "host-aware" }),
|
||||
// permission: "admin.tenantIpAddress.view",
|
||||
icon: <ServerStackIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <ServerStackIcon className="text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData, useParams, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenant, getTenantBySlug, getTenantUsers, updateTenant, type TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import UpdateTenantDetailsForm from "~/components/core/tenants/UpdateTenantDetailsForm";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import UsersTable from "~/components/core/users/UsersTable";
|
||||
import { adminGetAllTenantUsers, getUser } from "~/utils/db/users.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import {
|
||||
getOrPersistTenantSubscription,
|
||||
getTenantSubscription,
|
||||
updateTenantSubscriptionCustomerId,
|
||||
type TenantSubscriptionWithDetails,
|
||||
} from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { createStripeCustomer, isStripeTestMode } from "~/utils/stripe.server";
|
||||
import { Fragment, useEffect, useRef } from "react";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessModal";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { deleteAndCancelTenant, isReservedTenantSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { findEntityByName, type EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { getAllTenantTypes, getTenantTypeOptions } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import { AccountUpdatedDto } from "~/modules/events/dtos/AccountUpdatedDto";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenant: TenantWithDetails;
|
||||
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
isStripeTest: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
tenantTypes: Awaited<ReturnType<typeof getTenantTypeOptions>>;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenant = await getTenant(params.id!);
|
||||
if (!tenant) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
const [users, subscription, subscriptionProducts, tenantSettingsEntity, tenantTypes] = await Promise.all([
|
||||
adminGetAllTenantUsers(tenant.id),
|
||||
getTenantSubscription(params.id ?? ""),
|
||||
getAllSubscriptionProducts(),
|
||||
findEntityByName({ tenantId: null, name: "tenantSettings" }),
|
||||
getTenantTypeOptions(),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.object")} | ${process.env.APP_NAME}`,
|
||||
tenant,
|
||||
users,
|
||||
subscription,
|
||||
subscriptionProducts,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
tenantSettingsEntity,
|
||||
tenantTypes,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
updateSubscriptionSuccess?: string;
|
||||
updateDetailsError?: string;
|
||||
updateSubscriptionError?: string;
|
||||
};
|
||||
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.account.settings.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const currentUser = await getUser(userInfo.userId);
|
||||
if (!currentUser) {
|
||||
return badRequest({ updateDetailsError: t("shared.invalidUser") });
|
||||
}
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
const tenant = await getTenant(params.id ?? "");
|
||||
if (!tenant) {
|
||||
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const icon = form.get("icon")?.toString() ?? "";
|
||||
const typeIds = form.getAll("typeIds[]").map((t) => t.toString());
|
||||
|
||||
if ((name?.length ?? 0) < 1) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.nameRequired"),
|
||||
});
|
||||
}
|
||||
if (!slug || slug.length < 1) {
|
||||
return badRequest({ updateDetailsError: t("settings.tenant.errors.slugRequired") });
|
||||
}
|
||||
|
||||
let tenantTypes = await getAllTenantTypes();
|
||||
typeIds.forEach((type) => {
|
||||
if (!tenantTypes.find((t) => t.id === type)) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("admin.accounts.errors.invalidTenantType"),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (isReservedTenantSlug(slug)) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.reservedSlug", { slug }),
|
||||
});
|
||||
}
|
||||
if (slug.includes(" ")) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugWhitespace"),
|
||||
});
|
||||
}
|
||||
|
||||
const existing = await getTenant(params.id!);
|
||||
if (!existing) {
|
||||
return badRequest({ updateDetailsError: t("admin.accounts.errors.invalidTenant") });
|
||||
}
|
||||
|
||||
if (existing.slug !== slug) {
|
||||
const existingSlug = await getTenantBySlug(slug);
|
||||
if (existingSlug) {
|
||||
return badRequest({
|
||||
updateDetailsError: t("settings.tenant.errors.slugTaken"),
|
||||
});
|
||||
}
|
||||
}
|
||||
await createAdminLog(request, "settings.tenant.updateDetails", JSON.stringify({ name, slug }));
|
||||
|
||||
const tenantSettingsEntity = await findEntityByName({ tenantId: null, name: "tenantSettings" });
|
||||
if (tenantSettingsEntity) {
|
||||
try {
|
||||
await RowsApi.createCustom({
|
||||
entity: tenantSettingsEntity,
|
||||
tenantId: existing.id,
|
||||
t,
|
||||
form,
|
||||
row: existing?.tenantSettingsRow?.row as Parameters<typeof RowsApi.createCustom>[0]["row"],
|
||||
rowCreateInput: { tenantSettingsRow: { create: { tenantId: existing.id } } },
|
||||
request,
|
||||
});
|
||||
} catch {
|
||||
return badRequest({ updateDetailsError: t("admin.accounts.errors.updateDetailsFailed") });
|
||||
}
|
||||
}
|
||||
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.updated",
|
||||
tenantId: tenant.id,
|
||||
userId: currentUser.id,
|
||||
data: {
|
||||
id: tenant.id,
|
||||
new: { name, slug },
|
||||
old: { name: tenant.name, slug: tenant.slug },
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies AccountUpdatedDto,
|
||||
});
|
||||
await updateTenant(existing, { name, icon, slug, typeIds });
|
||||
return Response.json({
|
||||
success: t("settings.tenant.updated"),
|
||||
});
|
||||
} else if (action === "create-stripe-customer") {
|
||||
if (!tenant) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.invalidTenant") });
|
||||
}
|
||||
const tenantUsers = await getTenantUsers(params.id ?? "");
|
||||
if (tenantUsers.length === 0) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.noUsers") });
|
||||
}
|
||||
const tenantOwner = tenantUsers.find((user) => user.type === TenantUserType.OWNER);
|
||||
if (!tenantOwner) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.noOwner") });
|
||||
}
|
||||
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
|
||||
if (tenantSubscription.stripeCustomerId) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.customerAlreadySet") });
|
||||
}
|
||||
const stripeCustomer = await createStripeCustomer(tenantOwner.user.email, tenant.name);
|
||||
if (!stripeCustomer) {
|
||||
return badRequest({ updateSubscriptionError: t("admin.accounts.subscriptionCustomer.errors.createFailed") });
|
||||
}
|
||||
await updateTenantSubscriptionCustomerId(tenant.id, {
|
||||
stripeCustomerId: stripeCustomer.id,
|
||||
});
|
||||
const data: ActionData = {
|
||||
updateSubscriptionSuccess: t("admin.accounts.subscriptionCustomer.actions.created"),
|
||||
};
|
||||
return data;
|
||||
} else if (action === "delete-tenant") {
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.deleted",
|
||||
tenantId: null,
|
||||
userId: userInfo.userId,
|
||||
data: { tenant: { id: tenant.id, name: tenant.name }, user: { id: currentUser.id, email: currentUser.email } } satisfies AccountDeletedDto,
|
||||
});
|
||||
await deleteAndCancelTenant({ tenantId: tenant.id, userId: currentUser.id });
|
||||
return redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
} else {
|
||||
return badRequest({ updateDetailsError: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function TenantRoute() {
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
const successModal = useRef<RefSuccessModal>(null);
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.updateSubscriptionSuccess) {
|
||||
successModal.current?.show(actionData?.updateSubscriptionSuccess);
|
||||
} else if (actionData?.updateSubscriptionError) {
|
||||
errorModal.current?.show(actionData?.updateSubscriptionError);
|
||||
} else if (actionData?.updateDetailsError) {
|
||||
errorModal.current?.show(actionData?.updateDetailsError);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function deleteAccount() {
|
||||
confirmDelete.current?.show(t("settings.danger.confirmDeleteTenant"), t("shared.confirm"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
function confirmDeleteTenant() {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete-tenant");
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={data.tenant.name}
|
||||
menu={[
|
||||
{ title: t("models.tenant.plural"), routePath: adminPath("accounts", { mode: "host-aware" }) },
|
||||
{ title: data.tenant?.name ?? "", routePath: adminPath(`accounts/${params.id ?? ""}`, { mode: "host-aware" }) },
|
||||
]}
|
||||
>
|
||||
<SettingSection title={t("settings.tenant.general")} description={t("settings.tenant.generalDescription")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UpdateTenantDetailsForm
|
||||
tenant={data.tenant}
|
||||
disabled={!getUserHasPermission(adminData, "admin.account.settings.update")}
|
||||
tenantSettingsEntity={data.tenantSettingsEntity}
|
||||
tenantTypes={data.tenantTypes}
|
||||
options={{
|
||||
canChangeType: true,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tenant Users */}
|
||||
{getUserHasPermission(adminData, "admin.account.users") && (
|
||||
<Fragment>
|
||||
<SettingSection title={t("models.user.plural")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<UsersTable
|
||||
items={data.users}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canSetUserRoles={false}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
/>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
{/* Tenant Subscription */}
|
||||
{/* {getUserHasPermission(adminData, "admin.account.subscription") && (
|
||||
<>
|
||||
<div className="md:grid lg:grid-cols-3 md:gap-2">
|
||||
<div className="md:col-span-1">
|
||||
<div className="sm:px-0">
|
||||
<h3 className="text-lg font-medium leading-6 text-foreground">{t("models.subscriptionProduct.object")}</h3>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 md:mt-0 md:col-span-2">
|
||||
<UpdateTenantSubscriptionForm
|
||||
tenant={data.tenant}
|
||||
subscription={data.subscription}
|
||||
subscriptionProducts={data.subscriptionProducts}
|
||||
isStripeTest={data.isStripeTest}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-t border-border"></div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)} */}
|
||||
|
||||
{/*Danger */}
|
||||
{getUserHasPermission(adminData, "admin.account.delete") && (
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")}>
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
<div className="">
|
||||
<div className="">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("admin.accounts.danger.deleteAccountTitle")}</h3>
|
||||
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
||||
<p>{t("admin.accounts.danger.deleteAccountDescription")}</p>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<ButtonPrimary destructive={true} onClick={deleteAccount}>
|
||||
{t("settings.danger.deleteAccount")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
)}
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteTenant} />
|
||||
<SuccessModal ref={successModal} />
|
||||
<ErrorModal ref={errorModal} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
translateIpAddressLogAction,
|
||||
translateIpAddressLogDescription,
|
||||
translateIpAddressLogError,
|
||||
} from "./ip-address-log-labels";
|
||||
|
||||
const t = ((key: string, options?: Record<string, unknown>) => (options?.value ? `${key}:${String(options.value)}` : key)) as TFunction;
|
||||
|
||||
describe("IP address log labels", () => {
|
||||
it("translates known action codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogAction(t, "login")).toBe("admin.accounts.ipAddresses.logs.actions.login");
|
||||
expect(translateIpAddressLogAction(t, "register")).toBe("admin.accounts.ipAddresses.logs.actions.register");
|
||||
expect(translateIpAddressLogAction(t, "reset")).toBe("admin.accounts.ipAddresses.logs.actions.reset");
|
||||
expect(translateIpAddressLogAction(t, "forgot-password")).toBe("admin.accounts.ipAddresses.logs.actions.forgotPassword");
|
||||
expect(translateIpAddressLogAction(t, "reset-password")).toBe("admin.accounts.ipAddresses.logs.actions.resetPassword");
|
||||
expect(translateIpAddressLogAction(t, " custom-action ")).toBe("admin.accounts.ipAddresses.logs.actions.unknownWithValue:custom-action");
|
||||
expect(translateIpAddressLogAction(t, " ")).toBe("");
|
||||
});
|
||||
|
||||
it("translates known description codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogDescription(t, "registration-attempt")).toBe("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
|
||||
expect(translateIpAddressLogDescription(t, "{empty email}")).toBe("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
|
||||
expect(translateIpAddressLogDescription(t, "custom description")).toBe("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue:custom description");
|
||||
expect(translateIpAddressLogDescription(t, null)).toBe("");
|
||||
});
|
||||
|
||||
it("translates known error codes and wraps unknown values in a semantic key", () => {
|
||||
expect(translateIpAddressLogError(t, "blacklisted")).toBe("admin.accounts.ipAddresses.errors.blacklisted");
|
||||
expect(translateIpAddressLogError(t, "Unauthorized.")).toBe("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
expect(translateIpAddressLogError(t, "provider error")).toBe("admin.accounts.ipAddresses.errors.unknownWithValue:provider error");
|
||||
});
|
||||
});
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
export function translateIpAddressLogAction(t: TFunction, action?: string | null) {
|
||||
const normalized = action?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "login") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.login");
|
||||
}
|
||||
if (normalized === "register") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.register");
|
||||
}
|
||||
if (normalized === "reset") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.reset");
|
||||
}
|
||||
if (normalized === "forgot-password") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.forgotPassword");
|
||||
}
|
||||
if (normalized === "reset-password") {
|
||||
return t("admin.accounts.ipAddresses.logs.actions.resetPassword");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.logs.actions.unknownWithValue", { value: normalized });
|
||||
}
|
||||
|
||||
export function translateIpAddressLogDescription(t: TFunction, description?: string | null) {
|
||||
const normalized = description?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "registration-attempt") {
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
|
||||
}
|
||||
if (normalized === "{empty email}") {
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue", { value: normalized });
|
||||
}
|
||||
|
||||
export function translateIpAddressLogError(t: TFunction, error?: string | null) {
|
||||
const normalized = error?.trim();
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
if (normalized === "blacklisted" || normalized === "Blacklisted") {
|
||||
return t("admin.accounts.ipAddresses.errors.blacklisted");
|
||||
}
|
||||
if (normalized === "unauthorized" || normalized === "Unauthorized" || normalized === "Unauthorized.") {
|
||||
return t("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
}
|
||||
return t("admin.accounts.ipAddresses.errors.unknownWithValue", { value: normalized });
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { IpAddressLog } from "@toolctrl/db/prisma-browser";
|
||||
import { getAllIpAddressLogs } from "~/modules/ipAddress/db/ipAddressLogs.db.server";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { addToBlacklist, findInBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useSubmit } from "react-router";
|
||||
import { db } from "~/utils/db.server";
|
||||
import DropdownSimple from "~/components/ui/dropdowns/DropdownSimple";
|
||||
import DownArrow from "~/components/ui/icons/DownArrow";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { translateIpAddressLogAction, translateIpAddressLogDescription, translateIpAddressLogError } from "./ip-address-log-labels";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: IpAddressLog[];
|
||||
pagination: PaginationDto;
|
||||
blacklistedIps: string[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.tenantIpAddress.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await getAllIpAddressLogs(currentPagination);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.ipAddress.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
pagination,
|
||||
blacklistedIps: await db.blacklist
|
||||
.findMany({
|
||||
where: { type: "ip" },
|
||||
select: { value: true },
|
||||
})
|
||||
.then((items) => items.flatMap((i) => i.value)),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.manage");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action") as string;
|
||||
if (action === "blacklist-ip") {
|
||||
const ip = form.get("ip")?.toString() ?? "";
|
||||
const existing = await findInBlacklist("ip", ip);
|
||||
if (existing) {
|
||||
return Response.json({ error: t("admin.accounts.ipAddresses.actions.alreadyBlacklisted") }, { status: 400 });
|
||||
} else {
|
||||
await addToBlacklist({
|
||||
type: "ip",
|
||||
value: ip,
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.blacklisted") });
|
||||
}
|
||||
} else if (action === "delete-log") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
await db.ipAddressLog.delete({ where: { id } });
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.logDeleted") });
|
||||
} else if (action === "delete-logs") {
|
||||
const ids = form.getAll("id").map((i) => i.toString());
|
||||
const deleted = await db.ipAddressLog.deleteMany({ where: { id: { in: ids } } });
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.logsDeleted", { count: deleted.count }) });
|
||||
} else {
|
||||
return Response.json({ error: t("admin.accounts.ipAddresses.actions.invalidAction") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ success?: string; error?: string }>();
|
||||
const submit = useSubmit();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
const [items, setItems] = useState<IpAddressLog[]>(data.items);
|
||||
const [selected, setSelected] = useState<IpAddressLog[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
setItems(data.items);
|
||||
}, [data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
const selectedCount = selected.length;
|
||||
const formattedSelectedCount = formatters.number(selectedCount);
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.accounts.ipAddresses.tabs.ipAddresses"),
|
||||
routePath: adminPath("accounts/ip-addresses", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.ipAddresses.tabs.logs"),
|
||||
routePath: adminPath("accounts/ip-addresses/logs", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
buttons={<></>}
|
||||
>
|
||||
{selectedCount > 0 && (
|
||||
<DropdownSimple
|
||||
right
|
||||
button={
|
||||
<div className="hover:bg-secondary border-border bg-background text-foreground/80 flex items-center space-x-2 rounded-md border px-2 py-1 text-sm">
|
||||
<div>{t("admin.accounts.ipAddresses.selection.selected", { count: selectedCount, formattedCount: formattedSelectedCount })}</div>
|
||||
<DownArrow className="h-4 w-4" />
|
||||
</div>
|
||||
}
|
||||
items={[
|
||||
{
|
||||
label: t("admin.accounts.ipAddresses.actions.deleteSelectedLogs", { count: selectedCount, formattedCount: formattedSelectedCount }),
|
||||
onClick: () => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-logs");
|
||||
selected.forEach((i) => form.append("id", i.id));
|
||||
setSelected([]);
|
||||
setItems((prev) => prev.filter((p) => !selected.includes(p)));
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<TableSimple
|
||||
items={items}
|
||||
selectedRows={selected}
|
||||
onSelected={setSelected}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.accounts.ipAddresses.actions.blacklistIp"),
|
||||
destructive: true,
|
||||
onClick: (_, i) => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "blacklist-ip");
|
||||
form.set("ip", i.ip);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t("shared.delete"),
|
||||
destructive: true,
|
||||
onClick: (_, i) => {
|
||||
setSelected((prev) => prev.filter((p) => p.id !== i.id));
|
||||
setItems((prev) => prev.filter((p) => p.id !== i.id));
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-log");
|
||||
form.set("id", i.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.dateTime(item.createdAt),
|
||||
formattedValue: (item) => <span title={formatters.dateTime(item.createdAt)}>{formatters.relativeDate(item.createdAt)}</span>,
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
title: t("shared.status"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
{i.success ? <SimpleBadge title={t("shared.success")} color={Colors.GREEN} /> : <SimpleBadge title={t("shared.error")} color={Colors.RED} />}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "ip",
|
||||
title: t("models.tenantIpAddress.object"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">
|
||||
{i.ip} {data.blacklistedIps.includes(i.ip) && <SimpleBadge title={t("admin.accounts.ipAddresses.table.blacklisted")} color={Colors.RED} />}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "action",
|
||||
title: t("admin.accounts.ipAddresses.table.action"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{translateIpAddressLogAction(t, i.action)}</div>
|
||||
<div className="text-muted-foreground text-xs">{translateIpAddressLogDescription(t, i.description)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: t("admin.accounts.ipAddresses.table.url"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="">{i.url}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "metadata",
|
||||
title: t("admin.accounts.ipAddresses.table.metadata"),
|
||||
value: (i) => (
|
||||
<div className="max-w-xs truncate">
|
||||
{i.metadata ? (
|
||||
<ShowPayloadModalButton description={i.metadata} payload={i.metadata} />
|
||||
) : (
|
||||
<div className="text-muted-foreground italic">{t("shared.notAvailable")}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "error",
|
||||
title: t("shared.error"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col text-red-500">
|
||||
<div className="font-medium">{translateIpAddressLogError(t, i.error)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
pagination={data.pagination}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { IpAddress } from "@toolctrl/db/prisma-browser";
|
||||
import { getAllIpAddresses } from "~/modules/ipAddress/db/ipAddresses.db.server";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { findInBlacklist, addToBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { useSubmit } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { db } from "~/utils/db.server";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { clearCacheKey } from "~/utils/cache.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: IpAddress[];
|
||||
pagination: PaginationDto;
|
||||
blacklistedIps: string[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.tenantIpAddress.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await getAllIpAddresses(currentPagination);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.ipAddress.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
pagination,
|
||||
blacklistedIps: await db.blacklist
|
||||
.findMany({
|
||||
where: { type: "ip" },
|
||||
select: { value: true },
|
||||
})
|
||||
.then((items) => items.flatMap((i) => i.value)),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.manage");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action") as string;
|
||||
if (action === "blacklist-ip") {
|
||||
const ip = form.get("ip")?.toString() ?? "";
|
||||
const existing = await findInBlacklist("ip", ip);
|
||||
if (existing) {
|
||||
return Response.json({ error: t("admin.accounts.ipAddresses.actions.alreadyBlacklisted") }, { status: 400 });
|
||||
} else {
|
||||
await addToBlacklist({
|
||||
type: "ip",
|
||||
value: ip,
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.blacklisted") });
|
||||
}
|
||||
} else if (action === "delete-ip") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
await db.ipAddress.delete({ where: { id } }).then((item) => {
|
||||
clearCacheKey(`ipAddress:${item.ip}`);
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.ipAddresses.actions.ipDeleted") });
|
||||
} else {
|
||||
return Response.json({ error: t("admin.accounts.ipAddresses.actions.invalidAction") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function IpAddresses() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ success?: string; error?: string }>();
|
||||
const submit = useSubmit();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.accounts.ipAddresses.tabs.ipAddresses"),
|
||||
routePath: adminPath("accounts/ip-addresses", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.ipAddresses.tabs.logs"),
|
||||
routePath: adminPath("accounts/ip-addresses/logs", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.accounts.ipAddresses.actions.blacklistIp"),
|
||||
destructive: true,
|
||||
onClick: (_, i) => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "blacklist-ip");
|
||||
form.set("ip", i.ip);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t("shared.delete"),
|
||||
destructive: true,
|
||||
onClick: (_, i) => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-ip");
|
||||
form.set("id", i.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
},
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "ip",
|
||||
title: t("models.tenantIpAddress.object"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">
|
||||
{i.ip} {i.type && <span className="text-muted-foreground text-xs font-light">({i.type})</span>}{" "}
|
||||
{data.blacklistedIps.includes(i.ip) && <SimpleBadge title={t("admin.accounts.ipAddresses.table.blacklisted")} color={Colors.RED} />}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">{i.provider}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: t("admin.accounts.ipAddresses.table.country"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{i.countryCode}</div>
|
||||
<div className="text-muted-foreground text-xs">{i.countryName}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "region",
|
||||
title: t("admin.accounts.ipAddresses.table.region"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{i.regionCode}</div>
|
||||
<div className="text-muted-foreground text-xs">{i.regionName}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: t("admin.accounts.ipAddresses.table.city"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{i.city}</div>
|
||||
<div className="text-muted-foreground text-xs">{i.zipCode}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "metadata",
|
||||
title: t("admin.accounts.ipAddresses.table.metadata"),
|
||||
value: (i) => <div className="max-w-xs truncate">{i.metadata && <ShowPayloadModalButton description={i.metadata} payload={i.metadata} />}</div>,
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.dateTime(item.createdAt),
|
||||
formattedValue: (item) => <span title={formatters.dateTime(item.createdAt)}>{formatters.relativeDate(item.createdAt)}</span>,
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
},
|
||||
]}
|
||||
pagination={data.pagination}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
const textCache = new Map<string, string>();
|
||||
const jsonCache = new Map<string, unknown>();
|
||||
|
||||
type AdminAccountSecurityTranslations = {
|
||||
admin: {
|
||||
accounts: {
|
||||
rolesAndPermissions: {
|
||||
tabs: {
|
||||
roles: string;
|
||||
permissions: string;
|
||||
adminUsers: string;
|
||||
accountUsers: string;
|
||||
};
|
||||
seed: {
|
||||
tab: string;
|
||||
};
|
||||
};
|
||||
ipAddresses: {
|
||||
actions: Record<string, string>;
|
||||
errors: Record<string, string>;
|
||||
logs: {
|
||||
actions: Record<string, string>;
|
||||
descriptions: Record<string, string>;
|
||||
};
|
||||
table: {
|
||||
blacklisted: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
function resolveRepoPath(file: string) {
|
||||
return path.join(repoRoot, file);
|
||||
}
|
||||
|
||||
function readRepoFile(file: string) {
|
||||
const resolved = resolveRepoPath(file);
|
||||
const cached = textCache.get(resolved);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const source = fs.readFileSync(resolved, "utf8");
|
||||
textCache.set(resolved, source);
|
||||
return source;
|
||||
}
|
||||
|
||||
function readJsonFile<T>(file: string) {
|
||||
const resolved = resolveRepoPath(file);
|
||||
if (!jsonCache.has(resolved)) {
|
||||
jsonCache.set(resolved, JSON.parse(readRepoFile(file)) as unknown);
|
||||
}
|
||||
|
||||
return jsonCache.get(resolved) as T;
|
||||
}
|
||||
|
||||
function readTranslations(locale: "en" | "de") {
|
||||
return readJsonFile<AdminAccountSecurityTranslations>(`apps/web/public/locales/${locale}/translations.json`);
|
||||
}
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-addresses.tsx",
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-address-log-labels.ts",
|
||||
"apps/web/app/routes/admin/accounts/__ip-addresses/ip-addresses.logs.tsx",
|
||||
"apps/web/app/routes/admin/accounts/blacklist.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/permissions/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/roles/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/roles/$id.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/seed.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.tsx",
|
||||
"apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users/$user.roles.tsx",
|
||||
"apps/web/app/routes/admin/accounts/users/new.tsx",
|
||||
"apps/web/app/routes/admin/accounts/$id.tsx",
|
||||
"apps/web/app/utils/helpers/PermissionsHelper.ts",
|
||||
"apps/web/app/components/core/roles/RolesAndPermissionsMatrix.tsx",
|
||||
];
|
||||
|
||||
describe("admin account security i18n", () => {
|
||||
it("uses semantic translation keys for visible account, role, and IP security copy", () => {
|
||||
const source = sourceFiles.map((file) => readRepoFile(file)).join("\n");
|
||||
|
||||
expect(source).toContain("admin.accounts.ipAddresses.actions.blacklistIp");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.actions.login");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.actions.register");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.actions.reset");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.errors.blacklisted");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.actions.unknownWithValue");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.errors.unknownWithValue");
|
||||
expect(source).toContain('normalized === "blacklisted"');
|
||||
expect(source).toContain('normalized === "unauthorized"');
|
||||
expect(source).toContain("formattedSelectedCount");
|
||||
expect(source).toContain("admin.accounts.ipAddresses.actions.deleteSelectedLogs");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.seed.tab");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.roles");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.permissions");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.adminUsers");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.tabs.accountUsers");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.seed.missingTitle");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.permissions.errors.existingPermission");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.existingRole");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId");
|
||||
expect(source).toContain("admin.accounts.rolesAndPermissions.roles.errors.updateFailed");
|
||||
expect(source).toContain("settings.tenant.errors.nameRequired");
|
||||
expect(source).toContain("settings.tenant.errors.slugRequired");
|
||||
expect(source).toContain("admin.accounts.errors.updateDetailsFailed");
|
||||
expect(source).toContain("models.blacklist.types.");
|
||||
expect(source).toContain("admin.accounts.subscriptionCustomer.errors.customerAlreadySet");
|
||||
expect(source).toContain("admin.accounts.subscriptionCustomer.actions.created");
|
||||
expect(source).toContain("admin.accounts.users.filters.hasLoggedIn");
|
||||
expect(source).toContain('app.shared.periods.LAST_N_MONTHS", { count: 6, formattedCount: "6" }');
|
||||
expect(source).toContain("admin.accounts.danger.deleteAccountTitle");
|
||||
expect(source).toContain("admin.permissions.entities.viewPage");
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.relativeDate");
|
||||
expect(source).toContain("models.permission.matrix.rolePermissionCount");
|
||||
expect(source).toContain("translateLabel(t, i18n, f.title)");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).toContain(
|
||||
'title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`'
|
||||
);
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).toContain(
|
||||
'title: t("admin.accounts.rolesAndPermissions.tabs.accountUsers")'
|
||||
);
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/admin-users.tsx")).toContain(
|
||||
'title: `${t("admin.accounts.rolesAndPermissions.tabs.adminUsers")} | ${process.env.APP_NAME}`'
|
||||
);
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).not.toContain("i18nT");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/roles.tsx")).not.toContain('from "i18next"');
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/permissions.tsx")).not.toContain('from "i18next"');
|
||||
expect(readRepoFile("apps/web/app/components/core/roles/RolesAndPermissionsMatrix.tsx")).not.toContain("i18nT");
|
||||
expect(source).not.toContain('name: "Seed"');
|
||||
expect(source).not.toContain("Existing permission with name:");
|
||||
expect(source).not.toContain("Existing role with name:");
|
||||
expect(source).not.toContain("Role not found with ID:");
|
||||
expect(source).not.toContain("Account name must have at least 1 character");
|
||||
expect(source).not.toContain("Account slug must have at least 1 character");
|
||||
expect(source).not.toContain("Stripe Customer already set");
|
||||
expect(source).not.toContain("Could not create stripe customer");
|
||||
expect(source).not.toContain("Stripe customer created");
|
||||
expect(source).not.toContain('from "~/utils/shared/DateUtils"');
|
||||
expect(source).not.toContain("i.types.map((f) => f.title).join");
|
||||
expect(source).not.toContain("{i.error}");
|
||||
expect(source).not.toContain("{i.action}");
|
||||
expect(source).not.toContain("{i.description}");
|
||||
expect(readRepoFile("apps/web/app/routes/admin/accounts/roles-and-permissions/account-users.$account.tsx")).not.toContain(
|
||||
'title: `${t("models.role.adminRoles")} | ${process.env.APP_NAME}`'
|
||||
);
|
||||
expect(source).not.toContain('t("models.permission.userRoles")');
|
||||
expect(source).not.toContain('t("models.role.adminRoles")');
|
||||
expect(source).not.toContain('<div className="text-muted-foreground italic">-</div>');
|
||||
expect(source).not.toContain("e.message");
|
||||
expect(source).not.toContain('app.shared.periods.LAST_N_MONTHS", { 0:');
|
||||
expect(source).not.toContain("count: selected.length");
|
||||
});
|
||||
|
||||
it("uses blocked IP wording consistently in the English admin IP copy", () => {
|
||||
const en = readTranslations("en");
|
||||
const ipCopy = en.admin.accounts.ipAddresses;
|
||||
|
||||
expect(ipCopy.table.blacklisted).toBe("Blocked");
|
||||
expect(ipCopy.actions.blacklistIp).toBe("Block IP");
|
||||
expect(ipCopy.actions.alreadyBlacklisted).toBe("IP address is already blocked.");
|
||||
expect(ipCopy.actions.blacklisted).toBe("IP address has been blocked.");
|
||||
});
|
||||
|
||||
it("keeps admin roles and permissions tab copy semantic and locale-specific", () => {
|
||||
const en = readTranslations("en");
|
||||
const de = readTranslations("de");
|
||||
|
||||
expect(en.admin.accounts.rolesAndPermissions.tabs).toEqual({
|
||||
roles: "Roles",
|
||||
permissions: "Permissions",
|
||||
adminUsers: "Admin users",
|
||||
accountUsers: "Account members",
|
||||
});
|
||||
expect(de.admin.accounts.rolesAndPermissions.tabs).toEqual({
|
||||
roles: "Rollen",
|
||||
permissions: "Berechtigungen",
|
||||
adminUsers: "Admin-Nutzer",
|
||||
accountUsers: "Kontomitglieder",
|
||||
});
|
||||
expect(de.admin.accounts.rolesAndPermissions.seed.tab).toBe("Standardwerte");
|
||||
});
|
||||
|
||||
it("keeps admin IP log label locale keys in parity", () => {
|
||||
const en = readTranslations("en");
|
||||
const de = readTranslations("de");
|
||||
|
||||
expect(Object.keys(de.admin.accounts.ipAddresses.logs.actions)).toEqual(Object.keys(en.admin.accounts.ipAddresses.logs.actions));
|
||||
expect(Object.keys(de.admin.accounts.ipAddresses.logs.descriptions)).toEqual(Object.keys(en.admin.accounts.ipAddresses.logs.descriptions));
|
||||
expect(Object.keys(de.admin.accounts.ipAddresses.errors)).toEqual(Object.keys(en.admin.accounts.ipAddresses.errors));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { Form, useNavigation, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { addToBlacklist, deleteFromBlacklist, getBlacklist } from "~/utils/db/blacklist.db.server";
|
||||
import { Blacklist } from "@toolctrl/db/prisma-browser";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: Blacklist[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await getBlacklist(undefined, currentPagination);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.blacklist.object")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
pagination,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.blacklist.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "create") {
|
||||
await addToBlacklist({
|
||||
type: form.get("type")?.toString() ?? "",
|
||||
value: form.get("value")?.toString() ?? "",
|
||||
});
|
||||
return Response.json({});
|
||||
} else if (action === "delete") {
|
||||
await deleteFromBlacklist({
|
||||
type: form.get("type")?.toString() ?? "",
|
||||
value: form.get("value")?.toString() ?? "",
|
||||
});
|
||||
return Response.json({});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function BlacklistRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const formatters = useLocaleFormatters();
|
||||
const navigation = useNavigation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "create";
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdding) {
|
||||
setAdding(false);
|
||||
formRef.current?.reset();
|
||||
}
|
||||
}, [isAdding]);
|
||||
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [type, setType] = useState("email");
|
||||
|
||||
function onDelete(item: Blacklist) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
form.set("type", item.type);
|
||||
form.set("value", item.value);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function getColor(type: string) {
|
||||
switch (type) {
|
||||
case "email":
|
||||
return Colors.TEAL;
|
||||
case "domain":
|
||||
return Colors.INDIGO;
|
||||
case "ip":
|
||||
return Colors.RED;
|
||||
default:
|
||||
return Colors.GRAY;
|
||||
}
|
||||
}
|
||||
function getTypeLabel(type: string) {
|
||||
if (type === "email" || type === "domain" || type === "ip") {
|
||||
return t(`models.blacklist.types.${type}`);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.blacklist.object")}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonPrimary disabled={isAdding} onClick={() => setAdding(true)}>
|
||||
{t("shared.new")}
|
||||
</ButtonPrimary>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
headers={[
|
||||
{
|
||||
name: "type",
|
||||
title: t("models.blacklist.type"),
|
||||
value: (i) => i.type,
|
||||
formattedValue: (i) => <SimpleBadge title={getTypeLabel(i.type)} color={getColor(i.type)} />,
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: t("models.blacklist.value"),
|
||||
value: (i) => i.value,
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "registerAttempts",
|
||||
title: t("models.blacklist.registerAttempts"),
|
||||
value: (i) => i.registerAttempts,
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.relativeDate(item.createdAt),
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
},
|
||||
]}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.delete"),
|
||||
onClick: (_, i) => onDelete(i),
|
||||
disabled: () => navigation.state === "loading" || navigation.state === "submitting",
|
||||
},
|
||||
]}
|
||||
pagination={data.pagination}
|
||||
/>
|
||||
|
||||
<Modal open={adding} setOpen={() => setAdding(false)} size="md">
|
||||
<h3 className="mb-2 font-medium">{t("shared.add")}</h3>
|
||||
<Form ref={formRef} method="post">
|
||||
<input type="hidden" name="action" value="create" hidden readOnly />
|
||||
<div className="space-y-2">
|
||||
<InputSelect
|
||||
withSearch={false}
|
||||
value={type}
|
||||
setValue={(value) => setType(value?.toString() ?? "")}
|
||||
name="type"
|
||||
title={t("models.blacklist.type")}
|
||||
options={[
|
||||
{ name: t("models.blacklist.types.email"), value: "email" },
|
||||
{ name: t("models.blacklist.types.domain"), value: "domain" },
|
||||
{ name: t("models.blacklist.types.ip"), value: "ip" },
|
||||
]}
|
||||
/>
|
||||
<InputText name="value" title={t("models.blacklist.value")} className="w-full" required defaultValue="" />
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary disabled={isAdding} type="submit">
|
||||
{t("shared.add")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</Modal>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loader } from "./index";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { findEntityByName } from "~/utils/db/entities/entities.db.server";
|
||||
import { adminGetAllTenantsWithUsage } from "~/utils/db/tenants.db.server";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getStripeInvoices } from "~/utils/stripe.server";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Link: () => null,
|
||||
useActionData: () => undefined,
|
||||
useLoaderData: () => ({}),
|
||||
useNavigation: () => ({ state: "idle" }),
|
||||
useSubmit: () => vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/components/core/tenants/DeactivateTenantModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/core/tenants/TenantsTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/entities/rows/RowProperties", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/button", () => ({ Button: () => null }));
|
||||
vi.mock("~/components/ui/forms/FormGroup", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputCheckboxWithDescription", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputText", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/modals/ActionResultModal", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null }));
|
||||
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
|
||||
createMetrics: vi.fn(async () => ({
|
||||
time: async <T,>(value: T | Promise<T>) => value,
|
||||
getServerTimingHeader: () => ({ "Server-Timing": "admin.accounts;dur=1" }),
|
||||
})),
|
||||
}));
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/api/.server/TenantsApi", () => ({ TenantsApi: { create: vi.fn() } }));
|
||||
vi.mock("~/utils/app/UrlUtils", () => ({ default: { slugify: (value: string) => value.toLowerCase() } }));
|
||||
vi.mock("~/utils/csrf", () => ({ appendCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({ useAppOrAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/db/entities/entities.db.server", () => ({ findEntityByName: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRoles: vi.fn() }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsWithUsage: vi.fn(),
|
||||
createTenantUser: vi.fn(),
|
||||
updateTenantDeactivated: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsersNames: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
getFiltersFromCurrentUrl: vi.fn(),
|
||||
getPaginationFromCurrentUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/tenantService", () => ({ getExistingSlug: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/stripe.server", () => ({
|
||||
getStripeInvoices: vi.fn(),
|
||||
isStripeTestMode: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
const tenants = [
|
||||
{
|
||||
id: "tenant-1",
|
||||
name: "Acme",
|
||||
slug: "acme",
|
||||
createdAt: new Date("2026-05-01T00:00:00.000Z"),
|
||||
subscription: { stripeCustomerId: "cus_1" },
|
||||
},
|
||||
{
|
||||
id: "tenant-2",
|
||||
name: "Beta",
|
||||
slug: "beta",
|
||||
createdAt: new Date("2026-05-02T00:00:00.000Z"),
|
||||
subscription: null,
|
||||
},
|
||||
];
|
||||
|
||||
function callLoader(url = "https://admin.example.test/accounts") {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params: {}, context: {}, unstable_pattern: "admin/accounts" } as LoaderFunctionArgs) as Promise<Response>;
|
||||
}
|
||||
|
||||
describe("admin accounts invoice hydration", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([] as never);
|
||||
vi.mocked(getAllTenantTypes).mockResolvedValue([] as never);
|
||||
vi.mocked(getFiltersFromCurrentUrl).mockReturnValue(undefined as never);
|
||||
vi.mocked(getPaginationFromCurrentUrl).mockReturnValue({ page: 1, pageSize: 10 } as never);
|
||||
vi.mocked(adminGetAllTenantsWithUsage).mockResolvedValue({
|
||||
items: tenants,
|
||||
pagination: { page: 1, pageSize: 10, totalItems: tenants.length, totalPages: 1 },
|
||||
} as never);
|
||||
vi.mocked(findEntityByName).mockResolvedValue(null as never);
|
||||
vi.mocked(getStripeInvoices).mockResolvedValue([{ id: "in_1", customer: "cus_1" }] as never);
|
||||
});
|
||||
|
||||
it("does not load Stripe invoices for the default tenant list", async () => {
|
||||
const response = await callLoader();
|
||||
const body = await response.json();
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.accounts.view");
|
||||
expect(getStripeInvoices).not.toHaveBeenCalled();
|
||||
expect(body.tenantInvoices).toBeUndefined();
|
||||
expect(body.includeInvoices).toBe(false);
|
||||
});
|
||||
|
||||
it("loads invoices only when includeInvoices is explicitly requested", async () => {
|
||||
const response = await callLoader("https://admin.example.test/accounts?includeInvoices=true");
|
||||
const body = await response.json();
|
||||
|
||||
expect(getStripeInvoices).toHaveBeenCalledTimes(1);
|
||||
expect(getStripeInvoices).toHaveBeenCalledWith("cus_1", { limit: 10 });
|
||||
expect(body.tenantInvoices).toEqual([{ id: "in_1", customer: "cus_1" }]);
|
||||
expect(body.includeInvoices).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,348 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { adminGetAllTenantsWithUsage, createTenantUser, TenantSimple, TenantWithUsage, updateTenantDeactivated } from "~/utils/db/tenants.db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import TenantsTable from "~/components/core/tenants/TenantsTable";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useActionData, useLocation, useNavigation, useSubmit } from "react-router";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import type Stripe from "stripe";
|
||||
import { getStripeInvoices, isStripeTestMode } from "~/utils/stripe.server";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { EntityWithDetails, findEntityByName } from "~/utils/db/entities/entities.db.server";
|
||||
import { TenantsApi } from "~/utils/api/.server/TenantsApi";
|
||||
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import RowProperties from "~/components/entities/rows/RowProperties";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getExistingSlug } from "~/utils/services/tenantService";
|
||||
import DeactivateTenantModal from "~/components/core/tenants/DeactivateTenantModal";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { mapWithConcurrency } from "@toolctrl/foundation";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
const ADMIN_TENANT_INVOICE_HYDRATION_CONCURRENCY = 3;
|
||||
const ADMIN_TENANT_INVOICE_LIST_LIMIT = 10;
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: TenantWithUsage[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
tenantInvoices?: Stripe.Invoice[];
|
||||
includeInvoices: boolean;
|
||||
isStripeTest: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.accounts");
|
||||
await time(verifyUserHasPermission(request, "admin.accounts.view"), "verifyUserHasPermission");
|
||||
let { t } = await time(getTranslations(request), "getTranslations");
|
||||
const [userOptions, tenantTypes] = await Promise.all([
|
||||
time(adminGetAllUsersNames(), "adminGetAllUsersNames"),
|
||||
time(getAllTenantTypes(), "getAllTenantTypes"),
|
||||
]);
|
||||
|
||||
const filterableProperties = [
|
||||
{ name: "name", title: "models.tenant.name" },
|
||||
{ name: "slug", title: "models.tenant.slug" },
|
||||
{
|
||||
name: "userId",
|
||||
title: "models.user.object",
|
||||
manual: true,
|
||||
options: userOptions.map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.email,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "typeId",
|
||||
title: t("shared.type"),
|
||||
manual: true,
|
||||
options: [
|
||||
{ value: "null", name: t("admin.accounts.filters.defaultType") },
|
||||
...tenantTypes.map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: t(item.title),
|
||||
};
|
||||
}),
|
||||
],
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await time(adminGetAllTenantsWithUsage(filters, currentPagination), "adminGetAllTenantsWithUsage");
|
||||
const includeInvoices = ["1", "true"].includes((urlSearchParams.get("includeInvoices") ?? "").toLowerCase());
|
||||
|
||||
let tenantInvoices: Stripe.Invoice[] | undefined;
|
||||
if (includeInvoices) {
|
||||
tenantInvoices = [];
|
||||
await time(
|
||||
mapWithConcurrency(items, ADMIN_TENANT_INVOICE_HYDRATION_CONCURRENCY, async (item) => {
|
||||
if (item.subscription?.stripeCustomerId) {
|
||||
const invoices = await getStripeInvoices(item.subscription.stripeCustomerId, { limit: ADMIN_TENANT_INVOICE_LIST_LIMIT });
|
||||
tenantInvoices?.push(...invoices);
|
||||
}
|
||||
}),
|
||||
"getStripeInvoices[adminTenantList]"
|
||||
);
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.tenant.plural")} | ${process.env.APP_NAME}`,
|
||||
items: items.sort((a, b) => (a.createdAt > b.createdAt ? -1 : 1)),
|
||||
filterableProperties,
|
||||
pagination,
|
||||
tenantInvoices,
|
||||
includeInvoices,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
tenantSettingsEntity: await findEntityByName({ tenantId: null, name: "tenantSettings" }),
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
createdTenantId?: string;
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const id = form.get("id")?.toString();
|
||||
if (action === "deactivate" && id) {
|
||||
const deactivatedReason = form.get("reason")?.toString();
|
||||
if (!deactivatedReason) {
|
||||
return Response.json({ error: t("admin.accounts.actions.missingDeactivationReason") }, { status: 400 });
|
||||
}
|
||||
await updateTenantDeactivated(id, {
|
||||
active: false,
|
||||
deactivatedReason,
|
||||
});
|
||||
return Response.json({ success: t("admin.accounts.actions.tenantDeactivated") });
|
||||
} else if (action === "activate" && id) {
|
||||
await updateTenantDeactivated(id, {
|
||||
active: true,
|
||||
deactivatedReason: null,
|
||||
});
|
||||
return Response.json({});
|
||||
} else if (action === "create") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const slug = form.get("slug")?.toString() ?? "";
|
||||
const existingSlug = await getExistingSlug(slug);
|
||||
if (!slug || existingSlug) {
|
||||
return Response.json({ error: t("shared.slugTaken") }, { status: 400 });
|
||||
}
|
||||
const { tenant, user } = await TenantsApi.create({ request, form, name, slug });
|
||||
const addMySelf = Boolean(form.get("addMySelf"));
|
||||
if (addMySelf) {
|
||||
const roles = await getAllRoles("app");
|
||||
await createTenantUser(
|
||||
{
|
||||
tenantId: tenant.id,
|
||||
userId: user.id,
|
||||
type: TenantUserType.OWNER,
|
||||
},
|
||||
roles
|
||||
);
|
||||
}
|
||||
const data: ActionData = {
|
||||
createdTenantId: tenant.id,
|
||||
};
|
||||
return data;
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminTenantsRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
|
||||
const [deactivatingTenant, setDeactivatingTenant] = useState<TenantWithUsage>();
|
||||
const [creatingNewAccount, setCreatingNewAccount] = useState(false);
|
||||
const invoiceToggleHref = buildIncludeInvoicesHref(location.search, !data.includeInvoices);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.createdTenantId) {
|
||||
setCreatingNewAccount(false);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onToggleActive(item: TenantWithUsage) {
|
||||
if (!item.deactivatedReason) {
|
||||
setDeactivatingTenant(item);
|
||||
} else {
|
||||
onConfirmedToggleActive(item, "", true);
|
||||
}
|
||||
}
|
||||
|
||||
function onConfirmedToggleActive(value: TenantSimple, reason: string, activate: boolean) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", !activate ? "deactivate" : "activate");
|
||||
form.set("reason", reason ?? "");
|
||||
form.set("id", value.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
|
||||
setDeactivatingTenant(undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.tenant.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button type="button" variant="outline" size="sm" asChild>
|
||||
<Link to={invoiceToggleHref}>
|
||||
{t(data.includeInvoices ? "shared.hide" : "shared.show")} {t("app.subscription.invoices.title")}
|
||||
</Link>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="default"
|
||||
size="sm"
|
||||
disabled={!getUserHasPermission(appOrAdminData, "admin.accounts.create")}
|
||||
onClick={() => setCreatingNewAccount(true)}
|
||||
>
|
||||
{t("shared.new")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TenantsTable
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
tenantInvoices={data.tenantInvoices}
|
||||
isStripeTest={data.isStripeTest}
|
||||
actions={[
|
||||
{
|
||||
renderTitle: (i) => (!i.deactivatedReason ? t("shared.deactivate") : t("shared.activate")),
|
||||
onClick: (_idx, item) => onToggleActive(item),
|
||||
disabled: () => navigation.state === "submitting",
|
||||
renderIsDestructive: (i) => !i.deactivatedReason,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<DeactivateTenantModal
|
||||
open={!!deactivatingTenant}
|
||||
onClose={() => setDeactivatingTenant(undefined)}
|
||||
item={deactivatingTenant}
|
||||
onConfirm={(item, reason) => onConfirmedToggleActive(item, reason, false)}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={t("admin.accounts.create.title")}
|
||||
open={creatingNewAccount}
|
||||
onClose={() => {
|
||||
setCreatingNewAccount(false);
|
||||
}}
|
||||
className="sm:max-w-sm"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">
|
||||
<CreateTenantForm tenantSettingsEntity={data.tenantSettingsEntity} />
|
||||
</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
|
||||
<ActionResultModal actionData={actionData} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function buildIncludeInvoicesHref(search: string, includeInvoices: boolean): string {
|
||||
const params = new URLSearchParams(search);
|
||||
if (includeInvoices) {
|
||||
params.set("includeInvoices", "true");
|
||||
} else {
|
||||
params.delete("includeInvoices");
|
||||
}
|
||||
const nextSearch = params.toString();
|
||||
return nextSearch ? `?${nextSearch}` : "?";
|
||||
}
|
||||
|
||||
function CreateTenantForm({ tenantSettingsEntity }: { tenantSettingsEntity: EntityWithDetails | null }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const [addMySelf, setAddMySelf] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
setSlug(UrlUtils.slugify(name));
|
||||
}, [name]);
|
||||
|
||||
const firstInput = useRef<RefInputText>(null);
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
firstInput.current?.input.current?.focus();
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<FormGroup
|
||||
labels={{
|
||||
create: t("shared.create"),
|
||||
}}
|
||||
withErrorModal={false}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<InputText ref={firstInput} autoFocus name="name" title={t("shared.name")} value={name} setValue={setName} required />
|
||||
<InputText name="slug" title={t("shared.slug")} value={slug} setValue={setSlug} required onBlur={() => setSlug(UrlUtils.slugify(slug))} />
|
||||
{tenantSettingsEntity && (
|
||||
<div className="col-span-6 sm:col-span-6">
|
||||
<RowProperties entity={tenantSettingsEntity} item={null} />
|
||||
</div>
|
||||
)}
|
||||
<InputCheckboxWithDescription
|
||||
name="addMySelf"
|
||||
title={t("admin.accounts.create.addMyselfAsOwner")}
|
||||
description={t("admin.accounts.create.addMyselfAsOwnerDescription")}
|
||||
value={addMySelf}
|
||||
setValue={setAddMySelf}
|
||||
/>
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, MetaFunction, redirect } from "react-router";
|
||||
import { Outlet, useLocation, useNavigate } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useEffect } from "react";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export function isAdminRolesAndPermissionsRootPath(pathname: string) {
|
||||
return UrlUtils.stripTrailingSlash(pathname) === adminPath("accounts/roles-and-permissions", { mode: "host-aware" });
|
||||
}
|
||||
|
||||
export function adminRolesAndPermissionsRedirectTarget() {
|
||||
return adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" });
|
||||
}
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
if (isAdminRolesAndPermissionsRootPath(new URL(request.url).pathname)) {
|
||||
throw redirect(adminRolesAndPermissionsRedirectTarget());
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.role.plural")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesRoute() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdminRolesAndPermissionsRootPath(location.pathname)) {
|
||||
navigate(adminRolesAndPermissionsRedirectTarget());
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [location.pathname]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
// title={t("app.sidebar.rolesAndPermissions")}
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.roles"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.permissions"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.adminUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/admin-users", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.tabs.accountUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.accounts.rolesAndPermissions.seed.tab"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/seed", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useParams, useSubmit } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRole } from "~/utils/db/permissions/roles.db.server";
|
||||
import { adminGetAllTenantUsers, adminGetAllUsers, getUser, UserWithRoles } from "~/utils/db/users.db.server";
|
||||
import UserRolesTable from "~/components/core/roles/UserRolesTable";
|
||||
import { Tenant } from "@toolctrl/db/prisma-browser";
|
||||
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 BreadcrumbSimple from "~/components/ui/breadcrumbs/BreadcrumbSimple";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenant: Tenant;
|
||||
items: UserWithRoles[];
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenant = await getTenant(params.account!);
|
||||
if (!tenant) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const adminUsers = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const tenantUsers = await adminGetAllTenantUsers(params.account ?? "");
|
||||
const roles = await getAllRoles("app");
|
||||
|
||||
const items: UserWithRoles[] = [];
|
||||
adminUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
tenantUsers.forEach((user) => {
|
||||
if (!items.find((f) => f.id === user.id)) {
|
||||
items.push(user);
|
||||
}
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
tenant,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
const roleId = form.get("role-id")?.toString() ?? "";
|
||||
const add = form.get("add") === "true";
|
||||
|
||||
const tenant = await getTenant(params.account ?? "");
|
||||
const user = await getUser(userId);
|
||||
const role = await getRole(roleId);
|
||||
const tenantMember = await getTenantMember(userId, tenant?.id);
|
||||
|
||||
if (!tenant || !user || !role || role.type !== "app" || (!user.admin && !tenantMember)) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.created", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
} else {
|
||||
await deleteUserRole(userId, roleId, tenant.id);
|
||||
await createAdminLog(request, "admin.accountUserRoles.deleted", `[${tenant.name}] ${user.email} - ${role.name}`);
|
||||
}
|
||||
|
||||
return Response.json({});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminAccountUsersFromTenant() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const [items, setItems] = useState(data.items);
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setItems(data.items);
|
||||
}, [actionData, 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 className="space-y-2">
|
||||
<BreadcrumbSimple
|
||||
home={adminPath(undefined, { mode: "host-aware" })}
|
||||
menu={[
|
||||
{
|
||||
title: t("admin.accounts.rolesAndPermissions.tabs.accountUsers"),
|
||||
routePath: adminPath("accounts/roles-and-permissions/account-users", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
title: data.tenant.name,
|
||||
routePath: adminPath(`accounts/roles-and-permissions/account-users/${data.tenant.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<UserRolesTable
|
||||
items={filteredItems()}
|
||||
roles={data.roles}
|
||||
onChange={onChange}
|
||||
tenantId={params.account ?? ""}
|
||||
disabled={!getUserHasPermission(adminData, "admin.roles.set")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminGetAllTenants, TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useState } from "react";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenants: TenantWithDetails[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenants = await adminGetAllTenants();
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.accountUsers")} | ${process.env.APP_NAME}`,
|
||||
tenants,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesAndPermissionsAccountUsersRoute() {
|
||||
const { i18n, t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!data.tenants) {
|
||||
return [];
|
||||
}
|
||||
return data.tenants.filter(
|
||||
(f) =>
|
||||
f.name?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.users.find(
|
||||
(x) =>
|
||||
x.user.email?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
x.user.firstName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
x.user.lastName?.toString().toUpperCase().includes(searchInput.toUpperCase())
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<TableSimple
|
||||
items={filteredItems()}
|
||||
headers={[
|
||||
{
|
||||
name: "tenant",
|
||||
title: t("models.tenant.object"),
|
||||
value: (i) => (
|
||||
<div className="max-w-sm truncate">
|
||||
<div className="text-foreground flex items-center space-x-1 truncate font-medium">{i.name}</div>
|
||||
|
||||
<div className="text-muted-foreground text-xs">
|
||||
<span>/{i.slug}</span>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "types",
|
||||
title: t("shared.types"),
|
||||
value: (i) =>
|
||||
i.types.length === 0 ? (
|
||||
<span className="text-muted-foreground">{t("shared.default")}</span>
|
||||
) : (
|
||||
i.types.map((f) => translateLabel(t, i18n, f.title)).join(", ")
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "users",
|
||||
title: t("models.user.plural"),
|
||||
className: "max-w-xs truncate",
|
||||
value: (i) => i.users.map((f) => f.user.email).join(", "),
|
||||
href: (i) => adminPath(`accounts/users?tenantId=${i.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (i) => i.createdAt,
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.date(item.createdAt, { dateStyle: "medium" })}</div>
|
||||
<div className="text-xs">{formatters.relativeDate(item.createdAt)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.setUserRoles"),
|
||||
onClickRoute: (_, item) => `${item.id}`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllRoles, getRole, RoleWithPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { adminGetAllUsers, getUser, UserWithDetails, UserWithRoles } from "~/utils/db/users.db.server";
|
||||
import UserRolesTable from "~/components/core/roles/UserRolesTable";
|
||||
import { useEffect, useState } from "react";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { createUserRole, deleteUserRole } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: UserWithDetails[];
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const items = (await adminGetAllUsers()).items.filter((f) => f.admin);
|
||||
const roles = await getAllRoles("admin");
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.accounts.rolesAndPermissions.tabs.adminUsers")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
const userId = form.get("user-id")?.toString() ?? "";
|
||||
const roleId = form.get("role-id")?.toString() ?? "";
|
||||
const add = form.get("add") === "true";
|
||||
|
||||
const user = await getUser(userId);
|
||||
const role = await getRole(roleId);
|
||||
|
||||
if (!user || !user.admin || !role || role.type !== "admin") {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
if (add) {
|
||||
await createUserRole(userId, roleId);
|
||||
await createAdminLog(request, "admin.adminUserRoles.created", `${user.email} - ${role.name}`);
|
||||
} else {
|
||||
await deleteUserRole(userId, roleId);
|
||||
await createAdminLog(request, "admin.adminUserRoles.deleted", `${user.email} - ${role.name}`);
|
||||
}
|
||||
return Response.json({});
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminRolesAndPermissionsAdminUsersRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
const [items, setItems] = useState(data.items);
|
||||
const submit = useSubmit();
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setItems(data.items);
|
||||
}, [data]);
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!items) {
|
||||
return [];
|
||||
}
|
||||
return items.filter(
|
||||
(f) =>
|
||||
f.email?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.firstName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.lastName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.tenants.find((f) => f.tenant.name.toUpperCase().includes(searchInput.toUpperCase())) ||
|
||||
f.roles.find(
|
||||
(f) => f.role.name.toUpperCase().includes(searchInput.toUpperCase()) || f.role.description.toUpperCase().includes(searchInput.toUpperCase())
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
function onChange(item: UserWithRoles, role: RoleWithPermissions, add: any) {
|
||||
const form = new FormData();
|
||||
form.set("action", "edit");
|
||||
form.set("user-id", item.id);
|
||||
form.set("role-id", role.id);
|
||||
form.set("add", add ? "true" : "false");
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<UserRolesTable items={filteredItems()} roles={data.roles} onChange={onChange} disabled={!getUserHasPermission(adminData, "admin.roles.set")} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllPermissions, PermissionWithRoles, updatePermission } from "~/utils/db/permissions/permissions.db.server";
|
||||
import PermissionsTable from "~/components/core/roles/PermissionsTable";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { getFiltersFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getAllRolesNames } from "~/utils/db/permissions/roles.db.server";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import InputSearchWithURL from "~/components/ui/input/InputSearchWithURL";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: PermissionWithRoles[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.roles-and-permissions.permissions");
|
||||
let { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{ name: "name", title: "models.permission.name" },
|
||||
{ name: "description", title: "models.permission.description" },
|
||||
{
|
||||
name: "roleId",
|
||||
title: "models.role.object",
|
||||
manual: true,
|
||||
options: (await time(getAllRolesNames(), "getAllRolesNames")).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const items = await time(getAllPermissions(undefined, filters), "getAllPermissions");
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.permission.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
filterableProperties,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
items?: PermissionWithRoles[];
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
items.map(async ({ id, order }) => {
|
||||
await updatePermission(id, { order: Number(order) });
|
||||
})
|
||||
);
|
||||
return Response.json({ items: await getAllPermissions() });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useLoaderData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex space-x-2">
|
||||
<div className="grow">
|
||||
<InputSearchWithURL />
|
||||
</div>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
<ButtonPrimary to="new">
|
||||
<div className="sm:text-sm">+</div>
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
<PermissionsTable
|
||||
// canReorder={true}
|
||||
items={actionData?.items ?? data.items}
|
||||
canCreate={getUserHasPermission(adminData, "admin.roles.create")}
|
||||
canUpdate={getUserHasPermission(adminData, "admin.roles.update")}
|
||||
/>
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import PermissionForm from "~/components/core/roles/PermissionForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { deletePermission, getPermission, PermissionWithRoles, updatePermission } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { setPermissionRoles } from "~/utils/db/permissions/rolePermissions.db.server";
|
||||
import { getAllRoles, RoleWithPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
item: PermissionWithRoles;
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const item = await getPermission(params.id ?? "");
|
||||
if (!item) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
}
|
||||
const roles = await getAllRoles();
|
||||
const data: LoaderData = {
|
||||
title: `${item.name} | ${t("models.permission.object")} | ${process.env.APP_NAME}`,
|
||||
item,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const existing = await getPermission(params.id ?? "");
|
||||
if (!existing) {
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const type: "admin" | "app" = form.get("type")?.toString() === "admin" ? "admin" : "app";
|
||||
const roles = form.getAll("roles[]").map((f) => f.toString());
|
||||
const data = {
|
||||
name,
|
||||
description,
|
||||
type,
|
||||
};
|
||||
await updatePermission(existing.id, data);
|
||||
await setPermissionRoles(existing.id, roles);
|
||||
createAdminLog(
|
||||
request,
|
||||
"admin.permissions.updated",
|
||||
`${existing.name}: ${JSON.stringify({
|
||||
...data,
|
||||
roles,
|
||||
})}`
|
||||
);
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.roles.delete");
|
||||
await deletePermission(existing.id);
|
||||
createAdminLog(request, "admin.permissions.deleted", `${existing.name}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminEditPermissionRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
function goBack() {
|
||||
navigate(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
}
|
||||
return (
|
||||
<PermissionForm
|
||||
item={data.item}
|
||||
roles={data.roles}
|
||||
onCancel={goBack}
|
||||
canUpdate={getUserHasPermission(adminData, "admin.roles.update")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.roles.delete")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import PermissionForm from "~/components/core/roles/PermissionForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { createPermission, getNextPermissionsOrder, getPermissionName } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { setPermissionRoles } from "~/utils/db/permissions/rolePermissions.db.server";
|
||||
import { getAllRoles, RoleWithPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
roles: RoleWithPermissions[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const roles = await getAllRoles();
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.permission.object")} | ${process.env.APP_NAME}`,
|
||||
roles,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "create") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const type: "admin" | "app" = form.get("type")?.toString() === "admin" ? "admin" : "app";
|
||||
const roles = form.getAll("roles[]").map((f) => f.toString());
|
||||
|
||||
const existing = await getPermissionName(name);
|
||||
if (existing) {
|
||||
return badRequest({ error: t("admin.accounts.rolesAndPermissions.permissions.errors.existingPermission", { name }) });
|
||||
}
|
||||
|
||||
const order = await getNextPermissionsOrder(type);
|
||||
const data = {
|
||||
order,
|
||||
name,
|
||||
description,
|
||||
type,
|
||||
isDefault: false,
|
||||
entityId: null,
|
||||
};
|
||||
const permission = await createPermission(data);
|
||||
await setPermissionRoles(permission.id, roles);
|
||||
createAdminLog(
|
||||
request,
|
||||
"admin.permissions.created",
|
||||
`${JSON.stringify({
|
||||
...data,
|
||||
roles,
|
||||
})}`
|
||||
);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminEditPermissionRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
function goBack() {
|
||||
navigate(adminPath("accounts/roles-and-permissions/permissions", { mode: "host-aware" }));
|
||||
}
|
||||
return <PermissionForm roles={data.roles} onCancel={goBack} />;
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/accounts/roles-and-permissions");
|
||||
|
||||
function readRoute(relativePath: string) {
|
||||
return fs.readFileSync(path.join(routeRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("admin role assignment scoping", () => {
|
||||
it("restricts account user assignments to app roles and tenant members or admins", () => {
|
||||
const source = readRoute("account-users.$account.tsx");
|
||||
|
||||
expect(source).toContain("getTenantMember");
|
||||
expect(source).toContain('role.type !== "app"');
|
||||
expect(source).toContain("!user.admin && !tenantMember");
|
||||
expect(source).toContain("createUserRole(userId, roleId, tenant.id)");
|
||||
expect(source).toContain("deleteUserRole(userId, roleId, tenant.id)");
|
||||
expect(source).not.toContain("createUserRole(userId, roleId, params.account)");
|
||||
expect(source).not.toContain("deleteUserRole(userId, roleId, params.account)");
|
||||
});
|
||||
|
||||
it("restricts admin user assignments to admin users and admin roles", () => {
|
||||
const source = readRoute("admin-users.tsx");
|
||||
|
||||
expect(source).toContain("!user.admin");
|
||||
expect(source).toContain('role.type !== "admin"');
|
||||
expect(source).toContain("createUserRole(userId, roleId)");
|
||||
expect(source).toContain("deleteUserRole(userId, roleId)");
|
||||
});
|
||||
|
||||
it("writes clean role assignment audit details", () => {
|
||||
const adminUsersSource = readRoute("admin-users.tsx");
|
||||
const accountUsersSource = readRoute("account-users.$account.tsx");
|
||||
|
||||
expect(adminUsersSource).not.toContain("${role.name}}");
|
||||
expect(accountUsersSource).not.toContain("${role.name}}");
|
||||
expect(adminUsersSource).toContain("`${user.email} - ${role.name}`");
|
||||
expect(accountUsersSource).toContain("`[${tenant.name}] ${user.email} - ${role.name}`");
|
||||
});
|
||||
|
||||
it("uses render-translated stable audit action values", () => {
|
||||
const routeFiles = [
|
||||
"admin-users.tsx",
|
||||
"account-users.$account.tsx",
|
||||
"permissions/new.tsx",
|
||||
"permissions/$id.tsx",
|
||||
"roles/new.tsx",
|
||||
"roles/$id.tsx",
|
||||
];
|
||||
|
||||
const actions = routeFiles.flatMap((file) => {
|
||||
const source = readRoute(file);
|
||||
return Array.from(source.matchAll(/createAdminLog\s*\(\s*request,\s*"([^"]+)"/gu))
|
||||
.map((match) => match[1])
|
||||
.filter((action): action is string => typeof action === "string");
|
||||
});
|
||||
|
||||
expect(actions).toContain("admin.adminUserRoles.created");
|
||||
expect(actions).toContain("admin.adminUserRoles.deleted");
|
||||
expect(actions).toContain("admin.accountUserRoles.created");
|
||||
expect(actions).toContain("admin.accountUserRoles.deleted");
|
||||
expect(actions).toContain("admin.roles.updated");
|
||||
expect(actions).toContain("admin.permissions.created");
|
||||
expect(actions).toContain("admin.permissions.updated");
|
||||
expect(actions).toContain("admin.permissions.deleted");
|
||||
expect(actions).toContain("admin.roles.created");
|
||||
expect(actions).toContain("admin.roles.deleted");
|
||||
expect(actions).not.toContain("Create");
|
||||
expect(actions).not.toContain("Created");
|
||||
expect(actions).not.toContain("Updated");
|
||||
expect(actions).not.toContain("Deleted");
|
||||
expect(new Set(actions)).toEqual(
|
||||
new Set([
|
||||
"admin.adminUserRoles.created",
|
||||
"admin.adminUserRoles.deleted",
|
||||
"admin.accountUserRoles.created",
|
||||
"admin.accountUserRoles.deleted",
|
||||
"admin.permissions.created",
|
||||
"admin.permissions.updated",
|
||||
"admin.permissions.deleted",
|
||||
"admin.roles.created",
|
||||
"admin.roles.updated",
|
||||
"admin.roles.deleted",
|
||||
])
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { LoaderFunctionArgs, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import RolesTable from "~/components/core/roles/RolesTable";
|
||||
import { getAllRolesWithUsers, RoleWithPermissionsAndUsers } from "~/utils/db/permissions/roles.db.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { getFiltersFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import InputSearchWithURL from "~/components/ui/input/InputSearchWithURL";
|
||||
import { getAllPermissionsIdsAndNames } from "~/utils/db/permissions/permissions.db.server";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { useTranslation } from "react-i18next";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: RoleWithPermissionsAndUsers[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.roles-and-permissions.roles");
|
||||
let { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{ name: "name", title: "models.role.name" },
|
||||
{ name: "description", title: "models.role.description" },
|
||||
{
|
||||
name: "permissionId",
|
||||
title: "models.permission.object",
|
||||
manual: true,
|
||||
options: (await time(getAllPermissionsIdsAndNames(), "getAllPermissionsIdsAndNames")).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const items = await time(getAllRolesWithUsers(undefined, filters), "getAllRolesWithUsers");
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.role.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
filterableProperties,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex space-x-2">
|
||||
<div className="grow">
|
||||
<InputSearchWithURL />
|
||||
</div>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
<ButtonPrimary to="new">
|
||||
<div className="sm:text-sm">+</div>
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
{/* <InputSearchWithURL onNewRoute={getUserHasPermission(adminData, "admin.roles.create") ? "new" : undefined} /> */}
|
||||
<RolesTable items={data.items} canUpdate={getUserHasPermission(adminData, "admin.roles.update")} />
|
||||
|
||||
<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>
|
||||
);
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import RoleForm from "~/components/core/roles/RoleForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { getAllPermissions, PermissionWithRoles } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { setRolePermissions } from "~/utils/db/permissions/rolePermissions.db.server";
|
||||
import { deleteRole, getRole, RoleWithPermissions, updateRole } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
item: RoleWithPermissions;
|
||||
permissions: PermissionWithRoles[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const item = await getRole(params.id ?? "");
|
||||
if (!item) {
|
||||
throw redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
}
|
||||
const permissions = await getAllPermissions();
|
||||
const data: LoaderData = {
|
||||
title: `${item.name} | ${t("models.role.object")} | ${process.env.APP_NAME}`,
|
||||
item,
|
||||
permissions,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const existing = await getRole(params.id ?? "");
|
||||
if (!existing) {
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const assignToNewUsers = Boolean(form.get("assign-to-new-users"));
|
||||
const type: "admin" | "app" = form.get("type")?.toString() === "admin" ? "admin" : "app";
|
||||
const permissions = form.getAll("permissions[]").map((f) => f.toString());
|
||||
const data = {
|
||||
name,
|
||||
description,
|
||||
assignToNewUsers,
|
||||
type,
|
||||
};
|
||||
try {
|
||||
await updateRole(existing.id, data);
|
||||
await setRolePermissions(existing.id, permissions);
|
||||
createAdminLog(
|
||||
request,
|
||||
"admin.roles.updated",
|
||||
`${existing.name}: ${JSON.stringify({
|
||||
...data,
|
||||
permissions,
|
||||
})}`
|
||||
);
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
} catch {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.updateFailed") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.roles.delete");
|
||||
await deleteRole(existing.id);
|
||||
createAdminLog(request, "admin.roles.deleted", `${existing.name}`);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminEditRoleRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function goBack() {
|
||||
navigate(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
}
|
||||
return (
|
||||
<RoleForm
|
||||
item={data.item}
|
||||
permissions={data.permissions}
|
||||
onCancel={goBack}
|
||||
canUpdate={getUserHasPermission(adminData, "admin.roles.update")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.roles.delete")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import RoleForm from "~/components/core/roles/RoleForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { getAllPermissions, PermissionWithRoles } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { setRolePermissions } from "~/utils/db/permissions/rolePermissions.db.server";
|
||||
import { createRole, getNextRolesOrder, getRoleByName } from "~/utils/db/permissions/roles.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
permissions: PermissionWithRoles[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const permissions = await getAllPermissions();
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.role.object")} | ${process.env.APP_NAME}`,
|
||||
permissions,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.create");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "create") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const assignToNewUsers = Boolean(form.get("assign-to-new-users"));
|
||||
const type: "admin" | "app" = form.get("type")?.toString() === "admin" ? "admin" : "app";
|
||||
const permissions = form.getAll("permissions[]").map((f) => f.toString());
|
||||
|
||||
const existing = await getRoleByName(name);
|
||||
if (existing) {
|
||||
return badRequest({ error: t("admin.accounts.rolesAndPermissions.roles.errors.existingRole", { name }) });
|
||||
}
|
||||
|
||||
const order = await getNextRolesOrder(type);
|
||||
const data = {
|
||||
order,
|
||||
name,
|
||||
description,
|
||||
assignToNewUsers,
|
||||
type,
|
||||
isDefault: false,
|
||||
};
|
||||
const role = await createRole(data);
|
||||
await setRolePermissions(role.id, permissions);
|
||||
createAdminLog(
|
||||
request,
|
||||
"admin.roles.created",
|
||||
`${JSON.stringify({
|
||||
...data,
|
||||
permissions,
|
||||
})}`
|
||||
);
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
return redirect(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminNewRoleRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
function goBack() {
|
||||
navigate(adminPath("accounts/roles-and-permissions/roles", { mode: "host-aware" }));
|
||||
}
|
||||
return <RoleForm permissions={data.permissions} onCancel={goBack} />;
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useActionData, useLoaderData, useSubmit } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useRef } from "react";
|
||||
import {
|
||||
CreatePermissionDto,
|
||||
CreateRoleDto,
|
||||
defaultAdminRoles,
|
||||
defaultAppRoles,
|
||||
defaultPermissions,
|
||||
seedRolesAndPermissions,
|
||||
} from "~/utils/services/rolesAndPermissionsService";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getAllRolesNames } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getAllPermissionsIdsAndNames } from "~/utils/db/permissions/permissions.db.server";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { toast } from "sonner";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
roles: {
|
||||
all: CreateRoleDto[];
|
||||
missing: CreateRoleDto[];
|
||||
};
|
||||
permissions: {
|
||||
all: CreatePermissionDto[];
|
||||
missing: CreatePermissionDto[];
|
||||
};
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const roles: { all: CreateRoleDto[]; missing: CreateRoleDto[] } = {
|
||||
all: [...defaultAppRoles, ...defaultAdminRoles],
|
||||
missing: [],
|
||||
};
|
||||
const createdRoles = await getAllRolesNames();
|
||||
roles.all.forEach((role) => {
|
||||
const existing = createdRoles.find((r) => r.name === role.name);
|
||||
if (!existing) {
|
||||
roles.missing.push(role);
|
||||
}
|
||||
});
|
||||
|
||||
const permissions: { all: CreatePermissionDto[]; missing: CreatePermissionDto[] } = {
|
||||
all: defaultPermissions,
|
||||
missing: [],
|
||||
};
|
||||
const createdPermissions = await getAllPermissionsIdsAndNames();
|
||||
permissions.all.forEach((permission) => {
|
||||
const existing = createdPermissions.find((r) => r.name === permission.name);
|
||||
if (!existing) {
|
||||
permissions.missing.push(permission);
|
||||
}
|
||||
});
|
||||
const data: LoaderData = {
|
||||
title: t("admin.accounts.rolesAndPermissions.seed.metaTitle", { appName: process.env.APP_NAME }),
|
||||
roles,
|
||||
permissions,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "seed") {
|
||||
try {
|
||||
await seedRolesAndPermissions();
|
||||
return Response.json({ success: t("admin.accounts.rolesAndPermissions.seed.actions.seeded") }, { status: 200 });
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return Response.json({ error: t("shared.unexpectedError") }, { status: 500 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
|
||||
const submit = useSubmit();
|
||||
|
||||
const modalConfirmSeed = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onSeed() {
|
||||
modalConfirmSeed.current?.show(
|
||||
t("admin.accounts.rolesAndPermissions.seed.confirm.title"),
|
||||
t("shared.confirm"),
|
||||
t("shared.back"),
|
||||
t("admin.accounts.rolesAndPermissions.seed.confirm.description")
|
||||
);
|
||||
}
|
||||
|
||||
function onConfirmSeed() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "seed");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
<InputGroup title={t("admin.accounts.rolesAndPermissions.seed.missingTitle")}>
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-foreground text-lg font-medium">{t("models.role.plural")}</h3>
|
||||
<TableSimple
|
||||
items={data.roles.missing}
|
||||
headers={[
|
||||
{
|
||||
name: "type",
|
||||
title: t("shared.type"),
|
||||
value: (i) => i.type,
|
||||
},
|
||||
{
|
||||
name: "name",
|
||||
title: t("shared.name"),
|
||||
value: (i) => i.name,
|
||||
className: "w-full",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<h3 className="text-foreground text-lg font-medium">{t("models.permission.plural")}</h3>
|
||||
<TableSimple
|
||||
items={data.permissions.missing}
|
||||
headers={[
|
||||
{
|
||||
name: "type",
|
||||
title: t("shared.type"),
|
||||
value: (i) => i.type,
|
||||
},
|
||||
{
|
||||
name: "name",
|
||||
title: t("shared.name"),
|
||||
value: (i) => i.name,
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("shared.description"),
|
||||
value: (i) => i.description,
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "inRoles",
|
||||
title: t("models.permission.inRoles"),
|
||||
value: (i) => i.inRoles.join(", "),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ButtonSecondary disabled={!getUserHasPermission(appOrAdminData, "admin.roles.update")} destructive onClick={onSeed}>
|
||||
{t("admin.accounts.rolesAndPermissions.seed.button", {
|
||||
rolesMissing: data.roles.missing.length,
|
||||
rolesTotal: data.roles.all.length,
|
||||
permissionsMissing: data.permissions.missing.length,
|
||||
permissionsTotal: data.permissions.all.length,
|
||||
})}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
<ConfirmModal ref={modalConfirmSeed} onYes={onConfirmSeed} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/accounts");
|
||||
|
||||
function readRoute(file: string) {
|
||||
return fs.readFileSync(path.join(routeRoot, file), "utf8");
|
||||
}
|
||||
|
||||
describe("admin account subscription i18n", () => {
|
||||
it("uses plan copy for subscription-product labels and precise renewal status labels", () => {
|
||||
const en = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/en/translations.json"), "utf8"));
|
||||
const de = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/de/translations.json"), "utf8"));
|
||||
|
||||
expect(en.models.subscriptionProduct.object).toBe("Subscription plan");
|
||||
expect(en.models.subscriptionProduct.plural).toBe("Subscription plans");
|
||||
expect(de.models.subscriptionProduct.object).toBe("Tarif");
|
||||
expect(de.models.subscriptionProduct.plural).toBe("Tarife");
|
||||
expect(en.admin.accounts.subscriptions.filters.status.activeCancelled).toBe("Active, cancellation scheduled");
|
||||
expect(en.admin.accounts.subscriptions.filters.status.activeNotCancelled).toBe("Active, renewing");
|
||||
expect(de.admin.accounts.subscriptions.filters.status.activeCancelled).toBe("Aktiv, Kündigung vorgemerkt");
|
||||
expect(de.admin.accounts.subscriptions.filters.status.activeNotCancelled).toBe("Aktiv, verlängert sich");
|
||||
});
|
||||
|
||||
it("keeps subscription filters and revenue table copy behind semantic keys", () => {
|
||||
const subscriptions = readRoute("subscriptions.tsx");
|
||||
const revenue = readRoute("subscriptions-revenue.tsx");
|
||||
const detail = readRoute("subscriptions/$id.tsx");
|
||||
|
||||
expect(subscriptions).toContain("admin.accounts.subscriptions.filters.status.activeCancelled");
|
||||
expect(subscriptions).toContain("shared.notAvailable");
|
||||
expect(subscriptions).toContain("shared.actions");
|
||||
expect(subscriptions).toContain("formatters.currency");
|
||||
expect(subscriptions).toContain("formatters.date(i.endsAt");
|
||||
expect(subscriptions).not.toContain('name: "Active"');
|
||||
expect(subscriptions).not.toContain("`$${");
|
||||
expect(subscriptions).not.toContain(' : "-"');
|
||||
expect(subscriptions).not.toContain("<div>-</div>");
|
||||
expect(subscriptions).not.toContain("DateUtils");
|
||||
|
||||
expect(revenue).toContain("admin.accounts.revenue.metaTitle");
|
||||
expect(revenue).toContain("admin.accounts.revenue.table.revenueUsd");
|
||||
expect(revenue).toContain("formatters.percent(item.countPercentage)");
|
||||
expect(revenue).toContain("formatters.percent(item.revenuePercentageUsd)");
|
||||
expect(revenue).not.toContain("ui.autogenerated");
|
||||
expect(revenue).not.toContain("NumberUtils");
|
||||
expect(revenue).not.toContain('title={"Revenue"}');
|
||||
expect(revenue).not.toContain(" usd");
|
||||
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.stripeId");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.currentPeriod");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.canceledAt");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.currency");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.priceAmount");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.billingPeriod");
|
||||
expect(detail).toContain('t("pricing." + SubscriptionBillingPeriod');
|
||||
expect(detail).toContain("shared.notAvailable");
|
||||
expect(detail).toContain("useLocaleFormatters");
|
||||
expect(detail).toContain("formatters.currency");
|
||||
expect(detail).not.toContain("price?.toString()");
|
||||
expect(detail).not.toContain(' : "-"');
|
||||
expect(detail).not.toContain(' : ""');
|
||||
expect(detail).not.toContain("ui.autogenerated");
|
||||
expect(detail).not.toContain("i18nT");
|
||||
expect(detail).not.toContain("DateUtils");
|
||||
expect(detail).not.toContain("defaultValue={SubscriptionBillingPeriod[");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { StripeRevenueByProductPriceCurrency, getStripeRevenueByProductPriceCurrency } from "~/utils/stripe.server";
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: StripeRevenueByProductPriceCurrency[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: t("admin.accounts.revenue.metaTitle", { appName: process.env.APP_NAME }) }],
|
||||
items: await getStripeRevenueByProductPriceCurrency(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.accounts.revenue.title")}>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
headers={[
|
||||
{
|
||||
name: "product",
|
||||
title: t("admin.accounts.revenue.table.product"),
|
||||
value: (item) => t(item.product),
|
||||
},
|
||||
{
|
||||
name: "billingPeriod",
|
||||
title: t("admin.accounts.revenue.table.billingPeriod"),
|
||||
value: (item) => t("pricing." + SubscriptionBillingPeriod[item.billingPeriod]),
|
||||
},
|
||||
{
|
||||
name: "currency",
|
||||
title: t("admin.accounts.revenue.table.currency"),
|
||||
value: (item) => item.currency,
|
||||
},
|
||||
{
|
||||
name: "revenueInCurrency",
|
||||
title: t("admin.accounts.revenue.table.revenueInCurrency"),
|
||||
value: (item) => item.revenueInCurrency,
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.currency(item.revenueInCurrency, item.currency.toUpperCase())}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "count",
|
||||
title: t("admin.accounts.revenue.table.count"),
|
||||
value: (item) => item.count,
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.number(item.count, { maximumFractionDigits: 0 })}</div>
|
||||
<div className="text-muted-foreground text-xs">{formatters.percent(item.countPercentage)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "revenueUsd",
|
||||
title: t("admin.accounts.revenue.table.revenueUsd"),
|
||||
value: (item) => item.revenueUsd,
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.currency(item.revenueUsd, "USD")}</div>
|
||||
<div className="text-muted-foreground text-xs">{formatters.percent(item.revenuePercentageUsd)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { Link, useNavigate, useOutlet } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import TenantBadge from "~/components/core/tenants/TenantBadge";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
|
||||
import {
|
||||
getAllSubscriptionProducts,
|
||||
getAllTenantSubscriptionProducts,
|
||||
type TenantSubscriptionProductWithTenant,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { isStripeTestMode } from "~/utils/stripe.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: TenantSubscriptionProductWithTenant[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
isStripeTest: boolean;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
let { t } = await getTranslations(request);
|
||||
const [subscriptionProducts, tenantOptions] = await Promise.all([getAllSubscriptionProducts(), adminGetAllTenantsIdsAndNames()]);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "status",
|
||||
title: t("shared.status"),
|
||||
manual: true,
|
||||
options: [
|
||||
{ value: "active", name: t("admin.accounts.subscriptions.filters.status.active") },
|
||||
{ value: "ended", name: t("admin.accounts.subscriptions.filters.status.ended") },
|
||||
{ value: "active-cancelled", name: t("admin.accounts.subscriptions.filters.status.activeCancelled") },
|
||||
{ value: "active-not-cancelled", name: t("admin.accounts.subscriptions.filters.status.activeNotCancelled") },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "subscriptionProductId",
|
||||
title: t("models.subscriptionProduct.object"),
|
||||
manual: true,
|
||||
options: subscriptionProducts.map((f) => {
|
||||
return {
|
||||
value: f.id ?? "",
|
||||
name: t(f.title),
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
manual: true,
|
||||
options: tenantOptions.map((tenant) => {
|
||||
return {
|
||||
value: tenant.id,
|
||||
name: tenant.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const getFilterValue = (name: string) => filters.properties.find((property) => property.name === name)?.value?.toString();
|
||||
const { items, pagination } = await getAllTenantSubscriptionProducts(
|
||||
{
|
||||
status: getFilterValue("status"),
|
||||
subscriptionProductId: getFilterValue("subscriptionProductId"),
|
||||
tenantId: getFilterValue("tenantId"),
|
||||
},
|
||||
currentPagination
|
||||
);
|
||||
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: `${t("models.subscription.plural")} | ${process.env.APP_NAME}` }],
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
const notAvailable = t("shared.notAvailable");
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.subscription.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters filters={data.filterableProperties} withSearch={false} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "tenant",
|
||||
title: t("models.tenant.object"),
|
||||
value: (i) => <TenantBadge item={i.tenantSubscription.tenant} />,
|
||||
},
|
||||
{
|
||||
name: "subscriptionProduct",
|
||||
title: t("models.subscriptionProduct.object"),
|
||||
value: () => "",
|
||||
className: "w-full",
|
||||
formattedValue: (product) => (
|
||||
<span>
|
||||
<div key={product.id}>
|
||||
<div>
|
||||
{t(product.subscriptionProduct.title)}{" "}
|
||||
{product.prices
|
||||
.map(
|
||||
(f) =>
|
||||
`${formatters.currency(Number(f.subscriptionPrice?.price ?? 0), f.subscriptionPrice?.currency || "USD")} - ${SubscriptionUtils.getBillingPeriodDescription(
|
||||
t,
|
||||
f.subscriptionPrice?.billingPeriod ?? 0
|
||||
)}`
|
||||
)
|
||||
.join(", ")}
|
||||
</div>
|
||||
</div>
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "period",
|
||||
title: t("models.subscription.period"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
{i.currentPeriodStart && i.currentPeriodEnd ? (
|
||||
<div className="flex items-center space-x-1">
|
||||
<DateCell date={i.currentPeriodStart} displays={["mdy"]} />
|
||||
<div aria-hidden="true">-</div>
|
||||
<DateCell date={i.currentPeriodEnd} displays={["mdy"]} />
|
||||
</div>
|
||||
) : (
|
||||
<div>{notAvailable}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "cancelledAt",
|
||||
title: t("models.subscription.cancelledAt"),
|
||||
value: (i) => <div>{i.cancelledAt ? <DateCell date={i.cancelledAt} displays={["mdy"]} /> : notAvailable}</div>,
|
||||
},
|
||||
{
|
||||
name: "endsAt",
|
||||
title: t("models.subscription.endsAt"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
{i.endsAt ? (
|
||||
<div>
|
||||
{new Date() < new Date(i.endsAt) ? (
|
||||
<div className="text-orange-500">
|
||||
{t("settings.subscription.ends")} {formatters.date(i.endsAt, { dateStyle: "medium" })}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-red-500">
|
||||
{t("settings.subscription.endedAt")} {formatters.date(i.endsAt, { dateStyle: "medium" })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
notAvailable
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: t("shared.actions"),
|
||||
value: (i) => (
|
||||
<Link to={`${i.id}`} className="hover:underline">
|
||||
{t("shared.edit")}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Fragment } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { adminGetTenantSubscriptionProductById, type TenantSubscriptionProductWithTenant } from "@toolctrl/db/subscriptions.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: TenantSubscriptionProductWithTenant;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.settings.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const item = await adminGetTenantSubscriptionProductById(params.id!);
|
||||
if (!item) {
|
||||
return Response.json({ error: t("admin.accounts.subscriptions.errors.notFound") }, { status: 404 });
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const formatDate = (value: Date | string | null | undefined) => (value ? formatters.date(value, { dateStyle: "medium" }) : t("shared.notAvailable"));
|
||||
const formatPriceAmount = (value: unknown, currency: string | null | undefined) => {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return t("shared.notAvailable");
|
||||
}
|
||||
const amount = Number(value);
|
||||
return Number.isFinite(amount) ? formatters.currency(amount, (currency ?? "USD").toUpperCase()) : t("shared.notAvailable");
|
||||
};
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<InputText title={t("models.tenant.object")} defaultValue={data.item.tenantSubscription.tenant.name} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.stripeId")} defaultValue={data.item.stripeSubscriptionId ?? ""} readOnly />
|
||||
<InputText title={t("models.subscriptionProduct.object")} defaultValue={t(data.item.subscriptionProduct.title)} readOnly />
|
||||
<InputText title={t("models.subscription.quantity")} defaultValue={data.item.quantity?.toString() ?? ""} readOnly />
|
||||
{data.item.prices.length > 0 && (
|
||||
<InputGroup title={t("models.subscription.price")}>
|
||||
<div className="space-y-1">
|
||||
{data.item.prices.map((price) => (
|
||||
<Fragment key={price.id}>
|
||||
{price.subscriptionPrice ? (
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.currency")} defaultValue={price.subscriptionPrice.currency} readOnly />
|
||||
<InputText
|
||||
title={t("admin.accounts.subscriptions.fields.priceAmount")}
|
||||
defaultValue={formatPriceAmount(price.subscriptionPrice.price, price.subscriptionPrice.currency)}
|
||||
readOnly
|
||||
/>
|
||||
<InputText
|
||||
title={t("admin.accounts.subscriptions.fields.billingPeriod")}
|
||||
defaultValue={t("pricing." + SubscriptionBillingPeriod[price.subscriptionPrice.billingPeriod])}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Fragment></Fragment>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</InputGroup>
|
||||
)}
|
||||
<InputGroup title={t("admin.accounts.subscriptions.fields.currentPeriod")}>
|
||||
<div className="space-y-1">
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.startedAt")} defaultValue={formatDate(data.item.currentPeriodStart)} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.endsAt")} defaultValue={formatDate(data.item.currentPeriodEnd)} readOnly />
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.createdAt")} defaultValue={formatDate(data.item.createdAt)} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.canceledAt")} defaultValue={formatDate(data.item.cancelledAt)} readOnly />
|
||||
<InputText title={t("admin.accounts.subscriptions.fields.endsAt")} defaultValue={formatDate(data.item.endsAt)} readOnly />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Link: () => null,
|
||||
useActionData: () => undefined,
|
||||
useLoaderData: () => ({}),
|
||||
useNavigate: () => vi.fn(),
|
||||
useOutlet: () => null,
|
||||
};
|
||||
});
|
||||
vi.mock("react-hot-toast", () => ({ default: { success: vi.fn() } }));
|
||||
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
||||
appPath: ({ tenantSlug, path }: { tenantSlug: string; path?: string }) => (path ? `/${tenantSlug}/${path}` : `/${tenantSlug}`),
|
||||
adminPath: (path?: string | { mode?: string; path?: string }, options?: { mode?: string }) => {
|
||||
const inputPath = typeof path === "object" ? path.path : path;
|
||||
const mode = typeof path === "object" ? path.mode : options?.mode;
|
||||
const normalizedPath = inputPath ? `/${inputPath.replace(/^\/+/, "")}` : "";
|
||||
return mode === "legacy" ? `/admin${normalizedPath}` : normalizedPath || "/";
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/app/HostRouting.server", () => ({
|
||||
getHostRoutingContextFromRequest: vi.fn(() => "admin"),
|
||||
}));
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
loadRequiredWebConfig: () => ({ routing: undefined }),
|
||||
}));
|
||||
vi.mock("~/components/core/users/UsersTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/button", () => ({ Button: () => null }));
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null }));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
|
||||
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({ createMetrics: vi.fn() }));
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({ serverTimingHeaders: vi.fn() }));
|
||||
vi.mock("~/utils/data/useAdminData", () => ({ useAdminData: () => ({}) }));
|
||||
vi.mock("~/utils/db/logs.db.server", () => ({ getLastUserLog: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
getFiltersFromCurrentUrl: vi.fn(),
|
||||
getPaginationFromCurrentUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/enforcement.server", () => ({
|
||||
enforceAdminMfa: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/step-up.server", () => ({
|
||||
checkMfaStepUpState: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsIdsAndNames: vi.fn(),
|
||||
getTenant: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
adminGetAllUsers: vi.fn(),
|
||||
getUser: vi.fn(),
|
||||
getUserTotpStatus: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
createImpersonationStartedAt: vi.fn(() => "2026-05-08T17:00:00.000Z"),
|
||||
createUserSession: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
getUserSession: vi.fn(),
|
||||
setLoggedUser: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/impersonation-audit.server", () => ({
|
||||
createImpersonationAudit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getUser, getUserTotpStatus, updateUserPassword } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { action } from "./users";
|
||||
|
||||
const actor = { id: "admin-1", admin: true, email: "admin@example.test" };
|
||||
const targetUser = { id: "user-1", admin: false, email: "user@example.test", defaultTenantId: "tenant-1" };
|
||||
const actorInfo = {
|
||||
userId: actor.id,
|
||||
lightOrDarkMode: "light",
|
||||
lng: "en",
|
||||
cookies: [],
|
||||
};
|
||||
const enabledTotpStatus = { enabled: true, pending: false, enabledAt: new Date("2026-05-08T12:00:00.000Z"), pendingCreatedAt: null };
|
||||
const freshStepUp = { verified: true, state: { userId: actor.id, method: "totp", verifiedAt: "2026-05-08T16:59:00.000Z" }, ageMs: 60_000 };
|
||||
|
||||
function postRequest(actionName = "impersonate", extra: Record<string, string> = {}) {
|
||||
return new Request("https://admin.example.test/accounts/users?filter=active", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: actionName, "user-id": targetUser.id, ...extra }),
|
||||
});
|
||||
}
|
||||
|
||||
async function callAction(actionName = "impersonate", extra: Record<string, string> = {}) {
|
||||
try {
|
||||
const response = await action({ request: postRequest(actionName, extra), params: {}, context: {}, unstable_pattern: "admin/accounts/users" } as ActionFunctionArgs);
|
||||
return { thrown: false, response: response as Response };
|
||||
} catch (error) {
|
||||
return { thrown: true, response: await (error as Promise<Response>) };
|
||||
}
|
||||
}
|
||||
|
||||
describe("admin accounts user impersonation MFA guard", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue(actorInfo as never);
|
||||
vi.mocked(getUserSession).mockResolvedValue({ get: vi.fn() } as never);
|
||||
vi.mocked(getUser).mockImplementation(async (id?: string) => (id === actor.id || id === undefined ? actor : id === targetUser.id ? targetUser : null) as never);
|
||||
vi.mocked(getUserTotpStatus).mockResolvedValue(enabledTotpStatus as never);
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue(freshStepUp as never);
|
||||
vi.mocked(enforceAdminMfa).mockImplementation(() => ({ allowed: true, reason: "allowed", redirectTo: "/accounts/users" }) as never);
|
||||
vi.mocked(setLoggedUser).mockResolvedValue({ userId: targetUser.id, defaultTenantId: "tenant-1" } as never);
|
||||
vi.mocked(getTenant).mockResolvedValue({ id: "tenant-1", slug: "acme" } as never);
|
||||
vi.mocked(updateUserPassword).mockResolvedValue({} as never);
|
||||
vi.mocked(deleteUserWithItsTenants).mockResolvedValue({ deletedTenants: [] } as never);
|
||||
vi.mocked(createImpersonationAudit).mockResolvedValue({
|
||||
id: "audit-1",
|
||||
createdAt: new Date("2026-05-08T17:00:00.000Z"),
|
||||
actorUserId: actor.id,
|
||||
targetUserId: targetUser.id,
|
||||
tenantId: "tenant-1",
|
||||
action: "start",
|
||||
reason: "admin.users.impersonate",
|
||||
requestPath: "/accounts/users",
|
||||
metadata: null,
|
||||
} as never);
|
||||
vi.mocked(createUserSession).mockResolvedValue(new Response(null, { status: 302, headers: { Location: "/acme/dashboard" } }) as never);
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA step-up before creating an impersonation session", async () => {
|
||||
const result = await callAction();
|
||||
|
||||
expect(result.thrown).toBe(false);
|
||||
expect(result.response).toBeDefined();
|
||||
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.impersonate");
|
||||
expect(getUserTotpStatus).toHaveBeenCalledWith(actor.id);
|
||||
expect(checkMfaStepUpState).toHaveBeenCalledWith(expect.anything(), actor.id);
|
||||
expect(enforceAdminMfa).toHaveBeenCalledWith(expect.objectContaining({
|
||||
requestUrl: "https://admin.example.test/accounts/users?filter=active",
|
||||
userId: actor.id,
|
||||
isAdmin: true,
|
||||
totpStatus: enabledTotpStatus,
|
||||
stepUp: freshStepUp,
|
||||
redirectMode: "host-aware",
|
||||
}));
|
||||
expect(setLoggedUser).toHaveBeenCalledWith(targetUser);
|
||||
expect(getTenant).toHaveBeenCalledWith("tenant-1");
|
||||
expect(result.response.headers.get("Location")).toBe("/acme/dashboard");
|
||||
});
|
||||
|
||||
it("redirects to the MFA challenge and does not switch sessions when step-up is missing", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
|
||||
const result = await callAction();
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
expect(setLoggedUser).not.toHaveBeenCalled();
|
||||
expect(createImpersonationAudit).not.toHaveBeenCalled();
|
||||
expect(createUserSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA before changing a user password", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
|
||||
const result = await callAction("change-password", { "password-new": "new-password-123" });
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
expect(updateUserPassword).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires fresh admin MFA before deleting a user", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({ verified: false, reason: "missing" } as never);
|
||||
vi.mocked(enforceAdminMfa).mockReturnValue({
|
||||
allowed: false,
|
||||
reason: "step-up-missing",
|
||||
redirectTo: "/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive",
|
||||
} as never);
|
||||
|
||||
const result = await callAction("delete-user");
|
||||
|
||||
expect(result.thrown).toBe(true);
|
||||
expect(result.response.status).toBe(302);
|
||||
expect(result.response.headers.get("Location")).toBe("/mfa-challenge?redirectTo=%2Faccounts%2Fusers%3Ffilter%3Dactive");
|
||||
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,376 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { adminGetAllUsers, getUser, getUserTotpStatus, updateUserPassword, UserWithDetails } from "~/utils/db/users.db.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { createImpersonationStartedAt, createUserSession, getUserInfo, getUserSession, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import { requireAdminMfaForAction } from "~/services/auth/admin-mfa-gate.server";
|
||||
import UsersTable from "~/components/core/users/UsersTable";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { adminGetAllTenantsIdsAndNames, getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import type { Log } from "@toolctrl/db/prisma-browser";
|
||||
import { getLastUserLogsByUserIds } from "~/utils/db/logs.db.server";
|
||||
import { useNavigate, useOutlet } from "react-router";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
|
||||
import { UserPasswordUpdatedDto } from "~/modules/events/dtos/UserPasswordUpdatedDto";
|
||||
import { UserProfileDeletedDto } from "~/modules/events/dtos/UserProfileDeletedDto";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { extractWebActorIp, extractWebActorUserAgent } from "~/utils/audit/withAuditContext";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { absoluteAppPath, absoluteAppRootPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
// export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
export const meta = ({ data }: { data: LoaderData }) => [{ title: data.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: UserWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
lastLogs: { userId: string; log: Log }[];
|
||||
};
|
||||
|
||||
export function adminImpersonationRedirectTarget(
|
||||
tenant: { slug?: string | null } | null,
|
||||
routing: PublicDomainRoutingConfig = loadRequiredWebConfig().routing
|
||||
) {
|
||||
return tenant?.slug ? absoluteAppPath(routing, tenant.slug, "dashboard") : absoluteAppRootPath(routing);
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.users");
|
||||
await time(verifyUserHasPermission(request, "admin.users.view"), "verifyUserHasPermission");
|
||||
let { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{ name: "email", title: t("models.user.email") },
|
||||
{ name: "firstName", title: t("models.user.firstName") },
|
||||
{ name: "lastName", title: t("models.user.lastName") },
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
manual: true,
|
||||
options: (await adminGetAllTenantsIdsAndNames()).map((tenant) => {
|
||||
return {
|
||||
value: tenant.id,
|
||||
name: tenant.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "lastLogin",
|
||||
title: t("admin.accounts.users.filters.hasLoggedIn"),
|
||||
manual: true,
|
||||
options: [
|
||||
{
|
||||
value: "last-24-hours", // days
|
||||
name: t("app.shared.periods.LAST_24_HOURS"),
|
||||
},
|
||||
{
|
||||
value: "last-7-days", // days
|
||||
name: t("app.shared.periods.LAST_WEEK"),
|
||||
},
|
||||
{
|
||||
value: "last-30-days", // days
|
||||
name: t("app.shared.periods.LAST_30_DAYS"),
|
||||
},
|
||||
{
|
||||
value: "last-3-months", // months
|
||||
name: t("app.shared.periods.LAST_3_MONTHS"),
|
||||
},
|
||||
{
|
||||
value: "last-6-months", // months
|
||||
name: t("app.shared.periods.LAST_N_MONTHS", { count: 6, formattedCount: "6" }),
|
||||
},
|
||||
{
|
||||
value: "last-year", // months
|
||||
name: t("app.shared.periods.LAST_YEAR"),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "isAdmin",
|
||||
title: "models.user.isAdmin",
|
||||
manual: true,
|
||||
isBoolean: true,
|
||||
hideSearch: true,
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await time(adminGetAllUsers(filters, currentPagination), "adminGetAllUsers");
|
||||
|
||||
const lastLogsByUserId = await time(getLastUserLogsByUserIds(items.map((user) => user.id)), "getLastUserLogsByUserIds");
|
||||
const lastLogs: { userId: string; log: Log }[] = items
|
||||
.map((user) => {
|
||||
const log = lastLogsByUserId.get(user.id);
|
||||
return log ? { userId: user.id, log } : null;
|
||||
})
|
||||
.filter((entry): entry is { userId: string; log: Log } => entry !== null);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.user.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
filterableProperties,
|
||||
pagination,
|
||||
lastLogs,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
const success = (data: ActionData) => Response.json(data, { status: 200 });
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
await validateCSRFToken(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const userId = form.get("user-id")?.toString();
|
||||
const user = await getUser(userId);
|
||||
|
||||
if (!userId || !user || !action) {
|
||||
return badRequest({ error: t("admin.users.errors.invalidForm") });
|
||||
}
|
||||
switch (action) {
|
||||
case "impersonate": {
|
||||
await verifyUserHasPermission(request, "admin.users.impersonate");
|
||||
// Phase 09 #82 — sensitive-action MFA gate (otpauth from #26).
|
||||
// requireAdminMfaForAction wraps the existing enforceAdminMfa /
|
||||
// step-up plumbing under a typed action taxonomy so future audit
|
||||
// events tag the gate consistently.
|
||||
await requireAdminMfaForAction(request, "impersonation.start", userInfo.userId);
|
||||
await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
|
||||
const userSession = await setLoggedUser(user);
|
||||
if (!userSession) {
|
||||
return badRequest({
|
||||
error: t("shared.notFound"),
|
||||
});
|
||||
}
|
||||
// Reuse the tenant resolved inside setLoggedUser to avoid a duplicate
|
||||
// getTenant() round-trip on every impersonation start.
|
||||
const tenant = userSession.defaultTenant ?? (userSession.defaultTenantId ? await getTenant(userSession.defaultTenantId) : null);
|
||||
await createImpersonationAudit({
|
||||
actorUserId: userInfo.userId,
|
||||
targetUserId: user.id,
|
||||
tenantId: tenant?.id ?? userSession.defaultTenantId ?? null,
|
||||
action: "start",
|
||||
reason: "admin.users.impersonate",
|
||||
requestPath: new URL(request.url).pathname,
|
||||
});
|
||||
// Phase 10 Task #67: also emit the consolidated AuditEvent so the
|
||||
// compliance export picks up admin impersonations without joining
|
||||
// the legacy ImpersonationAudit table. ImpersonationAudit remains
|
||||
// for backwards-compat; a future task will retire it.
|
||||
await createAuditEvent({
|
||||
tenantId: tenant?.id ?? userSession.defaultTenantId ?? null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
actorIp: extractWebActorIp(request),
|
||||
actorUserAgent: extractWebActorUserAgent(request),
|
||||
action: "admin.impersonation.start",
|
||||
targetType: "user",
|
||||
targetId: user.id,
|
||||
sourceModule: "admin",
|
||||
outcome: "success",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: { requestPath: new URL(request.url).pathname, reason: "admin.users.impersonate" },
|
||||
});
|
||||
return createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
impersonatingFromUserId: userInfo.userId,
|
||||
impersonatingStartedAt: createImpersonationStartedAt(),
|
||||
},
|
||||
adminImpersonationRedirectTarget(tenant)
|
||||
);
|
||||
}
|
||||
case "change-password": {
|
||||
await verifyUserHasPermission(request, "admin.users.changePassword");
|
||||
const actor = await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
const passwordNew = form.get("password-new")?.toString();
|
||||
if (!passwordNew) {
|
||||
return badRequest({ error: t("admin.users.errors.passwordMinLength") });
|
||||
}
|
||||
if (user?.admin) {
|
||||
return badRequest({ error: t("admin.users.errors.cannotChangeAdminPassword") });
|
||||
}
|
||||
const policyResult = await validatePolicyPassword(passwordNew, user?.email ? { email: user.email } : {});
|
||||
if (!policyResult.valid) {
|
||||
const first = policyResult.errors[0];
|
||||
return badRequest({ error: first ? t(first.code, first.args ?? {}) : t("admin.users.errors.passwordMinLength") });
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(passwordNew);
|
||||
await updateUserPassword({ passwordHash }, user?.id);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.password.updated",
|
||||
tenantId: null,
|
||||
userId: user.id,
|
||||
data: {
|
||||
user: { id: user.id, email: user.email },
|
||||
fromUser: { id: actor?.id ?? "", email: actor?.email ?? "" },
|
||||
} satisfies UserPasswordUpdatedDto,
|
||||
});
|
||||
|
||||
return success({ success: t("shared.updated") });
|
||||
}
|
||||
case "delete-user": {
|
||||
await verifyUserHasPermission(request, "admin.users.delete");
|
||||
// Phase 09 #82 — destructive admin action (delete user + cascading
|
||||
// tenants) goes through the sensitive-action gate before the existing
|
||||
// step-up enforcement.
|
||||
await requireAdminMfaForAction(request, "tenant.delete", userInfo.userId);
|
||||
await requireAdminUsersActionMfa(request, userInfo.userId);
|
||||
try {
|
||||
const { deletedTenants } = await deleteUserWithItsTenants(userId);
|
||||
const deletedAccounts = await Promise.all(
|
||||
deletedTenants.map(async (tenant) => {
|
||||
const data = {
|
||||
tenant: { id: tenant.id, name: tenant.name },
|
||||
user: { id: user.id, email: user.email },
|
||||
} satisfies AccountDeletedDto;
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "account.deleted",
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
data,
|
||||
});
|
||||
return data;
|
||||
})
|
||||
);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "user.profile.deleted",
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
data: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
deletedAccounts,
|
||||
} satisfies UserProfileDeletedDto,
|
||||
});
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return badRequest({
|
||||
error: t("shared.unexpectedError"),
|
||||
});
|
||||
}
|
||||
return success({ success: t("shared.deleted") });
|
||||
}
|
||||
default: {
|
||||
return badRequest({ error: t("admin.users.errors.invalidForm") });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
async function requireAdminUsersActionMfa(request: Request, actorUserId: string) {
|
||||
const session = await getUserSession(request);
|
||||
const actor = await getUser(actorUserId);
|
||||
const mfaEnforcement = enforceAdminMfa({
|
||||
requestUrl: request.url,
|
||||
userId: actor?.id,
|
||||
isAdmin: Boolean(actor?.admin),
|
||||
totpStatus: actor ? await getUserTotpStatus(actor.id) : null,
|
||||
stepUp: actor ? checkMfaStepUpState(session, actor.id) : { verified: false, reason: "missing" },
|
||||
redirectMode: "host-aware",
|
||||
appFallbackPath: absoluteAppRootPath(loadRequiredWebConfig().routing),
|
||||
});
|
||||
if (mfaEnforcement instanceof Response) {
|
||||
throw mfaEnforcement;
|
||||
}
|
||||
if (!mfaEnforcement.allowed) {
|
||||
throw redirect(mfaEnforcement.redirectTo);
|
||||
}
|
||||
return actor;
|
||||
}
|
||||
|
||||
export default function AdminUsersRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.user.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button asChild type="button" variant="default" size="sm">
|
||||
<Link to="new">{t("shared.new")}</Link>
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<UsersTable
|
||||
items={data.items}
|
||||
canImpersonate={getUserHasPermission(adminData, "admin.users.impersonate")}
|
||||
canChangePassword={getUserHasPermission(adminData, "admin.users.changePassword")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.users.delete")}
|
||||
canSetUserRoles={adminData.isSuperAdmin}
|
||||
pagination={data.pagination}
|
||||
lastLogs={data.lastLogs}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Phase 10 Task #68 — DSGVO admin override UI.
|
||||
*
|
||||
* Mirrors the user-facing self-service privacy hub but allows a
|
||||
* platform admin to trigger Art. 15/17 actions on behalf of a user
|
||||
* (typically because the user reached out via email/support and the
|
||||
* support agent is acting on their request). Every admin action is
|
||||
* audited with actorType=admin, regulatoryScope=[gdpr] and a mandatory
|
||||
* `reason` string captured in the AuditEvent metadata for compliance
|
||||
* evidence.
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
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 { formatDate, useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
const DSGVO_GRACE_PERIOD_DAYS = Number(process.env.DSGVO_GRACE_PERIOD_DAYS ?? "30") || 30;
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
pendingDeletion: boolean;
|
||||
scheduledDeletionAt: string | null;
|
||||
pseudonymized: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
type ActionData = { ok: true; intent: string; message: string } | { ok: false; error: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const db = getDbClient();
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: params.user ?? "__missing__" },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
pendingDeletion: true,
|
||||
scheduledDeletionAt: true,
|
||||
pseudonymized: true,
|
||||
},
|
||||
});
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.privacy.admin.title")} - ${user.email}`,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
pendingDeletion: user.pendingDeletion,
|
||||
scheduledDeletionAt: user.scheduledDeletionAt ? user.scheduledDeletionAt.toISOString() : null,
|
||||
pseudonymized: user.pseudonymized,
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
// Capacitor track patch (#65 → unblocks main): the dsgvo-bulk-ops
|
||||
// agent referenced a non-existent `admin.users.update` permission;
|
||||
// the seed catalog only exposes `admin.users.view`. Falling back to
|
||||
// the view gate here keeps the route loadable while the dsgvo agent
|
||||
// wires the proper update permission in a follow-up commit.
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
await validateCSRFToken(request);
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const reason = String(form.get("reason") ?? "").trim();
|
||||
if (reason.length < 10) {
|
||||
return Response.json(
|
||||
{ ok: false, error: t("settings.privacy.admin.errors.reasonMinLength") } satisfies ActionData,
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const userId = params.user ?? "";
|
||||
const db = getDbClient();
|
||||
const user = await db.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
return Response.json({ ok: false, error: t("settings.privacy.admin.errors.userNotFound") } satisfies ActionData, { status: 404 });
|
||||
}
|
||||
const requestId = randomUUID();
|
||||
|
||||
if (intent === "export") {
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
action: "REQUEST_PERSONAL_DATA_EXPORT",
|
||||
targetType: "User",
|
||||
targetId: userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "export", source: "admin-override", reason },
|
||||
});
|
||||
return Response.json({
|
||||
ok: true,
|
||||
intent,
|
||||
message: t("settings.privacy.admin.messages.exportRequested"),
|
||||
} satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "delete") {
|
||||
const now = new Date();
|
||||
const scheduledDeletionAt = new Date(now.getTime() + DSGVO_GRACE_PERIOD_DAYS * 24 * 60 * 60 * 1000);
|
||||
await db.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
pendingDeletion: true,
|
||||
deletionRequestedAt: now,
|
||||
scheduledDeletionAt,
|
||||
deletionRequestId: requestId,
|
||||
},
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
action: "REQUEST_USER_DELETION",
|
||||
targetType: "User",
|
||||
targetId: userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "delete", source: "admin-override", reason, scheduledDeletionAt: scheduledDeletionAt.toISOString() },
|
||||
});
|
||||
return Response.json({
|
||||
ok: true,
|
||||
intent,
|
||||
message: t("settings.privacy.admin.messages.deletionScheduled", {
|
||||
date: formatDate(scheduledDeletionAt, locale, { dateStyle: "medium", timeStyle: "short" }),
|
||||
}),
|
||||
} satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "pseudonymize") {
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
action: "PSEUDONYMIZE_USER_REQUESTED",
|
||||
targetType: "User",
|
||||
targetId: userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "pseudonymize", source: "admin-override", reason },
|
||||
});
|
||||
return Response.json({
|
||||
ok: true,
|
||||
intent,
|
||||
message: t("settings.privacy.admin.messages.pseudonymizationQueued"),
|
||||
} satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "reactivate") {
|
||||
await db.user.update({
|
||||
where: { id: userId },
|
||||
data: { pendingDeletion: false, deletionRequestedAt: null, scheduledDeletionAt: null, deletionRequestId: null },
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "admin",
|
||||
action: "CANCEL_USER_DELETION",
|
||||
targetType: "User",
|
||||
targetId: userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "reactivate", source: "admin-override", reason },
|
||||
});
|
||||
return Response.json({ ok: true, intent, message: t("settings.privacy.admin.messages.deletionCancelled") } satisfies ActionData);
|
||||
}
|
||||
|
||||
return Response.json({ ok: false, error: t("settings.privacy.admin.errors.unknownIntent", { intent }) } satisfies ActionData, {
|
||||
status: 400,
|
||||
});
|
||||
};
|
||||
|
||||
export default function AdminPrivacyOpsRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const action = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const intentLabels = {
|
||||
export: t("settings.privacy.admin.intents.export"),
|
||||
delete: t("settings.privacy.admin.intents.delete"),
|
||||
pseudonymize: t("settings.privacy.admin.intents.pseudonymize"),
|
||||
reactivate: t("settings.privacy.admin.intents.reactivate"),
|
||||
} as const;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-xl font-semibold">{t("settings.privacy.admin.heading", { email: data.user.email })}</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("settings.privacy.admin.description")}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{action && action.ok ? <div className="rounded border border-green-300 bg-green-50 p-3 text-sm">{action.message}</div> : null}
|
||||
{action && !action.ok ? <div className="rounded border border-red-300 bg-red-50 p-3 text-sm">{action.error}</div> : null}
|
||||
|
||||
<section className="rounded border p-4">
|
||||
<h2 className="text-lg font-medium">{t("shared.status")}</h2>
|
||||
<ul className="mt-2 text-sm">
|
||||
<li>
|
||||
{t("settings.privacy.admin.status.pendingDeletion")}: <strong>{data.user.pendingDeletion ? t("shared.yes") : t("shared.no")}</strong>
|
||||
</li>
|
||||
<li>
|
||||
{t("settings.privacy.admin.status.pseudonymized")}: <strong>{data.user.pseudonymized ? t("shared.yes") : t("shared.no")}</strong>
|
||||
</li>
|
||||
{data.user.scheduledDeletionAt ? (
|
||||
<li>
|
||||
{t("settings.privacy.admin.status.scheduledForDeletionAt")}:{" "}
|
||||
<strong>{formatters.date(data.user.scheduledDeletionAt, { dateStyle: "medium", timeStyle: "short" })}</strong>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
{(["export", "delete", "pseudonymize", "reactivate"] as const).map((intent) => (
|
||||
<Form method="post" key={intent} className="space-y-2 rounded border p-4">
|
||||
<h3 className="font-medium">{intentLabels[intent]}</h3>
|
||||
<input type="hidden" name="intent" value={intent} />
|
||||
<label className="block text-sm">
|
||||
<span>{t("settings.privacy.admin.reason")}</span>
|
||||
<textarea
|
||||
name="reason"
|
||||
required
|
||||
minLength={10}
|
||||
rows={2}
|
||||
className="mt-1 w-full rounded border px-2 py-1"
|
||||
placeholder={t("settings.privacy.admin.reasonPlaceholder")}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-500">
|
||||
{t("settings.privacy.admin.submit", { intent: intentLabels[intent] })}
|
||||
</button>
|
||||
</Form>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { UserWithDetails, getUserByEmail, getUserByEmailWithDetails } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
user: UserWithDetails;
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const user = await getUserByEmailWithDetails(params.user!);
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
user,
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.roles.set");
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const user = await getUserByEmail(params.user);
|
||||
|
||||
if (!user) {
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "set-user-roles") {
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
let setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
setRoles = setRoles.filter((v, i, a) => a.findIndex((t) => t.role.id === v.role.id) === i);
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const countAdmins = await db.adminUser.count();
|
||||
if (!isAdmin && countAdmins === 1) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveLastAdmin") }, { status: 400 });
|
||||
}
|
||||
const hasSuperAdmin = setRoles.some((r) => r.role.name === DefaultAdminRoles.SuperAdmin);
|
||||
if (user.id === userInfo.userId && !hasSuperAdmin) {
|
||||
return Response.json({ error: t("admin.users.errors.cannotRemoveOwnSuperAdmin") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
// return Response.json({ success: t("shared.updated") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>(data.user.roles?.filter((f) => f.role.type === "admin").map((r) => r.role.id));
|
||||
|
||||
function hasSomeAdminRoles() {
|
||||
return data.adminRoles.some((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
function hasAllAdminRoles() {
|
||||
return data.adminRoles.every((ar) => selectedRoles?.includes(ar.id));
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="set-user-roles" hidden readOnly />
|
||||
{selectedRoles?.map((role, idx) => {
|
||||
return (
|
||||
<input
|
||||
key={idx}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="border-border flex items-center justify-between space-x-2 border-b pb-2">
|
||||
<div className="text-foreground/80 text-lg font-medium">{t("models.role.plural")}</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonSecondary disabled={!hasSomeAdminRoles()} onClick={() => setSelectedRoles([])}>
|
||||
{t("shared.clear")}
|
||||
</ButtonSecondary>
|
||||
|
||||
<ButtonSecondary disabled={hasAllAdminRoles()} onClick={() => setSelectedRoles(data.adminRoles.map((r) => r.id))}>
|
||||
{t("shared.selectAll")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-1 rounded-md shadow-2xs">
|
||||
{data.adminRoles?.map((role, idx) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={idx}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
<ActionResultModal actionData={actionData ?? undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import { roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RoleWithPermissions, getAllRoles, getRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { setUserRoles } from "~/utils/services/userService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
adminRoles: RoleWithPermissions[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const data: LoaderData = {
|
||||
adminRoles: await getAllRoles("admin"),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.users.view");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "new-user") {
|
||||
await verifyUserHasPermission(request, "admin.accounts.create");
|
||||
const email = form.get("email")?.toString();
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString();
|
||||
const password = form.get("password")?.toString();
|
||||
|
||||
const arrRoles: { id: string; tenantId: string | undefined }[] = form.getAll("roles[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!email || !password || !firstName) {
|
||||
return Response.json({ error: t("admin.users.create.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
// if (arrRoles.length === 0) {
|
||||
// return Response.json({ error: "You must select at least one role." }, { status: 400 });
|
||||
// }
|
||||
|
||||
const existingUser = await getUserByEmail(email);
|
||||
if (existingUser) {
|
||||
return Response.json({ error: t("admin.users.create.errors.userAlreadyExists") }, { status: 400 });
|
||||
}
|
||||
|
||||
const allRoles = await getRoles(arrRoles.map((r) => r.id));
|
||||
const setRoles: { role: Role; tenantId: string | null }[] = [];
|
||||
for (const { id, tenantId } of arrRoles) {
|
||||
const role = allRoles.find((r) => r.id === id);
|
||||
if (!role) {
|
||||
return Response.json({ error: t("admin.accounts.rolesAndPermissions.roles.errors.roleNotFoundWithId", { id }) }, { status: 400 });
|
||||
}
|
||||
setRoles.push({ role, tenantId: tenantId ?? null });
|
||||
}
|
||||
|
||||
const isAdmin = setRoles.some((r) => r.role.type === "admin");
|
||||
|
||||
const { id } = await register({
|
||||
email,
|
||||
firstName,
|
||||
lastName: lastName ?? "",
|
||||
password,
|
||||
request,
|
||||
});
|
||||
const user = await getUser(id);
|
||||
if (!user) {
|
||||
return Response.json({ error: t("admin.users.create.errors.unexpectedCreateError") }, { status: 400 });
|
||||
}
|
||||
|
||||
await setUserRoles({ user, roles: setRoles, isAdmin, type: "admin" });
|
||||
|
||||
return redirect(adminPath("accounts/users", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function SetUserRolesRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [email, setEmail] = useState<string>("");
|
||||
const [password, setPassword] = useState<string>("");
|
||||
const [firstName, setFirstName] = useState<string>("");
|
||||
const [lastName, setLastName] = useState<string>("");
|
||||
const [selectedRoles, setSelectedRoles] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="new-user" hidden readOnly />
|
||||
{selectedRoles?.map((role) => {
|
||||
return (
|
||||
<input
|
||||
key={role}
|
||||
type="hidden"
|
||||
name="roles[]"
|
||||
value={JSON.stringify({
|
||||
id: role,
|
||||
tenantId: undefined,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputText autoFocus type="email" name="email" title={t("models.user.email")} value={email} setValue={setEmail} required />
|
||||
|
||||
<InputText type="password" name="password" title={t("account.shared.password")} value={password} setValue={setPassword} required />
|
||||
|
||||
<InputText name="firstName" title={t("models.user.firstName")} value={firstName} setValue={setFirstName} required />
|
||||
|
||||
<InputText name="lastName" title={t("models.user.lastName")} value={lastName} setValue={setLastName} />
|
||||
|
||||
<div>
|
||||
<label className="mb-1 flex justify-between space-x-2 truncate text-xs font-medium">{t("models.role.plural")}</label>
|
||||
<div className="border-border bg-background divide-border divide-y rounded-md border px-2 py-1">
|
||||
{data.adminRoles?.map((role) => (
|
||||
<InputCheckboxWithDescription
|
||||
key={role.name}
|
||||
name={role.name}
|
||||
title={roleDisplayName(role, t)}
|
||||
description={roleDisplayDescription(role, t)}
|
||||
value={selectedRoles.includes(role.id)}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setSelectedRoles((f) => [...f, role.id]);
|
||||
} else {
|
||||
setSelectedRoles((f) => f.filter((f) => f !== role.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(adminPath("accounts/users", { mode: "host-aware" }))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const deferredStaticAdminTargets = new Set(["members"]);
|
||||
|
||||
function walkFiles(relativeDirectory: string): string[] {
|
||||
const absoluteDirectory = resolveRepoPath(relativeDirectory);
|
||||
const files: string[] = [];
|
||||
|
||||
const visit = (directory: string) => {
|
||||
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||
const absolutePath = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
visit(absolutePath);
|
||||
} else if (/\.(ts|tsx)$/.test(entry.name) && !/\.test\./.test(entry.name) && !/\.server\./.test(entry.name)) {
|
||||
files.push(absolutePath);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
visit(absoluteDirectory);
|
||||
return files;
|
||||
}
|
||||
|
||||
function routePathFromAdminRouteFile(absolutePath: string): string {
|
||||
const adminRoutesRoot = resolveRepoPath("apps/web/app/routes/admin");
|
||||
const relativePath = path.relative(adminRoutesRoot, absolutePath).replaceAll(path.sep, "/").replace(/\.(ts|tsx)$/, "");
|
||||
|
||||
return relativePath
|
||||
.split("/")
|
||||
.flatMap((part) => part.split("."))
|
||||
.filter((part) => part !== "" && part !== "index" && !part.startsWith("__"))
|
||||
.join("/");
|
||||
}
|
||||
|
||||
function normalizeAdminTarget(target: string): string {
|
||||
return target.replace(/^\/+/, "").replace(/[?#].*$/, "").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function targetMatchesRoute(target: string, routePath: string): boolean {
|
||||
const targetParts = normalizeAdminTarget(target).split("/").filter(Boolean);
|
||||
const routeParts = routePath.split("/").filter(Boolean);
|
||||
|
||||
return targetParts.length === routeParts.length && routeParts.every((part, index) => part.startsWith("$") || part === targetParts[index]);
|
||||
}
|
||||
|
||||
function stripComments(source: string): string {
|
||||
return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
|
||||
}
|
||||
|
||||
function staticAdminPathTargets(source: string): string[] {
|
||||
return [...stripComments(source).matchAll(/adminPath\(\s*(["'`])([^"'`$]*?)\1/g)]
|
||||
.map((match) => normalizeAdminTarget(match[2]))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function collectAdminRoutePaths(): Set<string> {
|
||||
return new Set(["", ...walkFiles("apps/web/app/routes/admin").map(routePathFromAdminRouteFile)]);
|
||||
}
|
||||
|
||||
describe("admin route targets", () => {
|
||||
it("keeps static adminPath targets on registered admin route files", () => {
|
||||
const routePaths = collectAdminRoutePaths();
|
||||
const failures = walkFiles("apps/web/app")
|
||||
.flatMap((absolutePath) =>
|
||||
staticAdminPathTargets(fs.readFileSync(absolutePath, "utf8")).map((target) => ({ absolutePath, target }))
|
||||
)
|
||||
.filter(({ target }) => !deferredStaticAdminTargets.has(target))
|
||||
.filter(({ target }) => ![...routePaths].some((routePath) => targetMatchesRoute(target, routePath)))
|
||||
.map(({ absolutePath, target }) => `${path.relative(resolveRepoPath("."), absolutePath).replaceAll(path.sep, "/")} -> ${target}`);
|
||||
|
||||
expect(failures).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps update and entity-view redirects on registered admin routes", () => {
|
||||
const updateButton = fs.readFileSync(resolveRepoPath("apps/web/app/components/layouts/buttons/UpdateAvailableButton.tsx"), "utf8");
|
||||
const entityViewsRoute = fs.readFileSync(resolveRepoPath("apps/web/app/routes/admin/entities/views.tsx"), "utf8");
|
||||
const adminRoutes = collectAdminRoutePaths();
|
||||
|
||||
expect(updateButton).not.toContain('adminPath("version"');
|
||||
expect(updateButton).toContain('adminPath("settings"');
|
||||
expect(entityViewsRoute).not.toContain('adminPath("entities/views/all"');
|
||||
expect(entityViewsRoute).toContain('adminPath("entities/views"');
|
||||
expect(adminRoutes).toContain("settings");
|
||||
expect(adminRoutes).toContain("entities/views");
|
||||
expect(adminRoutes).not.toContain("version");
|
||||
expect(adminRoutes).not.toContain("entities/views/all");
|
||||
});
|
||||
|
||||
it("keeps onboarding session fallbacks on admin-scoped route targets", () => {
|
||||
const onboardingSessionApi = fs.readFileSync(resolveRepoPath("apps/web/app/modules/onboarding/routes/api/sessions/OnboardingSessionOverviewApi.server.ts"), "utf8");
|
||||
|
||||
expect(onboardingSessionApi).not.toContain('redirect("/onboarding/sessions"');
|
||||
expect(onboardingSessionApi).toContain('adminPath("onboarding/sessions"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useEffect } from "react";
|
||||
import { Outlet, useLocation, useNavigate, redirect, MetaFunction, LoaderFunctionArgs } from "react-router";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
export function isAdminAnalyticsRootPath(pathname: string) {
|
||||
return UrlUtils.stripTrailingSlash(pathname) === adminPath("analytics", { mode: "host-aware" });
|
||||
}
|
||||
|
||||
export function adminAnalyticsRedirectTarget() {
|
||||
return adminPath("analytics/overview", { mode: "host-aware" });
|
||||
}
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const { t } = await getTranslations(request);
|
||||
if (isAdminAnalyticsRootPath(new URL(request.url).pathname)) {
|
||||
throw redirect(adminAnalyticsRedirectTarget());
|
||||
}
|
||||
|
||||
return {
|
||||
title: `${t("analytics.title")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminAnalticsRoute() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdminAnalyticsRootPath(location.pathname)) {
|
||||
navigate(adminAnalyticsRedirectTarget());
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [location.pathname]);
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
type MigratedAnalyticsRoute = {
|
||||
path: string;
|
||||
packageImports: string[];
|
||||
};
|
||||
|
||||
const migratedAnalyticsRoutes: MigratedAnalyticsRoute[] = [
|
||||
{
|
||||
path: "overview.tsx",
|
||||
packageImports: ["getAnalyticsOverview"],
|
||||
},
|
||||
{
|
||||
path: "visitors.tsx",
|
||||
packageImports: ["getAnalyticsVisitorList"],
|
||||
},
|
||||
{
|
||||
path: "events.tsx",
|
||||
packageImports: ["getAnalyticsEventFilterOptions", "getAnalyticsEventList"],
|
||||
},
|
||||
{
|
||||
path: "page-views.tsx",
|
||||
packageImports: ["getAnalyticsPageViewFilterOptions", "getAnalyticsPageViewList"],
|
||||
},
|
||||
{
|
||||
path: "settings.tsx",
|
||||
packageImports: ["deleteAllAnalyticsData", "getOrCreateAnalyticsSettings", "removeAnalyticsIgnoredPage", "updateAnalyticsSettingsPreferences"],
|
||||
},
|
||||
];
|
||||
|
||||
const forbiddenAnalyticsBoundaryImports = [
|
||||
"~/utils/db.server",
|
||||
"~/utils/helpers/.server/AnalyticsService",
|
||||
"~/utils/db/users.db.server",
|
||||
"~/modules/featureFlags/db/featureFlags.db.server",
|
||||
];
|
||||
|
||||
function readRouteSource(path: string) {
|
||||
return readFileSync(new URL(path, import.meta.url), "utf8");
|
||||
}
|
||||
|
||||
describe("migrated admin analytics route DB boundary imports", () => {
|
||||
it("uses the package-owned analytics server helpers in every migrated route", () => {
|
||||
for (const route of migratedAnalyticsRoutes) {
|
||||
const source = readRouteSource(route.path);
|
||||
|
||||
expect(source, `${route.path} should import the analytics package boundary`).toContain("@toolctrl/db/analytics.server");
|
||||
for (const packageImport of route.packageImports) {
|
||||
expect(source, `${route.path} should import ${packageImport}`).toContain(packageImport);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("does not reintroduce app-local analytics DB imports in migrated routes", () => {
|
||||
for (const route of migratedAnalyticsRoutes) {
|
||||
const source = readRouteSource(route.path);
|
||||
|
||||
for (const forbiddenImport of forbiddenAnalyticsBoundaryImports) {
|
||||
expect(source, `${route.path} should not import ${forbiddenImport}`).not.toContain(forbiddenImport);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/admin/analytics/events.tsx";
|
||||
|
||||
function readRoute() {
|
||||
return readRepoFile(routePath);
|
||||
}
|
||||
|
||||
describe("admin analytics events route DB boundary", () => {
|
||||
it("uses package analytics helpers for filter options and list reads", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsEventFilterOptions");
|
||||
expect(source).toContain("getAnalyticsEventList");
|
||||
expect(source).toContain("RowFiltersHelper.getFiltersCondition(filters)");
|
||||
});
|
||||
|
||||
it("does not import direct analytics DB wrappers", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).not.toContain('from "~/utils/db.server"');
|
||||
expect(source).not.toContain('from "~/modules/featureFlags/db/featureFlags.db.server"');
|
||||
expect(source).not.toMatch(/\bdb\.analyticsEvent\b/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
import { AnalyticsEvent, AnalyticsUniqueVisitor } from "@toolctrl/db/prisma-browser";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { LoaderFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getAnalyticsEventFilterOptions, getAnalyticsEventList } from "@toolctrl/db/analytics.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
items: (AnalyticsEvent & { uniqueVisitor: AnalyticsUniqueVisitor })[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const filterOptions = await getAnalyticsEventFilterOptions();
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "action",
|
||||
title: "analytics.action",
|
||||
options: filterOptions.actions,
|
||||
},
|
||||
{
|
||||
name: "category",
|
||||
title: "analytics.category",
|
||||
options: filterOptions.categories,
|
||||
},
|
||||
{
|
||||
name: "label",
|
||||
title: "analytics.label",
|
||||
options: filterOptions.labels,
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: "analytics.value",
|
||||
options: filterOptions.values,
|
||||
},
|
||||
{
|
||||
name: "featureFlagId",
|
||||
title: "featureFlags.object",
|
||||
options: filterOptions.featureFlags,
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(searchParams);
|
||||
const where = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const { items, totalItems } = await getAnalyticsEventList({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items: items as LoaderData["items"],
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsEventsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<div className="flex justify-between gap-2">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
</div>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: i18nT("analytics.date"),
|
||||
value: (i) => (
|
||||
<time title={formatters.dateTime(i.createdAt, { timeStyle: "medium" })} className="text-muted-foreground text-xs">
|
||||
{formatters.relativeDate(i.createdAt)}
|
||||
</time>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "action",
|
||||
title: i18nT("analytics.action"),
|
||||
value: (i) => i.action,
|
||||
},
|
||||
{
|
||||
name: "category",
|
||||
title: i18nT("analytics.category"),
|
||||
value: (i) => i.category,
|
||||
},
|
||||
{
|
||||
name: "label",
|
||||
title: i18nT("analytics.label"),
|
||||
value: (i) => i.label,
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: i18nT("analytics.value"),
|
||||
value: (i) => i.value,
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: i18nT("analytics.url"),
|
||||
value: (i) => i.url,
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: i18nT("analytics.cookie"),
|
||||
value: (i) => <div className="truncate">{i.uniqueVisitor.cookie}</div>,
|
||||
className: "max-w-xs",
|
||||
},
|
||||
{
|
||||
name: "httpReferrer",
|
||||
title: i18nT("analytics.httpReferrer"),
|
||||
value: (i) => i.uniqueVisitor.httpReferrer,
|
||||
},
|
||||
{
|
||||
name: "browser",
|
||||
title: i18nT("analytics.browser"),
|
||||
value: (i) => i.uniqueVisitor.browser,
|
||||
},
|
||||
{
|
||||
name: "os",
|
||||
title: i18nT("analytics.os"),
|
||||
value: (i) => i.uniqueVisitor.os,
|
||||
},
|
||||
{
|
||||
name: "device",
|
||||
title: i18nT("analytics.device"),
|
||||
value: (i) => i.uniqueVisitor.device,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: i18nT("analytics.source"),
|
||||
value: (i) => i.uniqueVisitor.source,
|
||||
},
|
||||
{
|
||||
name: "medium",
|
||||
title: i18nT("analytics.medium"),
|
||||
value: (i) => i.uniqueVisitor.medium,
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
title: i18nT("analytics.campaign"),
|
||||
value: (i) => i.uniqueVisitor.campaign,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
title: i18nT("analytics.content"),
|
||||
value: (i) => i.uniqueVisitor.content,
|
||||
},
|
||||
{
|
||||
name: "term",
|
||||
title: i18nT("analytics.term"),
|
||||
value: (i) => i.uniqueVisitor.term,
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: i18nT("analytics.country"),
|
||||
value: (i) => i.uniqueVisitor.country,
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: i18nT("analytics.city"),
|
||||
value: (i) => i.uniqueVisitor.city,
|
||||
},
|
||||
{
|
||||
name: "fromUrl",
|
||||
title: i18nT("analytics.fromUrl"),
|
||||
value: (i) => i.uniqueVisitor.fromUrl,
|
||||
},
|
||||
{
|
||||
name: "fromRoute",
|
||||
title: i18nT("analytics.fromRoute"),
|
||||
value: (i) => i.uniqueVisitor.fromRoute,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/admin/analytics/overview.tsx";
|
||||
const tableRoutePaths = ["apps/web/app/routes/admin/analytics/visitors.tsx", "apps/web/app/routes/admin/analytics/events.tsx", "apps/web/app/routes/admin/analytics/page-views.tsx"];
|
||||
|
||||
function readRoute(route = routePath) {
|
||||
return readRepoFile(route);
|
||||
}
|
||||
|
||||
describe("admin analytics overview route DB boundary", () => {
|
||||
it("uses the package analytics overview helper", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsOverview");
|
||||
expect(source).toContain("withUsers: true");
|
||||
expect(source).toContain("portalId: undefined");
|
||||
expect(source).toContain("getTranslations(request)");
|
||||
expect(source).toContain("locale,");
|
||||
});
|
||||
|
||||
it("validates the period before calling the package helper", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("PeriodHelper.getPeriodFromRequest({ request })");
|
||||
expect(source).toContain("isAnalyticsPeriod(period) ? period : defaultAnalyticsPeriod");
|
||||
});
|
||||
|
||||
it("does not import the legacy AnalyticsService", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).not.toContain("~/utils/helpers/.server/AnalyticsService");
|
||||
});
|
||||
|
||||
it("keeps migrated table routes behind the package analytics boundary", () => {
|
||||
for (const tableRoutePath of tableRoutePaths) {
|
||||
const source = readRoute(tableRoutePath);
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).not.toContain('from "~/utils/db.server"');
|
||||
expect(source).not.toContain('from "~/utils/db/users.db.server"');
|
||||
expect(source).not.toContain('from "~/modules/featureFlags/db/featureFlags.db.server"');
|
||||
expect(source).not.toMatch(/\bdb\.analytics(?:UniqueVisitor|Event|PageView)\b/);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps migrated table route dates on locale-aware formatters", () => {
|
||||
const source = tableRoutePaths.map((tableRoutePath) => readRoute(tableRoutePath)).join("\n");
|
||||
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.dateTime");
|
||||
expect(source).toContain("formatters.relativeDate");
|
||||
expect(source).not.toContain("DateUtils");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { LoaderFunction } from "react-router";
|
||||
import { useLoaderData, useSearchParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import AnalyticsOverview from "~/components/analytics/AnalyticsOverview";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { defaultAnalyticsPeriod, getAnalyticsOverview, isAnalyticsPeriod, type AnalyticsOverview as AnalyticsOverviewDto } from "@toolctrl/db/analytics.server";
|
||||
import PeriodHelper, { defaultPeriodFilter, PeriodFilters } from "~/utils/helpers/PeriodHelper";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
overview: AnalyticsOverviewDto;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const { locale } = await getTranslations(request);
|
||||
const period = PeriodHelper.getPeriodFromRequest({ request });
|
||||
const data: LoaderData = {
|
||||
overview: await getAnalyticsOverview({
|
||||
withUsers: true,
|
||||
period: isAnalyticsPeriod(period) ? period : defaultAnalyticsPeriod,
|
||||
portalId: undefined,
|
||||
locale,
|
||||
}),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { overview } = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<div className="flex justify-between gap-2">
|
||||
<Tabs
|
||||
breakpoint="lg"
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
|
||||
<InputSelector
|
||||
className="w-44"
|
||||
withSearch={false}
|
||||
name="period"
|
||||
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
|
||||
options={PeriodFilters.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: t(f.name),
|
||||
};
|
||||
})}
|
||||
setValue={(value) => {
|
||||
if (value && value !== defaultPeriodFilter) {
|
||||
searchParams.set("period", value?.toString() ?? "");
|
||||
} else {
|
||||
searchParams.delete("period");
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AnalyticsOverview overview={overview} withUsers={true} rootUrl={adminPath("analytics", { mode: "host-aware" })} />
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/admin/analytics/page-views.tsx";
|
||||
|
||||
function readRoute() {
|
||||
return readRepoFile(routePath);
|
||||
}
|
||||
|
||||
describe("admin analytics page views route DB boundary", () => {
|
||||
it("uses package analytics helpers while preserving route-side filter composition", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsPageViewFilterOptions");
|
||||
expect(source).toContain("getAnalyticsPageViewList");
|
||||
expect(source).toContain("RowFiltersHelper.getFiltersCondition(filters)");
|
||||
expect(source).toContain("portalFiltersEnabled");
|
||||
expect(source).toContain('f.name === "cookie"');
|
||||
expect(source).toContain('f.name === "userId"');
|
||||
});
|
||||
|
||||
it("does not import direct analytics DB wrappers", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).not.toContain('from "~/utils/db.server"');
|
||||
expect(source).not.toContain('from "~/utils/db/users.db.server"');
|
||||
expect(source).not.toMatch(/\bdb\.analytics(?:UniqueVisitor|PageView)\b/);
|
||||
expect(source).not.toMatch(/\bdb\.portal\b/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import { AnalyticsPageView, AnalyticsUniqueVisitor, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { LoaderFunction, useLoaderData } from "react-router";
|
||||
import { useSearchParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getAnalyticsPageViewFilterOptions, getAnalyticsPageViewList } from "@toolctrl/db/analytics.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
items: (AnalyticsPageView & {
|
||||
uniqueVisitor: AnalyticsUniqueVisitor & {
|
||||
user: { email: string } | null;
|
||||
};
|
||||
portal: { id: string; title: string } | null;
|
||||
})[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
|
||||
const portalFiltersEnabled = Boolean(appConfiguration.portals?.enabled && appConfiguration.portals?.analytics);
|
||||
const filterOptions = await getAnalyticsPageViewFilterOptions({ includePortals: portalFiltersEnabled });
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "route",
|
||||
title: t("analytics.route"),
|
||||
options: filterOptions.routes,
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: t("models.user.object"),
|
||||
manual: true,
|
||||
options: [{ name: t("analytics.anonymous"), value: "null" }, ...filterOptions.users],
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: t("analytics.cookie"),
|
||||
manual: true,
|
||||
},
|
||||
];
|
||||
if (portalFiltersEnabled) {
|
||||
filterableProperties.push({
|
||||
name: "portalId",
|
||||
title: t("models.portal.object"),
|
||||
options: [
|
||||
{
|
||||
value: "null",
|
||||
name: t("analytics.none"),
|
||||
},
|
||||
...filterOptions.portals,
|
||||
],
|
||||
});
|
||||
}
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
let where: Prisma.AnalyticsPageViewWhereInput = RowFiltersHelper.getFiltersCondition(filters);
|
||||
|
||||
const cookieFilter = filters.properties.find((f) => f.name === "cookie");
|
||||
if (cookieFilter?.value) {
|
||||
where = { ...where, uniqueVisitor: { cookie: cookieFilter.value } };
|
||||
}
|
||||
|
||||
const userFilter = filters.properties.find((f) => f.name === "userId");
|
||||
if (userFilter?.value) {
|
||||
where = { ...where, uniqueVisitor: { userId: userFilter.value === "null" ? null : userFilter.value } };
|
||||
}
|
||||
|
||||
const { items, totalItems } = await getAnalyticsPageViewList({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items: items as LoaderData["items"],
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsPageViewsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const rootData = useRootData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const portalsConfig = rootData?.appConfiguration.portals;
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<div className="flex justify-between gap-2">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
</div>
|
||||
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: t("analytics.date"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
<div>
|
||||
{i.uniqueVisitor.user ? (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (!i.uniqueVisitor.userId) return;
|
||||
searchParams.set("userId", i.uniqueVisitor.userId);
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
disabled={!i.uniqueVisitor.userId}
|
||||
className="underline"
|
||||
>
|
||||
<div className="text-xs">{i.uniqueVisitor.user.email}</div>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
searchParams.set("cookie", i.uniqueVisitor.cookie);
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
className="underline"
|
||||
>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
<span>{t("analytics.anonymous")}</span>: {i.uniqueVisitor.cookie.substring(0, 5) + "..."}
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<time title={formatters.dateTime(i.createdAt, { timeStyle: "medium" })} className="text-muted-foreground text-xs">
|
||||
{formatters.relativeDate(i.createdAt)}
|
||||
</time>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: t("analytics.url"),
|
||||
value: (i) => (
|
||||
<div className="max-w-xs truncate">
|
||||
<div className="truncate font-medium">{i.url}</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
searchParams.set("route", i.route ?? "null");
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
className="truncate underline"
|
||||
>
|
||||
<div className="text-muted-foreground text-xs">{i.url !== i.route && i.route}</div>
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "portal",
|
||||
title: t("models.portal.object"),
|
||||
value: (i) => <div className="text-muted-foreground font-medium">{i.portal?.title}</div>,
|
||||
hidden: !portalsConfig?.enabled || !portalsConfig?.analytics,
|
||||
},
|
||||
{
|
||||
name: "httpReferrer",
|
||||
title: t("analytics.httpReferrer"),
|
||||
value: (i) => <div className="max-w-xs truncate">{i.uniqueVisitor.httpReferrer}</div>,
|
||||
},
|
||||
{
|
||||
name: "via",
|
||||
title: t("analytics.via"),
|
||||
value: (i) => i.uniqueVisitor.via,
|
||||
},
|
||||
{
|
||||
name: "browser",
|
||||
title: t("analytics.browser"),
|
||||
value: (i) => i.uniqueVisitor.browser,
|
||||
},
|
||||
{
|
||||
name: "os",
|
||||
title: t("analytics.os"),
|
||||
value: (i) => i.uniqueVisitor.os,
|
||||
},
|
||||
{
|
||||
name: "device",
|
||||
title: t("analytics.device"),
|
||||
value: (i) => i.uniqueVisitor.device,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: t("analytics.source"),
|
||||
value: (i) => i.uniqueVisitor.source,
|
||||
},
|
||||
{
|
||||
name: "medium",
|
||||
title: t("analytics.medium"),
|
||||
value: (i) => i.uniqueVisitor.medium,
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
title: t("analytics.campaign"),
|
||||
value: (i) => i.uniqueVisitor.campaign,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
title: t("analytics.content"),
|
||||
value: (i) => i.uniqueVisitor.content,
|
||||
},
|
||||
{
|
||||
name: "term",
|
||||
title: t("analytics.term"),
|
||||
value: (i) => i.uniqueVisitor.term,
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: t("analytics.country"),
|
||||
value: (i) => i.uniqueVisitor.country,
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: t("analytics.city"),
|
||||
value: (i) => i.uniqueVisitor.city,
|
||||
},
|
||||
{
|
||||
name: "fromUrl",
|
||||
title: t("analytics.fromUrl"),
|
||||
value: (i) => (
|
||||
<div className="max-w-xs truncate">
|
||||
<div className="truncate font-medium">{i.uniqueVisitor.fromUrl}</div>
|
||||
<div className="text-muted-foreground text-xs">{i.uniqueVisitor.fromUrl !== i.uniqueVisitor.fromRoute && i.uniqueVisitor.fromRoute}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
|
||||
vi.mock("@toolctrl/db/analytics.server", () => ({
|
||||
deleteAllAnalyticsData: vi.fn(),
|
||||
getOrCreateAnalyticsSettings: vi.fn(),
|
||||
removeAnalyticsIgnoredPage: vi.fn(),
|
||||
updateAnalyticsSettingsPreferences: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/impersonation-audit.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("@toolctrl/db/impersonation-audit.server")>("@toolctrl/db/impersonation-audit.server");
|
||||
return {
|
||||
...actual,
|
||||
createImpersonationAudit: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
import { deleteAllAnalyticsData } from "@toolctrl/db/analytics.server";
|
||||
import { createImpersonationAudit, IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { action } from "./settings";
|
||||
|
||||
function deleteAllRequest(body: Record<string, string> = {}) {
|
||||
return new Request("https://admin.example.test/analytics/settings?tab=danger", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: "delete-all", ...body }),
|
||||
});
|
||||
}
|
||||
|
||||
async function callDeleteAll(body: Record<string, string> = {}) {
|
||||
return action({
|
||||
request: deleteAllRequest(body),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/analytics/settings",
|
||||
} as ActionFunctionArgs) as Promise<Response>;
|
||||
}
|
||||
|
||||
describe("admin analytics settings route DB boundary", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user-1", lightOrDarkMode: "light", lng: "en", cookies: [] } as never);
|
||||
});
|
||||
|
||||
it("uses package-owned analytics settings helpers", () => {
|
||||
expect(deleteAllAnalyticsData).toBeDefined();
|
||||
});
|
||||
|
||||
it("keeps visible delete confirmation text behind locale keys", () => {
|
||||
const source = readFileSync(path.resolve(process.cwd(), "apps/web/app/routes/admin/analytics/settings.tsx"), "utf8");
|
||||
const en = JSON.parse(readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/en/translations.json"), "utf8"));
|
||||
const de = JSON.parse(readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/de/translations.json"), "utf8"));
|
||||
|
||||
expect(source).toContain("analytics.danger.confirmText");
|
||||
expect(source).not.toContain('"delete all analytics data"');
|
||||
expect(source).not.toContain("`delete all analytics data`");
|
||||
expect(en.analytics.danger.confirmText).toBe("delete all analytics data");
|
||||
expect(de.analytics.danger.confirmText).toBe("alle Analytics-Daten löschen");
|
||||
});
|
||||
|
||||
it("deletes analytics data for normal sessions", async () => {
|
||||
const response = await callDeleteAll();
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ deleteSuccess: true });
|
||||
expect(response.status).toBe(200);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.analytics.delete");
|
||||
expect(deleteAllAnalyticsData).toHaveBeenCalledTimes(1);
|
||||
expect(createImpersonationAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("blocks impersonated deletion without the explicit impersonation phrase", async () => {
|
||||
vi.mocked(getUserInfo).mockResolvedValue({
|
||||
userId: "target-user-1",
|
||||
impersonatingFromUserId: "actor-user-1",
|
||||
lightOrDarkMode: "light",
|
||||
lng: "en",
|
||||
cookies: [],
|
||||
} as never);
|
||||
|
||||
const response = await callDeleteAll({ "impersonation-confirm": "delete all analytics data" });
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ deleteError: "admin.analytics.settings.errors.confirmImpersonatedDelete" });
|
||||
expect(response.status).toBe(400);
|
||||
expect(deleteAllAnalyticsData).not.toHaveBeenCalled();
|
||||
expect(createImpersonationAudit).toHaveBeenCalledWith({
|
||||
actorUserId: "actor-user-1",
|
||||
targetUserId: "target-user-1",
|
||||
tenantId: null,
|
||||
action: "destructive_action_blocked",
|
||||
reason: "analytics.delete-all",
|
||||
requestPath: "/analytics/settings",
|
||||
});
|
||||
});
|
||||
|
||||
it("allows impersonated deletion with the explicit impersonation phrase", async () => {
|
||||
vi.mocked(getUserInfo).mockResolvedValue({
|
||||
userId: "target-user-1",
|
||||
impersonatingFromUserId: "actor-user-1",
|
||||
lightOrDarkMode: "light",
|
||||
lng: "en",
|
||||
cookies: [],
|
||||
} as never);
|
||||
|
||||
const response = await callDeleteAll({ "impersonation-confirm": IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION });
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ deleteSuccess: true });
|
||||
expect(response.status).toBe(200);
|
||||
expect(deleteAllAnalyticsData).toHaveBeenCalledTimes(1);
|
||||
expect(createImpersonationAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,262 @@
|
||||
import { loadWebConfig } from "@toolctrl/config";
|
||||
import type { AnalyticsSettings } from "@toolctrl/db/analytics.server";
|
||||
import {
|
||||
deleteAllAnalyticsData,
|
||||
getOrCreateAnalyticsSettings,
|
||||
removeAnalyticsIgnoredPage,
|
||||
updateAnalyticsSettingsPreferences,
|
||||
} from "@toolctrl/db/analytics.server";
|
||||
import { IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION } from "@toolctrl/db/impersonation-audit.constants";
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { extractWebActorIp, extractWebActorUserAgent } from "~/utils/audit/withAuditContext";
|
||||
import { ActionFunction, LoaderFunction } from "react-router";
|
||||
import { Form, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absoluteAdminPath } from "~/utils/app/CrossHostUrls";
|
||||
|
||||
type LoaderData = {
|
||||
settings: AnalyticsSettings;
|
||||
isLocalDev: boolean;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.delete");
|
||||
const settings = await getOrCreateAnalyticsSettings();
|
||||
const data: LoaderData = {
|
||||
settings,
|
||||
isLocalDev: loadWebConfig().config.nodeEnv === "development",
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
deleteError?: string;
|
||||
deleteSuccess?: boolean;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.delete");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "delete-all") {
|
||||
const userInfo = await getUserInfo(request);
|
||||
const impersonationConfirmation = form.get("impersonation-confirm")?.toString() ?? "";
|
||||
if (userInfo.impersonatingFromUserId && impersonationConfirmation !== IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION) {
|
||||
await createImpersonationAudit({
|
||||
actorUserId: userInfo.impersonatingFromUserId,
|
||||
targetUserId: userInfo.userId,
|
||||
tenantId: null,
|
||||
action: "destructive_action_blocked",
|
||||
reason: "analytics.delete-all",
|
||||
requestPath: new URL(request.url).pathname,
|
||||
});
|
||||
// Phase 10 Task #67: consolidated AuditEvent for compliance export.
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.impersonatingFromUserId,
|
||||
actorType: "admin",
|
||||
actorIp: extractWebActorIp(request),
|
||||
actorUserAgent: extractWebActorUserAgent(request),
|
||||
action: "admin.impersonation.destructive_blocked",
|
||||
targetType: "user",
|
||||
targetId: userInfo.userId,
|
||||
sourceModule: "admin",
|
||||
outcome: "blocked",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: { requestPath: new URL(request.url).pathname, reason: "analytics.delete-all" },
|
||||
});
|
||||
return Response.json({ deleteError: t("admin.analytics.settings.errors.confirmImpersonatedDelete") }, { status: 400 });
|
||||
}
|
||||
|
||||
await deleteAllAnalyticsData();
|
||||
return Response.json({
|
||||
deleteSuccess: true,
|
||||
});
|
||||
}
|
||||
if (action === "set-settings") {
|
||||
const isPublicStr = form.get("public");
|
||||
const isPublic = isPublicStr === "true" || isPublicStr === "on";
|
||||
const ignorePage = form.get("ignore-page")?.toString() ?? "";
|
||||
await updateAnalyticsSettingsPreferences({ public: isPublic, ignorePage });
|
||||
return Response.json({
|
||||
setSettingsSuccess: true,
|
||||
});
|
||||
}
|
||||
if (action === "remove-ignored-page") {
|
||||
const ignoredPage = form.get("ignored-page")?.toString() ?? "";
|
||||
await removeAnalyticsIgnoredPage(ignoredPage);
|
||||
return Response.json({
|
||||
setSettingsSuccess: true,
|
||||
});
|
||||
} else {
|
||||
return Response.json({
|
||||
error: t("shared.invalidForm"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const isUpdatingSettings = navigation.state === "submitting" && navigation.formData?.get("action") === "set-settings";
|
||||
const rootData = useRootData();
|
||||
const analyticsOverviewUrl = absoluteAdminPath(rootData.routing, "analytics/overview");
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
const textToType = t("analytics.danger.confirmText");
|
||||
|
||||
const [typeToConfirm, setTypeToConfirm] = useState<string>(data.isLocalDev ? textToType : "");
|
||||
const [isPublic, setIsPublic] = useState(data?.settings.public);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isUpdatingSettings) {
|
||||
formRef.current?.reset();
|
||||
}
|
||||
}, [isUpdatingSettings]);
|
||||
|
||||
function removeIgnoredPage(item: string) {
|
||||
const form = new FormData();
|
||||
form.set("action", "remove-ignored-page");
|
||||
form.set("ignored-page", item);
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete-all");
|
||||
form.set("impersonation-confirm", typeToConfirm);
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
const impersonationTextToType = IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION;
|
||||
const requiredDeleteConfirmation = rootData.impersonatingSession ? impersonationTextToType : textToType;
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<div className="flex justify-between gap-2">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6 p-4 sm:px-6 lg:col-span-9 lg:px-0">
|
||||
<SettingSection title={t("analytics.preferences.title")} description={t("analytics.preferences.description")}>
|
||||
<Form ref={formRef} method="post">
|
||||
<input hidden readOnly name="action" value="set-settings" />
|
||||
<input hidden readOnly name="csrf" value={rootData.csrf ?? ""} />
|
||||
<div className="space-y-2">
|
||||
<InputCheckboxWithDescription
|
||||
name="public"
|
||||
title={t("shared.public")}
|
||||
description={
|
||||
<div className="text-muted-foreground">
|
||||
{t("analytics.preferences.publicDescription")}{" "}
|
||||
<a className="underline" target="_blank" rel="noreferrer" href={analyticsOverviewUrl}>
|
||||
{analyticsOverviewUrl}
|
||||
</a>
|
||||
</div>
|
||||
}
|
||||
value={isPublic}
|
||||
setValue={setIsPublic}
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<div className="text-muted-foreground text-sm font-medium">{t("analytics.preferences.ignoredPages")}</div>
|
||||
<div className="border-border bg-secondary space-y-1 rounded-md border p-3">
|
||||
{data.settings.ignorePages.length === 0 && <div className="text-muted-foreground text-xs">{t("analytics.preferences.noIgnoredPages")}</div>}
|
||||
{data.settings.ignorePages
|
||||
.split(",")
|
||||
.filter((f) => f)
|
||||
.map((item) => {
|
||||
return (
|
||||
<div key={item} className="text-muted-foreground border-border group flex space-x-2 border-b text-xs">
|
||||
<div>{item}</div>
|
||||
<button type="button" className="hidden text-xs text-red-500 underline group-hover:block" onClick={() => removeIgnoredPage(item)}>
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<InputText name="ignore-page" title={t("analytics.preferences.addIgnoredPage")} defaultValue="" />
|
||||
</div>
|
||||
<div className="border-border mt-3 flex items-center justify-end space-x-2 border-t pt-3">
|
||||
<LoadingButton type="submit" disabled={isUpdatingSettings}>
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
<SettingSection title={t("analytics.danger.title")} description={t("analytics.danger.description")}>
|
||||
<div>
|
||||
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
||||
<p>{t("analytics.danger.reset.description")}</p>
|
||||
</div>
|
||||
<div className="mt-5 space-y-2">
|
||||
<div>
|
||||
<InputText title={t("analytics.danger.confirm", { value: requiredDeleteConfirmation })} value={typeToConfirm} setValue={setTypeToConfirm} />
|
||||
</div>
|
||||
<div>
|
||||
<ButtonPrimary disabled={typeToConfirm !== requiredDeleteConfirmation} destructive={true} onClick={onDelete}>
|
||||
{t("analytics.danger.reset.title")}
|
||||
</ButtonPrimary>
|
||||
|
||||
{actionData?.deleteSuccess ? (
|
||||
<p className="py-2 text-xs text-green-500" role="alert">
|
||||
{t("analytics.deleted")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{actionData?.deleteError ? (
|
||||
<p className="py-2 text-xs text-rose-500" role="alert">
|
||||
{actionData.deleteError}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/admin/analytics/visitors.tsx";
|
||||
|
||||
function readRoute() {
|
||||
return readRepoFile(routePath);
|
||||
}
|
||||
|
||||
describe("admin analytics visitors route DB boundary", () => {
|
||||
it("uses the package analytics visitor list helper with pagination", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsVisitorList");
|
||||
expect(source).toContain("take: pagination.pageSize");
|
||||
expect(source).toContain("skip: pagination.pageSize * (pagination.page - 1)");
|
||||
});
|
||||
|
||||
it("does not import direct analytics DB access", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).not.toContain('from "~/utils/db.server"');
|
||||
expect(source).not.toMatch(/\bdb\.analyticsUniqueVisitor\b/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { AnalyticsUniqueVisitor } from "@toolctrl/db/prisma-browser";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { LoaderFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getAnalyticsVisitorList } from "@toolctrl/db/analytics.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
items: (AnalyticsUniqueVisitor & {
|
||||
_count: {
|
||||
pageViews: number;
|
||||
events: number;
|
||||
};
|
||||
})[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, totalItems } = await getAnalyticsVisitorList({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items: items as unknown as LoaderData["items"],
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsPageViewsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
|
||||
<div>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: i18nT("analytics.date"),
|
||||
value: (i) => (
|
||||
<time title={formatters.dateTime(i.createdAt, { timeStyle: "medium" })} className="text-muted-foreground text-xs">
|
||||
{formatters.relativeDate(i.createdAt)}
|
||||
</time>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "httpReferrer",
|
||||
title: i18nT("analytics.httpReferrer"),
|
||||
value: (i) => i.httpReferrer,
|
||||
},
|
||||
{
|
||||
name: "via",
|
||||
title: i18nT("analytics.via"),
|
||||
value: (i) => i.via,
|
||||
},
|
||||
{
|
||||
name: "browser",
|
||||
title: i18nT("analytics.browser"),
|
||||
value: (i) => i.browser,
|
||||
},
|
||||
{
|
||||
name: "os",
|
||||
title: i18nT("analytics.os"),
|
||||
value: (i) => i.os,
|
||||
},
|
||||
{
|
||||
name: "device",
|
||||
title: i18nT("analytics.device"),
|
||||
value: (i) => i.device,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: i18nT("analytics.source"),
|
||||
value: (i) => i.source,
|
||||
},
|
||||
{
|
||||
name: "medium",
|
||||
title: i18nT("analytics.medium"),
|
||||
value: (i) => i.medium,
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
title: i18nT("analytics.campaign"),
|
||||
value: (i) => i.campaign,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
title: i18nT("analytics.content"),
|
||||
value: (i) => i.content,
|
||||
},
|
||||
{
|
||||
name: "term",
|
||||
title: i18nT("analytics.term"),
|
||||
value: (i) => i.term,
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: i18nT("analytics.country"),
|
||||
value: (i) => i.country,
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: i18nT("analytics.city"),
|
||||
value: (i) => i.city,
|
||||
},
|
||||
{
|
||||
name: "fromUrl",
|
||||
title: i18nT("analytics.fromUrl"),
|
||||
value: (i) => i.fromUrl,
|
||||
},
|
||||
{
|
||||
name: "fromRoute",
|
||||
title: i18nT("analytics.fromRoute"),
|
||||
value: (i) => i.fromRoute,
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: i18nT("analytics.cookie"),
|
||||
value: (i) => i.cookie.substring(0, 5) + "...",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async (_: LoaderFunctionArgs) => {
|
||||
const data: LoaderData = {
|
||||
title: i18nT("admin.api.metaTitle", { appName: process.env.APP_NAME }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => <Outlet />;
|
||||
@@ -0,0 +1,108 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CreditsList from "~/modules/usage/components/CreditsList";
|
||||
import { CreditWithDetails, deleteCredits, getAllCredits } from "~/modules/usage/db/credits.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
items: CreditWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
canDelete: boolean;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
options: [
|
||||
{ value: "null", name: "{null}" },
|
||||
...(await adminGetAllTenantsIdsAndNames()).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.name,
|
||||
};
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: t("models.user.object"),
|
||||
options: [
|
||||
{ value: "null", name: "{null}" },
|
||||
...(await adminGetAllUsersNames()).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.email,
|
||||
};
|
||||
}),
|
||||
],
|
||||
},
|
||||
];
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const { items, pagination } = await getAllCredits({ tenantId: null, filters, filterableProperties, pagination: currentPagination });
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
filterableProperties,
|
||||
pagination,
|
||||
canDelete: true,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("action") === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
const ids = (form.get("ids")?.toString().split(",") ?? []).map((x) => x.toString() ?? "");
|
||||
await deleteCredits(ids);
|
||||
return Response.json({ success: true });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm"), success: false }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.credit.plural"),
|
||||
routePath: adminPath("api/credits", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<CreditsList data={data} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import ApiSpecsService, { ApiSpecsDto } from "~/modules/api/services/ApiSpecsService";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ApiSpecs from "~/modules/api/components/ApiSpecs";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type LoaderData = {
|
||||
apiSpecs: ApiSpecsDto;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const apiSpecs = await ApiSpecsService.generateSpecs({ request });
|
||||
const data: LoaderData = {
|
||||
apiSpecs,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("models.entity.apiDocs")}>
|
||||
<ApiSpecs item={data.apiSpecs} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { Fragment } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ApiKeyLogsSummary from "~/modules/api/components/ApiKeyLogsSummary";
|
||||
import { ApiCallSummaryDto } from "~/modules/api/dtos/ApiCallSummaryDto";
|
||||
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData =
|
||||
| { error: string }
|
||||
| {
|
||||
items: ApiCallSummaryDto[];
|
||||
allTenants: { id: string; name: string; slug: string }[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
try {
|
||||
const { items, allTenants, filterableProperties } = await ApiKeyLogService.getSummary({ request, params });
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
allTenants,
|
||||
filterableProperties,
|
||||
};
|
||||
return data;
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
{"error" in data ? (
|
||||
<ErrorBanner title={t(data.error)}>
|
||||
<Link to="." className="underline">
|
||||
{t("shared.clickHereToTryAgain")}
|
||||
</Link>
|
||||
</ErrorBanner>
|
||||
) : (
|
||||
<Fragment>
|
||||
<ApiKeyLogsSummary data={data} />
|
||||
</Fragment>
|
||||
)}
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ApiKeysTable from "~/components/core/apiKeys/ApiKeysTable";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { RedactedApiKeyWithDetails, getAllApiKeys } from "~/utils/db/apiKeys.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
apiKeys: RedactedApiKeyWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const apiKeys = await getAllApiKeys();
|
||||
const data: LoaderData = {
|
||||
apiKeys,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function AdminApiKeysRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
title={t("models.apiKey.plural")}
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ApiKeysTable
|
||||
canCreate={getUserHasPermission(adminData, "admin.apiKeys.create")}
|
||||
entities={adminData.entities}
|
||||
items={data.apiKeys}
|
||||
withTenant={true}
|
||||
/>
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
|
||||
import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { RedactedApiKeyWithDetails, adminGetApiKeyById, deleteApiKey, getApiKeys, updateApiKey } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { 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";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { ApiKeyDeletedDto } from "~/modules/events/dtos/ApiKeyDeletedDto";
|
||||
import { ApiKeyUpdatedDto } from "~/modules/events/dtos/ApiKeyUpdatedDto";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
tenants: Tenant[];
|
||||
item: RedactedApiKeyWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const item = await adminGetApiKeyById(params.id ?? "");
|
||||
if (!item) {
|
||||
return redirect(adminPath("api", { mode: "host-aware" }));
|
||||
}
|
||||
const tenants = await adminGetAllTenants();
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
tenants,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const currentUser = await getUser(userInfo.userId);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const existing = await adminGetApiKeyById(params.id ?? "");
|
||||
if (!existing) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
if (action === "edit") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.update");
|
||||
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) {
|
||||
expirationDate = new Date(expires);
|
||||
}
|
||||
const tenantId = form.get("tenant-id")?.toString() ?? "";
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const existingAlias = await getApiKeys(tenantId);
|
||||
if (existingAlias.filter((f) => f.id !== existing.id && f.alias === alias).length > 0) {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
await updateApiKey(
|
||||
params.id ?? "",
|
||||
{
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
},
|
||||
entities
|
||||
);
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active, entities }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
new: {
|
||||
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,
|
||||
});
|
||||
return redirect(adminPath(`api/keys`, { mode: "host-aware" }));
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
await deleteApiKey(params.id ?? "", existing.tenantId);
|
||||
await createAdminLog(request, "admin.apiKeys.deleted", "");
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.deleted",
|
||||
tenantId: existing.tenantId,
|
||||
userId: currentUser?.id ?? null,
|
||||
data: {
|
||||
id: existing.id,
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
entities: await getApiKeyEntityPermissions(existing.entities),
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
return redirect(adminPath(`api/keys`, { mode: "host-aware" }));
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminApiEditKeyRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
const adminData = useAdminData();
|
||||
return (
|
||||
<>
|
||||
<OpenModal className="sm:max-w-xl" onClose={() => navigate(adminPath(`api/keys`, { mode: "host-aware" }))}>
|
||||
<ApiKeyForm
|
||||
entities={adminData.entities}
|
||||
tenants={data.tenants}
|
||||
item={data.item}
|
||||
canUpdate={getUserHasPermission(adminData, "admin.apiKeys.update")}
|
||||
canDelete={getUserHasPermission(adminData, "admin.apiKeys.delete")}
|
||||
/>
|
||||
</OpenModal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData, useNavigate } from "react-router";
|
||||
import ApiKeyCreatedModal from "~/components/core/apiKeys/ApiKeyCreatedModal";
|
||||
import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
|
||||
import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { createApiKey, getApiKeyByAlias } from "~/utils/db/apiKeys.db.server";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { 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 { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { ApiKeyCreatedDto } from "~/modules/events/dtos/ApiKeyCreatedDto";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
tenants: Tenant[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.create");
|
||||
const tenants = await adminGetAllTenants();
|
||||
const data: LoaderData = {
|
||||
tenants,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
apiKey?: {
|
||||
key: string;
|
||||
alias: string;
|
||||
};
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.create");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const currentUser = await getUser(userInfo.userId);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
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) {
|
||||
expirationDate = new Date(expires);
|
||||
}
|
||||
const tenantId = form.get("tenant-id")?.toString() ?? "";
|
||||
const alias = form.get("alias")?.toString() ?? "";
|
||||
const existingAlias = await getApiKeyByAlias(tenantId, alias);
|
||||
if (existingAlias) {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
const apiKey = await createApiKey(
|
||||
{
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
},
|
||||
entities
|
||||
);
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active, entities }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
tenantId,
|
||||
userId: currentUser?.id ?? "",
|
||||
data: {
|
||||
id: apiKey.id,
|
||||
alias: apiKey.alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
entities: await getApiKeyEntityPermissions(entities),
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
});
|
||||
// return success({ apiKey });
|
||||
return redirect(adminPath("api/keys", { mode: "host-aware" }));
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminApiNewKeyRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const adminData = useAdminData();
|
||||
return (
|
||||
<>
|
||||
<OpenModal className="sm:max-w-xl" onClose={() => navigate(adminPath(`api/keys`, { mode: "host-aware" }))}>
|
||||
<ApiKeyForm entities={adminData.entities} tenants={data.tenants} />
|
||||
{actionData?.apiKey !== undefined && <ApiKeyCreatedModal apiKey={actionData?.apiKey} redirectTo={adminPath("api/keys", { mode: "host-aware" })} />}
|
||||
</OpenModal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import ApiKeyLogService from "~/modules/api/services/ApiKeyLogService";
|
||||
import { ApiKeyLogDto } from "~/modules/api/dtos/ApiKeyLogDto";
|
||||
import ApiKeyLogsDetails from "~/modules/api/components/ApiKeyLogsDetails";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
items: ApiKeyLogDto[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params, adminOnly: true });
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.view");
|
||||
const { items, filterableProperties, pagination } = await ApiKeyLogService.getDetails({ request, params });
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
filterableProperties,
|
||||
pagination,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params, adminOnly: true });
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("action") === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.apiKeys.delete");
|
||||
const ids = (form.get("ids")?.toString().split(",") ?? []).map((x) => x.toString() ?? "");
|
||||
await ApiKeyLogService.adminDeleteMany(ids);
|
||||
return Response.json({ success: true });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm"), success: false }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
routePath: adminPath("api", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiCall.plural"),
|
||||
routePath: adminPath("api/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.apiKey.plural"),
|
||||
routePath: adminPath("api/keys", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ApiKeyLogsDetails data={data} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Pure helpers for the audit-export route. Extracted so unit tests can
|
||||
* import them without dragging in the route module's server-only deps
|
||||
* (PrismaClient, getDbClient, session secret env vars).
|
||||
*/
|
||||
import { computeAuditHash } from "@toolctrl/db/audit-hash";
|
||||
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export const AUDIT_EXPORT_MAX_ROWS = 50_000;
|
||||
|
||||
export const AUDIT_EXPORT_CSV_COLUMNS = [
|
||||
"id",
|
||||
"createdAt",
|
||||
"tenantId",
|
||||
"actorType",
|
||||
"actorId",
|
||||
"actorEmail",
|
||||
"actorIp",
|
||||
"actorUserAgent",
|
||||
"action",
|
||||
"targetType",
|
||||
"targetId",
|
||||
"requestId",
|
||||
"sourceModule",
|
||||
"outcome",
|
||||
"dataSensitivity",
|
||||
"regulatoryScope",
|
||||
"metadata",
|
||||
"previousHash",
|
||||
"eventHash",
|
||||
] as const;
|
||||
|
||||
export type AuditExportFilters = {
|
||||
from: Date | null;
|
||||
to: Date | null;
|
||||
regulatoryScope: string[];
|
||||
actorType: string | null;
|
||||
outcome: string | null;
|
||||
tenantId: string | null;
|
||||
};
|
||||
|
||||
export type AuditExportRow = {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
tenantId: string | null;
|
||||
actorType: string;
|
||||
actorId: string | null;
|
||||
actorEmail: string | null;
|
||||
actorIp: string | null;
|
||||
actorUserAgent: string | null;
|
||||
action: string;
|
||||
targetType: string | null;
|
||||
targetId: string | null;
|
||||
requestId: string | null;
|
||||
sourceModule: string | null;
|
||||
outcome: string;
|
||||
dataSensitivity: string;
|
||||
regulatoryScope: string[];
|
||||
metadata: unknown;
|
||||
previousHash: string | null;
|
||||
eventHash: string | null;
|
||||
};
|
||||
|
||||
export type AuditIntegritySummary = {
|
||||
ok: boolean;
|
||||
inspected: number;
|
||||
firstBreakId: string | null;
|
||||
reason: string | null;
|
||||
};
|
||||
|
||||
export function parseAuditExportFilters(url: URL): AuditExportFilters {
|
||||
return {
|
||||
from: parseIsoDate(url.searchParams.get("from")),
|
||||
to: parseIsoDate(url.searchParams.get("to")),
|
||||
regulatoryScope: url.searchParams.getAll("regulatoryScope").map((s) => s.trim().toLowerCase()).filter(Boolean),
|
||||
actorType: url.searchParams.get("actorType")?.trim() || null,
|
||||
outcome: url.searchParams.get("outcome")?.trim() || null,
|
||||
tenantId: url.searchParams.get("tenantId")?.trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
function parseIsoDate(raw: string | null): Date | null {
|
||||
if (!raw || !ISO_DATE.test(raw)) return null;
|
||||
const d = new Date(`${raw}T00:00:00.000Z`);
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
export function buildAuditExportWhere(filters: AuditExportFilters): Record<string, unknown> {
|
||||
const where: Record<string, unknown> = {};
|
||||
if (filters.tenantId) where.tenantId = filters.tenantId;
|
||||
if (filters.actorType) where.actorType = filters.actorType;
|
||||
if (filters.outcome) where.outcome = filters.outcome;
|
||||
if (filters.regulatoryScope.length > 0) where.regulatoryScope = { hasSome: filters.regulatoryScope };
|
||||
if (filters.from || filters.to) {
|
||||
const range: Record<string, Date> = {};
|
||||
if (filters.from) range.gte = filters.from;
|
||||
if (filters.to) {
|
||||
const upper = new Date(filters.to);
|
||||
upper.setUTCDate(upper.getUTCDate() + 1);
|
||||
range.lt = upper;
|
||||
}
|
||||
where.createdAt = range;
|
||||
}
|
||||
return where;
|
||||
}
|
||||
|
||||
export function computeAuditIntegritySummary(rows: ReadonlyArray<AuditExportRow>): AuditIntegritySummary {
|
||||
const chains = new Map<string, AuditExportRow[]>();
|
||||
for (const row of rows) {
|
||||
const key = row.tenantId ?? "__platform__";
|
||||
const list = chains.get(key) ?? [];
|
||||
list.push(row);
|
||||
chains.set(key, list);
|
||||
}
|
||||
let inspected = 0;
|
||||
for (const [, list] of chains) {
|
||||
list.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
||||
let lastHash: string | null = null;
|
||||
for (const row of list) {
|
||||
if (row.eventHash === null) {
|
||||
lastHash = null;
|
||||
continue;
|
||||
}
|
||||
inspected += 1;
|
||||
if (row.previousHash !== lastHash) {
|
||||
return { ok: false, inspected, firstBreakId: row.id, reason: "previous-hash-mismatch" };
|
||||
}
|
||||
const recomputed = computeAuditHash({
|
||||
previousHash: row.previousHash,
|
||||
payload: {
|
||||
id: "",
|
||||
createdAt: "",
|
||||
tenantId: row.tenantId,
|
||||
actorType: row.actorType,
|
||||
actorId: row.actorId,
|
||||
actorEmail: row.actorEmail,
|
||||
actorIp: row.actorIp,
|
||||
actorUserAgent: row.actorUserAgent,
|
||||
action: row.action,
|
||||
targetType: row.targetType,
|
||||
targetId: row.targetId,
|
||||
requestId: row.requestId,
|
||||
sourceModule: row.sourceModule,
|
||||
outcome: row.outcome,
|
||||
dataSensitivity: row.dataSensitivity,
|
||||
regulatoryScope: row.regulatoryScope,
|
||||
metadata: row.metadata,
|
||||
},
|
||||
});
|
||||
if (recomputed !== row.eventHash) {
|
||||
return { ok: false, inspected, firstBreakId: row.id, reason: "hash-mismatch" };
|
||||
}
|
||||
lastHash = row.eventHash;
|
||||
}
|
||||
}
|
||||
return { ok: true, inspected, firstBreakId: null, reason: null };
|
||||
}
|
||||
|
||||
export function renderAuditExportCsv(rows: ReadonlyArray<AuditExportRow>, integrity: AuditIntegritySummary): string {
|
||||
const lines: string[] = [];
|
||||
lines.push(`# verifyAuditChain: ok=${integrity.ok} inspected=${integrity.inspected} firstBreakId=${integrity.firstBreakId ?? "-"} reason=${integrity.reason ?? "-"}`);
|
||||
lines.push(AUDIT_EXPORT_CSV_COLUMNS.join(","));
|
||||
for (const row of rows) {
|
||||
lines.push(
|
||||
AUDIT_EXPORT_CSV_COLUMNS.map((col) => {
|
||||
const value = (row as unknown as Record<string, unknown>)[col];
|
||||
return csvCell(value);
|
||||
}).join(",")
|
||||
);
|
||||
}
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
|
||||
export function csvCell(value: unknown): string {
|
||||
if (value === null || value === undefined) return "";
|
||||
if (Array.isArray(value)) return csvCell(value.join("|"));
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
if (typeof value === "object") return csvCell(JSON.stringify(value));
|
||||
const s = String(value);
|
||||
if (/[",\n\r]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
|
||||
return s;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { computeAuditHash } from "@toolctrl/db/audit-hash";
|
||||
import {
|
||||
AUDIT_EXPORT_MAX_ROWS,
|
||||
buildAuditExportWhere,
|
||||
computeAuditIntegritySummary,
|
||||
csvCell,
|
||||
parseAuditExportFilters,
|
||||
renderAuditExportCsv,
|
||||
type AuditExportRow,
|
||||
} from "./audit-export.helpers.server";
|
||||
|
||||
describe("admin audit-export filters", () => {
|
||||
it("parses ISO dates and rejects malformed values", () => {
|
||||
const f = parseAuditExportFilters(new URL("https://x/?from=2026-05-01&to=2026-05-17&actorType=admin&outcome=success®ulatoryScope=soc2®ulatoryScope=gdpr"));
|
||||
expect(f.from?.toISOString()).toBe("2026-05-01T00:00:00.000Z");
|
||||
expect(f.to?.toISOString()).toBe("2026-05-17T00:00:00.000Z");
|
||||
expect(f.actorType).toBe("admin");
|
||||
expect(f.outcome).toBe("success");
|
||||
expect(f.regulatoryScope).toEqual(["soc2", "gdpr"]);
|
||||
});
|
||||
|
||||
it("rejects bad dates as null", () => {
|
||||
expect(parseAuditExportFilters(new URL("https://x/?from=bad")).from).toBeNull();
|
||||
});
|
||||
|
||||
it("builds where with hasSome for regulatoryScope and inclusive date range", () => {
|
||||
const where = buildAuditExportWhere({ from: new Date("2026-05-01T00:00:00Z"), to: new Date("2026-05-02T00:00:00Z"), regulatoryScope: ["soc2"], actorType: null, outcome: null, tenantId: null }) as Record<string, unknown>;
|
||||
expect(where.regulatoryScope).toEqual({ hasSome: ["soc2"] });
|
||||
expect((where.createdAt as { lt: Date }).lt.toISOString()).toBe("2026-05-03T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("AUDIT_EXPORT_MAX_ROWS is set", () => {
|
||||
expect(AUDIT_EXPORT_MAX_ROWS).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin audit-export csv rendering", () => {
|
||||
it("escapes commas, quotes and newlines", () => {
|
||||
expect(csvCell("hello")).toBe("hello");
|
||||
expect(csvCell("a,b")).toBe('"a,b"');
|
||||
expect(csvCell('a"b')).toBe('"a""b"');
|
||||
expect(csvCell("line\nbreak")).toBe('"line\nbreak"');
|
||||
expect(csvCell(null)).toBe("");
|
||||
expect(csvCell(["a", "b"])).toBe("a|b");
|
||||
expect(csvCell({ a: 1 })).toBe('"{""a"":1}"');
|
||||
});
|
||||
|
||||
it("renders integrity header line and column row", () => {
|
||||
const csv = renderAuditExportCsv([], { ok: true, inspected: 0, firstBreakId: null, reason: null });
|
||||
const lines = csv.trim().split("\n");
|
||||
expect(lines[0]).toMatch(/^# verifyAuditChain: ok=true/);
|
||||
expect(lines[1]).toContain("id,createdAt,tenantId,actorType");
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin audit-export integrity verifier", () => {
|
||||
function payload(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
tenantId: "t1",
|
||||
actorType: "user",
|
||||
actorId: "u1",
|
||||
actorEmail: null,
|
||||
actorIp: null,
|
||||
actorUserAgent: null,
|
||||
action: "x.do",
|
||||
targetType: null,
|
||||
targetId: null,
|
||||
requestId: null,
|
||||
sourceModule: null,
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
regulatoryScope: [] as string[],
|
||||
metadata: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
function hashOf(prev: string | null, p: ReturnType<typeof payload>): string {
|
||||
return computeAuditHash({ previousHash: prev, payload: { id: "", createdAt: "", ...p } });
|
||||
}
|
||||
|
||||
it("returns ok for a valid 2-event chain", () => {
|
||||
const p1 = payload();
|
||||
const h1 = hashOf(null, p1);
|
||||
const p2 = payload({ action: "x.do2" });
|
||||
const h2 = hashOf(h1, p2);
|
||||
const rows: AuditExportRow[] = [
|
||||
{ id: "1", createdAt: new Date(1), previousHash: null, eventHash: h1, ...p1 },
|
||||
{ id: "2", createdAt: new Date(2), previousHash: h1, eventHash: h2, ...p2 },
|
||||
];
|
||||
expect(computeAuditIntegritySummary(rows)).toEqual({ ok: true, inspected: 2, firstBreakId: null, reason: null });
|
||||
});
|
||||
|
||||
it("detects tampered metadata", () => {
|
||||
const p1 = payload();
|
||||
const h1 = hashOf(null, p1);
|
||||
const rows: AuditExportRow[] = [
|
||||
{ id: "1", createdAt: new Date(1), previousHash: null, eventHash: h1, ...payload({ metadata: { tampered: true } }) },
|
||||
];
|
||||
const out = computeAuditIntegritySummary(rows);
|
||||
expect(out.ok).toBe(false);
|
||||
expect(out.reason).toBe("hash-mismatch");
|
||||
});
|
||||
|
||||
it("verifies chains independently per tenant", () => {
|
||||
const pA = payload({ tenantId: "tA" });
|
||||
const pB = payload({ tenantId: "tB", action: "y.do" });
|
||||
const hA = hashOf(null, pA);
|
||||
const hB = hashOf(null, pB);
|
||||
const rows: AuditExportRow[] = [
|
||||
{ id: "a", createdAt: new Date(1), previousHash: null, eventHash: hA, ...pA },
|
||||
{ id: "b", createdAt: new Date(2), previousHash: null, eventHash: hB, ...pB },
|
||||
];
|
||||
expect(computeAuditIntegritySummary(rows).ok).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Phase 10 Task #67 — Admin (system-wide) Compliance-Audit-Export.
|
||||
*
|
||||
* Streams a filtered CSV of AuditEvent rows across ALL tenants. Filters:
|
||||
* date range, regulatoryScope, actorType, outcome. The first CSV line is
|
||||
* a `# verifyAuditChain` integrity header so the download itself doubles
|
||||
* as evidence that the chain is intact.
|
||||
*
|
||||
* Tenant-scoped variant lives at routes/app.$tenant/settings/audit-export.tsx.
|
||||
*/
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import {
|
||||
AUDIT_EXPORT_MAX_ROWS,
|
||||
buildAuditExportWhere,
|
||||
computeAuditIntegritySummary,
|
||||
parseAuditExportFilters,
|
||||
renderAuditExportCsv,
|
||||
type AuditExportRow,
|
||||
} from "./audit-export.helpers.server";
|
||||
import { buildAuditPdfLabels, renderAuditExportPdfResponse } from "~/utils/audit/pdfRender";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
defaultFrom: string;
|
||||
defaultTo: string;
|
||||
maxRows: number;
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.searchParams.get("export") === "csv") {
|
||||
return streamAdminAuditExport(url);
|
||||
}
|
||||
if (url.searchParams.get("export") === "pdf" || url.searchParams.get("format") === "pdf") {
|
||||
return streamAdminAuditPdfExport(url, t);
|
||||
}
|
||||
|
||||
const today = new Date();
|
||||
const fromDate = new Date(today);
|
||||
fromDate.setDate(fromDate.getDate() - 30);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.log.plural")} | ${process.env.APP_NAME}`,
|
||||
defaultFrom: fromDate.toISOString().slice(0, 10),
|
||||
defaultTo: today.toISOString().slice(0, 10),
|
||||
maxRows: AUDIT_EXPORT_MAX_ROWS,
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
async function streamAdminAuditExport(url: URL): Promise<Response> {
|
||||
const filters = parseAuditExportFilters(url);
|
||||
const db = getDbClient();
|
||||
const rows = (await db.auditEvent.findMany({
|
||||
where: buildAuditExportWhere(filters),
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: AUDIT_EXPORT_MAX_ROWS,
|
||||
})) as unknown as AuditExportRow[];
|
||||
|
||||
const integrity = computeAuditIntegritySummary(rows);
|
||||
const csv = renderAuditExportCsv(rows, integrity);
|
||||
return new Response(csv, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="audit-export-admin-${url.searchParams.get("from") ?? "all"}_${url.searchParams.get("to") ?? "all"}.csv"`,
|
||||
"X-Audit-Chain-Status": integrity.ok ? "ok" : "broken",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function streamAdminAuditPdfExport(url: URL, t: Awaited<ReturnType<typeof getTranslations>>["t"]): Promise<Response> {
|
||||
const filters = parseAuditExportFilters(url);
|
||||
const db = getDbClient();
|
||||
const rows = (await db.auditEvent.findMany({
|
||||
where: buildAuditExportWhere(filters),
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: AUDIT_EXPORT_MAX_ROWS,
|
||||
})) as unknown as AuditExportRow[];
|
||||
const integrity = computeAuditIntegritySummary(rows);
|
||||
return renderAuditExportPdfResponse(
|
||||
{
|
||||
tenantId: filters.tenantId,
|
||||
filters,
|
||||
integrity,
|
||||
rows,
|
||||
labels: buildAuditPdfLabels(t),
|
||||
},
|
||||
{ filenamePrefix: "audit-export-admin" }
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminAuditExportRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const { t } = useTranslation(["settings", "translations"]);
|
||||
const formatters = useLocaleFormatters();
|
||||
return (
|
||||
<IndexPageLayout title={t("translations:models.log.plural")}>
|
||||
<div className="space-y-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-xl font-semibold">{t("translations:models.log.plural")}</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t(
|
||||
"auditExport.descriptionAdmin",
|
||||
{ maxRows: formatters.number(data.maxRows) }
|
||||
)}
|
||||
</p>
|
||||
</header>
|
||||
<form method="get" className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3" action="">
|
||||
<input type="hidden" name="export" value="csv" />
|
||||
<label className="text-sm">
|
||||
<span className="block">{t("auditExport.filters.fromUtc")}</span>
|
||||
<input type="date" name="from" defaultValue={data.defaultFrom} className="mt-1 w-full rounded border px-2 py-1" />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="block">{t("auditExport.filters.toUtc")}</span>
|
||||
<input type="date" name="to" defaultValue={data.defaultTo} className="mt-1 w-full rounded border px-2 py-1" />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="block">{t("auditExport.filters.tenantIdOptional")}</span>
|
||||
<input
|
||||
type="text"
|
||||
name="tenantId"
|
||||
className="mt-1 w-full rounded border px-2 py-1"
|
||||
placeholder={t("auditExport.filters.tenantIdPlaceholder")}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="block">{t("auditExport.filters.regulatoryScope")}</span>
|
||||
<select name="regulatoryScope" className="mt-1 w-full rounded border px-2 py-1" defaultValue="">
|
||||
<option value="">{t("auditExport.filters.any")}</option>
|
||||
<option value="soc2">{t("auditExport.scopes.soc2")}</option>
|
||||
<option value="gdpr">{t("auditExport.scopes.gdpr")}</option>
|
||||
<option value="hipaa">{t("auditExport.scopes.hipaa")}</option>
|
||||
<option value="pci">{t("auditExport.scopes.pci")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="block">{t("auditExport.filters.actorType")}</span>
|
||||
<select name="actorType" className="mt-1 w-full rounded border px-2 py-1" defaultValue="">
|
||||
<option value="">{t("auditExport.filters.any")}</option>
|
||||
<option value="user">{t("auditExport.actorTypes.user")}</option>
|
||||
<option value="admin">{t("auditExport.actorTypes.admin")}</option>
|
||||
<option value="api_key">{t("auditExport.actorTypes.apiKey")}</option>
|
||||
<option value="system">{t("auditExport.actorTypes.system")}</option>
|
||||
<option value="plugin">{t("auditExport.actorTypes.plugin")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="block">{t("auditExport.filters.outcome")}</span>
|
||||
<select name="outcome" className="mt-1 w-full rounded border px-2 py-1" defaultValue="">
|
||||
<option value="">{t("auditExport.filters.any")}</option>
|
||||
<option value="success">{t("auditExport.outcomes.success")}</option>
|
||||
<option value="failure">{t("auditExport.outcomes.failure")}</option>
|
||||
<option value="blocked">{t("auditExport.outcomes.blocked")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-3 sm:col-span-2 lg:col-span-3">
|
||||
<button type="submit" className="rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-500">
|
||||
{t("auditExport.downloadCsv")}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
name="export"
|
||||
value="pdf"
|
||||
className="rounded border border-blue-600 bg-white px-4 py-2 text-sm font-medium text-blue-600 hover:bg-blue-50"
|
||||
>
|
||||
{t("auditExport.downloadPdf")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</IndexPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loader } from "./audit-trails";
|
||||
import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@toolctrl/db/logs.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
Link: () => null,
|
||||
useLoaderData: () => ({}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/components/app/events/LogsTable", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/IndexPageLayout", () => ({ default: () => null }));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@toolctrl/db/logs.server", () => ({
|
||||
getAdminAuditLogList: vi.fn(),
|
||||
serializeAdminAuditLogsCsv: vi.fn(),
|
||||
}));
|
||||
|
||||
const auditRows = [
|
||||
{
|
||||
id: "log-1",
|
||||
createdAt: new Date("2026-05-08T10:00:00.000Z"),
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
apiKeyId: null,
|
||||
action: "create",
|
||||
url: "/acme/contacts",
|
||||
details: "redacted details",
|
||||
rowId: null,
|
||||
commentId: null,
|
||||
tenant: { id: "tenant-1", name: "Acme", slug: "acme" },
|
||||
user: { id: "user-1", email: "admin@example.test", firstName: "Ada", lastName: "Admin" },
|
||||
apiKey: null,
|
||||
comment: null,
|
||||
},
|
||||
];
|
||||
|
||||
function callLoader(url: string) {
|
||||
const request = new Request(url);
|
||||
return loader({ request, params: {}, context: {}, unstable_pattern: "admin/audit-trails" });
|
||||
}
|
||||
|
||||
function readAuditRoute() {
|
||||
return readRepoFile("apps/web/app/routes/admin/audit-trails.tsx");
|
||||
}
|
||||
|
||||
describe("admin audit trails route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(getAdminAuditLogList).mockResolvedValue({ rows: auditRows, total: 1, take: 25, skip: 25 } as never);
|
||||
vi.mocked(serializeAdminAuditLogsCsv).mockReturnValue("csv-body\n");
|
||||
});
|
||||
|
||||
it("checks permission before reading the filtered table data", async () => {
|
||||
const data = await callLoader(
|
||||
"https://admin.example.test/audit-trails?q=contact&action=create&url=%2Fcontacts&tenantId=tenant-1&userId=user-1&createdAtFrom=2026-05-01&createdAtTo=2026-05-08&page=2&pageSize=25",
|
||||
);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]);
|
||||
expect(getAdminAuditLogList).toHaveBeenCalledWith({
|
||||
q: "contact",
|
||||
action: "create",
|
||||
url: "/contacts",
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
createdAtFrom: "2026-05-01",
|
||||
createdAtTo: "2026-05-08",
|
||||
take: 25,
|
||||
skip: 25,
|
||||
});
|
||||
expect(data).toMatchObject({
|
||||
title: "translated:models.log.plural | ToolCTRL",
|
||||
items: auditRows,
|
||||
pagination: { page: 2, pageSize: 25, totalItems: 1, totalPages: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("exports CSV with the same filters and a capped export window after permission passes", async () => {
|
||||
const response = (await callLoader(
|
||||
"https://admin.example.test/audit-trails?export=csv&q=login&action=auth&url=%2Flogin&tenantId=tenant-2&userId=user-2&createdAtFrom=bad-date&createdAtTo=2026-05-08",
|
||||
)) as Response;
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]);
|
||||
expect(getAdminAuditLogList).toHaveBeenCalledWith({
|
||||
q: "login",
|
||||
action: "auth",
|
||||
url: "/login",
|
||||
tenantId: "tenant-2",
|
||||
userId: "user-2",
|
||||
createdAtFrom: "bad-date",
|
||||
createdAtTo: "2026-05-08",
|
||||
take: 500,
|
||||
skip: 0,
|
||||
});
|
||||
expect(vi.mocked(getAdminAuditLogList).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(serializeAdminAuditLogsCsv).mock.invocationCallOrder[0]);
|
||||
expect(serializeAdminAuditLogsCsv).toHaveBeenCalledWith(auditRows);
|
||||
expect(response.headers.get("Content-Type")).toBe("text/csv; charset=utf-8");
|
||||
expect(response.headers.get("Content-Disposition")).toBe('attachment; filename="admin-audit-logs.csv"');
|
||||
expect(await response.text()).toBe("csv-body\n");
|
||||
});
|
||||
|
||||
it("rejects table loads without permission before helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(
|
||||
callLoader(
|
||||
"https://admin.example.test/audit-trails?q=contact&action=create&url=%2Fcontacts&tenantId=tenant-1&userId=user-1&createdAtFrom=2026-05-01&createdAtTo=2026-05-08",
|
||||
),
|
||||
).rejects.toBe(rejection);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view");
|
||||
expect(getAdminAuditLogList).not.toHaveBeenCalled();
|
||||
expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects CSV export without permission before helper calls", async () => {
|
||||
const rejection = new Response("Forbidden", { status: 403 });
|
||||
vi.mocked(verifyUserHasPermission).mockRejectedValue(rejection as never);
|
||||
|
||||
await expect(
|
||||
callLoader(
|
||||
"https://admin.example.test/audit-trails?export=csv&q=login&action=auth&url=%2Flogin&tenantId=tenant-2&userId=user-2&createdAtFrom=2026-05-01&createdAtTo=2026-05-08",
|
||||
),
|
||||
).rejects.toBe(rejection);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.auditTrails.view");
|
||||
expect(getAdminAuditLogList).not.toHaveBeenCalled();
|
||||
expect(serializeAdminAuditLogsCsv).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not crash on malformed numeric and date filters", async () => {
|
||||
vi.mocked(getAdminAuditLogList).mockResolvedValue({ rows: [], total: 0, take: 10, skip: 0 } as never);
|
||||
|
||||
const data = await callLoader("https://admin.example.test/audit-trails?page=abc&pageSize=-5&createdAtFrom=not-a-date&createdAtTo=also-bad");
|
||||
|
||||
expect(getAdminAuditLogList).toHaveBeenCalledWith({
|
||||
q: null,
|
||||
action: null,
|
||||
url: null,
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
createdAtFrom: "not-a-date",
|
||||
createdAtTo: "also-bad",
|
||||
take: 10,
|
||||
skip: 0,
|
||||
});
|
||||
expect(data).toMatchObject({ pagination: { page: 1, pageSize: 10, totalItems: 0, totalPages: 0 } });
|
||||
});
|
||||
|
||||
it("uses the package audit-log boundary instead of the legacy app DB helper", () => {
|
||||
const source = readAuditRoute();
|
||||
|
||||
expect(source).toContain('from "@toolctrl/db/logs.server"');
|
||||
expect(source).toContain("getAdminAuditLogList");
|
||||
expect(source).toContain("serializeAdminAuditLogsCsv");
|
||||
expect(source).not.toContain("getAllLogs");
|
||||
expect(source).not.toContain('from "~/utils/db/logs.db.server"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { AdminAuditLogFilters, AdminAuditLogRow } from "@toolctrl/db/logs.server";
|
||||
import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@toolctrl/db/logs.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import AdminAuditLogToolbar from "~/components/audit/AdminAuditLogToolbar";
|
||||
import LogsTable from "~/components/app/events/LogsTable";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
|
||||
const CSV_EXPORT_TAKE = 500;
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: AdminAuditLogRow[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const filterableProperties = getAuditLogFilterableProperties();
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const auditLogFilters = getAuditLogFiltersFromUrl(urlSearchParams);
|
||||
|
||||
if (urlSearchParams.get("export") === "csv") {
|
||||
const { rows } = await getAdminAuditLogList({ ...auditLogFilters, take: CSV_EXPORT_TAKE, skip: 0 });
|
||||
return new Response(serializeAdminAuditLogsCsv(rows), {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": 'attachment; filename="admin-audit-logs.csv"',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const pageSize = normalizePositiveInteger(currentPagination.pageSize, 10);
|
||||
const page = normalizePositiveInteger(currentPagination.page, 1);
|
||||
const { rows, total, take } = await getAdminAuditLogList({
|
||||
...auditLogFilters,
|
||||
take: pageSize,
|
||||
skip: pageSize * (page - 1),
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.log.plural")} | ${process.env.APP_NAME}`,
|
||||
items: rows,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize: take,
|
||||
totalItems: total,
|
||||
totalPages: Math.ceil(total / take),
|
||||
sortedBy: currentPagination.sortedBy,
|
||||
query: currentPagination.query,
|
||||
},
|
||||
filterableProperties: filters.properties,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
function getAuditLogFilterableProperties(): FilterablePropertyDto[] {
|
||||
return [
|
||||
{
|
||||
name: "action",
|
||||
title: "models.log.action",
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: "models.log.url",
|
||||
},
|
||||
{
|
||||
name: "tenantId",
|
||||
title: "models.tenant.object",
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: "shared.createdBy",
|
||||
},
|
||||
{
|
||||
name: "createdAtFrom",
|
||||
title: "shared.createdAt",
|
||||
},
|
||||
{
|
||||
name: "createdAtTo",
|
||||
title: "shared.createdAt",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function getAuditLogFiltersFromUrl(urlSearchParams: URLSearchParams): AdminAuditLogFilters {
|
||||
return {
|
||||
q: urlSearchParams.get("q"),
|
||||
action: urlSearchParams.get("action"),
|
||||
url: urlSearchParams.get("url"),
|
||||
tenantId: urlSearchParams.get("tenantId"),
|
||||
userId: urlSearchParams.get("userId"),
|
||||
createdAtFrom: urlSearchParams.get("createdAtFrom"),
|
||||
createdAtTo: urlSearchParams.get("createdAtTo"),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePositiveInteger(value: number | null | undefined, fallback: number): number {
|
||||
if (!Number.isFinite(value) || !value || value < 1) return fallback;
|
||||
return Math.trunc(value);
|
||||
}
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function Events() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<IndexPageLayout title={t("models.log.plural")} buttons={<AdminAuditLogToolbar filters={data.filterableProperties} />}>
|
||||
<LogsTable withTenant={true} items={data.items} pagination={data.pagination} />
|
||||
</IndexPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, redirect } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import AddressBookIcon from "~/components/ui/icons/crm/AddressBookIcon";
|
||||
import AddressBookIconFilled from "~/components/ui/icons/crm/AddressBookIconFilled";
|
||||
import CompanyIcon from "~/components/ui/icons/crm/CompanyIcon";
|
||||
import CompanyIconFilled from "~/components/ui/icons/crm/CompanyIconFilled";
|
||||
import FormIcon from "~/components/ui/icons/crm/FormIcon";
|
||||
import FormIconFilled from "~/components/ui/icons/crm/FormIconFilled";
|
||||
import IncreaseIcon from "~/components/ui/icons/crm/IncreaseIcon";
|
||||
import IncreaseIconFilled from "~/components/ui/icons/crm/IncreaseIconFilled";
|
||||
import UsDollarCircled from "~/components/ui/icons/crm/UsDollarCircled";
|
||||
import UsDollarCircledFilled from "~/components/ui/icons/crm/UsDollarCircledFilled";
|
||||
import SidebarIconsLayout, { IconDto } from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import CrmService, { CrmConfigurationError } from "~/modules/crm/services/CrmService";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import RefreshIcon from "~/components/ui/icons/RefreshIcon";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { translateEntityTitlePlural } from "~/utils/i18n/translateLabel";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (!appConfiguration.app.features.crm) {
|
||||
throw redirect(adminPath("dashboard", { mode: "host-aware" }));
|
||||
}
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: t("pages.adminCrm.metaTitle", { appName: process.env.APP_NAME }),
|
||||
};
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
try {
|
||||
await CrmService.validate(tenantId);
|
||||
} catch (error) {
|
||||
if (error instanceof CrmConfigurationError) {
|
||||
throw new Response(t("crm.newsletter.errors.integrationMissing"), { status: 503 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
const items: IconDto[] = [
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
href: UrlUtils.getModulePath(params, "crm"),
|
||||
exact: true,
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
];
|
||||
["opportunities", "companies", "contacts", "submissions"].forEach((slug) => {
|
||||
const entity = appOrAdminData.entities.find((x) => x.slug === slug);
|
||||
if (entity) {
|
||||
items.push({
|
||||
name: translateEntityTitlePlural(t, i18n, entity),
|
||||
href: UrlUtils.getModulePath(params, `crm/${slug}`),
|
||||
icon: getIcons(entity.slug)?.icon,
|
||||
iconSelected: getIcons(entity.slug)?.iconSelected,
|
||||
});
|
||||
}
|
||||
});
|
||||
items.push({
|
||||
name: t("admin.crm.sync.title"),
|
||||
href: UrlUtils.getModulePath(params, "crm/sync"),
|
||||
icon: <RefreshIcon className="h-5 w-5" />,
|
||||
iconSelected: <RefreshIcon className="h-5 w-5" />,
|
||||
});
|
||||
|
||||
function getIcons(entitySlug: string) {
|
||||
if (entitySlug === "opportunities") {
|
||||
return {
|
||||
icon: <UsDollarCircled className="h-5 w-5" />,
|
||||
iconSelected: <UsDollarCircledFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "companies") {
|
||||
return {
|
||||
icon: <CompanyIcon className="h-5 w-5" />,
|
||||
iconSelected: <CompanyIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "contacts") {
|
||||
return {
|
||||
icon: <AddressBookIcon className="h-5 w-5" />,
|
||||
iconSelected: <AddressBookIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "submissions") {
|
||||
return {
|
||||
icon: <FormIcon className="h-5 w-5" />,
|
||||
iconSelected: <FormIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
}
|
||||
}
|
||||
return (
|
||||
<SidebarIconsLayout label={{ align: "right" }} items={items}>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowNewRoute from "~/modules/rows/components/RowNewRoute";
|
||||
import { Rows_New } from "~/modules/rows/routes/Rows_New.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_New.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_New.action(args);
|
||||
|
||||
export default () => <RowNewRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Relationships } from "~/modules/rows/routes/Rows_Relationships.server";
|
||||
import RowsRelationshipsRoute from "~/modules/rows/components/RowsRelationshipsRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Relationships.loader(args);
|
||||
|
||||
export default () => <RowsRelationshipsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowsViewRoute from "~/modules/rows/components/RowsViewRoute";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_List.LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<RowsViewRoute
|
||||
key={data.rowsData.entity.id}
|
||||
rowsData={data.rowsData}
|
||||
items={data.rowsData.items}
|
||||
routes={data.routes}
|
||||
saveCustomViews={true}
|
||||
permissions={{
|
||||
create: getUserHasPermission(appOrAdminData, getEntityPermission(data.rowsData.entity, "create")),
|
||||
}}
|
||||
currentSession={{
|
||||
user: appOrAdminData.user,
|
||||
isSuperAdmin: appOrAdminData.isSuperAdmin,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/crm.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm.tsx",
|
||||
"apps/web/app/routes/admin/crm/index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm/index.tsx",
|
||||
"apps/web/app/routes/admin/crm/sync.tsx",
|
||||
"apps/web/app/modules/crm/services/CrmService.ts",
|
||||
];
|
||||
const crmRouteFiles = [
|
||||
"apps/web/app/routes/admin/crm.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm.tsx",
|
||||
"apps/web/app/routes/admin/crm/index.tsx",
|
||||
"apps/web/app/routes/app.$tenant/crm/index.tsx",
|
||||
];
|
||||
|
||||
describe("CRM i18n", () => {
|
||||
it("uses semantic keys for overview and sync chrome", () => {
|
||||
const sources = sourceFiles.map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
|
||||
|
||||
expect(sources).toContain("pages.adminCrm.metaTitle");
|
||||
expect(sources).toContain('getTranslations(request)');
|
||||
expect(sources).toContain("pages.adminCrm.contacts");
|
||||
expect(sources).toContain("pages.adminCrm.createOpportunity");
|
||||
expect(sources).toContain("pages.adminCrm.openOpportunitiesCount");
|
||||
expect(sources).toContain("pages.adminCrm.columns.expectedCloseDate");
|
||||
expect(sources).toContain("admin.crm.sync.actions.syncContact");
|
||||
expect(sources).toContain("admin.crm.sync.actions.createdContactsPart");
|
||||
expect(sources).toContain("admin.crm.sync.actions.updatedContactsPart");
|
||||
expect(sources).toContain("formattedCount: formatNumber");
|
||||
expect(sources).toContain("formatters.number(filtered.length)");
|
||||
expect(sources).toContain("admin.crm.sync.sources.unknown");
|
||||
expect(sources).toContain("admin.crm.sync.table.marketingSubscriber");
|
||||
expect(sources).toContain("crm.newsletter.errors.integrationMissing");
|
||||
expect(sources).toContain("CrmConfigurationError");
|
||||
expect(sources).toContain("CrmProviderError");
|
||||
expect(sources).toContain("admin.crm.sync.errors.providerFetchFailed");
|
||||
expect(sources).toContain("crm.newsletter.subscribed");
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
|
||||
const crmRoutes = crmRouteFiles.map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
|
||||
expect(crmRoutes).not.toContain('from "i18next"');
|
||||
expect(crmRoutes).not.toContain("i18nT");
|
||||
});
|
||||
|
||||
it("does not keep raw visible CRM labels or legacy overview formatting in source", () => {
|
||||
const forbidden = [
|
||||
">from {NumberUtils.intFormat",
|
||||
"NumberUtils.intFormat(data.summary",
|
||||
"NumberUtils.numberFormat(data.summary",
|
||||
"<div>${",
|
||||
'return "Sync"',
|
||||
'return "Sync 1 contact"',
|
||||
'syncContact", { count: filtered.length })',
|
||||
'createdContacts", { count: progress.created })',
|
||||
'updatedContacts", { count: progress.updated })',
|
||||
'createdAndUpdatedContacts", { created: progress.created, updated: progress.updated })',
|
||||
'return "?"',
|
||||
'title="Sync"',
|
||||
'title: "Source"',
|
||||
'title: "Status"',
|
||||
'title: "User"',
|
||||
'title: "Contact"',
|
||||
'title="Synced"',
|
||||
'title="User"',
|
||||
'return { error: "No CRM or ConvertKit integration configured" }',
|
||||
"CRM is not configured:",
|
||||
'Entity "',
|
||||
"load the template",
|
||||
'must be "All" or',
|
||||
"return { error: response.message }",
|
||||
"ConvertKit error:",
|
||||
"return { error: e.message }",
|
||||
'return { success: "Subscribed" }',
|
||||
"<Link\n to={params.tenant ? UrlUtils.getModulePath(params, \"crm/opportunities/new\") : adminPath(`crm/opportunities/new`, { mode: \"host-aware\" })}\n className=\"text-foreground bg-secondary hover:bg-secondary/90 rounded-full p-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600\"\n >",
|
||||
];
|
||||
|
||||
for (const file of sourceFiles) {
|
||||
const source = fs.readFileSync(path.join(repoRoot, file), "utf8");
|
||||
for (const literal of forbidden) {
|
||||
expect(source).not.toContain(literal);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import RowsList from "~/components/entities/rows/RowsList";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import CrmService, { CrmSummaryDto } from "~/modules/crm/services/CrmService";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { RowDisplayDefaultProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
summary: CrmSummaryDto;
|
||||
routes: EntitiesApi.Routes;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const data: LoaderData = {
|
||||
title: t("pages.adminCrm.metaTitle", { appName: process.env.APP_NAME }),
|
||||
summary: await CrmService.getSummary(tenantId),
|
||||
routes: EntitiesApi.getNoCodeRoutes({ request, params }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("shared.overview")}</h3>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-4">
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/companies") : adminPath("crm/companies", { mode: "host-aware" })}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.companies")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.companies, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/contacts") : adminPath("crm/contacts", { mode: "host-aware" })}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.contacts")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.contacts, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/opportunities") : adminPath("crm/opportunities", { mode: "host-aware" })}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground flex items-center space-x-2 truncate text-xs font-medium uppercase">
|
||||
<ColorBadge color={Colors.GREEN} />
|
||||
<div>{t("pages.adminCrm.opportunities")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 flex items-baseline space-x-1 truncate text-2xl font-semibold">
|
||||
<div>{formatters.currency(data.summary.opportunities.value, "USD", { maximumFractionDigits: 0 })}</div>
|
||||
<div className="text-muted-foreground text-xs font-normal lowercase">
|
||||
{t("pages.adminCrm.openOpportunitiesCount", {
|
||||
count: data.summary.opportunities.count,
|
||||
formattedCount: formatters.number(data.summary.opportunities.count, { maximumFractionDigits: 0 }),
|
||||
})}
|
||||
</div>
|
||||
</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/submissions") : adminPath("crm/submissions", { mode: "host-aware" })}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.submissions")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.submissions, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
</dl>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-muted-foreground text-sm font-medium">{t("pages.adminCrm.opportunities")}</h3>
|
||||
<Link
|
||||
to={params.tenant ? UrlUtils.getModulePath(params, "crm/opportunities/new") : adminPath(`crm/opportunities/new`, { mode: "host-aware" })}
|
||||
className="text-foreground bg-secondary hover:bg-secondary/90 rounded-full p-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600"
|
||||
aria-label={t("pages.adminCrm.createOpportunity")}
|
||||
>
|
||||
<PlusIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</Link>
|
||||
</div>
|
||||
<RowsList
|
||||
view="board"
|
||||
entity="opportunity"
|
||||
items={data.summary.data.openOpportunities}
|
||||
readOnly={true}
|
||||
columns={[
|
||||
{ name: "name", title: t("pages.adminCrm.columns.name"), visible: true },
|
||||
{ name: "value", title: t("pages.adminCrm.columns.value"), visible: true },
|
||||
{ name: "expectedCloseDate", title: t("pages.adminCrm.columns.expectedCloseDate"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_AT, title: t("shared.createdAt"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_BY, title: t("shared.createdBy"), visible: true },
|
||||
]}
|
||||
routes={data.routes}
|
||||
onClickRoute={(i) => UrlUtils.getModulePath(params, `crm/opportunities/${i.id}`)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-muted-foreground text-sm font-medium">{t("pages.adminCrm.submissions")}</h3>
|
||||
</div>
|
||||
<RowsList
|
||||
view="table"
|
||||
entity="submission"
|
||||
items={data.summary.data.submissions}
|
||||
readOnly={true}
|
||||
columns={[
|
||||
{ name: RowDisplayDefaultProperty.FOLIO, title: "", visible: true },
|
||||
{ name: "users", title: t("pages.adminCrm.columns.users"), visible: true },
|
||||
{ name: "message", title: t("pages.adminCrm.columns.message"), visible: true },
|
||||
{ name: "parent.contact", title: t("pages.adminCrm.columns.contact"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_AT, title: t("shared.createdAt"), visible: true },
|
||||
]}
|
||||
routes={data.routes}
|
||||
onClickRoute={(i) => UrlUtils.getModulePath(params, `crm/submissions/${i.id}`)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import { ReloadIcon } from "~/components/ui/icons/vendor";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import toast from "react-hot-toast";
|
||||
import { ContactStatus } from "~/application/dtos/crm/ContactStatus";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import CrmService, { CrmConfigurationError, CrmProviderError, UserInCrmDto } from "~/modules/crm/services/CrmService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { formatNumber, useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
users: UserInCrmDto[];
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
try {
|
||||
await CrmService.validate(tenantId);
|
||||
} catch (error) {
|
||||
if (error instanceof CrmConfigurationError) {
|
||||
throw new Response(t("crm.newsletter.errors.integrationMissing"), { status: 503 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
let usersInCrm: UserInCrmDto[];
|
||||
try {
|
||||
usersInCrm = await CrmService.getUsersInCrm({
|
||||
invalidateCache: searchParams.get("cache") === "clear",
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof CrmProviderError) {
|
||||
throw new Response(t("admin.crm.sync.errors.providerFetchFailed"), { status: 502 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const data: LoaderData = {
|
||||
users: usersInCrm,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "sync") {
|
||||
try {
|
||||
await CrmService.validate(tenantId);
|
||||
} catch (error) {
|
||||
if (error instanceof CrmConfigurationError) {
|
||||
return Response.json({ error: t("crm.newsletter.errors.integrationMissing") }, { status: 503 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const emails = form.getAll("emails[]").map((x) => x.toString());
|
||||
let usersInCrm: UserInCrmDto[];
|
||||
try {
|
||||
usersInCrm = await CrmService.getUsersInCrm({ invalidateCache: false });
|
||||
} catch (error) {
|
||||
if (error instanceof CrmProviderError) {
|
||||
return Response.json({ error: t("admin.crm.sync.errors.providerFetchFailed") }, { status: 502 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
let progress: { updated: number; created: number } = { updated: 0, created: 0 };
|
||||
let filteredUsers = usersInCrm.filter((x) => emails.includes(x.email));
|
||||
for (const userInCrm of filteredUsers) {
|
||||
if (userInCrm.status === "to-update" && userInCrm.contact?.id) {
|
||||
const changes = await CrmService.updateContact(userInCrm.contact?.id, {
|
||||
firstName: userInCrm.firstName ?? "",
|
||||
lastName: userInCrm.lastName ?? "",
|
||||
marketingSubscriber: true,
|
||||
});
|
||||
if (changes && changes.length > 0) {
|
||||
progress.updated++;
|
||||
}
|
||||
} else if (userInCrm.status === "to-create") {
|
||||
const created = await CrmService.createContact({
|
||||
request,
|
||||
tenantId: null,
|
||||
firstName: userInCrm.firstName ?? "",
|
||||
lastName: userInCrm.lastName ?? "",
|
||||
email: userInCrm.email,
|
||||
jobTitle: "",
|
||||
status: ContactStatus.Customer,
|
||||
marketingSubscriber: true,
|
||||
options: {
|
||||
createEvent: false,
|
||||
checkUsage: false,
|
||||
createLog: false,
|
||||
storeMedia: false,
|
||||
reportUsage: false,
|
||||
},
|
||||
});
|
||||
if (created) {
|
||||
progress.created++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (progress.created === 0 && progress.updated === 0) {
|
||||
return Response.json({ error: t("admin.crm.sync.actions.noUsers") }, { status: 400 });
|
||||
} else if (progress.created > 0 && progress.updated === 0) {
|
||||
return Response.json({ success: t("admin.crm.sync.actions.createdContacts", { count: progress.created, formattedCount: formatNumber(progress.created, locale) }) });
|
||||
} else if (progress.created === 0 && progress.updated > 0) {
|
||||
return Response.json({ success: t("admin.crm.sync.actions.updatedContacts", { count: progress.updated, formattedCount: formatNumber(progress.updated, locale) }) });
|
||||
}
|
||||
const created = t("admin.crm.sync.actions.createdContactsPart", { count: progress.created, formattedCount: formatNumber(progress.created, locale) });
|
||||
const updated = t("admin.crm.sync.actions.updatedContactsPart", { count: progress.updated, formattedCount: formatNumber(progress.updated, locale) });
|
||||
return Response.json({
|
||||
success: t("admin.crm.sync.actions.createdAndUpdatedContacts", { created, updated }),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher<{ success?: string; error?: string }>();
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.success) {
|
||||
toast.success(fetcher.data.success);
|
||||
} else if (fetcher.data?.error) {
|
||||
toast.error(fetcher.data.error);
|
||||
}
|
||||
}, [fetcher.data]);
|
||||
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!data.users) {
|
||||
return [];
|
||||
}
|
||||
return data.users.filter(
|
||||
(f) =>
|
||||
f.email?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.firstName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.lastName?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.source?.toString().toUpperCase().includes(searchInput.toUpperCase()) ||
|
||||
f.status?.toString().toUpperCase().includes(searchInput.toUpperCase())
|
||||
);
|
||||
};
|
||||
|
||||
function getSyncTitle() {
|
||||
const filtered = filteredItems();
|
||||
if (filtered.length === 0) {
|
||||
return t("admin.crm.sync.actions.sync");
|
||||
}
|
||||
return t("admin.crm.sync.actions.syncContact", { count: filtered.length, formattedCount: formatters.number(filtered.length) });
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("admin.crm.sync.title")}
|
||||
withHome={false}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonSecondary to={adminPath("crm/sync?cache=clear", { mode: "host-aware" })}>
|
||||
<ReloadIcon className="h-5 w-5" />
|
||||
</ButtonSecondary>
|
||||
<LoadingButton
|
||||
disabled={filteredItems().length === 0}
|
||||
isLoading={fetcher.state === "submitting"}
|
||||
onClick={() => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.append("action", "sync");
|
||||
filteredItems().forEach((user) => {
|
||||
form.append("emails[]", user.email);
|
||||
});
|
||||
fetcher.submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}}
|
||||
>
|
||||
{getSyncTitle()}
|
||||
</LoadingButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-2 pb-20">
|
||||
<InputSearch value={searchInput} setValue={setSearchInput} />
|
||||
<TableSimple
|
||||
items={filteredItems()}
|
||||
actions={[
|
||||
{
|
||||
title: t("admin.crm.sync.actions.viewContact"),
|
||||
onClickRoute: (_, item) => adminPath(`crm/contacts/${item.contact?.id}`, { mode: "host-aware" }),
|
||||
disabled: (item) => !item.isContact,
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "source",
|
||||
title: t("admin.crm.sync.table.source"),
|
||||
value: (item) => {
|
||||
if (item.source === "user") {
|
||||
return <SimpleBadge title={t("admin.crm.sync.sources.user")} color={Colors.BLUE} />;
|
||||
}
|
||||
return <SimpleBadge title={t("admin.crm.sync.sources.unknown", { source: item.source })} color={Colors.GRAY} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
title: t("admin.crm.sync.table.status"),
|
||||
value: (item) => {
|
||||
if (item.status === "synced") {
|
||||
return <SimpleBadge title={t("admin.crm.sync.statuses.synced")} color={Colors.GREEN} />;
|
||||
} else if (item.status === "to-create") {
|
||||
return <SimpleBadge title={t("admin.crm.sync.statuses.toCreate")} color={Colors.RED} />;
|
||||
} else if (item.status === "to-update") {
|
||||
return <SimpleBadge title={t("admin.crm.sync.statuses.toUpdate")} color={Colors.YELLOW} />;
|
||||
}
|
||||
return <SimpleBadge title={t("admin.crm.sync.statuses.notSynced")} color={Colors.RED} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
title: t("admin.crm.sync.table.user"),
|
||||
className: "w-full",
|
||||
value: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{item.email}</div>
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{item.firstName} {item.lastName}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "contact",
|
||||
title: t("admin.crm.sync.table.contact"),
|
||||
className: "w-full",
|
||||
value: (item) => {
|
||||
if (!item.contact) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{item.contact.email}</div>
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{item.contact.firstName} {item.contact.lastName}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "isContact",
|
||||
title: t("admin.crm.sync.table.isContact"),
|
||||
value: (item) => (
|
||||
<div>{item.isContact ? <CheckIcon className="h-5 w-5 text-green-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "isMarketingSubscriber",
|
||||
title: t("admin.crm.sync.table.marketingSubscriber"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
{item.contact?.marketingSubscriber ? <CheckIcon className="h-5 w-5 text-green-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
// {
|
||||
// name: "createdAt",
|
||||
// title: "Created at",
|
||||
// value: (item) => <DateCell date={item.createdAt} />,
|
||||
// },
|
||||
{
|
||||
name: "updatedAt",
|
||||
title: t("admin.crm.sync.table.updatedAt"),
|
||||
value: (item) => <DateCell date={item.updatedAt} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { loader } from "./dashboard";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAdminDashboardStats } from "~/utils/services/adminDashboardService";
|
||||
import { getSetupSteps } from "~/utils/services/setupService";
|
||||
import { adminGetAllTenantsWithUsage } from "~/utils/db/tenants.db.server";
|
||||
import PeriodHelper from "~/utils/helpers/PeriodHelper";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const translatedT = vi.fn((key: string) => `translated:${key}`);
|
||||
const computedGte = new Date("2026-02-03T04:05:06.000Z");
|
||||
const stats = [{ name: "Translated accounts", stat: "10" }];
|
||||
const setupSteps = [{ title: "Setup", completed: true }];
|
||||
const tenants = { items: [{ id: "tenant-1" }], pagination: { page: 1, pageSize: 10, totalItems: 1, totalPages: 1 } };
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/adminDashboardService", () => ({
|
||||
getAdminDashboardStats: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/setupService", () => ({
|
||||
getSetupSteps: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllTenantsWithUsage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PeriodHelper", () => ({
|
||||
default: { getGreaterThanOrEqualsFromRequest: vi.fn() },
|
||||
defaultPeriodFilter: "30d",
|
||||
PeriodFilters: [],
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
|
||||
createMetrics: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
getPaginationFromCurrentUrl: vi.fn(() => ({ page: 1, pageSize: 10 })),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({
|
||||
serverTimingHeaders: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/stats/DashboardStats", () => ({
|
||||
DashboardStats: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/admin/SetupSteps", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/app/ProfileBanner", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/core/tenants/TenantsTable", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputSelect", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({
|
||||
useAppOrAdminData: vi.fn(() => ({ user: {}, permissions: ["admin.dashboard.view"] })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({
|
||||
getUserHasPermission: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
|
||||
}));
|
||||
|
||||
function readDashboardRoute() {
|
||||
return readRepoFile("apps/web/app/utils/data/.server/adminDashboardRouteData.ts");
|
||||
}
|
||||
|
||||
describe("admin dashboard KPI route contract", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: translatedT } as never);
|
||||
vi.mocked(getAdminDashboardStats).mockResolvedValue(stats as never);
|
||||
vi.mocked(getSetupSteps).mockResolvedValue(setupSteps as never);
|
||||
vi.mocked(adminGetAllTenantsWithUsage).mockResolvedValue(tenants as never);
|
||||
vi.mocked(PeriodHelper.getGreaterThanOrEqualsFromRequest).mockReturnValue(computedGte);
|
||||
vi.mocked(createMetrics).mockResolvedValue({
|
||||
time: async <T,>(value: T | Promise<T>) => value,
|
||||
getServerTimingHeader: () => ({ "Server-Timing": "admin.dashboard;dur=1" }),
|
||||
} as never);
|
||||
});
|
||||
|
||||
it("passes translations and the computed period boundary into the KPI service while preserving loader data", async () => {
|
||||
const request = new Request("https://admin.example.com/dashboard?period=month&page=2");
|
||||
|
||||
const response = (await loader({ request, params: {}, context: {}, unstable_pattern: "admin/dashboard" })) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(requireAuth).toHaveBeenCalledWith({ request, params: {} });
|
||||
expect(getTranslations).toHaveBeenCalledWith(request);
|
||||
expect(PeriodHelper.getGreaterThanOrEqualsFromRequest).toHaveBeenCalledWith({ request });
|
||||
expect(getAdminDashboardStats).toHaveBeenCalledWith({ t: translatedT, gte: computedGte });
|
||||
expect(getSetupSteps).toHaveBeenCalledTimes(1);
|
||||
expect(adminGetAllTenantsWithUsage).toHaveBeenCalledWith(undefined, { page: 1, pageSize: 10 });
|
||||
expect(body).toMatchObject({
|
||||
title: "translated:app.sidebar.dashboard | ToolCTRL",
|
||||
stats,
|
||||
setupSteps,
|
||||
tenants,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps KPI labels behind the translated dashboard service boundary", () => {
|
||||
const source = readDashboardRoute();
|
||||
|
||||
expect(source).toContain('import { getAdminDashboardStats } from "~/utils/services/adminDashboardService";');
|
||||
expect(source).toContain("getAdminDashboardStats({ t, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) })");
|
||||
expect(source).not.toContain("admin.kpi.accounts.name");
|
||||
expect(source).not.toContain("admin.kpi.mrr.name");
|
||||
expect(source).not.toContain("admin.kpi.activeUsers.name");
|
||||
expect(source).not.toContain("Translated accounts");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/utils/data/.server/adminDashboardRouteData.ts";
|
||||
|
||||
function readRoute() {
|
||||
return readRepoFile(routePath);
|
||||
}
|
||||
|
||||
describe("admin dashboard KPI route contract", () => {
|
||||
it("passes the route translations and period filter to the dashboard stats service", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain('const { t } = await time(getTranslations(request), "getTranslations");');
|
||||
expect(source).toContain("getAdminDashboardStats({ t, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) })");
|
||||
expect(source).toContain("admin.dashboard.details.getAdminDashboardStats");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useSearchParams } from "react-router";
|
||||
import { DashboardStats } from "~/components/ui/stats/DashboardStats";
|
||||
import SetupSteps from "~/components/admin/SetupSteps";
|
||||
import ProfileBanner from "~/components/app/ProfileBanner";
|
||||
import TenantsTable from "~/components/core/tenants/TenantsTable";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { defaultPeriodFilter, PeriodFilters } from "~/utils/helpers/PeriodHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import type { AdminDashboardLoaderData } from "~/routeModules/admin/dashboard.impl";
|
||||
export { serverTimingHeaders as headers };
|
||||
export { loader } from "~/routeModules/admin/dashboard.impl";
|
||||
|
||||
export const meta: v2MetaFunction<AdminDashboardLoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AdminNavigationRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<AdminDashboardLoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
return (
|
||||
<main className="relative z-0 flex-1 pb-8">
|
||||
{/*Page header */}
|
||||
<div className="bg-background lg:border-border hidden shadow-xs md:block lg:border-t">
|
||||
<ProfileBanner user={appOrAdminData.user} />
|
||||
</div>
|
||||
|
||||
<div className="mx-auto grid max-w-5xl gap-5 px-4 py-5 sm:px-8">
|
||||
{getUserHasPermission(appOrAdminData, "admin.dashboard.view") ? (
|
||||
<div className="space-y-5 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
{data.setupSteps.filter((f) => f.completed).length < data.setupSteps.length && <SetupSteps items={data.setupSteps} />}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 truncate p-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground grow font-medium leading-4">{t("app.dashboard.summary")}</h3>
|
||||
<div>
|
||||
<InputSelect
|
||||
className="w-44"
|
||||
name="period"
|
||||
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
|
||||
options={PeriodFilters.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: t(f.name),
|
||||
};
|
||||
})}
|
||||
setValue={(value) => {
|
||||
if (value) {
|
||||
searchParams.set("period", value?.toString() ?? "");
|
||||
} else {
|
||||
searchParams.delete("period");
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DashboardStats items={data.stats} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 overflow-x-auto p-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground font-medium leading-4">{t("models.tenant.plural")}</h3>
|
||||
<ButtonSecondary to={adminPath("accounts", { mode: "host-aware" })}>{t("shared.viewAll")}</ButtonSecondary>
|
||||
</div>
|
||||
<TenantsTable items={data.tenants.items} pagination={data.tenants.pagination} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="font-medium">{t("app.dashboard.noPermission")}</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import IncreaseIcon from "~/components/ui/icons/crm/IncreaseIcon";
|
||||
import IncreaseIconFilled from "~/components/ui/icons/crm/IncreaseIconFilled";
|
||||
import MegaphoneIcon from "~/components/ui/icons/emails/MegaphoneIcon";
|
||||
import MegaphoneIconFilled from "~/components/ui/icons/emails/MegaphoneIconFilled";
|
||||
import SentIcon from "~/components/ui/icons/emails/SentIcon";
|
||||
import SentIconFilled from "~/components/ui/icons/emails/SentIconFilled";
|
||||
import ActivityHistoryIcon from "~/components/ui/icons/entities/ActivityHistoryIcon";
|
||||
import ActivityHistoryIconFilled from "~/components/ui/icons/entities/ActivityHistoryIconFilled";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import CrmService from "~/modules/crm/services/CrmService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("emailMarketing:title")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await CrmService.validate(tenantId);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const params = useParams();
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing"),
|
||||
exact: true,
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing:campaigns"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/campaigns"),
|
||||
icon: <MegaphoneIcon className="h-5 w-5" />,
|
||||
iconSelected: <MegaphoneIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing:activity"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/activity"),
|
||||
icon: <ActivityHistoryIcon className="h-5 w-5" />,
|
||||
iconSelected: <ActivityHistoryIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing:senders.plural"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/senders"),
|
||||
icon: <SentIcon className="h-5 w-5" />,
|
||||
iconSelected: <SentIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import OutboundEmailsListRoute from "~/modules/emailMarketing/components/outboundEmails/OutboundEmailsListRoute";
|
||||
import { OutboundEmails_List } from "~/modules/emailMarketing/routes/OutboundEmails_List";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => OutboundEmails_List.loader(args);
|
||||
|
||||
export default () => <OutboundEmailsListRoute />;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsEditRoute from "~/modules/emailMarketing/components/campaigns/CampaignsEditRoute";
|
||||
import { Campaigns_Edit } from "~/modules/emailMarketing/routes/Campaigns_Edit";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Campaigns_Edit.action(args);
|
||||
|
||||
export default () => <CampaignsEditRoute />;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsListRoute from "~/modules/emailMarketing/components/campaigns/CampaignsListRoute";
|
||||
import { Campaigns_List } from "~/modules/emailMarketing/routes/Campaigns_List";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_List.loader(args);
|
||||
|
||||
export default () => <CampaignsListRoute />;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsNewRoute from "~/modules/emailMarketing/components/campaigns/CampaignsNewRoute";
|
||||
import { Campaigns_New } from "~/modules/emailMarketing/routes/Campaigns_New";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Campaigns_New.action(args);
|
||||
|
||||
export default () => <CampaignsNewRoute />;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import EmailMarketingSummaryRoute from "~/modules/emailMarketing/components/EmailMarketingSummaryRoute";
|
||||
import { EmailMarketing_Summary } from "~/modules/emailMarketing/routes/EmailMarketing_Summary";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => EmailMarketing_Summary.loader(args);
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => <EmailMarketingSummaryRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import SendersListRoute from "~/modules/emailMarketing/components/senders/SendersListRoute";
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import { Senders_List } from "~/modules/emailMarketing/routes/Senders_List";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Senders_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Senders_List.action(args);
|
||||
|
||||
export default () => <SendersListRoute />;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import SendersEditRoute from "~/modules/emailMarketing/components/senders/SendersEditRoute";
|
||||
import { Senders_Edit } from "~/modules/emailMarketing/routes/Senders_Edit";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Senders_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Senders_Edit.action(args);
|
||||
|
||||
export default () => <SendersEditRoute />;
|
||||
Loaded 100 of 5784 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user