Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
type MigratedAnalyticsRoute = {
|
||||
path: string;
|
||||
packageImports: string[];
|
||||
};
|
||||
|
||||
const migratedAnalyticsRoutes: MigratedAnalyticsRoute[] = [
|
||||
{
|
||||
path: "overview.tsx",
|
||||
packageImports: ["getAnalyticsOverview"],
|
||||
},
|
||||
{
|
||||
path: "visitors.tsx",
|
||||
packageImports: ["getAnalyticsVisitorList"],
|
||||
},
|
||||
{
|
||||
path: "events.tsx",
|
||||
packageImports: ["getAnalyticsEventFilterOptions", "getAnalyticsEventList"],
|
||||
},
|
||||
{
|
||||
path: "page-views.tsx",
|
||||
packageImports: ["getAnalyticsPageViewFilterOptions", "getAnalyticsPageViewList"],
|
||||
},
|
||||
{
|
||||
path: "settings.tsx",
|
||||
packageImports: ["deleteAllAnalyticsData", "getOrCreateAnalyticsSettings", "removeAnalyticsIgnoredPage", "updateAnalyticsSettingsPreferences"],
|
||||
},
|
||||
];
|
||||
|
||||
const forbiddenAnalyticsBoundaryImports = [
|
||||
"~/utils/db.server",
|
||||
"~/utils/helpers/.server/AnalyticsService",
|
||||
"~/utils/db/users.db.server",
|
||||
"~/modules/featureFlags/db/featureFlags.db.server",
|
||||
];
|
||||
|
||||
function readRouteSource(path: string) {
|
||||
return readFileSync(new URL(path, import.meta.url), "utf8");
|
||||
}
|
||||
|
||||
describe("migrated admin analytics route DB boundary imports", () => {
|
||||
it("uses the package-owned analytics server helpers in every migrated route", () => {
|
||||
for (const route of migratedAnalyticsRoutes) {
|
||||
const source = readRouteSource(route.path);
|
||||
|
||||
expect(source, `${route.path} should import the analytics package boundary`).toContain("@toolctrl/db/analytics.server");
|
||||
for (const packageImport of route.packageImports) {
|
||||
expect(source, `${route.path} should import ${packageImport}`).toContain(packageImport);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("does not reintroduce app-local analytics DB imports in migrated routes", () => {
|
||||
for (const route of migratedAnalyticsRoutes) {
|
||||
const source = readRouteSource(route.path);
|
||||
|
||||
for (const forbiddenImport of forbiddenAnalyticsBoundaryImports) {
|
||||
expect(source, `${route.path} should not import ${forbiddenImport}`).not.toContain(forbiddenImport);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/admin/analytics/events.tsx";
|
||||
|
||||
function readRoute() {
|
||||
return readRepoFile(routePath);
|
||||
}
|
||||
|
||||
describe("admin analytics events route DB boundary", () => {
|
||||
it("uses package analytics helpers for filter options and list reads", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsEventFilterOptions");
|
||||
expect(source).toContain("getAnalyticsEventList");
|
||||
expect(source).toContain("RowFiltersHelper.getFiltersCondition(filters)");
|
||||
});
|
||||
|
||||
it("does not import direct analytics DB wrappers", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).not.toContain('from "~/utils/db.server"');
|
||||
expect(source).not.toContain('from "~/modules/featureFlags/db/featureFlags.db.server"');
|
||||
expect(source).not.toMatch(/\bdb\.analyticsEvent\b/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,210 @@
|
||||
import { AnalyticsEvent, AnalyticsUniqueVisitor } from "@toolctrl/db/prisma-browser";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { LoaderFunction, useLoaderData } 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 { getAnalyticsEventFilterOptions, getAnalyticsEventList } from "@toolctrl/db/analytics.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
items: (AnalyticsEvent & { uniqueVisitor: AnalyticsUniqueVisitor })[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const filterOptions = await getAnalyticsEventFilterOptions();
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "action",
|
||||
title: "analytics.action",
|
||||
options: filterOptions.actions,
|
||||
},
|
||||
{
|
||||
name: "category",
|
||||
title: "analytics.category",
|
||||
options: filterOptions.categories,
|
||||
},
|
||||
{
|
||||
name: "label",
|
||||
title: "analytics.label",
|
||||
options: filterOptions.labels,
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: "analytics.value",
|
||||
options: filterOptions.values,
|
||||
},
|
||||
{
|
||||
name: "featureFlagId",
|
||||
title: "featureFlags.object",
|
||||
options: filterOptions.featureFlags,
|
||||
},
|
||||
];
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(searchParams);
|
||||
const where = RowFiltersHelper.getFiltersCondition(filters);
|
||||
const { items, totalItems } = await getAnalyticsEventList({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items: items as LoaderData["items"],
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsEventsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<div className="flex justify-between gap-2">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
</div>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: i18nT("analytics.date"),
|
||||
value: (i) => (
|
||||
<time title={formatters.dateTime(i.createdAt, { timeStyle: "medium" })} className="text-muted-foreground text-xs">
|
||||
{formatters.relativeDate(i.createdAt)}
|
||||
</time>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "action",
|
||||
title: i18nT("analytics.action"),
|
||||
value: (i) => i.action,
|
||||
},
|
||||
{
|
||||
name: "category",
|
||||
title: i18nT("analytics.category"),
|
||||
value: (i) => i.category,
|
||||
},
|
||||
{
|
||||
name: "label",
|
||||
title: i18nT("analytics.label"),
|
||||
value: (i) => i.label,
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
title: i18nT("analytics.value"),
|
||||
value: (i) => i.value,
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: i18nT("analytics.url"),
|
||||
value: (i) => i.url,
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: i18nT("analytics.cookie"),
|
||||
value: (i) => <div className="truncate">{i.uniqueVisitor.cookie}</div>,
|
||||
className: "max-w-xs",
|
||||
},
|
||||
{
|
||||
name: "httpReferrer",
|
||||
title: i18nT("analytics.httpReferrer"),
|
||||
value: (i) => i.uniqueVisitor.httpReferrer,
|
||||
},
|
||||
{
|
||||
name: "browser",
|
||||
title: i18nT("analytics.browser"),
|
||||
value: (i) => i.uniqueVisitor.browser,
|
||||
},
|
||||
{
|
||||
name: "os",
|
||||
title: i18nT("analytics.os"),
|
||||
value: (i) => i.uniqueVisitor.os,
|
||||
},
|
||||
{
|
||||
name: "device",
|
||||
title: i18nT("analytics.device"),
|
||||
value: (i) => i.uniqueVisitor.device,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: i18nT("analytics.source"),
|
||||
value: (i) => i.uniqueVisitor.source,
|
||||
},
|
||||
{
|
||||
name: "medium",
|
||||
title: i18nT("analytics.medium"),
|
||||
value: (i) => i.uniqueVisitor.medium,
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
title: i18nT("analytics.campaign"),
|
||||
value: (i) => i.uniqueVisitor.campaign,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
title: i18nT("analytics.content"),
|
||||
value: (i) => i.uniqueVisitor.content,
|
||||
},
|
||||
{
|
||||
name: "term",
|
||||
title: i18nT("analytics.term"),
|
||||
value: (i) => i.uniqueVisitor.term,
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: i18nT("analytics.country"),
|
||||
value: (i) => i.uniqueVisitor.country,
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: i18nT("analytics.city"),
|
||||
value: (i) => i.uniqueVisitor.city,
|
||||
},
|
||||
{
|
||||
name: "fromUrl",
|
||||
title: i18nT("analytics.fromUrl"),
|
||||
value: (i) => i.uniqueVisitor.fromUrl,
|
||||
},
|
||||
{
|
||||
name: "fromRoute",
|
||||
title: i18nT("analytics.fromRoute"),
|
||||
value: (i) => i.uniqueVisitor.fromRoute,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/admin/analytics/overview.tsx";
|
||||
const tableRoutePaths = ["apps/web/app/routes/admin/analytics/visitors.tsx", "apps/web/app/routes/admin/analytics/events.tsx", "apps/web/app/routes/admin/analytics/page-views.tsx"];
|
||||
|
||||
function readRoute(route = routePath) {
|
||||
return readRepoFile(route);
|
||||
}
|
||||
|
||||
describe("admin 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: true");
|
||||
expect(source).toContain("portalId: undefined");
|
||||
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("keeps migrated table routes behind the package analytics boundary", () => {
|
||||
for (const tableRoutePath of tableRoutePaths) {
|
||||
const source = readRoute(tableRoutePath);
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).not.toContain('from "~/utils/db.server"');
|
||||
expect(source).not.toContain('from "~/utils/db/users.db.server"');
|
||||
expect(source).not.toContain('from "~/modules/featureFlags/db/featureFlags.db.server"');
|
||||
expect(source).not.toMatch(/\bdb\.analytics(?:UniqueVisitor|Event|PageView)\b/);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps migrated table route dates on locale-aware formatters", () => {
|
||||
const source = tableRoutePaths.map((tableRoutePath) => readRoute(tableRoutePath)).join("\n");
|
||||
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.dateTime");
|
||||
expect(source).toContain("formatters.relativeDate");
|
||||
expect(source).not.toContain("DateUtils");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { LoaderFunction } from "react-router";
|
||||
import { useLoaderData, useSearchParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import AnalyticsOverview from "~/components/analytics/AnalyticsOverview";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { defaultAnalyticsPeriod, getAnalyticsOverview, isAnalyticsPeriod, type AnalyticsOverview as AnalyticsOverviewDto } from "@toolctrl/db/analytics.server";
|
||||
import PeriodHelper, { defaultPeriodFilter, PeriodFilters } from "~/utils/helpers/PeriodHelper";
|
||||
import InputSelector from "~/components/ui/input/InputSelector";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
overview: AnalyticsOverviewDto;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const { locale } = await getTranslations(request);
|
||||
const period = PeriodHelper.getPeriodFromRequest({ request });
|
||||
const data: LoaderData = {
|
||||
overview: await getAnalyticsOverview({
|
||||
withUsers: true,
|
||||
period: isAnalyticsPeriod(period) ? period : defaultAnalyticsPeriod,
|
||||
portalId: undefined,
|
||||
locale,
|
||||
}),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { overview } = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<div className="flex justify-between gap-2">
|
||||
<Tabs
|
||||
breakpoint="lg"
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
|
||||
<InputSelector
|
||||
className="w-44"
|
||||
withSearch={false}
|
||||
name="period"
|
||||
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
|
||||
options={PeriodFilters.map((f) => {
|
||||
return {
|
||||
value: f.value,
|
||||
name: t(f.name),
|
||||
};
|
||||
})}
|
||||
setValue={(value) => {
|
||||
if (value && value !== defaultPeriodFilter) {
|
||||
searchParams.set("period", value?.toString() ?? "");
|
||||
} else {
|
||||
searchParams.delete("period");
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AnalyticsOverview overview={overview} withUsers={true} rootUrl={adminPath("analytics", { mode: "host-aware" })} />
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/admin/analytics/page-views.tsx";
|
||||
|
||||
function readRoute() {
|
||||
return readRepoFile(routePath);
|
||||
}
|
||||
|
||||
describe("admin analytics page views route DB boundary", () => {
|
||||
it("uses package analytics helpers while preserving route-side filter composition", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsPageViewFilterOptions");
|
||||
expect(source).toContain("getAnalyticsPageViewList");
|
||||
expect(source).toContain("RowFiltersHelper.getFiltersCondition(filters)");
|
||||
expect(source).toContain("portalFiltersEnabled");
|
||||
expect(source).toContain('f.name === "cookie"');
|
||||
expect(source).toContain('f.name === "userId"');
|
||||
});
|
||||
|
||||
it("does not import direct analytics DB wrappers", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).not.toContain('from "~/utils/db.server"');
|
||||
expect(source).not.toContain('from "~/utils/db/users.db.server"');
|
||||
expect(source).not.toMatch(/\bdb\.analytics(?:UniqueVisitor|PageView)\b/);
|
||||
expect(source).not.toMatch(/\bdb\.portal\b/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import { AnalyticsPageView, AnalyticsUniqueVisitor, Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { LoaderFunction, useLoaderData } from "react-router";
|
||||
import { 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 { useRootData } from "~/utils/data/useRootData";
|
||||
import { getAnalyticsPageViewFilterOptions, getAnalyticsPageViewList } from "@toolctrl/db/analytics.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
|
||||
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
items: (AnalyticsPageView & {
|
||||
uniqueVisitor: AnalyticsUniqueVisitor & {
|
||||
user: { email: string } | null;
|
||||
};
|
||||
portal: { id: string; title: string } | null;
|
||||
})[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
|
||||
const portalFiltersEnabled = Boolean(appConfiguration.portals?.enabled && appConfiguration.portals?.analytics);
|
||||
const filterOptions = await getAnalyticsPageViewFilterOptions({ includePortals: portalFiltersEnabled });
|
||||
|
||||
const filterableProperties: FilterablePropertyDto[] = [
|
||||
{
|
||||
name: "route",
|
||||
title: t("analytics.route"),
|
||||
options: filterOptions.routes,
|
||||
},
|
||||
{
|
||||
name: "userId",
|
||||
title: t("models.user.object"),
|
||||
manual: true,
|
||||
options: [{ name: t("analytics.anonymous"), value: "null" }, ...filterOptions.users],
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: t("analytics.cookie"),
|
||||
manual: true,
|
||||
},
|
||||
];
|
||||
if (portalFiltersEnabled) {
|
||||
filterableProperties.push({
|
||||
name: "portalId",
|
||||
title: t("models.portal.object"),
|
||||
options: [
|
||||
{
|
||||
value: "null",
|
||||
name: t("analytics.none"),
|
||||
},
|
||||
...filterOptions.portals,
|
||||
],
|
||||
});
|
||||
}
|
||||
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
||||
let where: Prisma.AnalyticsPageViewWhereInput = RowFiltersHelper.getFiltersCondition(filters);
|
||||
|
||||
const cookieFilter = filters.properties.find((f) => f.name === "cookie");
|
||||
if (cookieFilter?.value) {
|
||||
where = { ...where, uniqueVisitor: { cookie: cookieFilter.value } };
|
||||
}
|
||||
|
||||
const userFilter = filters.properties.find((f) => f.name === "userId");
|
||||
if (userFilter?.value) {
|
||||
where = { ...where, uniqueVisitor: { userId: userFilter.value === "null" ? null : userFilter.value } };
|
||||
}
|
||||
|
||||
const { items, totalItems } = await getAnalyticsPageViewList({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where,
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items: items as LoaderData["items"],
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsPageViewsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const rootData = useRootData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const portalsConfig = rootData?.appConfiguration.portals;
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<div className="flex justify-between gap-2">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
|
||||
<InputFilters filters={data.filterableProperties} />
|
||||
</div>
|
||||
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: t("analytics.date"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>
|
||||
<div>
|
||||
{i.uniqueVisitor.user ? (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (!i.uniqueVisitor.userId) return;
|
||||
searchParams.set("userId", i.uniqueVisitor.userId);
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
disabled={!i.uniqueVisitor.userId}
|
||||
className="underline"
|
||||
>
|
||||
<div className="text-xs">{i.uniqueVisitor.user.email}</div>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
searchParams.set("cookie", i.uniqueVisitor.cookie);
|
||||
setSearchParams(searchParams);
|
||||
}}
|
||||
className="underline"
|
||||
>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
<span>{t("analytics.anonymous")}</span>: {i.uniqueVisitor.cookie.substring(0, 5) + "..."}
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<time title={formatters.dateTime(i.createdAt, { timeStyle: "medium" })} className="text-muted-foreground text-xs">
|
||||
{formatters.relativeDate(i.createdAt)}
|
||||
</time>
|
||||
</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: "portal",
|
||||
title: t("models.portal.object"),
|
||||
value: (i) => <div className="text-muted-foreground font-medium">{i.portal?.title}</div>,
|
||||
hidden: !portalsConfig?.enabled || !portalsConfig?.analytics,
|
||||
},
|
||||
{
|
||||
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>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
|
||||
vi.mock("@toolctrl/db/analytics.server", () => ({
|
||||
deleteAllAnalyticsData: vi.fn(),
|
||||
getOrCreateAnalyticsSettings: vi.fn(),
|
||||
removeAnalyticsIgnoredPage: vi.fn(),
|
||||
updateAnalyticsSettingsPreferences: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/impersonation-audit.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("@toolctrl/db/impersonation-audit.server")>("@toolctrl/db/impersonation-audit.server");
|
||||
return {
|
||||
...actual,
|
||||
createImpersonationAudit: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("@toolctrl/db/audit-events.server", () => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
import { deleteAllAnalyticsData } from "@toolctrl/db/analytics.server";
|
||||
import { createImpersonationAudit, IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { action } from "./settings";
|
||||
|
||||
function deleteAllRequest(body: Record<string, string> = {}) {
|
||||
return new Request("https://admin.example.test/analytics/settings?tab=danger", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: "delete-all", ...body }),
|
||||
});
|
||||
}
|
||||
|
||||
async function callDeleteAll(body: Record<string, string> = {}) {
|
||||
return action({
|
||||
request: deleteAllRequest(body),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/analytics/settings",
|
||||
} as ActionFunctionArgs) as Promise<Response>;
|
||||
}
|
||||
|
||||
describe("admin analytics settings route DB boundary", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user-1", lightOrDarkMode: "light", lng: "en", cookies: [] } as never);
|
||||
});
|
||||
|
||||
it("uses package-owned analytics settings helpers", () => {
|
||||
expect(deleteAllAnalyticsData).toBeDefined();
|
||||
});
|
||||
|
||||
it("keeps visible delete confirmation text behind locale keys", () => {
|
||||
const source = readFileSync(path.resolve(process.cwd(), "apps/web/app/routes/admin/analytics/settings.tsx"), "utf8");
|
||||
const en = JSON.parse(readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/en/translations.json"), "utf8"));
|
||||
const de = JSON.parse(readFileSync(path.resolve(process.cwd(), "apps/web/public/locales/de/translations.json"), "utf8"));
|
||||
|
||||
expect(source).toContain("analytics.danger.confirmText");
|
||||
expect(source).not.toContain('"delete all analytics data"');
|
||||
expect(source).not.toContain("`delete all analytics data`");
|
||||
expect(en.analytics.danger.confirmText).toBe("delete all analytics data");
|
||||
expect(de.analytics.danger.confirmText).toBe("alle Analytics-Daten löschen");
|
||||
});
|
||||
|
||||
it("deletes analytics data for normal sessions", async () => {
|
||||
const response = await callDeleteAll();
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ deleteSuccess: true });
|
||||
expect(response.status).toBe(200);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.analytics.delete");
|
||||
expect(deleteAllAnalyticsData).toHaveBeenCalledTimes(1);
|
||||
expect(createImpersonationAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("blocks impersonated deletion without the explicit impersonation phrase", async () => {
|
||||
vi.mocked(getUserInfo).mockResolvedValue({
|
||||
userId: "target-user-1",
|
||||
impersonatingFromUserId: "actor-user-1",
|
||||
lightOrDarkMode: "light",
|
||||
lng: "en",
|
||||
cookies: [],
|
||||
} as never);
|
||||
|
||||
const response = await callDeleteAll({ "impersonation-confirm": "delete all analytics data" });
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ deleteError: "admin.analytics.settings.errors.confirmImpersonatedDelete" });
|
||||
expect(response.status).toBe(400);
|
||||
expect(deleteAllAnalyticsData).not.toHaveBeenCalled();
|
||||
expect(createImpersonationAudit).toHaveBeenCalledWith({
|
||||
actorUserId: "actor-user-1",
|
||||
targetUserId: "target-user-1",
|
||||
tenantId: null,
|
||||
action: "destructive_action_blocked",
|
||||
reason: "analytics.delete-all",
|
||||
requestPath: "/analytics/settings",
|
||||
});
|
||||
});
|
||||
|
||||
it("allows impersonated deletion with the explicit impersonation phrase", async () => {
|
||||
vi.mocked(getUserInfo).mockResolvedValue({
|
||||
userId: "target-user-1",
|
||||
impersonatingFromUserId: "actor-user-1",
|
||||
lightOrDarkMode: "light",
|
||||
lng: "en",
|
||||
cookies: [],
|
||||
} as never);
|
||||
|
||||
const response = await callDeleteAll({ "impersonation-confirm": IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION });
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ deleteSuccess: true });
|
||||
expect(response.status).toBe(200);
|
||||
expect(deleteAllAnalyticsData).toHaveBeenCalledTimes(1);
|
||||
expect(createImpersonationAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,262 @@
|
||||
import { loadWebConfig } from "@toolctrl/config";
|
||||
import type { AnalyticsSettings } from "@toolctrl/db/analytics.server";
|
||||
import {
|
||||
deleteAllAnalyticsData,
|
||||
getOrCreateAnalyticsSettings,
|
||||
removeAnalyticsIgnoredPage,
|
||||
updateAnalyticsSettingsPreferences,
|
||||
} from "@toolctrl/db/analytics.server";
|
||||
import { IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION } from "@toolctrl/db/impersonation-audit.constants";
|
||||
import { createImpersonationAudit } from "@toolctrl/db/impersonation-audit.server";
|
||||
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
|
||||
import { extractWebActorIp, extractWebActorUserAgent } from "~/utils/audit/withAuditContext";
|
||||
import { ActionFunction, LoaderFunction } from "react-router";
|
||||
import { Form, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputText from "~/components/ui/input/InputText";
|
||||
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 { useRootData } from "~/utils/data/useRootData";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absoluteAdminPath } from "~/utils/app/CrossHostUrls";
|
||||
|
||||
type LoaderData = {
|
||||
settings: AnalyticsSettings;
|
||||
isLocalDev: boolean;
|
||||
};
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.delete");
|
||||
const settings = await getOrCreateAnalyticsSettings();
|
||||
const data: LoaderData = {
|
||||
settings,
|
||||
isLocalDev: loadWebConfig().config.nodeEnv === "development",
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
deleteError?: string;
|
||||
deleteSuccess?: boolean;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.delete");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "delete-all") {
|
||||
const userInfo = await getUserInfo(request);
|
||||
const impersonationConfirmation = form.get("impersonation-confirm")?.toString() ?? "";
|
||||
if (userInfo.impersonatingFromUserId && impersonationConfirmation !== IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION) {
|
||||
await createImpersonationAudit({
|
||||
actorUserId: userInfo.impersonatingFromUserId,
|
||||
targetUserId: userInfo.userId,
|
||||
tenantId: null,
|
||||
action: "destructive_action_blocked",
|
||||
reason: "analytics.delete-all",
|
||||
requestPath: new URL(request.url).pathname,
|
||||
});
|
||||
// Phase 10 Task #67: consolidated AuditEvent for compliance export.
|
||||
await createAuditEvent({
|
||||
tenantId: null,
|
||||
actorId: userInfo.impersonatingFromUserId,
|
||||
actorType: "admin",
|
||||
actorIp: extractWebActorIp(request),
|
||||
actorUserAgent: extractWebActorUserAgent(request),
|
||||
action: "admin.impersonation.destructive_blocked",
|
||||
targetType: "user",
|
||||
targetId: userInfo.userId,
|
||||
sourceModule: "admin",
|
||||
outcome: "blocked",
|
||||
dataSensitivity: "confidential",
|
||||
regulatoryScope: ["soc2"],
|
||||
metadata: { requestPath: new URL(request.url).pathname, reason: "analytics.delete-all" },
|
||||
});
|
||||
return Response.json({ deleteError: t("admin.analytics.settings.errors.confirmImpersonatedDelete") }, { status: 400 });
|
||||
}
|
||||
|
||||
await deleteAllAnalyticsData();
|
||||
return Response.json({
|
||||
deleteSuccess: true,
|
||||
});
|
||||
}
|
||||
if (action === "set-settings") {
|
||||
const isPublicStr = form.get("public");
|
||||
const isPublic = isPublicStr === "true" || isPublicStr === "on";
|
||||
const ignorePage = form.get("ignore-page")?.toString() ?? "";
|
||||
await updateAnalyticsSettingsPreferences({ public: isPublic, ignorePage });
|
||||
return Response.json({
|
||||
setSettingsSuccess: true,
|
||||
});
|
||||
}
|
||||
if (action === "remove-ignored-page") {
|
||||
const ignoredPage = form.get("ignored-page")?.toString() ?? "";
|
||||
await removeAnalyticsIgnoredPage(ignoredPage);
|
||||
return Response.json({
|
||||
setSettingsSuccess: true,
|
||||
});
|
||||
} else {
|
||||
return Response.json({
|
||||
error: t("shared.invalidForm"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const isUpdatingSettings = navigation.state === "submitting" && navigation.formData?.get("action") === "set-settings";
|
||||
const rootData = useRootData();
|
||||
const analyticsOverviewUrl = absoluteAdminPath(rootData.routing, "analytics/overview");
|
||||
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const confirmDelete = useRef<RefConfirmModal>(null);
|
||||
const textToType = t("analytics.danger.confirmText");
|
||||
|
||||
const [typeToConfirm, setTypeToConfirm] = useState<string>(data.isLocalDev ? textToType : "");
|
||||
const [isPublic, setIsPublic] = useState(data?.settings.public);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isUpdatingSettings) {
|
||||
formRef.current?.reset();
|
||||
}
|
||||
}, [isUpdatingSettings]);
|
||||
|
||||
function removeIgnoredPage(item: string) {
|
||||
const form = new FormData();
|
||||
form.set("action", "remove-ignored-page");
|
||||
form.set("ignored-page", item);
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
function onDelete() {
|
||||
confirmDelete.current?.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
|
||||
function onDeleteConfirm() {
|
||||
const form = new FormData();
|
||||
form.set("action", "delete-all");
|
||||
form.set("impersonation-confirm", typeToConfirm);
|
||||
form.set("csrf", rootData.csrf ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
const impersonationTextToType = IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION;
|
||||
const requiredDeleteConfirmation = rootData.impersonatingSession ? impersonationTextToType : textToType;
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<div className="flex justify-between gap-2">
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6 p-4 sm:px-6 lg:col-span-9 lg:px-0">
|
||||
<SettingSection title={t("analytics.preferences.title")} description={t("analytics.preferences.description")}>
|
||||
<Form ref={formRef} method="post">
|
||||
<input hidden readOnly name="action" value="set-settings" />
|
||||
<input hidden readOnly name="csrf" value={rootData.csrf ?? ""} />
|
||||
<div className="space-y-2">
|
||||
<InputCheckboxWithDescription
|
||||
name="public"
|
||||
title={t("shared.public")}
|
||||
description={
|
||||
<div className="text-muted-foreground">
|
||||
{t("analytics.preferences.publicDescription")}{" "}
|
||||
<a className="underline" target="_blank" rel="noreferrer" href={analyticsOverviewUrl}>
|
||||
{analyticsOverviewUrl}
|
||||
</a>
|
||||
</div>
|
||||
}
|
||||
value={isPublic}
|
||||
setValue={setIsPublic}
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<div className="text-muted-foreground text-sm font-medium">{t("analytics.preferences.ignoredPages")}</div>
|
||||
<div className="border-border bg-secondary space-y-1 rounded-md border p-3">
|
||||
{data.settings.ignorePages.length === 0 && <div className="text-muted-foreground text-xs">{t("analytics.preferences.noIgnoredPages")}</div>}
|
||||
{data.settings.ignorePages
|
||||
.split(",")
|
||||
.filter((f) => f)
|
||||
.map((item) => {
|
||||
return (
|
||||
<div key={item} className="text-muted-foreground border-border group flex space-x-2 border-b text-xs">
|
||||
<div>{item}</div>
|
||||
<button type="button" className="hidden text-xs text-red-500 underline group-hover:block" onClick={() => removeIgnoredPage(item)}>
|
||||
{t("shared.remove")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<InputText name="ignore-page" title={t("analytics.preferences.addIgnoredPage")} defaultValue="" />
|
||||
</div>
|
||||
<div className="border-border mt-3 flex items-center justify-end space-x-2 border-t pt-3">
|
||||
<LoadingButton type="submit" disabled={isUpdatingSettings}>
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
</SettingSection>
|
||||
|
||||
<SettingSection title={t("analytics.danger.title")} description={t("analytics.danger.description")}>
|
||||
<div>
|
||||
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
||||
<p>{t("analytics.danger.reset.description")}</p>
|
||||
</div>
|
||||
<div className="mt-5 space-y-2">
|
||||
<div>
|
||||
<InputText title={t("analytics.danger.confirm", { value: requiredDeleteConfirmation })} value={typeToConfirm} setValue={setTypeToConfirm} />
|
||||
</div>
|
||||
<div>
|
||||
<ButtonPrimary disabled={typeToConfirm !== requiredDeleteConfirmation} destructive={true} onClick={onDelete}>
|
||||
{t("analytics.danger.reset.title")}
|
||||
</ButtonPrimary>
|
||||
|
||||
{actionData?.deleteSuccess ? (
|
||||
<p className="py-2 text-xs text-green-500" role="alert">
|
||||
{t("analytics.deleted")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{actionData?.deleteError ? (
|
||||
<p className="py-2 text-xs text-rose-500" role="alert">
|
||||
{actionData.deleteError}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirm} destructive />
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const routePath = "apps/web/app/routes/admin/analytics/visitors.tsx";
|
||||
|
||||
function readRoute() {
|
||||
return readRepoFile(routePath);
|
||||
}
|
||||
|
||||
describe("admin analytics visitors route DB boundary", () => {
|
||||
it("uses the package analytics visitor list helper with pagination", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).toContain("@toolctrl/db/analytics.server");
|
||||
expect(source).toContain("getAnalyticsVisitorList");
|
||||
expect(source).toContain("take: pagination.pageSize");
|
||||
expect(source).toContain("skip: pagination.pageSize * (pagination.page - 1)");
|
||||
});
|
||||
|
||||
it("does not import direct analytics DB access", () => {
|
||||
const source = readRoute();
|
||||
|
||||
expect(source).not.toContain('from "~/utils/db.server"');
|
||||
expect(source).not.toMatch(/\bdb\.analyticsUniqueVisitor\b/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { AnalyticsUniqueVisitor } from "@toolctrl/db/prisma-browser";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { LoaderFunction, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getAnalyticsVisitorList } from "@toolctrl/db/analytics.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import Tabs from "~/components/ui/tabs/Tabs";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type LoaderData = {
|
||||
items: (AnalyticsUniqueVisitor & {
|
||||
_count: {
|
||||
pageViews: number;
|
||||
events: number;
|
||||
};
|
||||
})[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.analytics.view");
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
const { items, totalItems } = await getAnalyticsVisitorList({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items: items as unknown as LoaderData["items"],
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsPageViewsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout>
|
||||
<Tabs
|
||||
tabs={[
|
||||
{ name: t("analytics.overview"), routePath: adminPath("analytics/overview", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.uniqueVisitors"), routePath: adminPath("analytics/visitors", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.pageViews"), routePath: adminPath("analytics/page-views", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.events"), routePath: adminPath("analytics/events", { mode: "host-aware" }) },
|
||||
{ name: t("analytics.settings"), routePath: adminPath("analytics/settings", { mode: "host-aware" }) },
|
||||
]}
|
||||
className="grow"
|
||||
/>
|
||||
|
||||
<div>
|
||||
<TableSimple
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "date",
|
||||
title: i18nT("analytics.date"),
|
||||
value: (i) => (
|
||||
<time title={formatters.dateTime(i.createdAt, { timeStyle: "medium" })} className="text-muted-foreground text-xs">
|
||||
{formatters.relativeDate(i.createdAt)}
|
||||
</time>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "httpReferrer",
|
||||
title: i18nT("analytics.httpReferrer"),
|
||||
value: (i) => i.httpReferrer,
|
||||
},
|
||||
{
|
||||
name: "via",
|
||||
title: i18nT("analytics.via"),
|
||||
value: (i) => i.via,
|
||||
},
|
||||
{
|
||||
name: "browser",
|
||||
title: i18nT("analytics.browser"),
|
||||
value: (i) => i.browser,
|
||||
},
|
||||
{
|
||||
name: "os",
|
||||
title: i18nT("analytics.os"),
|
||||
value: (i) => i.os,
|
||||
},
|
||||
{
|
||||
name: "device",
|
||||
title: i18nT("analytics.device"),
|
||||
value: (i) => i.device,
|
||||
},
|
||||
{
|
||||
name: "source",
|
||||
title: i18nT("analytics.source"),
|
||||
value: (i) => i.source,
|
||||
},
|
||||
{
|
||||
name: "medium",
|
||||
title: i18nT("analytics.medium"),
|
||||
value: (i) => i.medium,
|
||||
},
|
||||
{
|
||||
name: "campaign",
|
||||
title: i18nT("analytics.campaign"),
|
||||
value: (i) => i.campaign,
|
||||
},
|
||||
{
|
||||
name: "content",
|
||||
title: i18nT("analytics.content"),
|
||||
value: (i) => i.content,
|
||||
},
|
||||
{
|
||||
name: "term",
|
||||
title: i18nT("analytics.term"),
|
||||
value: (i) => i.term,
|
||||
},
|
||||
{
|
||||
name: "country",
|
||||
title: i18nT("analytics.country"),
|
||||
value: (i) => i.country,
|
||||
},
|
||||
{
|
||||
name: "city",
|
||||
title: i18nT("analytics.city"),
|
||||
value: (i) => i.city,
|
||||
},
|
||||
{
|
||||
name: "fromUrl",
|
||||
title: i18nT("analytics.fromUrl"),
|
||||
value: (i) => i.fromUrl,
|
||||
},
|
||||
{
|
||||
name: "fromRoute",
|
||||
title: i18nT("analytics.fromRoute"),
|
||||
value: (i) => i.fromRoute,
|
||||
},
|
||||
{
|
||||
name: "cookie",
|
||||
title: i18nT("analytics.cookie"),
|
||||
value: (i) => i.cookie.substring(0, 5) + "...",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user