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,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readRepoFile } from "~/utils/testing/repoPaths";
|
||||
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/metrics/logs.tsx",
|
||||
"apps/web/app/routes/admin/metrics/summary.tsx",
|
||||
"apps/web/app/routes/admin/settings/cache.tsx",
|
||||
];
|
||||
|
||||
describe("admin metrics and cache i18n formatting", () => {
|
||||
it("uses locale-aware formatters for visible dates, durations, counts, and sizes", () => {
|
||||
const sources = sourceFiles.map((file) => readRepoFile(file)).join("\n");
|
||||
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("createLocaleFormatters");
|
||||
expect(sources).toContain('unit: "millisecond"');
|
||||
expect(sources).toContain('unit: "megabyte"');
|
||||
expect(sources).not.toContain("DateUtils");
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
expect(sources).not.toContain("toFixed(");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
});
|
||||
|
||||
it("keeps destructive metrics count labels plural-aware", () => {
|
||||
const en = JSON.parse(readRepoFile("apps/web/public/locales/en/translations.json"));
|
||||
const de = JSON.parse(readRepoFile("apps/web/public/locales/de/translations.json"));
|
||||
|
||||
expect(en.admin.metrics.deleteLogsButton_one).toBe("Delete {{count}} log");
|
||||
expect(en.admin.metrics.deleteLogsButton_other).toBe("Delete {{count}} logs");
|
||||
expect(en.admin.metrics.deleteSelectedButton_one).toBe("Delete {{count}} log entry");
|
||||
expect(en.admin.metrics.deleteSelectedButton_other).toBe("Delete {{count}} log entries");
|
||||
expect(de.admin.metrics.deleteSelectedButton_one).toContain("Protokolleintrag");
|
||||
expect(de.admin.metrics.deleteSelectedButton_other).toContain("Protokolleinträge");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
import { MetricLog, Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunction, LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { useSearchParams, useSubmit } from "react-router";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import RefreshIcon from "~/components/ui/icons/RefreshIcon";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import InputSearchWithURL from "~/components/ui/input/InputSearchWithURL";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { FilterableValueLink } from "~/components/ui/links/FilterableValueLink";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import SpeedBadge from "~/modules/metrics/components/SpeedBadge";
|
||||
import MetricService from "~/modules/metrics/services/MetricService";
|
||||
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { UserSimple } from "~/utils/db/users.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type ItemDto = MetricLog & {
|
||||
tenant: Tenant | null;
|
||||
user: UserSimple | null;
|
||||
};
|
||||
type LoaderData = {
|
||||
items: ItemDto[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.metrics.view");
|
||||
const { filterableProperties, whereFilters } = await MetricService.getFilters({ request });
|
||||
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const pagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
|
||||
const items = await db.metricLog.findMany({
|
||||
take: pagination.pageSize,
|
||||
skip: pagination.pageSize * (pagination.page - 1),
|
||||
where: whereFilters,
|
||||
include: {
|
||||
tenant: true,
|
||||
user: { select: UserModelHelper.selectSimpleUserProperties },
|
||||
},
|
||||
orderBy: !pagination.sortedBy.length
|
||||
? { createdAt: "desc" }
|
||||
: pagination.sortedBy.map((x) => ({
|
||||
[x.name]: x.direction,
|
||||
})),
|
||||
});
|
||||
const totalItems = await db.metricLog.count({
|
||||
where: whereFilters,
|
||||
});
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
filterableProperties,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.metrics.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
if (form.get("action") === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.metrics.delete");
|
||||
const ids = (form.get("ids")?.toString().split(",") ?? []).map((x) => x.toString() ?? "");
|
||||
await db.metricLog.deleteMany({
|
||||
where: { id: { in: ids } },
|
||||
});
|
||||
return Response.json({ success: true });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm"), success: false }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const submit = useSubmit();
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const [selectedRows, setSelectedRows] = useState<ItemDto[]>([]);
|
||||
function onDelete(ids: string[]) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
form.set("ids", ids.join(","));
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
// title="Metrics"
|
||||
// replaceTitleWithTabs={true}
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.metrics.tabs.summary"),
|
||||
routePath: adminPath("metrics/summary", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.metrics.tabs.logs"),
|
||||
routePath: adminPath("metrics/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.metrics.tabs.settings"),
|
||||
routePath: adminPath("metrics/settings", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<div className="flex w-full items-center space-x-2">
|
||||
<div className="grow">
|
||||
<InputSearchWithURL />
|
||||
</div>
|
||||
{selectedRows.length > 0 && (
|
||||
<ButtonSecondary
|
||||
destructive
|
||||
disabled={!getUserHasPermission(appOrAdminData, "admin.metrics.delete")}
|
||||
onClick={() => {
|
||||
onDelete(selectedRows.map((x) => x.id));
|
||||
setSelectedRows([]);
|
||||
}}
|
||||
>
|
||||
{t("admin.metrics.deleteSelectedButton", { count: selectedRows.length })}
|
||||
</ButtonSecondary>
|
||||
)}
|
||||
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
<Button type="button" variant="secondary" size="sm" onClick={() => setSearchParams(searchParams)}>
|
||||
<RefreshIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<TableSimple
|
||||
selectedRows={selectedRows}
|
||||
onSelected={setSelectedRows}
|
||||
items={data.items}
|
||||
pagination={data.pagination}
|
||||
headers={[
|
||||
{
|
||||
name: "route",
|
||||
title: t("admin.metrics.columns.route"),
|
||||
value: (item) => <FilterableValueLink name="route" value={item.route} />,
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
title: t("admin.metrics.columns.url"),
|
||||
value: (item) => <FilterableValueLink name="url" value={item.url} />,
|
||||
},
|
||||
{
|
||||
name: "function",
|
||||
title: t("admin.metrics.columns.function"),
|
||||
value: (item) => <FilterableValueLink name="function" value={item.function} />,
|
||||
className: "w-full",
|
||||
},
|
||||
{
|
||||
name: "speed",
|
||||
title: t("admin.metrics.columns.speed"),
|
||||
value: (item) => <SpeedBadge duration={item.duration} />,
|
||||
},
|
||||
{
|
||||
sortBy: "duration",
|
||||
name: "duration",
|
||||
title: t("admin.metrics.columns.duration"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
{formatters.number(item.duration, {
|
||||
style: "unit",
|
||||
unit: "millisecond",
|
||||
unitDisplay: "short",
|
||||
minimumFractionDigits: 3,
|
||||
maximumFractionDigits: 3,
|
||||
})}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "type",
|
||||
title: t("admin.metrics.columns.type"),
|
||||
value: (item) => <FilterableValueLink name="type" value={item.type} />,
|
||||
},
|
||||
{
|
||||
name: "tenant",
|
||||
title: t("admin.metrics.columns.tenant"),
|
||||
value: (item) => <FilterableValueLink name="tenantId" value={item.tenant?.name} param={item.tenant?.id} />,
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
title: t("admin.metrics.columns.user"),
|
||||
value: (item) => <FilterableValueLink name="userId" value={item.user?.email} param={item.user?.id} />,
|
||||
},
|
||||
{
|
||||
name: "env",
|
||||
title: t("admin.metrics.columns.env"),
|
||||
value: (item) => <FilterableValueLink name="env" value={item.env} />,
|
||||
},
|
||||
{
|
||||
sortBy: "createdAt",
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (item) => formatters.dateTime(item.createdAt, { timeStyle: "medium" }),
|
||||
formattedValue: (item) => (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{item.createdAt && <span>{formatters.dateTime(item.createdAt, { timeStyle: "medium" })}</span>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: "",
|
||||
value: (item) => (
|
||||
<button type="button" onClick={() => onDelete([item.id])} className="text-red-600 hover:text-red-900 hover:underline">
|
||||
{t("shared.delete")}
|
||||
</button>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { action } from "./settings";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
metricLog: {
|
||||
count: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
||||
getAppConfiguration: vi.fn(),
|
||||
getOrCreateAppConfiguration: vi.fn(),
|
||||
updateAppConfiguration: 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) =>
|
||||
({
|
||||
"admin.metrics.logsDeleted": "Metrics logs deleted.",
|
||||
"shared.invalidForm": "Invalid form.",
|
||||
})[key] ?? key,
|
||||
})),
|
||||
}));
|
||||
|
||||
function postRequest(form: FormData) {
|
||||
return new Request("https://admin.example.test/metrics/settings", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(form as unknown as Record<string, string>),
|
||||
});
|
||||
}
|
||||
|
||||
function formWithAction(value: string) {
|
||||
const form = new FormData();
|
||||
form.set("action", value);
|
||||
return form;
|
||||
}
|
||||
|
||||
describe("admin metrics settings action", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(verifyUserHasPermission).mockResolvedValue(undefined as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined as never);
|
||||
vi.mocked(db.metricLog.deleteMany).mockResolvedValue({ count: 2 } as never);
|
||||
vi.mocked(updateAppConfiguration).mockResolvedValue(undefined as never);
|
||||
});
|
||||
|
||||
it("returns the localized invalid form message without mutating settings or logs", async () => {
|
||||
const response = (await action({
|
||||
request: postRequest(formWithAction("rotate")),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/metrics/settings",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ error: "Invalid form." });
|
||||
expect(response.status).toBe(400);
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "admin.metrics.update");
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(updateAppConfiguration).not.toHaveBeenCalled();
|
||||
expect(db.metricLog.deleteMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the localized delete success message after the delete permission check", async () => {
|
||||
const response = (await action({
|
||||
request: postRequest(formWithAction("delete")),
|
||||
params: {},
|
||||
context: {},
|
||||
unstable_pattern: "admin/metrics/settings",
|
||||
})) as Response;
|
||||
|
||||
await expect(response.json()).resolves.toEqual({ success: "Metrics logs deleted." });
|
||||
expect(response.status).toBe(200);
|
||||
expect(verifyUserHasPermission).toHaveBeenNthCalledWith(1, expect.any(Request), "admin.metrics.update");
|
||||
expect(verifyUserHasPermission).toHaveBeenNthCalledWith(2, expect.any(Request), "admin.metrics.delete");
|
||||
expect(db.metricLog.deleteMany).toHaveBeenCalledWith({ where: {} });
|
||||
expect(updateAppConfiguration).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { Form, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
|
||||
import InputMultiText from "~/components/ui/input/InputMultiText";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { AppConfiguration, getAppConfiguration, getOrCreateAppConfiguration, updateAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
type LoaderData = {
|
||||
totalMetricLogs: number;
|
||||
appConfiguration: AppConfiguration;
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
await verifyUserHasPermission(request, "admin.metrics.view");
|
||||
await getOrCreateAppConfiguration({ request });
|
||||
const data: LoaderData = {
|
||||
totalMetricLogs: await db.metricLog.count(),
|
||||
appConfiguration: await getAppConfiguration({ request }),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.metrics.update");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "set-settings") {
|
||||
const ignoreUrls: RowValueMultipleDto[] = form.getAll("ignoreUrls[]").map((f: FormDataEntryValue) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
await updateAppConfiguration({
|
||||
metricsEnabled: ["true", "on"].includes(form.get("enabled")?.toString() ?? "false"),
|
||||
metricsLogToConsole: ["true", "on"].includes(form.get("logToConsole")?.toString() ?? "false"),
|
||||
metricsSaveToDatabase: ["true", "on"].includes(form.get("saveToDatabase")?.toString() ?? "false"),
|
||||
metricsIgnoreUrls: ignoreUrls
|
||||
.filter((f) => !!f.value)
|
||||
.map((i) => i.value)
|
||||
.sort()
|
||||
.join(","),
|
||||
});
|
||||
|
||||
return Response.json({ success: true });
|
||||
} else if (action === "delete") {
|
||||
await verifyUserHasPermission(request, "admin.metrics.delete");
|
||||
await db.metricLog.deleteMany({ where: {} });
|
||||
return Response.json({ success: t("admin.metrics.logsDeleted") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const rootData = useRootData();
|
||||
|
||||
const confirmModalDelete = useRef<RefConfirmModal>(null);
|
||||
|
||||
const [enabled, setEnabled] = useState<boolean>(data.appConfiguration.metrics.enabled);
|
||||
const [logToConsole, setLogToConsole] = useState<boolean>(data.appConfiguration.metrics.logToConsole);
|
||||
const [saveToDatabase, setSaveToDatabase] = useState<boolean>(data.appConfiguration.metrics.saveToDatabase);
|
||||
const [ignoredUrls, setIgnoredUrls] = useState<string[]>(data.appConfiguration.metrics.ignoreUrls.sort());
|
||||
|
||||
useEffect(() => {
|
||||
setEnabled(data.appConfiguration.metrics.enabled);
|
||||
setLogToConsole(data.appConfiguration.metrics.logToConsole);
|
||||
setSaveToDatabase(data.appConfiguration.metrics.saveToDatabase);
|
||||
setIgnoredUrls(data.appConfiguration.metrics.ignoreUrls.sort());
|
||||
}, [data]);
|
||||
|
||||
function canUpdate() {
|
||||
return navigation.state === "idle" && getUserHasPermission(appOrAdminData, "admin.metrics.update");
|
||||
}
|
||||
function canDelete() {
|
||||
return getUserHasPermission(appOrAdminData, "admin.metrics.delete") && data.totalMetricLogs > 0;
|
||||
}
|
||||
function onDelete() {
|
||||
confirmModalDelete.current?.show(t("admin.metrics.deleteLogsTitle"), t("shared.delete"), t("shared.cancel"), t("admin.metrics.deleteLogsDescription"));
|
||||
}
|
||||
|
||||
function onConfirmedDelete() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
// setBlocks(data.page.blocks);
|
||||
}
|
||||
return (
|
||||
<EditPageLayout
|
||||
// title="Metrics"
|
||||
// replaceTitleWithTabs={true}
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.metrics.tabs.summary"),
|
||||
routePath: adminPath("metrics/summary", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.metrics.tabs.logs"),
|
||||
routePath: adminPath("metrics/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.metrics.tabs.settings"),
|
||||
routePath: adminPath("metrics/settings", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Form method="post" className="space-y-2 px-3">
|
||||
{rootData.csrf && <input hidden readOnly name="csrf" value={rootData.csrf} />}
|
||||
<input name="action" value="set-settings" hidden readOnly />
|
||||
<div className="grid grid-cols-1 gap-y-6 sm:grid-cols-6 sm:gap-x-6">
|
||||
<div className="sm:col-span-6">
|
||||
<InputCheckboxWithDescription
|
||||
name="enabled"
|
||||
value={enabled}
|
||||
title={t("admin.metrics.enabled")}
|
||||
description={t("admin.metrics.enabledDescription")}
|
||||
disabled={!canUpdate()}
|
||||
setValue={(e) => setEnabled(e)}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
name="logToConsole"
|
||||
value={logToConsole}
|
||||
title={t("admin.metrics.logToConsole")}
|
||||
description={t("admin.metrics.logToConsoleDescription")}
|
||||
disabled={!canUpdate()}
|
||||
setValue={(e) => setLogToConsole(e)}
|
||||
/>
|
||||
<InputCheckboxWithDescription
|
||||
name="saveToDatabase"
|
||||
value={saveToDatabase}
|
||||
title={t("admin.metrics.saveToDatabase")}
|
||||
description={t("admin.metrics.saveToDatabaseDescription")}
|
||||
disabled={!canUpdate()}
|
||||
setValue={(e) => setSaveToDatabase(e)}
|
||||
/>
|
||||
<InputMultiText
|
||||
name="ignoreUrls"
|
||||
title={t("admin.metrics.ignoredUrls")}
|
||||
value={ignoredUrls.map((f, idx) => {
|
||||
return {
|
||||
order: idx,
|
||||
value: f,
|
||||
};
|
||||
})}
|
||||
disabled={!canUpdate()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-border flex justify-between space-x-2 border-t pt-3">
|
||||
<ButtonTertiary
|
||||
destructive
|
||||
disabled={!canDelete() || (navigation.state === "submitting" && navigation.formData?.get("action") !== "delete")}
|
||||
onClick={onDelete}
|
||||
>
|
||||
{t("admin.metrics.deleteLogsButton", { count: data.totalMetricLogs })}
|
||||
</ButtonTertiary>
|
||||
<div className="flex items-center space-x-2">
|
||||
<LoadingButton type="submit" disabled={!canUpdate()}>
|
||||
{t("shared.save")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
</div>
|
||||
<ActionResultModal actionData={actionData} showSuccess={false} />
|
||||
<ConfirmModal ref={confirmModalDelete} onYes={onConfirmedDelete} />
|
||||
</Form>
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
import { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import { LoaderFunctionArgs, useLoaderData } from "react-router";
|
||||
import { Link, useSearchParams } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
||||
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import InputCombobox from "~/components/ui/input/InputCombobox";
|
||||
import InputFilters from "~/components/ui/input/InputFilters";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import { FilterableValueLink } from "~/components/ui/links/FilterableValueLink";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import SpeedBadge from "~/modules/metrics/components/SpeedBadge";
|
||||
import MetricService from "~/modules/metrics/services/MetricService";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { createLocaleFormatters } from "~/locale/format";
|
||||
|
||||
const defaultGroupBy = ["function"];
|
||||
|
||||
type ItemDto = {
|
||||
userId: string | null;
|
||||
tenantId: string | null;
|
||||
function: string;
|
||||
route: string;
|
||||
url: string;
|
||||
env: string;
|
||||
type: string;
|
||||
_avg: {
|
||||
duration: number | null;
|
||||
};
|
||||
_count: {
|
||||
_all: number;
|
||||
};
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
items: ItemDto[];
|
||||
users: { id: string; email: string }[];
|
||||
tenants: { id: string; name: string }[];
|
||||
filterableProperties: FilterablePropertyDto[];
|
||||
};
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.metrics.view");
|
||||
const { filterableProperties, whereFilters } = await MetricService.getFilters({ request });
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
|
||||
let users: { id: string; email: string }[] = [];
|
||||
let tenants: { id: string; name: string }[] = [];
|
||||
|
||||
let groupBy = getGroupByValues(searchParams);
|
||||
let items: ItemDto[] = [];
|
||||
if (groupBy.length > 0) {
|
||||
const data = await db.metricLog.groupBy({
|
||||
by: groupBy.map((x) => x as Prisma.MetricLogScalarFieldEnum),
|
||||
where: whereFilters,
|
||||
_avg: { duration: true },
|
||||
_count: { _all: true },
|
||||
orderBy: {
|
||||
_avg: { duration: "desc" },
|
||||
},
|
||||
});
|
||||
items = data.map((x) => x as ItemDto);
|
||||
const userIds: string[] = [];
|
||||
const tenantIds: string[] = [];
|
||||
for (const item of items) {
|
||||
if (item.userId && !userIds.includes(item.userId)) {
|
||||
userIds.push(item.userId);
|
||||
}
|
||||
if (item.tenantId && !tenantIds.includes(item.tenantId)) {
|
||||
tenantIds.push(item.tenantId);
|
||||
}
|
||||
}
|
||||
users = await db.user.findMany({
|
||||
where: { id: { in: userIds } },
|
||||
select: { id: true, email: true },
|
||||
});
|
||||
tenants = await db.tenant.findMany({
|
||||
where: { id: { in: tenantIds } },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
}
|
||||
const data: LoaderData = {
|
||||
items,
|
||||
users,
|
||||
tenants,
|
||||
filterableProperties,
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
function getGroupByValues(searchParams: URLSearchParams) {
|
||||
const groupByValues = searchParams
|
||||
.getAll("groupBy")
|
||||
.filter((x) => x)
|
||||
.sort();
|
||||
const groupBy: Prisma.MetricLogScalarFieldEnum[] = [];
|
||||
for (const param of groupByValues) {
|
||||
if (Object.keys(Prisma.MetricLogScalarFieldEnum).includes(param)) {
|
||||
groupBy.push(param as Prisma.MetricLogScalarFieldEnum);
|
||||
}
|
||||
}
|
||||
return groupBy.length > 0 ? groupBy.map((x) => x.toString()) : defaultGroupBy;
|
||||
}
|
||||
|
||||
export default function () {
|
||||
const { i18n, t } = useTranslation();
|
||||
const formatters = useMemo(() => createLocaleFormatters(i18n.language), [i18n.language]);
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [groupBy, setGroupBy] = useState<string[]>(getGroupByValues(searchParams));
|
||||
|
||||
const [headers, setHeaders] = useState<RowHeaderDisplayDto<ItemDto>[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (getGroupByValues(searchParams).sort().join(",") !== groupBy.sort().join(",")) {
|
||||
searchParams.delete("groupBy");
|
||||
groupBy.forEach((by) => {
|
||||
searchParams.append("groupBy", by);
|
||||
});
|
||||
setSearchParams(searchParams);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [groupBy]);
|
||||
|
||||
useEffect(() => {
|
||||
const headers: RowHeaderDisplayDto<ItemDto>[] = [];
|
||||
let currentGroupBy = groupBy;
|
||||
if (currentGroupBy.length === 0) {
|
||||
currentGroupBy = defaultGroupBy;
|
||||
}
|
||||
const getCountLink = (item: ItemDto) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("pageSize", "100");
|
||||
currentGroupBy.forEach((groupBy) => {
|
||||
if (groupBy === "function") {
|
||||
searchParams.append("function", item.function);
|
||||
} else if (groupBy === "route") {
|
||||
searchParams.append("route", item.route);
|
||||
} else if (groupBy === "url") {
|
||||
searchParams.append("url", item.url);
|
||||
} else if (groupBy === "env") {
|
||||
searchParams.append("env", item.env);
|
||||
} else if (groupBy === "type") {
|
||||
searchParams.append("type", item.type);
|
||||
} else if (groupBy === "userId") {
|
||||
searchParams.append("userId", item.userId ?? "null");
|
||||
} else if (groupBy === "tenantId") {
|
||||
searchParams.append("tenantId", item.tenantId ?? "null");
|
||||
}
|
||||
});
|
||||
return adminPath(`metrics/logs?${searchParams.toString()}`, { mode: "host-aware" });
|
||||
};
|
||||
const getUser = (item: ItemDto) => {
|
||||
return data.users.find((x) => x.id === item.userId);
|
||||
};
|
||||
const getTenant = (item: ItemDto) => {
|
||||
return data.tenants.find((x) => x.id === item.tenantId);
|
||||
};
|
||||
if (groupBy.includes("env")) {
|
||||
headers.push({
|
||||
name: "env",
|
||||
title: t("admin.metrics.columns.env"),
|
||||
value: (item) => <FilterableValueLink name="env" value={item.env} />,
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("type")) {
|
||||
headers.push({
|
||||
name: "type",
|
||||
title: t("admin.metrics.columns.type"),
|
||||
value: (item) => <FilterableValueLink name="type" value={item.type} />,
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("route")) {
|
||||
headers.push({
|
||||
name: "route",
|
||||
title: t("admin.metrics.columns.route"),
|
||||
value: (item) => <FilterableValueLink name="route" value={item.route} />,
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("url")) {
|
||||
headers.push({
|
||||
name: "url",
|
||||
title: t("admin.metrics.columns.url"),
|
||||
value: (item) => <FilterableValueLink name="url" value={item.url} />,
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("function")) {
|
||||
headers.push({
|
||||
name: "function",
|
||||
title: t("admin.metrics.columns.function"),
|
||||
value: (item) => (
|
||||
<div className={clsx(item.function === "_unidentifiedFunction_" && "text-red-500")}>
|
||||
<FilterableValueLink name="function" value={item.function} />
|
||||
</div>
|
||||
),
|
||||
className: "w-full",
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("userId")) {
|
||||
headers.push({
|
||||
name: "userId",
|
||||
title: t("admin.metrics.columns.user"),
|
||||
value: (item) => <FilterableValueLink name="userId" value={getUser(item)?.email ?? ""} />,
|
||||
});
|
||||
}
|
||||
if (groupBy.includes("tenantId")) {
|
||||
headers.push({
|
||||
name: "tenantId",
|
||||
title: t("admin.metrics.columns.tenant"),
|
||||
value: (item) => <FilterableValueLink name="tenantId" value={getTenant(item)?.name ?? ""} />,
|
||||
});
|
||||
}
|
||||
headers.push({
|
||||
name: "count",
|
||||
title: t("admin.metrics.columns.count"),
|
||||
value: (item) => (
|
||||
<Link to={getCountLink(item)} className="hover:underline">
|
||||
{formatters.number(Number(item._count._all))}
|
||||
</Link>
|
||||
),
|
||||
});
|
||||
headers.push({
|
||||
name: "speed",
|
||||
title: t("admin.metrics.columns.speed"),
|
||||
value: (item) => <SpeedBadge duration={Number(item._avg.duration)} />,
|
||||
});
|
||||
headers.push({
|
||||
name: "duration",
|
||||
title: t("admin.metrics.columns.avgDuration"),
|
||||
value: (item) => (
|
||||
<div>
|
||||
{formatters.number(Number(item._avg.duration), {
|
||||
style: "unit",
|
||||
unit: "millisecond",
|
||||
unitDisplay: "short",
|
||||
minimumFractionDigits: 3,
|
||||
maximumFractionDigits: 3,
|
||||
})}
|
||||
</div>
|
||||
),
|
||||
});
|
||||
// headers.push({
|
||||
// name: "all",
|
||||
// title: "All",
|
||||
// value: (item) => <div>{JSON.stringify(item)}</div>,
|
||||
// });
|
||||
|
||||
setHeaders(headers);
|
||||
}, [data, formatters, groupBy, t]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout
|
||||
tabs={[
|
||||
{
|
||||
name: t("admin.metrics.tabs.summary"),
|
||||
routePath: adminPath("metrics/summary", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.metrics.tabs.logs"),
|
||||
routePath: adminPath("metrics/logs", { mode: "host-aware" }),
|
||||
},
|
||||
{
|
||||
name: t("admin.metrics.tabs.settings"),
|
||||
routePath: adminPath("metrics/settings", { mode: "host-aware" }),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<div className="flex w-full items-center space-x-2">
|
||||
<InputCombobox
|
||||
name="groupBy"
|
||||
prefix={t("admin.metrics.groupBy.prefix")}
|
||||
className="bg-background"
|
||||
selectPlaceholder={t("admin.metrics.groupBy.placeholder")}
|
||||
options={[
|
||||
{ value: "env", name: t("admin.metrics.columns.env") },
|
||||
{ value: "type", name: t("admin.metrics.columns.type") },
|
||||
{ value: "route", name: t("admin.metrics.columns.route") },
|
||||
{ value: "url", name: t("admin.metrics.columns.url") },
|
||||
{ value: "userId", name: t("admin.metrics.columns.user") },
|
||||
{ value: "tenantId", name: t("admin.metrics.columns.tenant") },
|
||||
{ value: "function", name: t("admin.metrics.columns.function") },
|
||||
]}
|
||||
value={groupBy}
|
||||
onChange={(value) => {
|
||||
setGroupBy(value as string[]);
|
||||
}}
|
||||
/>
|
||||
<div className="grow">{/* <InputSearchWithURL /> */}</div>
|
||||
<InputFilters size="sm" filters={data.filterableProperties} />
|
||||
</div>
|
||||
{groupBy.length === 0 ? (
|
||||
<WarningBanner title={t("admin.metrics.groupBy.title")} text={t("admin.metrics.groupBy.required")} />
|
||||
) : (
|
||||
<TableSimple items={data.items} headers={headers} />
|
||||
)}
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
Reference in new issue
Block a user