Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,54 @@
|
||||
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
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowNewRoute from "~/modules/rows/components/RowNewRoute";
|
||||
import { Rows_New } from "~/modules/rows/routes/Rows_New.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_New.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_New.action(args);
|
||||
|
||||
export default () => <RowNewRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Relationships } from "~/modules/rows/routes/Rows_Relationships.server";
|
||||
import RowsRelationshipsRoute from "~/modules/rows/components/RowsRelationshipsRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Relationships.loader(args);
|
||||
|
||||
export default () => <RowsRelationshipsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowsViewRoute from "~/modules/rows/components/RowsViewRoute";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_List.LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<RowsViewRoute
|
||||
key={data.rowsData.entity.id}
|
||||
rowsData={data.rowsData}
|
||||
items={data.rowsData.items}
|
||||
routes={data.routes}
|
||||
saveCustomViews={true}
|
||||
permissions={{
|
||||
create: getUserHasPermission(appOrAdminData, getEntityPermission(data.rowsData.entity, "create")),
|
||||
}}
|
||||
currentSession={{
|
||||
user: appOrAdminData.user,
|
||||
isSuperAdmin: appOrAdminData.isSuperAdmin,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { Fragment, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { getRows, RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import NoCodeViewsHelper from "~/utils/helpers/NoCodeViewsHelper";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
rows: RowWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
rows: await getRows({ entityId: entity.id, tenantId: null }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function EditEntityCrudRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [previews] = useState(NoCodeViewsHelper.getEntityPreviews({ t, entity: data.entity, rows: data.rows }));
|
||||
return (
|
||||
<div className="space-y-4 overflow-y-auto p-4 sm:px-8 sm:py-7">
|
||||
{previews.map((item) => {
|
||||
return (
|
||||
<div key={item.title} className="space-y-2">
|
||||
<div>
|
||||
<div className="text-foreground text-lg font-bold">{item.title}</div>
|
||||
<div className="text-muted-foreground text-sm">{item.description}</div>
|
||||
</div>
|
||||
<div className="grid gap-2 md:grid-cols-2 lg:grid-cols-3">
|
||||
{item.views.map((view) => (
|
||||
<Fragment key={view.name}>
|
||||
{!view.error ? (
|
||||
<Link
|
||||
to={`${view.href}`}
|
||||
reloadDocument={view.reloadDocument}
|
||||
className="border-border focus:bg-background hover:border-border relative flex w-full flex-col justify-center space-y-2 rounded-lg border-2 border-dashed p-3 text-center focus:border-2 focus:border-gray-600 focus:outline-hidden"
|
||||
>
|
||||
{view.icon}
|
||||
<div className="text-foreground block text-sm font-medium">
|
||||
{view.name} {view.error && <span className="text-xs lowercase text-red-500">({view.error})</span>}
|
||||
{view.underConstruction && <span className="text-xs lowercase text-orange-500">({t("shared.underConstruction")})</span>}
|
||||
</div>
|
||||
<div className="text-muted-foreground block text-xs">{view.description}</div>
|
||||
</Link>
|
||||
) : (
|
||||
<div className="border-border relative flex w-full flex-col justify-center space-y-2 rounded-lg border-2 border-dashed bg-red-50 p-3 text-center dark:bg-red-900/80">
|
||||
{view.icon}
|
||||
<div className="text-foreground block text-sm font-medium">
|
||||
{view.name} {view.error && <span className="text-xs lowercase text-red-500">({view.error})</span>}
|
||||
{view.underConstruction && <span className="text-xs lowercase text-orange-500">({t("shared.underConstruction")})</span>}
|
||||
</div>
|
||||
<div className="text-muted-foreground block text-xs">{view.description}</div>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
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 TabsVertical from "~/components/ui/tabs/TabsVertical";
|
||||
import { findEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
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 findEntityBySlug(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 EditEntityRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={`${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" }) },
|
||||
]}
|
||||
withHome={false}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-12 xl:gap-12">
|
||||
<div className="lg:col-span-3">
|
||||
<TabsVertical
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.details"),
|
||||
routePath: adminPath(`entities/${params.entity}/details`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.property.plural"),
|
||||
routePath: adminPath(`entities/${params.entity}/properties`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.relationship.plural"),
|
||||
routePath: adminPath(`entities/${params.entity}/relationships`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.view.plural"),
|
||||
routePath: adminPath(`entities/${params.entity}/views`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.entity.rows"),
|
||||
routePath: adminPath(`entities/${params.entity}/rows`, { mode: "host-aware" }),
|
||||
},
|
||||
// {
|
||||
// name: "Views and Forms",
|
||||
// routePath: adminPath(`entities/${params.entity}/views-and-forms`, { mode: "host-aware" }),
|
||||
// },
|
||||
{
|
||||
name: t("models.log.plural"),
|
||||
routePath: adminPath(`entities/logs?entity=${data.item.id}`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.entityWebhook.plural"),
|
||||
routePath: adminPath(`entities/${params.entity}/webhooks`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.entityTemplate.plural"),
|
||||
routePath: adminPath(`entities/${params.entity}/templates`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.entity.api"),
|
||||
routePath: adminPath(`entities/${params.entity}/api`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.entity.noCode.menu"),
|
||||
routePath: adminPath(`entities/${params.entity}/no-code`, { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("shared.danger"),
|
||||
routePath: adminPath(`entities/${params.entity}/danger`, { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="lg:col-span-9">
|
||||
<div className="w-full">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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.entities.view");
|
||||
const data: LoaderData = {
|
||||
apiSpecs: await ApiSpecsService.generateSpecs({ request }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("models.entity.apiDocs")}>
|
||||
<ApiSpecs item={data.apiSpecs} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useActionData } from "react-router";
|
||||
import { useLoaderData, useSubmit } from "react-router";
|
||||
import { useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { cache } from "~/utils/cache.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { deleteEntity, EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { countRows, deleteRows } from "~/utils/db/entities/rows.db.server";
|
||||
import { deleteEntityPermissions } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { getUserRoles } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
count: number;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
count: await countRows({ entityId: entity.id }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const user = await getUser(userInfo.userId);
|
||||
if (!user?.admin) {
|
||||
const userRoles = await getUserRoles(userInfo.userId);
|
||||
if (!userRoles.find((f) => f.role.name === DefaultAdminRoles.SuperAdmin)) {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "delete-all-rows") {
|
||||
await deleteRows({ entityId: entity.id, tenantId: null });
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
} else if (action === "delete") {
|
||||
try {
|
||||
const count = await countRows({ entityId: entity.id });
|
||||
if (count > 0) {
|
||||
return Response.json({ error: t("admin.entities.errors.cannotDeleteWithRows", { entity: entity.name, count }) }, { status: 400 });
|
||||
}
|
||||
await deleteEntityPermissions(entity);
|
||||
await deleteEntity(entity.id ?? "");
|
||||
cache.clear();
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
} catch (error: any) {
|
||||
return Response.json({ error: error.message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const adminData = useAdminData();
|
||||
const submit = useSubmit();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
function onDelete(action: string) {
|
||||
confirmDelete.current?.setValue(action);
|
||||
let title = t("shared.delete");
|
||||
let button = t("shared.delete");
|
||||
if (action === "delete") {
|
||||
title = t("models.entity.danger.deleteEntity", { entity: t(data.entity.title) });
|
||||
button = title;
|
||||
} else {
|
||||
title = t("models.entity.danger.deleteRows", { entity: t(data.entity.title), count: data.count });
|
||||
button = title;
|
||||
}
|
||||
confirmDelete.current?.show(title, button, t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onDeleteConfirmed(action: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", action);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function canDelete() {
|
||||
return !adminData.isSuperAdmin || !getUserHasPermission(adminData, "admin.entities.delete");
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("shared.dangerZone")}</h3>
|
||||
</div>
|
||||
<p className="pt-2 text-sm text-red-900 dark:text-red-500">{t("shared.warningCannotUndo")}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonPrimary disabled={canDelete() || data.count > 0} destructive onClick={() => onDelete("delete")}>
|
||||
{t("models.entity.danger.deleteEntity", { entity: t(data.entity.title) })}
|
||||
</ButtonPrimary>
|
||||
|
||||
<ButtonPrimary disabled={canDelete() || data.count === 0} destructive onClick={() => onDelete("delete-all-rows")}>
|
||||
{t("models.entity.danger.deleteRowsSuperAdminOnly", { count: data.count })}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirmed} destructive />
|
||||
<ActionResultModal actionData={actionData} showSuccess={false} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Entity } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import Constants from "~/application/Constants";
|
||||
import EntityForm from "~/components/entities/EntityForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { updateEntity, getEntityBySlug, getEntityById } from "~/utils/db/entities/entities.db.server";
|
||||
import { createEntityPermissions, deleteEntityPermissions } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: Entity;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const item = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
if (!item) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const item = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
if (!item) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const 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 active = Boolean(form.get("active"));
|
||||
const type = form.get("type")?.toString() ?? "";
|
||||
|
||||
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, prefix, entity: item });
|
||||
if (errors.length > 0) {
|
||||
return Response.json({ error: errors.join(", ") }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await updateEntity(item.id ?? "", {
|
||||
name,
|
||||
slug,
|
||||
order,
|
||||
prefix,
|
||||
title,
|
||||
titlePlural,
|
||||
isAutogenerated,
|
||||
hasApi,
|
||||
icon,
|
||||
active,
|
||||
type,
|
||||
showInSidebar,
|
||||
hasTags,
|
||||
hasComments,
|
||||
hasTasks,
|
||||
hasActivity,
|
||||
hasBulkDelete,
|
||||
hasViews,
|
||||
defaultVisibility,
|
||||
onCreated,
|
||||
onEdit,
|
||||
});
|
||||
await deleteEntityPermissions(item);
|
||||
const updatedEntity = await getEntityById({ tenantId: null, id: item.id });
|
||||
if (updatedEntity) {
|
||||
await createEntityPermissions(updatedEntity);
|
||||
}
|
||||
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
} catch (error: any) {
|
||||
return Response.json({ error: error.message }, { status: 400 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function EditEntityIndexRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return <EntityForm item={data.item} />;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import LogsTable from "~/components/app/events/LogsTable";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { getAllRowLogs, LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
items: LogWithDetails[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const item = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
if (!item) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await getAllRowLogs({ entityId: item.id, pagination: currentPagination });
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
pagination,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityIndexRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div>
|
||||
<LogsTable withTenant={true} items={data.items} pagination={data.pagination} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import PropertiesList from "~/components/entities/properties/PropertiesList";
|
||||
import RowForm from "~/components/entities/rows/RowForm";
|
||||
import RowTitle from "~/components/entities/rows/RowTitle";
|
||||
import RowsList from "~/components/entities/rows/RowsList";
|
||||
import InfoBanner from "~/components/ui/banners/InfoBanner";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityViewLayoutTypes } from "~/modules/rows/dtos/EntityViewLayoutType";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { PropertiesApi } from "~/utils/api/.server/PropertiesApi";
|
||||
import { PropertyWithDetails, getEntityBySlug, EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { deleteScopedProperty, getScopedProperty, updateScopedProperty, updateScopedPropertyOrder } from "~/utils/db/entities/properties.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
properties: PropertyWithDetails[];
|
||||
allEntities: EntityWithDetails[];
|
||||
routes: EntitiesApi.Routes;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
if (!entity) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
properties: entity.properties,
|
||||
allEntities: await getAllEntities({ tenantId: null }),
|
||||
routes: EntitiesApi.getNoCodeRoutes({ request, params }),
|
||||
};
|
||||
return success(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
properties?: PropertyWithDetails[];
|
||||
created?: boolean;
|
||||
updated?: boolean;
|
||||
deleted?: boolean;
|
||||
};
|
||||
const success = (data: ActionData) => Response.json(data, { status: 200 });
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
if (!entity) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
const allowedPropertyIds = new Set(entity.properties.map((property) => property.id));
|
||||
if (items.some(({ id }) => !allowedPropertyIds.has(id))) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
items.map(async ({ id, order }) => {
|
||||
await updateScopedPropertyOrder({ id, tenantId: null, entityId: entity.id }, Number(order));
|
||||
})
|
||||
);
|
||||
return Response.json({ updated: true });
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const propertyScope = { id, tenantId: null, entityId: entity.id };
|
||||
const existingProperty = await getScopedProperty(propertyScope);
|
||||
if (!existingProperty) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
await deleteScopedProperty(propertyScope);
|
||||
return success({
|
||||
properties: (await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" }))?.properties,
|
||||
deleted: true,
|
||||
});
|
||||
// return redirect(adminPath(`entities/${params.entity}/properties`, { mode: "host-aware" }));
|
||||
} else if (action === "toggle-display") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const propertyScope = { id, tenantId: null, entityId: entity.id };
|
||||
const existingProperty = await getScopedProperty(propertyScope);
|
||||
if (!existingProperty) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
await updateScopedProperty(propertyScope, {
|
||||
isDisplay: !existingProperty.isDisplay,
|
||||
});
|
||||
return Response.json({});
|
||||
// return redirect(adminPath(`entities/${params.entity}/properties`, { mode: "host-aware" }));
|
||||
} else if (action === "duplicate") {
|
||||
await verifyUserHasPermission(request, "admin.entities.create");
|
||||
try {
|
||||
const propertyId = form.get("id")?.toString() ?? "";
|
||||
const existingProperty = await getScopedProperty({ id: propertyId, tenantId: null, entityId: entity.id });
|
||||
if (!existingProperty) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
await PropertiesApi.duplicate({ entity, propertyId });
|
||||
return Response.json({ created: true });
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
const outlet = useOutlet();
|
||||
const params = useParams();
|
||||
|
||||
const [entity, setEntity] = useState<EntityWithDetails>(data.entity);
|
||||
const [fakeItems, setFakeItems] = useState<RowWithDetails[]>([]);
|
||||
const [fakeItem, setFakeItem] = useState<RowWithDetails | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setEntity(data.entity);
|
||||
|
||||
const items: RowWithDetails[] = Array.from({ length: 10 }).map((_, idx) => {
|
||||
const item: RowWithDetails = {
|
||||
values: data.entity.properties.map((property) => {
|
||||
return RowHelper.getFakePropertyValue({ property, t, idx: idx + 1 });
|
||||
}),
|
||||
folio: idx + 1,
|
||||
createdAt: new Date(),
|
||||
createdByUser: {
|
||||
email: "john.doe@email.com",
|
||||
firstName: "John",
|
||||
lastName: "Doe",
|
||||
},
|
||||
} as RowWithDetails;
|
||||
return item;
|
||||
});
|
||||
setFakeItems(items);
|
||||
setFakeItem(items[0]);
|
||||
}, [data, t]);
|
||||
|
||||
return (
|
||||
<div className="space-y-2 2xl:grid 2xl:grid-cols-2 2xl:gap-6 2xl:space-y-0">
|
||||
<PropertiesList items={data.properties.filter((f) => f.tenantId === null)} />
|
||||
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-lg font-bold">{t("models.property.previews.title")}</h2>
|
||||
<div className="border-border space-y-2 rounded-lg border-2 border-dashed px-3 pt-3 pb-3">
|
||||
{entity.properties.filter((f) => !f.isDefault).length === 0 ? (
|
||||
<InfoBanner title={t("models.property.previews.emptyTitle")} text={t("models.property.previews.emptyDescription")} />
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{fakeItem && (
|
||||
<Fragment>
|
||||
<div className="space-y-2">
|
||||
<Section title={t("models.property.previews.rowTitle")} />
|
||||
<div className="border-border text-foreground bg-background rounded-md border p-3 font-medium">
|
||||
<RowTitle entity={entity} item={fakeItem} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Section title={t("models.property.previews.form")} />
|
||||
<RowForm entity={entity} item={fakeItem} canSubmit={false} allEntities={data.allEntities} routes={data.routes} />
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
{EntityViewLayoutTypes.map((layout) => {
|
||||
if (layout.value === "board" && !entity.properties.find((f) => f.type === PropertyType.SELECT)) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Fragment key={layout.value}>
|
||||
<div className="space-y-2">
|
||||
<Section title={t("models.property.previews.listLayout", { layout: t(layout.labelKey) })} />
|
||||
<RowsList view={layout.value} entity={entity} items={fakeItems} routes={data.routes} />
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("shared.edit") : t("shared.new")}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-lg"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title }: { title: string }) {
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center" aria-hidden="true">
|
||||
<div className="border-border w-full border-t"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center">
|
||||
<span className="text-foreground bg-secondary px-3 text-base leading-6 font-semibold">{title}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import PropertyForm from "~/components/entities/properties/PropertyForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllFormulas } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import FormulaHelpers from "~/modules/formulas/utils/FormulaHelpers";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { PropertyWithDetails, EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import {
|
||||
deleteScopedProperty,
|
||||
getScopedProperty,
|
||||
updateScopedProperty,
|
||||
updateScopedPropertyAttributes,
|
||||
updateScopedPropertyOptions,
|
||||
} from "~/utils/db/entities/properties.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
item: PropertyWithDetails;
|
||||
formulas: FormulaDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
const propertyScope = { id: params.id ?? "", tenantId: null, entityId: entity.id };
|
||||
const item = await getScopedProperty(propertyScope);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/properties`));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
item,
|
||||
formulas: (await getAllFormulas()).map((formula) => FormulaHelpers.getFormulaDto(formula)),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
|
||||
const propertyScope = { id: params.id ?? "", tenantId: null, entityId: entity.id };
|
||||
const existing = await getScopedProperty(propertyScope);
|
||||
if (!existing) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const type = Number(form.get("type")) as PropertyType;
|
||||
const subtype = form.get("subtype")?.toString() ?? null;
|
||||
const order = Number(form.get("order"));
|
||||
let isRequired = Boolean(form.get("is-required"));
|
||||
const isHidden = Boolean(form.get("is-hidden"));
|
||||
const isDisplay = Boolean(form.get("is-display"));
|
||||
const isReadOnly = Boolean(form.get("is-read-only"));
|
||||
const canUpdate = Boolean(form.get("can-update"));
|
||||
let showInCreate = Boolean(form.get("show-in-create"));
|
||||
let formulaId = form.get("formula-id")?.toString() ?? null;
|
||||
|
||||
if (["id", "folio", "createdAt", "createdByUser", "sort", "page", "q", "v", "redirect", "tags"].includes(name)) {
|
||||
return badRequest({ error: t("models.property.errors.reservedName", { name }) });
|
||||
}
|
||||
|
||||
const options: { order: number; value: string; name?: string; color?: Colors }[] = form.getAll("options[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
const attributes: { name: string; value: string }[] = form.getAll("attributes[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if ([PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(type) && options.length === 0) {
|
||||
// return badRequest({ error: "Add at least one option" });
|
||||
}
|
||||
|
||||
if (type !== PropertyType.FORMULA) {
|
||||
formulaId = null;
|
||||
} else {
|
||||
isRequired = false;
|
||||
}
|
||||
if ([PropertyType.FORMULA].includes(type) && !formulaId) {
|
||||
return badRequest({ error: t("models.property.errors.selectFormula") });
|
||||
}
|
||||
|
||||
const errors = await validateProperty(name, title, entity.properties, existing, t);
|
||||
if (errors.length > 0) {
|
||||
return badRequest({ error: errors.join(", ") });
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
try {
|
||||
if (name?.includes(" ")) {
|
||||
throw Error(t("models.property.errors.nameNoSpaces"));
|
||||
}
|
||||
if (name?.includes("-")) {
|
||||
throw Error(t("models.property.errors.nameNoHyphen"));
|
||||
}
|
||||
await updateScopedProperty(propertyScope, {
|
||||
name,
|
||||
title,
|
||||
type,
|
||||
subtype,
|
||||
order,
|
||||
isDefault: existing?.isDefault ?? false,
|
||||
isRequired,
|
||||
isHidden,
|
||||
isDisplay,
|
||||
isReadOnly,
|
||||
canUpdate,
|
||||
showInCreate,
|
||||
formulaId,
|
||||
});
|
||||
await updateScopedPropertyOptions(propertyScope, options);
|
||||
await updateScopedPropertyAttributes(propertyScope, attributes);
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/properties`));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const deleteScope = { id, tenantId: null, entityId: entity.id };
|
||||
const existingProperty = await getScopedProperty(deleteScope);
|
||||
if (!existingProperty) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
await deleteScopedProperty(deleteScope);
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/properties`));
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityPropertyRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<PropertyForm
|
||||
item={data.item}
|
||||
properties={[]}
|
||||
entities={appOrAdminData.entities}
|
||||
formulas={data.formulas}
|
||||
formulaListPath={adminPath("entities/formulas", { mode: "host-aware" })}
|
||||
formulaDetailsPath={(formulaId) => adminPath(`entities/formulas/${formulaId}`, { mode: "host-aware" })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import PropertyForm from "~/components/entities/properties/PropertyForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllFormulas } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import FormulaHelpers from "~/modules/formulas/utils/FormulaHelpers";
|
||||
import { PropertiesApi } from "~/utils/api/.server/PropertiesApi";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { PropertyWithDetails, getEntityBySlug, EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { validateProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
properties: PropertyWithDetails[];
|
||||
formulas: FormulaDto[];
|
||||
};
|
||||
export const loader = async ({ params }: LoaderFunctionArgs) => {
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
properties: entity?.properties ?? [],
|
||||
formulas: (await getAllFormulas()).map((formula) => FormulaHelpers.getFormulaDto(formula)),
|
||||
};
|
||||
return success(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
properties?: PropertyWithDetails[];
|
||||
};
|
||||
const success = (data: ActionData) => Response.json(data, { status: 200 });
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const type = Number(form.get("type")) as PropertyType;
|
||||
const subtype = form.get("subtype")?.toString() ?? null;
|
||||
const order = Number(form.get("order"));
|
||||
const isDefault = Boolean(form.get("is-default"));
|
||||
let isRequired = Boolean(form.get("is-required"));
|
||||
const isHidden = Boolean(form.get("is-hidden"));
|
||||
const isDisplay = Boolean(form.get("is-display"));
|
||||
const isReadOnly = Boolean(form.get("is-read-only"));
|
||||
const canUpdate = Boolean(form.get("can-update"));
|
||||
let showInCreate = Boolean(form.get("show-in-create"));
|
||||
let formulaId = form.get("formula-id")?.toString() ?? null;
|
||||
|
||||
if (["id", "folio", "createdAt", "createdByUser", "sort", "page", "q", "v", "redirect", "tags"].includes(name)) {
|
||||
return badRequest({ error: t("models.property.errors.reservedName", { name }) });
|
||||
}
|
||||
|
||||
const options: { order: number; value: string; name?: string; color?: Colors }[] = form.getAll("options[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
const attributes: { name: string; value: string }[] = form.getAll("attributes[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if ([PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(type) && options.length === 0) {
|
||||
// return badRequest({ error: "Add at least one option" });
|
||||
}
|
||||
|
||||
if (type !== PropertyType.FORMULA) {
|
||||
formulaId = null;
|
||||
} else {
|
||||
isRequired = false;
|
||||
showInCreate = false;
|
||||
}
|
||||
if ([PropertyType.FORMULA].includes(type) && !formulaId) {
|
||||
return badRequest({ error: t("models.property.errors.selectFormula") });
|
||||
}
|
||||
|
||||
const errors = await validateProperty(name, title, entity.properties, null, t);
|
||||
if (errors.length > 0) {
|
||||
return badRequest({ error: errors.join(", ") });
|
||||
}
|
||||
|
||||
if (action === "create") {
|
||||
try {
|
||||
await PropertiesApi.create({
|
||||
entityId: entity.id,
|
||||
name,
|
||||
title,
|
||||
type,
|
||||
subtype,
|
||||
order,
|
||||
isDefault,
|
||||
isRequired,
|
||||
isHidden,
|
||||
isDisplay,
|
||||
isReadOnly,
|
||||
canUpdate,
|
||||
showInCreate,
|
||||
formulaId,
|
||||
options,
|
||||
attributes,
|
||||
tenantId: null,
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/properties`));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function NewEntityPropertyRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
|
||||
return (
|
||||
<PropertyForm
|
||||
properties={data.properties}
|
||||
entities={appOrAdminData.entities}
|
||||
formulas={data.formulas}
|
||||
formulaListPath={adminPath("entities/formulas", { mode: "host-aware" })}
|
||||
formulaDetailsPath={(formulaId) => adminPath(`entities/formulas/${formulaId}`, { mode: "host-aware" })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import { useNavigate, useOutlet } from "react-router";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import { EntityRelationshipWithDetails, getEntityRelationshipsWithCount, updateScopedEntityRelationship } from "~/utils/db/entities/entityRelationships.db.server";
|
||||
import { getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import EntityRelationshipsTable from "~/components/entities/relationships/EntityRelationshipsTable";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
items: (EntityRelationshipWithDetails & { _count: { rows: number } })[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
const items = await getEntityRelationshipsWithCount(entity.id);
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
const allowedRelationshipIds = new Set((await getEntityRelationshipsWithCount(entity.id)).map((relationship) => relationship.id));
|
||||
if (items.some(({ id }) => !allowedRelationshipIds.has(id))) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 400 });
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
items.map(async ({ id, order }) => {
|
||||
await updateScopedEntityRelationship({ id, entityId: entity.id }, { order: Number(order) });
|
||||
})
|
||||
);
|
||||
return Response.json({ updated: true });
|
||||
}
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
};
|
||||
|
||||
export default function EditEntityRelationshipsIndexRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const { t } = useTranslation();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">{t("models.relationship.plural")}</h3>
|
||||
<EntityRelationshipsTable items={data.items} editable={true} />
|
||||
<div className="w-fu flex justify-start">
|
||||
<ButtonTertiary to="new">
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
<span className="font-medium uppercase">{t("shared.add")}</span>
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={""}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-md"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import EntityRelationshipForm from "~/components/entities/relationships/EntityRelationshipForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityWithDetails, getAllEntities, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import {
|
||||
deleteScopedEntityRelationship,
|
||||
EntityRelationshipWithCount,
|
||||
findEntityRelationship,
|
||||
getScopedEntityRelationship,
|
||||
updateScopedEntityRelationship,
|
||||
} from "~/utils/db/entities/entityRelationships.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
entities: EntityWithDetails[];
|
||||
item: EntityRelationshipWithCount;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
const item = await getScopedEntityRelationship({ id: params.id ?? "", entityId: entity.id });
|
||||
if (!item) {
|
||||
return redirect(adminPath(`entities/${params.entity}/relationships`, { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
entities: await getAllEntities({ tenantId: null }),
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
const relationshipScope = { id: params.id ?? "", entityId: entity.id };
|
||||
let existing = await getScopedEntityRelationship(relationshipScope);
|
||||
if (!existing) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
// const order = Number(form.get("order"));
|
||||
let title = form.get("title")?.toString() ?? null;
|
||||
const type = form.get("relationshipType")?.toString() ?? "one-to-many";
|
||||
const required = Boolean(form.get("required"));
|
||||
const cascade = Boolean(form.get("cascade"));
|
||||
const readOnly = Boolean(form.get("readOnly"));
|
||||
const hiddenIfEmpty = Boolean(form.get("hiddenIfEmpty"));
|
||||
const childEntityViewId = form.get("childEntityViewId")?.toString() ?? null;
|
||||
const parentEntityViewId = form.get("parentEntityViewId")?.toString() ?? null;
|
||||
|
||||
if (title?.trim() === "") {
|
||||
title = null;
|
||||
}
|
||||
if (action === "edit") {
|
||||
existing = await findEntityRelationship({ parentId: existing.parentId, childId: existing.childId, title, notIn: [existing.id] });
|
||||
if (existing) {
|
||||
return badRequest({ error: t("models.relationship.errors.alreadyExists") });
|
||||
}
|
||||
try {
|
||||
await updateScopedEntityRelationship(relationshipScope, {
|
||||
// order,
|
||||
title,
|
||||
type,
|
||||
required,
|
||||
cascade,
|
||||
readOnly,
|
||||
hiddenIfEmpty,
|
||||
childEntityViewId: childEntityViewId?.length ? childEntityViewId : null,
|
||||
parentEntityViewId: parentEntityViewId?.length ? parentEntityViewId : null,
|
||||
});
|
||||
return redirect(adminPath(`entities/${params.entity}/relationships`, { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
if (existing._count.rows > 0) {
|
||||
return badRequest({ error: t("models.relationship.errors.cannotDeleteWithRows", { id: existing.id }) });
|
||||
}
|
||||
await deleteScopedEntityRelationship(relationshipScope);
|
||||
return redirect(adminPath(`entities/${params.entity}/relationships`, { mode: "host-aware" }));
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityRelationshipRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div>
|
||||
<EntityRelationshipForm entity={data.entity} entities={data.entities} item={data.item} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import EntityRelationshipForm from "~/components/entities/relationships/EntityRelationshipForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityWithDetails, getAllEntities, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { createEntityRelationship, getEntityRelationships, findEntityRelationship } from "~/utils/db/entities/entityRelationships.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
entity: EntityWithDetails;
|
||||
entities: EntityWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
const data: LoaderData = {
|
||||
title: t("models.relationship.metaTitle", { appName: process.env.APP_NAME }),
|
||||
entity,
|
||||
entities: await getAllEntities({ tenantId: null }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
if (!entity) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const parentId = form.get("parentId")?.toString() ?? entity.id;
|
||||
const childId = form.get("childId")?.toString() ?? entity.id;
|
||||
let title = form.get("title")?.toString().trim() ?? null;
|
||||
const type = form.get("relationshipType")?.toString() ?? "one-to-many";
|
||||
const required = Boolean(form.get("required"));
|
||||
const cascade = Boolean(form.get("cascade"));
|
||||
const readOnly = Boolean(form.get("readOnly"));
|
||||
const hiddenIfEmpty = Boolean(form.get("hiddenIfEmpty"));
|
||||
const childEntityViewId = form.get("childEntityViewId")?.toString() ?? null;
|
||||
const parentEntityViewId = form.get("parentEntityViewId")?.toString() ?? null;
|
||||
|
||||
if (title?.trim() === "") {
|
||||
title = null;
|
||||
}
|
||||
if (action === "create") {
|
||||
const adminEntityIds = new Set((await getAllEntities({ tenantId: null })).map((candidate) => candidate.id));
|
||||
if (!adminEntityIds.has(parentId) || !adminEntityIds.has(childId) || (parentId !== entity.id && childId !== entity.id)) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
const existing = await findEntityRelationship({ parentId, childId, title });
|
||||
if (existing) {
|
||||
return badRequest({ error: t("models.relationship.errors.alreadyExists") });
|
||||
}
|
||||
const allRelationships = await getEntityRelationships(entity.id);
|
||||
let maxOrder = 0;
|
||||
if (allRelationships.length > 0) {
|
||||
maxOrder = Math.max(...allRelationships.map((f) => f.order ?? 0));
|
||||
}
|
||||
try {
|
||||
await createEntityRelationship({
|
||||
parentId,
|
||||
childId,
|
||||
order: maxOrder + 1,
|
||||
title,
|
||||
type,
|
||||
required,
|
||||
cascade,
|
||||
readOnly,
|
||||
hiddenIfEmpty,
|
||||
childEntityViewId: childEntityViewId?.length ? childEntityViewId : null,
|
||||
parentEntityViewId: parentEntityViewId?.length ? parentEntityViewId : null,
|
||||
});
|
||||
return redirect(adminPath(`entities/${params.entity}/relationships`, { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function NewEntityRelationshipRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div>
|
||||
<EntityRelationshipForm entity={data.entity} entities={data.entities} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {};
|
||||
export const loader = async ({ params }: LoaderFunctionArgs) => {
|
||||
const data: LoaderData = {};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityIndexRoute() {
|
||||
const { t } = useTranslation();
|
||||
return <div>{t("models.entity.routes.title")}</div>;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import RowsList from "~/components/entities/rows/RowsList";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getRowsWithPagination } from "~/utils/helpers/.server/RowPaginationService";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
items: RowWithDetails[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
if (!entity) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, pagination } = await getRowsWithPagination({
|
||||
entityId: entity.id,
|
||||
page: currentPagination.page,
|
||||
pageSize: currentPagination.pageSize,
|
||||
orderBy: [{ createdAt: "desc" }],
|
||||
});
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
items,
|
||||
pagination,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityIndexRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">{t("models.row.plural")}</h3>
|
||||
<RowsList
|
||||
view="table"
|
||||
entity={data.entity}
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
leftHeaders={[
|
||||
{
|
||||
name: "object",
|
||||
title: t("models.row.payload.object"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<ShowPayloadModalButton title={t("shared.details")} description={t("shared.details")} payload={JSON.stringify(item)} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Outlet } from "react-router";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityTemplate } from "@toolctrl/db/prisma-browser";
|
||||
import { getEntityTemplates } from "~/utils/db/entities/entityTemplates.db.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
items: EntityTemplate[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const items = await getEntityTemplates(entity.id, { tenantId });
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function EntityTemplatesIndex() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
function getConfig(item: EntityTemplate) {
|
||||
try {
|
||||
const config = JSON.parse(item.config);
|
||||
const values: string[] = [];
|
||||
data.entity.properties
|
||||
.filter((f) => !f.isDefault)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.forEach((property) => {
|
||||
let value = config[property.name];
|
||||
if (value) {
|
||||
if (property.type === PropertyType.SELECT) {
|
||||
const option = property.options.find((f) => f.value === value);
|
||||
if (option) {
|
||||
value = option.name || option.value;
|
||||
}
|
||||
}
|
||||
values.push(t(property.title) + ": " + value);
|
||||
}
|
||||
});
|
||||
return values.join(", ");
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">{t("models.entityTemplate.plural")}</h3>
|
||||
<TableSimple
|
||||
headers={[
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.entityTemplate.title"),
|
||||
value: (item) => item.title,
|
||||
},
|
||||
{
|
||||
title: t("models.entityTemplate.object"),
|
||||
name: "template",
|
||||
className: "max-w-xs",
|
||||
value: (item) => <ShowPayloadModalButton title={t("models.entityTemplate.templateWithTitle", { title: item.title })} payload={getConfig(item)} />,
|
||||
},
|
||||
]}
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (idx, item) => item.id,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
<div className="w-fu flex justify-start">
|
||||
<ButtonTertiary to="new">
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
<span className="font-medium uppercase">{t("shared.add")}</span>
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
<Outlet />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { EntityTemplate } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityTemplateForm from "~/components/entities/entityTemplates/EntityTemplateForm";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { deleteScopedEntityTemplate, getEntityTemplate, updateScopedEntityTemplate } from "~/utils/db/entities/entityTemplates.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
item: EntityTemplate;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const item = await getEntityTemplate(params.id ?? "", { tenantId, entityId: entity.id });
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const templateScope = { id: params.id ?? "", tenantId, entityId: entity.id };
|
||||
const existing = await getEntityTemplate(templateScope.id, { tenantId, entityId: entity.id });
|
||||
if (!existing) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const config = form.get("config")?.toString() ?? "";
|
||||
|
||||
if (action === "edit") {
|
||||
try {
|
||||
await updateScopedEntityTemplate(templateScope, {
|
||||
title,
|
||||
config,
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
await deleteScopedEntityTemplate(templateScope);
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityTemplateRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
const navigate = useNavigate();
|
||||
function close() {
|
||||
navigate(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
}
|
||||
return (
|
||||
<SlideOverWideEmpty title={t("models.entityTemplate.edit")} open={true} className="sm:max-w-lg" onClose={close}>
|
||||
<EntityTemplateForm entity={data.entity} item={data.item} />
|
||||
</SlideOverWideEmpty>
|
||||
);
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/components/entities/entityTemplates/EntityTemplateForm", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/slideOvers/SlideOverWideEmpty", () => ({ default: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/utils/app/UrlUtils", () => ({ default: { getModulePath: vi.fn(() => "/entities/company/templates") } }));
|
||||
vi.mock("~/utils/db/entities/entities.db.server", () => ({ getEntityBySlug: vi.fn(async () => ({ id: "entity_1", slug: "company" })) }));
|
||||
vi.mock("~/utils/db/entities/entityTemplates.db.server", () => ({ createEntityTemplate: vi.fn(async () => ({ id: "template_1" })) }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn() }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdOrNull: vi.fn(async () => null) }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
|
||||
const permissions = await import("~/utils/helpers/.server/PermissionsService");
|
||||
const templatesDb = await import("~/utils/db/entities/entityTemplates.db.server");
|
||||
const sessionServer = await import("~/utils/session.server");
|
||||
const { action, loader } = await import("./new");
|
||||
|
||||
describe("admin entity template new route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(permissions.verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(sessionServer.validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
});
|
||||
|
||||
it("requires view permission before loading template form data", async () => {
|
||||
await loader({
|
||||
request: new Request("https://admin.example.com/entities/company/templates/new"),
|
||||
params: { entity: "company" },
|
||||
context: {},
|
||||
} as unknown as LoaderFunctionArgs);
|
||||
|
||||
expect(permissions.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.entities.view");
|
||||
});
|
||||
|
||||
it("requires create permission before creating a template", async () => {
|
||||
const body = new URLSearchParams({ action: "create", title: "Default", config: "{}", csrf: "csrf-token" });
|
||||
|
||||
await action({
|
||||
request: new Request("https://admin.example.com/entities/company/templates/new", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body }),
|
||||
params: { entity: "company" },
|
||||
context: {},
|
||||
} as unknown as ActionFunctionArgs);
|
||||
|
||||
expect(permissions.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.entities.create");
|
||||
expect(templatesDb.createEntityTemplate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not create a template when permission validation fails", async () => {
|
||||
vi.mocked(permissions.verifyUserHasPermission).mockRejectedValueOnce(Response.json("Unauthorized", { status: 401 }) as never);
|
||||
|
||||
await expect(
|
||||
action({
|
||||
request: new Request("https://admin.example.com/entities/company/templates/new", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: "create", title: "Default", csrf: "csrf-token" }),
|
||||
}),
|
||||
params: { entity: "company" },
|
||||
context: {},
|
||||
} as unknown as ActionFunctionArgs),
|
||||
).rejects.toMatchObject({ status: 401 });
|
||||
expect(templatesDb.createEntityTemplate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityTemplateForm from "~/components/entities/entityTemplates/EntityTemplateForm";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { createEntityTemplate } from "~/utils/db/entities/entityTemplates.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
entity: EntityWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity ?? "" });
|
||||
const data: LoaderData = {
|
||||
title: t("models.entityTemplate.metaTitle", { appName: process.env.APP_NAME }),
|
||||
entity,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.create");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId, slug: params.entity! });
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const config = form.get("config")?.toString() ?? "";
|
||||
|
||||
if (action === "create") {
|
||||
try {
|
||||
await createEntityTemplate({
|
||||
entityId: entity.id,
|
||||
tenantId,
|
||||
title,
|
||||
config,
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function NewEntityTemplateRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
const navigate = useNavigate();
|
||||
function close() {
|
||||
navigate(UrlUtils.getModulePath(params, `entities/${params.entity}/templates`));
|
||||
}
|
||||
return (
|
||||
<SlideOverWideEmpty title={t("models.entityTemplate.new")} open={true} className="sm:max-w-lg" onClose={close}>
|
||||
<EntityTemplateForm entity={data.entity} />
|
||||
</SlideOverWideEmpty>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityViewsTable from "~/components/entities/views/EntityViewsTable";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import { EntityWithDetails, getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityViewWithTenantAndUser, getAllEntityViews } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
items: EntityViewWithTenantAndUser[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
const { items } = await getAllEntityViews({
|
||||
entityId: entity.id,
|
||||
pagination: { pageSize: 1000, page: 1 },
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
entity,
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function EditEntityIndexRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">{t("models.view.plural")}</h3>
|
||||
<div>
|
||||
<div className="space-y-2">
|
||||
<EntityViewsTable
|
||||
items={data.items}
|
||||
onClickRoute={(i) => {
|
||||
return adminPath(`entities/views/${i.id}`, { mode: "host-aware" });
|
||||
}}
|
||||
/>
|
||||
|
||||
<Link
|
||||
to={adminPath(`entities/views/new/${data.entity.name}`, { mode: "host-aware" })}
|
||||
className="focus:ring-ring border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center focus:outline-hidden focus:ring-2 focus:ring-offset-2"
|
||||
>
|
||||
<PlusIcon className="text-muted-foreground mx-auto h-5" />
|
||||
<span className="text-foreground mt-2 block text-sm font-medium">{t("models.view.actions.addCustom")}</span>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LoaderFunctionArgs, redirect } from "react-router";
|
||||
import { Outlet, useLoaderData } from "react-router";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityWebhookWithDetails, getEntityWebhooks } from "~/utils/db/entities/entityWebhooks.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
items: EntityWebhookWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity ?? "" });
|
||||
if (!entity) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
const items = await getEntityWebhooks(entity.id);
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function EditEntityIndexRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">{t("models.entityWebhook.plural")}</h3>
|
||||
<TableSimple
|
||||
headers={[
|
||||
{
|
||||
title: t("models.entityWebhook.action"),
|
||||
name: "action",
|
||||
value: (item) => t(`models.entityWebhook.actions.${item.action.toLowerCase()}`),
|
||||
},
|
||||
{
|
||||
title: t("models.entityWebhook.method"),
|
||||
name: "method",
|
||||
value: (item) => item.method,
|
||||
},
|
||||
{
|
||||
title: t("models.entityWebhook.endpoint"),
|
||||
name: "endpoint",
|
||||
className: "w-full",
|
||||
value: (item) => item.endpoint,
|
||||
},
|
||||
{
|
||||
title: t("models.entityWebhook.logs"),
|
||||
name: "logs",
|
||||
className: "w-full",
|
||||
value: (item) => item._count.logs,
|
||||
},
|
||||
]}
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (idx, item) => item.id,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
<div className="w-fu flex justify-start">
|
||||
<ButtonTertiary to="new">
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
<span className="font-medium uppercase">{t("shared.add")}</span>
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
<Outlet />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { EntityWebhook } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect } from "react-router";
|
||||
import { useLoaderData, useNavigate, useParams } from "react-router";
|
||||
import EntityWebhookForm from "~/components/entities/webhooks/EntityWebhookForm";
|
||||
import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { getEntityWebhook, updateEntityWebhook, deleteEntityWebhook } from "~/utils/db/entities/entityWebhooks.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
entityId: string;
|
||||
item: EntityWebhook;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
if (!entity) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
const item = await getEntityWebhook({ id: params.id ?? "", entityId: entity.id });
|
||||
if (!item) {
|
||||
return redirect(adminPath(`entities/${params.entity}/webhooks`, { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
entityId: entity.id,
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
if (!entity) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const existing = await getEntityWebhook({ id: params.id ?? "", entityId: entity.id });
|
||||
if (!existing) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const webhookAction = form.get("webhook-action")?.toString() ?? "";
|
||||
const method = form.get("webhook-method")?.toString() ?? "";
|
||||
const endpoint = form.get("webhook-endpoint")?.toString() ?? "";
|
||||
|
||||
if (action === "edit") {
|
||||
try {
|
||||
await updateEntityWebhook({ id: params.id ?? "", entityId: entity.id }, {
|
||||
action: webhookAction,
|
||||
method,
|
||||
endpoint,
|
||||
});
|
||||
return redirect(adminPath(`entities/${params.entity}/webhooks`, { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
await deleteEntityWebhook({ id: existing.id, entityId: entity.id });
|
||||
return redirect(adminPath(`entities/${params.entity}/webhooks`, { mode: "host-aware" }));
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityWebhookRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
const navigate = useNavigate();
|
||||
function close() {
|
||||
navigate(adminPath(`entities/${params.entity}/webhooks`, { mode: "host-aware" }));
|
||||
}
|
||||
return (
|
||||
<OpenModal className="sm:max-w-sm" onClose={close}>
|
||||
<EntityWebhookForm item={data.item} />
|
||||
</OpenModal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect } from "react-router";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import EntityWebhookForm from "~/components/entities/webhooks/EntityWebhookForm";
|
||||
import OpenModal from "~/components/ui/modals/OpenModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getEntityBySlug } from "~/utils/db/entities/entities.db.server";
|
||||
import { createEntityWebhook } from "~/utils/db/entities/entityWebhooks.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: t("models.entityWebhook.metaTitle", { appName: process.env.APP_NAME }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const entity = await getEntityBySlug({ tenantId: null, slug: params.entity! });
|
||||
if (!entity) {
|
||||
return redirect(adminPath("entities", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
const webhookAction = form.get("webhook-action")?.toString() ?? "";
|
||||
const method = form.get("webhook-method")?.toString() ?? "";
|
||||
const endpoint = form.get("webhook-endpoint")?.toString() ?? "";
|
||||
|
||||
if (action === "create") {
|
||||
try {
|
||||
await createEntityWebhook({
|
||||
entityId: entity.id,
|
||||
action: webhookAction,
|
||||
method,
|
||||
endpoint,
|
||||
});
|
||||
return redirect(adminPath(`entities/${params.entity}/webhooks`, { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
}
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function NewEntityWebhookRoute() {
|
||||
const params = useParams();
|
||||
const navigate = useNavigate();
|
||||
function close() {
|
||||
navigate(adminPath(`entities/${params.entity}/webhooks`, { mode: "host-aware" }));
|
||||
}
|
||||
return (
|
||||
<OpenModal className="sm:max-w-sm" onClose={close}>
|
||||
<EntityWebhookForm />
|
||||
</OpenModal>
|
||||
);
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/entities/formulas.logs.tsx",
|
||||
"apps/web/app/routes/admin/entities/index.tsx",
|
||||
"apps/web/app/routes/admin/entities/logs.tsx",
|
||||
"apps/web/app/routes/admin/entities/no-code/lists/tasks.tsx",
|
||||
"apps/web/app/routes/admin/entities/no-code/stats/count.tsx",
|
||||
"apps/web/app/routes/admin/entities/rows.tsx",
|
||||
];
|
||||
|
||||
describe("admin entity route i18n formatting", () => {
|
||||
it("uses locale-aware formatters for visible dates, durations, and counts", () => {
|
||||
const sources = sourceFiles.map((file) => readRepoFile(file)).join("\n");
|
||||
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("formatters.dateTime");
|
||||
expect(sources).toContain("formatters.relativeDate");
|
||||
expect(sources).toContain("formatters.number");
|
||||
expect(sources).toContain('unit: "millisecond"');
|
||||
expect(sources).not.toContain("DateUtils");
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
expect(sources).not.toContain("toFixed(");
|
||||
expect(sources).not.toContain("toLocaleString");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
expect(sources).not.toContain('"{Admin}"');
|
||||
expect(sources).toContain('t("shared.admin")');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
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.entities.view");
|
||||
const data: LoaderData = {
|
||||
apiSpecs: await ApiSpecsService.generateSpecs({ request }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<EditPageLayout title={t("models.entity.apiDocs")}>
|
||||
<ApiSpecs item={data.apiSpecs} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const indexPath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities/code-generator/index.tsx");
|
||||
const filesPath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities/code-generator/files.$entity.tsx");
|
||||
const servicePath = path.resolve(process.cwd(), "apps/web/app/modules/codeGenerator/service/CodeGeneratorService.ts");
|
||||
const editApiTemplatePath = path.resolve(process.cwd(), "apps/web/app/modules/codeGenerator/templates/routes/api/CodeTemplate.Routes.Edit.Api.ts");
|
||||
const editViewTemplatePath = path.resolve(process.cwd(), "apps/web/app/modules/codeGenerator/templates/routes/views/CodeTemplate.Routes.Edit.View.ts");
|
||||
|
||||
describe("entity code generator i18n", () => {
|
||||
it("uses semantic translation keys for visible code generator labels", () => {
|
||||
const source = `${fs.readFileSync(indexPath, "utf8")}\n${fs.readFileSync(filesPath, "utf8")}`;
|
||||
|
||||
expect(source).toContain("models.entity.codeGenerator.title");
|
||||
expect(source).toContain("models.entity.codeGenerator.searchFiles");
|
||||
expect(source).toContain("models.entity.codeGenerator.lineCount");
|
||||
expect(source).toContain("models.entity.actions.create");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('"Dynamic"');
|
||||
expect(source).not.toContain(" lines)");
|
||||
});
|
||||
|
||||
it("uses semantic translation keys for generated file descriptions", () => {
|
||||
const source = fs.readFileSync(servicePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.entity.codeGenerator.fileDescriptions.dto.rowInterface");
|
||||
expect(source).toContain("models.entity.codeGenerator.fileDescriptions.api.index");
|
||||
expect(source).toContain("models.entity.codeGenerator.fileDescriptions.views.index");
|
||||
expect(source).toContain("models.entity.codeGenerator.fileDescriptions.routeShells.index");
|
||||
expect(source).toContain("models.entity.codeGenerator.fileDescriptions.schema.prisma");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain("DateUtils");
|
||||
});
|
||||
|
||||
it("generates folio labels without legacy NumberUtils imports", () => {
|
||||
const source = `${fs.readFileSync(editApiTemplatePath, "utf8")}\n${fs.readFileSync(editViewTemplatePath, "utf8")}`;
|
||||
|
||||
expect(source).toContain('padStart(4, "0")');
|
||||
expect(source).not.toContain("NumberUtils");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
import { LoaderFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useNavigate, useSearchParams } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import CodeGeneratorService, { CodeGeneratorFileDto, CodeGeneratorOptions } from "~/modules/codeGenerator/service/CodeGeneratorService";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { EntityWithDetails, getEntityByName } from "~/utils/db/entities/entities.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
type LoaderData = {
|
||||
entity: EntityWithDetails;
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await getEntityByName({ tenantId: null, name: params.entity! });
|
||||
return Response.json({ entity });
|
||||
};
|
||||
|
||||
export default function CodeGeneratorFiles() {
|
||||
const { t } = useTranslation();
|
||||
const { debug } = useRootData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [showEditor] = useState<boolean>(true);
|
||||
const [searchInput, setSearchInput] = useState<string>("");
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const [options, setOptions] = useState<CodeGeneratorOptions>(getDefaultOptions(data.entity, searchParams.get("type")?.toString()));
|
||||
|
||||
const [files, setFiles] = useState<CodeGeneratorFileDto[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const options: CodeGeneratorOptions = getDefaultOptions(data.entity, searchParams.get("type")?.toString());
|
||||
setOptions(options);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data.entity, searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (options) {
|
||||
const moduleFiles = CodeGeneratorService.getModuleFiles(options);
|
||||
const routeFiles = CodeGeneratorService.getRouteFiles(options);
|
||||
setFiles([...moduleFiles, ...routeFiles]);
|
||||
} else {
|
||||
setFiles([]);
|
||||
}
|
||||
}, [options]);
|
||||
|
||||
useEffect(() => {
|
||||
const file = searchParams.get("file");
|
||||
if (!file && files.length > 0) {
|
||||
searchParams.set("file", files[0].file);
|
||||
setSearchParams(searchParams);
|
||||
}
|
||||
}, [files, searchParams, setSearchParams]);
|
||||
|
||||
function getDefaultOptions(entity: EntityWithDetails, type?: string) {
|
||||
const options: CodeGeneratorOptions = {
|
||||
entity,
|
||||
type: type ?? "dynamic",
|
||||
moduleDirectory: CodeGeneratorService.moduleDirectoryOptions(data.entity)[0].value,
|
||||
routesDirectory: CodeGeneratorService.routeDirectoryOptions(data.entity)[0].value,
|
||||
deleteFilesOnFinish: false,
|
||||
// generateZip: false,
|
||||
};
|
||||
return options;
|
||||
}
|
||||
|
||||
function getSelectedFileCode() {
|
||||
const file = searchParams.get("file");
|
||||
const selectedFile = files.find((e) => e.file === file);
|
||||
if (selectedFile) {
|
||||
return selectedFile.content;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function getSelectedRoute() {
|
||||
if (options?.routesDirectory.includes("/app.$tenant")) {
|
||||
return "/";
|
||||
} else {
|
||||
return options?.routesDirectory.replace("./apps/web/app/routes", "") ?? "";
|
||||
}
|
||||
}
|
||||
function onTry() {
|
||||
navigate(getSelectedRoute());
|
||||
}
|
||||
function filteredItems() {
|
||||
return files.filter(
|
||||
(e) =>
|
||||
e.file.toLowerCase().includes(searchInput.toLowerCase()) ||
|
||||
// e.content.toLowerCase().includes(searchInput.toLowerCase()) ||
|
||||
e.type.toLowerCase().includes(searchInput.toLowerCase())
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3 p-4">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="text-foreground text-lg font-bold">{t("models.entity.codeGenerator.title")}</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<InputSelect
|
||||
className="col-span-3"
|
||||
title={t("models.entity.type")}
|
||||
value={options?.type}
|
||||
setValue={(e) => {
|
||||
setOptions({ ...options, type: e?.toString() ?? "" });
|
||||
searchParams.set("type", e?.toString() ?? "");
|
||||
searchParams.delete("file");
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
options={[
|
||||
{ name: t("models.entity.codeGenerator.types.dynamic"), value: "dynamic" },
|
||||
{ name: t("models.entity.codeGenerator.types.customModel"), value: "custom", disabled: true },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<InputSelect
|
||||
title={t("models.entity.codeGenerator.moduleDirectory")}
|
||||
value={options?.moduleDirectory}
|
||||
setValue={(e) => setOptions({ ...options, moduleDirectory: e?.toString() ?? "" })}
|
||||
options={CodeGeneratorService.moduleDirectoryOptions(data.entity)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<InputSelect
|
||||
title={t("models.entity.codeGenerator.routesDirectory")}
|
||||
value={options?.routesDirectory}
|
||||
setValue={(e) => setOptions({ ...options, routesDirectory: e?.toString() ?? "" })}
|
||||
options={CodeGeneratorService.routeDirectoryOptions(data.entity)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-muted-foreground mb-1 flex justify-between space-x-2 truncate text-xs font-medium">{t("models.entity.codeGenerator.files")}</label>
|
||||
<div className="border-border bg-background my-1 h-[calc(100vh-270px)] overflow-hidden rounded-md border p-2">
|
||||
<div className="flex flex-col space-y-2 md:flex-row md:space-x-2 md:space-y-0">
|
||||
<div className="md:w-5/12">
|
||||
<div className="hidden space-y-2 overflow-y-auto p-1 md:block">
|
||||
<InputText placeholder={t("models.entity.codeGenerator.searchFiles", { count: files.length })} value={searchInput} setValue={(e) => setSearchInput(e.toString() ?? "")} />
|
||||
<ul className="bg-background border-border divide-border h-[calc(100vh-325px)] divide-y overflow-y-scroll rounded-md border">
|
||||
{filteredItems().map((file, idx) => (
|
||||
<li key={idx}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
searchParams.set("file", file.file);
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
className={clsx(
|
||||
"w-full cursor-pointer truncate rounded-sm border-2 border-dashed p-2 text-left text-sm",
|
||||
searchParams.get("file") === file.file
|
||||
? "border-border text-foreground bg-secondary/90 "
|
||||
: "hover:bg-secondary/90 text-foreground/80 border-transparent"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between space-x-3">
|
||||
<div className="flex flex-col">
|
||||
<div className="truncate">
|
||||
{file.file} <span className="text-muted-foreground text-xs">({t("models.entity.codeGenerator.lineCount", { count: file.content.split("\n").length })})</span>
|
||||
</div>
|
||||
{file.directory && <span className="text-muted-foreground text-xs font-medium">{file.directory}/</span>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<ColorBadge color={file.type === "module" ? Colors.BLUE : file.type === "route" ? Colors.RED : Colors.VIOLET} />
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
<InputSelect
|
||||
className="md:hidden"
|
||||
options={files.map((file, idx) => {
|
||||
return { name: file.file, value: idx };
|
||||
})}
|
||||
title={t("models.entity.codeGenerator.selectFile")}
|
||||
value="test"
|
||||
setValue={(i) => {
|
||||
searchParams.set("file", files[i as number].file);
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{showEditor && (
|
||||
<div className="overflow-y-auto md:w-7/12">
|
||||
<div>
|
||||
<InputText
|
||||
editor="monaco"
|
||||
editorLanguage="typescript"
|
||||
withLabel={false}
|
||||
value={getSelectedFileCode()}
|
||||
setValue={() => {}}
|
||||
editorSize="screen"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-1">
|
||||
<ButtonSecondary disabled={!debug} onClick={onTry}>
|
||||
{t("shared.try")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { LoaderFunction } from "react-router";
|
||||
import { Link, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
entities: EntityWithDetails[];
|
||||
};
|
||||
export let loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const data: LoaderData = {
|
||||
entities: await getAllEntities({ tenantId: null }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div className="space-y-4 overflow-y-auto p-4 sm:px-8 sm:py-7">
|
||||
{data.entities.length === 0 ? (
|
||||
<Link
|
||||
to={adminPath("entities/new", { mode: "host-aware" })}
|
||||
className="border-border focus:bg-background hover:border-border relative flex w-full flex-col justify-center space-y-2 rounded-lg border-2 border-dashed p-6 text-center focus:border-2 focus:border-gray-600 focus:outline-hidden"
|
||||
>
|
||||
<div className="text-foreground block text-sm font-medium">{t("models.entity.actions.create")}</div>
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-foreground text-lg font-bold">{t("shared.generate")}</div>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{data.entities.map((item) => {
|
||||
return (
|
||||
<Link
|
||||
key={item.name}
|
||||
to={`files/${item.name}`}
|
||||
reloadDocument
|
||||
className="border-border focus:bg-background hover:border-border relative flex w-full flex-col justify-center space-y-2 rounded-lg border-2 border-dashed p-3 text-center focus:border-2 focus:border-gray-600 focus:outline-hidden"
|
||||
>
|
||||
<div className="text-foreground block text-sm font-medium">{t(item.titlePlural)}</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import UnderConstruction from "~/components/ui/misc/UnderConstruction";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
return <UnderConstruction title={t("admin.entities.code.title")} description={t("admin.entities.code.description")} />;
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const sourcePath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities/$entity/danger.tsx");
|
||||
|
||||
describe("admin entity danger i18n", () => {
|
||||
it("uses semantic translation keys for danger labels and delete actions", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.entity.danger.deleteEntity");
|
||||
expect(source).toContain("models.entity.danger.deleteRows");
|
||||
expect(source).toContain("models.entity.danger.deleteRowsSuperAdminOnly");
|
||||
expect(source).toContain("shared.dangerZone");
|
||||
expect(source).toContain("shared.warningCannotUndo");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain("Delete {data.entity.title} entity");
|
||||
expect(source).not.toContain("Delete {data.count} rows");
|
||||
});
|
||||
|
||||
it("keeps entity danger count copy plural-aware in English and German", () => {
|
||||
const en = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/en/translations.json"), "utf8"));
|
||||
const de = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/de/translations.json"), "utf8"));
|
||||
|
||||
expect(en.admin.entities.errors.cannotDeleteWithRows_one).toContain("{{count}} row");
|
||||
expect(en.admin.entities.errors.cannotDeleteWithRows_other).toContain("{{count}} rows");
|
||||
expect(en.models.entity.danger.deleteRows_one).toContain("row");
|
||||
expect(en.models.entity.danger.deleteRows_other).toContain("rows");
|
||||
expect(en.models.entity.danger.deleteRowsSuperAdminOnly_one).toContain("row");
|
||||
expect(en.models.entity.danger.deleteRowsSuperAdminOnly_other).toContain("rows");
|
||||
expect(de.admin.entities.errors.cannotDeleteWithRows_one).toContain("{{count}} Datensatz vorhanden ist");
|
||||
expect(de.models.entity.danger.deleteRowsSuperAdminOnly_other).toContain("Datensätze");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities");
|
||||
const componentsRoot = path.resolve(process.cwd(), "apps/web/app/components/entities");
|
||||
|
||||
function read(file: string) {
|
||||
return fs.readFileSync(file, "utf8");
|
||||
}
|
||||
|
||||
describe("admin entity micro labels i18n", () => {
|
||||
it("uses semantic translation keys for remaining small labels", () => {
|
||||
const sources = [
|
||||
read(path.join(componentsRoot, "rows/RowSettingsPermissions.tsx")),
|
||||
read(path.join(routeRoot, "no-code/stats/count.tsx")),
|
||||
read(path.join(routeRoot, "rows.tsx")),
|
||||
read(path.join(routeRoot, "$entity/rows.tsx")),
|
||||
read(path.join(routeRoot, "api.tsx")),
|
||||
read(path.join(routeRoot, "$entity/api.tsx")),
|
||||
].join("\n");
|
||||
|
||||
expect(sources).toContain("shared.remove");
|
||||
expect(sources).toContain("shared.summary");
|
||||
expect(sources).toContain("shared.details");
|
||||
expect(sources).toContain("models.row.payload.object");
|
||||
expect(sources).toContain("models.entity.apiDocs");
|
||||
expect(sources).not.toContain('title="API Docs"');
|
||||
expect(sources).not.toContain('title: "Object"');
|
||||
expect(sources).not.toContain('name: "Remove"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities");
|
||||
const componentsRoot = path.resolve(process.cwd(), "apps/web/app/components/entities");
|
||||
|
||||
describe("admin entity navigation i18n", () => {
|
||||
it("uses semantic translation keys for entity tabs and no-code links", () => {
|
||||
const sources = [
|
||||
fs.readFileSync(path.join(routeRoot, "$entity.tsx"), "utf8"),
|
||||
fs.readFileSync(path.join(routeRoot, "$entity.no-code.tsx"), "utf8"),
|
||||
fs.readFileSync(path.join(componentsRoot, "EntitiesTable.tsx"), "utf8"),
|
||||
].join("\n");
|
||||
|
||||
expect(sources).toContain("models.entity.noCode.menu");
|
||||
expect(sources).toContain("models.entity.noCode.sampleViewsTitle");
|
||||
expect(sources).toContain("models.entityWebhook.plural");
|
||||
expect(sources).toContain("models.entityTemplate.plural");
|
||||
expect(sources).toContain("models.entity.api");
|
||||
expect(sources).not.toContain('name: "No-code"');
|
||||
expect(sources).not.toContain('name: "Danger"');
|
||||
expect(sources).not.toContain('title: "No-code"');
|
||||
expect(sources).not.toContain(" - Sample views");
|
||||
});
|
||||
});
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities");
|
||||
|
||||
function readRoute(relativePath: string) {
|
||||
return fs.readFileSync(path.join(routeRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("admin entity property previews i18n", () => {
|
||||
it("uses semantic translation keys for preview labels", () => {
|
||||
const source = readRoute("$entity/properties.tsx");
|
||||
|
||||
expect(source).toContain("models.property.previews.title");
|
||||
expect(source).toContain("models.property.previews.emptyTitle");
|
||||
expect(source).toContain("models.property.previews.emptyDescription");
|
||||
expect(source).toContain("models.property.previews.rowTitle");
|
||||
expect(source).toContain("models.property.previews.form");
|
||||
expect(source).toContain("models.property.previews.listLayout");
|
||||
expect(source).not.toContain("ui.autogenerated.previews");
|
||||
expect(source).not.toContain("Add some properties to see previews");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities");
|
||||
const tenantRouteRoot = path.resolve(process.cwd(), "apps/web/app/routes/app.$tenant/settings/entities");
|
||||
const propertyHelperPath = path.resolve(process.cwd(), "apps/web/app/utils/helpers/PropertyHelper.ts");
|
||||
|
||||
function readRoute(relativePath: string) {
|
||||
return fs.readFileSync(path.join(routeRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("admin entity property route scoping", () => {
|
||||
it("scopes property detail reads and mutations to the current entity", () => {
|
||||
const source = readRoute("$entity/properties/$id.tsx");
|
||||
|
||||
expect(source).toContain("getScopedProperty");
|
||||
expect(source).toContain("updateScopedProperty");
|
||||
expect(source).toContain("updateScopedPropertyOptions");
|
||||
expect(source).toContain("updateScopedPropertyAttributes");
|
||||
expect(source).toContain("deleteScopedProperty");
|
||||
expect(source).toContain("entityId: entity.id");
|
||||
expect(source).not.toMatch(/\bgetProperty\(/);
|
||||
expect(source).not.toMatch(/\bupdateProperty\(/);
|
||||
expect(source).not.toMatch(/\bupdatePropertyOptions\(/);
|
||||
expect(source).not.toMatch(/\bupdatePropertyAttributes\(/);
|
||||
expect(source).not.toMatch(/\bdeleteProperty\(/);
|
||||
});
|
||||
|
||||
it("scopes property list actions to the current entity", () => {
|
||||
const source = readRoute("$entity/properties.tsx");
|
||||
|
||||
expect(source).toContain("getScopedProperty");
|
||||
expect(source).toContain("updateScopedProperty");
|
||||
expect(source).toContain("updateScopedPropertyOrder");
|
||||
expect(source).toContain("deleteScopedProperty");
|
||||
expect(source).toContain("allowedPropertyIds");
|
||||
expect(source).toContain("entityId: entity.id");
|
||||
expect(source).not.toMatch(/\bgetProperty\(/);
|
||||
expect(source).not.toMatch(/\bupdateProperty\(/);
|
||||
expect(source).not.toMatch(/\bupdatePropertyOrder\(/);
|
||||
expect(source).not.toMatch(/\bdeleteProperty\(/);
|
||||
});
|
||||
|
||||
it("keeps property validation errors behind semantic translation keys", () => {
|
||||
const source = [
|
||||
readRoute("$entity/properties/new.tsx"),
|
||||
readRoute("$entity/properties/$id.tsx"),
|
||||
fs.readFileSync(path.join(tenantRouteRoot, "$entity/new.tsx"), "utf8"),
|
||||
fs.readFileSync(path.join(tenantRouteRoot, "$entity/$id.tsx"), "utf8"),
|
||||
fs.readFileSync(propertyHelperPath, "utf8"),
|
||||
].join("\n");
|
||||
|
||||
expect(source).toContain("models.property.errors.existingName");
|
||||
expect(source).toContain("models.property.errors.existingTitle");
|
||||
expect(source).toContain("models.property.errors.nameNoSpaces");
|
||||
expect(source).toContain("models.property.errors.nameNoHyphen");
|
||||
expect(source).toContain("models.property.errors.reservedName");
|
||||
expect(source).not.toContain('throw Error("Property names cannot contain spaces")');
|
||||
expect(source).not.toContain('throw Error("Property names cannot contain: -")');
|
||||
expect(source).not.toContain('" is a reserved property name"');
|
||||
});
|
||||
|
||||
it("keeps tenant entity feature gate errors behind semantic translation keys", () => {
|
||||
const source = [fs.readFileSync(path.join(tenantRouteRoot, "index.tsx"), "utf8"), fs.readFileSync(path.join(tenantRouteRoot, "$entity.tsx"), "utf8")].join(
|
||||
"\n"
|
||||
);
|
||||
|
||||
expect(source).toContain("settings.entities.errors.tenantEntityCustomizationNotEnabled");
|
||||
expect(source).not.toContain('throw Error("Entity customization is not enabled")');
|
||||
});
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities");
|
||||
const helperPath = path.resolve(process.cwd(), "apps/web/app/utils/db/entities/entityRelationships.db.server.ts");
|
||||
|
||||
function readRoute(relativePath: string) {
|
||||
return fs.readFileSync(path.join(routeRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("admin entity relationship route scoping", () => {
|
||||
it("exposes scoped relationship DB helpers", () => {
|
||||
const source = fs.readFileSync(helperPath, "utf8");
|
||||
|
||||
expect(source).toContain("getScopedEntityRelationship");
|
||||
expect(source).toContain("updateScopedEntityRelationship");
|
||||
expect(source).toContain("deleteScopedEntityRelationship");
|
||||
expect(source).toContain("OR: [{ parentId: scope.entityId }, { childId: scope.entityId }]");
|
||||
});
|
||||
|
||||
it("scopes relationship detail mutations to the current entity", () => {
|
||||
const source = readRoute("$entity/relationships/$id.tsx");
|
||||
|
||||
expect(source).toContain("getScopedEntityRelationship");
|
||||
expect(source).toContain("updateScopedEntityRelationship");
|
||||
expect(source).toContain("deleteScopedEntityRelationship");
|
||||
expect(source).toContain("entityId: entity.id");
|
||||
expect(source).not.toMatch(/\bgetEntityRelationship\(/);
|
||||
expect(source).not.toMatch(/\bupdateEntityRelationship\(/);
|
||||
expect(source).not.toMatch(/\bdeleteEntityRelationship\(/);
|
||||
});
|
||||
|
||||
it("scopes relationship list order updates to the current entity", () => {
|
||||
const source = readRoute("$entity/relationships.tsx");
|
||||
|
||||
expect(source).toContain("allowedRelationshipIds");
|
||||
expect(source).toContain("updateScopedEntityRelationship");
|
||||
expect(source).toContain("entityId: entity.id");
|
||||
expect(source).not.toMatch(/\bupdateEntityRelationship\(/);
|
||||
});
|
||||
|
||||
it("scopes relationship creation to admin entities and the current entity", () => {
|
||||
const source = readRoute("$entity/relationships/new.tsx");
|
||||
|
||||
expect(source).toContain("adminEntityIds");
|
||||
expect(source).toContain("parentId !== entity.id && childId !== entity.id");
|
||||
expect(source).toContain("getAllEntities({ tenantId: null })");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const relationshipNewPath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities/$entity/relationships/new.tsx");
|
||||
const entityViewsPath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities/$entity/views.tsx");
|
||||
const viewsPath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities/views.tsx");
|
||||
const entitiesShellPath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities.tsx");
|
||||
|
||||
describe("entity route shell i18n", () => {
|
||||
it("uses semantic translation keys for relationship and view route shell labels", () => {
|
||||
const source = [relationshipNewPath, entityViewsPath, viewsPath, entitiesShellPath].map((file) => fs.readFileSync(file, "utf8")).join("\n");
|
||||
|
||||
expect(source).toContain("models.relationship.metaTitle");
|
||||
expect(source).toContain("models.view.actions.addCustom");
|
||||
expect(source).toContain("models.view.actions.newForEntity");
|
||||
expect(source).toContain("models.view.typeOptions.default");
|
||||
expect(source).toContain("models.entity.codeGenerator.menu");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('"All accounts"');
|
||||
expect(source).not.toContain('"Edit view"');
|
||||
expect(source).not.toContain('name: "Rows"');
|
||||
expect(source).not.toContain('name: "Yes-code"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const indexPath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities/templates/index.tsx");
|
||||
const manualPath = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities/templates/manual.tsx");
|
||||
|
||||
describe("entity template manual i18n", () => {
|
||||
it("uses semantic translation keys for the template picker and manual import flow", () => {
|
||||
const source = `${fs.readFileSync(indexPath, "utf8")}\n${fs.readFileSync(manualPath, "utf8")}`;
|
||||
|
||||
expect(source).toContain("models.entityTemplate.manual");
|
||||
expect(source).toContain("models.entityTemplate.uploadJsonConfiguration");
|
||||
expect(source).toContain("models.entityTemplate.defaultTemplates.crm");
|
||||
expect(source).toContain("models.entityTemplate.actions.createEntities");
|
||||
expect(source).toContain("models.entityTemplate.actions.createdEntities");
|
||||
expect(source).toContain("shared.invalidForm");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain("Invalid form");
|
||||
expect(source).not.toContain("Create {actionData.previewTemplate.entities.length} entities");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createFormula, getFormula, updateFormula } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
vi.mock("~/modules/formulas/db/formulas.db.server", () => ({
|
||||
createFormula: vi.fn(),
|
||||
deleteFormula: vi.fn(),
|
||||
getFormula: vi.fn(),
|
||||
updateFormula: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string) =>
|
||||
({
|
||||
"pages.formulas.errors.missingComponents": "Add at least one formula component.",
|
||||
"pages.formulas.errors.missingRequiredFields": "Name, result type, and calculation trigger are required.",
|
||||
"shared.invalidForm": "Invalid form.",
|
||||
})[key] ?? key,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/modals/ActionResultModal", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/formulas/components/FormulaForm", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
function postRequest(form: FormData) {
|
||||
return new Request("https://admin.example.test/entities/formulas", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(form as unknown as Record<string, string>),
|
||||
});
|
||||
}
|
||||
|
||||
function newFormulaForm(overrides: Record<string, string> = {}) {
|
||||
const form = new FormData();
|
||||
form.set("action", "new");
|
||||
form.set("name", "Revenue");
|
||||
form.set("resultAs", "number");
|
||||
form.set("calculationTrigger", "IF_UNSET");
|
||||
for (const [key, value] of Object.entries(overrides)) {
|
||||
form.set(key, value);
|
||||
}
|
||||
return form;
|
||||
}
|
||||
|
||||
describe("admin formula action errors", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getFormula).mockResolvedValue({
|
||||
id: "formula_1",
|
||||
name: "Revenue",
|
||||
description: "",
|
||||
resultAs: "number",
|
||||
calculationTrigger: "IF_UNSET",
|
||||
withLogs: false,
|
||||
components: [],
|
||||
} as never);
|
||||
});
|
||||
|
||||
it("returns localized invalid-form errors for unknown create actions without creating a formula", async () => {
|
||||
const { action } = await import("./formulas/new");
|
||||
const form = new FormData();
|
||||
form.set("action", "rotate");
|
||||
|
||||
const response = (await action({
|
||||
request: postRequest(form),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/entities/formulas/new",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ error: "Invalid form." });
|
||||
expect(response.status).toBe(400);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.formulas.create");
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(createFormula).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns localized missing-required-field errors before creating a formula", async () => {
|
||||
const { action } = await import("./formulas/new");
|
||||
|
||||
const response = (await action({
|
||||
request: postRequest(newFormulaForm({ name: "" })),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/entities/formulas/new",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ error: "Name, result type, and calculation trigger are required." });
|
||||
expect(response.status).toBe(400);
|
||||
expect(createFormula).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns localized missing-component errors before updating a formula", async () => {
|
||||
const { action } = await import("./formulas/$id");
|
||||
|
||||
const response = (await action({
|
||||
request: postRequest(
|
||||
(() => {
|
||||
const form = newFormulaForm();
|
||||
form.set("action", "edit");
|
||||
return form;
|
||||
})()
|
||||
),
|
||||
params: { id: "formula_1" },
|
||||
context: {},
|
||||
unstable_pattern: "admin/entities/formulas/$id",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ error: "Add at least one formula component." });
|
||||
expect(response.status).toBe(400);
|
||||
expect(getFormula).toHaveBeenCalledWith("formula_1");
|
||||
expect(updateFormula).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "formulas.logs.tsx"), "utf8");
|
||||
|
||||
describe("admin formula logs route i18n", () => {
|
||||
it("uses formula log translation keys for visible labels", () => {
|
||||
expect(source).toContain("pages.formulas.logs.status.success");
|
||||
expect(source).toContain("pages.formulas.logs.status.error");
|
||||
expect(source).toContain("pages.formulas.logs.status.noResult");
|
||||
expect(source).toContain("pages.formulas.logs.deleteSelected");
|
||||
expect(source).toContain("pages.formulas.logs.componentsCount");
|
||||
expect(source).toContain("pages.formulas.calculationTriggers.${item}");
|
||||
});
|
||||
|
||||
it("does not render legacy autogenerated keys or hardcoded formula log labels", () => {
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('name: "Success"');
|
||||
expect(source).not.toContain('name: "Error"');
|
||||
expect(source).not.toContain('name: "No result"');
|
||||
expect(source).not.toContain("Delete {selectedRows.length}");
|
||||
expect(source).not.toContain('+ " components"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,362 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useSubmit } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { FilterableValueLink } from "~/components/ui/links/FilterableValueLink";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { FormulaLogWithDetails, getFormulaLogs } from "~/modules/formulas/db/formulaLogs.db.server";
|
||||
import { getAllFormulasIdsAndNames } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { FormulaCalculationTriggerTypes } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import SpeedBadge from "~/modules/metrics/components/SpeedBadge";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: FormulaLogWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
allEntities: EntityWithDetails[];
|
||||
};
|
||||
|
||||
const formulaLogTriggerSourceKeys: Record<string, string> = {
|
||||
TEST: "pages.formulas.logs.triggerSources.TEST",
|
||||
};
|
||||
|
||||
function getFormulaLogTriggerLabel(t: TFunction, value: string | null | undefined) {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
if ((FormulaCalculationTriggerTypes as readonly string[]).includes(value)) {
|
||||
return t(`pages.formulas.calculationTriggers.${value}`);
|
||||
}
|
||||
const triggerSourceKey = formulaLogTriggerSourceKeys[value];
|
||||
return triggerSourceKey ? t(triggerSourceKey) : value;
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.formulas.view");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "formulaId",
|
||||
title: t("pages.formulas.object"),
|
||||
options: (await getAllFormulasIdsAndNames()).map((item) => {
|
||||
return { value: item.id, name: item.name };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
title: t("pages.formulas.logs.columns.status"),
|
||||
manual: true,
|
||||
options: [
|
||||
{ name: t("pages.formulas.logs.status.success"), value: "success" },
|
||||
{ name: t("pages.formulas.logs.status.error"), value: "error" },
|
||||
{ name: t("pages.formulas.logs.status.noResult"), value: "empty" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "originalTrigger",
|
||||
title: t("pages.formulas.logs.columns.originalTrigger"),
|
||||
options: FormulaCalculationTriggerTypes.map((item) => ({ name: t(`pages.formulas.calculationTriggers.${item}`), value: item })),
|
||||
},
|
||||
{
|
||||
name: "triggeredBy",
|
||||
title: t("pages.formulas.logs.columns.triggeredBy"),
|
||||
options: FormulaCalculationTriggerTypes.map((item) => ({ name: t(`pages.formulas.calculationTriggers.${item}`), value: item })),
|
||||
},
|
||||
{
|
||||
name: "hasRowId",
|
||||
title: t("pages.formulas.logs.columns.hasRow"),
|
||||
manual: true,
|
||||
},
|
||||
{
|
||||
name: "rowValueId",
|
||||
title: t("pages.formulas.logs.columns.rowValueId"),
|
||||
},
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
options: (await adminGetAllTenantsIdsAndNames()).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: t("models.user.object"),
|
||||
options: (await adminGetAllUsersNames()).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.email,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
|
||||
const logs = await getFormulaLogs({
|
||||
id: params.id!,
|
||||
pagination: { pageSize: pagination.pageSize, page: pagination.page },
|
||||
filters,
|
||||
});
|
||||
const allEntities = await getAllEntities({ tenantId: null });
|
||||
const data: LoaderData = {
|
||||
title: t("pages.formulas.logs.metaTitle", { appName: process.env.APP_NAME }),
|
||||
items: logs.items,
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems: logs.total,
|
||||
totalPages: Math.ceil(logs.total / pagination.pageSize),
|
||||
},
|
||||
allEntities,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("action") === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.formulas.delete");
|
||||
const ids = (form.get("ids")?.toString().split(",") ?? []).map((x) => x.toString() ?? "");
|
||||
await db.formulaLog.deleteMany({
|
||||
where: { id: { in: ids } },
|
||||
});
|
||||
return Response.json({ success: true });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm"), success: false }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const submit = useSubmit();
|
||||
|
||||
const [selectedRows, setSelectedRows] = useState<FormulaLogWithDetails[]>([]);
|
||||
function onDelete(ids: string[]) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
form.set("ids", ids.join(","));
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={``}
|
||||
menu={[
|
||||
{
|
||||
title: t("pages.formulas.plural"),
|
||||
routePath: adminPath("entities/formulas", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
title: t("pages.formulas.logs.breadcrumb"),
|
||||
routePath: adminPath("entities/formulas/logs", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between space-x-2">
|
||||
<h2 className="text-xl font-semibold">{t("pages.formulas.logs.title")}</h2>
|
||||
<div className="flex items-center space-x-2">
|
||||
{selectedRows.length > 0 && (
|
||||
<ButtonSecondary
|
||||
destructive
|
||||
disabled={!getUserHasPermission(appOrAdminData, "admin.formulas.delete")}
|
||||
onClick={() => {
|
||||
onDelete(selectedRows.map((x) => x.id));
|
||||
setSelectedRows([]);
|
||||
}}
|
||||
>
|
||||
{t("pages.formulas.logs.deleteSelected", { count: selectedRows.length })}
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
<InputFilters withSearch={false} filters={data.filterableProperties} />
|
||||
</div>
|
||||
</div>
|
||||
<TableSimple
|
||||
selectedRows={selectedRows}
|
||||
onSelected={setSelectedRows}
|
||||
pagination={data.pagination}
|
||||
items={data.items}
|
||||
headers={[
|
||||
{
|
||||
name: "formula",
|
||||
title: t("pages.formulas.object"),
|
||||
value: (item) => item.formula.name,
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
title: t("pages.formulas.logs.columns.status"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
{item.error ? (
|
||||
<FilterableValueLink name="status" value="error">
|
||||
<SimpleBadge title={t("pages.formulas.logs.status.error")} color={Colors.RED} />
|
||||
</FilterableValueLink>
|
||||
) : item.result.length === 0 ? (
|
||||
<FilterableValueLink name="status" value="empty">
|
||||
<SimpleBadge title={t("pages.formulas.logs.status.noResult")} color={Colors.YELLOW} />
|
||||
</FilterableValueLink>
|
||||
) : item.result.length > 0 ? (
|
||||
<FilterableValueLink name="status" value="success">
|
||||
<SimpleBadge title={t("pages.formulas.logs.status.success")} color={Colors.GREEN} />
|
||||
</FilterableValueLink>
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "result",
|
||||
title: t("pages.formulas.logs.columns.result"),
|
||||
value: (item) => <div>{item.result}</div>,
|
||||
},
|
||||
{
|
||||
name: "originalTrigger",
|
||||
title: t("pages.formulas.logs.columns.originalTrigger"),
|
||||
value: (item) => (
|
||||
<FilterableValueLink name="originalTrigger" value={item.originalTrigger ?? ""}>
|
||||
{getFormulaLogTriggerLabel(t, item.originalTrigger)}
|
||||
</FilterableValueLink>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "triggeredBy",
|
||||
title: t("pages.formulas.logs.columns.triggeredBy"),
|
||||
value: (item) => (
|
||||
<FilterableValueLink name="triggeredBy" value={item.triggeredBy}>
|
||||
{getFormulaLogTriggerLabel(t, item.triggeredBy)}
|
||||
</FilterableValueLink>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "expression",
|
||||
title: t("pages.formulas.logs.columns.expression"),
|
||||
value: (item) => <div>{item.expression}</div>,
|
||||
},
|
||||
{
|
||||
name: "components",
|
||||
title: t("pages.formulas.logs.columns.components"),
|
||||
value: (item) => (
|
||||
<ShowPayloadModalButton
|
||||
title={t("pages.formulas.logs.columns.components")}
|
||||
description={t("pages.formulas.logs.componentsCount", { count: item.components.length })}
|
||||
payload={JSON.stringify(
|
||||
{
|
||||
components: item.components
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((f) => ({ order: f.order ?? undefined, type: f.type, value: f.value, rowId: f.rowId ?? undefined })),
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "error",
|
||||
title: t("pages.formulas.logs.columns.error"),
|
||||
value: (item) => <div className="text-red-500">{item.error}</div>,
|
||||
},
|
||||
{
|
||||
name: "speed",
|
||||
title: t("pages.formulas.logs.columns.speed"),
|
||||
value: (item) => <SpeedBadge duration={item.duration} />,
|
||||
},
|
||||
{
|
||||
name: "duration",
|
||||
title: t("pages.formulas.logs.columns.duration"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
{formatters.number(item.duration, {
|
||||
style: "unit",
|
||||
unit: "millisecond",
|
||||
unitDisplay: "short",
|
||||
minimumFractionDigits: 3,
|
||||
maximumFractionDigits: 3,
|
||||
})}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "usedRows",
|
||||
title: t("pages.formulas.logs.columns.usedRows"),
|
||||
value: (item) => (
|
||||
<div className="flex flex-col">
|
||||
{item.components
|
||||
.filter((f) => f.rowId)
|
||||
.filter((f, index, self) => self.findIndex((t) => t.rowId === f.rowId) === index)
|
||||
.map((f) => (
|
||||
<FilterableValueLink key={f.id} name="hasRowId" value={f.rowId ?? ""} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "rowValueId",
|
||||
title: t("pages.formulas.logs.columns.rowValue"),
|
||||
value: (item) => <FilterableValueLink name="rowValueId" value={item.rowValueId ?? ""} />,
|
||||
},
|
||||
{
|
||||
name: "tenant",
|
||||
title: t("models.tenant.object"),
|
||||
value: (item) => <div>{item.tenant?.name}</div>,
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
title: t("models.user.object"),
|
||||
value: (item) => <div>{item.user?.email}</div>,
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.dateTime(item.createdAt, { timeStyle: "medium" }),
|
||||
formattedValue: (item) => (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{item.createdAt && <span>{formatters.dateTime(item.createdAt, { timeStyle: "medium" })}</span>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useActionData, useNavigate, useNavigation, useOutlet, useParams, useSubmit } from "react-router";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { FormEvent, useEffect, useState, Fragment } from "react";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import { getAllFormulas, getFormula } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { FormulaComponentDto, FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import FormulaService from "~/modules/formulas/services/.server/FormulaService";
|
||||
import { FormulaVariableValueDto } from "~/modules/formulas/dtos/FormulaVariableValueDto";
|
||||
import FormulaHelpers from "~/modules/formulas/utils/FormulaHelpers";
|
||||
import InfoBanner from "~/components/ui/banners/InfoBanner";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import FormulaComponentBadge from "~/modules/formulas/components/FormulaComponentBadge";
|
||||
import { countLogs } from "~/modules/formulas/db/formulaLogs.db.server";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import FormulaDefaultService from "~/modules/formulas/services/.server/FormulaDefaultService";
|
||||
import SuccessBanner from "~/components/ui/banners/SuccessBanner";
|
||||
import ExperimentIconFilled from "~/components/ui/icons/tests/ExperimentIconFilled";
|
||||
import { defaultFormulas } from "~/modules/formulas/utils/DefaultFormulas";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: FormulaDto[];
|
||||
allEntities: EntityWithDetails[];
|
||||
logs: { formulaId: string; count: number }[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.formulas.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const items = await getAllFormulas();
|
||||
const logs = await countLogs(items.map((item) => item.id ?? ""));
|
||||
const allEntities = await getAllEntities({ tenantId });
|
||||
const data: LoaderData = {
|
||||
title: t("pages.formulas.metaTitle", { appName: process.env.APP_NAME }),
|
||||
items: items.map((item) => FormulaHelpers.getFormulaDto(item)),
|
||||
logs,
|
||||
allEntities,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const allEntities = await getAllEntities({ tenantId });
|
||||
|
||||
if (action === "calculate") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
|
||||
const formula = await getFormula(id);
|
||||
if (!formula) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 400 });
|
||||
}
|
||||
|
||||
const variables: FormulaVariableValueDto[] = form.getAll("variables[]").map((variable) => JSON.parse(variable.toString()));
|
||||
try {
|
||||
const result = await FormulaService.calculate({
|
||||
formula,
|
||||
variables,
|
||||
allEntities,
|
||||
session: {
|
||||
userId: userInfo.userId,
|
||||
tenantId,
|
||||
},
|
||||
originalTrigger: "",
|
||||
triggeredBy: "TEST",
|
||||
t,
|
||||
});
|
||||
return Response.json({ success: result });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
} else if (action === "createDefault") {
|
||||
await verifyUserHasPermission(request, "admin.formulas.create");
|
||||
const name = form.get("name")?.toString();
|
||||
const createdDefault = await FormulaDefaultService.createDefault(name);
|
||||
return Response.json({ createdDefault });
|
||||
} 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 navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
const params = useParams();
|
||||
|
||||
const [executingFormula, setExecutingFormula] = useState<FormulaDto | undefined>(undefined);
|
||||
|
||||
function onExecute(item: FormulaDto, variables: FormulaVariableValueDto[]) {
|
||||
setExecutingFormula(undefined);
|
||||
|
||||
const form = new FormData();
|
||||
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "calculate");
|
||||
form.set("id", item.id?.toString() ?? "");
|
||||
variables.forEach((variable) => {
|
||||
form.append("variables[]", JSON.stringify(variable));
|
||||
});
|
||||
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function onCreateDefault(name: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "createDefault");
|
||||
form.set("name", name);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function missingDefaults() {
|
||||
const items = defaultFormulas();
|
||||
const missing: FormulaDto[] = [];
|
||||
items.forEach((item) => {
|
||||
if (data.items.some((formula) => formula.name === item.name)) {
|
||||
return;
|
||||
}
|
||||
missing.push(item);
|
||||
});
|
||||
|
||||
let hasOneNotInDefault = data.items.some((item) => !items.some((formula) => formula.name === item.name));
|
||||
return hasOneNotInDefault ? [] : missing;
|
||||
}
|
||||
|
||||
function getLogsCount(item: FormulaDto) {
|
||||
return data.logs.find((log) => log.formulaId === item.id)?.count ?? 0;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-3 px-4 py-2 pb-6 sm:px-6 sm:pt-3 lg:px-8 xl:max-w-full">
|
||||
<div className="">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("pages.formulas.plural")}</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonSecondary to="logs">
|
||||
<span>{t("pages.formulas.logs.breadcrumb")}</span>
|
||||
</ButtonSecondary>
|
||||
<ButtonPrimary to="new">
|
||||
<span>{t("shared.new")}</span>
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{missingDefaults().length > 0 && (
|
||||
<InfoBanner title={t("pages.formulas.sampleFormulas")}>
|
||||
<div className="flex flex-wrap">
|
||||
{missingDefaults().map((item) => {
|
||||
return (
|
||||
<ButtonSecondary
|
||||
className="m-0.5"
|
||||
key={item.name}
|
||||
disabled={navigation.state === "submitting" && navigation.formData?.get("name") === item.name.toString()}
|
||||
onClick={() => onCreateDefault(item.name)}
|
||||
>
|
||||
{navigation.state === "submitting" && navigation.formData?.get("name") === item.name.toString() ? (
|
||||
<span>{t("pages.formulas.creating")}</span>
|
||||
) : (
|
||||
<span>{item.name}</span>
|
||||
)}
|
||||
</ButtonSecondary>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</InfoBanner>
|
||||
)}
|
||||
|
||||
{actionData?.success !== undefined ? (
|
||||
<SuccessBanner>
|
||||
<span className="font-bold">{t("pages.formulas.resultLabel")}</span> {actionData.success}
|
||||
</SuccessBanner>
|
||||
) : (
|
||||
actionData?.error !== undefined && <ErrorBanner title={t("shared.error")}>{actionData.error}</ErrorBanner>
|
||||
)}
|
||||
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, i) => `${i.id}`,
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "actions",
|
||||
title: "",
|
||||
value: (i) => {
|
||||
return (
|
||||
<div>
|
||||
<LoadingButton
|
||||
isLoading={navigation.state === "submitting" && !!navigation.formData?.get("id") && navigation.formData?.get("id") === i.id?.toString()}
|
||||
type="button"
|
||||
disabled={navigation.state !== "idle"}
|
||||
onClick={() => setExecutingFormula(i)}
|
||||
>
|
||||
<ExperimentIconFilled className="h-3 w-3" />
|
||||
</LoadingButton>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "formula",
|
||||
title: t("pages.formulas.object"),
|
||||
value: (i) => (
|
||||
<div className="flex max-w-xs flex-col truncate">
|
||||
<div className="truncate text-base font-bold">
|
||||
{i.name} <span className="text-muted-foreground text-sm font-normal">({t(`pages.formulas.resultAs.${i.resultAs}`)})</span>
|
||||
</div>
|
||||
<div className="text-muted-foreground truncate text-sm">{i.description}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "calculationTrigger",
|
||||
title: t("pages.formulas.columns.trigger"),
|
||||
value: (i) => t(`pages.formulas.calculationTriggers.${i.calculationTrigger}`),
|
||||
},
|
||||
{
|
||||
name: "components",
|
||||
title: t("pages.formulas.components.title"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-wrap">
|
||||
{i.components.map((item, idx) => {
|
||||
return (
|
||||
<span key={idx} className="m-0.5">
|
||||
<FormulaComponentBadge item={item} />
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
),
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "withLogs",
|
||||
title: t("pages.formulas.columns.logging"),
|
||||
value: (i) => <div>{i.withLogs ? <CheckIcon className="h-4 w-4 text-green-500" /> : <XIcon className="text-muted-foreground h-4 w-4" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "calculations",
|
||||
title: t("pages.formulas.columns.calculations"),
|
||||
value: (i) => (
|
||||
<Link to={adminPath(`entities/formulas/logs?formulaId=${i.id}`, { mode: "host-aware" })} className="text-muted-foreground text-sm hover:text-blue-700 hover:underline">
|
||||
{t("pages.formulas.calculationsCount", { count: getLogsCount(i) })}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "inProperties",
|
||||
title: t("pages.formulas.columns.inProperties"),
|
||||
value: (i) => <div className="text-muted-foreground text-sm">{i.inProperties?.map((f) => `${f.entity.name}.${f.name}`).join(", ")}</div>,
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (i) => <DateCell date={i.createdAt ?? null} />,
|
||||
className: "hidden 2xl:table-cell",
|
||||
},
|
||||
]}
|
||||
noRecords={
|
||||
<div className="p-12 text-center">
|
||||
<h3 className="text-foreground mt-1 text-sm font-medium">{t("pages.formulas.noFormulasHeading")}</h3>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("pages.formulas.noFormulasDescription")}</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<ExecuteModal
|
||||
item={executingFormula}
|
||||
open={executingFormula !== undefined}
|
||||
onClose={() => setExecutingFormula(undefined)}
|
||||
onCreate={({ item, variables }) => onExecute(item, variables)}
|
||||
allEntities={data.allEntities}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={t("pages.formulas.object")}
|
||||
description={params.id ? t("pages.formulas.edit") : t("pages.formulas.create")}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(adminPath("entities/formulas", { mode: "host-aware" }));
|
||||
}}
|
||||
className="sm:max-w-2xl"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
{outlet}
|
||||
</SlideOverWideEmpty>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ExecuteModal({
|
||||
item,
|
||||
open,
|
||||
onClose,
|
||||
onCreate,
|
||||
allEntities,
|
||||
}: {
|
||||
item?: FormulaDto;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCreate: ({ item, variables }: { item: FormulaDto; variables: FormulaVariableValueDto[] }) => void;
|
||||
allEntities: EntityWithDetails[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [formula, setFormula] = useState<FormulaDto | undefined>(item);
|
||||
const [variablesValues, setVariablesValues] = useState<FormulaVariableValueDto[]>([]);
|
||||
|
||||
const [result] = useState<string>();
|
||||
const [resultState] = useState<"error" | "success">();
|
||||
|
||||
useEffect(() => {
|
||||
setFormula(item);
|
||||
setVariablesValues([]);
|
||||
}, [formula, item]);
|
||||
|
||||
useEffect(() => {
|
||||
if (formula) {
|
||||
// FormulaService.calculate({
|
||||
// allEntities,
|
||||
// formula: formula as FormulaWithDetails,
|
||||
// variables: variablesValues,
|
||||
// session: { userId: undefined, tenantId: null },
|
||||
// originalTrigger: "",
|
||||
// triggeredBy: "",
|
||||
// isDebugging: true,
|
||||
// t,
|
||||
// })
|
||||
// .then((r) => {
|
||||
// setResultState("success");
|
||||
// setResult(r?.toString() ?? "null");
|
||||
// })
|
||||
// .catch((e) => {
|
||||
// setResultState("error");
|
||||
// setResult(e.message);
|
||||
// });
|
||||
}
|
||||
}, [allEntities, formula, variablesValues, t]);
|
||||
|
||||
function onChangeVariableValue(component: FormulaComponentDto, value: string) {
|
||||
if (component.type === "variable") {
|
||||
const newValues = variablesValues.filter((v) => v.plain?.variable !== component.value);
|
||||
newValues.push({ plain: { variable: component.value ?? "", textValue: value } });
|
||||
setVariablesValues(newValues);
|
||||
}
|
||||
}
|
||||
function getValue(variable: FormulaComponentDto) {
|
||||
if (variable.type === "variable") {
|
||||
return variablesValues.find((v) => v.plain?.variable === variable.value)?.plain?.textValue ?? "";
|
||||
}
|
||||
}
|
||||
function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
onCreate({ item: formula!, variables: variablesValues });
|
||||
}
|
||||
return (
|
||||
<Modal open={open} setOpen={onClose} size="md">
|
||||
<form onSubmit={handleSubmit} className="bg-background inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<div className="mt-3 sm:mt-5">
|
||||
<div className="flex items-baseline justify-between space-x-2">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("pages.formulas.testFormula")}</h3>
|
||||
<div className="text-muted-foreground text-sm font-bold italic">{formula?.resultAs ? t(`pages.formulas.resultAs.${formula.resultAs}`) : null}</div>
|
||||
</div>
|
||||
</div>
|
||||
{!formula ? (
|
||||
<></>
|
||||
) : (
|
||||
<>
|
||||
<div className="mt-4 space-y-2">
|
||||
<div className="border-border bg-secondary grid max-h-72 grid-cols-12 gap-1 overflow-x-auto rounded-md border border-dashed p-2 pb-4">
|
||||
{formula.components.map((v, idx) => {
|
||||
return (
|
||||
<Fragment key={idx}>
|
||||
{v.type === "variable" ? (
|
||||
<InputText
|
||||
className="col-span-12"
|
||||
placeholder={v.value ?? ""}
|
||||
name={v.value ?? ""}
|
||||
readOnly={!v.value}
|
||||
value={getValue(v)}
|
||||
setValue={(e) => onChangeVariableValue(v, e.toString())}
|
||||
/>
|
||||
) : v.type === "operator" ? (
|
||||
<InputText
|
||||
className="col-span-12"
|
||||
name={v.value}
|
||||
disabled={true}
|
||||
defaultValue={
|
||||
`${FormulaHelpers.getOperatorSymbol(v.value)}`
|
||||
// `${v.operator} (${FormulaHelpers.getOperatorSymbol(v.operator)})`
|
||||
}
|
||||
/>
|
||||
) : v.type == "parenthesis" ? (
|
||||
<InputText className="col-span-12" readOnly={true} defaultValue={v.value} />
|
||||
) : v.type === "value" ? (
|
||||
<InputText className="col-span-12" readOnly={true} defaultValue={v.value} />
|
||||
) : null}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 w-full sm:mt-6">
|
||||
<InputText
|
||||
name="result"
|
||||
title={t("pages.formulas.test.result")}
|
||||
placeholder={t("pages.formulas.test.waitingForVariables")}
|
||||
readOnly={true}
|
||||
defaultValue={result}
|
||||
isError={resultState === "error"}
|
||||
isSuccess={resultState === "success"}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useSubmit } from "react-router";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import FormulaForm from "~/modules/formulas/components/FormulaForm";
|
||||
import { deleteFormula, getFormula, updateFormula } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import FormulaHelpers from "~/modules/formulas/utils/FormulaHelpers";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
item: FormulaDto;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.formulas.update");
|
||||
const item = await getFormula(params.id!);
|
||||
if (!item) {
|
||||
throw redirect(adminPath("entities/formulas", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item: FormulaHelpers.getFormulaDto(item),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.formulas.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
const item = await getFormula(params.id!);
|
||||
if (!item) {
|
||||
return redirect(adminPath("entities/formulas", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const resultAs = form.get("resultAs")?.toString();
|
||||
const calculationTrigger = form.get("calculationTrigger")?.toString();
|
||||
const withLogs = ["true", "on"].includes(form.get("withLogs")?.toString() ?? "false");
|
||||
|
||||
const components: { order: number; type: string; value: string }[] = form.getAll("components[]").map((f) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!name || !resultAs || !calculationTrigger) {
|
||||
return Response.json({ error: t("pages.formulas.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
if (components.length === 0) {
|
||||
return Response.json({ error: t("pages.formulas.errors.missingComponents") }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await updateFormula(item.id, {
|
||||
name,
|
||||
description,
|
||||
resultAs,
|
||||
calculationTrigger,
|
||||
withLogs,
|
||||
components,
|
||||
});
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e.message);
|
||||
}
|
||||
|
||||
return redirect(adminPath("entities/formulas", { mode: "host-aware" }));
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.formulas.delete");
|
||||
await deleteFormula(params.id!);
|
||||
return redirect(adminPath("entities/formulas", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
function onDelete() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<FormulaForm item={data.item} onDelete={onDelete} />
|
||||
|
||||
<ActionResultModal actionData={actionData ?? undefined} showSuccess={false} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData } from "react-router";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import FormulaForm from "~/modules/formulas/components/FormulaForm";
|
||||
import { createFormula } from "~/modules/formulas/db/formulas.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.formulas.create");
|
||||
return Response.json({});
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.formulas.create");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "new") {
|
||||
const name = form.get("name")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const resultAs = form.get("resultAs")?.toString();
|
||||
const calculationTrigger = form.get("calculationTrigger")?.toString();
|
||||
const withLogs = ["true", "on"].includes(form.get("withLogs")?.toString() ?? "false");
|
||||
|
||||
const components: { order: number; type: string; value: string }[] = form.getAll("components[]").map((f) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!name || !resultAs || !calculationTrigger) {
|
||||
return Response.json({ error: t("pages.formulas.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
if (components.length === 0) {
|
||||
return Response.json({ error: t("pages.formulas.errors.missingComponents") }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await createFormula({
|
||||
name,
|
||||
description,
|
||||
resultAs,
|
||||
calculationTrigger,
|
||||
components,
|
||||
withLogs,
|
||||
});
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e.message);
|
||||
}
|
||||
|
||||
throw redirect(adminPath("entities/formulas", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<FormulaForm item={undefined} />
|
||||
|
||||
<ActionResultModal actionData={actionData ?? undefined} showSuccess={false} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { deleteEntityGroup, EntityGroupWithDetails, getAllEntityGroups, updateEntityGroup } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import OrderListButtons from "~/components/ui/sort/OrderListButtons";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: EntityGroupWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const items = await getAllEntityGroups();
|
||||
const data: LoaderData = {
|
||||
title: t("models.entityGroup.metaTitle", { appName: process.env.APP_NAME }),
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "set-orders") {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
items.map(async ({ id, order }) => {
|
||||
await updateEntityGroup(id, { order: Number(order) });
|
||||
})
|
||||
);
|
||||
return Response.json({ updated: true });
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
await deleteEntityGroup(id);
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
const params = useParams();
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-3 px-4 py-2 pb-6 sm:px-6 sm:pt-3 lg:px-8 xl:max-w-full">
|
||||
<div className="">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("models.entityGroup.plural")}</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonPrimary to="new" disabled={!getUserHasPermission(appOrAdminData, "admin.entities.create")}>
|
||||
{t("shared.new")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
headers={[
|
||||
{
|
||||
name: "order",
|
||||
title: t("models.entity.order"),
|
||||
value: (_item, idx) => (
|
||||
<div>
|
||||
<OrderListButtons index={idx} items={data.items.map((f) => ({ ...f, order: f.order ?? 0 }))} editable={true} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "group",
|
||||
title: t("models.entityGroup.object"),
|
||||
value: (item) => (
|
||||
<Link to={item.id} className="hover:underline">
|
||||
<span className="font-medium">{t(item.title)}</span> <span className="text-muted-foreground text-xs italic">({item.slug})</span>
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "section",
|
||||
title: t("models.entityGroup.section"),
|
||||
value: (item) => <div>{item.section}</div>,
|
||||
},
|
||||
{
|
||||
name: "collapsible",
|
||||
title: t("models.entityGroup.collapsible"),
|
||||
value: (i) => (i.collapsible ? <CheckIcon className="h-4 w-4 text-teal-500" /> : <XIcon className="h-4 w-4 text-gray-300" />),
|
||||
},
|
||||
{
|
||||
name: "entities",
|
||||
title: t("models.entity.plural"),
|
||||
className: "w-full",
|
||||
value: (i) => (
|
||||
<ul className="list-disc">
|
||||
{i.entities.map((f) => (
|
||||
<li key={f.id}>
|
||||
<div>
|
||||
{t(f.entity.title)} {f.allView && <span className="text-muted-foreground text-xs italic">({f.allView.title})</span>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: "",
|
||||
value: (item) => (
|
||||
<Link to={item.id} className="hover:underline">
|
||||
{t("shared.edit")}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("models.entityGroup.edit") : t("models.entityGroup.new")}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-sm"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { EntityGroupForm } from "~/components/entities/EntityGroupForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityGroupWithDetails, deleteEntityGroup, getAllEntityGroups, getEntityGroup, updateEntityGroup } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { EntityViewWithTenantAndUser, getAllEntityViews } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { isReservedTenantChildRouteSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
|
||||
|
||||
type LoaderData = {
|
||||
item: EntityGroupWithDetails;
|
||||
allEntities: EntityWithDetails[];
|
||||
systemViews: EntityViewWithTenantAndUser[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const item = await getEntityGroup(params.id!);
|
||||
if (!item) {
|
||||
return redirect(adminPath("entities/groups", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
allEntities: await getAllEntities({ tenantId: null }),
|
||||
systemViews: (await getAllEntityViews({ type: "system" })).items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
const item = await getEntityGroup(params.id!);
|
||||
if (!item) {
|
||||
return redirect(adminPath("entities/groups", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const title = form.get("title")?.toString();
|
||||
const icon = form.get("icon")?.toString();
|
||||
const collapsible = Boolean(form.get("collapsible"));
|
||||
const section = form.get("section")?.toString() ?? null;
|
||||
const entities: { entityId: string; allViewId: string | null }[] = form.getAll("entities[]").map((f) => JSON.parse(f.toString()));
|
||||
|
||||
const allGroups = await getAllEntityGroups();
|
||||
const existing = allGroups.find((f) => f.slug.trim() === slug?.trim() && f.id !== params.id);
|
||||
if (isReservedTenantChildRouteSlug(slug)) {
|
||||
return Response.json({ error: t("admin.entities.groups.errors.slugConflictsWithWorkspaceRoute") }, { status: 400 });
|
||||
}
|
||||
if (slug && existing) {
|
||||
return Response.json({ error: t("admin.entities.groups.errors.slugAlreadyExists") }, { status: 400 });
|
||||
}
|
||||
await updateEntityGroup(params.id!, {
|
||||
slug,
|
||||
title,
|
||||
icon,
|
||||
collapsible,
|
||||
section,
|
||||
entities,
|
||||
});
|
||||
return redirect(adminPath("entities/groups", { mode: "host-aware" }));
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.entities.delete");
|
||||
await deleteEntityGroup(params.id!);
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<EntityGroupForm item={data.item} allEntities={data.allEntities} systemViews={data.systemViews} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
function readRouteSource(path: string) {
|
||||
return readFileSync(new URL(path, import.meta.url), "utf8");
|
||||
}
|
||||
|
||||
describe("entity group route slug boundary", () => {
|
||||
it("rejects reserved tenant child route slugs before creating groups", () => {
|
||||
const source = readRouteSource("new.tsx");
|
||||
|
||||
expect(source).toContain("isReservedTenantChildRouteSlug(slug)");
|
||||
expect(source.indexOf("isReservedTenantChildRouteSlug(slug)")).toBeLessThan(source.indexOf("await createEntityGroup"));
|
||||
});
|
||||
|
||||
it("rejects reserved tenant child route slugs before updating groups", () => {
|
||||
const source = readRouteSource("$id.tsx");
|
||||
|
||||
expect(source).toContain("isReservedTenantChildRouteSlug(slug)");
|
||||
expect(source.indexOf("isReservedTenantChildRouteSlug(slug)")).toBeLessThan(source.indexOf("await updateEntityGroup"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { EntityGroupForm } from "~/components/entities/EntityGroupForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { createEntityGroup, getAllEntityGroups } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { EntityViewWithTenantAndUser, getAllEntityViews } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { isReservedTenantChildRouteSlug, normalizeTenantSlug } from "~/utils/services/tenantService";
|
||||
|
||||
type LoaderData = {
|
||||
allEntities: EntityWithDetails[];
|
||||
systemViews: EntityViewWithTenantAndUser[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.create");
|
||||
const data: LoaderData = {
|
||||
allEntities: await getAllEntities({ tenantId: null }),
|
||||
systemViews: (await getAllEntityViews({ type: "system" })).items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "create") {
|
||||
await verifyUserHasPermission(request, "admin.entities.create");
|
||||
const slug = normalizeTenantSlug(form.get("slug")?.toString() ?? "");
|
||||
const title = form.get("title")?.toString().trim() ?? "";
|
||||
const icon = form.get("icon")?.toString().trim() ?? "";
|
||||
const collapsible = Boolean(form.get("collapsible"));
|
||||
const section = form.get("section")?.toString() ?? null;
|
||||
const entities: { entityId: string; allViewId: string | null }[] = form.getAll("entities[]").map((f) => JSON.parse(f.toString()));
|
||||
const allGroups = await getAllEntityGroups();
|
||||
let maxOrder = 0;
|
||||
if (allGroups.length > 0) {
|
||||
maxOrder = Math.max(...allGroups.map((f) => f.order ?? 0));
|
||||
}
|
||||
const existing = allGroups.find((f) => f.slug.trim() === slug.trim());
|
||||
if (isReservedTenantChildRouteSlug(slug)) {
|
||||
return Response.json({ error: t("admin.entities.groups.errors.slugConflictsWithWorkspaceRoute") }, { status: 400 });
|
||||
}
|
||||
if (existing) {
|
||||
return Response.json({ error: t("admin.entities.groups.errors.slugAlreadyExists") }, { status: 400 });
|
||||
}
|
||||
await createEntityGroup({
|
||||
order: maxOrder + 1,
|
||||
slug,
|
||||
title,
|
||||
icon,
|
||||
collapsible,
|
||||
section,
|
||||
entities,
|
||||
});
|
||||
return redirect(adminPath("entities/groups", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<EntityGroupForm item={undefined} allEntities={data.allEntities} systemViews={data.systemViews} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import EntitiesTable from "~/components/entities/EntitiesTable";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import InputSearch from "~/components/ui/input/InputSearch";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import { EntityWithCount, getAllEntitiesWithRowCount, updateEntity } from "~/utils/db/entities/entities.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { EntityRelationshipWithDetails, getAllEntityRelationships } from "~/utils/db/entities/entityRelationships.db.server";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import DownloadIcon from "~/components/ui/icons/DownloadIcon";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: EntityWithCount[];
|
||||
relationships: EntityRelationshipWithDetails[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const items = await getAllEntitiesWithRowCount({ tenantId });
|
||||
const relationships = await getAllEntityRelationships();
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("models.entity.plural")} | ${process.env.APP_NAME}`,
|
||||
items,
|
||||
relationships,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
|
||||
if (action === "set-orders") {
|
||||
const items: { id: string; order: number }[] = form.getAll("orders[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
items.map(async ({ id, order }) => {
|
||||
await updateEntity(id, { order: Number(order) });
|
||||
})
|
||||
);
|
||||
return Response.json({ updated: true });
|
||||
}
|
||||
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 formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const adminData = useAdminData();
|
||||
|
||||
const [selected, setSelected] = useState<EntityWithCount[]>([]);
|
||||
const [searchInput, setSearchInput] = useState("");
|
||||
|
||||
const filteredItems = () => {
|
||||
if (!data.items) {
|
||||
return [];
|
||||
}
|
||||
const query = searchInput.toUpperCase();
|
||||
return data.items.filter((f) => {
|
||||
const createdAtSearch = [formatters.dateTime(f.createdAt, { timeStyle: "medium" }), f.createdAt.toISOString()].join(" ").toUpperCase();
|
||||
return (
|
||||
createdAtSearch.includes(query) ||
|
||||
f.slug?.toString().toUpperCase().includes(query) ||
|
||||
f.title?.toString().toUpperCase().includes(query) ||
|
||||
f.titlePlural?.toString().toUpperCase().includes(query) ||
|
||||
t(f.title)?.toString().toUpperCase().includes(query) ||
|
||||
t(f.titlePlural)?.toString().toUpperCase().includes(query) ||
|
||||
f.properties.find(
|
||||
(x) =>
|
||||
x.name?.toString().toUpperCase().includes(query) ||
|
||||
x.title?.toString().toUpperCase().includes(query) ||
|
||||
t(x.title)?.toString().toUpperCase().includes(query)
|
||||
)
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
function exportEntities() {
|
||||
let items = selected.length > 0 ? selected : filteredItems();
|
||||
const templateEntities = EntityHelper.exportEntitiesToTemplate(items, data.relationships);
|
||||
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(templateEntities, null, "\t"));
|
||||
const downloadAnchorNode = document.createElement("a");
|
||||
downloadAnchorNode.setAttribute("href", dataStr);
|
||||
downloadAnchorNode.setAttribute("download", "entities.json");
|
||||
document.body.appendChild(downloadAnchorNode); // required for firefox
|
||||
downloadAnchorNode.click();
|
||||
downloadAnchorNode.remove();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-3 px-4 py-2 pb-6 sm:px-6 sm:pt-3 lg:px-8 xl:max-w-full">
|
||||
<div className="md:border-border md:border-b md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("models.entity.plural")}</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<InputSearch className="hidden sm:block" value={searchInput} setValue={setSearchInput} />
|
||||
<ButtonSecondary disabled={data.items.length === 0} onClick={exportEntities} className="text-muted-foreground">
|
||||
<DownloadIcon className="h-5 w-5" />
|
||||
</ButtonSecondary>
|
||||
<ButtonPrimary disabled={!getUserHasPermission(adminData, "admin.entities.create")} to={adminPath("entities/new", { mode: "host-aware" })}>
|
||||
<span>{t("shared.new")}</span>
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<EntitiesTable items={filteredItems()} selected={selected} onSelected={(e) => setSelected(e)} />
|
||||
|
||||
{/* <div className="mt-2">
|
||||
<h3 className="text-lg font-medium leading-6 text-foreground">{t("models.relationship.plural")}</h3>
|
||||
<EntityRelationshipsTable items={data.relationships} editable={false} />
|
||||
</div> */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import LogsTable from "~/components/app/events/LogsTable";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { getAllRowLogs, LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
|
||||
type LoaderData = {
|
||||
items: LogWithDetails[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const entities = await getAllEntities({ tenantId });
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "entityId",
|
||||
title: t("models.entity.object"),
|
||||
options: entities.map((i) => {
|
||||
return { value: i.id, name: i.name };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
options: [
|
||||
{ name: t("shared.admin"), value: "null" },
|
||||
...(await adminGetAllTenantsIdsAndNames()).map((i) => {
|
||||
return { value: i.id, name: i.name };
|
||||
}),
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "rowId",
|
||||
title: t("models.row.object"),
|
||||
},
|
||||
];
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const filterTenantId = filters.properties.find((f) => f.name === "tenantId")?.value;
|
||||
const { items, pagination } = await getAllRowLogs({
|
||||
entityId: filters.properties.find((f) => f.name === "entityId")?.value ?? undefined,
|
||||
rowId: filters.properties.find((f) => f.name === "rowId")?.value ?? undefined,
|
||||
tenantId: filterTenantId === "null" ? null : filterTenantId ?? undefined,
|
||||
pagination: {
|
||||
page: currentPagination.page,
|
||||
pageSize: currentPagination.pageSize,
|
||||
},
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function EditEntityIndexRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-3 px-4 py-2 pb-6 sm:px-6 sm:pt-3 lg:px-8 xl:max-w-full">
|
||||
<div className="md:border-border md:border-b md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("models.log.plural")}</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<InputFilters withSearch={false} filters={data.filterableProperties} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LogsTable withTenant={true} items={data.items} pagination={data.pagination} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const routeRoot = path.resolve(process.cwd(), "apps/web/app/routes/admin/entities");
|
||||
const helperPath = path.resolve(process.cwd(), "apps/web/app/utils/helpers/NoCodeViewsHelper.tsx");
|
||||
const enTranslationsPath = path.resolve(process.cwd(), "apps/web/public/locales/en/translations.json");
|
||||
const deTranslationsPath = path.resolve(process.cwd(), "apps/web/public/locales/de/translations.json");
|
||||
|
||||
function readRoute(relativePath: string) {
|
||||
return fs.readFileSync(path.join(routeRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("admin entity no-code routes i18n", () => {
|
||||
it("uses semantic translation keys for shell and summary labels", () => {
|
||||
const sources = [readRoute("no-code.tsx"), readRoute("no-code/index.tsx"), readRoute("no-code/stats/count.tsx"), fs.readFileSync(helperPath, "utf8")].join("\n");
|
||||
|
||||
expect(sources).toContain("models.entity.noCode.title");
|
||||
expect(sources).toContain("models.entity.noCode.menu");
|
||||
expect(sources).toContain("models.entity.noCode.previews.blocks.crud.title");
|
||||
expect(sources).toContain("models.entity.noCode.previews.entityRoutes.views.allInOne.name");
|
||||
expect(sources).toContain("models.entity.noCode.previews.errors.noRows");
|
||||
expect(sources).toContain("models.entity.actions.create");
|
||||
expect(sources).toContain("shared.viewAll");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
expect(sources).not.toContain('name: "Count"');
|
||||
expect(sources).not.toContain('error: "No rows"');
|
||||
expect(sources).not.toContain('view.error = "not autogenerated"');
|
||||
});
|
||||
|
||||
it("uses user-facing wording for unavailable generated previews", () => {
|
||||
const en = JSON.parse(fs.readFileSync(enTranslationsPath, "utf8"));
|
||||
const de = JSON.parse(fs.readFileSync(deTranslationsPath, "utf8"));
|
||||
|
||||
expect(en.models.entity.noCode.previews.errors.notAutogenerated).toBe("Preview unavailable for this entity");
|
||||
expect(de.models.entity.noCode.previews.errors.notAutogenerated).toBe("Vorschau für diese Entität nicht verfügbar");
|
||||
expect(en.models.entity.noCode.previews.errors.notAutogenerated.toLowerCase()).not.toContain("autogenerated");
|
||||
expect(de.models.entity.noCode.previews.errors.notAutogenerated.toLowerCase()).not.toContain("automatisch generiert");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Outlet } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.entity.noCode.title")}
|
||||
menu={[{ title: t("models.entity.noCode.menu"), routePath: adminPath("entities/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 />;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { Fragment, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import NoCodeViewsHelper, { NoCodeEntityViewsDto } from "~/utils/helpers/NoCodeViewsHelper";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
entities: EntityWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const data: LoaderData = {
|
||||
entities: await getAllEntities({ tenantId: null }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [previews] = useState<NoCodeEntityViewsDto[]>(NoCodeViewsHelper.getBlockPreviews({ t, entities: data.entities }));
|
||||
return (
|
||||
<div className="space-y-4 overflow-y-auto p-4 sm:px-8 sm:py-7">
|
||||
{data.entities.length === 0 ? (
|
||||
<Link
|
||||
to={adminPath("entities/new", { mode: "host-aware" })}
|
||||
className="border-border focus:bg-background hover:border-border relative flex w-full flex-col justify-center space-y-2 rounded-lg border-2 border-dashed p-6 text-center focus:border-2 focus:border-gray-600 focus:outline-hidden"
|
||||
>
|
||||
<div className="text-foreground block text-sm font-medium">{t("models.entity.actions.create")}</div>
|
||||
</Link>
|
||||
) : (
|
||||
<>
|
||||
{previews.map((item) => {
|
||||
return (
|
||||
<div key={item.title} className="space-y-2">
|
||||
<div>
|
||||
<div className="text-foreground text-lg font-bold">{item.title}</div>
|
||||
<div className="text-muted-foreground text-sm">{item.description}</div>
|
||||
</div>
|
||||
<div className="grid gap-2 md:grid-cols-2 lg:grid-cols-3">
|
||||
{item.views.map((view) => (
|
||||
<Fragment key={view.name}>
|
||||
{!view.error ? (
|
||||
<Link
|
||||
to={`${view.href}`}
|
||||
reloadDocument={view.reloadDocument}
|
||||
className="border-border focus:bg-background hover:border-border relative flex w-full flex-col justify-center space-y-2 rounded-lg border-2 border-dashed p-3 text-center focus:border-2 focus:border-gray-600 focus:outline-hidden"
|
||||
>
|
||||
{view.icon}
|
||||
<div className="text-foreground block text-sm font-medium">
|
||||
{view.name} {view.error && <span className="text-xs lowercase text-red-500">({view.error})</span>}
|
||||
</div>
|
||||
<div className="text-muted-foreground block text-xs">{view.description}</div>
|
||||
{view.underConstruction && <div className="text-xs lowercase text-orange-500">({t("shared.underConstruction")})</div>}
|
||||
</Link>
|
||||
) : (
|
||||
<div className="relative flex w-full flex-col justify-center space-y-2 rounded-lg border-2 border-dashed border-red-300 bg-red-50 p-3 text-center">
|
||||
{view.icon}
|
||||
<div className="text-foreground block text-sm font-medium">
|
||||
{view.name} {view.error && <span className="text-xs lowercase text-red-500">({view.error})</span>}
|
||||
{view.underConstruction && <span className="text-xs lowercase text-orange-500">({t("shared.underConstruction")})</span>}
|
||||
</div>
|
||||
<div className="text-muted-foreground block text-xs">{view.description}</div>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowTaskWithDetails } from "~/utils/db/entities/rowTasks.db.server";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
tasks: RowTaskWithDetails[];
|
||||
allEntities: EntityWithDetails[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const userInfo = await getUserInfo(request);
|
||||
|
||||
const tasks = await RowsApi.getTasks({
|
||||
assignedOrCreatedUserId: userInfo.userId,
|
||||
tenantId,
|
||||
});
|
||||
const data: LoaderData = {
|
||||
tasks,
|
||||
allEntities: await getAllEntities({ tenantId, active: true }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<div className="space-y-5 p-8">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground grow text-lg font-medium leading-6">{t("models.rowTask.plural")}</h3>
|
||||
</div>
|
||||
<TableSimple
|
||||
items={data.tasks}
|
||||
headers={[
|
||||
{
|
||||
name: "row",
|
||||
title: t("models.row.object"),
|
||||
value: (i) => <TaskRow allEntities={data.allEntities} task={i} />,
|
||||
},
|
||||
{
|
||||
name: "task",
|
||||
title: t("models.rowTask.object"),
|
||||
value: (i) => <div className="w-full">{i.title}</div>,
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "completed",
|
||||
title: t("models.rowTask.completed"),
|
||||
value: (i) => (
|
||||
<div>{i.completed ? <CheckIcon className="text-muted-foreground h-4 w-4" /> : <XIcon className="text-muted-foreground h-4 w-4" />}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.relativeDate(item.createdAt),
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
sortable: true,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
function TaskRow({ allEntities, task }: { allEntities: EntityWithDetails[]; task: RowTaskWithDetails }) {
|
||||
const { t } = useTranslation();
|
||||
const [entity] = useState(allEntities.find((f) => f.id === task.row.entityId));
|
||||
return <div>{entity && RowHelper.getTextDescription({ entity, item: task.row, t })}</div>;
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { useLoaderData, useSearchParams, useNavigation } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
enum FilterType {
|
||||
Last30Days = "last-30-days",
|
||||
Last7Days = "last-7-days",
|
||||
}
|
||||
const defaultFilter = FilterType.Last30Days;
|
||||
|
||||
function daysFromDate(date: Date, days: number) {
|
||||
return new Date(date.getTime() + days * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
type EntityCountDto = {
|
||||
entity: EntityWithDetails;
|
||||
href?: string;
|
||||
count: number;
|
||||
};
|
||||
type LoaderData = {
|
||||
summary: EntityCountDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
let entities: EntityWithDetails[] = [];
|
||||
if (tenantId) {
|
||||
entities = await getAllEntities({ tenantId, active: true, types: [DefaultEntityTypes.All, DefaultEntityTypes.AdminOnly] });
|
||||
} else {
|
||||
entities = await getAllEntities({ tenantId, active: true, types: [DefaultEntityTypes.All, DefaultEntityTypes.AppOnly] });
|
||||
}
|
||||
const userInfo = await getUserInfo(request);
|
||||
|
||||
const rowWhere: Prisma.RowWhereInput = {};
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const countFilter = searchParams.get("count") ?? defaultFilter;
|
||||
if (countFilter) {
|
||||
if (countFilter === "last-30-days") {
|
||||
rowWhere.createdAt = {
|
||||
gte: daysFromDate(new Date(), 30 * -1),
|
||||
};
|
||||
} else if (countFilter === "last-7-days") {
|
||||
rowWhere.createdAt = {
|
||||
gte: daysFromDate(new Date(), 7 * -1),
|
||||
};
|
||||
}
|
||||
}
|
||||
const summary: EntityCountDto[] = await Promise.all(
|
||||
entities.map(async (entity) => {
|
||||
return {
|
||||
entity,
|
||||
href: EntityHelper.getRoutes({ routes: EntitiesApi.getNoCodeRoutes({ request, params }), entity })?.list,
|
||||
count: await RowsApi.count({
|
||||
entity,
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
rowWhere,
|
||||
}),
|
||||
};
|
||||
})
|
||||
);
|
||||
const data: LoaderData = {
|
||||
summary,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigation = useNavigation();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
return (
|
||||
<div className="space-y-5 p-8">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground grow text-lg font-medium leading-6">{t("shared.summary")}</h3>
|
||||
<div>
|
||||
<InputSelector
|
||||
className="w-44"
|
||||
withSearch={false}
|
||||
name="count"
|
||||
value={searchParams.get("count")?.toString() ?? defaultFilter}
|
||||
options={[
|
||||
{ name: t("app.shared.periods.LAST_30_DAYS"), value: FilterType.Last30Days },
|
||||
{ name: t("app.shared.periods.LAST_7_DAYS"), value: FilterType.Last7Days },
|
||||
]}
|
||||
setValue={(value) => {
|
||||
if (value) {
|
||||
searchParams.set("count", value?.toString() ?? "");
|
||||
} else {
|
||||
searchParams.delete("count");
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<dl
|
||||
className={clsx(
|
||||
"grid grid-cols-1 gap-5",
|
||||
data.summary.length === 2 && "sm:grid-cols-2",
|
||||
data.summary.length === 3 && "sm:grid-cols-3",
|
||||
data.summary.length === 4 && "sm:grid-cols-4",
|
||||
data.summary.length === 5 && "sm:grid-cols-3",
|
||||
data.summary.length === 6 && "sm:grid-cols-3"
|
||||
)}
|
||||
>
|
||||
{data.summary.map((item, idx) => (
|
||||
<div key={idx} className="bg-background overflow-hidden rounded-lg shadow-xs">
|
||||
<div className="p-5">
|
||||
<div className="flex items-center">
|
||||
<div className="w-0 flex-1">
|
||||
<dl>
|
||||
<dt className="text-muted-foreground truncate text-sm font-medium">{t(item.entity.titlePlural)}</dt>
|
||||
<dd>
|
||||
<div className="text-foreground text-lg font-medium">
|
||||
<span>{navigation.state === "loading" ? "..." : formatters.number(item.count)}</span>
|
||||
</div>
|
||||
</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{item.href && (
|
||||
<div className="bg-secondary px-5 py-3">
|
||||
<div className="text-sm">
|
||||
<a href={item.href} className="text-theme-700 hover:text-theme-900 font-medium">
|
||||
{t("shared.viewAll")}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "relationships.tsx"), "utf8");
|
||||
|
||||
describe("admin entity relationships route", () => {
|
||||
it("does not render a raw Todo placeholder", () => {
|
||||
expect(source).not.toContain("<div>Todo</div>");
|
||||
expect(source).toContain("UnderConstruction");
|
||||
expect(source).toContain("admin.entities.relationships.title");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import UnderConstruction from "~/components/ui/misc/UnderConstruction";
|
||||
|
||||
export default function EntityRowRelationshipsRoute() {
|
||||
const { t } = useTranslation();
|
||||
return <UnderConstruction title={t("admin.entities.relationships.title")} description={t("admin.entities.relationships.description")} />;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityWithDetails, getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getRowsWithPagination } from "~/utils/helpers/.server/RowPaginationService";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import ActivityHistoryIcon from "~/components/ui/icons/entities/ActivityHistoryIcon";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
items: RowWithDetails[];
|
||||
pagination: PaginationDto;
|
||||
entities: EntityWithDetails[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const entities = await getAllEntities({ tenantId: null });
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "entity",
|
||||
title: t("models.entity.object"),
|
||||
options: entities.map((i) => {
|
||||
return {
|
||||
value: i.id,
|
||||
name: i.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
options: [
|
||||
{ name: t("shared.admin"), value: "null" },
|
||||
...(await adminGetAllTenantsIdsAndNames()).map((i) => {
|
||||
return { value: i.id, name: i.name };
|
||||
}),
|
||||
],
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const filterTenantId = filters.properties.find((f) => f.name === "tenantId")?.value;
|
||||
const { items, pagination } = await getRowsWithPagination({
|
||||
page: currentPagination.page,
|
||||
pageSize: currentPagination.pageSize,
|
||||
rowWhere: {
|
||||
entityId: filters.properties.find((f) => f.name === "entity")?.value ?? undefined,
|
||||
tenantId: filterTenantId === "null" ? null : filterTenantId ?? undefined,
|
||||
},
|
||||
});
|
||||
const data: LoaderData = {
|
||||
entities,
|
||||
items,
|
||||
pagination,
|
||||
filterableProperties,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
};
|
||||
|
||||
export default function AdminEntityRowsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
function findEntity(item: RowWithDetails) {
|
||||
return data.entities.find((e) => e.id === item.entityId);
|
||||
}
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-3 px-4 py-2 pb-6 sm:px-6 sm:pt-3 lg:px-8 xl:max-w-full">
|
||||
<div className="md:border-border md:border-b md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("models.row.plural")}</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<InputFilters withSearch={false} filters={data.filterableProperties} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TableSimple
|
||||
headers={[
|
||||
{
|
||||
name: "object",
|
||||
title: t("models.row.payload.object"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<ShowPayloadModalButton title={t("shared.details")} description={t("shared.details")} payload={JSON.stringify(item)} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "tenant",
|
||||
title: t("models.tenant.object"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
{item.tenant ? (
|
||||
<Link
|
||||
to={appPath({ tenantSlug: item.tenant.slug, mode: "host-aware" })}
|
||||
className="focus:bg-secondary/90 hover:border-border rounded-md border-b border-dashed border-transparent"
|
||||
>
|
||||
{item.tenant.name}
|
||||
</Link>
|
||||
) : (
|
||||
<div className="text-muted-foreground italic">{t("shared.admin")}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
breakpoint: "sm",
|
||||
},
|
||||
{
|
||||
name: "entity",
|
||||
title: t("models.entity.object"),
|
||||
value: (i) => t(findEntity(i)?.title ?? ""),
|
||||
},
|
||||
{
|
||||
name: "folio",
|
||||
title: t("models.row.folio"),
|
||||
value: (i) => RowHelper.getRowFolio(findEntity(i)!, i),
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("shared.description"),
|
||||
value: (i) => RowHelper.getTextDescription({ entity: findEntity(i)!, item: i, t }),
|
||||
},
|
||||
{
|
||||
name: "logs",
|
||||
title: t("models.log.plural"),
|
||||
value: (item) => (
|
||||
<Link to={adminPath("entities/logs?rowId=" + item.id, { mode: "host-aware" })}>
|
||||
<ActivityHistoryIcon className="hover:text-theme-800 text-muted-foreground h-4 w-4" />
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "createdByUser",
|
||||
title: t("shared.createdBy"),
|
||||
value: (item) => item.createdByUser?.email ?? (item.createdByApiKey ? t("models.apiKey.object") : t("shared.unknown")),
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.relativeDate(item.createdAt),
|
||||
formattedValue: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.date(item.createdAt, { dateStyle: "medium" })}</div>
|
||||
<div className="text-xs">{formatters.relativeDate(item.createdAt)}</div>
|
||||
</div>
|
||||
),
|
||||
className: "text-muted-foreground text-xs",
|
||||
breakpoint: "sm",
|
||||
sortable: true,
|
||||
},
|
||||
]}
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type LoaderData = {};
|
||||
export const loader = async ({ params }: LoaderFunctionArgs) => {
|
||||
const data: LoaderData = {};
|
||||
return data;
|
||||
};
|
||||
|
||||
type CreateTemplateType = {
|
||||
titleKey: string;
|
||||
descriptionKey: string;
|
||||
href: string;
|
||||
enterprise?: boolean;
|
||||
underConstruction?: boolean;
|
||||
};
|
||||
|
||||
const types: CreateTemplateType[] = [
|
||||
{
|
||||
titleKey: "models.entityTemplate.manual",
|
||||
descriptionKey: "models.entityTemplate.uploadJsonConfiguration",
|
||||
href: "manual",
|
||||
},
|
||||
];
|
||||
|
||||
export default function AdminEntityNoCodeRoute() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-3 px-4 py-2 pb-6 sm:px-6 sm:pt-3 lg:px-8 xl:max-w-full">
|
||||
<div className="md:border-border md:border-b md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("models.entityTemplate.plural")}</h3>
|
||||
{/* <div className="flex items-center space-x-2">
|
||||
<InputFilters withSearch={false} filters={data.filterableProperties} />
|
||||
</div> */}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2 md:grid-cols-2 lg:grid-cols-3">
|
||||
{types.map((item) => {
|
||||
return (
|
||||
<Link
|
||||
key={item.titleKey}
|
||||
to={item.href}
|
||||
className="border-border focus:bg-background hover:border-border relative flex w-full flex-col justify-center space-y-2 rounded-lg border-2 border-dashed p-3 text-center focus:border-2 focus:border-gray-600 focus:outline-hidden"
|
||||
>
|
||||
<div className="text-foreground block text-sm font-medium">
|
||||
{t(item.titleKey)} {item.enterprise && <span className="text-xs font-extrabold">({t("shared.pro")})</span>}
|
||||
</div>
|
||||
<div className="text-muted-foreground block text-xs">{t(item.descriptionKey)}</div>
|
||||
{item.underConstruction && <div className="text-muted-foreground text-xs">{t("shared.underConstruction")}</div>}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { ActionFunction, useActionData } from "react-router";
|
||||
import { Form, Link } from "react-router";
|
||||
import { useState } from "react";
|
||||
import PreviewEntitiesTemplate from "~/components/entities/templates/PreviewEntitiesTemplate";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import * as DefaultEntityTemplates from "~/modules/templates/defaultEntityTemplates";
|
||||
import { EntitiesTemplateDto } from "~/modules/templates/EntityTemplateDto";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { importEntitiesFromTemplate, validateEntitiesFromTemplate } from "~/utils/services/.server/entitiesTemplatesService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export const loader = async () => {
|
||||
return Response.json({});
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
previewTemplate?: EntitiesTemplateDto;
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
const success = (data: ActionData) => Response.json(data, { status: 200 });
|
||||
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);
|
||||
const userInfo = await getUserInfo(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "preview") {
|
||||
try {
|
||||
const previewTemplate = JSON.parse(form.get("configuration")?.toString() ?? "{}") as EntitiesTemplateDto;
|
||||
await validateEntitiesFromTemplate(previewTemplate);
|
||||
const data: ActionData = {
|
||||
previewTemplate,
|
||||
};
|
||||
return success(data);
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
}
|
||||
} else if (action === "create") {
|
||||
try {
|
||||
const template = JSON.parse(form.get("configuration")?.toString() ?? "{}") as EntitiesTemplateDto;
|
||||
const entities = await importEntitiesFromTemplate({
|
||||
template,
|
||||
createdByUserId: userInfo.userId,
|
||||
});
|
||||
return success({
|
||||
success: t("models.entityTemplate.actions.createdEntities", { entities: entities.map((e) => t(e.titlePlural)).join(", ") }),
|
||||
});
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
}
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
const defaultTemplates: { titleKey: string; template: EntitiesTemplateDto }[] = [
|
||||
{ titleKey: "models.entityTemplate.defaultTemplates.crm", template: DefaultEntityTemplates.CRM_ENTITIES_TEMPLATE },
|
||||
{ titleKey: "models.entityTemplate.defaultTemplates.tenantSettings", template: DefaultEntityTemplates.TENANT_SETTINGS_ENTITIES_TEMPLATE },
|
||||
{ titleKey: "models.entityTemplate.defaultTemplates.employee", template: DefaultEntityTemplates.EMPLOYEES_ENTITIES_TEMPLATE },
|
||||
{ titleKey: "models.entityTemplate.defaultTemplates.contracts", template: DefaultEntityTemplates.CONTRACTS_ENTITIES_TEMPLATE },
|
||||
{ titleKey: "models.entityTemplate.defaultTemplates.allPropertyTypes", template: DefaultEntityTemplates.ALL_PROPERTY_TYPES_ENTITY_TEMPLATE },
|
||||
];
|
||||
|
||||
export default function AdminEntityTemplatesManual() {
|
||||
const { t } = useTranslation();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const [configuration, setConfiguration] = useState<string>("");
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.entityTemplate.uploadJsonConfiguration")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: t("models.entityTemplate.plural"),
|
||||
routePath: adminPath("entities/templates", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
title: t("models.entityTemplate.manual"),
|
||||
routePath: adminPath("entities/templates/manual", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="md:border-border md:border-t md:py-2">
|
||||
{actionData?.error ? (
|
||||
<>
|
||||
<p id="form-error-message" className="py-2 text-sm text-rose-500" role="alert">
|
||||
{actionData.error}
|
||||
</p>
|
||||
</>
|
||||
) : actionData?.success ? (
|
||||
<>
|
||||
<p id="form-success-message" className="text-text-500 py-2 text-sm" role="alert">
|
||||
{actionData.success}
|
||||
</p>
|
||||
<Link to={adminPath("entities", { mode: "host-aware" })} className="text-theme-600 hover:text-theme-500 text-sm font-medium underline">
|
||||
{t("models.entity.actions.goToEntities")}
|
||||
</Link>
|
||||
</>
|
||||
) : actionData?.previewTemplate === undefined ? (
|
||||
<>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="preview" hidden readOnly />
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{defaultTemplates.map((templateOption) => (
|
||||
<button
|
||||
key={templateOption.titleKey}
|
||||
type="button"
|
||||
onClick={() => setConfiguration(JSON.stringify(templateOption.template, null, "\t"))}
|
||||
className="bg-theme-100 text-theme-700 hover:bg-theme-200 focus:ring-ring inline-flex items-center rounded border border-transparent px-2.5 py-1.5 text-xs font-medium focus:outline-hidden focus:ring-2 focus:ring-offset-2"
|
||||
>
|
||||
{t(templateOption.titleKey)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div>
|
||||
<InputText
|
||||
name="configuration"
|
||||
title={t("models.entityTemplate.configuration")}
|
||||
editor="monaco"
|
||||
editorLanguage="json"
|
||||
value={configuration}
|
||||
setValue={setConfiguration}
|
||||
editorSize="lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.preview")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</>
|
||||
) : (
|
||||
actionData?.previewTemplate !== undefined && (
|
||||
<>
|
||||
<div className="md:border-border md:border-b md:py-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-foreground text-lg font-medium leading-6">{t("models.entityTemplate.previewEntities")}</h3>
|
||||
</div>
|
||||
</div>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="create" hidden readOnly />
|
||||
<input type="hidden" name="configuration" value={configuration} hidden readOnly />
|
||||
<div className="space-y-2">
|
||||
<PreviewEntitiesTemplate template={actionData.previewTemplate} />
|
||||
<div className="flex justify-end space-x-2">
|
||||
<ButtonPrimary type="submit">
|
||||
{actionData.previewTemplate.entities.length === 1 ? (
|
||||
<span>{t("models.entityTemplate.actions.createEntities", { count: 1 })}</span>
|
||||
) : (
|
||||
<span>{t("models.entityTemplate.actions.createEntities", { count: actionData.previewTemplate.entities.length })}</span>
|
||||
)}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useLocation, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityViewWithTenantAndUser, getAllEntityViews } from "~/utils/db/entities/entityViews.db.server";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import TabsWithIcons from "~/components/ui/tabs/TabsWithIcons";
|
||||
import { Menu } from "@headlessui/react";
|
||||
import Dropdown from "~/components/ui/dropdowns/Dropdown";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import clsx from "clsx";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EntityViewsTable from "~/components/entities/views/EntityViewsTable";
|
||||
import { getAllEntitiesSimple } from "~/utils/db/entities/entities.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
items: EntityViewWithTenantAndUser[];
|
||||
pagination: PaginationDto;
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
let type = searchParams.get("type");
|
||||
if (type && ["default", "tenant", "user", "system"].includes(type) === false) {
|
||||
throw redirect(adminPath("entities/views", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "entityId",
|
||||
title: t("models.entity.object"),
|
||||
options: (await getAllEntitiesSimple()).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: `${t(item.title)} (${item.name})`,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "tenantId",
|
||||
title: t("models.tenant.object"),
|
||||
options: (await adminGetAllTenantsIdsAndNames()).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.name,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: t("models.user.object"),
|
||||
options: (await adminGetAllUsersNames()).map((item) => {
|
||||
return {
|
||||
value: item.id,
|
||||
name: item.email,
|
||||
};
|
||||
}),
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
|
||||
const { items, total } = await getAllEntityViews({
|
||||
type: type ?? undefined,
|
||||
pagination: { pageSize: pagination.pageSize, page: pagination.page },
|
||||
filters,
|
||||
});
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: `${t("models.view.plural")} | ${process.env.APP_NAME}` }],
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems: total,
|
||||
totalPages: Math.ceil(total / pagination.pageSize),
|
||||
},
|
||||
filterableProperties,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action === "") {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const params = useParams();
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={
|
||||
<TabsWithIcons
|
||||
breakpoint="lg"
|
||||
tabs={[
|
||||
{
|
||||
name: t("shared.all"),
|
||||
href: adminPath("entities/views", { mode: "host-aware" }),
|
||||
current: location.pathname + location.search === adminPath("entities/views", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.view.typeOptions.default"),
|
||||
href: adminPath("entities/views?type=default", { mode: "host-aware" }),
|
||||
current: location.pathname + location.search === adminPath("entities/views?type=default", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.view.types.tenant"),
|
||||
href: adminPath("entities/views?type=tenant", { mode: "host-aware" }),
|
||||
current: location.pathname + location.search === adminPath("entities/views?type=tenant", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.view.types.user"),
|
||||
href: adminPath("entities/views?type=user", { mode: "host-aware" }),
|
||||
current: location.pathname + location.search === adminPath("entities/views?type=user", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("models.view.types.system"),
|
||||
href: adminPath("entities/views?type=system", { mode: "host-aware" }),
|
||||
current: location.pathname + location.search === adminPath("entities/views?type=system", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters filters={data.filterableProperties} withSearch={false} />
|
||||
<Dropdown
|
||||
right={false}
|
||||
button={<span>{t("models.view.actions.create")}</span>}
|
||||
disabled={appOrAdminData.entities.length === 0}
|
||||
options={
|
||||
<div>
|
||||
{appOrAdminData.entities
|
||||
.filter((f) => f.hasViews)
|
||||
.map((f) => {
|
||||
return (
|
||||
<Menu.Item key={f.id}>
|
||||
{({ active }) => (
|
||||
<Link
|
||||
to={adminPath(`entities/views/new/${f.name}${location.search}`, { mode: "host-aware" })}
|
||||
className={clsx("w-full truncate", active ? "text-foreground bg-secondary/90" : "text-foreground/80", "block px-4 py-2 text-sm")}
|
||||
>
|
||||
<div className="truncate">
|
||||
{t(f.title)} <span className="text-muted-foreground text-xs">({f.name})</span>
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
</Menu.Item>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
}
|
||||
></Dropdown>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<EntityViewsTable
|
||||
items={data.items}
|
||||
onClickRoute={(i) => {
|
||||
return adminPath(`entities/views/${i.id}${location.search}`, { mode: "host-aware" });
|
||||
}}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={params.id ? t("models.view.actions.edit") : params.entity ? t("models.view.actions.newForEntity", { entity: params.entity }) : t("models.view.actions.new")}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate("." + location.search, { replace: true });
|
||||
}}
|
||||
className="sm:max-w-2xl"
|
||||
overflowYScroll={true}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useNavigate } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import EntityViewForm from "~/components/entities/views/EntityViewForm";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityViewsApi } from "~/utils/api/.server/EntityViewsApi";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { EntityWithDetails, getEntityById } from "~/utils/db/entities/entities.db.server";
|
||||
import { deleteEntityView, EntityViewWithTenantAndUser, getEntityViewWithTenantAndUser } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { TenantWithDetails, adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { UserWithNames, adminGetAllUsersNames } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: EntityViewWithTenantAndUser;
|
||||
allTenants: TenantWithDetails[];
|
||||
allUsers: UserWithNames[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const item = await getEntityViewWithTenantAndUser(params.id ?? "");
|
||||
if (!item) {
|
||||
return redirect(adminPath(`entities/views`, { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
allTenants: await adminGetAllTenants(),
|
||||
allUsers: await adminGetAllUsersNames(),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const item = await getEntityViewWithTenantAndUser(params.id ?? "");
|
||||
if (!item) {
|
||||
return redirect(adminPath(`entities/views`, { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "edit") {
|
||||
try {
|
||||
const entityId = form.get("entityId")?.toString() ?? "";
|
||||
const entity = await getEntityById({ tenantId: null, id: entityId });
|
||||
if (!entity) {
|
||||
return Response.json({ error: t("models.view.errors.entityNotFound") }, { status: 404 });
|
||||
}
|
||||
await EntityViewsApi.updateFromForm({ entity, item, form });
|
||||
return redirect(adminPath(`entities/views`, { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
try {
|
||||
await deleteEntityView(item.id);
|
||||
return redirect(adminPath(`entities/views`, { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [entity, setEntity] = useState<EntityWithDetails>();
|
||||
const [type, setType] = useState<"default" | "tenant" | "user" | "system">();
|
||||
const [tenantId, setTenantId] = useState<string | null>(null);
|
||||
const [userId, setUserId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setEntity(appOrAdminData.entities.find((f) => f.id === data.item.entityId));
|
||||
setTenantId(data.item.tenantId ?? null);
|
||||
setUserId(data.item.userId ?? null);
|
||||
if (data.item.isSystem) {
|
||||
setType("system");
|
||||
} else if (!data.item.tenantId && !data.item.userId) {
|
||||
setType("default");
|
||||
} else if (data.item.tenantId && !data.item.userId) {
|
||||
setType("tenant");
|
||||
} else if (data.item.userId) {
|
||||
setType("user");
|
||||
}
|
||||
}, [appOrAdminData, data]);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{entity && type && (
|
||||
<EntityViewForm
|
||||
entity={entity}
|
||||
tenantId={tenantId}
|
||||
userId={userId}
|
||||
isSystem={type === "system"}
|
||||
item={data.item}
|
||||
onClose={() => navigate(adminPath(`entities/views`, { mode: "host-aware" }))}
|
||||
showViewType={true}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useSearchParams } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityViewForm from "~/components/entities/views/EntityViewForm";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import InputRadioGroupCards from "~/components/ui/input/InputRadioGroupCards";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { EntityViewsApi } from "~/utils/api/.server/EntityViewsApi";
|
||||
import { EntityWithDetails, findEntityByName, getEntityById } from "~/utils/db/entities/entities.db.server";
|
||||
import { adminGetAllTenants, TenantWithDetails } from "~/utils/db/tenants.db.server";
|
||||
import { adminGetAllUsersNames, UserWithNames } from "~/utils/db/users.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import EntityViewHelper from "~/utils/helpers/EntityViewHelper";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
allTenants: TenantWithDetails[];
|
||||
allUsers: UserWithNames[];
|
||||
entity: EntityWithDetails;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.view");
|
||||
const entity = await findEntityByName({ tenantId: null, name: params.entity! });
|
||||
if (!entity || !entity.hasViews) {
|
||||
return redirect(adminPath(`entities/views`, { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
allTenants: await adminGetAllTenants(),
|
||||
allUsers: await adminGetAllUsersNames(),
|
||||
entity,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await verifyUserHasPermission(request, "admin.entities.update");
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString() ?? "";
|
||||
if (action === "create") {
|
||||
try {
|
||||
const entityId = form.get("entityId")?.toString() ?? "";
|
||||
const entity = await getEntityById({ tenantId: null, id: entityId });
|
||||
if (!entity) {
|
||||
return Response.json({ error: t("models.view.errors.entityNotFound") }, { status: 404 });
|
||||
}
|
||||
const view = await EntityViewsApi.createFromForm({ entity, form, createdByUserId: userInfo.userId });
|
||||
const type = EntityViewHelper.getType(view);
|
||||
return redirect(adminPath(`entities/views?type=${type}`, { mode: "host-aware" }));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e.message });
|
||||
}
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const [type, setType] = useState<"default" | "tenant" | "user" | "system">();
|
||||
const [tenantId, setTenantId] = useState<string>();
|
||||
const [userId, setUserId] = useState<string>();
|
||||
|
||||
const [viewType, setViewType] = useState<{
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
isSystem: boolean;
|
||||
}>();
|
||||
|
||||
useEffect(() => {
|
||||
const type = searchParams.get("type");
|
||||
if (type && ["default", "tenant", "user", "system"].includes(type)) {
|
||||
setType(type as any);
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
setUserId(undefined);
|
||||
}, [tenantId]);
|
||||
|
||||
useEffect(() => {
|
||||
setTenantId(undefined);
|
||||
setUserId(undefined);
|
||||
}, [type]);
|
||||
|
||||
function getUsers() {
|
||||
const tenant = data.allTenants?.find((f) => f.id === tenantId);
|
||||
if (!tenant) {
|
||||
return data.allUsers ?? [];
|
||||
}
|
||||
return tenant?.users.map((f) => f.user) ?? [];
|
||||
}
|
||||
|
||||
function getError() {
|
||||
let error: string | undefined = undefined;
|
||||
if (!type) {
|
||||
error = t("models.view.errors.selectType");
|
||||
} else if (type === "tenant" && !tenantId) {
|
||||
error = t("models.view.errors.selectAccount");
|
||||
} else if (type === "user" && (!userId || !tenantId)) {
|
||||
error = t("models.view.errors.selectAccountAndUser");
|
||||
} else if (type === "system" && (userId || tenantId)) {
|
||||
error = t("models.view.errors.systemAssociation");
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
function onAccept() {
|
||||
const error = getError();
|
||||
setError(error);
|
||||
|
||||
if (!error) {
|
||||
setViewType({
|
||||
tenantId: tenantId ?? null,
|
||||
userId: userId ?? null,
|
||||
isSystem: type === "system",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
onAccept();
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{!viewType ? (
|
||||
<Form onSubmit={handleSubmit} className="space-y-3">
|
||||
<InputGroup title={t("models.view.type")}>
|
||||
<div className="space-y-1">
|
||||
<InputRadioGroupCards
|
||||
display="name"
|
||||
name="type"
|
||||
value={type}
|
||||
onChange={(e) => setType((e?.toString() ?? "default") as any)}
|
||||
columns={2}
|
||||
options={[
|
||||
{ name: t("models.view.typeOptions.default"), value: "default" },
|
||||
{ name: t("models.view.typeOptions.tenant"), value: "tenant" },
|
||||
{ name: t("models.view.typeOptions.user"), value: "user" },
|
||||
{ name: t("models.view.typeOptions.system"), value: "system" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
{type && ["tenant", "user"].includes(type) && (
|
||||
<InputGroup title={t("models.view.appliesTo")}>
|
||||
<div className="grid gap-2">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
name="tenantId"
|
||||
title={t("models.view.tenant")}
|
||||
value={tenantId}
|
||||
setValue={(e) => setTenantId(e?.toString())}
|
||||
hint={
|
||||
<>
|
||||
{tenantId !== undefined && (
|
||||
<button type="button" onClick={() => setTenantId(undefined)} className="text-muted-foreground text-xs">
|
||||
{t("shared.clear")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
options={(data.allTenants ?? []).map((f) => {
|
||||
return {
|
||||
value: f.id,
|
||||
name: f.name + " (" + f.slug + ")",
|
||||
};
|
||||
})}
|
||||
/>
|
||||
{type === "user" && (
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
title={t("models.view.user")}
|
||||
disabled={!tenantId}
|
||||
value={userId}
|
||||
setValue={(e) => setUserId(e?.toString())}
|
||||
options={getUsers().map((f) => {
|
||||
return {
|
||||
value: f.id,
|
||||
name: f.email,
|
||||
};
|
||||
})}
|
||||
hint={
|
||||
<>
|
||||
{userId !== undefined && (
|
||||
<button type="button" onClick={() => setUserId(undefined)} className="text-muted-foreground text-xs">
|
||||
{t("shared.clear")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</InputGroup>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between space-x-2">
|
||||
<div></div>
|
||||
<ButtonPrimary disabled={!!getError()} type="submit">
|
||||
{t("shared.next")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
|
||||
{error && <ErrorBanner title={t("shared.error")} text={error} />}
|
||||
</Form>
|
||||
) : (
|
||||
<EntityViewForm
|
||||
entity={data.entity}
|
||||
tenantId={viewType.tenantId}
|
||||
userId={viewType.userId}
|
||||
isSystem={viewType.isSystem}
|
||||
onClose={() => navigate(adminPath(`entities/views`, { mode: "host-aware" }))}
|
||||
showViewType={true}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ErrorModal ref={errorModal} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user