Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
-101
@@ -1,101 +0,0 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
requireAuth: vi.fn(),
|
||||
getTranslations: vi.fn(),
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
requirePortalReadAccess: vi.fn(),
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
getPortalById: vi.fn(),
|
||||
db: {
|
||||
analyticsEvent: { groupBy: vi.fn(), findMany: vi.fn(), count: vi.fn() },
|
||||
analyticsPageView: { groupBy: vi.fn(), findMany: vi.fn(), count: vi.fn() },
|
||||
analyticsUniqueVisitor: { findMany: vi.fn(), count: vi.fn() },
|
||||
portalUser: { findMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: (...args: unknown[]) => mocks.requireAuth(...args) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
|
||||
vi.mock("./portalAccess.server", () => ({ requirePortalReadAccess: (...args: unknown[]) => mocks.requirePortalReadAccess(...args) }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: (...args: unknown[]) => mocks.verifyUserHasPermission(...args) }));
|
||||
vi.mock("~/modules/portals/db/portals.db.server", () => ({ getPortalById: (...args: unknown[]) => mocks.getPortalById(...args) }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: mocks.db }));
|
||||
vi.mock("~/components/ui/input/InputFilters", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/layouts/EditPageLayout", () => ({ default: () => null }));
|
||||
vi.mock("~/components/ui/tables/TableSimple", () => ({ default: () => null }));
|
||||
vi.mock("~/modules/portals/components/PortalTimestamp", () => ({ PortalTimestamp: () => null }));
|
||||
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
|
||||
const params = { tenant: "acme", portal: "docs" };
|
||||
|
||||
function args(url: string): LoaderFunctionArgs {
|
||||
return { request: new Request(url), params, context: {}, unstable_pattern: "app/:tenant/portals/:portal/analytics" } as LoaderFunctionArgs;
|
||||
}
|
||||
|
||||
describe("portal analytics table loader filters", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
|
||||
mocks.getTenantIdFromUrl.mockResolvedValue("tenant-1");
|
||||
mocks.getPortalById.mockResolvedValue({ id: "portal-1", subdomain: "docs", title: "Docs" });
|
||||
mocks.db.portalUser.findMany.mockResolvedValue([{ id: "portal-user-1", email: "u@example.test" }]);
|
||||
mocks.db.analyticsEvent.groupBy.mockImplementation(async ({ by }: { by: string[] }) => [{ [by[0] ?? "action"]: `${by[0] ?? "action"}-1` }]);
|
||||
mocks.db.analyticsPageView.groupBy.mockResolvedValue([{ route: "/docs" }]);
|
||||
mocks.db.analyticsEvent.findMany.mockResolvedValue([]);
|
||||
mocks.db.analyticsPageView.findMany.mockResolvedValue([]);
|
||||
mocks.db.analyticsUniqueVisitor.findMany.mockResolvedValue([]);
|
||||
mocks.db.analyticsEvent.count.mockResolvedValue(0);
|
||||
mocks.db.analyticsPageView.count.mockResolvedValue(0);
|
||||
mocks.db.analyticsUniqueVisitor.count.mockResolvedValue(0);
|
||||
});
|
||||
|
||||
it("passes the composed event where clause to both list and count queries", async () => {
|
||||
const { loader } = await import("./portals.$portal/analytics.events.js");
|
||||
|
||||
await loader(
|
||||
args(
|
||||
"https://app.example.test/app/acme/portals/docs/analytics/events?action=download&category=cta&label=hero&value=42&cookie=cookie-1&portalUserId=portal-user-1&page=3&pageSize=25"
|
||||
)
|
||||
);
|
||||
|
||||
const expectedWhere = {
|
||||
portalId: "portal-1",
|
||||
action: "download",
|
||||
category: "cta",
|
||||
label: "hero",
|
||||
value: "42",
|
||||
uniqueVisitor: { cookie: "cookie-1", portalUserId: "portal-user-1" },
|
||||
};
|
||||
expect(mocks.db.analyticsEvent.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 25, skip: 50, where: expectedWhere }));
|
||||
expect(mocks.db.analyticsEvent.count).toHaveBeenCalledWith({ where: expectedWhere });
|
||||
});
|
||||
|
||||
it("passes the composed page-view where clause to both list and count queries", async () => {
|
||||
const { loader } = await import("./portals.$portal/analytics.page-views.js");
|
||||
|
||||
await loader(
|
||||
args("https://app.example.test/app/acme/portals/docs/analytics/page-views?route=/docs&cookie=cookie-1&portalUserId=portal-user-1&page=2&pageSize=10")
|
||||
);
|
||||
|
||||
const expectedWhere = {
|
||||
portalId: "portal-1",
|
||||
route: "/docs",
|
||||
uniqueVisitor: { cookie: "cookie-1", portalUserId: "portal-user-1" },
|
||||
};
|
||||
expect(mocks.db.analyticsPageView.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 10, skip: 10, where: expectedWhere }));
|
||||
expect(mocks.db.analyticsPageView.count).toHaveBeenCalledWith({ where: expectedWhere });
|
||||
});
|
||||
|
||||
it("passes visitor cookie and portal-user filters to both list and count queries", async () => {
|
||||
const { loader } = await import("./portals.$portal/analytics.visitors.js");
|
||||
|
||||
await loader(args("https://app.example.test/app/acme/portals/docs/analytics/visitors?cookie=cookie-1&portalUserId=null&page=4&pageSize=5"));
|
||||
|
||||
const expectedWhere = { portalId: "portal-1", cookie: "cookie-1", portalUserId: null };
|
||||
expect(mocks.db.analyticsUniqueVisitor.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 5, skip: 15, where: expectedWhere }));
|
||||
expect(mocks.db.analyticsUniqueVisitor.count).toHaveBeenCalledWith({ where: expectedWhere });
|
||||
});
|
||||
});
|
||||
-133
@@ -1,133 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const appRoot = resolveRepoPath("apps/web/app");
|
||||
|
||||
const portalMutationHandlers = [
|
||||
"routes/app.$tenant/__portals/portals.new.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/danger.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/domains.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/index.tsx",
|
||||
"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.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",
|
||||
"routes/app.$tenant/__portals/portals.$portal/users/$userId.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.edit.$product.tsx",
|
||||
];
|
||||
|
||||
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.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.paymentProvider.tsx",
|
||||
];
|
||||
|
||||
const portalDomainHandlers = ["routes/app.$tenant/__portals/portals.$portal/domains.tsx"];
|
||||
|
||||
const portalReadLoaders = [
|
||||
"routes/app.$tenant/__portals/portals.tsx",
|
||||
"routes/app.$tenant/__portals/portals.new.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/analytics.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/analytics.events.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/analytics.page-views.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/analytics.visitors.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/danger.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/domains.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/index.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pages.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pages/$name.tsx",
|
||||
"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.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",
|
||||
"routes/app.$tenant/__portals/portals.$portal/users/$userId.tsx",
|
||||
];
|
||||
|
||||
function getActionSource(source: string) {
|
||||
const actionStart = source.search(/export\s+(const|let)\s+action/);
|
||||
if (actionStart < 0) {
|
||||
return "";
|
||||
}
|
||||
const defaultStart = source.indexOf("export default", actionStart);
|
||||
return source.slice(actionStart, defaultStart > actionStart ? defaultStart : undefined);
|
||||
}
|
||||
|
||||
describe("portal route authorization boundary", () => {
|
||||
test("requires portal read access before portal management loaders read data", () => {
|
||||
for (const relativePath of portalReadLoaders) {
|
||||
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
|
||||
const loaderStart = source.search(/export\s+(const|let)\s+loader/);
|
||||
const actionStart = source.search(/export\s+(const|let)\s+action/);
|
||||
const loaderSource = source.slice(loaderStart, actionStart > loaderStart ? actionStart : undefined);
|
||||
|
||||
expect(loaderSource, relativePath).toContain("await requirePortalReadAccess({ request, params, tenantId })");
|
||||
}
|
||||
});
|
||||
|
||||
test("requires tenant admin access and csrf before parsing mutating forms", () => {
|
||||
for (const relativePath of portalMutationHandlers) {
|
||||
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
|
||||
const actionSource = getActionSource(source);
|
||||
expect(actionSource.indexOf("await requirePortalMutationAccess({ request, params, tenantId })"), relativePath).toBeGreaterThanOrEqual(0);
|
||||
expect(actionSource.indexOf("await validateCSRFToken(request)"), relativePath).toBeGreaterThanOrEqual(0);
|
||||
expect(actionSource.indexOf("await requirePortalMutationAccess({ request, params, tenantId })"), relativePath).toBeLessThan(
|
||||
actionSource.indexOf("await request.formData()")
|
||||
);
|
||||
expect(actionSource.indexOf("await validateCSRFToken(request)"), relativePath).toBeLessThan(actionSource.indexOf("await request.formData()"));
|
||||
}
|
||||
});
|
||||
|
||||
test("requires mutation access before portal actions read portal records", () => {
|
||||
for (const relativePath of portalMutationHandlers) {
|
||||
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
|
||||
const actionSource = getActionSource(source);
|
||||
const portalReadIndex = actionSource.indexOf("await getPortalById(");
|
||||
if (portalReadIndex < 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
expect(actionSource.indexOf("await requirePortalMutationAccess({ request, params, tenantId })"), relativePath).toBeLessThan(portalReadIndex);
|
||||
}
|
||||
});
|
||||
|
||||
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");
|
||||
const actionStart = source.indexOf("action = async");
|
||||
const loaderSource = source.slice(loaderStart, actionStart > loaderStart ? actionStart : undefined);
|
||||
|
||||
expect(loaderSource, relativePath).not.toContain("await updatePortal");
|
||||
}
|
||||
});
|
||||
|
||||
test("requires portal feature gates before pricing and domain handlers read or mutate data", () => {
|
||||
for (const relativePath of portalPricingHandlers) {
|
||||
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
|
||||
expect(source, relativePath).toContain("requirePortalPricingEnabled");
|
||||
expect(source.indexOf("await requirePortalPricingEnabled({ request, tenantId })"), relativePath).toBeLessThan(source.indexOf("await request.formData()"));
|
||||
}
|
||||
|
||||
for (const relativePath of portalDomainHandlers) {
|
||||
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
|
||||
expect(source, relativePath).toContain("requirePortalDomainsEnabled");
|
||||
expect(source.indexOf("await requirePortalDomainsEnabled({ request, tenantId })"), relativePath).toBeLessThan(source.indexOf("await request.formData()"));
|
||||
}
|
||||
});
|
||||
});
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
describe("tenant portal loader performance guards", () => {
|
||||
it("loads portal visitor counts with one grouped query instead of one count per portal", () => {
|
||||
const source = readRepoFile("apps/web/app/routes/app.$tenant/__portals/portals.tsx");
|
||||
|
||||
expect(source).toContain("db.analyticsUniqueVisitor.groupBy");
|
||||
expect(source).toContain('by: ["portalId"]');
|
||||
expect(source).toContain("visitorsByPortalId");
|
||||
expect(source).not.toContain("visitors: await db.analyticsUniqueVisitor.count");
|
||||
});
|
||||
|
||||
it("loads portal overview counters in parallel", () => {
|
||||
const source = readRepoFile("apps/web/app/routes/app.$tenant/__portals/portals.$portal/index.tsx");
|
||||
const dataBlockIndex = source.indexOf("const data: LoaderData =");
|
||||
|
||||
expect(source).toContain("const [users, visitors, products] = await Promise.all");
|
||||
expect(source.indexOf("const [users, visitors, products] = await Promise.all")).toBeLessThan(dataBlockIndex);
|
||||
expect(dataBlockIndex).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("loads portal event analytics filters and table counts in parallel", () => {
|
||||
const source = readRepoFile("apps/web/app/routes/app.$tenant/__portals/portals.$portal/analytics.events.tsx");
|
||||
|
||||
expect(source).toContain("const [allActions, allCategories, allLabels, allValues, allUsers] = await Promise.all");
|
||||
expect(source).toContain("const [items, totalItems] = await Promise.all");
|
||||
expect(source).toContain("const PORTAL_ANALYTICS_FILTER_OPTION_LIMIT = 100");
|
||||
expect(source.match(/take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT/gu)).toHaveLength(5);
|
||||
expect(source).toContain('orderBy: { action: "asc" }');
|
||||
expect(source).toContain('orderBy: { email: "asc" }');
|
||||
});
|
||||
|
||||
it("loads portal page-view analytics filters and table counts in parallel", () => {
|
||||
const source = readRepoFile("apps/web/app/routes/app.$tenant/__portals/portals.$portal/analytics.page-views.tsx");
|
||||
|
||||
expect(source).toContain("const [allRoutes, allUsers] = await Promise.all");
|
||||
expect(source).toContain("const [items, totalItems] = await Promise.all");
|
||||
expect(source).toContain("const PORTAL_ANALYTICS_FILTER_OPTION_LIMIT = 100");
|
||||
expect(source.match(/take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT/gu)).toHaveLength(2);
|
||||
expect(source).toContain('orderBy: { route: "asc" }');
|
||||
expect(source).toContain('orderBy: { email: "asc" }');
|
||||
});
|
||||
|
||||
it("loads portal visitor analytics table counts in parallel", () => {
|
||||
const source = readRepoFile("apps/web/app/routes/app.$tenant/__portals/portals.$portal/analytics.visitors.tsx");
|
||||
|
||||
expect(source).toContain("const [items, totalItems] = await Promise.all");
|
||||
expect(source).toContain("const PORTAL_ANALYTICS_FILTER_OPTION_LIMIT = 100");
|
||||
expect(source).toContain("take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT");
|
||||
expect(source).toContain('orderBy: { email: "asc" }');
|
||||
});
|
||||
});
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
import type { Params } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { requireSuperUserOrAdmin } from "~/utils/loaders.middleware";
|
||||
|
||||
type PortalAccessInput = {
|
||||
request: Request;
|
||||
params: Params;
|
||||
tenantId: string | null;
|
||||
};
|
||||
|
||||
export async function requirePortalManagementAvailable({ request, tenantId }: Pick<PortalAccessInput, "request" | "tenantId">) {
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const portalsConfig = appConfiguration.portals;
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
if (!portalsConfig?.enabled) {
|
||||
throw Response.json({ error: t("models.portal.errors.disabled") }, { status: 400 });
|
||||
}
|
||||
|
||||
if (tenantId && !portalsConfig.forTenants) {
|
||||
throw Response.json({ error: t("models.portal.errors.tenantsDisabled") }, { status: 400 });
|
||||
}
|
||||
|
||||
return portalsConfig;
|
||||
}
|
||||
|
||||
export async function requirePortalPricingEnabled({ request, tenantId }: Pick<PortalAccessInput, "request" | "tenantId">) {
|
||||
const portalsConfig = await requirePortalManagementAvailable({ request, tenantId });
|
||||
if (!portalsConfig.pricing) {
|
||||
const { t } = await getTranslations(request);
|
||||
throw Response.json({ error: t("models.portal.errors.pricingDisabled") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function requirePortalDomainsEnabled({ request, tenantId }: Pick<PortalAccessInput, "request" | "tenantId">) {
|
||||
const portalsConfig = await requirePortalManagementAvailable({ request, tenantId });
|
||||
if (!portalsConfig.domains?.enabled) {
|
||||
const { t } = await getTranslations(request);
|
||||
throw Response.json({ error: t("models.portal.errors.domainsDisabled") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function requirePortalMutationAccess({
|
||||
request,
|
||||
params,
|
||||
tenantId,
|
||||
}: PortalAccessInput) {
|
||||
await requirePortalManagementAvailable({ request, tenantId });
|
||||
|
||||
if (tenantId) {
|
||||
await requireSuperUserOrAdmin({ request, params });
|
||||
}
|
||||
}
|
||||
|
||||
export const requirePortalReadAccess = requirePortalMutationAccess;
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const sourcePath = path.resolve(process.cwd(), "apps/web/app/routes/app.$tenant/__portals/portals.tsx");
|
||||
const configurationPath = path.resolve(process.cwd(), "apps/web/app/utils/db/appPortalConfiguration.db.server.ts");
|
||||
|
||||
describe("portal list i18n", () => {
|
||||
it("formats portal card counts through semantic translation keys", () => {
|
||||
const source = fs.readFileSync(sourcePath, "utf8");
|
||||
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("models.portal.counts.users");
|
||||
expect(source).toContain("models.portal.counts.plans");
|
||||
expect(source).toContain("models.portal.counts.visitors");
|
||||
expect(source).toContain("formatters.number(item._count.users)");
|
||||
expect(source).toContain("formatters.number(item._count.subscriptionProducts)");
|
||||
expect(source).toContain("formatters.number(item._count.visitors)");
|
||||
expect(source).not.toContain('"plan"');
|
||||
expect(source).not.toContain('"plans"');
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
});
|
||||
|
||||
it("keeps portal page configuration labels and validation errors translated", () => {
|
||||
const source = fs.readFileSync(configurationPath, "utf8");
|
||||
|
||||
expect(source).toContain("models.portal.seo");
|
||||
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 Payment provider account connected");
|
||||
expect(source).not.toContain("No privacy policy content");
|
||||
expect(source).not.toContain("No terms and conditions content");
|
||||
});
|
||||
});
|
||||
-136
@@ -1,136 +0,0 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { Outlet, redirect, useLoaderData, useParams } from "react-router";
|
||||
import type { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import CurrencyIcon from "~/components/ui/icons/CurrencyIcon";
|
||||
import SettingsIcon from "~/components/ui/icons/crm/SettingsIcon";
|
||||
import SettingsIconFilled from "~/components/ui/icons/crm/SettingsIconFilled";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import IconAnalytics from "~/components/layouts/icons/IconAnalytics";
|
||||
import WebsiteIcon from "~/components/ui/icons/WebsiteIcon";
|
||||
import WebsiteIconFilled from "~/components/ui/icons/WebsiteIconFilled";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import IconPages from "~/components/layouts/icons/IconPages";
|
||||
import ExclamationTriangleIcon from "~/components/ui/icons/ExclamationTriangleIcon";
|
||||
import UserGroupIconFilled from "~/components/ui/icons/UserGroupIconFilled";
|
||||
import UserGroupIcon from "~/components/ui/icons/UserGroupIcon";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { requirePortalReadAccess } from "./portalAccess.server";
|
||||
import { getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
portalSubdomain: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const config = appConfiguration.portals;
|
||||
if (!config?.enabled) {
|
||||
throw Response.json({ error: t("models.portal.errors.disabled") }, { status: 400 });
|
||||
}
|
||||
if (!config?.forTenants) {
|
||||
throw Response.json({ error: t("models.portal.errors.noAccess") }, { status: 403 });
|
||||
}
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
throw redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: t("models.portal.plural") }],
|
||||
portalSubdomain: portal.subdomain || params.portal || "",
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const rootData = useRootData();
|
||||
const portalsConfig = rootData.appConfiguration.portals;
|
||||
const portalPath = (path = "") => UrlUtils.getModulePath(params, `portals/${data.portalSubdomain}${path}`);
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
href: portalPath(),
|
||||
exact: true,
|
||||
icon: (
|
||||
<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: (
|
||||
<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>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: t("models.portal.pages.plural"),
|
||||
href: portalPath("/pages"),
|
||||
icon: <IconPages className=" text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <IconPages className=" text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
},
|
||||
{
|
||||
name: t("models.user.plural"),
|
||||
href: portalPath("/users"),
|
||||
icon: <UserGroupIcon className="h-5 w-5" />,
|
||||
iconSelected: <UserGroupIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("models.portal.analytics"),
|
||||
href: portalPath("/analytics"),
|
||||
icon: <IconAnalytics className="h-5 w-5" />,
|
||||
iconSelected: <IconAnalytics className="h-5 w-5" />,
|
||||
hidden: !portalsConfig?.analytics,
|
||||
},
|
||||
{
|
||||
name: t("models.portal.pricing.title"),
|
||||
href: portalPath("/pricing"),
|
||||
icon: <CurrencyIcon className=" text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <CurrencyIcon className=" text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
hidden: !portalsConfig?.pricing,
|
||||
},
|
||||
{
|
||||
name: t("models.domain.object"),
|
||||
href: portalPath("/domains"),
|
||||
icon: <WebsiteIcon className="h-5 w-5" />,
|
||||
iconSelected: <WebsiteIconFilled className="h-5 w-5" />,
|
||||
hidden: !portalsConfig?.domains?.enabled,
|
||||
},
|
||||
{
|
||||
name: t("shared.settings"),
|
||||
href: portalPath("/settings"),
|
||||
icon: <SettingsIcon className="h-5 w-5" />,
|
||||
iconSelected: <SettingsIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("shared.danger"),
|
||||
href: portalPath("/danger"),
|
||||
icon: <ExclamationTriangleIcon className=" text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
iconSelected: <ExclamationTriangleIcon className=" text-muted-foreground h-5 w-5 shrink-0" aria-hidden="true" />,
|
||||
bottom: true,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-382
@@ -1,382 +0,0 @@
|
||||
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";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requirePortalReadAccess } from "../portalAccess.server";
|
||||
import { redactAnalyticsCookie, redactAnalyticsUrl } from "~/modules/portals/utils/analytics-redaction";
|
||||
import { PortalTimestamp } from "~/modules/portals/components/PortalTimestamp";
|
||||
|
||||
const PORTAL_ANALYTICS_FILTER_OPTION_LIMIT = 100;
|
||||
|
||||
type LoaderData = {
|
||||
portal: Portal;
|
||||
items: (AnalyticsEvent & {
|
||||
uniqueVisitor: AnalyticsUniqueVisitor & {
|
||||
portalUser: { email: string } | null;
|
||||
};
|
||||
})[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
await verifyUserHasPermission(request, "app.dashboard.view", tenantId);
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
throw new Error(t("models.portal.errors.notFound"));
|
||||
}
|
||||
const [allActions, allCategories, allLabels, allValues, allUsers] = await Promise.all([
|
||||
db.analyticsEvent.groupBy({
|
||||
by: ["action"],
|
||||
where: {
|
||||
portalId: portal.id,
|
||||
},
|
||||
orderBy: { action: "asc" },
|
||||
take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT,
|
||||
}),
|
||||
db.analyticsEvent.groupBy({
|
||||
where: {
|
||||
portalId: portal.id,
|
||||
category: { not: null },
|
||||
},
|
||||
by: ["category"],
|
||||
orderBy: { category: "asc" },
|
||||
take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT,
|
||||
}),
|
||||
db.analyticsEvent.groupBy({
|
||||
where: {
|
||||
portalId: portal.id,
|
||||
label: { not: null },
|
||||
},
|
||||
by: ["label"],
|
||||
orderBy: { label: "asc" },
|
||||
take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT,
|
||||
}),
|
||||
db.analyticsEvent.groupBy({
|
||||
where: {
|
||||
portalId: portal.id,
|
||||
value: { not: null },
|
||||
},
|
||||
by: ["value"],
|
||||
orderBy: { value: "asc" },
|
||||
take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT,
|
||||
}),
|
||||
db.portalUser.findMany({
|
||||
where: { portalId: portal.id },
|
||||
select: { id: true, email: true },
|
||||
orderBy: { email: "asc" },
|
||||
take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT,
|
||||
}),
|
||||
]);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "action",
|
||||
title: t("analytics.action"),
|
||||
options: allActions.map((f) => {
|
||||
return { value: f.action, name: f.action };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "category",
|
||||
title: t("analytics.category"),
|
||||
options: allCategories.map((f) => {
|
||||
return { value: f.category ?? "", name: f.category ?? "" };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "label",
|
||||
title: t("analytics.label"),
|
||||
options: allLabels.map((f) => {
|
||||
return { value: f.label ?? "", name: f.label ?? "" };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: t("analytics.value"),
|
||||
options: allValues.map((f) => {
|
||||
return { value: f.value ?? "", name: f.value ?? "" };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "portalUserId",
|
||||
title: t("models.user.object"),
|
||||
options: allUsers.map((f) => {
|
||||
return { value: f.id, name: f.email };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: t("analytics.cookie"),
|
||||
manual: true,
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
let where: Prisma.AnalyticsEventWhereInput = {
|
||||
portalId: portal.id,
|
||||
};
|
||||
|
||||
const actionFilter = filters.properties.find((f) => f.name === "action");
|
||||
if (actionFilter?.value) {
|
||||
where = { ...where, action: actionFilter.value };
|
||||
}
|
||||
|
||||
const categoryFilter = filters.properties.find((f) => f.name === "category");
|
||||
if (categoryFilter?.value) {
|
||||
where = { ...where, category: categoryFilter.value };
|
||||
}
|
||||
const labelFilter = filters.properties.find((f) => f.name === "label");
|
||||
if (labelFilter?.value) {
|
||||
where = { ...where, label: labelFilter.value };
|
||||
}
|
||||
const valueFilter = filters.properties.find((f) => f.name === "value");
|
||||
if (valueFilter?.value) {
|
||||
where = { ...where, value: valueFilter.value };
|
||||
}
|
||||
|
||||
const cookieFilter = filters.properties.find((f) => f.name === "cookie");
|
||||
if (cookieFilter?.value) {
|
||||
where = { ...where, uniqueVisitor: { ...(where.uniqueVisitor as object | undefined), cookie: cookieFilter.value === "null" ? undefined : cookieFilter.value } };
|
||||
}
|
||||
|
||||
const portalUserFilter = filters.properties.find((f) => f.name === "portalUserId");
|
||||
if (portalUserFilter?.value) {
|
||||
where = { ...where, uniqueVisitor: { ...(where.uniqueVisitor as object | undefined), portalUserId: portalUserFilter.value === "null" ? null : portalUserFilter.value } };
|
||||
}
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(searchParams);
|
||||
const [items, totalItems] = await Promise.all([
|
||||
db.analyticsEvent.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
include: {
|
||||
uniqueVisitor: {
|
||||
include: {
|
||||
portalUser: { select: { email: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
}),
|
||||
db.analyticsEvent.count({
|
||||
where,
|
||||
}),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
portal,
|
||||
items: items.map((item) => ({
|
||||
...item,
|
||||
url: redactAnalyticsUrl(item.url),
|
||||
uniqueVisitor: {
|
||||
...item.uniqueVisitor,
|
||||
cookie: redactAnalyticsCookie(item.uniqueVisitor.cookie),
|
||||
httpReferrer: redactAnalyticsUrl(item.uniqueVisitor.httpReferrer),
|
||||
fromUrl: redactAnalyticsUrl(item.uniqueVisitor.fromUrl),
|
||||
},
|
||||
})),
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
title={t("analytics.events")}
|
||||
withHome={false}
|
||||
tabs={[
|
||||
{
|
||||
name: t("analytics.overview"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.uniqueVisitors"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/visitors`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.pageViews"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/page-views`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.events"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/events`),
|
||||
},
|
||||
]}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: t("analytics.date"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
{i.uniqueVisitor.portalUser ? (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (searchParams.get("portalUserId") || !i.uniqueVisitor.portalUserId) {
|
||||
searchParams.delete("portalUserId");
|
||||
} else {
|
||||
searchParams.set("portalUserId", i.uniqueVisitor.portalUserId);
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
disabled={!i.uniqueVisitor.portalUserId}
|
||||
className="underline"
|
||||
>
|
||||
<div className="text-xs">{i.uniqueVisitor.portalUser.email}</div>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
<span className="">{t("analytics.anonymous")}</span>: {i.uniqueVisitor.cookie}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<PortalTimestamp value={i.createdAt} className="text-muted-foreground text-xs" />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "action",
|
||||
title: t("analytics.action"),
|
||||
value: (i) => i.action,
|
||||
},
|
||||
{
|
||||
name: "category",
|
||||
title: t("analytics.category"),
|
||||
value: (i) => i.category,
|
||||
},
|
||||
{
|
||||
name: "label",
|
||||
title: t("analytics.label"),
|
||||
value: (i) => i.label,
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: t("analytics.value"),
|
||||
value: (i) => i.value,
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: t("analytics.url"),
|
||||
value: (i) => i.url,
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: t("analytics.cookie"),
|
||||
value: (i) => <div className="truncate">{i.uniqueVisitor.cookie}</div>,
|
||||
className: "max-w-xs",
|
||||
},
|
||||
{
|
||||
name: "httpReferrer",
|
||||
title: t("analytics.httpReferrer"),
|
||||
value: (i) => i.uniqueVisitor.httpReferrer,
|
||||
},
|
||||
{
|
||||
name: "browser",
|
||||
title: t("analytics.browser"),
|
||||
value: (i) => i.uniqueVisitor.browser,
|
||||
},
|
||||
{
|
||||
name: "os",
|
||||
title: t("analytics.os"),
|
||||
value: (i) => i.uniqueVisitor.os,
|
||||
},
|
||||
{
|
||||
name: "device",
|
||||
title: t("analytics.device"),
|
||||
value: (i) => i.uniqueVisitor.device,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: t("analytics.source"),
|
||||
value: (i) => i.uniqueVisitor.source,
|
||||
},
|
||||
{
|
||||
name: "medium",
|
||||
title: t("analytics.medium"),
|
||||
value: (i) => i.uniqueVisitor.medium,
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
title: t("analytics.campaign"),
|
||||
value: (i) => i.uniqueVisitor.campaign,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
title: t("analytics.content"),
|
||||
value: (i) => i.uniqueVisitor.content,
|
||||
},
|
||||
{
|
||||
name: "term",
|
||||
title: t("analytics.term"),
|
||||
value: (i) => i.uniqueVisitor.term,
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: t("analytics.country"),
|
||||
value: (i) => i.uniqueVisitor.country,
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: t("analytics.city"),
|
||||
value: (i) => i.uniqueVisitor.city,
|
||||
},
|
||||
{
|
||||
name: "fromUrl",
|
||||
title: t("analytics.fromUrl"),
|
||||
value: (i) => i.uniqueVisitor.fromUrl,
|
||||
},
|
||||
{
|
||||
name: "fromRoute",
|
||||
title: t("analytics.fromRoute"),
|
||||
value: (i) => i.uniqueVisitor.fromRoute,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-318
@@ -1,318 +0,0 @@
|
||||
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";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requirePortalReadAccess } from "../portalAccess.server";
|
||||
import { redactAnalyticsCookie, redactAnalyticsUrl } from "~/modules/portals/utils/analytics-redaction";
|
||||
import { PortalTimestamp } from "~/modules/portals/components/PortalTimestamp";
|
||||
|
||||
const PORTAL_ANALYTICS_FILTER_OPTION_LIMIT = 100;
|
||||
|
||||
type LoaderData = {
|
||||
portal: Portal;
|
||||
items: (AnalyticsPageView & {
|
||||
uniqueVisitor: AnalyticsUniqueVisitor & {
|
||||
portalUser: { email: string } | null;
|
||||
};
|
||||
})[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
await verifyUserHasPermission(request, "app.dashboard.view", tenantId);
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
throw new Error(t("models.portal.errors.notFound"));
|
||||
}
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
|
||||
const [allRoutes, allUsers] = await Promise.all([
|
||||
db.analyticsPageView.groupBy({
|
||||
where: { portalId: portal.id },
|
||||
by: ["route"],
|
||||
orderBy: { route: "asc" },
|
||||
take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT,
|
||||
}),
|
||||
db.portalUser.findMany({
|
||||
where: { portalId: portal.id },
|
||||
select: { id: true, email: true },
|
||||
orderBy: { email: "asc" },
|
||||
take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT,
|
||||
}),
|
||||
]);
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "route",
|
||||
title: t("analytics.route"),
|
||||
options: allRoutes.map((f) => {
|
||||
return { value: f.route ?? "", name: f.route ?? "" };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "portalUserId",
|
||||
title: t("models.user.object"),
|
||||
options: allUsers.map((f) => {
|
||||
return { value: f.id, name: f.email };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: t("analytics.cookie"),
|
||||
manual: true,
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
let where: Prisma.AnalyticsPageViewWhereInput = {
|
||||
portalId: portal.id,
|
||||
};
|
||||
|
||||
const routeFilter = filters.properties.find((f) => f.name === "route");
|
||||
if (routeFilter?.value) {
|
||||
where = { ...where, route: routeFilter.value === "null" ? null : routeFilter.value };
|
||||
}
|
||||
|
||||
const cookieFilter = filters.properties.find((f) => f.name === "cookie");
|
||||
if (cookieFilter?.value) {
|
||||
where = { ...where, uniqueVisitor: { ...(where.uniqueVisitor as object | undefined), cookie: cookieFilter.value === "null" ? undefined : cookieFilter.value } };
|
||||
}
|
||||
|
||||
const portalUserFilter = filters.properties.find((f) => f.name === "portalUserId");
|
||||
if (portalUserFilter?.value) {
|
||||
where = { ...where, uniqueVisitor: { ...(where.uniqueVisitor as object | undefined), portalUserId: portalUserFilter.value === "null" ? null : portalUserFilter.value } };
|
||||
}
|
||||
const [items, totalItems] = await Promise.all([
|
||||
db.analyticsPageView.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
include: {
|
||||
uniqueVisitor: {
|
||||
include: {
|
||||
user: {
|
||||
select: { email: true },
|
||||
},
|
||||
portalUser: {
|
||||
select: { email: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
}),
|
||||
db.analyticsPageView.count({
|
||||
where,
|
||||
}),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
portal,
|
||||
items: items.map((item) => ({
|
||||
...item,
|
||||
url: redactAnalyticsUrl(item.url) ?? item.url,
|
||||
uniqueVisitor: {
|
||||
...item.uniqueVisitor,
|
||||
cookie: redactAnalyticsCookie(item.uniqueVisitor.cookie),
|
||||
httpReferrer: redactAnalyticsUrl(item.uniqueVisitor.httpReferrer),
|
||||
fromUrl: redactAnalyticsUrl(item.uniqueVisitor.fromUrl),
|
||||
},
|
||||
})),
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
withHome={false}
|
||||
tabs={[
|
||||
{
|
||||
name: t("analytics.overview"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.uniqueVisitors"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/visitors`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.pageViews"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/page-views`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.events"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/events`),
|
||||
},
|
||||
]}
|
||||
title={t("analytics.pageViews")}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: t("analytics.date"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
{i.uniqueVisitor.portalUser ? (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (searchParams.get("portalUserId") || !i.uniqueVisitor.portalUserId) {
|
||||
searchParams.delete("portalUserId");
|
||||
} else {
|
||||
searchParams.set("portalUserId", i.uniqueVisitor.portalUserId);
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
disabled={!i.uniqueVisitor.portalUserId}
|
||||
className="underline"
|
||||
>
|
||||
<div className="text-xs">{i.uniqueVisitor.portalUser.email}</div>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
<span className="">{t("analytics.anonymous")}</span>: {i.uniqueVisitor.cookie}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<PortalTimestamp value={i.createdAt} className="text-muted-foreground text-xs" />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: t("analytics.url"),
|
||||
value: (i) => (
|
||||
<div className="max-w-xs truncate">
|
||||
<div className="truncate font-medium">{i.url}</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
searchParams.set("route", i.route ?? "null");
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
className="truncate underline"
|
||||
>
|
||||
<div className="text-muted-foreground text-xs">{i.url !== i.route && i.route}</div>
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "httpReferrer",
|
||||
title: t("analytics.httpReferrer"),
|
||||
value: (i) => <div className="max-w-xs truncate">{i.uniqueVisitor.httpReferrer}</div>,
|
||||
},
|
||||
{
|
||||
name: "via",
|
||||
title: t("analytics.via"),
|
||||
value: (i) => i.uniqueVisitor.via,
|
||||
},
|
||||
{
|
||||
name: "browser",
|
||||
title: t("analytics.browser"),
|
||||
value: (i) => i.uniqueVisitor.browser,
|
||||
},
|
||||
{
|
||||
name: "os",
|
||||
title: t("analytics.os"),
|
||||
value: (i) => i.uniqueVisitor.os,
|
||||
},
|
||||
{
|
||||
name: "device",
|
||||
title: t("analytics.device"),
|
||||
value: (i) => i.uniqueVisitor.device,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: t("analytics.source"),
|
||||
value: (i) => i.uniqueVisitor.source,
|
||||
},
|
||||
{
|
||||
name: "medium",
|
||||
title: t("analytics.medium"),
|
||||
value: (i) => i.uniqueVisitor.medium,
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
title: t("analytics.campaign"),
|
||||
value: (i) => i.uniqueVisitor.campaign,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
title: t("analytics.content"),
|
||||
value: (i) => i.uniqueVisitor.content,
|
||||
},
|
||||
{
|
||||
name: "term",
|
||||
title: t("analytics.term"),
|
||||
value: (i) => i.uniqueVisitor.term,
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: t("analytics.country"),
|
||||
value: (i) => i.uniqueVisitor.country,
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: t("analytics.city"),
|
||||
value: (i) => i.uniqueVisitor.city,
|
||||
},
|
||||
{
|
||||
name: "fromUrl",
|
||||
title: t("analytics.fromUrl"),
|
||||
value: (i) => (
|
||||
<div className="max-w-xs truncate">
|
||||
<div className="truncate font-medium">{i.uniqueVisitor.fromUrl}</div>
|
||||
<div className="text-muted-foreground text-xs">{i.uniqueVisitor.fromUrl !== i.uniqueVisitor.fromRoute && i.uniqueVisitor.fromRoute}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/app.$tenant/__portals/portals.$portal/analytics.tsx";
|
||||
const overviewRoutePath = "apps/web/app/routes/app.$tenant/__portals/portals.$portal/index.tsx";
|
||||
const timestampRoutePaths = [
|
||||
"apps/web/app/routes/app.$tenant/__portals/portals.$portal/analytics.events.tsx",
|
||||
"apps/web/app/routes/app.$tenant/__portals/portals.$portal/analytics.page-views.tsx",
|
||||
"apps/web/app/routes/app.$tenant/__portals/portals.$portal/analytics.visitors.tsx",
|
||||
"apps/web/app/routes/app.$tenant/__portals/portals.$portal/users.tsx",
|
||||
];
|
||||
|
||||
function readRoute() {
|
||||
return readRepoFile(routePath);
|
||||
}
|
||||
|
||||
describe("portal analytics overview route DB boundary", () => {
|
||||
it("uses the package analytics overview helper", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@hivegrid/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsOverview");
|
||||
expect(source).toContain("withUsers: false");
|
||||
expect(source).toContain("portalId: item.id");
|
||||
expect(source).toContain("getTranslations(request)");
|
||||
expect(source).toContain("locale,");
|
||||
});
|
||||
|
||||
it("validates the period before calling the package helper", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("PeriodHelper.getPeriodFromRequest({ request })");
|
||||
expect(source).toContain("isAnalyticsPeriod(period) ? period : defaultAnalyticsPeriod");
|
||||
});
|
||||
|
||||
it("does not import the legacy AnalyticsService", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).not.toContain("~/utils/helpers/.server/AnalyticsService");
|
||||
});
|
||||
|
||||
it("uses the shared portal timestamp component for visible portal dates", () => {
|
||||
const source = timestampRoutePaths.map((timestampRoutePath) => readRepoFile(timestampRoutePath)).join("\n");
|
||||
|
||||
expect(source).toContain("PortalTimestamp");
|
||||
expect(source).not.toContain("~/utils/shared/DateUtils");
|
||||
expect(source).not.toContain("DateUtils.");
|
||||
});
|
||||
|
||||
it("formats visible portal overview counts through locale helpers", () => {
|
||||
const source = readRepoFile(overviewRoutePath);
|
||||
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.number");
|
||||
expect(source).toContain("models.subscriptionProduct.plural");
|
||||
expect(source).not.toContain('from "~/utils/shared/NumberUtils"');
|
||||
expect(source).not.toContain("NumberUtils.");
|
||||
});
|
||||
});
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData, useSearchParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { PortalWithDetails, getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
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 "@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";
|
||||
import ExternalLinkEmptyIcon from "~/components/ui/icons/ExternalLinkEmptyIcon";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { requirePortalReadAccess } from "../portalAccess.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails & { portalUrl?: string };
|
||||
overview: AnalyticsOverviewDto;
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (!appConfiguration.portals?.analytics) {
|
||||
throw Response.json({ error: t("models.portal.errors.analyticsDisabled") }, { status: 400 });
|
||||
}
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const item: (PortalWithDetails & { portalUrl?: string }) | null = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
item.portalUrl = PortalServer.getPortalUrl(item);
|
||||
const period = PeriodHelper.getPeriodFromRequest({ request });
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
overview: await getAnalyticsOverview({
|
||||
withUsers: false,
|
||||
period: isAnalyticsPeriod(period) ? period : defaultAnalyticsPeriod,
|
||||
portalId: item.id,
|
||||
locale,
|
||||
}),
|
||||
};
|
||||
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("analytics.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: "Domain",
|
||||
// },
|
||||
// ]}
|
||||
buttons={
|
||||
<>
|
||||
<InputSelect
|
||||
className="w-44"
|
||||
name="period"
|
||||
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
|
||||
options={PeriodFilters.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: t(f.name),
|
||||
};
|
||||
})}
|
||||
setValue={(value) => {
|
||||
if (value && value !== defaultPeriodFilter) {
|
||||
searchParams.set("period", value?.toString() ?? "");
|
||||
} else {
|
||||
searchParams.delete("period");
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
/>
|
||||
{data.item.portalUrl && (
|
||||
<ButtonPrimary to={data.item.portalUrl} target="_blank" disabled={!data.item.isPublished}>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ExternalLinkEmptyIcon className="h-4 w-4" />
|
||||
</div>
|
||||
</ButtonPrimary>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-2 pb-10">
|
||||
<AnalyticsOverview overview={data.overview} withUsers={false} />
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-280
@@ -1,280 +0,0 @@
|
||||
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";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requirePortalReadAccess } from "../portalAccess.server";
|
||||
import { redactAnalyticsCookie, redactAnalyticsUrl } from "~/modules/portals/utils/analytics-redaction";
|
||||
import { PortalTimestamp } from "~/modules/portals/components/PortalTimestamp";
|
||||
|
||||
const PORTAL_ANALYTICS_FILTER_OPTION_LIMIT = 100;
|
||||
|
||||
type LoaderData = {
|
||||
portal: Portal;
|
||||
items: (AnalyticsUniqueVisitor & {
|
||||
portalUser: { email: string } | null;
|
||||
_count: {
|
||||
pageViews: number;
|
||||
events: number;
|
||||
};
|
||||
})[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
|
||||
export const loader: LoaderFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
await verifyUserHasPermission(request, "app.dashboard.view", tenantId);
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
throw new Error(t("models.portal.errors.notFound"));
|
||||
}
|
||||
const allUsers = await db.portalUser.findMany({
|
||||
where: { portalId: portal.id },
|
||||
select: { id: true, email: true },
|
||||
orderBy: { email: "asc" },
|
||||
take: PORTAL_ANALYTICS_FILTER_OPTION_LIMIT,
|
||||
});
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "portalUserId",
|
||||
title: t("models.user.object"),
|
||||
options: allUsers.map((f) => {
|
||||
return { value: f.id, name: f.email };
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: t("analytics.cookie"),
|
||||
manual: true,
|
||||
},
|
||||
];
|
||||
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
let where: Prisma.AnalyticsUniqueVisitorWhereInput = {
|
||||
portalId: portal.id,
|
||||
};
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
|
||||
const cookieFilter = filters.properties.find((f) => f.name === "cookie");
|
||||
if (cookieFilter?.value) {
|
||||
where = { ...where, cookie: cookieFilter.value };
|
||||
}
|
||||
|
||||
const portalUserFilter = filters.properties.find((f) => f.name === "portalUserId");
|
||||
if (portalUserFilter?.value) {
|
||||
where = { ...where, portalUserId: portalUserFilter.value === "null" ? null : portalUserFilter.value };
|
||||
}
|
||||
|
||||
const [items, totalItems] = await Promise.all([
|
||||
db.analyticsUniqueVisitor.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
include: {
|
||||
portalUser: { select: { email: true } },
|
||||
_count: {
|
||||
select: {
|
||||
pageViews: true,
|
||||
events: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
}),
|
||||
db.analyticsUniqueVisitor.count({
|
||||
where,
|
||||
}),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
portal,
|
||||
items: items.map((item) => ({
|
||||
...item,
|
||||
cookie: redactAnalyticsCookie(item.cookie),
|
||||
httpReferrer: redactAnalyticsUrl(item.httpReferrer),
|
||||
fromUrl: redactAnalyticsUrl(item.fromUrl),
|
||||
})),
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
title={t("analytics.uniqueVisitors")}
|
||||
withHome={false}
|
||||
tabs={[
|
||||
{
|
||||
name: t("analytics.overview"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.uniqueVisitors"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/visitors`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.pageViews"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/page-views`),
|
||||
},
|
||||
{
|
||||
name: t("analytics.events"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/analytics/events`),
|
||||
},
|
||||
]}
|
||||
buttons={
|
||||
<>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: t("analytics.date"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
{i.portalUser ? (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (searchParams.get("portalUserId") || !i.portalUserId) {
|
||||
searchParams.delete("portalUserId");
|
||||
} else {
|
||||
searchParams.set("portalUserId", i.portalUserId);
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
className="underline"
|
||||
>
|
||||
<div className="text-xs">{i.portalUser.email}</div>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
<span className="">{t("analytics.anonymous")}</span>: {i.cookie}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<PortalTimestamp value={i.createdAt} className="text-muted-foreground text-xs" />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "httpReferrer",
|
||||
title: t("analytics.httpReferrer"),
|
||||
value: (i) => i.httpReferrer,
|
||||
},
|
||||
{
|
||||
name: "via",
|
||||
title: t("analytics.via"),
|
||||
value: (i) => i.via,
|
||||
},
|
||||
{
|
||||
name: "browser",
|
||||
title: t("analytics.browser"),
|
||||
value: (i) => i.browser,
|
||||
},
|
||||
{
|
||||
name: "os",
|
||||
title: t("analytics.os"),
|
||||
value: (i) => i.os,
|
||||
},
|
||||
{
|
||||
name: "device",
|
||||
title: t("analytics.device"),
|
||||
value: (i) => i.device,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: t("analytics.source"),
|
||||
value: (i) => i.source,
|
||||
},
|
||||
{
|
||||
name: "medium",
|
||||
title: t("analytics.medium"),
|
||||
value: (i) => i.medium,
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
title: t("analytics.campaign"),
|
||||
value: (i) => i.campaign,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
title: t("analytics.content"),
|
||||
value: (i) => i.content,
|
||||
},
|
||||
{
|
||||
name: "term",
|
||||
title: t("analytics.term"),
|
||||
value: (i) => i.term,
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: t("analytics.country"),
|
||||
value: (i) => i.country,
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: t("analytics.city"),
|
||||
value: (i) => i.city,
|
||||
},
|
||||
{
|
||||
name: "fromUrl",
|
||||
title: t("analytics.fromUrl"),
|
||||
value: (i) => i.fromUrl,
|
||||
},
|
||||
{
|
||||
name: "fromRoute",
|
||||
title: t("analytics.fromRoute"),
|
||||
value: (i) => i.fromRoute,
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: t("analytics.cookie"),
|
||||
value: (i) => i.cookie,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-142
@@ -1,142 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useParams, useSubmit } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "react-hot-toast";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPortalUsers } from "~/modules/portals/db/portalUsers.db.server";
|
||||
import { PortalWithDetails, deletePortal, getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import { getAllPortalSubscriptionProducts } from "~/modules/portals/db/portalSubscriptionProducts.db.server";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails & { portalUrl?: string };
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const item: (PortalWithDetails & { portalUrl?: string }) | null = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
item.portalUrl = PortalServer.getPortalUrl(item);
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "delete") {
|
||||
const users = await getPortalUsers(item.id);
|
||||
const products = await getAllPortalSubscriptionProducts(item.id);
|
||||
if (users.length > 0) {
|
||||
return Response.json({ error: t("models.portal.errors.cannotDeleteWithUsers") }, { status: 400 });
|
||||
}
|
||||
if (products.length > 0) {
|
||||
return Response.json({ error: t("models.portal.errors.cannotDeleteWithProducts") }, { status: 400 });
|
||||
}
|
||||
await deletePortal({ id: item.id, tenantId });
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
const submit = useSubmit();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const [typeToConfirm, setTypeToConfirm] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
const textToType = `${t("shared.delete")} ${data.item.subdomain}`;
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("shared.danger")}
|
||||
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("shared.settings"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="pb-10">
|
||||
<SettingSection title={t("shared.dangerZone")} description={t("shared.warningCannotUndo")}>
|
||||
<div className="mt-12 space-y-2 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<InputText title={t("models.portal.danger.confirmType", { value0: textToType })} value={typeToConfirm} setValue={setTypeToConfirm} />
|
||||
</div>
|
||||
<div>
|
||||
<ButtonPrimary disabled={typeToConfirm !== textToType} destructive={true} onClick={onDelete}>
|
||||
{t("shared.delete")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-332
@@ -1,332 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, Link, useNavigation, useParams, useSubmit } from "react-router";
|
||||
import { Fragment, useEffect, useId, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "react-hot-toast";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { PortalWithDetails, getPortalByDomain, getPortalById, updatePortal } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import DomainsServer from "~/modules/domains/services/Domains.server";
|
||||
import { GetCertDto } from "~/modules/domains/dtos/GetCertDto";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import clsx from "clsx";
|
||||
import ClipboardIcon from "~/components/ui/icons/ClipboardIcon";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SuccessBanner from "~/components/ui/banners/SuccessBanner";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { requirePortalDomainsEnabled, requirePortalMutationAccess, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails;
|
||||
certificate: GetCertDto | null;
|
||||
portalUrl: string;
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalDomainsEnabled({ request, tenantId });
|
||||
await DomainsServer.getConfig({ request }).catch((e) => {
|
||||
throw Response.json({ error: e.message }, { status: 400 });
|
||||
});
|
||||
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const certificate = await DomainsServer.getCert({ hostname: item.domain, request });
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
certificate,
|
||||
portalUrl: PortalServer.getPortalUrl(item),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalDomainsEnabled({ request, tenantId });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "edit") {
|
||||
let domain = form.get("domain")?.toString().toLowerCase().trim().replace("http://", "").replace("https://", "");
|
||||
if (domain) {
|
||||
const existingDomain = domain ? await getPortalByDomain(domain) : null;
|
||||
if (existingDomain) {
|
||||
return Response.json({ error: t("models.portal.errors.domainTaken") }, { status: 400 });
|
||||
}
|
||||
await DomainsServer.addCert({ hostname: domain, request });
|
||||
}
|
||||
|
||||
await updatePortal(item, {
|
||||
domain,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
} else if (action === "check") {
|
||||
const certificate = await DomainsServer.getCert({ hostname: item.domain, request });
|
||||
if (certificate?.configured) {
|
||||
return Response.json({ success: t("models.domain.verified.title") });
|
||||
} else {
|
||||
return Response.json({ error: t("models.domain.notVerified.title") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
await DomainsServer.delCert({ hostname: item.domain!, request });
|
||||
await updatePortal(item, {
|
||||
domain: null,
|
||||
});
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete() {
|
||||
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", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
function onCheck() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "check");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.domain.object")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: data.item.title,
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.item.subdomain}`),
|
||||
},
|
||||
{
|
||||
title: t("models.domain.object"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<SettingSection title={t("models.domain.custom")} size="lg">
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="edit" readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<InputText
|
||||
name="domain"
|
||||
title={t("models.domain.object")}
|
||||
defaultValue={data.item.domain ?? ""}
|
||||
disabled={!!data.item.domain}
|
||||
placeholder={t("models.domain.placeholder")}
|
||||
readOnly={navigation.state !== "idle"}
|
||||
hint={
|
||||
<div>
|
||||
{data.portalUrl && data.item.domain && (
|
||||
<Link to={data.item.domain} target="_blank" className="underline">
|
||||
{data.item.domain}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<div className="border-border mt-3 border-t pt-3">
|
||||
<div className="flex justify-end">
|
||||
<div>
|
||||
{!data.item.domain && <LoadingButton type="submit">{t("shared.save")}</LoadingButton>}
|
||||
{data.item.domain && (
|
||||
<ButtonPrimary onClick={onDelete} destructive>
|
||||
{t("shared.remove")}
|
||||
</ButtonPrimary>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
{data.certificate?.records && (
|
||||
<Fragment>
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection
|
||||
title={
|
||||
<div className="flex items-center space-x-2 truncate">
|
||||
<ColorBadge color={data.certificate.configured ? Colors.GREEN : Colors.YELLOW} />
|
||||
<div className="truncate">{t("models.domain.verification.title")}</div>
|
||||
</div>
|
||||
}
|
||||
size="lg"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<div className="text-muted-foreground text-sm">{t("models.domain.verification.description")}</div>
|
||||
{data.certificate.records.A && (
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<div className="w-full sm:w-1/2">
|
||||
<RecordInput title={t("models.domain.recordName")} type="A" value={data.certificate.records.A.name} />
|
||||
</div>
|
||||
<div className="px-2 font-medium sm:pt-5" aria-hidden="true">
|
||||
→
|
||||
</div>
|
||||
<div className="w-full sm:w-1/2">
|
||||
<RecordInput title={t("models.domain.recordValue")} value={data.certificate.records.A.value} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{data.certificate.records.AAAA && (
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<div className="w-full sm:w-1/2">
|
||||
<RecordInput title={t("models.domain.recordName")} type="AAAA" value={data.certificate.records.AAAA.name} />
|
||||
</div>
|
||||
<div className="px-2 font-medium sm:pt-5" aria-hidden="true">
|
||||
→
|
||||
</div>
|
||||
<div className="w-full sm:w-1/2">
|
||||
<RecordInput title={t("models.domain.recordValue")} value={data.certificate.records.AAAA.value} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{data.certificate.records.CNAME && (
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<div className="w-full sm:w-1/2">
|
||||
<RecordInput title={t("models.domain.recordName")} type="CNAME" value={data.certificate.records.CNAME.name} />
|
||||
</div>
|
||||
<div className="px-2 font-medium sm:pt-5" aria-hidden="true">
|
||||
→
|
||||
</div>
|
||||
<div className="w-full sm:w-1/2">
|
||||
<RecordInput title={t("models.domain.recordValue")} value={data.certificate.records.CNAME.value} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!data.certificate.configured ? (
|
||||
<div className="border-border mt-3 space-y-2 border-t pt-3">
|
||||
<WarningBanner title={t("models.domain.notVerified.title")}>
|
||||
<ButtonSecondary onClick={onCheck}>{t("models.domain.notVerified.description")}</ButtonSecondary>
|
||||
</WarningBanner>
|
||||
<div className="flex justify-end">
|
||||
<ButtonSecondary onClick={onCheck}>{t("models.domain.notVerified.cta")}</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<SuccessBanner title={t("models.domain.verified.title")}>
|
||||
<div>{t("models.domain.verified.description")}</div>
|
||||
<Link to={data.portalUrl} target="_blank" className="underline">
|
||||
{t("models.domain.verified.cta")}
|
||||
</Link>
|
||||
</SuccessBanner>
|
||||
)}
|
||||
</div>
|
||||
</SettingSection>
|
||||
</Fragment>
|
||||
)}
|
||||
|
||||
{/* <div>{JSON.stringify(data.certificate)}</div> */}
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function RecordInput({ title, type, value }: { title: string; type?: string; value: string }) {
|
||||
const { t } = useTranslation();
|
||||
const inputId = useId();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<label htmlFor={inputId} className="text-foreground text-xs font-medium">
|
||||
{title}
|
||||
</label>
|
||||
<div className="border-border mt-1 flex overflow-hidden rounded-md border">
|
||||
<div className="relative flex grow items-stretch focus-within:z-10">
|
||||
{type && (
|
||||
<div className="text-muted-foreground bg-secondary/90 absolute inset-y-0 left-0 flex w-16 items-center justify-center border-r pr-4 pl-3 text-xs font-medium">
|
||||
{type}
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
id={inputId}
|
||||
className={clsx("text-foreground block w-full rounded-none rounded-l-md border-0 py-2 text-xs focus:outline-hidden", type && "pl-20")}
|
||||
value={value}
|
||||
readOnly
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("shared.copyToClipboard")}
|
||||
className="border-border text-foreground bg-background relative -ml-px inline-flex min-h-10 min-w-10 items-center justify-center gap-x-1.5 rounded-r-md border-l px-3 py-2 text-sm font-semibold"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(value);
|
||||
toast.success(t("shared.copied"));
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true">
|
||||
<ClipboardIcon className="h-4 w-4" />
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-194
@@ -1,194 +0,0 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData } from "react-router";
|
||||
import { Link, useLoaderData, useParams, useSubmit } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ExternalLinkEmptyIcon from "~/components/ui/icons/ExternalLinkEmptyIcon";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPortalById, PortalWithDetails, updatePortal } from "~/modules/portals/db/portals.db.server";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import GearIcon from "~/components/ui/icons/GearIcon";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "../portalAccess.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
item: PortalWithDetails & { portalUrl?: string };
|
||||
overview: {
|
||||
users: number;
|
||||
visitors: number;
|
||||
products: number;
|
||||
};
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const item: (PortalWithDetails & { portalUrl?: string }) | null = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
throw redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
item.portalUrl = PortalServer.getPortalUrl(item);
|
||||
const [users, visitors, products] = await Promise.all([
|
||||
db.portalUser.count({ where: { portalId: item.id } }),
|
||||
db.analyticsUniqueVisitor.count({ where: { portalId: item.id } }),
|
||||
db.portalSubscriptionProduct.count({ where: { portalId: item.id } }),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: `${item.title} | ${t("models.portal.object")}` }],
|
||||
item,
|
||||
overview: {
|
||||
users,
|
||||
visitors,
|
||||
products,
|
||||
},
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = { success?: string; error?: string };
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
if (action === "toggle-published") {
|
||||
await updatePortal(item, {
|
||||
isPublished: !item.isPublished,
|
||||
});
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
const rootData = useRootData();
|
||||
const portalsConfig = rootData.appConfiguration.portals;
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
title={
|
||||
<div className="flex items-baseline space-x-2">
|
||||
<div>{data.item.title} </div>
|
||||
<SimpleBadge
|
||||
title={data.item.isPublished ? t("shared.published") : t("shared.unpublished")}
|
||||
color={data.item.isPublished ? Colors.GREEN : Colors.GRAY}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
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("shared.overview"),
|
||||
},
|
||||
]}
|
||||
buttons={
|
||||
<>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonSecondary to="settings">
|
||||
<GearIcon className="h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
<ButtonSecondary
|
||||
onClick={() => {
|
||||
const form = new FormData();
|
||||
form.set("action", "toggle-published");
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}}
|
||||
>
|
||||
{data.item.isPublished ? t("shared.unpublish") : t("shared.publish")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
{data.item.portalUrl && (
|
||||
<ButtonPrimary to={data.item.portalUrl} target="_blank" disabled={!data.item.isPublished}>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ExternalLinkEmptyIcon className="h-4 w-4" />
|
||||
{/* <div>{t("shared.preview")}</div> */}
|
||||
</div>
|
||||
</ButtonPrimary>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<dl className="grid gap-2 sm:grid-cols-3">
|
||||
<Link to="users" className="group">
|
||||
<div className="bg-background border-border group rounded-lg border p-4">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase group-hover:underline">{t("models.user.plural")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">
|
||||
{formatters.number(data.overview.users, { maximumFractionDigits: 0 })}
|
||||
</dd>
|
||||
</div>
|
||||
</Link>
|
||||
{portalsConfig?.analytics && (
|
||||
<Link to="analytics" className="group">
|
||||
<div className="bg-background border-border group rounded-lg border p-4">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase group-hover:underline">{t("analytics.visitors")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">
|
||||
{formatters.number(data.overview.visitors, { maximumFractionDigits: 0 })}
|
||||
</dd>
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{portalsConfig?.pricing && (
|
||||
<Link to="pricing" className="group">
|
||||
<div className="bg-background border-border group rounded-lg border p-4">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase group-hover:underline">{t("models.subscriptionProduct.plural")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">
|
||||
{formatters.number(data.overview.products, { maximumFractionDigits: 0 })}
|
||||
</dd>
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
</dl>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
-197
@@ -1,197 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Link, useNavigate, useOutlet, useParams } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "react-hot-toast";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { PortalWithDetails, getPortalById, updatePortal } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { getPortalPages } from "~/modules/portals/db/portalPages.db.server";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { ExternalLinkIcon } from "~/components/ui/icons/vendor";
|
||||
import ExternalLinkEmptyIcon from "~/components/ui/icons/ExternalLinkEmptyIcon";
|
||||
import clsx from "clsx";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
portal: PortalWithDetails;
|
||||
pages: {
|
||||
name: string;
|
||||
title: string;
|
||||
attributes: JsonPropertiesValuesDto | null;
|
||||
errors: string[];
|
||||
slug: string;
|
||||
href: string;
|
||||
}[];
|
||||
portalUrl: string;
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const allPages = await getPortalPages(portal.id);
|
||||
const portalUrl = PortalServer.getPortalUrl(portal);
|
||||
const pages = appConfiguration.portals.pages.map((page) => {
|
||||
const existing = allPages.find((p) => p.name === page.name);
|
||||
const attributes = existing ? (existing.attributes as JsonPropertiesValuesDto) : null;
|
||||
return {
|
||||
name: page.name,
|
||||
title: page.title,
|
||||
attributes,
|
||||
errors: page.errors ? page.errors({ portal, page: attributes ? { attributes } : null }) : [],
|
||||
slug: page.slug,
|
||||
href: `${portalUrl}${page.slug}`,
|
||||
};
|
||||
});
|
||||
const data: LoaderData = {
|
||||
portal,
|
||||
pages,
|
||||
portalUrl,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "edit") {
|
||||
const seoTitle = form.get("seoTitle")?.toString();
|
||||
const seoDescription = form.get("seoDescription")?.toString();
|
||||
const seoImage = form.get("seoImage")?.toString();
|
||||
const paymentProviderAccountId = form.get("paymentProviderAccountId")?.toString();
|
||||
|
||||
await updatePortal(item, {
|
||||
seoTitle: seoTitle || null,
|
||||
seoDescription: seoDescription || null,
|
||||
seoImage: seoImage || null,
|
||||
paymentProviderAccountId: paymentProviderAccountId || null,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
const selectedPage = data.pages.find((p) => p.name === params.name);
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.portal.pages.plural")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: data.portal.title,
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}`),
|
||||
},
|
||||
{
|
||||
title: t("models.portal.pages.plural"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
{data.pages.map((page) => {
|
||||
return (
|
||||
<div
|
||||
key={page.name}
|
||||
className={clsx(
|
||||
"border-border hover:border-primary group relative flex flex-col rounded-lg border hover:shadow-2xs",
|
||||
page.errors.length === 0 ? "bg-background" : "bg-red-50"
|
||||
)}
|
||||
>
|
||||
<Link to={page.name}>
|
||||
{page.href && (
|
||||
<div>
|
||||
<Link
|
||||
to={page.href}
|
||||
target="_blank"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-secondary/80 text-muted-foreground hover:text-secondary-foreground hover:bg-secondary absolute right-3 top-4 hidden rounded-md p-1.5 group-hover:flex"
|
||||
>
|
||||
<ExternalLinkEmptyIcon className="h-4 w-4" />
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
<div className="p-4">
|
||||
<div className="flex flex-col">
|
||||
<div className="font-medium">{page.title}</div>
|
||||
{/* <div className="text-muted-foreground text-sm">{page.slug}</div> */}
|
||||
{page.errors.length > 0 && <div className="line-clamp-2 text-sm text-red-500">{page.errors.join(", ")}</div>}
|
||||
{/* <div className="text-muted-foreground text-sm">{JSON.stringify(page.attributes)}</div> */}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
title={selectedPage?.title ?? t("models.portal.pages.object")}
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
withClose={false}
|
||||
className="sm:max-w-xl"
|
||||
overflowYScroll={true}
|
||||
buttons={
|
||||
<>
|
||||
{selectedPage && (
|
||||
<div>
|
||||
<ButtonSecondary to={data.portalUrl + selectedPage.slug} target="_blank">
|
||||
<ExternalLinkIcon className="h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-194
@@ -1,194 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation, useParams, useSubmit } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { toast } from "sonner";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
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 "@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";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "../../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
portal: Portal;
|
||||
pageConfig: PortalPageConfigDto;
|
||||
page: PortalPage | null;
|
||||
portalUrl: string;
|
||||
};
|
||||
|
||||
function portalSegment(portal: Pick<Portal, "subdomain">, params: { portal?: string }) {
|
||||
return portal.subdomain || params.portal || "";
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const page = await getPortalPagesByName(portal.id, params.name!);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const pageConfig = appConfiguration.portals.pages.find((p) => p.name === params.name);
|
||||
// const page = existing;
|
||||
if (!pageConfig) {
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${portalSegment(portal, params)}/pages`));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
portal,
|
||||
pageConfig,
|
||||
page,
|
||||
portalUrl: PortalServer.getPortalUrl(portal),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const page = await getPortalPagesByName(portal.id, params.name!);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const pageConfig = appConfiguration.portals.pages.find((p) => p.name === params.name);
|
||||
if (!pageConfig) {
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${portalSegment(portal, params)}/pages`));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
const attributes = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: pageConfig.properties,
|
||||
});
|
||||
|
||||
if (!page) {
|
||||
await createPortalPage({
|
||||
portalId: portal.id,
|
||||
name: params.name!,
|
||||
attributes,
|
||||
});
|
||||
} else {
|
||||
await updatePortalPage(portal.id, page.id, {
|
||||
attributes,
|
||||
});
|
||||
}
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
// return redirect(UrlUtils.getModulePath(params, `portals/${portalSegment(portal, params)}/pages`));
|
||||
} else if (action === "delete") {
|
||||
try {
|
||||
if (page) {
|
||||
await deletePortalPage(portal.id, page.id);
|
||||
}
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${portalSegment(portal, params)}/pages`));
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e }, { status: 400 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [attributes] = useState<JsonPropertiesValuesDto>((data.page?.attributes ?? {}) as JsonPropertiesValuesDto);
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success, {
|
||||
action: {
|
||||
label: t("shared.preview"),
|
||||
onClick: () => {
|
||||
const href = `${data.portalUrl}${data.pageConfig.slug}`;
|
||||
window.open(href, "_blank");
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="edit" hidden readOnly />
|
||||
|
||||
<div className="space-y-2">
|
||||
<JsonPropertyValuesInput prefix="attributes" properties={data.pageConfig.properties} attributes={attributes} />
|
||||
</div>
|
||||
<div className="mt-5 flex justify-between space-x-2">
|
||||
<div>
|
||||
{data.page && (
|
||||
<ButtonSecondary onClick={onDelete} destructive>
|
||||
{t("shared.reset")}
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-between space-x-2">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(UrlUtils.getModulePath(params, `portals/${portalSegment(data.portal, params)}/pages`))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
-187
@@ -1,187 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import PricingPlanForm from "~/components/core/pricing/PricingPlanForm";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
||||
import { getAllPortalSubscriptionProducts, getPortalSubscriptionProduct } from "~/modules/portals/db/portalSubscriptionProducts.db.server";
|
||||
import { getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
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 "@hivegrid/db/prisma-browser";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requirePortalMutationAccess, requirePortalPricingEnabled, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
portal: Portal;
|
||||
item: SubscriptionProductDto;
|
||||
plans: SubscriptionProductDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalPricingEnabled({ request, tenantId });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
throw redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const item = await getPortalSubscriptionProduct(portal.id, params.product ?? "");
|
||||
if (!item) {
|
||||
throw redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.pricing.edit")} | ${process.env.APP_NAME}`,
|
||||
portal,
|
||||
item,
|
||||
plans: await getAllPortalSubscriptionProducts(portal.id),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalPricingEnabled({ request, tenantId });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const item = await getPortalSubscriptionProduct(portal.id, params.product ?? "");
|
||||
if (!item) {
|
||||
return badRequest({ error: t("shared.notFound") });
|
||||
}
|
||||
if (action === "edit") {
|
||||
const order = Number(form.get("order"));
|
||||
const title = form.get("title")?.toString();
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const badge = form.get("badge")?.toString() ?? "";
|
||||
const groupTitle = form.get("group-title")?.toString() ?? "";
|
||||
const groupDescription = form.get("group-description")?.toString() ?? "";
|
||||
const isPublic = Boolean(form.get("is-public"));
|
||||
const isBillingRequired = Boolean(form.get("is-billing-required"));
|
||||
const hasQuantity = Boolean(form.get("has-quantity"));
|
||||
const canBuyAgain = Boolean(form.get("can-buy-again"));
|
||||
|
||||
const featuresArr = form.getAll("features[]");
|
||||
const features: SubscriptionFeatureDto[] = featuresArr.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!title) {
|
||||
return badRequest({ error: t("models.portal.pricingErrors.titleRequired") });
|
||||
}
|
||||
|
||||
const plan: SubscriptionProductDto = {
|
||||
id: params.product,
|
||||
billingProviderId: "",
|
||||
order,
|
||||
title,
|
||||
description,
|
||||
badge,
|
||||
groupTitle,
|
||||
groupDescription,
|
||||
active: true,
|
||||
model: item.model,
|
||||
public: isPublic,
|
||||
prices: [],
|
||||
usageBasedPrices: [],
|
||||
features: [],
|
||||
billingAddressCollection: isBillingRequired ? "required" : "auto",
|
||||
hasQuantity,
|
||||
canBuyAgain,
|
||||
};
|
||||
|
||||
try {
|
||||
await PortalPricingServer.updatePlan(portal.id, plan, features);
|
||||
await createAdminLog(request, "portal.pricing.plan.updated", plan.translatedTitle ?? plan.title);
|
||||
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${portal.subdomain}/pricing`));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e?.toString() });
|
||||
}
|
||||
} else if (action === "delete") {
|
||||
if (!item) {
|
||||
return badRequest({ error: t("models.portal.pricingErrors.notFound") });
|
||||
}
|
||||
try {
|
||||
await PortalPricingServer.deletePlan(portal.id, item);
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${portal.subdomain}/pricing`));
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
}
|
||||
} else {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("admin.pricing.title")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
// {
|
||||
// title: t("models.portal.plural"),
|
||||
// routePath: UrlUtils.getModulePath(params, "portals"),
|
||||
// },
|
||||
{
|
||||
title: data.portal.title,
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}`),
|
||||
},
|
||||
{
|
||||
title: t("models.portal.pricing.title"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/pricing`),
|
||||
},
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<PricingPlanForm
|
||||
item={data.item}
|
||||
plans={data.plans}
|
||||
canUpdate={true}
|
||||
canDelete={true}
|
||||
isPortalPlan={true}
|
||||
cancelPath={UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/pricing`)}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-176
@@ -1,176 +0,0 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData, useParams } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import PricingPlanForm from "~/components/core/pricing/PricingPlanForm";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
||||
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
|
||||
import { getAllPortalSubscriptionProducts } from "~/modules/portals/db/portalSubscriptionProducts.db.server";
|
||||
import { getPortalById, PortalWithDetails } from "~/modules/portals/db/portals.db.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import PortalPricingServer from "~/modules/portals/services/PortalPricing.server";
|
||||
import toast from "react-hot-toast";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requirePortalMutationAccess, requirePortalPricingEnabled, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
portal: PortalWithDetails;
|
||||
plans: SubscriptionProductDto[];
|
||||
};
|
||||
|
||||
export const 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 portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
throw redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
const data: LoaderData = {
|
||||
title: i18nT("models.portal.pricing.newProductMetaTitle", { appName: process.env.APP_NAME }),
|
||||
portal,
|
||||
plans: await getAllPortalSubscriptionProducts(portal.id),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalPricingEnabled({ request, tenantId });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (action !== "create") {
|
||||
return badRequest({ error: t("shared.invalidForm") });
|
||||
}
|
||||
const order = Number(form.get("order"));
|
||||
const title = form.get("title")?.toString();
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const model = Number(form.get("model"));
|
||||
const badge = form.get("badge")?.toString() ?? "";
|
||||
const groupTitle = form.get("group-title")?.toString() ?? "";
|
||||
const groupDescription = form.get("group-description")?.toString() ?? "";
|
||||
const isPublic = Boolean(form.get("is-public"));
|
||||
const isBillingRequired = Boolean(form.get("is-billing-required"));
|
||||
const hasQuantity = Boolean(form.get("has-quantity"));
|
||||
const canBuyAgain = Boolean(form.get("can-buy-again"));
|
||||
|
||||
const featuresArr = form.getAll("features[]");
|
||||
const features: SubscriptionFeatureDto[] = featuresArr.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
const prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[] = form
|
||||
.getAll("prices[]")
|
||||
.map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
const oneTimePricesWithZero = prices.filter((p) => p.billingPeriod === SubscriptionBillingPeriod.ONCE && p.price === 0);
|
||||
if (oneTimePricesWithZero.length > 0) {
|
||||
return badRequest({ error: t("models.portal.pricingErrors.oneTimePriceZero") });
|
||||
}
|
||||
|
||||
const usageBasedPrices: SubscriptionUsageBasedPriceDto[] = form.getAll("usage-based-prices[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!title) {
|
||||
return badRequest({ error: t("models.portal.pricingErrors.planTitleRequired") });
|
||||
}
|
||||
|
||||
const plan: SubscriptionProductDto = {
|
||||
billingProviderId: "",
|
||||
order,
|
||||
title,
|
||||
model,
|
||||
description,
|
||||
badge,
|
||||
groupTitle,
|
||||
groupDescription,
|
||||
active: true,
|
||||
public: isPublic,
|
||||
prices: [],
|
||||
features: [],
|
||||
usageBasedPrices,
|
||||
billingAddressCollection: isBillingRequired ? "required" : "auto",
|
||||
hasQuantity,
|
||||
canBuyAgain,
|
||||
};
|
||||
|
||||
try {
|
||||
await PortalPricingServer.createPlan(portal.id, plan, prices, features);
|
||||
await createAdminLog(request, "admin.pricing.createdPlan", plan.title);
|
||||
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${portal.subdomain}/pricing`));
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e?.toString() });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.portal.pricing.newProduct")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
// {
|
||||
// title: t("models.portal.plural"),
|
||||
// routePath: UrlUtils.getModulePath(params, "portals"),
|
||||
// },
|
||||
{
|
||||
title: data.portal.title,
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}`),
|
||||
},
|
||||
{
|
||||
title: t("models.portal.pricing.title"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/pricing`),
|
||||
},
|
||||
{
|
||||
title: t("shared.new"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<PricingPlanForm plans={data.plans} isPortalPlan={true} cancelPath={UrlUtils.getModulePath(params, `portals/${data.portal.subdomain}/pricing`)} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useParams } from "react-router";
|
||||
import { EyeIcon } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next";
|
||||
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 ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
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 UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { requirePortalPricingEnabled, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails;
|
||||
items: SubscriptionProductDto[];
|
||||
portalUrl: string;
|
||||
publicPricingUrl: string;
|
||||
};
|
||||
|
||||
const PORTAL_PRICING_PUBLIC_PATH = "/plans";
|
||||
|
||||
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"));
|
||||
}
|
||||
const portalUrl = PortalServer.getPortalUrl(item);
|
||||
const items = await getAllPortalSubscriptionProductsWithUsers(item.id);
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
items: items.sort((x, y) => {
|
||||
return x?.order > y?.order ? 1 : -1;
|
||||
}),
|
||||
portalUrl,
|
||||
publicPricingUrl: `${portalUrl}${PORTAL_PRICING_PUBLIC_PATH}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.portal.pricing.title")}
|
||||
withHome={false}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonSecondary to={data.publicPricingUrl} target="_blank">
|
||||
<EyeIcon className="h-4 w-4" />
|
||||
<div>{t("shared.preview")}</div>
|
||||
</ButtonSecondary>
|
||||
<ButtonPrimary to="new">{t("shared.new")}</ButtonPrimary>
|
||||
</>
|
||||
}
|
||||
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`),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
headers={[
|
||||
{
|
||||
name: "order",
|
||||
title: t("models.subscriptionProduct.order"),
|
||||
value: (i) => i.order,
|
||||
},
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.subscriptionProduct.title"),
|
||||
value: (item) => (
|
||||
<>
|
||||
{t(item.title)}{" "}
|
||||
{item.badge && <span className=" border-border bg-theme-50 text-theme-800 ml-1 rounded-md border px-1 py-0.5 text-xs">{t(item.badge)}</span>}
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "model",
|
||||
title: t("models.subscriptionProduct.model"),
|
||||
value: (item) => <>{t("pricing." + PricingModel[item.model])}</>,
|
||||
},
|
||||
// ...allFeatures.map((feature) => {
|
||||
// return {
|
||||
// name: feature.name,
|
||||
// title: feature.name,
|
||||
// value: (item: SubscriptionProductDto) => <PlanFeatureValue item={getFeatureValue(item, feature.name)} />,
|
||||
// };
|
||||
// }),
|
||||
{
|
||||
name: "subscriptions",
|
||||
title: t("models.subscriptionProduct.plural"),
|
||||
value: (item) => (
|
||||
<div className=" text-muted-foreground lowercase">
|
||||
{item.tenantProducts?.length ?? 0} {t("shared.active")}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "active",
|
||||
title: t("models.subscriptionProduct.status"),
|
||||
value: (item) => (
|
||||
<>
|
||||
{item.active ? (
|
||||
<>
|
||||
{item.public ? (
|
||||
<SimpleBadge title={t("models.subscriptionProduct.public")} color={Colors.TEAL} />
|
||||
) : (
|
||||
<SimpleBadge title={t("models.subscriptionProduct.custom")} color={Colors.ORANGE} />
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<SimpleBadge title={t("shared.inactive")} color={Colors.RED} />
|
||||
)}
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: t("shared.actions"),
|
||||
value: (item) => (
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonTertiary disabled={!item.id} to={"edit/" + item.id}>
|
||||
{t("shared.edit")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-571
@@ -1,571 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, Link, useParams } from "react-router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "react-hot-toast";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { PortalWithDetails, getPortalById, getPortalBySubdomain, updatePortal } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import FormHelper from "~/utils/helpers/FormHelper";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import { defaultThemes } from "~/utils/theme/defaultThemes";
|
||||
import clsx from "clsx";
|
||||
import InputImage from "~/components/ui/input/InputImage";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails & { portalUrl?: string };
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const item: (PortalWithDetails & { portalUrl?: string }) | null = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
item.portalUrl = PortalServer.getPortalUrl(item);
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "edit") {
|
||||
const subdomain = UrlUtils.slugify(form.get("subdomain")?.toString() ?? "");
|
||||
const title = form.get("title")?.toString();
|
||||
// const isPublished = FormHelper.getBoolean(form, "isPublished");
|
||||
|
||||
if (subdomain && subdomain !== item.subdomain) {
|
||||
let isValidSubdomainSyntax = /^[a-z0-9-]+$/i.test(subdomain);
|
||||
if (!isValidSubdomainSyntax) {
|
||||
return Response.json({ error: t("models.portal.errors.invalidSubdomain") }, { status: 400 });
|
||||
}
|
||||
const existingSubdomain = await getPortalBySubdomain(subdomain);
|
||||
if (existingSubdomain) {
|
||||
return Response.json({ error: t("models.portal.errors.subdomainTaken") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const metadata = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: appConfiguration.portals?.metadata || [],
|
||||
prefix: "metadata",
|
||||
});
|
||||
|
||||
await updatePortal(item, {
|
||||
subdomain,
|
||||
title,
|
||||
metadata,
|
||||
// isPublished: true,
|
||||
});
|
||||
|
||||
if (subdomain && subdomain !== item.subdomain) {
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${subdomain}/settings`));
|
||||
}
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
} else if (action === "edit-seo") {
|
||||
const seoTitle = form.get("seoTitle")?.toString();
|
||||
const seoDescription = form.get("seoDescription")?.toString();
|
||||
const seoTwitterCreator = form.get("seoTwitterCreator")?.toString();
|
||||
const seoTwitterSite = form.get("seoTwitterSite")?.toString();
|
||||
const seoKeywords = form.get("seoKeywords")?.toString();
|
||||
|
||||
const seoImage = form.get("seoImage")?.toString();
|
||||
const seoThumbnail = form.get("seoThumbnail")?.toString();
|
||||
|
||||
const { storedSeoImage, storedSeoThumbnail } = await promiseHash({
|
||||
storedSeoImage: seoImage
|
||||
? storeFile({
|
||||
bucket: "seo",
|
||||
content: seoImage,
|
||||
id: `${item.id}-seo-image.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.portal.branding"),
|
||||
filename: `${item.id}-seo-image.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedSeoThumbnail: seoThumbnail
|
||||
? storeFile({
|
||||
bucket: "seo",
|
||||
content: seoThumbnail,
|
||||
id: `${item.id}-thumbnail.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.portal.branding"),
|
||||
filename: `${item.id}-thumbnail.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
});
|
||||
|
||||
await updatePortal(item, {
|
||||
seoTitle,
|
||||
seoDescription,
|
||||
seoImage: storedSeoImage,
|
||||
seoThumbnail: storedSeoThumbnail,
|
||||
seoTwitterCreator,
|
||||
seoTwitterSite,
|
||||
seoKeywords,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
} else if (action === "edit-branding") {
|
||||
const themeColor = form.get("themeColor")?.toString();
|
||||
const themeScheme = form.get("themeScheme")?.toString();
|
||||
let logo = form.get("logo")?.toString();
|
||||
let logoDarkMode = form.get("logoDarkMode")?.toString();
|
||||
let icon = form.get("icon")?.toString();
|
||||
let iconDarkMode = form.get("iconDarkMode")?.toString();
|
||||
let favicon = form.get("favicon")?.toString();
|
||||
|
||||
const { storedLogo, storedLogoDarkMode, storedIcon, storedIconDarkMode, storedFavicon } = await promiseHash({
|
||||
storedLogo: logo
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: logo,
|
||||
id: `${item.id}-logo.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.portal.branding"),
|
||||
filename: `${item.id}-logo.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedLogoDarkMode: logoDarkMode
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: logoDarkMode,
|
||||
id: `${item.id}-logo-dark-mode.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.portal.branding"),
|
||||
filename: `${item.id}-logo-dark-mode.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedIcon: icon
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: icon,
|
||||
id: `${item.id}-icon.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.portal.branding"),
|
||||
filename: `${item.id}-icon.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedIconDarkMode: iconDarkMode
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: iconDarkMode,
|
||||
id: `${item.id}-icon-dark-mode.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.portal.branding"),
|
||||
filename: `${item.id}-icon-dark-mode.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
storedFavicon: favicon
|
||||
? storeFile({
|
||||
bucket: "branding",
|
||||
content: favicon,
|
||||
id: `${item.id}-favicon.ico`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.portal.branding"),
|
||||
filename: `${item.id}-favicon.ico`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
});
|
||||
|
||||
await updatePortal(item, {
|
||||
themeColor,
|
||||
themeScheme,
|
||||
brandingLogo: storedLogo,
|
||||
brandingLogoDarkMode: storedLogoDarkMode,
|
||||
brandingIcon: storedIcon,
|
||||
brandingIconDarkMode: storedIconDarkMode,
|
||||
brandingFavicon: storedFavicon,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
} else if (action === "edit-analytics") {
|
||||
const simpleAnalytics = FormHelper.getBoolean(form, "simpleAnalytics");
|
||||
const plausibleAnalytics = FormHelper.getBoolean(form, "plausibleAnalytics");
|
||||
const googleAnalyticsTrackingId = form.get("googleAnalyticsTrackingId")?.toString();
|
||||
|
||||
await updatePortal(item, {
|
||||
analyticsSimpleAnalytics: simpleAnalytics,
|
||||
analyticsPlausibleAnalytics: plausibleAnalytics,
|
||||
analyticsGoogleAnalyticsTrackingId: googleAnalyticsTrackingId,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
const rootData = useRootData();
|
||||
const portalsConfig = rootData.appConfiguration.portals;
|
||||
|
||||
const [item, setItem] = useState(data.item);
|
||||
|
||||
useEffect(() => {
|
||||
setItem(data.item);
|
||||
}, [data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("shared.settings")}
|
||||
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("shared.settings"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="pb-10">
|
||||
<SettingSection title={t("settings.tenant.general")}>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="edit" readOnly hidden />
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<InputText
|
||||
name="title"
|
||||
title={t("models.portal.title")}
|
||||
value={item.title}
|
||||
setValue={(e) => setItem({ ...item, title: e.toString() })}
|
||||
required
|
||||
/>
|
||||
<InputText
|
||||
name="subdomain"
|
||||
title={t("models.portal.subdomain")}
|
||||
value={item.subdomain}
|
||||
setValue={(e) => setItem({ ...item, subdomain: e.toString() })}
|
||||
required
|
||||
hint={
|
||||
<div>
|
||||
{item.portalUrl && (
|
||||
<Link to={item.portalUrl} target="_blank" className="underline">
|
||||
{item.portalUrl}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
{portalsConfig?.metadata && (
|
||||
<JsonPropertyValuesInput prefix="metadata" properties={portalsConfig?.metadata} attributes={item.metadata as JsonPropertiesValuesDto} />
|
||||
)}
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("models.portal.branding")}>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="edit-branding" readOnly hidden />
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-1 gap-y-6 sm:grid-cols-6 sm:gap-x-6">
|
||||
<div className="sm:col-span-3">
|
||||
<InputSelect
|
||||
name="themeColor"
|
||||
title={t("models.portal.themeColor")}
|
||||
defaultValue={item.themeColor ?? ""}
|
||||
placeholder={t("shared.select") + "..."}
|
||||
options={defaultThemes.map((item) => {
|
||||
const label = t(item.labelKey, { defaultValue: item.name });
|
||||
return {
|
||||
name: label,
|
||||
value: item.value,
|
||||
component: (
|
||||
<div className="flex items-center space-x-2">
|
||||
<div
|
||||
className={clsx(
|
||||
`theme-${item.value}`,
|
||||
"bg-primary text-primary inline-flex shrink-0 items-center rounded-full text-xs font-medium"
|
||||
)}
|
||||
>
|
||||
<svg className={clsx("h-2 w-2")} fill="currentColor" viewBox="0 0 8 8">
|
||||
<circle cx={4} cy={4} r={3} />
|
||||
</svg>
|
||||
</div>
|
||||
<div>{label}</div>
|
||||
</div>
|
||||
),
|
||||
};
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputSelect
|
||||
name="themeScheme"
|
||||
title={t("models.portal.themeScheme")}
|
||||
defaultValue={item.themeScheme ?? "light"}
|
||||
placeholder={t("shared.select") + "..."}
|
||||
options={[
|
||||
{
|
||||
name: t("shared.light"),
|
||||
value: "light",
|
||||
},
|
||||
{
|
||||
name: t("shared.dark"),
|
||||
value: "dark",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputImage
|
||||
name="logo"
|
||||
title={t("models.portal.logo")}
|
||||
value={item.brandingLogo ?? ""}
|
||||
setValue={(e) => setItem({ ...item, brandingLogo: e.toString() })}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputImage
|
||||
name="logoDarkMode"
|
||||
title={t("models.portal.logoDark")}
|
||||
value={item.brandingLogoDarkMode ?? ""}
|
||||
setValue={(e) => setItem({ ...item, brandingLogoDarkMode: e.toString() })}
|
||||
className="dark"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputImage
|
||||
name="icon"
|
||||
title={t("models.portal.icon")}
|
||||
value={item.brandingIcon ?? ""}
|
||||
setValue={(e) => setItem({ ...item, brandingIcon: e.toString() })}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-3">
|
||||
<InputImage
|
||||
name="iconDarkMode"
|
||||
title={t("models.portal.iconDark")}
|
||||
value={item.brandingIconDarkMode ?? ""}
|
||||
setValue={(e) => setItem({ ...item, brandingIconDarkMode: e.toString() })}
|
||||
className="dark"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-6">
|
||||
<InputImage
|
||||
name="favicon"
|
||||
title={t("models.portal.favicon")}
|
||||
value={item.brandingFavicon ?? ""}
|
||||
setValue={(e) => setItem({ ...item, brandingFavicon: e.toString() })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("models.portal.seo")}>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="edit-seo" readOnly hidden />
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<InputText
|
||||
name="seoTitle"
|
||||
title={t("shared.title")}
|
||||
value={item.seoTitle ?? ""}
|
||||
setValue={(e) => setItem({ ...item, seoTitle: e.toString() })}
|
||||
required
|
||||
/>
|
||||
<InputText
|
||||
name="seoDescription"
|
||||
title={t("shared.description")}
|
||||
value={item.seoDescription ?? ""}
|
||||
setValue={(e) => setItem({ ...item, seoDescription: e.toString() })}
|
||||
required
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<InputImage
|
||||
name="seoImage"
|
||||
title={t("shared.image")}
|
||||
value={item.seoImage ?? ""}
|
||||
setValue={(e) => setItem({ ...item, seoImage: e.toString() })}
|
||||
/>
|
||||
<InputImage
|
||||
name="seoThumbnail"
|
||||
title={t("shared.thumbnail")}
|
||||
value={item.seoThumbnail ?? ""}
|
||||
setValue={(e) => setItem({ ...item, seoThumbnail: e.toString() })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<InputText
|
||||
name="seoTwitterCreator"
|
||||
title={t("models.portal.seoTwitterCreator")}
|
||||
value={item.seoTwitterCreator ?? ""}
|
||||
setValue={(e) => setItem({ ...item, seoTwitterCreator: e.toString() })}
|
||||
/>
|
||||
<InputText
|
||||
name="seoTwitterSite"
|
||||
title={t("models.portal.seoTwitterSite")}
|
||||
value={item.seoTwitterSite ?? ""}
|
||||
setValue={(e) => setItem({ ...item, seoTwitterSite: e.toString() })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<InputText
|
||||
name="seoKeywords"
|
||||
title={t("shared.keywords")}
|
||||
value={item.seoKeywords ?? ""}
|
||||
setValue={(e) => setItem({ ...item, seoKeywords: e.toString() })}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("models.portal.analytics")}>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="edit-analytics" readOnly hidden />
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<InputCheckboxWithDescription
|
||||
name="simpleAnalytics"
|
||||
value={item.analyticsSimpleAnalytics}
|
||||
setValue={(e) => setItem({ ...item, analyticsSimpleAnalytics: Boolean(e) })}
|
||||
title={t("models.portal.analyticsProviders.simpleAnalytics")}
|
||||
description={
|
||||
<a href="https://www.simpleanalytics.com/?referral=hesef" target="_blank" rel="noreferrer">
|
||||
{t("shared.clickHereToTryLearnMore")}.
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
|
||||
<InputCheckboxWithDescription
|
||||
name="plausibleAnalytics"
|
||||
value={item.analyticsPlausibleAnalytics}
|
||||
setValue={(e) => setItem({ ...item, analyticsPlausibleAnalytics: Boolean(e) })}
|
||||
title={t("models.portal.analyticsProviders.plausible")}
|
||||
description={
|
||||
<a href="https://plausible.io/" target="_blank" rel="noreferrer">
|
||||
{t("shared.clickHereToTryLearnMore")}.
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
|
||||
<InputText
|
||||
hideChars
|
||||
name="googleAnalyticsTrackingId"
|
||||
value={item.analyticsGoogleAnalyticsTrackingId ?? ""}
|
||||
setValue={(e) => setItem({ ...item, analyticsGoogleAnalyticsTrackingId: e.toString() })}
|
||||
title={t("models.portal.analyticsProviders.googleAnalyticsId")}
|
||||
placeholder={t("models.portal.analyticsProviders.googleAnalyticsPlaceholder")}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-228
@@ -1,228 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useNavigate, useOutlet, useParams, useSubmit } from "react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import UserBadge from "~/components/core/users/UserBadge";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { deletePortalUser, getPortalUserById, getPortalUsers, updatePortalUserPassword } from "~/modules/portals/db/portalUsers.db.server";
|
||||
import { PortalWithDetails, getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import { PortalUserDto } from "~/modules/portals/dtos/PortalUserDto";
|
||||
import { PortalTimestamp } from "~/modules/portals/components/PortalTimestamp";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
item: PortalWithDetails;
|
||||
items: PortalUserDto[];
|
||||
};
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
throw redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const items = await getPortalUsers(item.id);
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: `${t("models.user.plural")} | ${item.title} | ${process.env.APP_NAME}` }],
|
||||
item,
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const userId = form.get("id")?.toString() ?? "";
|
||||
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
const user = await getPortalUserById(portal.id, userId);
|
||||
|
||||
if (!userId || !user || !action) {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
switch (action) {
|
||||
case "change-password": {
|
||||
const passwordNew = form.get("password-new")?.toString();
|
||||
if (!passwordNew) {
|
||||
return Response.json({ error: t("admin.users.errors.passwordMinLength") }, { status: 400 });
|
||||
}
|
||||
const policyResult = await validatePolicyPassword(passwordNew, user.email ? { email: user.email } : {});
|
||||
if (!policyResult.valid) {
|
||||
const first = policyResult.errors[0];
|
||||
return Response.json({ error: first ? t(first.code, first.args ?? {}) : t("admin.users.errors.passwordMinLength") }, { status: 400 });
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(passwordNew);
|
||||
await updatePortalUserPassword(portal.id, user.id, { passwordHash });
|
||||
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
}
|
||||
case "delete-user": {
|
||||
try {
|
||||
await deletePortalUser(portal.id, userId);
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e }, { status: 400 });
|
||||
}
|
||||
}
|
||||
default: {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
const outlet = useOutlet();
|
||||
const navigate = useNavigate();
|
||||
const submit = useSubmit();
|
||||
const rootData = useRootData();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onChangePassword(user: PortalUserDto) {
|
||||
const password = prompt(t("settings.profile.changePassword"));
|
||||
if (password && confirm(t("models.portal.users.confirmUpdatePassword", { email: user.email }))) {
|
||||
const form = new FormData();
|
||||
form.set("action", "change-password");
|
||||
form.set("id", user.id);
|
||||
form.set("password-new", password);
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
}
|
||||
function deleteUser(item: PortalUserDto) {
|
||||
if (confirmDelete.current) {
|
||||
confirmDelete.current.setValue(item);
|
||||
confirmDelete.current.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
}
|
||||
function onConfirmDeleteUser(item: PortalUserDto) {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete-user");
|
||||
form.set("id", item.id);
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.user.plural")}
|
||||
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.user.plural"),
|
||||
},
|
||||
]}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonPrimary to="new">{t("shared.new")}</ButtonPrimary>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("settings.profile.changePassword"),
|
||||
onClick: (_, item) => onChangePassword(item),
|
||||
},
|
||||
{
|
||||
title: t("shared.delete"),
|
||||
onClick: (_, item) => deleteUser(item),
|
||||
destructive: true,
|
||||
hidden: () => true,
|
||||
},
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute: (_, item) => item.id,
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "user",
|
||||
title: t("models.user.object"),
|
||||
value: (item) => <UserBadge item={item} withAvatar={true} />,
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => <PortalTimestamp value={item.createdAt} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<SlideOverWideEmpty
|
||||
open={!!outlet}
|
||||
onClose={() => {
|
||||
navigate(".", { replace: true });
|
||||
}}
|
||||
className="sm:max-w-sm"
|
||||
overflowYScroll={true}
|
||||
title={params.userId ? t("shared.edit") : t("shared.new")}
|
||||
>
|
||||
<div className="-mx-1 -mt-3">
|
||||
<div className="space-y-4">{outlet}</div>
|
||||
</div>
|
||||
</SlideOverWideEmpty>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onConfirmDeleteUser} destructive />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation, useParams, useSubmit } from "react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { deletePortalUser, getPortalUserById, updatePortalUser } from "~/modules/portals/db/portalUsers.db.server";
|
||||
import { getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { toast } from "sonner";
|
||||
import { PortalUserDto } from "~/modules/portals/dtos/PortalUserDto";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "../../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
user: PortalUserDto;
|
||||
portalSubdomain: string;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const user = await getPortalUserById(portal.id, params.userId!);
|
||||
if (!user) {
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${portal.subdomain || params.portal}/users`));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
user,
|
||||
portalSubdomain: portal.subdomain || params.portal || "",
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
|
||||
function portalUsersPath(params: { portal?: string }, portal: { subdomain?: string | null }) {
|
||||
return UrlUtils.getModulePath(params, `portals/${portal.subdomain || params.portal}/users`);
|
||||
}
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
const user = await getPortalUserById(portal.id, params.userId!);
|
||||
if (!user) {
|
||||
return redirect(portalUsersPath(params, portal));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString();
|
||||
const avatar = form.get("avatar")?.toString();
|
||||
|
||||
await updatePortalUser(portal.id, user.id, {
|
||||
firstName,
|
||||
lastName,
|
||||
avatar,
|
||||
});
|
||||
|
||||
return redirect(portalUsersPath(params, portal));
|
||||
} else if (action === "delete") {
|
||||
try {
|
||||
await deletePortalUser(portal.id, user.id);
|
||||
return redirect(portalUsersPath(params, portal));
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e }, { status: 400 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="edit" hidden readOnly />
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputText autoFocus type="email" name="email" title={t("models.user.email")} disabled defaultValue={data.user.email} />
|
||||
|
||||
<InputText name="firstName" title={t("models.user.firstName")} defaultValue={data.user.firstName} />
|
||||
|
||||
<InputText name="lastName" title={t("models.user.lastName")} defaultValue={data.user.lastName ?? ""} />
|
||||
</div>
|
||||
<div className="mt-5 flex justify-between space-x-2">
|
||||
<div>
|
||||
<ButtonSecondary onClick={onDelete} destructive>
|
||||
{t("shared.delete")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
<div className="flex justify-between space-x-2">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(UrlUtils.getModulePath(params, `portals/${data.portalSubdomain}/users`))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
-140
@@ -1,140 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigate, useNavigation, useParams } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createPortalUser, getPortalUserByEmail } from "~/modules/portals/db/portalUsers.db.server";
|
||||
import { getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { toast } from "sonner";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "../../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
portalSubdomain: string;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
portalSubdomain: portal.subdomain || params.portal || "",
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
if (action === "create") {
|
||||
const email = form.get("email")?.toString();
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString();
|
||||
const password = form.get("password")?.toString();
|
||||
const avatar = form.get("avatar")?.toString();
|
||||
|
||||
if (!email || !password || !firstName) {
|
||||
return Response.json({ error: t("models.portal.users.errors.missingRequired") }, { status: 400 });
|
||||
}
|
||||
const existingUser = await getPortalUserByEmail(portal.id, email);
|
||||
if (existingUser) {
|
||||
return Response.json({ error: t("models.portal.users.errors.emailExists") }, { status: 400 });
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(password);
|
||||
await createPortalUser({
|
||||
tenantId,
|
||||
portalId: portal.id,
|
||||
email,
|
||||
passwordHash,
|
||||
firstName,
|
||||
lastName: lastName ?? "",
|
||||
avatar: avatar ?? null,
|
||||
});
|
||||
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${portal.subdomain || params.portal}/users`));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const mainInput = useRef<RefInputText>(null);
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
mainInput.current?.input.current?.focus();
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
const [email, setEmail] = useState<string>("");
|
||||
const [password, setPassword] = useState<string>("");
|
||||
const [firstName, setFirstName] = useState<string>("");
|
||||
const [lastName, setLastName] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form method="post" className="inline-block w-full overflow-hidden p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="create" hidden readOnly />
|
||||
|
||||
<div className="space-y-2">
|
||||
<InputText ref={mainInput} autoFocus type="email" name="email" title={t("models.user.email")} value={email} setValue={setEmail} required />
|
||||
|
||||
<InputText type="password" name="password" title={t("account.shared.password")} value={password} setValue={setPassword} required />
|
||||
|
||||
<InputText name="firstName" title={t("models.user.firstName")} value={firstName} setValue={setFirstName} required />
|
||||
|
||||
<InputText name="lastName" title={t("models.user.lastName")} value={lastName} setValue={setLastName} />
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<ButtonSecondary type="button" className="w-full" onClick={() => navigate(UrlUtils.getModulePath(params, `portals/${data.portalSubdomain}/users`))}>
|
||||
<div className="w-full text-center">{t("shared.back")}</div>
|
||||
</ButtonSecondary>
|
||||
<LoadingButton type="submit" disabled={navigation.state === "submitting"} className="w-full">
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
-226
@@ -1,226 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, redirect, useActionData } from "react-router";
|
||||
import { Form, useParams } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import InputText, { RefInputText } from "~/components/ui/input/InputText";
|
||||
import NewPageLayout from "~/components/ui/layouts/NewPageLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createPortal, getPortalByDomain, getPortalBySubdomain } from "~/modules/portals/db/portals.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import FormHelper from "~/utils/helpers/FormHelper";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { requirePortalMutationAccess, requirePortalReadAccess } from "./portalAccess.server";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
|
||||
type LoaderData = {
|
||||
metatags: MetaTagsDto;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (!appConfiguration.portals?.enabled) {
|
||||
throw Response.json({ error: t("models.portal.errors.disabled") }, { status: 400 });
|
||||
}
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const data: LoaderData = {
|
||||
metatags: [{ title: `${t("shared.new")} ${t("models.portal.object")} | ${process.env.APP_NAME}` }],
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const userInfo = await getUserInfo(request);
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "create") {
|
||||
const subdomain = UrlUtils.slugify(form.get("subdomain")?.toString() ?? "");
|
||||
const domain = form.get("domain")?.toString().toLowerCase().trim();
|
||||
const title = form.get("title")?.toString() ?? "";
|
||||
const description = form.get("description")?.toString() ?? "";
|
||||
const isPublished = FormHelper.getBoolean(form, "isPublished");
|
||||
const themeColor = form.get("themeColor")?.toString();
|
||||
const themeScheme = form.get("themeScheme")?.toString();
|
||||
// const seoTitle = form.get("seoTitle")?.toString();
|
||||
// const seoDescription = form.get("seoDescription")?.toString();
|
||||
const seoImage = form.get("seoImage")?.toString();
|
||||
|
||||
let isValidSubdomainSyntax = /^[a-z0-9-]+$/i.test(subdomain);
|
||||
if (!isValidSubdomainSyntax) {
|
||||
return Response.json({ error: t("models.portal.errors.invalidSubdomain") }, { status: 400 });
|
||||
}
|
||||
const existingSubdomain = await getPortalBySubdomain(subdomain);
|
||||
if (existingSubdomain) {
|
||||
return Response.json({ error: t("models.portal.errors.subdomainTaken") }, { status: 400 });
|
||||
}
|
||||
const existingDomain = domain ? await getPortalByDomain(domain) : null;
|
||||
if (existingDomain) {
|
||||
return Response.json({ error: t("models.portal.errors.domainTaken") }, { status: 400 });
|
||||
}
|
||||
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const metadata = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: appConfiguration.portals?.metadata || [],
|
||||
prefix: "metadata",
|
||||
});
|
||||
|
||||
// throw Response.json({ error: JSON.stringify(metadata, null, 2) }, { status: 400 });
|
||||
|
||||
const item = await createPortal({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
subdomain,
|
||||
domain: domain || null,
|
||||
title,
|
||||
isPublished: isPublished || true,
|
||||
paymentProviderAccountId: null,
|
||||
metadata,
|
||||
themeColor: themeColor || null,
|
||||
themeScheme: themeScheme || null,
|
||||
seoTitle: title,
|
||||
seoDescription: description,
|
||||
seoImage: seoImage || null,
|
||||
seoThumbnail: null,
|
||||
seoTwitterCreator: null,
|
||||
seoTwitterSite: null,
|
||||
seoKeywords: null,
|
||||
authRequireEmailVerification: false,
|
||||
authRequireOrganization: false,
|
||||
authRequireName: false,
|
||||
analyticsSimpleAnalytics: false,
|
||||
analyticsPlausibleAnalytics: false,
|
||||
analyticsGoogleAnalyticsTrackingId: null,
|
||||
brandingLogo: null,
|
||||
brandingLogoDarkMode: null,
|
||||
brandingIcon: null,
|
||||
brandingIconDarkMode: null,
|
||||
brandingFavicon: null,
|
||||
});
|
||||
|
||||
return redirect(UrlUtils.getModulePath(params, `portals/${item.subdomain}`));
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const params = useParams();
|
||||
const rootData = useRootData();
|
||||
const portalsConfig = rootData.appConfiguration.portals;
|
||||
|
||||
const mainInput = useRef<RefInputText>(null);
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
mainInput.current?.input.current?.focus();
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
const [item, setItem] = useState({
|
||||
title: "",
|
||||
subdomain: "",
|
||||
domain: "",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const subdomain = UrlUtils.slugify(item.title);
|
||||
if (item.subdomain !== subdomain) {
|
||||
setItem({ ...item, subdomain });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [item.title]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<NewPageLayout
|
||||
title={`${t("models.portal.actions.new.title")}`}
|
||||
menu={[
|
||||
{
|
||||
title: t("models.portal.plural"),
|
||||
routePath: UrlUtils.getModulePath(params, "portals"),
|
||||
},
|
||||
{
|
||||
title: t("shared.new"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="create" readOnly hidden />
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<InputText
|
||||
ref={mainInput}
|
||||
autoFocus
|
||||
name="title"
|
||||
title={t("models.portal.title")}
|
||||
value={item.title}
|
||||
setValue={(e) => setItem({ ...item, title: e.toString() })}
|
||||
required
|
||||
/>
|
||||
<InputText
|
||||
name="subdomain"
|
||||
title={t("models.portal.subdomain")}
|
||||
value={item.subdomain}
|
||||
setValue={(e) => setItem({ ...item, subdomain: e.toString() })}
|
||||
required
|
||||
className="rounded-r-none"
|
||||
button={
|
||||
<div className="bg-secondary/90 rounded rounded-l-none border border-l-0 px-3 py-1">
|
||||
<kbd className="border-border text-muted-foreground inline-flex items-center justify-center px-1 text-center font-sans text-xs font-medium">
|
||||
.{rootData.appConfiguration.app.domain}
|
||||
</kbd>
|
||||
</div>
|
||||
}
|
||||
onBlur={() => setItem({ ...item, subdomain: UrlUtils.slugify(item.subdomain) })}
|
||||
/>
|
||||
|
||||
{portalsConfig?.metadata && <JsonPropertyValuesInput prefix="metadata" properties={portalsConfig?.metadata} attributes={{}} />}
|
||||
</div>
|
||||
|
||||
{/* {portalsConfig?.domains?.enabled && (
|
||||
<InputText name="domain" title={t("models.portal.domain")} value={item.domain} setValue={(e) => setItem({ ...item, domain: e.toString() })} />
|
||||
)} */}
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</NewPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-186
@@ -1,186 +0,0 @@
|
||||
import { loadWebConfig } from "@hivegrid/config";
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getAllTenantPortals, PortalWithCount } from "~/modules/portals/db/portals.db.server";
|
||||
import { Link, useParams } from "react-router";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import EmptyState from "~/components/ui/emptyState/EmptyState";
|
||||
import ExternalLinkEmptyIcon from "~/components/ui/icons/ExternalLinkEmptyIcon";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import { Fragment } from "react";
|
||||
import TagsIconFilled from "~/components/ui/icons/crud/TagsIconFilled";
|
||||
import EyeIcon from "~/components/ui/icons/EyeIcon";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { requirePortalReadAccess } from "./portalAccess.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type PortalWithCounts = PortalWithCount & {
|
||||
portalUrl?: string;
|
||||
_count: {
|
||||
users: number;
|
||||
subscriptionProducts: number;
|
||||
visitors?: number;
|
||||
};
|
||||
};
|
||||
type LoaderData = {
|
||||
items: PortalWithCounts[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const config = appConfiguration.portals;
|
||||
if (!config?.enabled) {
|
||||
throw Response.json({ error: t("models.portal.errors.disabled") }, { status: 400 });
|
||||
}
|
||||
if (!config?.forTenants) {
|
||||
throw Response.json({ error: t("models.portal.errors.noAccess") }, { status: 403 });
|
||||
}
|
||||
if (!loadWebConfig().config.portalServer.url) {
|
||||
throw new Error("PORTAL_SERVER_URL is not defined");
|
||||
}
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const items: PortalWithCounts[] = await getAllTenantPortals({ tenantId });
|
||||
const visitorCounts =
|
||||
items.length > 0
|
||||
? await db.analyticsUniqueVisitor.groupBy({
|
||||
by: ["portalId"],
|
||||
where: { portalId: { in: items.map((item) => item.id) } },
|
||||
_count: { _all: true },
|
||||
})
|
||||
: [];
|
||||
const visitorsByPortalId = new Map(visitorCounts.flatMap((row) => (row.portalId ? [[row.portalId, row._count._all]] : [])));
|
||||
for (const item of items) {
|
||||
item.portalUrl = PortalServer.getPortalUrl(item);
|
||||
item._count = {
|
||||
...item._count,
|
||||
visitors: visitorsByPortalId.get(item.id) ?? 0,
|
||||
};
|
||||
}
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const rootData = useRootData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
const portalsConfig = rootData.appConfiguration.portals;
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.portal.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonPrimary to={UrlUtils.getModulePath(params, `portals/new`)}>{t("shared.new")}</ButtonPrimary>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{!rootData.appConfiguration.portals?.enabled && <WarningBanner title={t("shared.warning")}>{t("models.portal.disabled.description")}</WarningBanner>}
|
||||
<div className="space-y-2">
|
||||
{data.items.length === 0 && (
|
||||
<EmptyState
|
||||
className="bg-background"
|
||||
to="new"
|
||||
captions={{
|
||||
// description: t("shared.noRecords"),
|
||||
new: t("models.portal.actions.new.title"),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{data.items.map((item) => {
|
||||
return (
|
||||
<div key={item.id} className="border-border hover:border-primary bg-background group relative flex flex-col rounded-lg border hover:shadow-2xs">
|
||||
<Link to={item.subdomain}>
|
||||
{item.portalUrl && (
|
||||
<Fragment>
|
||||
{item.isPublished ? (
|
||||
<Link
|
||||
to={item.portalUrl}
|
||||
target="_blank"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-secondary/80 text-muted-foreground hover:text-secondary-foreground hover:bg-secondary absolute top-4 right-3 hidden rounded-md p-1.5 group-hover:flex"
|
||||
>
|
||||
<ExternalLinkEmptyIcon className="h-4 w-4" />
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-muted-foreground/80 absolute top-4 right-3 hidden text-xs italic group-hover:flex">
|
||||
{t("models.portal.unpublished")}
|
||||
</span>
|
||||
)}
|
||||
</Fragment>
|
||||
)}
|
||||
<div className="p-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
{item.brandingIcon && (
|
||||
<img
|
||||
src={item.brandingIcon}
|
||||
alt={item.title}
|
||||
className="bg-secondary/90 inline-block h-9 w-9 shrink-0 rounded-full object-contain p-0.5 shadow-2xs"
|
||||
/>
|
||||
)}
|
||||
<div className="space-y-1">
|
||||
<div>
|
||||
<div className="line-clamp-1 text-base font-medium">{item.title}</div>
|
||||
<div className="text-muted-foreground text-xs">{item.portalUrl?.replace("https://", "").replace("http://", "")}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<div className="text-muted-foreground inline-flex items-center gap-1 text-sm">
|
||||
<UserIcon className="h-3 w-3 text-gray-300" />{" "}
|
||||
{t("models.portal.counts.users", { count: item._count.users, formattedCount: formatters.number(item._count.users) })}
|
||||
</div>
|
||||
{portalsConfig?.pricing && (
|
||||
<div className="text-muted-foreground inline-flex items-center gap-1 text-sm">
|
||||
<TagsIconFilled className="h-3 w-3 text-gray-300" />{" "}
|
||||
{t("models.portal.counts.plans", { count: item._count.subscriptionProducts, formattedCount: formatters.number(item._count.subscriptionProducts) })}
|
||||
</div>
|
||||
)}
|
||||
{portalsConfig?.analytics && (
|
||||
<div className="text-muted-foreground inline-flex items-center gap-1 text-sm">
|
||||
<EyeIcon className="h-3 w-3 text-gray-300" />{" "}
|
||||
{t("models.portal.counts.visitors", { count: item._count.visitors ?? 0, formattedCount: formatters.number(item._count.visitors ?? 0) })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
function UserIcon({ className }: { className: string }) {
|
||||
return (
|
||||
// <svg className={className} fill="currentColor" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="30" height="30" viewBox="0 0 30 30">
|
||||
// <path d="M 15 3 C 11.686 3 9 5.686 9 9 L 9 10 C 9 13.314 11.686 16 15 16 C 18.314 16 21 13.314 21 10 L 21 9 C 21 5.686 18.314 3 15 3 z M 14.998047 19 C 10.992047 19 5.8520469 21.166844 4.3730469 23.089844 C 3.4590469 24.278844 4.329125 26 5.828125 26 L 24.169922 26 C 25.668922 26 26.539 24.278844 25.625 23.089844 C 24.146 21.167844 19.004047 19 14.998047 19 z"></path>
|
||||
// </svg>
|
||||
<svg className={className} fill="currentColor" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="48" height="48" viewBox="0 0 48 48">
|
||||
<path d="M24 4A10 10 0 1024 24 10 10 0 1024 4zM36.021 28H11.979C9.785 28 8 29.785 8 31.979V33.5c0 3.312 1.885 6.176 5.307 8.063C16.154 43.135 19.952 44 24 44c7.706 0 16-3.286 16-10.5v-1.521C40 29.785 38.215 28 36.021 28z"></path>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import IconWidgets from "~/components/layouts/icons/IconWidgets";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (params.tenant && !appConfiguration.widgets.enabled) {
|
||||
throw Response.json({ error: t("widgets.errors.disabled") }, { status: 400 });
|
||||
}
|
||||
return Response.json({});
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const params = useParams();
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("widgets.plural"),
|
||||
href: UrlUtils.getModulePath(params, `widgets`),
|
||||
exact: true,
|
||||
icon: <IconWidgets className="h-5 w-5" />,
|
||||
iconSelected: <IconWidgets className="h-5 w-5" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-475
@@ -1,475 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigation, useParams, useSubmit } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { ClipboardIcon } from "~/components/ui/icons/vendor";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import InputImage from "~/components/ui/input/InputImage";
|
||||
import InputMultipleText from "~/components/ui/input/InputMultipleText";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { WidgetDto } from "~/modules/widgets/dtos/WidgetDto";
|
||||
import WidgetUtils from "~/modules/widgets/utils/WidgetUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { defaultTheme, defaultThemes } from "~/utils/theme/defaultThemes";
|
||||
import { getAbsoluteUrl } from "~/utils/url.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
item: WidgetDto;
|
||||
widgetUrl: string;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
|
||||
const item = await db.widget.findFirst({
|
||||
where: { id: params.id, tenantId },
|
||||
});
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item: WidgetUtils.toDto(item),
|
||||
widgetUrl: `<script src="${getAbsoluteUrl(request, "/embed.js")}" data-widget-id="${item.id}" data-open-delay="-1" defer async />`,
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const item = await db.widget.findFirst({
|
||||
where: { id: params.id, tenantId },
|
||||
});
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() || "";
|
||||
const metadata = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: appConfiguration.widgets?.metadata || [],
|
||||
prefix: "metadata",
|
||||
});
|
||||
|
||||
if (name !== item.name) {
|
||||
const existing = await db.widget.findUnique({
|
||||
where: {
|
||||
tenantId_name: { tenantId, name },
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return Response.json({ error: t("widgets.errors.nameAlreadyTaken") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
try {
|
||||
const update = await db.widget.updateMany({
|
||||
where: { id: item.id, tenantId },
|
||||
data: {
|
||||
name,
|
||||
metadata: JSON.stringify(metadata),
|
||||
},
|
||||
});
|
||||
if (update.count !== 1) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
} else if (action === "edit-branding") {
|
||||
const themeColor = form.get("themeColor")?.toString();
|
||||
const themeScheme = form.get("themeScheme")?.toString();
|
||||
let logo = form.get("logo")?.toString();
|
||||
const position = form.get("position")?.toString();
|
||||
const placeholder = form.get("placeholder")?.toString();
|
||||
const hiddenInUrls = form.getAll("hiddenInUrls[]").map((f) => f.toString());
|
||||
const visibleInUrls = form.getAll("visibleInUrls[]").map((f) => f.toString());
|
||||
|
||||
const { storedLogo } = await promiseHash({
|
||||
storedLogo: logo
|
||||
? storeFile({
|
||||
bucket: "widgets",
|
||||
content: logo,
|
||||
id: `${item.id}-logo.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.widget.logo"),
|
||||
filename: `${item.id}-logo.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
});
|
||||
|
||||
const appearance: WidgetDto["appearance"] = {
|
||||
theme: themeColor || "",
|
||||
mode: themeScheme === "light" ? "light" : "dark",
|
||||
logo: storedLogo,
|
||||
position: position as any,
|
||||
hiddenInUrls,
|
||||
visibleInUrls,
|
||||
};
|
||||
const update = await db.widget.updateMany({
|
||||
where: { id: item.id, tenantId },
|
||||
data: {
|
||||
appearance: JSON.stringify(appearance),
|
||||
},
|
||||
});
|
||||
if (update.count !== 1) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
} else if (action === "delete") {
|
||||
await db.widget.deleteMany({
|
||||
where: { id: item.id, tenantId },
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration } = useRootData();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
const [item, setItem] = useState<WidgetDto>(data.item);
|
||||
|
||||
const navigation = useNavigation();
|
||||
const isDeleting = navigation.state === "submitting";
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const textToType = `${t("shared.delete")} ${data.item.name}`;
|
||||
const [typeToConfirm, setTypeToConfirm] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
setItem(data.item);
|
||||
}, [data.item]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onConfirmDelete() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.append("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={item.name}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: t("widgets.plural"),
|
||||
routePath: UrlUtils.getModulePath(params, `widgets`),
|
||||
},
|
||||
{
|
||||
title: data.item.name,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="pb-20">
|
||||
<SettingSection title={t("widgets.settings.details")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<Form method="post">
|
||||
<input hidden type="text" name="action" value="edit" readOnly />
|
||||
<div className="">
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-6 gap-2">
|
||||
<div className="col-span-6 sm:col-span-6 md:col-span-6">
|
||||
<label htmlFor="name" className="text-muted-foreground mb-1 block text-sm leading-5 font-medium">
|
||||
{t("shared.name")}
|
||||
</label>
|
||||
<Input name="name" required type="text" defaultValue={data.item.name} />
|
||||
</div>
|
||||
</div>
|
||||
<JsonPropertyValuesInput attributes={data.item.metadata} prefix="metadata" properties={appConfiguration.widgets.metadata || []} />
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<div className="flex justify-between">
|
||||
<div></div>
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* */}
|
||||
<SettingSection title={t("widgets.settings.embed.title")}>
|
||||
<div>
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("widgets.settings.embed.instructionBefore")} <code><head></code> {t("widgets.settings.embed.instructionAfter")}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className=""
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(data.widgetUrl);
|
||||
toast.success(t("shared.copied"));
|
||||
}}
|
||||
>
|
||||
<ClipboardIcon className="text-muted-foreground h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<InputText rows={2} className="bg-secondary" defaultValue={data.widgetUrl} readOnly />
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("widgets.settings.appearance.title")}>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="edit-branding" readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-6 sm:gap-x-3">
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="themeColor"
|
||||
title={t("widgets.settings.appearance.themeColor")}
|
||||
value={item.appearance.theme}
|
||||
setValue={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
theme: e?.toString() || "",
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("shared.select") + "..."}
|
||||
options={defaultThemes.map((item) => {
|
||||
const label = t(item.labelKey, { defaultValue: item.name });
|
||||
return {
|
||||
name: label,
|
||||
value: item.value,
|
||||
component: (
|
||||
<div className="flex items-center space-x-2">
|
||||
<div
|
||||
className={clsx(
|
||||
`theme-${item.value}`,
|
||||
"bg-primary text-primary inline-flex flex-shrink-0 items-center rounded-full text-xs font-medium"
|
||||
)}
|
||||
>
|
||||
<svg className={clsx("h-2 w-2")} fill="currentColor" viewBox="0 0 8 8">
|
||||
<circle cx={4} cy={4} r={3} />
|
||||
</svg>
|
||||
</div>
|
||||
<div>{label}</div>
|
||||
</div>
|
||||
),
|
||||
};
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="themeScheme"
|
||||
title={t("widgets.settings.appearance.themeScheme")}
|
||||
value={item.appearance.mode}
|
||||
setValue={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
mode: e === "light" ? "light" : "dark",
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("shared.select") + "..."}
|
||||
options={[
|
||||
{
|
||||
name: t("shared.light"),
|
||||
value: "light",
|
||||
},
|
||||
{
|
||||
name: t("shared.dark"),
|
||||
value: "dark",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="position"
|
||||
title={t("widgets.settings.appearance.position")}
|
||||
defaultValue={item.appearance.position}
|
||||
options={[
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.bottomRight"),
|
||||
value: "bottom-right",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.bottomLeft"),
|
||||
value: "bottom-left",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.topRight"),
|
||||
value: "top-right",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.topLeft"),
|
||||
value: "top-left",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-6">
|
||||
<InputImage name="logo" title={t("shared.logo")} defaultValue={item.appearance.logo || ""} />
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-3">
|
||||
<InputMultipleText
|
||||
name="hiddenInUrls[]"
|
||||
title={t("widgets.settings.appearance.hideInUrls")}
|
||||
value={item.appearance.hiddenInUrls}
|
||||
onChange={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
hiddenInUrls: e.map((i) => {
|
||||
i = i.trim();
|
||||
return "/" + UrlUtils.slugify(i);
|
||||
}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("widgets.settings.appearance.hideInUrlsPlaceholder")}
|
||||
separator="Enter"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-3">
|
||||
<InputMultipleText
|
||||
name="visibleInUrls[]"
|
||||
title={t("widgets.settings.appearance.onlyShowInUrls")}
|
||||
value={item.appearance.visibleInUrls}
|
||||
onChange={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
visibleInUrls: e.map((i) => {
|
||||
i = i.trim();
|
||||
return "/" + UrlUtils.slugify(i);
|
||||
}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("widgets.settings.appearance.onlyShowInUrlsPlaceholder")}
|
||||
separator="Enter"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")}>
|
||||
<div className="mt-12 space-y-2 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<InputText title={t("widgets.settings.danger.confirmDelete", { text: textToType })} value={typeToConfirm} setValue={setTypeToConfirm} />
|
||||
</div>
|
||||
<div>
|
||||
<ButtonPrimary
|
||||
disabled={typeToConfirm !== textToType || isDeleting}
|
||||
className={clsx(isDeleting && "base-spinner")}
|
||||
destructive={true}
|
||||
onClick={onDelete}
|
||||
>
|
||||
{t("shared.delete")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} destructive onYes={onConfirmDelete} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
-216
@@ -1,216 +0,0 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, Link, useParams, useSubmit } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import JsonPropertyValueCell from "~/modules/jsonProperties/components/JsonPropertyValueCell";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { WidgetDto } from "~/modules/widgets/dtos/WidgetDto";
|
||||
import WidgetUtils from "~/modules/widgets/utils/WidgetUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { AppConfiguration, getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { defaultTheme } from "~/utils/theme/defaultThemes";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
items: WidgetDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
|
||||
const data: LoaderData = {
|
||||
items: (await db.widget.findMany({ where: { tenantId } })).map((f) => WidgetUtils.toDto(f)),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "create") {
|
||||
const name = form.get("name")?.toString() || "";
|
||||
const metadata = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: appConfiguration.widgets?.metadata || [],
|
||||
prefix: "metadata",
|
||||
});
|
||||
const existing = await db.widget.findUnique({
|
||||
where: {
|
||||
tenantId_name: { tenantId, name },
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return Response.json({ error: t("widgets.errors.nameAlreadyTaken") }, { status: 400 });
|
||||
}
|
||||
const appearance: WidgetDto["appearance"] = {
|
||||
logo: null,
|
||||
theme: defaultTheme,
|
||||
mode: "light",
|
||||
position: "bottom-right",
|
||||
hiddenInUrls: [],
|
||||
visibleInUrls: [],
|
||||
};
|
||||
const item = await db.widget.create({
|
||||
data: {
|
||||
name,
|
||||
tenantId,
|
||||
metadata: JSON.stringify(metadata),
|
||||
appearance: JSON.stringify(appearance),
|
||||
},
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `widgets/${item.id}`));
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration } = useRootData();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const [addingWidget, setAddingWidget] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("widgets.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonPrimary onClick={() => setAddingWidget(true)}>{t("shared.new")}</ButtonPrimary>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute(idx, item) {
|
||||
return UrlUtils.getModulePath(params, `widgets/${item.id}`);
|
||||
},
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
title: t("shared.title"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<Link to={UrlUtils.getModulePath(params, `widgets/${item.id}`)} className="font-medium hover:underline">
|
||||
{item.name}
|
||||
</Link>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
...(appConfiguration.widgets.metadata
|
||||
?.filter((f) => !f.hideInTable)
|
||||
.map((f) => ({
|
||||
name: f.name,
|
||||
title: f.title,
|
||||
value: (item: WidgetDto) => {
|
||||
return <JsonPropertyValueCell property={f} value={item.metadata ? item.metadata[f.name] : null} />;
|
||||
},
|
||||
})) || []),
|
||||
{
|
||||
title: t("widgets.appearance"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<ShowPayloadModalButton description={t("widgets.appearance")} payload={JSON.stringify(item.appearance)} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("shared.created"),
|
||||
value: (item) => <DateCell date={item.createdAt} />,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
|
||||
<AddWidgetModal appConfiguration={appConfiguration} open={addingWidget} onClose={() => setAddingWidget(false)} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function AddWidgetModal({ appConfiguration, open, onClose }: { appConfiguration: AppConfiguration; open: boolean; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState({ name: "" });
|
||||
|
||||
return (
|
||||
<Modal open={open} setOpen={onClose} size="md">
|
||||
<Form method="post" className="inline-block w-full overflow-hidden bg-white p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="create" readOnly hidden />
|
||||
<div className="mt-3 text-center sm:mt-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("widgets.create")}</h3>
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
<InputText
|
||||
title={t("shared.name")}
|
||||
value={state.name}
|
||||
setValue={(e) => setState({ ...state, name: e.toString() })}
|
||||
type="text"
|
||||
name="name"
|
||||
id="name"
|
||||
placeholder={t("shared.name")}
|
||||
required
|
||||
/>
|
||||
<JsonPropertyValuesInput attributes={{}} prefix="metadata" properties={appConfiguration.widgets.metadata || []} />
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<button
|
||||
type="submit"
|
||||
className={clsx(
|
||||
"inline-flex w-full justify-center rounded-md border border-transparent px-4 py-2 text-base font-medium text-white shadow-sm focus:ring-2 focus:ring-offset-2 focus:outline-none sm:col-start-2 sm:text-sm",
|
||||
"bg-foreground text-background"
|
||||
)}
|
||||
>
|
||||
{t("shared.create")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="border-border hover:bg-secondary text-muted-foreground mt-3 inline-flex w-full justify-center rounded-md border bg-white px-4 py-2 text-base font-medium shadow-sm focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 focus:outline-none sm:col-start-1 sm:mt-0 sm:text-sm"
|
||||
onClick={onClose}
|
||||
>
|
||||
{t("shared.back")}
|
||||
</button>
|
||||
</div>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const widgetsRouteDirectory = resolveRepoPath("apps/web/app/routes/app.$tenant/__widgets/widgets");
|
||||
|
||||
function readRoute(fileName: string) {
|
||||
return fs.readFileSync(path.join(widgetsRouteDirectory, fileName), "utf8");
|
||||
}
|
||||
|
||||
describe("tenant widget route auth boundaries", () => {
|
||||
it("requires tenant auth and permissions before listing or creating widgets", () => {
|
||||
const source = readRoute("index.tsx");
|
||||
|
||||
expect(source).toContain('import { requireAuth } from "~/utils/loaders.middleware";');
|
||||
expect(source).toMatch(/export const loader[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.view", tenantId\);/);
|
||||
expect(source).toMatch(/export const action[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.update", tenantId\);/);
|
||||
});
|
||||
|
||||
it("requires tenant auth and tenant-scopes widget mutations by id and tenant", () => {
|
||||
const source = readRoute("$id.tsx");
|
||||
|
||||
expect(source).toContain('import { requireAuth } from "~/utils/loaders.middleware";');
|
||||
expect(source).toMatch(/export const loader[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.view", tenantId\);/);
|
||||
expect(source).toMatch(/export const action[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.update", tenantId\);/);
|
||||
expect(source).toContain("findFirst({\n where: { id: params.id, tenantId },");
|
||||
expect(source).toContain("updateMany({\n where: { id: item.id, tenantId },");
|
||||
expect(source).toContain("deleteMany({\n where: { id: item.id, tenantId },");
|
||||
expect(source).not.toContain("db.widget.update({");
|
||||
expect(source).not.toContain("db.widget.delete({");
|
||||
});
|
||||
});
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
function routeSource(relativePath: string): string {
|
||||
return readFileSync(path.join(resolveRepoPath("apps/web/app/routes/app.$tenant"), relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("core route activity summary i18n contract", () => {
|
||||
it("persists semantic keys for lead activities instead of request-locale text", () => {
|
||||
const sources = ["leads.new.tsx", "leads.$id.tsx", "leads._index.tsx", "leads.board.tsx"]
|
||||
.map(routeSource)
|
||||
.join("\n");
|
||||
for (const key of ["leads.activity.created", "leads.activity.updated", "leads.activity.convertRequested", "activity.runtime.leads.statusChanged"]) {
|
||||
expect(sources).toContain(`summaryText: "${key}"`);
|
||||
}
|
||||
expect(sources).not.toMatch(/summaryText:\s*t\("leads\.activity\./u);
|
||||
});
|
||||
|
||||
it("persists semantic keys for every email-marketing activity", () => {
|
||||
const sources = [
|
||||
"email-marketing/segments.tsx",
|
||||
"email-marketing/campaigns/new.tsx",
|
||||
"email-marketing/campaigns/$id.tsx",
|
||||
"email-marketing/sending-domain.tsx",
|
||||
].map(routeSource).join("\n");
|
||||
for (const suffix of [
|
||||
"segmentCreated",
|
||||
"campaignDraftCreated",
|
||||
"scheduleCancelled",
|
||||
"campaignScheduled",
|
||||
"campaignSendStarted",
|
||||
"sendingDomainConfigured",
|
||||
]) {
|
||||
expect(sources).toContain(`activity.runtime.emailMarketing.${suffix}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
+29
-24
@@ -1,18 +1,24 @@
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import { buildLeadAntiSpamVM, type LeadAntiSpamVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
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 { getLeadAntiSpamConfig, updateLeadAntiSpamConfig, type LeadAntiSpamMode } from "~/utils/integrations/leads/leadService.server";
|
||||
import { LeadAntiSpamAdminPage } from "~/components/screens/leads/LeadAntiSpamAdminPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = { config: LeadAntiSpamConfigRow };
|
||||
type LoaderData = { title: string; vm: LeadAntiSpamVM };
|
||||
const MODES = new Set<LeadAntiSpamMode>(["quarantine", "spam"]);
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
||||
requireLeadPermission(ctx, "leads.admin");
|
||||
return Response.json({ config: await getLeadAntiSpamConfig(ctx.tenantId) } satisfies LoaderData);
|
||||
const config = await getLeadAntiSpamConfig(ctx.tenantId);
|
||||
const title = `${t("leads.antiSpam.title")} | ${process.env.APP_NAME}`;
|
||||
return Response.json({ title, vm: buildLeadAntiSpamVM({ config, canWrite: true }) } satisfies LoaderData);
|
||||
};
|
||||
|
||||
function intValue(form: FormData, name: string): number | undefined {
|
||||
@@ -40,33 +46,32 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
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 ?? ""));
|
||||
return redirect(`${leadAntiSpamAdminPath(params.tenant ?? "")}?toast=${encodeURIComponent("leads.toast.antiSpamSaved")}`);
|
||||
} catch (error) {
|
||||
return leadActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function LeadAntiSpamRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { config } = useLoaderData<LoaderData>();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
useSaveToast(actionData);
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
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>
|
||||
<LeadAntiSpamAdminPage
|
||||
vm={vm}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onSave: (fields) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "save");
|
||||
for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+57
-29
@@ -1,56 +1,84 @@
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import { buildLeadSourceAdminVM, type LeadSourceAdminVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
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 { archiveLeadSource, listAssignableUsers, listLeadSources, upsertLeadSource } from "~/utils/integrations/leads/leadService.server";
|
||||
import { LeadSourcesAdminPage } from "~/components/screens/leads/LeadSourcesAdminPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = { sources: LeadSourceRow[] };
|
||||
type LoaderData = { title: string; vm: LeadSourceAdminVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
||||
requireLeadPermission(ctx, "leads.admin");
|
||||
return Response.json({ sources: await listLeadSources(ctx.tenantId) } satisfies LoaderData);
|
||||
const [sources, assignableUsers] = await Promise.all([listLeadSources(ctx.tenantId), listAssignableUsers(ctx.tenantId)]);
|
||||
const title = `${t("leads.sources.title")} | ${process.env.APP_NAME}`;
|
||||
return Response.json({ title, vm: buildLeadSourceAdminVM({ rows: sources, assignableUsers, canWrite: true }) } 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();
|
||||
const intent = form.get("intent")?.toString();
|
||||
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 ?? ""));
|
||||
if (intent === "upsert") {
|
||||
const source = await upsertLeadSource({
|
||||
tenantId: ctx.tenantId,
|
||||
key: form.get("key")?.toString() ?? "",
|
||||
name: form.get("name")?.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 ?? "")}?toast=${encodeURIComponent("leads.toast.sourceSaved")}`);
|
||||
}
|
||||
// "Delete" in the UI, archive in the data: leads captured through the
|
||||
// source keep pointing at a row that still exists.
|
||||
if (intent === "archive") {
|
||||
const sourceId = form.get("sourceId")?.toString();
|
||||
if (!sourceId) throw badRequestResponse();
|
||||
await archiveLeadSource({ tenantId: ctx.tenantId, sourceId });
|
||||
await auditLeadEvent({ ctx, action: "lead.source_archived", targetType: "lead_source", targetId: sourceId });
|
||||
return redirect(`${leadSourcesAdminPath(params.tenant ?? "")}?toast=${encodeURIComponent("leads.toast.sourceArchived")}`);
|
||||
}
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
return leadActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function LeadSourcesRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { sources } = useLoaderData<LoaderData>();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
useSaveToast(actionData);
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
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>
|
||||
<LeadSourcesAdminPage
|
||||
vm={vm}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onUpsert: ({ key, name, defaultZustaendigerUserId }) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "upsert");
|
||||
form.set("key", key);
|
||||
form.set("name", name);
|
||||
form.set("defaultZustaendigerUserId", defaultZustaendigerUserId);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onDelete: (sourceId) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "archive");
|
||||
form.set("sourceId", sourceId);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
// WF-P8 S04 "Board-Einstellungen" route: one board in depth. The S07 table
|
||||
// (admin.pipelines._index) links here per row. Both routes share
|
||||
// handlePipelineAdminAction, so the write path cannot drift apart.
|
||||
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { buildBoardSettingsVM, buildPipelineAdminVM, type BoardSettingsVM } from "@hivegrid/view-models";
|
||||
import { listPipelinesForAdmin, loadPipelineAdminCounts } from "~/utils/integrations/projects/projectService.server";
|
||||
import { handlePipelineAdminAction } from "~/utils/integrations/projects/pipelineAdminAction.server";
|
||||
import { loadProjectContext, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import { PROJECTS_MODULE_KEY, projectPipelineFieldsAdminPath, projectPipelinesAdminPath, projectsBoardsPath } from "~/utils/integrations/projects/projectRoutePaths";
|
||||
import { BoardSettingsPage } from "~/components/screens/projects/BoardSettingsPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
vm: BoardSettingsVM;
|
||||
title: string;
|
||||
breadcrumbAncestors: { label: string; href: string }[];
|
||||
fieldTemplateHref: string;
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const { t } = await getTranslations(request);
|
||||
const [pipelines, counts] = await Promise.all([
|
||||
listPipelinesForAdmin({ tenantId: ctx.tenantId }),
|
||||
loadPipelineAdminCounts({ tenantId: ctx.tenantId }),
|
||||
]);
|
||||
const adminVM = buildPipelineAdminVM({
|
||||
canAdmin: true,
|
||||
pipelines: pipelines.map((pipeline) => ({
|
||||
id: pipeline.id,
|
||||
name: pipeline.name,
|
||||
typHint: pipeline.typHint,
|
||||
isDefault: pipeline.isDefault,
|
||||
nachfolgePipelineId: pipeline.nachfolgePipelineId,
|
||||
projectCount: counts.byPipeline.get(pipeline.id) ?? 0,
|
||||
updatedAtIso: pipeline.updatedAt.toISOString(),
|
||||
stages: pipeline.stages.map((stage) => ({
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
stageKind: stage.stageKind,
|
||||
winProbability: stage.winProbability,
|
||||
color: stage.color,
|
||||
position: stage.position,
|
||||
projectCount: counts.byStage.get(stage.id) ?? 0,
|
||||
})),
|
||||
accessRules: pipeline.accessRules.map((rule) => ({ id: rule.id, principalType: rule.principalType, principalId: rule.principalId, kannSehen: rule.kannSehen, kannBearbeiten: rule.kannBearbeiten })),
|
||||
fieldConfigs: pipeline.fieldConfigs.map((config) => ({
|
||||
id: config.id,
|
||||
stageId: config.stageId,
|
||||
fieldKey: config.fieldKey,
|
||||
sichtbar: config.sichtbar,
|
||||
pflicht: config.pflicht,
|
||||
reihenfolge: config.reihenfolge,
|
||||
visibilities: config.visibilities.map((visibility) => ({ id: visibility.id, principalType: visibility.principalType, principalId: visibility.principalId, kannSehen: visibility.kannSehen, kannBearbeiten: visibility.kannBearbeiten })),
|
||||
})),
|
||||
})),
|
||||
});
|
||||
const boardId = params.pipelineId ?? "";
|
||||
const vm = buildBoardSettingsVM({
|
||||
boards: adminVM.status === "ready" ? adminVM.data.pipelines : [],
|
||||
boardId,
|
||||
canAdmin: true,
|
||||
});
|
||||
// An unknown board and a board outside the viewer's scope must look the same
|
||||
// from outside — 404, never 403 (Bauprinzip A.5.3).
|
||||
if (vm.status !== "ready") throw new Response(t("shared.notFound"), { status: 404 });
|
||||
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
return Response.json({
|
||||
vm,
|
||||
title: `${vm.data.board.name} | ${process.env.APP_NAME}`,
|
||||
breadcrumbAncestors: [
|
||||
{ label: t("projects.boards.title"), href: projectsBoardsPath(tenantSlug) },
|
||||
{ label: t("projects.admin.title"), href: projectPipelinesAdminPath(tenantSlug) },
|
||||
],
|
||||
fieldTemplateHref: projectPipelineFieldsAdminPath(tenantSlug, boardId),
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
return handlePipelineAdminAction({ tenantId: ctx.tenantId, userId: ctx.userId, formData: await request.formData() });
|
||||
}
|
||||
|
||||
export default function BoardSettingsRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const actionData = useActionData<{ error?: string; ok?: boolean; intent?: string; messageKey?: string }>();
|
||||
useSaveToast(actionData);
|
||||
if (data.vm.status !== "ready") return null;
|
||||
|
||||
return (
|
||||
<BoardSettingsPage
|
||||
data={data.vm.data}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
fieldTemplateHref={data.fieldTemplateHref}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
const fd = new FormData();
|
||||
fd.set("_action", intent);
|
||||
for (const [key, value] of Object.entries(fields)) fd.set(key, value);
|
||||
submit(fd, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: PROJECTS_MODULE_KEY };
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
// WF-P8 S05 (Detail-Schablone Edit-Mode) + M05 (Modal Bestandsfeld).
|
||||
// Route: /admin/pipelines/:pipelineId/fields — reached from S04 board settings
|
||||
// via "Zur Detailfelder-Konfiguration".
|
||||
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import {
|
||||
buildPipelineFieldTemplateVM,
|
||||
isTemplateFieldType,
|
||||
parseCustomFieldOptions,
|
||||
serializeCustomFieldOptions,
|
||||
type CustomFieldOption,
|
||||
type PipelineFieldTemplateData,
|
||||
} from "@hivegrid/view-models";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import {
|
||||
ALWAYS_VISIBLE_FIELD_KEYS,
|
||||
createFieldGroup,
|
||||
deleteFieldGroup,
|
||||
deleteTemplateField,
|
||||
loadPipelineFieldTemplate,
|
||||
moveFieldToGroup,
|
||||
PipelineFieldTemplateError,
|
||||
renameFieldGroup,
|
||||
} from "~/utils/integrations/projects/pipelineFieldTemplateService.server";
|
||||
import { upsertPipelineFieldConfig } from "~/utils/integrations/projects/projectService.server";
|
||||
import { listCustomFieldDefinitions, updateCustomFieldDefinition } from "~/utils/integrations/crm/customFieldService.server";
|
||||
import { CrmServiceError } from "~/utils/integrations/crm/crmService.server";
|
||||
import { loadProjectContext, projectActionErrorResponse, projectNotFoundResponse, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import { projectPipelinesAdminPath, projectsBoardsPath } from "~/utils/integrations/projects/projectRoutePaths";
|
||||
import { PipelineFieldTemplatePage } from "~/components/screens/projects/PipelineFieldTemplatePage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
const FIELD_TEMPLATE_SUCCESS_KEYS: Record<string, string> = {
|
||||
createFieldGroup: "projects.toast.fieldGroupCreated",
|
||||
renameFieldGroup: "projects.toast.fieldGroupRenamed",
|
||||
deleteFieldGroup: "projects.toast.fieldGroupDeleted",
|
||||
moveTemplateField: "projects.toast.fieldMoved",
|
||||
updateTemplateField: "projects.toast.fieldSettingsSaved",
|
||||
updateCustomField: "projects.toast.customFieldDefinitionSaved",
|
||||
deleteTemplateField: "projects.toast.fieldDeleted",
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
data: PipelineFieldTemplateData;
|
||||
title: string;
|
||||
backHref: string;
|
||||
breadcrumbAncestors: { label: string; href: string }[];
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const { t } = await getTranslations(request);
|
||||
try {
|
||||
const [template, definitions] = await Promise.all([
|
||||
loadPipelineFieldTemplate({ tenantId: ctx.tenantId, pipelineId: params.pipelineId! }),
|
||||
listCustomFieldDefinitions({ tenantId: ctx.tenantId, entityType: "projekt" }),
|
||||
]);
|
||||
const data = buildPipelineFieldTemplateVM({
|
||||
...template,
|
||||
definitions: Object.fromEntries(
|
||||
definitions.map((definition) => [
|
||||
definition.key,
|
||||
{ id: definition.id, label: definition.label, datentyp: definition.datentyp, optionen: definition.optionen },
|
||||
])
|
||||
),
|
||||
alwaysVisibleKeys: ALWAYS_VISIBLE_FIELD_KEYS,
|
||||
canEdit: true,
|
||||
});
|
||||
return Response.json({
|
||||
data,
|
||||
title: `${t("projects.fieldTemplate.title")} | ${process.env.APP_NAME}`,
|
||||
backHref: projectPipelinesAdminPath(params.tenant ?? ""),
|
||||
breadcrumbAncestors: [
|
||||
{ label: t("projects.boards.nav"), href: projectsBoardsPath(params.tenant ?? "") },
|
||||
{ label: t("projects.admin.title"), href: projectPipelinesAdminPath(params.tenant ?? "") },
|
||||
],
|
||||
} satisfies LoaderData);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) throw projectNotFoundResponse();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
const parsed = Number(formString(formData, name));
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The options payload of the S05 inspector. `undefined` means "field absent or
|
||||
* unreadable, leave the stored options alone"; an empty list is a real
|
||||
* instruction and clears them. Anything else would turn a malformed request into
|
||||
* silent data loss.
|
||||
*/
|
||||
function parseOptionsPayload(raw: string | null): CustomFieldOption[] | undefined {
|
||||
if (raw === null) return undefined;
|
||||
try {
|
||||
return parseCustomFieldOptions(JSON.parse(raw));
|
||||
} catch {
|
||||
return 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");
|
||||
const pipelineId = params.pipelineId!;
|
||||
try {
|
||||
if (intent === "createFieldGroup") {
|
||||
const group = await createFieldGroup({ tenantId: ctx.tenantId, pipelineId, name: formString(formData, "name") ?? "" });
|
||||
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent], group });
|
||||
}
|
||||
if (intent === "renameFieldGroup") {
|
||||
await renameFieldGroup({
|
||||
tenantId: ctx.tenantId,
|
||||
pipelineId,
|
||||
groupId: formString(formData, "groupId") ?? "",
|
||||
name: formString(formData, "name") ?? "",
|
||||
});
|
||||
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
|
||||
}
|
||||
if (intent === "deleteFieldGroup") {
|
||||
await deleteFieldGroup({ tenantId: ctx.tenantId, pipelineId, groupId: formString(formData, "groupId") ?? "" });
|
||||
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
|
||||
}
|
||||
if (intent === "moveTemplateField") {
|
||||
// An empty groupId means "back into the Bestandsfelder pool".
|
||||
const rawGroupId = formString(formData, "groupId");
|
||||
await moveFieldToGroup({
|
||||
tenantId: ctx.tenantId,
|
||||
pipelineId,
|
||||
fieldConfigId: formString(formData, "fieldConfigId") ?? "",
|
||||
groupId: rawGroupId ? rawGroupId : null,
|
||||
reihenfolge: formNumber(formData, "reihenfolge"),
|
||||
});
|
||||
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
|
||||
}
|
||||
if (intent === "updateTemplateField") {
|
||||
await upsertPipelineFieldConfig({
|
||||
tenantId: ctx.tenantId,
|
||||
pipelineId,
|
||||
fieldKey: formString(formData, "fieldKey") ?? "",
|
||||
stageId: null,
|
||||
hinweis: formString(formData, "hinweis"),
|
||||
pflicht: Boolean(formString(formData, "pflicht")),
|
||||
pflichtAbStageId: formString(formData, "pflichtAbStageId") || null,
|
||||
gesperrt: Boolean(formString(formData, "gesperrt")),
|
||||
});
|
||||
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
|
||||
}
|
||||
if (intent === "updateCustomField") {
|
||||
// The label, the type and its options live on the tenant-wide
|
||||
// CustomFieldDefinition, not on this pipeline's field config, so this is a
|
||||
// separate intent. The options arrive as one JSON field: order matters and
|
||||
// each entry carries a label and a colour.
|
||||
const datentyp = formString(formData, "datentyp");
|
||||
const optionen = parseOptionsPayload(formString(formData, "optionen"));
|
||||
// An empty label would leave the field nameless in every screen that reads
|
||||
// the definition, so a blank submission keeps the stored one.
|
||||
const label = formString(formData, "label")?.trim();
|
||||
await updateCustomFieldDefinition({
|
||||
tenantId: ctx.tenantId,
|
||||
definitionId: formString(formData, "definitionId") ?? "",
|
||||
...(label ? { label } : {}),
|
||||
...(datentyp && isTemplateFieldType(datentyp) ? { datentyp } : {}),
|
||||
...(optionen === undefined ? {} : { optionen: serializeCustomFieldOptions(optionen) }),
|
||||
});
|
||||
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
|
||||
}
|
||||
if (intent === "deleteTemplateField") {
|
||||
await deleteTemplateField({ tenantId: ctx.tenantId, pipelineId, fieldConfigId: formString(formData, "fieldConfigId") ?? "" });
|
||||
return Response.json({ ok: true, intent, messageKey: FIELD_TEMPLATE_SUCCESS_KEYS[intent] });
|
||||
}
|
||||
return Response.json({ intent, error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
if (error instanceof PipelineFieldTemplateError || error instanceof CrmServiceError) {
|
||||
// The retype guard is a CrmServiceError: it belongs to the CRM definition,
|
||||
// not to this pipeline's template, and the actor needs its plain text.
|
||||
return Response.json({ intent, error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export default function PipelineFieldTemplateRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
|
||||
useSaveToast(actionData);
|
||||
|
||||
return (
|
||||
<PipelineFieldTemplatePage
|
||||
data={data.data}
|
||||
backHref={data.backHref}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
const formData = new FormData();
|
||||
formData.set("_action", intent);
|
||||
for (const [key, value] of Object.entries(fields ?? {})) formData.set(key, value);
|
||||
submit(formData, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+101
-166
@@ -1,183 +1,118 @@
|
||||
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";
|
||||
// WF-P8 S07 "Boards-Übersicht" route: the board table. Each row links to S04
|
||||
// (admin.pipelines.$pipelineId) for the per-board configuration. Both routes
|
||||
// share handlePipelineAdminAction so the write path stays single-sourced.
|
||||
|
||||
type LoaderData = { pipelines: Array<PipelineRow & { stages: PipelineStageRow[] }> };
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { buildPipelineAdminVM, type PipelineAdminVM } from "@hivegrid/view-models";
|
||||
import {
|
||||
ensureDefaultSalesPipeline,
|
||||
listPipelinesForAdmin,
|
||||
loadPipelineAdminCounts,
|
||||
} from "~/utils/integrations/projects/projectService.server";
|
||||
import { handlePipelineAdminAction } from "~/utils/integrations/projects/pipelineAdminAction.server";
|
||||
import { loadProjectContext, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import {
|
||||
PROJECTS_MODULE_KEY,
|
||||
projectBoardSettingsPath,
|
||||
projectLostReasonsAdminPath,
|
||||
projectsBoardsPath,
|
||||
} from "~/utils/integrations/projects/projectRoutePaths";
|
||||
import { PipelineAdminPage } from "~/components/screens/projects/PipelineAdminPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
vm: PipelineAdminVM;
|
||||
title: string;
|
||||
breadcrumbAncestors: { label: string; href: string }[];
|
||||
lostReasonsHref: string;
|
||||
tenantSlug: string;
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const ctx = requireProjectPermission(await loadProjectContext({ request, params, requireModule: true }), "projects.admin");
|
||||
const { t } = await getTranslations(request);
|
||||
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);
|
||||
const [pipelines, counts] = await Promise.all([
|
||||
listPipelinesForAdmin({ tenantId: ctx.tenantId }),
|
||||
loadPipelineAdminCounts({ tenantId: ctx.tenantId }),
|
||||
]);
|
||||
const vm = buildPipelineAdminVM({
|
||||
canAdmin: true,
|
||||
pipelines: pipelines.map((pipeline) => ({
|
||||
id: pipeline.id,
|
||||
name: pipeline.name,
|
||||
typHint: pipeline.typHint,
|
||||
isDefault: pipeline.isDefault,
|
||||
nachfolgePipelineId: pipeline.nachfolgePipelineId,
|
||||
projectCount: counts.byPipeline.get(pipeline.id) ?? 0,
|
||||
updatedAtIso: pipeline.updatedAt.toISOString(),
|
||||
stages: pipeline.stages.map((stage) => ({
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
stageKind: stage.stageKind,
|
||||
winProbability: stage.winProbability,
|
||||
color: stage.color,
|
||||
position: stage.position,
|
||||
projectCount: counts.byStage.get(stage.id) ?? 0,
|
||||
})),
|
||||
accessRules: pipeline.accessRules.map((rule) => ({ id: rule.id, principalType: rule.principalType, principalId: rule.principalId, kannSehen: rule.kannSehen, kannBearbeiten: rule.kannBearbeiten })),
|
||||
fieldConfigs: pipeline.fieldConfigs.map((config) => ({
|
||||
id: config.id,
|
||||
stageId: config.stageId,
|
||||
fieldKey: config.fieldKey,
|
||||
sichtbar: config.sichtbar,
|
||||
pflicht: config.pflicht,
|
||||
reihenfolge: config.reihenfolge,
|
||||
visibilities: config.visibilities.map((visibility) => ({ id: visibility.id, principalType: visibility.principalType, principalId: visibility.principalId, kannSehen: visibility.kannSehen, kannBearbeiten: visibility.kannBearbeiten })),
|
||||
})),
|
||||
})),
|
||||
});
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
return Response.json({
|
||||
vm,
|
||||
title: `${t("projects.admin.title")} | ${process.env.APP_NAME}`,
|
||||
breadcrumbAncestors: [{ label: t("projects.boards.title"), href: projectsBoardsPath(tenantSlug) }],
|
||||
lostReasonsHref: projectLostReasonsAdminPath(tenantSlug),
|
||||
tenantSlug,
|
||||
} 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 === "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);
|
||||
}
|
||||
return handlePipelineAdminAction({ tenantId: ctx.tenantId, userId: ctx.userId, formData: await request.formData() });
|
||||
}
|
||||
|
||||
export default function PipelinesAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const actionData = useActionData<{ error?: string; ok?: boolean; intent?: string; messageKey?: string }>();
|
||||
useSaveToast(actionData);
|
||||
const vmData = data.vm.status === "ready" ? data.vm.data : null;
|
||||
|
||||
if (!vmData) return null;
|
||||
|
||||
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>
|
||||
<PipelineAdminPage
|
||||
data={vmData}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
lostReasonsHref={data.lostReasonsHref}
|
||||
settingsHref={(pipelineId) => projectBoardSettingsPath(data.tenantSlug, pipelineId)}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
const fd = new FormData();
|
||||
fd.set("_action", intent);
|
||||
for (const [key, value] of Object.entries(fields)) fd.set(key, value);
|
||||
submit(fd, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: PROJECTS_MODULE_KEY };
|
||||
+75
-23
@@ -1,15 +1,47 @@
|
||||
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 { useActionData, useLoaderData, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { buildLostReasonAdminVM, type LostReasonAdminVM } from "@hivegrid/view-models";
|
||||
import { archiveLostReason, listLostReasonsForAdmin, reactivateLostReason, 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";
|
||||
import { PROJECTS_MODULE_KEY, projectsBoardsPath } from "~/utils/integrations/projects/projectRoutePaths";
|
||||
import { LostReasonAdminPage } from "~/components/screens/projects/LostReasonAdminPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = { reasons: LostReasonRow[] };
|
||||
type LoaderData = {
|
||||
vm: LostReasonAdminVM;
|
||||
title: string;
|
||||
breadcrumbAncestors: { label: string; href: string }[];
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
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);
|
||||
const { t } = await getTranslations(request);
|
||||
const { rows, insights } = await listLostReasonsForAdmin({ tenantId: ctx.tenantId });
|
||||
const vm = buildLostReasonAdminVM({
|
||||
canAdmin: true,
|
||||
insights,
|
||||
reasons: rows.map((reason) => ({
|
||||
id: reason.id,
|
||||
name: reason.name,
|
||||
beschreibung: reason.beschreibung,
|
||||
kategorie: reason.kategorie,
|
||||
position: reason.position,
|
||||
isDemoData: reason.isDemoData,
|
||||
istVorlage: reason.istVorlage,
|
||||
archivedAt: reason.archivedAt?.toISOString() ?? null,
|
||||
projectCount: reason.projectCount,
|
||||
lastUsedIso: reason.lastUsedAt?.toISOString() ?? null,
|
||||
})),
|
||||
});
|
||||
return Response.json({
|
||||
vm,
|
||||
title: `${t("projects.lostReasonsAdmin.title")} | ${process.env.APP_NAME}`,
|
||||
// Shell breadcrumb: tenant > Boards > Verlustgründe (Boards links to the boards page).
|
||||
breadcrumbAncestors: [{ label: t("projects.boards.nav"), href: projectsBoardsPath(params.tenant ?? "") }],
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
function formString(formData: FormData, name: string): string | null {
|
||||
@@ -34,36 +66,56 @@ export async function action({ request, params }: ActionFunctionArgs) {
|
||||
tenantId: ctx.tenantId,
|
||||
reasonId: formString(formData, "reasonId"),
|
||||
name: formString(formData, "name") ?? "",
|
||||
beschreibung: formString(formData, "beschreibung"),
|
||||
kategorie: formString(formData, "kategorie"),
|
||||
position: formNumber(formData, "position"),
|
||||
});
|
||||
return Response.json({ ok: true, reason });
|
||||
return Response.json({
|
||||
ok: true,
|
||||
intent,
|
||||
messageKey: formString(formData, "reasonId") ? "projects.toast.lostReasonUpdated" : "projects.toast.lostReasonCreated",
|
||||
reason,
|
||||
});
|
||||
}
|
||||
if (intent === "archiveLostReason") {
|
||||
const reason = await archiveLostReason({ tenantId: ctx.tenantId, reasonId: formString(formData, "reasonId") ?? "" });
|
||||
return Response.json({ ok: true, reason });
|
||||
return Response.json({ ok: true, intent, messageKey: "projects.toast.lostReasonArchived", reason });
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
if (intent === "reactivateLostReason") {
|
||||
const reason = await reactivateLostReason({ tenantId: ctx.tenantId, reasonId: formString(formData, "reasonId") ?? "" });
|
||||
return Response.json({ ok: true, intent, messageKey: "projects.toast.lostReasonReactivated", reason });
|
||||
}
|
||||
return Response.json({ intent, error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export default function LostReasonsAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
|
||||
useSaveToast(actionData);
|
||||
const vmData = data.vm.status === "ready" ? data.vm.data : null;
|
||||
|
||||
if (!vmData) return null;
|
||||
|
||||
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>
|
||||
<LostReasonAdminPage
|
||||
data={vmData}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
const fd = new FormData();
|
||||
fd.set("_action", intent);
|
||||
for (const [key, value] of Object.entries(fields)) fd.set(key, value);
|
||||
submit(fd, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: PROJECTS_MODULE_KEY };
|
||||
+45
-49
@@ -1,35 +1,39 @@
|
||||
import { Form, useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
// R-P9a — acceptance-form template admin route (restored; the original route
|
||||
// was removed in the seat-billing recut while the backend services stayed).
|
||||
// Loader/action delegate to auftragService; the screen is interim UI (AD-28).
|
||||
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { buildAcceptanceFormTemplatesAdminVM } from "@hivegrid/view-models";
|
||||
import {
|
||||
listAcceptanceFormTemplates,
|
||||
upsertAcceptanceFormTemplate,
|
||||
type AcceptanceFormTemplateRow,
|
||||
} from "~/utils/integrations/projects/auftragService.server";
|
||||
import { loadProjectContext, projectActionErrorResponse, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import { projectPipelinesAdminPath } from "~/utils/integrations/projects/projectRoutePaths";
|
||||
import { AcceptanceFormTemplatesAdminPage } from "~/components/screens/projects/AcceptanceFormTemplatesAdminPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = { templates: AcceptanceFormTemplateRow[] };
|
||||
type LoaderData = { tenantSlug: string; title: string; templates: AcceptanceFormTemplateRow[] };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
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 { t } = await getTranslations(request);
|
||||
const templates = await listAcceptanceFormTemplates({ tenantId: ctx.tenantId });
|
||||
return Response.json({ templates } satisfies LoaderData);
|
||||
return Response.json({
|
||||
tenantSlug: params.tenant ?? "",
|
||||
title: `${t("projects.acceptanceFormsAdmin.title")} | ${process.env.APP_NAME}`,
|
||||
templates,
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
@@ -38,52 +42,44 @@ export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const intent = formString(formData, "_action");
|
||||
try {
|
||||
if (intent === "upsertAcceptanceFormTemplate") {
|
||||
const formId = formString(formData, "formId");
|
||||
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"),
|
||||
...(formId === null ? {} : { formId: formId || null }),
|
||||
isDefault: formString(formData, "isDefault") === "1" || undefined,
|
||||
});
|
||||
return Response.json({ ok: true, template });
|
||||
return Response.json({ ok: true, intent, messageKey: "projects.toast.acceptanceTemplateSaved", templateId: template.id });
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
return Response.json({ intent, error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export default function AcceptanceFormsAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
export default function AcceptanceFormTemplatesAdminRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
|
||||
useSaveToast(actionData);
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const vm = buildAcceptanceFormTemplatesAdminVM({ templates: data.templates });
|
||||
|
||||
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>
|
||||
<AcceptanceFormTemplatesAdminPage
|
||||
vm={vm}
|
||||
backHref={projectPipelinesAdminPath(data.tenantSlug)}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
const fd = new FormData();
|
||||
fd.set("_action", intent);
|
||||
for (const [key, value] of Object.entries(fields)) fd.set(key, value);
|
||||
submit(fd, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+59
-52
@@ -1,31 +1,45 @@
|
||||
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";
|
||||
// R-P9a — project template admin route (restored; the original route was
|
||||
// removed in the seat-billing recut while the backend services stayed).
|
||||
// Loader/action delegate to auftragService; the screen is interim UI (AD-28).
|
||||
|
||||
type LoaderData = { templates: ProjectTemplateRow[] };
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { buildProjectTemplatesAdminVM } from "@hivegrid/view-models";
|
||||
import { listProjectTemplates, upsertProjectTemplate, type ProjectTemplateRow } from "~/utils/integrations/projects/auftragService.server";
|
||||
import { listPipelinesForAdmin } from "~/utils/integrations/projects/projectService.server";
|
||||
import { loadProjectContext, projectActionErrorResponse, requireProjectPermission } from "~/utils/integrations/projects/projectAccess.server";
|
||||
import { projectPipelinesAdminPath } from "~/utils/integrations/projects/projectRoutePaths";
|
||||
import { ProjectTemplatesAdminPage } from "~/components/screens/projects/ProjectTemplatesAdminPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type PipelineOption = { id: string; name: string; stages: { id: string; name: string }[] };
|
||||
type LoaderData = { tenantSlug: string; title: string; templates: ProjectTemplateRow[]; pipelines: PipelineOption[] };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
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);
|
||||
const { t } = await getTranslations(request);
|
||||
const [templates, pipelines] = await Promise.all([
|
||||
listProjectTemplates({ tenantId: ctx.tenantId }),
|
||||
listPipelinesForAdmin({ tenantId: ctx.tenantId }),
|
||||
]);
|
||||
return Response.json({
|
||||
tenantSlug: params.tenant ?? "",
|
||||
title: `${t("projects.templatesAdmin.title")} | ${process.env.APP_NAME}`,
|
||||
templates,
|
||||
pipelines: pipelines.map((pipeline) => ({
|
||||
id: pipeline.id,
|
||||
name: pipeline.name,
|
||||
stages: pipeline.stages.map((stage) => ({ id: stage.id, name: stage.name })),
|
||||
})),
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
@@ -38,49 +52,42 @@ export async function action({ request, params }: ActionFunctionArgs) {
|
||||
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")),
|
||||
defaultPipelineId: formString(formData, "defaultPipelineId") || null,
|
||||
defaultStageId: formString(formData, "defaultStageId") || null,
|
||||
defaultMembers: [],
|
||||
defaultTasks: [],
|
||||
customFields: {},
|
||||
});
|
||||
return Response.json({ ok: true, template });
|
||||
return Response.json({ ok: true, intent, messageKey: "projects.toast.projectTemplateSaved", templateId: template.id });
|
||||
}
|
||||
return Response.json({ error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
return Response.json({ intent, error: "projects.error.unsupportedAction" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return projectActionErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export default function ProjectTemplatesAdminRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
|
||||
useSaveToast(actionData);
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const vm = buildProjectTemplatesAdminVM({ templates: data.templates, pipelines: data.pipelines });
|
||||
|
||||
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>
|
||||
<ProjectTemplatesAdminPage
|
||||
vm={vm}
|
||||
backHref={projectPipelinesAdminPath(data.tenantSlug)}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
const fd = new FormData();
|
||||
fd.set("_action", intent);
|
||||
for (const [key, value] of Object.entries(fields)) fd.set(key, value);
|
||||
submit(fd, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { redirect, type LoaderFunctionArgs } from "react-router";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
export { default, ErrorBoundary } from "../settings/integrations/api/index";
|
||||
|
||||
export const loader = ({ request, params }: LoaderFunctionArgs) =>
|
||||
redirect(`${UrlUtils.currentTenantUrl(params, "settings/integrations/api")}${new URL(request.url).search}`);
|
||||
@@ -0,0 +1,7 @@
|
||||
import { redirect, type LoaderFunctionArgs } from "react-router";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
export { default } from "../settings/integrations/api/keys";
|
||||
|
||||
export const loader = ({ request, params }: LoaderFunctionArgs) =>
|
||||
redirect(`${UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys")}${new URL(request.url).search}`);
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { redirect, type LoaderFunctionArgs } from "react-router";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
export { action, default } from "../../settings/integrations/api/keys/$id";
|
||||
|
||||
export const loader = ({ request, params }: LoaderFunctionArgs) =>
|
||||
redirect(`${UrlUtils.currentTenantUrl(params, `settings/integrations/api/keys/${params.id ?? ""}`)}${new URL(request.url).search}`);
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { redirect, type LoaderFunctionArgs } from "react-router";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
export { action, default } from "../../settings/integrations/api/keys/new";
|
||||
|
||||
export const loader = ({ request, params }: LoaderFunctionArgs) =>
|
||||
redirect(`${UrlUtils.currentTenantUrl(params, "settings/integrations/api/keys/new")}${new URL(request.url).search}`);
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { loader as overviewLoader } from "./index";
|
||||
import { loader as keysLoader } from "./keys";
|
||||
import { loader as keyDetailLoader } from "./keys/$id";
|
||||
import { loader as newKeyLoader } from "./keys/new";
|
||||
import { loader as logsLoader } from "./logs";
|
||||
|
||||
type LegacyLoader = (args: LoaderFunctionArgs) => Response | Promise<Response>;
|
||||
|
||||
async function expectSettingsRedirect(loader: LegacyLoader, path: string, expectedLocation: string, params: Record<string, string>) {
|
||||
const response = await loader({
|
||||
request: new Request(`https://app.example.test${path}`),
|
||||
params,
|
||||
context: {},
|
||||
} as unknown as LoaderFunctionArgs);
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toBe(expectedLocation);
|
||||
}
|
||||
|
||||
describe("legacy tenant API routes", () => {
|
||||
it.each([
|
||||
[overviewLoader, "/acme/api?period=7d", "/acme/settings/integrations/api?period=7d", { tenant: "acme" }],
|
||||
[logsLoader, "/acme/api/logs?page=2", "/acme/settings/integrations/api/logs?page=2", { tenant: "acme" }],
|
||||
[keysLoader, "/acme/api/keys", "/acme/settings/integrations/api/keys", { tenant: "acme" }],
|
||||
[newKeyLoader, "/acme/api/keys/new", "/acme/settings/integrations/api/keys/new", { tenant: "acme" }],
|
||||
[keyDetailLoader, "/acme/api/keys/key-1", "/acme/settings/integrations/api/keys/key-1", { tenant: "acme", id: "key-1" }],
|
||||
])("redirects %s into the settings workspace", async (loader, path, expectedLocation, params) => {
|
||||
await expectSettingsRedirect(loader as LegacyLoader, path as string, expectedLocation as string, params as Record<string, string>);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { redirect, type LoaderFunctionArgs } from "react-router";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
export { default } from "../settings/integrations/api/logs";
|
||||
|
||||
export const loader = ({ request, params }: LoaderFunctionArgs) =>
|
||||
redirect(`${UrlUtils.currentTenantUrl(params, "settings/integrations/api/logs")}${new URL(request.url).search}`);
|
||||
+26
-199
@@ -1,10 +1,17 @@
|
||||
import { Form, Link, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { AutomationEditorPage } from "~/components/screens/automation/AutomationEditorPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { handleAutomationEditorAction, loadAutomationEditorVM, type AutomationEditorActionData, type AutomationEditorVM } from "~/services/automation/automation.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
|
||||
type LoaderData = AutomationEditorVM & { title: string };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationEditorVM({ request, params }));
|
||||
const [{ t }, vm] = await Promise.all([getTranslations(request), loadAutomationEditorVM({ request, params })]);
|
||||
return Response.json({ ...vm, title: `${vm.rule.name} · ${t("automation.editor.graph.title")} | ${process.env.APP_NAME}` } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
@@ -12,204 +19,24 @@ export async function action({ request, params }: ActionFunctionArgs) {
|
||||
}
|
||||
|
||||
export default function AutomationEditorRoute() {
|
||||
const data = useLoaderData() as AutomationEditorVM;
|
||||
const data = useLoaderData() as LoaderData;
|
||||
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 ?? "";
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
|
||||
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>
|
||||
<AutomationEditorPage
|
||||
vm={data}
|
||||
actionData={actionData}
|
||||
submitting={navigation.state !== "idle"}
|
||||
actions={{
|
||||
onSubmit: (intent, fields = {}) => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", intent);
|
||||
for (const [key, value] of Object.entries(fields)) formData.set(key, value);
|
||||
submit(formData, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+49
-78
@@ -1,86 +1,57 @@
|
||||
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";
|
||||
import { useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
handleAutomationExecutionDetailAction,
|
||||
loadAutomationExecutionDetailVM,
|
||||
type AutomationExecutionDetailActionData,
|
||||
type AutomationExecutionDetailVM,
|
||||
} from "~/services/automation/automation.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { AutomationExecutionDetailPage } from "~/components/screens/automation/AutomationExecutionDetailPage";
|
||||
|
||||
type LoaderData = AutomationExecutionDetailVM & { title: string };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationExecutionDetailVM({ request, params }));
|
||||
const [{ t }, vm] = await Promise.all([getTranslations(request), loadAutomationExecutionDetailVM({ request, params })]);
|
||||
return Response.json({ ...vm, title: `${vm.rule.name} · ${t("automation.executions.detailTitle")} | ${process.env.APP_NAME}` } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
return Response.json(await handleAutomationExecutionDetailAction({ request, params }));
|
||||
}
|
||||
|
||||
export default function AutomationExecutionDetailRoute() {
|
||||
const data = useLoaderData() as AutomationExecutionDetailVM;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const data = useLoaderData() as LoaderData;
|
||||
const actionData = useActionData() as AutomationExecutionDetailActionData | undefined;
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
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>
|
||||
<AutomationExecutionDetailPage
|
||||
vm={data}
|
||||
actionData={actionData}
|
||||
submitting={navigation.state !== "idle"}
|
||||
actions={{
|
||||
onReverse: (confirmationPhrase) => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "reverse");
|
||||
formData.set("confirmationPhrase", confirmationPhrase);
|
||||
submit(formData, { method: "post" });
|
||||
},
|
||||
onRetry: () => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "retry");
|
||||
submit(formData, { method: "post" });
|
||||
},
|
||||
onResume: (stepExecutionId) => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "resume");
|
||||
formData.set("stepExecutionId", stepExecutionId);
|
||||
submit(formData, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+26
-39
@@ -1,45 +1,32 @@
|
||||
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";
|
||||
import { useActionData, useLoaderData } from "react-router";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
handleAutomationExecutionsAction,
|
||||
loadAutomationExecutionsVM,
|
||||
type AutomationExecutionsActionData,
|
||||
type AutomationExecutionListVM,
|
||||
} from "~/services/automation/automation.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { AutomationExecutionsPage } from "~/components/screens/automation/AutomationExecutionsPage";
|
||||
|
||||
type LoaderData = AutomationExecutionListVM & { title: string };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationExecutionsVM({ request, params }));
|
||||
const [{ t }, vm] = await Promise.all([getTranslations(request), loadAutomationExecutionsVM({ request, params })]);
|
||||
return Response.json({ ...vm, title: `${vm.rule.name} · ${t("automation.sections.executions")} | ${process.env.APP_NAME}` } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
await validateCSRFToken(request);
|
||||
return handleAutomationExecutionsAction({ 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>
|
||||
);
|
||||
const data = useLoaderData() as LoaderData;
|
||||
const actionData = useActionData() as AutomationExecutionsActionData | undefined;
|
||||
return <AutomationExecutionsPage vm={data} actionData={actionData} />;
|
||||
}
|
||||
+32
-59
@@ -1,65 +1,38 @@
|
||||
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";
|
||||
import { redirect, useActionData, useLoaderData } from "react-router";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
handleAutomationListAction,
|
||||
loadAutomationListVM,
|
||||
type AutomationListActionData,
|
||||
type AutomationListVM,
|
||||
} from "~/services/automation/automation.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { AutomationListPage } from "~/components/screens/automation/AutomationListPage";
|
||||
|
||||
type LoaderData = AutomationListVM & { title: string };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationListVM({ request, params }));
|
||||
const [{ t }, vm] = await Promise.all([getTranslations(request), loadAutomationListVM({ request, params })]);
|
||||
return Response.json({ ...vm, title: `${t("automation.title")} | ${process.env.APP_NAME}` } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
await validateCSRFToken(request);
|
||||
const result = await handleAutomationListAction({ request, params });
|
||||
if (result.ok && result.redirectTo) {
|
||||
const target = new URL(result.redirectTo, request.url);
|
||||
target.searchParams.set("toast", result.messageKey);
|
||||
return redirect(target.toString());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
const data = useLoaderData() as LoaderData;
|
||||
const actionData = useActionData() as AutomationListActionData | undefined;
|
||||
return <AutomationListPage vm={data} actionData={actionData} />;
|
||||
}
|
||||
+15
-50
@@ -1,11 +1,18 @@
|
||||
import { Form, Link, redirect, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { redirect, useLoaderData } from "react-router";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createAutomationRuleFromTemplateForRoute, loadAutomationTemplateCatalogVM, type AutomationTemplateCatalogVM } from "~/services/automation/automation.server";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { AutomationTemplatesPage } from "~/components/screens/automation/AutomationTemplatesPage";
|
||||
|
||||
type LoaderData = AutomationTemplateCatalogVM & { title: string };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
return Response.json(await loadAutomationTemplateCatalogVM({ request, params }));
|
||||
const [{ t }, vm] = await Promise.all([getTranslations(request), loadAutomationTemplateCatalogVM({ request, params })]);
|
||||
return Response.json({ ...vm, title: `${t("automation.templatesPage.title")} | ${process.env.APP_NAME}` } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
@@ -18,56 +25,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
|
||||
templateId: String(formData.get("templateId") ?? ""),
|
||||
name: String(formData.get("ruleName") ?? "").trim() || undefined,
|
||||
});
|
||||
return redirect(result.editUrl);
|
||||
const target = new URL(result.editUrl, request.url);
|
||||
target.searchParams.set("toast", "automation.list.actions.createdFromTemplate");
|
||||
return redirect(target.toString());
|
||||
}
|
||||
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>
|
||||
);
|
||||
const data = useLoaderData() as LoaderData;
|
||||
return <AutomationTemplatesPage vm={data} />;
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
// AK-P16b · provider availability route (M06 Block F). Every provider edits
|
||||
// their OWN weekly rules + date exceptions (bookings.read_own covers own
|
||||
// availability; foreign availability via bookings.admin is deferred). The
|
||||
// editor submits one serialized payload, replaced atomically by
|
||||
// AvailabilityService. Module off -> locked empty; missing permission -> 404.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { buildAvailabilityVM, parseAvailabilityPayload, type AvailabilityVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { APP_TIME_ZONE } from "~/locale/format";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { loadBookingContext, requireBookingPermission, BOOKING_PERMISSIONS } from "~/modules/booking/routes/bookingAccess.server";
|
||||
import { BOOKING_MODULE_KEY, notFoundResponse } from "~/modules/booking/routes/bookingRoutePaths";
|
||||
import { listProviderAvailability, replaceProviderAvailability, AvailabilityValidationError } from "~/modules/booking/services/AvailabilityService.server";
|
||||
import { AvailabilityPage } from "~/components/screens/booking/AvailabilityPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: AvailabilityVM };
|
||||
type ActionData = { ok: true } | { ok: false; errorKey: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadBookingContext({ request, params });
|
||||
const title = `${t("bookings.availability.title")} | ${process.env.APP_NAME}`;
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, vm: buildAvailabilityVM({ rules: [], exceptions: [], fallbackTimezone: APP_TIME_ZONE }) } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn);
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const settings = await listProviderAvailability(ctx.tenantId, ctx.userId);
|
||||
const vm = buildAvailabilityVM({
|
||||
rules: settings.rules.map((rule) => ({ id: rule.id, dayOfWeek: rule.dayOfWeek, startTime: rule.startTime, endTime: rule.endTime, timezone: rule.timezone })),
|
||||
exceptions: settings.exceptions.map((exception) => ({
|
||||
id: exception.id,
|
||||
date: exception.date,
|
||||
kind: exception.kind,
|
||||
startTime: exception.startTime,
|
||||
endTime: exception.endTime,
|
||||
reason: exception.reason,
|
||||
timezone: exception.timezone,
|
||||
})),
|
||||
fallbackTimezone: APP_TIME_ZONE,
|
||||
});
|
||||
return Response.json({ title, 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 form = await request.formData();
|
||||
const parsed = parseAvailabilityPayload((form.get("payload") as string | null) ?? "");
|
||||
if (!parsed.ok) {
|
||||
return Response.json({ ok: false, errorKey: parsed.errorKey } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await replaceProviderAvailability({
|
||||
tenantId: ctx.tenantId,
|
||||
providerUserId: ctx.userId,
|
||||
rules: parsed.payload.rules,
|
||||
exceptions: parsed.payload.exceptions,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof AvailabilityValidationError) {
|
||||
return Response.json({ ok: false, errorKey: error.code } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return Response.json({ ok: true } satisfies ActionData);
|
||||
};
|
||||
|
||||
export default function AvailabilityRoute() {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
return <AvailabilityPage vm={vm} csrf={rootData.csrf ?? null} actionData={actionData ?? null} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: BOOKING_MODULE_KEY };
|
||||
+122
-108
@@ -1,37 +1,58 @@
|
||||
// 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.
|
||||
// / re-assign) through the interim ~/ui screen (AD-28) incl. the reschedule slot
|
||||
// picker (loader recomputes candidate slots per `?slotsDate=` via the slot engine)
|
||||
// and the admin re-assign provider picker. 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 { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData, useNavigate, useParams } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import { formatInTimeZone } from "date-fns-tz";
|
||||
import { buildBookingDetailVM, type BookingDetailVM, type BookingProviderOption, type RescheduleSlotOption } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { formatDateTime } from "~/locale/format";
|
||||
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 { loadBookingContext, requireBookingPermission, requireAppointmentOwner, bookingHasPermission, 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 { loadSlotsForDate } from "~/modules/booking/services/SlotQueryService.server";
|
||||
import { getTenantUsers } from "~/utils/db/tenants.db.server";
|
||||
import { markAppointmentHeld, markAppointmentNoShow, cancelAppointment, rescheduleAppointment, reassignAppointment } from "~/modules/booking/services/BookingLifecycleService.server";
|
||||
import { BookingDetailPage } from "~/components/screens/booking/BookingDetailPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
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: BookingDetailVM;
|
||||
/** Candidate slots for `?slotsDate=`; null when no date was requested. */
|
||||
rescheduleSlots: RescheduleSlotOption[] | null;
|
||||
slotsDate: string | null;
|
||||
/** Names the bookings list the detail was reached through (tenant > Buchungen > Buchung). */
|
||||
breadcrumbAncestors: { label: string; href: string }[];
|
||||
};
|
||||
|
||||
type LoaderData = { title: string; vm: DetailVM };
|
||||
type ActionData = {
|
||||
intent?: string;
|
||||
ok?: true;
|
||||
messageKey?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
const BOOKING_SUCCESS_KEYS: Readonly<Record<string, string>> = {
|
||||
held: "bookings.toast.held",
|
||||
no_show: "bookings.toast.noShow",
|
||||
cancel: "bookings.toast.cancelled",
|
||||
reschedule: "bookings.toast.rescheduled",
|
||||
reassign: "bookings.toast.reassigned",
|
||||
};
|
||||
|
||||
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/u;
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const ctx = await loadBookingContext({ request, params, requireModule: true });
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn);
|
||||
|
||||
@@ -41,19 +62,54 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
}
|
||||
requireAppointmentOwner(ctx, appt.providerUserId);
|
||||
|
||||
const vm: DetailVM = {
|
||||
const canWrite = bookingHasPermission(ctx, BOOKING_PERMISSIONS.write);
|
||||
const canAdmin = ctx.permissions.includes(BOOKING_PERMISSIONS.admin);
|
||||
const now = new Date();
|
||||
|
||||
// Re-assign candidates (admin only): active tenant members.
|
||||
let providerOptions: BookingProviderOption[] = [];
|
||||
if (canAdmin) {
|
||||
const members = await getTenantUsers(ctx.tenantId);
|
||||
providerOptions = members.map((member) => ({
|
||||
id: member.userId,
|
||||
label: [member.user.firstName, member.user.lastName].filter(Boolean).join(" ") || member.user.email,
|
||||
}));
|
||||
}
|
||||
|
||||
// Reschedule picker: recompute the provider's bookable slots for a requested
|
||||
// date via the same engine the public flow uses (busy calendar incl. Google).
|
||||
const url = new URL(request.url);
|
||||
const slotsDateParam = url.searchParams.get("slotsDate");
|
||||
const slotsDate = slotsDateParam && DATE_RE.test(slotsDateParam) ? slotsDateParam : null;
|
||||
let rescheduleSlots: RescheduleSlotOption[] | null = null;
|
||||
if (slotsDate && canWrite && appt.status === "scheduled") {
|
||||
const slots = await loadSlotsForDate({ tenantId: ctx.tenantId, providerUserIds: [appt.providerUserId], date: slotsDate, config: appt.pageConfig, now });
|
||||
rescheduleSlots = slots.map((slot) => ({ startAtIso: slot.startAt.toISOString(), label: formatInTimeZone(slot.startAt, appt.timezone, "HH:mm") }));
|
||||
}
|
||||
|
||||
const vm = buildBookingDetailVM({
|
||||
id: appt.id,
|
||||
status: appt.status,
|
||||
statusKey: `bookings.status.${appt.status}`,
|
||||
whenLabel: new Date(appt.startAt).toLocaleString(),
|
||||
// Locale-aware + fixed app time zone (Europe/Berlin) instead of the server default.
|
||||
whenLabel: formatDateTime(appt.startAt, locale),
|
||||
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);
|
||||
canWrite,
|
||||
canAdmin,
|
||||
providerOptions,
|
||||
minRescheduleDateIso: formatInTimeZone(now, appt.timezone, "yyyy-MM-dd"),
|
||||
maxRescheduleDateIso: formatInTimeZone(new Date(now.getTime() + appt.pageConfig.maxAdvanceDays * DAY_MS), appt.timezone, "yyyy-MM-dd"),
|
||||
});
|
||||
return Response.json({
|
||||
title: `${t("bookings.detail.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
rescheduleSlots,
|
||||
slotsDate,
|
||||
breadcrumbAncestors: [{ label: t("bookings.list.title"), href: bookingsListPath(params.tenant ?? "") }],
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
@@ -68,97 +124,55 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
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 });
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
try {
|
||||
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({ intent, error: "bookings.error.invalidSlot" } satisfies ActionData, { 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({ intent, error: "bookings.error.providerRequired" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
await reassignAppointment({ tenantId: ctx.tenantId, appointmentId: appt.id, newProviderUserId, actorUserId: ctx.userId });
|
||||
} else {
|
||||
return Response.json({ intent, error: "bookings.error.invalidAction" } satisfies ActionData, { 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 });
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
return Response.json({ intent, error: "bookings.error.lifecycleFailed" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
return redirect(bookingsListPath(params.tenant ?? ""));
|
||||
return Response.json({ intent, ok: true, messageKey: BOOKING_SUCCESS_KEYS[intent] } satisfies ActionData);
|
||||
};
|
||||
|
||||
export default function BookingDetailRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const { vm, rescheduleSlots, slotsDate } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const params = useParams();
|
||||
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>
|
||||
useSaveToast(actionData);
|
||||
|
||||
<section className="mt-6">
|
||||
<h2 className="font-medium">{t("bookings.detail.customer")}</h2>
|
||||
<p>
|
||||
{vm.customerName} {vm.customerEmail ? `· ${vm.customerEmail}` : ""}
|
||||
</p>
|
||||
</section>
|
||||
useEffect(() => {
|
||||
if (actionData?.ok) navigate(bookingsListPath(params.tenant ?? ""));
|
||||
}, [actionData, navigate, params.tenant]);
|
||||
|
||||
{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>
|
||||
);
|
||||
return <BookingDetailPage vm={vm} csrf={rootData.csrf ?? null} rescheduleSlots={rescheduleSlots} slotsDate={slotsDate} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
|
||||
+13
-49
@@ -1,26 +1,27 @@
|
||||
// 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.
|
||||
// Interim ~/ui screen with tab buckets (AD-28); final 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 { BOOKING_MODULE_KEY, bookingDetailPath, bookingPagesListPath, notFoundResponse } from "~/modules/booking/routes/bookingRoutePaths";
|
||||
import { listAppointmentsForTenant } from "~/modules/booking/db/booking.db.server";
|
||||
import { BookingListPage } from "~/components/screens/booking/BookingListPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: BookingListVM };
|
||||
type LoaderData = { title: string; vm: BookingListVM; nowIso: string; pagesHref: string | null };
|
||||
|
||||
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}`;
|
||||
|
||||
const nowIso = new Date().toISOString();
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, vm: buildBookingListVM({ rows: [] }) } satisfies LoaderData);
|
||||
return Response.json({ title, vm: buildBookingListVM({ rows: [] }), nowIso, pagesHref: null } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn);
|
||||
@@ -29,6 +30,10 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
}
|
||||
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
// Reachability (DoD B.6): the booking-pages admin list has no sidebar entry of
|
||||
// its own — it is linked inline from here, only for users who may view it
|
||||
// (bookings.read_all mirrors the pages route's own loader gate).
|
||||
const pagesHref = canReadAllBookings(ctx) ? bookingPagesListPath(tenantSlug) : null;
|
||||
const appointments = await listAppointmentsForTenant({ tenantId: ctx.tenantId, ownerUserId: canReadAllBookings(ctx) ? null : ctx.userId });
|
||||
const rows: BookingListRow[] = appointments.map((a) => ({
|
||||
id: a.id,
|
||||
@@ -43,53 +48,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
detailHref: bookingDetailPath(tenantSlug, a.id),
|
||||
}));
|
||||
|
||||
return Response.json({ title, vm: buildBookingListVM({ rows }) } satisfies LoaderData);
|
||||
return Response.json({ title, vm: buildBookingListVM({ rows }), nowIso, pagesHref } 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>
|
||||
);
|
||||
const { vm, nowIso, pagesHref } = useLoaderData<LoaderData>();
|
||||
return <BookingListPage vm={vm} nowIso={nowIso} pagesHref={pagesHref} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
|
||||
+25
-68
@@ -1,26 +1,17 @@
|
||||
// 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.
|
||||
// URL with copy (DoD 3). Interim ~/ui screen (AD-28); final polish follows D-P16.
|
||||
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildBookingPagesListVM, type BookingPageListRow as BookingPageListRowVM, type BookingPagesListVM } from "@hivegrid/view-models";
|
||||
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 { BookingPagesPage } from "~/components/screens/booking/BookingPagesPage";
|
||||
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 };
|
||||
type LoaderData = { title: string; vm: BookingPagesListVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
@@ -31,67 +22,33 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const origin = new URL(request.url).origin;
|
||||
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),
|
||||
const rows: BookingPageListRowVM[] = pages.map((p) => {
|
||||
const publicPath = publicBookingPath(tenantSlug, p.slug);
|
||||
return {
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
slug: p.slug,
|
||||
durationMinutes: p.durationMinutes,
|
||||
isPublished: p.isPublished,
|
||||
providerCount: p.providerCount,
|
||||
editHref: bookingPageEditPath(tenantSlug, p.id),
|
||||
publicPath,
|
||||
publicUrl: `${origin}${publicPath}`,
|
||||
};
|
||||
});
|
||||
const vm = buildBookingPagesListVM({
|
||||
rows,
|
||||
canCreate: ctx.permissions.includes(BOOKING_PERMISSIONS.admin),
|
||||
newHref: bookingPageNewPath(tenantSlug),
|
||||
} satisfies LoaderData);
|
||||
});
|
||||
return Response.json({ title: `${t("bookings.pages.title")} | ${process.env.APP_NAME}`, vm } 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>
|
||||
);
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
return <BookingPagesPage vm={vm} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
|
||||
+29
-46
@@ -1,29 +1,40 @@
|
||||
// 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.
|
||||
// off -> locked empty; missing calendar.connect_own -> 404. Interim month/week
|
||||
// grid from ~/ui (AD-28); final Subframe optics follow 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 { addDaysIso, addMonthsIso, buildCalendarViewVM, calendarSourceKey, startOfWeekIso, type CalendarViewEventRow, type CalendarViewVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { APP_TIME_ZONE } from "~/locale/format";
|
||||
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 { CalendarViewPage, type CalendarViewMode } from "~/components/screens/calendar/CalendarViewPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: CalendarViewVM };
|
||||
type LoaderData = { title: string; vm: CalendarViewVM; view: CalendarViewMode; anchorIso: string; todayIso: string };
|
||||
|
||||
const WINDOW_PAST_DAYS = 7;
|
||||
const WINDOW_FUTURE_DAYS = 30;
|
||||
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/u;
|
||||
|
||||
/** Today as a `YYYY-MM-DD` in the fixed app time zone (hydration rule). */
|
||||
function todayIsoInAppTz(now: Date): string {
|
||||
return new Intl.DateTimeFormat("en-CA", { timeZone: APP_TIME_ZONE, year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
|
||||
}
|
||||
|
||||
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}`;
|
||||
|
||||
const url = new URL(request.url);
|
||||
const view: CalendarViewMode = url.searchParams.get("view") === "week" ? "week" : "month";
|
||||
const todayIso = todayIsoInAppTz(new Date());
|
||||
const anchorParam = url.searchParams.get("anchor");
|
||||
const anchorIso = anchorParam && DATE_RE.test(anchorParam) ? anchorParam : todayIso;
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, vm: buildCalendarViewVM({ events: [], rangeStart: "", rangeEnd: "" }) } satisfies LoaderData);
|
||||
return Response.json({ title, vm: buildCalendarViewVM({ events: [], rangeStart: "", rangeEnd: "" }), view, anchorIso, todayIso } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCalendarPermission(ctx, CALENDAR_PERMISSIONS.connectOwn);
|
||||
@@ -31,9 +42,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
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);
|
||||
// Resolve the event window for the rendered grid (padded so the leading/
|
||||
// trailing padding days of the month grid carry their events too).
|
||||
const windowStartIso = view === "month" ? addDaysIso(`${anchorIso.slice(0, 7)}-01`, -7) : startOfWeekIso(anchorIso);
|
||||
const windowEndIso = view === "month" ? addDaysIso(addMonthsIso(anchorIso, 1), 7) : addDaysIso(startOfWeekIso(anchorIso), 7);
|
||||
const rangeStart = new Date(`${windowStartIso}T00:00:00Z`);
|
||||
const rangeEnd = new Date(`${windowEndIso}T23:59:59Z`);
|
||||
const events = await listEventsForUser(ctx.tenantId, ctx.userId, rangeStart, rangeEnd);
|
||||
|
||||
const rows: CalendarViewEventRow[] = events.map((e) => {
|
||||
@@ -50,44 +64,13 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
};
|
||||
});
|
||||
|
||||
const vm = buildCalendarViewVM({ events: rows, rangeStart: rangeStart.toISOString().slice(0, 10), rangeEnd: rangeEnd.toISOString().slice(0, 10) });
|
||||
return Response.json({ title, vm } satisfies LoaderData);
|
||||
const vm = buildCalendarViewVM({ events: rows, rangeStart: windowStartIso, rangeEnd: windowEndIso });
|
||||
return Response.json({ title, vm, view, anchorIso, todayIso } 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>
|
||||
);
|
||||
const { vm, view, anchorIso, todayIso } = useLoaderData<LoaderData>();
|
||||
return <CalendarViewPage vm={vm} view={view} anchorIso={anchorIso} todayIso={todayIso} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import type { TelephonyCallDetailVM, TelephonyMatchedEntityType } from "@hivegrid/view-models";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate } from "react-router";
|
||||
|
||||
import { TelephonyCallDetailPage } from "~/components/screens/telephony/TelephonyCallDetailPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadTelephonyContext } from "~/modules/telephony/routes/telephonyAccess.server";
|
||||
import { TELEPHONY_MODULE_KEY } from "~/modules/telephony/routes/telephonyRoutePaths";
|
||||
import {
|
||||
loadTelephonyCallDetail,
|
||||
overrideTelephonyCallMatch,
|
||||
saveTelephonyCallNote,
|
||||
startTelephonyCallBack,
|
||||
TelephonyServiceError,
|
||||
} from "~/modules/telephony/services/TelephonyService.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
readonly title: string;
|
||||
readonly vm: TelephonyCallDetailVM;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
readonly intent?: string;
|
||||
readonly ok?: true;
|
||||
readonly messageKey?: string;
|
||||
readonly error?: string;
|
||||
};
|
||||
|
||||
const MATCH_TYPES = new Set<TelephonyMatchedEntityType>(["contact", "lead", "project"]);
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const [{ t }, ctx] = await Promise.all([getTranslations(request), loadTelephonyContext({ request, params, requireModule: true })]);
|
||||
const vm = await loadTelephonyCallDetail(ctx, params.tenant ?? "", params.id ?? "");
|
||||
return Response.json({
|
||||
title: `${t("telephony.callDetail.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const form = await request.formData();
|
||||
await validateCSRFToken(request, { formData: form });
|
||||
const ctx = await loadTelephonyContext({ request, params, requireModule: true });
|
||||
const callId = params.id ?? "";
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
|
||||
try {
|
||||
if (intent === "saveNote") {
|
||||
await saveTelephonyCallNote(ctx, {
|
||||
callId,
|
||||
noteMarkdown: String(form.get("noteMarkdown") ?? ""),
|
||||
});
|
||||
return Response.json({
|
||||
intent,
|
||||
ok: true,
|
||||
messageKey: "telephony.callDetail.feedback.noteSaved",
|
||||
} satisfies ActionData);
|
||||
}
|
||||
if (intent === "overrideMatch") {
|
||||
const type = String(form.get("matchType") ?? "");
|
||||
const id = String(form.get("matchId") ?? "").trim();
|
||||
const match =
|
||||
!type && !id ? null : MATCH_TYPES.has(type as TelephonyMatchedEntityType) && id ? { type: type as TelephonyMatchedEntityType, id } : undefined;
|
||||
if (match === undefined) return invalidRequestResponse(intent);
|
||||
await overrideTelephonyCallMatch(ctx, { callId, match });
|
||||
return Response.json({
|
||||
intent,
|
||||
ok: true,
|
||||
messageKey:
|
||||
match === null
|
||||
? "telephony.callDetail.feedback.matchRemoved"
|
||||
: "telephony.callDetail.feedback.matchSaved",
|
||||
} satisfies ActionData);
|
||||
}
|
||||
if (intent === "callBack") {
|
||||
await startTelephonyCallBack(ctx, callId);
|
||||
return Response.json({
|
||||
intent,
|
||||
ok: true,
|
||||
messageKey: "telephony.callDetail.feedback.callbackStarted",
|
||||
} satisfies ActionData);
|
||||
}
|
||||
return invalidRequestResponse(intent);
|
||||
} catch (error) {
|
||||
return telephonyActionErrorResponse(error, intent);
|
||||
}
|
||||
};
|
||||
|
||||
export default function TelephonyCallDetailRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const actionVm: TelephonyCallDetailVM = fetcher.data?.error
|
||||
? {
|
||||
status: "error",
|
||||
data: vm.status === "ready" ? vm.data : undefined,
|
||||
error: { messageKey: fetcher.data.error },
|
||||
}
|
||||
: vm;
|
||||
// Keep the existing inline error state, and toast only confirmed successes
|
||||
// so a failed action is not announced twice.
|
||||
useSaveToast(fetcher.data?.ok ? fetcher.data : undefined);
|
||||
|
||||
const submit = (fields: Record<string, string>) => {
|
||||
const form = new FormData();
|
||||
for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
||||
fetcher.submit(appendCSRFToken(form), { method: "post" });
|
||||
};
|
||||
|
||||
return (
|
||||
<TelephonyCallDetailPage
|
||||
vm={actionVm}
|
||||
busy={fetcher.state !== "idle"}
|
||||
actions={{
|
||||
onBack: (listHref) => navigate(listHref),
|
||||
onOverrideMatch: (_callId, option) =>
|
||||
submit({
|
||||
intent: "overrideMatch",
|
||||
matchType: option?.type ?? "",
|
||||
matchId: option?.id ?? "",
|
||||
}),
|
||||
onSaveNote: (_callId, noteMarkdown) => submit({ intent: "saveNote", noteMarkdown }),
|
||||
onCallBack: () => submit({ intent: "callBack" }),
|
||||
onRetry: () => window.location.reload(),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function invalidRequestResponse(intent?: string): Response {
|
||||
return Response.json({ intent, error: "telephony.errors.invalidRequest" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
function telephonyActionErrorResponse(error: unknown, intent: string): Response {
|
||||
if (error instanceof Response) return error;
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ intent, error: error.i18nKey } satisfies ActionData, { status: error.status });
|
||||
}
|
||||
if (error instanceof TelephonyServiceError) {
|
||||
return Response.json({ intent, error: error.messageKey } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = {
|
||||
moduleKey: TELEPHONY_MODULE_KEY,
|
||||
breadcrumbKey: "telephony.callDetail.title",
|
||||
};
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { type LoaderFunctionArgs, type MetaFunction, useLoaderData, useNavigate, useRevalidator } from "react-router";
|
||||
import type { TelephonyCallListVM } from "@hivegrid/view-models";
|
||||
|
||||
import { TelephonyCallsPage } from "~/components/screens/telephony/TelephonyCallsPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadTelephonyContext } from "~/modules/telephony/routes/telephonyAccess.server";
|
||||
import { TELEPHONY_MODULE_KEY } from "~/modules/telephony/routes/telephonyRoutePaths";
|
||||
import { loadTelephonyCalls } from "~/modules/telephony/services/TelephonyService.server";
|
||||
|
||||
type LoaderData = {
|
||||
readonly title: string;
|
||||
readonly vm: TelephonyCallListVM;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const [{ t }, ctx] = await Promise.all([getTranslations(request), loadTelephonyContext({ request, params, requireModule: true })]);
|
||||
const vm = await loadTelephonyCalls(ctx, params.tenant ?? "");
|
||||
return Response.json({
|
||||
title: `${t("telephony.calls.title")} | ${process.env.APP_NAME}`,
|
||||
vm,
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function TelephonyCallsRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
const revalidator = useRevalidator();
|
||||
return (
|
||||
<TelephonyCallsPage
|
||||
vm={vm}
|
||||
busy={revalidator.state !== "idle"}
|
||||
actions={{
|
||||
onOpenCall: (_callId, detailHref) => navigate(detailHref),
|
||||
onRefresh: () => revalidator.revalidate(),
|
||||
onRetry: () => revalidator.revalidate(),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: TELEPHONY_MODULE_KEY };
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadChatContext: vi.fn(),
|
||||
loadMemberChatChannel: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
sendMemberChatMessage: vi.fn(),
|
||||
loadTasksContext: vi.fn(),
|
||||
requireTasksPermission: vi.fn(),
|
||||
markChatMessageAsTask: vi.fn(),
|
||||
editMemberChatMessage: vi.fn(),
|
||||
removeMemberChatMessage: vi.fn(),
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({ loadChatContext: mocks.loadChatContext }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: mocks.getTranslations }));
|
||||
vi.mock("~/modules/chat/services/ChatService.server", () => ({
|
||||
loadMemberChatChannel: mocks.loadMemberChatChannel,
|
||||
sendMemberChatMessage: mocks.sendMemberChatMessage,
|
||||
}));
|
||||
vi.mock("~/modules/chat/services/ChatMessageFeaturesService.server", () => ({
|
||||
changeChatMessagePin: vi.fn(),
|
||||
changeChatReaction: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/modules/chat/services/ChatMessageTaskService.server", () => ({ markChatMessageAsTask: mocks.markChatMessageAsTask }));
|
||||
vi.mock("~/modules/chat/services/ChatMessageMutationsService.server", () => ({
|
||||
editMemberChatMessage: mocks.editMemberChatMessage,
|
||||
removeMemberChatMessage: mocks.removeMemberChatMessage,
|
||||
}));
|
||||
vi.mock("~/utils/integrations/taskAccess.server", () => ({
|
||||
loadTasksContext: mocks.loadTasksContext,
|
||||
requireTasksPermission: mocks.requireTasksPermission,
|
||||
}));
|
||||
|
||||
import { action, loader, parseAttachmentFileIds } from "./chat.$id";
|
||||
|
||||
describe("chat channel attachment and task actions", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadChatContext.mockResolvedValue({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_current",
|
||||
tenantUserId: "tenant_user_1",
|
||||
permissions: ["chat.read_own_channels", "chat.write", "tasks.write"],
|
||||
hasModule: true,
|
||||
});
|
||||
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
||||
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
|
||||
mocks.loadMemberChatChannel.mockResolvedValue({
|
||||
vm: { status: "empty", data: null, error: null },
|
||||
eventCursor: "stream_1:1",
|
||||
authors: [],
|
||||
});
|
||||
mocks.loadTasksContext.mockResolvedValue({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_current",
|
||||
permissions: ["tasks.write"],
|
||||
hasModule: true,
|
||||
});
|
||||
mocks.requireTasksPermission.mockImplementation((context) => context);
|
||||
});
|
||||
|
||||
it("sends an attachment-only message through the member and CSRF boundaries", async () => {
|
||||
mocks.sendMemberChatMessage.mockResolvedValue({ message: { id: "message_attachment" }, replayed: false });
|
||||
const response = await actionRequest([
|
||||
["intent", "send_attachment_message"],
|
||||
["requestId", "request_attachment"],
|
||||
["clientMessageId", "client_attachment"],
|
||||
["body", ""],
|
||||
["attachmentFileIds", JSON.stringify(["file_1"])],
|
||||
]);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.validateCSRFToken).toHaveBeenCalled();
|
||||
expect(mocks.sendMemberChatMessage).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
chatId: "chat_1",
|
||||
requestId: "request_attachment",
|
||||
clientMessageId: "client_attachment",
|
||||
body: "",
|
||||
attachmentFileIds: ["file_1"],
|
||||
})
|
||||
);
|
||||
await expect(response.json()).resolves.toMatchObject({ ok: true, intent: "send_attachment_message", messageId: "message_attachment" });
|
||||
});
|
||||
|
||||
it("creates a task idempotently from a visible chat message", async () => {
|
||||
mocks.markChatMessageAsTask.mockResolvedValue({ taskId: "task_1", replayed: false });
|
||||
const response = await actionRequest([
|
||||
["intent", "mark_task"],
|
||||
["requestId", "request_task"],
|
||||
["messageId", "message_1"],
|
||||
]);
|
||||
|
||||
expect(mocks.requireTasksPermission).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1" }), "tasks.write");
|
||||
expect(mocks.markChatMessageAsTask).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ chatId: "chat_1", messageId: "message_1", fallbackTitle: "chat.task.fallbackTitle" })
|
||||
);
|
||||
await expect(response.json()).resolves.toMatchObject({ ok: true, intent: "mark_task", taskId: "task_1", replayed: false });
|
||||
});
|
||||
|
||||
it("rejects duplicate and oversized attachment payloads before the repository", async () => {
|
||||
expect(parseAttachmentFileIds(JSON.stringify(["file_1", "file_1"]))).toBeNull();
|
||||
expect(parseAttachmentFileIds(JSON.stringify(Array.from({ length: 21 }, (_, index) => `file_${index}`)))).toBeNull();
|
||||
});
|
||||
|
||||
it("edits a message through the member mutation service", async () => {
|
||||
mocks.editMemberChatMessage.mockResolvedValue({ message: { id: "message_1" }, replayed: false });
|
||||
|
||||
const response = await actionRequest([
|
||||
["intent", "edit_message"],
|
||||
["requestId", "request_edit"],
|
||||
["messageId", "message_1"],
|
||||
["body", "Aktualisiert"],
|
||||
]);
|
||||
|
||||
expect(mocks.editMemberChatMessage).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ chatId: "chat_1", requestId: "request_edit", messageId: "message_1", body: "Aktualisiert" })
|
||||
);
|
||||
await expect(response.json()).resolves.toMatchObject({ ok: true, intent: "edit_message", messageId: "message_1", replayed: false });
|
||||
});
|
||||
|
||||
it("deletes a message through the member mutation service", async () => {
|
||||
mocks.removeMemberChatMessage.mockResolvedValue({ messageId: "message_1", replayed: false });
|
||||
|
||||
const response = await actionRequest([
|
||||
["intent", "delete_message"],
|
||||
["requestId", "request_delete"],
|
||||
["messageId", "message_1"],
|
||||
]);
|
||||
|
||||
expect(mocks.removeMemberChatMessage).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ chatId: "chat_1", requestId: "request_delete", messageId: "message_1" })
|
||||
);
|
||||
await expect(response.json()).resolves.toMatchObject({ ok: true, intent: "delete_message", messageId: "message_1", replayed: false });
|
||||
});
|
||||
|
||||
it("passes a top-level message deep-link target into the member-scoped loader", async () => {
|
||||
await loader({
|
||||
request: new Request("http://app.localhost/demo/chat/chat_1?message=message_old#message-message_old"),
|
||||
params: { tenant: "demo", id: "chat_1" },
|
||||
context: {},
|
||||
});
|
||||
|
||||
expect(mocks.loadMemberChatChannel).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tenantSlug: "demo", chatId: "chat_1", focusMessageId: "message_old" })
|
||||
);
|
||||
});
|
||||
|
||||
it("uses explicit history pagination instead of a simultaneous focus target", async () => {
|
||||
await loader({
|
||||
request: new Request("http://app.localhost/demo/chat/chat_1?before=opaque_cursor&message=message_old"),
|
||||
params: { tenant: "demo", id: "chat_1" },
|
||||
context: {},
|
||||
});
|
||||
|
||||
expect(mocks.loadMemberChatChannel).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tenantSlug: "demo", chatId: "chat_1", beforeMessageCursor: "opaque_cursor" })
|
||||
);
|
||||
expect(mocks.loadMemberChatChannel).not.toHaveBeenCalledWith(expect.objectContaining({ focusMessageId: expect.anything() }));
|
||||
});
|
||||
});
|
||||
|
||||
async function actionRequest(entries: readonly (readonly [string, string])[]): Promise<Response> {
|
||||
const formData = new URLSearchParams();
|
||||
formData.set("csrf", "csrf");
|
||||
for (const [key, value] of entries) formData.set(key, value);
|
||||
return action({
|
||||
request: new Request("http://app.localhost/demo/chat/chat_1", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: formData,
|
||||
}),
|
||||
params: { tenant: "demo", id: "chat_1" },
|
||||
context: {},
|
||||
});
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ loadContext: vi.fn(), loadSuggestions: vi.fn() }));
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({ loadChatContext: mocks.loadContext }));
|
||||
vi.mock("~/modules/chat/services/ChatMentionsService.server", () => ({ loadChatMentionSuggestions: mocks.loadSuggestions }));
|
||||
|
||||
import { loader } from "./chat.$id.mentions";
|
||||
|
||||
describe("chat mention resource route", () => {
|
||||
it("normalizes the requested kind and returns the server-built VM", async () => {
|
||||
const context = { tenantId: "tenant_1", userId: "user_1", permissions: [], hasModule: true };
|
||||
mocks.loadContext.mockResolvedValue(context);
|
||||
mocks.loadSuggestions.mockResolvedValue({ groups: [], total: 0 });
|
||||
|
||||
const response = await loader({
|
||||
request: new Request("https://app.test/acme/chat/chat_1/mentions?q=anna&type=contact"),
|
||||
params: { tenant: "acme", id: "chat_1" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.loadSuggestions).toHaveBeenCalledWith({ context, tenantSlug: "acme", chatId: "chat_1", query: "anna", type: "contact" });
|
||||
});
|
||||
|
||||
it("does not pass an unsupported kind into the repository", async () => {
|
||||
mocks.loadContext.mockResolvedValue({ tenantId: "tenant_1", userId: "user_1", permissions: [], hasModule: true });
|
||||
mocks.loadSuggestions.mockResolvedValue({ groups: [], total: 0 });
|
||||
await loader({
|
||||
request: new Request("https://app.test/acme/chat/chat_1/mentions?type=deal"),
|
||||
params: { tenant: "acme", id: "chat_1" },
|
||||
context: {},
|
||||
} as never);
|
||||
expect(mocks.loadSuggestions).toHaveBeenLastCalledWith(expect.objectContaining({ type: null }));
|
||||
});
|
||||
});
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import type { ChatMentionType } from "@hivegrid/realtime";
|
||||
|
||||
import { loadChatContext } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { CHAT_MODULE_KEY } from "~/modules/chat/routes/chatRoutePaths";
|
||||
import { loadChatMentionSuggestions } from "~/modules/chat/services/ChatMentionsService.server";
|
||||
|
||||
const TYPES = new Set<ChatMentionType>(["user", "project", "contact", "company"]);
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const context = await loadChatContext({ request, params });
|
||||
const url = new URL(request.url);
|
||||
const query = (url.searchParams.get("q") ?? "").trim();
|
||||
const rawType = url.searchParams.get("type");
|
||||
const type = rawType && TYPES.has(rawType as ChatMentionType) ? (rawType as ChatMentionType) : null;
|
||||
const vm = await loadChatMentionSuggestions({
|
||||
context,
|
||||
tenantSlug: params.tenant ?? "",
|
||||
chatId: params.id ?? "",
|
||||
query,
|
||||
type,
|
||||
});
|
||||
return Response.json({ query, type, vm });
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CHAT_MODULE_KEY };
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate, useRevalidator } from "react-router";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import type { ChatPinnedMessagesVM } from "@hivegrid/view-models";
|
||||
|
||||
import { ChatPinnedMessagesPage } from "~/components/screens/chat/ChatPinnedMessagesPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useChatChannelRealtime } from "~/modules/chat/client/useChatChannelRealtime";
|
||||
import {
|
||||
beginChatFeatureMutation,
|
||||
chatFeatureErrorsByMessageId,
|
||||
failedChatFeatureMutationForMessage,
|
||||
overlayChatPinnedFeatureMutations,
|
||||
reconcileChatPinnedFeatureMutations,
|
||||
settleChatFeatureMutation,
|
||||
type ChatOptimisticFeatureMutation,
|
||||
type ChatOptimisticFeatureMutationInput,
|
||||
} from "~/modules/chat/client/ChatFeatureOptimistic";
|
||||
import { loadChatContext } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { CHAT_MODULE_KEY } from "~/modules/chat/routes/chatRoutePaths";
|
||||
import { changeChatMessagePin, loadChatPinnedPage } from "~/modules/chat/services/ChatMessageFeaturesService.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
readonly title: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly currentUserId: string;
|
||||
readonly chatId: string;
|
||||
readonly eventCursor: string;
|
||||
readonly vm: ChatPinnedMessagesVM;
|
||||
};
|
||||
type ActionData = { readonly ok: boolean; readonly requestId: string; readonly messageId: string; readonly errorKey: string | null };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
||||
const result = await loadChatPinnedPage({
|
||||
context,
|
||||
tenantSlug: params.tenant ?? "",
|
||||
chatId: params.id ?? "",
|
||||
labels: {
|
||||
directMessage: t("chat.channel.fallback.directMessage"),
|
||||
unnamedGroup: t("chat.channel.fallback.group"),
|
||||
unnamedProject: t("chat.channel.fallback.project"),
|
||||
unknownUser: t("chat.participant.unknown"),
|
||||
unknownMention: t("chat.mention.unknown"),
|
||||
},
|
||||
});
|
||||
const { vm } = result;
|
||||
const channelTitle = vm.status === "ready" ? vm.data.channelTitle : t("chat.pinned.titleFallback");
|
||||
return Response.json({
|
||||
title: `${t("chat.pinned.title", { channel: channelTitle })} | ${process.env.APP_NAME}`,
|
||||
tenantSlug: params.tenant ?? "",
|
||||
currentUserId: context.userId,
|
||||
chatId: params.id ?? "",
|
||||
eventCursor: result.eventCursor,
|
||||
vm,
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const context = await loadChatContext({ request, params });
|
||||
const formData = await request.formData();
|
||||
await validateCSRFToken(request, { formData });
|
||||
const messageId = formData.get("messageId")?.toString().trim() ?? "";
|
||||
const requestId = formData.get("requestId")?.toString().trim() ?? "";
|
||||
try {
|
||||
await changeChatMessagePin({
|
||||
context,
|
||||
chatId: params.id ?? "",
|
||||
messageId,
|
||||
pinned: false,
|
||||
requestId,
|
||||
});
|
||||
return Response.json({ ok: true, requestId, messageId, errorKey: null } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ ok: false, requestId, messageId, errorKey: error.i18nKey } satisfies ActionData, { status: error.status });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatPinnedMessagesRoute(): React.JSX.Element {
|
||||
const loaderData = useLoaderData<LoaderData>();
|
||||
const authoritativeVm = loaderData.vm;
|
||||
const navigate = useNavigate();
|
||||
const revalidator = useRevalidator();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const { csrf, routing } = useRootData();
|
||||
const [featureMutations, setFeatureMutations] = useState<readonly ChatOptimisticFeatureMutation[]>([]);
|
||||
const vm = overlayChatPinnedFeatureMutations(authoritativeVm, featureMutations);
|
||||
useEffect(() => {
|
||||
setFeatureMutations((current) => reconcileChatPinnedFeatureMutations(current, authoritativeVm));
|
||||
}, [authoritativeVm]);
|
||||
useEffect(() => {
|
||||
if (fetcher.state !== "idle" || !fetcher.data) return;
|
||||
setFeatureMutations((current) => settleChatFeatureMutation(current, fetcher.data!.requestId, fetcher.data!));
|
||||
}, [fetcher.data, fetcher.state]);
|
||||
useChatChannelRealtime({
|
||||
enabled: vm.status === "ready",
|
||||
tenantSlug: loaderData.tenantSlug,
|
||||
chatId: loaderData.chatId,
|
||||
initialCursor: loaderData.eventCursor,
|
||||
csrfToken: csrf ?? null,
|
||||
routing,
|
||||
initialMessages: [],
|
||||
currentUser: {
|
||||
userId: loaderData.currentUserId,
|
||||
displayName: loaderData.currentUserId,
|
||||
avatar: { imageUrl: null, fallbackLabel: "?" },
|
||||
isCurrentUser: true,
|
||||
},
|
||||
unknownAuthorLabel: "?",
|
||||
resolveAuthor: () => null,
|
||||
revalidate: () => revalidator.revalidate(),
|
||||
});
|
||||
|
||||
function submitFeatureMutation(mutation: ChatOptimisticFeatureMutationInput): void {
|
||||
if (fetcher.state !== "idle") return;
|
||||
setFeatureMutations((current) => beginChatFeatureMutation(current, mutation));
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", csrf ?? "");
|
||||
formData.set("requestId", mutation.requestId);
|
||||
formData.set("messageId", mutation.messageId);
|
||||
void fetcher.submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
function unpin(messageId: string): void {
|
||||
submitFeatureMutation({
|
||||
kind: "pin",
|
||||
requestId: crypto.randomUUID(),
|
||||
messageId,
|
||||
pinned: false,
|
||||
actorLabel: loaderData.currentUserId,
|
||||
startedAtIso: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
function retryFeatureMutation(messageId: string): void {
|
||||
const mutation = failedChatFeatureMutationForMessage(featureMutations, messageId);
|
||||
if (mutation?.kind === "pin") submitFeatureMutation(mutation);
|
||||
}
|
||||
return (
|
||||
<ChatPinnedMessagesPage
|
||||
vm={vm}
|
||||
busyMessageId={fetcher.state === "idle" ? null : (fetcher.formData?.get("messageId")?.toString() ?? null)}
|
||||
errorKey={null}
|
||||
featureErrorKeys={chatFeatureErrorsByMessageId(featureMutations)}
|
||||
actions={{
|
||||
onBack: (href) => void navigate(href),
|
||||
onUnpin: unpin,
|
||||
onRetryFeature: retryFeatureMutation,
|
||||
onRetry: () => revalidator.revalidate(),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CHAT_MODULE_KEY, breadcrumbKey: "chat.pinned.breadcrumb" };
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadChatContext: vi.fn(),
|
||||
loadPage: vi.fn(),
|
||||
addMember: vi.fn(),
|
||||
changeRole: vi.fn(),
|
||||
removeMember: vi.fn(),
|
||||
changePrivacy: vi.fn(),
|
||||
leave: vi.fn(),
|
||||
archive: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({ loadChatContext: mocks.loadChatContext }));
|
||||
vi.mock("~/modules/chat/services/ChatChannelSettingsService.server", () => ({
|
||||
loadChatChannelSettingsPage: mocks.loadPage,
|
||||
addChatChannelMember: mocks.addMember,
|
||||
changeChatChannelMemberRole: mocks.changeRole,
|
||||
removeChatChannelMember: mocks.removeMember,
|
||||
changeChatChannelPrivacy: mocks.changePrivacy,
|
||||
leaveChatChannel: mocks.leave,
|
||||
archiveChatChannel: mocks.archive,
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf_1" }) }));
|
||||
vi.mock("~/components/screens/chat/ChatChannelSettingsPage", () => ({ ChatChannelSettingsPage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
|
||||
import { action, loader } from "./chat.$id.settings";
|
||||
|
||||
const context = {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_current",
|
||||
tenantUserId: "tenant_user_current",
|
||||
permissions: ["chat.read_own_channels"],
|
||||
hasModule: true as const,
|
||||
};
|
||||
|
||||
describe("AK-P15b chat channel settings route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadChatContext.mockResolvedValue(context);
|
||||
mocks.loadPage.mockResolvedValue({ status: "empty" });
|
||||
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("loads settings through the tenant chat context with localized fallbacks", async () => {
|
||||
const request = new Request("https://app.example.test/demo/chat/chat_1/settings");
|
||||
const response = await loader({
|
||||
request,
|
||||
params: { tenant: "demo", id: "chat_1" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.$id.settings",
|
||||
});
|
||||
|
||||
expect(mocks.loadPage).toHaveBeenCalledWith({
|
||||
context,
|
||||
tenantSlug: "demo",
|
||||
chatId: "chat_1",
|
||||
labels: {
|
||||
directMessage: "chat.channel.fallback.directMessage",
|
||||
unnamedGroup: "chat.channel.fallback.group",
|
||||
unnamedProject: "chat.channel.fallback.project",
|
||||
unknownProjectStage: "chat.channel.fallback.projectStage",
|
||||
},
|
||||
});
|
||||
await expect(response.json()).resolves.toMatchObject({
|
||||
tenantSlug: "demo",
|
||||
chatId: "chat_1",
|
||||
requestId: expect.any(String),
|
||||
vm: { status: "empty" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["add_member", { memberUserId: "user_new" }, "addMember", "chat.toast.memberAdded"],
|
||||
["set_role", { memberUserId: "user_new", roleInChat: "admin" }, "changeRole", "chat.toast.memberRoleChanged"],
|
||||
["remove_member", { memberUserId: "user_new" }, "removeMember", "chat.toast.memberRemoved"],
|
||||
["set_privacy", { privacy: "public" }, "changePrivacy", "chat.toast.channelMadePublic"],
|
||||
] as const)("handles %s with CSRF and redirects to the settings page", async (intent, values, mockName, toastKey) => {
|
||||
const form = new FormData();
|
||||
form.set("csrf", "csrf_1");
|
||||
form.set("intent", intent);
|
||||
form.set("requestId", `request_${intent}`);
|
||||
for (const [key, value] of Object.entries(values)) form.set(key, value);
|
||||
const request = postRequest(form);
|
||||
|
||||
const response = await action({
|
||||
request,
|
||||
params: { tenant: "demo", id: "chat_1" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.$id.settings",
|
||||
});
|
||||
|
||||
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() });
|
||||
expect(mocks[mockName]).toHaveBeenCalledWith({
|
||||
context,
|
||||
chatId: "chat_1",
|
||||
requestId: `request_${intent}`,
|
||||
...values,
|
||||
});
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("location")).toBe(`/demo/chat/chat_1/settings?toast=${toastKey}`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["leave", "leave", "chat.toast.channelLeft"],
|
||||
["archive", "archive", "chat.toast.channelArchived"],
|
||||
] as const)("returns to the channel list after %s", async (intent, mockName, toastKey) => {
|
||||
const form = new FormData();
|
||||
form.set("csrf", "csrf_1");
|
||||
form.set("intent", intent);
|
||||
form.set("requestId", `request_${intent}`);
|
||||
|
||||
const response = await action({
|
||||
request: postRequest(form),
|
||||
params: { tenant: "demo", id: "chat_1" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.$id.settings",
|
||||
});
|
||||
|
||||
expect(mocks[mockName]).toHaveBeenCalledWith({ context, chatId: "chat_1", requestId: `request_${intent}` });
|
||||
expect(response.headers.get("location")).toBe(`/demo/chat?toast=${toastKey}`);
|
||||
});
|
||||
|
||||
it("rejects malformed action input before any mutation", async () => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "set_role");
|
||||
form.set("requestId", "request_invalid");
|
||||
form.set("memberUserId", "user_new");
|
||||
form.set("roleInChat", "owner");
|
||||
|
||||
const response = await action({
|
||||
request: postRequest(form),
|
||||
params: { tenant: "demo", id: "chat_1" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.$id.settings",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ errorKey: "chat.errors.invalidInput" });
|
||||
expect(mocks.changeRole).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
function postRequest(formData: FormData): Request {
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of formData.entries()) body.append(key, value.toString());
|
||||
return new Request("https://app.example.test/demo/chat/chat_1/settings", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
import {
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
type MetaFunction,
|
||||
redirect,
|
||||
useActionData,
|
||||
useLoaderData,
|
||||
useNavigate,
|
||||
useNavigation,
|
||||
useRevalidator,
|
||||
useSubmit,
|
||||
} from "react-router";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import type { ChatChannelSettingsMemberRole, ChatChannelSettingsVM } from "@hivegrid/view-models";
|
||||
|
||||
import { ChatChannelSettingsPage } from "~/components/screens/chat/ChatChannelSettingsPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadChatContext } from "~/modules/chat/routes/chatAccess.server";
|
||||
import {
|
||||
CHAT_MODULE_KEY,
|
||||
chatChannelPath,
|
||||
chatChannelSettingsPath,
|
||||
chatIndexPath,
|
||||
} from "~/modules/chat/routes/chatRoutePaths";
|
||||
import {
|
||||
addChatChannelMember,
|
||||
archiveChatChannel,
|
||||
changeChatChannelMemberRole,
|
||||
changeChatChannelPrivacy,
|
||||
leaveChatChannel,
|
||||
loadChatChannelSettingsPage,
|
||||
removeChatChannelMember,
|
||||
} from "~/modules/chat/services/ChatChannelSettingsService.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = Readonly<{
|
||||
title: string;
|
||||
tenantSlug: string;
|
||||
chatId: string;
|
||||
requestId: string;
|
||||
vm: ChatChannelSettingsVM;
|
||||
}>;
|
||||
|
||||
type ActionData = Readonly<{ errorKey: string }>;
|
||||
type SettingsIntent = "add_member" | "set_role" | "remove_member" | "set_privacy" | "leave" | "archive";
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const chatId = params.id ?? "";
|
||||
const vm = await loadChatChannelSettingsPage({
|
||||
context,
|
||||
tenantSlug,
|
||||
chatId,
|
||||
labels: {
|
||||
directMessage: t("chat.channel.fallback.directMessage"),
|
||||
unnamedGroup: t("chat.channel.fallback.group"),
|
||||
unnamedProject: t("chat.channel.fallback.project"),
|
||||
unknownProjectStage: t("chat.channel.fallback.projectStage"),
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({
|
||||
title: `${t("chat.channelSettings.title")} | ${process.env.APP_NAME}`,
|
||||
tenantSlug,
|
||||
chatId,
|
||||
requestId: crypto.randomUUID(),
|
||||
vm,
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const context = await loadChatContext({ request, params });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const chatId = params.id ?? "";
|
||||
const formData = await request.formData();
|
||||
await validateCSRFToken(request, { formData });
|
||||
|
||||
const intent = parseIntent(formData.get("intent"));
|
||||
const requestId = parseIdentifier(formData.get("requestId"));
|
||||
if (!intent || !requestId) return invalidInput();
|
||||
const base = { context, chatId, requestId };
|
||||
|
||||
try {
|
||||
if (intent === "add_member") {
|
||||
const memberUserId = parseIdentifier(formData.get("memberUserId"));
|
||||
if (!memberUserId) return invalidInput();
|
||||
await addChatChannelMember({ ...base, memberUserId });
|
||||
} else if (intent === "set_role") {
|
||||
const memberUserId = parseIdentifier(formData.get("memberUserId"));
|
||||
const roleInChat = parseRole(formData.get("roleInChat"));
|
||||
if (!memberUserId || !roleInChat) return invalidInput();
|
||||
await changeChatChannelMemberRole({ ...base, memberUserId, roleInChat });
|
||||
} else if (intent === "remove_member") {
|
||||
const memberUserId = parseIdentifier(formData.get("memberUserId"));
|
||||
if (!memberUserId) return invalidInput();
|
||||
await removeChatChannelMember({ ...base, memberUserId });
|
||||
} else if (intent === "set_privacy") {
|
||||
const privacy = parsePrivacy(formData.get("privacy"));
|
||||
if (!privacy) return invalidInput();
|
||||
await changeChatChannelPrivacy({ ...base, privacy });
|
||||
} else if (intent === "leave") {
|
||||
await leaveChatChannel(base);
|
||||
return redirect(withToast(chatIndexPath(tenantSlug), "chat.toast.channelLeft"));
|
||||
} else {
|
||||
await archiveChatChannel(base);
|
||||
return redirect(withToast(chatIndexPath(tenantSlug), "chat.toast.channelArchived"));
|
||||
}
|
||||
|
||||
return redirect(withToast(chatChannelSettingsPath(tenantSlug, chatId), settingsSuccessKey(intent, formData)));
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ errorKey: error.i18nKey } satisfies ActionData, { status: error.status });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatChannelSettingsRoute(): React.JSX.Element {
|
||||
const { tenantSlug, chatId, requestId, vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const navigation = useNavigation();
|
||||
const revalidator = useRevalidator();
|
||||
const submit = useSubmit();
|
||||
const { csrf } = useRootData();
|
||||
const busy = navigation.state === "submitting";
|
||||
|
||||
function submitIntent(intent: SettingsIntent, values: Readonly<Record<string, string>> = {}): void {
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", csrf ?? "");
|
||||
formData.set("intent", intent);
|
||||
formData.set("requestId", mutationRequestId(requestId, intent));
|
||||
for (const [key, value] of Object.entries(values)) formData.set(key, value);
|
||||
void submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<ChatChannelSettingsPage
|
||||
vm={vm}
|
||||
busy={busy}
|
||||
actionErrorKey={actionData?.errorKey}
|
||||
actions={{
|
||||
onBack: () => void navigate(chatChannelPath(tenantSlug, chatId)),
|
||||
onRetry: () => revalidator.revalidate(),
|
||||
onAddMember: (memberUserId) => submitIntent("add_member", { memberUserId }),
|
||||
onChangeRole: (memberUserId, roleInChat) => submitIntent("set_role", { memberUserId, roleInChat }),
|
||||
onRemoveMember: (memberUserId) => submitIntent("remove_member", { memberUserId }),
|
||||
onPrivacyChange: (privacy) => submitIntent("set_privacy", { privacy }),
|
||||
onLeave: () => submitIntent("leave"),
|
||||
onArchive: () => submitIntent("archive"),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function mutationRequestId(base: string, intent: SettingsIntent): string {
|
||||
return `${base}:${intent}`;
|
||||
}
|
||||
|
||||
function parseIntent(value: FormDataEntryValue | null): SettingsIntent | null {
|
||||
const intent = value?.toString() ?? "";
|
||||
return ["add_member", "set_role", "remove_member", "set_privacy", "leave", "archive"].includes(intent)
|
||||
? (intent as SettingsIntent)
|
||||
: null;
|
||||
}
|
||||
|
||||
function parseIdentifier(value: FormDataEntryValue | null): string | null {
|
||||
const normalized = value?.toString().trim() ?? "";
|
||||
return normalized && normalized.length <= 191 && !normalized.includes("\0") ? normalized : null;
|
||||
}
|
||||
|
||||
function parseRole(value: FormDataEntryValue | null): ChatChannelSettingsMemberRole | null {
|
||||
const role = value?.toString() ?? "";
|
||||
return role === "admin" || role === "member" ? role : null;
|
||||
}
|
||||
|
||||
function parsePrivacy(value: FormDataEntryValue | null): "public" | "private" | null {
|
||||
const privacy = value?.toString() ?? "";
|
||||
return privacy === "public" || privacy === "private" ? privacy : null;
|
||||
}
|
||||
|
||||
function invalidInput(): Response {
|
||||
return Response.json({ errorKey: "chat.errors.invalidInput" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
function settingsSuccessKey(intent: SettingsIntent, formData: FormData): string {
|
||||
if (intent === "add_member") return "chat.toast.memberAdded";
|
||||
if (intent === "set_role") return "chat.toast.memberRoleChanged";
|
||||
if (intent === "remove_member") return "chat.toast.memberRemoved";
|
||||
if (intent === "leave") return "chat.toast.channelLeft";
|
||||
if (intent === "archive") return "chat.toast.channelArchived";
|
||||
return formData.get("privacy") === "public"
|
||||
? "chat.toast.channelMadePublic"
|
||||
: "chat.toast.channelMadePrivate";
|
||||
}
|
||||
|
||||
function withToast(path: string, messageKey: string): string {
|
||||
const separator = path.includes("?") ? "&" : "?";
|
||||
return `${path}${separator}toast=${encodeURIComponent(messageKey)}`;
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = {
|
||||
moduleKey: CHAT_MODULE_KEY,
|
||||
breadcrumbKey: "chat.channelSettings.title",
|
||||
};
|
||||
+355
@@ -0,0 +1,355 @@
|
||||
// @vitest-environment jsdom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import {
|
||||
buildChatChannelDetailVM,
|
||||
type ChatChannelDetailVM,
|
||||
type ChatMessageCandidate,
|
||||
type ChatMessageVM,
|
||||
type ChatResolvedAuthorVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { ChatChannelDetailPageProps } from "~/components/screens/chat/ChatChannelDetailPage";
|
||||
import type { UseChatChannelRealtimeInput } from "~/modules/chat/client/useChatChannelRealtime";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loaderData: undefined as unknown,
|
||||
fetcher: {
|
||||
data: undefined as unknown,
|
||||
state: "idle" as "idle" | "loading",
|
||||
load: vi.fn(),
|
||||
submit: vi.fn(),
|
||||
},
|
||||
navigate: vi.fn(),
|
||||
revalidate: vi.fn(),
|
||||
pageProps: undefined as ChatChannelDetailPageProps | undefined,
|
||||
renders: [] as Array<{ chatId: string; draft: string; messageIds: string[] }>,
|
||||
realtimeInputs: [] as Array<{ chatId: string; initialMessages: ChatMessageVM[] }>,
|
||||
}));
|
||||
|
||||
vi.mock("react-router", () => ({
|
||||
useLoaderData: () => mocks.loaderData,
|
||||
useNavigate: () => mocks.navigate,
|
||||
useRevalidator: () => ({ revalidate: mocks.revalidate }),
|
||||
useFetcher: () => mocks.fetcher,
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ csrf: "csrf", routing: { apiHost: "api.test", protocol: "https" } }),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
|
||||
vi.mock("~/modules/chat/client/useChatChannelRealtime", () => ({
|
||||
useChatChannelRealtime: (input: UseChatChannelRealtimeInput) => {
|
||||
const messages = [...input.initialMessages] as ChatMessageVM[];
|
||||
mocks.realtimeInputs.push({ chatId: input.chatId, initialMessages: messages });
|
||||
return {
|
||||
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
|
||||
messages,
|
||||
messageGroups: [],
|
||||
typingLabels: [],
|
||||
presence: [],
|
||||
sendMessage: () => null,
|
||||
restoreFailedMessage: () => null,
|
||||
retryMessage: () => null,
|
||||
discardMessage: () => false,
|
||||
updateTyping: () => undefined,
|
||||
stopTyping: () => undefined,
|
||||
beginMessageVisible: () => undefined,
|
||||
endMessageVisible: () => undefined,
|
||||
retryConnection: () => undefined,
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/components/screens/chat/ChatChannelDetailPage", () => ({
|
||||
ChatChannelDetailPage: (props: ChatChannelDetailPageProps) => {
|
||||
mocks.pageProps = props;
|
||||
const data = props.vm.status === "ready" ? props.vm.data : null;
|
||||
const snapshot = {
|
||||
chatId: data?.header.id ?? "unavailable",
|
||||
draft: props.draft,
|
||||
messageIds: data?.messages.map((message) => message.id) ?? [],
|
||||
};
|
||||
mocks.renders.push(snapshot);
|
||||
return (
|
||||
<div>
|
||||
<output data-testid="chat-id">{snapshot.chatId}</output>
|
||||
<output data-testid="draft">{snapshot.draft}</output>
|
||||
<output data-testid="message-count">{snapshot.messageIds.length}</output>
|
||||
<output data-testid="message-ids">{snapshot.messageIds.join(",")}</output>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({ loadChatContext: vi.fn() }));
|
||||
vi.mock("~/modules/chat/services/ChatService.server", () => ({
|
||||
loadMemberChatChannel: vi.fn(),
|
||||
sendMemberChatMessage: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/modules/chat/services/ChatMessageFeaturesService.server", () => ({
|
||||
changeChatMessagePin: vi.fn(),
|
||||
changeChatReaction: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/modules/chat/services/ChatMessageTaskService.server", () => ({ markChatMessageAsTask: vi.fn() }));
|
||||
vi.mock("~/utils/integrations/taskAccess.server", () => ({ loadTasksContext: vi.fn(), requireTasksPermission: vi.fn() }));
|
||||
|
||||
import ChatChannelDetailRoute from "./chat.$id";
|
||||
|
||||
const currentUser: ChatResolvedAuthorVM = {
|
||||
userId: "user_current",
|
||||
displayName: "Raffael",
|
||||
avatar: { imageUrl: null, fallbackLabel: "RS" },
|
||||
isCurrentUser: true,
|
||||
};
|
||||
|
||||
describe("chat channel detail route hydration", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal("localStorage", createMemoryStorage());
|
||||
mocks.fetcher.data = undefined;
|
||||
mocks.fetcher.state = "idle";
|
||||
mocks.pageProps = undefined;
|
||||
mocks.renders.length = 0;
|
||||
mocks.realtimeInputs.length = 0;
|
||||
window.history.replaceState({ idx: 0 }, "");
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("remounts every channel-local state owner before rendering a different chat", async () => {
|
||||
const chatA = routeData("chat_a", detailVm("chat_a", [message("chat_a_message", 1)]));
|
||||
const chatB = routeData("chat_b", detailVm("chat_b", [message("chat_b_message", 2)]));
|
||||
window.localStorage.setItem("chat:draft:chat_a", "Vertraulicher Entwurf aus A");
|
||||
mocks.loaderData = chatA;
|
||||
|
||||
const view = render(<ChatChannelDetailRoute />);
|
||||
await waitFor(() => expect(screen.getByTestId("draft")).toHaveTextContent("Vertraulicher Entwurf aus A"));
|
||||
|
||||
mocks.fetcher.data = routeData("chat_a", detailVm("chat_a", [message("chat_a_older", 0)], { hasOlder: false, olderCursor: null }));
|
||||
view.rerender(<ChatChannelDetailRoute />);
|
||||
await waitFor(() => expect(screen.getByTestId("message-ids")).toHaveTextContent("chat_a_older"));
|
||||
|
||||
mocks.loaderData = chatB;
|
||||
view.rerender(<ChatChannelDetailRoute />);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("chat-id")).toHaveTextContent("chat_b"));
|
||||
const chatBRenders = mocks.renders.filter((entry) => entry.chatId === "chat_b");
|
||||
expect(chatBRenders.length).toBeGreaterThan(0);
|
||||
expect(chatBRenders.every((entry) => entry.draft !== "Vertraulicher Entwurf aus A")).toBe(true);
|
||||
expect(chatBRenders.every((entry) => entry.messageIds.every((id) => id.startsWith("chat_b_")))).toBe(true);
|
||||
});
|
||||
|
||||
it("retains the page seam when a live revalidation shifts the newest fifty-message window", async () => {
|
||||
const initialNewest = messageRange(51, 100);
|
||||
mocks.loaderData = routeData("chat_long", detailVm("chat_long", initialNewest, { hasOlder: true, olderCursor: "before_51" }));
|
||||
const view = render(<ChatChannelDetailRoute />);
|
||||
|
||||
mocks.fetcher.data = routeData("chat_long", detailVm("chat_long", messageRange(1, 50), { hasOlder: false, olderCursor: null }));
|
||||
view.rerender(<ChatChannelDetailRoute />);
|
||||
await waitFor(() => expect(screen.getByTestId("message-count")).toHaveTextContent("100"));
|
||||
|
||||
mocks.fetcher.data = undefined;
|
||||
mocks.loaderData = routeData("chat_long", detailVm("chat_long", messageRange(52, 101), { hasOlder: true, olderCursor: "before_52" }), "stream:101");
|
||||
view.rerender(<ChatChannelDetailRoute />);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("message-count")).toHaveTextContent("101"));
|
||||
const ids = mocks.pageProps?.vm.status === "ready" ? mocks.pageProps.vm.data.messages.map((entry) => entry.id) : [];
|
||||
expect(ids).toHaveLength(101);
|
||||
expect(ids).toContain("message_051");
|
||||
expect(ids[0]).toBe("message_001");
|
||||
expect(ids.at(-1)).toBe("message_101");
|
||||
});
|
||||
|
||||
it("uses browser history for back navigation and falls back to the chat index", () => {
|
||||
mocks.loaderData = routeData("chat_a", detailVm("chat_a", []));
|
||||
window.history.replaceState({ idx: 2 }, "");
|
||||
const view = render(<ChatChannelDetailRoute />);
|
||||
|
||||
mocks.pageProps?.actions.onBack();
|
||||
expect(mocks.navigate).toHaveBeenLastCalledWith(-1);
|
||||
|
||||
mocks.navigate.mockClear();
|
||||
window.history.replaceState({ idx: 0 }, "");
|
||||
view.rerender(<ChatChannelDetailRoute />);
|
||||
mocks.pageProps?.actions.onBack();
|
||||
expect(mocks.navigate).toHaveBeenLastCalledWith("/demo/chat");
|
||||
});
|
||||
|
||||
it("shows reaction changes immediately, rolls them back on failure, and retries with the same request id", async () => {
|
||||
const candidate = message("message_feature", 1);
|
||||
candidate.actions = { ...candidate.actions, canReact: true, canPin: true };
|
||||
mocks.loaderData = routeData("chat_a", detailVm("chat_a", [candidate]));
|
||||
const view = render(<ChatChannelDetailRoute />);
|
||||
|
||||
act(() => mocks.pageProps?.actions.onToggleReaction?.("message_feature", "👍", true));
|
||||
await waitFor(() => {
|
||||
const data = mocks.pageProps?.vm.status === "ready" ? mocks.pageProps.vm.data : null;
|
||||
expect(data?.messages[0]?.reactions).toEqual([
|
||||
{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] },
|
||||
]);
|
||||
});
|
||||
const firstFormData = mocks.fetcher.submit.mock.calls[0]?.[0] as FormData;
|
||||
const requestId = firstFormData.get("requestId")?.toString() ?? "";
|
||||
expect(requestId).not.toBe("");
|
||||
|
||||
mocks.fetcher.data = { ok: false, requestId, errorKey: "chat.errors.invalidInput" };
|
||||
view.rerender(<ChatChannelDetailRoute />);
|
||||
await waitFor(() => {
|
||||
const data = mocks.pageProps?.vm.status === "ready" ? mocks.pageProps.vm.data : null;
|
||||
expect(data?.messages[0]?.reactions).toEqual([]);
|
||||
expect(mocks.pageProps?.featureErrorKeys).toEqual({ message_feature: "chat.errors.invalidInput" });
|
||||
});
|
||||
|
||||
act(() => mocks.pageProps?.actions.onRetryFeature?.("message_feature"));
|
||||
await waitFor(() => expect(mocks.fetcher.submit).toHaveBeenCalledTimes(2));
|
||||
const retryFormData = mocks.fetcher.submit.mock.calls[1]?.[0] as FormData;
|
||||
expect(retryFormData.get("requestId")).toBe(requestId);
|
||||
});
|
||||
|
||||
it("debounces member-scoped mention suggestions by 200 ms", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const baseVm = detailVm("chat_a", []);
|
||||
const mentionVm: ChatChannelDetailVM =
|
||||
baseVm.status === "ready"
|
||||
? { ...baseVm, data: { ...baseVm.data, composer: { ...baseVm.data.composer, canMention: true } } }
|
||||
: baseVm;
|
||||
mocks.loaderData = routeData("chat_a", mentionVm);
|
||||
render(<ChatChannelDetailRoute />);
|
||||
|
||||
act(() => mocks.pageProps?.actions.onDraftChange("@Ada", "chat:draft:chat_a", 4));
|
||||
await act(async () => undefined);
|
||||
act(() => vi.advanceTimersByTime(199));
|
||||
expect(mocks.fetcher.load).not.toHaveBeenCalled();
|
||||
|
||||
act(() => vi.advanceTimersByTime(1));
|
||||
expect(mocks.fetcher.load).toHaveBeenCalledWith("/demo/chat/chat_a/mentions?q=Ada");
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
function routeData(chatId: string, vm: ChatChannelDetailVM, eventCursor = "stream:100") {
|
||||
return {
|
||||
title: `${chatId} | HiveGrid`,
|
||||
tenantSlug: "demo",
|
||||
currentUserId: currentUser.userId,
|
||||
chatId,
|
||||
vm,
|
||||
eventCursor,
|
||||
authors: [currentUser],
|
||||
};
|
||||
}
|
||||
|
||||
function detailVm(
|
||||
chatId: string,
|
||||
messages: readonly ChatMessageCandidate[],
|
||||
history: { readonly hasOlder: boolean; readonly olderCursor: string | null } = { hasOlder: false, olderCursor: null }
|
||||
): ChatChannelDetailVM {
|
||||
return buildChatChannelDetailVM({
|
||||
header: {
|
||||
id: chatId,
|
||||
kind: "group",
|
||||
title: chatId,
|
||||
subtitle: null,
|
||||
avatar: { imageUrl: null, fallbackLabel: "C" },
|
||||
project: null,
|
||||
memberCount: 2,
|
||||
isPrivate: true,
|
||||
isArchived: false,
|
||||
isAuditMode: false,
|
||||
canManage: false,
|
||||
settingsHref: null,
|
||||
pinnedHref: null,
|
||||
searchHref: null,
|
||||
},
|
||||
messages,
|
||||
pinnedMessages: [],
|
||||
typingLabels: [],
|
||||
history,
|
||||
composer: {
|
||||
disabledReasonKey: null,
|
||||
canSend: true,
|
||||
canAttachFiles: false,
|
||||
canRecordVoice: false,
|
||||
canMention: false,
|
||||
canMarkAsTask: false,
|
||||
draftStorageKey: `chat:draft:${chatId}`,
|
||||
maxBodyLength: 4_000,
|
||||
},
|
||||
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
|
||||
});
|
||||
}
|
||||
|
||||
function messageRange(first: number, last: number): ChatMessageCandidate[] {
|
||||
return Array.from({ length: last - first + 1 }, (_, offset) => message(`message_${String(first + offset).padStart(3, "0")}`, first + offset));
|
||||
}
|
||||
|
||||
function message(id: string, order: number): ChatMessageCandidate {
|
||||
const timestamp = new Date(Date.UTC(2026, 0, 1, 0, order)).toISOString();
|
||||
return {
|
||||
id,
|
||||
clientMessageId: `client_${id}`,
|
||||
source: "persisted",
|
||||
deliveryState: "sent",
|
||||
failureReasonKey: null,
|
||||
author: currentUser,
|
||||
bodyMarkdown: id,
|
||||
bodyFormat: "markdown",
|
||||
systemEvent: null,
|
||||
createdAtIso: timestamp,
|
||||
updatedAtIso: timestamp,
|
||||
editedAtIso: null,
|
||||
deletedAtIso: null,
|
||||
parentMessageId: null,
|
||||
mentions: [],
|
||||
reactions: [],
|
||||
thread: null,
|
||||
attachments: [],
|
||||
linkPreviews: [],
|
||||
readAggregate: {
|
||||
readCount: 0,
|
||||
recipientCount: 1,
|
||||
readerUserIds: [],
|
||||
readerLabels: [],
|
||||
labelKey: "chat.message.read.aggregate",
|
||||
},
|
||||
pin: null,
|
||||
actions: {
|
||||
canReact: false,
|
||||
canReply: false,
|
||||
canEdit: false,
|
||||
canDelete: false,
|
||||
canPin: false,
|
||||
canMarkAsTask: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createMemoryStorage(): Storage {
|
||||
const values = new Map<string, string>();
|
||||
return {
|
||||
get length() {
|
||||
return values.size;
|
||||
},
|
||||
clear: () => values.clear(),
|
||||
getItem: (key) => values.get(key) ?? null,
|
||||
key: (index) => [...values.keys()][index] ?? null,
|
||||
removeItem: (key) => {
|
||||
values.delete(key);
|
||||
},
|
||||
setItem: (key, value) => {
|
||||
values.set(key, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate, useRevalidator } from "react-router";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { extractChatMentions, findChatMentionQuery, insertChatMention, type ChatMentionQuery, type ChatMentionType } from "@hivegrid/realtime";
|
||||
import type { ChatMentionAutocompleteVM, ChatMentionSuggestionVM, ChatResolvedMentionVM, ChatThreadVM } from "@hivegrid/view-models";
|
||||
|
||||
import { ChatThreadPage, type ChatOptimisticThreadReply } from "~/components/screens/chat/ChatThreadPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useChatChannelRealtime } from "~/modules/chat/client/useChatChannelRealtime";
|
||||
import {
|
||||
beginChatMessageMutation,
|
||||
chatMessageMutationErrors,
|
||||
failedChatMessageMutationForMessage,
|
||||
overlayChatThreadMessageMutations,
|
||||
reconcileChatThreadMessageMutations,
|
||||
retryChatMessageMutation,
|
||||
settleChatMessageMutation,
|
||||
type ChatOptimisticMessageMutation,
|
||||
type ChatOptimisticMessageMutationInput,
|
||||
} from "~/modules/chat/client/chatMessageMutationOptimistic";
|
||||
import {
|
||||
beginChatFeatureMutation,
|
||||
chatFeatureErrorsByMessageId,
|
||||
failedChatFeatureMutationForMessage,
|
||||
overlayChatThreadFeatureMutations,
|
||||
reconcileChatThreadFeatureMutations,
|
||||
settleChatFeatureMutation,
|
||||
type ChatOptimisticFeatureMutation,
|
||||
type ChatOptimisticFeatureMutationInput,
|
||||
} from "~/modules/chat/client/ChatFeatureOptimistic";
|
||||
import { loadChatContext } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { CHAT_MODULE_KEY } from "~/modules/chat/routes/chatRoutePaths";
|
||||
import { changeChatMessagePin, changeChatReaction, createChatThreadReply, loadChatThreadPage } from "~/modules/chat/services/ChatMessageFeaturesService.server";
|
||||
import { editMemberChatMessage, removeMemberChatMessage } from "~/modules/chat/services/ChatMessageMutationsService.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
readonly title: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly currentUserId: string;
|
||||
readonly chatId: string;
|
||||
readonly eventCursor: string;
|
||||
readonly vm: ChatThreadVM;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
readonly ok: boolean;
|
||||
readonly intent: string;
|
||||
readonly requestId: string;
|
||||
readonly errorKey: string | null;
|
||||
readonly messageId: string | null;
|
||||
};
|
||||
|
||||
type PendingThreadReply = ChatOptimisticThreadReply &
|
||||
Readonly<{
|
||||
requestId: string;
|
||||
serverMessageId: string | null;
|
||||
}>;
|
||||
|
||||
type MentionLoaderData = {
|
||||
readonly query: string;
|
||||
readonly type: ChatMentionType | null;
|
||||
readonly vm: ChatMentionAutocompleteVM;
|
||||
};
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
||||
const result = await loadChatThreadPage({
|
||||
context,
|
||||
tenantSlug: params.tenant ?? "",
|
||||
chatId: params.id ?? "",
|
||||
threadId: params.threadId ?? "",
|
||||
labels: featureLabels(t),
|
||||
});
|
||||
const { vm } = result;
|
||||
const channelTitle = vm.status === "ready" ? vm.data.channelTitle : t("chat.thread.titleFallback");
|
||||
return Response.json({
|
||||
title: `${t("chat.thread.title", { channel: channelTitle })} | ${process.env.APP_NAME}`,
|
||||
tenantSlug: params.tenant ?? "",
|
||||
currentUserId: context.userId,
|
||||
chatId: params.id ?? "",
|
||||
eventCursor: result.eventCursor,
|
||||
vm,
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const context = await loadChatContext({ request, params });
|
||||
const formData = await request.formData();
|
||||
await validateCSRFToken(request, { formData });
|
||||
const intent = formValue(formData, "intent");
|
||||
const requestId = formValue(formData, "requestId");
|
||||
const chatId = params.id ?? "";
|
||||
const threadId = params.threadId ?? "";
|
||||
let messageId: string | null = null;
|
||||
try {
|
||||
if (intent === "reply") {
|
||||
const result = await createChatThreadReply({
|
||||
context,
|
||||
chatId,
|
||||
threadId,
|
||||
requestId,
|
||||
clientMessageId: formValue(formData, "clientMessageId"),
|
||||
body: formValue(formData, "body"),
|
||||
});
|
||||
messageId = result.message.id;
|
||||
} else if (intent === "reaction") {
|
||||
await changeChatReaction({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
messageId: formValue(formData, "messageId"),
|
||||
emoji: formValue(formData, "emoji"),
|
||||
active: formValue(formData, "active") === "true",
|
||||
});
|
||||
} else if (intent === "pin") {
|
||||
await changeChatMessagePin({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
messageId: formValue(formData, "messageId"),
|
||||
pinned: formValue(formData, "pinned") === "true",
|
||||
});
|
||||
} else if (intent === "edit_message") {
|
||||
await editMemberChatMessage({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
messageId: formValue(formData, "messageId"),
|
||||
body: formValue(formData, "body"),
|
||||
});
|
||||
} else if (intent === "delete_message") {
|
||||
await removeMemberChatMessage({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
messageId: formValue(formData, "messageId"),
|
||||
});
|
||||
} else {
|
||||
return Response.json({ ok: false, intent, requestId, errorKey: "chat.errors.invalidInput", messageId: null } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
return Response.json({ ok: true, intent, requestId, errorKey: null, messageId } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ ok: false, intent, requestId, errorKey: error.i18nKey, messageId: null } satisfies ActionData, { status: error.status });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatThreadRoute(): React.JSX.Element {
|
||||
const loaderData = useLoaderData<LoaderData>();
|
||||
const authoritativeVm = loaderData.vm;
|
||||
const navigate = useNavigate();
|
||||
const revalidator = useRevalidator();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const mentionFetcher = useFetcher<MentionLoaderData>();
|
||||
const { csrf, routing } = useRootData();
|
||||
const [draft, setDraft] = useState("");
|
||||
const [composerCaret, setComposerCaret] = useState(0);
|
||||
const [mentionQuery, setMentionQuery] = useState<ChatMentionQuery | null>(null);
|
||||
const [mentionActiveIndex, setMentionActiveIndex] = useState(0);
|
||||
const [featureMutations, setFeatureMutations] = useState<readonly ChatOptimisticFeatureMutation[]>([]);
|
||||
const [messageMutations, setMessageMutations] = useState<readonly ChatOptimisticMessageMutation[]>([]);
|
||||
const [pendingReplies, setPendingReplies] = useState<readonly PendingThreadReply[]>([]);
|
||||
const submittedIntent = useRef<string | null>(null);
|
||||
const handledReplyResponse = useRef<string | null>(null);
|
||||
const vm = overlayChatThreadMessageMutations(overlayChatThreadFeatureMutations(authoritativeVm, featureMutations), messageMutations);
|
||||
const mentionResponseMatches = mentionQuery !== null && mentionFetcher.data?.query === mentionQuery.query && mentionFetcher.data.type === mentionQuery.kind;
|
||||
const mentionVm = mentionResponseMatches ? (mentionFetcher.data?.vm ?? null) : null;
|
||||
const mentionItems = mentionVm?.groups.flatMap((group) => group.items) ?? [];
|
||||
|
||||
useEffect(() => {
|
||||
const query = findChatMentionQuery(draft, composerCaret);
|
||||
setMentionQuery(query);
|
||||
setMentionActiveIndex(0);
|
||||
if (!query) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
const search = new URLSearchParams({ q: query.query });
|
||||
if (query.kind) search.set("type", query.kind);
|
||||
void mentionFetcher.load(`/${encodeURIComponent(loaderData.tenantSlug)}/chat/${encodeURIComponent(loaderData.chatId)}/mentions?${search.toString()}`);
|
||||
}, 200);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [composerCaret, draft, loaderData.chatId, loaderData.tenantSlug]);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.state !== "idle" || !fetcher.data?.ok || submittedIntent.current === null) return;
|
||||
submittedIntent.current = null;
|
||||
}, [fetcher.data, fetcher.state]);
|
||||
|
||||
useEffect(() => {
|
||||
const result = fetcher.data;
|
||||
if (fetcher.state !== "idle" || !result || result.intent !== "reply" || handledReplyResponse.current === result.requestId) return;
|
||||
handledReplyResponse.current = result.requestId;
|
||||
setPendingReplies((current) =>
|
||||
current.map((reply) =>
|
||||
reply.requestId !== result.requestId
|
||||
? reply
|
||||
: {
|
||||
...reply,
|
||||
deliveryState: result.ok ? "sent" : "failed",
|
||||
failureReasonKey: result.ok ? null : (result.errorKey ?? "chat.message.sendFailed"),
|
||||
serverMessageId: result.messageId,
|
||||
}
|
||||
)
|
||||
);
|
||||
if (result.ok) revalidator.revalidate();
|
||||
}, [fetcher.data, fetcher.state, revalidator]);
|
||||
|
||||
useEffect(() => {
|
||||
if (authoritativeVm.status !== "ready") return;
|
||||
const hydratedIds = new Set(authoritativeVm.data.replies.map((reply) => reply.id));
|
||||
setPendingReplies((current) => current.filter((reply) => !reply.serverMessageId || !hydratedIds.has(reply.serverMessageId)));
|
||||
}, [authoritativeVm]);
|
||||
|
||||
useEffect(() => {
|
||||
setFeatureMutations((current) => reconcileChatThreadFeatureMutations(current, authoritativeVm));
|
||||
setMessageMutations((current) => reconcileChatThreadMessageMutations(current, authoritativeVm));
|
||||
}, [authoritativeVm]);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.state !== "idle" || !fetcher.data || fetcher.data.intent === "reply") return;
|
||||
if (fetcher.data.intent === "edit_message" || fetcher.data.intent === "delete_message") {
|
||||
setMessageMutations((current) => settleChatMessageMutation(current, fetcher.data!));
|
||||
return;
|
||||
}
|
||||
setFeatureMutations((current) => settleChatFeatureMutation(current, fetcher.data!.requestId, fetcher.data!));
|
||||
}, [fetcher.data, fetcher.state]);
|
||||
useChatChannelRealtime({
|
||||
enabled: vm.status === "ready",
|
||||
tenantSlug: loaderData.tenantSlug,
|
||||
chatId: loaderData.chatId,
|
||||
initialCursor: loaderData.eventCursor,
|
||||
csrfToken: csrf ?? null,
|
||||
routing,
|
||||
initialMessages: [],
|
||||
currentUser: {
|
||||
userId: loaderData.currentUserId,
|
||||
displayName: loaderData.currentUserId,
|
||||
avatar: { imageUrl: null, fallbackLabel: "?" },
|
||||
isCurrentUser: true,
|
||||
},
|
||||
unknownAuthorLabel: "?",
|
||||
resolveAuthor: () => null,
|
||||
revalidate: () => revalidator.revalidate(),
|
||||
});
|
||||
|
||||
function submit(intent: string, values: Record<string, string>): void {
|
||||
if (fetcher.state !== "idle") return;
|
||||
submittedIntent.current = intent;
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", csrf ?? "");
|
||||
formData.set("intent", intent);
|
||||
formData.set("requestId", crypto.randomUUID());
|
||||
for (const [key, value] of Object.entries(values)) formData.set(key, value);
|
||||
void fetcher.submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
function sendReply(body: string): void {
|
||||
const normalized = body.trim();
|
||||
if (!normalized || fetcher.state !== "idle") return;
|
||||
const requestId = crypto.randomUUID();
|
||||
const clientMessageId = crypto.randomUUID();
|
||||
handledReplyResponse.current = null;
|
||||
setPendingReplies((current) => [
|
||||
...current,
|
||||
{
|
||||
requestId,
|
||||
clientMessageId,
|
||||
serverMessageId: null,
|
||||
authorLabel: loaderData.currentUserId,
|
||||
bodyMarkdown: normalized,
|
||||
createdAtIso: new Date().toISOString(),
|
||||
deliveryState: "sending",
|
||||
failureReasonKey: null,
|
||||
},
|
||||
]);
|
||||
setDraft("");
|
||||
setComposerCaret(0);
|
||||
setMentionQuery(null);
|
||||
submit("reply", { body: normalized, clientMessageId, requestId });
|
||||
}
|
||||
|
||||
function retryReply(clientMessageId: string): void {
|
||||
if (fetcher.state !== "idle") return;
|
||||
const failed = pendingReplies.find((reply) => reply.clientMessageId === clientMessageId && reply.deliveryState === "failed");
|
||||
if (!failed) return;
|
||||
const requestId = crypto.randomUUID();
|
||||
handledReplyResponse.current = null;
|
||||
setPendingReplies((current) =>
|
||||
current.map((reply) =>
|
||||
reply.clientMessageId === clientMessageId ? { ...reply, requestId, serverMessageId: null, deliveryState: "sending", failureReasonKey: null } : reply
|
||||
)
|
||||
);
|
||||
submit("reply", { body: failed.bodyMarkdown, clientMessageId, requestId });
|
||||
}
|
||||
|
||||
function submitFeatureMutation(mutation: ChatOptimisticFeatureMutationInput): void {
|
||||
if (fetcher.state !== "idle") return;
|
||||
setFeatureMutations((current) => beginChatFeatureMutation(current, mutation));
|
||||
submit(mutation.kind, {
|
||||
requestId: mutation.requestId,
|
||||
messageId: mutation.messageId,
|
||||
...(mutation.kind === "reaction" ? { emoji: mutation.emoji, active: String(mutation.active) } : { pinned: String(mutation.pinned) }),
|
||||
});
|
||||
}
|
||||
|
||||
function beginFeatureMutation(
|
||||
input:
|
||||
| { readonly kind: "reaction"; readonly messageId: string; readonly emoji: string; readonly active: boolean }
|
||||
| { readonly kind: "pin"; readonly messageId: string; readonly pinned: boolean }
|
||||
): void {
|
||||
submitFeatureMutation({
|
||||
...input,
|
||||
requestId: crypto.randomUUID(),
|
||||
actorLabel: loaderData.currentUserId,
|
||||
startedAtIso: new Date().toISOString(),
|
||||
} as ChatOptimisticFeatureMutationInput);
|
||||
}
|
||||
|
||||
function retryFeatureMutation(messageId: string): void {
|
||||
const messageMutation = failedChatMessageMutationForMessage(messageMutations, messageId);
|
||||
if (messageMutation) {
|
||||
setMessageMutations((current) => retryChatMessageMutation(current, messageMutation.requestId));
|
||||
submit(messageMutation.kind, {
|
||||
requestId: messageMutation.requestId,
|
||||
messageId: messageMutation.messageId,
|
||||
...(messageMutation.kind === "edit_message" ? { body: messageMutation.bodyMarkdown } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const mutation = failedChatFeatureMutationForMessage(featureMutations, messageId);
|
||||
if (!mutation) return;
|
||||
submitFeatureMutation(mutation);
|
||||
}
|
||||
|
||||
function submitMessageMutation(mutation: ChatOptimisticMessageMutationInput): void {
|
||||
if (fetcher.state !== "idle") return;
|
||||
setMessageMutations((current) => beginChatMessageMutation(current, mutation));
|
||||
submit(mutation.kind, {
|
||||
requestId: mutation.requestId,
|
||||
messageId: mutation.messageId,
|
||||
...(mutation.kind === "edit_message" ? { body: mutation.bodyMarkdown } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function mentionsForEditedBody(messageId: string, body: string): readonly ChatResolvedMentionVM[] {
|
||||
if (vm.status !== "ready") return [];
|
||||
const message = [vm.data.parent, ...vm.data.replies].find((candidate) => candidate.id === messageId);
|
||||
if (!message) return [];
|
||||
const available = new Map(message.mentions.map((mention) => [`${mention.kind}\u0000${mention.id}`, mention]));
|
||||
try {
|
||||
return extractChatMentions(body).flatMap((mention) => {
|
||||
const resolved = available.get(`${mention.type}\u0000${mention.id}`);
|
||||
return resolved ? [resolved] : [];
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function selectMention(suggestion: ChatMentionSuggestionVM): number | null {
|
||||
if (!mentionQuery) return null;
|
||||
const inserted = insertChatMention(draft, mentionQuery, { type: suggestion.kind, id: suggestion.id });
|
||||
setDraft(inserted.body);
|
||||
setComposerCaret(inserted.caret);
|
||||
setMentionQuery(null);
|
||||
return inserted.caret;
|
||||
}
|
||||
|
||||
function handleMentionKeyDown(key: "ArrowDown" | "ArrowUp" | "Enter" | "Escape"): boolean {
|
||||
if (!mentionQuery) return false;
|
||||
if (key === "Escape") {
|
||||
setMentionQuery(null);
|
||||
return true;
|
||||
}
|
||||
if (key === "ArrowDown" || key === "ArrowUp") {
|
||||
if (mentionItems.length === 0) return false;
|
||||
setMentionActiveIndex((current) =>
|
||||
key === "ArrowDown" ? (current + 1) % mentionItems.length : (current - 1 + mentionItems.length) % mentionItems.length
|
||||
);
|
||||
return true;
|
||||
}
|
||||
const selected = mentionItems[mentionActiveIndex];
|
||||
if (!selected) return false;
|
||||
selectMention(selected);
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
<ChatThreadPage
|
||||
vm={vm}
|
||||
draft={draft}
|
||||
busy={fetcher.state !== "idle"}
|
||||
errorKey={fetcher.data?.ok === false && fetcher.data.intent === "reply" ? fetcher.data.errorKey : null}
|
||||
featureErrorKeys={{ ...chatFeatureErrorsByMessageId(featureMutations), ...chatMessageMutationErrors(messageMutations) }}
|
||||
mentionAutocomplete={{
|
||||
vm: mentionVm,
|
||||
open: mentionQuery !== null,
|
||||
loading: mentionQuery !== null && (!mentionResponseMatches || mentionFetcher.state !== "idle"),
|
||||
activeIndex: Math.min(mentionActiveIndex, Math.max(0, mentionItems.length - 1)),
|
||||
listboxId: "chat-thread-mention-listbox",
|
||||
}}
|
||||
optimisticReplies={pendingReplies}
|
||||
actions={{
|
||||
onBack: (href) => void navigate(href),
|
||||
onDraftChange: (value, caret) => {
|
||||
setDraft(value);
|
||||
setComposerCaret(caret);
|
||||
},
|
||||
onSendReply: sendReply,
|
||||
onToggleReaction: (messageId, emoji, active) => beginFeatureMutation({ kind: "reaction", messageId, emoji, active }),
|
||||
onTogglePin: (messageId, pinned) => beginFeatureMutation({ kind: "pin", messageId, pinned }),
|
||||
onEditMessage: (messageId, body) =>
|
||||
submitMessageMutation({
|
||||
kind: "edit_message",
|
||||
messageId,
|
||||
bodyMarkdown: body,
|
||||
mentions: mentionsForEditedBody(messageId, body),
|
||||
requestId: crypto.randomUUID(),
|
||||
startedAtIso: new Date().toISOString(),
|
||||
}),
|
||||
onDeleteMessage: (messageId) =>
|
||||
submitMessageMutation({
|
||||
kind: "delete_message",
|
||||
messageId,
|
||||
requestId: crypto.randomUUID(),
|
||||
startedAtIso: new Date().toISOString(),
|
||||
}),
|
||||
onMentionActiveIndexChange: setMentionActiveIndex,
|
||||
onMentionSelect: selectMention,
|
||||
onMentionKeyDown: handleMentionKeyDown,
|
||||
onRetryReply: retryReply,
|
||||
onDiscardReply: (clientMessageId) => setPendingReplies((current) => current.filter((reply) => reply.clientMessageId !== clientMessageId)),
|
||||
onRetryFeature: retryFeatureMutation,
|
||||
onRetry: () => revalidator.revalidate(),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function formValue(formData: FormData, key: string): string {
|
||||
return formData.get(key)?.toString().trim() ?? "";
|
||||
}
|
||||
|
||||
function featureLabels(t: (key: string) => string) {
|
||||
return {
|
||||
directMessage: t("chat.channel.fallback.directMessage"),
|
||||
unnamedGroup: t("chat.channel.fallback.group"),
|
||||
unnamedProject: t("chat.channel.fallback.project"),
|
||||
unknownUser: t("chat.participant.unknown"),
|
||||
unknownMention: t("chat.mention.unknown"),
|
||||
};
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CHAT_MODULE_KEY, breadcrumbKey: "chat.thread.breadcrumb" };
|
||||
+732
@@ -0,0 +1,732 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate, useRevalidator } from "react-router";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { extractChatMentions, findChatMentionQuery, insertChatMention, type ChatMentionQuery, type ChatMentionType } from "@hivegrid/realtime";
|
||||
import {
|
||||
chatMessageIdentityKey,
|
||||
type ChatMentionAutocompleteVM,
|
||||
type ChatMentionSuggestionVM,
|
||||
type ChatChannelDetailVM,
|
||||
type ChatMessageVM,
|
||||
type ChatResolvedMentionVM,
|
||||
type ChatResolvedAuthorVM,
|
||||
} from "@hivegrid/view-models";
|
||||
|
||||
import { ChatChannelDetailPage } from "~/components/screens/chat/ChatChannelDetailPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { overlayChatChannelDetailRealtime } from "~/modules/chat/client/chatRealtimeViewModel";
|
||||
import {
|
||||
beginChatFeatureMutation,
|
||||
chatFeatureErrorsByMessageId,
|
||||
failedChatFeatureMutationForMessage,
|
||||
overlayChatChannelFeatureMutations,
|
||||
reconcileChatChannelFeatureMutations,
|
||||
retryChatFeatureMutation,
|
||||
settleChatFeatureMutation,
|
||||
type ChatOptimisticFeatureMutation,
|
||||
type ChatOptimisticFeatureMutationInput,
|
||||
} from "~/modules/chat/client/ChatFeatureOptimistic";
|
||||
import { overlayChatAttachmentSendAttempt, type ChatAttachmentSendAttempt } from "~/modules/chat/client/chatAttachmentOptimistic";
|
||||
import { useChatAttachmentUploads } from "~/modules/chat/client/useChatAttachmentUploads";
|
||||
import { useChatChannelRealtime } from "~/modules/chat/client/useChatChannelRealtime";
|
||||
import {
|
||||
beginChatMessageMutation,
|
||||
chatMessageMutationErrors,
|
||||
failedChatMessageMutationForMessage,
|
||||
overlayChatMessageMutations,
|
||||
reconcileChatMessageMutations,
|
||||
retryChatMessageMutation,
|
||||
settleChatMessageMutation,
|
||||
type ChatOptimisticMessageMutation,
|
||||
type ChatOptimisticMessageMutationInput,
|
||||
} from "~/modules/chat/client/chatMessageMutationOptimistic";
|
||||
import { useChatDraft } from "~/modules/chat/client/useChatDraft";
|
||||
import { loadChatContext } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { CHAT_MODULE_KEY, chatChannelPath, chatIndexPath, chatThreadPath } from "~/modules/chat/routes/chatRoutePaths";
|
||||
import { loadMemberChatChannel, sendMemberChatMessage } from "~/modules/chat/services/ChatService.server";
|
||||
import { changeChatMessagePin, changeChatReaction } from "~/modules/chat/services/ChatMessageFeaturesService.server";
|
||||
import { markChatMessageAsTask } from "~/modules/chat/services/ChatMessageTaskService.server";
|
||||
import { editMemberChatMessage, removeMemberChatMessage } from "~/modules/chat/services/ChatMessageMutationsService.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { loadTasksContext, requireTasksPermission } from "~/utils/integrations/taskAccess.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
readonly title: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly currentUserId: string;
|
||||
readonly chatId: string;
|
||||
readonly vm: ChatChannelDetailVM;
|
||||
readonly eventCursor: string;
|
||||
readonly authors: readonly ChatResolvedAuthorVM[];
|
||||
readonly focusMessageId: string | null;
|
||||
};
|
||||
|
||||
type ActionIntent = "reaction" | "pin" | "send_attachment_message" | "mark_task" | "edit_message" | "delete_message";
|
||||
type ActionData = {
|
||||
readonly ok: boolean;
|
||||
readonly intent: ActionIntent | "invalid";
|
||||
readonly requestId: string;
|
||||
readonly errorKey: string | null;
|
||||
readonly messageId: string | null;
|
||||
readonly taskId: string | null;
|
||||
readonly replayed: boolean | null;
|
||||
};
|
||||
|
||||
type MentionLoaderData = {
|
||||
readonly query: string;
|
||||
readonly type: ChatMentionType | null;
|
||||
readonly vm: ChatMentionAutocompleteVM;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const chatId = params.id ?? "";
|
||||
const url = new URL(request.url);
|
||||
const beforeMessageCursor = url.searchParams.get("before") ?? undefined;
|
||||
const focusMessageId = beforeMessageCursor ? null : url.searchParams.get("message")?.trim() || null;
|
||||
const result = await loadMemberChatChannel({
|
||||
context,
|
||||
tenantSlug,
|
||||
chatId,
|
||||
...(beforeMessageCursor ? { beforeMessageCursor } : {}),
|
||||
...(focusMessageId ? { focusMessageId } : {}),
|
||||
labels: {
|
||||
directMessage: t("chat.channel.fallback.directMessage"),
|
||||
unnamedGroup: t("chat.channel.fallback.group"),
|
||||
unnamedProject: t("chat.channel.fallback.project"),
|
||||
unknownUser: t("chat.participant.unknown"),
|
||||
unknownMention: t("chat.mention.unknown"),
|
||||
},
|
||||
});
|
||||
const channelTitle = result.vm.status === "ready" ? result.vm.data.header.title : t("chat.titleFallback");
|
||||
|
||||
return Response.json({
|
||||
title: `${channelTitle} | ${process.env.APP_NAME}`,
|
||||
tenantSlug,
|
||||
currentUserId: context.userId,
|
||||
chatId,
|
||||
focusMessageId,
|
||||
...result,
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const context = await loadChatContext({ request, params });
|
||||
const formData = await request.formData();
|
||||
await validateCSRFToken(request, { formData });
|
||||
const intent = formData.get("intent")?.toString() ?? "";
|
||||
const chatId = params.id ?? "";
|
||||
const requestId = formData.get("requestId")?.toString() ?? "";
|
||||
try {
|
||||
let messageId: string | null = null;
|
||||
let taskId: string | null = null;
|
||||
let replayed: boolean | null = null;
|
||||
if (intent === "reaction") {
|
||||
await changeChatReaction({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
messageId: formData.get("messageId")?.toString() ?? "",
|
||||
emoji: formData.get("emoji")?.toString() ?? "",
|
||||
active: formData.get("active")?.toString() === "true",
|
||||
});
|
||||
} else if (intent === "pin") {
|
||||
await changeChatMessagePin({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
messageId: formData.get("messageId")?.toString() ?? "",
|
||||
pinned: formData.get("pinned")?.toString() === "true",
|
||||
});
|
||||
} else if (intent === "send_attachment_message") {
|
||||
const attachmentFileIds = parseAttachmentFileIds(formData.get("attachmentFileIds"));
|
||||
const clientMessageId = formData.get("clientMessageId")?.toString().trim() ?? "";
|
||||
if (!requestId || !clientMessageId || attachmentFileIds === null || attachmentFileIds.length === 0) {
|
||||
return actionResponse({ ok: false, intent: "send_attachment_message", requestId, errorKey: "chat.errors.invalidInput" }, 400);
|
||||
}
|
||||
const result = await sendMemberChatMessage({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
clientMessageId,
|
||||
body: formData.get("body")?.toString() ?? "",
|
||||
attachmentFileIds,
|
||||
});
|
||||
messageId = result.message.id;
|
||||
} else if (intent === "mark_task") {
|
||||
const messageToMarkId = formData.get("messageId")?.toString().trim() ?? "";
|
||||
if (!requestId || !messageToMarkId) {
|
||||
return actionResponse({ ok: false, intent: "mark_task", requestId, errorKey: "chat.errors.invalidInput" }, 400);
|
||||
}
|
||||
const [{ t }, taskContext] = await Promise.all([getTranslations(request), loadTasksContext({ request, params, requireModule: true })]);
|
||||
requireTasksPermission(taskContext, "tasks.write");
|
||||
const result = await markChatMessageAsTask({
|
||||
chatContext: context,
|
||||
taskContext,
|
||||
chatId,
|
||||
messageId: messageToMarkId,
|
||||
requestId,
|
||||
tenantSlug: params.tenant ?? "",
|
||||
fallbackTitle: t("chat.task.fallbackTitle"),
|
||||
});
|
||||
taskId = result.taskId;
|
||||
replayed = result.replayed;
|
||||
} else if (intent === "edit_message") {
|
||||
const result = await editMemberChatMessage({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
messageId: formData.get("messageId")?.toString() ?? "",
|
||||
body: formData.get("body")?.toString() ?? "",
|
||||
});
|
||||
messageId = result.message.id;
|
||||
replayed = result.replayed;
|
||||
} else if (intent === "delete_message") {
|
||||
const result = await removeMemberChatMessage({
|
||||
context,
|
||||
chatId,
|
||||
requestId,
|
||||
messageId: formData.get("messageId")?.toString() ?? "",
|
||||
});
|
||||
messageId = result.messageId;
|
||||
replayed = result.replayed;
|
||||
} else {
|
||||
return actionResponse({ ok: false, intent: "invalid", requestId, errorKey: "chat.errors.invalidInput" }, 400);
|
||||
}
|
||||
return actionResponse({ ok: true, intent: intent as ActionIntent, requestId, errorKey: null, messageId, taskId, replayed });
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
return actionResponse({ ok: false, intent: isActionIntent(intent) ? intent : "invalid", requestId, errorKey: error.i18nKey }, error.status);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function actionResponse(
|
||||
input: Pick<ActionData, "ok" | "intent" | "requestId" | "errorKey"> & Partial<Pick<ActionData, "messageId" | "taskId" | "replayed">>,
|
||||
status = 200
|
||||
): Response {
|
||||
return Response.json(
|
||||
{
|
||||
...input,
|
||||
messageId: input.messageId ?? null,
|
||||
taskId: input.taskId ?? null,
|
||||
replayed: input.replayed ?? null,
|
||||
} satisfies ActionData,
|
||||
{ status }
|
||||
);
|
||||
}
|
||||
|
||||
function isActionIntent(value: string): value is ActionIntent {
|
||||
return (
|
||||
value === "reaction" ||
|
||||
value === "pin" ||
|
||||
value === "send_attachment_message" ||
|
||||
value === "mark_task" ||
|
||||
value === "edit_message" ||
|
||||
value === "delete_message"
|
||||
);
|
||||
}
|
||||
|
||||
export function parseAttachmentFileIds(value: FormDataEntryValue | null): readonly string[] | null {
|
||||
if (typeof value !== "string") return null;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!Array.isArray(parsed) || parsed.length > 20) return null;
|
||||
const ids = parsed.map((id) => (typeof id === "string" ? id.trim() : ""));
|
||||
if (ids.some((id) => id.length === 0) || new Set(ids).size !== ids.length) return null;
|
||||
return ids;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatChannelDetailRoute(): React.JSX.Element {
|
||||
const loaderData = useLoaderData<LoaderData>();
|
||||
|
||||
return <ChatChannelDetailController key={`${loaderData.tenantSlug}\u0000${loaderData.currentUserId}\u0000${loaderData.chatId}`} loaderData={loaderData} />;
|
||||
}
|
||||
|
||||
function ChatChannelDetailController({ loaderData }: { readonly loaderData: LoaderData }): React.JSX.Element {
|
||||
const { t } = useTranslation();
|
||||
const rootData = useRootData();
|
||||
const navigate = useNavigate();
|
||||
const revalidator = useRevalidator();
|
||||
const olderFetcher = useFetcher<LoaderData>();
|
||||
const featureFetcher = useFetcher<ActionData>();
|
||||
const mutationFetcher = useFetcher<ActionData>();
|
||||
const mentionFetcher = useFetcher<MentionLoaderData>();
|
||||
const attachmentFetcher = useFetcher<ActionData>();
|
||||
const taskFetcher = useFetcher<ActionData>();
|
||||
const readyData = loaderData.vm.status === "ready" ? loaderData.vm.data : null;
|
||||
const [hydratedMessages, setHydratedMessages] = useState<readonly ChatMessageVM[]>(() => readyData?.messages ?? []);
|
||||
const [olderHistory, setOlderHistory] = useState<NonNullable<ChatChannelDetailVM["data"]>["history"] | null>(null);
|
||||
const [featureMutations, setFeatureMutations] = useState<readonly ChatOptimisticFeatureMutation[]>([]);
|
||||
const [messageMutations, setMessageMutations] = useState<readonly ChatOptimisticMessageMutation[]>([]);
|
||||
const [composerCaret, setComposerCaret] = useState(0);
|
||||
const [mentionQuery, setMentionQuery] = useState<ChatMentionQuery | null>(null);
|
||||
const [mentionActiveIndex, setMentionActiveIndex] = useState(0);
|
||||
const [selectedMentionLabels, setSelectedMentionLabels] = useState<ReadonlyMap<string, ChatResolvedMentionVM>>(new Map());
|
||||
const [markingTaskMessageId, setMarkingTaskMessageId] = useState<string | null>(null);
|
||||
const [attachmentSendAttempt, setAttachmentSendAttempt] = useState<ChatAttachmentSendAttempt | null>(null);
|
||||
const attachmentAttemptRef = useRef<ChatAttachmentSendAttempt | null>(null);
|
||||
const handledAttachmentRequestRef = useRef<string | null>(null);
|
||||
const handledTaskRequestRef = useRef<string | null>(null);
|
||||
const authorById = useMemo(() => new Map(loaderData.authors.map((author) => [author.userId, author])), [loaderData.authors]);
|
||||
const currentUser = authorById.get(loaderData.currentUserId) ?? fallbackCurrentUser(loaderData.currentUserId, t("chat.participant.unknown"));
|
||||
const attachmentUploads = useChatAttachmentUploads({
|
||||
tenantSlug: loaderData.tenantSlug,
|
||||
enabled: readyData?.composer.canAttachFiles === true,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!readyData) return;
|
||||
setHydratedMessages((current) => mergeHydratedMessages(current, readyData.messages));
|
||||
}, [readyData]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetched = olderFetcher.data;
|
||||
const page = fetched?.vm;
|
||||
if (!fetched || !page || page.status !== "ready" || fetched.chatId !== loaderData.chatId) return;
|
||||
setHydratedMessages((current) => mergeHydratedMessages(page.data.messages, current));
|
||||
setOlderHistory(page.data.history);
|
||||
}, [loaderData.chatId, olderFetcher.data]);
|
||||
|
||||
const initialMessages = useMemo(() => (readyData ? mergeHydratedMessages(hydratedMessages, readyData.messages) : []), [hydratedMessages, readyData]);
|
||||
const realtime = useChatChannelRealtime({
|
||||
enabled: readyData !== null,
|
||||
tenantSlug: loaderData.tenantSlug,
|
||||
chatId: loaderData.chatId,
|
||||
initialCursor: loaderData.eventCursor,
|
||||
csrfToken: rootData.csrf ?? null,
|
||||
routing: rootData.routing,
|
||||
initialMessages,
|
||||
currentUser,
|
||||
unknownAuthorLabel: t("chat.participant.unknown"),
|
||||
resolveAuthor: (userId) => authorById.get(userId),
|
||||
revalidate: () => revalidator.revalidate(),
|
||||
});
|
||||
const draftDeliveries = useMemo(
|
||||
() =>
|
||||
realtime.messages.map((message) => ({
|
||||
clientMessageId: message.clientMessageId,
|
||||
isCurrentUser: message.author?.isCurrentUser ?? false,
|
||||
deliveryState: message.deliveryState,
|
||||
failureReasonKey: message.failureReasonKey,
|
||||
retryable: message.retryable,
|
||||
})),
|
||||
[realtime.messages]
|
||||
);
|
||||
const chatDraft = useChatDraft({
|
||||
storageKey: readyData?.composer.draftStorageKey ?? null,
|
||||
deliveries: draftDeliveries,
|
||||
sendMessage: (body, clientMessageId, requestId) =>
|
||||
realtime.sendMessage(
|
||||
body,
|
||||
resolvedMentionsForBody(body).map((mention) => ({ type: mention.kind, id: mention.id, label: mention.label })),
|
||||
clientMessageId,
|
||||
requestId
|
||||
),
|
||||
restoreFailedMessage: realtime.restoreFailedMessage,
|
||||
retryMessage: realtime.retryMessage,
|
||||
updateTyping: realtime.updateTyping,
|
||||
});
|
||||
const controlledDraft = chatDraft.loaded ? chatDraft.draft : "";
|
||||
const mentionResponseMatches = mentionQuery !== null && mentionFetcher.data?.query === mentionQuery.query && mentionFetcher.data.type === mentionQuery.kind;
|
||||
const mentionVm = mentionResponseMatches ? (mentionFetcher.data?.vm ?? null) : null;
|
||||
const mentionItems = mentionVm?.groups.flatMap((group) => group.items) ?? [];
|
||||
|
||||
useEffect(() => {
|
||||
if (readyData?.composer.canMention !== true) {
|
||||
setMentionQuery(null);
|
||||
setMentionActiveIndex(0);
|
||||
return;
|
||||
}
|
||||
const query = findChatMentionQuery(controlledDraft, composerCaret);
|
||||
setMentionQuery(query);
|
||||
setMentionActiveIndex(0);
|
||||
if (!query) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
const search = new URLSearchParams({ q: query.query });
|
||||
if (query.kind) search.set("type", query.kind);
|
||||
void mentionFetcher.load(`/${encodeURIComponent(loaderData.tenantSlug)}/chat/${encodeURIComponent(loaderData.chatId)}/mentions?${search.toString()}`);
|
||||
}, 200);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [composerCaret, controlledDraft, loaderData.chatId, loaderData.tenantSlug, readyData?.composer.canMention]);
|
||||
|
||||
useEffect(() => {
|
||||
const result = attachmentFetcher.data;
|
||||
if (
|
||||
attachmentFetcher.state !== "idle" ||
|
||||
!result ||
|
||||
result.intent !== "send_attachment_message" ||
|
||||
handledAttachmentRequestRef.current === result.requestId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
handledAttachmentRequestRef.current = result.requestId;
|
||||
const attempt = attachmentAttemptRef.current;
|
||||
if (!attempt || attempt.requestId !== result.requestId) return;
|
||||
if (!result.ok) {
|
||||
updateAttachmentAttempt({ ...attempt, deliveryState: "failed", errorKey: result.errorKey ?? "chat.message.sendFailed" });
|
||||
return;
|
||||
}
|
||||
attachmentUploads.clearReady(attempt.fileIds);
|
||||
chatDraft.updateDraft("");
|
||||
updateAttachmentAttempt(null);
|
||||
revalidator.revalidate();
|
||||
}, [attachmentFetcher.data, attachmentFetcher.state, attachmentUploads.clearReady, chatDraft.updateDraft, revalidator]);
|
||||
|
||||
useEffect(() => {
|
||||
const result = taskFetcher.data;
|
||||
if (taskFetcher.state !== "idle" || !result || result.intent !== "mark_task" || handledTaskRequestRef.current === result.requestId) return;
|
||||
handledTaskRequestRef.current = result.requestId;
|
||||
setMarkingTaskMessageId(null);
|
||||
}, [taskFetcher.data, taskFetcher.state]);
|
||||
|
||||
const loaderVmWithHistory = withOlderHistory(loaderData.vm, olderHistory);
|
||||
const authoritativeVm = overlayChatChannelDetailRealtime(loaderVmWithHistory, {
|
||||
...realtime,
|
||||
presence: realtime.presence.filter((entry) => entry.userId !== loaderData.currentUserId),
|
||||
});
|
||||
const vm = overlayChatMessageMutations(
|
||||
overlayChatChannelFeatureMutations(overlayChatAttachmentSendAttempt(authoritativeVm, attachmentSendAttempt, currentUser), featureMutations),
|
||||
messageMutations
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setFeatureMutations((current) => reconcileChatChannelFeatureMutations(current, authoritativeVm));
|
||||
setMessageMutations((current) => reconcileChatMessageMutations(current, authoritativeVm));
|
||||
}, [authoritativeVm]);
|
||||
|
||||
useEffect(() => {
|
||||
if (featureFetcher.state !== "idle" || !featureFetcher.data) return;
|
||||
setFeatureMutations((current) => settleChatFeatureMutation(current, featureFetcher.data!.requestId, featureFetcher.data!));
|
||||
}, [featureFetcher.data, featureFetcher.state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mutationFetcher.state !== "idle" || !mutationFetcher.data) return;
|
||||
setMessageMutations((current) => settleChatMessageMutation(current, mutationFetcher.data!));
|
||||
}, [mutationFetcher.data, mutationFetcher.state]);
|
||||
|
||||
function submitFeatureMutation(mutation: ChatOptimisticFeatureMutationInput): void {
|
||||
if (featureFetcher.state !== "idle") return;
|
||||
setFeatureMutations((current) => beginChatFeatureMutation(current, mutation));
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", rootData.csrf ?? "");
|
||||
formData.set("intent", mutation.kind);
|
||||
formData.set("requestId", mutation.requestId);
|
||||
formData.set("messageId", mutation.messageId);
|
||||
if (mutation.kind === "reaction") {
|
||||
formData.set("emoji", mutation.emoji);
|
||||
formData.set("active", String(mutation.active));
|
||||
} else {
|
||||
formData.set("pinned", String(mutation.pinned));
|
||||
}
|
||||
void featureFetcher.submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
function beginFeatureMutation(
|
||||
input:
|
||||
| { readonly kind: "reaction"; readonly messageId: string; readonly emoji: string; readonly active: boolean }
|
||||
| { readonly kind: "pin"; readonly messageId: string; readonly pinned: boolean }
|
||||
): void {
|
||||
submitFeatureMutation({
|
||||
...input,
|
||||
requestId: crypto.randomUUID(),
|
||||
actorLabel: currentUser.displayName,
|
||||
startedAtIso: new Date().toISOString(),
|
||||
} as ChatOptimisticFeatureMutationInput);
|
||||
}
|
||||
|
||||
function retryFeatureMutation(messageId: string): void {
|
||||
const messageMutation = failedChatMessageMutationForMessage(messageMutations, messageId);
|
||||
if (messageMutation) {
|
||||
if (mutationFetcher.state !== "idle") return;
|
||||
setMessageMutations((current) => retryChatMessageMutation(current, messageMutation.requestId));
|
||||
submitMessageMutationForm(messageMutation);
|
||||
return;
|
||||
}
|
||||
if (featureFetcher.state !== "idle") return;
|
||||
const mutation = failedChatFeatureMutationForMessage(featureMutations, messageId);
|
||||
if (!mutation) return;
|
||||
setFeatureMutations((current) => retryChatFeatureMutation(current, mutation.requestId));
|
||||
submitFeatureMutation(mutation);
|
||||
}
|
||||
|
||||
function submitMessageMutationForm(mutation: ChatOptimisticMessageMutation): void {
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", rootData.csrf ?? "");
|
||||
formData.set("intent", mutation.kind);
|
||||
formData.set("requestId", mutation.requestId);
|
||||
formData.set("messageId", mutation.messageId);
|
||||
if (mutation.kind === "edit_message") formData.set("body", mutation.bodyMarkdown);
|
||||
void mutationFetcher.submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
function submitMessageMutation(mutation: ChatOptimisticMessageMutationInput): void {
|
||||
if (mutationFetcher.state !== "idle") return;
|
||||
setMessageMutations((current) => beginChatMessageMutation(current, mutation));
|
||||
submitMessageMutationForm({ ...mutation, state: "pending", errorKey: null } as ChatOptimisticMessageMutation);
|
||||
}
|
||||
|
||||
function resolvedMentionsForBody(body: string): readonly ChatResolvedMentionVM[] {
|
||||
const available = new Map(selectedMentionLabels);
|
||||
if (vm.status === "ready") {
|
||||
for (const message of vm.data.messages) {
|
||||
for (const mention of message.mentions) available.set(`${mention.kind}\u0000${mention.id}`, mention);
|
||||
}
|
||||
}
|
||||
try {
|
||||
return extractChatMentions(body).flatMap((mention) => {
|
||||
const resolved = available.get(`${mention.type}\u0000${mention.id}`);
|
||||
return resolved ? [resolved] : [];
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function selectMention(suggestion: ChatMentionSuggestionVM): number | null {
|
||||
if (!mentionQuery) return null;
|
||||
const inserted = insertChatMention(controlledDraft, mentionQuery, { type: suggestion.kind, id: suggestion.id });
|
||||
setSelectedMentionLabels((current) => {
|
||||
const next = new Map(current);
|
||||
next.set(`${suggestion.kind}\u0000${suggestion.id}`, {
|
||||
kind: suggestion.kind,
|
||||
id: suggestion.id,
|
||||
label: suggestion.label,
|
||||
href: suggestion.href,
|
||||
});
|
||||
return next;
|
||||
});
|
||||
chatDraft.updateDraft(inserted.body);
|
||||
setComposerCaret(inserted.caret);
|
||||
setMentionQuery(null);
|
||||
return inserted.caret;
|
||||
}
|
||||
|
||||
function handleMentionKeyDown(key: "ArrowDown" | "ArrowUp" | "Enter" | "Escape"): boolean {
|
||||
if (!mentionQuery) return false;
|
||||
if (key === "Escape") {
|
||||
setMentionQuery(null);
|
||||
return true;
|
||||
}
|
||||
if (key === "ArrowDown" || key === "ArrowUp") {
|
||||
if (mentionItems.length === 0) return false;
|
||||
setMentionActiveIndex((current) =>
|
||||
key === "ArrowDown" ? (current + 1) % mentionItems.length : (current - 1 + mentionItems.length) % mentionItems.length
|
||||
);
|
||||
return true;
|
||||
}
|
||||
const selected = mentionItems[mentionActiveIndex];
|
||||
if (!selected) return false;
|
||||
selectMention(selected);
|
||||
return true;
|
||||
}
|
||||
|
||||
function updateAttachmentAttempt(attempt: ChatAttachmentSendAttempt | null): void {
|
||||
attachmentAttemptRef.current = attempt;
|
||||
setAttachmentSendAttempt(attempt);
|
||||
}
|
||||
|
||||
function submitAttachmentAttempt(attempt: ChatAttachmentSendAttempt): void {
|
||||
if (attachmentFetcher.state !== "idle") return;
|
||||
handledAttachmentRequestRef.current = null;
|
||||
const sendingAttempt = { ...attempt, deliveryState: "sending" as const, errorKey: null };
|
||||
updateAttachmentAttempt(sendingAttempt);
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", rootData.csrf ?? "");
|
||||
formData.set("intent", "send_attachment_message");
|
||||
formData.set("requestId", sendingAttempt.requestId);
|
||||
formData.set("clientMessageId", sendingAttempt.clientMessageId);
|
||||
formData.set("body", sendingAttempt.body);
|
||||
formData.set("attachmentFileIds", JSON.stringify(sendingAttempt.fileIds));
|
||||
void attachmentFetcher.submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
function sendDraftOrAttachments(bodyMarkdown: string): boolean | void {
|
||||
const readyFileIds = attachmentUploads.attachments.flatMap((attachment) => (attachment.status === "ready" && attachment.fileId ? [attachment.fileId] : []));
|
||||
if (readyFileIds.length === 0) return chatDraft.sendDraft(bodyMarkdown);
|
||||
if (attachmentFetcher.state !== "idle" || attachmentUploads.attachments.some((attachment) => attachment.status !== "ready")) return false;
|
||||
|
||||
const body = bodyMarkdown.trim();
|
||||
const payloadKey = JSON.stringify([body, readyFileIds]);
|
||||
const previous = attachmentAttemptRef.current;
|
||||
const attempt =
|
||||
previous?.payloadKey === payloadKey
|
||||
? previous
|
||||
: {
|
||||
payloadKey,
|
||||
requestId: crypto.randomUUID(),
|
||||
clientMessageId: crypto.randomUUID(),
|
||||
fileIds: readyFileIds,
|
||||
body,
|
||||
attachments: attachmentUploads.attachments.filter((attachment) => attachment.status === "ready" && attachment.fileId !== null),
|
||||
createdAtIso: new Date().toISOString(),
|
||||
deliveryState: "sending" as const,
|
||||
errorKey: null,
|
||||
};
|
||||
submitAttachmentAttempt(attempt);
|
||||
return true;
|
||||
}
|
||||
|
||||
function markMessageAsTask(messageId: string): void {
|
||||
if (taskFetcher.state !== "idle") return;
|
||||
const formData = new FormData();
|
||||
formData.set("csrf", rootData.csrf ?? "");
|
||||
formData.set("intent", "mark_task");
|
||||
formData.set("requestId", crypto.randomUUID());
|
||||
formData.set("messageId", messageId);
|
||||
setMarkingTaskMessageId(messageId);
|
||||
void taskFetcher.submit(formData, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<ChatChannelDetailPage
|
||||
vm={vm}
|
||||
draft={controlledDraft}
|
||||
focusedMessageId={loaderData.focusMessageId}
|
||||
mentionAutocomplete={{
|
||||
vm: mentionVm,
|
||||
open: mentionQuery !== null,
|
||||
loading: mentionQuery !== null && (!mentionResponseMatches || mentionFetcher.state !== "idle"),
|
||||
activeIndex: Math.min(mentionActiveIndex, Math.max(0, mentionItems.length - 1)),
|
||||
listboxId: "chat-channel-mention-listbox",
|
||||
}}
|
||||
actions={{
|
||||
onBack: () => navigateBackToChatList(navigate, chatIndexPath(loaderData.tenantSlug)),
|
||||
onOpenSettings: () => {
|
||||
if (readyData?.header.settingsHref) void navigate(readyData.header.settingsHref);
|
||||
},
|
||||
onOpenPinned: () => {
|
||||
if (readyData?.header.pinnedHref) void navigate(readyData.header.pinnedHref);
|
||||
},
|
||||
onOpenThread: (messageId, href) => void navigate(href ?? chatThreadPath(loaderData.tenantSlug, loaderData.chatId, messageId)),
|
||||
onToggleReaction: (messageId, emoji, active) => beginFeatureMutation({ kind: "reaction", messageId, emoji, active }),
|
||||
onTogglePin: (messageId, pinned) => beginFeatureMutation({ kind: "pin", messageId, pinned }),
|
||||
onRetryFeature: retryFeatureMutation,
|
||||
onEditMessage: (messageId, body) =>
|
||||
submitMessageMutation({
|
||||
kind: "edit_message",
|
||||
messageId,
|
||||
bodyMarkdown: body,
|
||||
mentions: resolvedMentionsForBody(body),
|
||||
requestId: crypto.randomUUID(),
|
||||
startedAtIso: new Date().toISOString(),
|
||||
}),
|
||||
onDeleteMessage: (messageId) =>
|
||||
submitMessageMutation({
|
||||
kind: "delete_message",
|
||||
messageId,
|
||||
requestId: crypto.randomUUID(),
|
||||
startedAtIso: new Date().toISOString(),
|
||||
}),
|
||||
onMentionActiveIndexChange: setMentionActiveIndex,
|
||||
onMentionSelect: selectMention,
|
||||
onMentionKeyDown: handleMentionKeyDown,
|
||||
onAddFiles: (files) => attachmentUploads.addFiles(files),
|
||||
onAddPhotos: (files) => attachmentUploads.addFiles(files),
|
||||
onStartRecording: attachmentUploads.startRecording,
|
||||
onStopRecording: attachmentUploads.stopRecording,
|
||||
onCancelRecording: attachmentUploads.cancelRecording,
|
||||
onRetryAttachment: attachmentUploads.retry,
|
||||
onRemoveAttachment: attachmentUploads.remove,
|
||||
onMarkAsTask: markMessageAsTask,
|
||||
onDraftChange: (body, _storageKey, caret) => {
|
||||
chatDraft.updateDraft(body);
|
||||
setComposerCaret(caret);
|
||||
},
|
||||
onSend: sendDraftOrAttachments,
|
||||
onRetryMessage: (clientMessageId) => {
|
||||
const attachmentAttempt = attachmentAttemptRef.current;
|
||||
if (attachmentAttempt?.clientMessageId === clientMessageId && attachmentAttempt.deliveryState === "failed") {
|
||||
submitAttachmentAttempt(attachmentAttempt);
|
||||
return;
|
||||
}
|
||||
realtime.retryMessage(clientMessageId);
|
||||
},
|
||||
onDiscardMessage: (clientMessageId) => {
|
||||
if (attachmentAttemptRef.current?.clientMessageId === clientMessageId) {
|
||||
updateAttachmentAttempt(null);
|
||||
return;
|
||||
}
|
||||
chatDraft.discardPendingDraft(clientMessageId);
|
||||
realtime.discardMessage(clientMessageId);
|
||||
},
|
||||
onMessageVisibilityChange: (messageId, createdAtIso, visible) => {
|
||||
if (messageId.startsWith("local:")) return;
|
||||
if (visible) realtime.beginMessageVisible(messageId, createdAtIso);
|
||||
else realtime.endMessageVisible(messageId);
|
||||
},
|
||||
onRetryConnection: () => realtime.retryConnection(),
|
||||
onLoadOlder: (cursor) => {
|
||||
const href = `${chatChannelPath(loaderData.tenantSlug, loaderData.chatId)}?before=${encodeURIComponent(cursor)}`;
|
||||
void olderFetcher.load(href);
|
||||
},
|
||||
}}
|
||||
pendingAttachments={attachmentUploads.attachments}
|
||||
isStartingRecording={attachmentUploads.isStartingRecording}
|
||||
isRecording={attachmentUploads.isRecording}
|
||||
recordingDurationSeconds={attachmentUploads.recordingDurationSeconds}
|
||||
scrollStorageKey={`team-chat:scroll:v1:${loaderData.tenantSlug}:${loaderData.currentUserId}:${loaderData.chatId}`}
|
||||
sending={attachmentFetcher.state !== "idle"}
|
||||
markingTaskMessageId={markingTaskMessageId}
|
||||
actionErrorKey={attachmentUploads.errorKey ?? (taskFetcher.data?.intent === "mark_task" && !taskFetcher.data.ok ? taskFetcher.data.errorKey : null)}
|
||||
actionSuccessKey={taskFetcher.data?.intent === "mark_task" && taskFetcher.data.ok ? "chat.task.created" : null}
|
||||
featureErrorKeys={{ ...chatFeatureErrorsByMessageId(featureMutations), ...chatMessageMutationErrors(messageMutations) }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function navigateBackToChatList(navigate: ReturnType<typeof useNavigate>, fallbackHref: string): void {
|
||||
const historyIndex = typeof window === "undefined" ? 0 : (window.history.state as { readonly idx?: unknown } | null)?.idx;
|
||||
if (typeof historyIndex === "number" && historyIndex > 0) {
|
||||
navigate(-1);
|
||||
return;
|
||||
}
|
||||
void navigate(fallbackHref);
|
||||
}
|
||||
|
||||
function withOlderHistory(vm: ChatChannelDetailVM, olderHistory: NonNullable<ChatChannelDetailVM["data"]>["history"] | null): ChatChannelDetailVM {
|
||||
if (vm.status !== "ready" || olderHistory === null) return vm;
|
||||
return {
|
||||
...vm,
|
||||
data: {
|
||||
...vm.data,
|
||||
history: olderHistory,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function mergeHydratedMessages(older: readonly ChatMessageVM[], newer: readonly ChatMessageVM[]): readonly ChatMessageVM[] {
|
||||
const byKey = new Map<string, ChatMessageVM>();
|
||||
for (const message of [...older, ...newer]) {
|
||||
byKey.set(chatMessageIdentityKey(message), message);
|
||||
}
|
||||
return [...byKey.values()].sort((left, right) => left.createdAtIso.localeCompare(right.createdAtIso));
|
||||
}
|
||||
|
||||
function fallbackCurrentUser(userId: string, label: string): ChatResolvedAuthorVM {
|
||||
return {
|
||||
userId,
|
||||
displayName: label,
|
||||
avatar: { imageUrl: null, fallbackLabel: label.slice(0, 1).toLocaleUpperCase() || "?" },
|
||||
isCurrentUser: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = {
|
||||
moduleKey: CHAT_MODULE_KEY,
|
||||
breadcrumbKey: "chat.channel.detailTitle",
|
||||
};
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadChatContext: vi.fn(),
|
||||
loadMemberChatChannels: vi.fn(),
|
||||
joinPublicChatChannel: vi.fn(),
|
||||
updateOwnChatChannelPreferences: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({ loadChatContext: mocks.loadChatContext }));
|
||||
vi.mock("~/modules/chat/services/ChatService.server", () => ({
|
||||
loadMemberChatChannels: mocks.loadMemberChatChannels,
|
||||
joinPublicChatChannel: mocks.joinPublicChatChannel,
|
||||
updateOwnChatChannelPreferences: mocks.updateOwnChatChannelPreferences,
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken }));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf_1" }) }));
|
||||
vi.mock("~/components/screens/chat/ChatChannelListPage", () => ({ ChatChannelListPage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
|
||||
import { action, loader } from "./chat._index";
|
||||
|
||||
const context = { tenantId: "tenant_1", userId: "user_1", permissions: ["chat.read_own_channels"] };
|
||||
|
||||
describe("public chat join action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadChatContext.mockResolvedValue(context);
|
||||
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
||||
mocks.joinPublicChatChannel.mockResolvedValue({ chatId: "chat_public", changed: true });
|
||||
mocks.updateOwnChatChannelPreferences.mockResolvedValue({
|
||||
chatId: "chat_public",
|
||||
isPinned: true,
|
||||
notificationPreference: "all_messages",
|
||||
changed: true,
|
||||
});
|
||||
mocks.loadMemberChatChannels.mockResolvedValue({ status: "ready", data: {} });
|
||||
});
|
||||
|
||||
it("loads the URL cursor with the canonical filter and fixed page limit", async () => {
|
||||
const request = new Request("https://app.test/demo/chat?q=Montage&view=groups&archived=1&cursor=opaque_cursor");
|
||||
const response = await loader({ request, params: { tenant: "demo" }, context: {}, unstable_pattern: "app.$tenant/chat._index" });
|
||||
|
||||
expect(mocks.loadMemberChatChannels).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantSlug: "demo",
|
||||
filter: { query: "Montage", view: "groups", showArchived: true },
|
||||
afterCursor: "opaque_cursor",
|
||||
limit: 50,
|
||||
})
|
||||
);
|
||||
await expect(response.json()).resolves.toMatchObject({ pageCursor: "opaque_cursor" });
|
||||
});
|
||||
|
||||
it("joins through the server service and redirects only after the lifecycle boundary succeeds", async () => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "join");
|
||||
formData.set("chatId", "chat_public");
|
||||
formData.set("csrf", "csrf_1");
|
||||
const request = postRequest(formData);
|
||||
|
||||
const response = await action({ request, params: { tenant: "demo" }, context: {}, unstable_pattern: "app.$tenant/chat._index" });
|
||||
|
||||
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() });
|
||||
expect(mocks.joinPublicChatChannel).toHaveBeenCalledWith({
|
||||
context,
|
||||
chatId: "chat_public",
|
||||
requestId: expect.any(String),
|
||||
});
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("location")).toBe("/demo/chat/chat_public?toast=chat.toast.channelJoined");
|
||||
});
|
||||
|
||||
it("rejects malformed join intents before the lifecycle mutation", async () => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "join");
|
||||
const response = await action({
|
||||
request: postRequest(formData),
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat._index",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ errorKey: "chat.errors.invalidInput" });
|
||||
expect(mocks.joinPublicChatChannel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates the current member pin through a CSRF-protected action", async () => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "set-pin");
|
||||
formData.set("chatId", "chat_public");
|
||||
formData.set("requestId", "request_pin_1");
|
||||
formData.set("isPinned", "true");
|
||||
formData.set("csrf", "csrf_1");
|
||||
const request = postRequest(formData);
|
||||
|
||||
const response = await action({ request, params: { tenant: "demo" }, context: {}, unstable_pattern: "app.$tenant/chat._index" });
|
||||
|
||||
expect(mocks.updateOwnChatChannelPreferences).toHaveBeenCalledWith({
|
||||
context,
|
||||
chatId: "chat_public",
|
||||
requestId: "request_pin_1",
|
||||
isPinned: true,
|
||||
});
|
||||
await expect(response.json()).resolves.toMatchObject({
|
||||
errorKey: null,
|
||||
mutation: { chatId: "chat_public", isPinned: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("updates notification preferences and rejects malformed preference values", async () => {
|
||||
const valid = new FormData();
|
||||
valid.set("intent", "set-notification");
|
||||
valid.set("chatId", "chat_public");
|
||||
valid.set("requestId", "request_notification_1");
|
||||
valid.set("notificationPreference", "muted");
|
||||
const validRequest = postRequest(valid);
|
||||
await action({ request: validRequest, params: { tenant: "demo" }, context: {}, unstable_pattern: "app.$tenant/chat._index" });
|
||||
expect(mocks.updateOwnChatChannelPreferences).toHaveBeenCalledWith({
|
||||
context,
|
||||
chatId: "chat_public",
|
||||
requestId: "request_notification_1",
|
||||
notificationPreference: "muted",
|
||||
});
|
||||
|
||||
const invalid = new FormData();
|
||||
invalid.set("intent", "set-notification");
|
||||
invalid.set("chatId", "chat_public");
|
||||
invalid.set("requestId", "request_notification_2");
|
||||
invalid.set("notificationPreference", "everything");
|
||||
const response = await action({
|
||||
request: postRequest(invalid),
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat._index",
|
||||
});
|
||||
expect(response.status).toBe(400);
|
||||
expect(mocks.updateOwnChatChannelPreferences).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
function postRequest(formData: FormData): Request {
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of formData.entries()) body.append(key, value.toString());
|
||||
return new Request("https://app.test/demo/chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
// @vitest-environment jsdom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import {
|
||||
buildChatChannelListVM,
|
||||
type ChatChannelListFilterState,
|
||||
type ChatChannelListRowInput,
|
||||
type ChatChannelListVM,
|
||||
type ChatDiscoverChannelRowVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { ChatChannelListPageProps } from "~/components/screens/chat/ChatChannelListPage";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loaderData: undefined as unknown,
|
||||
pageProps: undefined as ChatChannelListPageProps | undefined,
|
||||
navigate: vi.fn(),
|
||||
revalidate: vi.fn(),
|
||||
fetcher: {
|
||||
data: undefined as unknown,
|
||||
state: "idle" as "idle" | "loading" | "submitting",
|
||||
load: vi.fn(),
|
||||
submit: vi.fn(),
|
||||
},
|
||||
getTranslations: vi.fn(),
|
||||
loadChatContext: vi.fn(),
|
||||
loadMemberChatChannels: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", () => ({
|
||||
useLoaderData: () => mocks.loaderData,
|
||||
useNavigate: () => mocks.navigate,
|
||||
useRevalidator: () => ({ revalidate: mocks.revalidate }),
|
||||
useFetcher: () => mocks.fetcher,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/screens/chat/ChatChannelListPage", () => ({
|
||||
ChatChannelListPage: (props: ChatChannelListPageProps) => {
|
||||
mocks.pageProps = props;
|
||||
const rows = props.vm.status === "ready" ? props.vm.data.rows : [];
|
||||
const discoverRows = props.vm.status === "ready" ? props.vm.data.discoverRows : [];
|
||||
const cursor = props.vm.status === "ready" ? props.vm.data.nextCursor : null;
|
||||
return (
|
||||
<div>
|
||||
<output data-testid="channel-rows">{rows.map((row) => `${row.id}:${row.unreadCount}`).join(",")}</output>
|
||||
<output data-testid="channel-query">{props.vm.status === "ready" ? props.vm.data.filter.query : ""}</output>
|
||||
<output data-testid="join-error">{props.joinErrorKey ?? ""}</output>
|
||||
{cursor && props.actions.onLoadMore ? <button onClick={() => void props.actions.onLoadMore?.(cursor)}>load-more</button> : null}
|
||||
{discoverRows.map((row) =>
|
||||
row.joinHref && props.actions.onJoinChannel ? (
|
||||
<button key={row.id} onClick={() => props.actions.onJoinChannel?.(row.id, row.joinHref!)}>
|
||||
join-{row.id}
|
||||
</button>
|
||||
) : null
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({ loadChatContext: (...args: unknown[]) => mocks.loadChatContext(...args) }));
|
||||
vi.mock("~/modules/chat/services/ChatService.server", () => ({
|
||||
loadMemberChatChannels: (...args: unknown[]) => mocks.loadMemberChatChannels(...args),
|
||||
joinPublicChatChannel: vi.fn(),
|
||||
updateOwnChatChannelPreferences: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf_1" }) }));
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
|
||||
|
||||
import ChatChannelListRoute from "./chat._index";
|
||||
|
||||
const DEFAULT_FILTER: ChatChannelListFilterState = { query: "", view: "all", showArchived: false };
|
||||
|
||||
function row(id: string, unreadCount = 0): ChatChannelListRowInput {
|
||||
return {
|
||||
id,
|
||||
kind: "group",
|
||||
title: id,
|
||||
subtitle: null,
|
||||
detailHref: `/demo/chat/${id}`,
|
||||
avatar: { imageUrl: null, fallbackLabel: id.slice(0, 1) },
|
||||
project: null,
|
||||
lastMessage: null,
|
||||
typingLabels: [],
|
||||
unreadCount,
|
||||
hasMention: unreadCount > 1,
|
||||
isPinned: false,
|
||||
isPrivate: false,
|
||||
notificationPreference: "all_messages",
|
||||
archivedAtIso: null,
|
||||
memberCount: 2,
|
||||
canManage: false,
|
||||
};
|
||||
}
|
||||
|
||||
function page(
|
||||
rows: readonly ChatChannelListRowInput[],
|
||||
nextCursor: string | null,
|
||||
filter = DEFAULT_FILTER,
|
||||
discoverRows: readonly ChatDiscoverChannelRowVM[] = []
|
||||
): ChatChannelListVM {
|
||||
return buildChatChannelListVM({
|
||||
rows,
|
||||
discoverRows,
|
||||
filter,
|
||||
permissions: {
|
||||
canWrite: false,
|
||||
canCreateGroup: false,
|
||||
canCreateDm: false,
|
||||
canDiscover: discoverRows.length > 0,
|
||||
canViewMentions: false,
|
||||
canSearch: true,
|
||||
canViewArchived: true,
|
||||
canAdmin: false,
|
||||
},
|
||||
hrefs: {
|
||||
newChannel: "/demo/chat/new",
|
||||
newDm: "/demo/chat/new?kind=dm",
|
||||
search: "/demo/chat/search",
|
||||
mentions: "/demo/chat/mentions",
|
||||
archived: "/demo/chat?archived=1",
|
||||
},
|
||||
totals: { unread: rows.reduce((total, entry) => total + entry.unreadCount, 0), mentions: 0 },
|
||||
nextCursor,
|
||||
});
|
||||
}
|
||||
|
||||
function routeData(vm: ChatChannelListVM, pageCursor: string | null = null) {
|
||||
return { title: "Chat", tenantSlug: "demo", pageCursor, vm };
|
||||
}
|
||||
|
||||
describe("chat channel list route pagination", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.fetcher.data = undefined;
|
||||
mocks.fetcher.state = "idle";
|
||||
mocks.loaderData = routeData(page([row("chat_1", 1)], "cursor_2"));
|
||||
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
|
||||
mocks.loadChatContext.mockResolvedValue({ tenantId: "tenant_1", userId: "user_1", permissions: [] });
|
||||
mocks.loadMemberChatChannels.mockResolvedValue(page([row("chat_2")], null));
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("loads another page without navigation, appends in order, deduplicates, and adopts its cursor", async () => {
|
||||
const view = render(<ChatChannelListRoute />);
|
||||
expect(screen.getByTestId("channel-rows")).toHaveTextContent("chat_1:1");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "load-more" }));
|
||||
expect(mocks.fetcher.load).toHaveBeenCalledWith("/demo/chat?cursor=cursor_2");
|
||||
|
||||
mocks.fetcher.state = "loading";
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
mocks.fetcher.data = routeData(page([row("chat_1", 3), row("chat_2", 2)], null), "cursor_2");
|
||||
mocks.fetcher.state = "idle";
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("channel-rows")).toHaveTextContent("chat_1:3,chat_2:2"));
|
||||
expect(screen.queryByRole("button", { name: "load-more" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("resets appended rows and ignores an old in-flight page when the server filter changes", async () => {
|
||||
const view = render(<ChatChannelListRoute />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "load-more" }));
|
||||
mocks.fetcher.state = "loading";
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
|
||||
const unreadFilter = { query: "", view: "unread" as const, showArchived: false };
|
||||
mocks.loaderData = routeData(page([row("chat_unread", 4)], null, unreadFilter));
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
mocks.fetcher.data = routeData(page([row("chat_stale", 9)], null), "cursor_2");
|
||||
mocks.fetcher.state = "idle";
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("channel-rows")).toHaveTextContent("chat_unread:4"));
|
||||
expect(screen.getByTestId("channel-rows")).not.toHaveTextContent("chat_stale");
|
||||
});
|
||||
|
||||
it("does not let a late loader response overwrite a newer local search query", () => {
|
||||
vi.useFakeTimers();
|
||||
const view = render(<ChatChannelListRoute />);
|
||||
|
||||
act(() => mocks.pageProps?.actions.onQueryChange("abc"));
|
||||
act(() => vi.advanceTimersByTime(250));
|
||||
act(() => mocks.pageProps?.actions.onQueryChange("abcd"));
|
||||
|
||||
mocks.loaderData = routeData(page([row("chat_old")], null, { ...DEFAULT_FILTER, query: "abc" }));
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
expect(screen.getByTestId("channel-query")).toHaveTextContent("abcd");
|
||||
|
||||
mocks.loaderData = routeData(page([row("chat_new")], null, { ...DEFAULT_FILTER, query: "abcd" }));
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
expect(screen.getByTestId("channel-query")).toHaveTextContent("abcd");
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it.each(["abc ", "x".repeat(250)])("releases local query protection when the normalized loader value returns", (rawQuery) => {
|
||||
vi.useFakeTimers();
|
||||
const normalizedQuery = rawQuery.trim().slice(0, 200);
|
||||
const view = render(<ChatChannelListRoute />);
|
||||
act(() => mocks.pageProps?.actions.onQueryChange(rawQuery));
|
||||
act(() => vi.advanceTimersByTime(250));
|
||||
|
||||
mocks.loaderData = routeData(page([row("chat_match")], null, { ...DEFAULT_FILTER, query: normalizedQuery }));
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
expect(screen.getByTestId("channel-query")).toHaveTextContent(normalizedQuery);
|
||||
|
||||
mocks.loaderData = routeData(page([row("chat_back")], null, { ...DEFAULT_FILTER, query: "back" }));
|
||||
view.rerender(<ChatChannelListRoute />);
|
||||
expect(screen.getByTestId("channel-query")).toHaveTextContent("back");
|
||||
});
|
||||
|
||||
it("submits a CSRF-protected join intent for a discoverable public group", () => {
|
||||
mocks.loaderData = routeData(
|
||||
page([row("chat_1")], null, DEFAULT_FILTER, [
|
||||
{
|
||||
id: "chat_public",
|
||||
title: "Montage Nord",
|
||||
description: null,
|
||||
avatar: { imageUrl: null, fallbackLabel: "MN" },
|
||||
memberCount: 4,
|
||||
isJoined: false,
|
||||
canJoin: true,
|
||||
joinHref: "/demo/chat",
|
||||
detailHref: null,
|
||||
},
|
||||
])
|
||||
);
|
||||
render(<ChatChannelListRoute />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "join-chat_public" }));
|
||||
|
||||
expect(mocks.fetcher.submit).toHaveBeenCalledOnce();
|
||||
const [formData, options] = mocks.fetcher.submit.mock.calls[0] as [FormData, { method: string; action: string }];
|
||||
expect(Object.fromEntries(formData.entries())).toEqual({ intent: "join", chatId: "chat_public", csrf: "csrf_1" });
|
||||
expect(options).toEqual({ method: "post", action: "/demo/chat" });
|
||||
});
|
||||
|
||||
it("optimistically applies a personal pin and submits the desired state", async () => {
|
||||
render(<ChatChannelListRoute />);
|
||||
|
||||
act(() => mocks.pageProps?.actions.onSetPinned?.("chat_1", true));
|
||||
|
||||
expect(mocks.fetcher.submit).toHaveBeenCalledOnce();
|
||||
const [formData, options] = mocks.fetcher.submit.mock.calls[0] as [FormData, { method: string }];
|
||||
expect(Object.fromEntries(formData.entries())).toMatchObject({
|
||||
intent: "set-pin",
|
||||
chatId: "chat_1",
|
||||
isPinned: "true",
|
||||
csrf: "csrf_1",
|
||||
});
|
||||
expect(formData.get("requestId")).toEqual(expect.any(String));
|
||||
expect(options).toEqual({ method: "post" });
|
||||
await waitFor(() => expect(mocks.pageProps?.vm.status === "ready" ? mocks.pageProps.vm.data.rows[0]?.isPinned : false).toBe(true));
|
||||
});
|
||||
|
||||
});
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
type MetaFunction,
|
||||
redirect,
|
||||
useFetcher,
|
||||
useLoaderData,
|
||||
useNavigate,
|
||||
useRevalidator,
|
||||
} from "react-router";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { chatErrors } from "@hivegrid/chat";
|
||||
import type { ChatChannelListFilterState, ChatChannelListVM, ChatChannelNotificationPreference } from "@hivegrid/view-models";
|
||||
|
||||
import { ChatChannelListPage } from "~/components/screens/chat/ChatChannelListPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadChatContext } from "~/modules/chat/routes/chatAccess.server";
|
||||
import {
|
||||
chatChannelListFilterHref,
|
||||
chatChannelListPageHref,
|
||||
normalizeChatChannelQuery,
|
||||
parseChatChannelListCursor,
|
||||
parseChatChannelListFilter,
|
||||
} from "~/modules/chat/routes/chatListFilter";
|
||||
import { mergeChatChannelListPages, sameChatChannelListFilter } from "~/modules/chat/routes/chatListPagination";
|
||||
import { CHAT_MODULE_KEY, chatChannelPath } from "~/modules/chat/routes/chatRoutePaths";
|
||||
import { joinPublicChatChannel, loadMemberChatChannels, updateOwnChatChannelPreferences } from "~/modules/chat/services/ChatService.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
readonly title: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly pageCursor: string | null;
|
||||
readonly vm: ChatChannelListVM;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
readonly errorKey: string | null;
|
||||
readonly mutation?: Readonly<{
|
||||
chatId: string;
|
||||
isPinned: boolean;
|
||||
notificationPreference: ChatChannelNotificationPreference;
|
||||
}>;
|
||||
};
|
||||
|
||||
const QUERY_DEBOUNCE_MS = 250;
|
||||
const CHANNEL_PAGE_LIMIT = 50;
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const url = new URL(request.url);
|
||||
const filter = parseChatChannelListFilter(url);
|
||||
const pageCursor = parseChatChannelListCursor(url);
|
||||
const vm = await loadMemberChatChannels({
|
||||
context,
|
||||
tenantSlug,
|
||||
filter,
|
||||
afterCursor: pageCursor,
|
||||
limit: CHANNEL_PAGE_LIMIT,
|
||||
labels: {
|
||||
directMessage: t("chat.channel.fallback.directMessage"),
|
||||
unnamedGroup: t("chat.channel.fallback.group"),
|
||||
unnamedProject: t("chat.channel.fallback.project"),
|
||||
unknownUser: t("chat.participant.unknown"),
|
||||
unknownMention: t("chat.mention.unknown"),
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({
|
||||
title: `${t("chat.nav.title")} | ${process.env.APP_NAME}`,
|
||||
tenantSlug,
|
||||
pageCursor: pageCursor ?? null,
|
||||
vm,
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const context = await loadChatContext({ request, params });
|
||||
const formData = await request.formData();
|
||||
await validateCSRFToken(request, { formData });
|
||||
|
||||
const intent = formData.get("intent")?.toString() ?? "";
|
||||
const chatId = formData.get("chatId")?.toString().trim() ?? "";
|
||||
if (!chatId || chatId.length > 191 || chatId.includes("\0")) {
|
||||
return Response.json({ errorKey: "chat.errors.invalidInput" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
if (intent === "join") {
|
||||
const result = await joinPublicChatChannel({ context, chatId, requestId: crypto.randomUUID() });
|
||||
return redirect(`${chatChannelPath(params.tenant ?? "", result.chatId)}?toast=${encodeURIComponent("chat.toast.channelJoined")}`);
|
||||
}
|
||||
|
||||
const requestId = normalizePreferenceRequestId(formData.get("requestId"));
|
||||
if (intent === "set-pin") {
|
||||
const isPinned = parseFormBoolean(formData.get("isPinned"));
|
||||
const mutation = await updateOwnChatChannelPreferences({ context, chatId, requestId, isPinned });
|
||||
return Response.json({ errorKey: null, mutation } satisfies ActionData);
|
||||
}
|
||||
if (intent === "set-notification") {
|
||||
const notificationPreference = parseNotificationPreference(formData.get("notificationPreference"));
|
||||
const mutation = await updateOwnChatChannelPreferences({ context, chatId, requestId, notificationPreference });
|
||||
return Response.json({ errorKey: null, mutation } satisfies ActionData);
|
||||
}
|
||||
return Response.json({ errorKey: "chat.errors.invalidInput" } satisfies ActionData, { status: 400 });
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ errorKey: error.i18nKey } satisfies ActionData, { status: error.status });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatChannelListRoute(): React.JSX.Element {
|
||||
const { tenantSlug, vm } = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
const revalidator = useRevalidator();
|
||||
const pageFetcher = useFetcher<LoaderData | ActionData>();
|
||||
const { csrf } = useRootData();
|
||||
const filter = vm.status === "ready" ? vm.data.filter : DEFAULT_FILTER;
|
||||
const [query, setQuery] = useState(filter.query);
|
||||
const [pagination, setPagination] = useState<{ readonly baseVm: ChatChannelListVM; readonly mergedVm: ChatChannelListVM }>({
|
||||
baseVm: vm,
|
||||
mergedVm: vm,
|
||||
});
|
||||
const [joinState, setJoinState] = useState<{ readonly channelId: string | null; readonly errorKey: string | null }>({
|
||||
channelId: null,
|
||||
errorKey: null,
|
||||
});
|
||||
const [preferenceState, setPreferenceState] = useState<{
|
||||
readonly channelId: string | null;
|
||||
readonly errorKey: string | null;
|
||||
readonly overrides: Readonly<Record<string, Readonly<{ isPinned?: boolean; notificationPreference?: ChatChannelNotificationPreference }>>>;
|
||||
}>({ channelId: null, errorKey: null, overrides: {} });
|
||||
const queryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const locallyEditedQuery = useRef<string | null>(null);
|
||||
const requestedCursor = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (locallyEditedQuery.current !== null && filter.query !== locallyEditedQuery.current) return;
|
||||
locallyEditedQuery.current = null;
|
||||
setQuery(filter.query);
|
||||
}, [filter.query]);
|
||||
useEffect(() => {
|
||||
requestedCursor.current = null;
|
||||
setPagination({ baseVm: vm, mergedVm: vm });
|
||||
}, [vm]);
|
||||
useEffect(() => {
|
||||
if (pageFetcher.state !== "idle") return;
|
||||
const cursor = requestedCursor.current;
|
||||
if (!cursor) return;
|
||||
requestedCursor.current = null;
|
||||
const fetched = pageFetcher.data;
|
||||
if (!isLoaderData(fetched) || fetched.pageCursor !== cursor || fetched.tenantSlug !== tenantSlug || vm.status !== "ready" || fetched.vm.status !== "ready") return;
|
||||
if (!sameChatChannelListFilter(vm.data.filter, fetched.vm.data.filter)) return;
|
||||
|
||||
setPagination((current) => ({
|
||||
baseVm: vm,
|
||||
mergedVm: mergeChatChannelListPages(current.baseVm === vm ? current.mergedVm : vm, fetched.vm),
|
||||
}));
|
||||
}, [pageFetcher.data, pageFetcher.state, tenantSlug, vm]);
|
||||
useEffect(() => {
|
||||
if (pageFetcher.state !== "idle" || joinState.channelId === null || !isActionData(pageFetcher.data)) return;
|
||||
setJoinState({ channelId: null, errorKey: pageFetcher.data.errorKey });
|
||||
}, [joinState.channelId, pageFetcher.data, pageFetcher.state]);
|
||||
useEffect(() => {
|
||||
if (pageFetcher.state !== "idle" || preferenceState.channelId === null || !isActionData(pageFetcher.data)) return;
|
||||
const response = pageFetcher.data;
|
||||
if (response.errorKey) {
|
||||
setPreferenceState((current) => {
|
||||
const nextOverrides = { ...current.overrides };
|
||||
delete nextOverrides[current.channelId ?? ""];
|
||||
return { channelId: null, errorKey: response.errorKey, overrides: nextOverrides };
|
||||
});
|
||||
return;
|
||||
}
|
||||
setPreferenceState((current) => ({ ...current, channelId: null, errorKey: null }));
|
||||
revalidator.revalidate();
|
||||
}, [pageFetcher.data, pageFetcher.state, preferenceState.channelId, revalidator]);
|
||||
useEffect(() => {
|
||||
if (vm.status !== "ready" || Object.keys(preferenceState.overrides).length === 0) return;
|
||||
setPreferenceState((current) => {
|
||||
const nextOverrides = { ...current.overrides };
|
||||
for (const row of vm.data.rows) {
|
||||
const override = nextOverrides[row.id];
|
||||
if (!override) continue;
|
||||
const pinMatches = override.isPinned === undefined || override.isPinned === row.isPinned;
|
||||
const notificationMatches = override.notificationPreference === undefined || override.notificationPreference === row.notificationPreference;
|
||||
if (pinMatches && notificationMatches) delete nextOverrides[row.id];
|
||||
}
|
||||
if (Object.keys(nextOverrides).length === Object.keys(current.overrides).length) return current;
|
||||
return { ...current, overrides: nextOverrides };
|
||||
});
|
||||
}, [preferenceState.overrides, vm]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (queryTimer.current) clearTimeout(queryTimer.current);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const pagedVm = pagination.baseVm === vm ? pagination.mergedVm : vm;
|
||||
|
||||
const openFilter = useCallback(
|
||||
(nextFilter: ChatChannelListFilterState, replace = false) => {
|
||||
void navigate(chatChannelListFilterHref(tenantSlug, nextFilter), { replace });
|
||||
},
|
||||
[navigate, tenantSlug]
|
||||
);
|
||||
|
||||
const displayVm = useMemo<ChatChannelListVM>(() => {
|
||||
if (pagedVm.status !== "ready") return pagedVm;
|
||||
const overriddenRows = pagedVm.data.rows.map((row) => {
|
||||
const override = preferenceState.overrides[row.id];
|
||||
if (!override) return row;
|
||||
const notificationPreference = override.notificationPreference ?? row.notificationPreference;
|
||||
return {
|
||||
...row,
|
||||
...(override.isPinned === undefined ? {} : { isPinned: override.isPinned }),
|
||||
notificationPreference,
|
||||
isMuted: notificationPreference === "muted",
|
||||
};
|
||||
});
|
||||
const rows =
|
||||
pagedVm.data.filter.view === "pinned"
|
||||
? overriddenRows.filter((row) => row.isPinned)
|
||||
: [...overriddenRows.filter((row) => row.isPinned), ...overriddenRows.filter((row) => !row.isPinned)];
|
||||
return {
|
||||
...pagedVm,
|
||||
data: {
|
||||
...pagedVm.data,
|
||||
rows,
|
||||
filter: query === pagedVm.data.filter.query ? pagedVm.data.filter : { ...pagedVm.data.filter, query },
|
||||
},
|
||||
};
|
||||
}, [pagedVm, preferenceState.overrides, query]);
|
||||
|
||||
return (
|
||||
<ChatChannelListPage
|
||||
vm={displayVm}
|
||||
joiningChannelId={joinState.channelId}
|
||||
joinErrorKey={joinState.errorKey}
|
||||
preferenceErrorKey={preferenceState.errorKey}
|
||||
updatingPreferenceChannelId={preferenceState.channelId}
|
||||
actions={{
|
||||
onOpenChannel: (_channelId, detailHref) => void navigate(detailHref),
|
||||
onCreateGroup: (href) => void navigate(href),
|
||||
onCreateDm: (href) => void navigate(href),
|
||||
onOpenMessageSearch: (href) => void navigate(href),
|
||||
onOpenMentions: (href) => void navigate(href),
|
||||
onJoinChannel: (channelId, joinHref) => {
|
||||
if (pageFetcher.state !== "idle" || requestedCursor.current !== null || joinState.channelId !== null) return;
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "join");
|
||||
formData.set("chatId", channelId);
|
||||
formData.set("csrf", csrf ?? "");
|
||||
setJoinState({ channelId, errorKey: null });
|
||||
void pageFetcher.submit(formData, { method: "post", action: joinHref });
|
||||
},
|
||||
onSetPinned: (channelId, isPinned) => {
|
||||
submitPreferenceMutation(channelId, { intent: "set-pin", isPinned });
|
||||
},
|
||||
onSetNotificationPreference: (channelId, notificationPreference) => {
|
||||
submitPreferenceMutation(channelId, { intent: "set-notification", notificationPreference });
|
||||
},
|
||||
onQueryChange: (nextQuery) => {
|
||||
locallyEditedQuery.current = normalizeChatChannelQuery(nextQuery);
|
||||
setQuery(nextQuery);
|
||||
if (queryTimer.current) clearTimeout(queryTimer.current);
|
||||
queryTimer.current = setTimeout(() => {
|
||||
queryTimer.current = null;
|
||||
openFilter({ ...filter, query: nextQuery }, true);
|
||||
}, QUERY_DEBOUNCE_MS);
|
||||
},
|
||||
onViewChange: (view) => {
|
||||
if (queryTimer.current) clearTimeout(queryTimer.current);
|
||||
openFilter({ ...filter, query, view });
|
||||
},
|
||||
onShowArchivedChange: (showArchived) => {
|
||||
if (queryTimer.current) clearTimeout(queryTimer.current);
|
||||
openFilter({ ...filter, query, showArchived });
|
||||
},
|
||||
onLoadMore: (cursor) => {
|
||||
if (pageFetcher.state !== "idle" || requestedCursor.current !== null) return;
|
||||
requestedCursor.current = cursor;
|
||||
void pageFetcher.load(chatChannelListPageHref(tenantSlug, filter, cursor));
|
||||
},
|
||||
onRetry: () => revalidator.revalidate(),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
function submitPreferenceMutation(
|
||||
channelId: string,
|
||||
mutation:
|
||||
| { readonly intent: "set-pin"; readonly isPinned: boolean }
|
||||
| { readonly intent: "set-notification"; readonly notificationPreference: ChatChannelNotificationPreference }
|
||||
): void {
|
||||
if (pageFetcher.state !== "idle" || requestedCursor.current !== null || preferenceState.channelId !== null) return;
|
||||
const formData = new FormData();
|
||||
formData.set("intent", mutation.intent);
|
||||
formData.set("chatId", channelId);
|
||||
formData.set("requestId", crypto.randomUUID());
|
||||
formData.set("csrf", csrf ?? "");
|
||||
if (mutation.intent === "set-pin") formData.set("isPinned", String(mutation.isPinned));
|
||||
else formData.set("notificationPreference", mutation.notificationPreference);
|
||||
setPreferenceState((current) => ({
|
||||
channelId,
|
||||
errorKey: null,
|
||||
overrides: {
|
||||
...current.overrides,
|
||||
[channelId]: {
|
||||
...current.overrides[channelId],
|
||||
...(mutation.intent === "set-pin" ? { isPinned: mutation.isPinned } : { notificationPreference: mutation.notificationPreference }),
|
||||
},
|
||||
},
|
||||
}));
|
||||
void pageFetcher.submit(formData, { method: "post" });
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_FILTER: ChatChannelListFilterState = {
|
||||
query: "",
|
||||
view: "all",
|
||||
showArchived: false,
|
||||
};
|
||||
|
||||
function isLoaderData(data: LoaderData | ActionData | undefined): data is LoaderData {
|
||||
return Boolean(data && "vm" in data && "pageCursor" in data);
|
||||
}
|
||||
|
||||
function isActionData(data: LoaderData | ActionData | undefined): data is ActionData {
|
||||
return Boolean(data && "errorKey" in data);
|
||||
}
|
||||
|
||||
function normalizePreferenceRequestId(value: FormDataEntryValue | null): string {
|
||||
const requestId = typeof value === "string" ? value.trim() : "";
|
||||
if (!requestId || requestId.length > 191 || requestId.includes("\0")) throw new CatalogError(chatErrors.invalidInput);
|
||||
return requestId;
|
||||
}
|
||||
|
||||
function parseFormBoolean(value: FormDataEntryValue | null): boolean {
|
||||
if (value === "true") return true;
|
||||
if (value === "false") return false;
|
||||
throw new CatalogError(chatErrors.invalidInput);
|
||||
}
|
||||
|
||||
function parseNotificationPreference(value: FormDataEntryValue | null): ChatChannelNotificationPreference {
|
||||
if (value === "all_messages" || value === "mentions_only" || value === "muted") return value;
|
||||
throw new CatalogError(chatErrors.invalidInput);
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CHAT_MODULE_KEY };
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { loader } from "./chat.archived";
|
||||
|
||||
describe("archived chat route", () => {
|
||||
it("keeps the canonical route reachable and opens the archived index view", () => {
|
||||
const response = loader({
|
||||
request: new Request("https://app.test/demo/chat/archived?query=montage"),
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "/:tenant/chat/archived",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toBe("/demo/chat?archived=true&query=montage");
|
||||
});
|
||||
});
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { chatIndexPath } from "~/modules/chat/routes/chatRoutePaths";
|
||||
|
||||
export const loader = ({ request, params }: LoaderFunctionArgs): Response => {
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const source = new URL(request.url);
|
||||
const target = new URL(chatIndexPath(tenantSlug), source.origin);
|
||||
target.searchParams.set("archived", "true");
|
||||
const query = source.searchParams.get("query");
|
||||
if (query) target.searchParams.set("query", query);
|
||||
return redirect(`${target.pathname}${target.search}`);
|
||||
};
|
||||
|
||||
export const handle = {
|
||||
moduleKey: "chat",
|
||||
breadcrumbKey: "chat.archived.title",
|
||||
};
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadChatContext: vi.fn(),
|
||||
requireChatPermission: vi.fn(),
|
||||
loadFilesContext: vi.fn(),
|
||||
requireFilesPermission: vi.fn(),
|
||||
getOwnedFileScanStatus: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({
|
||||
loadChatContext: mocks.loadChatContext,
|
||||
requireChatPermission: mocks.requireChatPermission,
|
||||
}));
|
||||
vi.mock("~/utils/integrations/fileAccess.server", () => ({
|
||||
loadFilesContext: mocks.loadFilesContext,
|
||||
requireFilesPermission: mocks.requireFilesPermission,
|
||||
}));
|
||||
vi.mock("~/utils/integrations/fileService.server", () => ({ getOwnedFileScanStatus: mocks.getOwnedFileScanStatus }));
|
||||
|
||||
import { loader } from "./chat.attachments.$fileId.status";
|
||||
|
||||
const chatContext = {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
tenantUserId: "tenant_user_1",
|
||||
permissions: ["chat.write", "files.write"],
|
||||
hasModule: true,
|
||||
};
|
||||
const filesContext = { tenantId: "tenant_1", userId: "user_1", permissions: ["files.write"], hasModule: true };
|
||||
|
||||
describe("chat attachment scan status resource", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadChatContext.mockResolvedValue(chatContext);
|
||||
mocks.loadFilesContext.mockResolvedValue(filesContext);
|
||||
mocks.requireChatPermission.mockImplementation((context) => context);
|
||||
mocks.requireFilesPermission.mockImplementation((context) => context);
|
||||
mocks.getOwnedFileScanStatus.mockResolvedValue("clean");
|
||||
});
|
||||
|
||||
it("returns only the owner-scoped scan status behind chat and files write gates", async () => {
|
||||
const response = await loader({
|
||||
request: new Request("http://app.localhost/demo/chat/attachments/file_1/status"),
|
||||
params: { tenant: "demo", fileId: "file_1" },
|
||||
context: {},
|
||||
});
|
||||
|
||||
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||
await expect(response.json()).resolves.toEqual({ scanStatus: "clean" });
|
||||
expect(mocks.getOwnedFileScanStatus).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", fileId: "file_1" });
|
||||
expect(mocks.requireFilesPermission).toHaveBeenCalledWith(filesContext, "files.write");
|
||||
});
|
||||
|
||||
it("does not query a file when chat and files contexts disagree", async () => {
|
||||
mocks.loadFilesContext.mockResolvedValue({ ...filesContext, userId: "user_other" });
|
||||
const response = await loader({
|
||||
request: new Request("http://app.localhost/demo/chat/attachments/file_1/status"),
|
||||
params: { tenant: "demo", fileId: "file_1" },
|
||||
context: {},
|
||||
});
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(mocks.getOwnedFileScanStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
import { loadChatContext, requireChatPermission } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { loadFilesContext, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { getOwnedFileScanStatus } from "~/utils/integrations/fileService.server";
|
||||
|
||||
type LoaderData = { readonly scanStatus: "pending" | "clean" | "infected" | "skipped" };
|
||||
|
||||
/** Owner-only, tenant/RLS-bound status endpoint used by the chat composer after
|
||||
* the chunk upload finishes. It intentionally exposes no file metadata. */
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [chatContext, filesContext] = await Promise.all([
|
||||
loadChatContext({ request, params }),
|
||||
loadFilesContext({ request, params, requireModule: true }),
|
||||
]);
|
||||
requireChatPermission(chatContext, CHAT_PERMISSIONS.write);
|
||||
requireFilesPermission(filesContext, "files.write");
|
||||
if (chatContext.tenantId !== filesContext.tenantId || chatContext.userId !== filesContext.userId) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
const scanStatus = await getOwnedFileScanStatus({
|
||||
tenantId: chatContext.tenantId,
|
||||
userId: chatContext.userId,
|
||||
fileId: params.fileId ?? "",
|
||||
});
|
||||
return Response.json({ scanStatus } satisfies LoaderData, {
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
});
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { type LoaderFunctionArgs, type MetaFunction, useLoaderData } from "react-router";
|
||||
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { ChatMessageDiscoveryRouteView } from "~/modules/chat/routes/ChatMessageDiscoveryRouteView";
|
||||
import { loadChatMessageDiscoveryRoute } from "~/modules/chat/routes/chatMessageDiscoveryLoader.server";
|
||||
import type { ChatMessageDiscoveryLoaderData } from "~/modules/chat/routes/chatMessageDiscoveryRouteTypes";
|
||||
import { CHAT_MODULE_KEY } from "~/modules/chat/routes/chatRoutePaths";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => loadChatMessageDiscoveryRoute(args, "mentions");
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as ChatMessageDiscoveryLoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatMentionsRoute() {
|
||||
return <ChatMessageDiscoveryRouteView data={useLoaderData<ChatMessageDiscoveryLoaderData>()} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CHAT_MODULE_KEY };
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { buildChatChannelCreateVM } from "@hivegrid/view-models";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadChatContext: vi.fn(),
|
||||
loadCreatePage: vi.fn(),
|
||||
createChatChannel: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({
|
||||
loadChatContext: mocks.loadChatContext,
|
||||
}));
|
||||
vi.mock("~/modules/chat/services/ChatChannelCreateService.server", () => ({
|
||||
loadChatChannelCreatePage: mocks.loadCreatePage,
|
||||
createChatChannel: mocks.createChatChannel,
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: mocks.validateCSRFToken,
|
||||
}));
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ csrf: "csrf_test" }),
|
||||
}));
|
||||
vi.mock("~/components/screens/chat/ChatChannelCreatePage", () => ({
|
||||
ChatChannelCreatePage: () => null,
|
||||
}));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
|
||||
import { action, loader } from "./chat.new";
|
||||
|
||||
const context = {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_current",
|
||||
tenantUserId: "tenant_user_current",
|
||||
permissions: ["chat.create_channel", "chat.create_dm"],
|
||||
hasModule: true as const,
|
||||
};
|
||||
const CREATION_REQUEST_ID = "chat-create-request-0001";
|
||||
|
||||
describe("AK-P15b chat create route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.loadChatContext.mockResolvedValue(context);
|
||||
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
||||
mocks.createChatChannel.mockResolvedValue({ chatId: "chat_created" });
|
||||
mocks.loadCreatePage.mockResolvedValue(createVm("dm"));
|
||||
});
|
||||
|
||||
it("loads the requested create mode through the tenant-scoped chat context", async () => {
|
||||
const request = new Request("https://app.example.test/demo/chat/new?kind=dm");
|
||||
const response = await loader({ request, params: { tenant: "demo" }, context: {}, unstable_pattern: "app.$tenant/chat.new" });
|
||||
const data = await response.json();
|
||||
|
||||
expect(mocks.loadChatContext).toHaveBeenCalledWith({ request, params: { tenant: "demo" } });
|
||||
expect(mocks.loadCreatePage).toHaveBeenCalledWith({ context, requestedMode: "dm" });
|
||||
expect(data).toEqual(expect.objectContaining({ tenantSlug: "demo", requestId: expect.any(String), vm: createVm("dm") }));
|
||||
});
|
||||
|
||||
it("returns a 404 when neither create permission is available", async () => {
|
||||
mocks.loadCreatePage.mockResolvedValue(
|
||||
buildChatChannelCreateVM({
|
||||
currentUserId: "user_current",
|
||||
tenantUsers: [],
|
||||
permissions: { canCreateGroup: false, canCreateDm: false },
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
loader({
|
||||
request: new Request("https://app.example.test/demo/chat/new"),
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.new",
|
||||
})
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("validates CSRF and creates a group with unique initial members", async () => {
|
||||
const form = new FormData();
|
||||
form.set("csrf", "csrf_test");
|
||||
form.set("requestId", CREATION_REQUEST_ID);
|
||||
form.set("mode", "group");
|
||||
form.set("name", " Montage Nord ");
|
||||
form.set("description", " Abstimmung ");
|
||||
form.set("privacy", "private");
|
||||
form.append("initialUserIds", "user_mara");
|
||||
form.append("initialUserIds", "user_noah");
|
||||
form.append("initialGroupIds", "group_south");
|
||||
form.set("syncGroupMembership", "true");
|
||||
const request = postRequest(form);
|
||||
|
||||
const response = await action({ request, params: { tenant: "demo" }, context: {}, unstable_pattern: "app.$tenant/chat.new" });
|
||||
|
||||
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() });
|
||||
expect(mocks.createChatChannel).toHaveBeenCalledWith({
|
||||
context,
|
||||
requestId: CREATION_REQUEST_ID,
|
||||
submission: {
|
||||
mode: "group",
|
||||
name: "Montage Nord",
|
||||
description: "Abstimmung",
|
||||
privacy: "private",
|
||||
initialUserIds: ["user_mara", "user_noah"],
|
||||
initialGroupIds: ["group_south"],
|
||||
syncGroupMembership: true,
|
||||
},
|
||||
});
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("location")).toBe("/demo/chat/chat_created?toast=chat.toast.groupCreated");
|
||||
});
|
||||
|
||||
it("strictly rejects duplicate group members before the lifecycle call", async () => {
|
||||
const form = new FormData();
|
||||
form.set("csrf", "csrf_test");
|
||||
form.set("requestId", CREATION_REQUEST_ID);
|
||||
form.set("mode", "group");
|
||||
form.set("name", "Montage Nord");
|
||||
form.set("description", "");
|
||||
form.set("privacy", "public");
|
||||
form.set("syncGroupMembership", "false");
|
||||
form.append("initialUserIds", "user_mara");
|
||||
form.append("initialUserIds", "user_mara");
|
||||
|
||||
const response = await action({
|
||||
request: postRequest(form),
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.new",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(await response.json()).toEqual({ errorKey: "chat.channelCreate.validation.duplicateInitialUsers" });
|
||||
expect(mocks.createChatChannel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects automatic group sync without a selected permission group", async () => {
|
||||
const form = new FormData();
|
||||
form.set("csrf", "csrf_test");
|
||||
form.set("requestId", CREATION_REQUEST_ID);
|
||||
form.set("mode", "group");
|
||||
form.set("name", "Team Süd");
|
||||
form.set("description", "");
|
||||
form.set("privacy", "private");
|
||||
form.set("syncGroupMembership", "true");
|
||||
|
||||
const response = await action({
|
||||
request: postRequest(form),
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.new",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(await response.json()).toEqual({ errorKey: "chat.channelCreate.validation.groupUnavailable" });
|
||||
expect(mocks.createChatChannel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("parses exactly one DM peer and redirects to the canonical chat", async () => {
|
||||
const form = new FormData();
|
||||
form.set("csrf", "csrf_test");
|
||||
form.set("requestId", CREATION_REQUEST_ID);
|
||||
form.set("mode", "dm");
|
||||
form.set("peerUserId", "user_mara");
|
||||
|
||||
const response = await action({
|
||||
request: postRequest(form),
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.new",
|
||||
});
|
||||
|
||||
expect(mocks.createChatChannel).toHaveBeenCalledWith({
|
||||
context,
|
||||
requestId: CREATION_REQUEST_ID,
|
||||
submission: { mode: "dm", peerUserId: "user_mara" },
|
||||
});
|
||||
expect(response.headers.get("location")).toBe("/demo/chat/chat_created?toast=chat.toast.directOpened");
|
||||
});
|
||||
|
||||
it("rejects a create submission without the stable browser request id", async () => {
|
||||
const form = new FormData();
|
||||
form.set("csrf", "csrf_test");
|
||||
form.set("mode", "dm");
|
||||
form.set("peerUserId", "user_mara");
|
||||
|
||||
const response = await action({
|
||||
request: postRequest(form),
|
||||
params: { tenant: "demo" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/chat.new",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(await response.json()).toEqual({ errorKey: "chat.errors.invalidInput" });
|
||||
expect(mocks.createChatChannel).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
function createVm(requestedMode: "group" | "dm") {
|
||||
return buildChatChannelCreateVM({
|
||||
currentUserId: "user_current",
|
||||
requestedMode,
|
||||
tenantUsers: [
|
||||
{
|
||||
userId: "user_mara",
|
||||
displayName: "Mara Klein",
|
||||
email: "mara@example.test",
|
||||
avatar: { imageUrl: null, fallbackLabel: "MK" },
|
||||
},
|
||||
],
|
||||
permissions: { canCreateGroup: true, canCreateDm: true },
|
||||
});
|
||||
}
|
||||
|
||||
function postRequest(formData: FormData): Request {
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of formData.entries()) body.append(key, value.toString());
|
||||
return new Request("https://app.example.test/demo/chat/new", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
import {
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
type MetaFunction,
|
||||
redirect,
|
||||
useActionData,
|
||||
useLoaderData,
|
||||
useNavigate,
|
||||
useNavigation,
|
||||
useRevalidator,
|
||||
useSubmit,
|
||||
} from "react-router";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import {
|
||||
chatChannelCreateSubmissionSchema,
|
||||
type ChatChannelCreateMode,
|
||||
type ChatChannelCreateSubmission,
|
||||
type ChatChannelCreateVM,
|
||||
} from "@hivegrid/view-models";
|
||||
|
||||
import { ChatChannelCreatePage } from "~/components/screens/chat/ChatChannelCreatePage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadChatContext } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { CHAT_MODULE_KEY, chatChannelPath, chatIndexPath, chatNotFoundResponse } from "~/modules/chat/routes/chatRoutePaths";
|
||||
import { createChatChannel, loadChatChannelCreatePage } from "~/modules/chat/services/ChatChannelCreateService.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
readonly title: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly requestId: string;
|
||||
readonly vm: ChatChannelCreateVM;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
readonly errorKey: string;
|
||||
};
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const vm = await loadChatChannelCreatePage({
|
||||
context,
|
||||
requestedMode: parseRequestedMode(new URL(request.url).searchParams.get("kind")),
|
||||
});
|
||||
|
||||
if (vm.status === "ready" && vm.data.allowedModes.length === 0) {
|
||||
throw chatNotFoundResponse();
|
||||
}
|
||||
|
||||
return Response.json({
|
||||
title: `${t("chat.channelCreate.title")} | ${process.env.APP_NAME}`,
|
||||
tenantSlug,
|
||||
requestId: crypto.randomUUID(),
|
||||
vm,
|
||||
} satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const context = await loadChatContext({ request, params });
|
||||
const formData = await request.formData();
|
||||
await validateCSRFToken(request, { formData });
|
||||
|
||||
const parsed = chatChannelCreateSubmissionSchema.safeParse(readSubmission(formData));
|
||||
if (!parsed.success) {
|
||||
return Response.json({ errorKey: parsed.error.issues[0]?.message ?? "chat.errors.invalidInput" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const requestId = formData.get("requestId")?.toString().trim() ?? "";
|
||||
if (!requestId || requestId.length > 191 || requestId.includes("\0")) {
|
||||
return Response.json({ errorKey: "chat.errors.invalidInput" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await createChatChannel({
|
||||
context,
|
||||
requestId,
|
||||
submission: parsed.data,
|
||||
});
|
||||
const messageKey = parsed.data.mode === "group" ? "chat.toast.groupCreated" : "chat.toast.directOpened";
|
||||
return redirect(`${chatChannelPath(params.tenant ?? "", result.chatId)}?toast=${encodeURIComponent(messageKey)}`);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
return Response.json({ errorKey: error.i18nKey } satisfies ActionData, { status: error.status });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatChannelCreateRoute(): React.JSX.Element {
|
||||
const { tenantSlug, requestId, vm } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const navigation = useNavigation();
|
||||
const revalidator = useRevalidator();
|
||||
const submit = useSubmit();
|
||||
const { csrf } = useRootData();
|
||||
|
||||
return (
|
||||
<ChatChannelCreatePage
|
||||
vm={vm}
|
||||
busy={navigation.state === "submitting"}
|
||||
actionErrorKey={actionData?.errorKey}
|
||||
actions={{
|
||||
onCancel: () => void navigate(chatIndexPath(tenantSlug)),
|
||||
onRetry: () => revalidator.revalidate(),
|
||||
onCreate: (submission) => {
|
||||
const formData = submissionToFormData(submission, requestId);
|
||||
formData.set("csrf", csrf ?? "");
|
||||
void submit(formData, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function parseRequestedMode(value: string | null): ChatChannelCreateMode | undefined {
|
||||
return value === "group" || value === "dm" ? value : undefined;
|
||||
}
|
||||
|
||||
function readSubmission(formData: FormData): unknown {
|
||||
const mode = formData.get("mode")?.toString() ?? "";
|
||||
if (mode === "group") {
|
||||
const description = formData.get("description")?.toString().trim() ?? "";
|
||||
return {
|
||||
mode,
|
||||
name: formData.get("name")?.toString() ?? "",
|
||||
description: description || null,
|
||||
privacy: formData.get("privacy")?.toString() ?? "",
|
||||
initialUserIds: formData.getAll("initialUserIds").map((value) => value.toString()),
|
||||
initialGroupIds: formData.getAll("initialGroupIds").map((value) => value.toString()),
|
||||
syncGroupMembership: formData.get("syncGroupMembership")?.toString() === "true",
|
||||
};
|
||||
}
|
||||
if (mode === "dm") {
|
||||
return {
|
||||
mode,
|
||||
peerUserId: formData.get("peerUserId")?.toString() ?? "",
|
||||
};
|
||||
}
|
||||
return { mode };
|
||||
}
|
||||
|
||||
function submissionToFormData(submission: ChatChannelCreateSubmission, requestId: string): FormData {
|
||||
const formData = new FormData();
|
||||
formData.set("requestId", requestId);
|
||||
formData.set("mode", submission.mode);
|
||||
if (submission.mode === "group") {
|
||||
formData.set("name", submission.name);
|
||||
formData.set("description", submission.description ?? "");
|
||||
formData.set("privacy", submission.privacy);
|
||||
for (const userId of submission.initialUserIds) formData.append("initialUserIds", userId);
|
||||
for (const groupId of submission.initialGroupIds) formData.append("initialGroupIds", groupId);
|
||||
formData.set("syncGroupMembership", String(submission.syncGroupMembership));
|
||||
} else {
|
||||
formData.set("peerUserId", submission.peerUserId);
|
||||
}
|
||||
return formData;
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = {
|
||||
moduleKey: CHAT_MODULE_KEY,
|
||||
breadcrumbKey: "chat.channelCreate.title",
|
||||
};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { type LoaderFunctionArgs, type MetaFunction, useLoaderData } from "react-router";
|
||||
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { ChatMessageDiscoveryRouteView } from "~/modules/chat/routes/ChatMessageDiscoveryRouteView";
|
||||
import { loadChatMessageDiscoveryRoute } from "~/modules/chat/routes/chatMessageDiscoveryLoader.server";
|
||||
import type { ChatMessageDiscoveryLoaderData } from "~/modules/chat/routes/chatMessageDiscoveryRouteTypes";
|
||||
import { CHAT_MODULE_KEY } from "~/modules/chat/routes/chatRoutePaths";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => loadChatMessageDiscoveryRoute(args, "search");
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as ChatMessageDiscoveryLoaderData | undefined)?.title }];
|
||||
|
||||
export default function ChatMessageSearchRoute() {
|
||||
return <ChatMessageDiscoveryRouteView data={useLoaderData<ChatMessageDiscoveryLoaderData>()} />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: CHAT_MODULE_KEY };
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
loadChatContext: vi.fn(),
|
||||
requireChatPermission: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
getValidatedServerSession: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
issueChatGatewayToken: vi.fn(),
|
||||
checkChatGatewayTokenRateLimit: vi.fn(),
|
||||
loggerWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({
|
||||
loadChatContext: mocks.loadChatContext,
|
||||
requireChatPermission: mocks.requireChatPermission,
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: mocks.getUserInfo,
|
||||
getValidatedServerSession: mocks.getValidatedServerSession,
|
||||
validateCSRFToken: mocks.validateCSRFToken,
|
||||
}));
|
||||
vi.mock("@hivegrid/chat/gateway-auth.server", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@hivegrid/chat/gateway-auth.server")>()),
|
||||
issueChatGatewayToken: mocks.issueChatGatewayToken,
|
||||
}));
|
||||
vi.mock("~/modules/chat/services/chatGatewayRateLimit.server", () => ({
|
||||
checkChatGatewayTokenRateLimit: mocks.checkChatGatewayTokenRateLimit,
|
||||
}));
|
||||
vi.mock("~/utils/logger.server", () => ({
|
||||
createScopedLogger: () => ({ warn: mocks.loggerWarn }),
|
||||
}));
|
||||
|
||||
import { action, loader } from "./chat.token";
|
||||
|
||||
const context = {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
tenantUserId: "tenant_user_1",
|
||||
permissions: ["chat.read_own_channels"],
|
||||
hasModule: true,
|
||||
} as const;
|
||||
const NOW = new Date("2026-07-15T10:00:00.000Z");
|
||||
|
||||
function request() {
|
||||
return new Request("https://app.example.test/hivegrid-demo/chat/token", {
|
||||
method: "POST",
|
||||
headers: { "x-csrf-token": "csrf-token" },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(NOW);
|
||||
vi.stubEnv("CHAT_GATEWAY_AUTH_SECRET", "chat-gateway-secret-at-least-32-bytes-long");
|
||||
mocks.loadChatContext.mockResolvedValue(context);
|
||||
mocks.requireChatPermission.mockImplementation((value) => value);
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
|
||||
mocks.getValidatedServerSession.mockResolvedValue({
|
||||
id: "session_1",
|
||||
userId: "user_1",
|
||||
expiresAt: new Date("2026-07-15T11:00:00.000Z"),
|
||||
user: { admin: null },
|
||||
});
|
||||
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
||||
mocks.issueChatGatewayToken.mockReturnValue("signed-chat-token");
|
||||
mocks.checkChatGatewayTokenRateLimit.mockResolvedValue({ allowed: true, remaining: 19 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("tenant chat token resource", () => {
|
||||
it("keeps GET undiscoverable", () => {
|
||||
expect(loader()).toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("mints an identity-only token after module, permission, CSRF, and live-session checks", async () => {
|
||||
const incoming = request();
|
||||
const response = await action({ request: incoming, params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.loadChatContext).toHaveBeenCalledWith({ request: incoming, params: { tenant: "hivegrid-demo" } });
|
||||
expect(mocks.requireChatPermission).toHaveBeenCalledWith(context, "chat.read_own_channels");
|
||||
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(incoming, { headerOnly: true });
|
||||
expect(mocks.getValidatedServerSession).toHaveBeenCalledWith(incoming, { userId: "user_1" });
|
||||
expect(mocks.checkChatGatewayTokenRateLimit).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
sessionId: "session_1",
|
||||
});
|
||||
expect(mocks.issueChatGatewayToken).toHaveBeenCalledWith({
|
||||
userId: "user_1",
|
||||
tenantId: "tenant_1",
|
||||
sessionId: "session_1",
|
||||
secret: "chat-gateway-secret-at-least-32-bytes-long",
|
||||
ttlSeconds: 900,
|
||||
now: NOW,
|
||||
});
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
ok: true,
|
||||
data: { token: "signed-chat-token", expiresIn: 900, refreshAfter: 840 },
|
||||
});
|
||||
});
|
||||
|
||||
it("caps token lifetime to the remaining live session", async () => {
|
||||
mocks.getValidatedServerSession.mockResolvedValueOnce({
|
||||
id: "session_1",
|
||||
userId: "user_1",
|
||||
expiresAt: new Date("2026-07-15T10:01:30.000Z"),
|
||||
user: { admin: null },
|
||||
});
|
||||
|
||||
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(mocks.issueChatGatewayToken).toHaveBeenCalledWith(expect.objectContaining({ ttlSeconds: 90, now: NOW }));
|
||||
await expect(response.json()).resolves.toMatchObject({ data: { expiresIn: 90, refreshAfter: 72 } });
|
||||
});
|
||||
|
||||
it("ignores the removed legacy User admin projection for regular tenant sessions", async () => {
|
||||
mocks.getValidatedServerSession.mockResolvedValueOnce({
|
||||
id: "session_admin",
|
||||
userId: "user_1",
|
||||
expiresAt: new Date("2026-07-15T10:10:00.000Z"),
|
||||
user: { admin: { userId: "user_1" } },
|
||||
});
|
||||
|
||||
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.issueChatGatewayToken).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: "user_1", tenantId: "tenant_1", sessionId: "session_admin" })
|
||||
);
|
||||
});
|
||||
|
||||
it("allows only POST for token minting", async () => {
|
||||
const incoming = new Request("https://app.example.test/hivegrid-demo/chat/token", { method: "PATCH" });
|
||||
|
||||
const response = await action({ request: incoming, params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(405);
|
||||
expect(response.headers.get("allow")).toBe("POST");
|
||||
expect(mocks.loadChatContext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 404 before token issuance when module or permission access is denied", async () => {
|
||||
mocks.requireChatPermission.mockImplementationOnce(() => {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
});
|
||||
|
||||
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(mocks.validateCSRFToken).not.toHaveBeenCalled();
|
||||
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects impersonation and a revoked server session", async () => {
|
||||
mocks.getUserInfo.mockResolvedValueOnce({ userId: "user_1", impersonatingFromUserId: "operator_1" });
|
||||
const impersonated = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
mocks.getValidatedServerSession.mockResolvedValueOnce(null);
|
||||
const revoked = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(impersonated.status).toBe(404);
|
||||
expect(revoked.status).toBe(404);
|
||||
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails clearly without a dedicated strong gateway secret", async () => {
|
||||
vi.stubEnv("CHAT_GATEWAY_AUTH_SECRET", "too-short");
|
||||
|
||||
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
ok: false,
|
||||
error: "chat.errors.realtimeUnavailable",
|
||||
code: "chat.realtime_unavailable",
|
||||
});
|
||||
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rate limits token minting with retry timing and no token disclosure", async () => {
|
||||
mocks.checkChatGatewayTokenRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 37 });
|
||||
|
||||
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.headers.get("retry-after")).toBe("37");
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
ok: false,
|
||||
error: "chat.errors.realtimeRateLimited",
|
||||
code: "chat.realtime_rate_limited",
|
||||
});
|
||||
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the shared token limiter is unavailable", async () => {
|
||||
mocks.checkChatGatewayTokenRateLimit.mockRejectedValueOnce(new Error("Redis unavailable"));
|
||||
|
||||
const response = await action({ request: request(), params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
ok: false,
|
||||
error: "chat.errors.realtimeUnavailable",
|
||||
code: "chat.realtime_unavailable",
|
||||
});
|
||||
expect(mocks.issueChatGatewayToken).not.toHaveBeenCalled();
|
||||
expect(mocks.loggerWarn).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", errorName: "Error" }, "Chat gateway token rate limiter failed");
|
||||
});
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import { CHAT_PERMISSIONS, chatErrors } from "@hivegrid/chat";
|
||||
import { CHAT_GATEWAY_MIN_SECRET_BYTES, CHAT_GATEWAY_TOKEN_DEFAULT_TTL_SECONDS, issueChatGatewayToken } from "@hivegrid/chat/gateway-auth.server";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
|
||||
import { loadChatContext, requireChatPermission } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { checkChatGatewayTokenRateLimit } from "~/modules/chat/services/chatGatewayRateLimit.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { getUserInfo, getValidatedServerSession, validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
const TOKEN_REFRESH_SKEW_SECONDS = 60;
|
||||
const MIN_TOKEN_TTL_SECONDS = 5;
|
||||
const NO_STORE_HEADERS = { "cache-control": "no-store", pragma: "no-cache" } as const;
|
||||
const logger = createScopedLogger("chat.gateway-token");
|
||||
|
||||
export const loader = () => new Response(null, { status: 404 });
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
if (request.method !== "POST") {
|
||||
return new Response(null, { status: 405, headers: { allow: "POST", ...NO_STORE_HEADERS } });
|
||||
}
|
||||
|
||||
let context;
|
||||
try {
|
||||
context = requireChatPermission(await loadChatContext({ request, params }), CHAT_PERMISSIONS.readOwnChannels);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) return new Response(null, { status: 404 });
|
||||
throw error;
|
||||
}
|
||||
|
||||
await validateCSRFToken(request, { headerOnly: true });
|
||||
const userInfo = await getUserInfo(request);
|
||||
if (userInfo.impersonatingFromUserId || userInfo.userId !== context.userId) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
|
||||
const session = await getValidatedServerSession(request, userInfo);
|
||||
if (!session || !("user" in session) || session.userId !== context.userId) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
|
||||
const secret = process.env.CHAT_GATEWAY_AUTH_SECRET ?? "";
|
||||
if (secret !== secret.trim() || Buffer.byteLength(secret, "utf8") < CHAT_GATEWAY_MIN_SECRET_BYTES) {
|
||||
return Response.json(
|
||||
{ ok: false, error: chatErrors.realtimeUnavailable.i18nKey, code: chatErrors.realtimeUnavailable.code },
|
||||
{ status: chatErrors.realtimeUnavailable.status, headers: NO_STORE_HEADERS }
|
||||
);
|
||||
}
|
||||
|
||||
let rateLimit;
|
||||
try {
|
||||
rateLimit = await checkChatGatewayTokenRateLimit({
|
||||
tenantId: context.tenantId,
|
||||
userId: context.userId,
|
||||
sessionId: session.id,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{
|
||||
tenantId: context.tenantId,
|
||||
userId: context.userId,
|
||||
errorName: error instanceof Error ? error.name : "Error",
|
||||
},
|
||||
"Chat gateway token rate limiter failed"
|
||||
);
|
||||
return Response.json(
|
||||
{ ok: false, error: chatErrors.realtimeUnavailable.i18nKey, code: chatErrors.realtimeUnavailable.code },
|
||||
{ status: chatErrors.realtimeUnavailable.status, headers: NO_STORE_HEADERS }
|
||||
);
|
||||
}
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json(
|
||||
{ ok: false, error: chatErrors.realtimeRateLimited.i18nKey, code: chatErrors.realtimeRateLimited.code },
|
||||
{
|
||||
status: chatErrors.realtimeRateLimited.status,
|
||||
headers: { ...NO_STORE_HEADERS, "retry-after": String(rateLimit.retryAfterSeconds) },
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const sessionExpiryMs = session.expiresAt instanceof Date ? session.expiresAt.getTime() : Number.NaN;
|
||||
const remainingSessionSeconds = Math.floor((sessionExpiryMs - now.getTime()) / 1_000);
|
||||
const expiresIn = Math.min(CHAT_GATEWAY_TOKEN_DEFAULT_TTL_SECONDS, remainingSessionSeconds);
|
||||
if (!Number.isFinite(expiresIn) || expiresIn < MIN_TOKEN_TTL_SECONDS) {
|
||||
return new Response(null, { status: 404, headers: NO_STORE_HEADERS });
|
||||
}
|
||||
const refreshSkew = Math.min(TOKEN_REFRESH_SKEW_SECONDS, Math.max(1, Math.floor(expiresIn / 5)));
|
||||
|
||||
const token = issueChatGatewayToken({
|
||||
userId: context.userId,
|
||||
tenantId: context.tenantId,
|
||||
sessionId: session.id,
|
||||
secret,
|
||||
ttlSeconds: expiresIn,
|
||||
now,
|
||||
});
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
ok: true,
|
||||
data: {
|
||||
token,
|
||||
expiresIn,
|
||||
refreshAfter: expiresIn - refreshSkew,
|
||||
},
|
||||
},
|
||||
{ headers: NO_STORE_HEADERS }
|
||||
);
|
||||
}
|
||||
+9
-1
@@ -32,7 +32,15 @@ describe("CRM contact routes (R-P6 slice 4)", () => {
|
||||
expect(list).toContain("export const action");
|
||||
expect(list).toContain("loadKontaktListData");
|
||||
expect(list).toContain("handleKontaktListAction");
|
||||
expect(list).not.toContain("useFetcher");
|
||||
// The route may own a fetcher (the create dialog's live duplicate check posts
|
||||
// to the new-route via useFetcher and the result is injected as a prop). The
|
||||
// layer rule (DoD A.5) applies to the presentational screen, not the route:
|
||||
// the dialog component itself must not call useFetcher / useLoaderData.
|
||||
// Match real hook calls (`useFetcher(` / `useFetcher<`) with no space, so the
|
||||
// "No useLoaderData / useFetcher (DoD A.5)" comment in the file is not a hit.
|
||||
const newDialog = fs.readFileSync(path.join(repoRoot, "apps/web/app/components/screens/crm/KontaktNewDialog.tsx"), "utf8");
|
||||
expect(newDialog).not.toMatch(/useFetcher[(<]/);
|
||||
expect(newDialog).not.toMatch(/useLoaderData[(<]/);
|
||||
|
||||
const companies = read("contacts.companies._index.tsx");
|
||||
expect(companies).toContain('variant: "companies"');
|
||||
|
||||
+40
-6
@@ -1,13 +1,16 @@
|
||||
// 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.
|
||||
// contact list (DoD 9). Not visible / module off -> 404. UI is the AD-28 interim
|
||||
// KontaktDetailPage (composed from ~/ui); the route POSTs each intent.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData, useNavigation, useSubmit } 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 { KontaktDetailPage } from "~/components/screens/crm/KontaktDetailPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json(await loadKontaktDetailData({ request, params, variant: "contacts" }));
|
||||
@@ -19,20 +22,51 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
export default function ContactDetailRoute() {
|
||||
const data = useLoaderData<KontaktDetailLoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
const actionData = useActionData<{ error?: string; messageKey?: string }>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
useSaveToast(actionData);
|
||||
|
||||
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 <div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.crm.detail" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<KontaktDetailView
|
||||
<KontaktDetailPage
|
||||
data={data.detailVM.data}
|
||||
activity={data.activityVM}
|
||||
allTags={data.allTags}
|
||||
tagsAdminHref={data.tagsAdminHref ?? undefined}
|
||||
customFieldDefs={data.customFieldDefs}
|
||||
ownerOptions={data.ownerOptions}
|
||||
backHref={data.backHref}
|
||||
listLabelKey={data.listLabelKey}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
messageKey={actionData?.messageKey ?? null}
|
||||
clickToCall={{
|
||||
vm: data.clickToCallVM,
|
||||
busy: navigation.state !== "idle",
|
||||
onCall: (number, mode) => {
|
||||
if (mode === "tel-fallback") {
|
||||
window.location.assign(`tel:${number.e164}`);
|
||||
return;
|
||||
}
|
||||
const form = new FormData();
|
||||
form.set("intent", "startTelephonyCall");
|
||||
form.set("numberId", number.id);
|
||||
form.set("destination", number.e164);
|
||||
submit(appendCSRFToken(form), { method: "post" });
|
||||
},
|
||||
}}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", intent);
|
||||
if (fields) for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
||||
submit(intent === "invitePortalContact" ? appendCSRFToken(form) : form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
+75
-10
@@ -1,14 +1,26 @@
|
||||
// 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).
|
||||
// crm.read_own -> 404. UI is the AD-28 interim KontaktListPage (composed from
|
||||
// ~/ui); the route owns navigation (filter/sort/page) + the bulk POST and injects
|
||||
// them as action callbacks. Final optics arrive with David's D-CRM delta.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import {
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
useActionData,
|
||||
useLoaderData,
|
||||
useFetcher,
|
||||
useNavigate,
|
||||
useSubmit,
|
||||
} from "react-router";
|
||||
import { handleKontaktListAction, loadKontaktListData, type KontaktListLoaderData } from "~/utils/integrations/crm/crmListRoute.server";
|
||||
import { kontaktListQueryToParams, type KontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
|
||||
import { CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import KontaktListView from "~/components/crm/KontaktListView";
|
||||
import { KontaktListPage } from "~/components/screens/crm/KontaktListPage";
|
||||
import type { KontaktNewDuplicates } from "~/components/screens/crm/KontaktNewPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json(await loadKontaktListData({ request, params, variant: "contacts" }));
|
||||
@@ -21,18 +33,71 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
export default function ContactsIndexRoute() {
|
||||
const data = useLoaderData<KontaktListLoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
const navigate = useNavigate();
|
||||
// Live duplicate check for the create dialog — posts to the create route, which
|
||||
// owns the `intent=checkDuplicates` branch (same contract as the standalone page).
|
||||
const dupFetcher = useFetcher<KontaktNewDuplicates>();
|
||||
const submit = useSubmit();
|
||||
useSaveToast(actionData);
|
||||
|
||||
const toHref = (query: KontaktListQuery): string => {
|
||||
const qs = kontaktListQueryToParams(query).toString();
|
||||
return qs ? `${data.baseHref}?${qs}` : data.baseHref;
|
||||
};
|
||||
|
||||
return (
|
||||
<KontaktListView
|
||||
moduleActive={data.moduleActive}
|
||||
variant="contacts"
|
||||
<KontaktListPage
|
||||
vm={data.vm}
|
||||
variant="contacts"
|
||||
moduleActive={data.moduleActive}
|
||||
query={data.query}
|
||||
tagOptions={data.tagOptions}
|
||||
ownerOptions={data.ownerOptions}
|
||||
query={data.query}
|
||||
baseHref={data.baseHref}
|
||||
canWrite={data.canWrite}
|
||||
canAdmin={data.canAdmin}
|
||||
nav={{
|
||||
contactsHref: data.contactsHref,
|
||||
companiesHref: data.companiesHref,
|
||||
customFieldsHref: data.customFieldsHref,
|
||||
tagsHref: data.tagsHref,
|
||||
duplicatesHref: data.duplicatesHref,
|
||||
}}
|
||||
newHref={data.newHref}
|
||||
exportHref={data.exportHref}
|
||||
defaultOwnerId={data.defaultOwnerId}
|
||||
duplicates={dupFetcher.data ?? null}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onApplyFilter: (query) => navigate(toHref(query)),
|
||||
onGoToPage: (page) => navigate(toHref({ ...data.query, page })),
|
||||
onBulk: (intent, ids) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", intent);
|
||||
ids.forEach((id) => form.append("kontaktId", id));
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onCheckDuplicates: (fields) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "checkDuplicates");
|
||||
for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
||||
dupFetcher.submit(form, { method: "post", action: data.newHref });
|
||||
},
|
||||
onExport: () => window.location.assign(data.exportHref),
|
||||
onNavigate: (href) => navigate(href),
|
||||
onAssignTag: (kontaktId, tagId) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "assignTag");
|
||||
form.set("kontaktId", kontaktId);
|
||||
form.set("tagId", tagId);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onRemoveTag: (kontaktId, tagId) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "removeTag");
|
||||
form.set("kontaktId", kontaktId);
|
||||
form.set("tagId", tagId);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
+40
-116
@@ -2,8 +2,7 @@
|
||||
// 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 { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import { buildCustomFieldAdminVM, type CustomFieldAdminVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
@@ -20,33 +19,25 @@ import {
|
||||
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 { contactsPath, CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import { CustomFieldAdminPage } from "~/components/screens/crm/CustomFieldAdminPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
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 };
|
||||
type BreadcrumbAncestor = { label: string; href: string };
|
||||
type LoaderData = { title: string; moduleActive: boolean; vm: CustomFieldAdminVM; breadcrumbAncestors: BreadcrumbAncestor[] };
|
||||
|
||||
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}`;
|
||||
// Flat routes give this admin page no shared "Kontakte" layout to hang a crumb
|
||||
// on, so name the list page it is reached through explicitly.
|
||||
const breadcrumbAncestors = [{ label: t("crm.contacts.title"), href: contactsPath(params.tenant ?? "") }];
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, moduleActive: false, vm: buildCustomFieldAdminVM({ rows: [], entityType: ENTITY_TYPE, canWrite: false }) } satisfies LoaderData);
|
||||
return Response.json({ title, moduleActive: false, vm: buildCustomFieldAdminVM({ rows: [], entityType: ENTITY_TYPE, canWrite: false }), breadcrumbAncestors } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.admin");
|
||||
@@ -55,7 +46,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
}
|
||||
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);
|
||||
return Response.json({ title, moduleActive: true, vm, breadcrumbAncestors } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
@@ -77,7 +68,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
optionen,
|
||||
});
|
||||
await auditCrmEvent({ ctx, action: "custom_field.created", targetType: "custom_field", targetId: created.id, metadata: { key: created.key } });
|
||||
return Response.json({ ok: true });
|
||||
return Response.json({ ok: true, intent, messageKey: "crm.toast.customFieldCreated" });
|
||||
}
|
||||
if (intent === "archive") {
|
||||
const definitionId = form.get("definitionId")?.toString().trim();
|
||||
@@ -86,7 +77,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
}
|
||||
await archiveCustomFieldDefinition({ tenantId: ctx.tenantId, definitionId });
|
||||
await auditCrmEvent({ ctx, action: "custom_field.archived", targetType: "custom_field", targetId: definitionId });
|
||||
return Response.json({ ok: true });
|
||||
return Response.json({ ok: true, intent, messageKey: "crm.toast.customFieldArchived" });
|
||||
}
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
@@ -98,103 +89,36 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
};
|
||||
|
||||
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 : [];
|
||||
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
|
||||
useSaveToast(actionData);
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
|
||||
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>
|
||||
<CustomFieldAdminPage
|
||||
vm={vm}
|
||||
moduleActive={moduleActive}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onCreate: ({ key, label, datentyp, optionen }) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "create");
|
||||
form.set("key", key);
|
||||
form.set("label", label);
|
||||
form.set("datentyp", datentyp);
|
||||
form.set("optionen", optionen);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onArchive: (definitionId) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "archive");
|
||||
form.set("definitionId", definitionId);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+75
-55
@@ -3,18 +3,34 @@
|
||||
// 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 { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
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 {
|
||||
badRequestResponse,
|
||||
crmActionErrorResponse,
|
||||
loadCrmContext,
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
type CrmVisibilityContext,
|
||||
} from "~/utils/integrations/crm/crmAccess.server";
|
||||
import { findDuplicateKontakte, getVisibleKontaktOrThrow, hardDeleteKontakt, listKontakteForCsv, resolveUserLabels, type KontaktRow } from "~/utils/integrations/crm/crmService.server";
|
||||
import { auditCrmEvent } from "~/utils/integrations/crm/crmAudit.server";
|
||||
import { contactDetailPath, contactsPath, CRM_MODULE_KEY, duplicatesAdminPath } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import { DuplicateToolPage } from "~/components/screens/crm/DuplicateToolPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
const MAX_SCAN = 200;
|
||||
|
||||
type LoaderData = { title: string; moduleActive: boolean; vm: DuplicateVM; tenantSlug: string };
|
||||
type BreadcrumbAncestor = { label: string; href: string };
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
moduleActive: boolean;
|
||||
vm: DuplicateVM;
|
||||
tenantSlug: string;
|
||||
canDelete: boolean;
|
||||
breadcrumbAncestors: BreadcrumbAncestor[];
|
||||
};
|
||||
|
||||
function hardReason(a: KontaktRow, b: KontaktRow): string {
|
||||
if (a.primaerEmail && b.primaerEmail && a.primaerEmail.toLowerCase() === b.primaerEmail.toLowerCase()) {
|
||||
@@ -31,15 +47,19 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const ctx = await loadCrmContext({ request, params });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const title = `${t("crm.admin.duplicates.title")} | ${process.env.APP_NAME}`;
|
||||
// Flat routes give this admin page no shared "Kontakte" layout to hang a crumb
|
||||
// on, so name the list page it is reached through explicitly.
|
||||
const breadcrumbAncestors = [{ label: t("crm.contacts.title"), href: contactsPath(tenantSlug) }];
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, moduleActive: false, vm: buildDuplicateVM({ pairs: [], userLabels: new Map(), canMerge: false, tenantSlug }), tenantSlug } satisfies LoaderData);
|
||||
return Response.json({ title, moduleActive: false, vm: buildDuplicateVM({ pairs: [], userLabels: new Map(), canMerge: false, tenantSlug }), tenantSlug, canDelete: false, breadcrumbAncestors } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.admin");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const canDelete = ctx.permissions.includes("crm.delete");
|
||||
|
||||
// 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).
|
||||
@@ -75,58 +95,58 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
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);
|
||||
return Response.json({ title, moduleActive: true, vm, tenantSlug, canDelete, breadcrumbAncestors } 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();
|
||||
try {
|
||||
if (intent === "delete") {
|
||||
// Hard delete is the most destructive CRM op, so it needs crm.delete on top
|
||||
// of the crm.admin gate that guards the whole duplicate tool.
|
||||
requireCrmPermission(ctx, "crm.delete");
|
||||
const kontaktId = form.get("kontaktId")?.toString().trim();
|
||||
if (!kontaktId) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
// Enforce owner visibility (404 for a contact the operator cannot see).
|
||||
await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
||||
await hardDeleteKontakt({ tenantId: ctx.tenantId, kontaktId });
|
||||
await auditCrmEvent({ ctx, action: "kontakt.deleted", targetType: "kontakt", targetId: kontaktId, metadata: { source: "duplicates" } });
|
||||
return redirect(`${duplicatesAdminPath(tenantSlug)}?toast=${encodeURIComponent("crm.toast.duplicateDeleted")}`);
|
||||
}
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
return crmActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
const { moduleActive, vm, tenantSlug, canDelete } = useLoaderData<LoaderData>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
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>
|
||||
<DuplicateToolPage
|
||||
vm={vm}
|
||||
moduleActive={moduleActive}
|
||||
detailHrefFor={(kontaktId) => contactDetailPath(tenantSlug, kontaktId)}
|
||||
canDelete={canDelete}
|
||||
submitting={navigation.state !== "idle"}
|
||||
actions={{
|
||||
onDelete: (kontaktId) => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "delete");
|
||||
formData.set("kontaktId", kontaktId);
|
||||
submit(formData, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+49
-87
@@ -2,8 +2,7 @@
|
||||
// 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 { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import { buildTagAdminVM, type TagAdminVM } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
@@ -13,19 +12,25 @@ import {
|
||||
notFoundResponse,
|
||||
requireCrmPermission,
|
||||
} from "~/utils/integrations/crm/crmAccess.server";
|
||||
import { countTagUsage, createTag, deleteTag, listTags, updateTag } from "~/utils/integrations/crm/tagService.server";
|
||||
import { countTagUsageByTagIds, 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 { contactsPath, CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import { TagAdminPage } from "~/components/screens/crm/TagAdminPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = { title: string; moduleActive: boolean; vm: TagAdminVM };
|
||||
type BreadcrumbAncestor = { label: string; href: string };
|
||||
type LoaderData = { title: string; moduleActive: boolean; vm: TagAdminVM; breadcrumbAncestors: BreadcrumbAncestor[] };
|
||||
|
||||
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}`;
|
||||
// Flat routes give this admin page no shared "Kontakte" layout to hang a crumb
|
||||
// on, so name the list page it is reached through explicitly.
|
||||
const breadcrumbAncestors = [{ label: t("crm.contacts.title"), href: contactsPath(params.tenant ?? "") }];
|
||||
if (!ctx.hasModule) {
|
||||
return Response.json({ title, moduleActive: false, vm: buildTagAdminVM({ tags: [], usageCounts: new Map(), canWrite: false }) } satisfies LoaderData);
|
||||
return Response.json({ title, moduleActive: false, vm: buildTagAdminVM({ tags: [], usageCounts: new Map(), canWrite: false }), breadcrumbAncestors } satisfies LoaderData);
|
||||
}
|
||||
try {
|
||||
requireCrmPermission(ctx, "crm.admin");
|
||||
@@ -33,10 +38,9 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
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 usageCounts = await countTagUsageByTagIds(ctx.tenantId, tags.map((tag) => tag.id));
|
||||
const vm = buildTagAdminVM({ tags, usageCounts, canWrite: true });
|
||||
return Response.json({ title, moduleActive: true, vm } satisfies LoaderData);
|
||||
return Response.json({ title, moduleActive: true, vm, breadcrumbAncestors } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
@@ -48,7 +52,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
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 });
|
||||
return Response.json({ ok: true, intent, messageKey: "crm.toast.tagCreated" });
|
||||
}
|
||||
const tagId = form.get("tagId")?.toString().trim();
|
||||
if (!tagId) {
|
||||
@@ -57,12 +61,12 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
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 });
|
||||
return Response.json({ ok: true, intent, messageKey: "crm.toast.tagUpdated" });
|
||||
}
|
||||
if (intent === "delete") {
|
||||
await deleteTag({ tenantId: ctx.tenantId, tagId });
|
||||
await auditCrmEvent({ ctx, action: "tag.deleted", targetType: "tag", targetId: tagId });
|
||||
return Response.json({ ok: true });
|
||||
return Response.json({ ok: true, intent, messageKey: "crm.toast.tagDeleted" });
|
||||
}
|
||||
throw badRequestResponse();
|
||||
} catch (error) {
|
||||
@@ -74,84 +78,42 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
};
|
||||
|
||||
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 : [];
|
||||
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
|
||||
useSaveToast(actionData);
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
|
||||
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>
|
||||
<TagAdminPage
|
||||
vm={vm}
|
||||
moduleActive={moduleActive}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onCreate: ({ name, farbe }) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "create");
|
||||
form.set("name", name);
|
||||
form.set("farbe", farbe);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onUpdate: ({ tagId, name, farbe }) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "update");
|
||||
form.set("tagId", tagId);
|
||||
form.set("name", name);
|
||||
form.set("farbe", farbe);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onDelete: (tagId) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "delete");
|
||||
form.set("tagId", tagId);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+39
-7
@@ -1,13 +1,15 @@
|
||||
// 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.
|
||||
// (`/contacts/companies/:id`). Reuses the SAME loader/action/screen as the contact
|
||||
// detail; only the back link / breadcrumb root differs (variant "companies"). Not
|
||||
// visible / module off -> 404. UI is the AD-28 interim KontaktDetailPage.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData, useNavigation, useSubmit } 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 { KontaktDetailPage } from "~/components/screens/crm/KontaktDetailPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json(await loadKontaktDetailData({ request, params, variant: "companies" }));
|
||||
@@ -20,19 +22,49 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
export default function CompanyDetailRoute() {
|
||||
const data = useLoaderData<KontaktDetailLoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
useSaveToast(actionData);
|
||||
|
||||
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 <div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.crm.detail" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<KontaktDetailView
|
||||
<KontaktDetailPage
|
||||
data={data.detailVM.data}
|
||||
activity={data.activityVM}
|
||||
allTags={data.allTags}
|
||||
tagsAdminHref={data.tagsAdminHref ?? undefined}
|
||||
customFieldDefs={data.customFieldDefs}
|
||||
ownerOptions={data.ownerOptions}
|
||||
backHref={data.backHref}
|
||||
listLabelKey={data.listLabelKey}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
clickToCall={{
|
||||
vm: data.clickToCallVM,
|
||||
busy: navigation.state !== "idle",
|
||||
onCall: (number, mode) => {
|
||||
if (mode === "tel-fallback") {
|
||||
window.location.assign(`tel:${number.e164}`);
|
||||
return;
|
||||
}
|
||||
const form = new FormData();
|
||||
form.set("intent", "startTelephonyCall");
|
||||
form.set("numberId", number.id);
|
||||
form.set("destination", number.e164);
|
||||
submit(appendCSRFToken(form), { method: "post" });
|
||||
},
|
||||
}}
|
||||
actions={{
|
||||
onSubmit: (intent, fields) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", intent);
|
||||
if (fields) for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
+73
-9
@@ -1,13 +1,24 @@
|
||||
// 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.
|
||||
// crm.read_own -> 404. UI is the AD-28 interim KontaktListPage (companies variant).
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import {
|
||||
type ActionFunctionArgs,
|
||||
type LoaderFunctionArgs,
|
||||
useActionData,
|
||||
useLoaderData,
|
||||
useFetcher,
|
||||
useNavigate,
|
||||
useSubmit,
|
||||
} from "react-router";
|
||||
import { handleKontaktListAction, loadKontaktListData, type KontaktListLoaderData } from "~/utils/integrations/crm/crmListRoute.server";
|
||||
import { kontaktListQueryToParams, type KontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
|
||||
import { CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import KontaktListView from "~/components/crm/KontaktListView";
|
||||
import { KontaktListPage } from "~/components/screens/crm/KontaktListPage";
|
||||
import type { KontaktNewDuplicates } from "~/components/screens/crm/KontaktNewPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
return Response.json(await loadKontaktListData({ request, params, variant: "companies" }));
|
||||
@@ -20,18 +31,71 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
export default function CompaniesIndexRoute() {
|
||||
const data = useLoaderData<KontaktListLoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
const navigate = useNavigate();
|
||||
// Live duplicate check for the create dialog — posts to the create route, which
|
||||
// owns the `intent=checkDuplicates` branch (same contract as the standalone page).
|
||||
const dupFetcher = useFetcher<KontaktNewDuplicates>();
|
||||
const submit = useSubmit();
|
||||
useSaveToast(actionData);
|
||||
|
||||
const toHref = (query: KontaktListQuery): string => {
|
||||
const qs = kontaktListQueryToParams(query).toString();
|
||||
return qs ? `${data.baseHref}?${qs}` : data.baseHref;
|
||||
};
|
||||
|
||||
return (
|
||||
<KontaktListView
|
||||
moduleActive={data.moduleActive}
|
||||
variant="companies"
|
||||
<KontaktListPage
|
||||
vm={data.vm}
|
||||
variant="companies"
|
||||
moduleActive={data.moduleActive}
|
||||
query={data.query}
|
||||
tagOptions={data.tagOptions}
|
||||
ownerOptions={data.ownerOptions}
|
||||
query={data.query}
|
||||
baseHref={data.baseHref}
|
||||
canWrite={data.canWrite}
|
||||
canAdmin={data.canAdmin}
|
||||
nav={{
|
||||
contactsHref: data.contactsHref,
|
||||
companiesHref: data.companiesHref,
|
||||
customFieldsHref: data.customFieldsHref,
|
||||
tagsHref: data.tagsHref,
|
||||
duplicatesHref: data.duplicatesHref,
|
||||
}}
|
||||
newHref={data.newHref}
|
||||
exportHref={data.exportHref}
|
||||
defaultOwnerId={data.defaultOwnerId}
|
||||
duplicates={dupFetcher.data ?? null}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onApplyFilter: (query) => navigate(toHref(query)),
|
||||
onGoToPage: (page) => navigate(toHref({ ...data.query, page })),
|
||||
onBulk: (intent, ids) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", intent);
|
||||
ids.forEach((id) => form.append("kontaktId", id));
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onCheckDuplicates: (fields) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "checkDuplicates");
|
||||
for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
||||
dupFetcher.submit(form, { method: "post", action: data.newHref });
|
||||
},
|
||||
onExport: () => window.location.assign(data.exportHref),
|
||||
onNavigate: (href) => navigate(href),
|
||||
onAssignTag: (kontaktId, tagId) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "assignTag");
|
||||
form.set("kontaktId", kontaktId);
|
||||
form.set("tagId", tagId);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
onRemoveTag: (kontaktId, tagId) => {
|
||||
const form = new FormData();
|
||||
form.set("intent", "removeTag");
|
||||
form.set("kontaktId", kontaktId);
|
||||
form.set("tagId", tagId);
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
+7
-1
@@ -10,6 +10,7 @@ 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";
|
||||
import { isDemoDataUiEnabled } from "~/utils/services/.server/demoDataUi.server";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
@@ -24,7 +25,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const { filter, sort } = parseKontaktListQuery(url.searchParams);
|
||||
const { filter: parsedFilter, sort } = parseKontaktListQuery(url.searchParams);
|
||||
// Outside staging/dev the `demo=show` query param is ignored server-side
|
||||
// (demo data is a staging/dev-only affordance).
|
||||
const filter = isDemoDataUiEnabled(undefined, { tenantId: ctx.tenantId, tenantSlug: params.tenant })
|
||||
? parsedFilter
|
||||
: { ...parsedFilter, includeDemoData: false };
|
||||
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)));
|
||||
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
// Same shape as the other route guards here: the action pulls in the CRM
|
||||
// context, audit and activity writers, so the contract is asserted against the
|
||||
// source rather than by executing it.
|
||||
const source = readFileSync(resolve(process.cwd(), "apps/web/app/routes/app.$tenant/contacts.new.tsx"), "utf8");
|
||||
|
||||
/** Body of the `intent === "create"` branch, up to the next branch. */
|
||||
function createBranch(): string {
|
||||
const start = source.indexOf('if (intent === "create")');
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const end = source.indexOf("throw badRequestResponse();", start);
|
||||
expect(end).toBeGreaterThan(start);
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
describe("contact creation lands back on the list", () => {
|
||||
it("redirects to the list a contact was created from, not into the new record", () => {
|
||||
const branch = createBranch();
|
||||
|
||||
expect(branch).toContain("companiesPath(tenantSlug)");
|
||||
expect(branch).toContain("contactsPath(tenantSlug)");
|
||||
// Creating from the list is usually one of several in a row; a detail page
|
||||
// would turn the next one into a trip back first.
|
||||
expect(branch).not.toContain("companyDetailPath");
|
||||
expect(branch).not.toContain("contactDetailPath");
|
||||
});
|
||||
|
||||
it("keeps the detail links the duplicate check offers", () => {
|
||||
// The duplicate cards still have to point at the existing records — the
|
||||
// list redirect must not have taken those with it.
|
||||
const duplicates = source.slice(source.indexOf("const toCard"), source.indexOf('if (intent === "create")'));
|
||||
expect(duplicates).toContain("companyDetailPath(tenantSlug, row.id)");
|
||||
expect(duplicates).toContain("contactDetailPath(tenantSlug, row.id)");
|
||||
});
|
||||
|
||||
it("still audits and logs the creation before answering", () => {
|
||||
const branch = createBranch();
|
||||
const audit = branch.indexOf('action: "kontakt.created"');
|
||||
const activity = branch.indexOf('activityType: "contact_created"');
|
||||
const answer = branch.indexOf("return redirect(");
|
||||
|
||||
expect(audit).toBeGreaterThan(-1);
|
||||
expect(activity).toBeGreaterThan(audit);
|
||||
expect(answer).toBeGreaterThan(activity);
|
||||
});
|
||||
|
||||
it("stores a locale-independent activity summary key", () => {
|
||||
const branch = createBranch();
|
||||
|
||||
expect(branch).toContain('summaryText: "crm.activity.contact_created"');
|
||||
expect(branch).not.toContain('summaryText: t("crm.activity.contact_created")');
|
||||
expect(branch).not.toContain('summaryText: "Kontakt angelegt"');
|
||||
});
|
||||
});
|
||||
+40
-168
@@ -3,9 +3,7 @@
|
||||
// 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 { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useFetcher, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import { buildKontaktDisplayName } from "@hivegrid/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import {
|
||||
@@ -17,16 +15,14 @@ import {
|
||||
} 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 { companiesPath, companyDetailPath, contactDetailPath, contactsPath, CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths";
|
||||
import { KontaktNewPage, type KontaktNewFields } from "~/components/screens/crm/KontaktNewPage";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
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 });
|
||||
@@ -91,8 +87,18 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
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));
|
||||
await logKontaktActivity({
|
||||
ctx,
|
||||
kontaktId: created.id,
|
||||
kontaktTyp,
|
||||
activityType: "contact_created",
|
||||
summaryText: "crm.activity.contact_created",
|
||||
});
|
||||
// Back to the list the dialog was opened from, not into the new record.
|
||||
// Creating a contact from the list is usually one of several in a row, and
|
||||
// landing on a detail page turns the next one into a trip back first.
|
||||
const listHref = kontaktTyp === "organisation" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
||||
return redirect(`${listHref}?toast=${encodeURIComponent(kontaktTyp === "organisation" ? "crm.toast.companyCreated" : "crm.toast.contactCreated")}`);
|
||||
}
|
||||
|
||||
throw badRequestResponse();
|
||||
@@ -104,170 +110,36 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
}
|
||||
};
|
||||
|
||||
function fieldsToFormData(fields: KontaktNewFields, intent: string): FormData {
|
||||
const form = new FormData();
|
||||
form.set("intent", intent);
|
||||
for (const [key, value] of Object.entries(fields)) form.set(key, value);
|
||||
return form;
|
||||
}
|
||||
|
||||
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;
|
||||
const submit = useSubmit();
|
||||
useSaveToast(actionData);
|
||||
const navigation = useNavigation();
|
||||
|
||||
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>
|
||||
<KontaktNewPage
|
||||
moduleActive={moduleActive}
|
||||
ownerOptions={ownerOptions}
|
||||
defaultOwnerId={defaultOwnerId}
|
||||
backHref={backHref}
|
||||
listLabelKey="crm.contacts.title"
|
||||
duplicates={dupFetcher.data ?? null}
|
||||
submitting={navigation.state !== "idle"}
|
||||
errorKey={actionData?.error ?? null}
|
||||
actions={{
|
||||
onCheckDuplicates: (fields) => dupFetcher.submit(fieldsToFormData(fields, "checkDuplicates"), { method: "post" }),
|
||||
onCreate: (fields) => submit(fieldsToFormData(fields, "create"), { method: "post" }),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
requireContext: vi.fn(),
|
||||
loadSnapshot: vi.fn(),
|
||||
updateInbox: vi.fn(),
|
||||
validateCsrf: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/screens/customer-portal/CustomerPortalInterimPages", () => ({ PortalAdminInboxPage: () => null }));
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/services/customer-portal/portal-admin-context.server", () => ({
|
||||
requirePortalAdminWorkspaceContext: (...args: unknown[]) => mocks.requireContext(...args),
|
||||
}));
|
||||
vi.mock("~/services/customer-portal/portal-admin.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/services/customer-portal/portal-admin.server")>();
|
||||
return {
|
||||
...actual,
|
||||
loadPortalAdminSnapshot: (...args: unknown[]) => mocks.loadSnapshot(...args),
|
||||
updatePortalInbox: (...args: unknown[]) => mocks.updateInbox(...args),
|
||||
};
|
||||
});
|
||||
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: (...args: unknown[]) => mocks.validateCsrf(...args) }));
|
||||
|
||||
import { action, loader } from "./inbox";
|
||||
|
||||
const configuration = {
|
||||
published: true,
|
||||
lifecycleMode: "customer" as const,
|
||||
projectAutoCloseMonths: 12,
|
||||
inactivityDisableMonths: 24,
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 50 * 1024 * 1024,
|
||||
enabledProjectTypes: ["shk"],
|
||||
statusEmailsEnabled: true,
|
||||
imprintUrl: "https://example.test/imprint",
|
||||
privacyUrl: "https://example.test/privacy",
|
||||
termsUrl: null,
|
||||
legalLinksComplete: true,
|
||||
visibleStageCount: 2,
|
||||
autoReleaseRuleCount: 0,
|
||||
emailTemplateHref: "/acme/settings/customer-portal/email-templates",
|
||||
};
|
||||
|
||||
describe("customer portal service inbox route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.requireContext.mockResolvedValue({
|
||||
tenantId: "tenant_1",
|
||||
tenantSlug: "acme",
|
||||
userId: "user_1",
|
||||
permissions: ["portal.activity.read", "portal.activity.manage"],
|
||||
});
|
||||
mocks.loadSnapshot.mockResolvedValue({
|
||||
frozen: false,
|
||||
portalId: "portal_1",
|
||||
published: true,
|
||||
configuration,
|
||||
users: [],
|
||||
accessRows: [],
|
||||
inbox: [],
|
||||
stages: [],
|
||||
autoReleaseRules: [],
|
||||
projectOptions: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("loads for an activity-only reader and asks for the narrow read permission", async () => {
|
||||
const response = await loader({
|
||||
request: new Request("https://app.example.test/acme/customer-portal/inbox"),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
} as never);
|
||||
const payload = await response.json();
|
||||
|
||||
expect(payload.vm).toMatchObject({ status: "ready", data: { permissions: { canReadActivity: true, canManageActivity: true } } });
|
||||
expect(mocks.requireContext).toHaveBeenCalledWith(expect.any(Request), { tenant: "acme" }, "portal.activity.read");
|
||||
});
|
||||
|
||||
it("validates CSRF and the manage permission before updating one scoped item", async () => {
|
||||
const request = new Request("https://app.example.test/acme/customer-portal/inbox", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ itemId: "inbox_1", status: "resolved", csrf: "token" }),
|
||||
});
|
||||
const response = await action({ request, params: { tenant: "acme" }, context: {} } as never);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledOnce();
|
||||
expect(mocks.requireContext).toHaveBeenCalledWith(request, { tenant: "acme" }, "portal.activity.manage");
|
||||
expect(mocks.updateInbox).toHaveBeenCalledWith({ tenantId: "tenant_1", actorUserId: "user_1", itemId: "inbox_1", status: "resolved" });
|
||||
});
|
||||
|
||||
it("rejects an unknown status before calling the mutation", async () => {
|
||||
const response = await action({
|
||||
request: new Request("https://app.example.test/acme/customer-portal/inbox", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ itemId: "inbox_1", status: "other", csrf: "token" }),
|
||||
}),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(mocks.updateInbox).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns manage-permission failures before CSRF and payload validation", async () => {
|
||||
const notFound = new Response(null, { status: 404 });
|
||||
mocks.requireContext.mockRejectedValueOnce(notFound);
|
||||
const request = new Request("https://app.example.test/acme/customer-portal/inbox", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ status: "other" }),
|
||||
});
|
||||
|
||||
await expect(action({ request, params: { tenant: "acme" }, context: {} } as never)).rejects.toBe(notFound);
|
||||
|
||||
expect(mocks.requireContext).toHaveBeenCalledWith(request, { tenant: "acme" }, "portal.activity.manage");
|
||||
expect(mocks.validateCsrf).not.toHaveBeenCalled();
|
||||
expect(mocks.updateInbox).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { buildPortalAdminVM, type PortalAdminVM } from "@hivegrid/view-models";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate, useParams } from "react-router";
|
||||
|
||||
import { PortalAdminInboxPage } from "~/components/screens/customer-portal/CustomerPortalInterimPages";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requirePortalAdminWorkspaceContext } from "~/services/customer-portal/portal-admin-context.server";
|
||||
import { loadPortalAdminSnapshot, PortalAdminError, updatePortalInbox } from "~/services/customer-portal/portal-admin.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = { readonly title: string; readonly vm: PortalAdminVM };
|
||||
type ActionData = { readonly ok?: true; readonly messageKey?: string; readonly errorKey?: string };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const [{ t }, ctx] = await Promise.all([
|
||||
getTranslations(request),
|
||||
requirePortalAdminWorkspaceContext(request, params, "portal.activity.read"),
|
||||
]);
|
||||
const snapshot = await loadPortalAdminSnapshot({ tenantId: ctx.tenantId, tenantSlug: ctx.tenantSlug });
|
||||
const vm = buildPortalAdminVM({
|
||||
frozen: snapshot.frozen,
|
||||
permissions: {
|
||||
canRead: ctx.permissions.includes("portal.read"),
|
||||
canManageUsers: false,
|
||||
canManageAccess: false,
|
||||
canDeleteUsers: false,
|
||||
canReadActivity: true,
|
||||
canManageActivity: ctx.permissions.includes("portal.activity.manage"),
|
||||
canAdminister: ctx.permissions.includes("portal.admin"),
|
||||
},
|
||||
configuration: snapshot.configuration,
|
||||
stages: [],
|
||||
autoReleaseRules: [],
|
||||
projectOptions: [],
|
||||
users: [],
|
||||
accessRows: [],
|
||||
inbox: snapshot.inbox,
|
||||
});
|
||||
return Response.json({ title: `${t("customerPortal.admin.inbox.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
||||
const ctx = await requirePortalAdminWorkspaceContext(request, params, "portal.activity.manage");
|
||||
const form = await request.formData();
|
||||
await validateCSRFToken(request, { formData: form });
|
||||
const itemId = required(form, "itemId");
|
||||
const status = required(form, "status");
|
||||
if (status !== "open" && status !== "in_progress" && status !== "resolved" && status !== "dismissed") {
|
||||
return Response.json({ errorKey: "customerPortal.admin.errors.invalidInput" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await updatePortalInbox({ tenantId: ctx.tenantId, actorUserId: ctx.userId, itemId, status });
|
||||
return Response.json({ ok: true, messageKey: "customerPortal.admin.messages.saved" } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof PortalAdminError) return Response.json({ errorKey: error.messageKey } satisfies ActionData, { status: error.status });
|
||||
if (error instanceof Response) throw error;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export default function CustomerPortalServiceInboxRoute(): React.JSX.Element {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const params = useParams();
|
||||
return (
|
||||
<PortalAdminInboxPage
|
||||
vm={vm}
|
||||
busy={fetcher.state !== "idle"}
|
||||
messageKey={fetcher.data?.ok ? fetcher.data.messageKey : null}
|
||||
errorKey={fetcher.data?.errorKey ?? null}
|
||||
actions={{
|
||||
onUpdate: ({ itemId, status }) => {
|
||||
const form = new FormData();
|
||||
form.set("itemId", itemId);
|
||||
form.set("status", status);
|
||||
fetcher.submit(appendCSRFToken(form), { method: "post" });
|
||||
},
|
||||
onBackToSettings: () => navigate(`/${encodeURIComponent(params.tenant ?? "")}/settings/customer-portal`),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function required(form: FormData, key: string): string {
|
||||
const value = form.get(key);
|
||||
if (typeof value !== "string" || !value.trim()) throw new PortalAdminError("customerPortal.admin.errors.invalidInput", 400);
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
export function ErrorBoundary(): React.JSX.Element {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { breadcrumbKey: "customerPortal.admin.inbox.title" };
|
||||
+52
-4
@@ -1,19 +1,67 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import { loadDashboardStreamSnapshot } from "~/services/dashboard/dashboard.server";
|
||||
import { openDashboardStreamSession } from "~/services/dashboard/dashboard.server";
|
||||
import { subscribeToDashboardChanges } from "~/services/dashboard/dashboardEvents.server";
|
||||
import { eventStream } from "~/utils/stream/event-stream";
|
||||
|
||||
// Debounce window for change-triggered snapshot refreshes: a mutation burst
|
||||
// (e.g. a bulk stage move) collapses into one recomputed snapshot.
|
||||
const DASHBOARD_STREAM_REFRESH_DEBOUNCE_MS = 2_000;
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
// Authorize before the stream opens so auth failures surface as a proper
|
||||
// error response instead of an empty event stream.
|
||||
const session = await openDashboardStreamSession({ request, params });
|
||||
|
||||
return eventStream(request.signal, (send) => {
|
||||
let closed = false;
|
||||
void loadDashboardStreamSnapshot({ request, params }).then((snapshot) => {
|
||||
if (!closed) send({ event: "dashboard.snapshot", data: JSON.stringify(snapshot) });
|
||||
});
|
||||
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let refreshing = false;
|
||||
let refreshQueued = false;
|
||||
|
||||
function pushSnapshot() {
|
||||
if (closed) return;
|
||||
if (refreshing) {
|
||||
refreshQueued = true;
|
||||
return;
|
||||
}
|
||||
refreshing = true;
|
||||
void session
|
||||
.loadSnapshot()
|
||||
.then((snapshot) => {
|
||||
if (!closed) send({ event: "dashboard.snapshot", data: JSON.stringify(snapshot) });
|
||||
})
|
||||
.catch(() => {
|
||||
// A failed refresh keeps the last delivered snapshot visible; the
|
||||
// next change event or a reconnect retries.
|
||||
})
|
||||
.finally(() => {
|
||||
refreshing = false;
|
||||
if (refreshQueued && !closed) {
|
||||
refreshQueued = false;
|
||||
scheduleRefresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleRefresh() {
|
||||
if (closed || refreshTimer) return;
|
||||
refreshTimer = setTimeout(() => {
|
||||
refreshTimer = null;
|
||||
pushSnapshot();
|
||||
}, DASHBOARD_STREAM_REFRESH_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
pushSnapshot();
|
||||
const unsubscribe = subscribeToDashboardChanges(session.tenantId, scheduleRefresh);
|
||||
const heartbeat = setInterval(() => {
|
||||
send({ event: "dashboard.heartbeat", data: JSON.stringify({ at: new Date().toISOString() }) });
|
||||
}, 30_000);
|
||||
|
||||
return () => {
|
||||
closed = true;
|
||||
unsubscribe();
|
||||
clearInterval(heartbeat);
|
||||
if (refreshTimer) clearTimeout(refreshTimer);
|
||||
};
|
||||
});
|
||||
}
|
||||
+81
-44
@@ -1,6 +1,6 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import React from "react";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import DashboardRoute, { loader } from "./dashboard";
|
||||
@@ -17,53 +17,60 @@ import { evaluateDashboardModuleGates, type DashboardModuleGateDecision } from "
|
||||
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";
|
||||
import { toFirstStepsChecklistVM } from "@hivegrid/view-models";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
|
||||
const translatedT = vi.fn((key: string) => `translated:${key}`);
|
||||
const computedGte = new Date("2026-02-03T04:05:06.000Z");
|
||||
const tenant = { id: "tenant_1", slug: "acme" };
|
||||
const appData = { mySubscription: { products: [], trial: { active: false, period: "trial-ended" } } };
|
||||
const appData = { mySubscription: { status: "past_due", trialStartsAt: null, trialEndsAt: null, products: [] } };
|
||||
const stats = [{ name: "Contacts", stat: "7", previousStat: "3" }];
|
||||
const dashboardData = { users: 4 };
|
||||
const firstStepsChecklist = {
|
||||
const firstStepsChecklistSource = {
|
||||
id: "checklist_1",
|
||||
status: "active",
|
||||
dismissed: false,
|
||||
completedCount: 2,
|
||||
totalCount: 4,
|
||||
completedCount: 1,
|
||||
totalCount: 2,
|
||||
percentComplete: 50,
|
||||
items: [],
|
||||
items: [
|
||||
{ id: "step_1", block: "profile", titleKey: "onboarding.firstSteps.profile", href: "settings/profile", completed: true, hidden: false },
|
||||
{ id: "step_2", block: "contacts", titleKey: "onboarding.firstSteps.contacts", href: "contacts", completed: false, hidden: false },
|
||||
],
|
||||
};
|
||||
const firstStepsChecklist = toFirstStepsChecklistVM({
|
||||
...firstStepsChecklistSource,
|
||||
items: firstStepsChecklistSource.items.map((item) => ({ ...item, href: `/acme/${item.href}` })),
|
||||
});
|
||||
const dashboardVm = {
|
||||
activeRole: "office",
|
||||
generatedAt: "2026-07-01T00:00:00.000Z",
|
||||
streamUrl: "/acme/dashboard.stream?role=office",
|
||||
liveUpdatesEnabled: true,
|
||||
streamUrl: "/acme/dashboard.stream",
|
||||
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 },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
layout: {
|
||||
role: "office",
|
||||
nameKey: "app.dashboard.roles.office.name",
|
||||
descriptionKey: "app.dashboard.roles.office.description",
|
||||
mobileFirst: false,
|
||||
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: [],
|
||||
chart: null,
|
||||
series: null,
|
||||
position: { x: 0, y: 1 },
|
||||
size: { w: 4, h: 2 },
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const registryModules = getDashboardModuleDefinitions();
|
||||
const getRegistryModule = (moduleId: DashboardModuleId): DashboardModuleDefinition => {
|
||||
@@ -77,6 +84,7 @@ const summaryModule = getRegistryModule("summary-stats");
|
||||
const featureGatedModule = getRegistryModule("subscription-health");
|
||||
const planGatedModule = getRegistryModule("priority-insights");
|
||||
let routeLoaderData: unknown;
|
||||
const navigateMock = vi.hoisted(() => vi.fn());
|
||||
let moduleDecisions: DashboardModuleGateDecision[] = [
|
||||
{ module: summaryModule, allowed: true },
|
||||
{
|
||||
@@ -134,6 +142,7 @@ vi.mock("react-router", async () => {
|
||||
return {
|
||||
...actual,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
useNavigate: () => navigateMock,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -158,7 +167,7 @@ vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("~/components/app/ProfileBanner", () => ({
|
||||
default: () => null,
|
||||
default: () => <div data-testid="profile-banner" />,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/stats/DashboardStats", () => ({
|
||||
@@ -195,11 +204,12 @@ vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
|
||||
useTranslation: vi.fn(() => ({ t: (key: string) => key, i18n: { language: "de" } })),
|
||||
}));
|
||||
|
||||
describe("app tenant dashboard route contract", () => {
|
||||
beforeEach(() => {
|
||||
navigateMock.mockReset();
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "HiveGrid";
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: translatedT } as never);
|
||||
@@ -225,7 +235,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(getFirstStepsChecklist).mockResolvedValue(firstStepsChecklistSource as never);
|
||||
vi.mocked(getUserHasPermission).mockReturnValue(true);
|
||||
vi.mocked(getAppDashboardStats).mockResolvedValue(stats as never);
|
||||
vi.mocked(loadDashboardData).mockResolvedValue(dashboardData as never);
|
||||
vi.mocked(PeriodHelper.getGreaterThanOrEqualsFromRequest).mockReturnValue(computedGte);
|
||||
@@ -291,6 +302,27 @@ describe("app tenant dashboard route contract", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("does not load or render the checklist without checklist permission", async () => {
|
||||
vi.mocked(getUserHasPermission).mockImplementation((_data, permission) => permission !== "app.onboarding.checklist.update");
|
||||
const request = new Request("https://example.com/acme/dashboard");
|
||||
const params = { tenant: "acme" };
|
||||
|
||||
const response = (await loader({ request, params, context: {}, unstable_pattern: "app.$tenant/dashboard" })) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(getFirstStepsChecklist).not.toHaveBeenCalled();
|
||||
expect(body.firstStepsChecklist).toEqual({ status: "empty" });
|
||||
|
||||
routeLoaderData = body;
|
||||
vi.mocked(getUserHasPermission).mockReturnValue(true);
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<DashboardRoute />
|
||||
</MemoryRouter>
|
||||
);
|
||||
expect(screen.queryByText("onboarding.firstSteps.dashboardTitle")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the allowed summary registry module with the existing dashboard stats", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
@@ -301,9 +333,17 @@ 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.queryByTestId("profile-banner")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("onboarding.firstSteps.dashboardTitle")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "onboarding.firstSteps.open" })).toHaveAttribute("href", "/onboarding/checklist");
|
||||
expect(screen.getByRole("button", { name: "onboarding.firstSteps.open" })).toBeEnabled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "onboarding.firstSteps.open" }));
|
||||
expect(navigateMock).toHaveBeenCalledWith("../onboarding/checklist");
|
||||
expect(screen.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
||||
// R-P11b interim screen (AD-28): the widget grid renders the single layout the
|
||||
// loader derived; there is no role switcher to pick another one.
|
||||
expect(document.querySelector("[data-ui-id^='ui.dashboard.roleSwitcher']")).not.toBeInTheDocument();
|
||||
expect(document.querySelector('[data-ui-id="ui.dashboard.widget.projects.kpis"]')).toBeInTheDocument();
|
||||
expect(document.querySelector('[data-ui-id="ui.dashboard.live.toggle"]')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("omits gated summary content when the summary module is feature-disabled", () => {
|
||||
@@ -324,9 +364,7 @@ describe("app tenant dashboard route contract", () => {
|
||||
|
||||
expect(screen.queryByRole("heading", { name: "app.dashboard.summary" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("Contacts")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("app.dashboard.moduleDiagnostics.unavailableTitle")).toBeInTheDocument();
|
||||
expect(screen.getByText("app.dashboard.moduleDiagnostics.unavailableDescription")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "app.dashboard.moduleDiagnostics.learnMore" })).toHaveAttribute("href", "/feature-disabled?tenant=acme");
|
||||
expect(screen.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders plan-required diagnostics with the safe tenant-aware plan link and no gated module content", () => {
|
||||
@@ -351,7 +389,7 @@ describe("app tenant dashboard route contract", () => {
|
||||
expect(screen.queryByText(planGatedModule.titleKey)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders feature-disabled diagnostics with only the safe fallback link and no gated module content", () => {
|
||||
it("suppresses feature-disabled diagnostics entirely while still hiding the gated module content", () => {
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
dashboard: dashboardVm,
|
||||
@@ -369,9 +407,8 @@ describe("app tenant dashboard route contract", () => {
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByText("app.dashboard.moduleDiagnostics.unavailableTitle")).toBeInTheDocument();
|
||||
expect(screen.getByText("app.dashboard.moduleDiagnostics.unavailableDescription")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "app.dashboard.moduleDiagnostics.learnMore" })).toHaveAttribute("href", "/feature-disabled");
|
||||
expect(screen.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "app.dashboard.moduleDiagnostics.learnMore" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(featureGatedModule.titleKey)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
+40
-134
@@ -1,10 +1,10 @@
|
||||
import { Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link, LoaderFunctionArgs, useLoaderData, useNavigate } from "react-router";
|
||||
import { useSearchParams } from "react-router";
|
||||
import { ready, toFirstStepsChecklistVM, type FirstStepsChecklistVM } from "@hivegrid/view-models";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { DashboardLoaderData, loadDashboardData } from "~/utils/data/useDashboardData";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAppDashboardStats } from "~/utils/services/appDashboardService";
|
||||
import ProfileBanner from "~/components/app/ProfileBanner";
|
||||
import { DashboardStats } from "~/components/ui/stats/DashboardStats";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { Stat } from "~/application/dtos/stats/Stat";
|
||||
@@ -29,12 +29,17 @@ 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 { loadDashboardVM, type DashboardVM } from "~/services/dashboard/dashboard.server";
|
||||
import { getFirstStepsChecklist } from "~/utils/services/.server/akP20OnboardingService";
|
||||
import { DashboardPage } from "~/components/screens/dashboard/DashboardPage";
|
||||
import { useDashboardStream } from "~/components/screens/dashboard/useDashboardStream";
|
||||
import { FirstStepsChecklistWidget } from "~/components/screens/onboarding/FirstStepsChecklistWidget";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
const DASHBOARD_READ_PERMISSION = "dashboard.read";
|
||||
const LEGACY_DASHBOARD_PERMISSION = "app.dashboard.view";
|
||||
const FIRST_STEPS_CHECKLIST_PERMISSION = "app.onboarding.checklist.update";
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
@@ -44,7 +49,7 @@ type LoaderData = DashboardLoaderData & {
|
||||
modules: DashboardModuleDefinition[];
|
||||
moduleDiagnostics: DashboardModuleGateDiagnostic[];
|
||||
dashboard: DashboardVM;
|
||||
firstStepsChecklist: Awaited<ReturnType<typeof getFirstStepsChecklist>>;
|
||||
firstStepsChecklist: FirstStepsChecklistVM;
|
||||
};
|
||||
|
||||
function isDashboardModuleVisible(modules: readonly DashboardModuleDefinition[], moduleId: DashboardModuleId) {
|
||||
@@ -75,12 +80,21 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
if (!tenant) {
|
||||
throw Response.json({ error: t("app.dashboard.errors.tenantNotFound") }, { status: 404 });
|
||||
}
|
||||
const canViewFirstStepsChecklist = getUserHasPermission(appData, FIRST_STEPS_CHECKLIST_PERMISSION);
|
||||
const firstStepsChecklistRequest = canViewFirstStepsChecklist
|
||||
? getFirstStepsChecklist({ tenantId, userId: userInfo.userId }).then((checklist) =>
|
||||
toFirstStepsChecklistVM({
|
||||
...checklist,
|
||||
items: checklist.items.map((item) => ({ ...item, href: UrlUtils.currentTenantUrl(params, item.href) })),
|
||||
})
|
||||
)
|
||||
: Promise.resolve<FirstStepsChecklistVM>({ status: "empty" });
|
||||
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 }),
|
||||
firstStepsChecklist: firstStepsChecklistRequest,
|
||||
moduleDecisions: evaluateDashboardModuleGates({
|
||||
request,
|
||||
params,
|
||||
@@ -110,60 +124,28 @@ export default function DashboardRoute() {
|
||||
const { t } = useTranslation();
|
||||
const appData = useAppData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { snapshot } = useDashboardStream({
|
||||
streamUrl: data.dashboard.streamUrl,
|
||||
initialGeneratedAt: data.dashboard.generatedAt,
|
||||
});
|
||||
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];
|
||||
const dashboard = snapshot ?? data.dashboard;
|
||||
|
||||
const planRequiredDiagnostics = data.moduleDiagnostics.filter((diagnostic) => diagnostic.reason === "plan-required");
|
||||
|
||||
return (
|
||||
<main className="relative z-0 flex-1 pb-8" data-ui-id="ui.dashboard.page">
|
||||
{/*Page header */}
|
||||
<div className="bg-background border-border hidden border-b md:block">
|
||||
<ProfileBanner user={appData.user} />
|
||||
</div>
|
||||
|
||||
<div className="mx-auto grid max-w-5xl gap-5 px-4 py-5 sm:px-8">
|
||||
{/* The screen renders its own full-bleed page header; only the sibling blocks stay in the centered column. */}
|
||||
{canViewDashboard ? (
|
||||
<DashboardPage vm={ready(dashboard)} />
|
||||
) : null}
|
||||
<div className="grid w-full gap-5 px-4 py-5 sm:px-6">
|
||||
{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 p-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
@@ -193,52 +175,22 @@ export default function DashboardRoute() {
|
||||
<DashboardStats items={data.stats} />
|
||||
</div>
|
||||
)}
|
||||
{data.moduleDiagnostics.length > 0 && (
|
||||
{/* Feature-disabled diagnostics still gate the module content but render no notice —
|
||||
only actionable plan-required diagnostics surface to the user. */}
|
||||
{planRequiredDiagnostics.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{data.moduleDiagnostics.map((diagnostic) => (
|
||||
{planRequiredDiagnostics.map((diagnostic) => (
|
||||
<div key={diagnostic.moduleId} className="border-border bg-secondary rounded-md border border-dashed px-4 py-3 text-sm">
|
||||
<div className="text-foreground font-medium">
|
||||
{diagnostic.reason === "plan-required"
|
||||
? t("app.dashboard.moduleDiagnostics.planRequiredTitle")
|
||||
: t("app.dashboard.moduleDiagnostics.unavailableTitle")}
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-1">
|
||||
{diagnostic.reason === "plan-required"
|
||||
? t("app.dashboard.moduleDiagnostics.planRequiredDescription")
|
||||
: t("app.dashboard.moduleDiagnostics.unavailableDescription")}
|
||||
</div>
|
||||
<div className="text-foreground font-medium">{t("app.dashboard.moduleDiagnostics.planRequiredTitle")}</div>
|
||||
<div className="text-muted-foreground mt-1">{t("app.dashboard.moduleDiagnostics.planRequiredDescription")}</div>
|
||||
<Link className="text-theme-600 mt-2 inline-flex underline" to={getSafeModuleNoticePath(diagnostic)}>
|
||||
{diagnostic.reason === "plan-required"
|
||||
? t("app.dashboard.moduleDiagnostics.viewPlanOptions")
|
||||
: t("app.dashboard.moduleDiagnostics.learnMore")}
|
||||
{t("app.dashboard.moduleDiagnostics.viewPlanOptions")}
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</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>
|
||||
)}
|
||||
<FirstStepsChecklistWidget vm={data.firstStepsChecklist} href="../onboarding/checklist" onOpen={(href) => navigate(href)} />
|
||||
</Fragment>
|
||||
) : (
|
||||
<div className="font-medium">{t("app.dashboard.noPermission")}</div>
|
||||
@@ -248,52 +200,6 @@ 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 />;
|
||||
}
|
||||
+42
-22
@@ -1,32 +1,36 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { Outlet, useLoaderData, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import IncreaseIcon from "~/components/ui/icons/crm/IncreaseIcon";
|
||||
import IncreaseIconFilled from "~/components/ui/icons/crm/IncreaseIconFilled";
|
||||
import MegaphoneIcon from "~/components/ui/icons/emails/MegaphoneIcon";
|
||||
import MegaphoneIconFilled from "~/components/ui/icons/emails/MegaphoneIconFilled";
|
||||
import SentIcon from "~/components/ui/icons/emails/SentIcon";
|
||||
import SentIconFilled from "~/components/ui/icons/emails/SentIconFilled";
|
||||
import ActivityHistoryIcon from "~/components/ui/icons/entities/ActivityHistoryIcon";
|
||||
import ActivityHistoryIconFilled from "~/components/ui/icons/entities/ActivityHistoryIconFilled";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { featureKeys } from "@hivegrid/entitlements";
|
||||
import { requireTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
|
||||
import { GlobeIcon, UserIcon } from "~/components/ui/icons/vendor";
|
||||
import { loadEmailDomainContext, notFoundResponse } from "~/utils/integrations/emailDomainService.server";
|
||||
import { emailMarketingCanManage, emailMarketingCanView } from "~/modules/emailMarketing/routes/emailMarketingAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
canManage: boolean;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await requireTenantProductAccess({ request, params, featureKey: featureKeys.emailMarketing });
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!emailMarketingCanView(ctx.permissions)) {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
// 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}`,
|
||||
canManage: emailMarketingCanManage(ctx.permissions),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
@@ -36,6 +40,21 @@ export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.t
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const params = useParams();
|
||||
const { canManage } = useLoaderData<LoaderData>();
|
||||
const manageItems = canManage
|
||||
? [
|
||||
{
|
||||
name: t("emailMarketing:senders.plural"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/senders"),
|
||||
icon: <UserIcon className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("email.domain.title"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/sending-domain"),
|
||||
icon: <GlobeIcon className="h-5 w-5" />,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
@@ -45,33 +64,34 @@ export default () => {
|
||||
href: UrlUtils.getModulePath(params, "email-marketing"),
|
||||
exact: true,
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing.setup.title"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/setup"),
|
||||
icon: <GlobeIcon className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
// AK-P14b — campaign drafting + reporting + guarded send flow.
|
||||
name: t("emailMarketing.campaign.tab"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/campaigns"),
|
||||
icon: <MegaphoneIcon className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing:activity"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/activity"),
|
||||
icon: <ActivityHistoryIcon className="h-5 w-5" />,
|
||||
iconSelected: <ActivityHistoryIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing:senders.plural"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/senders"),
|
||||
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" />,
|
||||
},
|
||||
...manageItems,
|
||||
{
|
||||
// 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" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing.templates.tab"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/templates"),
|
||||
icon: <ActivityHistoryIcon className="h-5 w-5" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { Outlet } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
export default function CampaignsRoute() {
|
||||
return <Outlet />;
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData, useSubmit } from "react-router";
|
||||
import { buildCampaignDetailVM } from "@hivegrid/view-models";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { notify } from "@hivegrid/foundation";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { CampaignDetailPage } from "~/components/screens/email-marketing/EmailMarketingInterimScreens";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getCampaign } from "~/modules/emailMarketing/db/campaigns.db.server";
|
||||
import {
|
||||
CampaignSendError,
|
||||
cancelCampaignSchedule,
|
||||
dispatchCampaign,
|
||||
} from "~/modules/emailMarketing/services/CampaignSendService.server";
|
||||
import { loadCampaignPreflight } from "~/modules/emailMarketing/services/CampaignPreflightService.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { loadEmailDomainContext, notFoundResponse } from "~/utils/integrations/emailDomainService.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { z } from "zod";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type ActionData = { errorKey?: string; successKey?: string };
|
||||
type LoaderData = {
|
||||
vm: ReturnType<typeof buildCampaignDetailVM>;
|
||||
checklist: NonNullable<Awaited<ReturnType<typeof loadCampaignPreflight>>>["checklistVM"];
|
||||
confirmation: {
|
||||
recipientCount: number;
|
||||
scheduledAtIso: string | null;
|
||||
timezone: string;
|
||||
deliveryLabel: string;
|
||||
senderLabel: string;
|
||||
mode: "send" | "schedule";
|
||||
};
|
||||
};
|
||||
|
||||
const CampaignCommandSchema = z.discriminatedUnion("intent", [
|
||||
z.object({ intent: z.literal("cancel-schedule") }),
|
||||
z.object({
|
||||
intent: z.literal("send"),
|
||||
confirmation: z.literal("confirmed"),
|
||||
recipientCount: z.coerce.number().int().nonnegative(),
|
||||
scheduledAt: z.string().max(64).optional().default(""),
|
||||
}),
|
||||
]);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
function buildClickMap(campaign: NonNullable<Awaited<ReturnType<typeof getCampaign>>>) {
|
||||
const counts = new Map<string, number>();
|
||||
for (const recipient of campaign.recipients) {
|
||||
for (const click of recipient.clicks) {
|
||||
counts.set(click.link, (counts.get(click.link) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
return Array.from(counts.entries()).map(([link, count]) => ({ link, count }));
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!canView(ctx.permissions)) throw notFoundResponse();
|
||||
const campaign = await getCampaign(params.id ?? "", ctx.tenantId);
|
||||
if (!campaign) throw notFoundResponse();
|
||||
const preflight = await loadCampaignPreflight({
|
||||
tenantId: ctx.tenantId,
|
||||
ctx: { userId: ctx.userId, permissions: ctx.permissions },
|
||||
campaignId: campaign.id,
|
||||
});
|
||||
if (!preflight) throw notFoundResponse();
|
||||
const stats = {
|
||||
total: campaign.recipients.length,
|
||||
delivered: campaign.recipients.filter((recipient) => recipient.deliveredAt).length,
|
||||
opened: campaign.recipients.filter((recipient) => recipient.opens.length > 0).length,
|
||||
clicked: campaign.recipients.filter((recipient) => recipient.clicks.length > 0).length,
|
||||
bounced: campaign.recipients.filter((recipient) => recipient.bouncedAt).length,
|
||||
unsubscribed: campaign.recipients.filter((recipient) => recipient.unsubscribedAt).length,
|
||||
};
|
||||
const vm = buildCampaignDetailVM({
|
||||
campaign: {
|
||||
id: campaign.id,
|
||||
name: campaign.name,
|
||||
subject: campaign.subject,
|
||||
status: campaign.status,
|
||||
createdAt:
|
||||
campaign.recipients.length > 0 ? new Date(Math.min(...campaign.recipients.map((recipient) => recipient.createdAt.getTime()))) : campaign.sentAt,
|
||||
scheduledAt: campaign.scheduledAt,
|
||||
sentAt: campaign.sentAt,
|
||||
},
|
||||
stats,
|
||||
clickMap: buildClickMap(campaign),
|
||||
recipients: campaign.recipients.map((recipient) => ({
|
||||
email: recipient.email,
|
||||
name: recipient.email,
|
||||
variantLabel: null,
|
||||
deliveredAt: recipient.deliveredAt,
|
||||
openedAt: recipient.opens[0]?.createdAt ?? null,
|
||||
clickedAt: recipient.clicks[0]?.createdAt ?? null,
|
||||
bouncedAt: recipient.bouncedAt,
|
||||
error: recipient.error,
|
||||
})),
|
||||
variants: campaign.variants.map((variant) => ({
|
||||
label: variant.label,
|
||||
subject: variant.subject,
|
||||
delivered: variant.deliveredCount,
|
||||
opened: variant.openedCount,
|
||||
clicked: variant.clickedCount,
|
||||
})),
|
||||
});
|
||||
return Response.json({
|
||||
vm,
|
||||
checklist: preflight.checklistVM,
|
||||
confirmation: {
|
||||
recipientCount: preflight.recipientIds.length,
|
||||
scheduledAtIso: campaign.scheduledAt?.toISOString() ?? null,
|
||||
timezone: campaign.timezone ?? "Europe/Berlin",
|
||||
deliveryLabel: campaign.scheduledAt
|
||||
? new Intl.DateTimeFormat(locale, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
timeZone: campaign.timezone ?? "Europe/Berlin",
|
||||
}).format(campaign.scheduledAt)
|
||||
: t("emailMarketing.presend.immediately"),
|
||||
senderLabel: campaign.emailSender.fromName ?? campaign.emailSender.fromEmail,
|
||||
mode: campaign.scheduledAt && campaign.scheduledAt.getTime() > Date.now() ? "schedule" : "send",
|
||||
},
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!canManage(ctx.permissions)) throw notFoundResponse();
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const rawCommand = Object.fromEntries(form);
|
||||
if (rawCommand.intent === "send" && rawCommand.confirmation !== "confirmed") {
|
||||
return Response.json({ errorKey: "emailMarketing.send.error.confirmationRequired" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const command = CampaignCommandSchema.safeParse(rawCommand);
|
||||
if (!command.success) {
|
||||
return Response.json({ errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const { intent } = command.data;
|
||||
if (intent === "cancel-schedule") {
|
||||
try {
|
||||
const campaignId = params.id ?? "";
|
||||
await cancelCampaignSchedule({ tenantId: ctx.tenantId, campaignId });
|
||||
await Promise.all([
|
||||
createAuditEvent({
|
||||
tenantId: ctx.tenantId,
|
||||
actorId: ctx.userId,
|
||||
actorType: "user",
|
||||
action: "EMAIL_CAMPAIGN_SCHEDULE_CANCELLED",
|
||||
targetType: "Campaign",
|
||||
targetId: campaignId,
|
||||
sourceModule: "email-marketing",
|
||||
}).catch(() => undefined),
|
||||
logActivity({
|
||||
tenantId: ctx.tenantId,
|
||||
actorUserId: ctx.userId,
|
||||
actorKind: "user",
|
||||
activityType: "email_sent",
|
||||
subjectType: "tenant",
|
||||
subjectId: ctx.tenantId,
|
||||
summaryText: "activity.runtime.emailMarketing.scheduleCancelled",
|
||||
metadata: { campaignId },
|
||||
}).catch(() => undefined),
|
||||
withTenantRLS(ctx.tenantId, (tx) =>
|
||||
notify(
|
||||
{
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
channel: "IN_APP",
|
||||
category: "email-marketing",
|
||||
messageKey: "emailMarketing.notification.scheduleCancelled",
|
||||
sourceKey: `email-campaign:${campaignId}:schedule-cancelled`,
|
||||
payloadMetadata: { campaignId },
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1],
|
||||
),
|
||||
).catch(() => undefined),
|
||||
]);
|
||||
return Response.json({ successKey: "emailMarketing.send.cancellationAccepted" } satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof CampaignSendError) {
|
||||
return Response.json({ errorKey: error.messageKey } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const campaignId = params.id ?? "";
|
||||
const expectedRecipientCount = command.data.recipientCount;
|
||||
const expectedScheduledAt = command.data.scheduledAt || null;
|
||||
const preflight = await loadCampaignPreflight({
|
||||
tenantId: ctx.tenantId,
|
||||
ctx: { userId: ctx.userId, permissions: ctx.permissions },
|
||||
campaignId,
|
||||
});
|
||||
if (
|
||||
!preflight ||
|
||||
preflight.recipientIds.length !== expectedRecipientCount ||
|
||||
(preflight.campaign.scheduledAt?.toISOString() ?? null) !== expectedScheduledAt
|
||||
) {
|
||||
return Response.json({ errorKey: "emailMarketing.send.error.confirmationStale" } satisfies ActionData, { status: 409 });
|
||||
}
|
||||
const result = await dispatchCampaign({
|
||||
tenantId: ctx.tenantId,
|
||||
ctx: { userId: ctx.userId, permissions: ctx.permissions },
|
||||
campaignId,
|
||||
baseUrl: new URL(request.url).origin,
|
||||
});
|
||||
const scheduled = Boolean(preflight.campaign.scheduledAt && preflight.campaign.scheduledAt.getTime() > Date.now());
|
||||
await Promise.all([
|
||||
createAuditEvent({
|
||||
tenantId: ctx.tenantId,
|
||||
actorId: ctx.userId,
|
||||
actorType: "user",
|
||||
action: scheduled ? "EMAIL_CAMPAIGN_SCHEDULED" : "EMAIL_CAMPAIGN_SEND_ACCEPTED",
|
||||
targetType: "Campaign",
|
||||
targetId: campaignId,
|
||||
sourceModule: "email-marketing",
|
||||
metadata: { recipientCount: result.recipientCount, enqueued: result.enqueued },
|
||||
}).catch(() => undefined),
|
||||
logActivity({
|
||||
tenantId: ctx.tenantId,
|
||||
actorUserId: ctx.userId,
|
||||
actorKind: "user",
|
||||
activityType: "email_sent",
|
||||
subjectType: "tenant",
|
||||
subjectId: ctx.tenantId,
|
||||
summaryText: scheduled
|
||||
? "activity.runtime.emailMarketing.campaignScheduled"
|
||||
: "activity.runtime.emailMarketing.campaignSendStarted",
|
||||
metadata: { campaignId, recipientCount: result.recipientCount },
|
||||
}).catch(() => undefined),
|
||||
withTenantRLS(ctx.tenantId, (tx) =>
|
||||
notify(
|
||||
{
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
channel: "IN_APP",
|
||||
category: "email-marketing",
|
||||
messageKey: scheduled ? "emailMarketing.notification.scheduled" : "emailMarketing.notification.sendAccepted",
|
||||
sourceKey: `email-campaign:${campaignId}:${scheduled ? "scheduled" : "send"}`,
|
||||
payloadMetadata: { campaignId, recipientCount: result.recipientCount },
|
||||
},
|
||||
tx as unknown as Parameters<typeof notify>[1]
|
||||
)
|
||||
).catch(() => undefined),
|
||||
]);
|
||||
return Response.json({
|
||||
successKey: scheduled ? "emailMarketing.send.scheduledSuccess" : "emailMarketing.send.success",
|
||||
} satisfies ActionData);
|
||||
} catch (error) {
|
||||
if (error instanceof CampaignSendError) {
|
||||
return Response.json({ errorKey: error.messageKey } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export default function CampaignDetailRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const { csrf } = useRootData();
|
||||
return (
|
||||
<CampaignDetailPage
|
||||
vm={data.vm}
|
||||
checklist={data.checklist}
|
||||
confirmation={data.confirmation}
|
||||
actionData={actionData}
|
||||
actions={{
|
||||
onSend: (formData) => {
|
||||
formData.set("csrf", csrf ?? "");
|
||||
submit(formData, { method: "post" });
|
||||
},
|
||||
onCancelSchedule: () => {
|
||||
const formData = new FormData();
|
||||
formData.set("intent", "cancel-schedule");
|
||||
formData.set("csrf", csrf ?? "");
|
||||
submit(formData, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { type LoaderFunctionArgs, useLoaderData, useParams, useSubmit } from "react-router";
|
||||
import { buildCampaignListVM } from "@hivegrid/view-models";
|
||||
import { CampaignListPage } from "~/components/screens/email-marketing/EmailMarketingInterimScreens";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getAllCampaigns } from "~/modules/emailMarketing/db/campaigns.db.server";
|
||||
import { loadEmailDomainContext, notFoundResponse } from "~/utils/integrations/emailDomainService.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
type LoaderData = {
|
||||
vm: ReturnType<typeof buildCampaignListVM>;
|
||||
filters: { query: string; status: string };
|
||||
};
|
||||
|
||||
function canView(permissions: readonly string[]): boolean {
|
||||
return permissions.includes("emailMarketing.view") || permissions.includes("emailMarketing.manage");
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!canView(ctx.permissions)) throw notFoundResponse();
|
||||
const url = new URL(request.url);
|
||||
const query = url.searchParams.get("query")?.slice(0, 120) ?? "";
|
||||
const requestedStatus = url.searchParams.get("status") ?? "";
|
||||
const status = ["draft", "scheduled", "sending", "sent", "paused", "archived"].includes(requestedStatus) ? requestedStatus : "";
|
||||
const campaigns = await getAllCampaigns(ctx.tenantId, status || undefined, query || undefined);
|
||||
const vm = buildCampaignListVM({
|
||||
items: campaigns.map((campaign) => ({
|
||||
id: campaign.id,
|
||||
name: campaign.name,
|
||||
status: campaign.status,
|
||||
recipientCount: campaign.recipients.length,
|
||||
delivered: campaign.recipients.filter((recipient) => recipient.deliveredAt).length,
|
||||
opened: campaign.recipients.filter((recipient) => recipient._count.opens > 0).length,
|
||||
clicked: campaign.recipients.filter((recipient) => recipient._count.clicks > 0).length,
|
||||
sentAt: campaign.sentAt,
|
||||
})),
|
||||
});
|
||||
return Response.json({ vm, filters: { query, status } } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export default function CampaignsIndexRoute() {
|
||||
const { vm, filters } = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
const submit = useSubmit();
|
||||
return (
|
||||
<CampaignListPage
|
||||
vm={vm}
|
||||
newHref={UrlUtils.getModulePath(params, "email-marketing/campaigns/new")}
|
||||
detailHref={(id) => UrlUtils.getModulePath(params, `email-marketing/campaigns/${id}`)}
|
||||
filters={filters}
|
||||
actions={{ onFilter: (formData) => submit(formData, { method: "get" }) }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
import { useEffect } from "react";
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useFetcher, useLoaderData, useNavigate } from "react-router";
|
||||
import { z } from "zod";
|
||||
import { buildCampaignDraftVM, CAMPAIGN_DRAFT_STEPS, type CampaignDraftStep, type CampaignDraftVM, type PresendChecklistVM } from "@hivegrid/view-models";
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { CampaignEditorPage } from "~/components/screens/email-marketing/EmailMarketingInterimScreens";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { getAllEmailSenders } from "~/modules/emailMarketing/db/emailSender";
|
||||
import { sendBroadcast } from "~/modules/emailMarketing/services/EmailMarketingSenderService.server";
|
||||
import { loadCampaignPreflight } from "~/modules/emailMarketing/services/CampaignPreflightService.server";
|
||||
import { listSegments } from "~/modules/emailMarketing/services/SegmentService.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { loadEmailDomainContext, notFoundResponse } from "~/utils/integrations/emailDomainService.server";
|
||||
import { parseScheduledAt } from "~/utils/integrations/email/campaignSchedule";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
const logger = createScopedLogger("email-marketing-campaign-editor");
|
||||
const DraftPayloadSchema = z.object({
|
||||
draftId: z.string().trim().min(1).nullable(),
|
||||
autosaveVersion: z.string().trim().min(1).max(128).nullable(),
|
||||
currentStep: z.enum(CAMPAIGN_DRAFT_STEPS),
|
||||
name: z.string().trim().max(160),
|
||||
subject: z.string().trim().max(255),
|
||||
previewText: z.string().trim().max(255).nullable(),
|
||||
emailSenderId: z.string().trim().min(1),
|
||||
recipientSegmentId: z.string().trim().min(1).nullable(),
|
||||
htmlBody: z.string().max(500_000),
|
||||
textBody: z.string().max(500_000).nullable(),
|
||||
footerHtml: z.string().max(50_000).nullable(),
|
||||
scheduleDate: z.string().trim().max(10),
|
||||
scheduleTime: z.string().trim().max(5),
|
||||
timezone: z.string().trim().min(1).max(100),
|
||||
track: z.boolean(),
|
||||
});
|
||||
const TestEmailSchema = z.array(z.string().trim().email()).min(1).max(5);
|
||||
|
||||
type TestResult = { email: string; ok: boolean; messageKey: string; reference?: string };
|
||||
type ActionData =
|
||||
| { intent: "save-draft"; ok: true; draftId: string; version: string }
|
||||
| { intent: "send-test"; ok: true; results: TestResult[] }
|
||||
| { intent: "error"; ok: false; errorKey: string };
|
||||
type LoaderData = {
|
||||
senders: Array<{ id: string; label: string }>;
|
||||
segments: Array<{ id: string; name: string }>;
|
||||
templates: Array<{ id: string; name: string; subject: string; htmlBody: string }>;
|
||||
initialTemplateId?: string;
|
||||
vm: CampaignDraftVM;
|
||||
preflight: PresendChecklistVM | null;
|
||||
canManage: boolean;
|
||||
};
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
function optionalString(value: FormDataEntryValue | null): string | null {
|
||||
const text = value?.toString().trim() ?? "";
|
||||
return text.length > 0 ? text : null;
|
||||
}
|
||||
|
||||
type DraftVersionFields = {
|
||||
name: string;
|
||||
subject: string;
|
||||
previewText: string | null;
|
||||
emailSenderId: string;
|
||||
recipientSegmentId: string | null;
|
||||
htmlBody: string;
|
||||
textBody: string | null;
|
||||
footerHtml: string | null;
|
||||
scheduledAt: Date | null;
|
||||
timezone: string | null;
|
||||
track: boolean;
|
||||
};
|
||||
|
||||
export async function buildCampaignDraftVersion(draft: DraftVersionFields): Promise<string> {
|
||||
const value = JSON.stringify({
|
||||
name: draft.name,
|
||||
subject: draft.subject,
|
||||
previewText: draft.previewText,
|
||||
emailSenderId: draft.emailSenderId,
|
||||
recipientSegmentId: draft.recipientSegmentId,
|
||||
htmlBody: draft.htmlBody,
|
||||
textBody: draft.textBody,
|
||||
footerHtml: draft.footerHtml,
|
||||
scheduledAt: draft.scheduledAt?.toISOString() ?? null,
|
||||
timezone: draft.timezone,
|
||||
track: draft.track,
|
||||
});
|
||||
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
||||
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
function parseDraftPayload(form: FormData) {
|
||||
return DraftPayloadSchema.safeParse({
|
||||
draftId: optionalString(form.get("draftId")),
|
||||
autosaveVersion: optionalString(form.get("autosaveVersion")),
|
||||
currentStep: form.get("currentStep")?.toString() ?? "basics",
|
||||
name: form.get("name")?.toString() ?? "",
|
||||
subject: form.get("subject")?.toString() ?? "",
|
||||
previewText: optionalString(form.get("previewText")),
|
||||
emailSenderId: form.get("emailSenderId")?.toString() ?? "",
|
||||
recipientSegmentId: optionalString(form.get("recipientSegmentId")),
|
||||
htmlBody: form.get("htmlBody")?.toString() ?? "",
|
||||
textBody: optionalString(form.get("textBody")),
|
||||
footerHtml: optionalString(form.get("footerHtml")),
|
||||
scheduleDate: form.get("scheduleDate")?.toString() ?? "",
|
||||
scheduleTime: form.get("scheduleTime")?.toString() ?? "",
|
||||
timezone: form.get("timezone")?.toString() ?? "",
|
||||
track: form.get("track")?.toString() === "true",
|
||||
});
|
||||
}
|
||||
|
||||
function firstIncompleteStep(input: {
|
||||
name: string;
|
||||
subject: string;
|
||||
emailSenderId: string;
|
||||
htmlBody: string;
|
||||
footerHtml: string | null;
|
||||
recipientSegmentId: string | null;
|
||||
testCompleted: boolean;
|
||||
}): CampaignDraftStep {
|
||||
if (!input.name.trim() || !input.subject.trim() || !input.emailSenderId) return "basics";
|
||||
if (!input.htmlBody.trim() || !input.footerHtml?.trim()) return "content";
|
||||
if (!input.recipientSegmentId) return "audience";
|
||||
if (!input.testCompleted) return "test";
|
||||
return "schedule";
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!canView(ctx.permissions)) throw notFoundResponse();
|
||||
const requestedTemplateId = new URL(request.url).searchParams.get("templateId");
|
||||
const draftId = new URL(request.url).searchParams.get("draftId");
|
||||
const [senders, segments, templates, draft] = await Promise.all([
|
||||
getAllEmailSenders(ctx.tenantId),
|
||||
listSegments(ctx.tenantId),
|
||||
withTenantRLS(ctx.tenantId, (tx) =>
|
||||
tx.emailTemplate.findMany({
|
||||
where: { tenantId: ctx.tenantId, archivedAt: null },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 25,
|
||||
})
|
||||
),
|
||||
draftId
|
||||
? withTenantRLS(ctx.tenantId, (tx) =>
|
||||
tx.campaign.findFirst({
|
||||
where: { id: draftId, tenantId: ctx.tenantId, status: "draft", archivedAt: null },
|
||||
include: { recipients: { where: { isPreview: true }, select: { id: true }, take: 1 } },
|
||||
})
|
||||
)
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
if (draftId && !draft) throw notFoundResponse();
|
||||
const preflight = draft
|
||||
? await loadCampaignPreflight({
|
||||
tenantId: ctx.tenantId,
|
||||
ctx: { userId: ctx.userId, permissions: ctx.permissions },
|
||||
campaignId: draft.id,
|
||||
})
|
||||
: null;
|
||||
const initialTemplate = templates.find((template) => template.id === requestedTemplateId);
|
||||
const draftValues = draft ?? {
|
||||
id: null,
|
||||
name: "",
|
||||
subject: initialTemplate?.subject ?? "",
|
||||
previewText: null,
|
||||
emailSenderId: senders.find((sender) => sender.isDefault)?.id ?? senders[0]?.id ?? "",
|
||||
recipientSegmentId: null,
|
||||
htmlBody: initialTemplate?.htmlBody ?? "",
|
||||
textBody: null,
|
||||
footerHtml: null,
|
||||
scheduledAt: null,
|
||||
timezone: "Europe/Berlin",
|
||||
track: true,
|
||||
recipients: [],
|
||||
};
|
||||
const testCompleted = draftValues.recipients.length > 0;
|
||||
const vm = buildCampaignDraftVM({
|
||||
id: draftValues.id,
|
||||
autosaveVersion: draft ? await buildCampaignDraftVersion(draft) : null,
|
||||
currentStep: firstIncompleteStep({ ...draftValues, testCompleted }),
|
||||
name: draftValues.name,
|
||||
subject: draftValues.subject,
|
||||
previewText: draftValues.previewText,
|
||||
emailSenderId: draftValues.emailSenderId,
|
||||
recipientSegmentId: draftValues.recipientSegmentId,
|
||||
htmlBody: draftValues.htmlBody,
|
||||
textBody: draftValues.textBody,
|
||||
footerHtml: draftValues.footerHtml,
|
||||
scheduledAt: draftValues.scheduledAt,
|
||||
timezone: draftValues.timezone ?? "Europe/Berlin",
|
||||
track: draftValues.track,
|
||||
testCompleted,
|
||||
});
|
||||
return Response.json({
|
||||
senders: senders.map((sender) => ({
|
||||
id: sender.id,
|
||||
label: sender.fromName ? `${sender.fromName} <${sender.fromEmail}>` : sender.fromEmail,
|
||||
})),
|
||||
segments: segments.map((segment) => ({ id: segment.id, name: segment.name })),
|
||||
templates: templates.map((template) => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
subject: template.subject,
|
||||
htmlBody: template.htmlBody,
|
||||
})),
|
||||
initialTemplateId: initialTemplate?.id,
|
||||
vm,
|
||||
preflight: preflight?.checklistVM ?? null,
|
||||
canManage: canManage(ctx.permissions),
|
||||
} satisfies LoaderData);
|
||||
};
|
||||
|
||||
async function auditDraft(input: { tenantId: string; userId: string; campaignId: string; created: boolean; step: CampaignDraftStep }): Promise<void> {
|
||||
await createAuditEvent({
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.userId,
|
||||
actorType: "user",
|
||||
action: input.created ? "EMAIL_CAMPAIGN_DRAFT_CREATED" : "EMAIL_CAMPAIGN_DRAFT_SAVED",
|
||||
targetType: "Campaign",
|
||||
targetId: input.campaignId,
|
||||
sourceModule: "email-marketing",
|
||||
metadata: { step: input.step },
|
||||
}).catch(() => undefined);
|
||||
if (input.created) {
|
||||
await logActivity({
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.userId,
|
||||
actorKind: "user",
|
||||
activityType: "audit_event",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: "activity.runtime.emailMarketing.campaignDraftCreated",
|
||||
metadata: { campaignId: input.campaignId },
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveDraft(
|
||||
ctx: Awaited<ReturnType<typeof loadEmailDomainContext>>,
|
||||
form: FormData,
|
||||
untitledDraftName: string
|
||||
): Promise<ActionData> {
|
||||
const parsed = parseDraftPayload(form);
|
||||
if (!parsed.success) return { intent: "error", ok: false, errorKey: "emailMarketing.campaign.editor.error.invalidPayload" };
|
||||
const payload = parsed.data;
|
||||
const scheduledAt =
|
||||
payload.scheduleDate || payload.scheduleTime
|
||||
? parseScheduledAt(`${payload.scheduleDate}T${payload.scheduleTime}`, payload.timezone)
|
||||
: { ok: true as const, date: null };
|
||||
if (!scheduledAt.ok || Boolean(payload.scheduleDate) !== Boolean(payload.scheduleTime)) {
|
||||
return { intent: "error", ok: false, errorKey: "emailMarketing.campaign.editor.error.invalidSchedule" };
|
||||
}
|
||||
|
||||
const saved = await withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const [sender, segment] = await Promise.all([
|
||||
tx.emailSender.findFirst({ where: { id: payload.emailSenderId, tenantId: ctx.tenantId }, select: { id: true } }),
|
||||
payload.recipientSegmentId
|
||||
? tx.recipientSegment.findFirst({
|
||||
where: { id: payload.recipientSegmentId, tenantId: ctx.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
})
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
if (!sender || (payload.recipientSegmentId && !segment)) return null;
|
||||
const data = {
|
||||
emailSenderId: payload.emailSenderId,
|
||||
recipientSegmentId: payload.recipientSegmentId,
|
||||
name: payload.name || untitledDraftName,
|
||||
subject: payload.subject,
|
||||
previewText: payload.previewText,
|
||||
htmlBody: payload.htmlBody,
|
||||
textBody: payload.textBody,
|
||||
footerHtml: payload.footerHtml,
|
||||
scheduledAt: scheduledAt.date,
|
||||
timezone: payload.timezone,
|
||||
track: payload.track,
|
||||
};
|
||||
if (!payload.draftId) {
|
||||
const campaign = await tx.campaign.create({
|
||||
data: { ...data, tenantId: ctx.tenantId, status: "draft" },
|
||||
});
|
||||
return { ...campaign, created: true };
|
||||
}
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`email-campaign:${payload.draftId}`}))`;
|
||||
const current = await tx.campaign.findFirst({
|
||||
where: { id: payload.draftId, tenantId: ctx.tenantId, status: "draft" },
|
||||
});
|
||||
if (!current) return null;
|
||||
if (payload.autosaveVersion && (await buildCampaignDraftVersion(current)) !== payload.autosaveVersion) {
|
||||
return "conflict" as const;
|
||||
}
|
||||
const updated = await tx.campaign.updateMany({
|
||||
where: { id: payload.draftId, tenantId: ctx.tenantId, status: "draft" },
|
||||
data,
|
||||
});
|
||||
if (updated.count !== 1) return null;
|
||||
const campaign = await tx.campaign.findFirstOrThrow({
|
||||
where: { id: payload.draftId, tenantId: ctx.tenantId },
|
||||
});
|
||||
return { ...campaign, created: false };
|
||||
});
|
||||
if (saved === "conflict") return { intent: "error", ok: false, errorKey: "emailMarketing.campaign.editor.error.conflict" };
|
||||
if (!saved) return { intent: "error", ok: false, errorKey: "emailMarketing.campaign.editor.error.invalidSelection" };
|
||||
await auditDraft({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
campaignId: saved.id,
|
||||
created: saved.created,
|
||||
step: payload.currentStep,
|
||||
});
|
||||
return { intent: "save-draft", ok: true, draftId: saved.id, version: await buildCampaignDraftVersion(saved) };
|
||||
}
|
||||
|
||||
async function sendTests(ctx: Awaited<ReturnType<typeof loadEmailDomainContext>>, form: FormData): Promise<ActionData> {
|
||||
const draftId = optionalString(form.get("draftId"));
|
||||
const parsedEmails = TestEmailSchema.safeParse(
|
||||
form
|
||||
.getAll("testEmail")
|
||||
.map((value) => value.toString().trim().toLocaleLowerCase("de-DE"))
|
||||
.filter(Boolean)
|
||||
);
|
||||
if (!draftId || !parsedEmails.success) {
|
||||
return { intent: "error", ok: false, errorKey: "emailMarketing.campaign.editor.error.invalidTestRecipients" };
|
||||
}
|
||||
const loaded = await withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const campaign = await tx.campaign.findFirst({
|
||||
where: { id: draftId, tenantId: ctx.tenantId, status: "draft" },
|
||||
include: { emailSender: true },
|
||||
});
|
||||
if (!campaign) return null;
|
||||
const domain = campaign.emailSender.sendingDomainId
|
||||
? await tx.tenantSendingDomain.findFirst({
|
||||
where: { id: campaign.emailSender.sendingDomainId, tenantId: ctx.tenantId },
|
||||
select: { verificationStatus: true },
|
||||
})
|
||||
: null;
|
||||
return { campaign, domainReady: domain?.verificationStatus === "verified" };
|
||||
});
|
||||
if (!loaded) return { intent: "error", ok: false, errorKey: "emailMarketing.send.error.notFound" };
|
||||
if (!loaded.domainReady) return { intent: "error", ok: false, errorKey: "emailMarketing.campaign.editor.error.testDomain" };
|
||||
|
||||
const results: TestResult[] = [];
|
||||
for (const email of parsedEmails.data) {
|
||||
const preview = await withTenantRLS(ctx.tenantId, (tx) =>
|
||||
tx.outboundEmail.create({
|
||||
data: {
|
||||
tenantId: ctx.tenantId,
|
||||
campaignId: loaded.campaign.id,
|
||||
email,
|
||||
fromSenderId: loaded.campaign.emailSenderId,
|
||||
isPreview: true,
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
);
|
||||
try {
|
||||
await sendBroadcast({
|
||||
sender: loaded.campaign.emailSender,
|
||||
to: email,
|
||||
subject: loaded.campaign.subject,
|
||||
htmlBody: loaded.campaign.htmlBody,
|
||||
textBody: loaded.campaign.textBody ?? "",
|
||||
track: false,
|
||||
metadata: { outboundEmailId: preview.id, campaignId: loaded.campaign.id },
|
||||
});
|
||||
await withTenantRLS(ctx.tenantId, (tx) =>
|
||||
tx.outboundEmail.updateMany({
|
||||
where: { id: preview.id, tenantId: ctx.tenantId, isPreview: true },
|
||||
data: { sentAt: new Date() },
|
||||
})
|
||||
);
|
||||
results.push({ email, ok: true, messageKey: "emailMarketing.campaign.editor.test.sent" });
|
||||
} catch (error) {
|
||||
const reference = crypto.randomUUID();
|
||||
logger.error(
|
||||
{
|
||||
event: "email_marketing.campaign_test_failed",
|
||||
reference,
|
||||
tenantId: ctx.tenantId,
|
||||
campaignId: loaded.campaign.id,
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
},
|
||||
"Campaign test delivery failed"
|
||||
);
|
||||
await withTenantRLS(ctx.tenantId, (tx) =>
|
||||
tx.outboundEmail.updateMany({
|
||||
where: { id: preview.id, tenantId: ctx.tenantId, isPreview: true },
|
||||
data: { error: `emailMarketing.campaignTest.providerFailed:${reference}` },
|
||||
})
|
||||
);
|
||||
results.push({
|
||||
email,
|
||||
ok: false,
|
||||
messageKey: "emailMarketing.campaign.editor.test.providerFailed",
|
||||
reference,
|
||||
});
|
||||
}
|
||||
}
|
||||
await createAuditEvent({
|
||||
tenantId: ctx.tenantId,
|
||||
actorId: ctx.userId,
|
||||
actorType: "user",
|
||||
action: "EMAIL_CAMPAIGN_TEST_SENT",
|
||||
targetType: "Campaign",
|
||||
targetId: loaded.campaign.id,
|
||||
sourceModule: "email-marketing",
|
||||
metadata: { recipientCount: results.length, successful: results.filter((result) => result.ok).length },
|
||||
}).catch(() => undefined);
|
||||
return { intent: "send-test", ok: true, results };
|
||||
}
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadEmailDomainContext({ request, params });
|
||||
if (!canManage(ctx.permissions)) throw notFoundResponse();
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent")?.toString();
|
||||
if (intent === "save-draft") {
|
||||
return Response.json(await saveDraft(ctx, form, String(t("emailMarketing.campaign.editor.untitledDraft"))));
|
||||
}
|
||||
if (intent === "send-test") return Response.json(await sendTests(ctx, form));
|
||||
return Response.json({ intent: "error", ok: false, errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
};
|
||||
|
||||
export default function CampaignNewRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const { csrf } = useRootData();
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.intent !== "save-draft" || !fetcher.data.ok || data.vm.data?.id) return;
|
||||
void navigate(`?draftId=${encodeURIComponent(fetcher.data.draftId)}`, { replace: true });
|
||||
}, [data.vm.data?.id, fetcher.data, navigate]);
|
||||
const submit = (intent: "save-draft" | "send-test") => (formData: FormData) => {
|
||||
formData.set("intent", intent);
|
||||
formData.set("csrf", csrf ?? "");
|
||||
fetcher.submit(formData, { method: "post" });
|
||||
};
|
||||
return (
|
||||
<CampaignEditorPage
|
||||
senders={data.senders}
|
||||
segments={data.segments}
|
||||
templates={data.templates}
|
||||
initialTemplateId={data.initialTemplateId}
|
||||
vm={data.vm}
|
||||
preflight={data.preflight}
|
||||
canManage={data.canManage}
|
||||
actionData={fetcher.data}
|
||||
saveState={fetcher.state}
|
||||
actions={{ onSaveDraft: submit("save-draft"), onSendTest: submit("send-test") }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+26
-4
@@ -1,13 +1,35 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { LoaderFunctionArgs, MetaFunction, redirect, useLoaderData, useParams } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import EmailMarketingSummaryRoute from "~/modules/emailMarketing/components/EmailMarketingSummaryRoute";
|
||||
import { EmailMarketingOverviewPage } from "~/components/screens/email-marketing/EmailMarketingInterimScreens";
|
||||
import { EmailMarketing_Summary } from "~/modules/emailMarketing/routes/EmailMarketing_Summary";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { loadEmailMarketingSetup } from "~/modules/emailMarketing/services/EmailMarketingSetupService.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => EmailMarketing_Summary.loader(args);
|
||||
export const loader = async (args: LoaderFunctionArgs) => {
|
||||
const summary = await EmailMarketing_Summary.loader(args);
|
||||
const tenantId = await getTenantIdFromUrl(args.params);
|
||||
const setup = await loadEmailMarketingSetup(tenantId);
|
||||
if (setup.status === "ready" && setup.data && !setup.data.ready) {
|
||||
throw redirect(UrlUtils.getModulePath(args.params, "email-marketing/setup"));
|
||||
}
|
||||
return summary;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => <EmailMarketingSummaryRoute />;
|
||||
export default function EmailMarketingIndexRoute() {
|
||||
const { summary } = useLoaderData<typeof loader>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<EmailMarketingOverviewPage
|
||||
summary={summary}
|
||||
campaignsHref={UrlUtils.getModulePath(params, "email-marketing/campaigns")}
|
||||
sendersHref={UrlUtils.getModulePath(params, "email-marketing/senders")}
|
||||
domainHref={UrlUtils.getModulePath(params, "email-marketing/sending-domain")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
|
||||
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user