Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,34 @@
import type { TFunction } from "i18next";
import { describe, expect, it } from "vitest";
import {
translateIpAddressLogAction,
translateIpAddressLogDescription,
translateIpAddressLogError,
} from "./ip-address-log-labels";
const t = ((key: string, options?: Record<string, unknown>) => (options?.value ? `${key}:${String(options.value)}` : key)) as TFunction;
describe("IP address log labels", () => {
it("translates known action codes and wraps unknown values in a semantic key", () => {
expect(translateIpAddressLogAction(t, "login")).toBe("admin.accounts.ipAddresses.logs.actions.login");
expect(translateIpAddressLogAction(t, "register")).toBe("admin.accounts.ipAddresses.logs.actions.register");
expect(translateIpAddressLogAction(t, "reset")).toBe("admin.accounts.ipAddresses.logs.actions.reset");
expect(translateIpAddressLogAction(t, "forgot-password")).toBe("admin.accounts.ipAddresses.logs.actions.forgotPassword");
expect(translateIpAddressLogAction(t, "reset-password")).toBe("admin.accounts.ipAddresses.logs.actions.resetPassword");
expect(translateIpAddressLogAction(t, " custom-action ")).toBe("admin.accounts.ipAddresses.logs.actions.unknownWithValue:custom-action");
expect(translateIpAddressLogAction(t, " ")).toBe("");
});
it("translates known description codes and wraps unknown values in a semantic key", () => {
expect(translateIpAddressLogDescription(t, "registration-attempt")).toBe("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
expect(translateIpAddressLogDescription(t, "{empty email}")).toBe("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
expect(translateIpAddressLogDescription(t, "custom description")).toBe("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue:custom description");
expect(translateIpAddressLogDescription(t, null)).toBe("");
});
it("translates known error codes and wraps unknown values in a semantic key", () => {
expect(translateIpAddressLogError(t, "blacklisted")).toBe("admin.accounts.ipAddresses.errors.blacklisted");
expect(translateIpAddressLogError(t, "Unauthorized.")).toBe("admin.accounts.ipAddresses.errors.unauthorized");
expect(translateIpAddressLogError(t, "provider error")).toBe("admin.accounts.ipAddresses.errors.unknownWithValue:provider error");
});
});
@@ -0,0 +1,52 @@
import type { TFunction } from "i18next";
export function translateIpAddressLogAction(t: TFunction, action?: string | null) {
const normalized = action?.trim();
if (!normalized) {
return "";
}
if (normalized === "login") {
return t("admin.accounts.ipAddresses.logs.actions.login");
}
if (normalized === "register") {
return t("admin.accounts.ipAddresses.logs.actions.register");
}
if (normalized === "reset") {
return t("admin.accounts.ipAddresses.logs.actions.reset");
}
if (normalized === "forgot-password") {
return t("admin.accounts.ipAddresses.logs.actions.forgotPassword");
}
if (normalized === "reset-password") {
return t("admin.accounts.ipAddresses.logs.actions.resetPassword");
}
return t("admin.accounts.ipAddresses.logs.actions.unknownWithValue", { value: normalized });
}
export function translateIpAddressLogDescription(t: TFunction, description?: string | null) {
const normalized = description?.trim();
if (!normalized) {
return "";
}
if (normalized === "registration-attempt") {
return t("admin.accounts.ipAddresses.logs.descriptions.registrationAttempt");
}
if (normalized === "{empty email}") {
return t("admin.accounts.ipAddresses.logs.descriptions.emptyEmail");
}
return t("admin.accounts.ipAddresses.logs.descriptions.unknownWithValue", { value: normalized });
}
export function translateIpAddressLogError(t: TFunction, error?: string | null) {
const normalized = error?.trim();
if (!normalized) {
return "";
}
if (normalized === "blacklisted" || normalized === "Blacklisted") {
return t("admin.accounts.ipAddresses.errors.blacklisted");
}
if (normalized === "unauthorized" || normalized === "Unauthorized" || normalized === "Unauthorized.") {
return t("admin.accounts.ipAddresses.errors.unauthorized");
}
return t("admin.accounts.ipAddresses.errors.unknownWithValue", { value: normalized });
}
@@ -0,0 +1,264 @@
import { useTranslation } from "react-i18next";
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import TableSimple from "~/components/ui/tables/TableSimple";
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { useLocaleFormatters } from "~/locale/format";
import { IpAddressLog } from "@toolctrl/db/prisma-browser";
import { getAllIpAddressLogs } from "~/modules/ipAddress/db/ipAddressLogs.db.server";
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import { Colors } from "~/application/enums/shared/Colors";
import { addToBlacklist, findInBlacklist } from "~/utils/db/blacklist.db.server";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useSubmit } from "react-router";
import { db } from "~/utils/db.server";
import DropdownSimple from "~/components/ui/dropdowns/DropdownSimple";
import DownArrow from "~/components/ui/icons/DownArrow";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { validateCSRFToken } from "~/utils/session.server";
import { appendCSRFToken } from "~/utils/csrf";
import { translateIpAddressLogAction, translateIpAddressLogDescription, translateIpAddressLogError } from "./ip-address-log-labels";
type LoaderData = {
title: string;
items: IpAddressLog[];
pagination: PaginationDto;
blacklistedIps: string[];
};
export const loader = async ({ request }: LoaderFunctionArgs) => {
await verifyUserHasPermission(request, "admin.tenantIpAddress.view");
const { t } = await getTranslations(request);
const urlSearchParams = new URL(request.url).searchParams;
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
const { items, pagination } = await getAllIpAddressLogs(currentPagination);
const data: LoaderData = {
title: `${t("models.ipAddress.plural")} | ${process.env.APP_NAME}`,
items,
pagination,
blacklistedIps: await db.blacklist
.findMany({
where: { type: "ip" },
select: { value: true },
})
.then((items) => items.flatMap((i) => i.value)),
};
return data;
};
export const action = async ({ request }: ActionFunctionArgs) => {
await verifyUserHasPermission(request, "admin.blacklist.manage");
await validateCSRFToken(request);
const { t } = await getTranslations(request);
const form = await request.formData();
const action = form.get("action") as string;
if (action === "blacklist-ip") {
const ip = form.get("ip")?.toString() ?? "";
const existing = await findInBlacklist("ip", ip);
if (existing) {
return Response.json({ error: t("admin.accounts.ipAddresses.actions.alreadyBlacklisted") }, { status: 400 });
} else {
await addToBlacklist({
type: "ip",
value: ip,
});
return Response.json({ success: t("admin.accounts.ipAddresses.actions.blacklisted") });
}
} else if (action === "delete-log") {
const id = form.get("id")?.toString() ?? "";
await db.ipAddressLog.delete({ where: { id } });
return Response.json({ success: t("admin.accounts.ipAddresses.actions.logDeleted") });
} else if (action === "delete-logs") {
const ids = form.getAll("id").map((i) => i.toString());
const deleted = await db.ipAddressLog.deleteMany({ where: { id: { in: ids } } });
return Response.json({ success: t("admin.accounts.ipAddresses.actions.logsDeleted", { count: deleted.count }) });
} else {
return Response.json({ error: t("admin.accounts.ipAddresses.actions.invalidAction") }, { status: 400 });
}
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function () {
const data = useLoaderData<LoaderData>();
const actionData = useActionData<{ success?: string; error?: string }>();
const submit = useSubmit();
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [items, setItems] = useState<IpAddressLog[]>(data.items);
const [selected, setSelected] = useState<IpAddressLog[]>([]);
useEffect(() => {
setItems(data.items);
}, [data]);
useEffect(() => {
if (actionData?.success) {
toast.success(actionData.success);
} else if (actionData?.error) {
toast.error(actionData.error);
}
}, [actionData]);
const selectedCount = selected.length;
const formattedSelectedCount = formatters.number(selectedCount);
return (
<EditPageLayout
tabs={[
{
name: t("admin.accounts.ipAddresses.tabs.ipAddresses"),
routePath: adminPath("accounts/ip-addresses", { mode: "host-aware" }),
},
{
name: t("admin.accounts.ipAddresses.tabs.logs"),
routePath: adminPath("accounts/ip-addresses/logs", { mode: "host-aware" }),
},
]}
buttons={<></>}
>
{selectedCount > 0 && (
<DropdownSimple
right
button={
<div className="hover:bg-secondary border-border bg-background text-foreground/80 flex items-center space-x-2 rounded-md border px-2 py-1 text-sm">
<div>{t("admin.accounts.ipAddresses.selection.selected", { count: selectedCount, formattedCount: formattedSelectedCount })}</div>
<DownArrow className="h-4 w-4" />
</div>
}
items={[
{
label: t("admin.accounts.ipAddresses.actions.deleteSelectedLogs", { count: selectedCount, formattedCount: formattedSelectedCount }),
onClick: () => {
const form = new FormData();
appendCSRFToken(form);
form.set("action", "delete-logs");
selected.forEach((i) => form.append("id", i.id));
setSelected([]);
setItems((prev) => prev.filter((p) => !selected.includes(p)));
submit(form, {
method: "post",
});
},
},
]}
/>
)}
<TableSimple
items={items}
selectedRows={selected}
onSelected={setSelected}
actions={[
{
title: t("admin.accounts.ipAddresses.actions.blacklistIp"),
destructive: true,
onClick: (_, i) => {
const form = new FormData();
appendCSRFToken(form);
form.set("action", "blacklist-ip");
form.set("ip", i.ip);
submit(form, {
method: "post",
});
},
},
{
title: t("shared.delete"),
destructive: true,
onClick: (_, i) => {
setSelected((prev) => prev.filter((p) => p.id !== i.id));
setItems((prev) => prev.filter((p) => p.id !== i.id));
const form = new FormData();
appendCSRFToken(form);
form.set("action", "delete-log");
form.set("id", i.id);
submit(form, {
method: "post",
});
},
},
]}
headers={[
{
name: "createdAt",
title: t("shared.createdAt"),
value: (item) => formatters.dateTime(item.createdAt),
formattedValue: (item) => <span title={formatters.dateTime(item.createdAt)}>{formatters.relativeDate(item.createdAt)}</span>,
className: "text-muted-foreground text-xs",
breakpoint: "sm",
},
{
name: "status",
title: t("shared.status"),
value: (i) => (
<div className="flex flex-col">
<div>
{i.success ? <SimpleBadge title={t("shared.success")} color={Colors.GREEN} /> : <SimpleBadge title={t("shared.error")} color={Colors.RED} />}
</div>
</div>
),
},
{
name: "ip",
title: t("models.tenantIpAddress.object"),
value: (i) => (
<div className="flex flex-col">
<div className="font-medium">
{i.ip} {data.blacklistedIps.includes(i.ip) && <SimpleBadge title={t("admin.accounts.ipAddresses.table.blacklisted")} color={Colors.RED} />}
</div>
</div>
),
},
{
name: "action",
title: t("admin.accounts.ipAddresses.table.action"),
value: (i) => (
<div className="flex flex-col">
<div className="font-medium">{translateIpAddressLogAction(t, i.action)}</div>
<div className="text-muted-foreground text-xs">{translateIpAddressLogDescription(t, i.description)}</div>
</div>
),
},
{
name: "url",
title: t("admin.accounts.ipAddresses.table.url"),
value: (i) => (
<div className="flex flex-col">
<div className="">{i.url}</div>
</div>
),
},
{
name: "metadata",
title: t("admin.accounts.ipAddresses.table.metadata"),
value: (i) => (
<div className="max-w-xs truncate">
{i.metadata ? (
<ShowPayloadModalButton description={i.metadata} payload={i.metadata} />
) : (
<div className="text-muted-foreground italic">{t("shared.notAvailable")}</div>
)}
</div>
),
},
{
name: "error",
title: t("shared.error"),
value: (i) => (
<div className="flex flex-col text-red-500">
<div className="font-medium">{translateIpAddressLogError(t, i.error)}</div>
</div>
),
},
]}
pagination={data.pagination}
/>
</EditPageLayout>
);
}
@@ -0,0 +1,204 @@
import { useTranslation } from "react-i18next";
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
import TableSimple from "~/components/ui/tables/TableSimple";
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { useLocaleFormatters } from "~/locale/format";
import { IpAddress } from "@toolctrl/db/prisma-browser";
import { getAllIpAddresses } from "~/modules/ipAddress/db/ipAddresses.db.server";
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import { findInBlacklist, addToBlacklist } from "~/utils/db/blacklist.db.server";
import { useSubmit } from "react-router";
import { useEffect } from "react";
import toast from "react-hot-toast";
import { db } from "~/utils/db.server";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import { Colors } from "~/application/enums/shared/Colors";
import { clearCacheKey } from "~/utils/cache.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { validateCSRFToken } from "~/utils/session.server";
import { appendCSRFToken } from "~/utils/csrf";
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
type LoaderData = {
title: string;
items: IpAddress[];
pagination: PaginationDto;
blacklistedIps: string[];
};
export const loader = async ({ request }: LoaderFunctionArgs) => {
await verifyUserHasPermission(request, "admin.tenantIpAddress.view");
const { t } = await getTranslations(request);
const urlSearchParams = new URL(request.url).searchParams;
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
const { items, pagination } = await getAllIpAddresses(currentPagination);
const data: LoaderData = {
title: `${t("models.ipAddress.plural")} | ${process.env.APP_NAME}`,
items,
pagination,
blacklistedIps: await db.blacklist
.findMany({
where: { type: "ip" },
select: { value: true },
})
.then((items) => items.flatMap((i) => i.value)),
};
return data;
};
export const action = async ({ request }: ActionFunctionArgs) => {
await verifyUserHasPermission(request, "admin.blacklist.manage");
await validateCSRFToken(request);
const { t } = await getTranslations(request);
const form = await request.formData();
const action = form.get("action") as string;
if (action === "blacklist-ip") {
const ip = form.get("ip")?.toString() ?? "";
const existing = await findInBlacklist("ip", ip);
if (existing) {
return Response.json({ error: t("admin.accounts.ipAddresses.actions.alreadyBlacklisted") }, { status: 400 });
} else {
await addToBlacklist({
type: "ip",
value: ip,
});
return Response.json({ success: t("admin.accounts.ipAddresses.actions.blacklisted") });
}
} else if (action === "delete-ip") {
const id = form.get("id")?.toString() ?? "";
await db.ipAddress.delete({ where: { id } }).then((item) => {
clearCacheKey(`ipAddress:${item.ip}`);
});
return Response.json({ success: t("admin.accounts.ipAddresses.actions.ipDeleted") });
} else {
return Response.json({ error: t("admin.accounts.ipAddresses.actions.invalidAction") }, { status: 400 });
}
};
export default function IpAddresses() {
const data = useLoaderData<LoaderData>();
const actionData = useActionData<{ success?: string; error?: string }>();
const submit = useSubmit();
const { t } = useTranslation();
const formatters = useLocaleFormatters();
useEffect(() => {
if (actionData?.success) {
toast.success(actionData.success);
} else if (actionData?.error) {
toast.error(actionData.error);
}
}, [actionData]);
return (
<EditPageLayout
tabs={[
{
name: t("admin.accounts.ipAddresses.tabs.ipAddresses"),
routePath: adminPath("accounts/ip-addresses", { mode: "host-aware" }),
},
{
name: t("admin.accounts.ipAddresses.tabs.logs"),
routePath: adminPath("accounts/ip-addresses/logs", { mode: "host-aware" }),
},
]}
>
<TableSimple
items={data.items}
actions={[
{
title: t("admin.accounts.ipAddresses.actions.blacklistIp"),
destructive: true,
onClick: (_, i) => {
const form = new FormData();
appendCSRFToken(form);
form.set("action", "blacklist-ip");
form.set("ip", i.ip);
submit(form, {
method: "post",
});
},
},
{
title: t("shared.delete"),
destructive: true,
onClick: (_, i) => {
const form = new FormData();
appendCSRFToken(form);
form.set("action", "delete-ip");
form.set("id", i.id);
submit(form, {
method: "post",
});
},
},
]}
headers={[
{
name: "ip",
title: t("models.tenantIpAddress.object"),
value: (i) => (
<div className="flex flex-col">
<div className="font-medium">
{i.ip} {i.type && <span className="text-muted-foreground text-xs font-light">({i.type})</span>}{" "}
{data.blacklistedIps.includes(i.ip) && <SimpleBadge title={t("admin.accounts.ipAddresses.table.blacklisted")} color={Colors.RED} />}
</div>
<div className="text-muted-foreground text-xs">{i.provider}</div>
</div>
),
},
{
name: "country",
title: t("admin.accounts.ipAddresses.table.country"),
value: (i) => (
<div className="flex flex-col">
<div className="font-medium">{i.countryCode}</div>
<div className="text-muted-foreground text-xs">{i.countryName}</div>
</div>
),
},
{
name: "region",
title: t("admin.accounts.ipAddresses.table.region"),
value: (i) => (
<div className="flex flex-col">
<div className="font-medium">{i.regionCode}</div>
<div className="text-muted-foreground text-xs">{i.regionName}</div>
</div>
),
},
{
name: "city",
title: t("admin.accounts.ipAddresses.table.city"),
value: (i) => (
<div className="flex flex-col">
<div className="font-medium">{i.city}</div>
<div className="text-muted-foreground text-xs">{i.zipCode}</div>
</div>
),
},
{
name: "metadata",
title: t("admin.accounts.ipAddresses.table.metadata"),
value: (i) => <div className="max-w-xs truncate">{i.metadata && <ShowPayloadModalButton description={i.metadata} payload={i.metadata} />}</div>,
},
{
name: "createdAt",
title: t("shared.createdAt"),
value: (item) => formatters.dateTime(item.createdAt),
formattedValue: (item) => <span title={formatters.dateTime(item.createdAt)}>{formatters.relativeDate(item.createdAt)}</span>,
className: "text-muted-foreground text-xs",
breakpoint: "sm",
},
]}
pagination={data.pagination}
/>
</EditPageLayout>
);
}