Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowNewRoute from "~/modules/rows/components/RowNewRoute";
|
||||
import { Rows_New } from "~/modules/rows/routes/Rows_New.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_New.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_New.action(args);
|
||||
|
||||
export default () => <RowNewRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Relationships } from "~/modules/rows/routes/Rows_Relationships.server";
|
||||
import RowsRelationshipsRoute from "~/modules/rows/components/RowsRelationshipsRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Relationships.loader(args);
|
||||
|
||||
export default () => <RowsRelationshipsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowsViewRoute from "~/modules/rows/components/RowsViewRoute";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_List.LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<RowsViewRoute
|
||||
key={data.rowsData.entity.id}
|
||||
rowsData={data.rowsData}
|
||||
items={data.rowsData.items}
|
||||
routes={data.routes}
|
||||
saveCustomViews={true}
|
||||
permissions={{
|
||||
create: getUserHasPermission(appOrAdminData, getEntityPermission(data.rowsData.entity, "create")),
|
||||
}}
|
||||
currentSession={{
|
||||
user: appOrAdminData.user,
|
||||
isSuperAdmin: appOrAdminData.isSuperAdmin,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import Page404 from "~/components/pages/Page404";
|
||||
|
||||
export default function App404Route() {
|
||||
return (
|
||||
<>
|
||||
<Page404 withLogo={false} withFooter={false} withGoBack={false} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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
@@ -0,0 +1,133 @@
|
||||
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.stripe.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.stripe.tsx",
|
||||
];
|
||||
|
||||
const portalPricingHandlers = [
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.edit.$product.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.new.tsx",
|
||||
"routes/app.$tenant/__portals/portals.$portal/pricing.stripe.tsx",
|
||||
];
|
||||
|
||||
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.stripe.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 Stripe 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()"));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
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" }');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
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;
|
||||
@@ -0,0 +1,37 @@
|
||||
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.stripeAccountMissing");
|
||||
expect(source).toContain("models.portal.pages.errors.privacyPolicyContentMissing");
|
||||
expect(source).toContain("models.portal.pages.errors.termsContentMissing");
|
||||
expect(source).not.toContain('group: "SEO"');
|
||||
expect(source).not.toContain("No Stripe account connected");
|
||||
expect(source).not.toContain("No privacy policy content");
|
||||
expect(source).not.toContain("No terms and conditions content");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
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
@@ -0,0 +1,382 @@
|
||||
import { AnalyticsEvent, AnalyticsUniqueVisitor, Portal, Prisma } from "@toolctrl/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
@@ -0,0 +1,318 @@
|
||||
import { AnalyticsPageView, AnalyticsUniqueVisitor, Portal, Prisma } from "@toolctrl/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
@@ -0,0 +1,59 @@
|
||||
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("@toolctrl/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
@@ -0,0 +1,110 @@
|
||||
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 "@toolctrl/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
@@ -0,0 +1,280 @@
|
||||
import { AnalyticsUniqueVisitor, Portal, Prisma } from "@toolctrl/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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
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 />;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
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 stripeAccountId = form.get("stripeAccountId")?.toString();
|
||||
|
||||
await updatePortal(item, {
|
||||
seoTitle: seoTitle || null,
|
||||
seoDescription: seoDescription || null,
|
||||
seoImage: seoImage || null,
|
||||
stripeAccountId: stripeAccountId || 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
@@ -0,0 +1,194 @@
|
||||
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 "@toolctrl/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
@@ -0,0 +1,187 @@
|
||||
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 "@toolctrl/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,
|
||||
stripeId: "",
|
||||
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
@@ -0,0 +1,176 @@
|
||||
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 = {
|
||||
stripeId: "",
|
||||
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>
|
||||
);
|
||||
}
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useParams, useSubmit } from "react-router";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import type Stripe from "stripe";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { PortalWithDetails, getPortalById, updatePortal } from "~/modules/portals/db/portals.db.server";
|
||||
import StripeConnectUtils from "~/modules/portals/utils/StripeConnectUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import StripeConnectServer from "~/modules/portals/services/StripeConnect.server";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getAbsoluteCurrentUrl, getAbsoluteUrl } from "~/utils/url.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { requirePortalMutationAccess, requirePortalPricingEnabled, requirePortalReadAccess } from "../portalAccess.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails;
|
||||
stripeAccount: Stripe.Account | null;
|
||||
};
|
||||
|
||||
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalPricingEnabled({ request, tenantId });
|
||||
await requirePortalReadAccess({ request, params, tenantId });
|
||||
const item = await getPortalById(tenantId, params.portal!);
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
let stripeAccount: Stripe.Account | null = null;
|
||||
try {
|
||||
stripeAccount = item.stripeAccountId ? await StripeConnectServer.getStripeAccount(item.stripeAccountId) : null;
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e.message);
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
stripeAccount,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
|
||||
function portalPricingPath(params: { portal?: string }, portal: { subdomain?: string | null }) {
|
||||
return UrlUtils.getModulePath(params, `portals/${portal.subdomain || params.portal}/pricing`);
|
||||
}
|
||||
|
||||
export let action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await requirePortalPricingEnabled({ request, tenantId });
|
||||
await requirePortalMutationAccess({ request, params, tenantId });
|
||||
const userInfo = await getUserInfo(request);
|
||||
const user = await getUser(userInfo.userId);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
const portal = await getPortalById(tenantId, params.portal!);
|
||||
if (!portal) {
|
||||
return redirect(UrlUtils.getModulePath(params, "portals"));
|
||||
}
|
||||
|
||||
if (action === "connectStripe") {
|
||||
try {
|
||||
const country = form.get("country") as string;
|
||||
if (!country) {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.countryRequired") }, { status: 400 });
|
||||
}
|
||||
const stripeAccount = await StripeConnectServer.createStripeAccount({
|
||||
email: user!.email,
|
||||
country,
|
||||
metadata: {
|
||||
tenantId: portal.tenantId ?? "{admin}",
|
||||
},
|
||||
});
|
||||
await updatePortal(portal, {
|
||||
stripeAccountId: stripeAccount.id,
|
||||
});
|
||||
portal.stripeAccountId = stripeAccount.id;
|
||||
|
||||
const stripeAccountLink = await StripeConnectServer.createStripeAccountLink({
|
||||
account: portal.stripeAccountId,
|
||||
return_url: getAbsoluteUrl(request, portalPricingPath(params, portal)),
|
||||
refresh_url: getAbsoluteCurrentUrl(request),
|
||||
});
|
||||
return redirect(stripeAccountLink.url);
|
||||
} catch {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.connectFailed") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "reconnectStripe") {
|
||||
try {
|
||||
if (!portal.stripeAccountId) {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.accountNotFound") }, { status: 400 });
|
||||
}
|
||||
const stripeAccount = await StripeConnectServer.getStripeAccount(portal.stripeAccountId);
|
||||
if (!stripeAccount) {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.accountNotFoundWithId", { id: portal.stripeAccountId }) }, { status: 400 });
|
||||
}
|
||||
await updatePortal(portal, {
|
||||
stripeAccountId: stripeAccount.id,
|
||||
});
|
||||
portal.stripeAccountId = stripeAccount.id;
|
||||
const stripeAccountLink = await StripeConnectServer.createStripeAccountLink({
|
||||
account: portal.stripeAccountId,
|
||||
return_url: getAbsoluteUrl(request, portalPricingPath(params, portal)),
|
||||
refresh_url: getAbsoluteCurrentUrl(request),
|
||||
});
|
||||
return redirect(stripeAccountLink.url);
|
||||
} catch {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.reconnectFailed") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "deleteStripe") {
|
||||
try {
|
||||
if (!portal.stripeAccountId) {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.accountNotFound") }, { status: 400 });
|
||||
}
|
||||
await updatePortal(portal, {
|
||||
stripeAccountId: null,
|
||||
});
|
||||
await StripeConnectServer.deleteStripeAccount(portal.stripeAccountId);
|
||||
return Response.json({ success: t("models.portal.stripe.success.accountDeleted") });
|
||||
} catch {
|
||||
return Response.json({ error: t("models.portal.stripe.errors.disconnectFailed") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t, i18n } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const params = useParams();
|
||||
const stripeConnectCountries = useMemo(() => StripeConnectUtils.getLocalizedStripeConnectCountries(i18n.language), [i18n.language]);
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
confirmDelete.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "deleteStripe");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("models.portal.stripe.connect.title")}
|
||||
withHome={false}
|
||||
menu={[
|
||||
// {
|
||||
// title: t("models.portal.plural"),
|
||||
// routePath: UrlUtils.getModulePath(params, "portals"),
|
||||
// },
|
||||
{
|
||||
title: data.item.title,
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.item.subdomain}`),
|
||||
},
|
||||
{
|
||||
title: t("models.portal.pricing.title"),
|
||||
routePath: UrlUtils.getModulePath(params, `portals/${data.item.subdomain}/pricing`),
|
||||
},
|
||||
{
|
||||
title: t("models.portal.stripe.title"),
|
||||
},
|
||||
]}
|
||||
>
|
||||
{!data.stripeAccount ? (
|
||||
<div className="space-y-2">
|
||||
<p className="">{t("models.portal.stripe.connect.description")}</p>
|
||||
<Form method="post" className="space-y-2">
|
||||
<input type="hidden" name="action" value="connectStripe" />
|
||||
<div className="w-40">
|
||||
<InputSelect
|
||||
name="country"
|
||||
title={t("models.portal.stripe.country")}
|
||||
placeholder={t("shared.select")}
|
||||
options={stripeConnectCountries}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<LoadingButton
|
||||
className="focus:ring-opacity-50 bg-[#5433FF] text-white hover:bg-[#4F2DFF] focus:ring-[#5433FF] active:bg-[#4F2DFF]"
|
||||
type="submit"
|
||||
>
|
||||
{t("models.portal.stripe.connect.action")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
) : !data.stripeAccount.charges_enabled ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<XIcon className="h-6 w-6 text-red-500" />
|
||||
<div className="text-lg font-medium">{t("models.portal.stripe.pending.title")}</div>
|
||||
</div>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="reconnectStripe" />
|
||||
<LoadingButton
|
||||
className="focus:ring-opacity-50 bg-[#5433FF] hover:bg-[#4F2DFF] focus:ring-[#5433FF] active:bg-[#4F2DFF]"
|
||||
type="submit"
|
||||
actionName="reconnectStripe"
|
||||
>
|
||||
{t("models.portal.stripe.reconnect")}
|
||||
</LoadingButton>
|
||||
</Form>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Form method="post" onSubmit={onDelete}>
|
||||
<input type="hidden" name="action" value="deleteStripe" />
|
||||
<ButtonSecondary destructive type="submit">
|
||||
{t("models.portal.stripe.disconnect")}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<CheckIcon className="h-6 w-6 text-green-500" />
|
||||
<div className="text-lg font-medium">{t("models.portal.stripe.connected")}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Form method="post" onSubmit={onDelete}>
|
||||
<input type="hidden" name="action" value="deleteStripe" />
|
||||
<ButtonSecondary destructive type="submit">
|
||||
{t("models.portal.stripe.disconnect")}
|
||||
</ButtonSecondary>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { EyeIcon } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Stripe from "stripe";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import GearIcon from "~/components/ui/icons/GearIcon";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getAllPortalSubscriptionProductsWithUsers } from "~/modules/portals/db/portalSubscriptionProducts.db.server";
|
||||
import { PortalWithDetails, getPortalById } from "~/modules/portals/db/portals.db.server";
|
||||
import PortalServer from "~/modules/portals/services/Portal.server";
|
||||
import StripeConnectServer from "~/modules/portals/services/StripeConnect.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { requirePortalPricingEnabled, requirePortalReadAccess } from "../portalAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
item: PortalWithDetails;
|
||||
stripeAccount: Stripe.Account | null;
|
||||
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"));
|
||||
}
|
||||
let stripeAccount: Stripe.Account | null = null;
|
||||
try {
|
||||
stripeAccount = item.stripeAccountId ? await StripeConnectServer.getStripeAccount(item.stripeAccountId) : null;
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e.message);
|
||||
}
|
||||
if (stripeAccount && !stripeAccount.charges_enabled) {
|
||||
// return redirect(UrlUtils.getModulePath(params, `portals/${item.subdomain || params.portal}/pricing/stripe`));
|
||||
}
|
||||
const portalUrl = PortalServer.getPortalUrl(item);
|
||||
const items = await getAllPortalSubscriptionProductsWithUsers(item.id);
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
stripeAccount,
|
||||
items: items.sort((x, y) => {
|
||||
return x?.order > y?.order ? 1 : -1;
|
||||
}),
|
||||
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="stripe">
|
||||
<GearIcon className="h-4 w-4" />
|
||||
</ButtonSecondary>
|
||||
<ButtonSecondary to={data.publicPricingUrl} target="_blank">
|
||||
<EyeIcon className="h-4 w-4" />
|
||||
<div>{t("shared.preview")}</div>
|
||||
</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`),
|
||||
},
|
||||
]}
|
||||
>
|
||||
{data.stripeAccount === null ? (
|
||||
<WarningBanner title={t("models.portal.stripe.notConnected.title")}>
|
||||
{t("models.portal.stripe.notConnected.description")}{" "}
|
||||
<Link to={UrlUtils.getModulePath(params, `portals/${data.item.subdomain}/pricing/stripe`)} className="underline">
|
||||
{t("models.portal.stripe.notConnected.action")}
|
||||
</Link>
|
||||
</WarningBanner>
|
||||
) : !data.stripeAccount.charges_enabled ? (
|
||||
<WarningBanner title={t("models.portal.stripe.pending.title")}>
|
||||
{t("models.portal.stripe.pending.description")}{" "}
|
||||
<Link to={UrlUtils.getModulePath(params, `portals/${data.item.subdomain}/pricing/stripe`)} className="underline">
|
||||
{t("models.portal.stripe.pending.action")}
|
||||
</Link>
|
||||
</WarningBanner>
|
||||
) : null}
|
||||
<div>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
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
@@ -0,0 +1,571 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
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
@@ -0,0 +1,161 @@
|
||||
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
@@ -0,0 +1,140 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
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,
|
||||
stripeAccountId: 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 />;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { loadWebConfig } from "@toolctrl/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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import IconWidgets from "~/components/layouts/icons/IconWidgets";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (params.tenant && !appConfiguration.widgets.enabled) {
|
||||
throw Response.json({ error: t("widgets.errors.disabled") }, { status: 400 });
|
||||
}
|
||||
return Response.json({});
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const params = useParams();
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("widgets.plural"),
|
||||
href: UrlUtils.getModulePath(params, `widgets`),
|
||||
exact: true,
|
||||
icon: <IconWidgets className="h-5 w-5" />,
|
||||
iconSelected: <IconWidgets className="h-5 w-5" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, useNavigation, useParams, useSubmit } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { ClipboardIcon } from "~/components/ui/icons/vendor";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import InputImage from "~/components/ui/input/InputImage";
|
||||
import InputMultipleText from "~/components/ui/input/InputMultipleText";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { WidgetDto } from "~/modules/widgets/dtos/WidgetDto";
|
||||
import WidgetUtils from "~/modules/widgets/utils/WidgetUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { auditRejectedUpload } from "~/utils/integrations/storageAudit.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { defaultTheme, defaultThemes } from "~/utils/theme/defaultThemes";
|
||||
import { getAbsoluteUrl } from "~/utils/url.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
|
||||
type LoaderData = {
|
||||
item: WidgetDto;
|
||||
widgetUrl: string;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
|
||||
const item = await db.widget.findFirst({
|
||||
where: { id: params.id, tenantId },
|
||||
});
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item: WidgetUtils.toDto(item),
|
||||
widgetUrl: `<script src="${getAbsoluteUrl(request, "/embed.js")}" data-widget-id="${item.id}" data-open-delay="-1" defer async />`,
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
const item = await db.widget.findFirst({
|
||||
where: { id: params.id, tenantId },
|
||||
});
|
||||
if (!item) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString() || "";
|
||||
const metadata = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: appConfiguration.widgets?.metadata || [],
|
||||
prefix: "metadata",
|
||||
});
|
||||
|
||||
if (name !== item.name) {
|
||||
const existing = await db.widget.findUnique({
|
||||
where: {
|
||||
tenantId_name: { tenantId, name },
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return Response.json({ error: t("widgets.errors.nameAlreadyTaken") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
try {
|
||||
const update = await db.widget.updateMany({
|
||||
where: { id: item.id, tenantId },
|
||||
data: {
|
||||
name,
|
||||
metadata: JSON.stringify(metadata),
|
||||
},
|
||||
});
|
||||
if (update.count !== 1) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
return Response.json({ success: t("shared.updated") });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
} else if (action === "edit-branding") {
|
||||
const themeColor = form.get("themeColor")?.toString();
|
||||
const themeScheme = form.get("themeScheme")?.toString();
|
||||
let logo = form.get("logo")?.toString();
|
||||
const position = form.get("position")?.toString();
|
||||
const placeholder = form.get("placeholder")?.toString();
|
||||
const hiddenInUrls = form.getAll("hiddenInUrls[]").map((f) => f.toString());
|
||||
const visibleInUrls = form.getAll("visibleInUrls[]").map((f) => f.toString());
|
||||
|
||||
const { storedLogo } = await promiseHash({
|
||||
storedLogo: logo
|
||||
? storeFile({
|
||||
bucket: "widgets",
|
||||
content: logo,
|
||||
id: `${item.id}-logo.png`,
|
||||
scan: {
|
||||
context: "mediaLibrary",
|
||||
enqueuePostScan: true,
|
||||
onReject: auditRejectedUpload(request, "tenant.widget.logo"),
|
||||
filename: `${item.id}-logo.png`,
|
||||
},
|
||||
})
|
||||
: Promise.resolve(""),
|
||||
});
|
||||
|
||||
const appearance: WidgetDto["appearance"] = {
|
||||
theme: themeColor || "",
|
||||
mode: themeScheme === "light" ? "light" : "dark",
|
||||
logo: storedLogo,
|
||||
position: position as any,
|
||||
hiddenInUrls,
|
||||
visibleInUrls,
|
||||
};
|
||||
const update = await db.widget.updateMany({
|
||||
where: { id: item.id, tenantId },
|
||||
data: {
|
||||
appearance: JSON.stringify(appearance),
|
||||
},
|
||||
});
|
||||
if (update.count !== 1) {
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
|
||||
return Response.json({ success: t("shared.saved") });
|
||||
} else if (action === "delete") {
|
||||
await db.widget.deleteMany({
|
||||
where: { id: item.id, tenantId },
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, "widgets"));
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration } = useRootData();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
const [item, setItem] = useState<WidgetDto>(data.item);
|
||||
|
||||
const navigation = useNavigation();
|
||||
const isDeleting = navigation.state === "submitting";
|
||||
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const textToType = `${t("shared.delete")} ${data.item.name}`;
|
||||
const [typeToConfirm, setTypeToConfirm] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
setItem(data.item);
|
||||
}, [data.item]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onConfirmDelete() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.append("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={item.name}
|
||||
withHome={false}
|
||||
menu={[
|
||||
{
|
||||
title: t("widgets.plural"),
|
||||
routePath: UrlUtils.getModulePath(params, `widgets`),
|
||||
},
|
||||
{
|
||||
title: data.item.name,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="pb-20">
|
||||
<SettingSection title={t("widgets.settings.details")}>
|
||||
<div className="mt-5 md:col-span-2 md:mt-0">
|
||||
<Form method="post">
|
||||
<input hidden type="text" name="action" value="edit" readOnly />
|
||||
<div className="">
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-6 gap-2">
|
||||
<div className="col-span-6 sm:col-span-6 md:col-span-6">
|
||||
<label htmlFor="name" className="text-muted-foreground mb-1 block text-sm leading-5 font-medium">
|
||||
{t("shared.name")}
|
||||
</label>
|
||||
<Input name="name" required type="text" defaultValue={data.item.name} />
|
||||
</div>
|
||||
</div>
|
||||
<JsonPropertyValuesInput attributes={data.item.metadata} prefix="metadata" properties={appConfiguration.widgets.metadata || []} />
|
||||
</div>
|
||||
<div className="mt-3">
|
||||
<div className="flex justify-between">
|
||||
<div></div>
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* */}
|
||||
<SettingSection title={t("widgets.settings.embed.title")}>
|
||||
<div>
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{t("widgets.settings.embed.instructionBefore")} <code><head></code> {t("widgets.settings.embed.instructionAfter")}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className=""
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(data.widgetUrl);
|
||||
toast.success(t("shared.copied"));
|
||||
}}
|
||||
>
|
||||
<ClipboardIcon className="text-muted-foreground h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<InputText rows={2} className="bg-secondary" defaultValue={data.widgetUrl} readOnly />
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("widgets.settings.appearance.title")}>
|
||||
<Form method="post">
|
||||
<input type="hidden" name="action" value="edit-branding" readOnly hidden />
|
||||
<div className="space-y-2">
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-6 sm:gap-x-3">
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="themeColor"
|
||||
title={t("widgets.settings.appearance.themeColor")}
|
||||
value={item.appearance.theme}
|
||||
setValue={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
theme: e?.toString() || "",
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("shared.select") + "..."}
|
||||
options={defaultThemes.map((item) => {
|
||||
const label = t(item.labelKey, { defaultValue: item.name });
|
||||
return {
|
||||
name: label,
|
||||
value: item.value,
|
||||
component: (
|
||||
<div className="flex items-center space-x-2">
|
||||
<div
|
||||
className={clsx(
|
||||
`theme-${item.value}`,
|
||||
"bg-primary text-primary inline-flex flex-shrink-0 items-center rounded-full text-xs font-medium"
|
||||
)}
|
||||
>
|
||||
<svg className={clsx("h-2 w-2")} fill="currentColor" viewBox="0 0 8 8">
|
||||
<circle cx={4} cy={4} r={3} />
|
||||
</svg>
|
||||
</div>
|
||||
<div>{label}</div>
|
||||
</div>
|
||||
),
|
||||
};
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="themeScheme"
|
||||
title={t("widgets.settings.appearance.themeScheme")}
|
||||
value={item.appearance.mode}
|
||||
setValue={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
mode: e === "light" ? "light" : "dark",
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("shared.select") + "..."}
|
||||
options={[
|
||||
{
|
||||
name: t("shared.light"),
|
||||
value: "light",
|
||||
},
|
||||
{
|
||||
name: t("shared.dark"),
|
||||
value: "dark",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<InputSelect
|
||||
name="position"
|
||||
title={t("widgets.settings.appearance.position")}
|
||||
defaultValue={item.appearance.position}
|
||||
options={[
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.bottomRight"),
|
||||
value: "bottom-right",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.bottomLeft"),
|
||||
value: "bottom-left",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.topRight"),
|
||||
value: "top-right",
|
||||
},
|
||||
{
|
||||
name: t("widgets.settings.appearance.positions.topLeft"),
|
||||
value: "top-left",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-6">
|
||||
<InputImage name="logo" title={t("shared.logo")} defaultValue={item.appearance.logo || ""} />
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-3">
|
||||
<InputMultipleText
|
||||
name="hiddenInUrls[]"
|
||||
title={t("widgets.settings.appearance.hideInUrls")}
|
||||
value={item.appearance.hiddenInUrls}
|
||||
onChange={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
hiddenInUrls: e.map((i) => {
|
||||
i = i.trim();
|
||||
return "/" + UrlUtils.slugify(i);
|
||||
}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("widgets.settings.appearance.hideInUrlsPlaceholder")}
|
||||
separator="Enter"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-3">
|
||||
<InputMultipleText
|
||||
name="visibleInUrls[]"
|
||||
title={t("widgets.settings.appearance.onlyShowInUrls")}
|
||||
value={item.appearance.visibleInUrls}
|
||||
onChange={(e) => {
|
||||
setItem({
|
||||
...item,
|
||||
appearance: {
|
||||
...item.appearance,
|
||||
visibleInUrls: e.map((i) => {
|
||||
i = i.trim();
|
||||
return "/" + UrlUtils.slugify(i);
|
||||
}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
placeholder={t("widgets.settings.appearance.onlyShowInUrlsPlaceholder")}
|
||||
separator="Enter"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<ButtonPrimary type="submit">{t("shared.save")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
{/*Separator */}
|
||||
<div className="block">
|
||||
<div className="py-5">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("settings.danger.title")} description={t("settings.danger.description")}>
|
||||
<div className="mt-12 space-y-2 md:col-span-2 md:mt-0">
|
||||
<div>
|
||||
<InputText title={t("widgets.settings.danger.confirmDelete", { text: textToType })} value={typeToConfirm} setValue={setTypeToConfirm} />
|
||||
</div>
|
||||
<div>
|
||||
<ButtonPrimary
|
||||
disabled={typeToConfirm !== textToType || isDeleting}
|
||||
className={clsx(isDeleting && "base-spinner")}
|
||||
destructive={true}
|
||||
onClick={onDelete}
|
||||
>
|
||||
{t("shared.delete")}
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} destructive onYes={onConfirmDelete} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, Link, useParams, useSubmit } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import JsonPropertyValueCell from "~/modules/jsonProperties/components/JsonPropertyValueCell";
|
||||
import JsonPropertyValuesInput from "~/modules/jsonProperties/components/JsonPropertyValuesInput";
|
||||
import JsonPropertiesUtils from "~/modules/jsonProperties/utils/JsonPropertiesUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { WidgetDto } from "~/modules/widgets/dtos/WidgetDto";
|
||||
import WidgetUtils from "~/modules/widgets/utils/WidgetUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { AppConfiguration, getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { defaultTheme } from "~/utils/theme/defaultThemes";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
type LoaderData = {
|
||||
items: WidgetDto[];
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.view", tenantId);
|
||||
const data: LoaderData = {
|
||||
items: (await db.widget.findMany({ where: { tenantId } })).map((f) => WidgetUtils.toDto(f)),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "create") {
|
||||
const name = form.get("name")?.toString() || "";
|
||||
const metadata = JsonPropertiesUtils.getValuesFromForm({
|
||||
form,
|
||||
properties: appConfiguration.widgets?.metadata || [],
|
||||
prefix: "metadata",
|
||||
});
|
||||
const existing = await db.widget.findUnique({
|
||||
where: {
|
||||
tenantId_name: { tenantId, name },
|
||||
},
|
||||
});
|
||||
if (existing) {
|
||||
return Response.json({ error: t("widgets.errors.nameAlreadyTaken") }, { status: 400 });
|
||||
}
|
||||
const appearance: WidgetDto["appearance"] = {
|
||||
logo: null,
|
||||
theme: defaultTheme,
|
||||
mode: "light",
|
||||
position: "bottom-right",
|
||||
hiddenInUrls: [],
|
||||
visibleInUrls: [],
|
||||
};
|
||||
const item = await db.widget.create({
|
||||
data: {
|
||||
name,
|
||||
tenantId,
|
||||
metadata: JSON.stringify(metadata),
|
||||
appearance: JSON.stringify(appearance),
|
||||
},
|
||||
});
|
||||
return redirect(UrlUtils.getModulePath(params, `widgets/${item.id}`));
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration } = useRootData();
|
||||
const params = useParams();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const [addingWidget, setAddingWidget] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData?.error);
|
||||
} else if (actionData?.success) {
|
||||
toast.success(actionData?.success);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={t("widgets.plural")}
|
||||
buttons={
|
||||
<>
|
||||
<ButtonPrimary onClick={() => setAddingWidget(true)}>{t("shared.new")}</ButtonPrimary>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.edit"),
|
||||
onClickRoute(idx, item) {
|
||||
return UrlUtils.getModulePath(params, `widgets/${item.id}`);
|
||||
},
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
title: t("shared.title"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<Link to={UrlUtils.getModulePath(params, `widgets/${item.id}`)} className="font-medium hover:underline">
|
||||
{item.name}
|
||||
</Link>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
...(appConfiguration.widgets.metadata
|
||||
?.filter((f) => !f.hideInTable)
|
||||
.map((f) => ({
|
||||
name: f.name,
|
||||
title: f.title,
|
||||
value: (item: WidgetDto) => {
|
||||
return <JsonPropertyValueCell property={f} value={item.metadata ? item.metadata[f.name] : null} />;
|
||||
},
|
||||
})) || []),
|
||||
{
|
||||
title: t("widgets.appearance"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
<ShowPayloadModalButton description={t("widgets.appearance")} payload={JSON.stringify(item.appearance)} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("shared.created"),
|
||||
value: (item) => <DateCell date={item.createdAt} />,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
|
||||
<AddWidgetModal appConfiguration={appConfiguration} open={addingWidget} onClose={() => setAddingWidget(false)} />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function AddWidgetModal({ appConfiguration, open, onClose }: { appConfiguration: AppConfiguration; open: boolean; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [state, setState] = useState({ name: "" });
|
||||
|
||||
return (
|
||||
<Modal open={open} setOpen={onClose} size="md">
|
||||
<Form method="post" className="inline-block w-full overflow-hidden bg-white p-1 text-left align-bottom sm:align-middle">
|
||||
<input type="hidden" name="action" value="create" readOnly hidden />
|
||||
<div className="mt-3 text-center sm:mt-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("widgets.create")}</h3>
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
<InputText
|
||||
title={t("shared.name")}
|
||||
value={state.name}
|
||||
setValue={(e) => setState({ ...state, name: e.toString() })}
|
||||
type="text"
|
||||
name="name"
|
||||
id="name"
|
||||
placeholder={t("shared.name")}
|
||||
required
|
||||
/>
|
||||
<JsonPropertyValuesInput attributes={{}} prefix="metadata" properties={appConfiguration.widgets.metadata || []} />
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
|
||||
<button
|
||||
type="submit"
|
||||
className={clsx(
|
||||
"inline-flex w-full justify-center rounded-md border border-transparent px-4 py-2 text-base font-medium text-white shadow-sm focus:ring-2 focus:ring-offset-2 focus:outline-none sm:col-start-2 sm:text-sm",
|
||||
"bg-foreground text-background"
|
||||
)}
|
||||
>
|
||||
{t("shared.create")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="border-border hover:bg-secondary text-muted-foreground mt-3 inline-flex w-full justify-center rounded-md border bg-white px-4 py-2 text-base font-medium shadow-sm focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 focus:outline-none sm:col-start-1 sm:mt-0 sm:text-sm"
|
||||
onClick={onClose}
|
||||
>
|
||||
{t("shared.back")}
|
||||
</button>
|
||||
</div>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
|
||||
const widgetsRouteDirectory = resolveRepoPath("apps/web/app/routes/app.$tenant/__widgets/widgets");
|
||||
|
||||
function readRoute(fileName: string) {
|
||||
return fs.readFileSync(path.join(widgetsRouteDirectory, fileName), "utf8");
|
||||
}
|
||||
|
||||
describe("tenant widget route auth boundaries", () => {
|
||||
it("requires tenant auth and permissions before listing or creating widgets", () => {
|
||||
const source = readRoute("index.tsx");
|
||||
|
||||
expect(source).toContain('import { requireAuth } from "~/utils/loaders.middleware";');
|
||||
expect(source).toMatch(/export const loader[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.view", tenantId\);/);
|
||||
expect(source).toMatch(/export const action[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.update", tenantId\);/);
|
||||
});
|
||||
|
||||
it("requires tenant auth and tenant-scopes widget mutations by id and tenant", () => {
|
||||
const source = readRoute("$id.tsx");
|
||||
|
||||
expect(source).toContain('import { requireAuth } from "~/utils/loaders.middleware";');
|
||||
expect(source).toMatch(/export const loader[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.view", tenantId\);/);
|
||||
expect(source).toMatch(/export const action[\s\S]*?await requireAuth\(\{ request, params \}\);[\s\S]*?await verifyUserHasPermission\(request, "app\.settings\.account\.update", tenantId\);/);
|
||||
expect(source).toContain("findFirst({\n where: { id: params.id, tenantId },");
|
||||
expect(source).toContain("updateMany({\n where: { id: item.id, tenantId },");
|
||||
expect(source).toContain("deleteMany({\n where: { id: item.id, tenantId },");
|
||||
expect(source).not.toContain("db.widget.update({");
|
||||
expect(source).not.toContain("db.widget.delete({");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowEngineApi } from "~/modules/workflowEngine/routes/workflow-engine.api.server";
|
||||
import WorkflowEngineView from "~/modules/workflowEngine/routes/workflow-engine.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowEngineApi.loader(args);
|
||||
// export const action = (args: ActionFunctionArgs) => WorkflowEngineApi.action(args);
|
||||
|
||||
export default () => <WorkflowEngineView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdExecutionsApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.executions.api.server";
|
||||
import WorkflowsIdExecutionsView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.executions.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdExecutionsApi.loader(args);
|
||||
// export const action = (args: ActionFunctionArgs) => WorkflowsIdExecutionsApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdExecutionsView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdRunApiApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.api.server";
|
||||
import WorkflowsIdRunApiApiView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.api.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdRunApiApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIdRunApiApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdRunApiApiView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdRunManualApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.manual.api.server";
|
||||
import WorkflowsIdRunManualView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.manual.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdRunManualApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIdRunManualApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdRunManualView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { workflowExecutionStreamLoader } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.stream.$executionId.server";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => workflowExecutionStreamLoader(args);
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdRunStreamApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.stream.api.server";
|
||||
import WorkflowsIdRunStreamView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.run.stream.view";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
|
||||
export const meta: v2MetaFunction<WorkflowsIdRunStreamApi.LoaderData> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdRunStreamApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIdRunStreamApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdRunStreamView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIdIndexApi } from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.index.api.server";
|
||||
import WorkflowsIdIndexView from "~/modules/workflowEngine/routes/workflow-engine/__workflow/workflows.$id.index.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIdIndexApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIdIndexApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIdIndexView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsCredentialsApi } from "~/modules/workflowEngine/routes/workflow-engine/credentials.api.server";
|
||||
import WorkflowsCredentialsView from "~/modules/workflowEngine/routes/workflow-engine/credentials.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsCredentialsApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsCredentialsApi.action(args);
|
||||
|
||||
export default () => <WorkflowsCredentialsView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsCredentialsNewApi } from "~/modules/workflowEngine/routes/workflow-engine/credentials/credentials.new.api.server";
|
||||
import WorkflowsCredentialsNewView from "~/modules/workflowEngine/routes/workflow-engine/credentials/credentials.new.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsCredentialsNewApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsCredentialsNewApi.action(args);
|
||||
|
||||
export default () => <WorkflowsCredentialsNewView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsDangerApi } from "~/modules/workflowEngine/routes/workflow-engine/danger.api.server";
|
||||
import WorkflowsDangerView from "~/modules/workflowEngine/routes/workflow-engine/danger.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsDangerApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsDangerApi.action(args);
|
||||
|
||||
export default () => <WorkflowsDangerView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsExecutionsApi } from "~/modules/workflowEngine/routes/workflow-engine/executions.api.server";
|
||||
import WorkflowsExecutionsView from "~/modules/workflowEngine/routes/workflow-engine/executions.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsExecutionsApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsExecutionsApi.action(args);
|
||||
|
||||
export default () => <WorkflowsExecutionsView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowEngineIndexApi } from "~/modules/workflowEngine/routes/workflow-engine/index.api.server";
|
||||
import WorkflowEngineIndexView from "~/modules/workflowEngine/routes/workflow-engine/index.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowEngineIndexApi.loader(args);
|
||||
// export const action = (args: ActionFunctionArgs) => WorkflowEngineIndexApi.action(args);
|
||||
|
||||
export default () => <WorkflowEngineIndexView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsTemplatesApi } from "~/modules/workflowEngine/routes/workflow-engine/templates.api.server";
|
||||
import WorkflowsTemplatesView from "~/modules/workflowEngine/routes/workflow-engine/templates.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsTemplatesApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsTemplatesApi.action(args);
|
||||
|
||||
export default () => <WorkflowsTemplatesView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsVariablesApi } from "~/modules/workflowEngine/routes/workflow-engine/variables.api.server";
|
||||
import WorkflowsVariablesView from "~/modules/workflowEngine/routes/workflow-engine/variables.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsVariablesApi.loader(args);
|
||||
// export const action = (args: ActionFunctionArgs) => WorkflowsVariablesApi.action(args);
|
||||
|
||||
export default () => <WorkflowsVariablesView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsVariablesIdApi } from "~/modules/workflowEngine/routes/workflow-engine/variables/variables.$id.api.server";
|
||||
import WorkflowsVariablesIdView from "~/modules/workflowEngine/routes/workflow-engine/variables/variables.$id.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsVariablesIdApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsVariablesIdApi.action(args);
|
||||
|
||||
export default () => <WorkflowsVariablesIdView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsVariablesNewApi } from "~/modules/workflowEngine/routes/workflow-engine/variables/variables.new.api.server";
|
||||
import WorkflowsVariablesNewView from "~/modules/workflowEngine/routes/workflow-engine/variables/variables.new.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsVariablesNewApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsVariablesNewApi.action(args);
|
||||
|
||||
export default () => <WorkflowsVariablesNewView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { WorkflowsIndexApi } from "~/modules/workflowEngine/routes/workflow-engine/workflows.index.api.server";
|
||||
import WorkflowsIndexView from "~/modules/workflowEngine/routes/workflow-engine/workflows.index.view";
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => WorkflowsIndexApi.loader(args);
|
||||
export const action = (args: ActionFunctionArgs) => WorkflowsIndexApi.action(args);
|
||||
|
||||
export default () => <WorkflowsIndexView />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import AddressBookIcon from "~/components/ui/icons/crm/AddressBookIcon";
|
||||
import AddressBookIconFilled from "~/components/ui/icons/crm/AddressBookIconFilled";
|
||||
import CompanyIcon from "~/components/ui/icons/crm/CompanyIcon";
|
||||
import CompanyIconFilled from "~/components/ui/icons/crm/CompanyIconFilled";
|
||||
import FormIcon from "~/components/ui/icons/crm/FormIcon";
|
||||
import FormIconFilled from "~/components/ui/icons/crm/FormIconFilled";
|
||||
import IncreaseIcon from "~/components/ui/icons/crm/IncreaseIcon";
|
||||
import IncreaseIconFilled from "~/components/ui/icons/crm/IncreaseIconFilled";
|
||||
import UsDollarCircled from "~/components/ui/icons/crm/UsDollarCircled";
|
||||
import UsDollarCircledFilled from "~/components/ui/icons/crm/UsDollarCircledFilled";
|
||||
import SidebarIconsLayout, { IconDto } from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import CrmService, { CrmConfigurationError } from "~/modules/crm/services/CrmService";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { featureKeys } from "@toolctrl/entitlements";
|
||||
import { requireTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
|
||||
import { translateEntityTitlePlural } from "~/utils/i18n/translateLabel";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireTenantProductAccess({ request, params, featureKey: featureKeys.crmBasic });
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: t("pages.adminCrm.metaTitle", { appName: process.env.APP_NAME }),
|
||||
};
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
try {
|
||||
await CrmService.validate(tenantId);
|
||||
} catch (error) {
|
||||
if (error instanceof CrmConfigurationError) {
|
||||
throw new Response(t("crm.newsletter.errors.integrationMissing"), { status: 503 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
const items: IconDto[] = [
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
href: UrlUtils.getModulePath(params, "crm"),
|
||||
exact: true,
|
||||
icon: <IncreaseIcon className="h-5 w-5" />,
|
||||
iconSelected: <IncreaseIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
];
|
||||
["opportunities", "companies", "contacts"].forEach((slug) => {
|
||||
const entity = appOrAdminData.entities.find((x) => x.slug === slug);
|
||||
if (entity) {
|
||||
items.push({
|
||||
name: translateEntityTitlePlural(t, i18n, entity),
|
||||
href: UrlUtils.getModulePath(params, `crm/${slug}`),
|
||||
icon: getIcons(entity.slug)?.icon,
|
||||
iconSelected: getIcons(entity.slug)?.iconSelected,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function getIcons(entitySlug: string) {
|
||||
if (entitySlug === "opportunities") {
|
||||
return {
|
||||
icon: <UsDollarCircled className="h-5 w-5" />,
|
||||
iconSelected: <UsDollarCircledFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "companies") {
|
||||
return {
|
||||
icon: <CompanyIcon className="h-5 w-5" />,
|
||||
iconSelected: <CompanyIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "contacts") {
|
||||
return {
|
||||
icon: <AddressBookIcon className="h-5 w-5" />,
|
||||
iconSelected: <AddressBookIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
} else if (entitySlug === "submissions") {
|
||||
return {
|
||||
icon: <FormIcon className="h-5 w-5" />,
|
||||
iconSelected: <FormIconFilled className="h-5 w-5" />,
|
||||
};
|
||||
}
|
||||
}
|
||||
return (
|
||||
<SidebarIconsLayout label={{ align: "right" }} items={items}>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowNewRoute from "~/modules/rows/components/RowNewRoute";
|
||||
import { Rows_New } from "~/modules/rows/routes/Rows_New.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_New.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_New.action(args);
|
||||
|
||||
export default () => <RowNewRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Relationships } from "~/modules/rows/routes/Rows_Relationships.server";
|
||||
import RowsRelationshipsRoute from "~/modules/rows/components/RowsRelationshipsRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Relationships.loader(args);
|
||||
|
||||
export default () => <RowsRelationshipsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowsViewRoute from "~/modules/rows/components/RowsViewRoute";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_List.LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
return (
|
||||
<RowsViewRoute
|
||||
key={data.rowsData.entity.id}
|
||||
rowsData={data.rowsData}
|
||||
items={data.rowsData.items}
|
||||
routes={data.routes}
|
||||
saveCustomViews={true}
|
||||
permissions={{
|
||||
create: getUserHasPermission(appOrAdminData, getEntityPermission(data.rowsData.entity, "create")),
|
||||
}}
|
||||
currentSession={{
|
||||
user: appOrAdminData.user,
|
||||
isSuperAdmin: appOrAdminData.isSuperAdmin,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { PlusIcon } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import RowsList from "~/components/entities/rows/RowsList";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import CrmService, { CrmSummaryDto } from "~/modules/crm/services/CrmService";
|
||||
import { EntitiesApi } from "~/utils/api/.server/EntitiesApi";
|
||||
import { RowDisplayDefaultProperty } from "~/utils/helpers/PropertyHelper";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
summary: CrmSummaryDto;
|
||||
routes: EntitiesApi.Routes;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const data: LoaderData = {
|
||||
title: t("pages.adminCrm.metaTitle", { appName: process.env.APP_NAME }),
|
||||
summary: await CrmService.getSummary(tenantId),
|
||||
routes: EntitiesApi.getNoCodeRoutes({ request, params }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const params = useParams();
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-foreground text-lg leading-6 font-medium">{t("shared.overview")}</h3>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-3">
|
||||
<Link
|
||||
to={UrlUtils.getModulePath(params, "crm/companies")}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.companies")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.companies, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={UrlUtils.getModulePath(params, "crm/contacts")}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">{t("pages.adminCrm.contacts")}</dt>
|
||||
<dd className="text-foreground mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.contacts, { maximumFractionDigits: 0 })}</dd>
|
||||
</Link>
|
||||
<Link
|
||||
to={UrlUtils.getModulePath(params, "crm/opportunities")}
|
||||
className="hover:bg-secondary bg-background border-border overflow-hidden rounded-lg border px-4 py-3 shadow-xs"
|
||||
>
|
||||
<dt className="text-muted-foreground flex items-center space-x-2 truncate text-xs font-medium uppercase">
|
||||
<ColorBadge color={Colors.GREEN} />
|
||||
<div>{t("pages.adminCrm.opportunities")}</div>
|
||||
</dt>
|
||||
<dd className="text-foreground mt-1 flex items-baseline space-x-1 truncate text-2xl font-semibold">
|
||||
<div>{formatters.currency(data.summary.opportunities.value, "USD", { maximumFractionDigits: 0 })}</div>
|
||||
<div className="text-muted-foreground text-xs font-normal lowercase">
|
||||
{t("pages.adminCrm.openOpportunitiesCount", {
|
||||
count: data.summary.opportunities.count,
|
||||
formattedCount: formatters.number(data.summary.opportunities.count, { maximumFractionDigits: 0 }),
|
||||
})}
|
||||
</div>
|
||||
</dd>
|
||||
</Link>
|
||||
</dl>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-muted-foreground text-sm font-medium">{t("pages.adminCrm.opportunities")}</h3>
|
||||
<Link
|
||||
to={UrlUtils.getModulePath(params, "crm/opportunities/new")}
|
||||
aria-label={t("pages.adminCrm.createOpportunity")}
|
||||
className="text-foreground bg-secondary hover:bg-secondary/90 inline-flex min-h-10 min-w-10 items-center justify-center rounded-full p-2 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-600"
|
||||
>
|
||||
<PlusIcon className="h-5 w-5" aria-hidden="true" />
|
||||
</Link>
|
||||
</div>
|
||||
<RowsList
|
||||
view="board"
|
||||
entity="opportunity"
|
||||
items={data.summary.data.openOpportunities}
|
||||
readOnly={true}
|
||||
columns={[
|
||||
{ name: "name", title: t("pages.adminCrm.columns.name"), visible: true },
|
||||
{ name: "value", title: t("pages.adminCrm.columns.value"), visible: true },
|
||||
{ name: "expectedCloseDate", title: t("pages.adminCrm.columns.expectedCloseDate"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_AT, title: t("shared.createdAt"), visible: true },
|
||||
{ name: RowDisplayDefaultProperty.CREATED_BY, title: t("shared.createdBy"), visible: true },
|
||||
]}
|
||||
routes={data.routes}
|
||||
onClickRoute={(i) => UrlUtils.getModulePath(params, `crm/opportunities/${i.id}`)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import React from "react";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import DashboardRoute, { loader } from "./dashboard";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getAppDashboardStats } from "~/utils/services/appDashboardService";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { loadDashboardData } from "~/utils/data/useDashboardData";
|
||||
import PeriodHelper from "~/utils/helpers/PeriodHelper";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { loadAppData } from "~/utils/data/.server/appData";
|
||||
import { evaluateDashboardModuleGates, type DashboardModuleGateDecision } from "~/services/dashboard-registry/gating.server";
|
||||
import { getDashboardModuleDefinitions, type DashboardModuleDefinition, type DashboardModuleId } from "~/services/dashboard-registry/registry.server";
|
||||
|
||||
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 stats = [{ name: "Contacts", stat: "7", previousStat: "3" }];
|
||||
const dashboardData = { users: 4 };
|
||||
const registryModules = getDashboardModuleDefinitions();
|
||||
const getRegistryModule = (moduleId: DashboardModuleId): DashboardModuleDefinition => {
|
||||
const module = registryModules.find((definition) => definition.id === moduleId);
|
||||
if (!module) {
|
||||
throw new Error(`Missing dashboard registry module in test fixture: ${moduleId}`);
|
||||
}
|
||||
return module;
|
||||
};
|
||||
const summaryModule = getRegistryModule("summary-stats");
|
||||
const featureGatedModule = getRegistryModule("subscription-health");
|
||||
const planGatedModule = getRegistryModule("priority-insights");
|
||||
let routeLoaderData: unknown;
|
||||
let moduleDecisions: DashboardModuleGateDecision[] = [
|
||||
{ module: summaryModule, allowed: true },
|
||||
{
|
||||
module: planGatedModule,
|
||||
allowed: false,
|
||||
diagnostic: { moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/appDashboardService", () => ({
|
||||
getAppDashboardStats: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
getTenant: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useDashboardData", () => ({
|
||||
loadDashboardData: vi.fn(),
|
||||
useDashboardData: vi.fn(() => ({ users: 4 })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PeriodHelper", () => ({
|
||||
default: { getGreaterThanOrEqualsFromRequest: vi.fn() },
|
||||
defaultPeriodFilter: "30d",
|
||||
PeriodFilters: [],
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
|
||||
createMetrics: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/.server/appData", () => ({
|
||||
loadAppData: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/services/dashboard-registry/gating.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/services/dashboard-registry/gating.server")>();
|
||||
return {
|
||||
...actual,
|
||||
evaluateDashboardModuleGates: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({
|
||||
serverTimingHeaders: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/app/ProfileBanner", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/stats/DashboardStats", () => ({
|
||||
DashboardStats: ({ items }: { items: Array<{ name: string; stat: string }> }) => (
|
||||
<dl>
|
||||
{items.map((item) => (
|
||||
<div key={item.name}>
|
||||
<dt>{item.name}</dt>
|
||||
<dd>{item.stat}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/input/InputSelect", () => ({
|
||||
default: ({ value }: { value: string }) => <div aria-label="period-filter">{value}</div>,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/errors/ServerError", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAppData", () => ({
|
||||
useAppData: vi.fn(() => ({ user: {}, permissions: ["app.dashboard.view"] })),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/PermissionsHelper", () => ({
|
||||
getUserHasPermission: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
|
||||
}));
|
||||
|
||||
describe("app tenant dashboard route contract", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.APP_NAME = "ToolCTRL";
|
||||
vi.mocked(getTranslations).mockResolvedValue({ t: translatedT } as never);
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
|
||||
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
stats,
|
||||
modules: [summaryModule],
|
||||
moduleDiagnostics: [],
|
||||
};
|
||||
moduleDecisions = [
|
||||
{ module: summaryModule, allowed: true },
|
||||
{
|
||||
module: planGatedModule,
|
||||
allowed: false,
|
||||
diagnostic: { moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" },
|
||||
},
|
||||
];
|
||||
vi.mocked(loadAppData).mockResolvedValue(appData as never);
|
||||
vi.mocked(evaluateDashboardModuleGates).mockResolvedValue(moduleDecisions as never);
|
||||
vi.mocked(getAppDashboardStats).mockResolvedValue(stats as never);
|
||||
vi.mocked(loadDashboardData).mockResolvedValue(dashboardData as never);
|
||||
vi.mocked(PeriodHelper.getGreaterThanOrEqualsFromRequest).mockReturnValue(computedGte);
|
||||
vi.mocked(createMetrics).mockResolvedValue({
|
||||
time: async <T,>(value: T | Promise<T>) => value,
|
||||
getServerTimingHeader: () => ({ "Server-Timing": "app.dashboard;dur=1" }),
|
||||
} as never);
|
||||
});
|
||||
|
||||
it("passes tenant, translations, and the computed period boundary into the KPI service while preserving loader data", async () => {
|
||||
const request = new Request("https://example.com/acme/dashboard?period=month");
|
||||
const params = { tenant: "acme" };
|
||||
|
||||
const response = (await loader({ request, params, context: {}, unstable_pattern: "app.$tenant/dashboard" })) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(requireAuth).toHaveBeenCalledWith({ request, params });
|
||||
expect(getTranslations).toHaveBeenCalledWith(request);
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(loadAppData).toHaveBeenCalledWith({ request, params, t: translatedT, time: expect.any(Function) });
|
||||
expect(getTenant).toHaveBeenCalledWith("tenant_1");
|
||||
expect(PeriodHelper.getGreaterThanOrEqualsFromRequest).toHaveBeenCalledWith({ request });
|
||||
expect(getAppDashboardStats).toHaveBeenCalledWith({ t: translatedT, tenant, gte: computedGte });
|
||||
expect(loadDashboardData).toHaveBeenCalledWith({ request, params });
|
||||
expect(evaluateDashboardModuleGates).toHaveBeenCalledWith({
|
||||
request,
|
||||
params,
|
||||
subscription: appData.mySubscription,
|
||||
redirectPaths: {
|
||||
"feature-flag": "/feature-disabled?tenant=acme",
|
||||
plan: "/plan-required/acme",
|
||||
},
|
||||
});
|
||||
expect(vi.mocked(evaluateDashboardModuleGates).mock.calls[0]?.[0].redirectPaths?.plan).toBe("/plan-required/acme");
|
||||
expect(body).toMatchObject({
|
||||
title: "translated:app.sidebar.dashboard | ToolCTRL",
|
||||
users: 4,
|
||||
stats,
|
||||
modules: [summaryModule],
|
||||
moduleDiagnostics: [moduleDecisions[1].diagnostic],
|
||||
});
|
||||
expect(body.modules.map((module: DashboardModuleDefinition) => module.id)).toEqual(["summary-stats"]);
|
||||
expect(body.moduleDiagnostics.map((diagnostic: { moduleId: DashboardModuleId }) => diagnostic.moduleId)).toEqual(["priority-insights"]);
|
||||
expect(response.headers.get("Server-Timing")).toBe("app.dashboard;dur=1");
|
||||
});
|
||||
|
||||
it("returns a localized 404 when the tenant is not found", async () => {
|
||||
vi.mocked(getTenant).mockResolvedValue(null);
|
||||
const request = new Request("https://example.com/acme/dashboard");
|
||||
const params = { tenant: "acme" };
|
||||
|
||||
try {
|
||||
await loader({ request, params, context: {}, unstable_pattern: "app.$tenant/dashboard" });
|
||||
throw new Error("Expected loader to throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(Response);
|
||||
expect((error as Response).status).toBe(404);
|
||||
await expect((error as Response).json()).resolves.toEqual({ error: "translated:app.dashboard.errors.tenantNotFound" });
|
||||
}
|
||||
});
|
||||
|
||||
it("renders the allowed summary registry module with the existing dashboard stats", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<DashboardRoute />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("heading", { name: "app.dashboard.summary" })).toBeInTheDocument();
|
||||
expect(screen.getByText("Contacts")).toBeInTheDocument();
|
||||
expect(screen.getByText("7")).toBeInTheDocument();
|
||||
expect(screen.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("omits gated summary content when the summary module is feature-disabled", () => {
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
stats,
|
||||
modules: [],
|
||||
moduleDiagnostics: [{ moduleId: "summary-stats", source: "feature-flag", reason: "feature-disabled", redirectPath: "/feature-disabled?tenant=acme" }],
|
||||
};
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<DashboardRoute />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
it("renders plan-required diagnostics with the safe tenant-aware plan link and no gated module content", () => {
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
stats,
|
||||
modules: [summaryModule],
|
||||
moduleDiagnostics: [{ moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" }],
|
||||
};
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<DashboardRoute />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByText("app.dashboard.moduleDiagnostics.planRequiredTitle")).toBeInTheDocument();
|
||||
expect(screen.getByText("app.dashboard.moduleDiagnostics.planRequiredDescription")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "app.dashboard.moduleDiagnostics.viewPlanOptions" })).toHaveAttribute("href", "/plan-required/acme");
|
||||
expect(screen.queryByText(planGatedModule.titleKey)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders feature-disabled diagnostics with only the safe fallback link and no gated module content", () => {
|
||||
routeLoaderData = {
|
||||
...dashboardData,
|
||||
stats,
|
||||
modules: [summaryModule],
|
||||
moduleDiagnostics: [
|
||||
{ moduleId: "subscription-health", source: "feature-flag", reason: "feature-disabled", redirectPath: "https://unsafe.example.com/feature" },
|
||||
],
|
||||
};
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<DashboardRoute />
|
||||
</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(featureGatedModule.titleKey)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps loader diagnostics redacted from tenant, user, subscription, provider, token, and raw feature inputs", async () => {
|
||||
moduleDecisions = [
|
||||
{ module: summaryModule, allowed: true },
|
||||
{
|
||||
module: featureGatedModule,
|
||||
allowed: false,
|
||||
diagnostic: { moduleId: "subscription-health", source: "feature-flag", reason: "feature-disabled", redirectPath: "/feature-disabled" },
|
||||
},
|
||||
{
|
||||
module: planGatedModule,
|
||||
allowed: false,
|
||||
diagnostic: { moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" },
|
||||
},
|
||||
];
|
||||
vi.mocked(evaluateDashboardModuleGates).mockResolvedValue(moduleDecisions as never);
|
||||
|
||||
const response = (await loader({
|
||||
request: new Request(
|
||||
"https://example.com/acme/dashboard?tenantId=tenant_1&userId=user_123&subscriptionId=sub_123&providerKey=pk_live_secret&token=tok_secret&rawFeature=billing.enterprise.secret_feature"
|
||||
),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/dashboard",
|
||||
})) as Response;
|
||||
const body = await response.json();
|
||||
const diagnosticPayload = JSON.stringify(body.moduleDiagnostics);
|
||||
|
||||
expect(body.modules).toEqual([summaryModule]);
|
||||
expect(body.moduleDiagnostics).toEqual([moduleDecisions[1].diagnostic, moduleDecisions[2].diagnostic]);
|
||||
expect(body.moduleDiagnostics.map((diagnostic: { moduleId: DashboardModuleId }) => diagnostic.moduleId)).toEqual([
|
||||
"subscription-health",
|
||||
"priority-insights",
|
||||
]);
|
||||
expect(diagnosticPayload).not.toContain("tenant_1");
|
||||
expect(diagnosticPayload).not.toContain("user_123");
|
||||
expect(diagnosticPayload).not.toContain("sub_123");
|
||||
expect(diagnosticPayload).not.toContain("pk_live_secret");
|
||||
expect(diagnosticPayload).not.toContain("tok_secret");
|
||||
expect(diagnosticPayload).not.toContain("billing.enterprise.secret_feature");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { Link, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useSearchParams } from "react-router";
|
||||
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";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import PeriodHelper, { defaultPeriodFilter, PeriodFilters } from "~/utils/helpers/PeriodHelper";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { Fragment } from "react";
|
||||
import { loadAppData } from "~/utils/data/.server/appData";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
import {
|
||||
evaluateDashboardModuleGates,
|
||||
getDashboardModuleDiagnostics,
|
||||
getVisibleDashboardModules,
|
||||
type DashboardModuleGateDiagnostic,
|
||||
} from "~/services/dashboard-registry/gating.server";
|
||||
import type { DashboardModuleDefinition, DashboardModuleId } from "~/services/dashboard-registry/registry.server";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = DashboardLoaderData & {
|
||||
title: string;
|
||||
stats: Stat[];
|
||||
modules: DashboardModuleDefinition[];
|
||||
moduleDiagnostics: DashboardModuleGateDiagnostic[];
|
||||
};
|
||||
|
||||
function isDashboardModuleVisible(modules: readonly DashboardModuleDefinition[], moduleId: DashboardModuleId) {
|
||||
return modules.some((module) => module.id === moduleId);
|
||||
}
|
||||
|
||||
function getSafeModuleNoticePath(diagnostic: DashboardModuleGateDiagnostic) {
|
||||
if (diagnostic.source === "plan") {
|
||||
return diagnostic.redirectPath?.startsWith("/") ? diagnostic.redirectPath : "/plan-required";
|
||||
}
|
||||
|
||||
return diagnostic.redirectPath?.startsWith("/") ? diagnostic.redirectPath : "/feature-disabled";
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "app.$tenant.dashboard");
|
||||
let { t } = await getTranslations(request);
|
||||
const { tenantId, appData } = await time(
|
||||
promiseHash({
|
||||
tenantId: getTenantIdFromUrl(params),
|
||||
appData: loadAppData({ request, params, t, time }),
|
||||
}),
|
||||
"app.$tenant.dashboard.context"
|
||||
);
|
||||
const tenant = await time(getTenant(tenantId), "getTenant");
|
||||
|
||||
if (!tenant) {
|
||||
throw Response.json({ error: t("app.dashboard.errors.tenantNotFound") }, { status: 404 });
|
||||
}
|
||||
await verifyUserHasPermission(request, "app.dashboard.view", tenantId);
|
||||
|
||||
const { stats, dashboardData, moduleDecisions } = await time(
|
||||
promiseHash({
|
||||
stats: getAppDashboardStats({ t, tenant, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) }),
|
||||
dashboardData: loadDashboardData({ request, params }),
|
||||
moduleDecisions: evaluateDashboardModuleGates({
|
||||
request,
|
||||
params,
|
||||
subscription: appData.mySubscription,
|
||||
redirectPaths: {
|
||||
"feature-flag": `/feature-disabled?tenant=${encodeURIComponent(tenant.slug)}`,
|
||||
plan: appTenantPlanRequiredPath({ tenant: tenant.slug }),
|
||||
},
|
||||
}),
|
||||
}),
|
||||
"app.$tenant.dashboard.details"
|
||||
);
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("app.sidebar.dashboard")} | ${process.env.APP_NAME}`,
|
||||
...dashboardData,
|
||||
stats,
|
||||
modules: getVisibleDashboardModules(moduleDecisions),
|
||||
moduleDiagnostics: getDashboardModuleDiagnostics(moduleDecisions),
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
export default function DashboardRoute() {
|
||||
const { t } = useTranslation();
|
||||
const appData = useAppData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const canViewSummary = isDashboardModuleVisible(data.modules, "summary-stats");
|
||||
|
||||
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">
|
||||
{getUserHasPermission(appData, "app.dashboard.view") ? (
|
||||
<Fragment>
|
||||
{canViewSummary && data.stats.length > 0 && (
|
||||
<div className="space-y-3 truncate p-1">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<h3 className="text-foreground grow leading-4 font-medium">{t("app.dashboard.summary")}</h3>
|
||||
<div>
|
||||
<InputSelect
|
||||
className="w-44"
|
||||
name="period"
|
||||
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
|
||||
options={PeriodFilters.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: t(f.name),
|
||||
};
|
||||
})}
|
||||
setValue={(value) => {
|
||||
if (value) {
|
||||
searchParams.set("period", value?.toString() ?? "");
|
||||
} else {
|
||||
searchParams.delete("period");
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DashboardStats items={data.stats} />
|
||||
</div>
|
||||
)}
|
||||
{data.moduleDiagnostics.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{data.moduleDiagnostics.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>
|
||||
<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")}
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
) : (
|
||||
<div className="font-medium">{t("app.dashboard.noPermission")}</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Outlet, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import 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 CrmService from "~/modules/crm/services/CrmService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { featureKeys } from "@toolctrl/entitlements";
|
||||
import { requireTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await requireTenantProductAccess({ request, params, featureKey: featureKeys.emailMarketing });
|
||||
const data: LoaderData = {
|
||||
title: `${t("emailMarketing:title")} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
await CrmService.validate(tenantId);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t } = useTranslation();
|
||||
const params = useParams();
|
||||
return (
|
||||
<SidebarIconsLayout
|
||||
label={{ align: "right" }}
|
||||
items={[
|
||||
{
|
||||
name: t("shared.overview"),
|
||||
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:campaigns"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/campaigns"),
|
||||
icon: <MegaphoneIcon className="h-5 w-5" />,
|
||||
iconSelected: <MegaphoneIconFilled className="h-5 w-5" />,
|
||||
},
|
||||
{
|
||||
name: t("emailMarketing:activity"),
|
||||
href: UrlUtils.getModulePath(params, "email-marketing/activity"),
|
||||
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" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import OutboundEmailsListRoute from "~/modules/emailMarketing/components/outboundEmails/OutboundEmailsListRoute";
|
||||
import { OutboundEmails_List } from "~/modules/emailMarketing/routes/OutboundEmails_List";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => OutboundEmails_List.loader(args);
|
||||
|
||||
export default () => <OutboundEmailsListRoute />;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsEditRoute from "~/modules/emailMarketing/components/campaigns/CampaignsEditRoute";
|
||||
import { Campaigns_Edit } from "~/modules/emailMarketing/routes/Campaigns_Edit";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Campaigns_Edit.action(args);
|
||||
|
||||
export default () => <CampaignsEditRoute />;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsListRoute from "~/modules/emailMarketing/components/campaigns/CampaignsListRoute";
|
||||
import { Campaigns_List } from "~/modules/emailMarketing/routes/Campaigns_List";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_List.loader(args);
|
||||
|
||||
export default () => <CampaignsListRoute />;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import CampaignsNewRoute from "~/modules/emailMarketing/components/campaigns/CampaignsNewRoute";
|
||||
import { Campaigns_New } from "~/modules/emailMarketing/routes/Campaigns_New";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Campaigns_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Campaigns_New.action(args);
|
||||
|
||||
export default () => <CampaignsNewRoute />;
|
||||
@@ -0,0 +1,14 @@
|
||||
import { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import EmailMarketingSummaryRoute from "~/modules/emailMarketing/components/EmailMarketingSummaryRoute";
|
||||
import { EmailMarketing_Summary } from "~/modules/emailMarketing/routes/EmailMarketing_Summary";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => EmailMarketing_Summary.loader(args);
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => <EmailMarketingSummaryRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import SendersListRoute from "~/modules/emailMarketing/components/senders/SendersListRoute";
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import { Senders_List } from "~/modules/emailMarketing/routes/Senders_List";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Senders_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Senders_List.action(args);
|
||||
|
||||
export default () => <SendersListRoute />;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import SendersEditRoute from "~/modules/emailMarketing/components/senders/SendersEditRoute";
|
||||
import { Senders_Edit } from "~/modules/emailMarketing/routes/Senders_Edit";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Senders_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Senders_Edit.action(args);
|
||||
|
||||
export default () => <SendersEditRoute />;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import SendersNewRoute from "~/modules/emailMarketing/components/senders/SendersNewRoute";
|
||||
import { Senders_New } from "~/modules/emailMarketing/routes/Senders_New";
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Senders_New.loader(args);
|
||||
export const action: ActionFunction = (args) => Senders_New.action(args);
|
||||
|
||||
export default () => <SendersNewRoute />;
|
||||
@@ -0,0 +1,264 @@
|
||||
// P4 Files (AK-P4a) §11 — File detail route. Loader builds FileDetailVM (proxy
|
||||
// URLs only, AD-23); action handles archive/reactivate/delete/regenerate +
|
||||
// audit. Not-visible / foreign file -> 404. Baseline functional UI.
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildFileDetailVM, type FileDetailVM, type FileLinkedEntity } from "@toolctrl/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { badRequestResponse, loadFilesContext, notFoundResponse, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import {
|
||||
archiveFile,
|
||||
getVisibleFileWithLinks,
|
||||
hardDeleteFile,
|
||||
linkFile,
|
||||
reactivateFile,
|
||||
regenerateFilePreview,
|
||||
unlinkFile,
|
||||
type FileEntityType,
|
||||
} from "~/utils/integrations/fileService.server";
|
||||
import { auditFileEvent, logFileActivity } from "~/utils/integrations/fileAudit.server";
|
||||
import { filesDetailPath, mediaVariantPath } from "~/utils/integrations/fileRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: FileDetailVM };
|
||||
|
||||
const FILE_ENTITY_TYPES: FileEntityType[] = [
|
||||
"contact",
|
||||
"company",
|
||||
"lead",
|
||||
"deal",
|
||||
"project",
|
||||
"user",
|
||||
"form_submission",
|
||||
"order",
|
||||
"task",
|
||||
"appointment",
|
||||
];
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadFilesContext({ request, params, requireModule: true });
|
||||
const fileId = params.id ?? "";
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
|
||||
let file, links;
|
||||
try {
|
||||
({ file, links } = await getVisibleFileWithLinks(ctx.tenantId, fileId, ctx));
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const linkedEntities: FileLinkedEntity[] = links.map((link) => ({
|
||||
entityType: link.entityType,
|
||||
entityId: link.entityId,
|
||||
linkRole: link.linkRole,
|
||||
href: null,
|
||||
}));
|
||||
|
||||
const vm = buildFileDetailVM({
|
||||
id: file.id,
|
||||
displayName: file.displayName,
|
||||
mimeType: file.mimeType,
|
||||
sizeBytes: file.sizeBytes,
|
||||
createdAtIso: file.createdAt.toISOString(),
|
||||
tags: file.tags,
|
||||
notes: file.notes,
|
||||
source: file.source,
|
||||
previewStatus: file.previewStatus as never,
|
||||
scanStatus: file.scanStatus as never,
|
||||
previewUrl: file.previewStorageKey && file.previewStatus === "ready" ? mediaVariantPath(tenantSlug, file.id, "preview") : null,
|
||||
downloadUrl: mediaVariantPath(tenantSlug, file.id, "original"),
|
||||
assignedToUserId: file.assignedToUserId,
|
||||
linkedEntities,
|
||||
canWrite: ctx.permissions.includes("files.write"),
|
||||
canDelete: ctx.permissions.includes("files.delete"),
|
||||
canAdmin: ctx.permissions.includes("files.admin"),
|
||||
});
|
||||
|
||||
return Response.json({ title: `${file.displayName} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const ctx = await loadFilesContext({ request, params, requireModule: true });
|
||||
const fileId = params.id ?? "";
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const formData = await request.formData();
|
||||
const intent = String(formData.get("intent") ?? "");
|
||||
|
||||
try {
|
||||
if (intent === "delete") {
|
||||
requireFilesPermission(ctx, "files.delete");
|
||||
await hardDeleteFile({ tenantId: ctx.tenantId, fileId });
|
||||
await auditFileEvent({ ctx, action: "file.deleted", fileId });
|
||||
return redirect(`/${tenantSlug}/files`);
|
||||
}
|
||||
requireFilesPermission(ctx, "files.write");
|
||||
if (intent === "link") {
|
||||
const entityType = String(formData.get("entityType") ?? "") as FileEntityType;
|
||||
const entityId = String(formData.get("entityId") ?? "").trim();
|
||||
const linkRole = String(formData.get("linkRole") ?? "").trim() || null;
|
||||
if (!FILE_ENTITY_TYPES.includes(entityType) || !entityId) {
|
||||
throw badRequestResponse();
|
||||
}
|
||||
await linkFile({ tenantId: ctx.tenantId, userId: ctx.userId, fileId, entityType, entityId, linkRole });
|
||||
await auditFileEvent({ ctx, action: "file.linked", fileId, metadata: { entityType, entityId } });
|
||||
await logFileActivity({ ctx, entityType, entityId, activityType: "file_uploaded", summaryText: "Datei verknüpft", fileId });
|
||||
return redirect(filesDetailPath(tenantSlug, fileId));
|
||||
}
|
||||
if (intent === "unlink") {
|
||||
const entityType = String(formData.get("entityType") ?? "") as FileEntityType;
|
||||
const entityId = String(formData.get("entityId") ?? "").trim();
|
||||
await unlinkFile({ tenantId: ctx.tenantId, fileId, entityType, entityId });
|
||||
await auditFileEvent({ ctx, action: "file.unlinked", fileId, metadata: { entityType, entityId } });
|
||||
return redirect(filesDetailPath(tenantSlug, fileId));
|
||||
}
|
||||
if (intent === "archive") {
|
||||
await archiveFile({ tenantId: ctx.tenantId, fileId });
|
||||
await auditFileEvent({ ctx, action: "file.archived", fileId });
|
||||
} else if (intent === "reactivate") {
|
||||
await reactivateFile({ tenantId: ctx.tenantId, fileId });
|
||||
await auditFileEvent({ ctx, action: "file.reactivated", fileId });
|
||||
} else if (intent === "regeneratePreview") {
|
||||
await regenerateFilePreview({ tenantId: ctx.tenantId, fileId });
|
||||
await auditFileEvent({ ctx, action: "file.updated", fileId, metadata: { previewRegenerated: true } });
|
||||
}
|
||||
return redirect(filesDetailPath(tenantSlug, fileId));
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
throw notFoundResponse();
|
||||
}
|
||||
};
|
||||
|
||||
export default function FileDetailRoute() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.detail" />;
|
||||
}
|
||||
const data = vm.data;
|
||||
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" });
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.detail">
|
||||
<h1 className="text-foreground text-xl font-semibold">{data.displayName}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">
|
||||
{data.mimeType} · {dateFormatter.format(new Date(data.createdAtIso))}
|
||||
</p>
|
||||
|
||||
{data.scanNoticeKey ? (
|
||||
<p className="text-theme-600 mt-4 text-sm" data-ui-id="ui.files.detail.scanNotice">
|
||||
{t(data.scanNoticeKey)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="mt-6" data-ui-id="ui.files.detail.preview">
|
||||
{data.previewUrl ? (
|
||||
<img src={data.previewUrl} alt={data.displayName} className="max-h-96 rounded border" />
|
||||
) : data.previewFallbackKey ? (
|
||||
<p className="text-muted-foreground text-sm">{t(data.previewFallbackKey)}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex flex-wrap gap-3">
|
||||
<a href={data.downloadUrl} className="text-theme-600 font-medium" data-ui-id="ui.files.detail.download">
|
||||
{t("files.detail.actions.download")}
|
||||
</a>
|
||||
{data.canWrite && data.canRegeneratePreview ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="regeneratePreview" />
|
||||
<button type="submit" className="text-theme-600 font-medium">
|
||||
{t("files.detail.actions.regeneratePreview")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="archive" />
|
||||
<button type="submit" className="text-theme-600 font-medium" data-ui-id="ui.files.detail.archive">
|
||||
{t("files.detail.actions.archive")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
{data.canDelete ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="delete" />
|
||||
<button type="submit" className="text-destructive font-medium" data-ui-id="ui.files.detail.delete">
|
||||
{t("files.detail.actions.delete")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{data.tags.length > 0 ? (
|
||||
<section className="mt-6">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("files.detail.section.tags")}</h2>
|
||||
<p className="mt-1 text-sm">{data.tags.join(", ")}</p>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{data.notes ? (
|
||||
<section className="mt-6">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("files.detail.section.notes")}</h2>
|
||||
<p className="mt-1 text-sm">{data.notes}</p>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<section className="mt-6" data-ui-id="ui.files.detail.links">
|
||||
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("files.detail.section.links")}</h2>
|
||||
{data.linkedEntities.length > 0 ? (
|
||||
<ul className="mt-1 text-sm">
|
||||
{data.linkedEntities.map((link) => (
|
||||
<li key={`${link.entityType}-${link.entityId}`} className="flex items-center gap-2" data-link-id={`${link.entityType}-${link.entityId}`}>
|
||||
<span>
|
||||
{link.entityType}
|
||||
{link.linkRole ? ` · ${link.linkRole}` : ""}
|
||||
</span>
|
||||
{data.canWrite ? (
|
||||
<form method="post">
|
||||
<input type="hidden" name="intent" value="unlink" />
|
||||
<input type="hidden" name="entityType" value={link.entityType} />
|
||||
<input type="hidden" name="entityId" value={link.entityId} />
|
||||
<button type="submit" className="text-muted-foreground text-xs underline">
|
||||
{t("files.detail.actions.unlink")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
{data.canWrite ? (
|
||||
<form method="post" className="mt-3 flex flex-wrap items-end gap-2" data-ui-id="ui.files.detail.linkForm">
|
||||
<input type="hidden" name="intent" value="link" />
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("files.detail.link.entityType")}</span>
|
||||
<select name="entityType" className="border-muted-foreground/40 rounded border px-2 py-1">
|
||||
{FILE_ENTITY_TYPES.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("files.detail.link.entityId")}</span>
|
||||
<input name="entityId" required className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="text-muted-foreground block text-xs">{t("files.detail.link.role")}</span>
|
||||
<input name="linkRole" className="border-muted-foreground/40 rounded border px-2 py-1" />
|
||||
</label>
|
||||
<button type="submit" className="text-theme-600 font-medium">
|
||||
{t("files.detail.actions.link")}
|
||||
</button>
|
||||
</form>
|
||||
) : null}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// P4 Files (AK-P4a) §11 — Files browser route. Loader builds the FileBrowserVM
|
||||
// once (server-side); the component only renders (DoD A). Module off -> locked
|
||||
// empty state (like walking-skeleton). Missing files.read_own -> 404.
|
||||
//
|
||||
// Baseline functional UI (data-ui-id markers for e2e); the Subframe visual polish
|
||||
// follows Davids D-P4 delta (Dev-Nachzug).
|
||||
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildFileBrowserVM, type FileBrowserRow, type FileBrowserVM } from "@toolctrl/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadFilesContext, notFoundResponse, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { listFilesForBrowser } from "~/utils/integrations/fileService.server";
|
||||
import { mediaVariantPath, filesDetailPath } from "~/utils/integrations/fileRoutePaths";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: FileBrowserVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadFilesContext({ request, params });
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
|
||||
if (!ctx.hasModule) {
|
||||
// Locked connector state: render an empty VM (no rows, no write).
|
||||
const vm = buildFileBrowserVM({
|
||||
rows: [],
|
||||
filter: { entityType: null, mimeGroup: null, tags: [], assignedToUserId: null, includeArchived: false },
|
||||
canWrite: false,
|
||||
canDelete: false,
|
||||
});
|
||||
return Response.json({ title: `${t("files.browser.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
}
|
||||
|
||||
try {
|
||||
requireFilesPermission(ctx, "files.read_own");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const includeArchived = url.searchParams.get("archived") === "1";
|
||||
const mimeGroup = url.searchParams.get("mime");
|
||||
const cursor = url.searchParams.get("cursor");
|
||||
|
||||
const { rows, nextCursor } = await listFilesForBrowser({
|
||||
tenantId: ctx.tenantId,
|
||||
ctx,
|
||||
filter: { includeArchived, mimeGroup },
|
||||
cursor,
|
||||
});
|
||||
|
||||
const canWrite = ctx.permissions.includes("files.write");
|
||||
const canDelete = ctx.permissions.includes("files.delete");
|
||||
const browserRows: FileBrowserRow[] = rows.map((file) => ({
|
||||
id: file.id,
|
||||
displayName: file.displayName,
|
||||
mimeType: file.mimeType,
|
||||
sizeBytes: file.sizeBytes,
|
||||
createdAtIso: file.createdAt.toISOString(),
|
||||
tags: file.tags,
|
||||
source: file.source,
|
||||
previewStatus: file.previewStatus as FileBrowserRow["previewStatus"],
|
||||
scanStatus: file.scanStatus as FileBrowserRow["scanStatus"],
|
||||
thumbnailUrl: file.thumbnailStorageKey && file.previewStatus === "ready" ? mediaVariantPath(tenantSlug, file.id, "thumb") : null,
|
||||
detailHref: filesDetailPath(tenantSlug, file.id),
|
||||
linkedEntityLabelKey: null,
|
||||
}));
|
||||
|
||||
const vm = buildFileBrowserVM({
|
||||
rows: browserRows,
|
||||
filter: { entityType: null, mimeGroup, tags: [], assignedToUserId: null, includeArchived },
|
||||
canWrite,
|
||||
canDelete,
|
||||
nextCursor,
|
||||
});
|
||||
|
||||
return Response.json({ title: `${t("files.browser.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData);
|
||||
};
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const units = ["KB", "MB", "GB"];
|
||||
let value = bytes / 1024;
|
||||
let unitIndex = 0;
|
||||
while (value >= 1024 && unitIndex < units.length - 1) {
|
||||
value /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
return `${value.toFixed(1)} ${units[unitIndex]}`;
|
||||
}
|
||||
|
||||
export default function FilesBrowserRoute() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.files.browser" />;
|
||||
}
|
||||
|
||||
const { rows, canWrite, emptyHeadlineKey, emptyBodyKey } = vm.data;
|
||||
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium" });
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.files.browser">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("files.browser.title")}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("files.browser.subtitle")}</p>
|
||||
</div>
|
||||
{canWrite ? (
|
||||
<a href="upload" className="text-theme-600 font-medium" data-ui-id="ui.files.browser.upload">
|
||||
{t("files.browser.actions.upload")}
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="mt-10 text-center" data-ui-id="ui.files.browser.empty">
|
||||
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
|
||||
</div>
|
||||
) : (
|
||||
<table className="mt-6 w-full text-left text-sm" data-ui-id="ui.files.browser.table">
|
||||
<thead>
|
||||
<tr className="text-muted-foreground border-b">
|
||||
<th className="py-2">{t("files.browser.column.name")}</th>
|
||||
<th className="py-2">{t("files.browser.column.size")}</th>
|
||||
<th className="py-2">{t("files.browser.column.date")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.id} className="border-b" data-row-id={row.id}>
|
||||
<td className="py-2">
|
||||
<a href={row.detailHref} className="text-theme-600">
|
||||
{row.displayName}
|
||||
</a>
|
||||
</td>
|
||||
<td className="py-2">{formatBytes(row.sizeBytes)}</td>
|
||||
<td className="py-2">{dateFormatter.format(new Date(row.createdAtIso))}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
// P4 Files (AK-P4a) §3 — chunked-upload chunk endpoint (resource route, action
|
||||
// only). The browser uploader PUTs/POSTs raw chunk bytes; we store them as a
|
||||
// temp object and track the FileUploadChunk. Gated: auth -> module -> files.write.
|
||||
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { fileActionErrorResponse, loadFilesContext, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { FILE_UPLOAD_CHUNK_SIZE_BYTES } from "@toolctrl/view-models";
|
||||
import { storeUploadChunk } from "~/utils/integrations/fileService.server";
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
try {
|
||||
if (request.method !== "POST" && request.method !== "PUT") {
|
||||
return new Response("Method Not Allowed", { status: 405 });
|
||||
}
|
||||
const ctx = requireFilesPermission(await loadFilesContext({ request, params, requireModule: true }), "files.write");
|
||||
const uploadId = params.uploadId ?? "";
|
||||
const chunkIndex = Number.parseInt(params.index ?? "", 10);
|
||||
if (!uploadId || !Number.isInteger(chunkIndex)) {
|
||||
return Response.json({ error: "files.error.invalidUploadRequest" }, { status: 400 });
|
||||
}
|
||||
const bytes = new Uint8Array(await request.arrayBuffer());
|
||||
if (bytes.byteLength === 0) {
|
||||
return Response.json({ error: "files.error.emptyChunk" }, { status: 400 });
|
||||
}
|
||||
// Defensive upper bound so a malformed client cannot stream an oversized part.
|
||||
if (bytes.byteLength > FILE_UPLOAD_CHUNK_SIZE_BYTES) {
|
||||
return Response.json({ error: "files.error.chunkTooLarge" }, { status: 400 });
|
||||
}
|
||||
const result = await storeUploadChunk({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
uploadId,
|
||||
chunkIndex,
|
||||
bytes,
|
||||
});
|
||||
return Response.json(result);
|
||||
} catch (error) {
|
||||
return fileActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
// P4 Files (AK-P4a) §3 — chunked-upload complete endpoint (resource route,
|
||||
// action only). Assembles the stored chunks into the final object, creates the
|
||||
// File row and fans out scan + preview jobs. Gated: auth -> module -> files.write.
|
||||
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { fileActionErrorResponse, loadFilesContext, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { completeUpload } from "~/utils/integrations/fileService.server";
|
||||
import { auditFileEvent } from "~/utils/integrations/fileAudit.server";
|
||||
|
||||
type CompleteBody = {
|
||||
displayName?: unknown;
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
try {
|
||||
if (request.method !== "POST") {
|
||||
return new Response("Method Not Allowed", { status: 405 });
|
||||
}
|
||||
const ctx = requireFilesPermission(await loadFilesContext({ request, params, requireModule: true }), "files.write");
|
||||
const uploadId = params.uploadId ?? "";
|
||||
if (!uploadId) {
|
||||
return Response.json({ error: "files.error.invalidUploadRequest" }, { status: 400 });
|
||||
}
|
||||
let displayName: string | undefined;
|
||||
try {
|
||||
const body = (await request.json()) as CompleteBody;
|
||||
if (typeof body.displayName === "string" && body.displayName.trim().length > 0) {
|
||||
displayName = body.displayName.trim();
|
||||
}
|
||||
} catch {
|
||||
// body is optional; ignore parse errors
|
||||
}
|
||||
const file = await completeUpload({ tenantId: ctx.tenantId, userId: ctx.userId, uploadId, displayName });
|
||||
await auditFileEvent({ ctx, action: "file.uploaded", fileId: file.id, metadata: { mimeType: file.mimeType, sizeBytes: file.sizeBytes } });
|
||||
return Response.json({ id: file.id, displayName: file.displayName });
|
||||
} catch (error) {
|
||||
return fileActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
// P4 Files (AK-P4a) §3 — chunked-upload init endpoint (resource route, action
|
||||
// only). The browser uploader POSTs the file descriptor; we validate MIME/size,
|
||||
// create a FileUpload session and return the uploadId + chunk size. Gated:
|
||||
// auth -> module (404 if off) -> files.write.
|
||||
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
import { fileActionErrorResponse, loadFilesContext, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import { createUploadSession } from "~/utils/integrations/fileService.server";
|
||||
|
||||
type InitBody = {
|
||||
originalFilename?: unknown;
|
||||
mimeType?: unknown;
|
||||
totalSizeBytes?: unknown;
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
try {
|
||||
if (request.method !== "POST") {
|
||||
return new Response("Method Not Allowed", { status: 405 });
|
||||
}
|
||||
const ctx = requireFilesPermission(await loadFilesContext({ request, params, requireModule: true }), "files.write");
|
||||
const body = (await request.json()) as InitBody;
|
||||
const originalFilename = typeof body.originalFilename === "string" ? body.originalFilename.trim() : "";
|
||||
const mimeType = typeof body.mimeType === "string" ? body.mimeType.trim() : "";
|
||||
const totalSizeBytes = typeof body.totalSizeBytes === "number" ? body.totalSizeBytes : Number.NaN;
|
||||
if (!originalFilename || !mimeType || !Number.isFinite(totalSizeBytes)) {
|
||||
return Response.json({ error: "files.error.invalidUploadRequest" }, { status: 400 });
|
||||
}
|
||||
const result = await createUploadSession({
|
||||
tenantId: ctx.tenantId,
|
||||
userId: ctx.userId,
|
||||
originalFilename,
|
||||
mimeType,
|
||||
totalSizeBytes,
|
||||
});
|
||||
return Response.json(result);
|
||||
} catch (error) {
|
||||
return fileActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,139 @@
|
||||
// P4 Files (AK-P4a) §11 — Upload view with drag&drop + multi-file queue and
|
||||
// per-file progress (chunked init -> chunk -> complete). Loader gates on
|
||||
// files.write (404 if module off / missing). Baseline functional UI; Subframe
|
||||
// polish follows Davids D-P4 delta.
|
||||
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { type LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { buildFileUploadVM, type FileUploadVM } from "@toolctrl/view-models";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadFilesContext, notFoundResponse, requireFilesPermission } from "~/utils/integrations/fileAccess.server";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
|
||||
type LoaderData = { title: string; vm: FileUploadVM; tenantSlug: string };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const ctx = await loadFilesContext({ request, params, requireModule: true });
|
||||
try {
|
||||
requireFilesPermission(ctx, "files.write");
|
||||
} catch {
|
||||
throw notFoundResponse();
|
||||
}
|
||||
const vm = buildFileUploadVM({ canWrite: true });
|
||||
return Response.json({ title: `${t("files.upload.title")} | ${process.env.APP_NAME}`, vm, tenantSlug: params.tenant ?? "" } satisfies LoaderData);
|
||||
};
|
||||
|
||||
type QueueItem = { clientId: string; filename: string; sizeBytes: number; status: "queued" | "uploading" | "processing" | "done" | "error"; progressPercent: number; errorKey: string | null };
|
||||
|
||||
export default function FilesUploadRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { vm, tenantSlug } = useLoaderData<LoaderData>();
|
||||
const [items, setItems] = useState<QueueItem[]>([]);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const chunkSize = vm.status === "ready" && vm.data ? vm.data.chunkSizeBytes : 5 * 1024 * 1024;
|
||||
|
||||
const update = useCallback((clientId: string, patch: Partial<QueueItem>) => {
|
||||
setItems((current) => current.map((item) => (item.clientId === clientId ? { ...item, ...patch } : item)));
|
||||
}, []);
|
||||
|
||||
const uploadOne = useCallback(
|
||||
async (file: File, clientId: string) => {
|
||||
try {
|
||||
update(clientId, { status: "uploading", progressPercent: 0 });
|
||||
const initRes = await fetch(`/${tenantSlug}/files/upload/init`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ originalFilename: file.name, mimeType: file.type || "application/octet-stream", totalSizeBytes: file.size }),
|
||||
});
|
||||
if (!initRes.ok) {
|
||||
const body = (await initRes.json().catch(() => ({}))) as { error?: string };
|
||||
update(clientId, { status: "error", errorKey: body.error ?? "files.error.invalidUploadRequest" });
|
||||
return;
|
||||
}
|
||||
const { uploadId, totalChunks } = (await initRes.json()) as { uploadId: string; chunkSize: number; totalChunks: number };
|
||||
for (let index = 0; index < totalChunks; index += 1) {
|
||||
const slice = file.slice(index * chunkSize, (index + 1) * chunkSize);
|
||||
const chunkRes = await fetch(`/${tenantSlug}/files/upload/${uploadId}/chunk/${index}`, { method: "POST", body: slice });
|
||||
if (!chunkRes.ok) {
|
||||
const body = (await chunkRes.json().catch(() => ({}))) as { error?: string };
|
||||
update(clientId, { status: "error", errorKey: body.error ?? "files.error.uploadIncomplete" });
|
||||
return;
|
||||
}
|
||||
update(clientId, { progressPercent: Math.round(((index + 1) / totalChunks) * 100) });
|
||||
}
|
||||
update(clientId, { status: "processing" });
|
||||
const completeRes = await fetch(`/${tenantSlug}/files/upload/${uploadId}/complete`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
if (!completeRes.ok) {
|
||||
const body = (await completeRes.json().catch(() => ({}))) as { error?: string };
|
||||
update(clientId, { status: "error", errorKey: body.error ?? "files.error.uploadIncomplete" });
|
||||
return;
|
||||
}
|
||||
update(clientId, { status: "done", progressPercent: 100 });
|
||||
} catch {
|
||||
update(clientId, { status: "error", errorKey: "files.error.uploadIncomplete" });
|
||||
}
|
||||
},
|
||||
[chunkSize, tenantSlug, update],
|
||||
);
|
||||
|
||||
const onFiles = useCallback(
|
||||
(fileList: FileList | null) => {
|
||||
if (!fileList) return;
|
||||
const next: QueueItem[] = [];
|
||||
for (const file of Array.from(fileList)) {
|
||||
const clientId = `${file.name}-${file.size}-${file.lastModified}`;
|
||||
next.push({ clientId, filename: file.name, sizeBytes: file.size, status: "queued", progressPercent: 0, errorKey: null });
|
||||
void uploadOne(file, clientId);
|
||||
}
|
||||
setItems((current) => [...current, ...next]);
|
||||
},
|
||||
[uploadOne],
|
||||
);
|
||||
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
return <main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.upload" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-3xl px-4 py-10" data-ui-id="ui.files.upload">
|
||||
<h1 className="text-foreground text-xl font-semibold">{t("files.upload.title")}</h1>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
onDragOver={(event) => event.preventDefault()}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
onFiles(event.dataTransfer.files);
|
||||
}}
|
||||
className="border-muted-foreground/40 mt-6 flex w-full flex-col items-center rounded-lg border-2 border-dashed px-6 py-12"
|
||||
data-ui-id="ui.files.upload.dropzone"
|
||||
>
|
||||
<span className="text-foreground font-medium">{t(vm.data.dropzoneHeadlineKey)}</span>
|
||||
<span className="text-muted-foreground mt-1 text-sm">{t(vm.data.dropzoneBodyKey)}</span>
|
||||
<span className="text-muted-foreground mt-3 text-xs">{t(vm.data.heicNoticeKey)}</span>
|
||||
</button>
|
||||
<input ref={inputRef} type="file" multiple className="hidden" onChange={(event) => onFiles(event.target.files)} data-ui-id="ui.files.upload.input" />
|
||||
|
||||
<ul className="mt-6 space-y-2" data-ui-id="ui.files.upload.queue">
|
||||
{items.map((item) => (
|
||||
<li key={item.clientId} className="border-b py-2 text-sm" data-row-id={item.clientId} data-status={item.status}>
|
||||
<div className="flex items-center justify-between">
|
||||
<span>{item.filename}</span>
|
||||
<span className="text-muted-foreground">{item.status === "error" && item.errorKey ? t(item.errorKey) : `${item.progressPercent}%`}</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { action } from "./forms.$id";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
form: {
|
||||
findFirst: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
formSubmission: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string, fallbackOrOptions?: string | Record<string, unknown>) =>
|
||||
({
|
||||
"settings.forms.admin.defaults.submitLabel": "Absenden",
|
||||
"settings.forms.admin.defaults.successMessage": "Danke. Wir haben deine Einsendung erhalten.",
|
||||
"settings.forms.admin.errors.formNotFound": "Form not found.",
|
||||
"settings.forms.admin.errors.invalidWebhookUrl": "Webhook URL is invalid.",
|
||||
"settings.forms.admin.messages.saved": "Saved.",
|
||||
})[key] ?? (typeof fallbackOrOptions === "string" ? fallbackOrOptions : key),
|
||||
})),
|
||||
}));
|
||||
|
||||
function postRequest(form: FormData) {
|
||||
return new Request("https://app.example.test/acme/forms/form_1", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(form as unknown as Record<string, string>),
|
||||
});
|
||||
}
|
||||
|
||||
function validSaveForm(overrides: Record<string, string> = {}) {
|
||||
const form = new FormData();
|
||||
form.set("op", "save");
|
||||
form.set("name", "Contact");
|
||||
form.set("definition", JSON.stringify({
|
||||
title: "Kontakt",
|
||||
fields: [{ key: "email", type: "email", label: "E-Mail", required: true }],
|
||||
}));
|
||||
form.set("theme", "{}");
|
||||
form.set("fieldMapping", "{}");
|
||||
form.set("targetType", "generic");
|
||||
for (const [key, value] of Object.entries(overrides)) {
|
||||
form.set(key, value);
|
||||
}
|
||||
return form;
|
||||
}
|
||||
|
||||
describe("form detail action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1" as never);
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(db.form.findFirst).mockResolvedValue({ id: "form_1" } as never);
|
||||
vi.mocked(db.form.update).mockResolvedValue({ id: "form_1" } as never);
|
||||
});
|
||||
|
||||
it("persists localized definition defaults during save", async () => {
|
||||
const result = await action({
|
||||
request: postRequest(validSaveForm({ targetType: "unsupported-target" })),
|
||||
params: { tenant: "acme", id: "form_1" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/forms.$id",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ success: "Saved." });
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.account.update", "tenant_1");
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(db.form.update).toHaveBeenCalledWith({
|
||||
where: { id: "form_1" },
|
||||
data: expect.objectContaining({
|
||||
name: "Contact",
|
||||
targetType: "generic",
|
||||
definition: expect.objectContaining({
|
||||
title: "Kontakt",
|
||||
submitLabel: "Absenden",
|
||||
successMessage: "Danke. Wir haben deine Einsendung erhalten.",
|
||||
}),
|
||||
theme: {},
|
||||
fieldMapping: {},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("returns localized invalid-webhook errors without updating the form", async () => {
|
||||
const result = await action({
|
||||
request: postRequest(validSaveForm({ webhookUrl: "http://localhost:3000/hook" })),
|
||||
params: { tenant: "acme", id: "form_1" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/forms.$id",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ error: "Webhook URL is invalid." });
|
||||
expect(db.form.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyFormDefinitionDefaults } from "./forms.$id";
|
||||
|
||||
const translations: Record<string, string> = {
|
||||
"settings.forms.admin.defaults.submitLabel": "Absenden",
|
||||
"settings.forms.admin.defaults.successMessage": "Danke. Wir haben deine Einsendung erhalten.",
|
||||
};
|
||||
|
||||
const t = (key: string, fallback?: string) => translations[key] ?? fallback ?? key;
|
||||
|
||||
describe("applyFormDefinitionDefaults", () => {
|
||||
it("fills missing public form copy with localized admin defaults", () => {
|
||||
const definition = applyFormDefinitionDefaults(
|
||||
{
|
||||
title: "Kontakt",
|
||||
fields: [{ key: "email", type: "email", label: "E-Mail" }],
|
||||
},
|
||||
t
|
||||
);
|
||||
|
||||
expect(definition).toMatchObject({
|
||||
submitLabel: "Absenden",
|
||||
successMessage: "Danke. Wir haben deine Einsendung erhalten.",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves authored submit and success copy", () => {
|
||||
const definition = applyFormDefinitionDefaults(
|
||||
{
|
||||
title: "Contact",
|
||||
submitLabel: "Send now",
|
||||
successMessage: "Done",
|
||||
fields: [{ key: "email", type: "email", label: "Email" }],
|
||||
},
|
||||
t
|
||||
);
|
||||
|
||||
expect(definition).toMatchObject({
|
||||
submitLabel: "Send now",
|
||||
successMessage: "Done",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
|
||||
describe("form detail i18n formatting", () => {
|
||||
it("keeps the form admin allowed-origin placeholder behind a translation key", () => {
|
||||
const source = fs.readFileSync(path.join(repoRoot, "apps/web/app/routes/app.$tenant/forms.tsx"), "utf8");
|
||||
const en = fs.readFileSync(path.join(repoRoot, "apps/web/public/locales/en/translations.json"), "utf8");
|
||||
const de = fs.readFileSync(path.join(repoRoot, "apps/web/public/locales/de/translations.json"), "utf8");
|
||||
|
||||
expect(source).toContain('placeholder={t("settings.forms.admin.create.allowedOriginPlaceholder")}');
|
||||
expect(source).not.toContain('placeholder="https://www.example.com"');
|
||||
expect(en).toContain('"allowedOriginPlaceholder": "https://www.example.com"');
|
||||
expect(de).toContain('"allowedOriginPlaceholder": "https://www.example.com"');
|
||||
});
|
||||
|
||||
it("formats submission timestamps through locale helpers", () => {
|
||||
const source = fs.readFileSync(path.join(repoRoot, "apps/web/app/routes/app.$tenant/forms.$id.tsx"), "utf8");
|
||||
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.dateTime(s.createdAt");
|
||||
expect(source).toContain("<time dateTime={s.createdAt}");
|
||||
expect(source).not.toContain("<span>{s.createdAt}</span>");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* Tenant admin: form detail editor + submissions inbox (Phase 05 #58).
|
||||
*
|
||||
* The editor has been promoted from a JSON-textarea to a visual
|
||||
* drag-drop builder via `apps/web/app/modules/formWidget/builder/`.
|
||||
* Tabs (Builder / Settings / Preview) replace the linear form-fields
|
||||
* layout. The action endpoint accepts the same `definition` + `theme`
|
||||
* JSON shapes, plus targetType + fieldMapping persisted on the parent
|
||||
* Form row.
|
||||
*
|
||||
* Submissions table shows the 50 most-recent rows with sourceOrigin +
|
||||
* status + an inline JSON preview, plus a CSV export action that
|
||||
* streams via Response.
|
||||
*/
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, Form, Link, useActionData } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { FormDefinitionSchema, FormThemeSchema, type FormDefinition, type FormTheme } from "@toolctrl/form-widget";
|
||||
import { FormBuilder } from "~/modules/formWidget/builder/FormBuilder";
|
||||
import type { FormSettingsValue } from "~/modules/formWidget/builder/SettingsTab";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type FormDetail = {
|
||||
id: string;
|
||||
key: string;
|
||||
name: string;
|
||||
definition: unknown;
|
||||
theme: unknown;
|
||||
targetType: string;
|
||||
fieldMapping: unknown;
|
||||
allowedOrigins: string[];
|
||||
notifyEmails: string[];
|
||||
webhookUrl: string | null;
|
||||
isEnabled: boolean;
|
||||
};
|
||||
|
||||
type SubmissionRow = {
|
||||
id: string;
|
||||
status: string;
|
||||
sourceOrigin: string | null;
|
||||
createdAt: string;
|
||||
preview: string;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
form: FormDetail;
|
||||
submissions: SubmissionRow[];
|
||||
embedScriptBase: string;
|
||||
};
|
||||
|
||||
type ActionData = { error?: string; success?: string };
|
||||
|
||||
function isHttpUrl(value: string | null | undefined): boolean {
|
||||
if (!value) return false;
|
||||
try {
|
||||
const u = new URL(value);
|
||||
if (u.protocol !== "https:" && u.protocol !== "http:") return false;
|
||||
const host = u.hostname.toLowerCase();
|
||||
if (host === "localhost" || host === "127.0.0.1" || host.endsWith(".internal")) return false;
|
||||
if (host === "0.0.0.0" || host.startsWith("10.") || host.startsWith("192.168.") || host.startsWith("169.254.")) return false;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const id = params.id;
|
||||
if (!id) throw new Response(t("shared.notFound"), { status: 404 });
|
||||
const form = await db.form.findFirst({
|
||||
where: { id, tenantId },
|
||||
select: {
|
||||
id: true,
|
||||
key: true,
|
||||
name: true,
|
||||
definition: true,
|
||||
theme: true,
|
||||
targetType: true,
|
||||
fieldMapping: true,
|
||||
allowedOrigins: true,
|
||||
notifyEmails: true,
|
||||
webhookUrl: true,
|
||||
isEnabled: true,
|
||||
},
|
||||
});
|
||||
if (!form) throw new Response(t("settings.forms.admin.errors.formNotFound"), { status: 404 });
|
||||
|
||||
const url = new URL(request.url);
|
||||
if (url.searchParams.get("export") === "csv") {
|
||||
const all = await db.formSubmission.findMany({
|
||||
where: { formId: id, tenantId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1000,
|
||||
});
|
||||
const header = "id,createdAt,status,sourceOrigin,values\n";
|
||||
const rows = all.map((s) => {
|
||||
const vals = typeof s.payload === "object" && s.payload && "values" in s.payload
|
||||
? JSON.stringify((s.payload as { values: unknown }).values)
|
||||
: JSON.stringify(s.payload);
|
||||
const safe = vals.replace(/"/g, '""');
|
||||
return `${s.id},${s.createdAt.toISOString()},${s.status},${s.sourceOrigin ?? ""},"${safe}"`;
|
||||
});
|
||||
return new Response(header + rows.join("\n"), {
|
||||
headers: {
|
||||
"content-type": "text/csv; charset=utf-8",
|
||||
"content-disposition": `attachment; filename="form-${form.key}-submissions.csv"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const submissions = await db.formSubmission.findMany({
|
||||
where: { formId: id, tenantId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
select: { id: true, status: true, sourceOrigin: true, createdAt: true, payload: true },
|
||||
});
|
||||
const payload: LoaderData = {
|
||||
form: { ...form },
|
||||
submissions: submissions.map((s) => ({
|
||||
id: s.id,
|
||||
status: s.status,
|
||||
sourceOrigin: s.sourceOrigin,
|
||||
createdAt: s.createdAt.toISOString(),
|
||||
preview: JSON.stringify(s.payload).slice(0, 240),
|
||||
})),
|
||||
embedScriptBase: process.env.FORM_WIDGET_CDN_URL?.trim() || process.env.APP_URL?.trim() || "",
|
||||
};
|
||||
return Response.json(payload);
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<ActionData> {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const id = params.id;
|
||||
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
|
||||
const body = await request.formData();
|
||||
const op = body.get("op")?.toString() ?? "save";
|
||||
|
||||
const target = await db.form.findFirst({ where: { id, tenantId }, select: { id: true } });
|
||||
if (!target) return { error: t("settings.forms.admin.errors.formNotFound") };
|
||||
|
||||
if (op === "save") {
|
||||
const name = body.get("name")?.toString()?.trim();
|
||||
if (!name) return { error: t("settings.forms.admin.errors.nameRequired") };
|
||||
const allowedOrigins = (body.get("allowedOrigins")?.toString() ?? "")
|
||||
.split("\n")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const notifyEmails = (body.get("notifyEmails")?.toString() ?? "")
|
||||
.split(/[,\n]/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const webhookUrlRaw = body.get("webhookUrl")?.toString()?.trim() ?? "";
|
||||
const webhookUrl = webhookUrlRaw === "" ? null : webhookUrlRaw;
|
||||
if (webhookUrl && !isHttpUrl(webhookUrl)) {
|
||||
return { error: t("settings.forms.admin.errors.invalidWebhookUrl") };
|
||||
}
|
||||
const targetTypeRaw = body.get("targetType")?.toString()?.trim() ?? "generic";
|
||||
const allowedTargets = new Set(["generic", "crm-contact", "entity-row"]);
|
||||
const targetType = allowedTargets.has(targetTypeRaw) ? targetTypeRaw : "generic";
|
||||
let definition: unknown;
|
||||
let theme: unknown;
|
||||
let fieldMapping: unknown = null;
|
||||
try {
|
||||
definition = JSON.parse(body.get("definition")?.toString() ?? "{}");
|
||||
theme = JSON.parse(body.get("theme")?.toString() ?? "{}");
|
||||
const mappingRaw = body.get("fieldMapping")?.toString();
|
||||
if (mappingRaw && mappingRaw.length > 0) {
|
||||
fieldMapping = JSON.parse(mappingRaw);
|
||||
}
|
||||
} catch {
|
||||
return { error: t("settings.forms.admin.errors.invalidDefinitionJson") };
|
||||
}
|
||||
const defParse = FormDefinitionSchema.safeParse(
|
||||
applyFormDefinitionDefaults(definition, (key) => t(key))
|
||||
);
|
||||
if (!defParse.success) return { error: t("settings.forms.admin.errors.invalidDefinition", { details: defParse.error.message.slice(0, 240) }) };
|
||||
const themeParse = FormThemeSchema.safeParse(theme);
|
||||
if (!themeParse.success) return { error: t("settings.forms.admin.errors.invalidTheme", { details: themeParse.error.message.slice(0, 240) }) };
|
||||
await db.form.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name,
|
||||
definition: defParse.data as object,
|
||||
theme: themeParse.data as object,
|
||||
allowedOrigins,
|
||||
notifyEmails,
|
||||
webhookUrl,
|
||||
targetType,
|
||||
fieldMapping: fieldMapping as object,
|
||||
},
|
||||
});
|
||||
return { success: t("settings.forms.admin.messages.saved") };
|
||||
}
|
||||
return { error: t("settings.forms.admin.errors.unknownOperation") };
|
||||
}
|
||||
|
||||
export default function FormDetailPage(): React.JSX.Element {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData() as LoaderData;
|
||||
const action = useActionData() as ActionData | undefined;
|
||||
const rootData = useRootData();
|
||||
const formatters = useLocaleFormatters();
|
||||
const embedSnippet = `<script src="${data.embedScriptBase}/embed/widget.js" data-form-key="${data.form.key}" async></script>`;
|
||||
|
||||
// Initial state for the builder. The DB shapes are unknown until we
|
||||
// parse them; we use the canonical zod parsers so invalid persisted
|
||||
// payloads fall back to a safe minimal shape rather than crashing
|
||||
// the route.
|
||||
const definitionParsed = FormDefinitionSchema.safeParse(data.form.definition);
|
||||
const initialDefinition: FormDefinition = definitionParsed.success
|
||||
? definitionParsed.data
|
||||
: ({
|
||||
title: data.form.name || t("settings.forms.defaults.untitled"),
|
||||
submitLabel: t("settings.forms.admin.defaults.submitLabel"),
|
||||
successMessage: t("settings.forms.admin.defaults.successMessage"),
|
||||
fields: [{ key: "email", type: "email", label: t("settings.forms.admin.defaults.fields.email"), required: true }],
|
||||
} satisfies FormDefinition);
|
||||
const themeParsed = FormThemeSchema.safeParse(data.form.theme ?? {});
|
||||
const initialTheme: FormTheme = themeParsed.success ? themeParsed.data : {};
|
||||
const initialFieldMapping =
|
||||
data.form.fieldMapping && typeof data.form.fieldMapping === "object" && !Array.isArray(data.form.fieldMapping)
|
||||
? (data.form.fieldMapping as Record<string, string>)
|
||||
: {};
|
||||
const initialSettings: FormSettingsValue = {
|
||||
allowedOrigins: data.form.allowedOrigins,
|
||||
notifyEmails: data.form.notifyEmails,
|
||||
webhookUrl: data.form.webhookUrl ?? "",
|
||||
targetType: data.form.targetType || "generic",
|
||||
fieldMapping: initialFieldMapping,
|
||||
};
|
||||
|
||||
const [name, setName] = useState(data.form.name);
|
||||
const [definition, setDefinition] = useState<FormDefinition>(initialDefinition);
|
||||
const [theme, setTheme] = useState<FormTheme>(initialTheme);
|
||||
const [settings, setSettings] = useState<FormSettingsValue>(initialSettings);
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<Link to=".." className="text-sm text-blue-700 hover:underline">{t("settings.forms.admin.detail.backToForms")}</Link>
|
||||
<header className="flex items-center justify-between gap-3">
|
||||
<input
|
||||
aria-label={t("settings.forms.admin.detail.formName")}
|
||||
className="text-2xl font-semibold border-b border-transparent focus:border-blue-500 focus:outline-none px-1 py-0.5"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<Form method="post" replace>
|
||||
<input type="hidden" name="csrf" value={rootData.csrf ?? ""} readOnly />
|
||||
<input type="hidden" name="op" value="save" />
|
||||
<input type="hidden" name="name" value={name} />
|
||||
<input type="hidden" name="definition" value={JSON.stringify(definition)} />
|
||||
<input type="hidden" name="theme" value={JSON.stringify(theme)} />
|
||||
<input type="hidden" name="allowedOrigins" value={settings.allowedOrigins.join("\n")} />
|
||||
<input type="hidden" name="notifyEmails" value={settings.notifyEmails.join("\n")} />
|
||||
<input type="hidden" name="webhookUrl" value={settings.webhookUrl} />
|
||||
<input type="hidden" name="targetType" value={settings.targetType} />
|
||||
<input type="hidden" name="fieldMapping" value={JSON.stringify(settings.fieldMapping)} />
|
||||
<button type="submit" className="bg-blue-600 text-white px-4 py-1.5 rounded text-sm">
|
||||
{t("shared.save")}
|
||||
</button>
|
||||
</Form>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-600">{t("settings.forms.admin.detail.embedSnippet")}</h2>
|
||||
<pre className="text-xs bg-gray-50 p-2 rounded overflow-x-auto">{embedSnippet}</pre>
|
||||
</section>
|
||||
|
||||
{action?.error ? <p className="text-red-600 text-sm">{action.error}</p> : null}
|
||||
{action?.success ? <p className="text-green-700 text-sm">{action.success}</p> : null}
|
||||
|
||||
<FormBuilder
|
||||
initialDefinition={initialDefinition}
|
||||
initialTheme={initialTheme}
|
||||
initialSettings={initialSettings}
|
||||
onChange={(snapshot) => {
|
||||
setDefinition(snapshot.definition);
|
||||
setTheme(snapshot.theme);
|
||||
setSettings(snapshot.settings);
|
||||
}}
|
||||
/>
|
||||
|
||||
<section>
|
||||
<header className="flex items-center justify-between">
|
||||
<h2 className="text-lg font-medium">{t("settings.forms.admin.detail.submissionsLatest")}</h2>
|
||||
<a href="?export=csv" className="text-sm border rounded px-2 py-1">{t("settings.forms.admin.detail.exportCsv")}</a>
|
||||
</header>
|
||||
{data.submissions.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">{t("settings.forms.admin.detail.noSubmissions")}</p>
|
||||
) : (
|
||||
<ul className="divide-y border rounded mt-2">
|
||||
{data.submissions.map((s) => (
|
||||
<li key={s.id} className="p-3">
|
||||
<div className="flex items-center gap-2 text-xs text-gray-500">
|
||||
<time dateTime={s.createdAt}>{formatters.dateTime(s.createdAt, { timeStyle: "medium" })}</time>
|
||||
<span>{"·"}</span>
|
||||
<RoutingStatusBadge status={s.status} />
|
||||
<span>{"·"}</span>
|
||||
<span>{t("settings.forms.admin.detail.origin", { origin: s.sourceOrigin ?? t("shared.notSet") })}</span>
|
||||
</div>
|
||||
<pre className="text-xs mt-1 whitespace-pre-wrap break-words">{s.preview}</pre>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function applyFormDefinitionDefaults(value: unknown, t: (key: string) => string) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const definition = value as Record<string, unknown>;
|
||||
return {
|
||||
...definition,
|
||||
submitLabel: typeof definition.submitLabel === "string" && definition.submitLabel.trim() ? definition.submitLabel : t("settings.forms.admin.defaults.submitLabel"),
|
||||
successMessage:
|
||||
typeof definition.successMessage === "string" && definition.successMessage.trim()
|
||||
? definition.successMessage
|
||||
: t("settings.forms.admin.defaults.successMessage"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Visual status badge for `FormSubmission.status`. The status string is
|
||||
* produced by the form-submission-route worker (Phase 05 #58) — the
|
||||
* admin UI surfaces it inline next to each submission so operators can
|
||||
* see at a glance whether routing succeeded.
|
||||
*/
|
||||
function RoutingStatusBadge({ status }: { status: string }): React.JSX.Element {
|
||||
const palette: Record<string, string> = {
|
||||
received: "bg-gray-100 text-gray-700 border-gray-300",
|
||||
processed: "bg-blue-50 text-blue-700 border-blue-200",
|
||||
"routed-to-crm": "bg-green-50 text-green-700 border-green-200",
|
||||
"routed-to-entity": "bg-green-50 text-green-700 border-green-200",
|
||||
"route-failed": "bg-red-50 text-red-700 border-red-200",
|
||||
spam: "bg-yellow-50 text-yellow-700 border-yellow-200",
|
||||
};
|
||||
const className = palette[status] ?? "bg-gray-100 text-gray-700 border-gray-300";
|
||||
return (
|
||||
<span className={`inline-block px-1.5 py-0.5 border rounded text-[10px] uppercase tracking-wide ${className}`}>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Tenant admin: form-widget list + create (Phase 05 Task #58, layer 3).
|
||||
*
|
||||
* Permissions: `app.settings.account.update` (admin-only) — forms expose
|
||||
* a public submission endpoint so we keep authoring tightly scoped.
|
||||
*
|
||||
* The page renders existing forms with their public key + submission
|
||||
* count + embed-code snippet, plus a minimal create form that seeds a
|
||||
* single text+email definition. Field editing happens on the detail
|
||||
* route (forms.$id.tsx).
|
||||
*/
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, useLoaderData, Form, Link, useActionData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@toolctrl/form-widget";
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
key: string;
|
||||
name: string;
|
||||
isEnabled: boolean;
|
||||
submissions: number;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
forms: Row[];
|
||||
embedScriptBase: string;
|
||||
};
|
||||
|
||||
type ActionData = { error?: string; createdId?: string };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs): Promise<LoaderData> {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
const forms = await db.form.findMany({
|
||||
where: { tenantId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
key: true,
|
||||
name: true,
|
||||
isEnabled: true,
|
||||
createdAt: true,
|
||||
_count: { select: { submissions: true } },
|
||||
},
|
||||
});
|
||||
return {
|
||||
forms: forms.map((f) => ({
|
||||
id: f.id,
|
||||
key: f.key,
|
||||
name: f.name,
|
||||
isEnabled: f.isEnabled,
|
||||
submissions: f._count.submissions,
|
||||
createdAt: f.createdAt.toISOString(),
|
||||
})),
|
||||
embedScriptBase: process.env.FORM_WIDGET_CDN_URL?.trim() || process.env.APP_URL?.trim() || "",
|
||||
};
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs): Promise<Response | ActionData> {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.account.update", tenantId);
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const body = await request.formData();
|
||||
const op = body.get("op")?.toString() ?? "";
|
||||
if (op === "create") {
|
||||
const name = body.get("name")?.toString()?.trim();
|
||||
const origin = body.get("allowedOrigin")?.toString()?.trim() ?? "";
|
||||
if (!name) return { error: t("settings.forms.admin.errors.nameRequired") };
|
||||
const definition = FormDefinitionSchema.parse({
|
||||
title: name,
|
||||
submitLabel: t("settings.forms.admin.defaults.submitLabel"),
|
||||
successMessage: t("settings.forms.admin.defaults.successMessage"),
|
||||
fields: [
|
||||
{ key: "full_name", type: "text", label: t("settings.forms.admin.defaults.fields.fullName"), required: true },
|
||||
{ key: "email", type: "email", label: t("settings.forms.admin.defaults.fields.email"), required: true },
|
||||
{ key: "message", type: "textarea", label: t("settings.forms.admin.defaults.fields.message"), required: false },
|
||||
{ key: HONEYPOT_FIELD_KEY, type: "honeypot", label: t("settings.forms.admin.defaults.fields.honeypot") },
|
||||
],
|
||||
});
|
||||
const created = await db.form.create({
|
||||
data: {
|
||||
tenantId,
|
||||
name,
|
||||
definition: definition as object,
|
||||
allowedOrigins: origin ? [origin] : [],
|
||||
config: { honeypotEnabled: true } as object,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return { createdId: created.id };
|
||||
}
|
||||
if (op === "toggle") {
|
||||
const id = body.get("id")?.toString();
|
||||
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
|
||||
const target = await db.form.findFirst({ where: { id, tenantId }, select: { isEnabled: true } });
|
||||
if (!target) return { error: t("settings.forms.admin.errors.formNotFound") };
|
||||
await db.form.update({ where: { id }, data: { isEnabled: !target.isEnabled } });
|
||||
return { error: undefined };
|
||||
}
|
||||
if (op === "delete") {
|
||||
const id = body.get("id")?.toString();
|
||||
if (!id) return { error: t("settings.forms.admin.errors.missingFormId") };
|
||||
await db.form.deleteMany({ where: { id, tenantId } });
|
||||
return { error: undefined };
|
||||
}
|
||||
return { error: t("settings.forms.admin.errors.unknownOperation") };
|
||||
}
|
||||
|
||||
export default function FormsAdmin(): React.JSX.Element {
|
||||
const data = useLoaderData() as LoaderData;
|
||||
const actionData = useActionData() as ActionData | undefined;
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<header>
|
||||
<h1 className="text-2xl font-semibold">{t("settings.forms.admin.title")}</h1>
|
||||
<p className="text-sm text-gray-600">
|
||||
{t("settings.forms.admin.description")}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section>
|
||||
<h2 className="text-lg font-medium mb-2">{t("settings.forms.admin.create.title")}</h2>
|
||||
{actionData?.error ? <p className="text-red-600 text-sm mb-2">{actionData.error}</p> : null}
|
||||
<Form method="post" className="flex gap-2 items-end">
|
||||
<input type="hidden" name="op" value="create" />
|
||||
<label className="flex flex-col gap-1 flex-1">
|
||||
<span className="text-sm">{t("settings.forms.admin.create.name")}</span>
|
||||
<input name="name" required className="border rounded px-2 py-1" />
|
||||
</label>
|
||||
<label className="flex flex-col gap-1 flex-1">
|
||||
<span className="text-sm">{t("settings.forms.admin.create.allowedOrigin")}</span>
|
||||
<input name="allowedOrigin" placeholder={t("settings.forms.admin.create.allowedOriginPlaceholder")} className="border rounded px-2 py-1" />
|
||||
</label>
|
||||
<button type="submit" className="bg-blue-600 text-white px-4 py-1.5 rounded">{t("settings.forms.admin.create.submit")}</button>
|
||||
</Form>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 className="text-lg font-medium mb-2">{t("settings.forms.admin.existing.title")}</h2>
|
||||
{data.forms.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">{t("settings.forms.admin.existing.empty")}</p>
|
||||
) : (
|
||||
<ul className="divide-y border rounded">
|
||||
{data.forms.map((f) => (
|
||||
<li key={f.id} className="p-3 flex items-center justify-between">
|
||||
<div>
|
||||
<Link to={f.id} className="font-medium text-blue-700 hover:underline">{f.name}</Link>
|
||||
<div className="text-xs text-gray-500">
|
||||
{t("settings.forms.admin.existing.key")}: <code>{f.key}</code> ·{" "}
|
||||
{t("settings.forms.admin.existing.submissionsCount", {
|
||||
count: f.submissions,
|
||||
formattedCount: formatters.number(f.submissions),
|
||||
})}{" "}
|
||||
· {f.isEnabled ? t("shared.enabled") : t("shared.disabled")} ·{" "}
|
||||
{t("settings.forms.admin.existing.createdAtWithDate", {
|
||||
date: formatters.date(f.createdAt, { dateStyle: "medium", timeStyle: "short" }),
|
||||
})}
|
||||
</div>
|
||||
<pre className="text-xs bg-gray-50 mt-1 p-1 rounded inline-block">
|
||||
{`<script src="${data.embedScriptBase}/embed/widget.js" data-form-key="${f.key}" async></script>`}
|
||||
</pre>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Form method="post">
|
||||
<input type="hidden" name="op" value="toggle" />
|
||||
<input type="hidden" name="id" value={f.id} />
|
||||
<button className="text-sm border rounded px-2 py-1">{f.isEnabled ? t("shared.disable") : t("shared.enable")}</button>
|
||||
</Form>
|
||||
<Form method="post" onSubmit={(e) => { if (!confirm(t("settings.forms.admin.delete.confirm"))) e.preventDefault(); }}>
|
||||
<input type="hidden" name="op" value="delete" />
|
||||
<input type="hidden" name="id" value={f.id} />
|
||||
<button className="text-sm border rounded px-2 py-1 text-red-600">{t("shared.delete")}</button>
|
||||
</Form>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { LoaderFunctionArgs, MetaFunction, redirect } from "react-router";
|
||||
import { useParams, Outlet } from "react-router";
|
||||
import { useState, Fragment, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import SidebarIconsLayout, { IconDto } from "~/components/ui/layouts/SidebarIconsLayout";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { getEntityGroupBySlug } from "~/utils/db/entities/entityGroups.db.server";
|
||||
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
|
||||
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { translateEntityTitlePlural } from "~/utils/i18n/translateLabel";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdOrNull({ request, params });
|
||||
const group = await getEntityGroupBySlug(params.group!);
|
||||
if (!group) {
|
||||
throw redirect(tenantId ? UrlUtils.currentTenantUrl(params, "404") : "/404");
|
||||
}
|
||||
const data: LoaderData = {
|
||||
title: `${t(group.title)} | ${process.env.APP_NAME}`,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default () => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
const mainElement = useRef<HTMLDivElement>(null);
|
||||
|
||||
const group = appOrAdminData.entityGroups.find((f) => f.slug === params.group);
|
||||
if (!group) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const visibleGroupEntities = group.entities.filter(({ entity }) => getUserHasPermission(appOrAdminData, getEntityPermission(entity, "view")));
|
||||
const thereAreIcons = visibleGroupEntities.some(({ entity }) => !!entity.icon);
|
||||
const items: IconDto[] = [
|
||||
{
|
||||
name: t("shared.summary"),
|
||||
href: params.tenant ? appPath({ tenantSlug: params.tenant, path: `g/${params.group}`, mode: "host-aware" }) : adminPath(`g/${params.group}`, { mode: "host-aware" }),
|
||||
prefetch: "intent",
|
||||
exact: true,
|
||||
icon: !thereAreIcons ? undefined : (
|
||||
<svg className="h-5 w-5" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="50" height="50" viewBox="0 0 50 50" fill="currentColor">
|
||||
<path d="M 39 0 L 39 2 L 46.5625 2 L 34 14.5625 L 30.71875 11.28125 L 30 10.59375 L 29.28125 11.28125 L 18 22.5625 L 14.71875 19.28125 L 14 18.59375 L 13.28125 19.28125 L 0.28125 32.28125 L 1.71875 33.71875 L 14 21.4375 L 17.28125 24.71875 L 18 25.40625 L 18.71875 24.71875 L 30 13.4375 L 33.28125 16.71875 L 34 17.40625 L 34.71875 16.71875 L 48 3.4375 L 48 11 L 50 11 L 50 0 Z M 42 14 L 42 50 L 44 50 L 44 14 Z M 48 15 L 48 50 L 50 50 L 50 15 Z M 30 20 L 30 50 L 32 50 L 32 20 Z M 36 20 L 36 50 L 38 50 L 38 20 Z M 24 24 L 24 50 L 26 50 L 26 24 Z M 12 28 L 12 50 L 14 50 L 14 28 Z M 18 30 L 18 50 L 20 50 L 20 30 Z M 6 34 L 6 50 L 8 50 L 8 34 Z M 0 38 L 0 50 L 2 50 L 2 38 Z"></path>
|
||||
</svg>
|
||||
),
|
||||
iconSelected: !thereAreIcons ? undefined : (
|
||||
<svg className="h-5 w-5" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="50" height="50" viewBox="0 0 50 50" fill="currentColor">
|
||||
<path d="M 38 0 L 38 4 L 43.1875 4 L 34 13.1875 L 31.40625 10.59375 L 30 9.15625 L 28.59375 10.59375 L 18 21.1875 L 15.40625 18.59375 L 14 17.15625 L 12.59375 18.59375 L 0.59375 30.59375 L 3.40625 33.40625 L 14 22.8125 L 16.59375 25.40625 L 18 26.84375 L 19.40625 25.40625 L 30 14.8125 L 32.59375 17.40625 L 34 18.84375 L 35.40625 17.40625 L 46 6.8125 L 46 12 L 50 12 L 50 0 Z M 44 15 L 44 50 L 48 50 L 48 15 Z M 30 20 L 30 50 L 34 50 L 34 20 Z M 37 20 L 37 50 L 41 50 L 41 20 Z M 23 24 L 23 50 L 27 50 L 27 24 Z M 16 30 L 16 50 L 20 50 L 20 30 Z M 9 31 L 9 50 L 13 50 L 13 31 Z M 2 38 L 2 50 L 6 50 L 6 38 Z"></path>
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
visibleGroupEntities.forEach(({ entity }) => {
|
||||
items.push({
|
||||
name: translateEntityTitlePlural(t, i18n, entity),
|
||||
href: params.tenant
|
||||
? appPath({ tenantSlug: params.tenant, path: `g/${params.group}/${entity.slug}`, mode: "host-aware" })
|
||||
: adminPath(`g/${params.group}/${entity.slug}`, { mode: "host-aware" }),
|
||||
prefetch: "intent",
|
||||
textIcon: entity.icon,
|
||||
textIconSelected: entity.icon,
|
||||
});
|
||||
});
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
{!params.id ? (
|
||||
<SidebarIconsLayout label={{ align: "right" }} items={items}>
|
||||
<Outlet />
|
||||
</SidebarIconsLayout>
|
||||
) : (
|
||||
<div className="sm:h-[calc(100vh-56px)]">
|
||||
<div ref={mainElement} className="w-full overflow-x-hidden">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowEditRoute from "~/modules/rows/components/RowEditRoute";
|
||||
import { Rows_Edit } from "~/modules/rows/routes/Rows_Edit.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Edit.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Edit.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Edit.action(args);
|
||||
|
||||
export default () => <RowEditRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import RowOverviewRoute from "~/modules/rows/components/RowOverviewRoute";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_Overview } from "~/modules/rows/routes/Rows_Overview.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Overview.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Overview.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Overview.action(args);
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<Rows_Overview.LoaderData>();
|
||||
const actionData = useActionData<Rows_Overview.ActionData>();
|
||||
return (
|
||||
<RowOverviewRoute
|
||||
rowData={data.rowData}
|
||||
item={actionData?.updatedRow?.item ?? data.rowData.item}
|
||||
routes={data.routes}
|
||||
relationshipRows={data.relationshipRows}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowShareRoute from "~/modules/rows/components/RowShareRoute";
|
||||
import { Rows_Share } from "~/modules/rows/routes/Rows_Share.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Share.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Share.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Share.action(args);
|
||||
|
||||
export default () => <RowShareRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import RowTagsRoute from "~/modules/rows/components/RowTagsRoute";
|
||||
import { Rows_Tags } from "~/modules/rows/routes/Rows_Tags.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Tags.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Tags.action(args);
|
||||
|
||||
export default () => <RowTagsRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { Rows_List } from "~/modules/rows/routes/Rows_List.server";
|
||||
import RowsAllInOneRoute from "~/modules/rows/components/RowsAllInOneRoute";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_List.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_List.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_List.action(args);
|
||||
|
||||
export default () => <RowsAllInOneRoute />;
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import { LoaderFunctionArgs } from "react-router";
|
||||
import { Rows_Export } from "~/modules/rows/routes/Rows_Export.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Export.loader(args);
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { ActionFunction, LoaderFunctionArgs } from "react-router";
|
||||
import RowsImportRoute from "~/modules/rows/components/RowsImportRoute";
|
||||
import { Rows_Import } from "~/modules/rows/routes/Rows_Import.server";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
export const meta: v2MetaFunction<Rows_Import.LoaderData> = ({ data }) => data?.meta || [];
|
||||
export const loader = (args: LoaderFunctionArgs) => Rows_Import.loader(args);
|
||||
export const action: ActionFunction = (args) => Rows_Import.action(args);
|
||||
|
||||
export default () => <RowsImportRoute />;
|
||||
Loaded 100 of 5784 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user