Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
-14
@@ -1,14 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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
@@ -1,4 +0,0 @@
|
||||
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
@@ -1,15 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
+4
-64
@@ -2,20 +2,14 @@ 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 { getTenant, getTenantBySlug, 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 { getTenantSubscription, 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";
|
||||
@@ -25,12 +19,9 @@ 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";
|
||||
@@ -46,8 +37,6 @@ type LoaderData = {
|
||||
users: Awaited<ReturnType<typeof adminGetAllTenantUsers>>;
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
isStripeTest: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
tenantTypes: Awaited<ReturnType<typeof getTenantTypeOptions>>;
|
||||
};
|
||||
|
||||
@@ -59,11 +48,10 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
if (!tenant) {
|
||||
throw redirect(adminPath("accounts", { mode: "host-aware" }));
|
||||
}
|
||||
const [users, subscription, subscriptionProducts, tenantSettingsEntity, tenantTypes] = await Promise.all([
|
||||
const [users, subscription, subscriptionProducts, tenantTypes] = await Promise.all([
|
||||
adminGetAllTenantUsers(tenant.id),
|
||||
getTenantSubscription(params.id ?? ""),
|
||||
getAllSubscriptionProducts(),
|
||||
findEntityByName({ tenantId: null, name: "tenantSettings" }),
|
||||
getTenantTypeOptions(),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
@@ -72,8 +60,6 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
users,
|
||||
subscription,
|
||||
subscriptionProducts,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
tenantSettingsEntity,
|
||||
tenantTypes,
|
||||
};
|
||||
return data;
|
||||
@@ -153,23 +139,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
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",
|
||||
@@ -186,33 +155,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
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,
|
||||
@@ -274,7 +216,6 @@ export default function TenantRoute() {
|
||||
<UpdateTenantDetailsForm
|
||||
tenant={data.tenant}
|
||||
disabled={!getUserHasPermission(adminData, "admin.account.settings.update")}
|
||||
tenantSettingsEntity={data.tenantSettingsEntity}
|
||||
tenantTypes={data.tenantTypes}
|
||||
options={{
|
||||
canChangeType: true,
|
||||
@@ -328,7 +269,6 @@ export default function TenantRoute() {
|
||||
tenant={data.tenant}
|
||||
subscription={data.subscription}
|
||||
subscriptionProducts={data.subscriptionProducts}
|
||||
isStripeTest={data.isStripeTest}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -343,7 +283,7 @@ export default function TenantRoute() {
|
||||
|
||||
{/*Danger */}
|
||||
{getUserHasPermission(adminData, "admin.account.delete") && (
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")}>
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")} tone="danger">
|
||||
<div className="mt-12 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<input hidden type="text" name="action" value="deleteAccount" readOnly />
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
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
@@ -1,52 +0,0 @@
|
||||
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 });
|
||||
}
|
||||
+2
-2
@@ -6,7 +6,7 @@ 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 { IpAddressLog } from "@hivegrid/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";
|
||||
@@ -22,7 +22,7 @@ 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";
|
||||
import { translateIpAddressLogAction, translateIpAddressLogDescription, translateIpAddressLogError } from "~/modules/ipAddress/ipAddressLogLabels";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ 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 { IpAddress } from "@hivegrid/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";
|
||||
|
||||
+4
-14
@@ -16,9 +16,6 @@ type AdminAccountSecurityTranslations = {
|
||||
adminUsers: string;
|
||||
accountUsers: string;
|
||||
};
|
||||
seed: {
|
||||
tab: string;
|
||||
};
|
||||
};
|
||||
ipAddresses: {
|
||||
actions: Record<string, string>;
|
||||
@@ -66,14 +63,13 @@ function readTranslations(locale: "en" | "de") {
|
||||
|
||||
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/modules/ipAddress/ipAddressLogLabels.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",
|
||||
@@ -103,26 +99,20 @@ describe("admin account security i18n", () => {
|
||||
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");
|
||||
@@ -147,9 +137,9 @@ describe("admin account security i18n", () => {
|
||||
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("Mollie Customer already set");
|
||||
expect(source).not.toContain("Could not create billing customer");
|
||||
expect(source).not.toContain("Mollie 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}");
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { listAdminBillingRows, requestManualBillingSync, setTenantBillingPlanSeats } from "~/services/admin/billing-admin.server";
|
||||
import { action, loader } from "./billing";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string, params?: Record<string, string>) => (params?.provider ? `${key}:${params.provider}` : key) }),
|
||||
}));
|
||||
vi.mock("~/components/ui/buttons/ButtonPrimary", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/buttons/ButtonSecondary", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf" }) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn() }));
|
||||
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
|
||||
vi.mock("~/services/admin/billing-admin.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/billing-admin.server")>("~/services/admin/billing-admin.server");
|
||||
return {
|
||||
...actual,
|
||||
listAdminBillingRows: vi.fn(),
|
||||
requestManualBillingSync: vi.fn(),
|
||||
setTenantBillingPlanSeats: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
function requestWithForm(form: Record<string, string>) {
|
||||
return new Request("https://admin.example.test/accounts/billing", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams(form),
|
||||
});
|
||||
}
|
||||
|
||||
describe("admin accounts billing route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({
|
||||
t: (key: string, params?: Record<string, string>) => (params?.provider ? `${key}:${params.provider}` : key),
|
||||
} as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
|
||||
vi.mocked(getUser).mockResolvedValue({ id: "user_1", email: "ops@hivegrid.de" } as never);
|
||||
vi.mocked(listAdminBillingRows).mockResolvedValue([
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
tenantName: "Acme",
|
||||
tenantSlug: "acme",
|
||||
status: "active",
|
||||
readOnly: false,
|
||||
planCode: "starter",
|
||||
seatQuantity: 3,
|
||||
lagoCustomerId: "lago_1",
|
||||
mollieCustomerId: "mollie_1",
|
||||
lastInvoiceExternalId: "inv_1",
|
||||
lastPaymentExternalId: "pay_1",
|
||||
currentPeriodStart: null,
|
||||
currentPeriodEnd: null,
|
||||
pastDueSince: null,
|
||||
frozenAt: null,
|
||||
cancelledAt: null,
|
||||
entitlementCount: 1,
|
||||
},
|
||||
] as never);
|
||||
});
|
||||
|
||||
it("checks subscription permission before loading billing rows", async () => {
|
||||
const body = await loader({
|
||||
request: new Request("https://admin.example.test/accounts/billing"),
|
||||
params: {},
|
||||
context: {},
|
||||
} as LoaderFunctionArgs);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.account.subscription");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(listAdminBillingRows).mock.invocationCallOrder[0]);
|
||||
expect(body.vm.status).toBe("ready");
|
||||
expect(body.vm.data.rows[0].tenantName).toBe("Acme");
|
||||
});
|
||||
|
||||
it("routes plan/seat override actions to the admin service", async () => {
|
||||
const response = (await action({
|
||||
request: requestWithForm({
|
||||
csrf: "csrf",
|
||||
action: "set-plan-seats",
|
||||
tenantId: "tenant_1",
|
||||
planCode: "pro",
|
||||
seatQuantity: "7",
|
||||
reason: "Sonderkunde",
|
||||
}),
|
||||
params: {},
|
||||
context: {},
|
||||
} as ActionFunctionArgs)) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.billing.actions.planSeatsUpdated" });
|
||||
expect(setTenantBillingPlanSeats).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
planCode: "pro",
|
||||
seatQuantity: "7",
|
||||
reason: "Sonderkunde",
|
||||
actorUserId: "user_1",
|
||||
actorEmail: "ops@hivegrid.de",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("routes manual provider sync actions to the admin service", async () => {
|
||||
const response = (await action({
|
||||
request: requestWithForm({ csrf: "csrf", action: "request-sync", tenantId: "tenant_1", provider: "lago" }),
|
||||
params: {},
|
||||
context: {},
|
||||
} as ActionFunctionArgs)) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "admin.billing.actions.syncRequested:admin.billing.providers.lago" });
|
||||
expect(requestManualBillingSync).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", provider: "lago", actorUserId: "user_1" }));
|
||||
});
|
||||
});
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
import { buildAdminBillingVM, type AdminBillingRow } from "@hivegrid/view-models";
|
||||
import { ActionFunctionArgs, Form, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData, useNavigation } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import {
|
||||
listAdminBillingRows,
|
||||
requestManualBillingSync,
|
||||
setTenantBillingPlanSeats,
|
||||
AdminBillingError,
|
||||
type BillingSyncProvider,
|
||||
} from "~/services/admin/billing-admin.server";
|
||||
import { AdminActionInputError } from "~/services/admin/admin-action-audit.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: ReturnType<typeof buildAdminBillingVM>;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
const vm = buildAdminBillingVM({ rows: await listAdminBillingRows() });
|
||||
return {
|
||||
title: `${t("admin.billing.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
} satisfies LoaderData;
|
||||
};
|
||||
|
||||
function badRequest(data: ActionData) {
|
||||
return Response.json(data, { status: 400 });
|
||||
}
|
||||
|
||||
function billingErrorKey(error: unknown): string {
|
||||
if (error instanceof AdminBillingError || error instanceof AdminActionInputError) return error.i18nKey;
|
||||
return "admin.billing.errors.UNKNOWN";
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.account.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const tenantId = form.get("tenantId")?.toString() ?? "";
|
||||
const userInfo = await getUserInfo(request);
|
||||
const actor = await getUser(userInfo.userId);
|
||||
|
||||
try {
|
||||
if (action === "set-plan-seats") {
|
||||
await setTenantBillingPlanSeats({
|
||||
tenantId,
|
||||
planCode: form.get("planCode")?.toString() ?? "",
|
||||
seatQuantity: form.get("seatQuantity")?.toString() ?? "",
|
||||
reason: form.get("reason")?.toString() ?? "",
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.billing.actions.planSeatsUpdated") } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (action === "request-sync") {
|
||||
const provider = form.get("provider")?.toString() as BillingSyncProvider;
|
||||
if (provider !== "lago" && provider !== "mollie") {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
await requestManualBillingSync({
|
||||
tenantId,
|
||||
provider,
|
||||
actorUserId: userInfo.userId,
|
||||
actorEmail: actor?.email ?? null,
|
||||
request,
|
||||
});
|
||||
return Response.json({ success: t("admin.billing.actions.syncRequested", { provider: t(`admin.billing.providers.${provider}`) }) } satisfies ActionData);
|
||||
}
|
||||
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
} catch (error) {
|
||||
return badRequest({ error: t(billingErrorKey(error)) });
|
||||
}
|
||||
};
|
||||
|
||||
function FieldValue({ label, value }: { label: string; value: string | number | null }) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<div className="text-muted-foreground text-xs font-medium uppercase">{label}</div>
|
||||
<div className="text-foreground text-sm break-all">{value || "-"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SyncButtons({ row, csrf }: { row: AdminBillingRow; csrf?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(["lago", "mollie"] as const).map((provider) => (
|
||||
<Form key={provider} method="post">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="request-sync" />
|
||||
<input type="hidden" name="tenantId" value={row.tenantId} />
|
||||
<input type="hidden" name="provider" value={provider} />
|
||||
<ButtonSecondary type="submit" className="h-8 px-3 text-xs">
|
||||
{t("admin.billing.actions.requestProviderSync", { provider: t(`admin.billing.providers.${provider}`) })}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PlanSeatForm({ row, csrf, loading }: { row: AdminBillingRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Form method="post" className="grid gap-2 md:grid-cols-[minmax(120px,1fr)_96px_minmax(180px,1.5fr)_auto]">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} />
|
||||
<input type="hidden" name="action" value="set-plan-seats" />
|
||||
<input type="hidden" name="tenantId" value={row.tenantId} />
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.planCode")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="planCode"
|
||||
defaultValue={row.planCode ?? ""}
|
||||
placeholder={t("admin.billing.placeholders.planCode")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.seats")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="seatQuantity"
|
||||
type="number"
|
||||
min={1}
|
||||
defaultValue={row.seatQuantity ?? 1}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="text-muted-foreground space-y-1 text-xs font-medium">
|
||||
{t("admin.billing.fields.reason")}
|
||||
<input
|
||||
className="border-border bg-background text-foreground h-9 w-full rounded-md border px-3 text-sm"
|
||||
name="reason"
|
||||
placeholder={t("admin.billing.placeholders.reason")}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end">
|
||||
<ButtonPrimary type="submit" disabled={loading} className="h-9 px-3 text-xs">
|
||||
{t("admin.billing.actions.saveOverride")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function BillingRowCard({ row, csrf, loading }: { row: AdminBillingRow; csrf?: string; loading: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="border-border bg-background rounded-md border p-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-foreground text-base font-semibold">{row.tenantName}</div>
|
||||
<div className="text-muted-foreground text-sm">{row.tenantSlug}</div>
|
||||
</div>
|
||||
<div className="bg-muted text-foreground rounded-full px-3 py-1 text-xs font-medium">{t(row.statusLabelKey)}</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-4">
|
||||
<FieldValue label={t("admin.billing.fields.planCode")} value={row.planCode} />
|
||||
<FieldValue label={t("admin.billing.fields.seats")} value={row.seatQuantity} />
|
||||
<FieldValue label={t("admin.billing.fields.lastInvoice")} value={row.lastInvoiceExternalId} />
|
||||
<FieldValue label={t("admin.billing.fields.lastPayment")} value={row.lastPaymentExternalId} />
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 md:grid-cols-3">
|
||||
<FieldValue label={t("admin.billing.fields.readOnlyReason")} value={t(row.readOnlyReasonKey)} />
|
||||
<FieldValue label={t("admin.billing.fields.recoveryHint")} value={t(row.recoveryHintKey)} />
|
||||
<FieldValue label={t("admin.billing.fields.providers")} value={t(row.providerSummaryKey)} />
|
||||
</div>
|
||||
|
||||
<div className="border-border mt-4 border-t pt-4">
|
||||
<PlanSeatForm row={row} csrf={csrf} loading={loading} />
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<SyncButtons row={row} csrf={csrf} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminBillingRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const rootData = useRootData();
|
||||
const loading = navigation.state === "submitting";
|
||||
const rows = data.vm.status === "ready" ? data.vm.data.rows : [];
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("admin.billing.title")} fullWidth>
|
||||
<div className="space-y-4">
|
||||
<div className="border-border bg-surface-neutral-primary rounded-md border p-4">
|
||||
<div className="text-muted-foreground text-sm">{t("admin.billing.description")}</div>
|
||||
{actionData?.success && <div className="mt-3 rounded-md bg-green-50 px-3 py-2 text-sm text-green-800">{actionData.success}</div>}
|
||||
{actionData?.error && <div className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-800">{actionData.error}</div>}
|
||||
</div>
|
||||
|
||||
{data.vm.status === "empty" ? (
|
||||
<div className="border-border bg-background rounded-md border p-6">
|
||||
<div className="font-medium">{t("admin.billing.empty.headline")}</div>
|
||||
<div className="text-muted-foreground mt-1 text-sm">{t("admin.billing.empty.body")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => (
|
||||
<BillingRowCard key={row.tenantId} row={row} csrf={rootData.csrf} loading={loading} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ 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 { Blacklist } from "@hivegrid/db/prisma-browser";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
|
||||
+4
-26
@@ -3,13 +3,11 @@ 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 }),
|
||||
@@ -29,7 +27,6 @@ vi.mock("react-router", async () => {
|
||||
|
||||
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 }));
|
||||
@@ -52,7 +49,6 @@ 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(),
|
||||
@@ -69,18 +65,13 @@ vi.mock("~/utils/helpers/RowPaginationHelper", () => ({
|
||||
}));
|
||||
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" },
|
||||
subscription: { billingProviderCustomerId: "cus_1" },
|
||||
},
|
||||
{
|
||||
id: "tenant-2",
|
||||
@@ -99,7 +90,7 @@ function callLoader(url = "https://admin.example.test/accounts") {
|
||||
describe("admin accounts invoice hydration", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => `translated:${key}` } as never);
|
||||
vi.mocked(adminGetAllUsersNames).mockResolvedValue([] as never);
|
||||
@@ -110,27 +101,14 @@ describe("admin accounts invoice hydration", () => {
|
||||
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 () => {
|
||||
it("loads the default tenant list without processor invoice hydration", 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);
|
||||
expect(body).not.toHaveProperty("includeInvoices");
|
||||
});
|
||||
});
|
||||
+5
-62
@@ -1,5 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { ActionFunctionArgs, 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";
|
||||
@@ -11,24 +11,20 @@ import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropert
|
||||
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 { useActionData, 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";
|
||||
@@ -36,12 +32,8 @@ 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 = {
|
||||
@@ -49,10 +41,6 @@ type LoaderData = {
|
||||
items: TenantWithUsage[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
tenantInvoices?: Stripe.Invoice[];
|
||||
includeInvoices: boolean;
|
||||
isStripeTest: boolean;
|
||||
tenantSettingsEntity: EntityWithDetails | null;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
@@ -97,31 +85,11 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
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() });
|
||||
};
|
||||
@@ -163,7 +131,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
if (!slug || existingSlug) {
|
||||
return Response.json({ error: t("shared.slugTaken") }, { status: 400 });
|
||||
}
|
||||
const { tenant, user } = await TenantsApi.create({ request, form, name, slug });
|
||||
const { tenant, user } = await TenantsApi.create({ request, name, slug });
|
||||
const addMySelf = Boolean(form.get("addMySelf"));
|
||||
if (addMySelf) {
|
||||
const roles = await getAllRoles("app");
|
||||
@@ -192,11 +160,9 @@ export default function AdminTenantsRoute() {
|
||||
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) {
|
||||
@@ -231,11 +197,6 @@ export default function AdminTenantsRoute() {
|
||||
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"
|
||||
@@ -251,8 +212,6 @@ export default function AdminTenantsRoute() {
|
||||
<TenantsTable
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
tenantInvoices={data.tenantInvoices}
|
||||
isStripeTest={data.isStripeTest}
|
||||
actions={[
|
||||
{
|
||||
renderTitle: (i) => (!i.deactivatedReason ? t("shared.deactivate") : t("shared.activate")),
|
||||
@@ -281,7 +240,7 @@ export default function AdminTenantsRoute() {
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">
|
||||
<CreateTenantForm tenantSettingsEntity={data.tenantSettingsEntity} />
|
||||
<CreateTenantForm />
|
||||
</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
@@ -291,18 +250,7 @@ export default function AdminTenantsRoute() {
|
||||
);
|
||||
}
|
||||
|
||||
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 }) {
|
||||
function CreateTenantForm() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [name, setName] = useState("");
|
||||
@@ -330,11 +278,6 @@ function CreateTenantForm({ tenantSettingsEntity }: { tenantSettingsEntity: Enti
|
||||
<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")}
|
||||
|
||||
-4
@@ -69,10 +69,6 @@ export default function AdminRolesRoute() {
|
||||
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 />
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ 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 { Tenant } from "@hivegrid/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";
|
||||
|
||||
-1
@@ -56,7 +56,6 @@ export const action: ActionFunction = async ({ request }) => {
|
||||
description,
|
||||
type,
|
||||
isDefault: false,
|
||||
entityId: null,
|
||||
};
|
||||
const permission = await createPermission(data);
|
||||
await setPermissionRoles(permission.id, roles);
|
||||
|
||||
-207
@@ -1,207 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
+1
-1
@@ -48,7 +48,7 @@ describe("admin account subscription i18n", () => {
|
||||
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.billingProviderId");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.currentPeriod");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.canceledAt");
|
||||
expect(detail).toContain("admin.accounts.subscriptions.fields.currency");
|
||||
|
||||
+13
-3
@@ -7,18 +7,28 @@ 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 RevenueByProductPriceCurrency = {
|
||||
product: string;
|
||||
billingPeriod: SubscriptionBillingPeriod;
|
||||
currency: string;
|
||||
revenueInCurrency: number;
|
||||
revenueUsd: number;
|
||||
revenuePercentageUsd: number;
|
||||
count: number;
|
||||
countPercentage: number;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: StripeRevenueByProductPriceCurrency[];
|
||||
items: RevenueByProductPriceCurrency[];
|
||||
};
|
||||
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(),
|
||||
items: [],
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
+1
-4
@@ -16,11 +16,10 @@ import {
|
||||
getAllSubscriptionProducts,
|
||||
getAllTenantSubscriptionProducts,
|
||||
type TenantSubscriptionProductWithTenant,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
} from "@hivegrid/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 || [];
|
||||
@@ -30,7 +29,6 @@ type LoaderData = {
|
||||
items: TenantSubscriptionProductWithTenant[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
isStripeTest: boolean;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.accounts.view");
|
||||
@@ -90,7 +88,6 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ 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 { adminGetTenantSubscriptionProductById, type TenantSubscriptionProductWithTenant } from "@hivegrid/db/subscriptions.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
@@ -40,7 +40,7 @@ export default function () {
|
||||
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("admin.accounts.subscriptions.fields.billingProviderId")} defaultValue={data.item.billingProviderSubscriptionId ?? ""} 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 && (
|
||||
|
||||
+4
-4
@@ -29,7 +29,7 @@ vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
||||
vi.mock("~/utils/app/HostRouting.server", () => ({
|
||||
getHostRoutingContextFromRequest: vi.fn(() => "admin"),
|
||||
}));
|
||||
vi.mock("@toolctrl/config", () => ({
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({ routing: undefined }),
|
||||
}));
|
||||
vi.mock("~/components/core/users/UsersTable", () => ({ default: () => null }));
|
||||
@@ -78,14 +78,14 @@ vi.mock("~/utils/session.server", () => ({
|
||||
setLoggedUser: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/impersonation-audit.server", () => ({
|
||||
vi.mock("@hivegrid/db/impersonation-audit.server", () => ({
|
||||
createImpersonationAudit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
|
||||
+4
-4
@@ -19,7 +19,7 @@ import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropert
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { adminGetAllTenantsIdsAndNames, getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import type { Log } from "@toolctrl/db/prisma-browser";
|
||||
import type { Log } from "@hivegrid/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";
|
||||
@@ -33,10 +33,10 @@ 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 { createImpersonationAudit } from "@hivegrid/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { extractWebActorIp, extractWebActorUserAgent } from "~/utils/audit/withAuditContext";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAppPath, absoluteAppRootPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
|
||||
+3
-4
@@ -15,8 +15,8 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { getDbClient } from "@toolctrl/db/client.server";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
|
||||
import { formatDate, useLocaleFormatters } from "~/locale/format";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
@@ -76,8 +76,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
};
|
||||
|
||||
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 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.
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { Role } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useState } from "react";
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { Role } from "@toolctrl/db/prisma-browser";
|
||||
import { Role } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
+4
-13
@@ -3,7 +3,9 @@ import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const deferredStaticAdminTargets = new Set(["members"]);
|
||||
const deferredStaticAdminTargets = new Set([
|
||||
"members",
|
||||
]);
|
||||
|
||||
function walkFiles(relativeDirectory: string): string[] {
|
||||
const absoluteDirectory = resolveRepoPath(relativeDirectory);
|
||||
@@ -74,25 +76,14 @@ describe("admin route targets", () => {
|
||||
expect(failures).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps update and entity-view redirects on registered admin routes", () => {
|
||||
it("keeps update 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"');
|
||||
});
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
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/);
|
||||
});
|
||||
});
|
||||
-210
@@ -1,210 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
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/);
|
||||
});
|
||||
});
|
||||
-277
@@ -1,277 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
// @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();
|
||||
});
|
||||
});
|
||||
-262
@@ -1,262 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
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/);
|
||||
});
|
||||
});
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -46,7 +46,6 @@ export default function AdminApiKeysRoute() {
|
||||
>
|
||||
<ApiKeysTable
|
||||
canCreate={getUserHasPermission(adminData, "admin.apiKeys.create")}
|
||||
entities={adminData.entities}
|
||||
items={data.apiKeys}
|
||||
withTenant={true}
|
||||
/>
|
||||
|
||||
+8
-22
@@ -1,4 +1,4 @@
|
||||
import { Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import ApiKeyForm from "~/components/core/apiKeys/ApiKeyForm";
|
||||
@@ -9,7 +9,6 @@ import { RedactedApiKeyWithDetails, adminGetApiKeyById, deleteApiKey, getApiKeys
|
||||
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";
|
||||
@@ -55,11 +54,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
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) {
|
||||
@@ -72,17 +66,13 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
await updateApiKey(
|
||||
params.id ?? "",
|
||||
{
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
},
|
||||
entities
|
||||
);
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active, entities }));
|
||||
await updateApiKey(params.id ?? "", {
|
||||
tenantId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.updated", JSON.stringify({ tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.updated",
|
||||
@@ -94,13 +84,11 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
alias: alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
entities: await getApiKeyEntityPermissions(entities),
|
||||
},
|
||||
old: {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
entities: await getApiKeyEntityPermissions(existing.entities),
|
||||
},
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyUpdatedDto,
|
||||
@@ -120,7 +108,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
alias: existing.alias,
|
||||
expires: existing.expires,
|
||||
active: existing.active,
|
||||
entities: await getApiKeyEntityPermissions(existing.entities),
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyDeletedDto,
|
||||
});
|
||||
@@ -138,7 +125,6 @@ export default function AdminApiEditKeyRoute() {
|
||||
<>
|
||||
<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")}
|
||||
|
||||
+10
-22
@@ -1,16 +1,14 @@
|
||||
import { Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { Tenant } from "@hivegrid/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";
|
||||
@@ -47,11 +45,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "create") {
|
||||
const entities: { entityId: string; create: boolean; read: boolean; update: boolean; delete: boolean }[] = form
|
||||
.getAll("entities[]")
|
||||
.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
let expirationDate: Date | null = null;
|
||||
let expires = form.get("expires")?.toString();
|
||||
if (expires) {
|
||||
@@ -64,17 +57,14 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
return badRequest({ error: t("models.apiKey.errors.aliasExists", { alias }) });
|
||||
}
|
||||
const active = Boolean(form.get("active"));
|
||||
const apiKey = await createApiKey(
|
||||
{
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
},
|
||||
entities
|
||||
);
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active, entities }));
|
||||
const apiKey = await createApiKey({
|
||||
tenantId,
|
||||
createdByUserId: userInfo.userId,
|
||||
alias,
|
||||
expires: expirationDate,
|
||||
active,
|
||||
});
|
||||
await createAdminLog(request, "admin.apiKeys.created", JSON.stringify({ id: apiKey.id, tenantId, alias, expirationDate, active }));
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "api_key.created",
|
||||
@@ -85,7 +75,6 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
alias: apiKey.alias,
|
||||
expires: expirationDate,
|
||||
active: active,
|
||||
entities: await getApiKeyEntityPermissions(entities),
|
||||
user: { id: currentUser?.id ?? "", email: currentUser?.email ?? "" },
|
||||
} satisfies ApiKeyCreatedDto,
|
||||
});
|
||||
@@ -100,11 +89,10 @@ 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} />
|
||||
<ApiKeyForm tenants={data.tenants} />
|
||||
{actionData?.apiKey !== undefined && <ApiKeyCreatedModal apiKey={actionData?.apiKey} redirectTo={adminPath("api/keys", { mode: "host-aware" })} />}
|
||||
</OpenModal>
|
||||
</>
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderAuditExportNdjson, type AuditExportRow, type AuditIntegritySummary } from "./audit-export.helpers.server";
|
||||
|
||||
const integrity: AuditIntegritySummary = { ok: true, inspected: 1, firstBreakId: null, reason: null };
|
||||
|
||||
function row(overrides: Partial<AuditExportRow> = {}): AuditExportRow {
|
||||
return {
|
||||
id: "a1",
|
||||
createdAt: new Date("2026-06-24T08:00:00.000Z"),
|
||||
tenantId: "t1",
|
||||
actorType: "user",
|
||||
actorId: "u1",
|
||||
actorEmail: "a@example.com",
|
||||
actorIp: null,
|
||||
actorUserAgent: null,
|
||||
action: "kontakt.created",
|
||||
targetType: "Kontakt",
|
||||
targetId: "k1",
|
||||
requestId: null,
|
||||
sourceModule: "crm",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
regulatoryScope: ["gdpr"],
|
||||
metadata: { a: 1 },
|
||||
previousHash: null,
|
||||
eventHash: "h1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("renderAuditExportNdjson", () => {
|
||||
it("emits an integrity header line followed by one JSON object per row", () => {
|
||||
const out = renderAuditExportNdjson([row(), row({ id: "a2" })], integrity);
|
||||
const lines = out.trimEnd().split("\n");
|
||||
expect(lines).toHaveLength(3);
|
||||
expect(JSON.parse(lines[0])).toEqual({ _integrity: integrity });
|
||||
const first = JSON.parse(lines[1]);
|
||||
expect(first.id).toBe("a1");
|
||||
// Dates are serialized to ISO strings, not Date objects.
|
||||
expect(first.createdAt).toBe("2026-06-24T08:00:00.000Z");
|
||||
expect(first.regulatoryScope).toEqual(["gdpr"]);
|
||||
expect(JSON.parse(lines[2]).id).toBe("a2");
|
||||
});
|
||||
|
||||
it("produces only the header line for an empty export", () => {
|
||||
const out = renderAuditExportNdjson([], integrity);
|
||||
expect(out.trimEnd().split("\n")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
+20
-1
@@ -3,7 +3,7 @@
|
||||
* 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";
|
||||
import { computeAuditHash } from "@hivegrid/db/audit-hash";
|
||||
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
@@ -172,6 +172,25 @@ export function renderAuditExportCsv(rows: ReadonlyArray<AuditExportRow>, integr
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* NDJSON rendering (AK-P3 DoD 3): one JSON object per line. The first line is a
|
||||
* `{"_integrity": ...}` record mirroring the CSV integrity header so a streamed
|
||||
* export still carries the chain-verification evidence.
|
||||
*/
|
||||
export function renderAuditExportNdjson(rows: ReadonlyArray<AuditExportRow>, integrity: AuditIntegritySummary): string {
|
||||
const lines: string[] = [];
|
||||
lines.push(JSON.stringify({ _integrity: integrity }));
|
||||
for (const row of rows) {
|
||||
const record: Record<string, unknown> = {};
|
||||
for (const col of AUDIT_EXPORT_CSV_COLUMNS) {
|
||||
const value = (row as unknown as Record<string, unknown>)[col];
|
||||
record[col] = value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
lines.push(JSON.stringify(record));
|
||||
}
|
||||
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("|"));
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { computeAuditHash } from "@toolctrl/db/audit-hash";
|
||||
import { computeAuditHash } from "@hivegrid/db/audit-hash";
|
||||
import {
|
||||
AUDIT_EXPORT_MAX_ROWS,
|
||||
buildAuditExportWhere,
|
||||
|
||||
+79
-95
@@ -8,14 +8,15 @@
|
||||
*
|
||||
* 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 type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { useActionData, useLoaderData } from "react-router";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { buildAuditExportVM, toAuditExportResultVM, type AuditExportVM } from "@hivegrid/view-models";
|
||||
import { AuditExportPage } from "~/components/screens/audit/AuditExportPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import {
|
||||
AUDIT_EXPORT_MAX_ROWS,
|
||||
buildAuditExportWhere,
|
||||
@@ -25,18 +26,73 @@ import {
|
||||
type AuditExportRow,
|
||||
} from "./audit-export.helpers.server";
|
||||
import { buildAuditPdfLabels, renderAuditExportPdfResponse } from "~/utils/audit/pdfRender";
|
||||
import {
|
||||
AuditExportPurposeRequiredError,
|
||||
AuditExportStorageUnavailableError,
|
||||
parseAuditExportFormat,
|
||||
runAuditExportToStorage,
|
||||
} from "~/utils/audit/auditExportStorage.server";
|
||||
|
||||
type ActionData =
|
||||
| { ok: true; url: string; rowCount: number; integrityOk: boolean; expiresInSeconds: number }
|
||||
| { ok: false; errorKey: string };
|
||||
|
||||
// Interim-screen Selects submit a "__all__" sentinel for "no filter" (empty
|
||||
// string is not a valid ~/ui Select value) — treat it as absent everywhere.
|
||||
const FILTER_ALL = "__all__";
|
||||
|
||||
function filtersFromForm(form: FormData): URL {
|
||||
const params = new URLSearchParams();
|
||||
for (const key of ["from", "to", "actorType", "outcome", "tenantId"]) {
|
||||
const value = form.get(key)?.toString().trim();
|
||||
if (value && value !== FILTER_ALL) params.set(key, value);
|
||||
}
|
||||
for (const value of form.getAll("regulatoryScope")) {
|
||||
const v = value.toString().trim();
|
||||
if (v && v !== FILTER_ALL) params.append("regulatoryScope", v);
|
||||
}
|
||||
return new URL(`https://audit.local/?${params.toString()}`);
|
||||
}
|
||||
|
||||
function stripFilterSentinels(url: URL): URL {
|
||||
const cleaned = new URL(url.toString());
|
||||
for (const key of Array.from(cleaned.searchParams.keys())) {
|
||||
const values = cleaned.searchParams.getAll(key).filter((value) => value.trim() !== FILTER_ALL);
|
||||
cleaned.searchParams.delete(key);
|
||||
for (const value of values) cleaned.searchParams.append(key, value);
|
||||
}
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs): Promise<ActionData> => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
const [userInfo, form] = await Promise.all([getUserInfo(request), request.formData()]);
|
||||
const filters = parseAuditExportFilters(filtersFromForm(form));
|
||||
try {
|
||||
const result = await runAuditExportToStorage({
|
||||
filters,
|
||||
format: parseAuditExportFormat(form.get("format")?.toString()),
|
||||
purpose: form.get("purpose")?.toString() ?? "",
|
||||
actor: { id: userInfo.userId, type: "admin" },
|
||||
tenantId: filters.tenantId,
|
||||
});
|
||||
return { ok: true, url: result.url, rowCount: result.rowCount, integrityOk: result.integrityOk, expiresInSeconds: result.expiresInSeconds };
|
||||
} catch (error) {
|
||||
if (error instanceof AuditExportPurposeRequiredError) return { ok: false, errorKey: "auditExport.storage.errorPurpose" };
|
||||
if (error instanceof AuditExportStorageUnavailableError) return { ok: false, errorKey: "auditExport.storage.errorUnavailable" };
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
defaultFrom: string;
|
||||
defaultTo: string;
|
||||
maxRows: number;
|
||||
vm: AuditExportVM;
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const url = new URL(request.url);
|
||||
const url = stripFilterSentinels(new URL(request.url));
|
||||
|
||||
if (url.searchParams.get("export") === "csv") {
|
||||
return streamAdminAuditExport(url);
|
||||
@@ -49,10 +105,12 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
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,
|
||||
title: `${t("translations:models.log.plural")} | ${process.env.APP_NAME}`,
|
||||
vm: buildAuditExportVM({
|
||||
defaultFrom: fromDate.toISOString().slice(0, 10),
|
||||
defaultTo: today.toISOString().slice(0, 10),
|
||||
maxRows: AUDIT_EXPORT_MAX_ROWS,
|
||||
}),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
@@ -99,85 +157,11 @@ async function streamAdminAuditPdfExport(url: URL, t: Awaited<ReturnType<typeof
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<unknown>();
|
||||
return <AuditExportPage vm={vm} result={toAuditExportResultVM(actionData)} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+5
-5
@@ -1,7 +1,7 @@
|
||||
// @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 { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
@@ -31,7 +31,7 @@ vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@toolctrl/db/logs.server", () => ({
|
||||
vi.mock("@hivegrid/db/logs.server", () => ({
|
||||
getAdminAuditLogList: vi.fn(),
|
||||
serializeAdminAuditLogsCsv: vi.fn(),
|
||||
}));
|
||||
@@ -67,7 +67,7 @@ function readAuditRoute() {
|
||||
describe("admin audit trails route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
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);
|
||||
@@ -93,7 +93,7 @@ describe("admin audit trails route", () => {
|
||||
skip: 25,
|
||||
});
|
||||
expect(data).toMatchObject({
|
||||
title: "translated:models.log.plural | ToolCTRL",
|
||||
title: "translated:models.log.plural | HiveGrid",
|
||||
items: auditRows,
|
||||
pagination: { page: 2, pageSize: 25, totalItems: 1, totalPages: 1 },
|
||||
});
|
||||
@@ -176,7 +176,7 @@ describe("admin audit trails route", () => {
|
||||
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('from "@hivegrid/db/logs.server"');
|
||||
expect(source).toContain("getAdminAuditLogList");
|
||||
expect(source).toContain("serializeAdminAuditLogsCsv");
|
||||
expect(source).not.toContain("getAllLogs");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AdminAuditLogFilters, AdminAuditLogRow } from "@toolctrl/db/logs.server";
|
||||
import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@toolctrl/db/logs.server";
|
||||
import type { AdminAuditLogFilters, AdminAuditLogRow } from "@hivegrid/db/logs.server";
|
||||
import { getAdminAuditLogList, serializeAdminAuditLogsCsv } from "@hivegrid/db/logs.server";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import AdminAuditLogToolbar from "~/components/audit/AdminAuditLogToolbar";
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* AK-P3 — Audit-Viewer (`/admin/audit`).
|
||||
*
|
||||
* Permission-gated (`admin.auditTrails.view`), server-side filtered list over the
|
||||
* tamper-evident `AuditEvent` table (NOT the legacy `Log` model used by
|
||||
* `/admin/audit-trails`). The loader builds the AuditListVM once (persisted
|
||||
* summaryText + field-by-field beforeDiff/afterDiff since the AK-P3 core schema
|
||||
* extension; derived summary + metadata fallback for legacy rows) and the route
|
||||
* renders the interim `<AuditListPage vm actions />` screen (AD-28).
|
||||
*/
|
||||
import type { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { useLoaderData, useNavigate } from "react-router";
|
||||
import { listAuditEvents, AUDIT_VIEWER_DEFAULT_PAGE_SIZE } from "@hivegrid/db/audit-events-query.server";
|
||||
import { buildAuditListVM, type AuditListVM, type AuditListFilterState } from "@hivegrid/view-models";
|
||||
import { AuditListPage, type AuditListQuery } from "~/components/screens/audit/AuditListPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: AuditListVM;
|
||||
};
|
||||
|
||||
function parseFilters(url: URL): AuditListFilterState {
|
||||
const get = (k: string) => url.searchParams.get(k)?.trim() || null;
|
||||
const from = get("from");
|
||||
const to = get("to");
|
||||
return {
|
||||
from: from && ISO_DATE.test(from) ? from : null,
|
||||
to: to && ISO_DATE.test(to) ? to : null,
|
||||
actorType: get("actorType"),
|
||||
action: get("action"),
|
||||
outcome: get("outcome"),
|
||||
targetType: get("targetType"),
|
||||
};
|
||||
}
|
||||
|
||||
function buildWhere(filters: AuditListFilterState, tenantId: string | null): Record<string, unknown> {
|
||||
const where: Record<string, unknown> = {};
|
||||
if (tenantId) where.tenantId = tenantId;
|
||||
if (filters.actorType) where.actorType = filters.actorType;
|
||||
if (filters.outcome) where.outcome = filters.outcome;
|
||||
if (filters.targetType) where.targetType = filters.targetType;
|
||||
if (filters.action) where.action = { contains: filters.action, mode: "insensitive" };
|
||||
if (filters.from || filters.to) {
|
||||
const range: Record<string, Date> = {};
|
||||
if (filters.from) range.gte = new Date(`${filters.from}T00:00:00.000Z`);
|
||||
if (filters.to) {
|
||||
const upper = new Date(`${filters.to}T00:00:00.000Z`);
|
||||
upper.setUTCDate(upper.getUTCDate() + 1);
|
||||
range.lt = upper;
|
||||
}
|
||||
where.createdAt = range;
|
||||
}
|
||||
return where;
|
||||
}
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.auditTrails.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const url = new URL(request.url);
|
||||
|
||||
const filters = parseFilters(url);
|
||||
const tenantId = url.searchParams.get("tenantId")?.trim() || null;
|
||||
const pageRaw = Number.parseInt(url.searchParams.get("page") ?? "1", 10);
|
||||
const page = Number.isFinite(pageRaw) && pageRaw > 0 ? pageRaw : 1;
|
||||
const pageSize = AUDIT_VIEWER_DEFAULT_PAGE_SIZE;
|
||||
|
||||
// listAuditEvents lives in @hivegrid/db so the route stays free of findMany.
|
||||
const { rows, total, take } = await listAuditEvents({
|
||||
where: buildWhere(filters, tenantId),
|
||||
take: pageSize,
|
||||
skip: pageSize * (page - 1),
|
||||
});
|
||||
|
||||
const vm = buildAuditListVM({
|
||||
rows: rows.map((row) => ({
|
||||
id: row.id,
|
||||
createdAtIso: row.createdAt.toISOString(),
|
||||
actorType: row.actorType,
|
||||
actorEmail: row.actorEmail,
|
||||
actorId: row.actorId,
|
||||
action: row.action,
|
||||
targetType: row.targetType,
|
||||
targetId: row.targetId,
|
||||
outcome: row.outcome,
|
||||
hasMetadata: row.metadata != null,
|
||||
metadata: row.metadata,
|
||||
beforeDiff: row.beforeDiff,
|
||||
afterDiff: row.afterDiff,
|
||||
summaryText: row.summaryText,
|
||||
})),
|
||||
filter: filters,
|
||||
pagination: { page, pageSize: take, total, totalPages: Math.max(1, Math.ceil(total / take)) },
|
||||
canExport: true,
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings:audit.viewer.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function AuditViewerRoute() {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
function onApply(query: AuditListQuery) {
|
||||
const params = new URLSearchParams();
|
||||
if (query.from) params.set("from", query.from);
|
||||
if (query.to) params.set("to", query.to);
|
||||
if (query.actorType) params.set("actorType", query.actorType);
|
||||
if (query.action) params.set("action", query.action);
|
||||
if (query.outcome) params.set("outcome", query.outcome);
|
||||
if (query.targetType) params.set("targetType", query.targetType);
|
||||
if (query.page > 1) params.set("page", String(query.page));
|
||||
navigate({ search: params.toString() ? `?${params.toString()}` : "" });
|
||||
}
|
||||
|
||||
// Canonical admin-host link (host-aware alias, e.g. /audit-export) — matches
|
||||
// how every other admin surface links internally.
|
||||
return <AuditListPage vm={vm} exportHref={adminPath("audit-export", { mode: "host-aware" })} actions={{ onApply }} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
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
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,28 +0,0 @@
|
||||
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
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,15 +0,0 @@
|
||||
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
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,6 +0,0 @@
|
||||
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
@@ -1,12 +0,0 @@
|
||||
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
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,140 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
+2
-15
@@ -2,7 +2,6 @@ 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";
|
||||
@@ -12,7 +11,6 @@ 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", () => ({
|
||||
@@ -23,10 +21,6 @@ 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(),
|
||||
}));
|
||||
@@ -57,10 +51,6 @@ vi.mock("~/components/ui/stats/DashboardStats", () => ({
|
||||
DashboardStats: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/admin/SetupSteps", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/app/ProfileBanner", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
@@ -96,10 +86,9 @@ function readDashboardRoute() {
|
||||
describe("admin dashboard KPI route contract", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
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({
|
||||
@@ -118,12 +107,10 @@ describe("admin dashboard KPI route contract", () => {
|
||||
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",
|
||||
title: "translated:app.sidebar.dashboard | HiveGrid",
|
||||
stats,
|
||||
setupSteps,
|
||||
tenants,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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";
|
||||
@@ -35,10 +34,6 @@ export default function AdminNavigationRoute() {
|
||||
<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>
|
||||
|
||||
+3
-13
@@ -4,29 +4,25 @@ 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) => {
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
// R-P14C: legacy CrmService.validate gate (Entity-Builder "contact" entity)
|
||||
// removed; typed Kontakt model needs no bootstrap check.
|
||||
const data: LoaderData = {
|
||||
title: `${t("emailMarketing:title")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await CrmService.validate(tenantId);
|
||||
return data;
|
||||
};
|
||||
|
||||
@@ -46,12 +42,6 @@ export default () => {
|
||||
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"),
|
||||
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
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 />;
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
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 />;
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
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 />;
|
||||
+1
-1
@@ -81,7 +81,7 @@ export const action = async ({ params, request }: ActionFunctionArgs) => {
|
||||
} catch {
|
||||
return Response.json({ ok: false, error: t("admin.emailSequences.errors.stepsJsonInvalid"), field: "stepsJson" } satisfies ActionResponse);
|
||||
}
|
||||
const { parseSequenceSteps } = await import("@toolctrl/email-sequences");
|
||||
const { parseSequenceSteps } = await import("@hivegrid/email-sequences");
|
||||
try {
|
||||
parseSequenceSteps(stepsJson);
|
||||
} catch (error) {
|
||||
|
||||
+2
-2
@@ -22,7 +22,7 @@ const DEFAULT_STEPS = JSON.stringify(
|
||||
delayHours: 0,
|
||||
template: "welcome",
|
||||
subject: i18nT("admin.emailSequences.defaults.welcomeSubject"),
|
||||
variables: { productName: "Toolctrl" },
|
||||
variables: { productName: "HiveGrid" },
|
||||
},
|
||||
],
|
||||
null,
|
||||
@@ -51,7 +51,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
} catch {
|
||||
return Response.json({ ok: false, error: t("admin.emailSequences.errors.stepsJsonInvalid") } satisfies ActionResponse);
|
||||
}
|
||||
const { parseSequenceSteps } = await import("@toolctrl/email-sequences");
|
||||
const { parseSequenceSteps } = await import("@hivegrid/email-sequences");
|
||||
try {
|
||||
parseSequenceSteps(stepsJson);
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect } from "react-router";
|
||||
import EntityForm from "~/components/entities/EntityForm";
|
||||
import NewPageLayout from "~/components/ui/layouts/NewPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createEntity } from "~/utils/db/entities/entities.db.server";
|
||||
import { createEntityPermissions } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import Constants from "~/application/Constants";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { cache } from "~/utils/cache.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.create");
|
||||
return Response.json({});
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.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 slug = form.get("slug")?.toString().toLowerCase() ?? "";
|
||||
// const order = Number(form.get("order"));
|
||||
const prefix = form.get("prefix")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const titlePlural = form.get("title-plural")?.toString() ?? "";
|
||||
const isAutogenerated = Boolean(form.get("is-autogenerated"));
|
||||
const hasApi = Boolean(form.get("has-api"));
|
||||
const icon = form.get("icon")?.toString() ?? "";
|
||||
const type = form.get("type")?.toString() ?? "";
|
||||
const active = Boolean(form.get("active"));
|
||||
|
||||
const showInSidebar = Boolean(form.get("show-in-sidebar"));
|
||||
const hasTags = Boolean(form.get("has-tags"));
|
||||
const hasComments = Boolean(form.get("has-comments"));
|
||||
const hasTasks = Boolean(form.get("has-tasks"));
|
||||
const hasActivity = Boolean(form.get("has-activity"));
|
||||
const hasBulkDelete = Boolean(form.get("has-bulk-delete"));
|
||||
const hasViews = Boolean(form.get("has-views"));
|
||||
|
||||
const defaultVisibility = form.get("default-visibility")?.toString() ?? Constants.DEFAULT_ROW_VISIBILITY;
|
||||
|
||||
const onCreated = form.get("onCreated")?.toString() ?? "redirectToOverview";
|
||||
const onEdit = form.get("onEdit")?.toString() ?? "editRoute";
|
||||
|
||||
const errors = await EntitiesApi.validateEntity({ tenantId: null, name, slug, order: null, prefix });
|
||||
if (errors.length > 0) {
|
||||
return badRequest({ error: errors.join(", ") });
|
||||
}
|
||||
try {
|
||||
const entity = await createEntity({
|
||||
name,
|
||||
slug,
|
||||
prefix,
|
||||
title,
|
||||
titlePlural,
|
||||
isAutogenerated,
|
||||
hasApi,
|
||||
icon,
|
||||
active,
|
||||
type,
|
||||
showInSidebar,
|
||||
hasTags,
|
||||
hasComments,
|
||||
hasTasks,
|
||||
hasActivity,
|
||||
hasBulkDelete,
|
||||
hasViews,
|
||||
defaultVisibility,
|
||||
onCreated,
|
||||
onEdit,
|
||||
});
|
||||
|
||||
await createEntityPermissions(entity);
|
||||
|
||||
cache.clear();
|
||||
if (entity) {
|
||||
return redirect(adminPath(`entities/${slug}/properties`, { mode: "host-aware" }));
|
||||
} else {
|
||||
return badRequest({ error: t("models.entity.errors.createFailed") });
|
||||
}
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function NewEntityRoute() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<NewPageLayout
|
||||
title={`${t("shared.create")} ${t("models.entity.object")}`}
|
||||
menu={[
|
||||
{ title: t("models.entity.plural"), routePath: adminPath("entities", { mode: "host-aware" }) },
|
||||
{ title: t("shared.new"), routePath: adminPath("entities/new", { mode: "host-aware" }) },
|
||||
]}
|
||||
>
|
||||
<EntityForm />
|
||||
</NewPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import ViewBoardsEmptyIcon from "~/components/ui/icons/ViewBoardsEmptyIcon";
|
||||
import ViewBoardsIcon from "~/components/ui/icons/ViewBoardsIcon";
|
||||
import ActivityHistoryIcon from "~/components/ui/icons/entities/ActivityHistoryIcon";
|
||||
import ActivityHistoryIconFilled from "~/components/ui/icons/entities/ActivityHistoryIconFilled";
|
||||
import CodingIcon from "~/components/ui/icons/entities/CodingIcon";
|
||||
import CodingIconFilled from "~/components/ui/icons/entities/CodingIconFilled";
|
||||
import FolderIcon from "~/components/ui/icons/entities/FolderIcon";
|
||||
import FolderIconFilled from "~/components/ui/icons/entities/FolderIconFilled";
|
||||
import ModulesIcon from "~/components/ui/icons/entities/ModulesIcon";
|
||||
import ModulesIconFilled from "~/components/ui/icons/entities/ModulesIconFilled";
|
||||
import RestApiIcon from "~/components/ui/icons/entities/RestApiIcon";
|
||||
import RestApiIconFilled from "~/components/ui/icons/entities/RestApiIconFilled";
|
||||
import RowsIcon from "~/components/ui/icons/entities/RowsIcon";
|
||||
import RowsIconFilled from "~/components/ui/icons/entities/RowsIconFilled";
|
||||
import TemplateIcon from "~/components/ui/icons/entities/TemplateIcon";
|
||||
import TemplateIconFilled from "~/components/ui/icons/entities/TemplateIconFilled";
|
||||
import ExperimentIcon from "~/components/ui/icons/tests/ExperimentIcon";
|
||||
import ExperimentIconFilled from "~/components/ui/icons/tests/ExperimentIconFilled";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.entity.plural")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("models.entity.plural"),
|
||||
href: adminPath("entities", { mode: "host-aware" }),
|
||||
icon: <ModulesIcon className="h-5 w-5" />,
|
||||
iconSelected: <ModulesIconFilled className="h-5 w-5" />,
|
||||
exact: true,
|
||||
},
|
||||
{
|
||||
name: t("models.entityGroup.plural"),
|
||||
href: adminPath("entities/groups", { mode: "host-aware" }),
|
||||
icon: <FolderIcon className="h-5 w-5" />,
|
||||
iconSelected: <FolderIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.formula.plural"),
|
||||
href: adminPath("entities/formulas", { mode: "host-aware" }),
|
||||
icon: <ExperimentIcon className="h-5 w-5" />,
|
||||
iconSelected: <ExperimentIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.entity.rows"),
|
||||
href: adminPath("entities/rows", { mode: "host-aware" }),
|
||||
icon: <RowsIcon className="h-5 w-5" />,
|
||||
iconSelected: <RowsIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.view.plural"),
|
||||
href: adminPath("entities/views", { mode: "host-aware" }),
|
||||
icon: <ViewBoardsEmptyIcon className="h-5 w-5" />,
|
||||
iconSelected: <ViewBoardsIcon className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.log.plural"),
|
||||
href: adminPath("entities/logs", { mode: "host-aware" }),
|
||||
icon: <ActivityHistoryIcon className="h-5 w-5" />,
|
||||
iconSelected: <ActivityHistoryIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.entity.noCode.menu"),
|
||||
href: adminPath("entities/no-code", { mode: "host-aware" }),
|
||||
icon: <CodingIcon className="h-5 w-5" />,
|
||||
iconSelected: <CodingIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.entity.codeGenerator.menu"),
|
||||
href: adminPath("entities/code-generator", { mode: "host-aware" }),
|
||||
icon: <CodingIcon className="h-5 w-5" />,
|
||||
iconSelected: <CodingIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.entity.api"),
|
||||
href: adminPath("entities/api", { mode: "host-aware" }),
|
||||
icon: <RestApiIcon className="h-5 w-5" />,
|
||||
iconSelected: <RestApiIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.entityTemplate.plural"),
|
||||
href: adminPath("entities/templates", { mode: "host-aware" }),
|
||||
icon: <TemplateIcon className="h-5 w-5" />,
|
||||
iconSelected: <TemplateIconFilled className="h-5 w-5" />,
|
||||
bottom: true,
|
||||
},
|
||||
// {
|
||||
// name: "Code",
|
||||
// href: adminPath("entities/code", { mode: "host-aware" }),
|
||||
// icon: <CodeFileIcon className="h-5 w-5" />,
|
||||
// iconSelected: <CodeFileIconFilled className="h-5 w-5" />,
|
||||
// bottom: true,
|
||||
// },
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
import { Entity } from "@toolctrl/db/prisma-browser";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, redirect } from "react-router";
|
||||
import { Outlet, useLoaderData, useParams } from "react-router";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
item: Entity;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const item = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
if (!item) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const pathname = new URL(request.url).pathname;
|
||||
if (pathname === adminPath(`entities/${params.entity}`, { mode: "host-aware" })) {
|
||||
return redirect(adminPath(`entities/${params.entity}/details`, { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function EntityCrudPreviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.entity.noCode.sampleViewsTitle", { entity: t(data.item.title) })}
|
||||
menu={[
|
||||
{ title: t("models.entity.plural"), routePath: adminPath("entities", { mode: "host-aware" }) },
|
||||
{ title: t(data.item.title), routePath: adminPath(`entities/${params.entity}/details`, { mode: "host-aware" }) },
|
||||
{ title: t("models.entity.noCode.menu"), routePath: adminPath(`entities/${params.entity}/no-code`, { mode: "host-aware" }) },
|
||||
]}
|
||||
withHome={false}
|
||||
>
|
||||
<div className="border-border h-[calc(100vh-200px)] overflow-y-auto rounded-lg border-2 border-dashed sm:h-[calc(100vh-160px)]">
|
||||
<Outlet />
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,28 +0,0 @@
|
||||
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
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,15 +0,0 @@
|
||||
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
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,6 +0,0 @@
|
||||
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
@@ -1,12 +0,0 @@
|
||||
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
@@ -1,17 +0,0 @@
|
||||
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
@@ -1,14 +0,0 @@
|
||||
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 />;
|
||||
}
|
||||
Loaded 100 of 3781 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user