Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowNewRoute from "~/modules/rows/components/RowNewRoute";
|
||||
import { Rows_New } from "~/modules/rows/routes/Rows_New.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_New.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_New.action(args);
|
||||
|
||||
export default () => <RowNewRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Relationships } from "~/modules/rows/routes/Rows_Relationships.server";
|
||||
import RowsRelationshipsRoute from "~/modules/rows/components/RowsRelationshipsRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Relationships.loader(args);
|
||||
|
||||
export default () => <RowsRelationshipsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowsViewRoute from "~/modules/rows/components/RowsViewRoute";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_List.LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<RowsViewRoute
|
||||
key={data.rowsData.entity.id}
|
||||
rowsData={data.rowsData}
|
||||
items={data.rowsData.items}
|
||||
routes={data.routes}
|
||||
saveCustomViews={true}
|
||||
permissions={{
|
||||
create: getUserHasPermission(appOrAdminData, getEntityPermission(data.rowsData.entity, "create")),
|
||||
}}
|
||||
currentSession={{
|
||||
user: appOrAdminData.user,
|
||||
isSuperAdmin: appOrAdminData.isSuperAdmin,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+5
-5
@@ -13,7 +13,7 @@ const portalMutationHandlers = [
|
||||
"routes/app.$tenant/__portals/portals.$portal/pages.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pages/$name.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.new.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.stripe.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.paymentProvider.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/settings.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/users.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/users/new.tsx",
|
||||
@@ -25,13 +25,13 @@ const portalPricingLoaders = [
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.edit.$product.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.new.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.stripe.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.paymentProvider.tsx",
|
||||
];
|
||||
|
||||
const portalPricingHandlers = [
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.edit.$product.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.new.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.stripe.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.paymentProvider.tsx",
|
||||
];
|
||||
|
||||
const portalDomainHandlers = ["routes/app.$tenant/__portals/portals.$portal/domains.tsx"];
|
||||
@@ -52,7 +52,7 @@ const portalReadLoaders = [
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.edit.$product.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.new.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.stripe.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.paymentProvider.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/settings.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/users.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/users/new.tsx",
|
||||
@@ -106,7 +106,7 @@ describe("portal route authorization boundary", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps portal pricing loaders read-only when Stripe lookup fails", () => {
|
||||
test("keeps portal pricing loaders read-only when billing provider lookup fails", () => {
|
||||
for (const relativePath of portalPricingLoaders) {
|
||||
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
|
||||
const loaderStart = source.indexOf("loader = async");
|
||||
|
||||
+2
-2
@@ -26,11 +26,11 @@ describe("portal list i18n", () => {
|
||||
const source = fs.readFileSync(configurationPath, "utf8");
|
||||
|
||||
expect(source).toContain("models.portal.seo");
|
||||
expect(source).toContain("models.portal.pages.errors.stripeAccountMissing");
|
||||
expect(source).toContain("models.portal.pages.errors.paymentAccountMissing");
|
||||
expect(source).toContain("models.portal.pages.errors.privacyPolicyContentMissing");
|
||||
expect(source).toContain("models.portal.pages.errors.termsContentMissing");
|
||||
expect(source).not.toContain('group: "SEO"');
|
||||
expect(source).not.toContain("No Stripe account connected");
|
||||
expect(source).not.toContain("No Payment provider account connected");
|
||||
expect(source).not.toContain("No privacy policy content");
|
||||
expect(source).not.toContain("No terms and conditions content");
|
||||
});
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { AnalyticsEvent, AnalyticsUniqueVisitor, Portal, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { AnalyticsEvent, AnalyticsUniqueVisitor, Portal, Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { LoaderFunction, useLoaderData } from "react-router";
|
||||
import { useParams, useSearchParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { AnalyticsPageView, AnalyticsUniqueVisitor, Portal, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { AnalyticsPageView, AnalyticsUniqueVisitor, Portal, Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { LoaderFunction, useLoaderData } from "react-router";
|
||||
import { useParams, useSearchParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ describe("portal analytics overview route DB boundary", () => {
|
||||
it("uses the package analytics overview helper", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).toContain("@hivegrid/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsOverview");
|
||||
expect(source).toContain("withUsers: false");
|
||||
expect(source).toContain("portalId: item.id");
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import AnalyticsOverview from "~/components/analytics/AnalyticsOverview";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { defaultAnalyticsPeriod, getAnalyticsOverview, isAnalyticsPeriod, type AnalyticsOverview as AnalyticsOverviewDto } from "@toolctrl/db/analytics.server";
|
||||
import { defaultAnalyticsPeriod, getAnalyticsOverview, isAnalyticsPeriod, type AnalyticsOverview as AnalyticsOverviewDto } from "@hivegrid/db/analytics.server";
|
||||
import PeriodHelper, { PeriodFilters, defaultPeriodFilter } from "~/utils/helpers/PeriodHelper";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { AnalyticsUniqueVisitor, Portal, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { AnalyticsUniqueVisitor, Portal, Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { LoaderFunction, useLoaderData } from "react-router";
|
||||
import { useParams, useSearchParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
+2
-2
@@ -86,13 +86,13 @@ export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const seoTitle = form.get("seoTitle")?.toString();
|
||||
const seoDescription = form.get("seoDescription")?.toString();
|
||||
const seoImage = form.get("seoImage")?.toString();
|
||||
const stripeAccountId = form.get("stripeAccountId")?.toString();
|
||||
const paymentProviderAccountId = form.get("paymentProviderAccountId")?.toString();
|
||||
|
||||
await updatePortal(item, {
|
||||
seoTitle: seoTitle || null,
|
||||
seoDescription: seoDescription || null,
|
||||
seoImage: seoImage || null,
|
||||
stripeAccountId: stripeAccountId || null,
|
||||
paymentProviderAccountId: paymentProviderAccountId || null,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { createPortalPage, deletePortalPage, getPortalPagesByName, updatePortalPage } from "~/modules/portals/db/portalPages.db.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { PortalPageConfigDto } from "~/utils/db/appPortalConfiguration.db.server";
|
||||
import { Portal, PortalPage } from "@toolctrl/db/prisma-browser";
|
||||
import { Portal, PortalPage } from "@hivegrid/db/prisma-browser";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ import PortalPricingServer from "~/modules/portals/services/PortalPricing.server
|
||||
import toast from "react-hot-toast";
|
||||
import { useParams } from "react-router";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { Portal } from "@toolctrl/db/prisma-browser";
|
||||
import { Portal } from "@hivegrid/db/prisma-browser";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requirePortalMutationAccess, requirePortalPricingEnabled, requirePortalReadAccess } from "../portalAccess.server";
|
||||
@@ -99,7 +99,7 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
|
||||
const plan: SubscriptionProductDto = {
|
||||
id: params.product,
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
order,
|
||||
title,
|
||||
description,
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
}
|
||||
|
||||
const plan: SubscriptionProductDto = {
|
||||
stripeId: "",
|
||||
billingProviderId: "",
|
||||
order,
|
||||
title,
|
||||
model,
|
||||
|
||||
-269
@@ -1,269 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useParams, useSubmit } from "react-router";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import type Stripe from "stripe";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { PortalWithDetails, getPortalById, updatePortal } from "~/modules/portals/db/portals.db.server";
|
||||
import StripeConnectUtils from "~/modules/portals/utils/StripeConnectUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import StripeConnectServer from "~/modules/portals/services/StripeConnect.server";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getAbsoluteCurrentUrl, getAbsoluteUrl } from "~/utils/url.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { requirePortalMutationAccess, requirePortalPricingEnabled, requirePortalReadAccess } from "../portalAccess.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails;
|
||||
stripeAccount: Stripe.Account | null;
|
||||
};
|
||||
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalPricingEnabled({ request, tenantId });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
let stripeAccount: Stripe.Account | null = null;
|
||||
try {
|
||||
stripeAccount = item.stripeAccountId ? await StripeConnectServer.getStripeAccount(item.stripeAccountId) : null;
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e.message);
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
stripeAccount,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
|
||||
function portalPricingPath(params: { portal?: string }, portal: { subdomain?: string | null }) {
|
||||
return UrlUtils.getModulePath(params, `portals/${portal.subdomain || params.portal}/pricing`);
|
||||
}
|
||||
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalPricingEnabled({ request, tenantId });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
const userInfo = await getUserInfo(request);
|
||||
const user = await getUser(userInfo.userId);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
if (action === "connectStripe") {
|
||||
try {
|
||||
const country = form.get("country") as string;
|
||||
if (!country) {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.countryRequired") }, { status: 400 });
|
||||
}
|
||||
const stripeAccount = await StripeConnectServer.createStripeAccount({
|
||||
email: user!.email,
|
||||
country,
|
||||
metadata: {
|
||||
tenantId: portal.tenantId ?? "{admin}",
|
||||
},
|
||||
});
|
||||
await updatePortal(portal, {
|
||||
stripeAccountId: stripeAccount.id,
|
||||
});
|
||||
portal.stripeAccountId = stripeAccount.id;
|
||||
|
||||
const stripeAccountLink = await StripeConnectServer.createStripeAccountLink({
|
||||
account: portal.stripeAccountId,
|
||||
return_url: getAbsoluteUrl(request, portalPricingPath(params, portal)),
|
||||
refresh_url: getAbsoluteCurrentUrl(request),
|
||||
});
|
||||
return redirect(stripeAccountLink.url);
|
||||
} catch {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.connectFailed") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "reconnectStripe") {
|
||||
try {
|
||||
if (!portal.stripeAccountId) {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.accountNotFound") }, { status: 400 });
|
||||
}
|
||||
const stripeAccount = await StripeConnectServer.getStripeAccount(portal.stripeAccountId);
|
||||
if (!stripeAccount) {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.accountNotFoundWithId", { id: portal.stripeAccountId }) }, { status: 400 });
|
||||
}
|
||||
await updatePortal(portal, {
|
||||
stripeAccountId: stripeAccount.id,
|
||||
});
|
||||
portal.stripeAccountId = stripeAccount.id;
|
||||
const stripeAccountLink = await StripeConnectServer.createStripeAccountLink({
|
||||
account: portal.stripeAccountId,
|
||||
return_url: getAbsoluteUrl(request, portalPricingPath(params, portal)),
|
||||
refresh_url: getAbsoluteCurrentUrl(request),
|
||||
});
|
||||
return redirect(stripeAccountLink.url);
|
||||
} catch {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.reconnectFailed") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "deleteStripe") {
|
||||
try {
|
||||
if (!portal.stripeAccountId) {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.accountNotFound") }, { status: 400 });
|
||||
}
|
||||
await updatePortal(portal, {
|
||||
stripeAccountId: null,
|
||||
});
|
||||
await StripeConnectServer.deleteStripeAccount(portal.stripeAccountId);
|
||||
return Response.json({ success: t("models.portal.stripe.success.accountDeleted") });
|
||||
} catch {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.disconnectFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t, i18n } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
const stripeConnectCountries = useMemo(() => StripeConnectUtils.getLocalizedStripeConnectCountries(i18n.language), [i18n.language]);
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
confirmDelete.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "deleteStripe");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.portal.stripe.connect.title")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
// {
|
||||
// title: t("models.portal.plural"),
|
||||
// routePath: UrlUtils.getModulePath(params, "portals"),
|
||||
// },
|
||||
{
|
||||
title: data.item.title,
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.item.subdomain}`),
|
||||
},
|
||||
{
|
||||
title: t("models.portal.pricing.title"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.item.subdomain}/pricing`),
|
||||
},
|
||||
{
|
||||
title: t("models.portal.stripe.title"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
{!data.stripeAccount ? (
|
||||
<div className="space-y-2">
|
||||
<p className="">{t("models.portal.stripe.connect.description")}</p>
|
||||
<Form method="post" className="space-y-2">
|
||||
<input type="hidden" name="action" value="connectStripe" />
|
||||
<div className="w-40">
|
||||
<InputSelect
|
||||
name="country"
|
||||
title={t("models.portal.stripe.country")}
|
||||
placeholder={t("shared.select")}
|
||||
options={stripeConnectCountries}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<LoadingButton
|
||||
className="focus:ring-opacity-50 bg-[#5433FF] text-white hover:bg-[#4F2DFF] focus:ring-[#5433FF] active:bg-[#4F2DFF]"
|
||||
type="submit"
|
||||
>
|
||||
{t("models.portal.stripe.connect.action")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
) : !data.stripeAccount.charges_enabled ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<XIcon className="h-6 w-6 text-red-500" />
|
||||
<div className="text-lg font-medium">{t("models.portal.stripe.pending.title")}</div>
|
||||
</div>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="reconnectStripe" />
|
||||
<LoadingButton
|
||||
className="focus:ring-opacity-50 bg-[#5433FF] hover:bg-[#4F2DFF] focus:ring-[#5433FF] active:bg-[#4F2DFF]"
|
||||
type="submit"
|
||||
actionName="reconnectStripe"
|
||||
>
|
||||
{t("models.portal.stripe.reconnect")}
|
||||
</LoadingButton>
|
||||
</Form>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Form method="post" onSubmit={onDelete}>
|
||||
<input type="hidden" name="action" value="deleteStripe" />
|
||||
<ButtonSecondary destructive type="submit">
|
||||
{t("models.portal.stripe.disconnect")}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<CheckIcon className="h-6 w-6 text-green-500" />
|
||||
<div className="text-lg font-medium">{t("models.portal.stripe.connected")}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Form method="post" onSubmit={onDelete}>
|
||||
<input type="hidden" name="action" value="deleteStripe" />
|
||||
<ButtonSecondary destructive type="submit">
|
||||
{t("models.portal.stripe.disconnect")}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
+1
-35
@@ -1,23 +1,19 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
import { EyeIcon } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Stripe from "stripe";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import GearIcon from "~/components/ui/icons/GearIcon";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getAllPortalSubscriptionProductsWithUsers } from "~/modules/portals/db/portalSubscriptionProducts.db.server";
|
||||
import { PortalWithDetails, getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import StripeConnectServer from "~/modules/portals/services/StripeConnect.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
@@ -25,7 +21,6 @@ import { requirePortalPricingEnabled, requirePortalReadAccess } from "../portalA
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails;
|
||||
stripeAccount: Stripe.Account | null;
|
||||
items: SubscriptionProductDto[];
|
||||
portalUrl: string;
|
||||
publicPricingUrl: string;
|
||||
@@ -42,21 +37,10 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
let stripeAccount: Stripe.Account | null = null;
|
||||
try {
|
||||
stripeAccount = item.stripeAccountId ? await StripeConnectServer.getStripeAccount(item.stripeAccountId) : null;
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e.message);
|
||||
}
|
||||
if (stripeAccount && !stripeAccount.charges_enabled) {
|
||||
// return redirect(UrlUtils.getModulePath(params, `portals/${item.subdomain || params.portal}/pricing/stripe`));
|
||||
}
|
||||
const portalUrl = PortalServer.getPortalUrl(item);
|
||||
const items = await getAllPortalSubscriptionProductsWithUsers(item.id);
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
stripeAccount,
|
||||
items: items.sort((x, y) => {
|
||||
return x?.order > y?.order ? 1 : -1;
|
||||
}),
|
||||
@@ -77,9 +61,6 @@ export default function () {
|
||||
withHome={false}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonSecondary to="stripe">
|
||||
<GearIcon className="h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
<ButtonSecondary to={data.publicPricingUrl} target="_blank">
|
||||
<EyeIcon className="h-4 w-4" />
|
||||
<div>{t("shared.preview")}</div>
|
||||
@@ -102,21 +83,6 @@ export default function () {
|
||||
},
|
||||
]}
|
||||
>
|
||||
{data.stripeAccount === null ? (
|
||||
<WarningBanner title={t("models.portal.stripe.notConnected.title")}>
|
||||
{t("models.portal.stripe.notConnected.description")}{" "}
|
||||
<Link to={UrlUtils.getModulePath(params, `portals/${data.item.subdomain}/pricing/stripe`)} className="underline">
|
||||
{t("models.portal.stripe.notConnected.action")}
|
||||
</Link>
|
||||
</WarningBanner>
|
||||
) : !data.stripeAccount.charges_enabled ? (
|
||||
<WarningBanner title={t("models.portal.stripe.pending.title")}>
|
||||
{t("models.portal.stripe.pending.description")}{" "}
|
||||
<Link to={UrlUtils.getModulePath(params, `portals/${data.item.subdomain}/pricing/stripe`)} className="underline">
|
||||
{t("models.portal.stripe.pending.action")}
|
||||
</Link>
|
||||
</WarningBanner>
|
||||
) : null}
|
||||
<div>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
|
||||
+1
-1
@@ -96,7 +96,7 @@ export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
domain: domain || null,
|
||||
title,
|
||||
isPublished: isPublished || true,
|
||||
stripeAccountId: null,
|
||||
paymentProviderAccountId: null,
|
||||
metadata,
|
||||
themeColor: themeColor || null,
|
||||
themeScheme: themeScheme || null,
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { loadWebConfig } from "@toolctrl/config";
|
||||
import { loadWebConfig } from "@hivegrid/config";
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { badRequestResponse, leadActionErrorResponse, loadLeadContext, requireLeadPermission } from "~/utils/integrations/leads/leadAccess.server";
|
||||
import { auditLeadEvent } from "~/utils/integrations/leads/leadAudit.server";
|
||||
import { leadAntiSpamAdminPath, LEADS_MODULE_KEY } from "~/utils/integrations/leads/leadRoutePaths";
|
||||
import { getLeadAntiSpamConfig, updateLeadAntiSpamConfig, type LeadAntiSpamConfigRow, type LeadAntiSpamMode } from "~/utils/integrations/leads/leadService.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { config: LeadAntiSpamConfigRow };
|
||||
const MODES = new Set<LeadAntiSpamMode>(["quarantine", "spam"]);
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
||||
requireLeadPermission(ctx, "leads.admin");
|
||||
return Response.json({ config: await getLeadAntiSpamConfig(ctx.tenantId) } satisfies LoaderData);
|
||||
};
|
||||
|
||||
function intValue(form: FormData, name: string): number | undefined {
|
||||
const value = Number.parseInt(form.get(name)?.toString() ?? "", 10);
|
||||
return Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
||||
requireLeadPermission(ctx, "leads.admin");
|
||||
const form = await request.formData();
|
||||
if (form.get("intent")?.toString() !== "save") throw badRequestResponse();
|
||||
const mode = form.get("mode")?.toString() as LeadAntiSpamMode | undefined;
|
||||
if (!mode || !MODES.has(mode)) throw badRequestResponse();
|
||||
try {
|
||||
const config = await updateLeadAntiSpamConfig({
|
||||
tenantId: ctx.tenantId,
|
||||
mode,
|
||||
perSourcePerHourLimit: intValue(form, "perSourcePerHourLimit"),
|
||||
perIpPerHourLimit: intValue(form, "perIpPerHourLimit"),
|
||||
anomalySpikeFactor: intValue(form, "anomalySpikeFactor"),
|
||||
lostAutoDeleteDays: intValue(form, "lostAutoDeleteDays"),
|
||||
disposableDomainEnabled: form.get("disposableDomainEnabled") === "on",
|
||||
honeypotEnabled: form.get("honeypotEnabled") === "on",
|
||||
fastSubmitEnabled: form.get("fastSubmitEnabled") === "on",
|
||||
});
|
||||
await auditLeadEvent({ ctx, action: "lead.anti_spam_updated", targetType: "lead_anti_spam", targetId: config.id });
|
||||
return redirect(leadAntiSpamAdminPath(params.tenant ?? ""));
|
||||
} catch (error) {
|
||||
return leadActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function LeadAntiSpamRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { config } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.leads.antiSpam">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("leads.antiSpam.title")}</h1>
|
||||
{actionData?.error ? <p className="mt-4 text-sm text-red-600">{t(actionData.error)}</p> : null}
|
||||
<Form method="post" className="mt-6 grid gap-4 rounded-md border p-4">
|
||||
<input type="hidden" name="intent" value="save" />
|
||||
<label className="grid gap-1 text-sm">{t("leads.antiSpam.field.mode")}<select name="mode" defaultValue={config.mode} className="rounded border px-3 py-2">{Array.from(MODES).map((mode) => <option key={mode} value={mode}>{t(`leads.antiSpam.mode.${mode}`)}</option>)}</select></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.antiSpam.field.perSource")}<input name="perSourcePerHourLimit" type="number" defaultValue={config.perSourcePerHourLimit} className="rounded border px-3 py-2" /></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.antiSpam.field.perIp")}<input name="perIpPerHourLimit" type="number" defaultValue={config.perIpPerHourLimit} className="rounded border px-3 py-2" /></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.antiSpam.field.spike")}<input name="anomalySpikeFactor" type="number" defaultValue={config.anomalySpikeFactor} className="rounded border px-3 py-2" /></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.antiSpam.field.lostDelete")}<input name="lostAutoDeleteDays" type="number" defaultValue={config.lostAutoDeleteDays} className="rounded border px-3 py-2" /></label>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" name="disposableDomainEnabled" defaultChecked={config.disposableDomainEnabled} />{t("leads.antiSpam.field.disposable")}</label>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" name="honeypotEnabled" defaultChecked={config.honeypotEnabled} />{t("leads.antiSpam.field.honeypot")}</label>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" name="fastSubmitEnabled" defaultChecked={config.fastSubmitEnabled} />{t("leads.antiSpam.field.fastSubmit")}</label>
|
||||
<button className="bg-foreground text-background rounded px-4 py-2 text-sm font-medium">{t("leads.actions.save")}</button>
|
||||
</Form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: LEADS_MODULE_KEY };
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { badRequestResponse, leadActionErrorResponse, loadLeadContext, requireLeadPermission } from "~/utils/integrations/leads/leadAccess.server";
|
||||
import { auditLeadEvent } from "~/utils/integrations/leads/leadAudit.server";
|
||||
import { leadSourcesAdminPath, LEADS_MODULE_KEY } from "~/utils/integrations/leads/leadRoutePaths";
|
||||
import { listLeadSources, upsertLeadSource, type LeadSourceRow } from "~/utils/integrations/leads/leadService.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { sources: LeadSourceRow[] };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
||||
requireLeadPermission(ctx, "leads.admin");
|
||||
return Response.json({ sources: await listLeadSources(ctx.tenantId) } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
||||
requireLeadPermission(ctx, "leads.admin");
|
||||
const form = await request.formData();
|
||||
if (form.get("intent")?.toString() !== "upsert") throw badRequestResponse();
|
||||
try {
|
||||
const source = await upsertLeadSource({
|
||||
tenantId: ctx.tenantId,
|
||||
key: form.get("key")?.toString() ?? "",
|
||||
name: form.get("name")?.toString() ?? "",
|
||||
displayLabel: form.get("displayLabel")?.toString(),
|
||||
defaultZustaendigerUserId: form.get("defaultZustaendigerUserId")?.toString() || null,
|
||||
});
|
||||
await auditLeadEvent({ ctx, action: "lead.source_created", targetType: "lead_source", targetId: source.id });
|
||||
return redirect(leadSourcesAdminPath(params.tenant ?? ""));
|
||||
} catch (error) {
|
||||
return leadActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function LeadSourcesRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { sources } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.leads.sources">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("leads.sources.title")}</h1>
|
||||
{actionData?.error ? <p className="mt-4 text-sm text-red-600">{t(actionData.error)}</p> : null}
|
||||
<Form method="post" className="mt-6 grid gap-3 rounded-md border p-4">
|
||||
<input type="hidden" name="intent" value="upsert" />
|
||||
<label className="grid gap-1 text-sm">{t("leads.sources.field.key")}<input name="key" className="rounded border px-3 py-2" /></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.sources.field.name")}<input name="name" className="rounded border px-3 py-2" /></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.sources.field.displayLabel")}<input name="displayLabel" className="rounded border px-3 py-2" /></label>
|
||||
<button className="bg-foreground text-background rounded px-4 py-2 text-sm font-medium">{t("leads.sources.actions.save")}</button>
|
||||
</Form>
|
||||
<ul className="mt-6 grid gap-2 text-sm">{sources.map((source) => <li key={source.id} className="rounded border p-3">{source.displayLabel}</li>)}</ul>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: LEADS_MODULE_KEY };
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
import { useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
archivePipeline,
|
||||
createPipeline,
|
||||
duplicatePipeline,
|
||||
ensureDefaultSalesPipeline,
|
||||
listPipelines,
|
||||
updatePipeline,
|
||||
upsertPipelineAccess,
|
||||
upsertPipelineFieldConfig,
|
||||
upsertPipelineFieldVisibility,
|
||||
} from "~/utils/integrations/projects/projectService.server";
|
||||
import { upsertAuftragPipelineStageConfig } from "~/utils/integrations/projects/auftragService.server";
|
||||
import { loadProjectContext, projectActionErrorResponse, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import type { CreatePipelineStageInput, PipelinePrincipalType, PipelineRow, PipelineStageRow, PipelineTypHint } from "~/utils/integrations/projects/projectService.server";
|
||||
|
||||
type LoaderData = { pipelines: Array<PipelineRow & { stages: PipelineStageRow[] }> };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
await ensureDefaultSalesPipeline({ tenantId: ctx.tenantId, userId: ctx.userId });
|
||||
const pipelines = await listPipelines({ tenantId: ctx.tenantId });
|
||||
return Response.json({ pipelines } satisfies LoaderData);
|
||||
}
|
||||
|
||||
function formString(formData: FormData, name: string): string | null {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function formBoolean(formData: FormData, name: string): boolean | undefined {
|
||||
const value = formString(formData, name);
|
||||
if (value === null) return undefined;
|
||||
return value === "true" || value === "1" || value === "on";
|
||||
}
|
||||
|
||||
function formNumber(formData: FormData, name: string): number | undefined {
|
||||
const value = formString(formData, name);
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
function formStages(formData: FormData): CreatePipelineStageInput[] {
|
||||
const raw = formString(formData, "stages");
|
||||
if (!raw) return [];
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((stage): stage is CreatePipelineStageInput => typeof stage === "object" && stage !== null && "name" in stage && "stageKind" in stage);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const formData = await request.formData();
|
||||
const intent = formString(formData, "_action");
|
||||
try {
|
||||
if (intent === "createPipeline") {
|
||||
const pipeline = await createPipeline({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
name: formString(formData, "name") ?? "",
|
||||
typHint: (formString(formData, "typHint") as PipelineTypHint | null) ?? "custom",
|
||||
position: formNumber(formData, "position"),
|
||||
stages: formStages(formData),
|
||||
});
|
||||
return Response.json({ ok: true, pipeline });
|
||||
}
|
||||
if (intent === "updatePipeline") {
|
||||
const pipeline = await updatePipeline({
|
||||
tenantId: ctx.tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
name: formString(formData, "name"),
|
||||
position: formNumber(formData, "position"),
|
||||
typHint: formString(formData, "typHint") as PipelineTypHint | null,
|
||||
});
|
||||
return Response.json({ ok: true, pipeline });
|
||||
}
|
||||
if (intent === "archivePipeline") {
|
||||
const pipeline = await archivePipeline({ tenantId: ctx.tenantId, pipelineId: formString(formData, "pipelineId") ?? "" });
|
||||
return Response.json({ ok: true, pipeline });
|
||||
}
|
||||
if (intent === "duplicatePipeline") {
|
||||
const pipeline = await duplicatePipeline({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
name: formString(formData, "name") ?? "",
|
||||
});
|
||||
return Response.json({ ok: true, pipeline });
|
||||
}
|
||||
if (intent === "upsertAccess") {
|
||||
await upsertPipelineAccess({
|
||||
tenantId: ctx.tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
principalType: formString(formData, "principalType") as PipelinePrincipalType,
|
||||
principalId: formString(formData, "principalId") ?? "",
|
||||
kannSehen: formBoolean(formData, "kannSehen"),
|
||||
kannBearbeiten: formBoolean(formData, "kannBearbeiten"),
|
||||
});
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
if (intent === "upsertFieldConfig") {
|
||||
await upsertPipelineFieldConfig({
|
||||
tenantId: ctx.tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageId: formString(formData, "stageId"),
|
||||
fieldKey: formString(formData, "fieldKey") ?? "",
|
||||
sichtbar: formBoolean(formData, "sichtbar"),
|
||||
pflicht: formBoolean(formData, "pflicht"),
|
||||
reihenfolge: formNumber(formData, "reihenfolge"),
|
||||
});
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
if (intent === "upsertFieldVisibility") {
|
||||
await upsertPipelineFieldVisibility({
|
||||
tenantId: ctx.tenantId,
|
||||
fieldConfigId: formString(formData, "fieldConfigId") ?? "",
|
||||
principalType: formString(formData, "principalType") as PipelinePrincipalType,
|
||||
principalId: formString(formData, "principalId") ?? "",
|
||||
kannSehen: formBoolean(formData, "kannSehen"),
|
||||
kannBearbeiten: formBoolean(formData, "kannBearbeiten"),
|
||||
});
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
if (intent === "upsertAuftragStageConfig") {
|
||||
await upsertAuftragPipelineStageConfig({
|
||||
tenantId: ctx.tenantId,
|
||||
pipelineId: formString(formData, "pipelineId") ?? "",
|
||||
stageId: formString(formData, "stageId") ?? "",
|
||||
requiresAcceptanceProtocol: formBoolean(formData, "requiresAcceptanceProtocol"),
|
||||
acceptanceFormTemplateId: formString(formData, "acceptanceFormTemplateId"),
|
||||
autoArchiveAfterDays: formNumber(formData, "autoArchiveAfterDays") ?? null,
|
||||
});
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export default function PipelinesAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-2xl font-semibold">{t("projects.pipelines.title")}</h1>
|
||||
</header>
|
||||
<section className="grid gap-4">
|
||||
{data.pipelines.map((pipeline) => (
|
||||
<article key={pipeline.id} className="rounded-md border bg-background p-4">
|
||||
<h2 className="font-semibold">{pipeline.name}</h2>
|
||||
<p className="text-sm text-muted-foreground">{pipeline.typHint}</p>
|
||||
<ol className="mt-3 flex flex-wrap gap-2">
|
||||
{pipeline.stages.map((stage) => (
|
||||
<li key={stage.id} className="rounded-md border px-3 py-1 text-sm">
|
||||
{stage.name} · {stage.stageKind}
|
||||
<form className="mt-2 grid gap-2" method="post">
|
||||
<input type="hidden" name="_action" value="upsertAuftragStageConfig" />
|
||||
<input type="hidden" name="pipelineId" value={pipeline.id} />
|
||||
<input type="hidden" name="stageId" value={stage.id} />
|
||||
<label className="flex items-center gap-2">
|
||||
<input name="requiresAcceptanceProtocol" type="checkbox" />
|
||||
{t("projects.fields.requiresAcceptanceProtocol")}
|
||||
</label>
|
||||
<input className="rounded-md border px-2 py-1" name="acceptanceFormTemplateId" placeholder={t("projects.fields.acceptanceFormTemplateId")} />
|
||||
<input className="rounded-md border px-2 py-1" name="autoArchiveAfterDays" placeholder={t("projects.fields.autoArchiveAfterDays")} type="number" />
|
||||
<button className="rounded-md border px-2 py-1" type="submit">
|
||||
{t("projects.actions.saveAuftragConfig")}
|
||||
</button>
|
||||
</form>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { archiveLostReason, listLostReasons, upsertLostReason } from "~/utils/integrations/projects/projectService.server";
|
||||
import { loadProjectContext, projectActionErrorResponse, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import type { LostReasonRow } from "~/utils/integrations/projects/projectService.server";
|
||||
|
||||
type LoaderData = { reasons: LostReasonRow[] };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const reasons = await listLostReasons({ tenantId: ctx.tenantId });
|
||||
return Response.json({ reasons } satisfies LoaderData);
|
||||
}
|
||||
|
||||
function formString(formData: FormData, name: string): string | null {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function formNumber(formData: FormData, name: string): number | undefined {
|
||||
const value = formString(formData, name);
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const formData = await request.formData();
|
||||
const intent = formString(formData, "_action");
|
||||
try {
|
||||
if (intent === "upsertLostReason") {
|
||||
const reason = await upsertLostReason({
|
||||
tenantId: ctx.tenantId,
|
||||
reasonId: formString(formData, "reasonId"),
|
||||
name: formString(formData, "name") ?? "",
|
||||
position: formNumber(formData, "position"),
|
||||
});
|
||||
return Response.json({ ok: true, reason });
|
||||
}
|
||||
if (intent === "archiveLostReason") {
|
||||
const reason = await archiveLostReason({ tenantId: ctx.tenantId, reasonId: formString(formData, "reasonId") ?? "" });
|
||||
return Response.json({ ok: true, reason });
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export default function LostReasonsAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-2xl font-semibold">{t("projects.lostReasons.title")}</h1>
|
||||
</header>
|
||||
<ul className="rounded-md border bg-background">
|
||||
{data.reasons.map((reason) => (
|
||||
<li key={reason.id} className="border-b px-4 py-3 last:border-b-0">
|
||||
{reason.name}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import { Form, useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
listAcceptanceFormTemplates,
|
||||
upsertAcceptanceFormTemplate,
|
||||
type AcceptanceFormTemplateRow,
|
||||
} from "~/utils/integrations/projects/auftragService.server";
|
||||
import { loadProjectContext, projectActionErrorResponse, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
|
||||
type LoaderData = { templates: AcceptanceFormTemplateRow[] };
|
||||
|
||||
function formString(formData: FormData, name: string): string | null {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function formBoolean(formData: FormData, name: string): boolean | undefined {
|
||||
const value = formString(formData, name);
|
||||
if (value === null) return undefined;
|
||||
return value === "true" || value === "1" || value === "on";
|
||||
}
|
||||
|
||||
function parseJsonObject(value: string | null): unknown {
|
||||
if (!value) return {};
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
return typeof parsed === "object" && parsed !== null ? parsed : {};
|
||||
}
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const templates = await listAcceptanceFormTemplates({ tenantId: ctx.tenantId });
|
||||
return Response.json({ templates } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const formData = await request.formData();
|
||||
const intent = formString(formData, "_action");
|
||||
try {
|
||||
if (intent === "upsertAcceptanceFormTemplate") {
|
||||
const template = await upsertAcceptanceFormTemplate({
|
||||
tenantId: ctx.tenantId,
|
||||
templateId: formString(formData, "templateId"),
|
||||
name: formString(formData, "name") ?? "",
|
||||
formId: formString(formData, "formId"),
|
||||
definition: parseJsonObject(formString(formData, "definition")),
|
||||
isDefault: formBoolean(formData, "isDefault"),
|
||||
});
|
||||
return Response.json({ ok: true, template });
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export default function AcceptanceFormsAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-4xl flex-col gap-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-2xl font-semibold">{t("projects.acceptanceForms.title")}</h1>
|
||||
</header>
|
||||
<section className="grid gap-3">
|
||||
{data.templates.map((template) => (
|
||||
<article key={template.id} className="rounded-md border bg-background p-4">
|
||||
<h2 className="font-semibold">{template.name}</h2>
|
||||
<p className="text-sm text-muted-foreground">{template.formId ?? t("projects.acceptanceForms.noForm")}</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<Form className="grid gap-3 rounded-md border bg-background p-4" method="post">
|
||||
<input type="hidden" name="_action" value="upsertAcceptanceFormTemplate" />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="name" placeholder={t("projects.fields.templateName")} />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="formId" placeholder={t("projects.fields.formId")} />
|
||||
<textarea className="min-h-28 rounded-md border px-3 py-2 text-sm" name="definition" placeholder={t("projects.fields.definitionJson")} />
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input name="isDefault" type="checkbox" />
|
||||
{t("projects.fields.isDefault")}
|
||||
</label>
|
||||
<button className="rounded-md bg-primary px-3 py-2 text-sm text-primary-foreground" type="submit">
|
||||
{t("projects.actions.saveTemplate")}
|
||||
</button>
|
||||
</Form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { Form, useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { listProjectTemplates, upsertProjectTemplate, type ProjectTemplateRow } from "~/utils/integrations/projects/auftragService.server";
|
||||
import { loadProjectContext, projectActionErrorResponse, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
|
||||
type LoaderData = { templates: ProjectTemplateRow[] };
|
||||
|
||||
function formString(formData: FormData, name: string): string | null {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function parseJsonArray(value: string | null): unknown {
|
||||
if (!value) return [];
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
}
|
||||
|
||||
function parseJsonObject(value: string | null): unknown {
|
||||
if (!value) return {};
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
|
||||
}
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const templates = await listProjectTemplates({ tenantId: ctx.tenantId });
|
||||
return Response.json({ templates } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const formData = await request.formData();
|
||||
const intent = formString(formData, "_action");
|
||||
try {
|
||||
if (intent === "upsertProjectTemplate") {
|
||||
const template = await upsertProjectTemplate({
|
||||
tenantId: ctx.tenantId,
|
||||
templateId: formString(formData, "templateId"),
|
||||
name: formString(formData, "name") ?? "",
|
||||
defaultPipelineId: formString(formData, "defaultPipelineId"),
|
||||
defaultStageId: formString(formData, "defaultStageId"),
|
||||
defaultMembers: parseJsonArray(formString(formData, "defaultMembers")),
|
||||
defaultTasks: parseJsonArray(formString(formData, "defaultTasks")),
|
||||
customFields: parseJsonObject(formString(formData, "customFields")),
|
||||
});
|
||||
return Response.json({ ok: true, template });
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export default function ProjectTemplatesAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-4xl flex-col gap-6 p-6">
|
||||
<header>
|
||||
<h1 className="text-2xl font-semibold">{t("projects.templates.title")}</h1>
|
||||
</header>
|
||||
<section className="grid gap-3">
|
||||
{data.templates.map((template) => (
|
||||
<article key={template.id} className="rounded-md border bg-background p-4">
|
||||
<h2 className="font-semibold">{template.name}</h2>
|
||||
<p className="text-sm text-muted-foreground">{template.defaultPipelineId ?? t("projects.templates.noPipeline")}</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<Form className="grid gap-3 rounded-md border bg-background p-4" method="post">
|
||||
<input type="hidden" name="_action" value="upsertProjectTemplate" />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="name" placeholder={t("projects.fields.templateName")} />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="defaultPipelineId" placeholder={t("projects.fields.defaultPipelineId")} />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="defaultStageId" placeholder={t("projects.fields.defaultStageId")} />
|
||||
<textarea className="min-h-20 rounded-md border px-3 py-2 text-sm" name="defaultMembers" placeholder={t("projects.fields.defaultMembersJson")} />
|
||||
<textarea className="min-h-20 rounded-md border px-3 py-2 text-sm" name="defaultTasks" placeholder={t("projects.fields.defaultTasksJson")} />
|
||||
<textarea className="min-h-20 rounded-md border px-3 py-2 text-sm" name="customFields" placeholder={t("projects.fields.customFieldsJson")} />
|
||||
<button className="rounded-md bg-primary px-3 py-2 text-sm text-primary-foreground" type="submit">
|
||||
{t("projects.actions.saveTemplate")}
|
||||
</button>
|
||||
</Form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
import { Form, Link, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { handleAutomationEditorAction, loadAutomationEditorVM, type AutomationEditorActionData, type AutomationEditorVM } from "~/services/automation/automation.server";
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationEditorVM({ request, params }));
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
return Response.json(await handleAutomationEditorAction({ request, params }));
|
||||
}
|
||||
|
||||
export default function AutomationEditorRoute() {
|
||||
const data = useLoaderData() as AutomationEditorVM;
|
||||
const actionData = useActionData() as AutomationEditorActionData | undefined;
|
||||
const { t } = useTranslation();
|
||||
const lastStepKey = data.flow.steps[data.flow.steps.length - 1]?.stepKey ?? "";
|
||||
const firstStepKey = data.flow.steps[0]?.stepKey ?? "";
|
||||
const secondStepKey = data.flow.steps[1]?.stepKey ?? "";
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-7xl flex-col gap-6 p-6">
|
||||
<header className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Link className="text-theme-600 text-sm font-medium" to={data.rule.executionsUrl}>
|
||||
{t("automation.editor.backToExecutions")}
|
||||
</Link>
|
||||
<h1 className="text-foreground text-2xl font-semibold">{data.rule.name}</h1>
|
||||
<p className="text-muted-foreground text-sm">{data.rule.description ?? t("automation.editor.noDescription")}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Form method="post">
|
||||
<button className="rounded-md border px-3 py-2 text-sm font-medium" name="intent" value="auto-layout" type="submit">
|
||||
{t("automation.editor.actions.autoLayout")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post">
|
||||
<button className="rounded-md border px-3 py-2 text-sm font-medium" name="intent" value="undo" type="submit" disabled={data.flow.history.past.length === 0}>
|
||||
{t("automation.editor.actions.undo")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post">
|
||||
<button className="rounded-md border px-3 py-2 text-sm font-medium" name="intent" value="redo" type="submit" disabled={data.flow.history.future.length === 0}>
|
||||
{t("automation.editor.actions.redo")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post">
|
||||
<button className="bg-foreground text-background rounded-md px-3 py-2 text-sm font-medium" name="intent" value="activate" type="submit" disabled={!data.validation.canActivate}>
|
||||
{t("automation.editor.actions.activate")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post">
|
||||
<button className="rounded-md border px-3 py-2 text-sm font-medium" name="intent" value="pause" type="submit">
|
||||
{t("automation.editor.actions.pause")}
|
||||
</button>
|
||||
</Form>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{actionData ? (
|
||||
<section className={`rounded-lg border px-4 py-3 text-sm ${actionData.ok ? "border-emerald-200 bg-emerald-50 text-emerald-900" : "border-red-200 bg-red-50 text-red-900"}`}>
|
||||
{t(actionData.ok ? actionData.messageKey : actionData.errorKey)}
|
||||
{actionData.ok === false && actionData.detail ? <span className="ml-1">{t(actionData.detail)}</span> : null}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<section className="grid gap-4 lg:grid-cols-[280px_1fr_320px]">
|
||||
<aside className="flex flex-col gap-3 rounded-lg border p-4">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.editor.catalog.title")}</h2>
|
||||
<div className="flex flex-col gap-2">
|
||||
{data.catalog.map((node) => (
|
||||
<Form className="rounded-md border px-3 py-2" key={node.key} method="post">
|
||||
<input type="hidden" name="intent" value="add-node" />
|
||||
<input type="hidden" name="nodeType" value={node.key} />
|
||||
<input type="hidden" name="parentStepKey" value={lastStepKey} />
|
||||
<button className="flex w-full flex-col text-left" type="submit">
|
||||
<span className="text-foreground text-sm font-medium">{t(node.titleKey)}</span>
|
||||
<span className="text-muted-foreground text-xs">{node.group}</span>
|
||||
</button>
|
||||
</Form>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section className="flex min-h-[520px] flex-col gap-3 rounded-lg border p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.editor.graph.title")}</h2>
|
||||
<span className="text-muted-foreground text-xs">{t("automation.editor.graph.status", { count: data.flow.steps.length })}</span>
|
||||
</div>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{data.flow.steps.map((step) => (
|
||||
<article className="rounded-lg border px-4 py-3" key={step.stepKey}>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="text-foreground text-sm font-semibold">{t(step.summaryKey, { defaultValue: step.nodeType })}</h3>
|
||||
<p className="text-muted-foreground text-xs">{step.stepKey}</p>
|
||||
</div>
|
||||
<span className="text-muted-foreground text-xs">{step.kind}</span>
|
||||
</div>
|
||||
<dl className="mt-3 grid grid-cols-2 gap-2 text-xs">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">{t("automation.editor.graph.parents")}</dt>
|
||||
<dd className="text-foreground">{step.parentStepIds.join(", ") || t("automation.values.notAvailable")}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">{t("automation.editor.graph.position")}</dt>
|
||||
<dd className="text-foreground">
|
||||
{step.position.x}/{step.position.y}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<Form method="post">
|
||||
<input type="hidden" name="stepKey" value={step.stepKey} />
|
||||
<button className="text-theme-600 text-xs font-medium" name="intent" value="duplicate-node" type="submit">
|
||||
{t("automation.editor.actions.duplicate")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="stepKey" value={step.stepKey} />
|
||||
<button className="text-red-600 text-xs font-medium" name="intent" value="delete-node" type="submit">
|
||||
{t("automation.editor.actions.delete")}
|
||||
</button>
|
||||
</Form>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside className="flex flex-col gap-4">
|
||||
<section className="rounded-lg border p-4">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.editor.validation.title")}</h2>
|
||||
{data.validation.issues.length === 0 ? (
|
||||
<p className="text-muted-foreground mt-2 text-sm">{t("automation.editor.validation.clean")}</p>
|
||||
) : (
|
||||
<ul className="mt-2 flex flex-col gap-2">
|
||||
{data.validation.issues.map((issue, index) => (
|
||||
<li className="text-sm text-red-700" key={`${issue.code}-${issue.stepKey ?? "flow"}-${index}`}>
|
||||
{t(issue.messageKey)}
|
||||
{issue.detail ? <span className="text-muted-foreground ml-1">{issue.detail}</span> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="rounded-lg border p-4">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.editor.connections.title")}</h2>
|
||||
<Form className="mt-3 flex flex-col gap-2" method="post">
|
||||
<select className="rounded-md border px-3 py-2 text-sm" name="fromStepKey" defaultValue={firstStepKey}>
|
||||
{data.flow.steps.map((step) => (
|
||||
<option key={step.stepKey} value={step.stepKey}>
|
||||
{step.stepKey}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select className="rounded-md border px-3 py-2 text-sm" name="toStepKey" defaultValue={secondStepKey}>
|
||||
{data.flow.steps.map((step) => (
|
||||
<option key={step.stepKey} value={step.stepKey}>
|
||||
{step.stepKey}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="flex gap-2">
|
||||
<button className="rounded-md border px-3 py-2 text-sm font-medium" name="intent" value="connect" type="submit">
|
||||
{t("automation.editor.actions.connect")}
|
||||
</button>
|
||||
<button className="rounded-md border px-3 py-2 text-sm font-medium" name="intent" value="disconnect" type="submit">
|
||||
{t("automation.editor.actions.disconnect")}
|
||||
</button>
|
||||
</div>
|
||||
</Form>
|
||||
</section>
|
||||
|
||||
<section className="rounded-lg border p-4">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.editor.dryRun.title")}</h2>
|
||||
<Form className="mt-3 flex flex-col gap-2" method="post">
|
||||
<input className="rounded-md border px-3 py-2 text-sm" min="0" name="matchedRecords" type="number" defaultValue="0" />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="confirmationPhrase" placeholder={t("automation.editor.dryRun.confirmationPhrase")} />
|
||||
<button className="rounded-md border px-3 py-2 text-sm font-medium" name="intent" value="dry-run" type="submit">
|
||||
{t("automation.editor.actions.dryRun")}
|
||||
</button>
|
||||
</Form>
|
||||
{actionData?.dryRunPreview ? (
|
||||
<div className="mt-3 rounded-md bg-muted/40 p-3 text-sm">
|
||||
<p className="font-medium">{t("automation.editor.dryRun.records", { count: actionData.dryRunPreview.matchedRecords })}</p>
|
||||
<ul className="mt-2 flex flex-col gap-1">
|
||||
{actionData.dryRunPreview.steps.map((step) => (
|
||||
<li key={step.stepKey}>{t(step.effectKey, { node: step.nodeType })}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="rounded-lg border p-4">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.editor.templates.title")}</h2>
|
||||
<Form className="mt-3 flex flex-col gap-2" method="post">
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="templateName" placeholder={t("automation.editor.templates.namePlaceholder")} />
|
||||
<input type="hidden" name="category" value="operations" />
|
||||
<button className="rounded-md border px-3 py-2 text-sm font-medium" name="intent" value="create-template" type="submit">
|
||||
{t("automation.editor.actions.createTemplate")}
|
||||
</button>
|
||||
</Form>
|
||||
<Link className="text-theme-600 mt-3 block text-sm font-medium" to={data.templatesUrl}>
|
||||
{t("automation.editor.templates.openCatalog")}
|
||||
</Link>
|
||||
</section>
|
||||
</aside>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loadAutomationExecutionDetailVM, type AutomationExecutionDetailVM } from "~/services/automation/automation.server";
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationExecutionDetailVM({ request, params }));
|
||||
}
|
||||
|
||||
export default function AutomationExecutionDetailRoute() {
|
||||
const data = useLoaderData() as AutomationExecutionDetailVM;
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-6">
|
||||
<header className="flex flex-col gap-2">
|
||||
<h1 className="text-foreground text-2xl font-semibold">{data.rule.name}</h1>
|
||||
<p className="text-muted-foreground text-sm">{data.execution.summaryText}</p>
|
||||
</header>
|
||||
|
||||
<section className="grid gap-3 md:grid-cols-4">
|
||||
<DetailCard label={t("automation.detail.status")} value={t(`automation.status.${data.execution.status}`, { defaultValue: data.execution.status })} />
|
||||
<DetailCard label={t("automation.detail.trigger")} value={data.execution.triggerKey} />
|
||||
<DetailCard label={t("automation.detail.mode")} value={data.execution.dryRun ? t("automation.values.dryRun") : t("automation.values.liveRun")} />
|
||||
<DetailCard label={t("automation.detail.reverseWindow")} value={data.execution.reverseWindowExpiresAt ?? t("automation.values.notAvailable")} />
|
||||
</section>
|
||||
|
||||
<section className="overflow-hidden rounded-lg border">
|
||||
<div className="border-b px-4 py-3">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.sections.steps")}</h2>
|
||||
</div>
|
||||
<div className="divide-y">
|
||||
{data.steps.map((step) => (
|
||||
<div className="grid gap-2 px-4 py-3 md:grid-cols-[1fr_140px_120px]" key={step.id}>
|
||||
<span>
|
||||
<span className="text-foreground block text-sm font-medium">{step.summaryText}</span>
|
||||
<span className="text-muted-foreground block text-xs">{step.nodeType}</span>
|
||||
</span>
|
||||
<span className="text-muted-foreground text-sm">{t(`automation.status.${step.status}`, { defaultValue: step.status })}</span>
|
||||
<span className="text-muted-foreground text-sm">{step.durationMs == null ? t("automation.values.notAvailable") : `${step.durationMs} ms`}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="overflow-hidden rounded-lg border">
|
||||
<div className="border-b px-4 py-3">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.editor.reverse.title")}</h2>
|
||||
</div>
|
||||
<div className="grid gap-3 px-4 py-3 md:grid-cols-[1fr_220px]">
|
||||
<div>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{data.reversePlan.canReverse ? t("automation.editor.reverse.available") : t("automation.editor.reverse.expired")}
|
||||
</p>
|
||||
<div className="mt-3 divide-y rounded-md border">
|
||||
{data.reversePlan.items.map((item) => (
|
||||
<div className="grid gap-2 px-3 py-2 text-sm md:grid-cols-[1fr_140px]" key={`${item.stepKey}-${item.actionKey}`}>
|
||||
<span>
|
||||
<span className="text-foreground block font-medium">{t(item.actionKey)}</span>
|
||||
<span className="text-muted-foreground block text-xs">{item.nodeType}</span>
|
||||
</span>
|
||||
<span className={item.reversible ? "text-emerald-700" : "text-muted-foreground"}>
|
||||
{item.reversible ? t("automation.editor.reverse.reversible") : t("automation.editor.reverse.notReversible")}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-md bg-muted/40 p-3">
|
||||
<div className="text-muted-foreground text-xs">{t("automation.editor.reverse.confirmation")}</div>
|
||||
<div className="text-foreground mt-1 text-sm font-semibold">{data.reversePlan.confirmationPhrase}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailCard({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="rounded-lg border px-4 py-3">
|
||||
<div className="text-muted-foreground text-xs">{label}</div>
|
||||
<div className="text-foreground mt-1 text-sm font-medium">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { Link, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loadAutomationExecutionsVM, type AutomationExecutionListVM } from "~/services/automation/automation.server";
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationExecutionsVM({ request, params }));
|
||||
}
|
||||
|
||||
export default function AutomationExecutionsRoute() {
|
||||
const data = useLoaderData() as AutomationExecutionListVM;
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-6">
|
||||
<header className="flex flex-col gap-2">
|
||||
<h1 className="text-foreground text-2xl font-semibold">{data.rule.name}</h1>
|
||||
<p className="text-muted-foreground text-sm">{t("automation.executions.subtitle", { trigger: data.rule.triggerKey ?? t("automation.values.noTrigger") })}</p>
|
||||
</header>
|
||||
|
||||
<section className="overflow-hidden rounded-lg border">
|
||||
<div className="border-b px-4 py-3">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.sections.executions")}</h2>
|
||||
</div>
|
||||
{data.executions.length === 0 ? (
|
||||
<div className="text-muted-foreground px-4 py-8 text-sm">{t("automation.empty.executions")}</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{data.executions.map((execution) => (
|
||||
<Link className="hover:bg-muted/40 grid gap-2 px-4 py-3 md:grid-cols-[1fr_140px_120px_180px]" key={execution.id} to={execution.detailUrl}>
|
||||
<span>
|
||||
<span className="text-foreground block text-sm font-medium">{execution.summaryText}</span>
|
||||
<span className="text-muted-foreground block text-xs">{execution.triggerKey}</span>
|
||||
</span>
|
||||
<span className="text-muted-foreground text-sm">{t(`automation.status.${execution.status}`, { defaultValue: execution.status })}</span>
|
||||
<span className="text-muted-foreground text-sm">{execution.dryRun ? t("automation.values.dryRun") : t("automation.values.liveRun")}</span>
|
||||
<span className="text-muted-foreground text-sm">{execution.createdAt}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { Link, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loadAutomationListVM, type AutomationListVM } from "~/services/automation/automation.server";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationListVM({ request, params }));
|
||||
}
|
||||
|
||||
export default function AutomationsIndexRoute() {
|
||||
const data = useLoaderData() as AutomationListVM;
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-6">
|
||||
<header className="flex flex-col gap-2">
|
||||
<h1 className="text-foreground text-2xl font-semibold">{t("automation.title")}</h1>
|
||||
<p className="text-muted-foreground text-sm">{t("automation.subtitle")}</p>
|
||||
<Link className="text-theme-600 text-sm font-medium" to={appPath({ tenantSlug: data.tenantSlug, path: "automations/templates", mode: "host-aware" })}>
|
||||
{t("automation.templatesPage.title")}
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
<section className="grid gap-3 md:grid-cols-3">
|
||||
<MetricCard label={t("automation.metrics.triggers")} value={String(data.triggers.length)} />
|
||||
<MetricCard label={t("automation.metrics.actions")} value={String(data.actions.length)} />
|
||||
<MetricCard label={t("automation.metrics.templates")} value={String(data.templates.length)} />
|
||||
</section>
|
||||
|
||||
<section className="overflow-hidden rounded-lg border">
|
||||
<div className="border-b px-4 py-3">
|
||||
<h2 className="text-foreground text-sm font-semibold">{t("automation.sections.rules")}</h2>
|
||||
</div>
|
||||
{data.rules.length === 0 ? (
|
||||
<div className="text-muted-foreground px-4 py-8 text-sm">{t("automation.empty.rules")}</div>
|
||||
) : (
|
||||
<div className="divide-y">
|
||||
{data.rules.map((rule) => (
|
||||
<Link className="hover:bg-muted/40 grid gap-2 px-4 py-3 md:grid-cols-[1fr_160px_120px_140px_120px]" key={rule.id} to={rule.editUrl}>
|
||||
<span>
|
||||
<span className="text-foreground block text-sm font-medium">{rule.name}</span>
|
||||
<span className="text-muted-foreground block text-xs">{rule.triggerKey ?? t("automation.values.noTrigger")}</span>
|
||||
</span>
|
||||
<span className="text-muted-foreground text-sm">{t(`automation.status.${rule.status}`, { defaultValue: rule.status })}</span>
|
||||
<span className="text-muted-foreground text-sm">{rule.runs30d}</span>
|
||||
<span className="text-muted-foreground text-sm">{rule.lastExecutionAt ?? t("automation.values.never")}</span>
|
||||
<span className="text-theme-600 text-sm">{t("automation.editor.actions.openEditor")}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCard({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="rounded-lg border px-4 py-3">
|
||||
<div className="text-muted-foreground text-xs">{label}</div>
|
||||
<div className="text-foreground mt-1 text-2xl font-semibold">{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { Form, Link, redirect, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { createAutomationRuleFromTemplateForRoute, loadAutomationTemplateCatalogVM, type AutomationTemplateCatalogVM } from "~/services/automation/automation.server";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationTemplateCatalogVM({ request, params }));
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const formData = await request.formData();
|
||||
const intent = String(formData.get("intent") ?? "");
|
||||
if (intent === "use-template") {
|
||||
const result = await createAutomationRuleFromTemplateForRoute({
|
||||
request,
|
||||
params,
|
||||
templateId: String(formData.get("templateId") ?? ""),
|
||||
name: String(formData.get("ruleName") ?? "").trim() || undefined,
|
||||
});
|
||||
return redirect(result.editUrl);
|
||||
}
|
||||
return redirect(appPath({ tenantSlug: params.tenant ?? "", path: "automations/templates", mode: "host-aware" }));
|
||||
}
|
||||
|
||||
export default function AutomationTemplatesRoute() {
|
||||
const data = useLoaderData() as AutomationTemplateCatalogVM;
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 p-6">
|
||||
<header className="flex flex-col gap-2">
|
||||
<Link className="text-theme-600 text-sm font-medium" to="../">
|
||||
{t("automation.templatesPage.back")}
|
||||
</Link>
|
||||
<h1 className="text-foreground text-2xl font-semibold">{t("automation.templatesPage.title")}</h1>
|
||||
<p className="text-muted-foreground text-sm">{t("automation.templatesPage.subtitle")}</p>
|
||||
</header>
|
||||
|
||||
<section className="grid gap-4 md:grid-cols-2">
|
||||
{data.templates.map((template) => (
|
||||
<article className="rounded-lg border p-4" key={template.id}>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-foreground text-sm font-semibold">{t(template.name, { defaultValue: template.name })}</h2>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{template.description ? t(template.description, { defaultValue: template.description }) : t("automation.templatesPage.noDescription")}</p>
|
||||
</div>
|
||||
<span className="text-muted-foreground text-xs">{template.isTenantTemplate ? t("automation.templatesPage.tenantTemplate") : t("automation.templatesPage.platformTemplate")}</span>
|
||||
</div>
|
||||
<dl className="mt-4 grid grid-cols-2 gap-3 text-xs">
|
||||
<div>
|
||||
<dt className="text-muted-foreground">{t("automation.templatesPage.category")}</dt>
|
||||
<dd className="text-foreground">{template.category}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-muted-foreground">{t("automation.templatesPage.useCount")}</dt>
|
||||
<dd className="text-foreground">{template.useCount}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<Form className="mt-4 flex flex-col gap-2" method="post">
|
||||
<input type="hidden" name="intent" value="use-template" />
|
||||
<input type="hidden" name="templateId" value={template.id} />
|
||||
<input className="rounded-md border px-3 py-2 text-sm" name="ruleName" placeholder={t("automation.templatesPage.ruleNamePlaceholder")} />
|
||||
<button className="bg-foreground text-background rounded-md px-3 py-2 text-sm font-medium" type="submit">
|
||||
{t("automation.templatesPage.useTemplate")}
|
||||
</button>
|
||||
</Form>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
// AK-P16b · booking detail route (M06 Block D). Shows the appointment + intake
|
||||
// answers and exposes the lifecycle actions (held / no-show / cancel / reschedule
|
||||
// / re-assign). The final picker UI waits for David D-P16, but the server action
|
||||
// contract is complete. Owner-checked (read_own sees only own; write/admin acts),
|
||||
// CSRF on every mutation.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData, Form } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { loadBookingContext, requireBookingPermission, requireAppointmentOwner, BOOKING_PERMISSIONS } from "~/modules/booking/routes/bookingAccess.server";
|
||||
import { BOOKING_MODULE_KEY, bookingsListPath, notFoundResponse } from "~/modules/booking/routes/bookingRoutePaths";
|
||||
import { getAppointmentDetail } from "~/modules/booking/db/booking.db.server";
|
||||
import { markAppointmentHeld, markAppointmentNoShow, cancelAppointment, rescheduleAppointment, reassignAppointment } from "~/modules/booking/services/BookingLifecycleService.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
interface DetailVM {
|
||||
id: string;
|
||||
status: string;
|
||||
statusKey: string;
|
||||
whenLabel: string;
|
||||
pageTitle: string;
|
||||
customerName: string;
|
||||
customerEmail: string;
|
||||
intake: { key: string; value: string }[];
|
||||
cancellationReason: string | null;
|
||||
canAct: boolean;
|
||||
}
|
||||
|
||||
type LoaderData = { title: string; vm: DetailVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadBookingContext({ request, params, requireModule: true });
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn);
|
||||
|
||||
const appt = await getAppointmentDetail(ctx.tenantId, params.id ?? "");
|
||||
if (!appt) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
requireAppointmentOwner(ctx, appt.providerUserId);
|
||||
|
||||
const vm: DetailVM = {
|
||||
id: appt.id,
|
||||
status: appt.status,
|
||||
statusKey: `bookings.status.${appt.status}`,
|
||||
whenLabel: new Date(appt.startAt).toLocaleString(),
|
||||
pageTitle: appt.pageTitle,
|
||||
customerName: appt.customerName,
|
||||
customerEmail: appt.customerEmail,
|
||||
intake: Object.entries(appt.intakeAnswers).map(([key, value]) => ({ key, value: value === null ? "" : String(value) })),
|
||||
cancellationReason: appt.cancellationReason,
|
||||
canAct: ctx.permissions.includes(BOOKING_PERMISSIONS.write) || ctx.permissions.includes(BOOKING_PERMISSIONS.admin),
|
||||
};
|
||||
return Response.json({ title: `${t("bookings.detail.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadBookingContext({ request, params, requireModule: true });
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const appt = await getAppointmentDetail(ctx.tenantId, params.id ?? "");
|
||||
if (!appt) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
requireAppointmentOwner(ctx, appt.providerUserId);
|
||||
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent");
|
||||
if (intent === "held") {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.write);
|
||||
await markAppointmentHeld(ctx.tenantId, appt.id, ctx.userId);
|
||||
} else if (intent === "no_show") {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.write);
|
||||
await markAppointmentNoShow(ctx.tenantId, appt.id, ctx.userId);
|
||||
} else if (intent === "cancel") {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.write);
|
||||
await cancelAppointment({ tenantId: ctx.tenantId, appointmentId: appt.id, reason: (form.get("reason") as string | null)?.trim() || "—", byKind: "provider", actorUserId: ctx.userId });
|
||||
} else if (intent === "reschedule") {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.write);
|
||||
const newStartAt = new Date((form.get("newStartAt") as string | null) ?? "");
|
||||
if (Number.isNaN(newStartAt.getTime())) {
|
||||
return Response.json({ ok: false, error: "bookings.error.invalidSlot" }, { status: 400 });
|
||||
}
|
||||
await rescheduleAppointment({ tenantId: ctx.tenantId, appointmentId: appt.id, newStartAt, actorUserId: ctx.userId });
|
||||
} else if (intent === "reassign") {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
|
||||
const newProviderUserId = (form.get("newProviderUserId") as string | null)?.trim();
|
||||
if (!newProviderUserId) {
|
||||
return Response.json({ ok: false, error: "bookings.error.providerRequired" }, { status: 400 });
|
||||
}
|
||||
await reassignAppointment({ tenantId: ctx.tenantId, appointmentId: appt.id, newProviderUserId, actorUserId: ctx.userId });
|
||||
}
|
||||
return redirect(bookingsListPath(params.tenant ?? ""));
|
||||
};
|
||||
|
||||
export default function BookingDetailRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const rootData = useRootData();
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.booking.detail">
|
||||
<h1 className="text-foreground text-xl font-semibold">{vm.pageTitle}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">
|
||||
{vm.whenLabel} · {t(vm.statusKey)}
|
||||
</p>
|
||||
|
||||
<section className="mt-6">
|
||||
<h2 className="font-medium">{t("bookings.detail.customer")}</h2>
|
||||
<p>
|
||||
{vm.customerName} {vm.customerEmail ? `· ${vm.customerEmail}` : ""}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{vm.intake.length > 0 ? (
|
||||
<section className="mt-4">
|
||||
<h2 className="font-medium">{t("bookings.detail.intake")}</h2>
|
||||
<dl className="mt-1 text-sm">
|
||||
{vm.intake.map((entry) => (
|
||||
<div key={entry.key} className="flex gap-2">
|
||||
<dt className="text-muted-foreground">{entry.key}</dt>
|
||||
<dd>{entry.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{vm.cancellationReason ? <p className="mt-4 text-sm text-red-600">{vm.cancellationReason}</p> : null}
|
||||
|
||||
{vm.canAct && vm.status === "scheduled" ? (
|
||||
<section className="mt-8 flex flex-wrap gap-3" data-ui-id="ui.booking.detail.actions">
|
||||
<Form method="post">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="intent" value="held" />
|
||||
<button type="submit" className="rounded border px-3 py-1">
|
||||
{t("bookings.actions.markHeld")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="intent" value="no_show" />
|
||||
<button type="submit" className="rounded border px-3 py-1">
|
||||
{t("bookings.actions.markNoShow")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post" className="flex items-center gap-2">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="intent" value="cancel" />
|
||||
<input name="reason" placeholder={t("bookings.actions.cancelReason")} className="rounded border px-2 py-1 text-sm" />
|
||||
<button type="submit" className="rounded border border-red-300 px-3 py-1 text-red-600">
|
||||
{t("bookings.actions.cancel")}
|
||||
</button>
|
||||
</Form>
|
||||
</section>
|
||||
) : null}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: BOOKING_MODULE_KEY };
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
// AK-P16b · bookings list route (M06 Block C). Loader builds BookingListVM from the
|
||||
// tenant's appointments, server-side owner-filtered (read_own → own provider rows
|
||||
// only, DoD 6). Module off -> locked empty; missing bookings.read_own -> 404.
|
||||
// Baseline functional table (data-ui-id markers); bespoke polish follows D-P16.
|
||||
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildBookingListVM, bookingStatusKey, type BookingListRow, type BookingListVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadBookingContext, requireBookingPermission, canReadAllBookings, BOOKING_PERMISSIONS } from "~/modules/booking/routes/bookingAccess.server";
|
||||
import { BOOKING_MODULE_KEY, bookingDetailPath, notFoundResponse } from "~/modules/booking/routes/bookingRoutePaths";
|
||||
import { listAppointmentsForTenant } from "~/modules/booking/db/booking.db.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: BookingListVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadBookingContext({ request, params });
|
||||
const title = `${t("bookings.list.title")} | ${process.env.APP_NAME}`;
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, vm: buildBookingListVM({ rows: [] }) } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const appointments = await listAppointmentsForTenant({ tenantId: ctx.tenantId, ownerUserId: canReadAllBookings(ctx) ? null : ctx.userId });
|
||||
const rows: BookingListRow[] = appointments.map((a) => ({
|
||||
id: a.id,
|
||||
startAtIso: a.startAt.toISOString(),
|
||||
endAtIso: a.endAt.toISOString(),
|
||||
status: a.status,
|
||||
statusKey: bookingStatusKey(a.status),
|
||||
customerName: a.customerName,
|
||||
customerEmail: a.customerEmail,
|
||||
pageTitle: a.pageTitle,
|
||||
providerUserId: a.providerUserId,
|
||||
detailHref: bookingDetailPath(tenantSlug, a.id),
|
||||
}));
|
||||
|
||||
return Response.json({ title, vm: buildBookingListVM({ rows }) } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export default function BookingsListRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.booking.list" />;
|
||||
}
|
||||
const { rows, emptyHeadlineKey, emptyBodyKey } = vm.data;
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.booking.list">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("bookings.list.title")}</h1>
|
||||
{rows.length === 0 ? (
|
||||
<div className="mt-10 text-center" data-ui-id="ui.booking.list.empty">
|
||||
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
|
||||
</div>
|
||||
) : (
|
||||
<table className="mt-6 w-full text-sm" data-ui-id="ui.booking.list.table">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground text-left">
|
||||
<th className="py-2">{t("bookings.list.columns.when")}</th>
|
||||
<th>{t("bookings.list.columns.customer")}</th>
|
||||
<th>{t("bookings.list.columns.page")}</th>
|
||||
<th>{t("bookings.list.columns.status")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-border divide-y">
|
||||
{rows.map((row) => (
|
||||
<tr key={row.id} data-row-id={row.id}>
|
||||
<td className="py-2">
|
||||
<a className="underline" href={row.detailHref}>
|
||||
{new Date(row.startAtIso).toLocaleString()}
|
||||
</a>
|
||||
</td>
|
||||
<td>{row.customerName || row.customerEmail}</td>
|
||||
<td>{row.pageTitle}</td>
|
||||
<td data-status={row.status}>{t(row.statusKey)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: BOOKING_MODULE_KEY };
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// AK-P16b · edit booking-page route (M06 Block E.2). Delegates to the shared editor.
|
||||
|
||||
import { bookingPageEditorLoader, bookingPageEditorAction } from "~/modules/booking/routes/BookingPageEditor.server";
|
||||
import BookingPageEditorRoute from "~/modules/booking/components/BookingPageEditorRoute";
|
||||
import { BOOKING_MODULE_KEY } from "~/modules/booking/routes/bookingRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
export const loader = bookingPageEditorLoader;
|
||||
export const action = bookingPageEditorAction;
|
||||
export default BookingPageEditorRoute;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: BOOKING_MODULE_KEY };
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
// AK-P16b · booking-pages list route (M06 Block E.1). bookings.read_all to view;
|
||||
// editing requires bookings.admin (enforced in the editor). Shows each page's public
|
||||
// URL with copy (DoD 3). Functional table; bespoke polish follows D-P16.
|
||||
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadBookingContext, requireBookingPermission, BOOKING_PERMISSIONS } from "~/modules/booking/routes/bookingAccess.server";
|
||||
import { BOOKING_MODULE_KEY, bookingPageEditPath, bookingPageNewPath, publicBookingPath, notFoundResponse } from "~/modules/booking/routes/bookingRoutePaths";
|
||||
import { listBookingPages } from "~/modules/booking/db/booking.db.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
interface PageRow {
|
||||
id: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
durationMinutes: number;
|
||||
isPublished: boolean;
|
||||
providerCount: number;
|
||||
editHref: string;
|
||||
publicPath: string;
|
||||
}
|
||||
type LoaderData = { title: string; tenantSlug: string; canCreate: boolean; rows: PageRow[]; newHref: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadBookingContext({ request, params, requireModule: true });
|
||||
try {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.readAll);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const pages = await listBookingPages(ctx.tenantId);
|
||||
const rows: PageRow[] = pages.map((p) => ({
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
slug: p.slug,
|
||||
durationMinutes: p.durationMinutes,
|
||||
isPublished: p.isPublished,
|
||||
providerCount: p.providerCount,
|
||||
editHref: bookingPageEditPath(tenantSlug, p.id),
|
||||
publicPath: publicBookingPath(tenantSlug, p.slug),
|
||||
}));
|
||||
return Response.json({
|
||||
title: `${t("bookings.pages.title")} | ${process.env.APP_NAME}`,
|
||||
tenantSlug,
|
||||
canCreate: ctx.permissions.includes(BOOKING_PERMISSIONS.admin),
|
||||
rows,
|
||||
newHref: bookingPageNewPath(tenantSlug),
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export default function BookingPagesListRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { rows, canCreate, newHref } = useLoaderData<LoaderData>();
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.booking.pages.list">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("bookings.pages.title")}</h1>
|
||||
{canCreate ? (
|
||||
<a href={newHref} className="rounded border px-3 py-1 text-sm" data-ui-id="ui.booking.pages.new">
|
||||
{t("bookings.pages.new")}
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="mt-10 text-center" data-ui-id="ui.booking.pages.empty">
|
||||
<p className="text-foreground font-medium">{t("bookings.pages.empty.headline")}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("bookings.pages.empty.body")}</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="mt-6 divide-border divide-y" data-ui-id="ui.booking.pages.items">
|
||||
{rows.map((row) => (
|
||||
<li key={row.id} className="flex items-center justify-between py-3" data-row-id={row.id}>
|
||||
<div>
|
||||
<a className="font-medium underline" href={row.editHref}>
|
||||
{row.title}
|
||||
</a>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
/{row.slug} · {row.durationMinutes}min · {row.providerCount} · {row.isPublished ? t("bookings.pages.published") : t("bookings.pages.unpublished")}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="rounded border px-2 py-1 text-xs" onClick={() => navigator.clipboard?.writeText(`${window.location.origin}${row.publicPath}`)}>
|
||||
{t("bookings.pages.copyUrl")}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: BOOKING_MODULE_KEY };
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// AK-P16b · new booking-page route (M06 Block E.2). Delegates to the shared editor.
|
||||
|
||||
import { bookingPageEditorLoader, bookingPageEditorAction } from "~/modules/booking/routes/BookingPageEditor.server";
|
||||
import BookingPageEditorRoute from "~/modules/booking/components/BookingPageEditorRoute";
|
||||
import { BOOKING_MODULE_KEY } from "~/modules/booking/routes/bookingRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
export const loader = bookingPageEditorLoader;
|
||||
export const action = bookingPageEditorAction;
|
||||
export default BookingPageEditorRoute;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: BOOKING_MODULE_KEY };
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
// AK-P16a · calendar view route (M25 Block B). Loader builds CalendarViewVM from
|
||||
// the current user's own events (all sources) with source markers (DoD 5). Module
|
||||
// off -> locked empty; missing calendar.connect_own -> 404. Baseline functional UI
|
||||
// (data-ui-id markers); the bespoke month/week grid follows David's D-P16 delta.
|
||||
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildCalendarViewVM, calendarSourceKey, type CalendarViewEventRow, type CalendarViewVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadCalendarContext, requireCalendarPermission, CALENDAR_PERMISSIONS } from "~/modules/calendar/routes/calendarAccess.server";
|
||||
import { CALENDAR_MODULE_KEY, notFoundResponse } from "~/modules/calendar/routes/calendarRoutePaths";
|
||||
import { listEventsForUser } from "~/modules/calendar/db/calendar.db.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: CalendarViewVM };
|
||||
|
||||
const WINDOW_PAST_DAYS = 7;
|
||||
const WINDOW_FUTURE_DAYS = 30;
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadCalendarContext({ request, params });
|
||||
const title = `${t("calendar.view.title")} | ${process.env.APP_NAME}`;
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, vm: buildCalendarViewVM({ events: [], rangeStart: "", rangeEnd: "" }) } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCalendarPermission(ctx, CALENDAR_PERMISSIONS.connectOwn);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const rangeStart = new Date(now.getTime() - WINDOW_PAST_DAYS * 86_400_000);
|
||||
const rangeEnd = new Date(now.getTime() + WINDOW_FUTURE_DAYS * 86_400_000);
|
||||
const events = await listEventsForUser(ctx.tenantId, ctx.userId, rangeStart, rangeEnd);
|
||||
|
||||
const rows: CalendarViewEventRow[] = events.map((e) => {
|
||||
const link = e.internalEntityLink as { type?: string } | null;
|
||||
return {
|
||||
id: e.id,
|
||||
source: e.source,
|
||||
sourceKey: calendarSourceKey(e.source),
|
||||
title: e.title ?? "",
|
||||
startsAt: e.startsAt.toISOString(),
|
||||
endsAt: e.endsAt.toISOString(),
|
||||
isAllDay: e.isAllDay,
|
||||
linkType: link?.type ?? null,
|
||||
};
|
||||
});
|
||||
|
||||
const vm = buildCalendarViewVM({ events: rows, rangeStart: rangeStart.toISOString().slice(0, 10), rangeEnd: rangeEnd.toISOString().slice(0, 10) });
|
||||
return Response.json({ title, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export default function CalendarViewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.calendar.list" />;
|
||||
}
|
||||
const { events, emptyHeadlineKey, emptyBodyKey } = vm.data;
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.calendar.list">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("calendar.view.title")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("calendar.view.subtitle")}</p>
|
||||
{events.length === 0 ? (
|
||||
<div className="mt-10 text-center" data-ui-id="ui.calendar.list.empty">
|
||||
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="mt-6 divide-border divide-y" data-ui-id="ui.calendar.list.events">
|
||||
{events.map((event) => (
|
||||
<li key={event.id} className="flex items-center justify-between py-3" data-row-id={event.id}>
|
||||
<div>
|
||||
<span className="text-foreground font-medium">{event.title || t("calendar.source." + event.source)}</span>
|
||||
<p className="text-muted-foreground text-xs">{new Date(event.startsAt).toLocaleString()}</p>
|
||||
</div>
|
||||
<span className="text-muted-foreground text-xs" data-source={event.source}>
|
||||
{t(event.sourceKey)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CALENDAR_MODULE_KEY };
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
const routesDir = path.join(repoRoot, "apps/web/app/routes/app.$tenant");
|
||||
|
||||
function read(relative: string): string {
|
||||
return fs.readFileSync(path.join(routesDir, relative), "utf8");
|
||||
}
|
||||
|
||||
function localeCrm(locale: string): Record<string, unknown> {
|
||||
const json = JSON.parse(fs.readFileSync(path.join(repoRoot, `apps/web/public/locales/${locale}/translations.json`), "utf8"));
|
||||
return json.crm as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function hasKey(root: Record<string, unknown>, dotted: string): boolean {
|
||||
// `dotted` is a `crm.…` key; resolve the part after the `crm.` prefix.
|
||||
const segments = dotted.replace(/^crm\./, "").split(".");
|
||||
let node: unknown = root;
|
||||
for (const segment of segments) {
|
||||
if (!node || typeof node !== "object") return false;
|
||||
node = (node as Record<string, unknown>)[segment];
|
||||
}
|
||||
return typeof node === "string";
|
||||
}
|
||||
|
||||
describe("CRM contact routes (R-P6 slice 4)", () => {
|
||||
it("build the list/detail view-models server-side via the shared loaders", () => {
|
||||
const list = read("contacts._index.tsx");
|
||||
expect(list).toContain("export const loader");
|
||||
expect(list).toContain("export const action");
|
||||
expect(list).toContain("loadKontaktListData");
|
||||
expect(list).toContain("handleKontaktListAction");
|
||||
expect(list).not.toContain("useFetcher");
|
||||
|
||||
const companies = read("contacts.companies._index.tsx");
|
||||
expect(companies).toContain('variant: "companies"');
|
||||
|
||||
const detail = read("contacts.$id.tsx");
|
||||
expect(detail).toContain("loadKontaktDetailData");
|
||||
expect(detail).toContain("handleKontaktDetailAction");
|
||||
|
||||
const newRoute = read("contacts.new.tsx");
|
||||
expect(newRoute).toContain('intent === "checkDuplicates"');
|
||||
expect(newRoute).toContain("findDuplicateKontakte");
|
||||
|
||||
const exportRoute = read("contacts.export.tsx");
|
||||
expect(exportRoute).toContain("buildKontaktCsv");
|
||||
expect(exportRoute).toContain("text/csv");
|
||||
});
|
||||
|
||||
it("gates admin routes on crm.admin and the lists on crm.read_own", () => {
|
||||
expect(read("contacts._index.tsx") + read("contacts.$id.tsx")).toContain("crm.read_own");
|
||||
for (const file of ["contacts.admin.custom-fields.tsx", "contacts.admin.tags.tsx", "contacts.admin.duplicates.tsx"]) {
|
||||
expect(read(file)).toContain('requireCrmPermission(ctx, "crm.admin")');
|
||||
}
|
||||
});
|
||||
|
||||
it("has de + en translations for the keys the routes reference", () => {
|
||||
const keys = [
|
||||
"crm.contacts.title",
|
||||
"crm.companies.title",
|
||||
"crm.new.title",
|
||||
"crm.locked.headline",
|
||||
"crm.empty.contacts.headline",
|
||||
"crm.kontaktTyp.privatperson",
|
||||
"crm.kontaktStatus.kunde",
|
||||
"crm.orgMerkmal.gmbh",
|
||||
"crm.kontaktArt.hauptkontakt",
|
||||
"crm.datentyp.waehrung",
|
||||
"crm.activity.contact_created",
|
||||
"crm.duplicate.reason.email",
|
||||
"crm.duplicate.matchType.hard",
|
||||
"crm.error.nameRequired",
|
||||
"crm.error.tagNameExists",
|
||||
"crm.detail.section.activity",
|
||||
"crm.admin.customFields.title",
|
||||
"crm.admin.tags.usage",
|
||||
"crm.pagination.page",
|
||||
];
|
||||
const de = localeCrm("de");
|
||||
const en = localeCrm("en");
|
||||
for (const key of keys) {
|
||||
expect(hasKey(de, key), `de missing ${key}`).toBe(true);
|
||||
expect(hasKey(en, key), `en missing ${key}`).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — contact detail route (`/contacts/:id`).
|
||||
// Loader builds the KontaktDetailVM + ActivityStreamVM server-side; action wires
|
||||
// every inline-edit intent (audit + activity, DoD 3/13/14). Breadcrumb back to the
|
||||
// contact list (DoD 9). Not visible / module off -> 404.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { handleKontaktDetailAction, loadKontaktDetailData, type KontaktDetailLoaderData } from "~/utils/integrations/crm/crmDetailRoute.server";
|
||||
import { CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import KontaktDetailView from "~/components/crm/KontaktDetailView";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json(await loadKontaktDetailData({ request, params, variant: "contacts" }));
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return handleKontaktDetailAction({ request, params, variant: "contacts" });
|
||||
};
|
||||
|
||||
export default function ContactDetailRoute() {
|
||||
const data = useLoaderData<KontaktDetailLoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
if (data.detailVM.status !== "ready" || !data.detailVM.data) {
|
||||
return <main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.crm.detail" />;
|
||||
}
|
||||
return (
|
||||
<KontaktDetailView
|
||||
data={data.detailVM.data}
|
||||
activity={data.activityVM}
|
||||
allTags={data.allTags}
|
||||
customFieldDefs={data.customFieldDefs}
|
||||
ownerOptions={data.ownerOptions}
|
||||
backHref={data.backHref}
|
||||
listLabelKey={data.listLabelKey}
|
||||
errorKey={actionData?.error ?? null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CRM_MODULE_KEY };
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — contact browser route (`/contacts`). Loader
|
||||
// builds the KontaktListVM server-side (filter/sort/paginate, DoD 2); action runs
|
||||
// the bulk operations (archive/reassign/tag). Module off -> locked empty; missing
|
||||
// crm.read_own -> 404. UI is the shared KontaktListView (baseline inline UI; the
|
||||
// final optics arrive with David's D-CRM delta).
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { handleKontaktListAction, loadKontaktListData, type KontaktListLoaderData } from "~/utils/integrations/crm/crmListRoute.server";
|
||||
import { CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import KontaktListView from "~/components/crm/KontaktListView";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json(await loadKontaktListData({ request, params, variant: "contacts" }));
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return handleKontaktListAction({ request, params, variant: "contacts" });
|
||||
};
|
||||
|
||||
export default function ContactsIndexRoute() {
|
||||
const data = useLoaderData<KontaktListLoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
return (
|
||||
<KontaktListView
|
||||
moduleActive={data.moduleActive}
|
||||
variant="contacts"
|
||||
vm={data.vm}
|
||||
tagOptions={data.tagOptions}
|
||||
ownerOptions={data.ownerOptions}
|
||||
query={data.query}
|
||||
baseHref={data.baseHref}
|
||||
newHref={data.newHref}
|
||||
exportHref={data.exportHref}
|
||||
errorKey={actionData?.error ?? null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CRM_MODULE_KEY };
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — custom-field admin (`/contacts/admin/custom-fields`).
|
||||
// Lists + creates + archives the tenant's CONTACT custom-field definitions (DoD 3).
|
||||
// Gated on crm.admin (missing -> 404); module off -> locked empty.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildCustomFieldAdminVM, type CustomFieldAdminVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
badRequestResponse,
|
||||
crmActionErrorResponse,
|
||||
loadCrmContext,
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
} from "~/utils/integrations/crm/crmAccess.server";
|
||||
import {
|
||||
archiveCustomFieldDefinition,
|
||||
createCustomFieldDefinition,
|
||||
listCustomFieldDefinitions,
|
||||
type CustomFieldDatentyp,
|
||||
} from "~/utils/integrations/crm/customFieldService.server";
|
||||
import { auditCrmEvent } from "~/utils/integrations/crm/crmAudit.server";
|
||||
import { CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
const ENTITY_TYPE = "kontakt";
|
||||
const DATENTYPEN: CustomFieldDatentyp[] = [
|
||||
"text",
|
||||
"textarea",
|
||||
"zahl",
|
||||
"waehrung",
|
||||
"datum",
|
||||
"datum_range",
|
||||
"select",
|
||||
"multiselect",
|
||||
"boolean",
|
||||
"email",
|
||||
"telefon",
|
||||
"datei",
|
||||
];
|
||||
|
||||
type LoaderData = { title: string; moduleActive: boolean; vm: CustomFieldAdminVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadCrmContext({ request, params });
|
||||
const title = `${t("crm.admin.customFields.title")} | ${process.env.APP_NAME}`;
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, moduleActive: false, vm: buildCustomFieldAdminVM({ rows: [], entityType: ENTITY_TYPE, canWrite: false }) } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.admin");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const definitions = await listCustomFieldDefinitions({ tenantId: ctx.tenantId, entityType: ENTITY_TYPE, includeArchived: true });
|
||||
const vm = buildCustomFieldAdminVM({ rows: definitions, entityType: ENTITY_TYPE, canWrite: true });
|
||||
return Response.json({ title, moduleActive: true, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadCrmContext({ request, params, requireModule: true });
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent")?.toString();
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.admin");
|
||||
if (intent === "create") {
|
||||
const datentyp = (form.get("datentyp")?.toString() ?? "text") as CustomFieldDatentyp;
|
||||
const optionenRaw = form.get("optionen")?.toString().trim();
|
||||
const optionen = optionenRaw ? optionenRaw.split(",").map((option) => option.trim()).filter(Boolean) : null;
|
||||
const created = await createCustomFieldDefinition({
|
||||
tenantId: ctx.tenantId,
|
||||
entityType: ENTITY_TYPE,
|
||||
key: form.get("key")?.toString() ?? "",
|
||||
label: form.get("label")?.toString() ?? "",
|
||||
datentyp,
|
||||
optionen,
|
||||
});
|
||||
await auditCrmEvent({ ctx, action: "custom_field.created", targetType: "custom_field", targetId: created.id, metadata: { key: created.key } });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
if (intent === "archive") {
|
||||
const definitionId = form.get("definitionId")?.toString().trim();
|
||||
if (!definitionId) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
await archiveCustomFieldDefinition({ tenantId: ctx.tenantId, definitionId });
|
||||
await auditCrmEvent({ ctx, action: "custom_field.archived", targetType: "custom_field", targetId: definitionId });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
return crmActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function CustomFieldsAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { moduleActive, vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
|
||||
if (!moduleActive) {
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.crm.admin.customFields">
|
||||
<div className="mt-10 text-center">
|
||||
<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 rows = vm.status === "ready" && vm.data ? vm.data.rows : [];
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.crm.admin.customFields">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("crm.admin.customFields.title")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("crm.admin.customFields.subtitle")}</p>
|
||||
|
||||
{actionData?.error ? (
|
||||
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert">
|
||||
{t(actionData.error)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<p className="text-muted-foreground mt-6 text-sm" data-ui-id="ui.crm.admin.customFields.empty">
|
||||
{t("crm.admin.customFields.empty")}
|
||||
</p>
|
||||
) : (
|
||||
<table className="mt-6 w-full text-left text-sm" data-ui-id="ui.crm.admin.customFields.table">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground border-b">
|
||||
<th className="py-2">{t("crm.admin.customFields.colKey")}</th>
|
||||
<th className="py-2">{t("crm.admin.customFields.colLabel")}</th>
|
||||
<th className="py-2">{t("crm.admin.customFields.colType")}</th>
|
||||
<th className="py-2" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.id} className="border-b" data-row-id={row.id}>
|
||||
<td className="py-2">{row.key}</td>
|
||||
<td className="py-2">
|
||||
{row.label}
|
||||
{row.isDemoData ? <span className="text-muted-foreground ml-1 text-xs">{t("crm.admin.demoBadge")}</span> : null}
|
||||
{row.archiviert ? <span className="text-muted-foreground ml-1 text-xs">{t("crm.admin.archivedBadge")}</span> : null}
|
||||
</td>
|
||||
<td className="py-2">{t(row.datentypLabelKey)}</td>
|
||||
<td className="py-2">
|
||||
{!row.archiviert ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="archive" />
|
||||
<input type="hidden" name="definitionId" value={row.id} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("crm.actions.archive")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
|
||||
<form method="post" className="mt-6 flex flex-wrap items-end gap-2" data-ui-id="ui.crm.admin.customFields.create">
|
||||
<input type="hidden" name="intent" value="create" />
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.admin.customFields.colKey")}</span>
|
||||
<input name="key" required className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.admin.customFields.colLabel")}</span>
|
||||
<input name="label" required className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.admin.customFields.colType")}</span>
|
||||
<select name="datentyp" defaultValue="text" className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
{DATENTYPEN.map((datentyp) => (
|
||||
<option key={datentyp} value={datentyp}>
|
||||
{t(`crm.datentyp.${datentyp}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.admin.customFields.colOptions")}</span>
|
||||
<input name="optionen" placeholder={t("crm.admin.customFields.optionsPlaceholder")} className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.create")}
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CRM_MODULE_KEY };
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — duplicate tool (`/contacts/admin/duplicates`).
|
||||
// Scans the tenant's contacts and renders the duplicate candidate pairs
|
||||
// side-by-side (DoD 4 surface). Read-only here — the actual merge lands in a later
|
||||
// phase (the VM exposes `canMerge`, kept false). Gated on crm.admin (missing -> 404).
|
||||
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildDuplicateVM, type DuplicatePairSource, type DuplicateVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadCrmContext, notFoundResponse, requireCrmPermission, type CrmVisibilityContext } from "~/utils/integrations/crm/crmAccess.server";
|
||||
import { findDuplicateKontakte, listKontakteForCsv, resolveUserLabels, type KontaktRow } from "~/utils/integrations/crm/crmService.server";
|
||||
import { contactDetailPath, CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
const MAX_SCAN = 200;
|
||||
|
||||
type LoaderData = { title: string; moduleActive: boolean; vm: DuplicateVM; tenantSlug: string };
|
||||
|
||||
function hardReason(a: KontaktRow, b: KontaktRow): string {
|
||||
if (a.primaerEmail && b.primaerEmail && a.primaerEmail.toLowerCase() === b.primaerEmail.toLowerCase()) {
|
||||
return "email";
|
||||
}
|
||||
if (a.primaerTelefon && b.primaerTelefon && a.primaerTelefon === b.primaerTelefon) {
|
||||
return "telefon";
|
||||
}
|
||||
return "email";
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadCrmContext({ request, params });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const title = `${t("crm.admin.duplicates.title")} | ${process.env.APP_NAME}`;
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, moduleActive: false, vm: buildDuplicateVM({ pairs: [], userLabels: new Map(), canMerge: false, tenantSlug }), tenantSlug } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.admin");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
// The duplicate tool is tenant-wide: an admin scans every contact, so the scan
|
||||
// runs with read_all visibility (findDuplicateKontakte itself is not owner-scoped).
|
||||
const adminCtx: CrmVisibilityContext = { userId: ctx.userId, permissions: [...ctx.permissions, "crm.read_all"] };
|
||||
const contacts = (await listKontakteForCsv({ tenantId: ctx.tenantId, ctx: adminCtx, sort: { field: "createdAt", dir: "desc" } })).slice(0, MAX_SCAN);
|
||||
|
||||
const seen = new Set<string>();
|
||||
const pairs: DuplicatePairSource[] = [];
|
||||
for (const a of contacts) {
|
||||
const { hard, soft } = await findDuplicateKontakte({
|
||||
tenantId: ctx.tenantId,
|
||||
email: a.primaerEmail,
|
||||
telefon: a.primaerTelefon,
|
||||
vorname: a.vorname,
|
||||
nachname: a.nachname,
|
||||
orgName: a.orgName,
|
||||
excludeKontaktId: a.id,
|
||||
});
|
||||
for (const b of hard) {
|
||||
const key = [a.id, b.id].sort().join("|");
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
pairs.push({ matchType: "hard", matchReason: hardReason(a, b), a, b });
|
||||
}
|
||||
for (const b of soft) {
|
||||
const key = [a.id, b.id].sort().join("|");
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
pairs.push({ matchType: "soft", matchReason: a.kontaktTyp === "organisation" ? "orgName" : "name", a, b });
|
||||
}
|
||||
}
|
||||
|
||||
const allIds = pairs.flatMap((pair) => [pair.a.zustaendigerUserId, pair.b.zustaendigerUserId]).filter((id): id is string => Boolean(id));
|
||||
const userLabels = await resolveUserLabels(allIds);
|
||||
const vm = buildDuplicateVM({ pairs, userLabels, canMerge: false, tenantSlug });
|
||||
return Response.json({ title, moduleActive: true, vm, tenantSlug } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export default function DuplicatesAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { moduleActive, vm, tenantSlug } = useLoaderData<LoaderData>();
|
||||
|
||||
if (!moduleActive) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.crm.admin.duplicates">
|
||||
<div className="mt-10 text-center">
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.crm.admin.duplicates">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("crm.admin.duplicates.title")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("crm.admin.duplicates.subtitle")}</p>
|
||||
|
||||
{vm.status !== "ready" || !vm.data || vm.data.pairs.length === 0 ? (
|
||||
<p className="text-muted-foreground mt-6 text-sm" data-ui-id="ui.crm.admin.duplicates.empty">
|
||||
{t("crm.admin.duplicates.empty")}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="mt-6 space-y-4" data-ui-id="ui.crm.admin.duplicates.list">
|
||||
{vm.data.pairs.map((pair, index) => (
|
||||
<li key={`${pair.a.id}-${pair.b.id}-${index}`} className="border-border rounded border p-3" data-row-id={`${pair.a.id}-${pair.b.id}`}>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t(`crm.duplicate.matchType.${pair.matchType}`)} · {t(pair.matchReasonKey)}
|
||||
</p>
|
||||
<div className="mt-2 grid gap-3 sm:grid-cols-2">
|
||||
{[pair.a, pair.b].map((card) => (
|
||||
<div key={card.id} className="border-border rounded border p-2 text-sm">
|
||||
<a href={contactDetailPath(tenantSlug, card.id)} className="text-theme-600 font-medium">
|
||||
{card.displayName}
|
||||
</a>
|
||||
<p className="text-muted-foreground text-xs">{t(card.statusLabelKey)}</p>
|
||||
{card.primaerEmail ? <p>{card.primaerEmail}</p> : null}
|
||||
{card.primaerTelefon ? <p>{card.primaerTelefon}</p> : null}
|
||||
{card.zustaendigerLabel ? <p className="text-muted-foreground text-xs">{card.zustaendigerLabel}</p> : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CRM_MODULE_KEY };
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — tag admin (`/contacts/admin/tags`). Lists +
|
||||
// creates + edits + deletes the tenant's coloured tags with a per-tag usage count
|
||||
// (DoD 3). Gated on crm.admin (missing -> 404); module off -> locked empty.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildTagAdminVM, type TagAdminVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
badRequestResponse,
|
||||
crmActionErrorResponse,
|
||||
loadCrmContext,
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
} from "~/utils/integrations/crm/crmAccess.server";
|
||||
import { countTagUsage, createTag, deleteTag, listTags, updateTag } from "~/utils/integrations/crm/tagService.server";
|
||||
import { auditCrmEvent } from "~/utils/integrations/crm/crmAudit.server";
|
||||
import { CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; moduleActive: boolean; vm: TagAdminVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadCrmContext({ request, params });
|
||||
const title = `${t("crm.admin.tags.title")} | ${process.env.APP_NAME}`;
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, moduleActive: false, vm: buildTagAdminVM({ tags: [], usageCounts: new Map(), canWrite: false }) } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.admin");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const tags = await listTags(ctx.tenantId);
|
||||
const usageCounts = new Map<string, number>();
|
||||
await Promise.all(tags.map(async (tag) => usageCounts.set(tag.id, await countTagUsage(ctx.tenantId, tag.id))));
|
||||
const vm = buildTagAdminVM({ tags, usageCounts, canWrite: true });
|
||||
return Response.json({ title, moduleActive: true, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadCrmContext({ request, params, requireModule: true });
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent")?.toString();
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.admin");
|
||||
if (intent === "create") {
|
||||
const created = await createTag({ tenantId: ctx.tenantId, name: form.get("name")?.toString() ?? "", farbe: form.get("farbe")?.toString() || "#888888" });
|
||||
await auditCrmEvent({ ctx, action: "tag.created", targetType: "tag", targetId: created.id, metadata: { name: created.name } });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
const tagId = form.get("tagId")?.toString().trim();
|
||||
if (!tagId) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
if (intent === "update") {
|
||||
await updateTag({ tenantId: ctx.tenantId, tagId, name: form.get("name")?.toString(), farbe: form.get("farbe")?.toString() });
|
||||
await auditCrmEvent({ ctx, action: "tag.updated", targetType: "tag", targetId: tagId });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
if (intent === "delete") {
|
||||
await deleteTag({ tenantId: ctx.tenantId, tagId });
|
||||
await auditCrmEvent({ ctx, action: "tag.deleted", targetType: "tag", targetId: tagId });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
return crmActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function TagsAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { moduleActive, vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
|
||||
if (!moduleActive) {
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.crm.admin.tags">
|
||||
<div className="mt-10 text-center">
|
||||
<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 rows = vm.status === "ready" && vm.data ? vm.data.rows : [];
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.crm.admin.tags">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("crm.admin.tags.title")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("crm.admin.tags.subtitle")}</p>
|
||||
|
||||
{actionData?.error ? (
|
||||
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert">
|
||||
{t(actionData.error)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<p className="text-muted-foreground mt-6 text-sm" data-ui-id="ui.crm.admin.tags.empty">
|
||||
{t("crm.admin.tags.empty")}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="mt-6 space-y-2" data-ui-id="ui.crm.admin.tags.list">
|
||||
{rows.map((row) => (
|
||||
<li key={row.id} className="border-border flex flex-wrap items-end gap-2 rounded border px-3 py-2" data-row-id={row.id}>
|
||||
<form method="post" className="flex flex-wrap items-end gap-2">
|
||||
<input type="hidden" name="intent" value="update" />
|
||||
<input type="hidden" name="tagId" value={row.id} />
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.admin.tags.colName")}</span>
|
||||
<input name="name" defaultValue={row.name} className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.admin.tags.colColor")}</span>
|
||||
<input name="farbe" type="color" defaultValue={row.farbe} className="h-8 w-12 rounded border" />
|
||||
</label>
|
||||
<span className="text-muted-foreground text-xs">{t("crm.admin.tags.usage", { n: row.usageCount })}</span>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.save")}
|
||||
</button>
|
||||
</form>
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="delete" />
|
||||
<input type="hidden" name="tagId" value={row.id} />
|
||||
<button type="submit" className="text-destructive text-xs underline">
|
||||
{t("crm.actions.delete")}
|
||||
</button>
|
||||
</form>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<form method="post" className="mt-6 flex flex-wrap items-end gap-2" data-ui-id="ui.crm.admin.tags.create">
|
||||
<input type="hidden" name="intent" value="create" />
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.admin.tags.colName")}</span>
|
||||
<input name="name" required className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("crm.admin.tags.colColor")}</span>
|
||||
<input name="farbe" type="color" defaultValue="#888888" className="h-8 w-12 rounded border" />
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium">
|
||||
{t("crm.actions.create")}
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CRM_MODULE_KEY };
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — organisation detail route
|
||||
// (`/contacts/companies/:id`). Reuses the SAME loader/action/component as the
|
||||
// contact detail (Component-Extraktion, no .server re-export); only the back link
|
||||
// / breadcrumb root differs. Not visible / module off -> 404.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { handleKontaktDetailAction, loadKontaktDetailData, type KontaktDetailLoaderData } from "~/utils/integrations/crm/crmDetailRoute.server";
|
||||
import { CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import KontaktDetailView from "~/components/crm/KontaktDetailView";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json(await loadKontaktDetailData({ request, params, variant: "companies" }));
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return handleKontaktDetailAction({ request, params, variant: "companies" });
|
||||
};
|
||||
|
||||
export default function CompanyDetailRoute() {
|
||||
const data = useLoaderData<KontaktDetailLoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
if (data.detailVM.status !== "ready" || !data.detailVM.data) {
|
||||
return <main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.crm.detail" />;
|
||||
}
|
||||
return (
|
||||
<KontaktDetailView
|
||||
data={data.detailVM.data}
|
||||
activity={data.activityVM}
|
||||
allTags={data.allTags}
|
||||
customFieldDefs={data.customFieldDefs}
|
||||
ownerOptions={data.ownerOptions}
|
||||
backHref={data.backHref}
|
||||
listLabelKey={data.listLabelKey}
|
||||
errorKey={actionData?.error ?? null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CRM_MODULE_KEY };
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — organisation browser route
|
||||
// (`/contacts/companies`). Same server-built KontaktListVM as `/contacts`, but the
|
||||
// type filter is pinned to `organisation`. Module off -> locked empty; missing
|
||||
// crm.read_own -> 404.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { handleKontaktListAction, loadKontaktListData, type KontaktListLoaderData } from "~/utils/integrations/crm/crmListRoute.server";
|
||||
import { CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import KontaktListView from "~/components/crm/KontaktListView";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json(await loadKontaktListData({ request, params, variant: "companies" }));
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
return handleKontaktListAction({ request, params, variant: "companies" });
|
||||
};
|
||||
|
||||
export default function CompaniesIndexRoute() {
|
||||
const data = useLoaderData<KontaktListLoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
return (
|
||||
<KontaktListView
|
||||
moduleActive={data.moduleActive}
|
||||
variant="companies"
|
||||
vm={data.vm}
|
||||
tagOptions={data.tagOptions}
|
||||
ownerOptions={data.ownerOptions}
|
||||
query={data.query}
|
||||
baseHref={data.baseHref}
|
||||
newHref={data.newHref}
|
||||
exportHref={data.exportHref}
|
||||
errorKey={actionData?.error ?? null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CRM_MODULE_KEY };
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — CSV export resource route
|
||||
// (`/contacts/export`). Loader-only: it re-applies the same browser filter/sort
|
||||
// from the query (DoD 2), resolves the rows server-side and streams an RFC 4180
|
||||
// CSV (German headers, localized type/status labels). Module off / missing
|
||||
// crm.read_own -> 404 (no body is rendered for a download endpoint).
|
||||
|
||||
import { type LoaderFunctionArgs } from "react-router";
|
||||
import { buildKontaktCsv, buildKontaktDisplayName, kontaktStatusLabelKey, kontaktTypLabelKey, type KontaktCsvRow } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadCrmContext, notFoundResponse, requireCrmPermission } from "~/utils/integrations/crm/crmAccess.server";
|
||||
import { listKontakteForCsv, resolveUserLabels } from "~/utils/integrations/crm/crmService.server";
|
||||
import { parseKontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadCrmContext({ request, params });
|
||||
if (!ctx.hasModule) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.read_own");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const { filter, sort } = parseKontaktListQuery(url.searchParams);
|
||||
const rows = await listKontakteForCsv({ tenantId: ctx.tenantId, ctx, filter, sort });
|
||||
const userLabels = await resolveUserLabels(rows.map((row) => row.zustaendigerUserId).filter((id): id is string => Boolean(id)));
|
||||
|
||||
const csvRows: KontaktCsvRow[] = rows.map((row) => ({
|
||||
displayName: buildKontaktDisplayName(row),
|
||||
kontaktTyp: t(kontaktTypLabelKey(row.kontaktTyp)),
|
||||
kontaktStatus: t(kontaktStatusLabelKey(row.kontaktStatus)),
|
||||
primaerEmail: row.primaerEmail,
|
||||
primaerTelefon: row.primaerTelefon,
|
||||
zustaendigerLabel: row.zustaendigerUserId ? (userLabels.get(row.zustaendigerUserId) ?? null) : null,
|
||||
createdAtIso: row.createdAt.toISOString(),
|
||||
}));
|
||||
|
||||
const csv = buildKontaktCsv(csvRows);
|
||||
return new Response(`${csv}`, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": 'attachment; filename="kontakte.csv"',
|
||||
},
|
||||
});
|
||||
};
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
// R-P6 (P6 CRM core, Variante A) — create-contact route (`/contacts/new`).
|
||||
// `intent=checkDuplicates` (fetcher) surfaces hard/soft duplicate hits live while
|
||||
// typing (DoD 4); `intent=create` persists the typed Kontakt (+ audit + activity)
|
||||
// and redirects to the detail. Module off -> locked; missing crm.write -> 404.
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useFetcher, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildKontaktDisplayName } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
badRequestResponse,
|
||||
crmActionErrorResponse,
|
||||
loadCrmContext,
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
} from "~/utils/integrations/crm/crmAccess.server";
|
||||
import { createKontakt, findDuplicateKontakte, listAssignableUsers, type KontaktTyp, type OrgMerkmal, type KontaktStatus } from "~/utils/integrations/crm/crmService.server";
|
||||
import { auditCrmEvent, logKontaktActivity } from "~/utils/integrations/crm/crmAudit.server";
|
||||
import { companyDetailPath, contactDetailPath, contactsPath, CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type DuplicateCard = { id: string; displayName: string; primaerEmail: string | null; primaerTelefon: string | null; detailHref: string };
|
||||
type LoaderData = { title: string; moduleActive: boolean; ownerOptions: { id: string; label: string }[]; defaultOwnerId: string; backHref: string };
|
||||
|
||||
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";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadCrmContext({ request, params });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const base = { title: `${t("crm.new.title")} | ${process.env.APP_NAME}`, backHref: contactsPath(tenantSlug) };
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ ...base, moduleActive: false, ownerOptions: [], defaultOwnerId: ctx.userId } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const ownerOptions = await listAssignableUsers(ctx.tenantId);
|
||||
return Response.json({ ...base, moduleActive: true, ownerOptions, defaultOwnerId: ctx.userId } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadCrmContext({ request, params, requireModule: true });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent")?.toString();
|
||||
const str = (name: string) => form.get(name)?.toString().trim() || null;
|
||||
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.write");
|
||||
const kontaktTyp = (str("kontaktTyp") ?? "privatperson") as KontaktTyp;
|
||||
|
||||
if (intent === "checkDuplicates") {
|
||||
const { hard, soft } = await findDuplicateKontakte({
|
||||
tenantId: ctx.tenantId,
|
||||
email: str("email"),
|
||||
telefon: str("telefon"),
|
||||
vorname: str("vorname"),
|
||||
nachname: str("nachname"),
|
||||
orgName: str("orgName"),
|
||||
});
|
||||
const toCard = (row: (typeof hard)[number]): DuplicateCard => ({
|
||||
id: row.id,
|
||||
displayName: buildKontaktDisplayName(row),
|
||||
primaerEmail: row.primaerEmail,
|
||||
primaerTelefon: row.primaerTelefon,
|
||||
detailHref: row.kontaktTyp === "organisation" ? companyDetailPath(tenantSlug, row.id) : contactDetailPath(tenantSlug, row.id),
|
||||
});
|
||||
return Response.json({ hard: hard.map(toCard), soft: soft.map(toCard) });
|
||||
}
|
||||
|
||||
if (intent === "create") {
|
||||
const email = str("email");
|
||||
const telefon = str("telefon");
|
||||
const created = await createKontakt({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
kontaktTyp,
|
||||
kontaktStatus: (str("kontaktStatus") as KontaktStatus | null) ?? undefined,
|
||||
vorname: str("vorname"),
|
||||
nachname: str("nachname"),
|
||||
orgName: str("orgName"),
|
||||
orgMerkmal: (str("orgMerkmal") as OrgMerkmal | null) ?? undefined,
|
||||
emails: email ? [{ email, primaer: true }] : [],
|
||||
telefone: telefon ? [{ telefon, primaer: true }] : [],
|
||||
zustaendigerUserId: str("zustaendigerUserId"),
|
||||
});
|
||||
await auditCrmEvent({ ctx, action: "kontakt.created", targetType: "kontakt", targetId: created.id });
|
||||
await logKontaktActivity({ ctx, kontaktId: created.id, kontaktTyp, activityType: "contact_created", summaryText: "Kontakt angelegt" });
|
||||
return redirect(kontaktTyp === "organisation" ? companyDetailPath(tenantSlug, created.id) : contactDetailPath(tenantSlug, created.id));
|
||||
}
|
||||
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
return crmActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function ContactNewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { moduleActive, ownerOptions, defaultOwnerId, backHref } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
const dupFetcher = useFetcher<{ hard: DuplicateCard[]; soft: DuplicateCard[] }>();
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const [kontaktTyp, setKontaktTyp] = useState<KontaktTyp>("privatperson");
|
||||
|
||||
if (!moduleActive) {
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.crm.new">
|
||||
<div className="mt-10 text-center" data-ui-id="ui.crm.new.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 checkDuplicates = () => {
|
||||
if (!formRef.current) return;
|
||||
const fd = new FormData(formRef.current);
|
||||
fd.set("intent", "checkDuplicates");
|
||||
dupFetcher.submit(fd, { method: "post" });
|
||||
};
|
||||
|
||||
const dup = dupFetcher.data;
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.crm.new">
|
||||
<nav className="text-muted-foreground mb-4 text-sm">
|
||||
<a href={backHref} className="hover:text-foreground">
|
||||
{t("crm.contacts.title")}
|
||||
</a>
|
||||
</nav>
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("crm.new.title")}</h1>
|
||||
|
||||
{actionData?.error ? (
|
||||
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.new.error">
|
||||
{t(actionData.error)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{dup && (dup.hard.length > 0 || dup.soft.length > 0) ? (
|
||||
<div className="mt-4 space-y-2" data-ui-id="ui.crm.new.duplicates">
|
||||
{dup.hard.length > 0 ? (
|
||||
<div className="border-destructive rounded border px-3 py-2 text-sm" data-ui-id="ui.crm.new.duplicates.hard">
|
||||
<p className="text-destructive font-medium">{t("crm.new.duplicates.hard")}</p>
|
||||
<ul className="mt-1">
|
||||
{dup.hard.map((card) => (
|
||||
<li key={card.id}>
|
||||
<a href={card.detailHref} className="text-theme-600">
|
||||
{card.displayName}
|
||||
</a>
|
||||
{card.primaerEmail ? ` · ${card.primaerEmail}` : ""}
|
||||
{card.primaerTelefon ? ` · ${card.primaerTelefon}` : ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
{dup.soft.length > 0 ? (
|
||||
<div className="border-border rounded border px-3 py-2 text-sm" data-ui-id="ui.crm.new.duplicates.soft">
|
||||
<p className="font-medium">{t("crm.new.duplicates.soft")}</p>
|
||||
<ul className="mt-1">
|
||||
{dup.soft.map((card) => (
|
||||
<li key={card.id}>
|
||||
<a href={card.detailHref} className="text-theme-600">
|
||||
{card.displayName}
|
||||
</a>
|
||||
{card.primaerEmail ? ` · ${card.primaerEmail}` : ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<form method="post" ref={formRef} className="mt-6 grid gap-3 sm:grid-cols-2" data-ui-id="ui.crm.new.form">
|
||||
<input type="hidden" name="intent" value="create" />
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.type")}</span>
|
||||
<select
|
||||
name="kontaktTyp"
|
||||
value={kontaktTyp}
|
||||
onChange={(event) => setKontaktTyp(event.target.value as KontaktTyp)}
|
||||
className={crmFieldControlClass}
|
||||
>
|
||||
<option value="privatperson">{t("crm.kontaktTyp.privatperson")}</option>
|
||||
<option value="organisation">{t("crm.kontaktTyp.organisation")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.status")}</span>
|
||||
<select name="kontaktStatus" defaultValue="kontakt" className={crmFieldControlClass}>
|
||||
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
|
||||
<option key={status} value={status}>
|
||||
{t(`crm.kontaktStatus.${status}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{kontaktTyp === "organisation" ? (
|
||||
<>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.orgName")}</span>
|
||||
<input name="orgName" onBlur={checkDuplicates} className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.orgMerkmal")}</span>
|
||||
<select name="orgMerkmal" defaultValue="" 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" onBlur={checkDuplicates} className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.nachname")}</span>
|
||||
<input name="nachname" onBlur={checkDuplicates} className={crmFieldControlClass} />
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.email")}</span>
|
||||
<input name="email" type="email" onBlur={checkDuplicates} className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.telefon")}</span>
|
||||
<input name="telefon" onBlur={checkDuplicates} className={crmFieldControlClass} />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className={crmFieldLabelClass}>{t("crm.fields.owner")}</span>
|
||||
<select name="zustaendigerUserId" defaultValue={defaultOwnerId} className={crmFieldControlClass}>
|
||||
{ownerOptions.map((option) => (
|
||||
<option key={option.id} value={option.id}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div className="flex items-center gap-3 sm:col-span-2">
|
||||
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.new.submit">
|
||||
{t("crm.actions.create")}
|
||||
</button>
|
||||
<button type="button" onClick={checkDuplicates} className="text-muted-foreground text-sm underline" data-ui-id="ui.crm.new.checkDuplicates">
|
||||
{t("crm.actions.checkDuplicates")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CRM_MODULE_KEY };
|
||||
@@ -1,106 +0,0 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import AddressBookIcon from "~/components/ui/icons/crm/AddressBookIcon";
|
||||
import AddressBookIconFilled from "~/components/ui/icons/crm/AddressBookIconFilled";
|
||||
import CompanyIcon from "~/components/ui/icons/crm/CompanyIcon";
|
||||
import CompanyIconFilled from "~/components/ui/icons/crm/CompanyIconFilled";
|
||||
import FormIcon from "~/components/ui/icons/crm/FormIcon";
|
||||
import FormIconFilled from "~/components/ui/icons/crm/FormIconFilled";
|
||||
import IncreaseIcon from "~/components/ui/icons/crm/IncreaseIcon";
|
||||
import IncreaseIconFilled from "~/components/ui/icons/crm/IncreaseIconFilled";
|
||||
import UsDollarCircled from "~/components/ui/icons/crm/UsDollarCircled";
|
||||
import UsDollarCircledFilled from "~/components/ui/icons/crm/UsDollarCircledFilled";
|
||||
import SidebarIconsLayout, { IconDto } from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import CrmService, { CrmConfigurationError } from "~/modules/crm/services/CrmService";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { featureKeys } from "@toolctrl/entitlements";
|
||||
import { requireTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
|
||||
import { translateEntityTitlePlural } from "~/utils/i18n/translateLabel";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireTenantProductAccess({ request, params, featureKey: featureKeys.crmBasic });
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: t("pages.adminCrm.metaTitle", { appName: process.env.APP_NAME }),
|
||||
};
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
try {
|
||||
await CrmService.validate(tenantId);
|
||||
} catch (error) {
|
||||
if (error instanceof CrmConfigurationError) {
|
||||
throw new Response(t("crm.newsletter.errors.integrationMissing"), { status: 503 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
const items: IconDto[] = [
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
href: UrlUtils.getModulePath(params, "crm"),
|
||||
exact: true,
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
];
|
||||
["opportunities", "companies", "contacts"].forEach((slug) => {
|
||||
const entity = appOrAdminData.entities.find((x) => x.slug === slug);
|
||||
if (entity) {
|
||||
items.push({
|
||||
name: translateEntityTitlePlural(t, i18n, entity),
|
||||
href: UrlUtils.getModulePath(params, `crm/${slug}`),
|
||||
icon: getIcons(entity.slug)?.icon,
|
||||
iconSelected: getIcons(entity.slug)?.iconSelected,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function getIcons(entitySlug: string) {
|
||||
if (entitySlug === "opportunities") {
|
||||
return {
|
||||
icon: <UsDollarCircled className="h-5 w-5" />,
|
||||
iconSelected: <UsDollarCircledFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "companies") {
|
||||
return {
|
||||
icon: <CompanyIcon className="h-5 w-5" />,
|
||||
iconSelected: <CompanyIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "contacts") {
|
||||
return {
|
||||
icon: <AddressBookIcon className="h-5 w-5" />,
|
||||
iconSelected: <AddressBookIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "submissions") {
|
||||
return {
|
||||
icon: <FormIcon className="h-5 w-5" />,
|
||||
iconSelected: <FormIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
}
|
||||
}
|
||||
return (
|
||||
<SidebarIconsLayout label={{ align: "right" }} items={items}>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowNewRoute from "~/modules/rows/components/RowNewRoute";
|
||||
import { Rows_New } from "~/modules/rows/routes/Rows_New.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_New.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_New.action(args);
|
||||
|
||||
export default () => <RowNewRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Relationships } from "~/modules/rows/routes/Rows_Relationships.server";
|
||||
import RowsRelationshipsRoute from "~/modules/rows/components/RowsRelationshipsRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Relationships.loader(args);
|
||||
|
||||
export default () => <RowsRelationshipsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowsViewRoute from "~/modules/rows/components/RowsViewRoute";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_List.LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<RowsViewRoute
|
||||
key={data.rowsData.entity.id}
|
||||
rowsData={data.rowsData}
|
||||
items={data.rowsData.items}
|
||||
routes={data.routes}
|
||||
saveCustomViews={true}
|
||||
permissions={{
|
||||
create: getUserHasPermission(appOrAdminData, getEntityPermission(data.rowsData.entity, "create")),
|
||||
}}
|
||||
currentSession={{
|
||||
user: appOrAdminData.user,
|
||||
isSuperAdmin: appOrAdminData.isSuperAdmin,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import RowsList from "~/components/entities/rows/RowsList";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import CrmService, { CrmSummaryDto } from "~/modules/crm/services/CrmService";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { RowDisplayDefaultProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
summary: CrmSummaryDto;
|
||||
routes: EntitiesApi.Routes;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const data: LoaderData = {
|
||||
title: t("pages.adminCrm.metaTitle", { appName: process.env.APP_NAME }),
|
||||
summary: await CrmService.getSummary(tenantId),
|
||||
routes: EntitiesApi.getNoCodeRoutes({ request, params }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("shared.overview")}</h3>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-3">
|
||||
<Link
|
||||
to={UrlUtils.getModulePath(params, "crm/companies")}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.companies")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.companies, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={UrlUtils.getModulePath(params, "crm/contacts")}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.contacts")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.contacts, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={UrlUtils.getModulePath(params, "crm/opportunities")}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground flex items-center space-x-2 truncate text-xs font-medium uppercase">
|
||||
<ColorBadge color={Colors.GREEN} />
|
||||
<div>{t("pages.adminCrm.opportunities")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 flex items-baseline space-x-1 truncate text-2xl font-semibold">
|
||||
<div>{formatters.currency(data.summary.opportunities.value, "USD", { maximumFractionDigits: 0 })}</div>
|
||||
<div className="text-muted-foreground text-xs font-normal lowercase">
|
||||
{t("pages.adminCrm.openOpportunitiesCount", {
|
||||
count: data.summary.opportunities.count,
|
||||
formattedCount: formatters.number(data.summary.opportunities.count, { maximumFractionDigits: 0 }),
|
||||
})}
|
||||
</div>
|
||||
</dd>
|
||||
</Link>
|
||||
</dl>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-muted-foreground text-sm font-medium">{t("pages.adminCrm.opportunities")}</h3>
|
||||
<Link
|
||||
to={UrlUtils.getModulePath(params, "crm/opportunities/new")}
|
||||
aria-label={t("pages.adminCrm.createOpportunity")}
|
||||
className="text-foreground bg-secondary hover:bg-secondary/90 inline-flex min-h-10 min-w-10 items-center justify-center rounded-full p-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600"
|
||||
>
|
||||
<PlusIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</Link>
|
||||
</div>
|
||||
<RowsList
|
||||
view="board"
|
||||
entity="opportunity"
|
||||
items={data.summary.data.openOpportunities}
|
||||
readOnly={true}
|
||||
columns={[
|
||||
{ name: "name", title: t("pages.adminCrm.columns.name"), visible: true },
|
||||
{ name: "value", title: t("pages.adminCrm.columns.value"), visible: true },
|
||||
{ name: "expectedCloseDate", title: t("pages.adminCrm.columns.expectedCloseDate"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_AT, title: t("shared.createdAt"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_BY, title: t("shared.createdBy"), visible: true },
|
||||
]}
|
||||
routes={data.routes}
|
||||
onClickRoute={(i) => UrlUtils.getModulePath(params, `crm/opportunities/${i.id}`)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loadDashboardStreamSnapshot } from "~/services/dashboard/dashboard.server";
|
||||
import { eventStream } from "~/utils/stream/event-stream";
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return eventStream(request.signal, (send) => {
|
||||
let closed = false;
|
||||
void loadDashboardStreamSnapshot({ request, params }).then((snapshot) => {
|
||||
if (!closed) send({ event: "dashboard.snapshot", data: JSON.stringify(snapshot) });
|
||||
});
|
||||
const heartbeat = setInterval(() => {
|
||||
send({ event: "dashboard.heartbeat", data: JSON.stringify({ at: new Date().toISOString() }) });
|
||||
}, 30_000);
|
||||
return () => {
|
||||
closed = true;
|
||||
clearInterval(heartbeat);
|
||||
};
|
||||
});
|
||||
}
|
||||
+75
-3
@@ -15,6 +15,8 @@ import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { loadAppData } from "~/utils/data/.server/appData";
|
||||
import { evaluateDashboardModuleGates, type DashboardModuleGateDecision } from "~/services/dashboard-registry/gating.server";
|
||||
import { getDashboardModuleDefinitions, type DashboardModuleDefinition, type DashboardModuleId } from "~/services/dashboard-registry/registry.server";
|
||||
import { loadDashboardVM } from "~/services/dashboard/dashboard.server";
|
||||
import { getFirstStepsChecklist } from "~/utils/services/.server/akP20OnboardingService";
|
||||
|
||||
const translatedT = vi.fn((key: string) => `translated:${key}`);
|
||||
const computedGte = new Date("2026-02-03T04:05:06.000Z");
|
||||
@@ -22,6 +24,47 @@ const tenant = { id: "tenant_1", slug: "acme" };
|
||||
const appData = { mySubscription: { products: [], trial: { active: false, period: "trial-ended" } } };
|
||||
const stats = [{ name: "Contacts", stat: "7", previousStat: "3" }];
|
||||
const dashboardData = { users: 4 };
|
||||
const firstStepsChecklist = {
|
||||
id: "checklist_1",
|
||||
status: "active",
|
||||
dismissed: false,
|
||||
completedCount: 2,
|
||||
totalCount: 4,
|
||||
percentComplete: 50,
|
||||
items: [],
|
||||
};
|
||||
const dashboardVm = {
|
||||
activeRole: "office",
|
||||
generatedAt: "2026-07-01T00:00:00.000Z",
|
||||
streamUrl: "/acme/dashboard.stream?role=office",
|
||||
liveUpdatesEnabled: true,
|
||||
canCustomize: true,
|
||||
roles: [
|
||||
{
|
||||
role: "office",
|
||||
nameKey: "app.dashboard.roles.office.name",
|
||||
descriptionKey: "app.dashboard.roles.office.description",
|
||||
mobileFirst: false,
|
||||
isDefault: true,
|
||||
widgets: [
|
||||
{
|
||||
key: "projects.kpis",
|
||||
titleKey: "app.dashboard.widgets.projectKpis.title",
|
||||
descriptionKey: "app.dashboard.widgets.projectKpis.description",
|
||||
domain: "projects",
|
||||
kind: "kpi",
|
||||
period: "30d",
|
||||
visible: true,
|
||||
loadingMode: "lazy",
|
||||
metrics: [{ labelKey: "app.dashboard.metrics.activeProjects", value: "3" }],
|
||||
items: [],
|
||||
position: { x: 0, y: 1 },
|
||||
size: { w: 4, h: 2 },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const registryModules = getDashboardModuleDefinitions();
|
||||
const getRegistryModule = (moduleId: DashboardModuleId): DashboardModuleDefinition => {
|
||||
const module = registryModules.find((definition) => definition.id === moduleId);
|
||||
@@ -82,6 +125,10 @@ vi.mock("~/utils/data/.server/appData", () => ({
|
||||
loadAppData: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/akP20OnboardingService", () => ({
|
||||
getFirstStepsChecklist: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
@@ -98,6 +145,14 @@ vi.mock("~/services/dashboard-registry/gating.server", async (importOriginal) =>
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/services/dashboard/dashboard.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/services/dashboard/dashboard.server")>();
|
||||
return {
|
||||
...actual,
|
||||
loadDashboardVM: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({
|
||||
serverTimingHeaders: vi.fn(),
|
||||
}));
|
||||
@@ -128,7 +183,7 @@ vi.mock("~/components/ui/errors/ServerError", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAppData", () => ({
|
||||
useAppData: vi.fn(() => ({ user: {}, permissions: ["app.dashboard.view"] })),
|
||||
useAppData: vi.fn(() => ({ user: {}, permissions: ["app.dashboard.view", "dashboard.read", "dashboard.customize"] })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({
|
||||
@@ -146,15 +201,18 @@ vi.mock("react-i18next", () => ({
|
||||
describe("app tenant dashboard route contract", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: translatedT } as never);
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
|
||||
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
||||
vi.mocked(requireAuth).mockResolvedValue({ userId: "user_1" } as never);
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
dashboard: dashboardVm,
|
||||
stats,
|
||||
modules: [summaryModule],
|
||||
moduleDiagnostics: [],
|
||||
firstStepsChecklist,
|
||||
};
|
||||
moduleDecisions = [
|
||||
{ module: summaryModule, allowed: true },
|
||||
@@ -166,6 +224,8 @@ describe("app tenant dashboard route contract", () => {
|
||||
];
|
||||
vi.mocked(loadAppData).mockResolvedValue(appData as never);
|
||||
vi.mocked(evaluateDashboardModuleGates).mockResolvedValue(moduleDecisions as never);
|
||||
vi.mocked(loadDashboardVM).mockResolvedValue(dashboardVm as never);
|
||||
vi.mocked(getFirstStepsChecklist).mockResolvedValue(firstStepsChecklist as never);
|
||||
vi.mocked(getAppDashboardStats).mockResolvedValue(stats as never);
|
||||
vi.mocked(loadDashboardData).mockResolvedValue(dashboardData as never);
|
||||
vi.mocked(PeriodHelper.getGreaterThanOrEqualsFromRequest).mockReturnValue(computedGte);
|
||||
@@ -190,6 +250,8 @@ describe("app tenant dashboard route contract", () => {
|
||||
expect(PeriodHelper.getGreaterThanOrEqualsFromRequest).toHaveBeenCalledWith({ request });
|
||||
expect(getAppDashboardStats).toHaveBeenCalledWith({ t: translatedT, tenant, gte: computedGte });
|
||||
expect(loadDashboardData).toHaveBeenCalledWith({ request, params });
|
||||
expect(loadDashboardVM).toHaveBeenCalledWith({ request, params });
|
||||
expect(getFirstStepsChecklist).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" });
|
||||
expect(evaluateDashboardModuleGates).toHaveBeenCalledWith({
|
||||
request,
|
||||
params,
|
||||
@@ -201,11 +263,13 @@ describe("app tenant dashboard route contract", () => {
|
||||
});
|
||||
expect(vi.mocked(evaluateDashboardModuleGates).mock.calls[0]?.[0].redirectPaths?.plan).toBe("/plan-required/acme");
|
||||
expect(body).toMatchObject({
|
||||
title: "translated:app.sidebar.dashboard | ToolCTRL",
|
||||
title: "translated:app.sidebar.dashboard | HiveGrid",
|
||||
users: 4,
|
||||
dashboard: dashboardVm,
|
||||
stats,
|
||||
modules: [summaryModule],
|
||||
moduleDiagnostics: [moduleDecisions[1].diagnostic],
|
||||
firstStepsChecklist,
|
||||
});
|
||||
expect(body.modules.map((module: DashboardModuleDefinition) => module.id)).toEqual(["summary-stats"]);
|
||||
expect(body.moduleDiagnostics.map((diagnostic: { moduleId: DashboardModuleId }) => diagnostic.moduleId)).toEqual(["priority-insights"]);
|
||||
@@ -237,15 +301,19 @@ describe("app tenant dashboard route contract", () => {
|
||||
expect(screen.getByRole("heading", { name: "app.dashboard.summary" })).toBeInTheDocument();
|
||||
expect(screen.getByText("Contacts")).toBeInTheDocument();
|
||||
expect(screen.getByText("7")).toBeInTheDocument();
|
||||
expect(screen.getByText("onboarding.firstSteps.dashboardTitle")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "onboarding.firstSteps.open" })).toHaveAttribute("href", "/onboarding/checklist");
|
||||
expect(screen.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("omits gated summary content when the summary module is feature-disabled", () => {
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
dashboard: dashboardVm,
|
||||
stats,
|
||||
modules: [],
|
||||
moduleDiagnostics: [{ moduleId: "summary-stats", source: "feature-flag", reason: "feature-disabled", redirectPath: "/feature-disabled?tenant=acme" }],
|
||||
firstStepsChecklist,
|
||||
};
|
||||
|
||||
render(
|
||||
@@ -264,9 +332,11 @@ describe("app tenant dashboard route contract", () => {
|
||||
it("renders plan-required diagnostics with the safe tenant-aware plan link and no gated module content", () => {
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
dashboard: dashboardVm,
|
||||
stats,
|
||||
modules: [summaryModule],
|
||||
moduleDiagnostics: [{ moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" }],
|
||||
firstStepsChecklist,
|
||||
};
|
||||
|
||||
render(
|
||||
@@ -284,11 +354,13 @@ describe("app tenant dashboard route contract", () => {
|
||||
it("renders feature-disabled diagnostics with only the safe fallback link and no gated module content", () => {
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
dashboard: dashboardVm,
|
||||
stats,
|
||||
modules: [summaryModule],
|
||||
moduleDiagnostics: [
|
||||
{ moduleId: "subscription-health", source: "feature-flag", reason: "feature-disabled", redirectPath: "https://unsafe.example.com/feature" },
|
||||
],
|
||||
firstStepsChecklist,
|
||||
};
|
||||
|
||||
render(
|
||||
|
||||
+126
-8
@@ -19,7 +19,6 @@ import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { Fragment } from "react";
|
||||
import { loadAppData } from "~/utils/data/.server/appData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
@@ -30,8 +29,13 @@ import {
|
||||
type DashboardModuleGateDiagnostic,
|
||||
} from "~/services/dashboard-registry/gating.server";
|
||||
import type { DashboardModuleDefinition, DashboardModuleId } from "~/services/dashboard-registry/registry.server";
|
||||
import { loadDashboardVM, type DashboardVM, type DashboardWidgetVM } from "~/services/dashboard/dashboard.server";
|
||||
import { getFirstStepsChecklist } from "~/utils/services/.server/akP20OnboardingService";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
const DASHBOARD_READ_PERMISSION = "dashboard.read";
|
||||
const LEGACY_DASHBOARD_PERMISSION = "app.dashboard.view";
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = DashboardLoaderData & {
|
||||
@@ -39,6 +43,8 @@ type LoaderData = DashboardLoaderData & {
|
||||
stats: Stat[];
|
||||
modules: DashboardModuleDefinition[];
|
||||
moduleDiagnostics: DashboardModuleGateDiagnostic[];
|
||||
dashboard: DashboardVM;
|
||||
firstStepsChecklist: Awaited<ReturnType<typeof getFirstStepsChecklist>>;
|
||||
};
|
||||
|
||||
function isDashboardModuleVisible(modules: readonly DashboardModuleDefinition[], moduleId: DashboardModuleId) {
|
||||
@@ -54,7 +60,7 @@ function getSafeModuleNoticePath(diagnostic: DashboardModuleGateDiagnostic) {
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const userInfo = await requireAuth({ request, params });
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "app.$tenant.dashboard");
|
||||
let { t } = await getTranslations(request);
|
||||
const { tenantId, appData } = await time(
|
||||
@@ -69,12 +75,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
if (!tenant) {
|
||||
throw Response.json({ error: t("app.dashboard.errors.tenantNotFound") }, { status: 404 });
|
||||
}
|
||||
await verifyUserHasPermission(request, "app.dashboard.view", tenantId);
|
||||
|
||||
const { stats, dashboardData, moduleDecisions } = await time(
|
||||
const { stats, dashboardData, dashboard, firstStepsChecklist, moduleDecisions } = await time(
|
||||
promiseHash({
|
||||
stats: getAppDashboardStats({ t, tenant, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) }),
|
||||
dashboardData: loadDashboardData({ request, params }),
|
||||
dashboard: loadDashboardVM({ request, params }),
|
||||
firstStepsChecklist: getFirstStepsChecklist({ tenantId, userId: userInfo.userId }),
|
||||
moduleDecisions: evaluateDashboardModuleGates({
|
||||
request,
|
||||
params,
|
||||
@@ -94,6 +100,8 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
stats,
|
||||
modules: getVisibleDashboardModules(moduleDecisions),
|
||||
moduleDiagnostics: getDashboardModuleDiagnostics(moduleDecisions),
|
||||
dashboard,
|
||||
firstStepsChecklist,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
@@ -104,6 +112,9 @@ export default function DashboardRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const canViewSummary = isDashboardModuleVisible(data.modules, "summary-stats");
|
||||
const canViewDashboard =
|
||||
getUserHasPermission(appData, DASHBOARD_READ_PERMISSION) || getUserHasPermission(appData, LEGACY_DASHBOARD_PERMISSION);
|
||||
const activeRole = data.dashboard.roles.find((role) => role.role === data.dashboard.activeRole) ?? data.dashboard.roles[0];
|
||||
|
||||
return (
|
||||
<main className="relative z-0 flex-1 pb-8" data-ui-id="ui.dashboard.page">
|
||||
@@ -113,15 +124,53 @@ export default function DashboardRoute() {
|
||||
</div>
|
||||
|
||||
<div className="mx-auto grid max-w-5xl gap-5 px-4 py-5 sm:px-8">
|
||||
{getUserHasPermission(appData, "app.dashboard.view") ? (
|
||||
{canViewDashboard ? (
|
||||
<Fragment>
|
||||
{activeRole ? (
|
||||
<section className="space-y-4" data-ui-id="ui.dashboard.roleLayouts">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-foreground text-2xl font-semibold">{t("app.dashboard.title")}</h1>
|
||||
<p className="text-muted-foreground text-sm">{t(activeRole.descriptionKey)}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2" role="tablist" aria-label={t("app.dashboard.roleSwitcher.label")}>
|
||||
{data.dashboard.roles.map((role) => (
|
||||
<Link
|
||||
key={role.role}
|
||||
to={`?role=${role.role}`}
|
||||
role="tab"
|
||||
aria-selected={role.role === data.dashboard.activeRole}
|
||||
className={`rounded-md border px-3 py-2 text-sm font-medium ${
|
||||
role.role === data.dashboard.activeRole
|
||||
? "border-neutral-900 bg-neutral-900 text-white"
|
||||
: "border-border bg-background text-foreground hover:bg-secondary"
|
||||
}`}
|
||||
data-ui-id={`ui.dashboard.roleSwitcher.${role.role}`}
|
||||
>
|
||||
{t(role.nameKey)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-muted-foreground flex flex-wrap items-center gap-3 text-xs">
|
||||
<span>{t("app.dashboard.live.enabled")}</span>
|
||||
<span>{t("app.dashboard.live.lastUpdated", { at: data.dashboard.generatedAt })}</span>
|
||||
{data.dashboard.canCustomize ? <span>{t("app.dashboard.customize.available")}</span> : null}
|
||||
</div>
|
||||
<div className={activeRole.mobileFirst ? "grid gap-3 sm:grid-cols-2 xl:grid-cols-3" : "grid gap-4 md:grid-cols-2 xl:grid-cols-3"}>
|
||||
{activeRole.widgets.map((widget) => (
|
||||
<DashboardWidgetCard key={widget.key} widget={widget} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
{canViewSummary && data.stats.length > 0 && (
|
||||
<div className="space-y-3 truncate p-1">
|
||||
<div className="space-y-3 p-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground grow leading-4 font-medium">{t("app.dashboard.summary")}</h3>
|
||||
<div>
|
||||
<InputSelect
|
||||
className="w-44"
|
||||
className="w-48 shrink-0"
|
||||
name="period"
|
||||
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
|
||||
options={PeriodFilters.map((f) => {
|
||||
@@ -167,6 +216,29 @@ export default function DashboardRoute() {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!data.firstStepsChecklist.dismissed && (
|
||||
<section className="rounded-md border p-4">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="text-foreground font-medium">{t("onboarding.firstSteps.dashboardTitle")}</h3>
|
||||
<p className="text-muted-foreground mt-1 text-sm">
|
||||
{data.firstStepsChecklist.percentComplete === 100
|
||||
? t("onboarding.firstSteps.dashboardComplete")
|
||||
: t("onboarding.firstSteps.dashboardProgress", {
|
||||
completed: data.firstStepsChecklist.completedCount,
|
||||
total: data.firstStepsChecklist.totalCount,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
<Link className="text-theme-600 text-sm underline" to="../onboarding/checklist">
|
||||
{t("onboarding.firstSteps.open")}
|
||||
</Link>
|
||||
</div>
|
||||
<div className="bg-muted mt-4 h-2 overflow-hidden rounded">
|
||||
<div className="bg-primary h-full" style={{ width: `${data.firstStepsChecklist.percentComplete}%` }} />
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</Fragment>
|
||||
) : (
|
||||
<div className="font-medium">{t("app.dashboard.noPermission")}</div>
|
||||
@@ -176,6 +248,52 @@ export default function DashboardRoute() {
|
||||
);
|
||||
}
|
||||
|
||||
function DashboardWidgetCard({ widget }: { widget: DashboardWidgetVM }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<section
|
||||
className="border-border bg-background flex min-h-32 flex-col gap-3 rounded-md border px-4 py-4 shadow-sm"
|
||||
data-ui-id={`ui.dashboard.widget.${widget.key}`}
|
||||
data-loading={widget.loadingMode}
|
||||
>
|
||||
<div>
|
||||
<h2 className="text-foreground text-sm font-semibold">{t(widget.titleKey)}</h2>
|
||||
<p className="text-muted-foreground mt-1 text-xs">{t(widget.descriptionKey)}</p>
|
||||
</div>
|
||||
{!widget.visible ? (
|
||||
<p className="text-muted-foreground rounded-md border border-dashed px-3 py-2 text-xs">{t("app.dashboard.widgets.permissionHidden")}</p>
|
||||
) : widget.metrics.length > 0 ? (
|
||||
<dl className="grid grid-cols-2 gap-2">
|
||||
{widget.metrics.map((metric) => (
|
||||
<div key={metric.labelKey} className="rounded-md bg-secondary px-3 py-2">
|
||||
<dt className="text-muted-foreground text-xs">{t(metric.labelKey)}</dt>
|
||||
<dd className="text-foreground mt-1 text-lg font-semibold">{metric.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
) : widget.items.length > 0 ? (
|
||||
<ul className="divide-border divide-y">
|
||||
{widget.items.map((item) => (
|
||||
<li key={item.id} className="flex items-center justify-between gap-3 py-2 text-sm">
|
||||
{item.href ? (
|
||||
<Link className="text-theme-600 min-w-0 truncate hover:underline" to={item.href}>
|
||||
{item.labelKey ? t(item.labelKey) : item.label}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-foreground min-w-0 truncate">{item.labelKey ? t(item.labelKey) : item.label}</span>
|
||||
)}
|
||||
{item.meta ? <span className="text-muted-foreground shrink-0 text-xs">{item.meta}</span> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-muted-foreground rounded-md border border-dashed px-3 py-2 text-xs">{t("app.dashboard.widgets.empty")}</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
-11
@@ -12,10 +12,8 @@ import ActivityHistoryIcon from "~/components/ui/icons/entities/ActivityHistoryI
|
||||
import ActivityHistoryIconFilled from "~/components/ui/icons/entities/ActivityHistoryIconFilled";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import CrmService from "~/modules/crm/services/CrmService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { featureKeys } from "@toolctrl/entitlements";
|
||||
import { featureKeys } from "@hivegrid/entitlements";
|
||||
import { requireTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
@@ -25,11 +23,11 @@ type LoaderData = {
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await requireTenantProductAccess({ request, params, featureKey: featureKeys.emailMarketing });
|
||||
// R-P14C: the legacy CrmService.validate gate (it validated the Entity-Builder
|
||||
// "contact" entity) is gone; the typed Kontakt model needs no bootstrap check.
|
||||
const data: LoaderData = {
|
||||
title: `${t("emailMarketing:title")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await CrmService.validate(tenantId);
|
||||
return data;
|
||||
};
|
||||
|
||||
@@ -49,12 +47,6 @@ export default () => {
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing:campaigns"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/campaigns"),
|
||||
icon: <MegaphoneIcon className="h-5 w-5" />,
|
||||
iconSelected: <MegaphoneIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing:activity"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/activity"),
|
||||
@@ -67,6 +59,20 @@ export default () => {
|
||||
icon: <SentIcon className="h-5 w-5" />,
|
||||
iconSelected: <SentIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
// AK-P14a — sending-domain verification (DKIM/SPF/DMARC) + BCC logging.
|
||||
name: t("email.domain.title"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/sending-domain"),
|
||||
icon: <SentIcon className="h-5 w-5" />,
|
||||
iconSelected: <SentIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
// AK-P14b — typed recipient segments (nested AND/OR filter, live count).
|
||||
name: t("emailMarketing.segment.tab"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/segments"),
|
||||
icon: <MegaphoneIcon className="h-5 w-5" />,
|
||||
iconSelected: <MegaphoneIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsEditRoute from "~/modules/emailMarketing/components/campaigns/CampaignsEditRoute";
|
||||
import { Campaigns_Edit } from "~/modules/emailMarketing/routes/Campaigns_Edit";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Campaigns_Edit.action(args);
|
||||
|
||||
export default () => <CampaignsEditRoute />;
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsListRoute from "~/modules/emailMarketing/components/campaigns/CampaignsListRoute";
|
||||
import { Campaigns_List } from "~/modules/emailMarketing/routes/Campaigns_List";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_List.loader(args);
|
||||
|
||||
export default () => <CampaignsListRoute />;
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsNewRoute from "~/modules/emailMarketing/components/campaigns/CampaignsNewRoute";
|
||||
import { Campaigns_New } from "~/modules/emailMarketing/routes/Campaigns_New";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Campaigns_New.action(args);
|
||||
|
||||
export default () => <CampaignsNewRoute />;
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
// AK-P14b · P14 Email-Marketing — Segmente screen (reachable typed vertical).
|
||||
//
|
||||
// Lives under the feature-gated email-marketing module. Lists the tenant's
|
||||
// recipient segments and lets an emailMarketing.manage user create one from a
|
||||
// nested AND/OR filter tree (validated by the segment engine) and preview the
|
||||
// live recipient count + auto-exclusion breakdown + sample against the typed R-P6
|
||||
// Kontakt model. Transitional functional UI (data-ui-id markers); the final
|
||||
// AND/OR filter-builder UX follows David's D-P14 delta (Dev-Nachzug, S8).
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, Form, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildSegmentVM, type SegmentVM } from "@hivegrid/view-models";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { loadEmailDomainContext, notFoundResponse, badRequestResponse } from "~/utils/integrations/emailDomainService.server";
|
||||
import { createSegment, listSegments, resolveSegment, SegmentServiceError, type SegmentListRow } from "~/modules/emailMarketing/services/SegmentService.server";
|
||||
|
||||
type LoaderData = {
|
||||
canManage: boolean;
|
||||
segments: SegmentListRow[];
|
||||
};
|
||||
|
||||
type ActionData =
|
||||
| { ok: true; intent: "create" }
|
||||
| { ok: true; intent: "preview"; vm: SegmentVM }
|
||||
| { ok: false; errorKey: string };
|
||||
|
||||
function canView(permissions: readonly string[]): boolean {
|
||||
return permissions.includes("emailMarketing.view") || permissions.includes("emailMarketing.manage");
|
||||
}
|
||||
function canManage(permissions: readonly string[]): boolean {
|
||||
return permissions.includes("emailMarketing.manage");
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!canView(ctx.permissions)) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const segments = await listSegments(ctx.tenantId);
|
||||
return Response.json({ canManage: canManage(ctx.permissions), segments } satisfies LoaderData);
|
||||
};
|
||||
|
||||
function parseFilter(raw: string): unknown {
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!canManage(ctx.permissions)) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const crmCtx = { userId: ctx.userId, permissions: ctx.permissions };
|
||||
const filterDefinition = parseFilter(String(form.get("filterDefinition") ?? ""));
|
||||
if (filterDefinition === undefined) {
|
||||
return Response.json({ ok: false, errorKey: "emailMarketing.segment.error.invalidShape" } satisfies ActionData);
|
||||
}
|
||||
|
||||
try {
|
||||
if (intent === "preview") {
|
||||
const resolution = await resolveSegment({ tenantId: ctx.tenantId, ctx: crmCtx, filterDefinition });
|
||||
const vm = buildSegmentVM({ ...resolution, isStaticSnapshot: false });
|
||||
return Response.json({ ok: true, intent: "preview", vm } satisfies ActionData);
|
||||
}
|
||||
if (intent === "create") {
|
||||
const name = String(form.get("name") ?? "").trim();
|
||||
if (!name) throw badRequestResponse();
|
||||
const isStaticSnapshot = String(form.get("isStaticSnapshot") ?? "") === "true";
|
||||
await createSegment({ tenantId: ctx.tenantId, ctx: crmCtx, name, filterDefinition, isStaticSnapshot });
|
||||
return Response.json({ ok: true, intent: "create" } satisfies ActionData);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof SegmentServiceError) {
|
||||
return Response.json({ ok: false, errorKey: error.messageKey } satisfies ActionData);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
throw badRequestResponse();
|
||||
};
|
||||
|
||||
export default function SegmentsRoute() {
|
||||
const { canManage: mayManage, segments } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const preview = actionData && actionData.ok && actionData.intent === "preview" ? actionData.vm : null;
|
||||
const errorKey = actionData && !actionData.ok ? actionData.errorKey : null;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-4" data-ui-id="email-marketing.segments">
|
||||
<header>
|
||||
<h1 className="text-lg font-semibold">{t("emailMarketing.segment.title")}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t("emailMarketing.segment.subtitle")}</p>
|
||||
</header>
|
||||
|
||||
{segments.length === 0 ? (
|
||||
<section className="rounded border border-dashed p-6 text-sm" data-ui-id="email-marketing.segments.empty">
|
||||
<p className="font-medium">{t("emailMarketing.segment.empty.headline")}</p>
|
||||
<p className="text-muted-foreground">{t("emailMarketing.segment.empty.body")}</p>
|
||||
</section>
|
||||
) : (
|
||||
<ul className="divide-y rounded border" data-ui-id="email-marketing.segments.list">
|
||||
{segments.map((s) => (
|
||||
<li key={s.id} className="flex items-center justify-between px-3 py-2 text-sm">
|
||||
<span className="font-medium">{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{s.isStaticSnapshot ? t("emailMarketing.segment.kind.static") : t("emailMarketing.segment.kind.dynamic")}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{errorKey && (
|
||||
<p className="rounded border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive" data-ui-id="email-marketing.segments.error">
|
||||
{t(errorKey)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{preview && preview.status === "ready" && preview.data && (
|
||||
<section className="space-y-3 rounded border p-3" data-ui-id="email-marketing.segments.preview">
|
||||
<p className="text-sm font-medium">
|
||||
{t("emailMarketing.segment.preview.eligible", { eligible: preview.data.eligible, matched: preview.data.matched })}
|
||||
</p>
|
||||
<ul className="space-y-1 text-xs text-muted-foreground">
|
||||
{preview.data.exclusion.map((row) => (
|
||||
<li key={row.reason}>
|
||||
{t(row.labelKey)}: {row.count}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{preview.data.sample.length > 0 && (
|
||||
<ul className="space-y-1 text-xs" data-ui-id="email-marketing.segments.sample">
|
||||
{preview.data.sample.map((row) => (
|
||||
<li key={row.kontaktId}>
|
||||
{row.name} · {row.email}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{mayManage && (
|
||||
<section className="space-y-3 rounded border p-4" data-ui-id="email-marketing.segments.create">
|
||||
<h2 className="text-sm font-medium">{t("emailMarketing.segment.create.title")}</h2>
|
||||
<p className="text-xs text-muted-foreground">{t("emailMarketing.segment.create.filterHint")}</p>
|
||||
<Form method="post" className="space-y-2">
|
||||
<input
|
||||
name="name"
|
||||
placeholder={t("emailMarketing.segment.create.namePlaceholder")}
|
||||
className="w-full rounded border px-2 py-1 text-sm"
|
||||
data-ui-id="email-marketing.segments.name"
|
||||
required
|
||||
/>
|
||||
<textarea
|
||||
name="filterDefinition"
|
||||
rows={6}
|
||||
defaultValue={'{\n "op": "and",\n "children": [\n { "field": "hasPrimaerEmail", "value": true }\n ]\n}'}
|
||||
className="w-full rounded border px-2 py-1 font-mono text-xs"
|
||||
data-ui-id="email-marketing.segments.filter"
|
||||
required
|
||||
/>
|
||||
<label className="flex items-center gap-2 text-xs">
|
||||
<input type="checkbox" name="isStaticSnapshot" value="true" />
|
||||
{t("emailMarketing.segment.create.staticLabel")}
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
name="intent"
|
||||
value="preview"
|
||||
className="rounded border px-3 py-1 text-sm"
|
||||
data-ui-id="email-marketing.segments.previewBtn"
|
||||
>
|
||||
{t("emailMarketing.segment.create.preview")}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
name="intent"
|
||||
value="create"
|
||||
className="rounded bg-primary px-3 py-1 text-sm text-primary-foreground"
|
||||
data-ui-id="email-marketing.segments.createBtn"
|
||||
>
|
||||
{t("emailMarketing.segment.create.submit")}
|
||||
</button>
|
||||
</div>
|
||||
</Form>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
// AK-P14a · P14 Email — Sende-Domain settings screen (reachable vertical).
|
||||
//
|
||||
// Lives under the feature-gated email-marketing module (parent layout calls
|
||||
// requireTenantProductAccess). Adds a tenant sending domain, shows the DKIM/SPF/
|
||||
// DMARC records to publish (with copy), the verification status ampel (driven by
|
||||
// the 5-minute worker probe) and the BCC-logging toggle. Transitional functional
|
||||
// UI (data-ui-id markers); Subframe polish follows David's D-P14 delta. The final
|
||||
// home may move to /settings/integrations/email per that delta (Dev-Nachzug).
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, Form, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildSendingDomainVM, type SendingDomainVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import {
|
||||
badRequestResponse,
|
||||
bccAddressFor,
|
||||
createSendingDomain,
|
||||
emailDomainCanManage,
|
||||
emailDomainCanView,
|
||||
getSendingDomainState,
|
||||
loadEmailDomainContext,
|
||||
normalizeDomainInput,
|
||||
notFoundResponse,
|
||||
setBccLogging,
|
||||
} from "~/utils/integrations/emailDomainService.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: SendingDomainVM;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!emailDomainCanView(ctx)) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const state = await getSendingDomainState(ctx.tenantId);
|
||||
const vm = buildSendingDomainVM({
|
||||
domain: state.domain
|
||||
? {
|
||||
id: state.domain.id,
|
||||
domain: state.domain.domain,
|
||||
status: state.domain.status,
|
||||
dkimSelector: state.domain.dkimSelector,
|
||||
dkimRecord: state.domain.dkimRecord,
|
||||
spfRecord: state.domain.spfRecord,
|
||||
dmarcRecord: state.domain.dmarcRecord,
|
||||
errorMessageKey: state.domain.lastError,
|
||||
}
|
||||
: null,
|
||||
bccAddress: bccAddressFor(tenantSlug),
|
||||
bccEnabled: state.bccEnabled,
|
||||
canManage: emailDomainCanManage(ctx),
|
||||
});
|
||||
return Response.json({ title: `${t("email.domain.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!emailDomainCanManage(ctx)) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
|
||||
if (intent === "create-domain") {
|
||||
const domain = normalizeDomainInput(String(form.get("domain") ?? ""));
|
||||
if (!domain) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
await createSendingDomain(ctx.tenantId, domain);
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
if (intent === "toggle-bcc") {
|
||||
const enabled = String(form.get("enabled") ?? "") === "true";
|
||||
await setBccLogging(ctx.tenantId, tenantSlug, enabled);
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
throw badRequestResponse();
|
||||
};
|
||||
|
||||
function CopyField({ value }: { value: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 overflow-x-auto rounded bg-muted px-2 py-1 text-xs">{value}</code>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded border px-2 py-1 text-xs"
|
||||
onClick={() => {
|
||||
void navigator.clipboard?.writeText(value);
|
||||
}}
|
||||
>
|
||||
{t("email.domain.copy")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SendingDomainRoute() {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-4" data-ui-id="email.sending-domain">
|
||||
<header>
|
||||
<h1 className="text-lg font-semibold">{t("email.domain.title")}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t("email.domain.subtitle")}</p>
|
||||
</header>
|
||||
|
||||
{vm.status === "empty" && (
|
||||
<section className="rounded border border-dashed p-6 text-sm" data-ui-id="email.domain.empty">
|
||||
<p className="font-medium">{t("email.domain.empty.headline")}</p>
|
||||
<p className="mb-4 text-muted-foreground">{t("email.domain.empty.body")}</p>
|
||||
<Form method="post" className="flex items-center gap-2">
|
||||
<input type="hidden" name="intent" value="create-domain" />
|
||||
<input name="domain" placeholder="acme.de" className="rounded border px-2 py-1 text-sm" data-ui-id="email.domain.input" required />
|
||||
<button type="submit" className="rounded bg-primary px-3 py-1 text-sm text-primary-foreground" data-ui-id="email.domain.add">
|
||||
{t("email.domain.add")}
|
||||
</button>
|
||||
</Form>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{vm.status === "ready" && vm.data && (
|
||||
<section className="space-y-5" data-ui-id="email.domain.detail">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="font-mono text-sm">{vm.data.domain}</span>
|
||||
<span
|
||||
className="rounded-full px-2 py-0.5 text-xs"
|
||||
data-ui-id="email.domain.status"
|
||||
data-tone={vm.data.statusTone}
|
||||
>
|
||||
{t(vm.data.statusLabelKey)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{vm.data.showFailure && vm.data.errorMessageKey && (
|
||||
<p className="rounded border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive" data-ui-id="email.domain.error">
|
||||
{t(vm.data.errorMessageKey)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">{t("email.domain.records.hint")}</p>
|
||||
{vm.data.records.map((record) => (
|
||||
<div key={record.kind} className="rounded border p-3" data-ui-id={`email.domain.record.${record.kind}`}>
|
||||
<div className="mb-1 text-sm font-medium">{t(record.labelKey)}</div>
|
||||
{record.host && <div className="mb-1 text-xs text-muted-foreground">{record.host}</div>}
|
||||
{record.value ? <CopyField value={record.value} /> : <span className="text-xs text-muted-foreground">{t("email.domain.records.pending")}</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="rounded border p-3" data-ui-id="email.domain.bcc">
|
||||
<div className="mb-1 text-sm font-medium">{t("email.domain.bcc.title")}</div>
|
||||
<p className="mb-2 text-xs text-muted-foreground">{t("email.domain.bcc.hint")}</p>
|
||||
{vm.data.bccAddress && <CopyField value={vm.data.bccAddress} />}
|
||||
{vm.data.canManage && (
|
||||
<Form method="post" className="mt-2">
|
||||
<input type="hidden" name="intent" value="toggle-bcc" />
|
||||
<input type="hidden" name="enabled" value={vm.data.bccEnabled ? "false" : "true"} />
|
||||
<button type="submit" className="rounded border px-3 py-1 text-xs" data-ui-id="email.domain.bcc.toggle">
|
||||
{vm.data.bccEnabled ? t("email.domain.bcc.disable") : t("email.domain.bcc.enable")}
|
||||
</button>
|
||||
</Form>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
// VA-P23 · message/thread detail route (M09 Block F detail). The loader
|
||||
// sanitizes every body SERVER-SIDE (dompurify + external-image blocking with
|
||||
// the "Bilder laden" opt-in via ?images=1) and builds the thread VM. Actions:
|
||||
// link override (set/clear — manual wins, audited as email_match_changed +
|
||||
// activity), attachment import into v1-Files, read toggle. Visibility follows
|
||||
// read_own/read_all (mailbox set); a miss is a 404 (A.5.3).
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, useSearchParams, Form, Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import {
|
||||
buildEmailMessageDetailVM,
|
||||
emailMatchSourceKey,
|
||||
summarizeAddresses,
|
||||
type EmailAttachmentVM,
|
||||
type EmailLinkBadge,
|
||||
type EmailMessageDetailVM,
|
||||
type EmailThreadMessageVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import {
|
||||
canReadAllMailboxes,
|
||||
canWriteEmail,
|
||||
loadEmailInboxContext,
|
||||
requireEmailRead,
|
||||
requireEmailWrite,
|
||||
} from "~/modules/emailInbox/routes/emailInboxAccess.server";
|
||||
import { EMAIL_INBOX_MODULE_KEY, emailComposePath, emailInboxPath, notFoundResponse } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
|
||||
import {
|
||||
bulkUpdateMessages,
|
||||
getMessageForMailboxes,
|
||||
listImportedAttachmentFiles,
|
||||
listMailboxesForTenant,
|
||||
listMailboxesForUser,
|
||||
listThreadMessages,
|
||||
setMessageMatchOverride,
|
||||
} from "~/modules/emailInbox/db/emailInbox.db.server";
|
||||
import { EmailAttachmentError, importAttachmentToFiles, listProviderAttachments } from "~/modules/emailInbox/services/EmailAttachmentService.server";
|
||||
import { renderPlainTextAsHtml, sanitizeEmailHtml } from "~/modules/emailInbox/services/emailHtmlSanitizer";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: EmailMessageDetailVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
|
||||
try {
|
||||
requireEmailRead(ctx);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const messageId = params.id ?? "";
|
||||
const allowExternalImages = new URL(request.url).searchParams.get("images") === "1";
|
||||
|
||||
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
|
||||
const mailboxIds = mailboxes.map((m) => m.id);
|
||||
const message = await getMessageForMailboxes(ctx.tenantId, mailboxIds, messageId);
|
||||
if (!message) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const mailbox = mailboxes.find((m) => m.id === message.mailboxId);
|
||||
|
||||
const threadRows = message.providerThreadId
|
||||
? await listThreadMessages(ctx.tenantId, mailboxIds, message.providerThreadId)
|
||||
: [message];
|
||||
|
||||
const thread: EmailThreadMessageVM[] = threadRows.map((row) => {
|
||||
const rawHtml = row.bodyHtml ?? (row.bodyText ? renderPlainTextAsHtml(row.bodyText) : "");
|
||||
const sanitized = row.bodyHtml ? sanitizeEmailHtml(rawHtml, { allowExternalImages }) : { html: rawHtml, blockedImageCount: 0 };
|
||||
return {
|
||||
id: row.id,
|
||||
direction: row.direction,
|
||||
fromName: row.fromName,
|
||||
fromAddress: row.fromAddress,
|
||||
toSummary: summarizeAddresses(row.toAddresses),
|
||||
ccSummary: summarizeAddresses(row.ccAddresses) || null,
|
||||
subject: row.subject,
|
||||
safeBodyHtml: sanitized.html,
|
||||
blockedImageCount: sanitized.blockedImageCount,
|
||||
sentAt: row.sentAt.toISOString(),
|
||||
isRead: row.isRead,
|
||||
isFocused: row.id === message.id,
|
||||
collapsedByDefault: row.id !== message.id,
|
||||
};
|
||||
});
|
||||
|
||||
// Attachments: provider metadata (live) merged with already-imported Files.
|
||||
const imported = await listImportedAttachmentFiles(ctx.tenantId, message.id);
|
||||
const providerAttachments = message.hasAttachments && mailbox
|
||||
? await listProviderAttachments({ tenantId: ctx.tenantId, mailboxId: message.mailboxId, provider: mailbox.provider, providerMessageId: message.providerMessageId })
|
||||
: [];
|
||||
const importedByRole = new Map(imported.map((f) => [f.displayName, f.fileId]));
|
||||
const attachments: EmailAttachmentVM[] = providerAttachments.map((a) => {
|
||||
const importedFileId = importedByRole.get(a.filename) ?? null;
|
||||
return {
|
||||
attachmentId: a.attachmentId,
|
||||
filename: a.filename,
|
||||
sizeBytes: a.sizeBytes,
|
||||
importedFileId,
|
||||
downloadHref: importedFileId ? `/${tenantSlug}/files/${importedFileId}` : null,
|
||||
};
|
||||
});
|
||||
|
||||
const links: EmailLinkBadge[] = [
|
||||
...(message.matchedKontaktId ? [{ type: "kontakt" as const, id: message.matchedKontaktId, href: `/${tenantSlug}/contacts/${message.matchedKontaktId}` }] : []),
|
||||
...(message.matchedLeadId ? [{ type: "lead" as const, id: message.matchedLeadId, href: `/${tenantSlug}/leads/${message.matchedLeadId}` }] : []),
|
||||
...(message.matchedProjektId ? [{ type: "projekt" as const, id: message.matchedProjektId, href: `/${tenantSlug}/projects/${message.matchedProjektId}` }] : []),
|
||||
];
|
||||
|
||||
const vm = buildEmailMessageDetailVM({
|
||||
focusedId: message.id,
|
||||
subject: message.subject,
|
||||
mailbox: { emailAddress: mailbox?.emailAddress ?? "", provider: mailbox?.provider ?? "gmail" },
|
||||
thread,
|
||||
attachments,
|
||||
match: {
|
||||
links,
|
||||
confidence: message.matchConfidence,
|
||||
sourceKey: emailMatchSourceKey(message.matchConfidence),
|
||||
isManual: message.manualOverrideAt !== null,
|
||||
},
|
||||
canWrite: canWriteEmail(ctx),
|
||||
replyHref: `${emailComposePath(tenantSlug)}?replyTo=${message.id}`,
|
||||
forwardHref: `${emailComposePath(tenantSlug)}?forward=${message.id}`,
|
||||
backHref: emailInboxPath(tenantSlug),
|
||||
allowExternalImages,
|
||||
});
|
||||
const title = `${message.subject ?? t("emailInbox.list.noSubject")} | ${process.env.APP_NAME}`;
|
||||
return Response.json({ title, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
|
||||
try {
|
||||
requireEmailRead(ctx);
|
||||
requireEmailWrite(ctx);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
await validateCSRFToken(request);
|
||||
const messageId = params.id ?? "";
|
||||
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
|
||||
const mailboxIds = mailboxes.map((m) => m.id);
|
||||
const message = await getMessageForMailboxes(ctx.tenantId, mailboxIds, messageId);
|
||||
if (!message) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
|
||||
if (intent === "set-link" || intent === "clear-link") {
|
||||
const targets =
|
||||
intent === "clear-link"
|
||||
? { kontaktId: null, leadId: null, projektId: null }
|
||||
: {
|
||||
kontaktId: String(form.get("kontaktId") ?? "").trim() || null,
|
||||
leadId: String(form.get("leadId") ?? "").trim() || null,
|
||||
projektId: String(form.get("projektId") ?? "").trim() || null,
|
||||
};
|
||||
await setMessageMatchOverride(ctx.tenantId, mailboxIds, messageId, ctx.userId, targets);
|
||||
// M09 Block H: the manual override is an audit event (email_match_changed).
|
||||
await createAuditEvent({
|
||||
tenantId: ctx.tenantId,
|
||||
actorId: ctx.userId,
|
||||
actorType: "user",
|
||||
action: "email_match_changed",
|
||||
targetType: "email_message",
|
||||
targetId: messageId,
|
||||
sourceModule: "email-inbox",
|
||||
metadata: {
|
||||
previous: { kontaktId: message.matchedKontaktId, leadId: message.matchedLeadId, projektId: message.matchedProjektId, confidence: message.matchConfidence },
|
||||
next: targets,
|
||||
},
|
||||
}).catch(() => undefined);
|
||||
// The re-assignment is user-visible on the newly linked entity's timeline.
|
||||
const subject = targets.kontaktId
|
||||
? { subjectType: "contact" as const, subjectId: targets.kontaktId }
|
||||
: targets.leadId
|
||||
? { subjectType: "lead" as const, subjectId: targets.leadId }
|
||||
: targets.projektId
|
||||
? { subjectType: "project" as const, subjectId: targets.projektId }
|
||||
: null;
|
||||
if (subject) {
|
||||
await logActivity({
|
||||
tenantId: ctx.tenantId,
|
||||
actorUserId: ctx.userId,
|
||||
actorKind: "user",
|
||||
activityType: message.direction === "inbound" ? "email_received" : "email_sent",
|
||||
subjectType: subject.subjectType,
|
||||
subjectId: subject.subjectId,
|
||||
summaryText: `E-Mail manuell zugeordnet: ${message.subject?.trim() ? `„${message.subject.trim()}“` : "(ohne Betreff)"}`,
|
||||
metadata: { emailMessageId: messageId, manualOverride: true },
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
if (intent === "import-attachment") {
|
||||
const attachmentId = String(form.get("attachmentId") ?? "");
|
||||
const mailbox = mailboxes.find((m) => m.id === message.mailboxId);
|
||||
if (!attachmentId || !mailbox) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
try {
|
||||
const { fileId } = await importAttachmentToFiles({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
mailboxId: message.mailboxId,
|
||||
provider: mailbox.provider,
|
||||
messageId,
|
||||
providerMessageId: message.providerMessageId,
|
||||
attachmentId,
|
||||
});
|
||||
return Response.json({ ok: true, fileId });
|
||||
} catch (error) {
|
||||
if (error instanceof EmailAttachmentError) {
|
||||
return Response.json({ error: `emailInbox.detail.attachment.error.${error.code}` }, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (intent === "toggle-read") {
|
||||
await bulkUpdateMessages(ctx.tenantId, mailboxIds, [messageId], { isRead: !message.isRead });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
throw notFoundResponse();
|
||||
};
|
||||
|
||||
function ThreadMessage({ entry, csrf }: { entry: EmailThreadMessageVM; csrf?: string }) {
|
||||
const { t, i18n } = useTranslation();
|
||||
return (
|
||||
<details open={entry.isFocused} className="border-border rounded-md border" data-thread-id={entry.id} data-focused={entry.isFocused}>
|
||||
<summary className="flex cursor-pointer items-baseline justify-between px-3 py-2">
|
||||
<span className="text-foreground truncate text-sm font-medium">
|
||||
{entry.fromName ?? entry.fromAddress}
|
||||
<span className="text-muted-foreground ml-2 text-xs">{t("emailInbox.detail.to")} {entry.toSummary}</span>
|
||||
</span>
|
||||
<span className="text-muted-foreground shrink-0 text-xs">{new Date(entry.sentAt).toLocaleString(i18n.language)}</span>
|
||||
</summary>
|
||||
<div className="px-3 pb-3">
|
||||
{entry.blockedImageCount > 0 && (
|
||||
<Form method="get" className="border-border text-muted-foreground mb-2 flex items-center justify-between rounded border px-2 py-1 text-xs" data-ui-id="ui.email.detail.blockedImages">
|
||||
<span>{t("emailInbox.detail.imagesBlocked", { count: entry.blockedImageCount })}</span>
|
||||
<input type="hidden" name="images" value="1" />
|
||||
<button type="submit" className="text-theme-600 underline">
|
||||
{t("emailInbox.detail.loadImages")}
|
||||
</button>
|
||||
</Form>
|
||||
)}
|
||||
{/* Sanitized server-side (dompurify) — safe to inject. */}
|
||||
<div className="prose prose-sm max-w-none" dangerouslySetInnerHTML={{ __html: entry.safeBodyHtml }} data-ui-id="ui.email.detail.body" />
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EmailDetailRoute() {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
useSearchParams();
|
||||
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.email.detail" />;
|
||||
}
|
||||
const { subject, thread, attachments, match, canWrite, replyHref, forwardHref, backHref, mailbox } = vm.data;
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.email.detail">
|
||||
<Link to={backHref} className="text-muted-foreground text-sm underline">
|
||||
← {t("emailInbox.detail.back")}
|
||||
</Link>
|
||||
<div className="mt-2 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-foreground text-xl font-semibold">{subject ?? t("emailInbox.list.noSubject")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-xs">{mailbox.emailAddress}</p>
|
||||
</div>
|
||||
{canWrite && (
|
||||
<div className="flex gap-2">
|
||||
<Link to={replyHref} className="bg-theme-600 rounded-md px-3 py-1.5 text-sm font-medium text-white" data-ui-id="ui.email.detail.reply">
|
||||
{t("emailInbox.detail.reply")}
|
||||
</Link>
|
||||
<Link to={forwardHref} className="border-border rounded-md border px-3 py-1.5 text-sm" data-ui-id="ui.email.detail.forward">
|
||||
{t("emailInbox.detail.forward")}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<section className="border-border mt-4 rounded-md border px-3 py-2" data-ui-id="ui.email.detail.linkEditor">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm">
|
||||
<span className="text-muted-foreground">{t(match.sourceKey)}</span>
|
||||
{match.links.map((link) => (
|
||||
<Link key={`${link.type}:${link.id}`} to={link.href} className="text-theme-600 ml-2 text-sm underline" data-link-type={link.type}>
|
||||
{t(`emailInbox.list.linkBadge.${link.type}`)}
|
||||
</Link>
|
||||
))}
|
||||
{match.links.length === 0 && <span className="text-muted-foreground ml-2 text-sm">{t("emailInbox.detail.match.noneHint")}</span>}
|
||||
</p>
|
||||
</div>
|
||||
{canWrite && (
|
||||
<div className="mt-2 flex flex-wrap items-end gap-2">
|
||||
<Form method="post" className="flex flex-wrap items-end gap-2">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="intent" value="set-link" />
|
||||
<label className="text-xs">
|
||||
{t("emailInbox.detail.linkKontakt")}
|
||||
<input name="kontaktId" className="border-border ml-1 rounded border px-2 py-1 text-xs" placeholder={t("emailInbox.detail.linkIdPlaceholder")} />
|
||||
</label>
|
||||
<label className="text-xs">
|
||||
{t("emailInbox.detail.linkProjekt")}
|
||||
<input name="projektId" className="border-border ml-1 rounded border px-2 py-1 text-xs" placeholder={t("emailInbox.detail.linkIdPlaceholder")} />
|
||||
</label>
|
||||
<button type="submit" className="border-border rounded border px-2 py-1 text-xs" data-ui-id="ui.email.detail.setLink">
|
||||
{t("emailInbox.detail.applyLink")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="intent" value="clear-link" />
|
||||
<button type="submit" className="text-destructive px-2 py-1 text-xs underline" data-ui-id="ui.email.detail.clearLink">
|
||||
{t("emailInbox.detail.clearLink")}
|
||||
</button>
|
||||
</Form>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="mt-4 space-y-2" data-ui-id="ui.email.detail.thread">
|
||||
{thread.map((entry) => (
|
||||
<ThreadMessage key={entry.id} entry={entry} csrf={rootData.csrf} />
|
||||
))}
|
||||
</section>
|
||||
|
||||
{attachments.length > 0 && (
|
||||
<section className="mt-4" data-ui-id="ui.email.detail.attachments">
|
||||
<h2 className="text-foreground text-sm font-medium">{t("emailInbox.detail.attachments")}</h2>
|
||||
<ul className="mt-2 flex flex-wrap gap-2">
|
||||
{attachments.map((attachment) => (
|
||||
<li key={attachment.attachmentId} className="border-border flex items-center gap-2 rounded border px-2 py-1 text-xs" data-attachment-id={attachment.attachmentId}>
|
||||
<span className="max-w-48 truncate">{attachment.filename}</span>
|
||||
<span className="text-muted-foreground">{Math.max(1, Math.round(attachment.sizeBytes / 1024))} KB</span>
|
||||
{attachment.downloadHref ? (
|
||||
<Link to={attachment.downloadHref} className="text-theme-600 underline">
|
||||
{t("emailInbox.detail.attachment.download")}
|
||||
</Link>
|
||||
) : canWrite ? (
|
||||
<Form method="post">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="intent" value="import-attachment" />
|
||||
<input type="hidden" name="attachmentId" value={attachment.attachmentId} />
|
||||
<button type="submit" className="text-theme-600 underline" data-ui-id="ui.email.detail.attachment.import">
|
||||
{t("emailInbox.detail.attachment.import")}
|
||||
</button>
|
||||
</Form>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };
|
||||
+357
@@ -0,0 +1,357 @@
|
||||
// VA-P23 · inbox list route (M09 Block F). Loader builds the VM server-side
|
||||
// (read_own → only own mailboxes vs read_all; filters/search/keyset cursor in
|
||||
// the DB layer); the action handles the bulk intents mark-read/mark-unread/
|
||||
// archive (read state is mirrored back to the provider best-effort). Module
|
||||
// off -> locked empty; missing email.read_own -> 404 (A.5.3).
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, useSearchParams, Form, Link, useSubmit } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
buildEmailInboxListVM,
|
||||
decodeInboxCursor,
|
||||
encodeInboxCursor,
|
||||
parseInboxFilters,
|
||||
type EmailInboxListVM,
|
||||
type EmailInboxRow,
|
||||
type EmailLinkBadge,
|
||||
} from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import {
|
||||
canReadAllMailboxes,
|
||||
canWriteEmail,
|
||||
loadEmailInboxContext,
|
||||
requireEmailRead,
|
||||
requireEmailWrite,
|
||||
} from "~/modules/emailInbox/routes/emailInboxAccess.server";
|
||||
import { EMAIL_INBOX_MODULE_KEY, emailComposePath, emailInboxPath, emailMessagePath, emailSettingsPath, notFoundResponse } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
|
||||
import {
|
||||
bulkUpdateMessages,
|
||||
getProviderMessageRefs,
|
||||
listMailboxesForTenant,
|
||||
listMailboxesForUser,
|
||||
listMessagesForMailboxes,
|
||||
} from "~/modules/emailInbox/db/emailInbox.db.server";
|
||||
import { adapterForProvider, ensureFreshMailboxCreds, loadMailboxCreds } from "~/modules/emailInbox/services/MailboxConnectionService.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
type LoaderData = { title: string; vm: EmailInboxListVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadEmailInboxContext({ request, params });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const title = `${t("emailInbox.list.title")} | ${process.env.APP_NAME}`;
|
||||
const url = new URL(request.url);
|
||||
const filters = parseInboxFilters(url.searchParams);
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({
|
||||
title,
|
||||
vm: buildEmailInboxListVM({
|
||||
rows: [],
|
||||
filters,
|
||||
mailboxOptions: [],
|
||||
nextCursor: null,
|
||||
canWrite: false,
|
||||
composeHref: emailComposePath(tenantSlug),
|
||||
settingsHref: emailSettingsPath(tenantSlug),
|
||||
hasAnyMailbox: false,
|
||||
}),
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireEmailRead(ctx);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
|
||||
const mailboxById = new Map(mailboxes.map((m) => [m.id, m]));
|
||||
const decodedCursor = decodeInboxCursor(url.searchParams.get("cursor"));
|
||||
|
||||
const pageRows = await listMessagesForMailboxes(ctx.tenantId, {
|
||||
mailboxIds: mailboxes.map((m) => m.id),
|
||||
onlyMailboxId: filters.mailboxId,
|
||||
direction: filters.direction === "all" ? null : filters.direction,
|
||||
linked: filters.linked === "all" ? null : filters.linked,
|
||||
read: filters.read === "all" ? null : filters.read,
|
||||
q: filters.q || null,
|
||||
showArchived: filters.showArchived,
|
||||
cursor: decodedCursor ? { sentAt: new Date(decodedCursor.sentAtIso), id: decodedCursor.id } : null,
|
||||
take: PAGE_SIZE + 1,
|
||||
});
|
||||
const hasMore = pageRows.length > PAGE_SIZE;
|
||||
const visible = hasMore ? pageRows.slice(0, PAGE_SIZE) : pageRows;
|
||||
const last = visible.at(-1);
|
||||
|
||||
const rows: EmailInboxRow[] = visible.map((row) => {
|
||||
const mailbox = mailboxById.get(row.mailboxId);
|
||||
const links: EmailLinkBadge[] = [
|
||||
...(row.matchedKontaktId ? [{ type: "kontakt" as const, id: row.matchedKontaktId, href: `/${tenantSlug}/contacts/${row.matchedKontaktId}` }] : []),
|
||||
...(row.matchedLeadId ? [{ type: "lead" as const, id: row.matchedLeadId, href: `/${tenantSlug}/leads/${row.matchedLeadId}` }] : []),
|
||||
...(row.matchedProjektId ? [{ type: "projekt" as const, id: row.matchedProjektId, href: `/${tenantSlug}/projects/${row.matchedProjektId}` }] : []),
|
||||
];
|
||||
return {
|
||||
id: row.id,
|
||||
detailHref: emailMessagePath(tenantSlug, row.id),
|
||||
fromName: row.fromName,
|
||||
fromAddress: row.fromAddress,
|
||||
subject: row.subject,
|
||||
snippet: row.snippet,
|
||||
sentAt: row.sentAt.toISOString(),
|
||||
direction: row.direction,
|
||||
isRead: row.isRead,
|
||||
hasAttachments: row.hasAttachments,
|
||||
isNewsletter: row.isNewsletter,
|
||||
mailbox: { id: row.mailboxId, emailAddress: mailbox?.emailAddress ?? "", provider: mailbox?.provider ?? "gmail" },
|
||||
links,
|
||||
};
|
||||
});
|
||||
|
||||
const vm = buildEmailInboxListVM({
|
||||
rows,
|
||||
filters,
|
||||
mailboxOptions: mailboxes.map((m) => ({ id: m.id, emailAddress: m.emailAddress })),
|
||||
nextCursor: hasMore && last ? encodeInboxCursor(last.sentAt.toISOString(), last.id) : null,
|
||||
canWrite: canWriteEmail(ctx),
|
||||
composeHref: emailComposePath(tenantSlug),
|
||||
settingsHref: emailSettingsPath(tenantSlug),
|
||||
hasAnyMailbox: mailboxes.length > 0,
|
||||
});
|
||||
return Response.json({ title, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
|
||||
try {
|
||||
requireEmailRead(ctx);
|
||||
requireEmailWrite(ctx);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const messageIds = form.getAll("messageId").map(String).filter(Boolean);
|
||||
if (messageIds.length === 0) {
|
||||
return Response.json({ ok: true, updated: 0 });
|
||||
}
|
||||
const mailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : await listMailboxesForUser(ctx.tenantId, ctx.userId);
|
||||
const mailboxIds = mailboxes.map((m) => m.id);
|
||||
const mailboxById = new Map(mailboxes.map((m) => [m.id, m]));
|
||||
|
||||
if (intent === "mark-read" || intent === "mark-unread") {
|
||||
const isRead = intent === "mark-read";
|
||||
const { count } = await bulkUpdateMessages(ctx.tenantId, mailboxIds, messageIds, { isRead });
|
||||
// Mirror the read state back to the provider — best-effort (M09 Block F);
|
||||
// a provider hiccup must not fail the bulk action.
|
||||
const refs = await getProviderMessageRefs(ctx.tenantId, mailboxIds, messageIds);
|
||||
const byMailbox = new Map<string, string[]>();
|
||||
for (const ref of refs) {
|
||||
byMailbox.set(ref.mailboxId, [...(byMailbox.get(ref.mailboxId) ?? []), ref.providerMessageId]);
|
||||
}
|
||||
for (const [mailboxId, providerIds] of byMailbox) {
|
||||
const mailbox = mailboxById.get(mailboxId);
|
||||
if (!mailbox) continue;
|
||||
try {
|
||||
const adapter = adapterForProvider(mailbox.provider);
|
||||
const creds = await loadMailboxCreds(ctx.tenantId, mailboxId);
|
||||
if (!creds) continue;
|
||||
const fresh = await ensureFreshMailboxCreds(ctx.tenantId, mailboxId, mailbox.provider, creds);
|
||||
for (const providerMessageId of providerIds) {
|
||||
await adapter.markRead(fresh, providerMessageId, isRead).catch(() => undefined);
|
||||
}
|
||||
} catch {
|
||||
// best-effort mirror
|
||||
}
|
||||
}
|
||||
return Response.json({ ok: true, updated: count });
|
||||
}
|
||||
|
||||
if (intent === "archive") {
|
||||
// HiveGrid-side archive only — the provider mailbox stays untouched (M09 F).
|
||||
const { count } = await bulkUpdateMessages(ctx.tenantId, mailboxIds, messageIds, { archived: true });
|
||||
return Response.json({ ok: true, updated: count });
|
||||
}
|
||||
|
||||
throw notFoundResponse();
|
||||
};
|
||||
|
||||
function relativeOrAbsolute(iso: string, locale: string): string {
|
||||
const date = new Date(iso);
|
||||
const ageMs = Date.now() - date.getTime();
|
||||
if (ageMs < 7 * 86_400_000) {
|
||||
const days = Math.floor(ageMs / 86_400_000);
|
||||
if (days === 0) return date.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });
|
||||
return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(-days, "day");
|
||||
}
|
||||
return date.toLocaleDateString(locale);
|
||||
}
|
||||
|
||||
export default function EmailInboxRoute() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const [searchParams] = useSearchParams();
|
||||
const submit = useSubmit();
|
||||
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.email.inbox" />;
|
||||
}
|
||||
const { rows, filters, mailboxOptions, nextCursor, hasAnyMailbox, settingsHref, composeHref, canWrite } = vm.data;
|
||||
|
||||
const withParam = (key: string, value: string | null): string => {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.delete("cursor");
|
||||
if (value) next.set(key, value);
|
||||
else next.delete(key);
|
||||
return `?${next.toString()}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.email.inbox">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("emailInbox.list.title")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("emailInbox.list.subtitle")}</p>
|
||||
</div>
|
||||
{canWrite && hasAnyMailbox && (
|
||||
<Link to={composeHref} className="bg-theme-600 rounded-md px-4 py-2 text-sm font-medium text-white" data-ui-id="ui.email.inbox.compose">
|
||||
{t("emailInbox.list.compose")}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!hasAnyMailbox ? (
|
||||
<div className="mt-10 text-center" data-ui-id="ui.email.inbox.noMailbox">
|
||||
<p className="text-foreground font-medium">{t(vm.data.noMailboxHeadlineKey)}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t(vm.data.noMailboxBodyKey)}</p>
|
||||
<Link to={settingsHref} className="text-theme-600 mt-3 inline-block text-sm underline">
|
||||
{t("emailInbox.list.connectCta")}
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Form method="get" className="mt-4 flex flex-wrap items-center gap-2" data-ui-id="ui.email.inbox.filters">
|
||||
<input
|
||||
type="search"
|
||||
name="q"
|
||||
defaultValue={filters.q}
|
||||
placeholder={t("emailInbox.list.searchPlaceholder")}
|
||||
className="border-border w-64 rounded-md border px-3 py-1.5 text-sm"
|
||||
data-ui-id="ui.email.inbox.search"
|
||||
/>
|
||||
<select name="mailbox" defaultValue={filters.mailboxId ?? ""} className="border-border rounded-md border px-2 py-1.5 text-sm">
|
||||
<option value="">{t("emailInbox.list.filter.allMailboxes")}</option>
|
||||
{mailboxOptions.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.emailAddress}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select name="linked" defaultValue={filters.linked} className="border-border rounded-md border px-2 py-1.5 text-sm">
|
||||
<option value="all">{t("emailInbox.list.filter.linkedAll")}</option>
|
||||
<option value="linked">{t("emailInbox.list.filter.linked")}</option>
|
||||
<option value="unlinked">{t("emailInbox.list.filter.unlinked")}</option>
|
||||
</select>
|
||||
<select name="read" defaultValue={filters.read} className="border-border rounded-md border px-2 py-1.5 text-sm">
|
||||
<option value="all">{t("emailInbox.list.filter.readAll")}</option>
|
||||
<option value="unread">{t("emailInbox.list.filter.unread")}</option>
|
||||
<option value="read">{t("emailInbox.list.filter.read")}</option>
|
||||
</select>
|
||||
<button type="submit" className="border-border rounded-md border px-3 py-1.5 text-sm">
|
||||
{t("emailInbox.list.applyFilters")}
|
||||
</button>
|
||||
</Form>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="mt-10 text-center" data-ui-id="ui.email.inbox.empty">
|
||||
<p className="text-foreground font-medium">{t(vm.data.emptyHeadlineKey)}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t(vm.data.emptyBodyKey)}</p>
|
||||
</div>
|
||||
) : (
|
||||
<Form
|
||||
method="post"
|
||||
onChange={(event) => {
|
||||
// Bulk actions submit via the toolbar buttons; row checkboxes only select.
|
||||
event.stopPropagation();
|
||||
}}
|
||||
>
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
{canWrite && (
|
||||
<div className="mt-4 flex gap-2" data-ui-id="ui.email.inbox.bulk">
|
||||
<button type="submit" name="intent" value="mark-read" className="border-border rounded-md border px-3 py-1 text-xs">
|
||||
{t("emailInbox.list.bulk.markRead")}
|
||||
</button>
|
||||
<button type="submit" name="intent" value="mark-unread" className="border-border rounded-md border px-3 py-1 text-xs">
|
||||
{t("emailInbox.list.bulk.markUnread")}
|
||||
</button>
|
||||
<button type="submit" name="intent" value="archive" className="border-border rounded-md border px-3 py-1 text-xs">
|
||||
{t("emailInbox.list.bulk.archive")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<ul className="divide-border mt-2 divide-y" data-ui-id="ui.email.inbox.list">
|
||||
{rows.map((row) => (
|
||||
<li key={row.id} className="flex items-center gap-3 py-3" data-row-id={row.id} data-unread={!row.isRead}>
|
||||
{canWrite && <input type="checkbox" name="messageId" value={row.id} aria-label={t("emailInbox.list.selectRow")} />}
|
||||
<Link to={row.detailHref} className="min-w-0 flex-1">
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<p className={`truncate text-sm ${row.isRead ? "text-muted-foreground" : "text-foreground font-semibold"}`}>
|
||||
{row.fromName ?? row.fromAddress}
|
||||
{row.isNewsletter && (
|
||||
<span className="border-border text-muted-foreground ml-2 rounded border px-1 text-[10px]">{t("emailInbox.list.newsletterBadge")}</span>
|
||||
)}
|
||||
</p>
|
||||
<span className="text-muted-foreground shrink-0 text-xs">{relativeOrAbsolute(row.sentAt, i18n.language)}</span>
|
||||
</div>
|
||||
<p className={`truncate text-sm ${row.isRead ? "text-muted-foreground" : "text-foreground"}`}>
|
||||
{row.subject ?? t("emailInbox.list.noSubject")}
|
||||
{row.hasAttachments && <span className="ml-1">📎</span>}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-muted-foreground truncate text-xs">{row.snippet}</p>
|
||||
{row.links.map((link) => (
|
||||
<span key={`${link.type}:${link.id}`} className="border-border text-muted-foreground shrink-0 rounded border px-1 text-[10px]" data-link-type={link.type}>
|
||||
{t(`emailInbox.list.linkBadge.${link.type}`)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Form>
|
||||
)}
|
||||
|
||||
{nextCursor && (
|
||||
<div className="mt-4 text-center">
|
||||
<button
|
||||
type="button"
|
||||
className="border-border rounded-md border px-4 py-2 text-sm"
|
||||
data-ui-id="ui.email.inbox.more"
|
||||
onClick={() => {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
next.set("cursor", nextCursor);
|
||||
submit(next, { method: "get" });
|
||||
}}
|
||||
>
|
||||
{t("emailInbox.list.loadMore")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
// VA-P23 · compose route (M09 Block G): new mail / reply (?replyTo=) / forward
|
||||
// (?forward=) over the user's OWN mailbox. Templates come from the v1
|
||||
// EmailTemplate table (M098 — NOT rebuilt); attachments upload as multipart
|
||||
// form files (≤10 MB v1). Send errors surface as Klartext (M002 keys).
|
||||
|
||||
import * as React from "react";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, Form, Link } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
buildComposePrefill,
|
||||
buildEmailComposeVM,
|
||||
parseRecipients,
|
||||
type EmailComposeVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import {
|
||||
canReadAllMailboxes,
|
||||
loadEmailInboxContext,
|
||||
requireEmailRead,
|
||||
requireEmailWrite,
|
||||
} from "~/modules/emailInbox/routes/emailInboxAccess.server";
|
||||
import { EMAIL_INBOX_MODULE_KEY, emailInboxPath, emailMessagePath, emailSettingsPath, notFoundResponse } from "~/modules/emailInbox/routes/emailInboxRoutePaths";
|
||||
import { getMessageForMailboxes, listMailboxesForTenant, listMailboxesForUser } from "~/modules/emailInbox/db/emailInbox.db.server";
|
||||
import { EmailSendError, listEmailTemplates, sendEmail } from "~/modules/emailInbox/services/EmailSendService.server";
|
||||
import { renderPlainTextAsHtml, sanitizeEmailHtml } from "~/modules/emailInbox/services/emailHtmlSanitizer";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
const COMPOSE_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
type LoaderData = { title: string; vm: EmailComposeVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
|
||||
try {
|
||||
requireEmailRead(ctx);
|
||||
requireEmailWrite(ctx);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const url = new URL(request.url);
|
||||
const replyToId = url.searchParams.get("replyTo");
|
||||
const forwardId = url.searchParams.get("forward");
|
||||
|
||||
// Sending always runs over the user's OWN mailbox (M09 Block G).
|
||||
const ownMailboxes = await listMailboxesForUser(ctx.tenantId, ctx.userId);
|
||||
const templates = await listEmailTemplates(ctx.tenantId);
|
||||
|
||||
// Reply/forward context may live in a foreign mailbox for read_all users.
|
||||
const visibleMailboxes = canReadAllMailboxes(ctx) ? await listMailboxesForTenant(ctx.tenantId) : ownMailboxes;
|
||||
const originalId = replyToId ?? forwardId;
|
||||
const originalRow = originalId
|
||||
? await getMessageForMailboxes(
|
||||
ctx.tenantId,
|
||||
visibleMailboxes.map((m) => m.id),
|
||||
originalId,
|
||||
)
|
||||
: null;
|
||||
const original = originalRow
|
||||
? {
|
||||
id: originalRow.id,
|
||||
direction: originalRow.direction,
|
||||
fromAddress: originalRow.fromAddress,
|
||||
fromName: originalRow.fromName,
|
||||
toSummary: Array.isArray(originalRow.toAddresses)
|
||||
? (originalRow.toAddresses as Array<{ address?: string }>).map((a) => a.address ?? "").filter(Boolean).join(", ")
|
||||
: "",
|
||||
subject: originalRow.subject,
|
||||
sentAtIso: originalRow.sentAt.toISOString(),
|
||||
safeBodyHtml: originalRow.bodyHtml
|
||||
? sanitizeEmailHtml(originalRow.bodyHtml).html
|
||||
: originalRow.bodyText
|
||||
? renderPlainTextAsHtml(originalRow.bodyText)
|
||||
: "",
|
||||
}
|
||||
: null;
|
||||
|
||||
const vm = buildEmailComposeVM({
|
||||
mailboxes: ownMailboxes.map((m) => ({ id: m.id, emailAddress: m.emailAddress, provider: m.provider, isDefaultForUser: m.isDefaultForUser })),
|
||||
defaultMailboxId: ownMailboxes.find((m) => m.isDefaultForUser)?.id ?? ownMailboxes[0]?.id ?? null,
|
||||
templates,
|
||||
prefill: buildComposePrefill({ mode: replyToId ? "reply" : forwardId ? "forward" : "blank", original }),
|
||||
backHref: originalId ? emailMessagePath(tenantSlug, originalId) : emailInboxPath(tenantSlug),
|
||||
});
|
||||
return Response.json({ title: `${t("emailInbox.compose.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadEmailInboxContext({ request, params, requireModule: true });
|
||||
try {
|
||||
requireEmailRead(ctx);
|
||||
requireEmailWrite(ctx);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
await validateCSRFToken(request);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const form = await request.formData();
|
||||
|
||||
const to = parseRecipients(String(form.get("to") ?? ""));
|
||||
const cc = parseRecipients(String(form.get("cc") ?? ""));
|
||||
const bcc = parseRecipients(String(form.get("bcc") ?? ""));
|
||||
const subject = String(form.get("subject") ?? "").trim();
|
||||
const bodyText = String(form.get("body") ?? "");
|
||||
const mailboxId = String(form.get("mailboxId") ?? "");
|
||||
const replyToMessageId = String(form.get("replyToMessageId") ?? "").trim() || null;
|
||||
const quotedHtml = String(form.get("quotedHtml") ?? "");
|
||||
if (to.length === 0) {
|
||||
return Response.json({ error: "emailInbox.compose.error.no_recipients" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Body: user plain-text (escaped) + the sanitized quoted original below it.
|
||||
const bodyHtml = `${renderPlainTextAsHtml(bodyText)}${quotedHtml ? sanitizeEmailHtml(quotedHtml).html : ""}`;
|
||||
|
||||
const attachments: Array<{ filename: string; mimeType: string; contentBase64: string }> = [];
|
||||
for (const entry of form.getAll("attachments")) {
|
||||
if (typeof entry === "object" && entry && "arrayBuffer" in entry) {
|
||||
const file = entry as File;
|
||||
if (!file.name || file.size === 0) continue;
|
||||
if (file.size > COMPOSE_ATTACHMENT_MAX_BYTES) {
|
||||
return Response.json({ error: "emailInbox.compose.error.attachment_too_large" }, { status: 400 });
|
||||
}
|
||||
attachments.push({
|
||||
filename: file.name,
|
||||
mimeType: file.type || "application/octet-stream",
|
||||
contentBase64: Buffer.from(await file.arrayBuffer()).toString("base64"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const { messageId } = await sendEmail({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
mailboxId,
|
||||
to,
|
||||
cc,
|
||||
bcc,
|
||||
subject,
|
||||
bodyHtml,
|
||||
replyToMessageId,
|
||||
attachments,
|
||||
});
|
||||
return redirect(`${emailMessagePath(tenantSlug, messageId)}?sent=1`);
|
||||
} catch (error) {
|
||||
if (error instanceof EmailSendError) {
|
||||
return Response.json({ error: `emailInbox.compose.error.${error.code}` }, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export default function EmailComposeRoute() {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
const [subject, setSubject] = React.useState<string | null>(null);
|
||||
const [templateBody, setTemplateBody] = React.useState<string>("");
|
||||
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose" />;
|
||||
}
|
||||
const { mailboxes, defaultMailboxId, templates, prefill, backHref, noMailboxKey } = vm.data;
|
||||
|
||||
if (mailboxes.length === 0) {
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose">
|
||||
<p className="text-foreground font-medium">{t(noMailboxKey)}</p>
|
||||
<Link to={backHref.replace(/\/emails.*$/, "/settings/integrations/email")} className="text-theme-600 mt-2 inline-block text-sm underline">
|
||||
{t("emailInbox.list.connectCta")}
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.email.compose">
|
||||
<Link to={backHref} className="text-muted-foreground text-sm underline">
|
||||
← {t("emailInbox.compose.back")}
|
||||
</Link>
|
||||
<h1 className="text-foreground mt-2 text-xl font-semibold">{t("emailInbox.compose.title")}</h1>
|
||||
|
||||
{actionData?.error && (
|
||||
<p className="text-destructive border-border mt-3 rounded-md border px-3 py-2 text-sm" data-ui-id="ui.email.compose.error">
|
||||
{t(actionData.error)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Form method="post" encType="multipart/form-data" className="mt-4 space-y-3">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="replyToMessageId" value={prefill.replyToMessageId ?? ""} />
|
||||
<input type="hidden" name="quotedHtml" value={prefill.quotedHtml} />
|
||||
|
||||
<label className="block text-sm">
|
||||
{t("emailInbox.compose.mailbox")}
|
||||
<select name="mailboxId" defaultValue={defaultMailboxId ?? ""} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" data-ui-id="ui.email.compose.mailbox">
|
||||
{mailboxes.map((mailbox) => (
|
||||
<option key={mailbox.id} value={mailbox.id}>
|
||||
{mailbox.emailAddress}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="block text-sm">
|
||||
{t("emailInbox.compose.to")}
|
||||
<input name="to" defaultValue={prefill.to} required placeholder={t("emailInbox.compose.recipientsPlaceholder")} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" data-ui-id="ui.email.compose.to" />
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
{t("emailInbox.compose.cc")}
|
||||
<input name="cc" placeholder={t("emailInbox.compose.recipientsPlaceholder")} className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm" />
|
||||
</label>
|
||||
|
||||
{templates.length > 0 && (
|
||||
<label className="block text-sm">
|
||||
{t("emailInbox.compose.template")}
|
||||
<select
|
||||
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
|
||||
data-ui-id="ui.email.compose.template"
|
||||
defaultValue=""
|
||||
onChange={(event) => {
|
||||
const template = templates.find((candidate) => candidate.id === event.target.value);
|
||||
if (template) {
|
||||
setSubject(template.subject);
|
||||
setTemplateBody(template.htmlBody.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim());
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">{t("emailInbox.compose.noTemplate")}</option>
|
||||
{templates.map((template) => (
|
||||
<option key={template.id} value={template.id}>
|
||||
{template.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
|
||||
<label className="block text-sm">
|
||||
{t("emailInbox.compose.subject")}
|
||||
<input
|
||||
name="subject"
|
||||
value={subject ?? prefill.subject}
|
||||
onChange={(event) => setSubject(event.target.value)}
|
||||
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
|
||||
data-ui-id="ui.email.compose.subject"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="block text-sm">
|
||||
{t("emailInbox.compose.body")}
|
||||
<textarea
|
||||
name="body"
|
||||
rows={10}
|
||||
value={templateBody || undefined}
|
||||
onChange={(event) => setTemplateBody(event.target.value)}
|
||||
className="border-border mt-1 block w-full rounded-md border px-2 py-1.5 text-sm"
|
||||
data-ui-id="ui.email.compose.body"
|
||||
/>
|
||||
</label>
|
||||
{prefill.quotedHtml && <p className="text-muted-foreground text-xs">{t("emailInbox.compose.quotedHint")}</p>}
|
||||
|
||||
<label className="block text-sm">
|
||||
{t("emailInbox.compose.attachments")}
|
||||
<input type="file" name="attachments" multiple className="mt-1 block text-sm" data-ui-id="ui.email.compose.attachments" />
|
||||
</label>
|
||||
|
||||
<button type="submit" className="bg-theme-600 rounded-md px-4 py-2 text-sm font-medium text-white" data-ui-id="ui.email.compose.send">
|
||||
{t("emailInbox.compose.send")}
|
||||
</button>
|
||||
</Form>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: EMAIL_INBOX_MODULE_KEY };
|
||||
+23
-128
@@ -3,8 +3,7 @@
|
||||
// audit. Not-visible / foreign file -> 404. Baseline functional UI.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildFileDetailVM, type FileDetailVM, type FileLinkedEntity } from "@toolctrl/view-models";
|
||||
import { buildFileDetailVM, type FileDetailVM, type FileLinkedEntity } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { badRequestResponse, loadFilesContext, notFoundResponse, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import {
|
||||
@@ -15,13 +14,15 @@ import {
|
||||
reactivateFile,
|
||||
regenerateFilePreview,
|
||||
unlinkFile,
|
||||
updateFileMeta,
|
||||
type FileEntityType,
|
||||
} from "~/utils/integrations/fileService.server";
|
||||
import { auditFileEvent, logFileActivity } from "~/utils/integrations/fileAudit.server";
|
||||
import { filesDetailPath, mediaVariantPath } from "~/utils/integrations/fileRoutePaths";
|
||||
import { FileDetailPage } from "~/components/screens/files/FileDetailPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: FileDetailVM };
|
||||
type LoaderData = { title: string; vm: FileDetailVM; filesHref: string };
|
||||
|
||||
const FILE_ENTITY_TYPES: FileEntityType[] = [
|
||||
"contact",
|
||||
@@ -76,7 +77,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
canAdmin: ctx.permissions.includes("files.admin"),
|
||||
});
|
||||
|
||||
return Response.json({ title: `${file.displayName} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
return Response.json({ title: `${file.displayName} | ${process.env.APP_NAME}`, vm, filesHref: `/${tenantSlug}/files` } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
@@ -113,6 +114,21 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await auditFileEvent({ ctx, action: "file.unlinked", fileId, metadata: { entityType, entityId } });
|
||||
return redirect(filesDetailPath(tenantSlug, fileId));
|
||||
}
|
||||
if (intent === "updateMeta") {
|
||||
// Tags come in as a comma-separated list; normalize (trim, drop empties,
|
||||
// de-dupe, cap) into the String[] the File row stores.
|
||||
const tags = Array.from(
|
||||
new Set(
|
||||
String(formData.get("tags") ?? "")
|
||||
.split(",")
|
||||
.map((tag) => tag.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
).slice(0, 30);
|
||||
await updateFileMeta({ tenantId: ctx.tenantId, fileId, tags });
|
||||
await auditFileEvent({ ctx, action: "file.updated", fileId, metadata: { tagsUpdated: true } });
|
||||
return redirect(filesDetailPath(tenantSlug, fileId));
|
||||
}
|
||||
if (intent === "archive") {
|
||||
await archiveFile({ tenantId: ctx.tenantId, fileId });
|
||||
await auditFileEvent({ ctx, action: "file.archived", fileId });
|
||||
@@ -131,132 +147,11 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
};
|
||||
|
||||
export default function FileDetailRoute() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const { vm, filesHref } = useLoaderData<LoaderData>();
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.detail" />;
|
||||
return <div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.files.detail" />;
|
||||
}
|
||||
const data = vm.data;
|
||||
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" });
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.detail">
|
||||
<h1 className="text-foreground text-xl font-semibold">{data.displayName}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">
|
||||
{data.mimeType} · {dateFormatter.format(new Date(data.createdAtIso))}
|
||||
</p>
|
||||
|
||||
{data.scanNoticeKey ? (
|
||||
<p className="text-theme-600 mt-4 text-sm" data-ui-id="ui.files.detail.scanNotice">
|
||||
{t(data.scanNoticeKey)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="mt-6" data-ui-id="ui.files.detail.preview">
|
||||
{data.previewUrl ? (
|
||||
<img src={data.previewUrl} alt={data.displayName} className="max-h-96 rounded border" />
|
||||
) : data.previewFallbackKey ? (
|
||||
<p className="text-muted-foreground text-sm">{t(data.previewFallbackKey)}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex flex-wrap gap-3">
|
||||
<a href={data.downloadUrl} className="text-theme-600 font-medium" data-ui-id="ui.files.detail.download">
|
||||
{t("files.detail.actions.download")}
|
||||
</a>
|
||||
{data.canWrite && data.canRegeneratePreview ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="regeneratePreview" />
|
||||
<button type="submit" className="text-theme-600 font-medium">
|
||||
{t("files.detail.actions.regeneratePreview")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="archive" />
|
||||
<button type="submit" className="text-theme-600 font-medium" data-ui-id="ui.files.detail.archive">
|
||||
{t("files.detail.actions.archive")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{data.canDelete ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="delete" />
|
||||
<button type="submit" className="text-destructive font-medium" data-ui-id="ui.files.detail.delete">
|
||||
{t("files.detail.actions.delete")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{data.tags.length > 0 ? (
|
||||
<section className="mt-6">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("files.detail.section.tags")}</h2>
|
||||
<p className="mt-1 text-sm">{data.tags.join(", ")}</p>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{data.notes ? (
|
||||
<section className="mt-6">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("files.detail.section.notes")}</h2>
|
||||
<p className="mt-1 text-sm">{data.notes}</p>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<section className="mt-6" data-ui-id="ui.files.detail.links">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("files.detail.section.links")}</h2>
|
||||
{data.linkedEntities.length > 0 ? (
|
||||
<ul className="mt-1 text-sm">
|
||||
{data.linkedEntities.map((link) => (
|
||||
<li key={`${link.entityType}-${link.entityId}`} className="flex items-center gap-2" data-link-id={`${link.entityType}-${link.entityId}`}>
|
||||
<span>
|
||||
{link.entityType}
|
||||
{link.linkRole ? ` · ${link.linkRole}` : ""}
|
||||
</span>
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="unlink" />
|
||||
<input type="hidden" name="entityType" value={link.entityType} />
|
||||
<input type="hidden" name="entityId" value={link.entityId} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("files.detail.actions.unlink")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
{data.canWrite ? (
|
||||
<form method="post" className="mt-3 flex flex-wrap items-end gap-2" data-ui-id="ui.files.detail.linkForm">
|
||||
<input type="hidden" name="intent" value="link" />
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("files.detail.link.entityType")}</span>
|
||||
<select name="entityType" className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
{FILE_ENTITY_TYPES.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("files.detail.link.entityId")}</span>
|
||||
<input name="entityId" required className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("files.detail.link.role")}</span>
|
||||
<input name="linkRole" className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 font-medium">
|
||||
{t("files.detail.actions.link")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
return <FileDetailPage data={vm.data} entityTypes={FILE_ENTITY_TYPES} filesHref={filesHref} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
|
||||
+70
-77
@@ -2,24 +2,30 @@
|
||||
// once (server-side); the component only renders (DoD A). Module off -> locked
|
||||
// empty state (like walking-skeleton). Missing files.read_own -> 404.
|
||||
//
|
||||
// Baseline functional UI (data-ui-id markers for e2e); the Subframe visual polish
|
||||
// follows Davids D-P4 delta (Dev-Nachzug).
|
||||
// Interim-UI (AD-28): renders the ~/ui preview screen FilesBrowserPage; the loader
|
||||
// owns navigation for filter/view changes (server-side). Final Subframe optics land
|
||||
// as a tracked design-nachzug once David's D-P4 delta ships.
|
||||
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildFileBrowserVM, type FileBrowserRow, type FileBrowserVM } from "@toolctrl/view-models";
|
||||
import { useState } from "react";
|
||||
import { type LoaderFunctionArgs, useLoaderData, useNavigate } from "react-router";
|
||||
import { buildFileBrowserVM, type FileBrowserRow, type FileBrowserVM, type FileViewMode } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadFilesContext, notFoundResponse, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { listFilesForBrowser } from "~/utils/integrations/fileService.server";
|
||||
import { listFilesForBrowser, listFileFilterOptions } from "~/utils/integrations/fileService.server";
|
||||
import { mediaVariantPath, filesDetailPath } from "~/utils/integrations/fileRoutePaths";
|
||||
import { FilesBrowserPage, type FilesBrowserQuery } from "~/components/screens/files/FilesBrowserPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: FileBrowserVM };
|
||||
type LoaderData = { title: string; vm: FileBrowserVM; nextHref: string | null; uploadHref: string; bulkZipAction: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadFilesContext({ request, params });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
// Absolute (host-aware) URLs — a relative "upload" would resolve against the
|
||||
// /<tenant>/files base and drop the "files" segment (→ 404).
|
||||
const uploadHref = `/${tenantSlug}/files/upload`;
|
||||
const bulkZipAction = `/${tenantSlug}/files/bulk-zip`;
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
// Locked connector state: render an empty VM (no rows, no write).
|
||||
@@ -29,7 +35,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
canWrite: false,
|
||||
canDelete: false,
|
||||
});
|
||||
return Response.json({ title: `${t("files.browser.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
return Response.json({ title: `${t("files.browser.title")} | ${process.env.APP_NAME}`, vm, nextHref: null, uploadHref, bulkZipAction } satisfies LoaderData);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -41,14 +47,21 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const url = new URL(request.url);
|
||||
const includeArchived = url.searchParams.get("archived") === "1";
|
||||
const mimeGroup = url.searchParams.get("mime");
|
||||
const entityType = url.searchParams.get("entity");
|
||||
const tag = url.searchParams.get("tag");
|
||||
const assignedToUserId = url.searchParams.get("assignee");
|
||||
const cursor = url.searchParams.get("cursor");
|
||||
const viewMode: FileViewMode = url.searchParams.get("view") === "grid" ? "grid" : "table";
|
||||
|
||||
const { rows, nextCursor } = await listFilesForBrowser({
|
||||
tenantId: ctx.tenantId,
|
||||
ctx,
|
||||
filter: { includeArchived, mimeGroup },
|
||||
cursor,
|
||||
});
|
||||
const [{ rows, nextCursor }, filterOptions] = await Promise.all([
|
||||
listFilesForBrowser({
|
||||
tenantId: ctx.tenantId,
|
||||
ctx,
|
||||
filter: { includeArchived, mimeGroup, entityType, tags: tag ? [tag] : undefined, assignedToUserId },
|
||||
cursor,
|
||||
}),
|
||||
listFileFilterOptions({ tenantId: ctx.tenantId }),
|
||||
]);
|
||||
|
||||
const canWrite = ctx.permissions.includes("files.write");
|
||||
const canDelete = ctx.permissions.includes("files.delete");
|
||||
@@ -68,83 +81,63 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
}));
|
||||
|
||||
const vm = buildFileBrowserVM({
|
||||
viewMode,
|
||||
rows: browserRows,
|
||||
filter: { entityType: null, mimeGroup, tags: [], assignedToUserId: null, includeArchived },
|
||||
filter: { entityType, mimeGroup, tags: tag ? [tag] : [], assignedToUserId, includeArchived },
|
||||
filterOptions,
|
||||
canWrite,
|
||||
canDelete,
|
||||
nextCursor,
|
||||
});
|
||||
|
||||
return Response.json({ title: `${t("files.browser.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
// Preserve the active filter/view when paging via cursor.
|
||||
const nextParams = new URLSearchParams();
|
||||
if (mimeGroup) nextParams.set("mime", mimeGroup);
|
||||
if (entityType) nextParams.set("entity", entityType);
|
||||
if (tag) nextParams.set("tag", tag);
|
||||
if (assignedToUserId) nextParams.set("assignee", assignedToUserId);
|
||||
if (includeArchived) nextParams.set("archived", "1");
|
||||
if (viewMode === "grid") nextParams.set("view", "grid");
|
||||
if (nextCursor) nextParams.set("cursor", nextCursor);
|
||||
const nextHref = nextCursor ? `?${nextParams.toString()}` : null;
|
||||
|
||||
return Response.json({ title: `${t("files.browser.title")} | ${process.env.APP_NAME}`, vm, nextHref, uploadHref, bulkZipAction } satisfies LoaderData);
|
||||
};
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const units = ["KB", "MB", "GB"];
|
||||
let value = bytes / 1024;
|
||||
let unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
return `${value.toFixed(1)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
export default function FilesBrowserRoute() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const { vm, nextHref, uploadHref, bulkZipAction } = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([]);
|
||||
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.files.browser" />;
|
||||
function onToggleSelect(id: string) {
|
||||
setSelectedIds((prev) => (prev.includes(id) ? prev.filter((value) => value !== id) : [...prev, id]));
|
||||
}
|
||||
|
||||
const { rows, canWrite, emptyHeadlineKey, emptyBodyKey } = vm.data;
|
||||
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" });
|
||||
function onToggleSelectAll(ids: readonly string[], selectAll: boolean) {
|
||||
setSelectedIds(selectAll ? [...ids] : []);
|
||||
}
|
||||
|
||||
function onApply(query: FilesBrowserQuery) {
|
||||
const params = new URLSearchParams();
|
||||
if (query.mimeGroup) params.set("mime", query.mimeGroup);
|
||||
if (query.entityType) params.set("entity", query.entityType);
|
||||
if (query.tag) params.set("tag", query.tag);
|
||||
if (query.assignedToUserId) params.set("assignee", query.assignedToUserId);
|
||||
if (query.includeArchived) params.set("archived", "1");
|
||||
if (query.viewMode === "grid") params.set("view", "grid");
|
||||
// Reset cursor pagination whenever the filter/view changes.
|
||||
navigate({ search: params.toString() });
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.files.browser">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("files.browser.title")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("files.browser.subtitle")}</p>
|
||||
</div>
|
||||
{canWrite ? (
|
||||
<a href="upload" className="text-theme-600 font-medium" data-ui-id="ui.files.browser.upload">
|
||||
{t("files.browser.actions.upload")}
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="mt-10 text-center" data-ui-id="ui.files.browser.empty">
|
||||
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
|
||||
</div>
|
||||
) : (
|
||||
<table className="mt-6 w-full text-left text-sm" data-ui-id="ui.files.browser.table">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground border-b">
|
||||
<th className="py-2">{t("files.browser.column.name")}</th>
|
||||
<th className="py-2">{t("files.browser.column.size")}</th>
|
||||
<th className="py-2">{t("files.browser.column.date")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.id} className="border-b" data-row-id={row.id}>
|
||||
<td className="py-2">
|
||||
<a href={row.detailHref} className="text-theme-600">
|
||||
{row.displayName}
|
||||
</a>
|
||||
</td>
|
||||
<td className="py-2">{formatBytes(row.sizeBytes)}</td>
|
||||
<td className="py-2">{dateFormatter.format(new Date(row.createdAtIso))}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</main>
|
||||
<FilesBrowserPage
|
||||
vm={vm}
|
||||
uploadHref={uploadHref}
|
||||
nextHref={nextHref}
|
||||
bulkZipAction={bulkZipAction}
|
||||
selectedIds={selectedIds}
|
||||
actions={{ onApply, onToggleSelect, onToggleSelectAll }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
// P4 Files (AK-P4a) §11 — bulk-ZIP download resource route (action only). The
|
||||
// browser POSTs a set of fileIds; we stream back a zip of the files that are
|
||||
// visible to the user AND scan-clean (fail-closed, AD-23 — infected/invisible
|
||||
// files are silently dropped, never leaked). Gated: auth -> module -> files.read_own.
|
||||
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { zipSync } from "fflate";
|
||||
import { badRequestResponse, fileActionErrorResponse, loadFilesContext, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { collectFilesForZip } from "~/utils/integrations/fileService.server";
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
try {
|
||||
if (request.method !== "POST") {
|
||||
return new Response("Method Not Allowed", { status: 405 });
|
||||
}
|
||||
const ctx = requireFilesPermission(await loadFilesContext({ request, params, requireModule: true }), "files.read_own");
|
||||
const formData = await request.formData();
|
||||
const fileIds = formData
|
||||
.getAll("fileIds")
|
||||
.map((value) => String(value))
|
||||
.filter(Boolean);
|
||||
if (fileIds.length === 0) {
|
||||
return badRequestResponse();
|
||||
}
|
||||
|
||||
const { entries } = await collectFilesForZip({ tenantId: ctx.tenantId, ctx, fileIds });
|
||||
if (entries.length === 0) {
|
||||
// Nothing buildable (all invisible / infected / over the cap).
|
||||
return badRequestResponse();
|
||||
}
|
||||
|
||||
const zipInput: Record<string, Uint8Array> = {};
|
||||
for (const entry of entries) {
|
||||
zipInput[entry.name] = entry.bytes;
|
||||
}
|
||||
const zipped = zipSync(zipInput);
|
||||
|
||||
// Hand the Response a plain ArrayBuffer (a typed BodyInit) — the fflate
|
||||
// Uint8Array<ArrayBufferLike> is accepted at runtime but not by the type.
|
||||
const body = zipped.buffer.slice(zipped.byteOffset, zipped.byteOffset + zipped.byteLength) as ArrayBuffer;
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/zip",
|
||||
"content-disposition": 'attachment; filename="dateien.zip"',
|
||||
"content-length": String(zipped.byteLength),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return fileActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { fileActionErrorResponse, loadFilesContext, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { FILE_UPLOAD_CHUNK_SIZE_BYTES } from "@toolctrl/view-models";
|
||||
import { FILE_UPLOAD_CHUNK_SIZE_BYTES } from "@hivegrid/view-models";
|
||||
import { storeUploadChunk } from "~/utils/integrations/fileService.server";
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
+9
-44
@@ -1,14 +1,16 @@
|
||||
// P4 Files (AK-P4a) §11 — Upload view with drag&drop + multi-file queue and
|
||||
// per-file progress (chunked init -> chunk -> complete). Loader gates on
|
||||
// files.write (404 if module off / missing). Baseline functional UI; Subframe
|
||||
// polish follows Davids D-P4 delta.
|
||||
// files.write (404 if module off / missing).
|
||||
//
|
||||
// Interim-UI (AD-28): the client chunked pipeline + queue state stay in this route;
|
||||
// the ~/ui preview screen FileUploadPage renders them (VM + items + onFiles as props).
|
||||
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { useCallback, useState } from "react";
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildFileUploadVM, type FileUploadVM } from "@toolctrl/view-models";
|
||||
import { buildFileUploadVM, type FileUploadVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadFilesContext, notFoundResponse, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { FileUploadPage, type FileUploadDisplayItem } from "~/components/screens/files/FileUploadPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: FileUploadVM; tenantSlug: string };
|
||||
@@ -25,13 +27,11 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json({ title: `${t("files.upload.title")} | ${process.env.APP_NAME}`, vm, tenantSlug: params.tenant ?? "" } satisfies LoaderData);
|
||||
};
|
||||
|
||||
type QueueItem = { clientId: string; filename: string; sizeBytes: number; status: "queued" | "uploading" | "processing" | "done" | "error"; progressPercent: number; errorKey: string | null };
|
||||
type QueueItem = FileUploadDisplayItem;
|
||||
|
||||
export default function FilesUploadRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { vm, tenantSlug } = useLoaderData<LoaderData>();
|
||||
const [items, setItems] = useState<QueueItem[]>([]);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const chunkSize = vm.status === "ready" && vm.data ? vm.data.chunkSizeBytes : 5 * 1024 * 1024;
|
||||
|
||||
const update = useCallback((clientId: string, patch: Partial<QueueItem>) => {
|
||||
@@ -96,42 +96,7 @@ export default function FilesUploadRoute() {
|
||||
[uploadOne],
|
||||
);
|
||||
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.upload" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.upload">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("files.upload.title")}</h1>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
onDragOver={(event) => event.preventDefault()}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
onFiles(event.dataTransfer.files);
|
||||
}}
|
||||
className="border-muted-foreground/40 mt-6 flex w-full flex-col items-center rounded-lg border-2 border-dashed px-6 py-12"
|
||||
data-ui-id="ui.files.upload.dropzone"
|
||||
>
|
||||
<span className="text-foreground font-medium">{t(vm.data.dropzoneHeadlineKey)}</span>
|
||||
<span className="text-muted-foreground mt-1 text-sm">{t(vm.data.dropzoneBodyKey)}</span>
|
||||
<span className="text-muted-foreground mt-3 text-xs">{t(vm.data.heicNoticeKey)}</span>
|
||||
</button>
|
||||
<input ref={inputRef} type="file" multiple className="hidden" onChange={(event) => onFiles(event.target.files)} data-ui-id="ui.files.upload.input" />
|
||||
|
||||
<ul className="mt-6 space-y-2" data-ui-id="ui.files.upload.queue">
|
||||
{items.map((item) => (
|
||||
<li key={item.clientId} className="border-b py-2 text-sm" data-row-id={item.clientId} data-status={item.status}>
|
||||
<div className="flex items-center justify-between">
|
||||
<span>{item.filename}</span>
|
||||
<span className="text-muted-foreground">{item.status === "error" && item.errorKey ? t(item.errorKey) : `${item.progressPercent}%`}</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</main>
|
||||
);
|
||||
return <FileUploadPage vm={vm} items={items} actions={{ onFiles }} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
|
||||
+57
-24
@@ -1,34 +1,52 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { action } from "./forms.$id";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { loadFormsContext, requireFormsPermission } from "~/modules/forms/routes/formsAccess.server";
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
form: {
|
||||
findFirst: vi.fn(),
|
||||
update: vi.fn(),
|
||||
vi.mock("~/utils/db.server", () => {
|
||||
const tx = {
|
||||
form: { update: vi.fn() },
|
||||
formField: { deleteMany: vi.fn(), createMany: vi.fn() },
|
||||
formAction: { deleteMany: vi.fn(), createMany: vi.fn() },
|
||||
};
|
||||
return {
|
||||
db: {
|
||||
form: {
|
||||
findFirst: vi.fn(),
|
||||
update: tx.form.update,
|
||||
},
|
||||
formField: {
|
||||
deleteMany: tx.formField.deleteMany,
|
||||
createMany: tx.formField.createMany,
|
||||
},
|
||||
formAction: {
|
||||
deleteMany: tx.formAction.deleteMany,
|
||||
createMany: tx.formAction.createMany,
|
||||
},
|
||||
formSubmission: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(async (fn: (txArg: typeof tx) => Promise<unknown>) => fn(tx)),
|
||||
},
|
||||
formSubmission: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/forms/routes/formsAccess.server", () => ({
|
||||
loadFormsContext: vi.fn(async () => ({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
permissions: ["forms.basic", "forms.builder"],
|
||||
hasModule: true,
|
||||
})),
|
||||
requireFormsPermission: vi.fn(),
|
||||
formsOwnerWhere: vi.fn(() => ({ createdByUserId: "user_1" })),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string, fallbackOrOptions?: string | Record<string, unknown>) =>
|
||||
@@ -43,10 +61,14 @@ vi.mock("~/locale/i18next.server", () => ({
|
||||
}));
|
||||
|
||||
function postRequest(form: FormData) {
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of form.entries()) {
|
||||
body.set(key, String(value));
|
||||
}
|
||||
return new Request("https://app.example.test/acme/forms/form_1", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(form as unknown as Record<string, string>),
|
||||
body: body.toString(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -61,6 +83,7 @@ function validSaveForm(overrides: Record<string, string> = {}) {
|
||||
form.set("theme", "{}");
|
||||
form.set("fieldMapping", "{}");
|
||||
form.set("targetType", "generic");
|
||||
form.set("actions", "[]");
|
||||
for (const [key, value] of Object.entries(overrides)) {
|
||||
form.set(key, value);
|
||||
}
|
||||
@@ -70,8 +93,6 @@ function validSaveForm(overrides: Record<string, string> = {}) {
|
||||
describe("form detail action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1" as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(db.form.findFirst).mockResolvedValue({ id: "form_1" } as never);
|
||||
vi.mocked(db.form.update).mockResolvedValue({ id: "form_1" } as never);
|
||||
@@ -86,7 +107,8 @@ describe("form detail action", () => {
|
||||
});
|
||||
|
||||
expect(result).toEqual({ success: "Saved." });
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.account.update", "tenant_1");
|
||||
expect(loadFormsContext).toHaveBeenCalledWith({ request: expect.any(Request), params: { tenant: "acme", id: "form_1" }, requireModule: true });
|
||||
expect(requireFormsPermission).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1" }), "forms.builder");
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(db.form.update).toHaveBeenCalledWith({
|
||||
where: { id: "form_1" },
|
||||
@@ -102,6 +124,17 @@ describe("form detail action", () => {
|
||||
fieldMapping: {},
|
||||
}),
|
||||
});
|
||||
expect(db.formField.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
expect.objectContaining({
|
||||
formId: "form_1",
|
||||
tenantId: "tenant_1",
|
||||
fieldKey: "email",
|
||||
fieldType: "email",
|
||||
position: 0,
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns localized invalid-webhook errors without updating the form", async () => {
|
||||
|
||||
+413
-48
@@ -15,21 +15,26 @@
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, Form, Link, useActionData } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { QRCodeSVG } from "qrcode.react";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { buildPdfExportArtifact } from "@hivegrid/exports/pdf";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { FormDefinitionSchema, FormThemeSchema, type FormDefinition, type FormTheme } from "@toolctrl/form-widget";
|
||||
import { FormDefinitionSchema, FormThemeSchema, type FormDefinition, type FormTheme } from "@hivegrid/form-widget";
|
||||
import { FormBuilder } from "~/modules/formWidget/builder/FormBuilder";
|
||||
import type { FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
|
||||
import type { FormActionJsonObject, FormActionSetting, FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { formsOwnerWhere, loadFormsContext, requireFormsPermission } from "~/modules/forms/routes/formsAccess.server";
|
||||
|
||||
type FormDetail = {
|
||||
id: string;
|
||||
key: string;
|
||||
slug: string | null;
|
||||
name: string;
|
||||
status: string;
|
||||
isPublic: boolean;
|
||||
definition: unknown;
|
||||
theme: unknown;
|
||||
targetType: string;
|
||||
@@ -38,24 +43,93 @@ type FormDetail = {
|
||||
notifyEmails: string[];
|
||||
webhookUrl: string | null;
|
||||
isEnabled: boolean;
|
||||
actions: FormActionSetting[];
|
||||
};
|
||||
|
||||
type SubmissionRow = {
|
||||
id: string;
|
||||
status: string;
|
||||
sourceOrigin: string | null;
|
||||
userAgent: string | null;
|
||||
createdAt: string;
|
||||
values: Record<string, unknown>;
|
||||
preview: string;
|
||||
files: Array<{ fieldKey: string; fileId: string; kind: string }>;
|
||||
actionLogs: Array<{ id: string; actionType: string; status: string; targetType: string | null; targetId: string | null; errorMessage: string | null }>;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
form: FormDetail;
|
||||
submissions: SubmissionRow[];
|
||||
columns: Array<{ key: string; label: string; type: string }>;
|
||||
statusFilter: string;
|
||||
embedScriptBase: string;
|
||||
publicFormUrl: string | null;
|
||||
};
|
||||
|
||||
type ActionData = { error?: string; success?: string };
|
||||
|
||||
const FORM_ACTION_TYPES = new Set<FormActionSetting["actionType"]>([
|
||||
"auto_match",
|
||||
"create_lead",
|
||||
"create_contact",
|
||||
"create_project",
|
||||
"create_task",
|
||||
"send_email_to_team",
|
||||
"send_email_to_submitter",
|
||||
"webhook",
|
||||
"trigger_automation",
|
||||
]);
|
||||
|
||||
function objectValue(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
|
||||
}
|
||||
|
||||
function jsonObjectValue(value: unknown): FormActionJsonObject {
|
||||
const raw = objectValue(value);
|
||||
return JSON.parse(JSON.stringify(raw)) as FormActionJsonObject;
|
||||
}
|
||||
|
||||
function parseFormActions(value: unknown): FormActionSetting[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.flatMap((entry) => {
|
||||
const raw = objectValue(entry);
|
||||
const actionType = raw.actionType;
|
||||
if (typeof actionType !== "string" || !FORM_ACTION_TYPES.has(actionType as FormActionSetting["actionType"])) {
|
||||
return [];
|
||||
}
|
||||
const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 120) : actionType;
|
||||
return [
|
||||
{
|
||||
actionType: actionType as FormActionSetting["actionType"],
|
||||
name,
|
||||
enabled: raw.enabled !== false,
|
||||
fieldMapping: objectValue(raw.fieldMapping) as Record<string, string>,
|
||||
actionConfig: jsonObjectValue(raw.actionConfig),
|
||||
},
|
||||
];
|
||||
}).slice(0, 20);
|
||||
}
|
||||
|
||||
function submissionValues(payload: unknown): Record<string, unknown> {
|
||||
const raw = objectValue(payload);
|
||||
return objectValue(raw.values);
|
||||
}
|
||||
|
||||
function csvCell(value: unknown): string {
|
||||
const raw = Array.isArray(value) ? value.join("; ") : value === null || value === undefined ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
|
||||
return `"${raw.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
function displaySubmissionValue(value: unknown): string {
|
||||
if (Array.isArray(value)) return value.join(", ");
|
||||
if (value === true) return "true";
|
||||
if (value === false) return "false";
|
||||
if (value === null || value === undefined || value === "") return "";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function isHttpUrl(value: string | null | undefined): boolean {
|
||||
if (!value) return false;
|
||||
try {
|
||||
@@ -72,16 +146,19 @@ function isHttpUrl(value: string | null | undefined): boolean {
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const ctx = await loadFormsContext({ request, params, requireModule: true });
|
||||
requireFormsPermission(ctx, "forms.basic");
|
||||
const id = params.id;
|
||||
if (!id) throw new Response(t("shared.notFound"), { status: 404 });
|
||||
const form = await db.form.findFirst({
|
||||
where: { id, tenantId },
|
||||
where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) },
|
||||
select: {
|
||||
id: true,
|
||||
key: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
status: true,
|
||||
isPublic: true,
|
||||
definition: true,
|
||||
theme: true,
|
||||
targetType: true,
|
||||
@@ -90,24 +167,37 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
notifyEmails: true,
|
||||
webhookUrl: true,
|
||||
isEnabled: true,
|
||||
actions: {
|
||||
orderBy: { position: "asc" },
|
||||
select: { id: true, actionType: true, name: true, enabled: true, fieldMapping: true, actionConfig: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!form) throw new Response(t("settings.forms.admin.errors.formNotFound"), { status: 404 });
|
||||
|
||||
const url = new URL(request.url);
|
||||
const definitionParsed = FormDefinitionSchema.safeParse(form.definition);
|
||||
const columns = definitionParsed.success
|
||||
? definitionParsed.data.fields
|
||||
.filter((field) => field.type !== "honeypot")
|
||||
.map((field) => ({ key: field.key, label: field.label, type: field.type }))
|
||||
: [];
|
||||
const statusFilter = url.searchParams.get("status")?.trim() ?? "";
|
||||
const submissionWhere = {
|
||||
formId: id,
|
||||
tenantId: ctx.tenantId,
|
||||
...(statusFilter ? { status: statusFilter } : {}),
|
||||
};
|
||||
if (url.searchParams.get("export") === "csv") {
|
||||
const all = await db.formSubmission.findMany({
|
||||
where: { formId: id, tenantId },
|
||||
where: submissionWhere,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1000,
|
||||
});
|
||||
const header = "id,createdAt,status,sourceOrigin,values\n";
|
||||
const header = ["id", "createdAt", "status", "sourceOrigin", ...columns.map((column) => column.key)].join(",") + "\n";
|
||||
const rows = all.map((s) => {
|
||||
const vals = typeof s.payload === "object" && s.payload && "values" in s.payload
|
||||
? JSON.stringify((s.payload as { values: unknown }).values)
|
||||
: JSON.stringify(s.payload);
|
||||
const safe = vals.replace(/"/g, '""');
|
||||
return `${s.id},${s.createdAt.toISOString()},${s.status},${s.sourceOrigin ?? ""},"${safe}"`;
|
||||
const values = submissionValues(s.payload);
|
||||
return [s.id, s.createdAt.toISOString(), s.status, s.sourceOrigin ?? "", ...columns.map((column) => values[column.key])].map(csvCell).join(",");
|
||||
});
|
||||
return new Response(header + rows.join("\n"), {
|
||||
headers: {
|
||||
@@ -116,30 +206,101 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<R
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url.searchParams.get("export") === "pdf") {
|
||||
const all = await db.formSubmission.findMany({
|
||||
where: submissionWhere,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1000,
|
||||
});
|
||||
const artifact = await buildPdfExportArtifact(
|
||||
{
|
||||
columns: [
|
||||
{ key: "id", label: "ID" },
|
||||
{ key: "createdAt", label: t("settings.forms.admin.detail.submittedAt") },
|
||||
{ key: "status", label: t("settings.forms.admin.detail.status") },
|
||||
{ key: "sourceOrigin", label: t("settings.forms.admin.detail.originPdf") },
|
||||
...columns.map((column) => ({ key: column.key, label: column.label })),
|
||||
],
|
||||
rows: all.map((s) => {
|
||||
const values = submissionValues(s.payload);
|
||||
return {
|
||||
id: s.id,
|
||||
createdAt: s.createdAt.toISOString(),
|
||||
status: s.status,
|
||||
sourceOrigin: s.sourceOrigin ?? "",
|
||||
...Object.fromEntries(columns.map((column) => [column.key, displaySubmissionValue(values[column.key])])),
|
||||
};
|
||||
}),
|
||||
},
|
||||
{ title: `${form.name} - ${t("settings.forms.admin.detail.submissionsLatest")}` },
|
||||
);
|
||||
return new Response(new Uint8Array(artifact.bytes).buffer, {
|
||||
headers: {
|
||||
"content-type": artifact.contentType,
|
||||
"content-disposition": `attachment; filename="form-${form.key}-submissions.pdf"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const submissions = await db.formSubmission.findMany({
|
||||
where: { formId: id, tenantId },
|
||||
where: submissionWhere,
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
select: { id: true, status: true, sourceOrigin: true, createdAt: true, payload: true },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
sourceOrigin: true,
|
||||
userAgent: true,
|
||||
createdAt: true,
|
||||
payload: true,
|
||||
files: {
|
||||
orderBy: { createdAt: "asc" },
|
||||
select: { fieldKey: true, fileId: true, kind: true },
|
||||
},
|
||||
actionLogs: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 8,
|
||||
select: { id: true, actionType: true, status: true, targetType: true, targetId: true, errorMessage: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
const payload: LoaderData = {
|
||||
form: { ...form },
|
||||
form: {
|
||||
...form,
|
||||
actions: form.actions.map((action) => ({
|
||||
id: action.id,
|
||||
actionType: action.actionType,
|
||||
name: action.name,
|
||||
enabled: action.enabled,
|
||||
fieldMapping: objectValue(action.fieldMapping) as Record<string, string>,
|
||||
actionConfig: jsonObjectValue(action.actionConfig),
|
||||
})),
|
||||
},
|
||||
submissions: submissions.map((s) => ({
|
||||
values: submissionValues(s.payload),
|
||||
id: s.id,
|
||||
status: s.status,
|
||||
sourceOrigin: s.sourceOrigin,
|
||||
userAgent: s.userAgent,
|
||||
createdAt: s.createdAt.toISOString(),
|
||||
preview: JSON.stringify(s.payload).slice(0, 240),
|
||||
files: s.files,
|
||||
actionLogs: s.actionLogs,
|
||||
})),
|
||||
columns,
|
||||
statusFilter,
|
||||
embedScriptBase: process.env.FORM_WIDGET_CDN_URL?.trim() || process.env.APP_URL?.trim() || "",
|
||||
publicFormUrl:
|
||||
form.slug
|
||||
? `${(process.env.APP_URL?.trim() || new URL(request.url).origin).replace(/\/+$/u, "")}/f/${encodeURIComponent(params.tenant ?? ctx.tenantId)}/${encodeURIComponent(form.slug)}`
|
||||
: null,
|
||||
};
|
||||
return Response.json(payload);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<ActionData> {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const ctx = await loadFormsContext({ request, params, requireModule: true });
|
||||
requireFormsPermission(ctx, "forms.builder");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const id = params.id;
|
||||
@@ -147,7 +308,7 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
const body = await request.formData();
|
||||
const op = body.get("op")?.toString() ?? "save";
|
||||
|
||||
const target = await db.form.findFirst({ where: { id, tenantId }, select: { id: true } });
|
||||
const target = await db.form.findFirst({ where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) }, select: { id: true } });
|
||||
if (!target) return { error: t("settings.forms.admin.errors.formNotFound") };
|
||||
|
||||
if (op === "save") {
|
||||
@@ -167,11 +328,12 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
return { error: t("settings.forms.admin.errors.invalidWebhookUrl") };
|
||||
}
|
||||
const targetTypeRaw = body.get("targetType")?.toString()?.trim() ?? "generic";
|
||||
const allowedTargets = new Set(["generic", "crm-contact", "entity-row"]);
|
||||
const allowedTargets = new Set(["generic", "crm-contact", "create-lead"]);
|
||||
const targetType = allowedTargets.has(targetTypeRaw) ? targetTypeRaw : "generic";
|
||||
let definition: unknown;
|
||||
let theme: unknown;
|
||||
let fieldMapping: unknown = null;
|
||||
let actions: unknown = [];
|
||||
try {
|
||||
definition = JSON.parse(body.get("definition")?.toString() ?? "{}");
|
||||
theme = JSON.parse(body.get("theme")?.toString() ?? "{}");
|
||||
@@ -179,6 +341,7 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
if (mappingRaw && mappingRaw.length > 0) {
|
||||
fieldMapping = JSON.parse(mappingRaw);
|
||||
}
|
||||
actions = JSON.parse(body.get("actions")?.toString() ?? "[]");
|
||||
} catch {
|
||||
return { error: t("settings.forms.admin.errors.invalidDefinitionJson") };
|
||||
}
|
||||
@@ -188,20 +351,109 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<A
|
||||
if (!defParse.success) return { error: t("settings.forms.admin.errors.invalidDefinition", { details: defParse.error.message.slice(0, 240) }) };
|
||||
const themeParse = FormThemeSchema.safeParse(theme);
|
||||
if (!themeParse.success) return { error: t("settings.forms.admin.errors.invalidTheme", { details: themeParse.error.message.slice(0, 240) }) };
|
||||
const actionRows = parseFormActions(actions);
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.form.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name,
|
||||
definition: defParse.data as object,
|
||||
theme: themeParse.data as object,
|
||||
allowedOrigins,
|
||||
notifyEmails,
|
||||
webhookUrl,
|
||||
targetType,
|
||||
fieldMapping: fieldMapping as object,
|
||||
},
|
||||
});
|
||||
await tx.formField.deleteMany({ where: { formId: id, tenantId: ctx.tenantId } });
|
||||
if (defParse.data.fields.length > 0) {
|
||||
await tx.formField.createMany({
|
||||
data: defParse.data.fields.map((field, position) => ({
|
||||
formId: id,
|
||||
tenantId: ctx.tenantId,
|
||||
fieldKey: field.key,
|
||||
fieldType: field.type,
|
||||
label: field.label,
|
||||
helpText: field.helpText ?? null,
|
||||
placeholder: field.placeholder ?? null,
|
||||
required: field.required,
|
||||
position,
|
||||
options: field.options ?? [],
|
||||
validationRules: field.validationRules ?? {},
|
||||
conditionalLogic: field.conditionalLogic ?? [],
|
||||
isSystem: field.type === "honeypot",
|
||||
})),
|
||||
});
|
||||
}
|
||||
await tx.formAction.deleteMany({ where: { formId: id, tenantId: ctx.tenantId } });
|
||||
if (actionRows.length > 0) {
|
||||
await tx.formAction.createMany({
|
||||
data: actionRows.map((action, position) => ({
|
||||
formId: id,
|
||||
tenantId: ctx.tenantId,
|
||||
actionType: action.actionType,
|
||||
name: action.name,
|
||||
enabled: action.enabled,
|
||||
position,
|
||||
fieldMapping: action.fieldMapping,
|
||||
actionConfig: action.actionConfig,
|
||||
})),
|
||||
});
|
||||
}
|
||||
});
|
||||
return { success: t("settings.forms.admin.messages.saved") };
|
||||
}
|
||||
if (op === "publish") {
|
||||
requireFormsPermission(ctx, "forms.publisher");
|
||||
const nextPublic = body.get("isPublic")?.toString() === "true";
|
||||
await db.form.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name,
|
||||
definition: defParse.data as object,
|
||||
theme: themeParse.data as object,
|
||||
allowedOrigins,
|
||||
notifyEmails,
|
||||
webhookUrl,
|
||||
targetType,
|
||||
fieldMapping: fieldMapping as object,
|
||||
isPublic: nextPublic,
|
||||
status: nextPublic ? "published" : "draft",
|
||||
publishedAt: nextPublic ? new Date() : null,
|
||||
},
|
||||
});
|
||||
return { success: t("settings.forms.admin.messages.saved") };
|
||||
return { success: t(nextPublic ? "settings.forms.admin.messages.published" : "settings.forms.admin.messages.unpublished") };
|
||||
}
|
||||
if (op === "rerun-submission") {
|
||||
requireFormsPermission(ctx, "forms.admin");
|
||||
const submissionId = body.get("submissionId")?.toString();
|
||||
if (!submissionId) return { error: t("settings.forms.admin.errors.missingSubmissionId") };
|
||||
const submission = await db.formSubmission.findFirst({
|
||||
where: { id: submissionId, formId: id, tenantId: ctx.tenantId },
|
||||
select: { id: true, formId: true, tenantId: true, payload: true },
|
||||
});
|
||||
if (!submission) return { error: t("settings.forms.admin.errors.submissionNotFound") };
|
||||
const values =
|
||||
submission.payload && typeof submission.payload === "object" && "values" in submission.payload
|
||||
? ((submission.payload as { values?: unknown }).values as Record<string, unknown>)
|
||||
: {};
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.formSubmission.update({
|
||||
where: { id: submission.id },
|
||||
data: { status: "received", result: { rerunAt: new Date().toISOString() } },
|
||||
});
|
||||
const outboxPayload = {
|
||||
submissionId: submission.id,
|
||||
formId: submission.formId,
|
||||
tenantId: ctx.tenantId,
|
||||
targetType: "generic",
|
||||
targetEntityId: null,
|
||||
fieldMapping: {},
|
||||
webhookUrl: null,
|
||||
notifyEmails: [],
|
||||
values,
|
||||
} as unknown as Parameters<typeof publishOutboxEvent>[1]["payload"];
|
||||
await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId: ctx.tenantId,
|
||||
type: "form.submission.process",
|
||||
payload: outboxPayload,
|
||||
dispatchKey: `form-submission-rerun:${submission.id}:${Date.now()}`,
|
||||
});
|
||||
});
|
||||
return { success: t("settings.forms.admin.messages.rerunQueued") };
|
||||
}
|
||||
return { error: t("settings.forms.admin.errors.unknownOperation") };
|
||||
}
|
||||
@@ -213,6 +465,9 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
const rootData = useRootData();
|
||||
const formatters = useLocaleFormatters();
|
||||
const embedSnippet = `<script src="${data.embedScriptBase}/embed/widget.js" data-form-key="${data.form.key}" async></script>`;
|
||||
const iframeSnippet = data.publicFormUrl
|
||||
? `<iframe src="${data.publicFormUrl}" width="100%" height="720" style="border:0"></iframe>`
|
||||
: "";
|
||||
|
||||
// Initial state for the builder. The DB shapes are unknown until we
|
||||
// parse them; we use the canonical zod parsers so invalid persisted
|
||||
@@ -225,7 +480,18 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
title: data.form.name || t("settings.forms.defaults.untitled"),
|
||||
submitLabel: t("settings.forms.admin.defaults.submitLabel"),
|
||||
successMessage: t("settings.forms.admin.defaults.successMessage"),
|
||||
fields: [{ key: "email", type: "email", label: t("settings.forms.admin.defaults.fields.email"), required: true }],
|
||||
gdprConsentLabel: t("settings.forms.admin.defaults.gdprConsentLabel"),
|
||||
captchaEnabled: true,
|
||||
fields: [
|
||||
{
|
||||
key: "email",
|
||||
type: "email",
|
||||
label: t("settings.forms.admin.defaults.fields.email"),
|
||||
required: true,
|
||||
conditionalLogic: [],
|
||||
validationRules: {},
|
||||
},
|
||||
],
|
||||
} satisfies FormDefinition);
|
||||
const themeParsed = FormThemeSchema.safeParse(data.form.theme ?? {});
|
||||
const initialTheme: FormTheme = themeParsed.success ? themeParsed.data : {};
|
||||
@@ -239,6 +505,7 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
webhookUrl: data.form.webhookUrl ?? "",
|
||||
targetType: data.form.targetType || "generic",
|
||||
fieldMapping: initialFieldMapping,
|
||||
actions: data.form.actions,
|
||||
};
|
||||
|
||||
const [name, setName] = useState(data.form.name);
|
||||
@@ -267,6 +534,7 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
<input type="hidden" name="webhookUrl" value={settings.webhookUrl} />
|
||||
<input type="hidden" name="targetType" value={settings.targetType} />
|
||||
<input type="hidden" name="fieldMapping" value={JSON.stringify(settings.fieldMapping)} />
|
||||
<input type="hidden" name="actions" value={JSON.stringify(settings.actions)} />
|
||||
<button type="submit" className="bg-blue-600 text-white px-4 py-1.5 rounded text-sm">
|
||||
{t("shared.save")}
|
||||
</button>
|
||||
@@ -274,8 +542,33 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-600">{t("settings.forms.admin.detail.embedSnippet")}</h2>
|
||||
<pre className="text-xs bg-gray-50 p-2 rounded overflow-x-auto">{embedSnippet}</pre>
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div className="min-w-0 flex-1 space-y-2">
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-600">{t("settings.forms.admin.detail.sharing")}</h2>
|
||||
{data.publicFormUrl ? (
|
||||
<>
|
||||
<a className="text-sm text-blue-700 underline break-all" href={data.publicFormUrl} target="_blank" rel="noreferrer">
|
||||
{data.publicFormUrl}
|
||||
</a>
|
||||
<pre className="text-xs bg-gray-50 p-2 rounded overflow-x-auto">{iframeSnippet}</pre>
|
||||
</>
|
||||
) : null}
|
||||
<pre className="text-xs bg-gray-50 p-2 rounded overflow-x-auto">{embedSnippet}</pre>
|
||||
</div>
|
||||
{data.publicFormUrl ? (
|
||||
<div className="rounded border bg-white p-2">
|
||||
<QRCodeSVG value={data.publicFormUrl} size={128} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Form method="post" className="mt-3">
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="publish" />
|
||||
<input type="hidden" name="isPublic" value={data.form.isPublic ? "false" : "true"} />
|
||||
<button type="submit" className="text-sm border rounded px-3 py-1">
|
||||
{data.form.isPublic ? t("settings.forms.admin.detail.unpublish") : t("settings.forms.admin.detail.publish")}
|
||||
</button>
|
||||
</Form>
|
||||
</section>
|
||||
|
||||
{action?.error ? <p className="text-red-600 text-sm">{action.error}</p> : null}
|
||||
@@ -295,25 +588,97 @@ export default function FormDetailPage(): React.JSX.Element {
|
||||
<section>
|
||||
<header className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-medium">{t("settings.forms.admin.detail.submissionsLatest")}</h2>
|
||||
<a href="?export=csv" className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.exportCsv")}</a>
|
||||
<div className="flex items-center gap-2">
|
||||
<Form method="get" className="flex items-center gap-2">
|
||||
<select name="status" defaultValue={data.statusFilter} className="rounded border px-2 py-1 text-sm">
|
||||
<option value="">{t("settings.forms.admin.detail.filters.allStatuses")}</option>
|
||||
<option value="received">{t("settings.forms.admin.detail.filters.received")}</option>
|
||||
<option value="processed">{t("settings.forms.admin.detail.filters.processed")}</option>
|
||||
<option value="route-failed">{t("settings.forms.admin.detail.filters.failed")}</option>
|
||||
</select>
|
||||
<button type="submit" className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.filters.apply")}</button>
|
||||
</Form>
|
||||
<a href={`?export=csv${data.statusFilter ? `&status=${encodeURIComponent(data.statusFilter)}` : ""}`} className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.exportCsv")}</a>
|
||||
<a href={`?export=pdf${data.statusFilter ? `&status=${encodeURIComponent(data.statusFilter)}` : ""}`} className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.exportPdf")}</a>
|
||||
</div>
|
||||
</header>
|
||||
{data.submissions.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">{t("settings.forms.admin.detail.noSubmissions")}</p>
|
||||
) : (
|
||||
<ul className="divide-y border rounded mt-2">
|
||||
{data.submissions.map((s) => (
|
||||
<li key={s.id} className="p-3">
|
||||
<div className="flex items-center gap-2 text-xs text-gray-500">
|
||||
<time dateTime={s.createdAt}>{formatters.dateTime(s.createdAt, { timeStyle: "medium" })}</time>
|
||||
<span>{"·"}</span>
|
||||
<RoutingStatusBadge status={s.status} />
|
||||
<span>{"·"}</span>
|
||||
<span>{t("settings.forms.admin.detail.origin", { origin: s.sourceOrigin ?? t("shared.notSet") })}</span>
|
||||
</div>
|
||||
<pre className="text-xs mt-1 whitespace-pre-wrap break-words">{s.preview}</pre>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="mt-2 overflow-x-auto rounded border">
|
||||
<table className="min-w-full divide-y text-sm">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("settings.forms.admin.detail.submittedAt")}</th>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("settings.forms.admin.detail.status")}</th>
|
||||
{data.columns.map((column) => (
|
||||
<th key={column.key} className="px-3 py-2 text-left font-medium">{column.label}</th>
|
||||
))}
|
||||
<th className="px-3 py-2 text-left font-medium">{t("settings.forms.admin.detail.files")}</th>
|
||||
<th className="px-3 py-2 text-left font-medium">{t("settings.forms.admin.detail.actions")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-white">
|
||||
{data.submissions.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td className="px-3 py-2 align-top whitespace-nowrap">
|
||||
<time dateTime={s.createdAt}>{formatters.dateTime(s.createdAt, { timeStyle: "medium" })}</time>
|
||||
<div className="text-xs text-gray-500">{t("settings.forms.admin.detail.origin", { origin: s.sourceOrigin ?? t("shared.notSet") })}</div>
|
||||
</td>
|
||||
<td className="px-3 py-2 align-top"><RoutingStatusBadge status={s.status} /></td>
|
||||
{data.columns.map((column) => (
|
||||
<td key={column.key} className="max-w-[220px] px-3 py-2 align-top">
|
||||
<span className="line-clamp-3 break-words">{displaySubmissionValue(s.values[column.key]) || t("shared.notSet")}</span>
|
||||
</td>
|
||||
))}
|
||||
<td className="px-3 py-2 align-top">
|
||||
{s.files.length === 0 ? (
|
||||
<span className="text-gray-400">{t("shared.notSet")}</span>
|
||||
) : (
|
||||
<ul className="space-y-1">
|
||||
{s.files.map((file) => (
|
||||
<li key={`${file.fieldKey}:${file.fileId}`}>
|
||||
<Link className="text-blue-700 underline" to={`../media/${file.fileId}/original`}>
|
||||
{file.fieldKey}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 align-top">
|
||||
<details>
|
||||
<summary className="cursor-pointer text-blue-700">{t("settings.forms.admin.detail.details")}</summary>
|
||||
<dl className="mt-2 space-y-1 text-xs">
|
||||
<div><dt className="font-medium">{t("settings.forms.admin.detail.userAgent")}</dt><dd className="break-all">{s.userAgent ?? t("shared.notSet")}</dd></div>
|
||||
<div><dt className="font-medium">{t("settings.forms.admin.detail.payload")}</dt><dd><pre className="whitespace-pre-wrap break-words">{s.preview}</pre></dd></div>
|
||||
</dl>
|
||||
{s.actionLogs.length > 0 ? (
|
||||
<ul className="mt-2 space-y-1">
|
||||
{s.actionLogs.map((log) => (
|
||||
<li key={log.id} className="text-xs text-gray-600">
|
||||
<code>{log.actionType}</code> {"-"} {log.status}
|
||||
{log.targetId ? <> {"-"} {log.targetType}:{log.targetId}</> : null}
|
||||
{log.errorMessage ? <span className="text-red-600"> {"-"} {log.errorMessage}</span> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
<Form method="post" className="mt-2">
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="rerun-submission" />
|
||||
<input type="hidden" name="submissionId" value={s.id} />
|
||||
<button type="submit" className="text-xs border rounded px-2 py-1">
|
||||
{t("settings.forms.admin.detail.rerunSubmission")}
|
||||
</button>
|
||||
</Form>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
+51
-11
@@ -11,18 +11,23 @@
|
||||
*/
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, Form, Link, useActionData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@toolctrl/form-widget";
|
||||
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@hivegrid/form-widget";
|
||||
import { seedShkFormTemplates } from "~/modules/forms/services/shkFormTemplates.server";
|
||||
import { formsOwnerWhere, loadFormsContext, requireFormsPermission } from "~/modules/forms/routes/formsAccess.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
key: string;
|
||||
slug: string | null;
|
||||
name: string;
|
||||
subtype: string;
|
||||
status: string;
|
||||
isEnabled: boolean;
|
||||
submissions: number;
|
||||
createdAt: string;
|
||||
@@ -36,15 +41,18 @@ type LoaderData = {
|
||||
type ActionData = { error?: string; createdId?: string };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<LoaderData> {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const ctx = await loadFormsContext({ request, params, requireModule: true });
|
||||
requireFormsPermission(ctx, "forms.basic");
|
||||
const forms = await db.form.findMany({
|
||||
where: { tenantId },
|
||||
where: { tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
key: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
subtype: true,
|
||||
status: true,
|
||||
isEnabled: true,
|
||||
createdAt: true,
|
||||
_count: { select: { submissions: true } },
|
||||
@@ -54,7 +62,10 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<L
|
||||
forms: forms.map((f) => ({
|
||||
id: f.id,
|
||||
key: f.key,
|
||||
slug: f.slug,
|
||||
name: f.name,
|
||||
subtype: f.subtype,
|
||||
status: f.status,
|
||||
isEnabled: f.isEnabled,
|
||||
submissions: f._count.submissions,
|
||||
createdAt: f.createdAt.toISOString(),
|
||||
@@ -64,8 +75,8 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<L
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response | ActionData> {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const ctx = await loadFormsContext({ request, params, requireModule: true });
|
||||
requireFormsPermission(ctx, "forms.builder");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const body = await request.formData();
|
||||
@@ -74,10 +85,18 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<R
|
||||
const name = body.get("name")?.toString()?.trim();
|
||||
const origin = body.get("allowedOrigin")?.toString()?.trim() ?? "";
|
||||
if (!name) return { error: t("settings.forms.admin.errors.nameRequired") };
|
||||
const baseSlug = slugify(name).slice(0, 80) || "form";
|
||||
let slug = baseSlug;
|
||||
for (let i = 2; i < 100; i += 1) {
|
||||
const exists = await db.form.findFirst({ where: { tenantId: ctx.tenantId, slug }, select: { id: true } });
|
||||
if (!exists) break;
|
||||
slug = `${baseSlug}-${i}`;
|
||||
}
|
||||
const definition = FormDefinitionSchema.parse({
|
||||
title: name,
|
||||
submitLabel: t("settings.forms.admin.defaults.submitLabel"),
|
||||
successMessage: t("settings.forms.admin.defaults.successMessage"),
|
||||
gdprConsentLabel: t("settings.forms.admin.defaults.gdprConsentLabel"),
|
||||
fields: [
|
||||
{ key: "full_name", type: "text", label: t("settings.forms.admin.defaults.fields.fullName"), required: true },
|
||||
{ key: "email", type: "email", label: t("settings.forms.admin.defaults.fields.email"), required: true },
|
||||
@@ -87,8 +106,12 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<R
|
||||
});
|
||||
const created = await db.form.create({
|
||||
data: {
|
||||
tenantId,
|
||||
tenantId: ctx.tenantId,
|
||||
createdByUserId: ctx.userId,
|
||||
name,
|
||||
slug,
|
||||
subtype: "standard",
|
||||
status: "draft",
|
||||
definition: definition as object,
|
||||
allowedOrigins: origin ? [origin] : [],
|
||||
config: { honeypotEnabled: true } as object,
|
||||
@@ -97,10 +120,14 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<R
|
||||
});
|
||||
return { createdId: created.id };
|
||||
}
|
||||
if (op === "seed-shk-templates") {
|
||||
await seedShkFormTemplates({ tenantId: ctx.tenantId, userId: ctx.userId, t });
|
||||
return { error: undefined };
|
||||
}
|
||||
if (op === "toggle") {
|
||||
const id = body.get("id")?.toString();
|
||||
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
|
||||
const target = await db.form.findFirst({ where: { id, tenantId }, select: { isEnabled: true } });
|
||||
const target = await db.form.findFirst({ where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) }, select: { isEnabled: true } });
|
||||
if (!target) return { error: t("settings.forms.admin.errors.formNotFound") };
|
||||
await db.form.update({ where: { id }, data: { isEnabled: !target.isEnabled } });
|
||||
return { error: undefined };
|
||||
@@ -108,7 +135,7 @@ export async function action({ request, params }: ActionFunctionArgs): Promise<R
|
||||
if (op === "delete") {
|
||||
const id = body.get("id")?.toString();
|
||||
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
|
||||
await db.form.deleteMany({ where: { id, tenantId } });
|
||||
await db.form.deleteMany({ where: { id, tenantId: ctx.tenantId, ...formsOwnerWhere(ctx) } });
|
||||
return { error: undefined };
|
||||
}
|
||||
return { error: t("settings.forms.admin.errors.unknownOperation") };
|
||||
@@ -119,6 +146,7 @@ export default function FormsAdmin(): React.JSX.Element {
|
||||
const actionData = useActionData() as ActionData | undefined;
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const rootData = useRootData();
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<header>
|
||||
@@ -131,7 +159,15 @@ export default function FormsAdmin(): React.JSX.Element {
|
||||
<section>
|
||||
<h2 className="text-lg font-medium mb-2">{t("settings.forms.admin.create.title")}</h2>
|
||||
{actionData?.error ? <p className="text-red-600 text-sm mb-2">{actionData.error}</p> : null}
|
||||
<Form method="post" className="mb-3">
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="seed-shk-templates" />
|
||||
<button type="submit" className="text-sm border rounded px-3 py-1">
|
||||
{t("settings.forms.admin.create.seedShkTemplates")}
|
||||
</button>
|
||||
</Form>
|
||||
<Form method="post" className="flex gap-2 items-end">
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="create" />
|
||||
<label className="flex flex-col gap-1 flex-1">
|
||||
<span className="text-sm">{t("settings.forms.admin.create.name")}</span>
|
||||
@@ -157,6 +193,8 @@ export default function FormsAdmin(): React.JSX.Element {
|
||||
<Link to={f.id} className="font-medium text-blue-700 hover:underline">{f.name}</Link>
|
||||
<div className="text-xs text-gray-500">
|
||||
{t("settings.forms.admin.existing.key")}: <code>{f.key}</code> ·{" "}
|
||||
{t("settings.forms.admin.existing.slug")}: <code>{f.slug ?? "n/a"}</code> ·{" "}
|
||||
{t("settings.forms.admin.existing.status")}: {f.status} ·{" "}
|
||||
{t("settings.forms.admin.existing.submissionsCount", {
|
||||
count: f.submissions,
|
||||
formattedCount: formatters.number(f.submissions),
|
||||
@@ -172,11 +210,13 @@ export default function FormsAdmin(): React.JSX.Element {
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Form method="post">
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="toggle" />
|
||||
<input type="hidden" name="id" value={f.id} />
|
||||
<button className="text-sm border rounded px-2 py-1">{f.isEnabled ? t("shared.disable") : t("shared.enable")}</button>
|
||||
</Form>
|
||||
<Form method="post" onSubmit={(e) => { if (!confirm(t("settings.forms.admin.delete.confirm"))) e.preventDefault(); }}>
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="delete" />
|
||||
<input type="hidden" name="id" value={f.id} />
|
||||
<button className="text-sm border rounded px-2 py-1 text-red-600">{t("shared.delete")}</button>
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, redirect } from "react-router";
|
||||
import { useParams, Outlet } from "react-router";
|
||||
import { useState, Fragment, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import SidebarIconsLayout, { IconDto } from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityGroupBySlug } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { translateEntityTitlePlural } from "~/utils/i18n/translateLabel";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const group = await getEntityGroupBySlug(params.group!);
|
||||
if (!group) {
|
||||
throw redirect(tenantId ? UrlUtils.currentTenantUrl(params, "404") : "/404");
|
||||
}
|
||||
const data: LoaderData = {
|
||||
title: `${t(group.title)} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
const mainElement = useRef<HTMLDivElement>(null);
|
||||
|
||||
const group = appOrAdminData.entityGroups.find((f) => f.slug === params.group);
|
||||
if (!group) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const visibleGroupEntities = group.entities.filter(({ entity }) => getUserHasPermission(appOrAdminData, getEntityPermission(entity, "view")));
|
||||
const thereAreIcons = visibleGroupEntities.some(({ entity }) => !!entity.icon);
|
||||
const items: IconDto[] = [
|
||||
{
|
||||
name: t("shared.summary"),
|
||||
href: params.tenant ? appPath({ tenantSlug: params.tenant, path: `g/${params.group}`, mode: "host-aware" }) : adminPath(`g/${params.group}`, { mode: "host-aware" }),
|
||||
prefetch: "intent",
|
||||
exact: true,
|
||||
icon: !thereAreIcons ? undefined : (
|
||||
<svg className="h-5 w-5" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="50" height="50" viewBox="0 0 50 50" fill="currentColor">
|
||||
<path d="M 39 0 L 39 2 L 46.5625 2 L 34 14.5625 L 30.71875 11.28125 L 30 10.59375 L 29.28125 11.28125 L 18 22.5625 L 14.71875 19.28125 L 14 18.59375 L 13.28125 19.28125 L 0.28125 32.28125 L 1.71875 33.71875 L 14 21.4375 L 17.28125 24.71875 L 18 25.40625 L 18.71875 24.71875 L 30 13.4375 L 33.28125 16.71875 L 34 17.40625 L 34.71875 16.71875 L 48 3.4375 L 48 11 L 50 11 L 50 0 Z M 42 14 L 42 50 L 44 50 L 44 14 Z M 48 15 L 48 50 L 50 50 L 50 15 Z M 30 20 L 30 50 L 32 50 L 32 20 Z M 36 20 L 36 50 L 38 50 L 38 20 Z M 24 24 L 24 50 L 26 50 L 26 24 Z M 12 28 L 12 50 L 14 50 L 14 28 Z M 18 30 L 18 50 L 20 50 L 20 30 Z M 6 34 L 6 50 L 8 50 L 8 34 Z M 0 38 L 0 50 L 2 50 L 2 38 Z"></path>
|
||||
</svg>
|
||||
),
|
||||
iconSelected: !thereAreIcons ? undefined : (
|
||||
<svg className="h-5 w-5" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="50" height="50" viewBox="0 0 50 50" fill="currentColor">
|
||||
<path d="M 38 0 L 38 4 L 43.1875 4 L 34 13.1875 L 31.40625 10.59375 L 30 9.15625 L 28.59375 10.59375 L 18 21.1875 L 15.40625 18.59375 L 14 17.15625 L 12.59375 18.59375 L 0.59375 30.59375 L 3.40625 33.40625 L 14 22.8125 L 16.59375 25.40625 L 18 26.84375 L 19.40625 25.40625 L 30 14.8125 L 32.59375 17.40625 L 34 18.84375 L 35.40625 17.40625 L 46 6.8125 L 46 12 L 50 12 L 50 0 Z M 44 15 L 44 50 L 48 50 L 48 15 Z M 30 20 L 30 50 L 34 50 L 34 20 Z M 37 20 L 37 50 L 41 50 L 41 20 Z M 23 24 L 23 50 L 27 50 L 27 24 Z M 16 30 L 16 50 L 20 50 L 20 30 Z M 9 31 L 9 50 L 13 50 L 13 31 Z M 2 38 L 2 50 L 6 50 L 6 38 Z"></path>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
visibleGroupEntities.forEach(({ entity }) => {
|
||||
items.push({
|
||||
name: translateEntityTitlePlural(t, i18n, entity),
|
||||
href: params.tenant
|
||||
? appPath({ tenantSlug: params.tenant, path: `g/${params.group}/${entity.slug}`, mode: "host-aware" })
|
||||
: adminPath(`g/${params.group}/${entity.slug}`, { mode: "host-aware" }),
|
||||
prefetch: "intent",
|
||||
textIcon: entity.icon,
|
||||
textIconSelected: entity.icon,
|
||||
});
|
||||
});
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
{!params.id ? (
|
||||
<SidebarIconsLayout label={{ align: "right" }} items={items}>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
) : (
|
||||
<div className="sm:h-[calc(100vh-56px)]">
|
||||
<div ref={mainElement} className="w-full overflow-x-hidden">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowNewRoute from "~/modules/rows/components/RowNewRoute";
|
||||
import { Rows_New } from "~/modules/rows/routes/Rows_New.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_New.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_New.action(args);
|
||||
|
||||
export default () => <RowNewRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Relationships } from "~/modules/rows/routes/Rows_Relationships.server";
|
||||
import RowsRelationshipsRoute from "~/modules/rows/components/RowsRelationshipsRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Relationships.loader(args);
|
||||
|
||||
export default () => <RowsRelationshipsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/modules/rows/routes/Rows_List.server", () => ({
|
||||
Rows_List: {
|
||||
loader: vi.fn(() => Response.json({ ok: true })),
|
||||
action: vi.fn(() => Response.json({ ok: true })),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/entities/entityGroups.db.server", () => ({
|
||||
getEntityGroupBySlug: vi.fn(),
|
||||
}));
|
||||
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { getEntityGroupBySlug } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { action, loader } from "./__$entity";
|
||||
|
||||
const request = new Request("https://app.example.test/acme/g/sales/invoices");
|
||||
|
||||
describe("group entity route boundary", () => {
|
||||
it("rejects entities that are not part of the active group before loading rows", async () => {
|
||||
vi.mocked(getEntityGroupBySlug).mockResolvedValue({
|
||||
id: "group_1",
|
||||
slug: "sales",
|
||||
entities: [{ entity: { slug: "contacts", name: "contact" } }],
|
||||
} as never);
|
||||
|
||||
await expect(loader({ request, params: { tenant: "acme", group: "sales", entity: "invoices" }, context: {} } as never)).rejects.toMatchObject({ status: 302 });
|
||||
expect(Rows_List.loader).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("delegates actions only for entities in the active group", async () => {
|
||||
vi.mocked(getEntityGroupBySlug).mockResolvedValue({
|
||||
id: "group_1",
|
||||
slug: "sales",
|
||||
entities: [{ entity: { slug: "contacts", name: "contact" } }],
|
||||
} as never);
|
||||
|
||||
await action({ request, params: { tenant: "acme", group: "sales", entity: "contacts" }, context: {} } as never);
|
||||
expect(Rows_List.action).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowsViewRoute from "~/modules/rows/components/RowsViewRoute";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getEntityGroupBySlug } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
async function requireEntityInGroup(params: { group?: string; entity?: string; tenant?: string }) {
|
||||
if (!params.group || !params.entity) {
|
||||
throw redirect(UrlUtils.currentTenantUrl(params, "404"));
|
||||
}
|
||||
const group = await getEntityGroupBySlug(params.group);
|
||||
const entityBelongsToGroup = group?.entities.some(({ entity }) => entity.slug === params.entity || entity.name === params.entity) === true;
|
||||
if (!entityBelongsToGroup) {
|
||||
throw redirect(UrlUtils.currentTenantUrl(params, "404"));
|
||||
}
|
||||
}
|
||||
|
||||
export const loader = async (args: LoaderFunctionArgs) => {
|
||||
await requireEntityInGroup(args.params);
|
||||
return Rows_List.loader(args);
|
||||
};
|
||||
export const action: ActionFunction = async (args) => {
|
||||
await requireEntityInGroup(args.params);
|
||||
return Rows_List.action(args);
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_List.LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<RowsViewRoute
|
||||
key={data.rowsData.entity.id}
|
||||
rowsData={data.rowsData}
|
||||
items={data.rowsData.items}
|
||||
routes={data.routes}
|
||||
saveCustomViews={true}
|
||||
permissions={{
|
||||
create: getUserHasPermission(appOrAdminData, getEntityPermission(data.rowsData.entity, "create")),
|
||||
}}
|
||||
currentSession={{
|
||||
user: appOrAdminData.user,
|
||||
isSuperAdmin: appOrAdminData.isSuperAdmin,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { RowsApi } from "~/utils/api/.server/RowsApi";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
|
||||
import { getEntityGroupBySlug } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import RowsList from "~/components/entities/rows/RowsList";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getPermissionsByUser, getUserRoleInAdmin } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
entitiesData: { [entity: string]: RowsApi.GetRowsData };
|
||||
entitiesRoutes: { [entity: string]: EntitiesApi.Routes };
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const userInfo = await getUserInfo(request);
|
||||
const group = await getEntityGroupBySlug(params.group!);
|
||||
if (!group) {
|
||||
throw redirect(tenantId ? UrlUtils.currentTenantUrl(params, "404") : "/404");
|
||||
}
|
||||
const isSuperAdmin = Boolean(await getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin));
|
||||
const permissions = isSuperAdmin ? null : (await getPermissionsByUser(userInfo.userId, tenantId)).map((permission) => permission as string);
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const allEntities = await getAllEntities({ tenantId });
|
||||
const entitiesData: LoaderData["entitiesData"] = {};
|
||||
const entitiesRoutes: LoaderData["entitiesRoutes"] = {};
|
||||
await Promise.all(
|
||||
group.entities.map(async ({ entityId, allView }) => {
|
||||
const entity = allEntities.find((f) => f.id === entityId);
|
||||
if (!entity || (!isSuperAdmin && !permissions?.includes(getEntityPermission(entity, "view")))) {
|
||||
return;
|
||||
}
|
||||
const data = await RowsApi.getAll({
|
||||
entity,
|
||||
tenantId,
|
||||
userId: isSuperAdmin ? undefined : userInfo.userId,
|
||||
urlSearchParams,
|
||||
entityView: allView ?? undefined,
|
||||
});
|
||||
entitiesData[entity.name] = data;
|
||||
entitiesRoutes[entity.name] = EntitiesApi.getNoCodeRoutes({ request, params });
|
||||
return entitiesData;
|
||||
})
|
||||
);
|
||||
const data: LoaderData = {
|
||||
title: `${t(group.title)} | ${process.env.APP_NAME}`,
|
||||
entitiesData,
|
||||
entitiesRoutes,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
|
||||
function getGroup() {
|
||||
return appOrAdminData.entityGroups.find((f) => f.slug === params.group);
|
||||
}
|
||||
const visibleGroupEntities = getGroup()?.entities.filter(({ entity }) => getUserHasPermission(appOrAdminData, getEntityPermission(entity, "view"))) ?? [];
|
||||
|
||||
return (
|
||||
<IndexPageLayout>
|
||||
<div className="space-y-2">
|
||||
{visibleGroupEntities.map(({ entity, allView }) => {
|
||||
const entityData = data.entitiesData[entity.name];
|
||||
if (!entityData) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div key={entity.id} className="space-y-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-sm font-medium">
|
||||
{translateLabel(t, i18n, entity.titlePlural)} <span className="text-muted-foreground text-xs">({entityData.items.length})</span>
|
||||
</h3>
|
||||
{getUserHasPermission(appOrAdminData, getEntityPermission(entity, "create")) && (
|
||||
<Link
|
||||
to={entity.slug + "/new"}
|
||||
aria-label={`${t("shared.create")} ${translateLabel(t, i18n, entity.title)}`}
|
||||
className="text-foreground bg-secondary hover:bg-secondary/90 rounded-full p-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600"
|
||||
>
|
||||
<PlusIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<RowsList
|
||||
view={(allView?.layout ?? "card") as "table" | "board" | "grid" | "card"}
|
||||
entity={entityData.entity}
|
||||
items={entityData.items}
|
||||
routes={data.entitiesRoutes[entity.name]}
|
||||
pagination={entityData.pagination}
|
||||
currentView={allView}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</IndexPageLayout>
|
||||
);
|
||||
};
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
import { LoaderFunctionArgs, redirect, MetaFunction, useLoaderData } from "react-router";
|
||||
import { useSearchParams } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAppDashboardStats } from "~/utils/services/appDashboardService";
|
||||
import { DashboardStats } from "~/components/ui/stats/DashboardStats";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { Stat } from "~/application/dtos/stats/Stat";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import PeriodHelper, { defaultPeriodFilter, PeriodFilters } from "~/utils/helpers/PeriodHelper";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { EntityGroupWithDetails, getEntityGroupBySlug } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getPermissionsByUser, getUserRoleInAdmin } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getEntityPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { translateLabel } from "~/utils/i18n/translateLabel";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
group: EntityGroupWithDetails;
|
||||
stats: Stat[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const group = await getEntityGroupBySlug(params.group!);
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!group) {
|
||||
throw redirect(tenantId ? UrlUtils.currentTenantUrl(params, "404") : "/404");
|
||||
}
|
||||
const isSuperAdmin = Boolean(await getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin));
|
||||
const permissions = isSuperAdmin ? null : (await getPermissionsByUser(userInfo.userId, tenantId)).map((permission) => permission as string);
|
||||
const visibleEntities = group.entities.flatMap((e) => e.entity).filter((entity) => isSuperAdmin || permissions?.includes(getEntityPermission(entity, "view")));
|
||||
const stats = await getAppDashboardStats({
|
||||
t,
|
||||
tenant,
|
||||
gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }),
|
||||
entities: visibleEntities,
|
||||
});
|
||||
stats
|
||||
.filter((f) => f.entity)
|
||||
.forEach((stat) => {
|
||||
const tenantSlug = tenant?.slug ?? params.tenant ?? tenantId;
|
||||
stat.path = tenantId
|
||||
? appPath({ tenantSlug, path: `g/${params.group}/${stat.entity?.slug}`, mode: "host-aware" })
|
||||
: adminPath(`g/${params.group}/${stat.entity?.slug}`, { mode: "host-aware" });
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t(group.title)} | ${process.env.APP_NAME}`,
|
||||
group,
|
||||
stats,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function GroupIndexRoute() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
return (
|
||||
<EditPageLayout>
|
||||
{data.stats.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground grow font-medium leading-4">{translateLabel(t, i18n, data.group.title)}</h3>
|
||||
<div>
|
||||
<InputSelector
|
||||
className="w-44"
|
||||
withSearch={false}
|
||||
name="period"
|
||||
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
|
||||
options={PeriodFilters.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: t(f.name),
|
||||
};
|
||||
})}
|
||||
setValue={(value) => {
|
||||
if (value) {
|
||||
searchParams.set("period", value?.toString() ?? "");
|
||||
} else {
|
||||
searchParams.delete("period");
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DashboardStats items={data.stats} />
|
||||
</div>
|
||||
)}
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// P17 HR-Hub core (AK-P17a) — HR hub start route. Loader gates on the connector
|
||||
// (module off -> locked empty state) and hr.read_own (missing -> 404), then
|
||||
// renders quick links to the HR areas. Interim-UI (AD-28): the loader builds the
|
||||
// data, HrHubPage renders it from ~/ui; final Subframe optics = design-nachzug.
|
||||
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
|
||||
import {
|
||||
hrAnnouncementsPath,
|
||||
hrDirectoryPath,
|
||||
hrLeavePath,
|
||||
hrLocationsPath,
|
||||
hrMyDocumentsPath,
|
||||
hrPasswordSafePath,
|
||||
hrPayslipsPath,
|
||||
hrRequestsPath,
|
||||
hrSickPath,
|
||||
hrSurveysPath,
|
||||
HR_MODULE_KEY,
|
||||
} from "~/utils/integrations/hrRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { HrHubPage, type HrHubLink } from "~/components/screens/hr/HrHubPage";
|
||||
|
||||
type LoaderData = { title: string; moduleActive: boolean; links: HrHubLink[]; canViewAdmin: boolean };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadHrContext({ request, params });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title: `${t("hr.hub.title")} | ${process.env.APP_NAME}`, moduleActive: false, links: [], canViewAdmin: false } satisfies LoaderData);
|
||||
}
|
||||
|
||||
try {
|
||||
requireHrPermission(ctx, "hr.read_own");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const links: HrHubLink[] = [
|
||||
{ labelKey: "hr.nav.leave", href: hrLeavePath(tenantSlug) },
|
||||
{ labelKey: "hr.nav.sick", href: hrSickPath(tenantSlug) },
|
||||
{ labelKey: "hr.nav.announcements", href: hrAnnouncementsPath(tenantSlug) },
|
||||
{ labelKey: "hr.nav.payslips", href: hrPayslipsPath(tenantSlug) },
|
||||
{ labelKey: "hr.nav.requests", href: hrRequestsPath(tenantSlug) },
|
||||
{ labelKey: "hr.nav.surveys", href: hrSurveysPath(tenantSlug) },
|
||||
{ labelKey: "hr.nav.directory", href: hrDirectoryPath(tenantSlug) },
|
||||
{ labelKey: "hr.nav.locations", href: hrLocationsPath(tenantSlug) },
|
||||
{ labelKey: "hr.nav.myDocuments", href: hrMyDocumentsPath(tenantSlug) },
|
||||
];
|
||||
if (ctx.permissions.includes("hr.passwordsafe.use")) {
|
||||
links.push({ labelKey: "hr.nav.passwordSafe", href: hrPasswordSafePath(tenantSlug) });
|
||||
}
|
||||
const canViewAdmin = ctx.permissions.includes("hr.passwordsafe.admin");
|
||||
|
||||
return Response.json({ title: `${t("hr.hub.title")} | ${process.env.APP_NAME}`, moduleActive: true, links, canViewAdmin } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export default function HrHubRoute() {
|
||||
const { moduleActive, links } = useLoaderData<LoaderData>();
|
||||
return <HrHubPage moduleActive={moduleActive} links={links} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: HR_MODULE_KEY };
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
// P17 HR-Hub workflows (AK-P17b) — announcements editor (admin). Create with
|
||||
// audience, acknowledgement requirement, pin, schedule and expiry; archive.
|
||||
// Needs hr.write. Transitional UI.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { badRequestResponse, hrActionErrorResponse, loadHrContext, notFoundResponse, requireHrPermission } from "~/utils/integrations/hrAccess.server";
|
||||
import { archiveAnnouncement, createAnnouncement, listAllAnnouncements, type HrAudienceKind } from "~/utils/integrations/hrAnnouncementService.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { HrAdminAnnouncementsPage } from "~/components/screens/hr/HrAdminAnnouncementsPage";
|
||||
|
||||
type Row = { id: string; title: string; audienceKind: string; requiresAck: boolean; pinned: boolean; publishedIso: string | null };
|
||||
type LoaderData = { title: string; rows: Row[] };
|
||||
const AUDIENCES: HrAudienceKind[] = ["all", "team", "location"];
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadHrContext({ request, params });
|
||||
const title = `${t("hr.announcements.admin.title")} | ${process.env.APP_NAME}`;
|
||||
if (!ctx.hasModule) return Response.json({ title, rows: [] } satisfies LoaderData);
|
||||
try {
|
||||
requireHrPermission(ctx, "hr.write");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const list = await listAllAnnouncements(ctx.tenantId);
|
||||
const rows: Row[] = list.map((a) => ({ id: a.id, title: a.title, audienceKind: a.audienceKind, requiresAck: a.requiresAcknowledgement, pinned: a.pinnedAt != null, publishedIso: a.publishAt ? a.publishAt.toISOString() : null }));
|
||||
return Response.json({ title, rows } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadHrContext({ request, params, requireModule: true });
|
||||
requireHrPermission(ctx, "hr.write");
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent")?.toString();
|
||||
try {
|
||||
if (intent === "create") {
|
||||
const audience = (form.get("audienceKind")?.toString() ?? "all") as HrAudienceKind;
|
||||
const publishAt = form.get("publishAt")?.toString();
|
||||
const expiresAt = form.get("expiresAt")?.toString();
|
||||
await createAnnouncement({
|
||||
tenantId: ctx.tenantId,
|
||||
authorUserId: ctx.userId,
|
||||
title: form.get("title")?.toString() ?? "",
|
||||
body: form.get("body")?.toString() ?? "",
|
||||
audienceKind: AUDIENCES.includes(audience) ? audience : "all",
|
||||
audienceRef: form.get("audienceRef")?.toString() || null,
|
||||
requiresAcknowledgement: form.get("requiresAck") === "1",
|
||||
pinned: form.get("pinned") === "1",
|
||||
publishAt: publishAt ? new Date(publishAt) : null,
|
||||
expiresAt: expiresAt ? new Date(expiresAt) : null,
|
||||
});
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
if (intent === "archive") {
|
||||
await archiveAnnouncement({ tenantId: ctx.tenantId, actorUserId: ctx.userId, announcementId: form.get("announcementId")?.toString() ?? "" });
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
return hrActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function HrAdminAnnouncementsRoute() {
|
||||
const { rows } = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher();
|
||||
return (
|
||||
<HrAdminAnnouncementsPage
|
||||
rows={rows}
|
||||
audiences={AUDIENCES}
|
||||
submitting={fetcher.state !== "idle"}
|
||||
actions={{
|
||||
onCreate: (input) =>
|
||||
fetcher.submit(
|
||||
{
|
||||
intent: "create",
|
||||
title: input.title,
|
||||
body: input.body,
|
||||
audienceKind: input.audienceKind,
|
||||
audienceRef: input.audienceRef,
|
||||
requiresAck: input.requiresAck ? "1" : "0",
|
||||
pinned: input.pinned ? "1" : "0",
|
||||
publishAt: input.publishAt,
|
||||
expiresAt: input.expiresAt,
|
||||
},
|
||||
{ method: "post" },
|
||||
),
|
||||
onArchive: (announcementId) => fetcher.submit({ intent: "archive", announcementId }, { method: "post" }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: "hr" };
|
||||
Loaded 100 of 3781 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user