Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,43 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import IconWidgets from "~/components/layouts/icons/IconWidgets";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (params.tenant && !appConfiguration.widgets.enabled) {
|
||||
throw Response.json({ error: t("widgets.errors.disabled") }, { status: 400 });
|
||||
}
|
||||
return Response.json({});
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const params = useParams();
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("widgets.plural"),
|
||||
href: UrlUtils.getModulePath(params, `widgets`),
|
||||
exact: true,
|
||||
icon: <IconWidgets className="h-5 w-5" />,
|
||||
iconSelected: <IconWidgets className="h-5 w-5" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigation, useParams, useSubmit } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { ClipboardIcon } from "~/components/ui/icons/vendor";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import InputImage from "~/components/ui/input/InputImage";
|
||||
import InputMultipleText from "~/components/ui/input/InputMultipleText";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { WidgetDto } from "~/modules/widgets/dtos/WidgetDto";
|
||||
import WidgetUtils from "~/modules/widgets/utils/WidgetUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { defaultTheme, defaultThemes } from "~/utils/theme/defaultThemes";
|
||||
import { getAbsoluteUrl } from "~/utils/url.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
item: WidgetDto;
|
||||
widgetUrl: string;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
|
||||
const item = await db.widget.findFirst({
|
||||
where: { id: params.id, tenantId },
|
||||
});
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item: WidgetUtils.toDto(item),
|
||||
widgetUrl: `<script src="${getAbsoluteUrl(request, "/embed.js")}" data-widget-id="${item.id}" data-open-delay="-1" defer async />`,
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const item = await db.widget.findFirst({
|
||||
where: { id: params.id, tenantId },
|
||||
});
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() || "";
|
||||
const metadata = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: appConfiguration.widgets?.metadata || [],
|
||||
prefix: "metadata",
|
||||
});
|
||||
|
||||
if (name !== item.name) {
|
||||
const existing = await db.widget.findUnique({
|
||||
where: {
|
||||
tenantId_name: { tenantId, name },
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return Response.json({ error: t("widgets.errors.nameAlreadyTaken") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
try {
|
||||
const update = await db.widget.updateMany({
|
||||
where: { id: item.id, tenantId },
|
||||
data: {
|
||||
name,
|
||||
metadata: JSON.stringify(metadata),
|
||||
},
|
||||
});
|
||||
if (update.count !== 1) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
} else if (action === "edit-branding") {
|
||||
const themeColor = form.get("themeColor")?.toString();
|
||||
const themeScheme = form.get("themeScheme")?.toString();
|
||||
let logo = form.get("logo")?.toString();
|
||||
const position = form.get("position")?.toString();
|
||||
const placeholder = form.get("placeholder")?.toString();
|
||||
const hiddenInUrls = form.getAll("hiddenInUrls[]").map((f) => f.toString());
|
||||
const visibleInUrls = form.getAll("visibleInUrls[]").map((f) => f.toString());
|
||||
|
||||
const { storedLogo } = await promiseHash({
|
||||
storedLogo: logo
|
||||
? storeFile({
|
||||
bucket: "widgets",
|
||||
content: logo,
|
||||
id: `${item.id}-logo.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.widget.logo"),
|
||||
filename: `${item.id}-logo.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
});
|
||||
|
||||
const appearance: WidgetDto["appearance"] = {
|
||||
theme: themeColor || "",
|
||||
mode: themeScheme === "light" ? "light" : "dark",
|
||||
logo: storedLogo,
|
||||
position: position as any,
|
||||
hiddenInUrls,
|
||||
visibleInUrls,
|
||||
};
|
||||
const update = await db.widget.updateMany({
|
||||
where: { id: item.id, tenantId },
|
||||
data: {
|
||||
appearance: JSON.stringify(appearance),
|
||||
},
|
||||
});
|
||||
if (update.count !== 1) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
} else if (action === "delete") {
|
||||
await db.widget.deleteMany({
|
||||
where: { id: item.id, tenantId },
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration } = useRootData();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
const [item, setItem] = useState<WidgetDto>(data.item);
|
||||
|
||||
const navigation = useNavigation();
|
||||
const isDeleting = navigation.state === "submitting";
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const textToType = `${t("shared.delete")} ${data.item.name}`;
|
||||
const [typeToConfirm, setTypeToConfirm] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
setItem(data.item);
|
||||
}, [data.item]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onConfirmDelete() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.append("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={item.name}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: t("widgets.plural"),
|
||||
routePath: UrlUtils.getModulePath(params, `widgets`),
|
||||
},
|
||||
{
|
||||
title: data.item.name,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="pb-20">
|
||||
<SettingSection title={t("widgets.settings.details")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<Form method="post">
|
||||
<input hidden type="text" name="action" value="edit" readOnly />
|
||||
<div className="">
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-6 gap-2">
|
||||
<div className="col-span-6 sm:col-span-6 md:col-span-6">
|
||||
<label htmlFor="name" className="text-muted-foreground mb-1 block text-sm leading-5 font-medium">
|
||||
{t("shared.name")}
|
||||
</label>
|
||||
<Input name="name" required type="text" defaultValue={data.item.name} />
|
||||
</div>
|
||||
</div>
|
||||
<JsonPropertyValuesInput attributes={data.item.metadata} prefix="metadata" properties={appConfiguration.widgets.metadata || []} />
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<div className="flex justify-between">
|
||||
<div></div>
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* */}
|
||||
<SettingSection title={t("widgets.settings.embed.title")}>
|
||||
<div>
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("widgets.settings.embed.instructionBefore")} <code><head></code> {t("widgets.settings.embed.instructionAfter")}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className=""
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(data.widgetUrl);
|
||||
toast.success(t("shared.copied"));
|
||||
}}
|
||||
>
|
||||
<ClipboardIcon className="text-muted-foreground h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<InputText rows={2} className="bg-secondary" defaultValue={data.widgetUrl} readOnly />
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("widgets.settings.appearance.title")}>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="edit-branding" readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-6 sm:gap-x-3">
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="themeColor"
|
||||
title={t("widgets.settings.appearance.themeColor")}
|
||||
value={item.appearance.theme}
|
||||
setValue={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
theme: e?.toString() || "",
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("shared.select") + "..."}
|
||||
options={defaultThemes.map((item) => {
|
||||
const label = t(item.labelKey, { defaultValue: item.name });
|
||||
return {
|
||||
name: label,
|
||||
value: item.value,
|
||||
component: (
|
||||
<div className="flex items-center space-x-2">
|
||||
<div
|
||||
className={clsx(
|
||||
`theme-${item.value}`,
|
||||
"bg-primary text-primary inline-flex flex-shrink-0 items-center rounded-full text-xs font-medium"
|
||||
)}
|
||||
>
|
||||
<svg className={clsx("h-2 w-2")} fill="currentColor" viewBox="0 0 8 8">
|
||||
<circle cx={4} cy={4} r={3} />
|
||||
</svg>
|
||||
</div>
|
||||
<div>{label}</div>
|
||||
</div>
|
||||
),
|
||||
};
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="themeScheme"
|
||||
title={t("widgets.settings.appearance.themeScheme")}
|
||||
value={item.appearance.mode}
|
||||
setValue={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
mode: e === "light" ? "light" : "dark",
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("shared.select") + "..."}
|
||||
options={[
|
||||
{
|
||||
name: t("shared.light"),
|
||||
value: "light",
|
||||
},
|
||||
{
|
||||
name: t("shared.dark"),
|
||||
value: "dark",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="position"
|
||||
title={t("widgets.settings.appearance.position")}
|
||||
defaultValue={item.appearance.position}
|
||||
options={[
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.bottomRight"),
|
||||
value: "bottom-right",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.bottomLeft"),
|
||||
value: "bottom-left",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.topRight"),
|
||||
value: "top-right",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.topLeft"),
|
||||
value: "top-left",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-6">
|
||||
<InputImage name="logo" title={t("shared.logo")} defaultValue={item.appearance.logo || ""} />
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-3">
|
||||
<InputMultipleText
|
||||
name="hiddenInUrls[]"
|
||||
title={t("widgets.settings.appearance.hideInUrls")}
|
||||
value={item.appearance.hiddenInUrls}
|
||||
onChange={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
hiddenInUrls: e.map((i) => {
|
||||
i = i.trim();
|
||||
return "/" + UrlUtils.slugify(i);
|
||||
}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("widgets.settings.appearance.hideInUrlsPlaceholder")}
|
||||
separator="Enter"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-3">
|
||||
<InputMultipleText
|
||||
name="visibleInUrls[]"
|
||||
title={t("widgets.settings.appearance.onlyShowInUrls")}
|
||||
value={item.appearance.visibleInUrls}
|
||||
onChange={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
visibleInUrls: e.map((i) => {
|
||||
i = i.trim();
|
||||
return "/" + UrlUtils.slugify(i);
|
||||
}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("widgets.settings.appearance.onlyShowInUrlsPlaceholder")}
|
||||
separator="Enter"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")}>
|
||||
<div className="mt-12 space-y-2 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<InputText title={t("widgets.settings.danger.confirmDelete", { text: textToType })} value={typeToConfirm} setValue={setTypeToConfirm} />
|
||||
</div>
|
||||
<div>
|
||||
<ButtonPrimary
|
||||
disabled={typeToConfirm !== textToType || isDeleting}
|
||||
className={clsx(isDeleting && "base-spinner")}
|
||||
destructive={true}
|
||||
onClick={onDelete}
|
||||
>
|
||||
{t("shared.delete")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} destructive onYes={onConfirmDelete} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, Link, useParams, useSubmit } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import JsonPropertyValueCell from "~/modules/jsonProperties/components/JsonPropertyValueCell";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { WidgetDto } from "~/modules/widgets/dtos/WidgetDto";
|
||||
import WidgetUtils from "~/modules/widgets/utils/WidgetUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { AppConfiguration, getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { defaultTheme } from "~/utils/theme/defaultThemes";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
items: WidgetDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
|
||||
const data: LoaderData = {
|
||||
items: (await db.widget.findMany({ where: { tenantId } })).map((f) => WidgetUtils.toDto(f)),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "create") {
|
||||
const name = form.get("name")?.toString() || "";
|
||||
const metadata = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: appConfiguration.widgets?.metadata || [],
|
||||
prefix: "metadata",
|
||||
});
|
||||
const existing = await db.widget.findUnique({
|
||||
where: {
|
||||
tenantId_name: { tenantId, name },
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return Response.json({ error: t("widgets.errors.nameAlreadyTaken") }, { status: 400 });
|
||||
}
|
||||
const appearance: WidgetDto["appearance"] = {
|
||||
logo: null,
|
||||
theme: defaultTheme,
|
||||
mode: "light",
|
||||
position: "bottom-right",
|
||||
hiddenInUrls: [],
|
||||
visibleInUrls: [],
|
||||
};
|
||||
const item = await db.widget.create({
|
||||
data: {
|
||||
name,
|
||||
tenantId,
|
||||
metadata: JSON.stringify(metadata),
|
||||
appearance: JSON.stringify(appearance),
|
||||
},
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `widgets/${item.id}`));
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration } = useRootData();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const [addingWidget, setAddingWidget] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("widgets.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonPrimary onClick={() => setAddingWidget(true)}>{t("shared.new")}</ButtonPrimary>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute(idx, item) {
|
||||
return UrlUtils.getModulePath(params, `widgets/${item.id}`);
|
||||
},
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
title: t("shared.title"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<Link to={UrlUtils.getModulePath(params, `widgets/${item.id}`)} className="font-medium hover:underline">
|
||||
{item.name}
|
||||
</Link>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
...(appConfiguration.widgets.metadata
|
||||
?.filter((f) => !f.hideInTable)
|
||||
.map((f) => ({
|
||||
name: f.name,
|
||||
title: f.title,
|
||||
value: (item: WidgetDto) => {
|
||||
return <JsonPropertyValueCell property={f} value={item.metadata ? item.metadata[f.name] : null} />;
|
||||
},
|
||||
})) || []),
|
||||
{
|
||||
title: t("widgets.appearance"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<ShowPayloadModalButton description={t("widgets.appearance")} payload={JSON.stringify(item.appearance)} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("shared.created"),
|
||||
value: (item) => <DateCell date={item.createdAt} />,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
|
||||
<AddWidgetModal appConfiguration={appConfiguration} open={addingWidget} onClose={() => setAddingWidget(false)} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function AddWidgetModal({ appConfiguration, open, onClose }: { appConfiguration: AppConfiguration; open: boolean; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState({ name: "" });
|
||||
|
||||
return (
|
||||
<Modal open={open} setOpen={onClose} size="md">
|
||||
<Form method="post" className="inline-block w-full overflow-hidden bg-white p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="create" readOnly hidden />
|
||||
<div className="mt-3 text-center sm:mt-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("widgets.create")}</h3>
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
<InputText
|
||||
title={t("shared.name")}
|
||||
value={state.name}
|
||||
setValue={(e) => setState({ ...state, name: e.toString() })}
|
||||
type="text"
|
||||
name="name"
|
||||
id="name"
|
||||
placeholder={t("shared.name")}
|
||||
required
|
||||
/>
|
||||
<JsonPropertyValuesInput attributes={{}} prefix="metadata" properties={appConfiguration.widgets.metadata || []} />
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<button
|
||||
type="submit"
|
||||
className={clsx(
|
||||
"inline-flex w-full justify-center rounded-md border border-transparent px-4 py-2 text-base font-medium text-white shadow-sm focus:ring-2 focus:ring-offset-2 focus:outline-none sm:col-start-2 sm:text-sm",
|
||||
"bg-foreground text-background"
|
||||
)}
|
||||
>
|
||||
{t("shared.create")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="border-border hover:bg-secondary text-muted-foreground mt-3 inline-flex w-full justify-center rounded-md border bg-white px-4 py-2 text-base font-medium shadow-sm focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 focus:outline-none sm:col-start-1 sm:mt-0 sm:text-sm"
|
||||
onClick={onClose}
|
||||
>
|
||||
{t("shared.back")}
|
||||
</button>
|
||||
</div>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const widgetsRouteDirectory = resolveRepoPath("apps/web/app/routes/app.$tenant/__widgets/widgets");
|
||||
|
||||
function readRoute(fileName: string) {
|
||||
return fs.readFileSync(path.join(widgetsRouteDirectory, fileName), "utf8");
|
||||
}
|
||||
|
||||
describe("tenant widget route auth boundaries", () => {
|
||||
it("requires tenant auth and permissions before listing or creating widgets", () => {
|
||||
const source = readRoute("index.tsx");
|
||||
|
||||
expect(source).toContain('import { requireAuth } from "~/utils/loaders.middleware";');
|
||||
expect(source).toMatch(/export const loader[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.view", tenantId\);/);
|
||||
expect(source).toMatch(/export const action[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.update", tenantId\);/);
|
||||
});
|
||||
|
||||
it("requires tenant auth and tenant-scopes widget mutations by id and tenant", () => {
|
||||
const source = readRoute("$id.tsx");
|
||||
|
||||
expect(source).toContain('import { requireAuth } from "~/utils/loaders.middleware";');
|
||||
expect(source).toMatch(/export const loader[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.view", tenantId\);/);
|
||||
expect(source).toMatch(/export const action[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.update", tenantId\);/);
|
||||
expect(source).toContain("findFirst({\n where: { id: params.id, tenantId },");
|
||||
expect(source).toContain("updateMany({\n where: { id: item.id, tenantId },");
|
||||
expect(source).toContain("deleteMany({\n where: { id: item.id, tenantId },");
|
||||
expect(source).not.toContain("db.widget.update({");
|
||||
expect(source).not.toContain("db.widget.delete({");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user