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,123 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import { EntityWithCount } from "~/utils/db/entities/entities.db.server";
|
||||
import SimpleBadge from "../ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import TableSimple from "../ui/tables/TableSimple";
|
||||
import RelationshipHelper from "~/utils/helpers/RelationshipHelper";
|
||||
import OrderListButtons from "../ui/sort/OrderListButtons";
|
||||
import { useEffect, useState } from "react";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { translateEntityTitlePlural, translatePropertyTitle } from "~/utils/i18n/translateLabel";
|
||||
|
||||
interface Props {
|
||||
items: EntityWithCount[];
|
||||
selected?: EntityWithCount[];
|
||||
onSelected?: (items: EntityWithCount[]) => void;
|
||||
}
|
||||
|
||||
export default function EntitiesTable({ items, selected, onSelected }: Props) {
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<EntityWithCount>[]>([]);
|
||||
useEffect(() => {
|
||||
const headers: RowHeaderDisplayDto<EntityWithCount>[] = [
|
||||
{
|
||||
name: "type",
|
||||
title: t("models.entity.type"),
|
||||
value: (item) => (
|
||||
<SimpleBadge
|
||||
title={item.type === "all" ? "app-and-admin" : item.type}
|
||||
color={item.type === "app" ? Colors.BLUE : item.type === "admin" ? Colors.GRAY : Colors.EMERALD}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("shared.order"),
|
||||
name: "order",
|
||||
value: (item) => item.order,
|
||||
formattedValue: (_, idx) => <OrderListButtons index={idx} items={items} />,
|
||||
},
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.entity.title"),
|
||||
value: (item) => (
|
||||
<div className="flex items-center space-x-1">
|
||||
<Link to={adminPath("entities/" + item.slug + "/details", { mode: "host-aware" })} className="font-medium hover:underline">
|
||||
{translateEntityTitlePlural(t, i18n, item)}
|
||||
</Link>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "properties",
|
||||
title: t("models.property.plural"),
|
||||
className: "w-full text-xs",
|
||||
value: (item) => (
|
||||
<div className="max-w-xs truncate">
|
||||
{item.properties.filter((f) => !f.isDefault).length > 0 ? (
|
||||
<Link className="truncate pb-1 hover:underline" to={adminPath("entities/" + item.slug + "/properties", { mode: "host-aware" })}>
|
||||
{item.properties
|
||||
.filter((f) => !f.isDefault)
|
||||
.map((f) => translatePropertyTitle(t, i18n, item.name, f) + (f.isRequired ? "*" : ""))
|
||||
.join(", ")}
|
||||
</Link>
|
||||
) : (
|
||||
<Link className="text-muted-foreground truncate pb-1 hover:underline" to={adminPath("entities/" + item.slug + "/properties", { mode: "host-aware" })}>
|
||||
{t("shared.setCustomProperties")}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "relationships",
|
||||
title: t("models.relationship.plural"),
|
||||
value: (item) => (
|
||||
<Link className="truncate pb-1 hover:underline" to={adminPath("entities/" + item.slug + "/relationships", { mode: "host-aware" })}>
|
||||
{[...item.parentEntities, ...item.childEntities]
|
||||
.map((relationship) => t(RelationshipHelper.getTitleWithName({ fromEntityId: item.id, relationship })))
|
||||
.join(", ")}
|
||||
</Link>
|
||||
),
|
||||
className: "text-xs",
|
||||
},
|
||||
{
|
||||
name: "rows",
|
||||
title: t("models.row.plural"),
|
||||
value: (item) => (
|
||||
<Link to={adminPath("entities/" + item.slug + "/rows", { mode: "host-aware" })} className="hover:underline">
|
||||
{item._count.rows}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
setHeaders(headers);
|
||||
}, [appOrAdminData.tenantTypes, items, t]);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<TableSimple
|
||||
selectedRows={selected}
|
||||
onSelected={onSelected}
|
||||
items={items}
|
||||
actions={[
|
||||
{
|
||||
title: t("models.entity.noCode.menu"),
|
||||
onClickRoute: (_, item) => adminPath(`entities/${item.slug}/no-code`, { mode: "host-aware" }),
|
||||
disabled: (i) => !i.isAutogenerated,
|
||||
},
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, item) => adminPath(`entities/${item.slug}/details`, { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
headers={headers}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "./EntityForm.tsx"), "utf8");
|
||||
|
||||
describe("EntityForm routing examples", () => {
|
||||
it("renders entity API examples through the canonical API host helper", () => {
|
||||
expect(source).toContain("apiPath(`entities/${slug || \"entity-name\"}/rows`, { mode: \"host-aware\" })");
|
||||
expect(source).toContain("rootData.apiBaseUrl ? new URL(apiRowsPath, rootData.apiBaseUrl).toString() : apiRowsPath");
|
||||
expect(source).not.toContain("Generates entity API at /v1/entities/");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,373 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import InputText, { RefInputText } from "../ui/input/InputText";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import InputGroup from "../ui/forms/InputGroup";
|
||||
import EntityIcon from "../layouts/icons/EntityIcon";
|
||||
import QuestionMarkFilledIcon from "../ui/icons/QuestionMarkFilledIcon";
|
||||
import InputNumber from "../ui/input/InputNumber";
|
||||
import InputCheckboxWithDescription from "../ui/input/InputCheckboxWithDescription";
|
||||
import { Entity } from "@toolctrl/db/prisma-browser";
|
||||
import FormGroup from "../ui/forms/FormGroup";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import StringUtils from "~/utils/shared/StringUtils";
|
||||
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
|
||||
import InputSelect from "../ui/input/InputSelect";
|
||||
import VisibilityHelper from "~/utils/helpers/VisibilityHelper";
|
||||
import Constants from "~/application/Constants";
|
||||
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { adminPath, apiPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
interface Props {
|
||||
item?: Entity | null;
|
||||
}
|
||||
export default function EntityForm({ item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const adminData = useAdminData();
|
||||
const rootData = useRootData();
|
||||
|
||||
const inputName = useRef<RefInputText>(null);
|
||||
|
||||
const [title, setTitle] = useState(item?.title ?? "");
|
||||
const [titlePlural, setTitlePlural] = useState(item?.titlePlural ?? "");
|
||||
const [name, setName] = useState(item?.name ?? "");
|
||||
const [type, setType] = useState(item?.type ?? DefaultEntityTypes.AppOnly);
|
||||
|
||||
const [slug, setSlug] = useState(item?.slug ?? "");
|
||||
const [icon, setIcon] = useState(
|
||||
item?.icon ??
|
||||
`<svg stroke="currentColor" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /> </svg>`
|
||||
);
|
||||
const [order, setOrder] = useState<number | undefined>(
|
||||
item?.order ?? (adminData.entities.length > 0 ? Math.max(...adminData.entities.map((o) => o.order)) : 0) + 1
|
||||
);
|
||||
const [prefix, setPrefix] = useState(item?.prefix ?? "");
|
||||
const [isAutogenerated, setIsAutogenerated] = useState(item?.isAutogenerated ?? true);
|
||||
const [hasApi, setHasApi] = useState(item?.hasApi ?? true);
|
||||
const [active, setActive] = useState(item?.active ?? true);
|
||||
|
||||
const [showInSidebar, setShowInSidebar] = useState(item?.showInSidebar ?? true);
|
||||
const [hasTags, setHasTags] = useState(item?.hasTags ?? true);
|
||||
const [hasComments, setHasComments] = useState(item?.hasComments ?? true);
|
||||
const [hasTasks, setHasTasks] = useState(item?.hasTasks ?? false);
|
||||
const [hasActivity, setHasActivity] = useState(item ? item.hasActivity : true);
|
||||
const [hasBulkDelete, setHasBulkDelete] = useState(item ? item.hasBulkDelete : false);
|
||||
const [hasViews, setHasViews] = useState(item ? item.hasViews : false);
|
||||
|
||||
const [defaultVisibility, setDefaultVisibility] = useState<string | number | undefined>(item?.defaultVisibility ?? Constants.DEFAULT_ROW_VISIBILITY);
|
||||
|
||||
const [onCreated, setOnCreated] = useState(item?.onCreated ?? "redirectToOverview");
|
||||
const [onEdit, setOnEdit] = useState(item?.onEdit ?? "editRoute");
|
||||
const apiRowsPath = apiPath(`entities/${slug || "entity-name"}/rows`, { mode: "host-aware" });
|
||||
const apiRowsUrl = rootData.apiBaseUrl ? new URL(apiRowsPath, rootData.apiBaseUrl).toString() : apiRowsPath;
|
||||
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
inputName.current?.input.current?.focus();
|
||||
}, 100);
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// useEffect(() => {
|
||||
// if (!item) {
|
||||
// const slug = UrlUtils.slugify(t(titlePlural));
|
||||
// setSlug(slug);
|
||||
// if (titlePlural.length >= 3) {
|
||||
// setPrefix(t(titlePlural).substring(0, 3).toUpperCase());
|
||||
// }
|
||||
// }
|
||||
// // eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
// }, [titlePlural]);
|
||||
|
||||
return (
|
||||
<FormGroup id={item?.id} onCancel={() => navigate(adminPath("entities", { mode: "host-aware" }))} editing={true} canDelete={false}>
|
||||
<InputGroup title={t("models.entity.object")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputText
|
||||
ref={inputName}
|
||||
className="sm:col-span-6"
|
||||
name="name"
|
||||
title={t("models.entity.name")}
|
||||
value={name}
|
||||
setValue={setName}
|
||||
required
|
||||
help={t("models.entity.form.help.name")}
|
||||
autoComplete="off"
|
||||
onBlur={() => {
|
||||
if (!title.trim()) {
|
||||
const generateTitle = (str: string) => {
|
||||
return str
|
||||
.replace(/([a-z])([A-Z])/g, "$1 $2") // Insert space before capital letters
|
||||
.split(" ") // Split by spaces
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) // Capitalize the first letter of each word
|
||||
.join(" "); // Join the words back together
|
||||
};
|
||||
const newTitle = generateTitle(name);
|
||||
if (newTitle) {
|
||||
setTitle(newTitle);
|
||||
setPrefix(t(newTitle).substring(0, 3).toUpperCase());
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<InputText
|
||||
className="sm:col-span-6"
|
||||
name="title"
|
||||
title={t("models.entity.title")}
|
||||
value={title}
|
||||
setValue={setTitle}
|
||||
required
|
||||
autoComplete="off"
|
||||
help={t("models.entity.form.help.title")}
|
||||
withTranslation
|
||||
/>
|
||||
<InputText
|
||||
className="sm:col-span-6"
|
||||
name="slug"
|
||||
title={t("models.entity.slug")}
|
||||
value={slug}
|
||||
setValue={(e) => {
|
||||
const withoutStartingSlash = e?.toString().replace(/^\//, "");
|
||||
setSlug(withoutStartingSlash);
|
||||
}}
|
||||
required
|
||||
autoComplete="off"
|
||||
help={t("models.entity.form.help.slug")}
|
||||
onBlur={() => {
|
||||
setSlug(UrlUtils.slugify(slug));
|
||||
if (!titlePlural.trim()) {
|
||||
const words = slug.split(/[- ]/).map((w) => StringUtils.capitalize(w.toLowerCase()));
|
||||
setTitlePlural(words.join(" "));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<InputText
|
||||
className="sm:col-span-6"
|
||||
name="title-plural"
|
||||
title={t("models.entity.titlePlural")}
|
||||
value={titlePlural}
|
||||
setValue={setTitlePlural}
|
||||
required
|
||||
autoComplete="off"
|
||||
help={t("models.entity.form.help.titlePlural")}
|
||||
withTranslation
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputGroup title={t("models.entity.permissions")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputSelect
|
||||
className="sm:col-span-12"
|
||||
name="default-visibility"
|
||||
title={t("models.entity.defaultVisibility")}
|
||||
value={defaultVisibility}
|
||||
setValue={setDefaultVisibility}
|
||||
options={[
|
||||
{
|
||||
name: VisibilityHelper.getVisibilityTitle(t, DefaultVisibility.Private),
|
||||
value: DefaultVisibility.Private,
|
||||
},
|
||||
{
|
||||
name: VisibilityHelper.getVisibilityTitle(t, DefaultVisibility.Tenant),
|
||||
value: DefaultVisibility.Tenant,
|
||||
},
|
||||
{
|
||||
name: VisibilityHelper.getVisibilityTitle(t, DefaultVisibility.Public),
|
||||
value: DefaultVisibility.Public,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputGroup title={t("models.entity.form.sections.display")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputSelect
|
||||
className="sm:col-span-3"
|
||||
name="type"
|
||||
title={t("models.entity.type")}
|
||||
value={type}
|
||||
// display="name"
|
||||
setValue={(e) => setType(e?.toString() ?? DefaultEntityTypes.AppOnly)}
|
||||
options={[
|
||||
{ name: t("models.entity.typeOptions.app"), value: DefaultEntityTypes.AppOnly },
|
||||
{ name: t("models.entity.typeOptions.admin"), value: DefaultEntityTypes.AdminOnly },
|
||||
{ name: t("models.entity.typeOptions.appAndAdmin"), value: DefaultEntityTypes.All },
|
||||
{ name: t("models.entity.typeOptions.system"), value: DefaultEntityTypes.System },
|
||||
]}
|
||||
required
|
||||
/>
|
||||
<InputNumber
|
||||
className="sm:col-span-3"
|
||||
name="order"
|
||||
title={t("models.entity.order")}
|
||||
value={order}
|
||||
setValue={setOrder}
|
||||
disabled={!item}
|
||||
min={1}
|
||||
max={99}
|
||||
required
|
||||
help={t("models.entity.form.help.order")}
|
||||
// readOnly={item === undefined}
|
||||
/>
|
||||
|
||||
<InputText
|
||||
className="sm:col-span-3"
|
||||
name="prefix"
|
||||
title={t("models.entity.prefix")}
|
||||
value={prefix}
|
||||
setValue={(e) => setPrefix(e.toString().toUpperCase())}
|
||||
minLength={2}
|
||||
maxLength={5}
|
||||
required
|
||||
help={t("models.entity.form.help.prefix")}
|
||||
/>
|
||||
|
||||
<InputText
|
||||
className="sm:col-span-3"
|
||||
name="icon"
|
||||
title={t("models.entity.icon")}
|
||||
// required
|
||||
value={icon}
|
||||
setValue={setIcon}
|
||||
hint={<div className="text-muted-foreground">{t("models.entity.form.iconHint")}</div>}
|
||||
button={
|
||||
<div className="absolute inset-y-0 right-0 flex py-0.5 pr-0.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-secondary inline-flex w-10 items-center justify-center rounded border px-1 text-center font-sans text-xs font-medium">
|
||||
{icon ? (
|
||||
<EntityIcon className="text-muted-foreground h-7 w-7" icon={icon} title={title} />
|
||||
) : (
|
||||
<QuestionMarkFilledIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
)}
|
||||
</kbd>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputGroup title={t("models.entity.form.sections.behavior")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputSelect
|
||||
className="sm:col-span-6"
|
||||
name="onCreated"
|
||||
title={t("models.entity.form.onCreated")}
|
||||
value={onCreated}
|
||||
setValue={(e) => setOnCreated(e?.toString() ?? "")}
|
||||
options={[
|
||||
{ value: "redirectToOverview", name: t("models.entity.form.onCreatedOptions.redirectToOverview") },
|
||||
{ value: "redirectToEdit", name: t("models.entity.form.onCreatedOptions.redirectToEdit") },
|
||||
{ value: "redirectToList", name: t("models.entity.form.onCreatedOptions.redirectToList") },
|
||||
{ value: "redirectToNew", name: t("models.entity.form.onCreatedOptions.redirectToNew") },
|
||||
{ value: "addAnother", name: t("models.entity.form.onCreatedOptions.addAnother") },
|
||||
{ value: "redirectToGroup", name: t("models.entity.form.onCreatedOptions.redirectToGroup") },
|
||||
]}
|
||||
/>
|
||||
<InputSelect
|
||||
className="sm:col-span-6"
|
||||
name="onEdit"
|
||||
title={t("models.entity.form.onEdit")}
|
||||
value={onEdit}
|
||||
setValue={(e) => setOnEdit(e?.toString() ?? "")}
|
||||
options={[
|
||||
{ value: "editRoute", name: t("models.entity.form.onEditOptions.editRoute") },
|
||||
{ value: "overviewRoute", name: t("models.entity.form.onEditOptions.overviewRoute") },
|
||||
{ value: "overviewAlwaysEditable", name: t("models.entity.form.onEditOptions.overviewAlwaysEditable") },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
<InputGroup title={t("shared.settings")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<div className="divide-border col-span-12 divide-y">
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-api"
|
||||
title={t("models.entity.hasApi")}
|
||||
value={hasApi}
|
||||
setValue={setHasApi}
|
||||
description={t("models.entity.form.descriptions.hasApi", { apiRowsUrl })}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="is-autogenerated"
|
||||
title={t("models.entity.isAutogenerated")}
|
||||
value={isAutogenerated}
|
||||
setValue={setIsAutogenerated}
|
||||
description={t("models.entity.form.descriptions.isAutogenerated")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="active"
|
||||
title={t("models.entity.active")}
|
||||
value={active}
|
||||
setValue={setActive}
|
||||
description={t("models.entity.form.descriptions.active")}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="show-in-sidebar"
|
||||
title={t("models.entity.showInSidebar")}
|
||||
value={showInSidebar}
|
||||
setValue={setShowInSidebar}
|
||||
description={t("models.entity.form.descriptions.showInSidebar")}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-tags"
|
||||
title={t("models.entity.hasTags")}
|
||||
value={hasTags}
|
||||
setValue={setHasTags}
|
||||
description={t("models.entity.form.descriptions.hasTags")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-comments"
|
||||
title={t("models.entity.hasComments")}
|
||||
value={hasComments}
|
||||
setValue={setHasComments}
|
||||
description={t("models.entity.form.descriptions.hasComments")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-tasks"
|
||||
title={t("models.entity.hasTasks")}
|
||||
value={hasTasks}
|
||||
setValue={setHasTasks}
|
||||
description={t("models.entity.form.descriptions.hasTasks")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-activity"
|
||||
title={t("models.entity.hasActivity")}
|
||||
value={hasActivity}
|
||||
setValue={setHasActivity}
|
||||
description={t("models.entity.form.descriptions.hasActivity")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-bulk-delete"
|
||||
title={t("models.entity.hasBulkDelete")}
|
||||
value={hasBulkDelete}
|
||||
setValue={setHasBulkDelete}
|
||||
description={t("models.entity.form.descriptions.hasBulkDelete")}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-12"
|
||||
name="has-views"
|
||||
title={t("models.entity.hasViews")}
|
||||
value={hasViews}
|
||||
setValue={setHasViews}
|
||||
description={t("models.entity.form.descriptions.hasViews")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</InputGroup>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useNavigate } from "react-router";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityGroupWithDetails } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import InputText, { RefInputText } from "../ui/input/InputText";
|
||||
import FormGroup from "../ui/forms/FormGroup";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import InputCheckboxCards from "../ui/input/InputCheckboxCards";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EntityIcon from "../layouts/icons/EntityIcon";
|
||||
import QuestionMarkFilledIcon from "../ui/icons/QuestionMarkFilledIcon";
|
||||
import InputCheckboxWithDescription from "../ui/input/InputCheckboxWithDescription";
|
||||
import InputSelector from "../ui/input/InputSelector";
|
||||
import { EntityViewWithTenantAndUser } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export function EntityGroupForm({
|
||||
item,
|
||||
allEntities,
|
||||
systemViews,
|
||||
}: {
|
||||
item: EntityGroupWithDetails | undefined;
|
||||
allEntities: EntitySimple[];
|
||||
systemViews: EntityViewWithTenantAndUser[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [title, setTitle] = useState(item?.title ?? "");
|
||||
const [slug, setSlug] = useState(item?.slug ?? "");
|
||||
const [icon, setIcon] = useState(
|
||||
item?.icon ??
|
||||
`<svg stroke="currentColor" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5"> <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /> </svg>`
|
||||
);
|
||||
const [collapsible, setCollapsible] = useState(item?.collapsible ?? false);
|
||||
const [section, setSection] = useState(item?.section ?? "");
|
||||
const [entities, setEntities] = useState<{ entityId: string; allViewId: string | null }[]>(item?.entities ?? []);
|
||||
|
||||
const input = useRef<RefInputText>(null);
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
input.current?.input.current?.focus();
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!item) {
|
||||
const slug = UrlUtils.slugify(title.toLowerCase());
|
||||
setSlug(slug);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [title]);
|
||||
|
||||
return (
|
||||
<FormGroup
|
||||
id={item?.id}
|
||||
onCancel={() => navigate(adminPath("entities/groups", { mode: "host-aware" }))}
|
||||
editing={true}
|
||||
canDelete={getUserHasPermission(appOrAdminData, "admin.entities.delete")}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between space-x-2">
|
||||
<InputText ref={input} autoFocus name="title" title={t("shared.title")} value={title} setValue={setTitle} required />
|
||||
<InputText name="slug" title={t("shared.slug")} value={slug} setValue={setSlug} required onBlur={() => setSlug(UrlUtils.slugify(slug))} />
|
||||
</div>
|
||||
<InputText
|
||||
className="col-span-12"
|
||||
name="icon"
|
||||
title={t("models.entity.icon")}
|
||||
value={icon}
|
||||
setValue={setIcon}
|
||||
hint={<div className="text-muted-foreground">{t("models.entityGroup.form.iconHint")}</div>}
|
||||
button={
|
||||
<div className="absolute inset-y-0 right-0 flex py-0.5 pr-0.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-secondary inline-flex w-10 items-center justify-center rounded border px-1 text-center font-sans text-xs font-medium">
|
||||
{icon ? (
|
||||
<EntityIcon className="text-muted-foreground h-7 w-7" icon={icon} title={title} />
|
||||
) : (
|
||||
<QuestionMarkFilledIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
)}
|
||||
</kbd>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<InputText name="section" title={t("models.entityGroup.section")} value={section} setValue={setSection} />
|
||||
<InputCheckboxWithDescription
|
||||
name="collapsible"
|
||||
title={t("models.entityGroup.collapsible")}
|
||||
value={collapsible}
|
||||
setValue={setCollapsible}
|
||||
description={t("models.entityGroup.form.collapsibleDescription")}
|
||||
/>
|
||||
<InputCheckboxCards
|
||||
display="name"
|
||||
columns={allEntities.length === 1 ? 1 : 2}
|
||||
name="entities"
|
||||
title={t("models.entity.plural")}
|
||||
value={entities.map((f) => f.entityId)}
|
||||
selectAndClearAll
|
||||
onChange={(e) =>
|
||||
setEntities(
|
||||
e.map((v) => ({
|
||||
entityId: v.toString(),
|
||||
allViewId: entities.find((f) => f.entityId === v.toString())?.allViewId ?? null,
|
||||
}))
|
||||
)
|
||||
}
|
||||
options={allEntities.map((v) => ({ value: v.id, name: `${t(v.title)}` }))}
|
||||
/>
|
||||
|
||||
<div>
|
||||
{/* <label className="mb-1 flex justify-between space-x-2 text-xs font-medium">Layouts</label> */}
|
||||
<div className="space-y-1">
|
||||
{entities
|
||||
.filter((f) => systemViews.some((v) => v.entityId === f.entityId))
|
||||
.map((f, idx) => {
|
||||
const entity = allEntities.find((e) => e.id === f.entityId);
|
||||
if (!entity) {
|
||||
return <div key={f.entityId}>{t("models.entityGroup.form.invalidEntity")}</div>;
|
||||
}
|
||||
const entitySystemViews = systemViews.filter((v) => v.entityId === entity.id);
|
||||
return (
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
key={f.entityId}
|
||||
title={t("models.entityGroup.layoutFor", { entity: t(entity.title) })}
|
||||
value={f.allViewId ?? undefined}
|
||||
setValue={(e) => {
|
||||
const newEntities = [...entities];
|
||||
newEntities[idx].allViewId = e?.toString() ?? null;
|
||||
setEntities(newEntities);
|
||||
}}
|
||||
options={entitySystemViews.map((f) => {
|
||||
return {
|
||||
value: f.id,
|
||||
name: `${f.title} (${f.layout})`,
|
||||
};
|
||||
})}
|
||||
hint={
|
||||
<>
|
||||
{!!f.allViewId && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const newEntities = [...entities];
|
||||
const entity = entities.find((e) => e.entityId === f.entityId);
|
||||
if (entity) {
|
||||
entity.allViewId = null;
|
||||
}
|
||||
setEntities(newEntities);
|
||||
}}
|
||||
className="text-muted-foreground text-xs"
|
||||
>
|
||||
{t("shared.clear")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{entities.map((item) => {
|
||||
return <input key={item.entityId} type="hidden" name={"entities[]"} value={JSON.stringify(item)} />;
|
||||
})}
|
||||
</div>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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/components/entities/EntityForm.tsx");
|
||||
|
||||
describe("entity form i18n", () => {
|
||||
it("uses semantic translation keys for visible labels, options, help text, and descriptions", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.entity.defaultVisibility");
|
||||
expect(source).toContain("models.entity.typeOptions.appAndAdmin");
|
||||
expect(source).toContain("models.entity.form.help.slug");
|
||||
expect(source).toContain("models.entity.form.onCreatedOptions.redirectToOverview");
|
||||
expect(source).toContain("models.entity.form.descriptions.hasApi");
|
||||
expect(source).toContain("QuestionMarkFilledIcon");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('text-red-600">?</span>');
|
||||
expect(source).not.toContain('help="eg: contract"');
|
||||
expect(source).not.toContain('"Redirect to overview"');
|
||||
expect(source).not.toContain('"App and Admin"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/components/entities/relationships/EntityRelationshipsTable.tsx",
|
||||
"apps/web/app/components/entities/views/EntityViewsTable.tsx",
|
||||
];
|
||||
|
||||
describe("entity table i18n formatting", () => {
|
||||
it("uses locale-aware formatters for relationship and view counts", () => {
|
||||
const sources = sourceFiles.map((file) => readRepoFile(file)).join("\n");
|
||||
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("formatters.number");
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
});
|
||||
});
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
import { EntityTemplate } from "@toolctrl/db/prisma-browser";
|
||||
import { useSubmit } from "react-router";
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputCheckbox from "~/components/ui/input/InputCheckbox";
|
||||
import InputDate from "~/components/ui/input/InputDate";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
|
||||
const NovelEditor = lazy(() => import("~/modules/novel/ui/editor"));
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
item?: EntityTemplate;
|
||||
}
|
||||
|
||||
export default function EntityTemplateForm({ entity, item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const [title, setTitle] = useState<string>(item?.title ?? "");
|
||||
const [config, setConfig] = useState<{ [key: string]: any }>(item?.config ? JSON.parse(item?.config) : {});
|
||||
|
||||
function onSubmit(formData: FormData) {
|
||||
formData.set("config", JSON.stringify(config));
|
||||
submit(formData, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<FormGroup onSubmit={onSubmit} id={item?.id} editing={true}>
|
||||
<InputText name="title" title={t("models.entityTemplate.title")} value={title} setValue={setTitle} required />
|
||||
{entity.properties
|
||||
.filter((f) => !f.isDefault)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((property) => {
|
||||
return (
|
||||
<div key={property.name}>
|
||||
{property.type === PropertyType.TEXT ? (
|
||||
<>
|
||||
{PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Editor) === "wysiwyg" ? (
|
||||
<div className="h-52 overflow-y-auto">
|
||||
<div>
|
||||
<label htmlFor={property.name} className="text-muted-foreground mb-1 block text-xs font-medium">
|
||||
{t(property.title)}
|
||||
</label>
|
||||
<Suspense fallback={null}>
|
||||
<NovelEditor
|
||||
autoFocus={false}
|
||||
content={config[property.name]}
|
||||
onChange={(e) => {
|
||||
setConfig({ ...config, [property.name]: e.html });
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<InputText
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name]}
|
||||
setValue={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : property.type === PropertyType.BOOLEAN ? (
|
||||
<InputCheckbox
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name] === "false" ? false : config[property.name] === "true" ? true : config[property.name]}
|
||||
setValue={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
/>
|
||||
) : property.type === PropertyType.DATE ? (
|
||||
<InputDate
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name]}
|
||||
onChange={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
/>
|
||||
) : property.type === PropertyType.NUMBER ? (
|
||||
<InputNumber
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name]}
|
||||
setValue={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
/>
|
||||
) : property.type === PropertyType.SELECT ? (
|
||||
<InputSelector
|
||||
name={property.name}
|
||||
title={t(property.title)}
|
||||
value={config[property.name]}
|
||||
setValue={(e) => setConfig({ ...config, [property.name]: e })}
|
||||
options={property.options}
|
||||
/>
|
||||
) : (
|
||||
<div>{t("models.entityTemplate.errors.unsupportedPropertyType", { type: PropertyType[property.type] })}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Property } from "@toolctrl/db/prisma-browser";
|
||||
import clsx from "clsx";
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useSubmit } from "react-router";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import ButtonTertiary from "../../ui/buttons/ButtonTertiary";
|
||||
import LockClosedIcon from "../../ui/icons/LockClosedIcon";
|
||||
import NewFieldIcon from "../../ui/icons/NewFieldIcon";
|
||||
import PencilIcon from "../../ui/icons/PencilIcon";
|
||||
import TrashIcon from "../../ui/icons/TrashIcon";
|
||||
import ConfirmModal, { RefConfirmModal } from "../../ui/modals/ConfirmModal";
|
||||
import PropertyBadge from "./PropertyBadge";
|
||||
import OrderListButtons from "../../ui/sort/OrderListButtons";
|
||||
import { defaultDisplayProperties } from "~/utils/helpers/PropertyHelper";
|
||||
import EyeIcon from "~/components/ui/icons/EyeIcon";
|
||||
import EyeLashIcon from "~/components/ui/icons/EyeLashIcon";
|
||||
import DocumentDuplicateIconFilled from "~/components/ui/icons/DocumentDuplicateIconFilled";
|
||||
|
||||
interface Props {
|
||||
items: PropertyWithDetails[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function PropertiesList({ items, className }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const [showDefaultFields, setShowDefaultFields] = useState(false);
|
||||
|
||||
function deleteField(item: Property) {
|
||||
confirmDelete.current?.setValue(item);
|
||||
confirmDelete.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function confirmedDelete(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete");
|
||||
form.set("id", item.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function onToggleDisplay(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "toggle-display");
|
||||
form.set("id", item.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function onDuplicate(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "duplicate");
|
||||
form.set("id", item.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={clsx(className, "")}>
|
||||
<div className="space-y-2">
|
||||
{showDefaultFields && (
|
||||
<div className="mb-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium">{t("models.property.defaultProperties.title")}</h3>
|
||||
{showDefaultFields && (
|
||||
<div className="flex justify-end">
|
||||
<ButtonTertiary className="-my-1" onClick={() => setShowDefaultFields(!showDefaultFields)}>
|
||||
{t("models.property.defaultProperties.hide")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{defaultDisplayProperties.map((item, idx) => {
|
||||
return (
|
||||
<div key={idx} className="border-border bg-secondary/90 rounded-md border px-4 py-2 shadow-2xs">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex items-center space-x-2">
|
||||
<LockClosedIcon className="h-4 w-4 text-gray-300" />
|
||||
{/* <PropertyBadge className="h-4 w-4 text-muted-foreground" /> */}
|
||||
{/* <div className="truncate text-sm text-muted-foreground">{t("entities.fields." + PropertyType[item.type])}</div> */}
|
||||
</div>
|
||||
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{/* <PropertyTitle item={item} /> */}
|
||||
<div className="flex flex-col">
|
||||
<div>{t(item.title)}</div>
|
||||
<div className="text-muted-foreground text-xs">{item.name}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium">{t("models.property.plural")}</h3>
|
||||
{!showDefaultFields && (
|
||||
<div className="flex justify-end">
|
||||
<ButtonTertiary className="-my-1" onClick={() => setShowDefaultFields(!showDefaultFields)}>
|
||||
{t("models.property.defaultProperties.show")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{items
|
||||
.filter((f) => !f.isDefault)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((item, idx) => {
|
||||
return (
|
||||
<div key={idx} className="border-border bg-background rounded-md border px-4 py-1 shadow-2xs">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2 truncate">
|
||||
<div className="flex items-center space-x-3 truncate">
|
||||
<div className="hidden shrink-0 sm:flex">
|
||||
<OrderListButtons index={idx} items={items.filter((f) => !f.isDefault)} editable={true} />
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<PropertyBadge type={item.type} className="text-muted-foreground h-4 w-4" />
|
||||
</div>
|
||||
<div className="text-foreground flex items-center space-x-2 truncate text-sm">
|
||||
<PropertyTitle item={item} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 space-x-1">
|
||||
<div className="flex items-center space-x-1 truncate p-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onToggleDisplay(item)}
|
||||
aria-label={t(item.isDisplay ? "shared.hide" : "shared.show")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden"
|
||||
>
|
||||
{item.isDisplay ? (
|
||||
<EyeIcon className="text-muted-foreground hover:text-muted-foreground h-4 w-4" />
|
||||
) : (
|
||||
<EyeLashIcon className="hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
)}
|
||||
</button>
|
||||
<Link
|
||||
to={item.id}
|
||||
aria-label={t("shared.edit")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden"
|
||||
preventScrollReset
|
||||
// onClick={() => update(idx, item)}
|
||||
>
|
||||
<PencilIcon className="group-hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDuplicate(item)}
|
||||
aria-label={t("shared.duplicate")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden"
|
||||
>
|
||||
<DocumentDuplicateIconFilled className="hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("shared.delete")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden"
|
||||
onClick={() => deleteField(item)}
|
||||
>
|
||||
<TrashIcon className="group-hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<Link
|
||||
to={`new`}
|
||||
className="focus:ring-ring border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed px-12 py-6 text-center focus:ring-2 focus:ring-offset-2 focus:outline-hidden"
|
||||
preventScrollReset
|
||||
>
|
||||
<NewFieldIcon className="text-muted-foreground mx-auto h-8" />
|
||||
<span className="text-foreground mt-2 block text-sm font-medium">{t("models.property.actions.add")}</span>
|
||||
</Link>
|
||||
</div>
|
||||
{/* <PropertyForm ref={propertyForm} entityId={entityId} onCreated={created} onUpdated={updated} onDeleted={deleted} /> */}
|
||||
<ConfirmModal ref={confirmDelete} destructive onYes={confirmedDelete} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const PropertyTitle = ({ item }: { item: PropertyWithDetails }) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-baseline space-x-1 truncate">
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
{t(EntityHelper.getFieldTitle(item, item.isDefault))}
|
||||
{item.isRequired && <span className="text-red-500">*</span>}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{item.name}
|
||||
{item.subtype === "phone" && " (phone)"}
|
||||
{item.subtype === "url" && " (URL)"}
|
||||
{[PropertyType.MULTI_SELECT, PropertyType.SELECT].includes(item.type) && "[]"}
|
||||
{[PropertyType.RANGE_NUMBER, PropertyType.RANGE_DATE].includes(item.type) && ` (${t("models.property.badges.range")})`}
|
||||
{[PropertyType.FORMULA].includes(item.type) && ` (${t("models.property.badges.formula")})`}
|
||||
</div>
|
||||
</div>
|
||||
{/* {item.type === PropertyType.FORMULA && <div className="truncate italic text-muted-foreground">({item.formula})</div>} */}
|
||||
{[PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(item.type) && (
|
||||
<div className="text-muted-foreground truncate text-xs">
|
||||
[
|
||||
{item.options.length === 0
|
||||
? t("models.property.noOptions")
|
||||
: t("models.property.optionsSummary", { options: item.options?.map((f) => f.value).join(", ") })}
|
||||
]
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.attributes.filter((f) => f.value).length > 0 && (
|
||||
<div className="text-muted-foreground truncate text-xs">
|
||||
[
|
||||
{item.attributes
|
||||
.filter((f) => f.value)
|
||||
.map((f) => `${f.name}: ${f.value}`)
|
||||
.join(", ")}
|
||||
]
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
|
||||
interface Props {
|
||||
name: PropertyAttributeName;
|
||||
title: string;
|
||||
value: string | undefined;
|
||||
setValue: React.Dispatch<React.SetStateAction<string | undefined>>;
|
||||
className?: string;
|
||||
}
|
||||
export default function PropertyAttribute({ name, title, value, setValue, className }: Props) {
|
||||
const { t } = useTranslation();
|
||||
function isNumber() {
|
||||
return [
|
||||
PropertyAttributeName.Min,
|
||||
PropertyAttributeName.Max,
|
||||
PropertyAttributeName.MaxSize,
|
||||
PropertyAttributeName.Rows,
|
||||
PropertyAttributeName.Columns,
|
||||
].includes(name);
|
||||
}
|
||||
function isBoolean() {
|
||||
return [PropertyAttributeName.Uppercase, PropertyAttributeName.Lowercase, PropertyAttributeName.Password].includes(name);
|
||||
}
|
||||
function isSelector() {
|
||||
return PropertyAttributeHelper.getPropertyAttributeOptions(name, t).length > 0;
|
||||
}
|
||||
function getPlaceholder() {
|
||||
if (name === PropertyAttributeName.Step) {
|
||||
return "0.01";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
function getDescription() {
|
||||
if (name === PropertyAttributeName.Uppercase) {
|
||||
return t("models.entity.propertyAttributes.descriptions.uppercase");
|
||||
} else if (name === PropertyAttributeName.Lowercase) {
|
||||
return t("models.entity.propertyAttributes.descriptions.lowercase");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{isNumber() ? (
|
||||
<InputNumber
|
||||
className={className}
|
||||
name={name}
|
||||
title={title}
|
||||
value={Number(value)}
|
||||
setValue={(e) => setValue(e?.toString())}
|
||||
max={name === PropertyAttributeName.Columns ? 12 : undefined}
|
||||
hint={
|
||||
<>
|
||||
{value && (
|
||||
<button type="button" onClick={() => setValue("")} className="text-muted-foreground text-xs hover:text-red-500">
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
) : isBoolean() ? (
|
||||
<InputCheckboxWithDescription
|
||||
className={className}
|
||||
description={getDescription()}
|
||||
name={name}
|
||||
title={title}
|
||||
value={value === "true" ? true : false}
|
||||
setValue={(e) => setValue(e ? (Boolean(e) === true ? "true" : "false") : "false")}
|
||||
/>
|
||||
) : isSelector() ? (
|
||||
<InputSelector
|
||||
className={className}
|
||||
withSearch={false}
|
||||
name={name}
|
||||
title={title}
|
||||
value={value}
|
||||
setValue={(e) => setValue(e?.toString())}
|
||||
options={PropertyAttributeHelper.getPropertyAttributeOptions(name, t)}
|
||||
hint={
|
||||
<>
|
||||
{value && (
|
||||
<button type="button" onClick={() => setValue("")} className="text-muted-foreground text-xs hover:text-red-500">
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
></InputSelector>
|
||||
) : (
|
||||
<InputText
|
||||
className={className}
|
||||
name={name}
|
||||
title={title}
|
||||
value={value}
|
||||
setValue={(e) => setValue(e.toString())}
|
||||
placeholder={getPlaceholder()}
|
||||
hint={
|
||||
<>
|
||||
{value && (
|
||||
<button type="button" onClick={() => setValue("")} className="text-muted-foreground text-xs hover:text-red-500">
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import clsx from "clsx";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import SimpleBadge from "../../ui/badges/SimpleBadge";
|
||||
import PaperClipIcon from "../../ui/icons/PaperClipIcon";
|
||||
import ExperimentIconFilled from "~/components/ui/icons/tests/ExperimentIconFilled";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
type: PropertyType;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function PropertyBadge({ title, type, className }: Props) {
|
||||
return (
|
||||
<>
|
||||
{title ? (
|
||||
<SimpleBadge title={title} color={Colors.ORANGE} />
|
||||
) : [PropertyType.NUMBER, PropertyType.RANGE_NUMBER].includes(type) ? (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className={clsx(className, "h-5 w-5 shrink-0")} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
) : [PropertyType.DATE, PropertyType.RANGE_DATE].includes(type) ? (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className={clsx(className, "h-5 w-5 shrink-0")} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
) : type === PropertyType.TEXT ? (
|
||||
<svg
|
||||
className={clsx(className, "h-5 w-5 shrink-0")}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 172 172"
|
||||
fill="currentColor"
|
||||
>
|
||||
<g
|
||||
fill="none"
|
||||
fillRule="nonzero"
|
||||
stroke="none"
|
||||
strokeWidth="1"
|
||||
strokeLinecap="butt"
|
||||
strokeLinejoin="miter"
|
||||
strokeMiterlimit="10"
|
||||
strokeDasharray=""
|
||||
strokeDashoffset="0"
|
||||
fontFamily="none"
|
||||
fontWeight="none"
|
||||
fontSize="none"
|
||||
// textAnchor="none"
|
||||
>
|
||||
<path d="M0,172v-172h172v172z" fill="none"></path>
|
||||
<g fill="currentColor">
|
||||
<path d="M146.59473,57.24935c-5.28183,0 -9.90758,1.23715 -13.89941,3.69531c-3.98467,2.451 -7.04629,5.9742 -9.19629,10.56803c-2.14283,4.59384 -3.2194,9.90187 -3.2194,15.92904v3.83528c0,9.44567 2.33353,16.88702 6.9847,22.29785c4.65117,5.41083 11.04261,8.11849 19.16244,8.11849c7.42467,0 13.40816,-1.93175 17.94466,-5.80892c4.5365,-3.87717 7.05009,-9.19203 7.54459,-15.94304v-0.014h-13.03157c-0.29383,3.81983 -1.4442,6.6341 -3.42936,8.45443c-1.98517,1.8275 -4.99348,2.74349 -9.02832,2.74349c-4.46483,0 -7.74101,-1.5573 -9.81218,-4.68913c-2.07117,-3.12467 -3.10742,-8.08556 -3.10742,-14.86523v-4.73112c0.05733,-6.48583 1.16705,-11.2725 3.33138,-14.36133c2.16433,-3.08883 5.40602,-4.63314 9.75618,-4.63314c4.00617,0 6.98784,0.92316 8.94434,2.74349c1.96367,1.82033 3.10686,4.7552 3.42936,8.80436h13.04557c-0.69517,-7.009 -3.27573,-12.4438 -7.74056,-16.32096c-4.46483,-3.87717 -10.36871,-5.82292 -17.67871,-5.82292zM23.58561,58.11719l-23.58561,62.70833h13.88542l4.35319,-12.91959h22.87174l4.40918,12.91959h13.87142l-23.71159,-62.70833zM65.31185,58.11719v62.70833h24.63542c7.19533,-0.05733 12.73058,-1.64195 16.61491,-4.74511c3.8915,-3.10317 5.83691,-7.66229 5.83691,-13.68946c0,-3.53317 -0.94298,-6.52167 -2.81348,-8.95833c-1.8705,-2.43667 -4.43807,-4.06842 -7.68457,-4.87109c2.84517,-1.08933 5.06459,-2.79355 6.66276,-5.13705c1.59816,-2.3435 2.39355,-5.04399 2.39355,-8.11849c0,-5.62583 -1.98539,-9.90478 -5.96289,-12.82161c-3.9775,-2.91683 -9.80692,-4.36719 -17.49675,-4.36719zM78.35742,68.58724h9.1403c3.59767,0 6.2247,0.61465 7.89453,1.86165c1.66983,1.247 2.50553,3.29969 2.50553,6.14486c0,5.08117 -3.29599,7.68189 -9.88216,7.79655h-9.6582zM29.63249,73.96224l7.96452,23.47364h-15.84505zM78.35742,93.5306h11.96777c6.00567,0.086 9.00032,2.99387 9.00032,8.73438c0,2.55133 -0.86235,4.55722 -2.58952,6.00489c-1.72717,1.44767 -4.12016,2.16959 -7.19466,2.16959h-11.18392z"></path>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
) : type === PropertyType.BOOLEAN ? (
|
||||
<CheckIcon className={clsx(className, "h-5 w-5 shrink-0")} />
|
||||
) : type === PropertyType.SELECT || type === PropertyType.MULTI_SELECT || type === PropertyType.MULTI_TEXT ? (
|
||||
<svg
|
||||
className={clsx(className, "h-5 w-5 shrink-0")}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 172 172"
|
||||
fill="currentColor"
|
||||
>
|
||||
<g
|
||||
fill="none"
|
||||
fillRule="nonzero"
|
||||
stroke="none"
|
||||
strokeWidth="1"
|
||||
strokeLinecap="butt"
|
||||
strokeLinejoin="miter"
|
||||
strokeMiterlimit="10"
|
||||
strokeDasharray=""
|
||||
strokeDashoffset="0"
|
||||
fontFamily="none"
|
||||
fontWeight="none"
|
||||
fontSize="none"
|
||||
// textAnchor="none"
|
||||
>
|
||||
<path d="M0,172v-172h172v172z" fill="none"></path>
|
||||
<g fill="currentColor">
|
||||
<path d="M21.5,43v14.33333h129v-14.33333zM21.5,71.66667v14.33333h129v-14.33333zM21.5,100.33333v14.33333h129v-14.33333zM64.5,129l21.5,21.5l21.5,-21.5z"></path>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
) : type === PropertyType.MEDIA ? (
|
||||
<PaperClipIcon className={clsx(className, "h-5 w-5 shrink-0")} />
|
||||
) : type === PropertyType.FORMULA ? (
|
||||
<ExperimentIconFilled className={clsx(className, "h-5 w-5 shrink-0")} />
|
||||
) : (
|
||||
<div></div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import PencilAltIcon from "~/components/ui/icons/PencilAltIcon";
|
||||
import ViewListIcon from "~/components/ui/icons/ViewListIcon";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { PropertyWithDetails, EntitySimple } from "~/utils/db/entities/entities.db.server";
|
||||
import StringUtils from "~/utils/shared/StringUtils";
|
||||
import PropertyTypeSelector from "./PropertyTypeSelector";
|
||||
import PropertyOptionsForm, { OptionValue, RefPropertyOptionsForm } from "./PropertyOptionsForm";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
import PropertyAttribute from "./PropertyAttribute";
|
||||
import PropertySubtypeSelector from "./PropertySubtypeSelector";
|
||||
import PropertyFormulaSelector from "./PropertyFormulaSelector";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import { Link } from "react-router";
|
||||
|
||||
interface Props {
|
||||
item?: PropertyWithDetails;
|
||||
properties: PropertyWithDetails[];
|
||||
entities: EntitySimple[];
|
||||
formulas: FormulaDto[];
|
||||
formulaListPath?: string;
|
||||
formulaDetailsPath?: (formulaId: string) => string;
|
||||
}
|
||||
|
||||
export default function PropertyForm({ item, properties, formulas, formulaListPath, formulaDetailsPath }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const selectOptionsForm = useRef<RefPropertyOptionsForm>(null);
|
||||
|
||||
const [showAdvancedOptions, setShowAdvancedOptions] = useState(true);
|
||||
|
||||
const [order, setOrder] = useState<number | undefined>(item?.order ?? Math.max(...properties.map((o) => o.order)) + 1);
|
||||
const [name, setName] = useState<string>(item?.name ?? "");
|
||||
const [title, setTitle] = useState<string>(item?.title ?? "");
|
||||
const [type, setType] = useState<PropertyType>(item?.type ?? PropertyType.TEXT);
|
||||
const [subtype, setSubtype] = useState<string>(item?.subtype ?? "");
|
||||
const [formulaId, setFormulaId] = useState(item?.formulaId ?? undefined);
|
||||
const [options, setOptions] = useState<OptionValue[]>(
|
||||
item?.options?.map((o) => {
|
||||
return {
|
||||
id: o.id,
|
||||
order: o.order,
|
||||
value: o.value,
|
||||
name: o.name,
|
||||
color: o.color,
|
||||
};
|
||||
}) ?? []
|
||||
);
|
||||
const [isRequired, setIsRequired] = useState<boolean>(item?.isRequired ?? true);
|
||||
const [showInCreate, setShowInCreate] = useState<boolean>(item?.showInCreate ?? true);
|
||||
const [isHidden, setIsHidden] = useState<boolean>(item?.isHidden ?? false);
|
||||
const [isDisplay, setIsDisplay] = useState<boolean>(item?.isDisplay ?? properties.filter((f) => !f.isDefault).length === 0);
|
||||
const [isReadOnly, setIsReadOnly] = useState<boolean>(item?.isReadOnly ?? false);
|
||||
const [canUpdate, setCanUpdate] = useState<boolean>(item ? item.canUpdate : true);
|
||||
const [attributes, setAttributes] = useState<{ name: string; value: string | undefined }[]>(item?.attributes ?? []);
|
||||
|
||||
// const [formula, setFormula] = useState<string>();
|
||||
|
||||
const [titleEnabled, setTitleEnabled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!item) {
|
||||
if (title.includes(".")) {
|
||||
const keys = title.split(".");
|
||||
setName(StringUtils.toCamelCase(keys[keys.length - 1].toLowerCase()));
|
||||
} else {
|
||||
setName(StringUtils.toCamelCase(title.toLowerCase()));
|
||||
}
|
||||
}
|
||||
}, [item, title, type]);
|
||||
|
||||
useEffect(() => {
|
||||
const formula = formulas.find((f) => f.id === formulaId);
|
||||
if (!item && formula) {
|
||||
setTitle(formula.name);
|
||||
setName(StringUtils.toCamelCase(formula.name.toLowerCase()));
|
||||
}
|
||||
}, [item, formulaId, formulas]);
|
||||
|
||||
useEffect(() => {
|
||||
setTitleEnabled(true);
|
||||
if (!item) {
|
||||
if (type === PropertyType.TEXT) {
|
||||
setSubtype("singleLine");
|
||||
} else if (type === PropertyType.SELECT) {
|
||||
setSubtype("dropdown");
|
||||
} else if (type === PropertyType.MULTI_SELECT) {
|
||||
setSubtype("combobox");
|
||||
} else {
|
||||
// setSubtype("");
|
||||
}
|
||||
} else {
|
||||
if (type === PropertyType.TEXT) {
|
||||
if (!subtype || !["singleLine", "email", "phone", "url"].includes(subtype)) {
|
||||
setSubtype("singleLine");
|
||||
}
|
||||
} else if (type === PropertyType.SELECT) {
|
||||
if (!subtype || !["dropdown", "radioGroupCards"].includes(subtype)) {
|
||||
setSubtype("dropdown");
|
||||
}
|
||||
} else if (type === PropertyType.MULTI_SELECT) {
|
||||
if (!subtype || !["combobox", "checkboxCards"].includes(subtype)) {
|
||||
setSubtype("combobox");
|
||||
}
|
||||
} else {
|
||||
// setSubtype("");
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [item, type]);
|
||||
|
||||
useEffect(() => {
|
||||
if (type === PropertyType.FORMULA) {
|
||||
setShowAdvancedOptions(false);
|
||||
setIsRequired(false);
|
||||
setIsReadOnly(true);
|
||||
setShowInCreate(false);
|
||||
}
|
||||
}, [type]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<FormGroup
|
||||
id={item?.id}
|
||||
editing={true}
|
||||
canDelete={item !== undefined && !item?.isDefault && showAdvancedOptions}
|
||||
className="space-y-2 pb-4"
|
||||
classNameFooter="px-4"
|
||||
>
|
||||
<input type="hidden" name="order" value={order} hidden readOnly />
|
||||
|
||||
<div className="mt-4">
|
||||
<div className="space-y-3 px-4">
|
||||
<div className="w-full">
|
||||
<label htmlFor="type" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.type")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<PropertyTypeSelector selected={type} onSelected={(e) => setType(e)} />
|
||||
</div>
|
||||
</div>
|
||||
{type === PropertyType.TEXT && (
|
||||
<div>
|
||||
<label htmlFor="subtype" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.subtype")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<PropertySubtypeSelector types={["singleLine", "email", "phone", "url"]} selected={subtype} onSelected={(e) => setSubtype(e)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{type === PropertyType.SELECT && (
|
||||
<div>
|
||||
<label htmlFor="subtype" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.subtype")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<PropertySubtypeSelector types={["dropdown", "radioGroupCards"]} selected={subtype} onSelected={(e) => setSubtype(e)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{type === PropertyType.MULTI_SELECT && (
|
||||
<div>
|
||||
<label htmlFor="subtype" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.subtype")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<PropertySubtypeSelector types={["combobox", "checkboxCards"]} selected={subtype} onSelected={(e) => setSubtype(e)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{type === PropertyType.FORMULA && (
|
||||
<div>
|
||||
<div className="flex justify-between space-x-2">
|
||||
<label htmlFor="formula" className="text-foreground/80 block text-xs font-medium">
|
||||
{t("models.property.formula")}
|
||||
</label>
|
||||
{item?.formulaId && formulaDetailsPath ? (
|
||||
<Link to={formulaDetailsPath(item.formulaId)} className="text-xs text-blue-500 hover:underline">
|
||||
{t("models.property.goToFormula")}
|
||||
</Link>
|
||||
) : formulaListPath ? (
|
||||
<Link to={formulaListPath} className="text-xs text-blue-500 hover:underline">
|
||||
{t("models.property.viewFormulas")}
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
<PropertyFormulaSelector name="formula-id" items={formulas} selected={formulaId} onSelected={(e) => setFormulaId(e)} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{titleEnabled && (
|
||||
<InputText
|
||||
name="title"
|
||||
title={t("models.property.title")}
|
||||
value={title}
|
||||
setValue={(e) => setTitle(e)}
|
||||
disabled={!titleEnabled}
|
||||
required
|
||||
withTranslation
|
||||
placeholder={t("models.property.form.placeholders.title")}
|
||||
autoFocus
|
||||
/>
|
||||
)}
|
||||
<InputText
|
||||
name="name"
|
||||
title={t("models.property.name")}
|
||||
value={name}
|
||||
setValue={(e) => setName(e)}
|
||||
required
|
||||
placeholder={t("models.property.form.placeholders.name")}
|
||||
pattern="[a-z]+((\d)|([A-Z0-9][a-z0-9]+))*([A-Z])?"
|
||||
hint={<span className="text-muted-foreground font-normal italic">{t("models.property.form.hints.camelCase")}</span>}
|
||||
/>
|
||||
|
||||
<div className="border-border w-full rounded-md border border-dotted px-2 py-0">
|
||||
<InputCheckboxWithDescription
|
||||
name="is-display"
|
||||
title={t("models.property.isDisplay")}
|
||||
description={t("models.property.form.descriptions.isDisplay")}
|
||||
value={isDisplay}
|
||||
setValue={setIsDisplay}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* {type === PropertyType.FORMULA && (
|
||||
<div className="w-full">
|
||||
<label htmlFor="formula" className="block text-xs font-medium text-foreground/80">
|
||||
{t("entities.fields.FORMULA")}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<InputText
|
||||
name="formula"
|
||||
title={t("models.property.formula")}
|
||||
value={formula}
|
||||
setValue={(e) => setFormula(e.toString())}
|
||||
disabled={!titleEnabled}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)} */}
|
||||
{[PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(type) && (
|
||||
<div className="w-full">
|
||||
<label htmlFor="property-options-display" className="text-foreground/80 block text-sm font-medium">
|
||||
{t("models.property.options")}
|
||||
</label>
|
||||
<div className="mt-1 flex rounded-md shadow-2xs">
|
||||
<div className="relative flex grow items-stretch focus-within:z-10">
|
||||
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
|
||||
<ViewListIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
</div>
|
||||
{options.map((option) => {
|
||||
return <input key={option.order} hidden readOnly type="text" id="options[]" name="options[]" value={JSON.stringify(option)} />;
|
||||
})}
|
||||
<input
|
||||
id="property-options-display"
|
||||
disabled
|
||||
className="focus:border-border focus:ring-ring border-border text-foreground bg-secondary/90 block w-full rounded-none rounded-l-md border pl-10 sm:text-sm"
|
||||
value={options.length === 0 ? t("models.property.form.noDropdownValues") : options.map((f) => f.value).join(", ")}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => selectOptionsForm.current?.set(options)}
|
||||
className="focus:border-border focus:ring-ring border-border bg-secondary hover:bg-secondary/90 text-foreground/80 relative -ml-px inline-flex items-center space-x-2 rounded-r-md border px-4 py-1.5 text-sm font-medium focus:outline-hidden focus:ring-1"
|
||||
>
|
||||
<PencilAltIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
<span>{t("models.property.form.setOptions")}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex">
|
||||
<ButtonTertiary onClick={() => setShowAdvancedOptions(!showAdvancedOptions)}>
|
||||
{!showAdvancedOptions ? t("models.property.form.showAdvancedOptions") : t("models.property.form.hideAdvancedOptions")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={clsx("border-border bg-secondary my-2 space-y-3 border border-dashed px-4 py-3", showAdvancedOptions ? "" : "hidden")}>
|
||||
<div className="w-full">
|
||||
<InputNumber name="order" title={t("models.property.order")} value={order} setValue={setOrder} />
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="show-in-create"
|
||||
title={t("models.property.showInCreate")}
|
||||
description={t("models.property.form.descriptions.showInCreate")}
|
||||
value={showInCreate}
|
||||
setValue={setShowInCreate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="is-required"
|
||||
title={t("models.property.isRequired")}
|
||||
description={t("models.property.form.descriptions.isRequired")}
|
||||
value={isRequired}
|
||||
setValue={setIsRequired}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="is-hidden"
|
||||
title={t("models.property.isHidden")}
|
||||
description={t("models.property.form.descriptions.isHidden")}
|
||||
value={isHidden}
|
||||
setValue={setIsHidden}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="is-read-only"
|
||||
title={t("models.property.isReadOnly")}
|
||||
description={t("models.property.form.descriptions.isReadOnly")}
|
||||
value={isReadOnly}
|
||||
setValue={setIsReadOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="w-full">
|
||||
<InputCheckboxWithDescription
|
||||
name="can-update"
|
||||
title={t("models.property.canUpdate")}
|
||||
description={t("models.property.form.descriptions.canUpdate")}
|
||||
value={canUpdate}
|
||||
setValue={setCanUpdate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* <div className="font-bold">{t("models.propertyAttribute.plural")}</div> */}
|
||||
|
||||
{attributes.map((attribute) => {
|
||||
return <input key={attribute.name} hidden readOnly type="text" id="attributes[]" name="attributes[]" value={JSON.stringify(attribute)} />;
|
||||
})}
|
||||
|
||||
{PropertyAttributeHelper.getAttributesByType(type, attributes).map((item) => {
|
||||
return (
|
||||
<PropertyAttribute
|
||||
className="mb-2"
|
||||
key={item}
|
||||
name={item}
|
||||
title={PropertyAttributeHelper.getAttributeTitle(t, item)}
|
||||
value={attributes.find((f) => f.name === item)?.value ?? undefined}
|
||||
setValue={(e) => {
|
||||
const value = { name: item, value: e?.toString() };
|
||||
const found = attributes.find((f) => f.name === item);
|
||||
if (found) {
|
||||
setAttributes([...attributes.filter((f) => f.name !== item), value]);
|
||||
} else {
|
||||
setAttributes([...attributes, value]);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</FormGroup>
|
||||
<PropertyOptionsForm ref={selectOptionsForm} title={title} onSet={(e) => setOptions(e)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import { Fragment } from "react";
|
||||
import { Listbox, Transition } from "@headlessui/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import clsx from "clsx";
|
||||
import SelectorIcon from "../../ui/icons/SelectorIcon";
|
||||
import CheckIcon from "../../ui/icons/CheckIcon";
|
||||
import { FormulaDto } from "~/modules/formulas/dtos/FormulaDto";
|
||||
// import PropertySubtypeBadge from "./PropertySubtypeBadge";
|
||||
|
||||
interface Props {
|
||||
name: string;
|
||||
items: FormulaDto[];
|
||||
className?: string;
|
||||
selected: string | undefined;
|
||||
onSelected: (item: string) => void;
|
||||
}
|
||||
|
||||
export default function PropertyFormulaSelector({ name, items, className, selected, onSelected }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Listbox name={name} value={selected} onChange={onSelected}>
|
||||
{({ open }) => (
|
||||
<>
|
||||
<input type="hidden" name="subtype" value={selected} hidden readOnly />
|
||||
<div className={clsx("relative", className)}>
|
||||
<Listbox.Button className="focus:border-border focus:ring-ring border-border text-foreground bg-background relative w-full cursor-default rounded-md border py-2 pl-3 pr-10 text-left shadow-2xs focus:outline-hidden focus:ring-1 sm:text-sm">
|
||||
{selected ? (
|
||||
<div className="flex items-center space-x-2">
|
||||
{/* <PropertySubtypeBadge subtype={selected} className="h-4 w-4 text-muted-foreground" /> */}
|
||||
<div className="truncate">{items.find((item) => item.id === selected)?.name}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground">{t("shared.select")}...</div>
|
||||
)}
|
||||
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
|
||||
<SelectorIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
</Listbox.Button>
|
||||
|
||||
<Transition show={open} as={Fragment} leave="transition ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0">
|
||||
<Listbox.Options className="border-border bg-background absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border py-1 text-base shadow-lg focus:outline-hidden sm:text-sm">
|
||||
{items.length === 0 ? (
|
||||
<div className=" flex select-none justify-center p-2 text-red-500">{t("models.property.selectors.noFormulas")}</div>
|
||||
) : (
|
||||
<>
|
||||
{items.map((item, idx) => (
|
||||
<Listbox.Option
|
||||
key={idx}
|
||||
className={({ active }) =>
|
||||
clsx(active ? " bg-secondary " : "", "hover:bg-secondary relative cursor-default select-none py-2 pl-3 pr-9")
|
||||
}
|
||||
value={item.id}
|
||||
>
|
||||
{({ selected, active }) => (
|
||||
<>
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="truncate">{item.name}</div>
|
||||
</div>
|
||||
{selected ? (
|
||||
<span className={clsx(active ? "" : "", "absolute inset-y-0 right-0 flex items-center pr-4")}>
|
||||
<CheckIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Listbox.Option>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Listbox.Options>
|
||||
</Transition>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Listbox>
|
||||
);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { DateFormatType } from "~/utils/shared/DateUtils";
|
||||
import { NumberFormatType } from "~/utils/shared/NumberUtils";
|
||||
import RowNumberCell from "../rows/cells/RowNumberCell";
|
||||
import RowDateCell from "../rows/cells/RowDateCell";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { FormulaValueType } from "~/modules/formulas/dtos/FormulaDto";
|
||||
import { BooleanFormatType } from "~/utils/shared/BooleanUtils";
|
||||
import RowBooleanCell from "../rows/cells/RowBooleanCell";
|
||||
|
||||
interface Props {
|
||||
property: PropertyWithDetails;
|
||||
value: FormulaValueType;
|
||||
}
|
||||
export default function PropertyFormulaValueBadge({ property, value }: Props) {
|
||||
const getNumberFormat = () => {
|
||||
return property.attributes.find((f) => f.name === PropertyAttributeName.FormatNumber)?.value as NumberFormatType;
|
||||
};
|
||||
const getBooleanFormat = () => {
|
||||
return property.attributes.find((f) => f.name === PropertyAttributeName.FormatBoolean)?.value as BooleanFormatType;
|
||||
};
|
||||
const getDateFormat = () => {
|
||||
return property.attributes.find((f) => f.name === PropertyAttributeName.FormatDate)?.value as DateFormatType;
|
||||
};
|
||||
return (
|
||||
<div className="flex space-x-1">
|
||||
{/* <div>
|
||||
<div>[resultAs:{property.formula?.resultAs}]</div>
|
||||
<div>[calculationTrigger:{property.formula?.calculationTrigger}]</div>
|
||||
<div>value: {JSON.stringify(value)}</div>
|
||||
</div> */}
|
||||
{property.formula?.resultAs === "number" ? (
|
||||
<RowNumberCell value={Number(value) ?? undefined} format={getNumberFormat()} />
|
||||
) : property.formula?.resultAs === "boolean" ? (
|
||||
<RowBooleanCell value={Boolean(value) ?? undefined} format={getBooleanFormat()} />
|
||||
) : property.formula?.resultAs === "date" ? (
|
||||
<RowDateCell value={value ? (value as Date) : undefined} format={getDateFormat()} />
|
||||
) : (
|
||||
<div>{value?.toString()}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { ReactNode, useEffect, useState } from "react";
|
||||
import InputCombobox from "~/components/ui/input/InputCombobox";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import InputCheckboxCards from "~/components/ui/input/InputCheckboxCards";
|
||||
|
||||
interface Props {
|
||||
name: string;
|
||||
title: string;
|
||||
options: { value: string; name: string | null; color: number }[];
|
||||
subtype?: "combobox" | "checkboxCards";
|
||||
required?: boolean;
|
||||
disabled?: boolean;
|
||||
value?: RowValueMultipleDto[];
|
||||
onSelected?: (item: RowValueMultipleDto[]) => void;
|
||||
hint?: ReactNode;
|
||||
help?: string;
|
||||
icon?: string;
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
const PropertyMultiSelector = ({ name, title, options, subtype, disabled, value, onSelected, required }: Props) => {
|
||||
const [actualValue, setActualValue] = useState<(string | number)[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const selection = value?.map((f) => f.value) ?? [];
|
||||
if (selection.sort().join(",") !== actualValue.sort().join(",")) {
|
||||
setActualValue(selection);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [value]);
|
||||
|
||||
useEffect(() => {
|
||||
// onSelected(actualValue);
|
||||
}, [actualValue, onSelected]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* actualValue: {JSON.stringify(actualValue)} */}
|
||||
{!subtype || subtype === "combobox" ? (
|
||||
<InputCombobox
|
||||
name={name}
|
||||
title={title}
|
||||
value={actualValue}
|
||||
onChange={setActualValue}
|
||||
options={options}
|
||||
disabled={disabled}
|
||||
withSearch={false}
|
||||
withLabel={true}
|
||||
required={required}
|
||||
/>
|
||||
) : subtype === "checkboxCards" ? (
|
||||
<InputCheckboxCards
|
||||
name={name}
|
||||
title={title}
|
||||
value={actualValue}
|
||||
onChange={setActualValue}
|
||||
options={options.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: f.name ?? f.value,
|
||||
};
|
||||
})}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
/>
|
||||
) : null}
|
||||
{actualValue?.map((item, idx) => {
|
||||
return (
|
||||
<input
|
||||
key={idx}
|
||||
type="hidden"
|
||||
name={name + `[]`}
|
||||
value={JSON.stringify({
|
||||
value: item,
|
||||
order: idx,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PropertyMultiSelector;
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import { translateSelectOptionLabel } from "~/utils/i18n/translateLabel";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type OptionDto = { value: string; name: string | null };
|
||||
|
||||
interface Props {
|
||||
values: RowValueMultipleDto[] | null;
|
||||
options?: OptionDto[];
|
||||
entityName?: string;
|
||||
propertyName?: string;
|
||||
}
|
||||
export default function PropertyMultipleValueBadge({ values, options, entityName, propertyName }: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
function getSelectedNames() {
|
||||
let names: string[] = [];
|
||||
if (values) {
|
||||
for (const value of values) {
|
||||
const option = options?.find((f) => f.value === value.value);
|
||||
if (option && entityName && propertyName) {
|
||||
names.push(translateSelectOptionLabel(t, i18n, entityName, propertyName, option));
|
||||
} else {
|
||||
names.push(option?.name ?? value.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
return (
|
||||
<div className="flex space-x-1">
|
||||
{getSelectedNames().join(", ") ?? <span className="text-gray-300"></span>}
|
||||
{/* {values?.map((value) => {
|
||||
return (
|
||||
<div
|
||||
key={value.id}
|
||||
className="relative mx-0.5 inline-flex max-w-sm shrink-0 select-none items-center space-x-0.5 overflow-x-auto rounded-full border border-border bg-secondary px-2 py-0.5"
|
||||
>
|
||||
<div className="text-xs font-medium text-muted-foreground">{value.value}</div>
|
||||
</div>
|
||||
);
|
||||
})} */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import RowSelectedOptionCell from "../rows/cells/RowSelectedOptionCell";
|
||||
import { SelectOptionsDisplay } from "~/utils/shared/SelectOptionsUtils";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
property: string;
|
||||
value: string;
|
||||
display: SelectOptionsDisplay;
|
||||
}
|
||||
export default function PropertyOptionValueBadge({ entity, property, value, display }: Props) {
|
||||
return (
|
||||
<RowSelectedOptionCell
|
||||
value={value}
|
||||
options={entity.properties.find((f) => f.name === property)?.options ?? []}
|
||||
display={display}
|
||||
entityName={entity.name}
|
||||
propertyName={property}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { Ref, useImperativeHandle, useRef, useState, forwardRef, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import TrashIcon from "~/components/ui/icons/TrashIcon";
|
||||
import InputCheckboxInline from "~/components/ui/input/InputCheckboxInline";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { getColors } from "~/utils/shared/ColorUtils";
|
||||
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
|
||||
|
||||
export type OptionValue = {
|
||||
id?: string | null;
|
||||
parentId?: string | null;
|
||||
order: number;
|
||||
value: string;
|
||||
name: string | null;
|
||||
color?: Colors;
|
||||
options?: OptionValue[];
|
||||
};
|
||||
export interface RefPropertyOptionsForm {
|
||||
set: (options: OptionValue[]) => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
onSet: (items: OptionValue[]) => void;
|
||||
}
|
||||
|
||||
const PropertyOptionsForm = ({ title, onSet }: Props, ref: Ref<RefPropertyOptionsForm>) => {
|
||||
useImperativeHandle(ref, () => ({ set }));
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
|
||||
const inputOption = useRef<RefInputText>(null);
|
||||
|
||||
const [withColors, setWithColors] = useState(false);
|
||||
const [withDescriptions, setWithDescriptions] = useState(false);
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [items, setItems] = useState<OptionValue[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!withDescriptions) {
|
||||
setItems((items) => items.map((f) => ({ ...f, name: null })));
|
||||
}
|
||||
}, [withDescriptions]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!withColors) {
|
||||
setItems((items) => items.map((f) => ({ ...f, color: undefined })));
|
||||
}
|
||||
}, [withColors]);
|
||||
|
||||
function set(options: OptionValue[]) {
|
||||
setItems(options);
|
||||
if (options.length === 0 && items.length === 0) {
|
||||
addOption();
|
||||
}
|
||||
setWithColors(options.some((f) => f.color));
|
||||
setWithDescriptions(options.some((f) => f.name));
|
||||
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
function close() {
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
function save() {
|
||||
const emptyItems = items.filter((f) => !f.value || f.value.trim() === "");
|
||||
if (emptyItems.length > 0) {
|
||||
errorModal.current?.show(t("entities.errors.selectOptionCannotBeEmpty"));
|
||||
return;
|
||||
}
|
||||
onSet(items);
|
||||
close();
|
||||
}
|
||||
|
||||
function addOption() {
|
||||
const maxOrder = items.length === 0 ? 1 : Math.max(...items.map((o) => o.order));
|
||||
setItems([
|
||||
...items,
|
||||
{
|
||||
id: null,
|
||||
parentId: null,
|
||||
order: maxOrder + 1,
|
||||
value: "",
|
||||
name: null,
|
||||
color: Colors.UNDEFINED,
|
||||
options: [],
|
||||
},
|
||||
]);
|
||||
|
||||
setTimeout(() => {
|
||||
inputOption.current?.input.current?.focus();
|
||||
}, 1);
|
||||
}
|
||||
|
||||
return (
|
||||
<SlideOverWideEmpty title={t("models.property.optionEditor.titleWithProperty", { property: t(title) })} open={open} onClose={() => setOpen(false)}>
|
||||
<div className="">
|
||||
<div>
|
||||
<div className="mt-3 sm:mt-5">
|
||||
<div className="mt-4 space-y-3">
|
||||
<div className="flex space-x-3">
|
||||
<InputCheckboxInline name="with-colors" title={t("models.property.optionEditor.withColors")} description="" value={withColors} setValue={setWithColors} />
|
||||
<InputCheckboxInline
|
||||
name="with-descriptions"
|
||||
title={t("models.property.optionEditor.withDescriptions")}
|
||||
description=""
|
||||
value={withDescriptions}
|
||||
setValue={setWithDescriptions}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-full">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<label htmlFor="select" className="text-foreground/80 block text-sm font-medium">{t("models.property.options")}</label>
|
||||
<div className="flex space-x-2">
|
||||
<ButtonTertiary onClick={addOption}>
|
||||
<div className="-mx-1 text-xs">{t("models.property.optionEditor.add")}</div>
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-border bg-secondary mt-1 space-y-2 rounded-md border-2 border-dashed p-2">
|
||||
{items.map((option, idx) => {
|
||||
return (
|
||||
<div key={option.order} className="mt-1 flex items-center space-x-1 rounded-md">
|
||||
<InputText
|
||||
ref={inputOption}
|
||||
type="text"
|
||||
title="shared.value"
|
||||
withLabel={false}
|
||||
name={"select-option-" + idx}
|
||||
value={option.value}
|
||||
placeholder={t("shared.value")}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(items, setItems, idx, {
|
||||
value: e,
|
||||
})
|
||||
}
|
||||
className="flex-auto"
|
||||
/>
|
||||
|
||||
{withDescriptions && (
|
||||
<InputText
|
||||
type="text"
|
||||
title=""
|
||||
withLabel={false}
|
||||
name={"select-option-name-" + idx}
|
||||
placeholder={t("shared.name")}
|
||||
value={option.name ?? undefined}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(items, setItems, idx, {
|
||||
name: e,
|
||||
})
|
||||
}
|
||||
className="flex-auto"
|
||||
/>
|
||||
)}
|
||||
|
||||
{withColors && (
|
||||
<div className="w-32">
|
||||
<InputSelector
|
||||
name="color"
|
||||
title={t("models.group.color")}
|
||||
withSearch={false}
|
||||
value={option.color ?? Colors.UNDEFINED}
|
||||
withLabel={false}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(items, setItems, idx, {
|
||||
color: Number(e),
|
||||
})
|
||||
}
|
||||
selectPlaceholder={""}
|
||||
className="w-32"
|
||||
options={
|
||||
getColors().map((color) => {
|
||||
return {
|
||||
name: <ColorBadge color={color} />,
|
||||
value: color,
|
||||
};
|
||||
}) ?? []
|
||||
}
|
||||
></InputSelector>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ButtonSecondary disabled={items.length === 1} type="button" onClick={() => setItems([...items.filter((_, index) => index !== idx)])}>
|
||||
<TrashIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="w-full"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-border mt-5 border-t pt-3 sm:mt-6">
|
||||
<div className="flex items-center justify-end space-x-2">
|
||||
<ButtonSecondary onClick={close}>{t("shared.cancel")}</ButtonSecondary>
|
||||
<ButtonPrimary onClick={save}>{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
<ErrorModal ref={errorModal} />
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
);
|
||||
};
|
||||
|
||||
export default forwardRef(PropertyOptionsForm);
|
||||
@@ -0,0 +1,24 @@
|
||||
import EmailIcon from "~/components/ui/icons/EmailIcon";
|
||||
import LinkIcon from "~/components/ui/icons/crud/LinkIcon";
|
||||
import { PhoneIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
subtype?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function PropertySubtypeBadge({ subtype, className }: Props) {
|
||||
return (
|
||||
<>
|
||||
{subtype === "email" ? (
|
||||
<EmailIcon className="h-4 w-4 shrink-0" />
|
||||
) : subtype === "phone" ? (
|
||||
<PhoneIcon className="h-4 w-4 shrink-0" />
|
||||
) : subtype === "url" ? (
|
||||
<LinkIcon className="h-4 w-4 shrink-0" />
|
||||
) : (
|
||||
<div></div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import { Fragment } from "react";
|
||||
import { Listbox, Transition } from "@headlessui/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import clsx from "clsx";
|
||||
import SelectorIcon from "../../ui/icons/SelectorIcon";
|
||||
import CheckIcon from "../../ui/icons/CheckIcon";
|
||||
// import PropertySubtypeBadge from "./PropertySubtypeBadge";
|
||||
|
||||
interface Props {
|
||||
types: string[];
|
||||
className?: string;
|
||||
selected: string | undefined;
|
||||
onSelected: (item: string) => void;
|
||||
}
|
||||
|
||||
export default function PropertySubtypeSelector({ types, className, selected, onSelected }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Listbox name="formula" value={selected} onChange={onSelected}>
|
||||
{({ open }) => (
|
||||
<>
|
||||
<input type="hidden" name="subtype" value={selected} hidden readOnly />
|
||||
<div className={clsx("relative", className)}>
|
||||
<Listbox.Button className="focus:border-border focus:ring-ring border-border text-foreground bg-background relative w-full cursor-default rounded-md border py-2 pl-3 pr-10 text-left shadow-2xs focus:outline-hidden focus:ring-1 sm:text-sm">
|
||||
{selected ? (
|
||||
<div className="flex items-center space-x-2">
|
||||
{/* <PropertySubtypeBadge subtype={selected} className="h-4 w-4 text-muted-foreground" /> */}
|
||||
<div className="truncate">{t("entities.subtypes." + selected)}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground">{t("shared.select")}...</div>
|
||||
)}
|
||||
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
|
||||
<SelectorIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
</Listbox.Button>
|
||||
|
||||
<Transition show={open} as={Fragment} leave="transition ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0">
|
||||
<Listbox.Options className="border-border bg-background absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border py-1 text-base shadow-lg focus:outline-hidden sm:text-sm">
|
||||
{types.length === 0 ? (
|
||||
<div className=" flex select-none justify-center p-2 text-red-500">{t("models.property.selectors.noSubtypes")}</div>
|
||||
) : (
|
||||
<>
|
||||
{types.map((item, idx) => (
|
||||
<Listbox.Option
|
||||
key={idx}
|
||||
className={({ active }) =>
|
||||
clsx(active ? " bg-secondary " : "", "hover:bg-secondary relative cursor-default select-none py-2 pl-3 pr-9")
|
||||
}
|
||||
value={item}
|
||||
>
|
||||
{({ selected, active }) => (
|
||||
<>
|
||||
<div className="flex items-center space-x-2">
|
||||
{/* <PropertySubtypeBadge subtype={item} className={clsx(active ? "" : "", "h-4 w-4")} /> */}
|
||||
<div className="truncate">{t("entities.subtypes." + item)}</div>
|
||||
</div>
|
||||
{selected ? (
|
||||
<span className={clsx(active ? "" : "", "absolute inset-y-0 right-0 flex items-center pr-4")}>
|
||||
<CheckIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Listbox.Option>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Listbox.Options>
|
||||
</Transition>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Listbox>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Fragment } from "react";
|
||||
import { Listbox, Transition } from "@headlessui/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import clsx from "clsx";
|
||||
import PropertyBadge from "./PropertyBadge";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import SelectorIcon from "../../ui/icons/SelectorIcon";
|
||||
import CheckIcon from "../../ui/icons/CheckIcon";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
selected: PropertyType;
|
||||
onSelected: (item: PropertyType) => void;
|
||||
}
|
||||
|
||||
export default function PropertyTypeSelector({ className, selected, onSelected }: Props) {
|
||||
const items: PropertyType[] = [
|
||||
PropertyType.TEXT,
|
||||
PropertyType.NUMBER,
|
||||
PropertyType.DATE,
|
||||
// PropertyType.USER,
|
||||
// PropertyType.ROLE,
|
||||
PropertyType.SELECT,
|
||||
PropertyType.BOOLEAN,
|
||||
PropertyType.MEDIA,
|
||||
// PropertyType.ENTITY,
|
||||
// PropertyType.FORMULA,
|
||||
PropertyType.MULTI_SELECT,
|
||||
PropertyType.MULTI_TEXT,
|
||||
PropertyType.RANGE_NUMBER,
|
||||
PropertyType.RANGE_DATE,
|
||||
PropertyType.FORMULA,
|
||||
];
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Listbox value={selected} onChange={onSelected}>
|
||||
{({ open }) => (
|
||||
<>
|
||||
<input type="hidden" name="type" value={selected} hidden readOnly />
|
||||
<div className={clsx("relative", className)}>
|
||||
<Listbox.Button className="focus:border-border focus:ring-ring border-border text-foreground bg-background relative w-full cursor-default rounded-md border py-2 pl-3 pr-10 text-left shadow-2xs focus:outline-hidden focus:ring-1 sm:text-sm">
|
||||
<div className="flex items-center space-x-2">
|
||||
<PropertyBadge type={selected} className="text-muted-foreground h-4 w-4" />
|
||||
<div className="truncate">{t("entities.fields." + PropertyType[selected])}</div>
|
||||
</div>
|
||||
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
|
||||
<SelectorIcon className="text-muted-foreground h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
</Listbox.Button>
|
||||
|
||||
<Transition show={open} as={Fragment} leave="transition ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0">
|
||||
<Listbox.Options className="border-border bg-background absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border py-1 text-base shadow-lg focus:outline-hidden sm:text-sm">
|
||||
{items.length === 0 ? (
|
||||
<div className=" flex select-none justify-center p-2 text-red-500">{t("models.property.selectors.noFields")}</div>
|
||||
) : (
|
||||
<>
|
||||
{items.map((item, idx) => (
|
||||
<Listbox.Option
|
||||
key={idx}
|
||||
className={({ active }) =>
|
||||
clsx(active ? " bg-secondary " : "", "hover:bg-secondary relative cursor-default select-none py-2 pl-3 pr-9")
|
||||
}
|
||||
value={item}
|
||||
>
|
||||
{({ selected, active }) => (
|
||||
<>
|
||||
<div className="flex items-center space-x-2">
|
||||
<PropertyBadge type={item} className={clsx(active ? "" : "", "h-4 w-4")} />
|
||||
<div className="truncate">{t("entities.fields." + PropertyType[item])}</div>
|
||||
</div>
|
||||
{selected ? (
|
||||
<span className={clsx(active ? "" : "", "absolute inset-y-0 right-0 flex items-center pr-4")}>
|
||||
<CheckIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Listbox.Option>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Listbox.Options>
|
||||
</Transition>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Listbox>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { Property } from "@toolctrl/db/prisma-browser";
|
||||
import clsx from "clsx";
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, useSubmit } from "react-router";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import ButtonTertiary from "../../ui/buttons/ButtonTertiary";
|
||||
import LockClosedIcon from "../../ui/icons/LockClosedIcon";
|
||||
import NewFieldIcon from "../../ui/icons/NewFieldIcon";
|
||||
import PencilIcon from "../../ui/icons/PencilIcon";
|
||||
import TrashIcon from "../../ui/icons/TrashIcon";
|
||||
import ConfirmModal, { RefConfirmModal } from "../../ui/modals/ConfirmModal";
|
||||
import PropertyBadge from "./PropertyBadge";
|
||||
import OrderListButtons from "../../ui/sort/OrderListButtons";
|
||||
import EyeIcon from "~/components/ui/icons/EyeIcon";
|
||||
import EyeLashIcon from "~/components/ui/icons/EyeLashIcon";
|
||||
import DocumentDuplicateIconFilled from "~/components/ui/icons/DocumentDuplicateIconFilled";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
interface Props {
|
||||
tenantId: string | null;
|
||||
items: PropertyWithDetails[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function TenantPropertiesList({ tenantId, items, className }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const rootData = useRootData();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const [showDefaultFields, setShowDefaultFields] = useState(false);
|
||||
|
||||
function deleteField(item: Property) {
|
||||
confirmDelete.current?.setValue(item);
|
||||
confirmDelete.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function confirmedDelete(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete");
|
||||
form.set("id", item.id);
|
||||
if (rootData.csrf) {
|
||||
form.set("csrf", rootData.csrf);
|
||||
}
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function onToggleDisplay(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "toggle-display");
|
||||
form.set("id", item.id);
|
||||
if (rootData.csrf) {
|
||||
form.set("csrf", rootData.csrf);
|
||||
}
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function onDuplicate(item: Property) {
|
||||
const form = new FormData();
|
||||
form.set("action", "duplicate");
|
||||
form.set("id", item.id);
|
||||
if (rootData.csrf) {
|
||||
form.set("csrf", rootData.csrf);
|
||||
}
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={clsx(className, "")}>
|
||||
<div className="space-y-2">
|
||||
{showDefaultFields && (
|
||||
<div className="mb-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium">{t("models.property.defaultProperties.title")}</h3>
|
||||
{showDefaultFields && (
|
||||
<div className="flex justify-end">
|
||||
<ButtonTertiary className="-my-1" onClick={() => setShowDefaultFields(!showDefaultFields)}>
|
||||
{t("models.property.defaultProperties.hide")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{items
|
||||
.filter((f) => f.tenantId === null)
|
||||
.map((item, idx) => {
|
||||
return (
|
||||
<div key={idx} className="border-border bg-secondary/90 rounded-md border px-4 py-2 shadow-2xs">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className=" flex items-center space-x-3">
|
||||
<div className=" flex items-center space-x-2">
|
||||
<LockClosedIcon className="h-4 w-4 text-gray-300" />
|
||||
{/* <PropertyBadge className="h-4 w-4 text-muted-foreground" /> */}
|
||||
{/* <div className="truncate text-sm text-muted-foreground">{t("entities.fields." + PropertyType[item.type])}</div> */}
|
||||
</div>
|
||||
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{/* <PropertyTitle item={item} /> */}
|
||||
<div className="flex flex-col">
|
||||
<div>{t(item.title)}</div>
|
||||
<div className="text-muted-foreground text-xs">{item.name}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium">{t("models.property.plural")}</h3>
|
||||
{!showDefaultFields && (
|
||||
<div className="flex justify-end">
|
||||
<ButtonTertiary className="-my-1" onClick={() => setShowDefaultFields(!showDefaultFields)}>
|
||||
{t("models.property.defaultProperties.show")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{items
|
||||
.filter((f) => !f.isDefault && f.tenantId === tenantId)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((item, idx) => {
|
||||
return (
|
||||
<div key={idx} className="border-border bg-background rounded-md border px-4 py-1 shadow-2xs">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2 truncate">
|
||||
<div className=" flex items-center space-x-3 truncate">
|
||||
<div className="hidden shrink-0 sm:flex">
|
||||
<OrderListButtons index={idx} items={items.filter((f) => !f.isDefault)} editable={true} />
|
||||
</div>
|
||||
<div className=" flex items-center space-x-2">
|
||||
<PropertyBadge type={item.type} className="text-muted-foreground h-4 w-4" />
|
||||
</div>
|
||||
<div className="text-foreground flex items-center space-x-2 truncate text-sm">
|
||||
<PropertyTitle item={item} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 space-x-1">
|
||||
<div className="flex items-center space-x-1 truncate p-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onToggleDisplay(item)}
|
||||
aria-label={t(item.isDisplay ? "shared.hide" : "shared.show")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:outline-hidden focus:ring-2 focus:ring-gray-400 focus:ring-offset-1"
|
||||
>
|
||||
{item.isDisplay ? (
|
||||
<EyeIcon className="text-muted-foreground hover:text-muted-foreground h-4 w-4" />
|
||||
) : (
|
||||
<EyeLashIcon className="hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
)}
|
||||
</button>
|
||||
<Link
|
||||
to={item.id}
|
||||
aria-label={t("shared.edit")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:outline-hidden focus:ring-2 focus:ring-gray-400 focus:ring-offset-1"
|
||||
// onClick={() => update(idx, item)}
|
||||
>
|
||||
<PencilIcon className="group-hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDuplicate(item)}
|
||||
aria-label={t("shared.duplicate")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:outline-hidden focus:ring-2 focus:ring-gray-400 focus:ring-offset-1"
|
||||
>
|
||||
<DocumentDuplicateIconFilled className="hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("shared.delete")}
|
||||
className="hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent p-2 focus:outline-hidden focus:ring-2 focus:ring-gray-400 focus:ring-offset-1"
|
||||
onClick={() => deleteField(item)}
|
||||
>
|
||||
<TrashIcon className="group-hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<Link
|
||||
to={`new`}
|
||||
className="focus:ring-ring border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed px-12 py-6 text-center focus:outline-hidden focus:ring-2 focus:ring-offset-2"
|
||||
>
|
||||
<NewFieldIcon className="text-muted-foreground mx-auto h-8" />
|
||||
<span className="text-foreground mt-2 block text-sm font-medium">{t("models.property.actions.add")}</span>
|
||||
</Link>
|
||||
</div>
|
||||
{/* <PropertyForm ref={propertyForm} entityId={entityId} onCreated={created} onUpdated={updated} onDeleted={deleted} /> */}
|
||||
<ConfirmModal ref={confirmDelete} destructive onYes={confirmedDelete} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const PropertyTitle = ({ item }: { item: PropertyWithDetails }) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-baseline space-x-1 truncate">
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
{t(EntityHelper.getFieldTitle(item, item.isDefault))}
|
||||
{item.isRequired && <span className="text-red-500">*</span>}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{item.name}
|
||||
{item.subtype === "phone" && " (phone)"}
|
||||
{item.subtype === "url" && " (URL)"}
|
||||
{[PropertyType.MULTI_SELECT, PropertyType.SELECT].includes(item.type) && "[]"}
|
||||
{[PropertyType.RANGE_NUMBER, PropertyType.RANGE_DATE].includes(item.type) && ` (${t("models.property.badges.range")})`}
|
||||
{[PropertyType.FORMULA].includes(item.type) && ` (${t("models.property.badges.formula")})`}
|
||||
</div>
|
||||
</div>
|
||||
{/* {item.type === PropertyType.FORMULA && <div className="truncate italic text-muted-foreground">({item.formula})</div>} */}
|
||||
{[PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(item.type) && (
|
||||
<div className="text-muted-foreground truncate text-xs">
|
||||
[
|
||||
{item.options.length === 0
|
||||
? t("models.property.noOptions")
|
||||
: t("models.property.optionsSummary", { options: item.options?.map((f) => f.value).join(", ") })}
|
||||
]
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.attributes.filter((f) => f.value).length > 0 && (
|
||||
<div className="text-muted-foreground truncate text-xs">
|
||||
[
|
||||
{item.attributes
|
||||
.filter((f) => f.value)
|
||||
.map((f) => `${f.name}: ${f.value}`)
|
||||
.join(", ")}
|
||||
]
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
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/components/entities/properties/PropertiesList.tsx");
|
||||
|
||||
describe("properties list i18n", () => {
|
||||
it("uses semantic translation keys for option summaries", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.property.noOptions");
|
||||
expect(source).toContain("models.property.optionsSummary");
|
||||
expect(source).toContain("models.property.badges.range");
|
||||
expect(source).toContain("models.property.badges.formula");
|
||||
expect(source).not.toContain('"No options"');
|
||||
expect(source).not.toContain('"Options: "');
|
||||
expect(source).not.toContain('" (range)"');
|
||||
expect(source).not.toContain("` (formula)`");
|
||||
});
|
||||
});
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const selectorRoot = path.resolve(process.cwd(), "apps/web/app/components/entities/properties");
|
||||
|
||||
function readSelector(relativePath: string) {
|
||||
return fs.readFileSync(path.join(selectorRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("property selector empty states i18n", () => {
|
||||
it("uses semantic translation keys for empty dropdown states", () => {
|
||||
const sources = [
|
||||
readSelector("PropertySubtypeSelector.tsx"),
|
||||
readSelector("PropertyTypeSelector.tsx"),
|
||||
readSelector("PropertyFormulaSelector.tsx"),
|
||||
].join("\n");
|
||||
|
||||
expect(sources).toContain("models.property.selectors.noSubtypes");
|
||||
expect(sources).toContain("models.property.selectors.noFields");
|
||||
expect(sources).toContain("models.property.selectors.noFormulas");
|
||||
expect(sources).not.toContain("there_are_no_subtypes");
|
||||
expect(sources).not.toContain("there_are_no_fields");
|
||||
expect(sources).not.toContain("there_are_no_formulas");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Fragment } from "react";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { SelectOptionsDisplay } from "~/utils/shared/SelectOptionsUtils";
|
||||
|
||||
export default function RenderOption({
|
||||
option,
|
||||
hasColors,
|
||||
display,
|
||||
}: {
|
||||
option:
|
||||
| {
|
||||
name?: string | null;
|
||||
value: string;
|
||||
color?: Colors | number;
|
||||
}
|
||||
| undefined;
|
||||
hasColors: boolean;
|
||||
display?: SelectOptionsDisplay;
|
||||
}) {
|
||||
return (
|
||||
<Fragment>
|
||||
{!option ? (
|
||||
<></>
|
||||
) : (
|
||||
<Fragment>
|
||||
{!display ? (
|
||||
<Fragment>
|
||||
{option.name ? (
|
||||
option.name
|
||||
) : (
|
||||
<>
|
||||
{option.value}
|
||||
{option.name && option.value && " - "}
|
||||
{option.name}
|
||||
</>
|
||||
)}
|
||||
</Fragment>
|
||||
) : (
|
||||
<Fragment>
|
||||
<div className="flex space-x-2 truncate">
|
||||
{display === "Name" && (option.name ?? option.value)}
|
||||
{display === "Value" && option.value}
|
||||
{display === "Color" && (
|
||||
<Fragment>
|
||||
<ColorBadge color={option.color} />
|
||||
</Fragment>
|
||||
)}
|
||||
{display === "ColorWithTitle" && (
|
||||
<Fragment>
|
||||
<div>
|
||||
<ColorBadge color={option.color} />
|
||||
</div>
|
||||
{option.color !== undefined && option.color !== null && <div className="capitalize">{Colors[option.color]?.toLowerCase()}</div>}
|
||||
</Fragment>
|
||||
)}
|
||||
{display === "NameAndValue" && (
|
||||
<Fragment>
|
||||
{option.name}
|
||||
{option.name && option.value && " - "}
|
||||
{option.value}
|
||||
</Fragment>
|
||||
)}
|
||||
{display === "ValueAndName" && (
|
||||
<Fragment>
|
||||
{option.value}
|
||||
{option.name && option.value && " - "}
|
||||
{option.name}
|
||||
</Fragment>
|
||||
)}
|
||||
{display === "NameValueAndColor" && (
|
||||
<Fragment>
|
||||
<div>
|
||||
<ColorBadge color={option.color} />
|
||||
</div>
|
||||
<div>
|
||||
{option.name}
|
||||
{option.name && option.value && " - "}
|
||||
{option.value}
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
{display === "ValueNameAndColor" && (
|
||||
<Fragment>
|
||||
<div>
|
||||
<ColorBadge color={option.color} />
|
||||
</div>
|
||||
<div>
|
||||
{option.value}
|
||||
{option.name && option.value && " - "}
|
||||
{option.name}
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
{display === "NameAndColor" && (
|
||||
<Fragment>
|
||||
<div>
|
||||
<ColorBadge color={option.color} />
|
||||
</div>
|
||||
<div>{option.name}</div>
|
||||
</Fragment>
|
||||
)}
|
||||
{display === "ValueAndColor" && (
|
||||
<Fragment>
|
||||
<div>
|
||||
<ColorBadge color={option.color} />
|
||||
</div>
|
||||
<div>{option.value}</div>
|
||||
</Fragment>
|
||||
)}
|
||||
</div>
|
||||
</Fragment>
|
||||
)}
|
||||
</Fragment>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
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/components/entities/properties/TenantPropertiesList.tsx");
|
||||
|
||||
describe("tenant properties list i18n", () => {
|
||||
it("uses semantic translation keys for option summaries", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.property.noOptions");
|
||||
expect(source).toContain("models.property.optionsSummary");
|
||||
expect(source).toContain("models.property.badges.range");
|
||||
expect(source).toContain("models.property.badges.formula");
|
||||
expect(source).not.toContain('"No options"');
|
||||
expect(source).not.toContain('"Options: "');
|
||||
expect(source).not.toContain('" (range)"');
|
||||
expect(source).not.toContain("` (formula)`");
|
||||
});
|
||||
});
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
import { useNavigation } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputRadioGroup from "~/components/ui/input/InputRadioGroup";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityRelationshipWithDetails } from "~/utils/db/entities/entityRelationships.db.server";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
entities: EntityWithDetails[];
|
||||
item?: EntityRelationshipWithDetails;
|
||||
}
|
||||
|
||||
export default function EntityRelationshipForm({ entity, entities, item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const navigation = useNavigation();
|
||||
|
||||
const [type, setType] = useState<string>(!item ? "child" : item.parentId === entity?.id ? "parent" : "child");
|
||||
const [parentId, setParentId] = useState<string | undefined>(item?.parentId);
|
||||
const [childId, setChildId] = useState<string | undefined>(item?.childId);
|
||||
const [child, setChild] = useState<EntityWithDetails>();
|
||||
const [parent, setParent] = useState<EntityWithDetails>();
|
||||
const [title, setTitle] = useState(item?.title ?? "");
|
||||
const [relationshipType, setRelationshipType] = useState(item?.type ?? "one-to-many");
|
||||
const [required, setRequired] = useState(item ? item.required : false);
|
||||
const [cascade, setCascade] = useState(item ? item.cascade : false);
|
||||
const [readOnly, setReadOnly] = useState(item ? item.readOnly : false);
|
||||
const [hiddenIfEmpty, setHiddenIfEmpty] = useState(item ? item.hiddenIfEmpty : false);
|
||||
const [childEntityViewId, setChildEntityViewId] = useState(item?.childEntityViewId ?? undefined);
|
||||
const [parentEntityViewId, setParentEntityViewId] = useState(item?.parentEntityViewId ?? undefined);
|
||||
|
||||
useEffect(() => {
|
||||
if (type === "parent") {
|
||||
setParentId(entity?.id);
|
||||
setChildId(undefined);
|
||||
} else {
|
||||
setParentId(undefined);
|
||||
setChildId(entity?.id);
|
||||
}
|
||||
}, [entity, type, entities]);
|
||||
|
||||
useEffect(() => {
|
||||
setChild(entities.find((i) => i.id === childId));
|
||||
}, [childId, entities]);
|
||||
|
||||
useEffect(() => {
|
||||
setParent(entities.find((i) => i.id === parentId));
|
||||
}, [parentId, entities]);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* <h3 className="border-b border-border pb-4 text-lg font-medium leading-3 text-foreground">{t(entity.title)} relationship</h3> */}
|
||||
<FormGroup
|
||||
id={item?.id}
|
||||
editing={true}
|
||||
state={{
|
||||
loading: navigation.state === "loading",
|
||||
submitting: navigation.state === "submitting",
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<InputRadioGroup
|
||||
className="col-span-2"
|
||||
name="type"
|
||||
title={t("models.relationship.form.direction")}
|
||||
value={type}
|
||||
disabled={item !== undefined}
|
||||
setValue={(e) => setType(e?.toString() ?? "")}
|
||||
options={[
|
||||
{
|
||||
name: t("models.relationship.form.entityIsParent", { entity: t(entity.title) }),
|
||||
value: "parent",
|
||||
},
|
||||
{
|
||||
name: t("models.relationship.form.entityIsChild", { entity: t(entity.title) }),
|
||||
value: "child",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{type === "child" && (
|
||||
<InputSelector
|
||||
className="col-span-2"
|
||||
withSearch={false}
|
||||
name="parentId"
|
||||
title={t("models.relationship.form.parentEntity")}
|
||||
value={parentId}
|
||||
disabled={item !== undefined}
|
||||
setValue={(e) => setParentId(e?.toString() ?? "")}
|
||||
options={entities.map((i) => {
|
||||
return {
|
||||
value: i.id,
|
||||
name: t(i.title),
|
||||
};
|
||||
})}
|
||||
required
|
||||
/>
|
||||
)}
|
||||
{type === "parent" && (
|
||||
<InputSelector
|
||||
className="col-span-2"
|
||||
withSearch={false}
|
||||
name="childId"
|
||||
title={t("models.relationship.form.childEntity")}
|
||||
value={childId}
|
||||
disabled={item !== undefined}
|
||||
setValue={(e) => setChildId(e?.toString() ?? "")}
|
||||
options={entities.map((i) => {
|
||||
return {
|
||||
value: i.id,
|
||||
name: t(i.title),
|
||||
};
|
||||
})}
|
||||
required
|
||||
/>
|
||||
)}
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
className="col-span-2"
|
||||
name="relationshipType"
|
||||
title={t("models.relationship.form.relationshipType")}
|
||||
value={relationshipType}
|
||||
setValue={(e) => setRelationshipType(e?.toString() ?? "one-to-many")}
|
||||
options={[
|
||||
{ name: t("models.relationship.types.oneToMany"), value: "one-to-many" },
|
||||
{ name: t("models.relationship.types.oneToOne"), value: "one-to-one" },
|
||||
{ name: t("models.relationship.types.manyToOne"), value: "many-to-one" },
|
||||
{ name: t("models.relationship.types.manyToMany"), value: "many-to-many" },
|
||||
]}
|
||||
required
|
||||
/>
|
||||
<InputSelector
|
||||
disabled={child?.views.filter((f) => f.isSystem).length === 0}
|
||||
withSearch={false}
|
||||
className="col-span-2"
|
||||
name="childEntityViewId"
|
||||
title={t("models.relationship.form.childrenView")}
|
||||
value={childEntityViewId}
|
||||
setValue={(e) => setChildEntityViewId(e?.toString() ?? undefined)}
|
||||
options={
|
||||
child?.views
|
||||
.filter((f) => f.isSystem)
|
||||
.map((f) => {
|
||||
return {
|
||||
value: f.id,
|
||||
name: `${f.title} (${f.layout})`,
|
||||
};
|
||||
}) ?? []
|
||||
}
|
||||
hint={
|
||||
<>
|
||||
{childEntityViewId !== undefined && (
|
||||
<button type="button" onClick={() => setChildEntityViewId(undefined)} className="text-muted-foreground hover:text-foreground/80 text-sm">
|
||||
{t("shared.clear")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<InputSelector
|
||||
disabled={parent?.views.filter((f) => f.isSystem).length === 0}
|
||||
withSearch={false}
|
||||
className="col-span-2"
|
||||
name="parentEntityViewId"
|
||||
title={t("models.relationship.form.parentView")}
|
||||
value={parentEntityViewId}
|
||||
setValue={(e) => setParentEntityViewId(e?.toString() ?? undefined)}
|
||||
options={
|
||||
parent?.views
|
||||
.filter((f) => f.isSystem)
|
||||
.map((f) => {
|
||||
return {
|
||||
value: f.id,
|
||||
name: `${f.title} (${f.layout})`,
|
||||
};
|
||||
}) ?? []
|
||||
}
|
||||
hint={
|
||||
<>
|
||||
{childEntityViewId !== undefined && (
|
||||
<button type="button" onClick={() => setChildEntityViewId(undefined)} className="text-muted-foreground hover:text-foreground/80 text-sm">
|
||||
{t("shared.clear")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-2"
|
||||
name="required"
|
||||
title={t("models.relationship.required")}
|
||||
description={t("models.relationship.form.descriptions.required")}
|
||||
value={required}
|
||||
setValue={(e) => setRequired(Boolean(e))}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-2"
|
||||
name="cascade"
|
||||
title={t("models.relationship.form.cascadeDelete")}
|
||||
description={t("models.relationship.form.descriptions.cascadeDelete")}
|
||||
value={cascade}
|
||||
setValue={(e) => setCascade(Boolean(e))}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-2"
|
||||
name="readOnly"
|
||||
title={t("models.relationship.form.readOnly")}
|
||||
description={t("models.relationship.form.descriptions.readOnly")}
|
||||
value={readOnly}
|
||||
setValue={(e) => setReadOnly(Boolean(e))}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
className="col-span-2"
|
||||
name="hiddenIfEmpty"
|
||||
title={t("models.relationship.form.hiddenIfEmpty")}
|
||||
description={t("models.relationship.form.descriptions.hiddenIfEmpty")}
|
||||
value={hiddenIfEmpty}
|
||||
setValue={(e) => setHiddenIfEmpty(Boolean(e))}
|
||||
/>
|
||||
<InputText className="col-span-2" name="title" title={t("models.relationship.form.titleOptional")} value={title} setValue={(e) => setTitle(e)} />
|
||||
</div>
|
||||
</FormGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import OrderListButtons from "~/components/ui/sort/OrderListButtons";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { EntityRelationshipWithDetails } from "~/utils/db/entities/entityRelationships.db.server";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export default function EntityRelationshipsTable({
|
||||
items,
|
||||
editable,
|
||||
}: {
|
||||
items: (EntityRelationshipWithDetails & { _count: { rows: number } })[];
|
||||
editable: boolean;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
return (
|
||||
<TableSimple
|
||||
headers={[
|
||||
{
|
||||
name: "order",
|
||||
title: "shared.order",
|
||||
value: (_item, idx) => (
|
||||
<div>
|
||||
{/* {item.order} */}
|
||||
<OrderListButtons index={idx} items={items.map((f) => ({ ...f, order: f.order ?? 0 }))} editable={true} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "type",
|
||||
title: "shared.type",
|
||||
value: (item) => (
|
||||
<Link to={item.id} className="font-medium underline">
|
||||
{t("shared.relationships." + item.type)}
|
||||
</Link>
|
||||
),
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "parent",
|
||||
title: "admin.entities.relationships.table.parent",
|
||||
value: (item) => (
|
||||
<div>
|
||||
{translateLabel(t, i18n, item.parent.title)} {item.parentEntityView && <span className="text-muted-foreground text-xs italic">({item.parentEntityView.name})</span>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "child",
|
||||
title: "admin.entities.relationships.table.child",
|
||||
value: (item) => (
|
||||
<div>
|
||||
{translateLabel(t, i18n, item.child.title)} {item.childEntityView && <span className="text-muted-foreground text-xs italic">({item.childEntityView.name})</span>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "count",
|
||||
title: "admin.entities.relationships.table.count",
|
||||
value: (item) => <div>{formatters.number(item._count.rows)}</div>,
|
||||
},
|
||||
{
|
||||
name: "required",
|
||||
title: "shared.required",
|
||||
value: (item) => <div>{item.required ? <CheckIcon className="h-5 w-5 text-teal-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "cascade",
|
||||
title: "admin.entities.relationships.table.cascadeDelete",
|
||||
value: (item) => <div>{item.cascade ? <CheckIcon className="h-5 w-5 text-teal-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "readOnly",
|
||||
title: "admin.entities.relationships.table.readOnly",
|
||||
value: (item) => <div>{item.readOnly ? <CheckIcon className="h-5 w-5 text-teal-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "hiddenIfEmpty",
|
||||
title: "admin.entities.relationships.table.hiddenIfEmpty",
|
||||
value: (item) => (
|
||||
<div>{item.hiddenIfEmpty ? <CheckIcon className="h-5 w-5 text-teal-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "title",
|
||||
title: "shared.title",
|
||||
value: (item) => <div>{translateLabel(t, i18n, item.title)}</div>,
|
||||
},
|
||||
]}
|
||||
items={items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, item) => item.id,
|
||||
hidden: () => !editable,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
);
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
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/components/entities/relationships/EntityRelationshipForm.tsx");
|
||||
|
||||
describe("entity relationship form i18n", () => {
|
||||
it("uses semantic translation keys for relationship labels and descriptions", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.relationship.form.direction");
|
||||
expect(source).toContain("models.relationship.form.entityIsParent");
|
||||
expect(source).toContain("models.relationship.types.oneToMany");
|
||||
expect(source).toContain("models.relationship.form.descriptions.required");
|
||||
expect(source).toContain("models.relationship.form.titleOptional");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain("One to many");
|
||||
expect(source).not.toContain('title="Required"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
|
||||
import RowCard from "./RowCard";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import clsx from "clsx";
|
||||
|
||||
export default function RenderCard({
|
||||
layout,
|
||||
item,
|
||||
entity,
|
||||
columns,
|
||||
allEntities,
|
||||
routes,
|
||||
actions,
|
||||
href,
|
||||
}: {
|
||||
layout: "table" | "grid" | "board" | "card";
|
||||
item: RowWithDetails;
|
||||
entity: EntityWithDetails;
|
||||
columns: ColumnDto[];
|
||||
allEntities: EntityWithDetails[];
|
||||
routes: EntitiesApi.Routes | undefined;
|
||||
actions?: (row: RowWithDetails) => { title?: string; href?: string; onClick?: () => void; isLoading?: boolean; render?: React.ReactNode }[];
|
||||
href?: string | undefined;
|
||||
}) {
|
||||
return (
|
||||
<div className={clsx("border-border bg-background rounded-md border p-3 shadow-2xs", href && "hover:border-border hover:shadow-md")}>
|
||||
<RowCard layout={layout} item={item} entity={entity} columns={columns} allEntities={allEntities} routes={routes} actions={actions} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { FormEvent, useEffect, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Form, useLocation, useSubmit, useNavigation } from "react-router";
|
||||
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
|
||||
import UserAvatarBadge from "~/components/core/users/UserAvatarBadge";
|
||||
import UserBadge from "~/components/core/users/UserBadge";
|
||||
import CalendarFilledIcon from "~/components/ui/icons/CalendarFilledIcon";
|
||||
import ChatAltIcon from "~/components/ui/icons/ChatAltIcon";
|
||||
import PencilIcon from "~/components/ui/icons/PencilIcon";
|
||||
import QuestionMarkFilledIcon from "~/components/ui/icons/QuestionMarkFilledIcon";
|
||||
import { LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import RowLogComment from "./RowLogComment";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import clsx from "clsx";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
interface Props {
|
||||
items: LogWithDetails[];
|
||||
hasActivity?: boolean;
|
||||
hasComments?: boolean;
|
||||
onSubmit?: (formData: FormData) => void;
|
||||
withTitle?: boolean;
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
export default function RowActivity({ items, hasActivity = true, hasComments, onSubmit, withTitle = true, autoFocus }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const transition = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const isAdding = transition.state === "submitting" && transition.formData?.get("action") === "comment";
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
formRef.current?.reset();
|
||||
}, [isAdding]);
|
||||
|
||||
const sortedItems = () => {
|
||||
const filteredItems = items.filter((item) => {
|
||||
if (item.commentId && !hasComments) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return filteredItems.slice().sort((x, y) => {
|
||||
if (x.createdAt && y.createdAt) {
|
||||
return x.createdAt > y.createdAt ? 1 : -1;
|
||||
}
|
||||
return 1;
|
||||
});
|
||||
};
|
||||
|
||||
function getActionDescription(item: LogWithDetails) {
|
||||
return item.action;
|
||||
}
|
||||
|
||||
function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.currentTarget);
|
||||
appendCSRFToken(formData);
|
||||
if (onSubmit !== undefined) {
|
||||
onSubmit(formData);
|
||||
} else {
|
||||
submit(formData, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="relative">
|
||||
<div className="space-y-3">
|
||||
<div className="divide-border divide-y ">
|
||||
{withTitle && (
|
||||
<div className="pb-2">
|
||||
<h2 id="activity-title" className="text-foreground text-sm font-medium">
|
||||
{t("app.shared.activity.title")}
|
||||
</h2>
|
||||
</div>
|
||||
)}
|
||||
<div className={clsx("space-y-6 text-xs", withTitle && "pt-4")}>
|
||||
{/* Activity feed*/}
|
||||
<div className="">
|
||||
<ul className="-mb-8 space-y-6 pb-6">
|
||||
{sortedItems().map((item, idx) => (
|
||||
<li key={item.id}>
|
||||
<div className="relative">
|
||||
{idx !== sortedItems().length - 1 ? <span className="absolute left-5 top-5 -ml-px h-full w-0.5 bg-gray-200" aria-hidden="true" /> : null}
|
||||
<div className="relative flex items-start space-x-3">
|
||||
{item.comment ? (
|
||||
<>{hasComments && <RowLogComment item={item} />}</>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<div className="relative px-1">
|
||||
<div className="relative">
|
||||
<UserAvatarBadge className="h-9 w-9" avatar={item.user?.avatar} />
|
||||
|
||||
<span className="bg-secondary absolute -bottom-0.5 -right-1 rounded-tl px-0.5 py-px">
|
||||
{/* <TagIcon className="h-4 w-4 text-muted-foreground" aria-hidden="true" /> */}
|
||||
{item.action === DefaultLogActions.Created ? (
|
||||
<CalendarFilledIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
) : item.action === DefaultLogActions.Updated ? (
|
||||
<PencilIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<QuestionMarkFilledIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 py-0">
|
||||
<div className=" text-muted-foreground">
|
||||
<span className="mr-0.5 flex items-center space-x-1 text-sm">
|
||||
<div className="text-foreground font-medium">
|
||||
{item.user && (
|
||||
<span>
|
||||
<UserBadge item={item.user} withEmail={false} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</span>
|
||||
|
||||
<span className="mr-0.5" title={JSON.stringify(item.details) !== JSON.stringify("{}") ? item.details?.toString() : ""}>
|
||||
{getActionDescription(item)}
|
||||
</span>
|
||||
<span className="whitespace-nowrap pt-1">
|
||||
<time dateTime={new Date(item.createdAt).toISOString()} title={formatters.dateTime(item.createdAt, { timeStyle: "medium" })}>
|
||||
{formatters.relativeDate(item.createdAt)}
|
||||
</time>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{hasComments && (
|
||||
<div className="">
|
||||
<div className="flex space-x-3">
|
||||
<div className="shrink-0">
|
||||
<div className="relative px-1">
|
||||
<UserAvatarBadge className="h-9 w-9" avatar={appOrAdminData.user?.avatar} />
|
||||
|
||||
<span className="bg-secondary absolute -bottom-0.5 -right-1 rounded-tl px-0.5 py-px">
|
||||
<ChatAltIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<Form ref={formRef} onSubmit={handleSubmit} method="post" className="space-y-2">
|
||||
<div>
|
||||
<input hidden readOnly name="action" value="comment" />
|
||||
<label htmlFor="comment" className="sr-only">
|
||||
{t("shared.comment")}
|
||||
</label>
|
||||
<textarea
|
||||
autoFocus={autoFocus}
|
||||
required
|
||||
id="comment"
|
||||
name="comment"
|
||||
rows={3}
|
||||
className={clsx(
|
||||
"border-border block w-full rounded-md border shadow-2xs focus:border-gray-900 focus:ring-gray-900 sm:text-sm",
|
||||
(isAdding || !appOrAdminData.user) && "bg-secondary/90 cursor-not-allowed"
|
||||
)}
|
||||
placeholder={t("shared.addComment")}
|
||||
defaultValue={""}
|
||||
disabled={isAdding || !appOrAdminData.user}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-end space-x-4">
|
||||
<Button variant="outline" disabled={isAdding || !appOrAdminData.user} type="submit">
|
||||
{t("shared.comment")}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import clsx from "clsx";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import RowDisplayHeaderHelper from "~/utils/helpers/RowDisplayHeaderHelper";
|
||||
import RowDisplayValueHelper from "~/utils/helpers/RowDisplayValueHelper";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
item: RowWithDetails;
|
||||
layout: string;
|
||||
columns?: ColumnDto[];
|
||||
allEntities: EntityWithDetails[];
|
||||
routes?: EntitiesApi.Routes;
|
||||
actions?: (row: RowWithDetails) => {
|
||||
title?: string;
|
||||
href?: string;
|
||||
onClick?: () => void;
|
||||
isLoading?: boolean;
|
||||
render?: React.ReactNode;
|
||||
}[];
|
||||
}
|
||||
export default function RowCard({ entity, item, columns, layout, allEntities, routes, actions }: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<RowWithDetails>[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
setHeaders(RowDisplayHeaderHelper.getDisplayedHeaders({ entity, columns, layout, allEntities: allEntities, t, i18n, routes }));
|
||||
}, [entity, columns, layout, allEntities, t, i18n, routes]);
|
||||
|
||||
return (
|
||||
<div className="text-muted-foreground flex flex-col space-y-2 text-sm whitespace-nowrap">
|
||||
{headers.map((header, idx) => {
|
||||
return (
|
||||
<div key={idx} className={clsx("flex flex-col", header.className)}>
|
||||
<div className="text-muted-foreground text-xs font-medium">{translateLabel(t, i18n, header.title)}</div>
|
||||
<div>{RowDisplayValueHelper.displayRowValue(t, header, item, idx)}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{actions && (
|
||||
<div className="flex flex-col space-y-2">
|
||||
{actions(item).map((action, idx) => {
|
||||
return (
|
||||
<Fragment key={idx}>
|
||||
{action.render ?? (
|
||||
<ButtonSecondary
|
||||
className="w-full"
|
||||
to={action.href}
|
||||
isLoading={action.isLoading}
|
||||
onClick={(e) => {
|
||||
if (action.onClick) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
action.onClick();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex w-full justify-center">{action.title}</div>
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { RowWithCreatedBy } from "~/utils/db/entities/rows.db.server";
|
||||
import { DateDisplay } from "~/utils/shared/DateUtils";
|
||||
import RowCreatedByBadge from "./RowCreatedByBadge";
|
||||
|
||||
interface Props {
|
||||
row: RowWithCreatedBy;
|
||||
by?: { withEmail?: boolean };
|
||||
date?: { displays?: DateDisplay[] };
|
||||
}
|
||||
export default function RowCreatedBadge({ row, by = { withEmail: true }, date = { displays: ["ymd"] } }: Props) {
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{date && <DateCell displays={date.displays} date={row.createdAt} />}
|
||||
{by && <RowCreatedByBadge row={row} withEmail={by.withEmail} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RowWithCreatedBy } from "~/utils/db/entities/rows.db.server";
|
||||
|
||||
interface Props {
|
||||
row: RowWithCreatedBy;
|
||||
withEmail?: boolean;
|
||||
}
|
||||
export default function RowCreatedByBadge({ row, withEmail = true }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center space-x-1">
|
||||
{row.createdByUser && (
|
||||
<div className="text-muted-foreground flex items-baseline space-x-1 text-xs">
|
||||
<div className="font-normal">
|
||||
{t("shared.by")} {row.createdByUser.firstName} {row.createdByUser.lastName}
|
||||
</div>{" "}
|
||||
{withEmail && <span className="italic">({row.createdByUser.email})</span>}
|
||||
</div>
|
||||
)}{" "}
|
||||
{row.createdByApiKey && (
|
||||
<div className="text-muted-foreground flex items-baseline space-x-1">
|
||||
<div className="font-normal">
|
||||
{t("shared.by")} {t("models.apiKey.object")}
|
||||
</div>{" "}
|
||||
<span className="text-xs italic">({row.createdByApiKey.alias})</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,985 @@
|
||||
import { RowWithDetails, RowWithValues } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails, PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { Dispatch, forwardRef, Fragment, ReactNode, Ref, SetStateAction, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
|
||||
import { useNavigation, useParams, useSearchParams, useSubmit } from "react-router";
|
||||
import { RowValueDto } from "~/application/dtos/entities/RowValueDto";
|
||||
import FormGroup, { RefFormGroup } from "~/components/ui/forms/FormGroup";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import RowValueInput, { RefRowValueInput } from "./RowValueInput";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { EntityRelationshipWithDetails } from "~/utils/db/entities/entityRelationships.db.server";
|
||||
import RowListFetcher from "../../../modules/rows/fetchers/RowListFetcher";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import RelationshipHelper from "~/utils/helpers/RelationshipHelper";
|
||||
import RowsList from "./RowsList";
|
||||
import { EntityViewWithDetails } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { RowDisplayDefaultProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import RowUrlHelper from "~/utils/helpers/RowUrlHelper";
|
||||
import { translateEntityTitle } from "~/utils/i18n/translateLabel";
|
||||
|
||||
export interface RefRowForm {
|
||||
save: () => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
allEntities: EntityWithDetails[];
|
||||
routes?: EntitiesApi.Routes;
|
||||
item?: RowWithDetails | null;
|
||||
editing?: boolean;
|
||||
adding?: boolean;
|
||||
onSubmit?: (formData: FormData) => void;
|
||||
canUpdate?: boolean;
|
||||
canDelete?: boolean;
|
||||
canSubmit?: boolean;
|
||||
children?: ReactNode;
|
||||
parentEntity?: EntityWithDetails;
|
||||
onCreatedRedirect?: string;
|
||||
onDelete?: () => void;
|
||||
relationshipRows?: RowsApi.GetRelationshipRowsData;
|
||||
hiddenProperties?: string[];
|
||||
hiddenFields?: {
|
||||
[key: string]: string | null | undefined;
|
||||
};
|
||||
state?: { loading?: boolean; submitting?: boolean };
|
||||
createdRow?: RowWithDetails;
|
||||
onCancel?: () => void;
|
||||
onChange?: (values: RowValueDto[]) => void;
|
||||
customSearchParams?: URLSearchParams;
|
||||
template?: { title: string; config: string } | null;
|
||||
}
|
||||
|
||||
const RowForm = (
|
||||
{
|
||||
entity,
|
||||
routes,
|
||||
item,
|
||||
editing = false,
|
||||
adding,
|
||||
onSubmit,
|
||||
canUpdate,
|
||||
canDelete,
|
||||
canSubmit = true,
|
||||
children,
|
||||
parentEntity,
|
||||
onCreatedRedirect,
|
||||
allEntities,
|
||||
onDelete,
|
||||
relationshipRows,
|
||||
hiddenProperties,
|
||||
hiddenFields,
|
||||
state,
|
||||
createdRow,
|
||||
onCancel,
|
||||
onChange,
|
||||
customSearchParams,
|
||||
template,
|
||||
}: Props,
|
||||
ref: Ref<RefRowForm>
|
||||
) => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const params = useParams();
|
||||
// const actionData = useActionData<{ newRow?: RowWithDetails }>();
|
||||
|
||||
const formGroup = useRef<RefFormGroup>(null);
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
const [searchingRelationshipRows, setSearchingRelationshipRows] = useState<EntityRelationshipWithDetails>();
|
||||
const [selectedRelatedEntity, setSelectedRelatedEntity] = useState<{
|
||||
entity: { slug: string; onEdit: string | null };
|
||||
view: EntityViewWithDetails | null;
|
||||
multiple: boolean;
|
||||
}>();
|
||||
const [relatedRows, setRelatedRows] = useState<{ relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[]>([]);
|
||||
|
||||
const [headers, setHeaders] = useState<RowValueDto[]>([]);
|
||||
|
||||
const [childrenEntities, setChildrenEntities] = useState<{ visible: EntityRelationshipWithDetails[]; hidden: EntityRelationshipWithDetails[] }>({
|
||||
visible: [],
|
||||
hidden: [],
|
||||
});
|
||||
const [parentEntities, setParentEntities] = useState<{ visible: EntityRelationshipWithDetails[]; hidden: EntityRelationshipWithDetails[] }>({
|
||||
visible: [],
|
||||
hidden: [],
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
loadInitialFields();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [params.entity, params.group, customSearchParams, template]);
|
||||
|
||||
useEffect(() => {
|
||||
if (onChange) {
|
||||
onChange(headers);
|
||||
}
|
||||
}, [headers, onChange]);
|
||||
|
||||
// useEffect(() => {
|
||||
// if (headers.length > 0) {
|
||||
// rowValueInput.current?.focus();
|
||||
// }
|
||||
// }, [headers])
|
||||
|
||||
// useEffect(() => {
|
||||
// if (actionData?.newRow && onCreated) {
|
||||
// onCreated(actionData.newRow);
|
||||
// }
|
||||
// // eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
// }, [actionData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (searchingRelationshipRows?.parentId === entity.id) {
|
||||
setSelectedRelatedEntity({
|
||||
entity: searchingRelationshipRows.child,
|
||||
view: searchingRelationshipRows.childEntityView,
|
||||
multiple: true,
|
||||
});
|
||||
} else if (searchingRelationshipRows?.childId === entity.id) {
|
||||
setSelectedRelatedEntity({
|
||||
entity: searchingRelationshipRows.parent,
|
||||
view: searchingRelationshipRows.parentEntityView,
|
||||
multiple: false,
|
||||
});
|
||||
}
|
||||
}, [entity.id, searchingRelationshipRows]);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
save,
|
||||
}));
|
||||
function save() {
|
||||
formGroup.current?.submitForm();
|
||||
}
|
||||
|
||||
function loadInitialFields() {
|
||||
const initial: RowValueDto[] = [];
|
||||
if (template && !customSearchParams) {
|
||||
const config = JSON.parse(template.config);
|
||||
const defaultValues: { [key: string]: any } = {};
|
||||
Object.keys(config).forEach((key) => {
|
||||
defaultValues[key] = config[key];
|
||||
});
|
||||
customSearchParams = new URLSearchParams(defaultValues);
|
||||
}
|
||||
entity.properties
|
||||
?.filter((f) => isPropertyVisible(f))
|
||||
.forEach((property) => {
|
||||
const existing = item?.values?.find((f) => f?.propertyId === property.id);
|
||||
|
||||
let urlSearchParams = customSearchParams ?? searchParams;
|
||||
const defaultValueString =
|
||||
RowUrlHelper.getString({ urlSearchParams, property }) ??
|
||||
PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.DefaultValue);
|
||||
const defaultValueNumber =
|
||||
RowUrlHelper.getNumber({ urlSearchParams, property }) ??
|
||||
PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.DefaultValue);
|
||||
const defaultValueBoolean =
|
||||
RowUrlHelper.getBoolean({ urlSearchParams, property }) ??
|
||||
PropertyAttributeHelper.getPropertyAttributeValue_Boolean(property, PropertyAttributeName.DefaultValue);
|
||||
|
||||
let defaultDate = RowUrlHelper.getDate({ urlSearchParams, property }) ?? undefined;
|
||||
const defaultRange = RowUrlHelper.getRange({ urlSearchParams, property }) ?? undefined;
|
||||
|
||||
const defaultMultiple = RowUrlHelper.getMultiple({ urlSearchParams, property }) ?? undefined;
|
||||
|
||||
initial.push({
|
||||
propertyId: property.id,
|
||||
property: property,
|
||||
textValue: existing?.textValue ?? defaultValueString ?? undefined,
|
||||
numberValue: existing?.numberValue ? Number(existing?.numberValue) : defaultValueNumber,
|
||||
dateValue: existing?.dateValue ?? defaultDate,
|
||||
booleanValue: existing ? Boolean(existing?.booleanValue) : defaultValueBoolean,
|
||||
selectedOption: existing?.textValue ?? defaultValueString ?? undefined,
|
||||
media: existing?.media ?? [],
|
||||
multiple: existing?.multiple.sort((a: RowValueMultipleDto, b: RowValueMultipleDto) => a.order - b.order) ?? defaultMultiple ?? [],
|
||||
range: existing?.range ?? defaultRange,
|
||||
});
|
||||
});
|
||||
|
||||
const relatedRows: { relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[] = [];
|
||||
if (item) {
|
||||
entity.parentEntities.forEach((relationship) => {
|
||||
if (item.parentRows?.length > 0) {
|
||||
relatedRows.push({
|
||||
relationship,
|
||||
rows: item.parentRows.filter((f) => f.relationshipId === relationship.id).map((i) => i.parent),
|
||||
});
|
||||
}
|
||||
});
|
||||
entity.childEntities.forEach((relationship) => {
|
||||
if (item.childRows?.length > 0) {
|
||||
relatedRows.push({
|
||||
relationship,
|
||||
rows: item.childRows.filter((f) => f.relationshipId === relationship.id).map((i) => i.child),
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
entity.parentEntities.forEach((relationship) => {
|
||||
const rowId = customSearchParams?.get(relationship.parent.name) ?? searchParams.get(relationship.parent.name);
|
||||
if (rowId) {
|
||||
const foundRow = relationshipRows
|
||||
?.filter((f) => f.relationship.id === relationship.id)
|
||||
.map((m) => m.rows)
|
||||
.flat()
|
||||
.find((f) => f.id === rowId);
|
||||
relatedRows.push({
|
||||
relationship,
|
||||
rows: foundRow ? [foundRow] : [],
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const allChildren = entity.childEntities.filter((f) => childEntityVisible(f) && allEntities.find((x) => x.id === f.childId));
|
||||
setChildrenEntities(getVisibleRelatedEntities(allChildren, relatedRows));
|
||||
const allParents = entity.parentEntities.filter((f) => f.parentId !== parentEntity?.id && allEntities.find((x) => x.id === f.parentId));
|
||||
setParentEntities(getVisibleRelatedEntities(allParents, relatedRows));
|
||||
|
||||
setHeaders(initial);
|
||||
setRelatedRows(relatedRows);
|
||||
}
|
||||
|
||||
function onFindEntityRows(relationship: EntityRelationshipWithDetails) {
|
||||
if (!routes) {
|
||||
return;
|
||||
}
|
||||
setSearchingRelationshipRows(relationship);
|
||||
}
|
||||
|
||||
function addRelationshipRow(relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) {
|
||||
const newRelatedRows = [...relatedRows];
|
||||
const existing = newRelatedRows.find((f) => f.relationship.id === relationship.id);
|
||||
if (existing) {
|
||||
if (relationship.parentId === entity.id) {
|
||||
const nonExistingRows = rows.filter((f) => !existing.rows.find((ff) => ff.id === f.id));
|
||||
existing.rows = [...existing.rows, ...nonExistingRows];
|
||||
} else {
|
||||
existing.rows = rows;
|
||||
}
|
||||
} else {
|
||||
newRelatedRows.push({ relationship, rows });
|
||||
}
|
||||
setRelatedRows(newRelatedRows);
|
||||
}
|
||||
|
||||
function setRelationshipRows(relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) {
|
||||
const newRelatedRows = [...relatedRows];
|
||||
const existing = newRelatedRows.find((f) => f.relationship.id === relationship.id);
|
||||
if (existing) {
|
||||
existing.rows = rows;
|
||||
} else {
|
||||
newRelatedRows.push({ relationship, rows });
|
||||
}
|
||||
setRelatedRows(newRelatedRows);
|
||||
}
|
||||
|
||||
function onRemoveRelatedRow(relationship: EntityRelationshipWithDetails, row: RowWithValues) {
|
||||
const newRelatedRows = [...relatedRows];
|
||||
const existing = newRelatedRows.find((f) => f.relationship.id === relationship.id);
|
||||
if (existing) {
|
||||
existing.rows = existing.rows.filter((f) => f.id !== row.id);
|
||||
}
|
||||
setRelatedRows(newRelatedRows);
|
||||
}
|
||||
|
||||
function submitForm(formData: FormData) {
|
||||
if (onSubmit) {
|
||||
onSubmit(formData);
|
||||
} else {
|
||||
submit(formData, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function isPropertyVisible(f: PropertyWithDetails) {
|
||||
if (f.isHidden || (!item && !f.showInCreate) || (!item && f.isReadOnly) || (item && editing && f.isReadOnly)) {
|
||||
return false;
|
||||
} else if (hiddenProperties?.includes(f.name)) {
|
||||
return false;
|
||||
}
|
||||
if (item && editing && !f.canUpdate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function childEntityVisible(f: EntityRelationshipWithDetails) {
|
||||
if (f.readOnly) {
|
||||
if (!item) {
|
||||
return false;
|
||||
}
|
||||
if (item && editing) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function canSubmitForm() {
|
||||
if (!canSubmit) {
|
||||
return false;
|
||||
}
|
||||
const required = headers.filter((f) => f.property.isRequired);
|
||||
let hasError = false;
|
||||
required.forEach((f) => {
|
||||
if (f.property.type === PropertyType.MEDIA) {
|
||||
if (f.media?.length === 0) {
|
||||
hasError = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
return !hasError;
|
||||
}
|
||||
|
||||
function isAddingOrEditing() {
|
||||
if (adding) {
|
||||
return true;
|
||||
}
|
||||
if (editing && item && canUpdate && navigation.state === "idle") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function onSaveIfAllSet() {
|
||||
return;
|
||||
// if (item) {
|
||||
// return;
|
||||
// }
|
||||
// const missingValues = headers
|
||||
// .filter((f) => isPropertyVisible(f.property))
|
||||
// .map((header) => {
|
||||
// if ([PropertyType.TEXT, PropertyType.SELECT].includes(header.property.type) && !header.textValue) {
|
||||
// return header;
|
||||
// } else if ([PropertyType.NUMBER].includes(header.property.type) && !header.numberValue) {
|
||||
// return header;
|
||||
// } else if ([PropertyType.DATE].includes(header.property.type) && !header.dateValue) {
|
||||
// return header;
|
||||
// }
|
||||
// // else if ([PropertyType.MEDIA].includes(header.property.type) && (!header.media || header.media.length === 0)) {
|
||||
// // return header;
|
||||
// // }
|
||||
// else if ([PropertyType.MULTI_SELECT].includes(header.property.type) && (!header.multiple || header.multiple.length === 0)) {
|
||||
// return header;
|
||||
// }
|
||||
// return null;
|
||||
// });
|
||||
// const rowValues = missingValues.filter((f) => f !== null);
|
||||
|
||||
// if (rowValues.length === 0) {
|
||||
// formGroup.current?.submitForm();
|
||||
// }
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<FormGroup
|
||||
ref={formGroup}
|
||||
id={item?.id}
|
||||
editing={editing}
|
||||
canDelete={canDelete}
|
||||
onSubmit={submitForm}
|
||||
onDelete={onDelete}
|
||||
canUpdate={canUpdate}
|
||||
canSubmit={canSubmit}
|
||||
onCancel={onCancel}
|
||||
submitDisabled={!canSubmitForm()}
|
||||
onCreatedRedirect={onCreatedRedirect}
|
||||
deleteRedirect={EntityHelper.getRoutes({ routes, entity })?.list}
|
||||
state={state}
|
||||
message={
|
||||
createdRow
|
||||
? { success: t("shared.created") + ": " + RowHelper.getTextDescription({ entity, item: createdRow, t, defaultsToFolio: true }) }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{hiddenFields &&
|
||||
Object.keys(hiddenFields).map((f) => {
|
||||
return <Fragment key={f}>{hiddenFields[f] && <input type="hidden" name={f} value={hiddenFields[f] ?? ""} hidden readOnly />}</Fragment>;
|
||||
})}
|
||||
{!onSubmit && (
|
||||
<>
|
||||
{!item ? (
|
||||
<input type="hidden" name="redirect" value={EntityHelper.getRoutes({ routes, entity })?.list} hidden readOnly />
|
||||
) : (
|
||||
<input type="hidden" name="redirect" value={EntityHelper.getRoutes({ routes, entity, item })?.overview} hidden readOnly />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{onCreatedRedirect && <input type="hidden" name="onCreatedRedirect" value={onCreatedRedirect} hidden readOnly />}
|
||||
<RowGroups
|
||||
item={item}
|
||||
entity={entity}
|
||||
rowValues={headers}
|
||||
parentEntity={parentEntity}
|
||||
allEntities={allEntities}
|
||||
relatedRows={relatedRows}
|
||||
editing={editing}
|
||||
canUpdate={canUpdate}
|
||||
routes={routes}
|
||||
relationshipRows={relationshipRows}
|
||||
setHeaders={setHeaders}
|
||||
addRelationshipRow={addRelationshipRow}
|
||||
setRelationshipRows={setRelationshipRows}
|
||||
onFindEntityRows={onFindEntityRows}
|
||||
onRemoveRelatedRow={onRemoveRelatedRow}
|
||||
isPropertyVisible={isPropertyVisible}
|
||||
children={children}
|
||||
canSubmit={canSubmit}
|
||||
isAddingOrEditing={isAddingOrEditing()}
|
||||
parentEntities={{
|
||||
visible: parentEntities.visible,
|
||||
hidden: parentEntities.hidden,
|
||||
onAddParentEntity: (rel) => {
|
||||
setParentEntities((prev) => {
|
||||
return {
|
||||
visible: [...prev.visible, rel],
|
||||
hidden: prev.hidden.filter((f) => f.id !== rel.id),
|
||||
};
|
||||
});
|
||||
},
|
||||
}}
|
||||
onSaveIfAllSet={onSaveIfAllSet}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-12">
|
||||
{childrenEntities.visible.map((relationship) => (
|
||||
<div key={relationship.id} className="col-span-12">
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-foreground text-sm leading-3 font-medium">
|
||||
<div className="flex items-center space-x-1">
|
||||
<div>
|
||||
<span className="font-light italic"></span> {t(RelationshipHelper.getTitle({ fromEntityId: entity.id, relationship }))}
|
||||
{/* {relationship.required && <span className="ml-1 text-red-500">*</span>} */}
|
||||
</div>
|
||||
</div>
|
||||
</h3>
|
||||
<RelationshipSelector
|
||||
fromEntity={entity}
|
||||
type="child"
|
||||
relationship={relationship}
|
||||
relatedRows={relatedRows}
|
||||
onFindEntityRows={onFindEntityRows}
|
||||
allEntities={allEntities}
|
||||
onRemoveRelatedRow={onRemoveRelatedRow}
|
||||
readOnly={item?.id !== undefined && (!editing || !canUpdate)}
|
||||
routes={routes}
|
||||
relationshipRows={relationshipRows}
|
||||
addRelationshipRow={addRelationshipRow}
|
||||
setRelationshipRows={setRelationshipRows}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{isAddingOrEditing() && (
|
||||
<AddHiddenRelationshipEntities
|
||||
items={childrenEntities.hidden}
|
||||
onClick={(rel) => {
|
||||
setChildrenEntities((prev) => {
|
||||
return {
|
||||
visible: [...prev.visible, rel],
|
||||
hidden: prev.hidden.filter((f) => f.id !== rel.id),
|
||||
};
|
||||
});
|
||||
}}
|
||||
type="child"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{relatedRows.map(({ relationship, rows }) => (
|
||||
<Fragment key={relationship.id}>
|
||||
{rows.map((row) => (
|
||||
// <>
|
||||
<input
|
||||
key={row.id}
|
||||
type="hidden"
|
||||
readOnly
|
||||
hidden
|
||||
name={`${relationship.childId === entity.id ? `parents[${relationship.parent.name}]` : `children[${relationship.child.name}]`}`}
|
||||
value={row.id}
|
||||
/>
|
||||
// </>
|
||||
))}
|
||||
</Fragment>
|
||||
))}
|
||||
</FormGroup>
|
||||
{/* // <OpenModal className="sm:max-w-4xl" onClose={() => setSearchingRelationshipRows(undefined)}> */}
|
||||
<SlideOverWideEmpty
|
||||
withTitle={false}
|
||||
withClose={false}
|
||||
title={t("shared.select")}
|
||||
open={searchingRelationshipRows !== undefined}
|
||||
onClose={() => setSearchingRelationshipRows(undefined)}
|
||||
>
|
||||
{selectedRelatedEntity && searchingRelationshipRows && (
|
||||
<RowListFetcher
|
||||
currentView={selectedRelatedEntity.view}
|
||||
listUrl={EntityHelper.getRoutes({ routes, entity: selectedRelatedEntity.entity })?.list + "?view=null"}
|
||||
newUrl={EntityHelper.getRoutes({ routes, entity: selectedRelatedEntity.entity })?.new ?? ""}
|
||||
parentEntity={entity}
|
||||
onSelected={(rows) => {
|
||||
addRelationshipRow(searchingRelationshipRows, rows);
|
||||
setSearchingRelationshipRows(undefined);
|
||||
}}
|
||||
multipleSelection={selectedRelatedEntity.multiple}
|
||||
allEntities={allEntities}
|
||||
/>
|
||||
)}
|
||||
</SlideOverWideEmpty>
|
||||
{/* // </OpenModal> */}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
function RelationshipSelector({
|
||||
fromEntity,
|
||||
routes,
|
||||
type,
|
||||
relationship,
|
||||
relatedRows,
|
||||
onFindEntityRows,
|
||||
className,
|
||||
allEntities,
|
||||
onRemoveRelatedRow,
|
||||
readOnly,
|
||||
relationshipRows,
|
||||
addRelationshipRow,
|
||||
setRelationshipRows,
|
||||
}: {
|
||||
fromEntity: EntityWithDetails;
|
||||
type: "child" | "parent";
|
||||
relationship: EntityRelationshipWithDetails;
|
||||
relatedRows: { relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[];
|
||||
onFindEntityRows: (relationship: EntityRelationshipWithDetails) => void;
|
||||
className?: string;
|
||||
allEntities: EntityWithDetails[];
|
||||
onRemoveRelatedRow: (relationship: EntityRelationshipWithDetails, row: RowWithValues) => void;
|
||||
readOnly: boolean;
|
||||
routes?: EntitiesApi.Routes;
|
||||
relationshipRows?: RowsApi.GetRelationshipRowsData;
|
||||
addRelationshipRow: (relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) => void;
|
||||
setRelationshipRows: (relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [entity] = useState(
|
||||
type === "parent"
|
||||
? {
|
||||
entity: getChildEntity(relationship)!,
|
||||
view: relationship.parentEntityView,
|
||||
}
|
||||
: {
|
||||
entity: getParentEntity(relationship)!,
|
||||
view: relationship.childEntityView,
|
||||
}
|
||||
);
|
||||
|
||||
function getRows(relationship: EntityRelationshipWithDetails) {
|
||||
const existing = relatedRows.find((f) => f.relationship.id === relationship.id);
|
||||
return existing?.rows.sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) ?? [];
|
||||
}
|
||||
function getParentEntity(relationship: EntityRelationshipWithDetails) {
|
||||
return allEntities.find((f) => f.id === relationship.childId);
|
||||
}
|
||||
function getChildEntity(relationship: EntityRelationshipWithDetails) {
|
||||
return allEntities.find((f) => f.id === relationship.parentId);
|
||||
}
|
||||
return (
|
||||
<div className={className}>
|
||||
{/* <div>selectedRow: {getSelectedRow()}</div>
|
||||
<div>
|
||||
options:{" "}
|
||||
{getOptions()
|
||||
.map((f) => f.value)
|
||||
.join(",")}
|
||||
</div>
|
||||
<div>
|
||||
{relatedRows.filter((f) => f.relationship.id === relationship.id).length > 0 &&
|
||||
relatedRows
|
||||
.filter((f) => f.relationship.id === relationship.id)[0]
|
||||
.rows.map((f) => f.id)
|
||||
.join(",")}
|
||||
</div> */}
|
||||
{/* {RelationshipHelper.getInputType({ fromEntityId: fromEntity.id, relationship }) === "single-select" ? (
|
||||
<InputSelector
|
||||
className="mt-1"
|
||||
name={relationship.parent.name}
|
||||
disabled={readOnly}
|
||||
value={getSelectedRow()}
|
||||
options={getOptions()}
|
||||
setValue={(value) => {
|
||||
const row = relationshipRows?.find((f) => f.relationship.id === relationship.id)?.rows.find((f) => f.id === value);
|
||||
if (row) {
|
||||
setRelationshipRows(relationship, [row]);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : RelationshipHelper.getInputType({ fromEntityId: fromEntity.id, relationship }) === "multi-select" ? (
|
||||
<> */}
|
||||
{getRows(relationship).length === 0 ? (
|
||||
<button
|
||||
onClick={() => onFindEntityRows(relationship)}
|
||||
type="button"
|
||||
disabled={readOnly}
|
||||
className={clsx(
|
||||
"border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center",
|
||||
readOnly ? "bg-secondary/90 cursor-not-allowed" : "bg-background hover:border-border focus:ring-2 focus:ring-gray-500 focus:outline-hidden"
|
||||
)}
|
||||
>
|
||||
<span className="text-muted-foreground flex items-center space-x-1 text-xs font-normal">
|
||||
{readOnly ? (
|
||||
<div>{t("shared.notSet")}</div>
|
||||
) : (
|
||||
<>
|
||||
{type === "parent" && (
|
||||
<>
|
||||
<div>{t("shared.select")}</div>
|
||||
<div className="lowercase">{translateEntityTitle(t, i18n, relationship.parent)}</div>
|
||||
</>
|
||||
)}
|
||||
{type === "child" && (
|
||||
<>
|
||||
<div>{t("shared.add")}</div>
|
||||
<div className="lowercase">{translateEntityTitle(t, i18n, relationship.child)}</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="relative space-y-2 overflow-visible">
|
||||
<RowsList
|
||||
entity={entity.entity}
|
||||
items={getRows(relationship) as RowWithDetails[]}
|
||||
currentView={entity.view}
|
||||
view={(entity.view?.layout ?? "card") as "table" | "board" | "grid" | "card"}
|
||||
readOnly={readOnly}
|
||||
onRemove={readOnly ? undefined : (row) => onRemoveRelatedRow(relationship, row)}
|
||||
ignoreColumns={!readOnly ? [RowDisplayDefaultProperty.FOLIO, "parent." + relationship.parent.name, "child." + relationship.child.name] : []}
|
||||
routes={routes}
|
||||
/>
|
||||
{/* {getRows(relationship).map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className={clsx(
|
||||
"group relative w-full overflow-visible truncate rounded-md border border-border px-4 py-3 text-left text-sm",
|
||||
!readOnly ? "bg-background hover:border-border" : "bg-secondary/90"
|
||||
)}
|
||||
>
|
||||
<button
|
||||
onClick={() => onRemoveRelatedRow(relationship, item)}
|
||||
type="button"
|
||||
disabled={readOnly}
|
||||
className={clsx(
|
||||
"absolute right-0 top-0 mr-2 mt-2 hidden origin-top-right justify-center rounded-full bg-background text-muted-foreground",
|
||||
readOnly ? "cursor-not-allowed" : "hover:text-red-500 group-hover:flex"
|
||||
)}
|
||||
>
|
||||
<svg className="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
<div>{RowHelper.getTextDescription({ entity, item, t, defaultsToFolio: true })}</div>
|
||||
</div>
|
||||
</div>
|
||||
))} */}
|
||||
<button
|
||||
onClick={() => onFindEntityRows(relationship)}
|
||||
type="button"
|
||||
className={clsx(
|
||||
"hover:bg-secondary border-border text-muted-foreground hover:border-border relative flex space-x-1 rounded-md border border-dashed px-2 py-1 text-center text-xs focus:ring-1 focus:ring-gray-500 focus:outline-hidden",
|
||||
readOnly && "hidden"
|
||||
)}
|
||||
>
|
||||
{type === "parent" && (
|
||||
<>
|
||||
<div>{t("shared.select")}</div>
|
||||
<div className="lowercase">{translateEntityTitle(t, i18n, relationship.parent)}</div>
|
||||
</>
|
||||
)}
|
||||
{type === "child" && (
|
||||
<>
|
||||
<div>{t("shared.add")}</div>
|
||||
<div className="lowercase">{translateEntityTitle(t, i18n, relationship.child)}</div>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{/* </>
|
||||
) : null} */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RowGroups({
|
||||
item,
|
||||
entity,
|
||||
rowValues,
|
||||
parentEntity,
|
||||
allEntities,
|
||||
relatedRows,
|
||||
editing,
|
||||
canUpdate,
|
||||
routes,
|
||||
relationshipRows,
|
||||
setHeaders,
|
||||
addRelationshipRow,
|
||||
setRelationshipRows,
|
||||
onFindEntityRows,
|
||||
onRemoveRelatedRow,
|
||||
isPropertyVisible,
|
||||
children,
|
||||
canSubmit,
|
||||
isAddingOrEditing,
|
||||
parentEntities,
|
||||
onSaveIfAllSet,
|
||||
}: {
|
||||
item?: RowWithDetails | null;
|
||||
entity: EntityWithDetails;
|
||||
rowValues: RowValueDto[];
|
||||
parentEntity?: EntityWithDetails;
|
||||
allEntities: EntityWithDetails[];
|
||||
relatedRows: { relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[];
|
||||
editing?: boolean;
|
||||
canUpdate?: boolean;
|
||||
routes?: EntitiesApi.Routes;
|
||||
relationshipRows?: RowsApi.GetRelationshipRowsData;
|
||||
setHeaders: Dispatch<SetStateAction<RowValueDto[]>>;
|
||||
addRelationshipRow: (relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) => void;
|
||||
setRelationshipRows: (relationship: EntityRelationshipWithDetails, rows: RowWithDetails[]) => void;
|
||||
onFindEntityRows: (relationship: EntityRelationshipWithDetails) => void;
|
||||
onRemoveRelatedRow: (relationship: EntityRelationshipWithDetails, row: RowWithValues) => void;
|
||||
isPropertyVisible: (property: PropertyWithDetails) => boolean;
|
||||
children?: ReactNode;
|
||||
canSubmit?: boolean;
|
||||
isAddingOrEditing: boolean;
|
||||
parentEntities: {
|
||||
visible: EntityRelationshipWithDetails[];
|
||||
hidden: EntityRelationshipWithDetails[];
|
||||
onAddParentEntity: (item: EntityRelationshipWithDetails) => void;
|
||||
};
|
||||
onSaveIfAllSet: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const rowValueInput = useRef<RefRowValueInput>(null);
|
||||
|
||||
const groups = useMemo(() => {
|
||||
const groups: { group?: string; headers: RowValueDto[] }[] = [];
|
||||
rowValues.forEach((header) => {
|
||||
const groupName = PropertyAttributeHelper.getPropertyAttributeValue_String(header.property, PropertyAttributeName.Group);
|
||||
let found = groups.find((f) => f.group === groupName);
|
||||
if (!found) {
|
||||
found = groups.find((f) => !f.group && !groupName);
|
||||
}
|
||||
if (found) {
|
||||
found.headers.push(header);
|
||||
} else {
|
||||
groups.push({
|
||||
group: groupName,
|
||||
headers: [header],
|
||||
});
|
||||
}
|
||||
});
|
||||
if (groups.length === 0) {
|
||||
groups.push({ headers: rowValues });
|
||||
}
|
||||
return groups;
|
||||
}, [rowValues]);
|
||||
|
||||
function getPropertyColumnSpan(property: PropertyWithDetails) {
|
||||
const columns = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Columns);
|
||||
if (columns === undefined || isNaN(columns) || (columns < 1 && columns > 12)) {
|
||||
return "col-span-12";
|
||||
}
|
||||
return `col-span-${columns}`;
|
||||
}
|
||||
function onChange(rowValue: RowValueDto) {
|
||||
setHeaders((prev) => {
|
||||
return prev.map((f) => {
|
||||
if (f.propertyId === rowValue.propertyId) {
|
||||
return rowValue;
|
||||
}
|
||||
return f;
|
||||
});
|
||||
});
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{groups.map(({ group, headers }, idx) => {
|
||||
return (
|
||||
<InputGroup key={idx} title={group ? t(group) : t("shared.details")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
{headers.map((detailValue, idxDetailValue) => {
|
||||
return (
|
||||
<div key={detailValue.propertyId} className={clsx("w-full", getPropertyColumnSpan(detailValue.property))}>
|
||||
<RowValueInput
|
||||
ref={rowValueInput}
|
||||
entity={entity}
|
||||
textValue={detailValue.textValue}
|
||||
numberValue={detailValue.numberValue}
|
||||
dateValue={detailValue.dateValue}
|
||||
booleanValue={detailValue.booleanValue}
|
||||
multiple={detailValue.multiple}
|
||||
range={detailValue.range}
|
||||
initialOption={detailValue.selectedOption}
|
||||
selected={detailValue.property}
|
||||
initialMedia={detailValue.media}
|
||||
onChange={(e) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
...RowHelper.updateFieldValueTypeArray(detailValue, e),
|
||||
});
|
||||
}}
|
||||
onChangeOption={(e) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
selectedOption: e,
|
||||
textValue: e,
|
||||
});
|
||||
}}
|
||||
onChangeMedia={(media) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
media: media as any,
|
||||
});
|
||||
if (media.filter((f) => f.type).length > 0) {
|
||||
onSaveIfAllSet();
|
||||
}
|
||||
}}
|
||||
onChangeMultiple={(e) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
multiple: e as any[],
|
||||
});
|
||||
}}
|
||||
onChangeRange={(e) => {
|
||||
onChange({
|
||||
...detailValue,
|
||||
range: e as any,
|
||||
});
|
||||
}}
|
||||
readOnly={
|
||||
(editing && !detailValue.property.canUpdate) || (item?.id !== undefined && (!editing || !canUpdate)) || detailValue.property?.isReadOnly
|
||||
}
|
||||
autoFocus={idx === 0 && idxDetailValue === 0 && canSubmit}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{/* Show parent entities in Default Properties Group */}
|
||||
{!group && (
|
||||
<>
|
||||
{parentEntities.visible.map((relationship) => (
|
||||
<div key={relationship.id} className="col-span-12">
|
||||
<label htmlFor={relationship.id} className="text-muted-foreground flex items-center justify-between space-x-2 text-xs font-medium">
|
||||
<span className="truncate">
|
||||
{t(RelationshipHelper.getTitle({ fromEntityId: entity.id, relationship }))}
|
||||
{relationship.required && <span className="ml-1 text-red-500">*</span>}
|
||||
</span>
|
||||
</label>
|
||||
<RelationshipSelector
|
||||
fromEntity={entity}
|
||||
className="mt-1"
|
||||
type="parent"
|
||||
relationship={relationship}
|
||||
relatedRows={relatedRows}
|
||||
onFindEntityRows={onFindEntityRows}
|
||||
allEntities={allEntities}
|
||||
onRemoveRelatedRow={onRemoveRelatedRow}
|
||||
readOnly={item?.id !== undefined && (!editing || !canUpdate)}
|
||||
routes={routes}
|
||||
relationshipRows={relationshipRows}
|
||||
addRelationshipRow={addRelationshipRow}
|
||||
setRelationshipRows={setRelationshipRows}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{isAddingOrEditing && (
|
||||
<AddHiddenRelationshipEntities items={parentEntities.hidden} onClick={parentEntities.onAddParentEntity} type="parent" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{/* Show custom properties in Default Properties Group */}
|
||||
{!group && <>{children}</>}
|
||||
</div>
|
||||
</InputGroup>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AddHiddenRelationshipEntities({
|
||||
items,
|
||||
onClick,
|
||||
type,
|
||||
}: {
|
||||
items: EntityRelationshipWithDetails[];
|
||||
onClick: (item: EntityRelationshipWithDetails) => void;
|
||||
type: "parent" | "child";
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
return (
|
||||
<Fragment>
|
||||
{items.length > 0 && (
|
||||
<div className="col-span-12 flex flex-wrap items-center">
|
||||
{items.map((relationship) => (
|
||||
<button
|
||||
key={relationship.id}
|
||||
type="button"
|
||||
onClick={() => onClick(relationship)}
|
||||
className="text-muted-foreground bg-secondary/90 m-0.5 w-auto rounded-md px-2 py-1 text-xs font-medium hover:bg-gray-200"
|
||||
>
|
||||
{t("shared.add")} {type === "parent" ? translateEntityTitle(t, i18n, relationship.parent) : translateEntityTitle(t, i18n, relationship.child)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function getVisibleRelatedEntities(
|
||||
entityRelationships: EntityRelationshipWithDetails[],
|
||||
relatedRows: { relationship: EntityRelationshipWithDetails; rows: RowWithValues[] }[]
|
||||
) {
|
||||
const visible = entityRelationships.filter((f) => !f.hiddenIfEmpty);
|
||||
const hidden: EntityRelationshipWithDetails[] = [];
|
||||
|
||||
entityRelationships
|
||||
.filter((f) => f.hiddenIfEmpty)
|
||||
.forEach((relationship) => {
|
||||
const rows = relatedRows.filter((f) => f.relationship.id === relationship.id).flatMap((f) => f.rows);
|
||||
if (rows.length > 0) {
|
||||
visible.push(relationship);
|
||||
} else {
|
||||
hidden.push(relationship);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
visible,
|
||||
hidden,
|
||||
};
|
||||
}
|
||||
|
||||
export default forwardRef(RowForm);
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useLocation, useSubmit, useNavigation } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ApiKeyBadge from "~/components/core/users/ApiKeyBadge";
|
||||
import UserAvatarBadge from "~/components/core/users/UserAvatarBadge";
|
||||
import UserBadge from "~/components/core/users/UserBadge";
|
||||
import ChatAltIcon from "~/components/ui/icons/ChatAltIcon";
|
||||
import ThumbsUpEmptyIcon from "~/components/ui/icons/ThumbsUpEmptyIcon";
|
||||
import ThumbsUpFilledIcon from "~/components/ui/icons/ThumbsUpFilledIcon";
|
||||
import TrashEmptyIcon from "~/components/ui/icons/TrashEmptyIcon";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { renderSanitizedMarkdown } from "~/utils/html-sanitizer";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
interface Props {
|
||||
item: LogWithDetails;
|
||||
}
|
||||
export default function RowLogComment({ item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const submit = useSubmit();
|
||||
const { user } = useAppOrAdminData();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "comment-reaction";
|
||||
const isDeleting = navigation.state === "submitting" && navigation.formData?.get("action") === "comment-delete";
|
||||
|
||||
function onReacted(reaction: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "comment-reaction");
|
||||
form.set("comment-id", item.comment?.id ?? "");
|
||||
form.set("reaction", reaction);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
|
||||
function onDeleted() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "comment-delete");
|
||||
form.set("comment-id", item.comment?.id ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
|
||||
function getReactions(reaction: string) {
|
||||
return item.comment?.reactions.filter((f) => f.reaction === reaction) ?? [];
|
||||
}
|
||||
function hasMyReaction(reaction: string) {
|
||||
return item.comment?.reactions.find((f) => f.createdByUserId === user?.id && f.reaction === reaction);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{item.comment && (
|
||||
<>
|
||||
<div className="relative px-1">
|
||||
<UserAvatarBadge className="h-9 w-9" avatar={item.user?.avatar} />
|
||||
|
||||
<span className="bg-secondary absolute -bottom-0.5 -right-1 rounded-tl px-0.5 py-px">
|
||||
<ChatAltIcon className="text-muted-foreground h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
</div>
|
||||
<div className="group min-w-0 flex-1 space-y-0.5">
|
||||
<div>
|
||||
<div className="text-sm">
|
||||
<div className="text-foreground font-medium">
|
||||
{item.user && <UserBadge item={item.user} withEmail={false} />}
|
||||
{item.apiKey && <ApiKeyBadge item={item.apiKey} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-muted-foreground text-sm font-normal">
|
||||
{item.comment.isDeleted ? (
|
||||
<p className="text-muted-foreground italic">{t("shared.commentDeleted")}</p>
|
||||
) : (
|
||||
<div className="prose border-border rounded-md border border-dashed p-2 text-sm">
|
||||
<div dangerouslySetInnerHTML={{ __html: renderSanitizedMarkdown(item.comment.value) }} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-muted-foreground flex items-center justify-between space-x-1 font-medium">
|
||||
<time dateTime={new Date(item.createdAt).toISOString()} title={formatters.dateTime(item.createdAt, { timeStyle: "medium" })}>
|
||||
{formatters.relativeDate(item.createdAt)}
|
||||
</time>
|
||||
<div className="group flex items-center space-x-2">
|
||||
{!item.comment.isDeleted && item.comment.createdByUserId === user?.id && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isDeleting}
|
||||
onClick={() => onDeleted()}
|
||||
className="text-muted-foreground hover:text-muted-foreground invisible p-0.5 focus:outline-hidden group-hover:visible"
|
||||
>
|
||||
<div className="flex items-center space-x-1">
|
||||
<TrashEmptyIcon className="h-4 w-4" />
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={isAdding}
|
||||
onClick={() => onReacted("like")}
|
||||
className={clsx(
|
||||
"text-muted-foreground hover:text-muted-foreground p-0.5 focus:outline-hidden",
|
||||
getReactions("like").length === 0 && "invisible group-hover:visible"
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className="flex items-center space-x-1"
|
||||
title={
|
||||
getReactions("like")
|
||||
?.map((f) => `${f.createdByUser?.firstName} ${f.createdByUser?.lastName}`)
|
||||
.join(", ") ?? ""
|
||||
}
|
||||
>
|
||||
{(getReactions("like")?.length ?? 0) > 0 && <div className="">{getReactions("like")?.length ?? 0}</div>}
|
||||
{hasMyReaction("like") ? <ThumbsUpFilledIcon className="h-4 w-4" /> : <ThumbsUpEmptyIcon className="h-4 w-4" />}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LogWithDetails } from "~/utils/db/logs.db.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { CalendarIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
items: LogWithDetails[];
|
||||
}
|
||||
|
||||
export default function RowLogs({ items }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
const sortedItems = () => {
|
||||
return items.slice().sort((x, y) => {
|
||||
if (x.createdAt && y.createdAt) {
|
||||
return x.createdAt > y.createdAt ? -1 : 1;
|
||||
}
|
||||
return -1;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">
|
||||
<div className="flex items-center space-x-1">
|
||||
<div>
|
||||
<span className=" font-light italic"></span> {t("app.shared.activity.title")}
|
||||
</div>
|
||||
</div>
|
||||
</h3>
|
||||
<div className="bg-background border-border rounded-md border px-4 py-5 shadow-xs">
|
||||
<div className="flow-root">
|
||||
<ul className="-mb-8">
|
||||
{sortedItems().length === 0 && <div className=" text-muted-foreground mb-6 flex justify-center text-sm italic">{t("models.row.logs.noEvents")}</div>}
|
||||
{sortedItems().map((activity, idxActivity) => {
|
||||
return (
|
||||
<li key={idxActivity}>
|
||||
<div className="relative pb-8">
|
||||
{items.length > 0 && idxActivity + 1 < items.length && (
|
||||
<span className="absolute left-4 top-4 -ml-px h-full w-0.5 bg-gray-200" aria-hidden="true"></span>
|
||||
)}
|
||||
|
||||
<div className="relative flex space-x-3">
|
||||
<div>
|
||||
<span className={clsx("bg-secondary/90 flex h-8 w-8 items-center justify-center rounded-full ring-8 ring-white")}>
|
||||
<CalendarIcon className="text-muted-foreground h-4 w-4" />
|
||||
</span>
|
||||
</div>
|
||||
<div className="grow">
|
||||
<div className="flex min-w-0 flex-1 justify-between space-x-4">
|
||||
<div className="truncate">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
<div className="text-foreground truncate">
|
||||
<span title={activity.action}>{activity.action}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-muted-foreground truncate whitespace-nowrap text-right text-xs lowercase">
|
||||
{activity.createdAt && (
|
||||
<time dateTime={new Date(activity.createdAt).toISOString()} title={formatters.dateTime(activity.createdAt, { timeStyle: "medium" })}>
|
||||
{formatters.date(activity.createdAt, { month: "short", day: "numeric" })}, {formatters.date(activity.createdAt, { timeStyle: "medium" })}
|
||||
</time>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 justify-between space-x-4">
|
||||
{activity.user && <div className="text-xs font-light">{activity.user.email}</div>}
|
||||
{activity.apiKey && <div className="text-xs font-light">{activity.apiKey.alias}</div>}
|
||||
{!activity.user && !activity.apiKey && <div className="text-xs font-light">{t("shared.anonymousUser")}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import clsx from "clsx";
|
||||
import { useSubmit, useNavigation } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ChevronUpIcon, ChevronDownIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
order: number;
|
||||
editable?: boolean;
|
||||
}
|
||||
export default function RowOrderButtons({ id, order, editable = true }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const loading = navigation.state === "submitting";
|
||||
function changeOrder(forward: boolean) {
|
||||
const form = new FormData();
|
||||
form.set("action", forward ? "move-down" : "move-up");
|
||||
form.set("id", id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div className="flex items-center space-x-1 truncate">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => changeOrder(false)}
|
||||
className={clsx(
|
||||
!editable || loading ? " bg-secondary/90 cursor-not-allowed text-gray-300" : "hover:text-foreground hover:bg-secondary/90",
|
||||
"text-muted-foreground bg-secondary h-4 w-4 px-0.5 py-0.5 focus:outline-hidden"
|
||||
)}
|
||||
disabled={!editable || loading}
|
||||
aria-label={t("shared.moveUp")}
|
||||
>
|
||||
<ChevronUpIcon className="h-3 w-3" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => changeOrder(true)}
|
||||
className={clsx(
|
||||
!editable || loading ? " bg-secondary/90 cursor-not-allowed text-gray-300" : "hover:text-foreground hover:bg-secondary/90",
|
||||
"text-muted-foreground bg-secondary h-4 w-4 px-0.5 py-0.5 focus:outline-hidden"
|
||||
)}
|
||||
disabled={!editable || loading}
|
||||
aria-label={t("shared.moveDown")}
|
||||
>
|
||||
<ChevronDownIcon className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Fragment, ReactNode, useRef } from "react";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import TrashEmptyIcon from "~/components/ui/icons/TrashEmptyIcon";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import RowTitle from "./RowTitle";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useNavigation, useSubmit } from "react-router";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { getUserHasPermission, getEntityPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import ShareIcon from "~/components/ui/icons/ShareIcon";
|
||||
import PencilIcon from "~/components/ui/icons/PencilIcon";
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function RowOverviewHeader({
|
||||
rowData,
|
||||
item,
|
||||
canUpdate,
|
||||
isEditing,
|
||||
routes,
|
||||
title,
|
||||
options,
|
||||
buttons,
|
||||
customActions,
|
||||
truncate = true,
|
||||
}: {
|
||||
rowData: RowsApi.GetRowData;
|
||||
item: RowWithDetails;
|
||||
canUpdate: boolean;
|
||||
isEditing: boolean;
|
||||
routes: EntitiesApi.Routes | undefined;
|
||||
title?: React.ReactNode;
|
||||
options?: {
|
||||
hideTitle?: boolean;
|
||||
hideMenu?: boolean;
|
||||
hideShare?: boolean;
|
||||
hideTags?: boolean;
|
||||
hideTasks?: boolean;
|
||||
hideActivity?: boolean;
|
||||
disableUpdate?: boolean;
|
||||
disableDelete?: boolean;
|
||||
};
|
||||
buttons?: ReactNode;
|
||||
customActions?: { entity: string; label: string; action: string }[];
|
||||
truncate?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
function getEditRoute() {
|
||||
if (isEditing) {
|
||||
return EntityHelper.getRoutes({ routes, entity: rowData.entity, item })?.overview;
|
||||
} else {
|
||||
return EntityHelper.getRoutes({ routes, entity: rowData.entity, item })?.edit;
|
||||
}
|
||||
}
|
||||
function canDelete() {
|
||||
return !options?.disableDelete && getUserHasPermission(appOrAdminData, getEntityPermission(rowData.entity, "delete")) && rowData.rowPermissions.canDelete;
|
||||
}
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-border relative items-center justify-between space-y-2 border-b pb-4 sm:flex sm:space-x-4 sm:space-y-0">
|
||||
<div className={clsx(truncate && "truncate", "flex flex-col")}>
|
||||
<div className={clsx(truncate && "truncate", "flex items-center space-x-2 text-xl font-bold")}>
|
||||
{title ?? <RowTitle entity={rowData.entity} item={item} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center space-x-2 sm:justify-end">
|
||||
<div className="flex items-end space-x-2 space-y-0">
|
||||
{canUpdate || item.createdByUserId === appOrAdminData?.user?.id || appOrAdminData?.isSuperUser ? (
|
||||
<Fragment>
|
||||
{customActions
|
||||
?.filter((f) => f.entity === rowData.entity.name)
|
||||
.map((customAction) => {
|
||||
return (
|
||||
<ButtonSecondary
|
||||
key={customAction.action}
|
||||
isLoading={navigation.state === "submitting" && navigation.formData?.get("action") === customAction.action}
|
||||
onClick={() => {
|
||||
const form = new FormData();
|
||||
form.set("action", customAction.action);
|
||||
form.set("id", item.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}}
|
||||
>
|
||||
<span className="text-xs">{customAction.label}</span>
|
||||
</ButtonSecondary>
|
||||
);
|
||||
})}
|
||||
{buttons}
|
||||
{!options?.hideShare && (item.createdByUserId === appOrAdminData?.user?.id || appOrAdminData.isSuperAdmin) && (
|
||||
<ButtonSecondary to="share" ariaLabel={t("shared.share")}>
|
||||
<ShareIcon className="text-muted-foreground h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
{rowData.entity.onEdit !== "overviewAlwaysEditable" && (
|
||||
<ButtonSecondary disabled={!EntityHelper.getRoutes({ routes, entity: rowData.entity, item })?.edit} to={getEditRoute()} ariaLabel={t("shared.edit")}>
|
||||
<PencilIcon className="text-muted-foreground h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
{isEditing && (
|
||||
<ButtonSecondary onClick={onDelete} disabled={!canDelete()} ariaLabel={t("shared.delete")}>
|
||||
<TrashEmptyIcon className="text-muted-foreground h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
</Fragment>
|
||||
) : appOrAdminData.isSuperAdmin ? (
|
||||
<ButtonSecondary to="share" ariaLabel={t("shared.share")}>
|
||||
<ShareIcon className="text-muted-foreground h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} destructive onYes={onDeleteConfirm} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { EntityWithDetails, PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import RowValueInput from "./RowValueInput";
|
||||
import clsx from "clsx";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { useState } from "react";
|
||||
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import { RowValueDto } from "~/application/dtos/entities/RowValueDto";
|
||||
import { getFormProperties } from "~/utils/helpers/PropertyHelper";
|
||||
import { RowDto } from "~/modules/rows/repositories/RowDto";
|
||||
|
||||
export default function RowProperties({
|
||||
entity,
|
||||
item,
|
||||
readOnly,
|
||||
properties,
|
||||
gridColumns,
|
||||
}: {
|
||||
entity: EntityWithDetails;
|
||||
item: RowDto | null;
|
||||
readOnly?: boolean;
|
||||
properties?: string[];
|
||||
gridColumns?: "grid-cols-4" | "grid-cols-3" | "grid-cols-2";
|
||||
}) {
|
||||
const [values, setValues] = useState<RowValueDto[]>(
|
||||
getFormProperties({ mode: item ? "edit" : "create", entity, properties }).map((property) => {
|
||||
const existing = item?.values.find((f) => f.propertyId === property.id);
|
||||
return {
|
||||
propertyId: property.id,
|
||||
property,
|
||||
...existing,
|
||||
textValue: existing?.textValue ?? undefined,
|
||||
numberValue: existing?.numberValue ? Number(existing?.numberValue) : undefined,
|
||||
dateValue: existing?.dateValue ?? undefined,
|
||||
booleanValue: existing ? Boolean(existing?.booleanValue) : undefined,
|
||||
selectedOption: existing?.textValue ?? undefined,
|
||||
media: existing?.media ?? [],
|
||||
multiple: existing?.multiple.sort((a: { order: number }, b: { order: number }) => a.order - b.order) ?? [],
|
||||
range: existing?.range ?? undefined,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
function getPropertyColumnSpan(property: PropertyWithDetails) {
|
||||
const columns = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Columns);
|
||||
if (!columns || columns === undefined) {
|
||||
return "col-span-12";
|
||||
}
|
||||
return `col-span-${columns}`;
|
||||
}
|
||||
// function getValue(property: PropertyWithDetails) {
|
||||
// return values.find((f) => f.propertyId === property.id);
|
||||
// }
|
||||
// function getInitialOption(property: PropertyWithDetails) {
|
||||
// const defaultValueString = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.DefaultValue);
|
||||
// const textValue = getValue(property)?.textValue;
|
||||
// const selectedOption = property.options?.find((f) => f.value === (textValue ?? defaultValueString));
|
||||
// return selectedOption?.value;
|
||||
// }
|
||||
return (
|
||||
<div className={clsx("grid gap-2", gridColumns)}>
|
||||
{values.map((detailValue, idxDetailValue) => {
|
||||
return (
|
||||
<div key={idxDetailValue} className={clsx("w-full", !gridColumns && getPropertyColumnSpan(detailValue.property))}>
|
||||
{/* {prop.type === PropertyType.MULTI_SELECT && <>multiple: {JSON.stringify(value?.multiple)}</>} */}
|
||||
<RowValueInput
|
||||
entity={entity}
|
||||
textValue={values[idxDetailValue].textValue}
|
||||
numberValue={values[idxDetailValue].numberValue}
|
||||
dateValue={values[idxDetailValue].dateValue}
|
||||
booleanValue={values[idxDetailValue].booleanValue}
|
||||
multiple={values[idxDetailValue].multiple}
|
||||
range={values[idxDetailValue].range}
|
||||
initialOption={detailValue.selectedOption}
|
||||
selected={detailValue.property}
|
||||
initialMedia={detailValue.media}
|
||||
onChange={(e) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, RowHelper.updateFieldValueTypeArray(values[idxDetailValue], e));
|
||||
}}
|
||||
onChangeOption={(e) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, {
|
||||
textValue: e,
|
||||
selectedOption: e,
|
||||
});
|
||||
}}
|
||||
onChangeMedia={(media) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, {
|
||||
media,
|
||||
});
|
||||
}}
|
||||
onChangeMultiple={(e) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, {
|
||||
multiple: e,
|
||||
});
|
||||
}}
|
||||
onChangeRange={(e) => {
|
||||
updateItemByIdx(values, setValues, idxDetailValue, {
|
||||
range: e,
|
||||
});
|
||||
}}
|
||||
readOnly={readOnly || detailValue.property.isReadOnly}
|
||||
autoFocus={idxDetailValue === 0}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
import { RowPermission, Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { Form, useLocation, useSubmit, useNavigation, useActionData } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { UserWithDetails } from "~/utils/db/users.db.server";
|
||||
|
||||
type PermissionDto = {
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
groupId: string | null;
|
||||
roleId: string | null;
|
||||
};
|
||||
export default function RowSettingsPermissions({
|
||||
item,
|
||||
items,
|
||||
tenants,
|
||||
users,
|
||||
withTitle,
|
||||
}: {
|
||||
item: RowWithDetails;
|
||||
items: RowPermission[];
|
||||
tenants: Tenant[];
|
||||
users: UserWithDetails[];
|
||||
withTitle?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const location = useLocation();
|
||||
const submit = useSubmit();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const actionData = useActionData<{ error: string; success: string }>();
|
||||
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
function getTypeOrder(permission: PermissionDto) {
|
||||
if (permission.tenantId) {
|
||||
return 1;
|
||||
} else if (permission.userId) {
|
||||
return 2;
|
||||
} else if (permission.roleId) {
|
||||
return 3;
|
||||
} else if (permission.groupId) {
|
||||
return 4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
function getName(permission: PermissionDto) {
|
||||
if (permission.tenantId) {
|
||||
return tenants.find((x) => x.id === permission.tenantId)?.name;
|
||||
} else if (permission.userId) {
|
||||
return users.find((x) => x.id === permission.userId)?.email;
|
||||
} else if (permission.roleId) {
|
||||
return appOrAdminData.allRoles.find((x) => x.id === permission.roleId)?.name;
|
||||
} else if (permission.groupId) {
|
||||
return appOrAdminData.myGroups.find((x) => x.id === permission.groupId)?.name;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
function getTypes() {
|
||||
const options: { name: string; value: string; color: Colors }[] = [];
|
||||
if (users.length > 0) {
|
||||
options.push({ name: t("models.user.object") + "...", value: "user", color: Colors.BLUE });
|
||||
}
|
||||
if (tenants.length > 0) {
|
||||
options.push({ name: t("models.tenant.users") + "...", value: "tenant", color: Colors.GREEN });
|
||||
}
|
||||
if (appOrAdminData.myGroups.length > 0 && rootData.featureFlags?.includes("row-groups")) {
|
||||
options.push({ name: t("models.group.object") + "...", value: "group", color: Colors.INDIGO });
|
||||
}
|
||||
if (appOrAdminData.allRoles.length > 0) {
|
||||
options.push({ name: t("models.role.object") + "...", value: "role", color: Colors.RED });
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function sortedItems() {
|
||||
return items.filter((permission) => !permission.public).sort((a, b) => {
|
||||
const aOrder = getTypeOrder(a);
|
||||
const bOrder = getTypeOrder(b);
|
||||
if (aOrder === bOrder) {
|
||||
return getName(a)?.localeCompare(getName(b) ?? "") ?? 0;
|
||||
}
|
||||
return aOrder - bOrder;
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div className="text-foreground space-y-2">
|
||||
{withTitle && <div className="text-foreground text-sm font-medium">{t("shared.shareWith")}...</div>}
|
||||
{(sortedItems().length > 0 || item.createdByUser) && (
|
||||
<ul className="border-border bg-secondary/70 divide-border divide-y rounded-md border border-dashed">
|
||||
{item.createdByUser && (
|
||||
<div className="flex justify-between space-x-2 truncate px-2 py-2">
|
||||
<div className="flex w-full space-x-2 truncate">
|
||||
<div className="flex flex-col truncate">
|
||||
<div className="text-muted-foreground text-xs font-bold uppercase">
|
||||
<span>{t("models.row.permissionLabels.creator")}</span>
|
||||
</div>
|
||||
<div className="text-foreground truncate text-sm">{item.createdByUser.email}</div>
|
||||
</div>
|
||||
</div>
|
||||
<InputSelect className="w-32 shrink-0" disabled options={[{ name: t("models.row.permissionLabels.owner"), value: "owner" }]} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sortedItems().map((item, idx) => {
|
||||
return (
|
||||
<div key={idx} className="flex justify-between space-x-2 px-2 py-2">
|
||||
<div className="flex w-1/2 flex-col">
|
||||
<div className="text-muted-foreground text-xs font-bold uppercase">
|
||||
{item.tenantId ? (
|
||||
<span>{t("models.tenant.object")}</span>
|
||||
) : item.roleId ? (
|
||||
<span>{t("models.role.object")}</span>
|
||||
) : item.groupId ? (
|
||||
<span>{t("models.group.object")}</span>
|
||||
) : item.userId ? (
|
||||
<span>{t("models.user.object")}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="text-foreground truncate text-sm">{getName(item)}</div>
|
||||
</div>
|
||||
<InputSelect
|
||||
className="w-1/2"
|
||||
value={item.access}
|
||||
options={[
|
||||
{ name: t("shared.permissions.canView"), value: "view" },
|
||||
{ name: t("shared.permissions.canComment"), value: "comment" },
|
||||
{ name: t("shared.permissions.canEdit"), value: "edit" },
|
||||
{ name: t("shared.permissions.canDelete"), value: "delete" },
|
||||
{ name: t("shared.remove"), value: "remove" },
|
||||
]}
|
||||
setValue={(value) => {
|
||||
if (value === "remove") {
|
||||
const form = new FormData();
|
||||
form.set("action", "remove");
|
||||
form.set("id", item?.id ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
} else {
|
||||
const form = new FormData();
|
||||
form.set("action", "set-access");
|
||||
form.set("id", item?.id ?? "");
|
||||
form.set("access", value?.toString() ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{!adding && getTypes().length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAdding(true)}
|
||||
className="border-border hover:border-border relative block w-full rounded-lg border-2 border-dashed p-2 text-center focus:outline-hidden focus:ring-2 focus:ring-gray-500 focus:ring-offset-2"
|
||||
>
|
||||
<PlusIcon className="text-muted-foreground mx-auto h-4" />
|
||||
<span className="text-foreground mt-2 block text-sm font-medium">{t("shared.shareWith")}...</span>
|
||||
</button>
|
||||
)}
|
||||
{adding && <NewPermissionForm tenants={tenants} users={users} onClose={() => setAdding(false)} types={getTypes()} />}
|
||||
{actionData?.error && <ErrorBanner title={t("shared.error")} text={actionData?.error} />}
|
||||
{/* {actionData?.success && <InfoBanner title={t("shared.success")} text={actionData?.success} />} */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NewPermissionForm({
|
||||
tenants,
|
||||
users,
|
||||
types,
|
||||
onClose,
|
||||
}: {
|
||||
tenants: Tenant[];
|
||||
users: UserWithDetails[];
|
||||
types: { name: string; value: string; color: Colors }[];
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const appData = useAppData();
|
||||
const location = useLocation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const navigation = useNavigation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "share";
|
||||
|
||||
const [type, setType] = useState<string>("");
|
||||
const [id, setId] = useState<string>("");
|
||||
const [access, setAccess] = useState<string>("view");
|
||||
|
||||
useEffect(() => {
|
||||
if (isAdding) {
|
||||
onClose();
|
||||
}
|
||||
}, [isAdding, onClose]);
|
||||
|
||||
useEffect(() => {
|
||||
if (users.length > 0) {
|
||||
setType("user");
|
||||
} else if (tenants.length > 0) {
|
||||
setType("tenant");
|
||||
} else if (appOrAdminData.allRoles.length > 0) {
|
||||
setType("role");
|
||||
} else if (appOrAdminData.myGroups.length > 0) {
|
||||
setType("group");
|
||||
}
|
||||
}, [appOrAdminData.allRoles.length, appOrAdminData.myGroups.length, tenants.length, users.length]);
|
||||
|
||||
function getOptionValues() {
|
||||
if (type === "user") {
|
||||
return users.map((i) => {
|
||||
return { name: i.email + ` (${i.firstName} ${i.lastName})` + (appOrAdminData.user?.id === i.id ? ` (${t("shared.you")})` : ""), value: i.id };
|
||||
});
|
||||
} else if (type === "tenant") {
|
||||
return tenants.map((i) => {
|
||||
return { name: i.name + (appData.currentTenant?.id === i.id ? ` (${t("shared.current")})` : ""), value: i.id };
|
||||
});
|
||||
} else if (type === "role") {
|
||||
return appOrAdminData.allRoles.map((i) => {
|
||||
return { name: i.name, value: i.id };
|
||||
});
|
||||
} else if (type === "group") {
|
||||
return appOrAdminData.myGroups.map((i) => {
|
||||
return { name: i.name, value: i.id };
|
||||
});
|
||||
}
|
||||
return [];
|
||||
}
|
||||
function missingFields() {
|
||||
return !type || !id || !access;
|
||||
}
|
||||
return (
|
||||
<Form method="post" action={location.pathname + location.search}>
|
||||
<input type="hidden" name="action" value="share" hidden readOnly />
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputSelector
|
||||
name="type"
|
||||
withSearch={false}
|
||||
withColors={false}
|
||||
className="w-full"
|
||||
title={t("shared.shareWith") + "..."}
|
||||
value={type}
|
||||
setValue={(e) => setType(e?.toString() ?? "")}
|
||||
options={types}
|
||||
/>
|
||||
<InputSelector name="id" withSearch={true} className="col-span-2" value={id} setValue={(e) => setId(e?.toString() ?? "")} options={getOptionValues()} />
|
||||
|
||||
<InputSelector
|
||||
name="access"
|
||||
withSearch={false}
|
||||
value={access}
|
||||
setValue={(e) => setAccess(e?.toString() ?? "")}
|
||||
options={[
|
||||
{ name: t("shared.permissions.canView"), value: "view" },
|
||||
{ name: t("shared.permissions.canComment"), value: "comment" },
|
||||
{ name: t("shared.permissions.canEdit"), value: "edit" },
|
||||
{ name: t("shared.permissions.canDelete"), value: "delete" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<div className="flex space-x-2">
|
||||
<ButtonSecondary onClick={onClose}>{t("shared.cancel")}</ButtonSecondary>
|
||||
<ButtonPrimary type="submit" disabled={missingFields()}>
|
||||
{t("shared.share")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useLocation } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import IconHistory from "~/components/layouts/icons/IconHistory";
|
||||
import ShareIcon from "~/components/ui/icons/crud/ShareIcon";
|
||||
import TagsIcon from "~/components/ui/icons/crud/TagsIcon";
|
||||
import TabsWithIcons, { TabWithIcon } from "~/components/ui/tabs/TabsWithIcons";
|
||||
|
||||
export default function RowSettingsTabs({ canUpdate, isOwner, hasTags = true }: { canUpdate: boolean; isOwner: boolean; hasTags: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const location = useLocation();
|
||||
function isCurrent(name: string) {
|
||||
return location.pathname.endsWith(name);
|
||||
}
|
||||
function getTabs() {
|
||||
const tabs: TabWithIcon[] = [
|
||||
{
|
||||
name: t("shared.activity"),
|
||||
className: "flex justify-center",
|
||||
current: isCurrent("activity"),
|
||||
href: "activity",
|
||||
icon: <IconHistory className="h-6 w-6" />,
|
||||
},
|
||||
];
|
||||
if (canUpdate && hasTags) {
|
||||
tabs.push({
|
||||
name: t("models.row.tags"),
|
||||
className: "flex justify-center",
|
||||
current: isCurrent("tags"),
|
||||
href: "tags",
|
||||
icon: <TagsIcon className="h-5 w-5" />,
|
||||
});
|
||||
}
|
||||
if (isOwner) {
|
||||
tabs.push({
|
||||
name: t("shared.share"),
|
||||
className: "flex justify-center",
|
||||
current: isCurrent("share"),
|
||||
href: "share",
|
||||
icon: <ShareIcon className="h-5 w-5" />,
|
||||
});
|
||||
}
|
||||
return tabs;
|
||||
}
|
||||
return <>{getTabs().length > 1 && <TabsWithIcons justify="center" tabs={getTabs()} />}</>;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { EntityTag } from "@toolctrl/db/prisma-browser";
|
||||
import { Form, useLocation, useNavigation, useSubmit } from "react-router";
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import EmptyState from "~/components/ui/emptyState/EmptyState";
|
||||
import CheckEmptyCircle from "~/components/ui/icons/CheckEmptyCircleIcon";
|
||||
import CheckFilledCircleIcon from "~/components/ui/icons/CheckFilledCircleIcon";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import TrashEmptyIcon from "~/components/ui/icons/TrashEmptyIcon";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getColors } from "~/utils/shared/ColorUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
export default function RowSettingsTags({ item, tags }: { item: RowWithDetails; tags: EntityTag[] }) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const location = useLocation();
|
||||
const rootData = useRootData();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "new-tag";
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const [tagName, setTagName] = useState("");
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdding) {
|
||||
formRef.current?.reset();
|
||||
setTagName("");
|
||||
}
|
||||
}, [isAdding]);
|
||||
|
||||
function onChangeTag(tag: EntityTag, value: string, color: Colors) {
|
||||
if (tag.value === value && tag.color === color) {
|
||||
return;
|
||||
}
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "edit-tag");
|
||||
form.set("tag-id", tag.id);
|
||||
form.set("tag-name", value);
|
||||
form.set("tag-color", color.toString());
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
|
||||
function onSetRowTag(id: string, add: any) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "set-tag");
|
||||
form.set("tag-id", id);
|
||||
form.set("tag-action", add === true ? "add" : "remove");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
|
||||
function sortedItems() {
|
||||
return tags.sort((x, y) => {
|
||||
if (x.id && y.id) {
|
||||
return x.id > y.id ? -1 : 1;
|
||||
}
|
||||
return -1;
|
||||
});
|
||||
}
|
||||
function onDeleteTag(tag: EntityTag) {
|
||||
confirmDelete.current?.setValue(tag);
|
||||
confirmDelete.current?.show(t("shared.tagDelete", { 0: tag.value }), t("shared.delete"), t("shared.cancel"));
|
||||
}
|
||||
function onConfirmDelete(tag: EntityTag) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete-tag");
|
||||
form.set("tag-id", tag.id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
action: location.pathname + location.search,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Form ref={formRef} method="post" action={location.pathname + location.search}>
|
||||
<input hidden readOnly name="action" value="new-tag" />
|
||||
{rootData.csrf && <input hidden readOnly name="csrf" value={rootData.csrf} />}
|
||||
<div className="flex space-x-2">
|
||||
<InputText
|
||||
autoFocus
|
||||
className="w-full"
|
||||
name="tag-name"
|
||||
title={t("shared.newTag")}
|
||||
withLabel={false}
|
||||
placeholder={t("shared.tagNamePlaceholder")}
|
||||
autoComplete="off"
|
||||
required
|
||||
value={tagName}
|
||||
setValue={setTagName}
|
||||
button={
|
||||
<div className="absolute inset-y-0 right-0 flex py-1.5 pr-1.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-background inline-flex items-center rounded border px-1 font-sans text-sm font-medium">
|
||||
<button type="submit">
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</kbd>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</Form>
|
||||
|
||||
{tags.length === 0 && (
|
||||
<div>
|
||||
<EmptyState
|
||||
captions={{
|
||||
thereAreNo: t("shared.noTags"),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{sortedItems().map((tag) => {
|
||||
return (
|
||||
<div key={tag.id} className="flex space-x-2">
|
||||
<InputText
|
||||
className="w-full"
|
||||
name={"tag-name-" + tag.id}
|
||||
title={t("shared.tag")}
|
||||
withLabel={false}
|
||||
value={tag.value}
|
||||
setValue={(value) => onChangeTag(tag, value.toString(), tag.color)}
|
||||
/>
|
||||
<InputSelector
|
||||
className="w-36"
|
||||
name="color"
|
||||
title={t("models.group.color")}
|
||||
withSearch={false}
|
||||
withLabel={false}
|
||||
value={tag.color}
|
||||
setValue={(e) => onChangeTag(tag, tag.value, Number(e))}
|
||||
options={
|
||||
getColors().map((color) => {
|
||||
return {
|
||||
name: (
|
||||
<div className="flex items-center space-x-2">
|
||||
<ColorBadge color={color} />
|
||||
{/* <div>{t("app.shared.colors." + Colors[color])}</div> */}
|
||||
</div>
|
||||
),
|
||||
value: color,
|
||||
};
|
||||
}) ?? []
|
||||
}
|
||||
></InputSelector>
|
||||
{/* <InputCheckbox
|
||||
name={"tag-checked-" + tag.id}
|
||||
title=""
|
||||
value={data.item.tags.find((f) => f.tagId === tag.id) !== undefined}
|
||||
setValue={(e) => onSetRowTag(tag.id, e)}
|
||||
/> */}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(item.tags.filter((f) => f.tagId === tag.id).length > 0 ? "shared.remove" : "shared.add")}
|
||||
onClick={() => onSetRowTag(tag.id, item.tags.filter((f) => f.tagId === tag.id).length === 0)}
|
||||
className="focus:outline-hidden"
|
||||
>
|
||||
{item.tags.filter((f) => f.tagId === tag.id).length > 0 ? (
|
||||
<CheckFilledCircleIcon className="h-4 w-4 text-teal-500 hover:text-teal-600" />
|
||||
) : (
|
||||
<CheckEmptyCircle className="text-muted-foreground hover:text-muted-foreground h-4 w-4" />
|
||||
)}
|
||||
</button>
|
||||
<button type="button" aria-label={t("shared.delete")} onClick={() => onDeleteTag(tag)} className="focus:outline-hidden">
|
||||
<TrashEmptyIcon className="text-muted-foreground h-4 w-4 hover:text-red-600" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onConfirmDelete} destructive />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import TagFilledIcon from "~/components/ui/icons/TagFilledIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import { RowTagWithDetails } from "~/utils/db/entities/rowTags.db.server";
|
||||
import { getBackgroundColor } from "~/utils/shared/ColorUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
|
||||
interface Props {
|
||||
items: RowTagWithDetails[];
|
||||
onRemove?: (item: RowTagWithDetails) => void;
|
||||
onSetTagsRoute?: string;
|
||||
}
|
||||
|
||||
export default function RowTags({ items, onRemove, onSetTagsRoute }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
|
||||
const sortedItems = () => {
|
||||
return items.slice().sort((x, y) => {
|
||||
if (x.tag.id && y.tag.id) {
|
||||
return x.tag.id > y.tag.id ? -1 : 1;
|
||||
}
|
||||
return -1;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">
|
||||
<div className="flex items-center space-x-1">
|
||||
<TagFilledIcon className="text-muted-foreground h-4 w-4" />
|
||||
<div>
|
||||
<span className=" font-light italic"></span> {t("models.tag.plural")}
|
||||
</div>
|
||||
</div>
|
||||
</h3>
|
||||
{items.length > 0 && appOrAdminData.user !== undefined && onSetTagsRoute && (
|
||||
<div className="inline text-xs">
|
||||
<Link to={onSetTagsRoute} className="text-muted-foreground flex items-center space-x-1 text-sm hover:underline">
|
||||
<PlusIcon className="h-3 w-3" />
|
||||
<div>{t("shared.setTags")}</div>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{items.length === 0 && (
|
||||
<>
|
||||
{appOrAdminData.user && onSetTagsRoute ? (
|
||||
<Link
|
||||
to={onSetTagsRoute}
|
||||
className="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-gray-500"
|
||||
>
|
||||
<span className="text-muted-foreground block text-xs font-normal">{t("shared.noTags")}</span>
|
||||
</Link>
|
||||
) : (
|
||||
<div className="border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center">
|
||||
<span className="text-muted-foreground block text-xs font-normal">{t("shared.noTags")}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<ul className="leading-8">
|
||||
{sortedItems().map((item) => {
|
||||
return (
|
||||
<li key={item.tag.value} className="inline select-none p-0.5">
|
||||
<span className="border-border relative inline-flex items-center rounded-full border px-3 py-0.5">
|
||||
<div className="absolute flex shrink-0 items-center justify-center">
|
||||
<span className={clsx("h-1.5 w-1.5 rounded-full", getBackgroundColor(item.tag.color))} aria-hidden="true" />
|
||||
</div>
|
||||
<div className="text-foreground ml-3.5 text-sm font-medium">{item.tag.value}</div>
|
||||
{onRemove && (
|
||||
<div className="absolute flex shrink-0 items-center justify-center">
|
||||
<XIcon className="h-3 w-3"></XIcon>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Form, useSubmit, useNavigation } from "react-router";
|
||||
import CheckEmptyCircle from "~/components/ui/icons/CheckEmptyCircleIcon";
|
||||
import CheckFilledCircleIcon from "~/components/ui/icons/CheckFilledCircleIcon";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import TrashIcon from "~/components/ui/icons/TrashIcon";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { RowTaskWithDetails } from "~/utils/db/entities/rowTasks.db.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
interface Props {
|
||||
items: RowTaskWithDetails[];
|
||||
}
|
||||
|
||||
export default function RowTasks({ items }: Props) {
|
||||
const submit = useSubmit();
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const isAdding = navigation.state === "submitting" && navigation.formData?.get("action") === "task-new";
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const rootData = useRootData();
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
const [showAddTask, setShowAddTask] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdding) {
|
||||
formRef.current?.reset();
|
||||
}
|
||||
}, [isAdding]);
|
||||
|
||||
function onToggleTaskCompleted(id: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "task-complete-toggle");
|
||||
form.set("task-id", id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function onDeleteTask(id: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "task-delete");
|
||||
form.set("task-id", id);
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function canDelete(item: RowTaskWithDetails) {
|
||||
return appOrAdminData.isSuperUser || (!item.completed && item.createdByUserId === appOrAdminData.user?.id);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<h3 className="text-foreground text-sm font-medium leading-3">
|
||||
<div className="flex items-center space-x-1">
|
||||
<CheckFilledCircleIcon className="text-muted-foreground h-4 w-4" />
|
||||
<div>
|
||||
<span className=" font-light italic"></span> {t("models.rowTask.plural")}
|
||||
</div>
|
||||
</div>
|
||||
</h3>
|
||||
{items.length > 0 && appOrAdminData.user !== undefined && (
|
||||
<div className="inline text-xs">
|
||||
<button type="button" onClick={() => setShowAddTask(true)} className="text-muted-foreground flex items-center space-x-1 text-sm hover:underline">
|
||||
<PlusIcon className="h-3 w-3" />
|
||||
<div>{t("shared.addTask")}</div>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{items.length === 0 && !showAddTask && (
|
||||
<>
|
||||
{appOrAdminData.user !== undefined ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAddTask(true)}
|
||||
className="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-gray-500"
|
||||
>
|
||||
<span className="text-muted-foreground block text-xs font-normal">{t("shared.noTasks")}</span>
|
||||
</button>
|
||||
) : (
|
||||
<div className="border-border relative block w-full rounded-lg border-2 border-dashed p-4 text-center">
|
||||
<span className="text-muted-foreground block text-xs font-normal">{t("shared.noTasks")}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{items.length > 0 && (
|
||||
<ul className="border-border rounded-lg border-2 border-dashed p-2">
|
||||
{items.map((item) => {
|
||||
return (
|
||||
<li key={item.id} className="inline py-2">
|
||||
{/* <Link to={"tasks/" + item.id} className="relative inline-flex items-center rounded-md border border-border px-3 py-0.5">
|
||||
<span className="text-sm leading-5 font-medium text-foreground">{item.title}</span>
|
||||
</Link>{" "} */}
|
||||
<div className="group flex items-center justify-between space-x-1 truncate">
|
||||
<div className="flex grow items-center space-x-1 truncate">
|
||||
<button
|
||||
disabled={!appOrAdminData.user}
|
||||
type="button"
|
||||
onClick={() => onToggleTaskCompleted(item.id)}
|
||||
className="text-muted-foreground hover:text-foreground/80 shrink-0 focus:outline-hidden"
|
||||
>
|
||||
{item.completed ? <CheckFilledCircleIcon className="h-5 w-5 text-teal-500" /> : <CheckEmptyCircle className="h-5 w-5" />}
|
||||
</button>
|
||||
<div className="text-muted-foreground truncate text-sm">{item.title}</div>
|
||||
</div>
|
||||
{canDelete(item) && (
|
||||
<button
|
||||
disabled={!canDelete(item) || !appOrAdminData.user}
|
||||
type="button"
|
||||
onClick={() => onDeleteTask(item.id)}
|
||||
className={clsx(
|
||||
"hover:text-muted-foreground text-muted-foreground invisible shrink-0 focus:outline-hidden group-hover:visible",
|
||||
!canDelete(item) && "cursor-not-allowed opacity-50"
|
||||
)}
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{showAddTask && (
|
||||
<Form ref={formRef} method="post">
|
||||
<input hidden readOnly name="action" value="task-new" />
|
||||
{rootData.csrf && <input hidden readOnly name="csrf" value={rootData.csrf} />}
|
||||
<div className={clsx("relative flex w-full rounded-md")}>
|
||||
<input
|
||||
autoFocus
|
||||
type="text"
|
||||
className={clsx("focus:border-border focus:ring-ring border-border block w-full min-w-0 flex-1 rounded-md sm:text-sm")}
|
||||
name="task-title"
|
||||
placeholder={t("shared.newTask") + "..."}
|
||||
autoComplete="off"
|
||||
required
|
||||
/>
|
||||
<div className="absolute inset-y-0 right-0 flex py-1.5 pr-1.5 ">
|
||||
<kbd className="border-border text-muted-foreground bg-background inline-flex items-center rounded border px-1 font-sans text-sm font-medium">
|
||||
<button type="submit">
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</kbd>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useState, useEffect, Fragment } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithValues } from "~/utils/db/entities/rows.db.server";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
|
||||
export default function RowTitle({ entity, item }: { entity: EntityWithDetails; item: RowWithValues }) {
|
||||
const { t } = useTranslation();
|
||||
const [folio, setFolio] = useState<string | undefined>(undefined);
|
||||
const [description, setDescription] = useState<string | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
setFolio(RowHelper.getRowFolio(entity, item));
|
||||
let description = RowHelper.getTextDescription({ entity, item, t }) ?? "";
|
||||
if (description.length > 160) {
|
||||
description = description.substring(0, 160) + "...";
|
||||
}
|
||||
setDescription(description);
|
||||
}, [entity, item, t]);
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
{!description || folio === description ? (
|
||||
<div className="truncate">{RowHelper.getRowFolio(entity, item)}</div>
|
||||
) : (
|
||||
<div className="flex items-baseline space-x-1 truncate">
|
||||
<div className="truncate">
|
||||
{description} <span className="text-muted-foreground text-xs font-medium uppercase">({RowHelper.getRowFolio(entity, item)})</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
import { RowMedia, RowValueMultiple, RowValueRange } from "@toolctrl/db/prisma-browser";
|
||||
import { Ref, useImperativeHandle, useRef, useState, useEffect, forwardRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { MediaDto } from "~/application/dtos/entities/MediaDto";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import InputDate, { RefInputDate } from "~/components/ui/input/InputDate";
|
||||
import InputNumber, { RefInputNumber } from "~/components/ui/input/InputNumber";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import { PropertyWithDetails, EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import InputCheckbox from "~/components/ui/input/InputCheckbox";
|
||||
import InputMedia from "~/components/ui/input/InputMedia";
|
||||
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
|
||||
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import InputMultiText, { RefInputMultiText } from "~/components/ui/input/InputMultiText";
|
||||
import PropertyMultiSelector from "../properties/PropertyMultiSelector";
|
||||
import InputRangeNumber from "~/components/ui/input/ranges/InputRangeNumber";
|
||||
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
|
||||
import InputRangeDate from "~/components/ui/input/ranges/InputRangeDate";
|
||||
import { getSeparator } from "~/utils/shared/SeparatorUtils";
|
||||
import InputTextSubtype from "~/components/ui/input/subtypes/InputTextSubtype";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputRadioGroupCards from "~/components/ui/input/InputRadioGroupCards";
|
||||
import { renderSanitizedMarkdown } from "~/utils/html-sanitizer";
|
||||
import { translatePropertyTitle, translateSelectOptionLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
export interface RefRowValueInput {
|
||||
focus: () => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
selected: PropertyWithDetails | undefined;
|
||||
entity: EntityWithDetails;
|
||||
textValue: string | undefined;
|
||||
numberValue: number | undefined;
|
||||
dateValue: Date | undefined;
|
||||
booleanValue: boolean | undefined;
|
||||
multiple: RowValueMultiple[] | undefined;
|
||||
range: RowValueRange | undefined;
|
||||
initialMedia?: RowMedia[] | undefined;
|
||||
initialOption?: string | undefined;
|
||||
onChange?: (value: string | number | Date | boolean | undefined | null) => void;
|
||||
onChangeOption?: (option: string | undefined) => void;
|
||||
onChangeMedia?: (option: MediaDto[]) => void;
|
||||
onChangeMultiple?: (option: RowValueMultipleDto[]) => void;
|
||||
onChangeRange?: (option: RowValueRangeDto | undefined) => void;
|
||||
readOnly: boolean;
|
||||
className?: string;
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
const RowValueInput = (
|
||||
{
|
||||
entity,
|
||||
selected,
|
||||
textValue,
|
||||
numberValue,
|
||||
dateValue,
|
||||
booleanValue,
|
||||
multiple,
|
||||
range,
|
||||
initialMedia,
|
||||
initialOption,
|
||||
onChange,
|
||||
onChangeOption,
|
||||
onChangeMedia,
|
||||
onChangeMultiple,
|
||||
onChangeRange,
|
||||
className,
|
||||
readOnly,
|
||||
autoFocus,
|
||||
}: Props,
|
||||
ref: Ref<RefRowValueInput>
|
||||
) => {
|
||||
useImperativeHandle(ref, () => ({ focus }));
|
||||
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const numberInput = useRef<RefInputNumber>(null);
|
||||
const textInput = useRef<RefInputText>(null);
|
||||
const dateInput = useRef<RefInputDate>(null);
|
||||
const multipleInput = useRef<RefInputMultiText>(null);
|
||||
|
||||
const [media, setMedia] = useState<MediaDto[]>([]);
|
||||
|
||||
function focus() {
|
||||
if (selected?.type === PropertyType.TEXT) {
|
||||
textInput.current?.input.current?.focus();
|
||||
} else if (selected?.type === PropertyType.NUMBER) {
|
||||
numberInput.current?.input.current?.focus();
|
||||
} else if (selected?.type === PropertyType.DATE) {
|
||||
dateInput.current?.input.current?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function getSelectedTitle() {
|
||||
return selected ? translatePropertyTitle(t, i18n, entity.name, selected) : "";
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (selected?.type === PropertyType.MEDIA) {
|
||||
if (onChangeMedia) {
|
||||
onChangeMedia(media);
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [media]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{selected?.type === PropertyType.TEXT ? (
|
||||
<>
|
||||
{["monaco", "wysiwyg", "iframe"].includes(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Editor) ?? "") &&
|
||||
readOnly ? (
|
||||
<></>
|
||||
) : (
|
||||
<>
|
||||
<InputTextSubtype
|
||||
subtype={selected.subtype as any}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
value={textValue}
|
||||
setValue={(e) => (onChange ? onChange(e.toString()) : undefined)}
|
||||
required={selected.isRequired}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
disabled={readOnly}
|
||||
pattern={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Pattern)}
|
||||
minLength={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
maxLength={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
rows={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Rows)}
|
||||
placeholder={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Placeholder)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
uppercase={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Uppercase)}
|
||||
lowercase={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Lowercase)}
|
||||
password={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Password)}
|
||||
editor={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Editor)}
|
||||
editorLanguage={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.EditorLanguage)}
|
||||
editorSize={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.EditorSize) as any}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{["iframe"].includes(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Editor) ?? "") && readOnly && (
|
||||
<div className="overflow-auto">
|
||||
{getSafeIframePreviewUrl(textValue) ? (
|
||||
<iframe title={getSelectedTitle()} src={getSafeIframePreviewUrl(textValue)} sandbox="allow-scripts" className="h-96 w-full" />
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
{["monaco", "wysiwyg"].includes(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Editor) ?? "") &&
|
||||
readOnly && (
|
||||
<div className="overflow-auto">
|
||||
<label className="mb-1 flex justify-between space-x-2 truncate text-xs font-medium">
|
||||
<span>{getSelectedTitle()}</span>
|
||||
</label>
|
||||
<div className="prose border-border bg-secondary h-auto rounded-md border p-3">
|
||||
<div
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: renderSanitizedMarkdown(textValue),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : selected?.type === PropertyType.NUMBER ? (
|
||||
<InputNumber
|
||||
ref={numberInput}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
value={numberValue}
|
||||
setValue={(e) => (onChange ? onChange(Number(e)) : undefined)}
|
||||
disabled={readOnly}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
min={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
max={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
step={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Step)}
|
||||
placeholder={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Placeholder)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
canUnset={true}
|
||||
/>
|
||||
) : selected?.type === PropertyType.DATE ? (
|
||||
<>
|
||||
<InputDate
|
||||
ref={dateInput}
|
||||
required={selected.isRequired}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
value={dateValue}
|
||||
onChange={(e) => (onChange ? onChange(e) : undefined)}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.SELECT ? (
|
||||
<>
|
||||
{/* <PropertyOptionSelector
|
||||
property={selected}
|
||||
initial={initialOption}
|
||||
onSelected={(e) => {
|
||||
if (onChange) {
|
||||
onChange(e ?? "");
|
||||
}
|
||||
if (onChangeOption) {
|
||||
onChangeOption(e);
|
||||
}
|
||||
}}
|
||||
className={className}
|
||||
disabled={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
display={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.SelectOptions) as SelectOptionsDisplay}
|
||||
autoFocus={autoFocus}
|
||||
/> */}
|
||||
{!selected.subtype || selected.subtype === "dropdown" ? (
|
||||
<InputSelect
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
value={initialOption}
|
||||
defaultValue={textValue}
|
||||
setValue={(e) => {
|
||||
if (onChange) {
|
||||
onChange(e?.toString() ?? "");
|
||||
}
|
||||
if (onChangeOption) {
|
||||
onChangeOption(e?.toString());
|
||||
}
|
||||
}}
|
||||
disabled={readOnly}
|
||||
className={className}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
autoFocus={autoFocus}
|
||||
options={selected.options.map((f) => ({
|
||||
name: translateSelectOptionLabel(t, i18n, entity.name, selected.name, f),
|
||||
value: f.value,
|
||||
}))}
|
||||
/>
|
||||
) : selected.subtype === "radioGroupCards" ? (
|
||||
<InputRadioGroupCards
|
||||
title={getSelectedTitle()}
|
||||
name={selected.name}
|
||||
value={initialOption}
|
||||
defaultValue={textValue}
|
||||
disabled={readOnly}
|
||||
required={selected.isRequired}
|
||||
options={selected.options.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: translateSelectOptionLabel(t, i18n, entity.name, selected.name, f),
|
||||
};
|
||||
})}
|
||||
onChange={(e) => {
|
||||
if (onChange) {
|
||||
onChange(e);
|
||||
}
|
||||
if (onChangeOption) {
|
||||
onChangeOption(e);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : selected?.type === PropertyType.BOOLEAN ? (
|
||||
<>
|
||||
<InputCheckbox
|
||||
asToggle={true}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
value={booleanValue}
|
||||
setValue={(e) => (onChange ? onChange(e as boolean) : undefined)}
|
||||
disabled={readOnly}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.MEDIA ? (
|
||||
<InputMedia
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
initialMedia={initialMedia}
|
||||
className={className}
|
||||
disabled={readOnly}
|
||||
onSelected={(e) => setMedia(e)}
|
||||
readOnly={readOnly}
|
||||
required={selected.isRequired || (PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min) ?? 0) > 0}
|
||||
min={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
max={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
accept={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.AcceptFileTypes)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
) : selected?.type === PropertyType.MULTI_SELECT ? (
|
||||
<>
|
||||
<PropertyMultiSelector
|
||||
subtype={selected.subtype as any}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
options={selected.options}
|
||||
value={multiple}
|
||||
onSelected={(e) => (onChangeMultiple ? onChangeMultiple(e) : undefined)}
|
||||
disabled={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.MULTI_TEXT ? (
|
||||
<>
|
||||
<InputMultiText
|
||||
ref={multipleInput}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
value={multiple}
|
||||
// onSelected={(e) => (onChangeMultiple ? onChangeMultiple(e) : undefined)}
|
||||
required={selected.isRequired}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
disabled={readOnly}
|
||||
pattern={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Pattern)}
|
||||
minLength={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
maxLength={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
rows={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Rows)}
|
||||
placeholder={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Placeholder)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
uppercase={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Uppercase)}
|
||||
lowercase={PropertyAttributeHelper.getPropertyAttributeValue_Boolean(selected, PropertyAttributeName.Lowercase)}
|
||||
autoFocus={autoFocus}
|
||||
separator={getSeparator(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Separator))}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.RANGE_NUMBER ? (
|
||||
<>
|
||||
<InputRangeNumber
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
required={selected.isRequired}
|
||||
valueMin={range?.numberMin ? Number(range.numberMin) : undefined}
|
||||
valueMax={range?.numberMax ? Number(range.numberMax) : undefined}
|
||||
onChangeMin={(e) => {
|
||||
if (onChangeRange) {
|
||||
onChangeRange({
|
||||
dateMin: null,
|
||||
dateMax: null,
|
||||
numberMin: Number(e),
|
||||
numberMax: range?.numberMax ? Number(range.numberMax) : null,
|
||||
});
|
||||
}
|
||||
}}
|
||||
onChangeMax={(e) => {
|
||||
if (onChangeRange) {
|
||||
onChangeRange({
|
||||
dateMin: null,
|
||||
dateMax: null,
|
||||
numberMax: Number(e),
|
||||
numberMin: range?.numberMin ? Number(range.numberMin) : null,
|
||||
});
|
||||
}
|
||||
}}
|
||||
disabled={readOnly}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
min={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Min)}
|
||||
max={PropertyAttributeHelper.getPropertyAttributeValue_Number(selected, PropertyAttributeName.Max)}
|
||||
step={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Step)}
|
||||
placeholder={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Placeholder)}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.RANGE_DATE ? (
|
||||
<>
|
||||
<InputRangeDate
|
||||
required={selected.isRequired}
|
||||
name={selected.name}
|
||||
title={getSelectedTitle()}
|
||||
valueMin={range?.dateMin ?? undefined}
|
||||
valueMax={range?.dateMax ?? undefined}
|
||||
onChangeMin={(e) => {
|
||||
if (onChangeRange) {
|
||||
onChangeRange({
|
||||
dateMin: e,
|
||||
dateMax: range?.dateMax ?? null,
|
||||
numberMin: null,
|
||||
numberMax: null,
|
||||
});
|
||||
}
|
||||
}}
|
||||
onChangeMax={(e) => {
|
||||
if (onChangeRange) {
|
||||
onChangeRange({
|
||||
dateMin: range?.dateMin ?? null,
|
||||
dateMax: e,
|
||||
numberMin: null,
|
||||
numberMax: null,
|
||||
});
|
||||
}
|
||||
}}
|
||||
className={className}
|
||||
readOnly={readOnly}
|
||||
hint={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HintText) ?? "")}
|
||||
help={t(PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.HelpText) ?? "")}
|
||||
icon={PropertyAttributeHelper.getPropertyAttributeValue_String(selected, PropertyAttributeName.Icon)}
|
||||
autoFocus={autoFocus}
|
||||
/>
|
||||
</>
|
||||
) : selected?.type === PropertyType.FORMULA ? (
|
||||
<>
|
||||
{!selected.formula ? (
|
||||
<div className="text-red-500">{t("models.row.values.unknownFormula")}</div>
|
||||
) : (
|
||||
<InputFormulaValue
|
||||
property={selected}
|
||||
title={translatePropertyTitle(t, i18n, entity.name, selected)}
|
||||
textValue={textValue}
|
||||
numberValue={numberValue}
|
||||
dateValue={dateValue}
|
||||
booleanValue={booleanValue}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className={className}>{t("models.row.values.notSupported")}</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
function InputFormulaValue(props: {
|
||||
property: PropertyWithDetails;
|
||||
title: string;
|
||||
textValue?: string;
|
||||
numberValue?: number;
|
||||
dateValue?: Date;
|
||||
booleanValue?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{props.property.formula?.resultAs === "string" ? (
|
||||
<InputText name={props.property.name} title={props.title} defaultValue={props.textValue} readOnly={true} />
|
||||
) : props.property.formula?.resultAs === "number" ? (
|
||||
<InputNumber name={props.property.name} title={props.title} defaultValue={props.numberValue} readOnly={true} canUnset={true} />
|
||||
) : props.property.formula?.resultAs === "date" ? (
|
||||
<InputDate name={props.property.name} title={props.title} value={props.dateValue} readOnly={true} />
|
||||
) : props.property.formula?.resultAs === "boolean" ? (
|
||||
<InputCheckbox asToggle={true} name={props.property.name} title={props.title} value={props.booleanValue} readOnly={true} />
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function getSafeIframePreviewUrl(value: string | undefined) {
|
||||
if (!value) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = new URL(value.trim());
|
||||
return url.protocol === "https:" ? url.toString() : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export default forwardRef(RowValueInput);
|
||||
@@ -0,0 +1,85 @@
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { useEffect, useState } from "react";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import clsx from "clsx";
|
||||
import { Property } from "@toolctrl/db/prisma-browser";
|
||||
import { Link } from "react-router";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
items: RowWithDetails[];
|
||||
className?: string;
|
||||
}
|
||||
export default function RowsKanban({ entity, items, className }: Props) {
|
||||
const [columns, setColumns] = useState<{ name: string; title: string; color?: Colors }[]>([]);
|
||||
const [columnsProperty, setColumnsProperty] = useState<Property>();
|
||||
|
||||
useEffect(() => {
|
||||
const optionsField = entity.properties.find((f) => [PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(f.type));
|
||||
if (optionsField) {
|
||||
setColumns(
|
||||
optionsField.options
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((option) => {
|
||||
return {
|
||||
name: option.value,
|
||||
title: option.value,
|
||||
color: Colors.BLUE,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
setColumnsProperty(optionsField);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
function getItems(columnName: string) {
|
||||
return items.filter((f) => f.values.find((f) => f.propertyId === columnsProperty?.id && f.textValue === columnName));
|
||||
}
|
||||
return (
|
||||
<div className={clsx(className, "flex space-x-4 overflow-x-auto")}>
|
||||
{columns.map((column) => {
|
||||
return (
|
||||
<div key={column.name} className="border-border bg-secondary h-96 w-64 shrink-0 overflow-y-auto rounded-md border p-2 text-sm shadow-2xs">
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-between space-x-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
{column.color && (
|
||||
<div>
|
||||
<ColorBadge color={column.color} />
|
||||
</div>
|
||||
)}
|
||||
<div>{column.title}</div>
|
||||
</div>
|
||||
{/* <button type="button" onClick={onNew(column.name)}>
|
||||
<PlusIcon className="h-3 w-3" />
|
||||
</button> */}
|
||||
</div>
|
||||
{getItems(column.name).map((item) => {
|
||||
return (
|
||||
<div key={item.id} className="hover:bg-secondary border-border bg-background group rounded-md border p-2 shadow-2xs">
|
||||
<Link to={item.id} className="space-y-0.5 text-xs">
|
||||
{entity.properties
|
||||
.filter((f) => !f.isDefault && f.id !== columnsProperty?.id)
|
||||
.map((property, idxProp) => {
|
||||
return (
|
||||
<div key={property.name}>
|
||||
<span className={clsx(idxProp === 0 && "font-bold")}>{RowHelper.getCellValue({ entity, item, property })}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
import RowsListAndTable from "./RowsListAndTable";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails, PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
|
||||
import KanbanSimple, { KanbanColumn } from "~/components/ui/lists/KanbanSimple";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { Fragment, useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import GridContainer from "~/components/ui/lists/GridContainer";
|
||||
import { EntityViewWithDetails } from "~/utils/db/entities/entityViews.db.server";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import clsx from "clsx";
|
||||
import EntityViewHelper from "~/utils/helpers/EntityViewHelper";
|
||||
import RowColumnsHelper from "~/utils/helpers/RowColumnsHelper";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import EmptyState from "~/components/ui/emptyState/EmptyState";
|
||||
import RenderCard from "./RenderCard";
|
||||
import RowsLoadMoreCard from "~/components/ui/tables/RowsLoadMoreCard";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
import { MinusIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
view: "table" | "board" | "grid" | "card";
|
||||
items: RowWithDetails[];
|
||||
routes?: EntitiesApi.Routes;
|
||||
pagination?: PaginationDto;
|
||||
onEditRow?: (row: RowWithDetails) => void;
|
||||
currentView?: EntityViewWithDetails | null;
|
||||
selectedRows?: RowWithDetails[];
|
||||
onSelected?: (item: RowWithDetails[]) => void;
|
||||
readOnly?: boolean;
|
||||
onClickRoute?: (row: RowWithDetails) => string;
|
||||
onRemove?: (row: RowWithDetails) => void;
|
||||
ignoreColumns?: string[];
|
||||
columns?: ColumnDto[];
|
||||
actions?: (row: RowWithDetails) => {
|
||||
title?: string;
|
||||
href?: string;
|
||||
onClick?: () => void;
|
||||
isLoading?: boolean;
|
||||
render?: React.ReactNode;
|
||||
}[];
|
||||
leftHeaders?: RowHeaderDisplayDto<RowWithDetails>[];
|
||||
rightHeaders?: RowHeaderDisplayDto<RowWithDetails>[];
|
||||
}
|
||||
export default function RowsList(props: Props & { entity: EntityWithDetails | string }) {
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
|
||||
const [entity, setEntity] = useState<EntityWithDetails>();
|
||||
const [columns, setColumns] = useState<ColumnDto[]>([]);
|
||||
const [groupBy, setGroupBy] = useState<{ property?: PropertyWithDetails } | undefined>();
|
||||
|
||||
useEffect(() => {
|
||||
let entity: EntityWithDetails | undefined = undefined;
|
||||
let columns: ColumnDto[] = [];
|
||||
let groupBy: { property?: PropertyWithDetails } | undefined = undefined;
|
||||
|
||||
if (typeof props.entity === "string") {
|
||||
entity = appOrAdminData.entities.find((e) => e.name === props.entity);
|
||||
} else {
|
||||
entity = props.entity;
|
||||
}
|
||||
|
||||
if (entity) {
|
||||
const systemView = entity.views.find((f) => f.isSystem);
|
||||
let view = props.currentView ?? systemView;
|
||||
if (!view) {
|
||||
columns = RowColumnsHelper.getDefaultEntityColumns(entity);
|
||||
if (props.view === "board") {
|
||||
columns = columns.filter((f) => f.name !== groupBy?.property?.name);
|
||||
}
|
||||
if (props.ignoreColumns) {
|
||||
columns = columns.filter((f) => !props.ignoreColumns?.includes(f.name));
|
||||
}
|
||||
|
||||
if (props.view === "board") {
|
||||
const property = entity.properties.find((f) => f.type === PropertyType.SELECT && !f.isHidden);
|
||||
if (property) {
|
||||
groupBy = { property };
|
||||
}
|
||||
}
|
||||
} else {
|
||||
columns = view.properties
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((f) => {
|
||||
return { name: f.name ?? "", title: "", visible: true };
|
||||
});
|
||||
if (props.ignoreColumns) {
|
||||
columns = columns.filter((f) => !props.ignoreColumns?.includes(f.name));
|
||||
}
|
||||
|
||||
if (view.layout === "board") {
|
||||
columns = columns.filter((f) => f.name !== groupBy?.property?.name);
|
||||
}
|
||||
|
||||
if (view.groupByPropertyId) {
|
||||
const property = entity.properties.find((f) => f.id === view?.groupByPropertyId);
|
||||
if (property) {
|
||||
groupBy = { property };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if (props.readOnly) {
|
||||
// columns = columns.filter((f) => ![RowDisplayDefaultProperty.FOLIO.toString()].includes(f.name));
|
||||
// }
|
||||
|
||||
if (props.columns !== undefined) {
|
||||
columns = props.columns;
|
||||
}
|
||||
|
||||
setEntity(entity);
|
||||
setColumns(columns);
|
||||
setGroupBy(groupBy);
|
||||
}, [appOrAdminData.entities, props]);
|
||||
|
||||
if (!entity) {
|
||||
return null;
|
||||
} else if (columns.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <RowsListWrapped {...props} entity={entity} columns={columns} groupBy={groupBy} />;
|
||||
}
|
||||
|
||||
function RowsListWrapped({
|
||||
view,
|
||||
entity,
|
||||
items,
|
||||
routes,
|
||||
columns,
|
||||
pagination,
|
||||
groupBy,
|
||||
onEditRow,
|
||||
currentView,
|
||||
selectedRows,
|
||||
onSelected,
|
||||
readOnly,
|
||||
onClickRoute,
|
||||
onRemove,
|
||||
actions,
|
||||
leftHeaders,
|
||||
rightHeaders,
|
||||
}: Props & {
|
||||
entity: EntityWithDetails;
|
||||
columns: ColumnDto[];
|
||||
groupBy?: { property?: PropertyWithDetails };
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const params = useParams();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const entityLabel = translateLabel(t, i18n, entity.titlePlural);
|
||||
|
||||
const [options, setOptions] = useState<KanbanColumn<RowWithDetails>[]>([]);
|
||||
useEffect(() => {
|
||||
if (groupBy?.property) {
|
||||
setOptions(
|
||||
groupBy.property.options.map((option) => {
|
||||
return {
|
||||
name: option.value,
|
||||
color: option.color,
|
||||
title: (
|
||||
<div className="flex items-center space-x-1">
|
||||
{option.name ? <div className="font-bold">{option.name}</div> : <div className="font-bold">{option.value}</div>}
|
||||
</div>
|
||||
),
|
||||
value: (item: RowWithDetails) => (
|
||||
<RenderCard layout={view} item={item} entity={entity} columns={columns} allEntities={appOrAdminData.entities} routes={routes} actions={actions} />
|
||||
),
|
||||
onClickRoute: (i: RowWithDetails) => EntityHelper.getRoutes({ routes, entity, item: i })?.edit ?? "",
|
||||
onNewRoute: (columnValue: string) => {
|
||||
let newRoute = EntityHelper.getRoutes({ routes, entity })?.new;
|
||||
if (newRoute) {
|
||||
return newRoute + `?${groupBy?.property?.name}=${columnValue}`;
|
||||
}
|
||||
return "";
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [groupBy]);
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
{view == "table" && (
|
||||
<RowsListAndTable
|
||||
columns={columns}
|
||||
entity={entity}
|
||||
items={items}
|
||||
pagination={pagination}
|
||||
routes={routes}
|
||||
onFolioClick={onEditRow}
|
||||
onEditClick={onEditRow}
|
||||
onRelatedRowClick={onEditRow}
|
||||
allEntities={appOrAdminData.entities}
|
||||
editable={!readOnly}
|
||||
selectedRows={selectedRows}
|
||||
onSelected={onSelected}
|
||||
onRemove={onRemove}
|
||||
leftHeaders={leftHeaders}
|
||||
rightHeaders={rightHeaders}
|
||||
/>
|
||||
)}
|
||||
{view === "board" && groupBy && (
|
||||
<KanbanSimple
|
||||
className="pt-2"
|
||||
items={items}
|
||||
classNameWidth={clsx("")}
|
||||
filterValue={(item, column) => {
|
||||
if (groupBy.property) {
|
||||
const value = RowHelper.getPropertyValue({ entity, item, property: groupBy.property });
|
||||
if (column === null && !value) {
|
||||
return true;
|
||||
}
|
||||
return value === column?.name;
|
||||
}
|
||||
return false;
|
||||
}}
|
||||
columns={options}
|
||||
undefinedColumn={{
|
||||
name: "__unset",
|
||||
color: Colors.UNDEFINED,
|
||||
title: (
|
||||
<div className="flex items-center space-x-1">
|
||||
<div className="font-bold">{t("shared.notSet")}</div>
|
||||
</div>
|
||||
),
|
||||
value: (item: RowWithDetails) => {
|
||||
return (
|
||||
<div className="bg-background rounded-md">
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
onClickRoute: (i: RowWithDetails) => EntityHelper.getRoutes({ routes, entity, item: i })?.edit ?? "",
|
||||
}}
|
||||
column={groupBy.property?.name ?? ""}
|
||||
renderEmpty={<EmptyCard className="w-full" />}
|
||||
/>
|
||||
)}
|
||||
{view === "grid" && (
|
||||
<Fragment>
|
||||
{items.length === 0 ? (
|
||||
<EmptyState
|
||||
className="w-full py-8"
|
||||
// to={EntityHelper.getRoutes({ routes, entity })?.new ?? ""}
|
||||
captions={{
|
||||
// new: "Add",
|
||||
thereAreNo: t("shared.emptyEntityList", { entity: entityLabel }),
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{/* {pagination && (
|
||||
<GridPagination
|
||||
defaultPageSize={currentView?.pageSize ?? undefined}
|
||||
totalItems={pagination.totalItems}
|
||||
totalPages={pagination.totalPages}
|
||||
page={pagination.page}
|
||||
pageSize={pagination.pageSize}
|
||||
/>
|
||||
)} */}
|
||||
<GridContainer {...(currentView ? EntityViewHelper.getGridLayout(currentView) : { columns: 3, gap: "xs" })}>
|
||||
{items.map((item) => {
|
||||
const href = onClickRoute ? onClickRoute(item) : EntityHelper.getRoutes({ routes, entity, item })?.overview ?? undefined;
|
||||
if (onSelected && selectedRows !== undefined) {
|
||||
return (
|
||||
<ButtonSelectWrapper key={item.id} item={item} onSelected={onSelected} selectedRows={selectedRows}>
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
/>
|
||||
</ButtonSelectWrapper>
|
||||
);
|
||||
}
|
||||
const card = (
|
||||
<div className={clsx("bg-background group relative rounded-md text-left", href && "hover:bg-secondary")}>
|
||||
<RemoveButton item={item} readOnly={readOnly} onRemove={onRemove} />
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
href={href}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
return href ? (
|
||||
<Link key={item.id} to={href}>
|
||||
{card}
|
||||
</Link>
|
||||
) : (
|
||||
card
|
||||
);
|
||||
// return (
|
||||
// <Fragment key={item.id}>
|
||||
// <Link to={item.id}>
|
||||
// <div className="group w-full truncate rounded-md border border-border bg-background p-3 text-left shadow-2xs hover:bg-secondary">
|
||||
// <RenderCard layout={view} item={item} entity={entity} columns={columns} allEntities={appOrAdminData.entities} routes={routes} actions={actions} />
|
||||
// </div>
|
||||
// </Link>
|
||||
// </Fragment>
|
||||
// );
|
||||
})}
|
||||
{items.length === 0 ? (
|
||||
<Fragment>{readOnly ? <EmptyCard className="w-full" /> : <AddMoreCard entity={entity} routes={routes} />}</Fragment>
|
||||
) : (
|
||||
<Fragment>
|
||||
<RowsLoadMoreCard pagination={pagination} currentView={currentView} />
|
||||
</Fragment>
|
||||
)}
|
||||
</GridContainer>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
)}
|
||||
{view === "card" && (
|
||||
<Fragment>
|
||||
{items.length === 0 ? (
|
||||
<EmptyState
|
||||
className="w-full py-8"
|
||||
// to={EntityHelper.getRoutes({ routes, entity })?.new ?? ""}
|
||||
captions={{
|
||||
// new: "Add",
|
||||
thereAreNo: t("shared.emptyEntityList", { entity: entityLabel }),
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex space-x-2 overflow-x-scroll">
|
||||
{items.map((item) => {
|
||||
let className = clsx("w-64");
|
||||
if (onSelected && selectedRows !== undefined) {
|
||||
return (
|
||||
<ButtonSelectWrapper className={clsx("group relative")} key={item.id} item={item} onSelected={onSelected} selectedRows={selectedRows}>
|
||||
<div className={className}>
|
||||
<RemoveButton item={item} readOnly={readOnly} onRemove={onRemove} />
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
/>
|
||||
</div>
|
||||
</ButtonSelectWrapper>
|
||||
);
|
||||
}
|
||||
const href = onClickRoute ? onClickRoute(item) : EntityHelper.getRoutes({ routes, entity, item })?.overview ?? undefined;
|
||||
const card = (
|
||||
<div className={clsx(className, "group relative rounded-md text-left", href && "hover:bg-secondary")}>
|
||||
<div className={className}>
|
||||
<RemoveButton item={item} readOnly={readOnly} onRemove={onRemove} />
|
||||
<RenderCard
|
||||
layout={view}
|
||||
item={item}
|
||||
entity={entity}
|
||||
columns={columns}
|
||||
allEntities={appOrAdminData.entities}
|
||||
routes={routes}
|
||||
actions={actions}
|
||||
href={href}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return href ? (
|
||||
<Link to={`${EntityHelper.getEntityRoute({ entity, params, appOrAdminData })}/${item.id}`} key={item.id} className="group relative">
|
||||
{/* <RowLinkButton entityName={entity.name} id={item.id} /> */}
|
||||
{card}
|
||||
</Link>
|
||||
) : (
|
||||
card
|
||||
);
|
||||
})}
|
||||
{items.length === 0 ? (
|
||||
<Fragment>{readOnly ? <EmptyCard className="w-full" /> : <AddMoreCard className="w-64" entity={entity} routes={routes} />}</Fragment>
|
||||
) : (
|
||||
<Fragment>
|
||||
{!readOnly && <AddMoreCard className="w-64" entity={entity} routes={routes} />}
|
||||
<RowsLoadMoreCard className="w-64" pagination={pagination} currentView={currentView} />
|
||||
</Fragment>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
export function AddMoreCard({ entity, routes, className }: { entity: EntityWithDetails; routes?: EntitiesApi.Routes; className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Fragment>
|
||||
<div className={className}>
|
||||
{routes && (
|
||||
<Link
|
||||
className={clsx(
|
||||
"border-border hover:border-border group flex h-full items-center rounded-md border-2 border-dashed p-2 text-left align-middle shadow-2xs hover:border-dotted hover:bg-slate-100",
|
||||
className
|
||||
)}
|
||||
to={EntityHelper.getRoutes({ routes, entity })?.new ?? ""}
|
||||
>
|
||||
<div className="text-foreground/80 mx-auto flex justify-center text-center align-middle text-sm font-medium">{t("shared.add")}</div>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyCard({ className }: { className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Fragment>
|
||||
<div className={className}>
|
||||
<div className="bg-background border-border group inline-block h-full w-full truncate rounded-md border-2 border-dashed p-12 text-left align-middle shadow-2xs">
|
||||
<div className="text-foreground/80 mx-auto flex justify-center text-center align-middle text-sm font-medium">{t("shared.noRecords")}</div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function ButtonSelectWrapper({
|
||||
item,
|
||||
onSelected,
|
||||
selectedRows,
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
item: RowWithDetails;
|
||||
selectedRows: RowWithDetails[];
|
||||
onSelected: (item: RowWithDetails[]) => void;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
const isSelected = selectedRows.find((f) => f.id === item.id);
|
||||
return (
|
||||
<div className={clsx(className, "group relative rounded-md text-left", isSelected ? "bg-theme-50 hover:bg-theme-50" : "hover:bg-secondary bg-background")}>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-0 top-0 mr-2 mt-2 origin-top-right justify-center"
|
||||
onClick={() => {
|
||||
if (isSelected) {
|
||||
onSelected(selectedRows.filter((f) => f.id !== item.id));
|
||||
} else {
|
||||
onSelected([...(selectedRows ?? []), item]);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{isSelected ? (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
className="h-5 w-5 text-teal-700"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="50"
|
||||
height="50"
|
||||
viewBox="0 0 50 50"
|
||||
>
|
||||
<path d="M 39 4 L 11 4 C 7.140625 4 4 7.140625 4 11 L 4 39 C 4 42.859375 7.140625 46 11 46 L 39 46 C 42.859375 46 46 42.859375 46 39 L 46 11 C 46 7.140625 42.859375 4 39 4 Z M 23.085938 34.445313 L 13.417969 25.433594 L 14.78125 23.96875 L 22.914063 31.554688 L 36.238281 15.832031 L 37.761719 17.125 Z"></path>
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
className="h-5 w-5 text-teal-700"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
x="0px"
|
||||
y="0px"
|
||||
width="50"
|
||||
height="50"
|
||||
viewBox="0 0 50 50"
|
||||
>
|
||||
<path d="M 39 4 L 11 4 C 7.101563 4 4 7.101563 4 11 L 4 39 C 4 42.898438 7.101563 46 11 46 L 39 46 C 42.898438 46 46 42.898438 46 39 L 46 11 C 46 7.101563 42.898438 4 39 4 Z M 42 39 C 42 40.699219 40.699219 42 39 42 L 11 42 C 9.300781 42 8 40.699219 8 39 L 8 11 C 8 9.300781 9.300781 8 11 8 L 39 8 C 40.699219 8 42 9.300781 42 11 Z"></path>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoveButton({ item, readOnly, onRemove }: { item: RowWithDetails; readOnly?: boolean; onRemove?: (item: RowWithDetails) => void }) {
|
||||
return (
|
||||
<Fragment>
|
||||
{onRemove && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
onRemove(item);
|
||||
}}
|
||||
type="button"
|
||||
disabled={readOnly}
|
||||
className={clsx(
|
||||
"text-muted-foreground bg-background absolute right-0 top-0 mr-2 mt-2 hidden origin-top-right justify-center rounded-full",
|
||||
readOnly ? "cursor-not-allowed" : "hover:text-red-500 group-hover:flex"
|
||||
)}
|
||||
>
|
||||
<MinusIcon className="h-6 w-6" />
|
||||
</button>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect, useState } from "react";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { ColumnDto } from "~/application/dtos/data/ColumnDto";
|
||||
import RowDisplayHeaderHelper from "~/utils/helpers/RowDisplayHeaderHelper";
|
||||
import { RowHeaderActionDto } from "~/application/dtos/data/RowHeaderActionDto";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import TrashIcon from "~/components/ui/icons/TrashIcon";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails;
|
||||
items: RowWithDetails[];
|
||||
routes?: EntitiesApi.Routes;
|
||||
columns?: ColumnDto[];
|
||||
pagination?: PaginationDto;
|
||||
className?: string;
|
||||
editable?: boolean;
|
||||
selectedRows?: RowWithDetails[];
|
||||
onSelected?: (item: RowWithDetails[]) => void;
|
||||
onFolioClick?: (item: RowWithDetails) => void;
|
||||
onEditClick?: (item: RowWithDetails) => void;
|
||||
onRelatedRowClick?: (item: RowWithDetails) => void;
|
||||
leftHeaders?: RowHeaderDisplayDto<RowWithDetails>[];
|
||||
rightHeaders?: RowHeaderDisplayDto<RowWithDetails>[];
|
||||
allEntities: EntityWithDetails[];
|
||||
onRemove?: (item: RowWithDetails) => void;
|
||||
}
|
||||
|
||||
export default function RowsListAndTable({
|
||||
entity,
|
||||
routes,
|
||||
items,
|
||||
pagination,
|
||||
className = "",
|
||||
columns,
|
||||
editable = true,
|
||||
selectedRows,
|
||||
onSelected,
|
||||
onFolioClick,
|
||||
onEditClick,
|
||||
onRelatedRowClick,
|
||||
leftHeaders,
|
||||
rightHeaders,
|
||||
allEntities,
|
||||
onRemove,
|
||||
}: Props) {
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<RowWithDetails>[]>([]);
|
||||
const [actions, setActions] = useState<RowHeaderActionDto<RowWithDetails>[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
let headers = RowDisplayHeaderHelper.getDisplayedHeaders({
|
||||
routes,
|
||||
entity,
|
||||
columns,
|
||||
layout: "table",
|
||||
allEntities,
|
||||
onFolioClick,
|
||||
onEditClick,
|
||||
onRelatedRowClick,
|
||||
t,
|
||||
i18n,
|
||||
});
|
||||
if (leftHeaders) {
|
||||
headers = [...leftHeaders, ...headers];
|
||||
}
|
||||
if (rightHeaders) {
|
||||
headers = [...headers, ...rightHeaders];
|
||||
}
|
||||
setHeaders(headers);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [entity, columns]);
|
||||
|
||||
useEffect(() => {
|
||||
const actions: RowHeaderActionDto<RowWithDetails>[] = [];
|
||||
if (editable) {
|
||||
actions.push({
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, item) => (onEditClick !== undefined ? undefined : (EntityHelper.getRoutes({ routes, entity, item })?.edit ?? "")),
|
||||
onClick: (_, item) => (onEditClick !== undefined ? onEditClick(item) : undefined),
|
||||
hidden: (item) => !editable || !EntityHelper.getRoutes({ routes, entity, item })?.edit,
|
||||
});
|
||||
}
|
||||
if (onRemove) {
|
||||
actions.push({
|
||||
title: (
|
||||
<div>
|
||||
<TrashIcon className="hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</div>
|
||||
),
|
||||
onClick: (_, item) => onRemove(item),
|
||||
firstColumn: true,
|
||||
});
|
||||
}
|
||||
setActions(actions);
|
||||
}, [editable, entity, onEditClick, onRemove, routes, t]);
|
||||
|
||||
function getHref(item: RowWithDetails) {
|
||||
return EntityHelper.getRoutes({ routes, entity, item })?.overview;
|
||||
}
|
||||
return (
|
||||
<div className={className}>
|
||||
<TableSimple
|
||||
headers={headers}
|
||||
items={items}
|
||||
pagination={pagination}
|
||||
selectedRows={selectedRows}
|
||||
onSelected={onSelected}
|
||||
actions={actions}
|
||||
onClickRoute={(_, item) => getHref(item)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useFetcher, useSearchParams } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import Kanban from "~/components/ui/lists/Kanban";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import { translateEntityTitlePlural } from "~/utils/i18n/translateLabel";
|
||||
|
||||
// type EntityWithRows = {
|
||||
// entity: EntityWithDetails;
|
||||
// rows: RowWithDetails[];
|
||||
// };
|
||||
export default function RowsRelationships({ entities }: { entities: string[] }) {
|
||||
return (
|
||||
<div className="flex overflow-hidden overflow-x-auto">
|
||||
{entities.map((entity) => (
|
||||
<EntityRowsRelationships className="w-full" key={entity} entity={entity} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EntityRowsRelationships({ entity, className, withTitle }: { entity: string; className?: string; withTitle?: boolean }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const fetcher = useFetcher<{ entity: EntityWithDetails; items: RowWithDetails[] }>();
|
||||
const [data, setData] = useState<{ entity: EntityWithDetails; items: RowWithDetails[] }>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
fetcher.load(`relationships?entity=${encodeURIComponent(entity)}&${searchParams}`);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [entity, searchParams]);
|
||||
|
||||
useEffect(() => {
|
||||
setData(fetcher.data);
|
||||
}, [fetcher.data]);
|
||||
|
||||
function isSelected(item: RowWithDetails) {
|
||||
return searchParams.getAll(`${entity}[id]`).includes(item.id);
|
||||
}
|
||||
return (
|
||||
<div className={clsx(className)}>
|
||||
{data?.entity && (
|
||||
<Kanban
|
||||
withTitle={withTitle}
|
||||
columns={[
|
||||
{
|
||||
name: "entity",
|
||||
title: translateEntityTitlePlural(t, i18n, data.entity),
|
||||
items: data?.items ?? [],
|
||||
card: (item) => (
|
||||
<div className="hover:bg-secondary border-border bg-background group w-full truncate rounded-md border p-3 text-left shadow-2xs">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<button
|
||||
className="grow truncate text-left"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (isSelected(item)) {
|
||||
const rows = searchParams.getAll(`${entity}[id]`).filter((id) => id !== item.id);
|
||||
searchParams.delete(`${entity}[id]`);
|
||||
for (const row of rows) searchParams.append(`${entity}[id]`, row);
|
||||
} else {
|
||||
searchParams.append(`${entity}[id]`, item.id);
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
>
|
||||
<div>{RowHelper.getTextDescription({ entity: data.entity!, item, t })}</div>
|
||||
</button>
|
||||
<div className="w-4 shrink-0">{isSelected(item) ? <CheckIcon className="text-muted-foreground h-4 w-4" /> : null}</div>
|
||||
{/* <button type="button" onClick={() => alert("edit: " + item.id)}>
|
||||
Edit
|
||||
</button> */}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { TFunction, t as i18nT } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import { BooleanFormatType } from "~/utils/shared/BooleanUtils";
|
||||
|
||||
export function getBooleanAsStringValue({ value, format, t }: { value?: boolean; format?: BooleanFormatType; t?: TFunction }) {
|
||||
const translate = t ?? i18nT;
|
||||
return !format || format === "yesNo"
|
||||
? value
|
||||
? translate("shared.yes")
|
||||
: translate("shared.no")
|
||||
: format === "trueFalse"
|
||||
? value
|
||||
? translate("shared.true")
|
||||
: translate("shared.false")
|
||||
: format === "enabledDisabled"
|
||||
? value
|
||||
? translate("shared.enabled")
|
||||
: translate("shared.disabled")
|
||||
: format === "onOff"
|
||||
? value
|
||||
? translate("shared.on")
|
||||
: translate("shared.off")
|
||||
: format === "activeInactive"
|
||||
? value
|
||||
? translate("shared.active")
|
||||
: translate("shared.inactive")
|
||||
: "";
|
||||
}
|
||||
export default function RowBooleanCell({ value, format }: { value?: boolean; format?: BooleanFormatType }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
{!format ? (
|
||||
<div>{value ? <CheckIcon className="h-4 w-4 text-teal-500" /> : <XIcon className="text-muted-foreground h-4 w-4" />}</div>
|
||||
) : (
|
||||
<SimpleBadge title={getBooleanAsStringValue({ value, format, t })} color={value ? Colors.GREEN : Colors.GRAY} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
export default function RowCreatedByCell({
|
||||
user,
|
||||
apiKey,
|
||||
}: {
|
||||
user?: { firstName: string; lastName: string; email: string } | null;
|
||||
apiKey?: { alias: string } | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div>
|
||||
{user ? (
|
||||
<div className="flex flex-col text-xs">
|
||||
<div className="font-medium">
|
||||
{user?.firstName} {user?.lastName}
|
||||
</div>
|
||||
<div>{user?.email}</div>
|
||||
</div>
|
||||
) : apiKey ? (
|
||||
<div>
|
||||
{t("models.apiKey.object")}: {apiKey.alias}
|
||||
</div>
|
||||
) : (
|
||||
<div></div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createLocaleFormatters, type LocaleFormatters, useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export type DateFormatType = "YYYY-MM-DD" | "DD-MM-YYYY" | "MM-DD-YYYY" | "diff";
|
||||
|
||||
const fallbackFormatters = createLocaleFormatters("en");
|
||||
|
||||
function padDatePart(value: number) {
|
||||
return value.toString().padStart(2, "0");
|
||||
}
|
||||
|
||||
function formatExplicitDate(value: Date, pattern: Exclude<DateFormatType, "diff">) {
|
||||
const year = value.getFullYear();
|
||||
const month = padDatePart(value.getMonth() + 1);
|
||||
const day = padDatePart(value.getDate());
|
||||
if (pattern === "YYYY-MM-DD") {
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
if (pattern === "DD-MM-YYYY") {
|
||||
return `${day}-${month}-${year}`;
|
||||
}
|
||||
return `${month}-${day}-${year}`;
|
||||
}
|
||||
|
||||
export function getDateAsString({
|
||||
value,
|
||||
format,
|
||||
formatters = fallbackFormatters,
|
||||
}: {
|
||||
value?: Date | null;
|
||||
format?: DateFormatType;
|
||||
formatters?: LocaleFormatters;
|
||||
}) {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
|
||||
switch (format) {
|
||||
case "YYYY-MM-DD":
|
||||
case "DD-MM-YYYY":
|
||||
case "MM-DD-YYYY":
|
||||
return formatExplicitDate(value, format);
|
||||
case "diff":
|
||||
return formatters.relativeDate(value);
|
||||
default:
|
||||
return formatters.date(value, { dateStyle: "medium" });
|
||||
}
|
||||
}
|
||||
|
||||
export default function RowDateCell({ value, format }: { value?: Date | null; format?: DateFormatType }) {
|
||||
const formatters = useLocaleFormatters();
|
||||
const text = getDateAsString({ value, format, formatters });
|
||||
return <>{!value ? <div></div> : <div>{text}</div>}</>;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Link } from "react-router";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export default function RowFolioCell({ prefix, folio, href, onClick }: { prefix: string; folio: number; href?: string; onClick?: () => void }) {
|
||||
const formatters = useLocaleFormatters();
|
||||
const folioText = formatters.number(folio ?? 0, {
|
||||
maximumFractionDigits: 0,
|
||||
minimumIntegerDigits: 4,
|
||||
useGrouping: false,
|
||||
});
|
||||
const text = `${prefix}-${folioText}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
{href ? (
|
||||
<Link
|
||||
to={href}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
className="hover border-border text-muted-foreground hover:text-foreground bg-secondary rounded-md border border-b px-1 py-0.5 text-center text-sm hover:underline"
|
||||
>
|
||||
{text}
|
||||
</Link>
|
||||
) : onClick ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onClick();
|
||||
}}
|
||||
className="hover border-border text-muted-foreground hover:text-foreground bg-secondary rounded-md border border-b px-1 py-0.5 text-center text-sm hover:underline"
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
) : (
|
||||
<div>{text}</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import clsx from "clsx";
|
||||
import { Fragment } from "react";
|
||||
import { MediaDto } from "~/application/dtos/entities/MediaDto";
|
||||
import DownloadIcon from "~/components/ui/icons/DownloadIcon";
|
||||
|
||||
export default function RowMediaCell({ media, layout = "table" }: { media: MediaDto[] | undefined; layout?: string }) {
|
||||
const onDownload = (media: MediaDto) => {
|
||||
const downloadLink = document.createElement("a");
|
||||
downloadLink.href = media.publicUrl ?? media.file;
|
||||
downloadLink.download = media.name;
|
||||
downloadLink.click();
|
||||
};
|
||||
function getFileName(name: string) {
|
||||
let fileName = name;
|
||||
if (name.includes("/")) {
|
||||
fileName = name.split("/").pop() ?? name;
|
||||
}
|
||||
if (name.includes("\\")) {
|
||||
fileName = name.split("\\").pop() ?? name;
|
||||
}
|
||||
return fileName;
|
||||
}
|
||||
return (
|
||||
<Fragment>
|
||||
<div className={clsx(layout === "table" ? "flex max-h-12 items-center space-x-2 overflow-x-visible truncate" : "grid max-h-60 gap-1 overflow-auto")}>
|
||||
{media
|
||||
?.filter((f) => f.type.includes("image"))
|
||||
.map((item) => {
|
||||
return <img key={item.name} className={clsx("object-cover", layout === "table" ? "h-10" : "")} src={item.publicUrl ?? item.file} alt={item.name} />;
|
||||
})}
|
||||
|
||||
{media
|
||||
?.filter((f) => !f.type.includes("image"))
|
||||
.map((item, idx) => {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={idx}
|
||||
onClick={() => onDownload(item)}
|
||||
className={
|
||||
"hover:border-border text-muted-foreground hover:text-foreground flex items-center space-x-1 border-b border-transparent text-xs hover:border-dashed"
|
||||
}
|
||||
>
|
||||
<div className="font-normal">{getFileName(item.title)}</div>
|
||||
<DownloadIcon className="h-3 w-3" />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import RatingBadge from "~/components/ui/badges/RatingBadge";
|
||||
import { createLocaleFormatters, type LocaleFormatters, useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export type NumberFormatType = "integer" | "decimal" | "currency" | "percentage" | "rating";
|
||||
|
||||
const fallbackFormatters = createLocaleFormatters("en");
|
||||
const defaultCurrency = "USD";
|
||||
type NumberOptions = Parameters<LocaleFormatters["number"]>[1];
|
||||
const fixedDecimalOptions: NumberOptions = { minimumFractionDigits: 2, maximumFractionDigits: 2 };
|
||||
|
||||
export function getNumberAsStringValue({
|
||||
value,
|
||||
format,
|
||||
currencySymbol,
|
||||
formatters = fallbackFormatters,
|
||||
}: {
|
||||
value?: number | null;
|
||||
format?: NumberFormatType;
|
||||
currencySymbol?: string;
|
||||
formatters?: LocaleFormatters;
|
||||
}) {
|
||||
if (value === null || value === undefined) {
|
||||
return "";
|
||||
}
|
||||
switch (format) {
|
||||
case "integer":
|
||||
return formatters.number(value, { maximumFractionDigits: 0 });
|
||||
case "decimal":
|
||||
return formatters.number(value, fixedDecimalOptions);
|
||||
case "currency":
|
||||
return currencySymbol ? `${currencySymbol}${formatters.number(value, fixedDecimalOptions)}` : formatters.currency(value, defaultCurrency, fixedDecimalOptions);
|
||||
case "percentage":
|
||||
return formatters.percent(value / 100, fixedDecimalOptions);
|
||||
default:
|
||||
return formatters.number(value);
|
||||
}
|
||||
}
|
||||
export default function RowNumberCell({ value, format, currencySymbol }: { value?: number | null; format?: NumberFormatType; currencySymbol?: string }) {
|
||||
const formatters = useLocaleFormatters();
|
||||
const formattedValue = getNumberAsStringValue({ value, format, currencySymbol, formatters });
|
||||
|
||||
return (
|
||||
<>
|
||||
{value === null || value === undefined ? (
|
||||
<div></div>
|
||||
) : (
|
||||
<div>
|
||||
{format === "rating" ? (
|
||||
<span>
|
||||
<RatingBadge value={value} />
|
||||
</span>
|
||||
) : (
|
||||
<span>{formattedValue}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
|
||||
import RowDateCell from "./RowDateCell";
|
||||
import { DateFormatType } from "~/utils/shared/DateUtils";
|
||||
|
||||
interface Props {
|
||||
value: RowValueRangeDto;
|
||||
format?: DateFormatType;
|
||||
}
|
||||
export default function RowRangeDateCell({ value, format }: Props) {
|
||||
return (
|
||||
<div className="flex items-center space-x-1">
|
||||
<RowDateCell value={value?.dateMin ?? undefined} format={format} />
|
||||
<div className="text-muted-foreground">-</div>
|
||||
<RowDateCell value={value?.dateMax ?? undefined} format={format} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
|
||||
import { NumberFormatType } from "~/utils/shared/NumberUtils";
|
||||
import RowNumberCell from "./RowNumberCell";
|
||||
|
||||
interface Props {
|
||||
value: RowValueRangeDto;
|
||||
format?: NumberFormatType;
|
||||
currencySymbol?: string;
|
||||
}
|
||||
export default function RowRangeNumberCell({ value, format, currencySymbol }: Props) {
|
||||
return (
|
||||
<div className="flex items-center space-x-1">
|
||||
<RowNumberCell value={Number(value?.numberMin) ?? undefined} format={format} currencySymbol={currencySymbol} />
|
||||
<div className="text-muted-foreground">-</div>
|
||||
<RowNumberCell value={Number(value?.numberMax) ?? undefined} format={format} currencySymbol={currencySymbol} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Link } from "react-router";
|
||||
import { Fragment } from "react";
|
||||
import { TFunction } from "i18next";
|
||||
import { RowDto } from "~/modules/rows/repositories/RowDto";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
|
||||
export default function RowRelationshipRow({
|
||||
entity,
|
||||
item,
|
||||
onRelatedRowClick,
|
||||
routes,
|
||||
t,
|
||||
}: {
|
||||
entity: EntityWithDetails;
|
||||
item: RowDto;
|
||||
onRelatedRowClick?: () => void;
|
||||
routes?: EntitiesApi.Routes;
|
||||
t: TFunction;
|
||||
}) {
|
||||
return (
|
||||
<Fragment>
|
||||
{onRelatedRowClick !== undefined ? (
|
||||
<button type="button" onClick={onRelatedRowClick} className="hover truncate text-left text-sm hover:underline">
|
||||
{RowHelper.getTextDescription({ entity: entity, item, t })}
|
||||
</button>
|
||||
) : !routes || !EntityHelper.getRoutes({ routes, entity: entity, item })?.overview ? (
|
||||
<div className="hover truncate text-left text-sm hover:underline">{RowHelper.getTextDescription({ entity: entity, item, t })}</div>
|
||||
) : (
|
||||
<Link
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
to={EntityHelper.getRoutes({ routes, entity: entity, item })?.overview ?? ""}
|
||||
className="hover truncate text-left text-sm hover:underline"
|
||||
>
|
||||
{RowHelper.getTextDescription({ entity: entity, item, t })}
|
||||
</Link>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RowDto } from "~/modules/rows/repositories/RowDto";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import RowRelationshipRow from "./RowRelationshipRow";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { translateEntityTitle } from "~/utils/i18n/translateLabel";
|
||||
|
||||
export default function RowRelationshipRowsByEntity({
|
||||
entity,
|
||||
item,
|
||||
allEntities,
|
||||
onRelatedRowClick,
|
||||
routes,
|
||||
type,
|
||||
}: {
|
||||
entity: EntityWithDetails;
|
||||
item: RowWithDetails;
|
||||
allEntities: EntityWithDetails[];
|
||||
onRelatedRowClick?: () => void;
|
||||
routes?: EntitiesApi.Routes;
|
||||
type: "parents" | "children";
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const relatedEntities = type === "children" ? entity.childEntities.filter((f) => f.hiddenIfEmpty) : entity.parentEntities.filter((f) => f.hiddenIfEmpty);
|
||||
let relatedRows: any[] = [];
|
||||
if (type === "children") {
|
||||
relatedRows = item.childRows?.filter((f) => relatedEntities.some((p) => p.id === f.relationshipId)) ?? [];
|
||||
} else {
|
||||
relatedRows = item.parentRows?.filter((f) => relatedEntities.some((p) => p.id === f.relationshipId)) ?? [];
|
||||
}
|
||||
const relatedRowsByEntity: { entity: EntityWithDetails; rows: RowDto[] }[] = [];
|
||||
relatedRows?.forEach((row) => {
|
||||
const entity = type === "children" ? allEntities.find((f) => f.id === row.child.entityId) : allEntities.find((f) => f.id === row.parent.entityId);
|
||||
if (!entity) {
|
||||
return null;
|
||||
}
|
||||
const existing = relatedRowsByEntity.find((f) => f.entity.id === entity.id);
|
||||
if (existing) {
|
||||
existing.rows.push(type === "children" ? row.child : row.parent);
|
||||
} else {
|
||||
relatedRowsByEntity.push({ entity, rows: [type === "children" ? row.child : row.parent] });
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
{relatedRows.length === 0 ? (
|
||||
<div className="text-muted-foreground px-1 pt-1 pb-0.5 text-center text-sm italic">{t("shared.none")}</div>
|
||||
) : (
|
||||
<ul className="flex max-h-20 max-w-lg flex-col space-y-1 overflow-auto">
|
||||
{relatedRowsByEntity.map(({ entity, rows }) => {
|
||||
return (
|
||||
<div className="space-y-1" key={entity.id}>
|
||||
<div className="text-muted-foreground text-xs font-medium">{translateEntityTitle(t, i18n, entity)}</div>
|
||||
{rows.map((row) => {
|
||||
return (
|
||||
<li key={row.id}>
|
||||
<RowRelationshipRow entity={entity} item={row} onRelatedRowClick={onRelatedRowClick} routes={routes} t={t} />
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import RowSelectedOptionCell from "./RowSelectedOptionCell";
|
||||
|
||||
const translations: Record<string, string> = {
|
||||
"models.contact.status.options.customer": "Kunde",
|
||||
};
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => translations[key] ?? key,
|
||||
i18n: {
|
||||
exists: (key: string) => key in translations,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("RowSelectedOptionCell", () => {
|
||||
it("renders seed select option labels through model translation fallbacks", () => {
|
||||
render(
|
||||
<RowSelectedOptionCell
|
||||
value="customer"
|
||||
entityName="contact"
|
||||
propertyName="status"
|
||||
display="Name"
|
||||
options={[{ value: "customer", name: "Customer", color: Colors.GREEN }]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Kunde")).toBeTruthy();
|
||||
expect(screen.queryByText("Customer")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps custom option labels literal when no model translation exists", () => {
|
||||
render(
|
||||
<RowSelectedOptionCell
|
||||
value="vip"
|
||||
entityName="contact"
|
||||
propertyName="status"
|
||||
display="Name"
|
||||
options={[{ value: "vip", name: "VIP customer", color: Colors.YELLOW }]}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("VIP customer")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import RenderOption from "../../properties/select/RenderOption";
|
||||
import { SelectOptionsDisplay } from "~/utils/shared/SelectOptionsUtils";
|
||||
import { translateSelectOptionLabel } from "~/utils/i18n/translateLabel";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
type ItemDto = { value: string; name: string | null; color: Colors };
|
||||
export default function RowSelectedOptionCell({
|
||||
value,
|
||||
options,
|
||||
display = "Name",
|
||||
entityName,
|
||||
propertyName,
|
||||
}: {
|
||||
value: string;
|
||||
options: ItemDto[];
|
||||
display: SelectOptionsDisplay;
|
||||
entityName?: string;
|
||||
propertyName?: string;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const selected = options.find((f) => f.value === value);
|
||||
if (options.length === 0 || !selected) {
|
||||
return value;
|
||||
}
|
||||
const translatedSelected =
|
||||
entityName && propertyName ? { ...selected, name: translateSelectOptionLabel(t, i18n, entityName, propertyName, selected) } : selected;
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RenderOption option={translatedSelected} display={display} hasColors={true} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { clsx } from "clsx";
|
||||
import { RowTagWithDetails } from "~/utils/db/entities/rowTags.db.server";
|
||||
import { getBackgroundColor } from "~/utils/shared/ColorUtils";
|
||||
|
||||
export default function RowTagsCell({ items }: { items: RowTagWithDetails[] }) {
|
||||
return (
|
||||
<div>
|
||||
{items?.map((rowTag) => {
|
||||
return (
|
||||
<div
|
||||
key={rowTag.id}
|
||||
className="border-border bg-secondary relative mx-0.5 inline-flex max-w-sm select-none items-center space-x-0.5 overflow-x-auto rounded-full border px-2 py-0.5"
|
||||
>
|
||||
<div className="absolute flex shrink-0 items-center justify-center">
|
||||
<span className={clsx("h-1.5 w-1.5 rounded-full", getBackgroundColor(rowTag.tag.color))} aria-hidden="true" />
|
||||
</div>
|
||||
<div className="text-muted-foreground pl-2 text-xs font-medium">{rowTag.tag.value}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Link, useParams } from "react-router";
|
||||
import { ExternalLinkIcon } from "~/components/ui/icons/vendor";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import EntityHelper from "~/utils/helpers/EntityHelper";
|
||||
|
||||
export default function RowLinkButton({ entityName, id }: { entityName: string; id: string }) {
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
const entity = appOrAdminData.entities.find((f) => f.name === entityName)!;
|
||||
return (
|
||||
<Link
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
to={`${EntityHelper.getEntityRoute({ entity, params, appOrAdminData })}/${id}`}
|
||||
className="border-border bg-background hover:border-border absolute right-2 top-2 z-10 hidden rounded-md border p-2 opacity-80 hover:opacity-100 group-hover:block"
|
||||
>
|
||||
<ExternalLinkIcon className="text-foreground/80 h-4 w-4" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { TFunction } from "i18next";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getDateAsString } from "./cells/RowDateCell";
|
||||
import { getNumberAsStringValue } from "./cells/RowNumberCell";
|
||||
import { getBooleanAsStringValue } from "./cells/RowBooleanCell";
|
||||
import { createLocaleFormatters } from "~/locale/format";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
|
||||
const cellsRoot = path.resolve(process.cwd(), "apps/web/app/components/entities/rows/cells");
|
||||
|
||||
function readCell(relativePath: string) {
|
||||
return fs.readFileSync(path.join(cellsRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("row cell formatting i18n", () => {
|
||||
it("keeps visible date, number, and folio formatting on locale formatters", () => {
|
||||
const numberSource = readCell("RowNumberCell.tsx");
|
||||
const sources = [readCell("RowDateCell.tsx"), numberSource, readCell("RowFolioCell.tsx")].join("\n");
|
||||
|
||||
expect(sources).toContain("~/locale/format");
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("formatters.date");
|
||||
expect(sources).toContain("formatters.number");
|
||||
expect(sources).toContain("formatters.currency");
|
||||
expect(sources).toContain("formatters.percent");
|
||||
expect(sources).toContain("formatters.relativeDate");
|
||||
expect(numberSource).not.toContain("value.toString()");
|
||||
expect(sources).not.toContain("DateUtils");
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
expect(sources).not.toContain("Intl");
|
||||
expect(sources).not.toContain("toLocaleString");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
});
|
||||
|
||||
it("formats default row numbers through locale formatters", () => {
|
||||
expect(getNumberAsStringValue({ value: 1234567.89, formatters: createLocaleFormatters("en") })).toBe("1,234,567.89");
|
||||
expect(getNumberAsStringValue({ value: 1234567.89, formatters: createLocaleFormatters("de") })).toBe("1.234.567,89");
|
||||
});
|
||||
|
||||
it("keeps explicit row date patterns stable", () => {
|
||||
const value = new Date("2026-05-26T10:20:30.000Z");
|
||||
|
||||
expect(getDateAsString({ value, format: "YYYY-MM-DD" })).toBe("2026-05-26");
|
||||
expect(getDateAsString({ value, format: "DD-MM-YYYY" })).toBe("26-05-2026");
|
||||
expect(getDateAsString({ value, format: "MM-DD-YYYY" })).toBe("05-26-2026");
|
||||
});
|
||||
|
||||
it("formats boolean labels through shared translation keys", () => {
|
||||
const keys: string[] = [];
|
||||
const t = ((key: string) => {
|
||||
keys.push(key);
|
||||
return `translated:${key}`;
|
||||
}) as TFunction;
|
||||
|
||||
expect(getBooleanAsStringValue({ value: true, format: "yesNo", t })).toBe("translated:shared.yes");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "yesNo", t })).toBe("translated:shared.no");
|
||||
expect(getBooleanAsStringValue({ value: true, format: "trueFalse", t })).toBe("translated:shared.true");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "trueFalse", t })).toBe("translated:shared.false");
|
||||
expect(getBooleanAsStringValue({ value: true, format: "enabledDisabled", t })).toBe("translated:shared.enabled");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "enabledDisabled", t })).toBe("translated:shared.disabled");
|
||||
expect(getBooleanAsStringValue({ value: true, format: "onOff", t })).toBe("translated:shared.on");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "onOff", t })).toBe("translated:shared.off");
|
||||
expect(getBooleanAsStringValue({ value: true, format: "activeInactive", t })).toBe("translated:shared.active");
|
||||
expect(getBooleanAsStringValue({ value: false, format: "activeInactive", t })).toBe("translated:shared.inactive");
|
||||
expect(keys).toEqual([
|
||||
"shared.yes",
|
||||
"shared.no",
|
||||
"shared.true",
|
||||
"shared.false",
|
||||
"shared.enabled",
|
||||
"shared.disabled",
|
||||
"shared.on",
|
||||
"shared.off",
|
||||
"shared.active",
|
||||
"shared.inactive",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps RowHelper fallback values on translation keys", () => {
|
||||
const t = ((key: string) => `translated:${key}`) as TFunction;
|
||||
const source = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/utils/helpers/RowHelper.tsx"), "utf8");
|
||||
|
||||
expect(RowHelper.getFormattedValue(true, PropertyType.BOOLEAN, t)).toBe("translated:shared.yes");
|
||||
expect(RowHelper.getFormattedValue(false, PropertyType.BOOLEAN, t)).toBe("translated:shared.no");
|
||||
expect(RowHelper.getFormattedValue("value", "unsupported" as PropertyType, t)).toBe("translated:models.row.values.notSupported");
|
||||
expect(source).not.toContain('return "Not supported"');
|
||||
expect(source).not.toContain('return value ? "t" : "f"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const rowsRoot = path.resolve(process.cwd(), "apps/web/app/components/entities/rows");
|
||||
|
||||
function readRowComponent(relativePath: string) {
|
||||
return fs.readFileSync(path.join(rowsRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("row empty and error states i18n", () => {
|
||||
it("uses semantic translation keys for logs and unsupported values", () => {
|
||||
const sources = [readRowComponent("RowLogs.tsx"), readRowComponent("RowValueInput.tsx")].join("\n");
|
||||
|
||||
expect(sources).toContain("models.row.logs.noEvents");
|
||||
expect(sources).toContain("models.row.values.unknownFormula");
|
||||
expect(sources).toContain("models.row.values.notSupported");
|
||||
expect(sources).not.toContain("no_events_e339ba73");
|
||||
expect(sources).not.toContain("unknown_formula_f4bd1420");
|
||||
expect(sources).not.toContain("not_supported_8e635455");
|
||||
});
|
||||
|
||||
it("keeps row tag form copy on translated labels", () => {
|
||||
const source = readRowComponent("RowSettingsTags.tsx");
|
||||
|
||||
expect(source).toContain("shared.tagNamePlaceholder");
|
||||
expect(source).toContain('title={t("shared.tag")}');
|
||||
expect(source).not.toContain('title="shared.tag"');
|
||||
expect(source).not.toContain('t("shared.tagName") + "..."');
|
||||
});
|
||||
|
||||
it("keeps row activity timestamps on locale-aware formatters", () => {
|
||||
const sources = [readRowComponent("RowLogs.tsx"), readRowComponent("RowActivity.tsx"), readRowComponent("RowLogComment.tsx")].join("\n");
|
||||
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("formatters.relativeDate");
|
||||
expect(sources).toContain("formatters.dateTime");
|
||||
expect(sources).not.toContain("DateUtils");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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/components/entities/rows/RowSettingsPermissions.tsx");
|
||||
|
||||
describe("row permissions i18n", () => {
|
||||
it("uses semantic translation keys for creator and owner labels", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.row.permissionLabels.creator");
|
||||
expect(source).toContain("models.row.permissionLabels.owner");
|
||||
expect(source).not.toContain("<span>Creator</span>");
|
||||
expect(source).not.toContain('name: "Owner"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { EntitiesTemplateDto, TemplateEntityDto } from "~/modules/templates/EntityTemplateDto";
|
||||
import { translateEntityTitle, translateEntityTitlePlural, translateEntityViewTitle, translatePropertyTitle } from "~/utils/i18n/translateLabel";
|
||||
|
||||
export default function PreviewEntitiesTemplate({ template }: { template: EntitiesTemplateDto }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
function findParentRelationships(item: TemplateEntityDto) {
|
||||
return template.relationships.filter((f) => f.parent === item.name) ?? [];
|
||||
}
|
||||
function findChildRelationships(item: TemplateEntityDto) {
|
||||
return template.relationships.filter((f) => f.child === item.name) ?? [];
|
||||
}
|
||||
return (
|
||||
<TableSimple
|
||||
items={template.entities}
|
||||
headers={[
|
||||
{ name: "prefix", title: t("models.entity.prefix"), value: (i) => i.prefix },
|
||||
{
|
||||
name: "name",
|
||||
title: t("models.entity.name"),
|
||||
value: (i) => (
|
||||
<div className="flex items-baseline space-x-1">
|
||||
<div>{i.name}</div>
|
||||
<div className="text-xs italic">({i.slug})</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.entity.title"),
|
||||
value: (i) => (
|
||||
<div className="flex items-baseline space-x-1">
|
||||
<div>{translateEntityTitle(t, i18n, i)}</div>
|
||||
<div className="text-xs italic">({translateEntityTitlePlural(t, i18n, i)})</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "properties",
|
||||
title: t("models.property.plural"),
|
||||
value: (i) => i.properties.map((property) => `${translatePropertyTitle(t, i18n, i.name, property)}${property.isRequired ? "*" : ""} [${property.type}]`).join(", "),
|
||||
className: "text-xs",
|
||||
},
|
||||
{
|
||||
name: "parents",
|
||||
title: t("models.relationship.parents"),
|
||||
value: (item) =>
|
||||
findChildRelationships(item)
|
||||
.map((i) => i.parent)
|
||||
.join(", "),
|
||||
className: "text-xs",
|
||||
},
|
||||
{
|
||||
name: "children",
|
||||
title: t("models.relationship.children"),
|
||||
value: (item) =>
|
||||
findParentRelationships(item)
|
||||
.map((i) => i.child)
|
||||
.join(", "),
|
||||
className: "text-xs",
|
||||
},
|
||||
{
|
||||
name: "views",
|
||||
title: t("models.view.plural"),
|
||||
value: (item) => (
|
||||
<div>{item.views?.map((view) => translateEntityViewTitle(t, i18n, item.name, view) + (view.isDefault ? ` (${t("models.view.defaultBadge")})` : "")).join(", ")}</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
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/components/entities/templates/PreviewEntitiesTemplate.tsx");
|
||||
|
||||
describe("preview entities template i18n", () => {
|
||||
it("uses semantic translation keys for preview table headers", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("models.entity.prefix");
|
||||
expect(source).toContain("models.property.plural");
|
||||
expect(source).toContain("models.relationship.parents");
|
||||
expect(source).toContain("models.relationship.children");
|
||||
expect(source).toContain("models.view.defaultBadge");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain("(default)");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,722 @@
|
||||
import { Property } from "@toolctrl/db/prisma-browser";
|
||||
import clsx from "clsx";
|
||||
import { useRef, useState, useEffect, Fragment } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Constants from "~/application/Constants";
|
||||
import { PropertyType } from "~/application/enums/entities/PropertyType";
|
||||
import { ViewFilterCondition } from "~/application/enums/entities/ViewFilterCondition";
|
||||
import InfoBanner from "~/components/ui/banners/InfoBanner";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputGroup from "~/components/ui/forms/InputGroup";
|
||||
import InputCheckboxInline from "~/components/ui/input/InputCheckboxInline";
|
||||
import InputNumber from "~/components/ui/input/InputNumber";
|
||||
import InputRadioGroupCards from "~/components/ui/input/InputRadioGroupCards";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import OrderIndexButtons from "~/components/ui/sort/OrderIndexButtons";
|
||||
import CollapsibleRow from "~/components/ui/tables/CollapsibleRow";
|
||||
import { EntityViewLayoutTypes } from "~/modules/rows/dtos/EntityViewLayoutType";
|
||||
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
|
||||
import { EntityViewWithDetails } from "~/utils/db/entities/entityViews.db.server";
|
||||
import OrderHelper from "~/utils/helpers/OrderHelper";
|
||||
import RowColumnsHelper from "~/utils/helpers/RowColumnsHelper";
|
||||
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
|
||||
import StringUtils from "~/utils/shared/StringUtils";
|
||||
import EntityViewLayoutBadge from "./EntityViewLayoutBadge";
|
||||
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
|
||||
import RowHelper from "~/utils/helpers/RowHelper";
|
||||
import RowsList from "../rows/RowsList";
|
||||
import { defaultDisplayProperties } from "~/utils/helpers/PropertyHelper";
|
||||
import { translateEntityTitlePlural, translatePropertyTitle, translateSelectOptionLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
interface Props {
|
||||
entity: EntityWithDetails | undefined;
|
||||
item?: EntityViewWithDetails | null;
|
||||
canDelete?: boolean;
|
||||
onClose?: () => void;
|
||||
actionNames?: {
|
||||
create: string;
|
||||
update: string;
|
||||
delete: string;
|
||||
};
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
isSystem: boolean;
|
||||
showViewType: boolean;
|
||||
}
|
||||
|
||||
export default function EntityViewForm({
|
||||
entity,
|
||||
item,
|
||||
canDelete,
|
||||
onClose,
|
||||
actionNames,
|
||||
isSystem,
|
||||
tenantId,
|
||||
userId,
|
||||
showViewType,
|
||||
}: Props & { entity: EntityWithDetails }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const inputName = useRef<RefInputText>(null);
|
||||
|
||||
const [possibleProperties, setPossibleProperties] = useState<{ propertyId: string | null; name: string | null; order: number; title?: string }[]>(
|
||||
item?.properties ?? []
|
||||
);
|
||||
|
||||
const [fakeItems, setFakeItems] = useState<RowWithDetails[]>([]);
|
||||
|
||||
const [layout, setLayout] = useState<"table" | "board" | "grid" | "card">("table");
|
||||
const [name, setName] = useState("");
|
||||
const [title, setTitle] = useState("");
|
||||
const [order, setOrder] = useState<number | undefined>(item?.order ?? OrderHelper.getNextOrder(entity.views));
|
||||
const [pageSize, setPageSize] = useState<number | undefined>(item?.pageSize ?? Constants.DEFAULT_PAGE_SIZE);
|
||||
const [isDefault, setIsDefault] = useState(item?.isDefault ?? OrderHelper.getNextOrder(entity.views) === 1);
|
||||
|
||||
const [properties, setProperties] = useState<{ propertyId: string | null; name: string | null; order: number; title?: string }[]>([]);
|
||||
const [filters, setFilters] = useState<{ name: string; condition: string; value: string; match: string }[]>(item?.filters ?? []);
|
||||
// const [sort, setSort] = useState<{ name: string; asc: boolean; order: number }[]>(item?.sort ?? []);
|
||||
|
||||
// Board
|
||||
const [groupBy, setGroupBy] = useState<string | number | undefined>(item?.groupByPropertyId ? "byProperty" : undefined);
|
||||
const [groupByPropertyId, setGroupByPropertyId] = useState<string | number | undefined>(item?.groupByPropertyId ?? undefined);
|
||||
const [groupByOptions, setGroupByOptions] = useState<{ name: string; value: string }[]>([]);
|
||||
const [selectProperties, setSelectProperties] = useState<Property[]>([]);
|
||||
|
||||
// Grid
|
||||
const [gridColumns, setGridColumns] = useState<number | undefined>(item?.gridColumns || 0);
|
||||
const [gridColumnsSm, setGridColumnsSm] = useState<number | undefined>(item?.gridColumnsSm || 0);
|
||||
const [gridColumnsMd, setGridColumnsMd] = useState<number | undefined>(item?.gridColumnsMd || 0);
|
||||
const [gridColumnsLg, setGridColumnsLg] = useState<number | undefined>(item?.gridColumnsLg || 0);
|
||||
const [gridColumnsXl, setGridColumnsXl] = useState<number | undefined>(item?.gridColumnsXl || 0);
|
||||
const [gridColumns2xl, setGridColumns2xl] = useState<number | undefined>(item?.gridColumns2xl || 0);
|
||||
const [gridGap, setGridGap] = useState(item?.gridGap ?? "sm");
|
||||
|
||||
const [filterByProperties, setFilterByProperties] = useState<{ name: string; value: string }[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!item && isSystem) {
|
||||
setName("system-" + entity.slug);
|
||||
setTitle(t("models.view.systemTitle", { entity: translateEntityTitlePlural(t, i18n, entity) }));
|
||||
setLayout("card");
|
||||
} else if (item) {
|
||||
setName(item.name);
|
||||
setTitle(item.title);
|
||||
setLayout(item.layout as "table" | "board" | "grid" | "card");
|
||||
}
|
||||
}, [entity, isSystem, item, t]);
|
||||
|
||||
useEffect(() => {
|
||||
const items: RowWithDetails[] = Array.from({ length: 10 }).map((_, idx) => {
|
||||
let nonDefaultProperties = properties.filter((p) => !defaultDisplayProperties.find((dp) => dp.name === p.name));
|
||||
const item: RowWithDetails = {
|
||||
values: nonDefaultProperties.map(({ name }) => {
|
||||
const property = entity.properties.find((p) => p.name === name);
|
||||
if (!property) return null;
|
||||
return RowHelper.getFakePropertyValue({ property, t, idx: idx + 1 });
|
||||
}),
|
||||
folio: idx + 1,
|
||||
createdAt: new Date(),
|
||||
createdByUser: {
|
||||
email: "preview@example.invalid",
|
||||
firstName: "Preview",
|
||||
lastName: "User",
|
||||
},
|
||||
} as RowWithDetails;
|
||||
return item;
|
||||
});
|
||||
setFakeItems(items);
|
||||
}, [entity.properties, properties, t]);
|
||||
|
||||
useEffect(() => {
|
||||
const possibleProperties = RowColumnsHelper.getDefaultEntityColumns(entity).map((i, idx) => {
|
||||
const property = entity.properties.find((p) => p.name === i.name);
|
||||
return {
|
||||
propertyId: property?.id ?? null,
|
||||
name: i.name,
|
||||
title: i.title,
|
||||
order: idx + 1,
|
||||
};
|
||||
});
|
||||
setPossibleProperties(possibleProperties);
|
||||
}, [entity]);
|
||||
|
||||
// Initial selected properties
|
||||
useEffect(() => {
|
||||
if (item) {
|
||||
setProperties(item.properties);
|
||||
} else {
|
||||
setProperties(
|
||||
RowColumnsHelper.getDefaultEntityColumns(entity)
|
||||
.filter((f) => f.visible)
|
||||
.map((i, idx) => {
|
||||
return {
|
||||
propertyId: null,
|
||||
name: i.name,
|
||||
title: i.title,
|
||||
order: idx + 1,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
}, [entity, item]);
|
||||
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
inputName.current?.input.current?.focus();
|
||||
}, 100);
|
||||
|
||||
const selectProperties = entity.properties.filter((f) => [PropertyType.SELECT, PropertyType.MULTI_SELECT].includes(f.type));
|
||||
setGroupByOptions([
|
||||
{
|
||||
name: t("models.view.property"),
|
||||
value: "byProperty",
|
||||
},
|
||||
]);
|
||||
setSelectProperties(selectProperties);
|
||||
|
||||
let filterByProperties = entity.properties
|
||||
.filter((f) => f.type === PropertyType.TEXT || f.type === PropertyType.SELECT || f.type === PropertyType.BOOLEAN)
|
||||
.map((property) => {
|
||||
return {
|
||||
name: translatePropertyTitle(t, i18n, entity.name, property),
|
||||
value: property.name,
|
||||
};
|
||||
});
|
||||
if (entity.hasTags) {
|
||||
filterByProperties = [...filterByProperties, { name: t("models.row.tags"), value: "tags" }];
|
||||
}
|
||||
setFilterByProperties(filterByProperties);
|
||||
}, [entity, t]);
|
||||
|
||||
function getPropertyByName(name: string) {
|
||||
return entity.properties.find((f) => f.name === name);
|
||||
}
|
||||
|
||||
function getPropertyConditionsByName(name: string) {
|
||||
if (name === "tags") {
|
||||
return [
|
||||
{ value: ViewFilterCondition.equals, name: t("entities.conditions.equals") },
|
||||
{ value: ViewFilterCondition.contains, name: t("entities.conditions.contains") },
|
||||
{ value: ViewFilterCondition.notIn, name: t("entities.conditions.notIn") },
|
||||
];
|
||||
} else {
|
||||
const property = getPropertyByName(name);
|
||||
if (property?.type === PropertyType.BOOLEAN) {
|
||||
return [
|
||||
{ value: ViewFilterCondition.equals, name: t("entities.conditions.equals") },
|
||||
// { value: ViewFilterCondition.notIn, name: t("entities.conditions.notIn") },
|
||||
];
|
||||
} else if (property?.type === PropertyType.TEXT || property?.type === PropertyType.SELECT) {
|
||||
return [
|
||||
{ value: ViewFilterCondition.equals, name: t("entities.conditions.equals") },
|
||||
{ value: ViewFilterCondition.contains, name: t("entities.conditions.contains") },
|
||||
{ value: ViewFilterCondition.lt, name: t("entities.conditions.lt") },
|
||||
{ value: ViewFilterCondition.lte, name: t("entities.conditions.lte") },
|
||||
{ value: ViewFilterCondition.gt, name: t("entities.conditions.gt") },
|
||||
{ value: ViewFilterCondition.gte, name: t("entities.conditions.gte") },
|
||||
{ value: ViewFilterCondition.startsWith, name: t("entities.conditions.startsWith") },
|
||||
{ value: ViewFilterCondition.endsWith, name: t("entities.conditions.endsWith") },
|
||||
{ value: ViewFilterCondition.in, name: t("entities.conditions.in") },
|
||||
{ value: ViewFilterCondition.notIn, name: t("entities.conditions.notIn") },
|
||||
];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
function getPropertyTitle(name: string) {
|
||||
return RowColumnsHelper.getDefaultEntityColumns(entity).find((f) => f.name === name)?.title ?? "";
|
||||
}
|
||||
|
||||
function getTypeTitle() {
|
||||
if (isSystem) {
|
||||
return t("models.view.typeSummary", { type: t("models.view.types.system") });
|
||||
} else if (!tenantId && !userId) {
|
||||
return t("models.view.typeSummary", { type: t("models.view.types.default") });
|
||||
} else if (tenantId && !userId) {
|
||||
return t("models.view.typeSummary", { type: t("models.view.types.tenant") });
|
||||
} else if (tenantId && userId) {
|
||||
return t("models.view.typeSummary", { type: t("models.view.types.user") });
|
||||
}
|
||||
return t("models.view.typeSummary", { type: t("models.view.types.tenant") });
|
||||
}
|
||||
|
||||
function getTypeDescription() {
|
||||
if (isSystem) {
|
||||
return t("models.view.typeDescriptions.system");
|
||||
} else if (!tenantId && !userId) {
|
||||
return t("models.view.typeDescriptions.default");
|
||||
} else if (tenantId && !userId) {
|
||||
return t("models.view.typeDescriptions.tenant");
|
||||
} else if (tenantId && userId) {
|
||||
return t("models.view.typeDescriptions.user");
|
||||
}
|
||||
return t("models.view.typeDescriptions.tenant");
|
||||
}
|
||||
|
||||
return (
|
||||
<FormGroup id={item?.id} onCancel={onClose} editing={true} canDelete={canDelete} actionNames={actionNames} className="text-foreground">
|
||||
<input type="hidden" name="id" value={item?.id} hidden readOnly />
|
||||
<input type="hidden" name="entityId" value={entity.id} hidden readOnly />
|
||||
<input type="hidden" name="isSystem" value={isSystem ? "true" : "false"} hidden readOnly />
|
||||
<input type="hidden" name="tenantId" value={tenantId ?? undefined} hidden readOnly />
|
||||
<input type="hidden" name="userId" value={userId ?? undefined} hidden readOnly />
|
||||
|
||||
{showViewType && <InfoBanner title={getTypeTitle()} text={getTypeDescription()} />}
|
||||
|
||||
<InputGroup title={t("models.view.object")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<InputRadioGroupCards
|
||||
display="name"
|
||||
columns={EntityViewLayoutTypes.length}
|
||||
className="sm:col-span-12"
|
||||
name="layout"
|
||||
title={t("models.view.layout")}
|
||||
value={layout}
|
||||
onChange={(e) => setLayout((e?.toString() ?? "table") as "table" | "board" | "grid" | "card")}
|
||||
options={EntityViewLayoutTypes.map((f) => {
|
||||
return {
|
||||
name: t(f.labelKey),
|
||||
value: f.value,
|
||||
renderName: (
|
||||
<div className="flex items-center space-x-2">
|
||||
<EntityViewLayoutBadge layout={f.value} className="text-muted-foreground h-3 w-3" />
|
||||
<div>{t(f.labelKey)}</div>
|
||||
</div>
|
||||
),
|
||||
};
|
||||
})}
|
||||
/>
|
||||
|
||||
<InputText
|
||||
autoFocus
|
||||
className={clsx(isSystem ? "sm:col-span-6" : "sm:col-span-3")}
|
||||
name="name"
|
||||
title={t("models.entity.name")}
|
||||
value={name}
|
||||
setValue={(e) => setName(e.toString().toLowerCase())}
|
||||
autoComplete="off"
|
||||
required
|
||||
// lowercase
|
||||
onBlur={() => {
|
||||
if (!item) {
|
||||
let title = StringUtils.capitalize(name.toLowerCase());
|
||||
// replace - occurrences with spaces
|
||||
title = title.replace(/-/g, " ");
|
||||
setTitle(title);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<InputText
|
||||
className={clsx(isSystem ? "sm:col-span-6" : "sm:col-span-3")}
|
||||
name="title"
|
||||
title={t("models.entity.title")}
|
||||
value={title}
|
||||
setValue={setTitle}
|
||||
autoComplete="off"
|
||||
required
|
||||
withTranslation={true}
|
||||
/>
|
||||
{!isSystem && (
|
||||
<Fragment>
|
||||
<InputNumber className="sm:col-span-3" name="pageSize" title={t("models.view.pageSize")} value={pageSize} setValue={setPageSize} min={1} max={500} required />
|
||||
<InputNumber
|
||||
className="sm:col-span-3"
|
||||
name="order"
|
||||
title={t("models.entity.order")}
|
||||
value={order}
|
||||
setValue={setOrder}
|
||||
disabled={!item}
|
||||
min={1}
|
||||
max={99}
|
||||
required
|
||||
/>
|
||||
<InputCheckboxInline className="sm:col-span-12" name="isDefault" title={t("models.view.isDefault")} value={isDefault} setValue={setIsDefault} />
|
||||
</Fragment>
|
||||
)}
|
||||
</div>
|
||||
</InputGroup>
|
||||
|
||||
{layout === "board" && (
|
||||
<InputGroup title={t("models.view.board")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-12">
|
||||
<>
|
||||
<InputSelect className="sm:col-span-6" name="groupBy" title={t("models.view.groupBy")} value={groupBy} setValue={setGroupBy} options={groupByOptions} />
|
||||
<InputSelect
|
||||
className="sm:col-span-6"
|
||||
name="groupByPropertyId"
|
||||
title={t("models.view.property")}
|
||||
value={groupByPropertyId}
|
||||
setValue={setGroupByPropertyId}
|
||||
options={selectProperties.map((item) => {
|
||||
return {
|
||||
name: t(item.title),
|
||||
value: item.id,
|
||||
};
|
||||
})}
|
||||
/>
|
||||
</>
|
||||
</div>
|
||||
</InputGroup>
|
||||
)}
|
||||
|
||||
{layout === "grid" && (
|
||||
<InputGroup title={t("models.view.grid")}>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-7">
|
||||
<InputNumber name="gridColumns" title={t("models.view.columns")} value={gridColumns} setValue={setGridColumns} min={0} max={12} required />
|
||||
<InputNumber name="gridColumnsSm" title="sm" value={gridColumnsSm} setValue={setGridColumnsSm} min={0} max={12} required />
|
||||
<InputNumber name="gridColumnsMd" title="md" value={gridColumnsMd} setValue={setGridColumnsMd} min={0} max={12} required />
|
||||
<InputNumber name="gridColumnsLg" title="lg" value={gridColumnsLg} setValue={setGridColumnsLg} min={0} max={12} required />
|
||||
<InputNumber name="gridColumnsXl" title="xl" value={gridColumnsXl} setValue={setGridColumnsXl} min={0} max={12} required />
|
||||
<InputNumber name="gridColumns2xl" title="2xl" value={gridColumns2xl} setValue={setGridColumns2xl} min={0} max={12} required />
|
||||
|
||||
<InputSelect
|
||||
name="gridGap"
|
||||
title={t("models.view.gap")}
|
||||
value={gridGap}
|
||||
setValue={(e) => setGridGap(e?.toString() ?? "sm")}
|
||||
options={[
|
||||
{ name: "xs", value: "xs" },
|
||||
{ name: "sm", value: "sm" },
|
||||
{ name: "md", value: "md" },
|
||||
{ name: "lg", value: "lg" },
|
||||
{ name: "xl", value: "xl" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<div className="divide-border divide-y">
|
||||
{properties.map((item, idx) => (
|
||||
<input key={idx} type="text" name="properties[]" readOnly hidden value={JSON.stringify(item)} />
|
||||
))}
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-baseline space-x-1">
|
||||
<div className="text-sm font-medium">{t("shared.all")}</div>
|
||||
<div className="flex items-center space-x-1">
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground text-xs"
|
||||
onClick={() => setProperties(possibleProperties)}
|
||||
disabled={properties.length === possibleProperties.length}
|
||||
>
|
||||
({t("shared.selectAll")})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-border h-64 space-y-1 overflow-y-scroll rounded-md border-2 border-dashed p-2">
|
||||
{possibleProperties.map((item, idx) => (
|
||||
<div key={item.name}>
|
||||
<InputCheckboxInline
|
||||
name={"properties[" + idx + "].propertyId"}
|
||||
title={
|
||||
<div className="flex items-baseline space-x-1 truncate text-sm">
|
||||
<div className={clsx("truncate", item.name?.includes(".") ? "text-muted-foreground" : "text-foreground font-medium")}>
|
||||
{item.title ? t(item.title) : item.name}
|
||||
</div>
|
||||
<div
|
||||
className={clsx(
|
||||
"truncate text-xs font-normal",
|
||||
item.name?.includes(".") ? "text-muted-foreground italic" : "text-foreground font-bold"
|
||||
)}
|
||||
>
|
||||
({item?.name})
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
value={properties.find((f) => f.name === item.name) !== undefined}
|
||||
setValue={(e) => {
|
||||
if (e) {
|
||||
setProperties([
|
||||
...properties,
|
||||
{ propertyId: item.propertyId, name: item.name, title: item.title, order: OrderHelper.getNextOrder(properties) },
|
||||
]);
|
||||
} else {
|
||||
setProperties(properties.filter((f) => f.name !== item.name));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-baseline space-x-1">
|
||||
<div className="text-sm font-medium">{t("models.view.propertiesDisplayed")}</div>
|
||||
<button type="button" className="text-muted-foreground text-xs" onClick={() => setProperties([])} disabled={properties.length === 0}>
|
||||
({t("shared.clear")})
|
||||
</button>
|
||||
</div>
|
||||
<div className="border-border h-64 space-y-1 overflow-y-scroll rounded-md border-2 border-dashed p-2">
|
||||
{properties
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((item, idx) => (
|
||||
<div key={idx} className="flex items-baseline space-x-1 text-sm">
|
||||
<div className="shrink-0">
|
||||
<OrderIndexButtons
|
||||
idx={idx}
|
||||
items={properties.map((item, itemIdx) => {
|
||||
return {
|
||||
order: item.order,
|
||||
idx: itemIdx,
|
||||
};
|
||||
})}
|
||||
onChange={(newOrders) => {
|
||||
setProperties(
|
||||
properties.map((item, itemIdx) => {
|
||||
const newOrder = newOrders.find((f) => f.idx === itemIdx);
|
||||
if (newOrder) {
|
||||
return {
|
||||
...item,
|
||||
order: newOrder.order,
|
||||
};
|
||||
} else {
|
||||
return item;
|
||||
}
|
||||
})
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className={clsx("truncate", item.name?.includes(".") ? "text-muted-foreground" : "text-foreground font-medium")}>
|
||||
{item.title ? t(item.title) : t(getPropertyTitle(item.name ?? ""))}{" "}
|
||||
<span className={clsx("text-xs font-normal", item.name?.includes(".") ? "text-muted-foreground italic" : "text-foreground font-bold")}>
|
||||
({item?.name})
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!isSystem && (
|
||||
<Fragment>
|
||||
<InputGroup title={t("models.view.filters")}>
|
||||
{filters.map((item, idx) => (
|
||||
<input key={idx} type="text" name="filters[]" readOnly hidden value={JSON.stringify(item)} />
|
||||
))}
|
||||
<div className="mb-2 space-y-2">
|
||||
{filters.map((item, idx) => (
|
||||
<CollapsibleRow
|
||||
className="bg-secondary"
|
||||
initial={true}
|
||||
key={idx}
|
||||
title={`${item.name} (${item.condition}) ${item.value}`}
|
||||
value={
|
||||
<div className="flex items-center space-x-1 text-sm">
|
||||
<div className="font-medium">{item.name}</div>
|
||||
<div className="text-muted-foreground font-light">{item.condition}</div>
|
||||
<div className="">{item.value}</div>
|
||||
</div>
|
||||
}
|
||||
onRemove={() => setFilters(filters.filter((_, i) => i !== idx))}
|
||||
>
|
||||
<div className="grid grid-cols-12 gap-3">
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
name={"filters[" + idx + "].match"}
|
||||
title={t("models.view.match")}
|
||||
value={item.match}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(filters, setFilters, idx, {
|
||||
match: e,
|
||||
})
|
||||
}
|
||||
options={[
|
||||
{ name: t("models.view.matchOperators.and"), value: "and" },
|
||||
{ name: t("models.view.matchOperators.or"), value: "or" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-4">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
name={"filters[" + idx + "].propertyId"}
|
||||
title={t("models.view.property")}
|
||||
value={item.name}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(filters, setFilters, idx, {
|
||||
name: e,
|
||||
})
|
||||
}
|
||||
options={filterByProperties}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
name={"filters[" + idx + "].condition"}
|
||||
title={t("shared.condition")}
|
||||
value={item.condition}
|
||||
setValue={(e) =>
|
||||
updateItemByIdx(filters, setFilters, idx, {
|
||||
condition: e,
|
||||
})
|
||||
}
|
||||
options={getPropertyConditionsByName(item.name)}
|
||||
/>
|
||||
</div>
|
||||
<Fragment>
|
||||
{getPropertyByName(item.name)?.type === PropertyType.BOOLEAN ? (
|
||||
<div className="sm:col-span-3">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
name={"filters[" + idx + "].value"}
|
||||
title={t("shared.value")}
|
||||
value={item.value}
|
||||
setValue={(e) => updateItemByIdx(filters, setFilters, idx, { value: e })}
|
||||
options={[
|
||||
{ name: t("shared.true"), value: "true" },
|
||||
{ name: t("shared.false"), value: "false" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
) : getPropertyByName(item.name)?.type === PropertyType.SELECT ? (
|
||||
<div className="sm:col-span-3">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
name={"filters[" + idx + "].value"}
|
||||
title={t("shared.value")}
|
||||
value={item.value}
|
||||
setValue={(e) => updateItemByIdx(filters, setFilters, idx, { value: e })}
|
||||
options={
|
||||
getPropertyByName(item.name)?.options.map((i) => {
|
||||
return {
|
||||
name: translateSelectOptionLabel(t, i18n, entity.name, item.name, i),
|
||||
value: i.value,
|
||||
};
|
||||
}) ?? []
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="sm:col-span-3">
|
||||
<InputText
|
||||
name={"filters[" + idx + "].value"}
|
||||
title={t("shared.value")}
|
||||
value={item.value}
|
||||
setValue={(e) => updateItemByIdx(filters, setFilters, idx, { value: e })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
</div>
|
||||
</CollapsibleRow>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const firstProperty = filterByProperties.length > 0 ? filterByProperties[0].value : "";
|
||||
setFilters([
|
||||
...filters,
|
||||
{
|
||||
name: firstProperty,
|
||||
condition: "equals",
|
||||
value: "",
|
||||
match: "and",
|
||||
},
|
||||
]);
|
||||
}}
|
||||
className="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-gray-500"
|
||||
>
|
||||
<span className="text-muted-foreground block text-xs font-normal">
|
||||
{filters.length === 0 ? t("models.view.noFilters") : t("models.view.addFilter")}
|
||||
</span>
|
||||
</button>
|
||||
</InputGroup>
|
||||
|
||||
{/* <InputGroup title="Sort">
|
||||
{sort.map((item, idx) => (
|
||||
<input key={idx} type="text" name="sort[]" readOnly hidden value={JSON.stringify(item)} />
|
||||
))}
|
||||
<div className="space-y-2 mb-2">
|
||||
{sort
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((item, idx) => (
|
||||
<CollapsibleRow
|
||||
className="bg-secondary"
|
||||
key={idx}
|
||||
initial={true}
|
||||
title={`${item.name} (${item.asc ? "asc" : "desc"})`}
|
||||
value={
|
||||
<div className="flex space-x-1 items-center text-sm">
|
||||
<div className="font-medium">{item.name}</div>
|
||||
<div className="font-light text-muted-foreground">{item.asc ? "asc" : "desc"}</div>
|
||||
</div>
|
||||
}
|
||||
onRemove={() => setSort(sort.filter((_, i) => i !== idx))}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<InputSelector
|
||||
withSearch={false}
|
||||
name={"sort[" + idx + "].name"}
|
||||
title="Property"
|
||||
value={item.name}
|
||||
setValue={(e) => updateItemByIdx(sort, setSort, idx, { name: e })}
|
||||
options={entity.properties.map((property) => {
|
||||
return {
|
||||
name: translatePropertyTitle(t, i18n, entity.name, property),
|
||||
value: property.name,
|
||||
};
|
||||
})}
|
||||
/>
|
||||
<InputSelect
|
||||
name={"sort[" + idx + "].order"}
|
||||
title="Order"
|
||||
value={item.asc ? "asc" : "desc"}
|
||||
setValue={(e) => updateItemByIdx(sort, setSort, idx, { asc: e?.toString() === "asc" })}
|
||||
options={[
|
||||
{
|
||||
name: "Ascending",
|
||||
value: "asc",
|
||||
},
|
||||
{
|
||||
name: "Descending",
|
||||
value: "desc",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleRow>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setSort([...sort, { name: entity.properties.find((f) => !f.isDefault)?.name ?? "", asc: true, order: OrderHelper.getNextOrder(sort) }])
|
||||
}
|
||||
className="relative block w-full border-2 border-border border-dashed rounded-lg p-4 text-center hover:border-border focus:outline-hidden focus:ring-2 focus:ring-gray-500"
|
||||
>
|
||||
<span className="block text-xs font-normal text-muted-foreground">{filters.length === 0 ? "No sort fields" : "Add sort"}</span>
|
||||
</button>
|
||||
</InputGroup> */}
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
<InputGroup title={t("shared.preview")}>
|
||||
<div className="space-y-2">
|
||||
<RowsList
|
||||
view={layout}
|
||||
entity={entity}
|
||||
items={fakeItems}
|
||||
columns={properties.map((p) => ({
|
||||
name: p.name ?? "",
|
||||
title: p.title ?? "",
|
||||
visible: true,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</InputGroup>
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
interface Props {
|
||||
layout: string;
|
||||
className?: string;
|
||||
}
|
||||
export default function EntityViewLayoutBadge({ layout, className = "h-5 w-5 text-muted-foreground" }: Props) {
|
||||
return (
|
||||
<>
|
||||
{layout === "table" && (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className={className} viewBox="0 0 20 20" fill="currentColor">
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M5 4a3 3 0 00-3 3v6a3 3 0 003 3h10a3 3 0 003-3V7a3 3 0 00-3-3H5zm-1 9v-1h5v2H5a1 1 0 01-1-1zm7 1h4a1 1 0 001-1v-1h-5v2zm0-4h5V8h-5v2zM9 8H4v2h5V8z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
{layout === "board" && (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className={className} viewBox="0 0 20 20" fill="currentColor">
|
||||
<path d="M2 4a1 1 0 011-1h2a1 1 0 011 1v12a1 1 0 01-1 1H3a1 1 0 01-1-1V4zM8 4a1 1 0 011-1h2a1 1 0 011 1v12a1 1 0 01-1 1H9a1 1 0 01-1-1V4zM15 3a1 1 0 00-1 1v12a1 1 0 001 1h2a1 1 0 001-1V4a1 1 0 00-1-1h-2z" />
|
||||
</svg>
|
||||
)}
|
||||
|
||||
{layout === "grid" && (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className={className} viewBox="0 0 20 20" fill="currentColor">
|
||||
<path d="M5 3a2 2 0 00-2 2v2a2 2 0 002 2h2a2 2 0 002-2V5a2 2 0 00-2-2H5zM5 11a2 2 0 00-2 2v2a2 2 0 002 2h2a2 2 0 002-2v-2a2 2 0 00-2-2H5zM11 5a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V5zM11 13a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
|
||||
</svg>
|
||||
)}
|
||||
|
||||
{layout === "card" && (
|
||||
// <svg className={className} xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="80" height="80" viewBox="0 0 80 80" fill="currentColor">
|
||||
// <path d="M 19 14 C 12.9375 14 8 18.9375 8 25 L 8 55 C 8 61.0625 12.9375 66 19 66 L 61 66 C 67.0625 66 72 61.0625 72 55 L 72 25 C 72 18.9375 67.0625 14 61 14 Z M 19 16 L 61 16 C 65.984375 16 70 20.015625 70 25 L 70 55 C 70 59.984375 65.984375 64 61 64 L 19 64 C 14.015625 64 10 59.984375 10 55 L 10 25 C 10 20.015625 14.015625 16 19 16 Z M 22 19 C 21.449219 19 21 19.449219 21 20 C 21 20.550781 21.449219 21 22 21 C 22.550781 21 23 20.550781 23 20 C 23 19.449219 22.550781 19 22 19 Z M 26 19 C 25.449219 19 25 19.449219 25 20 C 25 20.550781 25.449219 21 26 21 C 26.550781 21 27 20.550781 27 20 C 27 19.449219 26.550781 19 26 19 Z M 30 19 C 29.449219 19 29 19.449219 29 20 C 29 20.550781 29.449219 21 30 21 C 30.550781 21 31 20.550781 31 20 C 31 19.449219 30.550781 19 30 19 Z M 34 19 C 33.449219 19 33 19.449219 33 20 C 33 20.550781 33.449219 21 34 21 C 34.550781 21 35 20.550781 35 20 C 35 19.449219 34.550781 19 34 19 Z M 38 19 C 37.449219 19 37 19.449219 37 20 C 37 20.550781 37.449219 21 38 21 C 38.550781 21 39 20.550781 39 20 C 39 19.449219 38.550781 19 38 19 Z M 42 19 C 41.449219 19 41 19.449219 41 20 C 41 20.550781 41.449219 21 42 21 C 42.550781 21 43 20.550781 43 20 C 43 19.449219 42.550781 19 42 19 Z M 46 19 C 45.449219 19 45 19.449219 45 20 C 45 20.550781 45.449219 21 46 21 C 46.550781 21 47 20.550781 47 20 C 47 19.449219 46.550781 19 46 19 Z M 50 19 C 49.449219 19 49 19.449219 49 20 C 49 20.550781 49.449219 21 50 21 C 50.550781 21 51 20.550781 51 20 C 51 19.449219 50.550781 19 50 19 Z M 54 19 C 53.449219 19 53 19.449219 53 20 C 53 20.550781 53.449219 21 54 21 C 54.550781 21 55 20.550781 55 20 C 55 19.449219 54.550781 19 54 19 Z M 58 19 C 57.449219 19 57 19.449219 57 20 C 57 20.550781 57.449219 21 58 21 C 58.550781 21 59 20.550781 59 20 C 59 19.449219 58.550781 19 58 19 Z M 18 20 C 17.449219 20 17 20.449219 17 21 C 17 21.550781 17.449219 22 18 22 C 18.550781 22 19 21.550781 19 21 C 19 20.449219 18.550781 20 18 20 Z M 62 20 C 61.449219 20 61 20.449219 61 21 C 61 21.550781 61.449219 22 62 22 C 62.550781 22 63 21.550781 63 21 C 63 20.449219 62.550781 20 62 20 Z M 15 23 C 14.449219 23 14 23.449219 14 24 C 14 24.550781 14.449219 25 15 25 C 15.550781 25 16 24.550781 16 24 C 16 23.449219 15.550781 23 15 23 Z M 65 23 C 64.449219 23 64 23.449219 64 24 C 64 24.550781 64.449219 25 65 25 C 65.550781 25 66 24.550781 66 24 C 66 23.449219 65.550781 23 65 23 Z M 14 27 C 13.449219 27 13 27.449219 13 28 C 13 28.550781 13.449219 29 14 29 C 14.550781 29 15 28.550781 15 28 C 15 27.449219 14.550781 27 14 27 Z M 66 27 C 65.449219 27 65 27.449219 65 28 C 65 28.550781 65.449219 29 66 29 C 66.550781 29 67 28.550781 67 28 C 67 27.449219 66.550781 27 66 27 Z M 14 31 C 13.449219 31 13 31.449219 13 32 C 13 32.550781 13.449219 33 14 33 C 14.550781 33 15 32.550781 15 32 C 15 31.449219 14.550781 31 14 31 Z M 66 31 C 65.449219 31 65 31.449219 65 32 C 65 32.550781 65.449219 33 66 33 C 66.550781 33 67 32.550781 67 32 C 67 31.449219 66.550781 31 66 31 Z M 14 35 C 13.449219 35 13 35.449219 13 36 C 13 36.550781 13.449219 37 14 37 C 14.550781 37 15 36.550781 15 36 C 15 35.449219 14.550781 35 14 35 Z M 66 35 C 65.449219 35 65 35.449219 65 36 C 65 36.550781 65.449219 37 66 37 C 66.550781 37 67 36.550781 67 36 C 67 35.449219 66.550781 35 66 35 Z M 14 39 C 13.449219 39 13 39.449219 13 40 C 13 40.550781 13.449219 41 14 41 C 14.550781 41 15 40.550781 15 40 C 15 39.449219 14.550781 39 14 39 Z M 66 39 C 65.449219 39 65 39.449219 65 40 C 65 40.550781 65.449219 41 66 41 C 66.550781 41 67 40.550781 67 40 C 67 39.449219 66.550781 39 66 39 Z M 14 43 C 13.449219 43 13 43.449219 13 44 C 13 44.550781 13.449219 45 14 45 C 14.550781 45 15 44.550781 15 44 C 15 43.449219 14.550781 43 14 43 Z M 66 43 C 65.449219 43 65 43.449219 65 44 C 65 44.550781 65.449219 45 66 45 C 66.550781 45 67 44.550781 67 44 C 67 43.449219 66.550781 43 66 43 Z M 14 47 C 13.449219 47 13 47.449219 13 48 C 13 48.550781 13.449219 49 14 49 C 14.550781 49 15 48.550781 15 48 C 15 47.449219 14.550781 47 14 47 Z M 66 47 C 65.449219 47 65 47.449219 65 48 C 65 48.550781 65.449219 49 66 49 C 66.550781 49 67 48.550781 67 48 C 67 47.449219 66.550781 47 66 47 Z M 14 51 C 13.449219 51 13 51.449219 13 52 C 13 52.550781 13.449219 53 14 53 C 14.550781 53 15 52.550781 15 52 C 15 51.449219 14.550781 51 14 51 Z M 66 51 C 65.449219 51 65 51.449219 65 52 C 65 52.550781 65.449219 53 66 53 C 66.550781 53 67 52.550781 67 52 C 67 51.449219 66.550781 51 66 51 Z M 15 55 C 14.449219 55 14 55.449219 14 56 C 14 56.550781 14.449219 57 15 57 C 15.550781 57 16 56.550781 16 56 C 16 55.449219 15.550781 55 15 55 Z M 65 55 C 64.449219 55 64 55.449219 64 56 C 64 56.550781 64.449219 57 65 57 C 65.550781 57 66 56.550781 66 56 C 66 55.449219 65.550781 55 65 55 Z M 18 58 C 17.449219 58 17 58.449219 17 59 C 17 59.550781 17.449219 60 18 60 C 18.550781 60 19 59.550781 19 59 C 19 58.449219 18.550781 58 18 58 Z M 62 58 C 61.449219 58 61 58.449219 61 59 C 61 59.550781 61.449219 60 62 60 C 62.550781 60 63 59.550781 63 59 C 63 58.44921
Line truncated
|
||||
// </svg>
|
||||
<svg className={className} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100">
|
||||
<rect x="20" y="20" rx="10" ry="10" width="80" height="80" fill="currentColor" />
|
||||
<rect x="110" y="20" rx="10" ry="10" width="80" height="80" fill="currentColor" />
|
||||
</svg>
|
||||
|
||||
// <span className="text-xs font-medium italic">Row</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import TenantBadge from "~/components/core/tenants/TenantBadge";
|
||||
import UserBadge from "~/components/core/users/UserBadge";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { EntityViewWithTenantAndUser } from "~/utils/db/entities/entityViews.db.server";
|
||||
import { defaultDisplayProperties } from "~/utils/helpers/PropertyHelper";
|
||||
import EntityViewLayoutBadge from "./EntityViewLayoutBadge";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { translateEntityTitlePlural, translateEntityViewTitle } from "~/utils/i18n/translateLabel";
|
||||
|
||||
export default function EntityViewsTable({
|
||||
items,
|
||||
onClickRoute,
|
||||
}: {
|
||||
items: EntityViewWithTenantAndUser[];
|
||||
onClickRoute: (item: EntityViewWithTenantAndUser) => string;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
return (
|
||||
<TableSimple
|
||||
items={items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, i) => onClickRoute(i),
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
// {
|
||||
// name: "debug",
|
||||
// title: "Debug",
|
||||
// value: (i) => (
|
||||
// <div>
|
||||
// <ShowPayloadModalButton title="Debug" description="Debug" payload={JSON.stringify(i, null, 2)} />
|
||||
// </div>
|
||||
// ),
|
||||
// },
|
||||
{
|
||||
name: "entity",
|
||||
title: t("models.entity.object"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{translateEntityTitlePlural(t, i18n, i.entity)}</div>
|
||||
{/* <div className="text-xs text-muted-foreground">{i.entity.name}</div> */}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "Layout",
|
||||
title: t("models.view.layout"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
<EntityViewLayoutBadge layout={i.layout} className="text-muted-foreground mx-auto h-5 w-5" />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.view.title"),
|
||||
className: "w-full",
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<Link to={adminPath(`entities/views/${i.id}`, { mode: "host-aware" })} className="hover:underline">
|
||||
{translateEntityViewTitle(t, i18n, i.entity.name, i)}
|
||||
</Link>
|
||||
{/* <div className="text-xs text-muted-foreground">{i.name}</div> */}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "appliesTo",
|
||||
title: t("models.view.appliesTo"),
|
||||
value: (i) => (
|
||||
<div className="flex items-center space-x-1">
|
||||
<div>
|
||||
{i.isSystem ? (
|
||||
<div className="font-medium italic">{t("models.view.appliesToStates.systemView")}</div>
|
||||
) : !i.tenant && !i.user ? (
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium italic">{t("models.view.appliesToStates.defaultAllAccounts")}</div>
|
||||
</div>
|
||||
) : i.tenant && i.user ? (
|
||||
<div className="flex items-center space-x-1">
|
||||
<div>
|
||||
<TenantBadge item={i.tenant} />
|
||||
</div>
|
||||
<div>→</div>
|
||||
<UserBadge item={i.user} />
|
||||
</div>
|
||||
) : i.tenant ? (
|
||||
<div>
|
||||
<TenantBadge item={i.tenant} />
|
||||
</div>
|
||||
) : i.user ? (
|
||||
<div>
|
||||
<UserBadge item={i.user} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="italic text-red-500">{t("models.view.appliesToStates.invalid")}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "properties",
|
||||
title: t("models.view.properties"),
|
||||
value: (i) => {
|
||||
return (
|
||||
<div>
|
||||
{/* {i.properties
|
||||
.map((p) => {
|
||||
const defaultProperty = defaultDisplayProperties.find((f) => f.name === p.name);
|
||||
if (defaultProperty) {
|
||||
return t(defaultProperty.title);
|
||||
}
|
||||
return p.name;
|
||||
})
|
||||
.join(", ")} */}
|
||||
<ShowPayloadModalButton
|
||||
description={t("models.view.payload.propertiesCount", { count: i.properties.length })}
|
||||
title={t("models.view.properties")}
|
||||
payload={JSON.stringify(
|
||||
i.properties.map((p) => {
|
||||
const defaultProperty = defaultDisplayProperties.find((f) => f.name === p.name);
|
||||
if (defaultProperty) {
|
||||
return t(defaultProperty.title);
|
||||
}
|
||||
return p.name;
|
||||
}),
|
||||
null,
|
||||
2
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "filters",
|
||||
title: t("models.view.filters"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
<ShowPayloadModalButton
|
||||
description={t("models.view.payload.filtersCount", { count: i.filters.length })}
|
||||
title={t("models.view.filters")}
|
||||
payload={JSON.stringify(
|
||||
i.filters.map((p) => {
|
||||
return `${p.name} ${p.condition} ${p.value}`;
|
||||
}),
|
||||
null,
|
||||
2
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "sort",
|
||||
title: t("models.view.sort"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
<ShowPayloadModalButton
|
||||
description={t("models.view.payload.sortCount", { count: i.sort.length })}
|
||||
title={t("models.view.sort")}
|
||||
payload={JSON.stringify(
|
||||
i.sort.map((p) => {
|
||||
return `${p.name} ${p.asc ? "asc" : "desc"}`;
|
||||
}),
|
||||
null,
|
||||
2
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "pageSize",
|
||||
title: t("models.view.pageSize"),
|
||||
value: (i) => <div>{formatters.number(i.pageSize)}</div>,
|
||||
},
|
||||
{
|
||||
name: "isDefault",
|
||||
title: t("models.view.isDefault"),
|
||||
value: (i) => <div>{i.isDefault ? <CheckIcon className="h-5 w-5 text-green-500" /> : <XIcon className="text-muted-foreground h-5 w-5" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "updatedAt",
|
||||
title: t("shared.updatedAt"),
|
||||
value: (i) => <DateCell date={i.updatedAt ?? null} />,
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (i) => <DateCell date={i.createdAt ?? null} />,
|
||||
},
|
||||
{
|
||||
name: "createdBy",
|
||||
title: t("shared.createdBy"),
|
||||
value: (i) => (i.createdByUser ? <UserBadge item={i.createdByUser} /> : <div>-</div>),
|
||||
},
|
||||
]}
|
||||
noRecords={
|
||||
<div className="p-12 text-center">
|
||||
<h3 className="text-foreground mt-1 text-sm font-medium">{t("models.view.empty.title")}</h3>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("models.view.empty.description")}</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const tablePath = path.resolve(process.cwd(), "apps/web/app/components/entities/views/EntityViewsTable.tsx");
|
||||
const formPath = path.resolve(process.cwd(), "apps/web/app/components/entities/views/EntityViewForm.tsx");
|
||||
const layoutTypePath = path.resolve(process.cwd(), "apps/web/app/modules/rows/dtos/EntityViewLayoutType.ts");
|
||||
|
||||
describe("entity view labels i18n", () => {
|
||||
it("uses semantic translation keys for view table and form labels", () => {
|
||||
const source = `${fs.readFileSync(tablePath, "utf8")}\n${fs.readFileSync(formPath, "utf8")}`;
|
||||
|
||||
expect(source).toContain("models.view.appliesToStates.systemView");
|
||||
expect(source).toContain("models.view.payload.propertiesCount");
|
||||
expect(source).toContain("models.view.empty.title");
|
||||
expect(source).toContain("models.view.propertiesDisplayed");
|
||||
expect(source).toContain("models.view.matchOperators.and");
|
||||
expect(source).toContain("models.view.systemTitle");
|
||||
expect(source).toContain("translateEntityTitlePlural(t, i18n, entity)");
|
||||
expect(source).toContain("translatePropertyTitle(t, i18n, entity.name, property)");
|
||||
expect(source).toContain("translateSelectOptionLabel(t, i18n, entity.name, item.name, i)");
|
||||
expect(source).toContain("shared.condition");
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
expect(source).not.toContain('"System - "');
|
||||
expect(source).not.toContain('"AND"');
|
||||
expect(source).not.toContain('"True"');
|
||||
expect(source).not.toContain("t(entity.titlePlural)");
|
||||
expect(source).not.toContain("t(property.title)");
|
||||
expect(source).not.toContain('" - " + t(i.name)');
|
||||
});
|
||||
|
||||
it("renders entity view layout options through semantic label keys", () => {
|
||||
const formSource = fs.readFileSync(formPath, "utf8");
|
||||
const layoutTypeSource = fs.readFileSync(layoutTypePath, "utf8");
|
||||
|
||||
expect(layoutTypeSource).toContain('labelKey: "models.view.layouts.table"');
|
||||
expect(layoutTypeSource).toContain('labelKey: "models.view.layouts.grid"');
|
||||
expect(layoutTypeSource).toContain('labelKey: "models.view.layouts.card"');
|
||||
expect(layoutTypeSource).toContain('labelKey: "models.view.layouts.board"');
|
||||
expect(layoutTypeSource).not.toContain('name: "Table"');
|
||||
expect(layoutTypeSource).not.toContain('name: "Grid"');
|
||||
expect(layoutTypeSource).not.toContain('name: "Card"');
|
||||
expect(layoutTypeSource).not.toContain('name: "Board"');
|
||||
expect(formSource).toContain("name: t(f.labelKey)");
|
||||
expect(formSource).toContain("<div>{t(f.labelKey)}</div>");
|
||||
expect(formSource).not.toContain("name: f.name");
|
||||
expect(formSource).not.toContain("{f.name}");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { EntityWebhook } from "@toolctrl/db/prisma-browser";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
|
||||
import FormGroup from "~/components/ui/forms/FormGroup";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
|
||||
interface Props {
|
||||
item?: EntityWebhook;
|
||||
}
|
||||
|
||||
export default function EntityWebhookForm({ item }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const [action, setAction] = useState<string>(item?.action ?? "Created");
|
||||
const [method, setMethod] = useState<string>(item?.method ?? "POST");
|
||||
const [endpoint, setEndpoint] = useState<string>(item?.endpoint ?? "");
|
||||
|
||||
return (
|
||||
<FormGroup id={item?.id} editing={true}>
|
||||
{/* <input type="hidden" name="order" value={order} hidden readOnly /> */}
|
||||
<InputSelect
|
||||
name="webhook-action"
|
||||
title={t("models.entityWebhook.action")}
|
||||
value={action}
|
||||
setValue={(e) => setAction(e?.toString() ?? "")}
|
||||
options={[
|
||||
{
|
||||
name: t("models.entityWebhook.actions.created"),
|
||||
value: DefaultLogActions.Created,
|
||||
},
|
||||
{
|
||||
name: t("models.entityWebhook.actions.updated"),
|
||||
value: DefaultLogActions.Updated,
|
||||
},
|
||||
{
|
||||
name: t("models.entityWebhook.actions.deleted"),
|
||||
value: DefaultLogActions.Deleted,
|
||||
},
|
||||
]}
|
||||
required
|
||||
/>
|
||||
<InputSelect
|
||||
name="webhook-method"
|
||||
title={t("models.entityWebhook.method")}
|
||||
value={method}
|
||||
setValue={(e) => setMethod(e?.toString() ?? "")}
|
||||
options={[
|
||||
{
|
||||
name: "POST",
|
||||
value: "POST",
|
||||
},
|
||||
{
|
||||
name: "GET",
|
||||
value: "GET",
|
||||
disabled: true,
|
||||
},
|
||||
]}
|
||||
required
|
||||
/>
|
||||
<InputText name="webhook-endpoint" title={t("models.entityWebhook.endpoint")} value={endpoint} setValue={setEndpoint} required />
|
||||
</FormGroup>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user