Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,40 +0,0 @@
import { vi, describe, it, expect } from "vitest";
import "@testing-library/jest-dom";
import { render } from "@testing-library/react";
import { BrowserRouter as Router } from "react-router";
import SetupSteps from "./SetupSteps";
vi.mock("react-i18next", () => ({
useTranslation: () => {
return { t: (str: string) => str };
},
}));
describe("SetupSteps component", () => {
const mockItems = [
{ title: "Step 1", description: "Description 1", path: "/step1", completed: true },
{ title: "Step 2", description: "Description 2", path: "/step2", completed: false },
{ title: "Step 3", description: "Description 3", path: "/step3", completed: false },
];
it("renders a list of setup steps with correct details", () => {
const { getAllByRole, getByText } = render(
<Router>
<SetupSteps items={mockItems} />
</Router>
);
const stepItems = getAllByRole("listitem");
expect(stepItems).toHaveLength(mockItems.length);
stepItems.forEach((stepItem, index) => {
const item = mockItems[index];
const title = getByText(item.title);
const description = getByText(item.description);
expect(title).toBeInTheDocument();
expect(description).toBeInTheDocument();
});
});
});
@@ -1,75 +0,0 @@
import { useTranslation } from "react-i18next";
import { SetupItem } from "~/application/dtos/setup/SetupItem";
import ButtonSecondary from "../ui/buttons/ButtonSecondary";
import clsx from "clsx";
import { CheckCircleIcon } from "~/components/ui/icons/vendor";
interface Props {
items: SetupItem[];
}
function CompletedIcon() {
return (
<CheckCircleIcon className="border-border h-6 w-6 rounded-full border text-gray-200" />
);
}
function IncompletedIcon() {
return (
<CheckCircleIcon className="h-6 w-6 rounded-full border border-teal-500 text-teal-500" />
);
}
function SetupStep({ item, index, total }: { item: SetupItem; index: number; total: number }) {
const { t } = useTranslation();
return (
<li key={index} className="border-border bg-background space-y-3 rounded-lg border p-4">
<div className="flex items-center space-x-2">
<div className="shrink-0">{!item.completed ? <CompletedIcon /> : <IncompletedIcon />}</div>
<div className="flex w-full justify-between">
<div className="font-medium">{item.title}</div>
<div className=" text-muted-foreground text-sm">
{index + 1}/{total}
</div>
</div>
</div>
<p className=" text-sm">{item.description}</p>
<div>
<ButtonSecondary to={item.path} className="mt-3">
{!item.completed ? t("app.sidebar.setup") : `${t("shared.goTo")} ${item.title.toLowerCase()}`} &rarr;
</ButtonSecondary>
</div>
</li>
);
}
export default function SetupSteps({ items }: Props) {
const { t } = useTranslation();
return (
<div>
<h3 className="text-foreground font-medium leading-4">{t("onboarding.gettingStarted.title")}</h3>
<ul
className={clsx(
"mt-3 grid grid-cols-1 gap-4",
items.length === 1 && "lg:grid-cols-3",
items.length === 2 && "lg:grid-cols-2",
items.length === 3 && "lg:grid-cols-3",
items.length === 4 && "lg:grid-cols-2",
items.length === 5 && "lg:grid-cols-3",
items.length === 6 && "lg:grid-cols-3",
items.length === 7 && "lg:grid-cols-4",
items.length === 8 && "lg:grid-cols-4",
items.length === 9 && "lg:grid-cols-3",
items.length === 10 && "lg:grid-cols-5",
items.length === 11 && "lg:grid-cols-4",
items.length === 12 && "lg:grid-cols-4"
)}
>
{items.map((item, index) => (
<SetupStep key={index} item={item} index={index} total={items.length} />
))}
</ul>
</div>
);
}
@@ -2,7 +2,7 @@ import React from "react";
import { render, screen } from "@testing-library/react";
import AnalyticsPageViewsTable from "./AnalyticsPageViewsTable";
import { BrowserRouter as Router } from "react-router";
import { AnalyticsPageView } from "@toolctrl/db/prisma-browser";
import { AnalyticsPageView } from "@hivegrid/db/prisma-browser";
import { vi, describe, expect, test } from "vitest";
vi.mock("react-i18next", () => ({
@@ -1,4 +1,4 @@
import { AnalyticsPageView } from "@toolctrl/db/prisma-browser";
import { AnalyticsPageView } from "@hivegrid/db/prisma-browser";
import { useTranslation } from "react-i18next";
import DateCell from "../ui/dates/DateCell";
import TableSimple from "../ui/tables/TableSimple";
@@ -118,8 +118,6 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
t,
i18n,
tenantId: params.tenant ?? "",
entities: appData?.entities ?? [],
entityGroups: appData?.entityGroups ?? [],
appConfiguration: rootData.appConfiguration,
routing: rootData.routing,
productAccess: appData?.productAccess,
@@ -138,7 +136,7 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
});
return groups.filter((g) => g.items.length > 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [layout, menuItems, location.pathname, params.tenant, appData?.productAccess, appData?.entities, appData?.entityGroups]);
}, [layout, menuItems, location.pathname, params.tenant, appData?.productAccess]);
const navMain = menu.filter((g) => g.type === "main");
const navSecondary = menu.filter((g) => g.type === "secondary");
@@ -241,15 +239,22 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
</div>
<div className="flex items-center gap-2 self-stretch pl-1" data-ui-id={UI_SURFACE_IDS.shellNavActions}>
<button
type="button"
className="hidden md:flex md:min-w-[192px] md:max-w-[320px] md:grow"
<div
role="button"
tabIndex={0}
className="hidden cursor-pointer md:flex md:min-w-[192px] md:max-w-[320px] md:grow"
onClick={() => commandPalette.toggle()}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
commandPalette.toggle();
}
}}
aria-label={t("shared.search")}
data-ui-id={UI_ACTION_IDS.search}
>
<SearchInput className="pointer-events-none h-auto w-full" size="small" placeholder={t("shared.searchPlaceholder")} />
</button>
<SearchInput className="pointer-events-none h-auto w-full min-w-0 max-w-none" size="small" fillContainer placeholder={t("shared.searchPlaceholder")} />
</div>
<a href={params.tenant ? UrlUtils.currentTenantUrl(params, "notifications") : "#"} aria-label={t("app.sidebar.notifications", { defaultValue: "Notifications" })} data-ui-id={UI_ACTION_IDS.notifications}>
<IconButton variant="ghost" size="small" icon={<FeatherBell />} />
</a>
@@ -1,6 +1,6 @@
import { useTranslation } from "react-i18next";
import { useMemo } from "react";
import type { Log } from "@toolctrl/db/prisma-browser";
import type { Log } from "@hivegrid/db/prisma-browser";
import { LogWithDetails } from "~/utils/db/logs.db.server";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import TableSimple from "~/components/ui/tables/TableSimple";
@@ -16,7 +16,6 @@ export type LogsTableItem = Log & {
user?: LogWithDetails["user"] | { id: string; email: string; firstName?: string | null; lastName?: string | null } | null;
apiKey?: LogWithDetails["apiKey"] | { id: string; alias: string } | null;
tenant?: LogWithDetails["tenant"] | { id: string; name: string; slug?: string | null } | null;
comment?: LogWithDetails["comment"] | { id: string; value: string } | null;
};
interface Props {
@@ -46,13 +46,15 @@ describe("log action i18n", () => {
["settings.groups.deleted", "models.log.actions.deleted"],
["settings.memberRoles.created", "models.log.actions.created"],
["settings.memberRoles.deleted", "models.log.actions.deleted"],
["settings.members.deactivated", "models.log.actions.memberDeactivated"],
["settings.members.reactivated", "models.log.actions.memberReactivated"],
["settings.groups.membersAdded", "models.log.actions.groupMembersAdded"],
["settings.groups.membersRemoved", "models.log.actions.groupMembersRemoved"],
["settings.rolesAndPermissions.userRoles.created", "models.log.actions.created"],
["settings.rolesAndPermissions.userRoles.deleted", "models.log.actions.deleted"],
["settings.tenant.updateDetails", "models.log.actions.updateTenantDetails"],
["Update tenant details", "models.log.actions.updateTenantDetails"],
["Updated", "models.log.actions.updated"],
["Updated AI overage configuration", "models.log.actions.updatedAiOverageConfiguration"],
["admin.pricing.aiOverage.updated", "models.log.actions.updatedAiOverageConfiguration"],
["Updated pricing plan", "models.log.actions.updatedPricingPlan"],
["portal.pricing.plan.updated", "models.log.actions.updatedPricingPlan"],
["Workspace Role Created", "models.log.actions.workspaceRoleCreated"],
@@ -38,13 +38,15 @@ export const LOG_ACTION_I18N_KEYS = {
"settings.groups.deleted": "models.log.actions.deleted",
"settings.memberRoles.created": "models.log.actions.created",
"settings.memberRoles.deleted": "models.log.actions.deleted",
"settings.members.deactivated": "models.log.actions.memberDeactivated",
"settings.members.reactivated": "models.log.actions.memberReactivated",
"settings.groups.membersAdded": "models.log.actions.groupMembersAdded",
"settings.groups.membersRemoved": "models.log.actions.groupMembersRemoved",
"settings.rolesAndPermissions.userRoles.created": "models.log.actions.created",
"settings.rolesAndPermissions.userRoles.deleted": "models.log.actions.deleted",
"settings.tenant.updateDetails": "models.log.actions.updateTenantDetails",
"Update tenant details": "models.log.actions.updateTenantDetails",
"Updated": "models.log.actions.updated",
"Updated AI overage configuration": "models.log.actions.updatedAiOverageConfiguration",
"admin.pricing.aiOverage.updated": "models.log.actions.updatedAiOverageConfiguration",
"Updated pricing plan": "models.log.actions.updatedPricingPlan",
"portal.pricing.plan.updated": "models.log.actions.updatedPricingPlan",
"Workspace Role Created": "models.log.actions.workspaceRoleCreated",
@@ -1,49 +1,58 @@
import type { ReactNode } from "react";
import { twClassNames } from "~/ui/utils";
import { Card } from "~/ui/components/Card";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { Logo } from "~/ui/components/Logo";
type StatusTone = "positive" | "negative" | "neutral";
type CardSize = "small" | "medium" | "large" | "extra-large";
type SubtitleVariant = "regular-0" | "regular-150" | "medium-150";
const STATUS_BADGE: Record<StatusTone, string> = {
positive: "bg-surface-feedback-subtle-positive",
negative: "bg-surface-feedback-subtle-negative",
neutral: "bg-surface-feedback-subtle-neutral",
};
const STATUS_ICON: Record<StatusTone, string> = {
positive: "text-icon-feedback-positive",
negative: "text-icon-feedback-negative",
neutral: "text-icon-neutral-primary",
const SUBTITLE_CLS: Record<SubtitleVariant, string> = {
"regular-0": "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary",
"regular-150": "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary",
"medium-150": "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary",
};
// Gemeinsames Auth-Layout nach Davids Subframe-Auth-Screens (Login/Signup/Reset/2FA/Magic-Link):
// zentriertes Logo (64) + Card (Titel/Untertitel + Inhalt) + optionaler Footer. min-h-screen statt Davids
// h-full (Auth-Routen ohne full-height-Parent). Titel-Ausrichtung + Untertitel-Gewicht variieren je Screen
// in Davids Designs -> als Props (titleAlign/subtitleStrong). twClassNames, damit cardClassName Basis-Tokens
// (gap/shadow) sauber ueberschreibt.
// Gemeinsames Auth-Layout nach Davids WF-P2-Subframe-Auth-Screens (Login/Signup/Reset/2FA/Magic-Link):
// optionales Logo (64) + Davids ECHTE Card-Komponente (~/ui) + optionaler Footer. min-h-screen statt Davids
// h-full (Auth-Routen ohne full-height-Parent). Card-Groesse/Logo-Sichtbarkeit/Header-Abstand/Untertitel-Stil
// variieren je Screen in Davids Designs -> als Props (cardSize/showLogo/headerGap/subtitleVariant/titleAlign).
// Card statt Inline-Nachbau beseitigt Token-Drift (rounded-md/px-6/items-start kommen jetzt aus der Card).
// `items-stretch`-Override haelt Form-Kinder auf voller Breite (Davids Card-Root ist items-start).
export function AuthShell({
title,
subtitle,
children,
footer,
cardClassName = "max-w-[400px]",
cardSize = "large",
cardClassName = "max-w-[448px]",
showLogo = true,
logoIconOnly = false,
titleAlign = "start",
subtitleStrong = false,
titleAlign = "center",
headerGap = "gap-1.5",
subtitleVariant = "regular-150",
dataUiId,
}: {
title: ReactNode;
subtitle?: ReactNode;
children: ReactNode;
footer?: ReactNode;
/** Davids Card-Groesse. S01 Login/V01/V02 = large, S04 2FA = extra-large. */
cardSize?: CardSize;
/** Breite/Overrides der Card; Forms = max-w-[400px] (Default). */
cardClassName?: string;
/** Icon-only-Logo (wie Davids 2FA-/Status-Screens) statt vollem Wortmarken-Logo. */
/** Logo ueber der Card zeigen. Davids S01 Login/V01/V02 = ohne Logo. */
showLogo?: boolean;
/** Icon-only-Logo (wie Davids Auth-Screens, Logo size=64 hideText) statt vollem Wortmarken-Logo. */
logoIconOnly?: boolean;
/** Titel-/Untertitel-Ausrichtung. David: Login=center, Signup/Forgot/Reset/2FA=start. */
titleAlign?: "center" | "start";
/** Untertitel-Gewicht. David: Forgot/2FA = medium-150, sonst regular-0. */
subtitleStrong?: boolean;
/** Abstand Titel<->Untertitel. David: S01 Login = gap-1.5, sonst gap-1. */
headerGap?: string;
/** Untertitel-Stil. David: S01 Login = regular-150, 2FA/Forgot = medium-150, sonst regular-0. */
subtitleVariant?: SubtitleVariant;
dataUiId?: string;
}) {
return (
@@ -51,29 +60,16 @@ export function AuthShell({
className="flex min-h-screen w-full flex-col items-center justify-center gap-8 bg-surface-neutral-primary px-4 py-12 mobile:gap-6 mobile:py-6"
data-ui-id={dataUiId}
>
<Logo size="64" showIcon={logoIconOnly || undefined} hideText={logoIconOnly || undefined} />
<div
className={twClassNames(
"flex w-full flex-col items-stretch gap-4 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-8 py-8 shadow-sm mobile:px-6",
cardClassName
)}
>
<div className={twClassNames("flex w-full flex-col gap-1", titleAlign === "center" ? "items-center" : "items-start")}>
{showLogo ? <Logo size="64" showIcon={logoIconOnly || undefined} hideText={logoIconOnly || undefined} /> : null}
<Card size={cardSize} variant="default" className={twClassNames("items-stretch", cardClassName)}>
<div className={twClassNames("flex w-full flex-col", headerGap, titleAlign === "center" ? "items-center" : "items-start")}>
<h1 className="text-heading- font-heading- text-text-neutral-primary">{title}</h1>
{subtitle ? (
<p
className={
subtitleStrong
? "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary"
}
>
{subtitle}
</p>
<p className={twClassNames(SUBTITLE_CLS[subtitleVariant], titleAlign === "center" ? "text-center" : "")}>{subtitle}</p>
) : null}
</div>
{children}
</div>
</Card>
{footer ? <div className="flex w-full flex-wrap items-center justify-center gap-2">{footer}</div> : null}
</div>
);
@@ -105,29 +101,44 @@ export function AuthStatus({
data-ui-id={dataUiId}
>
<Logo size="64" />
<div className="flex w-full max-w-[400px] flex-col items-center gap-6 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-8 py-8 text-center shadow-sm mobile:px-6">
<div className={`flex h-12 w-12 flex-none items-center justify-center rounded-round ${STATUS_BADGE[tone]}`}>
<span className={`text-heading- font-heading- ${STATUS_ICON[tone]}`}>{icon}</span>
<Card size="large" variant="default" className="max-w-[448px] items-center text-center">
<div className="flex w-full flex-col items-center gap-4">
<IconWithBackground
variant={tone === "positive" ? "success" : tone === "negative" ? "destructive" : "neutral"}
size="extra-large"
round={true}
icon={icon}
/>
<div className="flex w-full flex-col items-center gap-2">
<h1 className="text-center text-heading- font-heading- text-text-neutral-primary">{title}</h1>
<p className="text-center text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary">{message}</p>
{hint ? (
<p className="text-center text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{hint}</p>
) : null}
</div>
</div>
<div className="flex w-full flex-col items-center gap-2">
<h1 className="text-center text-heading- font-heading- text-text-neutral-primary">{title}</h1>
<p className="text-center text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary">{message}</p>
{hint ? (
<p className="text-center text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{hint}</p>
) : null}
</div>
{children ? <div className="flex w-full flex-col items-center gap-3">{children}</div> : null}
</div>
{children ? <div className="flex w-full flex-col items-center gap-3 py-1">{children}</div> : null}
</Card>
</div>
);
}
// Davids "oder"-Trenner zwischen Primär- und Sekundär-Aktion (z.B. Login vs. Magic-Link).
export function AuthDivider({ label }: { label: ReactNode }) {
export function AuthDivider({ label, labelSize = "small" }: { label: ReactNode; labelSize?: "small" | "extra-small" }) {
return (
<div className="flex w-full items-center justify-center gap-3">
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{label}</span>
<span
className={twClassNames(
"text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary",
{
"text-body-extra-small-regular-150 font-body-extra-small-regular-150":
labelSize === "extra-small",
}
)}
>
{label}
</span>
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
</div>
);
@@ -1,11 +1,13 @@
import { useEffect, useRef } from "react";
import { createElement, useEffect, useRef } from "react";
interface Props {
/** Render the mCaptcha widget. When false (or unconfigured) nothing is rendered. */
/** Render the captcha widget. When false (or unconfigured) nothing is rendered. */
enabled: boolean;
/** Public base URL of the self-hosted mCaptcha instance (web config / MCAPTCHA_INSTANCE_URL). */
/** Active self-hosted provider. Defaults to mCaptcha for compatibility. */
provider?: "mcaptcha" | "cap";
/** Public base URL of the self-hosted captcha instance. */
instanceUrl?: string;
/** Public sitekey for this surface (e.g. MCAPTCHA_SITEKEY_LOGIN). */
/** Public sitekey for this surface. */
sitekey?: string;
}
@@ -15,18 +17,17 @@ interface Props {
const MOUNT_ID = "mcaptcha__widget-container";
/**
* mCaptcha (proof-of-work) widget — replaces the former no-op RecaptchaWrapper.
* Self-hosted captcha widget — replaces the former no-op RecaptchaWrapper.
*
* Render this **inside** the <form> it should protect: the glue injects the
* hidden `mcaptcha__token` field next to this mount, so it is submitted with
* the form and verified server-side by `@toolctrl/captcha` (see AuthService /
* api.leads.capture / infra/mcaptcha/README.md + AD-7).
* Render this **inside** the <form> it should protect: the provider injects a
* hidden token field (`cap-token` or `mcaptcha__token`), so it is submitted
* with the form and verified server-side by `@hivegrid/captcha`.
*
* Client load failures are non-fatal — the server verifier fails open
* (CAPTCHA_FAIL_OPEN, default true) when no token is present. The glue is
* imported dynamically so it never runs during SSR.
* Client load failures are non-fatal. The server verifier applies
* CAPTCHA_FAIL_OPEN for provider outages, while a missing token remains a hard
* failure when captcha is required.
*/
export default function Captcha({ enabled, instanceUrl, sitekey }: Props) {
export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, sitekey }: Props) {
const active = enabled && Boolean(instanceUrl && sitekey);
const initialized = useRef(false);
@@ -36,6 +37,10 @@ export default function Captcha({ enabled, instanceUrl, sitekey }: Props) {
let cancelled = false;
void (async () => {
try {
if (provider === "cap") {
loadCapAssets(instanceUrl!);
return;
}
const { default: Widget } = await import("@mcaptcha/vanilla-glue");
if (cancelled) return;
// Widget self-mounts into #MOUNT_ID and injects the hidden mcaptcha__token field.
@@ -47,8 +52,47 @@ export default function Captcha({ enabled, instanceUrl, sitekey }: Props) {
return () => {
cancelled = true;
};
}, [active, instanceUrl, sitekey]);
}, [active, instanceUrl, provider, sitekey]);
if (!active) return null;
if (provider === "cap") {
return (
<>
{/*
Cap's custom element injects <input name="cap-token"> into the
enclosing form when solved.
*/}
{createCapWidget(instanceUrl!, sitekey!)}
</>
);
}
return <div id={MOUNT_ID} className="m-captcha" data-ui-id="ui.captcha.mount" />;
}
function createCapWidget(instanceUrl: string, sitekey: string) {
return createElement("cap-widget", {
required: true,
"data-cap-api-endpoint": `${instanceUrl.replace(/\/+$/, "")}/${sitekey}/`,
"data-ui-id": "ui.captcha.mount",
});
}
function loadCapAssets(instanceUrl: string): void {
const base = instanceUrl.replace(/\/+$/, "");
const scriptSrc = `${base}/assets/widget.js`;
window.CAP_CUSTOM_WASM_URL = `${base}/assets/cap_wasm_bg.wasm`;
if (document.querySelector(`script[data-cap-widget-loader="true"][src="${scriptSrc}"]`)) return;
const script = document.createElement("script");
script.type = "module";
script.async = true;
script.defer = true;
script.src = scriptSrc;
script.dataset.capWidgetLoader = "true";
document.head.appendChild(script);
}
declare global {
interface Window {
CAP_CUSTOM_WASM_URL?: string;
}
}
@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import SkipToContent from "./SkipToContent";
import { expectNoAxeViolations } from "@toolctrl/ui-app/test-setup/axe";
import { expectNoAxeViolations } from "@hivegrid/ui-app/test-setup/axe";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
@@ -1,114 +0,0 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import ApiKeyForm from "./ApiKeyForm";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (value: string) => value }),
}));
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
useSubmit: () => vi.fn(),
};
});
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({ csrf: "csrf-test-token" }),
}));
vi.mock("~/components/ui/forms/FormGroup", () => ({
default: ({ children }: { children: React.ReactNode }) => <form>{children}</form>,
}));
vi.mock("~/components/ui/input/InputText", () => ({
default: ({ title, name, value, setValue, disabled }: { title: string; name: string; value: string; setValue: (value: string) => void; disabled?: boolean }) => (
<label>
{title}
<input name={name} value={value} onChange={(event) => setValue(event.currentTarget.value)} disabled={disabled} />
</label>
),
}));
vi.mock("~/components/ui/input/InputDate", () => ({
default: ({ title, name, value, onChange, disabled }: { title: string; name: string; value?: Date; onChange: (value: Date) => void; disabled?: boolean }) => (
<label>
{title}
<input
type="date"
name={name}
value={value?.toISOString().split("T")[0] ?? ""}
onChange={(event) => onChange(new Date(event.currentTarget.value))}
disabled={disabled}
/>
</label>
),
}));
vi.mock("~/components/ui/input/InputCheckboxInline", () => ({
default: ({ name, title, value, setValue, disabled }: { name: string; title: React.ReactNode; value?: boolean; setValue?: (value: boolean) => void; disabled?: boolean }) => (
<label>
<input type="checkbox" name={name} checked={value} onChange={(event) => setValue?.(event.currentTarget.checked)} disabled={disabled} />
{title}
</label>
),
}));
vi.mock("~/components/ui/tooltips/HintTooltip", () => ({
default: ({ text }: { text: string }) => <span>{text}</span>,
}));
const entity = {
id: "entity_contacts",
order: 1,
name: "contact",
title: "Contacts",
titlePlural: "Contacts",
active: true,
slug: "contacts",
type: DefaultEntityTypes.AppOnly,
hasApi: true,
showInSidebar: true,
icon: "users",
onEdit: null,
};
describe("ApiKeyForm scope editor", () => {
it("uses accessible CRUD labels and keeps entities[] payloads in sync", () => {
render(<ApiKeyForm entities={[entity]} />);
const createCheckbox = screen.getByRole("checkbox", { name: /models\.apiKey\.create Contacts/i });
const readCheckbox = screen.getByRole("checkbox", { name: /models\.apiKey\.read Contacts/i });
const updateCheckbox = screen.getByRole("checkbox", { name: /models\.apiKey\.update Contacts/i });
const deleteCheckbox = screen.getByRole("checkbox", { name: /models\.apiKey\.delete Contacts/i });
expect(createCheckbox).toBeChecked();
expect(readCheckbox).toBeChecked();
expect(updateCheckbox).toBeChecked();
expect(deleteCheckbox).toBeChecked();
fireEvent.click(deleteCheckbox);
const hiddenPayload = document.querySelector<HTMLInputElement>('input[type="hidden"][name="entities[]"]');
expect(hiddenPayload).toBeInTheDocument();
expect(JSON.parse(hiddenPayload?.value ?? "{}")).toEqual({
entityId: "entity_contacts",
create: true,
read: true,
update: true,
delete: false,
});
});
it("disables scope checkboxes when updates are not allowed", () => {
render(<ApiKeyForm entities={[entity]} canUpdate={false} />);
expect(screen.getByRole("checkbox", { name: /models\.apiKey\.create Contacts/i })).toBeDisabled();
expect(screen.getByRole("checkbox", { name: /models\.apiKey\.read Contacts/i })).toBeDisabled();
expect(screen.getByRole("checkbox", { name: /models\.apiKey\.update Contacts/i })).toBeDisabled();
expect(screen.getByRole("checkbox", { name: /models\.apiKey\.delete Contacts/i })).toBeDisabled();
});
});
@@ -1,8 +1,7 @@
import type { Tenant } from "@toolctrl/db/prisma-browser";
import type { Tenant } from "@hivegrid/db/prisma-browser";
import { useRef, useState, useEffect } from "react";
import { useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import FormGroup from "~/components/ui/forms/FormGroup";
import InputCheckboxInline from "~/components/ui/input/InputCheckboxInline";
@@ -11,18 +10,15 @@ import InputSelect from "~/components/ui/input/InputSelect";
import InputText, { RefInputText } from "~/components/ui/input/InputText";
import { useRootData } from "~/utils/data/useRootData";
import type { RedactedApiKeyWithDetails } from "~/utils/db/apiKeys.db.server";
import type { EntitySimple } from "~/utils/db/entities/entities.db.server";
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
interface Props {
entities: EntitySimple[];
item?: RedactedApiKeyWithDetails | null;
tenants?: Tenant[];
canUpdate?: boolean;
canDelete?: boolean;
canRotate?: boolean;
}
export default function ApiKeyForm({ entities, item, tenants, canUpdate = true, canDelete, canRotate = false }: Props) {
export default function ApiKeyForm({ item, tenants, canUpdate = true, canDelete, canRotate = false }: Props) {
const { t } = useTranslation();
const submit = useSubmit();
const rootData = useRootData();
@@ -33,25 +29,6 @@ export default function ApiKeyForm({ entities, item, tenants, canUpdate = true,
const [alias, setAlias] = useState(item?.alias ?? "");
const [expires, setExpires] = useState<Date | undefined>(item?.expires ?? undefined);
const [active, setActive] = useState(item?.active ?? true);
const [permissions, setPermissions] = useState<{ entityId: string; create: boolean; read: boolean; update: boolean; delete: boolean }[]>([]);
useEffect(() => {
const permissions: { entityId: string; create: boolean; read: boolean; update: boolean; delete: boolean }[] = [];
entities
.filter((f) => (f.type === DefaultEntityTypes.AppOnly || f.type === DefaultEntityTypes.All) && f.hasApi)
.forEach((entity) => {
const existing = item?.entities.find((f) => f.entityId === entity.id);
permissions.push({
entityId: entity.id,
create: existing?.create ?? true,
read: existing?.read ?? true,
update: existing?.update ?? true,
delete: existing?.delete ?? true,
});
});
setPermissions(permissions);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
setTimeout(() => {
@@ -82,7 +59,7 @@ export default function ApiKeyForm({ entities, item, tenants, canUpdate = true,
{tenants && (
<>
<InputSelect
className="col-span-6"
className="col-span-12"
name="tenant-id"
title={t("models.tenant.object")}
value={tenantId}
@@ -114,6 +91,7 @@ export default function ApiKeyForm({ entities, item, tenants, canUpdate = true,
<InputDate
disabled={!canUpdate}
className="col-span-6"
classNameInput="h-[34px] !text-[16px] !leading-[22px] font-body-default-regular-0 md:!text-[16px]"
name="expires"
title={t("models.apiKey.expires")}
value={expires}
@@ -129,121 +107,6 @@ export default function ApiKeyForm({ entities, item, tenants, canUpdate = true,
}
/>
<div className="col-span-12 flex flex-col">
<div className="overflow-x-auto">
<div className="inline-block min-w-full py-2 align-middle">
<div className="border-border overflow-hidden border shadow-xs sm:rounded-lg">
<table className="divide-border min-w-full divide-y">
<thead className="bg-secondary">
<tr>
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
<div className="text-muted-foreground flex items-center space-x-1">
<div>{t("models.entity.object")}</div>
</div>
</th>
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
{t("models.apiKey.create")}
</th>
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
{t("models.apiKey.read")}
</th>
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
{t("models.apiKey.update")}
</th>
<th scope="col" className="text-muted-foreground select-none truncate px-3 py-2 text-left text-xs font-medium tracking-wider">
{t("models.apiKey.delete")}
</th>
</tr>
</thead>
<tbody className="divide-border bg-background divide-y">
{entities
.filter((f) => (f.type === DefaultEntityTypes.AppOnly || f.type === DefaultEntityTypes.All) && f.hasApi)
.map((item, idx) => {
const entityLabel = t(item.title);
const entityDescription = `/${item.slug}`;
return (
<tr key={idx}>
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
<input
type="hidden"
name="entities[]"
value={JSON.stringify({
entityId: item.id,
create: permissions.find((f) => f.entityId === item.id)?.create ?? false,
read: permissions.find((f) => f.entityId === item.id)?.read ?? false,
update: permissions.find((f) => f.entityId === item.id)?.update ?? false,
delete: permissions.find((f) => f.entityId === item.id)?.delete ?? false,
})}
/>
<div className="font-medium text-foreground">{entityLabel}</div>
<div className="text-xs">{entityDescription}</div>
</td>
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
<InputCheckboxInline
disabled={!canUpdate}
name={`${item.id}-create`}
title={`${t("models.apiKey.create")} ${entityLabel}`}
help={`${t("models.apiKey.create")} ${entityDescription}`}
value={permissions.find((f) => f.entityId === item.id)?.create ?? false}
setValue={(e) =>
updateItemByIdx(permissions, setPermissions, idx, {
create: e,
})
}
/>
</td>
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
<InputCheckboxInline
disabled={!canUpdate}
name={`${item.id}-read`}
title={`${t("models.apiKey.read")} ${entityLabel}`}
help={`${t("models.apiKey.read")} ${entityDescription}`}
value={permissions.find((f) => f.entityId === item.id)?.read ?? false}
setValue={(e) =>
updateItemByIdx(permissions, setPermissions, idx, {
read: e,
})
}
/>
</td>
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
<InputCheckboxInline
disabled={!canUpdate}
name={`${item.id}-update`}
title={`${t("models.apiKey.update")} ${entityLabel}`}
help={`${t("models.apiKey.update")} ${entityDescription}`}
value={permissions.find((f) => f.entityId === item.id)?.update ?? false}
setValue={(e) =>
updateItemByIdx(permissions, setPermissions, idx, {
update: e,
})
}
/>
</td>
<td className="text-muted-foreground whitespace-nowrap px-3 py-2 text-sm">
<InputCheckboxInline
disabled={!canUpdate}
name={`${item.id}-delete`}
title={`${t("models.apiKey.delete")} ${entityLabel}`}
help={`${t("models.apiKey.delete")} ${entityDescription}`}
value={permissions.find((f) => f.entityId === item.id)?.delete ?? false}
setValue={(e) =>
updateItemByIdx(permissions, setPermissions, idx, {
delete: e,
})
}
/>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
</div>
<InputCheckboxInline
disabled={!canUpdate}
className="col-span-12"
@@ -3,7 +3,6 @@ import { render, screen } from "@testing-library/react";
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import ApiKeysTable from "./ApiKeysTable";
vi.mock("react-i18next", () => ({
@@ -28,21 +27,6 @@ vi.mock("~/components/ui/buttons/ButtonTertiary", () => ({
}));
const now = new Date("2026-01-01T00:00:00.000Z");
const entity = {
id: "entity_contacts",
order: 1,
name: "contact",
title: "Contacts",
titlePlural: "Contacts",
active: true,
slug: "contacts",
type: DefaultEntityTypes.AppOnly,
hasApi: true,
showInSidebar: true,
icon: "users",
onEdit: null,
};
const apiKey = {
id: "api_key_1",
keyPrefix: "tc_live",
@@ -66,24 +50,12 @@ const apiKey = {
locale: "en",
createdAt: now,
},
entities: [
{
id: "permission_1",
apiKeyId: "api_key_1",
entityId: "entity_contacts",
create: true,
read: true,
update: false,
delete: false,
entity: { id: "entity_contacts", title: "Contacts", titlePlural: "Contacts", slug: "contacts" },
},
],
_count: { apiKeyLogs: 2 },
};
describe("ApiKeysTable redacted key display", () => {
it("renders redacted metadata without raw key text or copy controls", () => {
const { container } = render(<ApiKeysTable entities={[entity]} items={[apiKey]} />);
const { container } = render(<ApiKeysTable items={[apiKey]} />);
expect(screen.getByText("tc_live…••••9xyz")).toBeInTheDocument();
expect(screen.queryByText("tc_live_raw_secret_that_must_not_render")).not.toBeInTheDocument();
@@ -92,7 +64,7 @@ describe("ApiKeysTable redacted key display", () => {
});
it("keeps inactive state visible alongside redacted metadata", () => {
render(<ApiKeysTable entities={[entity]} items={[{ ...apiKey, active: false }]} />);
render(<ApiKeysTable items={[{ ...apiKey, active: false }]} />);
expect(screen.getByText("tc_live…••••9xyz")).toBeInTheDocument();
expect(screen.getByText("shared.inactive")).toBeInTheDocument();
@@ -103,7 +75,7 @@ describe("ApiKeysTable redacted key display", () => {
const newerApiKey = { ...apiKey, id: "api_key_newer", alias: "Newer integration", createdAt: new Date("2026-01-01T00:00:00.000Z") };
const sourceItems = [olderApiKey, newerApiKey];
render(<ApiKeysTable entities={[entity]} items={sourceItems} />);
render(<ApiKeysTable items={sourceItems} />);
expect(screen.getByText("Newer integration")).toBeInTheDocument();
expect(sourceItems.map((item) => item.id)).toEqual(["api_key_older", "api_key_newer"]);
@@ -113,7 +85,6 @@ describe("ApiKeysTable redacted key display", () => {
const source = readFileSync(path.resolve(process.cwd(), "apps/web/app/components/core/apiKeys/ApiKeysTable.tsx"), "utf8");
expect(source).toContain("const filteredSortedRows = useMemo<ApiKeyTableRow[]>(");
expect(source).toContain("apiKeyEntityById: new Map(item.entities.map");
expect(source).toContain("redactedKey: getRedactedKey(item)");
});
});
@@ -1,16 +1,12 @@
import clsx from "clsx";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
import EmptyState from "~/components/ui/emptyState/EmptyState";
import InputSearch from "~/components/ui/input/InputSearch";
import { useLocaleFormatters } from "~/locale/format";
import type { RedactedApiKeyWithDetails } from "~/utils/db/apiKeys.db.server";
import type { EntitySimple } from "~/utils/db/entities/entities.db.server";
interface Props {
entities: EntitySimple[];
items: RedactedApiKeyWithDetails[];
withTenant?: boolean;
canCreate?: boolean;
@@ -21,7 +17,6 @@ type Header = {
};
type ApiKeyTableRow = {
apiKeyEntityById: Map<string, RedactedApiKeyWithDetails["entities"][number]>;
item: RedactedApiKeyWithDetails;
redactedKey: string;
};
@@ -30,17 +25,12 @@ function getRedactedKey(item: RedactedApiKeyWithDetails) {
return [item.keyPrefix, item.keyLastFour ? `••••${item.keyLastFour}` : undefined].filter(Boolean).join("…") || "••••";
}
export default function ApiKeysTable({ entities, items, withTenant, canCreate }: Props) {
export default function ApiKeysTable({ items, withTenant, canCreate }: Props) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [searchInput, setSearchInput] = useState("");
const apiEntities = useMemo(
() => entities.filter((f) => (f.type === DefaultEntityTypes.AppOnly || f.type === DefaultEntityTypes.All) && f.hasApi),
[entities]
);
const headers = useMemo(() => {
const nextHeaders: Header[] = [];
if (withTenant) {
@@ -49,14 +39,11 @@ export default function ApiKeysTable({ entities, items, withTenant, canCreate }:
nextHeaders.push({ name: "key", title: t("models.apiKey.key") });
nextHeaders.push({ name: "alias", title: t("models.apiKey.alias") });
nextHeaders.push({ name: "usage", title: t("models.apiKey.usage") });
apiEntities.forEach((entity) => {
nextHeaders.push({ name: "entityId", title: t(entity.titlePlural) });
});
nextHeaders.push({ name: "expires", title: t("models.apiKey.expires") });
nextHeaders.push({ name: "createdAt", title: t("shared.createdAt") });
nextHeaders.push({ name: "createdByUser", title: t("shared.createdBy") });
return nextHeaders;
}, [apiEntities, t, withTenant]);
}, [t, withTenant]);
const filteredSortedRows = useMemo<ApiKeyTableRow[]>(() => {
if (!items) {
@@ -73,7 +60,6 @@ export default function ApiKeysTable({ entities, items, withTenant, canCreate }:
return -1;
})
.map((item) => ({
apiKeyEntityById: new Map(item.entities.map((apiKeyEntity) => [apiKeyEntity.entityId, apiKeyEntity])),
item,
redactedKey: getRedactedKey(item),
}));
@@ -136,7 +122,7 @@ export default function ApiKeysTable({ entities, items, withTenant, canCreate }:
</tr>
</thead>
<tbody className="divide-border bg-background divide-y">
{filteredSortedRows.map(({ apiKeyEntityById, item, redactedKey }, idx) => {
{filteredSortedRows.map(({ item, redactedKey }, idx) => {
return (
<tr key={idx}>
{withTenant && (
@@ -155,19 +141,6 @@ export default function ApiKeysTable({ entities, items, withTenant, canCreate }:
{formatters.number(item._count.apiKeyLogs)}{" "}
{item._count.apiKeyLogs === 1 ? t("models.apiCall.object") : t("models.apiCall.plural")}
</td>
{apiEntities.map((entity) => {
const apiKeyEntity = apiKeyEntityById.get(entity.id);
return (
<td key={entity.id} className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<div className="flex items-center">
<span className={clsx(apiKeyEntity?.create ? "text-foreground font-bold" : "text-red-400")}>C</span>
<span className={clsx(apiKeyEntity?.read ? "text-foreground font-bold" : "text-red-400")}>R</span>
<span className={clsx(apiKeyEntity?.update ? "text-foreground font-bold" : "text-red-400")}>U</span>
<span className={clsx(apiKeyEntity?.delete ? "text-foreground font-bold" : "text-red-400")}>D</span>
</div>
</td>
);
})}
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<time
dateTime={item.expires ? new Date(item.expires).toISOString() : undefined}
@@ -1,4 +1,3 @@
import { Entity } from "@toolctrl/db/prisma-browser";
import { useTranslation } from "react-i18next";
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
@@ -13,9 +12,8 @@ import { CheckCircleIcon, XCircleIcon, PlusIcon } from "~/components/ui/icons/ve
interface Props {
items: SubscriptionFeatureDto[];
setItems: React.Dispatch<React.SetStateAction<SubscriptionFeatureDto[]>>;
entities: Entity[];
}
export default function PricingFeaturesForm({ items, setItems, entities }: Props) {
export default function PricingFeaturesForm({ items, setItems }: Props) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
function addFeature() {
@@ -30,6 +30,7 @@ import { Button } from "~/components/ui/button";
import { TrashIcon } from "~/components/ui/icons/vendor";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { useLocaleFormatters } from "~/locale/format";
import { HIVEGRID_SUBSCRIPTION_PRICING_MODELS } from "~/application/pricing/pricingModelPolicy";
interface Props {
plans?: SubscriptionProductDto[];
@@ -48,31 +49,13 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
const navigate = useNavigate();
const submit = useSubmit();
let pricingModels = [
{
name: t("pricing." + PricingModel[PricingModel.FLAT_RATE]),
value: PricingModel.FLAT_RATE,
},
{
name: t("pricing." + PricingModel[PricingModel.PER_SEAT]),
value: PricingModel.PER_SEAT,
},
{
name: t("pricing." + PricingModel[PricingModel.USAGE_BASED]),
value: PricingModel.USAGE_BASED,
},
{
name: t("pricing." + PricingModel[PricingModel.FLAT_RATE_USAGE_BASED]),
value: PricingModel.FLAT_RATE_USAGE_BASED,
},
{
name: t("pricing." + PricingModel[PricingModel.ONCE]),
value: PricingModel.ONCE,
},
];
let pricingModels = HIVEGRID_SUBSCRIPTION_PRICING_MODELS.map((value) => ({
name: t("pricing." + PricingModel[value]),
value,
}));
if (isPortalPlan) {
pricingModels = pricingModels.filter(
(f) => f.value !== PricingModel.USAGE_BASED && f.value !== PricingModel.FLAT_RATE_USAGE_BASED && f.value !== PricingModel.PER_SEAT
(f) => f.value !== PricingModel.USAGE_BASED && f.value !== PricingModel.FLAT_RATE_USAGE_BASED
);
}
const inputTitle = useRef<RefInputText>(null);
@@ -393,7 +376,7 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
</div>
</div>
{[PricingModel.FLAT_RATE, PricingModel.PER_SEAT, PricingModel.FLAT_RATE_USAGE_BASED, PricingModel.ONCE].includes(model) && (
{[PricingModel.FLAT_RATE, PricingModel.FLAT_RATE_USAGE_BASED, PricingModel.ONCE].includes(model) && (
<SettingSection title={t("pricing.planForm.sections.flatPrices.title")} description={t("pricing.planForm.sections.flatPrices.description")} className="">
<FlatPrices model={model} prices={prices} setPrices={setPrices} disabled={item !== undefined} isPortalPlan={isPortalPlan} />
</SettingSection>
@@ -448,7 +431,7 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
model={model}
prices={prices}
usageBasedPrices={usageBasedPrices}
stripeCoupon={null}
billingProviderCoupon={null}
isPreview={true}
/>
</div>
@@ -97,7 +97,7 @@ export default function UsageBasedPrices({ initial, onUpdate, disabled }: Props)
usageBasedPrices.push({
id: "",
subscriptionProductId: "",
stripeId: "",
billingProviderId: "",
billingPeriod: SubscriptionBillingPeriod.MONTHLY,
currency: price.currency,
unit: unit.unit,
@@ -1,4 +1,4 @@
import type { Group } from "@toolctrl/db/prisma-browser";
import type { Group } from "@hivegrid/db/prisma-browser";
import ColorBadge from "~/components/ui/badges/ColorBadge";
interface Props {
@@ -1,4 +1,4 @@
import type { Permission, Role } from "@toolctrl/db/prisma-browser";
import type { Permission, Role } from "@hivegrid/db/prisma-browser";
import { useTranslation } from "react-i18next";
import { Colors } from "~/application/enums/shared/Colors";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
@@ -1,4 +1,4 @@
import type { Permission } from "@toolctrl/db/prisma-browser";
import type { Permission } from "@hivegrid/db/prisma-browser";
import clsx from "clsx";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -1,4 +1,4 @@
import type { Permission, Role } from "@toolctrl/db/prisma-browser";
import type { Permission, Role } from "@hivegrid/db/prisma-browser";
import { i18nNamespaces } from "~/locale/i18n";
@@ -72,6 +72,42 @@ const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
users: "users",
impersonate: "impersonate",
changePassword: "changePassword",
// P4 Files (AK-P4a) + Tasks (AK-P4b) bundle actions — the `files.*` / `tasks.*`
// permissions use these read/write/admin verbs instead of the CRUD set above.
read_own: "read_own",
read_own_member: "read_own_member",
read_own_pl: "read_own_pl",
read_all: "read_all",
write: "write",
bulk_reassign: "bulk_reassign",
change_stage: "change_stage",
manage_members: "manage_members",
read_volume_own: "read_volume_own",
read_volume_all: "read_volume_all",
read_aggregates: "read_aggregates",
admin: "admin",
// P5 Integrations (R-P5) — Apps-Engine connector bundle actions.
read: "read",
connect: "connect",
disconnect: "disconnect",
manual_sync: "manual_sync",
view_logs: "view_logs",
// P16 Calendar-Sync (AK-P16a) — per-user connect capability action.
connect_own: "connect_own",
// P17 HR-Hub workflows (AK-P17b) — leave approval + survey results capabilities.
approve: "approve",
results: "results",
basic: "basic",
builder: "builder",
publisher: "publisher",
send: "send",
revoke: "revoke",
customize: "customize",
run: "run",
self: "self",
tenant_export: "tenant_export",
tenant_deletion: "tenant_deletion",
accept: "accept",
};
const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
@@ -86,32 +122,29 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
"app.settings.subscription": "app.settings.subscription",
"app.settings.subscription.invoices": "app.settings.subscription.invoices",
"app.plugins": "app.plugins",
"app.onboarding.demoData": "app.onboarding.demoData",
"app.onboarding.checklist": "app.onboarding.checklist",
"admin.account": "admin.account",
"admin.account.settings": "admin.account.settings",
"admin.accountTypes": "admin.accountTypes",
"admin.accounts": "admin.accounts",
"admin.analytics": "admin.analytics",
"admin.apiKeys": "admin.apiKeys",
"admin.auditTrails": "admin.auditTrails",
"admin.blacklist": "admin.blacklist",
"admin.dashboard": "admin.dashboard",
"admin.emails": "admin.emails",
"admin.entities": "admin.entities",
"admin.events": "admin.events",
"admin.featureFlags": "admin.featureFlags",
"admin.formulas": "admin.formulas",
"admin.kb": "admin.kb",
"admin.marketing.funnels": "admin.marketing.funnels",
"admin.marketing.integrations": "admin.marketing.integrations",
"admin.marketing.leads": "admin.marketing.leads",
"admin.metrics": "admin.metrics",
"admin.notifications": "admin.notifications",
"admin.onboarding": "admin.onboarding",
"admin.pricing": "admin.pricing",
"admin.prompts": "admin.prompts",
"admin.relationships": "admin.relationships",
"admin.roles": "admin.roles",
"admin.settings.analytics": "admin.settings.analytics",
"admin.settings.authentication": "admin.settings.authentication",
"admin.settings.cookies": "admin.settings.cookies",
"admin.settings.danger": "admin.settings.danger",
@@ -120,6 +153,57 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
"admin.settings.seo": "admin.settings.seo",
"admin.tenantIpAddress": "admin.tenantIpAddress",
"admin.users": "admin.users",
// P4 platform primitives (AK-P4a Files, AK-P4b Tasks) — these scopes carry no
// `app.`/`admin.` prefix, so they need their own scope-key mapping.
files: "files",
tasks: "tasks",
// P6 CRM core (R-P6) — typed CRM contacts scope, no `app.`/`admin.` prefix.
crm: "crm",
// P7 Lead-Inbox (R-P7) — typed lead intake scope, no `app.`/`admin.` prefix.
leads: "leads",
// P8 Projekt/Pipelines (R-P8a). `deals.*` is the historical permission
// backstop for sales-pipeline volume/aggregates; the entity remains Projekt.
projects: "projects",
deals: "deals",
plantafel: "plantafel",
acceptance: "acceptance",
// P17 HR-Hub (AK-P17a). `hr.passwordsafe` maps to a FLAT key (`hrPasswordsafe`)
// on purpose: the `hr` scope is itself a string leaf, so a nested
// `scopes.hr.passwordsafe` path would collide with it.
hr: "hr",
"hr.passwordsafe": "hrPasswordsafe",
// P17 HR-Hub workflows (AK-P17b) — flat keys for the same collision reason as
// hrPasswordsafe (the `hr` scope is itself a string leaf).
"hr.leave": "hrLeave",
"hr.surveys": "hrSurveys",
// P5 Integrations (R-P5) — Apps-Engine connector scope.
integrations: "integrations",
// P14 Email (AK-P14a) — sending-domain settings. Flat key (the email-marketing
// module gate is feature-access; this scope is tenant-side domain management).
"email.domain": "emailDomain",
// P23 Postfach-Sync (VA-P23) — per-user mailbox mirror scope (read_own/read_all/write).
email: "email",
// P14 Email-Marketing (AK-P14b) — campaigns/segments/reporting scope.
emailMarketing: "emailMarketing",
// P16 Calendar-Sync (AK-P16a) — per-user calendar connection scope.
calendar: "calendar",
// P16 Booking (AK-P16b) — booking pages, availability, appointment lifecycle scope.
bookings: "bookings",
// P16 Forms (AK-P16c) — embedded forms and form-builder scope.
forms: "forms",
// P16 Signature (AK-P16d) — SES/PandaDoc signature workflow scope.
signature: "signature",
// P11 Global Search (R-P11a) — global permission-aware search surface.
search: "search",
// P11 Dashboard (R-P11b) — role dashboard surface and filter customization.
dashboard: "dashboard",
// P12 Automation (R-P12a) — typed automation rules, executions and guards.
automation: "automation",
// P21 Privacy/GDPR (AK-P21). Flat keys avoid colliding with the privacy leaf.
privacy: "privacy",
"privacy.user_export": "privacyUserExport",
"privacy.avv": "privacyAvv",
"privacy.subprocessors": "privacySubprocessors",
};
function humanizeIdentifier(value: string) {
@@ -1,7 +1,7 @@
import { useTranslation } from "react-i18next";
import { useState } from "react";
import clsx from "~/utils/shared/ClassesUtils";
import type { TenantUserInvitation } from "@toolctrl/db/prisma-browser";
import type { TenantUserInvitation } from "@hivegrid/db/prisma-browser";
import { useSubmit } from "react-router";
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
import UserBadge from "../../users/UserBadge";
@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import type { TenantUserWithUser } from "~/utils/db/tenants.db.server";
import type { TenantUser } from "@toolctrl/db/prisma-browser";
import type { TenantUser } from "@hivegrid/db/prisma-browser";
import { useLocaleFormatters } from "~/locale/format";
import UserBadge from "../../users/UserBadge";
import TableSimple from "~/components/ui/tables/TableSimple";
@@ -209,12 +209,12 @@ export default function ChangeSubscription({ items, current, billingPeriod, curr
{/* Button */}
<div className="shrink-0 space-y-2 pt-4">
<button
disabled={loading || isCurrent(plan) || !getPrice(plan)?.stripeId || !canSubscribe}
disabled={loading || isCurrent(plan) || !getPrice(plan)?.billingProviderId || !canSubscribe}
type="button"
onClick={() => selectPrice(plan)}
className={clsx(
"inline-flex w-full items-center justify-center rounded-lg border px-4 py-2 text-sm transition-colors focus:outline-hidden focus:ring-2 focus:ring-offset-2",
loading || isCurrent(plan) || !getPrice(plan)?.stripeId || !canSubscribe
loading || isCurrent(plan) || !getPrice(plan)?.billingProviderId || !canSubscribe
? "cursor-not-allowed opacity-80"
: "hover:bg-secondary/90 border-slate-800"
// isUpgrade(plan) && canSubscribe && "hover:text-teal-600",
@@ -1,22 +1,30 @@
import { useTranslation } from "react-i18next";
import type Stripe from "stripe";
import { Colors } from "~/application/enums/shared/Colors";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import DownloadIcon from "~/components/ui/icons/DownloadIcon";
import TableSimple from "~/components/ui/tables/TableSimple";
import { useLocaleFormatters } from "~/locale/format";
import type { CustomerBillingInvoiceDto } from "~/application/dtos/billing/CustomerBillingInvoiceDto";
interface Props {
items: Stripe.Invoice[];
items: CustomerBillingInvoiceDto[];
error?: string | null;
}
export default function MyInvoices({ items }: Props) {
function invoiceStatusColor(status: CustomerBillingInvoiceDto["status"], paymentStatus: CustomerBillingInvoiceDto["paymentStatus"]): Colors {
if (paymentStatus === "succeeded") return Colors.GREEN;
if (status === "voided" || status === "failed" || paymentStatus === "failed") return Colors.RED;
return Colors.YELLOW;
}
export default function MyInvoices({ items, error }: Props) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<div className="space-y-2">
<div className="text-sm font-medium">{t("app.subscription.invoices.title")}</div>
{items.length === 0 ? (
{error ? (
<div className="text-muted-foreground text-sm">{error}</div>
) : items.length === 0 ? (
<div className="text-muted-foreground text-sm italic">{t("shared.noRecords")}</div>
) : (
<TableSimple
@@ -25,11 +33,11 @@ export default function MyInvoices({ items }: Props) {
{
name: "date",
title: t("shared.createdAt"),
value: (i) => formatters.date(new Date(i.created * 1000), { dateStyle: "medium" }),
value: (i) => (i.issuingDate ? formatters.date(new Date(i.issuingDate), { dateStyle: "medium" }) : t("shared.unknown")),
formattedValue: (item) => (
<div className="flex flex-col">
<div>{formatters.date(new Date(item.created * 1000), { dateStyle: "medium" })}</div>
<div className="text-xs">{formatters.relativeDate(new Date(item.created * 1000))}</div>
<div>{item.issuingDate ? formatters.date(new Date(item.issuingDate), { dateStyle: "medium" }) : t("shared.unknown")}</div>
{item.issuingDate && <div className="text-xs">{formatters.relativeDate(new Date(item.issuingDate))}</div>}
</div>
),
},
@@ -38,8 +46,10 @@ export default function MyInvoices({ items }: Props) {
title: t("app.subscription.invoices.amount"),
value: (i) => (
<div className="flex flex-col">
<div>{formatters.currency(Number(i.amount_paid) / 100, i.currency.toUpperCase())}</div>
<div className="text-muted-foreground text-xs uppercase">{i.currency}</div>
<div>
{i.amountCents !== null && i.currency ? formatters.currency(i.amountCents / 100, i.currency.toUpperCase()) : t("shared.unknown")}
</div>
{i.currency && <div className="text-muted-foreground text-xs uppercase">{i.currency}</div>}
</div>
),
},
@@ -47,9 +57,10 @@ export default function MyInvoices({ items }: Props) {
name: "status",
title: t("shared.status"),
value: (i) => (
<div>
<SimpleBadge title={t("app.subscription.invoices.status." + i.status)} color={i.status === "paid" ? Colors.GREEN : Colors.YELLOW} />
</div>
<SimpleBadge
title={t(`app.subscription.invoices.paymentStatus.${i.paymentStatus}`)}
color={invoiceStatusColor(i.status, i.paymentStatus)}
/>
),
},
{
@@ -58,13 +69,8 @@ export default function MyInvoices({ items }: Props) {
title: t("app.subscription.invoices.items"),
value: (i) => (
<div className="flex flex-col">
{i.lines.data.map((lineItem, idx) => {
return (
<div key={idx}>
{lineItem.description}
</div>
);
})}
<span>{i.number ?? i.id}</span>
{i.invoiceType && <span className="text-muted-foreground text-xs">{t(`app.subscription.invoices.type.${i.invoiceType}`)}</span>}
</div>
),
},
@@ -76,8 +82,8 @@ export default function MyInvoices({ items }: Props) {
<DownloadIcon className="h-4 w-4" />
</div>
),
onClickRoute: (_, item) => item.invoice_pdf ?? "",
disabled: (item) => !item.invoice_pdf,
onClickRoute: (_, item) => item.downloadHref ?? "",
disabled: (item) => !item.downloadHref,
onClickRouteTarget: "_blank",
firstColumn: true,
},
@@ -1,12 +1,20 @@
import { useRef } from "react";
import { useTranslation } from "react-i18next";
import type Stripe from "stripe";
import PlusIcon from "~/components/ui/icons/PlusIcon";
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
import TableSimple from "~/components/ui/tables/TableSimple";
interface Props {
items: Stripe.PaymentMethod[];
items: {
id: string;
card?: {
brand?: string | null;
country?: string | null;
exp_month?: number | null;
exp_year?: number | null;
last4?: string | null;
} | null;
}[];
onAdd: () => void;
onDelete: (id: string) => void;
}
@@ -57,7 +65,7 @@ export default function MyPaymentMethods({ items, onAdd, onDelete }: Props) {
title: t("app.subscription.paymentMethods.expiration"),
value: (i) => (
<div className="flex flex-col">
{i.card?.exp_month.toString().padStart(2, "0")}/{i.card?.exp_year}
{i.card?.exp_month?.toString().padStart(2, "0")}/{i.card?.exp_year}
</div>
),
},
@@ -1,12 +1,16 @@
import { useTranslation } from "react-i18next";
import type Stripe from "stripe";
import { Colors } from "~/application/enums/shared/Colors";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import TableSimple from "~/components/ui/tables/TableSimple";
import { useLocaleFormatters } from "~/locale/format";
interface Props {
items: Stripe.PaymentIntent[];
items: {
created: number;
amount: number;
currency: string;
status: string;
}[];
}
export default function MyPayments({ items }: Props) {
@@ -1,13 +1,10 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import WarningBanner from "~/components/ui/banners/WarningBanner";
import { Link } from "react-router";
import TenantProduct from "./TenantProduct";
import { TenantSubscriptionProductWithDetails } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { subscriptionCheckoutPath } from "~/utils/app/SubscriptionUrlUtils";
interface Props {
currentTenant: { slug: string };
items: TenantSubscriptionProductWithDetails[];
onCancel?: (item: TenantSubscriptionProductWithDetails) => void;
}
@@ -37,7 +34,7 @@ function splitItems(items: TenantSubscriptionProductWithDetails[]) {
return { active, history };
}
export default function MyProducts({ currentTenant, items, onCancel }: Props) {
export default function MyProducts({ items, onCancel }: Props) {
const { t } = useTranslation();
const { active, history } = splitItems(items);
const [showHistory, setShowHistory] = useState(false);
@@ -45,11 +42,7 @@ export default function MyProducts({ currentTenant, items, onCancel }: Props) {
return (
<div className="space-y-4" data-ui-id="ui.subscription.products">
{active.length === 0 ? (
<WarningBanner title={t("settings.subscription.noSubscription")} text={""}>
<Link to={subscriptionCheckoutPath(currentTenant.slug)} className="underline" data-ui-id="ui.subscription.checkout.link">
{t("settings.subscription.viewAllProducts")}.
</Link>
</WarningBanner>
<WarningBanner title={t("settings.subscription.noSubscription")} text={t("settings.subscription.readOnlyExternalReference")} />
) : (
<div className="grid gap-2" data-ui-id="ui.subscription.product.active">
{active.map((item, idx) => {
@@ -1,9 +1,13 @@
import { useTranslation } from "react-i18next";
import type Stripe from "stripe";
import { useLocaleFormatters } from "~/locale/format";
interface Props {
items: Stripe.Invoice[];
items: {
amount_due: number;
currency: string;
next_payment_attempt?: number | null;
lines: { data: { description?: string | null }[] };
}[];
}
export default function MyUpcomingInvoice({ items }: Props) {
@@ -10,7 +10,7 @@ import { Fragment, useState } from "react";
import { useRootData } from "~/utils/data/useRootData";
import AnalyticsHelper from "~/utils/helpers/AnalyticsHelper";
import { useTranslation } from "react-i18next";
import type Stripe from "stripe";
import type { BillingProviderCouponDto } from "~/application/dtos/billing/BillingProviderCouponDto";
import PlanFeatureDescription from "./PlanFeatureDescription";
import WarningBanner from "~/components/ui/banners/WarningBanner";
import InputNumber from "~/components/ui/input/InputNumber";
@@ -42,7 +42,7 @@ interface Props {
canSubmit?: boolean;
isUpgrade?: boolean;
isDowngrade?: boolean;
stripeCoupon: Stripe.Coupon | null;
billingProviderCoupon: BillingProviderCouponDto | null;
isPreview?: boolean;
onClickFeature?: (name: string) => void;
/** When set, the user has an existing active subscription on a *different* plan. Click opens a proration preview before submitting. */
@@ -65,7 +65,7 @@ export default function Plan({
canSubmit,
isUpgrade,
isDowngrade,
stripeCoupon,
billingProviderCoupon,
isPreview,
onClickFeature,
currentPlanInfo,
@@ -154,7 +154,7 @@ export default function Plan({
}
// If the user has an existing sub on a different plan, show a proration
// preview modal before sending them to Stripe Checkout. First-subscribe
// preview modal before submitting the plan change. First-subscribe
// (no currentPlanInfo) and same-plan re-buy go straight through.
const isPlanChange = (isUpgrade || isDowngrade) && !!currentPlanInfo && !alreadyOwned;
if (isPlanChange) {
@@ -186,24 +186,24 @@ export default function Plan({
if (alreadyOwned && !product?.canBuyAgain) {
return true;
}
return isSubscribing || !product?.stripeId;
return isSubscribing || !product?.billingProviderId;
}
return isSubscribing || !product?.stripeId;
return isSubscribing || !product?.billingProviderId;
}
const getCoupon = () => {
if (!stripeCoupon) {
if (!billingProviderCoupon) {
return null;
}
if (stripeCoupon.applies_to) {
if (stripeCoupon.applies_to.products.includes(product?.stripeId ?? "")) {
if (!stripeCoupon.currency || stripeCoupon.currency === currency) {
return stripeCoupon;
if (billingProviderCoupon.applies_to) {
if (billingProviderCoupon.applies_to.products.includes(product?.billingProviderId ?? "")) {
if (!billingProviderCoupon.currency || billingProviderCoupon.currency === currency) {
return billingProviderCoupon;
}
}
} else {
if (!stripeCoupon.currency || stripeCoupon.currency === currency) {
return stripeCoupon;
if (!billingProviderCoupon.currency || billingProviderCoupon.currency === currency) {
return billingProviderCoupon;
}
}
return null;
@@ -384,7 +384,7 @@ export default function Plan({
</div>
<SubscribeOrBuyButton
product={product}
isPreview={product?.stripeId === undefined}
isPreview={product?.billingProviderId === undefined}
model={model}
price={getFlatPrice()}
badge={badge}
@@ -402,7 +402,7 @@ export default function Plan({
) : (
<SubscribeOrBuyButton
product={product}
isPreview={product?.stripeId === undefined}
isPreview={product?.billingProviderId === undefined}
model={model}
price={getFlatPrice()}
badge={badge}
@@ -45,7 +45,7 @@ describe("PlanChangePreviewModal i18n", () => {
"Wechsel auf ${toPlanTitle}?",
"You're upgrading from ${fromPlanTitle} to ${toPlanTitle}.",
"Heute (geschätzte anteilige Berechnung)",
"Stripe will show the exact prorated amount",
"The checkout will show the exact prorated amount",
"Continue to checkout",
"Weiter zur Bestätigung",
]) {
@@ -56,7 +56,7 @@ export default function PlanChangePreviewModal({
const { t } = useTranslation();
const formatters = useLocaleFormatters();
// Rough client-side proration estimate. The exact figure is what Stripe
// Rough client-side proration estimate. The exact figure is what Mollie
// Checkout shows on its hosted page before final confirmation — we just
// give the user a ballpark so they aren't surprised.
const estimate = useMemo(() => {
@@ -9,7 +9,7 @@ import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import { getBillingPeriodParams, getYearlyDiscount } from "~/utils/helpers/PricingHelper";
import type { TenantSubscriptionWithDetails } from "~/utils/db/tenantSubscriptions.db.server";
import type { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
import type Stripe from "stripe";
import type { BillingProviderCouponDto } from "~/application/dtos/billing/BillingProviderCouponDto";
import { useSearchParams } from "react-router";
import { useLocaleFormatters } from "~/locale/format";
@@ -18,14 +18,14 @@ interface Props {
tenantSubscription?: TenantSubscriptionWithDetails | null;
canSubmit?: boolean;
className?: string;
stripeCoupon: Stripe.Coupon | null;
billingProviderCoupon: BillingProviderCouponDto | null;
currenciesAndPeriod: {
currencies: { value: string; options: string[] };
billingPeriods: { value: SubscriptionBillingPeriod; options: SubscriptionBillingPeriod[] };
};
onClickFeature?: (name: string) => void;
}
export default function Plans({ items, tenantSubscription, canSubmit, className, stripeCoupon, currenciesAndPeriod, onClickFeature }: Props) {
export default function Plans({ items, tenantSubscription, canSubmit, className, billingProviderCoupon, currenciesAndPeriod, onClickFeature }: Props) {
const [searchParams, setSearchParams] = useSearchParams();
const formatters = useLocaleFormatters();
const [currency, setCurrency] = useState(currenciesAndPeriod.currencies.value);
@@ -156,7 +156,7 @@ export default function Plans({ items, tenantSubscription, canSubmit, className,
canSubmit={canSubmit}
isUpgrade={checkUpgradeDowngrade(plan)?.upgrade}
isDowngrade={checkUpgradeDowngrade(plan)?.downgrade}
stripeCoupon={stripeCoupon}
billingProviderCoupon={billingProviderCoupon}
onClickFeature={onClickFeature}
currentPlanInfo={currentPlanInfo}
/>
@@ -1,4 +1,4 @@
import { TenantSubscriptionProductPrice } from "@toolctrl/db/prisma-browser";
import { TenantSubscriptionProductPrice } from "@hivegrid/db/prisma-browser";
import { Fragment, useRef } from "react";
import { useTranslation } from "react-i18next";
import { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
@@ -188,17 +188,10 @@ export default function TenantProduct({ item, onCancel }: Props) {
<div className="font-medium">{t("settings.subscription.debug.id")}</div>
<div>{item.id}</div>
</div>
{item.stripeSubscriptionId && (
{item.billingProviderSubscriptionId && (
<div className="flex items-baseline space-x-2">
<div className="font-medium">{t("settings.subscription.debug.stripeId")}</div>
<a
target="_blank"
className="underline"
rel="noreferrer"
href={`https://dashboard.stripe.com${rootData.isStripeTest ? "/test" : ""}/subscriptions/${item.stripeSubscriptionId}`}
>
{item.stripeSubscriptionId}
</a>
<div className="font-medium">{t("settings.subscription.debug.billingProviderId")}</div>
<div>{item.billingProviderSubscriptionId}</div>
</div>
)}
</div>
@@ -2,7 +2,7 @@ import { Fragment, useMemo, useState } from "react";
import type { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import type { TenantSubscriptionWithDetails } from "~/utils/db/tenantSubscriptions.db.server";
import Plans from "../Plans";
import type Stripe from "stripe";
import type { BillingProviderCouponDto } from "~/application/dtos/billing/BillingProviderCouponDto";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import Modal from "~/components/ui/modals/Modal";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
@@ -12,13 +12,13 @@ interface Props {
items: SubscriptionProductDto[];
tenantSubscription?: TenantSubscriptionWithDetails | null;
canSubmit?: boolean;
stripeCoupon: Stripe.Coupon | null;
billingProviderCoupon: BillingProviderCouponDto | null;
currenciesAndPeriod: {
currencies: { value: string; options: string[] };
billingPeriods: { value: SubscriptionBillingPeriod; options: SubscriptionBillingPeriod[] };
};
}
export default function PlansGrouped({ items, tenantSubscription, canSubmit, stripeCoupon, currenciesAndPeriod }: Props) {
export default function PlansGrouped({ items, tenantSubscription, canSubmit, billingProviderCoupon, currenciesAndPeriod }: Props) {
const [showFeatureInfoModal, setShowFeatureInfoModal] = useState<boolean>(false);
const [showFeatureInfo, setShowFeatureInfo] = useState<string | null>(null);
const groups = useMemo(() => {
@@ -64,7 +64,7 @@ export default function PlansGrouped({ items, tenantSubscription, canSubmit, str
tenantSubscription={tenantSubscription}
canSubmit={canSubmit}
className="space-y-4"
stripeCoupon={stripeCoupon}
billingProviderCoupon={billingProviderCoupon}
currenciesAndPeriod={currenciesAndPeriod}
onClickFeature={(name) => {
setShowFeatureInfo(name);
@@ -1,105 +0,0 @@
import { useTranslation } from "react-i18next";
import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
import { useEffect, useRef, useState } from "react";
import LoadingButton from "~/components/ui/buttons/LoadingButton";
import { Form, useActionData, useSubmit } from "react-router";
import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessModal";
import RowProperties from "~/components/entities/rows/RowProperties";
import type { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import InputText, { RefInputText } from "~/components/ui/input/InputText";
import { useRootData } from "~/utils/data/useRootData";
export default function TenantNew({ tenantSettingsEntity }: { tenantSettingsEntity: EntityWithDetails | null }) {
const actionData = useActionData<{ tenantId?: string; error?: string; success?: string }>();
const { t } = useTranslation();
const submit = useSubmit();
const rootData = useRootData();
const inputName = useRef<RefInputText>(null);
const errorModal = useRef<RefErrorModal>(null);
const successModal = useRef<RefSuccessModal>(null);
const [name, setName] = useState("");
useEffect(() => {
inputName.current?.input.current?.focus();
inputName.current?.input.current?.select();
}, []);
useEffect(() => {
if (actionData?.error) {
errorModal.current?.show(actionData.error);
} else if (actionData?.success) {
successModal.current?.show(actionData.success);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [actionData]);
function createdTenant() {
if (actionData?.tenantId) {
const form = new FormData();
form.set("action", "set-tenant");
form.set("tenantId", actionData.tenantId);
form.set("redirectTo", location.pathname + location.search);
submit(form, {
method: "post",
action: "/",
});
}
}
return (
<div>
<div className="flex flex-1 flex-col justify-between">
<Form method="post" className="" data-ui-id="ui.account.create.form">
<input type="hidden" name="action" value="create" hidden readOnly />
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} hidden readOnly />
<div className="space-y-3 pb-5 pt-2">
<div>
{/* <label className="block text-xs font-medium text-muted-foreground">
{t("account.register.organization")} <span className="ml-1 text-red-500">*</span>
</label> */}
<div className="mt-1 -space-y-px rounded-md shadow-2xs">
<div>
{/* <label htmlFor="tax-id" className="sr-only">
{t("shared.name")}
</label> */}
<InputText
title={t("shared.name")}
ref={inputName}
type="text"
name="name"
id="name"
dataUiId="ui.account.create.name"
placeholder={t("shared.name")}
required
value={name}
setValue={setName}
// className="focus:border-theme-500 focus:ring-ring relative block w-full appearance-none rounded-md border border-border px-3 py-2 text-foreground placeholder-gray-500 focus:z-10 focus:outline-hidden sm:text-sm"
/>
</div>
</div>
</div>
{tenantSettingsEntity && (
<div className="col-span-6 sm:col-span-6">
<RowProperties entity={tenantSettingsEntity} item={null} />
</div>
)}
</div>
<div className="pb-6 text-right">
<div className="right-0 text-sm leading-5">
<span className="ml-2 inline-flex rounded-sm shadow-2xs">
<LoadingButton type="submit" dataUiId="ui.account.create.submit">{t("shared.create")}</LoadingButton>
</span>
</div>
</div>
</Form>
</div>
<SuccessModal ref={successModal} onClosed={createdTenant} />
<ErrorModal ref={errorModal} />
</div>
);
}
@@ -8,62 +8,25 @@ import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
import { RowHeaderActionDto } from "~/application/dtos/data/RowHeaderActionDto";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import { Colors } from "~/application/enums/shared/Colors";
import type Stripe from "stripe";
import { Link } from "react-router";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
import { useRootData } from "~/utils/data/useRootData";
import { createLocaleFormatters, type LocaleFormatters } from "~/locale/format";
import { createLocaleFormatters } from "~/locale/format";
import { translateLabel } from "~/utils/i18n/translateLabel";
interface Props {
items: TenantWithUsage[];
pagination: PaginationDto;
actions?: RowHeaderActionDto<TenantWithUsage>[];
tenantInvoices?: Stripe.Invoice[];
isStripeTest?: boolean;
}
type TenantInvoiceSummary = {
lastInvoice?: Stripe.Invoice;
paidCount: number;
totalsPaidByCurrency: Map<string, number>;
};
export default function TenantsTable({ items, pagination, actions = [], tenantInvoices, isStripeTest }: Props) {
export default function TenantsTable({ items, pagination, actions = [] }: Props) {
const { i18n, t } = useTranslation();
const formatters = useMemo(() => createLocaleFormatters(i18n.language), [i18n.language]);
const rootData = useRootData();
const [headers, setHeaders] = useState<RowHeaderDisplayDto<TenantWithUsage>[]>([]);
const invoiceSummaryByCustomer = useMemo(() => {
if (!tenantInvoices) {
return undefined;
}
const summaries = new Map<string, TenantInvoiceSummary>();
for (const invoice of tenantInvoices) {
const customerId = invoice.customer?.toString();
if (!customerId) {
continue;
}
const summary = summaries.get(customerId) ?? { paidCount: 0, totalsPaidByCurrency: new Map<string, number>() };
const currency = invoice.currency.toUpperCase();
const amountPaid = Number(invoice.amount_paid / 100);
if (amountPaid > 0) {
summary.totalsPaidByCurrency.set(currency, (summary.totalsPaidByCurrency.get(currency) ?? 0) + amountPaid);
}
if (invoice.status === "paid") {
summary.paidCount += 1;
}
if (!summary.lastInvoice || invoice.created > summary.lastInvoice.created) {
summary.lastInvoice = invoice;
}
summaries.set(customerId, summary);
}
return summaries;
}, [tenantInvoices]);
useEffect(() => {
const headers: RowHeaderDisplayDto<TenantWithUsage>[] = [];
@@ -136,63 +99,6 @@ export default function TenantsTable({ items, pagination, actions = [], tenantIn
</span>
),
});
if (tenantInvoices !== undefined) {
function getInvoiceSummary(tenant: TenantWithUsage): TenantInvoiceSummary | undefined {
const customerId = tenant.subscription?.stripeCustomerId;
return customerId ? invoiceSummaryByCustomer?.get(customerId) : undefined;
}
headers.push({
name: "lastInvoice",
title: t("settings.tenant.billing.lastInvoice"),
value: (i) =>
(() => {
const summary = getInvoiceSummary(i);
return (
<a
className="flex flex-col space-y-1 hover:underline"
target="_blank"
rel="noreferrer"
href={`https://dashboard.stripe.com${isStripeTest ? "/test" : ""}/customers/${i.subscription?.stripeCustomerId ?? ""}`}
>
<div className="flex flex-col space-y-1">
{!summary?.lastInvoice ? (
<span className="text-muted-foreground italic">{t("shared.none")}</span>
) : (
<TenantInvoice item={summary.lastInvoice} formatters={formatters} />
)}
</div>
</a>
);
})(),
});
headers.push({
name: "totalInvoicesPaid",
title: t("settings.tenant.billing.totalPaid"),
value: (i) =>
(() => {
const summary = getInvoiceSummary(i);
return (
<a
className="flex flex-col space-y-1 hover:underline"
target="_blank"
rel="noreferrer"
href={`https://dashboard.stripe.com${isStripeTest ? "/test" : ""}/customers/${i.subscription?.stripeCustomerId ?? ""}`}
>
{!summary || summary.totalsPaidByCurrency.size === 0 ? (
<span className="text-muted-foreground italic">{t("shared.none")}</span>
) : (
<div className="flex flex-col">
{[...summary.totalsPaidByCurrency.entries()].map(([currency, totalPaid]) => (
<span key={currency}>{formatters.currency(totalPaid, currency)}</span>
))}
<span className="text-muted-foreground text-xs">({formatters.number(summary.paidCount)})</span>
</div>
)}
</a>
);
})(),
});
}
headers.push({
name: "types",
title: t("shared.types"),
@@ -210,11 +116,6 @@ export default function TenantsTable({ items, pagination, actions = [], tenantIn
value: (i) => i.users.map((f) => f.user.email).join(", "),
href: (i) => adminPath(`accounts/users?tenantId=${i.id}`, { mode: "host-aware" }),
});
headers.push({
name: "rows",
title: t("models.row.plural"),
value: (item) => <Link to={adminPath("entities/rows?tenantId=" + item.id, { mode: "host-aware" })}>{formatters.number(item._count.rows ?? 0)}</Link>,
});
headers.push({
name: "events",
title: t("models.event.plural"),
@@ -233,7 +134,7 @@ export default function TenantsTable({ items, pagination, actions = [], tenantIn
),
});
setHeaders(headers);
}, [formatters, invoiceSummaryByCustomer, isStripeTest, rootData.routing, t, tenantInvoices]);
}, [formatters, rootData.routing, t]);
return (
<div className="space-y-2">
@@ -252,20 +153,3 @@ export default function TenantsTable({ items, pagination, actions = [], tenantIn
</div>
);
}
function TenantInvoice({ item, formatters }: { item: Stripe.Invoice; formatters: LocaleFormatters }) {
const { t } = useTranslation();
const createdAt = new Date(item.created * 1000);
return (
<div className="flex flex-col">
<div title={formatters.dateTime(createdAt, { timeStyle: "medium" })} className="flex items-center space-x-1">
<div className="flex items-baseline space-x-1">
<div>{formatters.currency(item.total / 100, item.currency.toUpperCase())}</div>
<div className="text-muted-foreground text-xs uppercase">{item.currency}</div>
</div>
<SimpleBadge title={t("app.subscription.invoices.status." + item.status)} color={item.status === "paid" ? Colors.GREEN : Colors.YELLOW} />
</div>
<div className="text-muted-foreground text-xs">{item.created ? formatters.relativeDate(createdAt) : ""}</div>
</div>
);
}
@@ -6,9 +6,7 @@ import UploadDocuments from "~/components/ui/uploaders/UploadDocument";
import InputText from "~/components/ui/input/InputText";
import UrlUtils from "~/utils/app/UrlUtils";
import type { TenantWithDetails } from "~/utils/db/tenants.db.server";
import RowProperties from "~/components/entities/rows/RowProperties";
import LoadingButton from "~/components/ui/buttons/LoadingButton";
import type { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import InputCombobox from "~/components/ui/input/InputCombobox";
import { useRootData } from "~/utils/data/useRootData";
import { translateLabel } from "~/utils/i18n/translateLabel";
@@ -22,14 +20,13 @@ type TenantTypeOption = {
interface Props {
tenant: TenantWithDetails;
disabled: boolean;
tenantSettingsEntity: EntityWithDetails | null;
tenantTypes?: TenantTypeOption[];
options?: {
canChangeType: boolean;
};
}
export default function UpdateTenantDetailsForm({ tenant, disabled, tenantSettingsEntity, tenantTypes, options }: Props) {
export default function UpdateTenantDetailsForm({ tenant, disabled, tenantTypes, options }: Props) {
const { i18n, t } = useTranslation();
const rootData = useRootData();
@@ -123,11 +120,6 @@ export default function UpdateTenantDetailsForm({ tenant, disabled, tenantSettin
</div>
</div>
{tenantSettingsEntity && (
<div className="col-span-6 sm:col-span-6">
<RowProperties entity={tenantSettingsEntity} item={tenant.tenantSettingsRow?.row ?? null} />
</div>
)}
</div>
</div>
@@ -0,0 +1,65 @@
import { useEffect, useState } from "react";
import { useFetcher } from "react-router";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { TenantWithProfile } from "~/utils/db/tenants.db.server";
import { useRootData } from "~/utils/data/useRootData";
import { defaultAnrede, isAnrede, type Anrede } from "@hivegrid/i18n";
import SettingSection from "~/components/ui/sections/SettingSection";
import InputChoicebox from "~/components/ui/input/InputChoicebox";
type Props = {
tenant: TenantWithProfile;
};
/**
* Schlichter du/Sie-Umschalter (Anrede). Persistiert `Tenant.anrede` und setzt
* den `_anrede`-Cookie (Server-Action `update-anrede`). Default "du" verhaelt
* sich byte-identisch zum Status quo; "sie" schaltet die App auf die
* "<locale>-formal"-Sprachvariante um (Fallback auf Basis-Locale).
*/
export default function UpdateTenantFormAnrede({ tenant }: Props) {
const { t } = useTranslation();
const { csrf } = useRootData();
const fetcher = useFetcher<{ success?: string; error?: string }>();
const initial: Anrede = isAnrede(tenant?.anrede ?? undefined) ? (tenant.anrede as Anrede) : defaultAnrede;
const [anrede, setAnrede] = useState<Anrede>(initial);
useEffect(() => {
if (fetcher.data?.success) {
toast.success(fetcher.data.success);
} else if (fetcher.data?.error) {
toast.error(fetcher.data.error);
}
}, [fetcher.data]);
const onChange = (value: string) => {
if (!isAnrede(value) || value === anrede) {
return;
}
setAnrede(value);
const form = new FormData();
form.set("action", "update-anrede");
form.set("anrede", value);
if (csrf) {
form.set("csrf", csrf);
}
fetcher.submit(form, { method: "post", preventScrollReset: true });
};
return (
<SettingSection title={t("settings:tenant.anrede.title")} description={t("settings:tenant.anrede.description")}>
<InputChoicebox
name="anrede"
value={anrede}
onChange={onChange}
disabled={fetcher.state !== "idle"}
options={[
{ value: "du", name: t("settings:tenant.anrede.du") },
{ value: "sie", name: t("settings:tenant.anrede.sie") },
]}
/>
</SettingSection>
);
}
@@ -1,4 +1,4 @@
import { ApiKey } from "@toolctrl/db/prisma-browser";
import { ApiKey } from "@hivegrid/db/prisma-browser";
import { useTranslation } from "react-i18next";
interface Props {
@@ -5,7 +5,7 @@ import ErrorModal, { RefErrorModal } from "~/components/ui/modals/ErrorModal";
import { useEscapeKeypress } from "~/utils/shared/KeypressUtils";
import clsx from "~/utils/shared/ClassesUtils";
import EmptyState from "~/components/ui/emptyState/EmptyState";
import { User } from "@toolctrl/db/prisma-browser";
import { User } from "@hivegrid/db/prisma-browser";
import { XIcon, PlusIcon } from "~/components/ui/icons/vendor";
export interface RefSelectUsers {
@@ -1,4 +1,4 @@
import { AdminUser, Role, UserRole } from "@toolctrl/db/prisma-browser";
import { AdminUser, Role, UserRole } from "@hivegrid/db/prisma-browser";
import { useTranslation } from "react-i18next";
import AtSymbolIcon from "~/components/ui/icons/AtSymbolIcon";
import UserAvatarBadge from "./UserAvatarBadge";
@@ -1,4 +1,4 @@
import { Log, Role, User } from "@toolctrl/db/prisma-browser";
import { Log, Role, User } from "@hivegrid/db/prisma-browser";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useSubmit } from "react-router";
@@ -0,0 +1,430 @@
// R-P6 (P6 CRM core, Variante A) — presentational contact/organisation detail.
// Pure component: it receives the server-built KontaktDetailVM data + the
// Activity-Stream VM + option lists and renders the inline-edit forms (DoD 3).
// It NEVER calls useLoaderData/useFetcher (the route injects the data) and holds
// no server imports; every form posts back to the current route's action.
import { useTranslation } from "react-i18next";
import type { ActivityStreamVM, KontaktDetailData } from "@hivegrid/view-models";
export type KontaktDetailViewProps = {
data: KontaktDetailData;
activity: ActivityStreamVM;
allTags: { id: string; name: string; farbe: string }[];
customFieldDefs: { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string }[];
ownerOptions: { id: string; label: string }[];
backHref: string;
listLabelKey: string;
errorKey?: string | null;
};
const crmFieldLabelClass = "block text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary";
const crmFieldControlClass =
"mt-1 h-9 w-full rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle focus:shadow-focus";
const crmTextareaClass =
"mt-1 w-full rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 py-2 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle focus:shadow-focus";
export default function KontaktDetailView(props: KontaktDetailViewProps) {
const { t, i18n } = useTranslation();
const { data } = props;
const isOrg = data.kontaktTyp === "organisation";
const dateTime = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium", timeStyle: "short" });
return (
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.crm.detail">
<nav className="text-muted-foreground mb-4 text-sm" aria-label={t("crm.detail.breadcrumb")} data-ui-id="ui.crm.detail.breadcrumb">
<a href={props.backHref} className="hover:text-foreground" data-ui-id="ui.crm.detail.back">
{t(props.listLabelKey)}
</a>
<span className="px-2">{"/"}</span>
<span className="text-foreground">{data.displayName}</span>
</nav>
<header className="flex flex-wrap items-center gap-3">
<h1 className="text-foreground text-xl font-semibold">{data.displayName}</h1>
<span className="border-border rounded border px-2 py-0.5 text-xs">{t(data.typLabelKey)}</span>
<span className="border-border rounded border px-2 py-0.5 text-xs">{t(data.statusLabelKey)}</span>
{data.isArchived ? <span className="text-destructive text-xs">{t("crm.detail.archivedBadge")}</span> : null}
</header>
{props.errorKey ? (
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.detail.error">
{t(props.errorKey)}
</p>
) : null}
{/* --- Basics (inline edit) --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.basics">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.basics")}</h2>
{data.canWrite ? (
<form method="post" className="mt-2 grid gap-2 sm:grid-cols-2">
<input type="hidden" name="intent" value="updateBasics" />
{isOrg ? (
<>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.orgName")}</span>
<input name="orgName" defaultValue={data.orgName ?? ""} className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.orgMerkmal")}</span>
<select name="orgMerkmal" defaultValue={data.orgMerkmal ?? ""} className={crmFieldControlClass}>
<option value="">{t("crm.fields.none")}</option>
{(["gmbh", "kg", "oeffentliche_einrichtung", "sonstige"] as const).map((merkmal) => (
<option key={merkmal} value={merkmal}>
{t(`crm.orgMerkmal.${merkmal}`)}
</option>
))}
</select>
</label>
</>
) : (
<>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.vorname")}</span>
<input name="vorname" defaultValue={data.vorname ?? ""} className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.nachname")}</span>
<input name="nachname" defaultValue={data.nachname ?? ""} className={crmFieldControlClass} />
</label>
</>
)}
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.status")}</span>
<select name="kontaktStatus" defaultValue={data.kontaktStatus} className={crmFieldControlClass}>
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
<option key={status} value={status}>
{t(`crm.kontaktStatus.${status}`)}
</option>
))}
</select>
</label>
<div className="sm:col-span-2">
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.detail.basics.save">
{t("crm.actions.save")}
</button>
</div>
</form>
) : (
<dl className="mt-2 grid grid-cols-[8rem_1fr] gap-y-1 text-sm">
<dt className="text-muted-foreground">{t("crm.fields.status")}</dt>
<dd>{t(data.statusLabelKey)}</dd>
{data.orgMerkmalLabelKey ? (
<>
<dt className="text-muted-foreground">{t("crm.fields.orgMerkmal")}</dt>
<dd>{t(data.orgMerkmalLabelKey)}</dd>
</>
) : null}
</dl>
)}
</section>
{/* --- Emails --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.emails">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.emails")}</h2>
<ul className="mt-2 text-sm">
{data.emails.map((email) => (
<li key={email.id} className="flex items-center gap-2 py-0.5" data-row-id={email.id}>
<span>{email.email}</span>
{email.primaer ? <span className="text-theme-600 text-xs">{t("crm.detail.primary")}</span> : null}
{data.canWrite && !email.primaer ? (
<form method="post">
<input type="hidden" name="intent" value="setPrimaryEmail" />
<input type="hidden" name="emailId" value={email.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.makePrimary")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeEmail" />
<input type="hidden" name="emailId" value={email.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addEmail" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.email")}</span>
<input name="email" type="email" required className={crmFieldControlClass} />
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="primaer" value="1" /> {t("crm.detail.primary")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Phones --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.telefone">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.telefone")}</h2>
<ul className="mt-2 text-sm">
{data.telefone.map((tel) => (
<li key={tel.id} className="flex items-center gap-2 py-0.5" data-row-id={tel.id}>
<span>{tel.telefon}</span>
{tel.primaer ? <span className="text-theme-600 text-xs">{t("crm.detail.primary")}</span> : null}
{data.canWrite && !tel.primaer ? (
<form method="post">
<input type="hidden" name="intent" value="setPrimaryTelefon" />
<input type="hidden" name="telefonId" value={tel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.makePrimary")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeTelefon" />
<input type="hidden" name="telefonId" value={tel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addTelefon" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.telefon")}</span>
<input name="telefon" required className={crmFieldControlClass} />
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="primaer" value="1" /> {t("crm.detail.primary")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Address (read-only) --- */}
{data.adresse ? (
<section className="mt-6" data-ui-id="ui.crm.detail.adresse">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.adresse")}</h2>
<p className="mt-1 text-sm">
{[data.adresse.strasse, data.adresse.hausnummer].filter(Boolean).join(" ")}
{data.adresse.plz || data.adresse.ort ? `, ${[data.adresse.plz, data.adresse.ort].filter(Boolean).join(" ")}` : ""}
{`, ${data.adresse.land}`}
</p>
</section>
) : null}
{/* --- Relations --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.relations">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.relations")}</h2>
<ul className="mt-2 text-sm">
{data.relationen.map((rel) => (
<li key={rel.id} className="flex items-center gap-2 py-0.5" data-row-id={rel.id}>
<span>{rel.otherKontaktId}</span>
<span className="text-muted-foreground text-xs">{t(rel.rolleLabelKey)}</span>
{rel.kontext ? <span className="text-muted-foreground text-xs">{rel.kontext}</span> : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeRelation" />
<input type="hidden" name="relationId" value={rel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addRelation" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationTarget")}</span>
<input name="zuKontaktId" required className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationRole")}</span>
<select name="rolle" className={crmFieldControlClass}>
{(["hauptkontakt", "sekundaerkontakt", "mitarbeiter", "sonstige"] as const).map((rolle) => (
<option key={rolle} value={rolle}>
{t(`crm.kontaktArt.${rolle}`)}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationContext")}</span>
<input name="kontext" className={crmFieldControlClass} />
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Tags --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.tags">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.tags")}</h2>
<ul className="mt-2 flex flex-wrap gap-2 text-sm">
{data.tags.map((tag) => (
<li key={tag.id} className="border-border flex items-center gap-1 rounded border px-2 py-0.5" data-row-id={tag.id}>
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
<span>{tag.name}</span>
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeTag" />
<input type="hidden" name="tagId" value={tag.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite && props.allTags.length > 0 ? (
<form method="post" className="mt-2 flex items-end gap-2">
<input type="hidden" name="intent" value="addTag" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.tag")}</span>
<select name="tagId" className={crmFieldControlClass}>
{props.allTags.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Custom fields --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.customFields">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.customFields")}</h2>
<dl className="mt-2 grid grid-cols-[10rem_1fr] gap-y-1 text-sm">
{data.customFields.map((cf) => (
<div key={cf.definitionId} className="contents" data-row-id={cf.definitionId}>
<dt className="text-muted-foreground">{cf.label}</dt>
<dd>{cf.wert == null ? "" : String(cf.wert)}</dd>
</div>
))}
</dl>
{data.canWrite && props.customFieldDefs.length > 0 ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="setCustomField" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.customField")}</span>
<select name="definitionId" className={crmFieldControlClass}>
{props.customFieldDefs.map((def) => (
<option key={def.id} value={def.id}>
{def.label}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.value")}</span>
<input name="wert" className={crmFieldControlClass} />
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.save")}
</button>
</form>
) : null}
</section>
{/* --- Quick actions --- */}
{data.canWrite || data.canDelete ? (
<section className="mt-8 border-t pt-4" data-ui-id="ui.crm.detail.actions">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.actions")}</h2>
<div className="mt-2 flex flex-wrap items-end gap-4">
{data.canWrite ? (
<form method="post" className="flex items-end gap-2">
<input type="hidden" name="intent" value="reassign" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.owner")}</span>
<select name="zustaendigerUserId" defaultValue={data.zustaendigerUserId ?? ""} className={crmFieldControlClass}>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.reassign")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post" className="flex-1">
<input type="hidden" name="intent" value="addNote" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.note")}</span>
<textarea name="note" required rows={2} className={crmTextareaClass} />
</label>
<button type="submit" className="text-theme-600 mt-1 text-sm font-medium" data-ui-id="ui.crm.detail.addNote">
{t("crm.actions.addNote")}
</button>
</form>
) : null}
</div>
<div className="mt-3 flex flex-wrap gap-3">
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value={data.isArchived ? "reactivate" : "archive"} />
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.detail.archive">
{t(data.isArchived ? "crm.actions.reactivate" : "crm.actions.archive")}
</button>
</form>
) : null}
{data.canDelete ? (
<form method="post">
<input type="hidden" name="intent" value="delete" />
<button type="submit" className="text-destructive text-sm font-medium" data-ui-id="ui.crm.detail.delete">
{t("crm.actions.delete")}
</button>
</form>
) : null}
</div>
</section>
) : null}
{/* --- Activity stream --- */}
<section className="mt-8 border-t pt-4" data-ui-id="ui.crm.detail.activity">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.activity")}</h2>
{props.activity.status === "ready" && props.activity.data ? (
<ul className="mt-2 space-y-2 text-sm">
{props.activity.data.entries.map((entry) => (
<li key={entry.id} className="border-border border-l-2 pl-3" data-row-id={entry.id}>
<p>{entry.summaryText}</p>
<p className="text-muted-foreground text-xs">
{t(entry.activityLabelKey)}
{entry.actorLabel ? ` · ${entry.actorLabel}` : ""} · <time dateTime={entry.createdAtIso}>{dateTime.format(new Date(entry.createdAtIso))}</time>
</p>
</li>
))}
</ul>
) : (
<p className="text-muted-foreground mt-2 text-sm" data-ui-id="ui.crm.detail.activity.empty">
{t("crm.detail.activityEmpty")}
</p>
)}
</section>
</main>
);
}
@@ -0,0 +1,256 @@
// R-P6 (P6 CRM core, Variante A) — presentational contact/organisation browser.
// Pure component: it renders the server-built KontaktListVM (filter / sort /
// paginate / bulk / CSV, DoD 2). The filter bar is a GET form (state lives in the
// URL); bulk actions are a POST form whose checkboxes carry the selected ids.
// No useLoaderData/useFetcher, no server imports.
import { useTranslation } from "react-i18next";
import type { KontaktListVM } from "@hivegrid/view-models";
import { kontaktListQueryToParams, type KontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
export type KontaktListViewProps = {
moduleActive: boolean;
variant: "contacts" | "companies";
vm: KontaktListVM;
tagOptions: { id: string; name: string; farbe: string }[];
ownerOptions: { id: string; label: string }[];
query: KontaktListQuery;
baseHref: string;
newHref: string;
exportHref: string;
errorKey?: string | null;
};
function pageHref(baseHref: string, query: KontaktListQuery, page: number): string {
const params = kontaktListQueryToParams({ ...query, page });
const qs = params.toString();
return qs ? `${baseHref}?${qs}` : baseHref;
}
export default function KontaktListView(props: KontaktListViewProps) {
const { t } = useTranslation();
const titleKey = props.variant === "companies" ? "crm.companies.title" : "crm.contacts.title";
const emptyHeadlineKey = props.variant === "companies" ? "crm.empty.companies.headline" : "crm.empty.contacts.headline";
const emptyBodyKey = props.variant === "companies" ? "crm.empty.companies.body" : "crm.empty.contacts.body";
if (!props.moduleActive) {
return (
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.crm.list">
<div className="mt-10 text-center" data-ui-id="ui.crm.list.locked">
<p className="text-foreground font-medium">{t("crm.locked.headline")}</p>
<p className="text-muted-foreground mt-1 text-sm">{t("crm.locked.body")}</p>
</div>
</main>
);
}
const data = props.vm.status === "ready" ? props.vm.data : null;
const { filter, sort } = props.query;
return (
<main className="mx-auto max-w-6xl px-4 py-10" data-ui-id="ui.crm.list">
<header className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-foreground text-xl font-semibold">{t(titleKey)}</h1>
<div className="flex gap-3 text-sm">
<a href={props.exportHref} className="text-theme-600 font-medium" data-ui-id="ui.crm.list.export">
{t("crm.actions.exportCsv")}
</a>
<a href={props.newHref} className="text-theme-600 font-medium" data-ui-id="ui.crm.list.new">
{t("crm.actions.newContact")}
</a>
</div>
</header>
{/* --- Filter bar (GET, URL-driven, server-side) --- */}
<form method="get" action={props.baseHref} className="mt-6 flex flex-wrap items-end gap-2" data-ui-id="ui.crm.list.filter">
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.search")}</span>
<input name="q" defaultValue={filter.search ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1" />
</label>
{props.variant === "contacts" ? (
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.type")}</span>
<select name="typ" defaultValue={filter.kontaktTyp ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
<option value="privatperson">{t("crm.kontaktTyp.privatperson")}</option>
<option value="organisation">{t("crm.kontaktTyp.organisation")}</option>
</select>
</label>
) : null}
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.status")}</span>
<select name="status" defaultValue={filter.kontaktStatus ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
<option key={status} value={status}>
{t(`crm.kontaktStatus.${status}`)}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.owner")}</span>
<select name="owner" defaultValue={filter.zustaendigerUserId ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.tags")}</span>
<select name="tags" multiple defaultValue={filter.tagIds ?? []} className="border-muted-foreground/40 rounded border px-2 py-1">
{props.tagOptions.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.tagMatch")}</span>
<select name="tagMatch" defaultValue={filter.tagMatch} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="or">{t("crm.filter.tagMatchOr")}</option>
<option value="and">{t("crm.filter.tagMatchAnd")}</option>
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.sort")}</span>
<select name="sort" defaultValue={sort.field} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="createdAt">{t("crm.filter.sortCreated")}</option>
<option value="name">{t("crm.filter.sortName")}</option>
<option value="kontaktStatus">{t("crm.filter.sortStatus")}</option>
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.direction")}</span>
<select name="dir" defaultValue={sort.dir} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="desc">{t("crm.filter.dirDesc")}</option>
<option value="asc">{t("crm.filter.dirAsc")}</option>
</select>
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="archived" value="1" defaultChecked={filter.includeArchived} /> {t("crm.filter.includeArchived")}
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="demo" value="show" defaultChecked={filter.includeDemoData} /> {t("onboarding.demoData.showInLists")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.applyFilter")}
</button>
</form>
{props.errorKey ? (
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.list.error">
{t(props.errorKey)}
</p>
) : null}
{!data ? (
<div className="mt-10 text-center" data-ui-id="ui.crm.list.empty">
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
<a href={props.newHref} className="text-theme-600 mt-2 inline-block text-sm font-medium">
{t("crm.actions.newContact")}
</a>
</div>
) : (
<form method="post" className="mt-6" data-ui-id="ui.crm.list.bulkForm">
<div className="overflow-x-auto">
<table className="w-full text-left text-sm" data-ui-id="ui.crm.list.table">
<thead>
<tr className="text-muted-foreground border-b">
<th className="py-2" />
<th className="py-2">{t("crm.column.name")}</th>
<th className="py-2">{t("crm.column.type")}</th>
<th className="py-2">{t("crm.column.status")}</th>
<th className="py-2">{t("crm.column.email")}</th>
<th className="py-2">{t("crm.column.telefon")}</th>
<th className="py-2">{t("crm.column.owner")}</th>
<th className="py-2">{t("crm.column.tags")}</th>
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<tr key={row.id} className="border-b" data-row-id={row.id}>
<td className="py-2">
<input type="checkbox" name="kontaktId" value={row.id} aria-label={t("crm.actions.select")} />
</td>
<td className="py-2">
<a href={row.detailHref} className="text-theme-600">
{row.displayName}
</a>
{row.isArchived ? <span className="text-muted-foreground ml-1 text-xs">{t("crm.detail.archivedBadge")}</span> : null}
</td>
<td className="py-2">{t(row.typLabelKey)}</td>
<td className="py-2">{t(row.statusLabelKey)}</td>
<td className="py-2">{row.primaerEmail ?? ""}</td>
<td className="py-2">{row.primaerTelefon ?? ""}</td>
<td className="py-2">{row.zustaendigerLabel ?? ""}</td>
<td className="py-2">
{row.tagChips.map((tag) => (
<span key={tag.id} className="mr-1 inline-flex items-center gap-1">
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
{tag.name}
</span>
))}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* --- Bulk actions (operate on the checked rows) --- */}
<div className="mt-4 flex flex-wrap items-end gap-3" data-ui-id="ui.crm.list.bulk">
<button type="submit" name="intent" value="bulkArchive" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkArchive")}
</button>
<span className="flex items-end gap-1">
<select name="zustaendigerUserId" className="border-muted-foreground/40 rounded border px-2 py-1 text-sm" aria-label={t("crm.fields.owner")}>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
<button type="submit" name="intent" value="bulkReassign" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkReassign")}
</button>
</span>
<span className="flex items-end gap-1">
<select name="tagId" className="border-muted-foreground/40 rounded border px-2 py-1 text-sm" aria-label={t("crm.fields.tag")}>
{props.tagOptions.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
<button type="submit" name="intent" value="bulkTag" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkTag")}
</button>
</span>
</div>
<nav className="mt-4 flex items-center gap-4 text-sm" data-ui-id="ui.crm.list.pagination">
{data.pagination.hasPrev ? (
<a href={pageHref(props.baseHref, props.query, data.pagination.page - 1)} className="text-theme-600">
{t("crm.pagination.prev")}
</a>
) : null}
<span className="text-muted-foreground">
{t("crm.pagination.page", { page: data.pagination.page, pageCount: Math.max(data.pagination.pageCount, 1), total: data.pagination.total })}
</span>
{data.pagination.hasNext ? (
<a href={pageHref(props.baseHref, props.query, data.pagination.page + 1)} className="text-theme-600">
{t("crm.pagination.next")}
</a>
) : null}
</nav>
</form>
)}
</main>
);
}
@@ -1,57 +0,0 @@
import { useParams } from "react-router";
import { Fragment, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
import UrlUtils from "~/utils/app/UrlUtils";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { EntitySummaryDto } from "~/utils/services/appDashboardService";
import RowsList from "../entities/rows/RowsList";
import EntityIcon from "../layouts/icons/EntityIcon";
import ButtonSecondary from "../ui/buttons/ButtonSecondary";
import { RowsApi } from "~/utils/api/.server/RowsApi";
export default function EntitySummaries({ items, routes }: { items: EntitySummaryDto[]; routes: EntitiesApi.Routes }) {
return (
<Fragment>
{items
.sort((a, b) => a.order - b.order)
.map(({ rowsData }, idx) => {
return <LatestRows key={idx} rowsData={rowsData} routes={routes} />;
})}
</Fragment>
);
}
function LatestRows({ rowsData, routes }: { rowsData: RowsApi.GetRowsData; routes: EntitiesApi.Routes }) {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
const params = useParams();
const [listRoute, setListRoute] = useState<string>();
useEffect(() => {
const group = appOrAdminData.entityGroups.find((f) => f.entities.some((g) => g.entityId === rowsData.entity.id));
if (group) {
setListRoute(UrlUtils.currentTenantUrl(params, `g/${group.slug}/${rowsData.entity.slug}`));
} else {
const entity = appOrAdminData.entities.find((f) => f.id === rowsData.entity.id);
if (entity) {
setListRoute(UrlUtils.currentTenantUrl(params, entity.slug));
}
}
}, [appOrAdminData.entityGroups, appOrAdminData.entities, rowsData.entity.id, rowsData.entity.slug, params]);
return (
<div className="space-y-3 overflow-hidden p-1">
<div className="flex items-center justify-between space-x-2">
<div className="flex items-center space-x-2">
<EntityIcon className="h-5 w-5" icon={rowsData.entity.icon} />
<h3 className="text-foreground grow font-medium leading-4">{t("models.dashboard.latestEntity", { entity: t(rowsData.entity.titlePlural) })}</h3>
</div>
{listRoute && <ButtonSecondary to={listRoute}>{t("shared.viewAll")}</ButtonSecondary>}
</div>
<div className="flex space-x-2 overflow-x-scroll">
<RowsList entity={rowsData.entity} view={"card"} items={rowsData.items} routes={routes} />
</div>
</div>
);
}
@@ -1,123 +0,0 @@
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>
);
}
@@ -1,14 +0,0 @@
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/");
});
});
@@ -1,373 +0,0 @@
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>
);
}
@@ -1,174 +0,0 @@
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>
);
}
@@ -1,23 +0,0 @@
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"');
});
});
@@ -1,18 +0,0 @@
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");
});
});
@@ -1,109 +0,0 @@
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>
);
}
@@ -1,248 +0,0 @@
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>
</>
);
};
@@ -1,116 +0,0 @@
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>
)}
</>
}
/>
)}
</>
);
}
@@ -1,113 +0,0 @@
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>
)}
</>
);
}
@@ -1,377 +0,0 @@
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)} />
</>
);
}
@@ -1,77 +0,0 @@
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>
);
}
@@ -1,43 +0,0 @@
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>
);
}
@@ -1,84 +0,0 @@
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;
@@ -1,44 +0,0 @@
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>
);
}
@@ -1,21 +0,0 @@
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}
/>
);
}
@@ -1,220 +0,0 @@
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);
@@ -1,24 +0,0 @@
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>
)}
</>
);
}
@@ -1,76 +0,0 @@
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>
);
}
@@ -1,89 +0,0 @@
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>
);
}
@@ -1,259 +0,0 @@
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>
</>
);
};
@@ -1,20 +0,0 @@
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)`");
});
});
@@ -1,26 +0,0 @@
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");
});
});
@@ -1,119 +0,0 @@
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>
);
}
@@ -1,20 +0,0 @@
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)`");
});
});
@@ -1,229 +0,0 @@
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>
);
}
@@ -1,104 +0,0 @@
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>
);
}
@@ -1,20 +0,0 @@
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"');
});
});
@@ -1,32 +0,0 @@
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>
);
}
@@ -1,198 +0,0 @@
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>
);
}
@@ -1,75 +0,0 @@
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>
);
}
@@ -1,18 +0,0 @@
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>
);
}
@@ -1,30 +0,0 @@
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>
);
}
@@ -1,985 +0,0 @@
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);
@@ -1,133 +0,0 @@
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>
</>
)}
</>
);
}
@@ -1,86 +0,0 @@
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>
);
}
@@ -1,52 +0,0 @@
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>
);
}
@@ -1,139 +0,0 @@
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>
);
}
@@ -1,110 +0,0 @@
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>
);
}
@@ -1,290 +0,0 @@
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>
);
}
@@ -1,45 +0,0 @@
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()} />}</>;
}
@@ -1,191 +0,0 @@
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>
);
}
@@ -1,88 +0,0 @@
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>
);
}
@@ -1,165 +0,0 @@
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>
);
}
@@ -1,34 +0,0 @@
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>
);
}
@@ -1,492 +0,0 @@
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);
@@ -1,85 +0,0 @@
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>
);
}
@@ -1,534 +0,0 @@
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>
);
}
@@ -1,120 +0,0 @@
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>
);
}
@@ -1,86 +0,0 @@
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>
);
}
@@ -1,44 +0,0 @@
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} />
)}
</>
);
}
@@ -1,29 +0,0 @@
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>
);
}
@@ -1,53 +0,0 @@
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>}</>;
}
Loaded 100 of 3781 files, more files were not shown because too many files have changed in this diff. Show more