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,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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user