Mobile friendly, lint correction, typescript error clear
This commit is contained in:
499
app/(app)/alerts/AlertsClient.tsx
Normal file
499
app/(app)/alerts/AlertsClient.tsx
Normal file
@@ -0,0 +1,499 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useI18n } from "@/lib/i18n/useI18n";
|
||||
|
||||
type MachineRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
location?: string | null;
|
||||
};
|
||||
|
||||
type ShiftRow = {
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
type AlertEvent = {
|
||||
id: string;
|
||||
ts: string;
|
||||
eventType: string;
|
||||
severity: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
machineId: string;
|
||||
machineName?: string | null;
|
||||
location?: string | null;
|
||||
workOrderId?: string | null;
|
||||
sku?: string | null;
|
||||
durationSec?: number | null;
|
||||
status?: string | null;
|
||||
shift?: string | null;
|
||||
alertId?: string | null;
|
||||
isUpdate?: boolean;
|
||||
isAutoAck?: boolean;
|
||||
};
|
||||
|
||||
const RANGE_OPTIONS = [
|
||||
{ value: "24h", labelKey: "alerts.inbox.range.24h" },
|
||||
{ value: "7d", labelKey: "alerts.inbox.range.7d" },
|
||||
{ value: "30d", labelKey: "alerts.inbox.range.30d" },
|
||||
{ value: "custom", labelKey: "alerts.inbox.range.custom" },
|
||||
] as const;
|
||||
|
||||
function formatDuration(seconds: number | null | undefined, t: (key: string) => string) {
|
||||
if (seconds == null || !Number.isFinite(seconds)) return t("alerts.inbox.duration.na");
|
||||
if (seconds < 60) return `${Math.round(seconds)}${t("alerts.inbox.duration.sec")}`;
|
||||
if (seconds < 3600) return `${Math.round(seconds / 60)}${t("alerts.inbox.duration.min")}`;
|
||||
return `${(seconds / 3600).toFixed(1)}${t("alerts.inbox.duration.hr")}`;
|
||||
}
|
||||
|
||||
function normalizeLabel(value?: string | null) {
|
||||
if (!value) return "";
|
||||
return String(value).trim();
|
||||
}
|
||||
|
||||
export default function AlertsClient({
|
||||
initialMachines = [],
|
||||
initialShifts = [],
|
||||
initialEvents = [],
|
||||
}: {
|
||||
initialMachines?: MachineRow[];
|
||||
initialShifts?: ShiftRow[];
|
||||
initialEvents?: AlertEvent[];
|
||||
}) {
|
||||
const { t, locale } = useI18n();
|
||||
const [events, setEvents] = useState<AlertEvent[]>(() => initialEvents);
|
||||
const [machines, setMachines] = useState<MachineRow[]>(() => initialMachines);
|
||||
const [shifts, setShifts] = useState<ShiftRow[]>(() => initialShifts);
|
||||
const [loading, setLoading] = useState(() => initialMachines.length === 0 || initialShifts.length === 0);
|
||||
const [loadingEvents, setLoadingEvents] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [range, setRange] = useState<string>("24h");
|
||||
const [start, setStart] = useState<string>("");
|
||||
const [end, setEnd] = useState<string>("");
|
||||
const [machineId, setMachineId] = useState<string>("");
|
||||
const [location, setLocation] = useState<string>("");
|
||||
const [shift, setShift] = useState<string>("");
|
||||
const [eventType, setEventType] = useState<string>("");
|
||||
const [severity, setSeverity] = useState<string>("");
|
||||
const [status, setStatus] = useState<string>("");
|
||||
const [includeUpdates, setIncludeUpdates] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const skipInitialEventsRef = useRef(true);
|
||||
|
||||
const locations = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
for (const machine of machines) {
|
||||
if (!machine.location) continue;
|
||||
seen.add(machine.location);
|
||||
}
|
||||
return Array.from(seen).sort();
|
||||
}, [machines]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialMachines.length && initialShifts.length) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
let alive = true;
|
||||
|
||||
async function loadFilters() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [machinesRes, settingsRes] = await Promise.all([
|
||||
fetch("/api/machines", { cache: "no-store" }),
|
||||
fetch("/api/settings", { cache: "no-store" }),
|
||||
]);
|
||||
const machinesJson = await machinesRes.json().catch(() => ({}));
|
||||
const settingsJson = await settingsRes.json().catch(() => ({}));
|
||||
if (!alive) return;
|
||||
setMachines(machinesJson.machines ?? []);
|
||||
const shiftRows = settingsJson?.settings?.shiftSchedule?.shifts ?? [];
|
||||
setShifts(
|
||||
Array.isArray(shiftRows)
|
||||
? shiftRows
|
||||
.map((row: unknown) => {
|
||||
const data = row && typeof row === "object" ? (row as Record<string, unknown>) : {};
|
||||
const name = typeof data.name === "string" ? data.name : "";
|
||||
const enabled = data.enabled !== false;
|
||||
return { name, enabled };
|
||||
})
|
||||
.filter((row) => row.name)
|
||||
: []
|
||||
);
|
||||
} catch {
|
||||
if (!alive) return;
|
||||
} finally {
|
||||
if (alive) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
loadFilters();
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [initialMachines, initialShifts]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const controller = new AbortController();
|
||||
|
||||
async function loadEvents() {
|
||||
const isDefault =
|
||||
range === "24h" &&
|
||||
!start &&
|
||||
!end &&
|
||||
!machineId &&
|
||||
!location &&
|
||||
!shift &&
|
||||
!eventType &&
|
||||
!severity &&
|
||||
!status &&
|
||||
!includeUpdates;
|
||||
if (skipInitialEventsRef.current) {
|
||||
skipInitialEventsRef.current = false;
|
||||
if (initialEvents.length && isDefault) return;
|
||||
}
|
||||
|
||||
setLoadingEvents(true);
|
||||
setError(null);
|
||||
const params = new URLSearchParams();
|
||||
params.set("range", range);
|
||||
if (range === "custom") {
|
||||
if (start) params.set("start", start);
|
||||
if (end) params.set("end", end);
|
||||
}
|
||||
if (machineId) params.set("machineId", machineId);
|
||||
if (location) params.set("location", location);
|
||||
if (shift) params.set("shift", shift);
|
||||
if (eventType) params.set("eventType", eventType);
|
||||
if (severity) params.set("severity", severity);
|
||||
if (status) params.set("status", status);
|
||||
if (includeUpdates) params.set("includeUpdates", "1");
|
||||
params.set("limit", "250");
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/alerts/inbox?${params.toString()}`, {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!alive) return;
|
||||
if (!res.ok || !json?.ok) {
|
||||
setError(json?.error || t("alerts.inbox.error"));
|
||||
setEvents([]);
|
||||
} else {
|
||||
setEvents(json.events ?? []);
|
||||
}
|
||||
} catch {
|
||||
if (alive) {
|
||||
setError(t("alerts.inbox.error"));
|
||||
setEvents([]);
|
||||
}
|
||||
} finally {
|
||||
if (alive) setLoadingEvents(false);
|
||||
}
|
||||
}
|
||||
|
||||
loadEvents();
|
||||
return () => {
|
||||
alive = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [
|
||||
range,
|
||||
start,
|
||||
end,
|
||||
machineId,
|
||||
location,
|
||||
shift,
|
||||
eventType,
|
||||
severity,
|
||||
status,
|
||||
includeUpdates,
|
||||
t,
|
||||
initialEvents.length,
|
||||
]);
|
||||
|
||||
const eventTypes = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
for (const ev of events) {
|
||||
if (ev.eventType) seen.add(ev.eventType);
|
||||
}
|
||||
return Array.from(seen).sort();
|
||||
}, [events]);
|
||||
|
||||
const severities = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
for (const ev of events) {
|
||||
if (ev.severity) seen.add(ev.severity);
|
||||
}
|
||||
return Array.from(seen).sort();
|
||||
}, [events]);
|
||||
|
||||
const statuses = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
for (const ev of events) {
|
||||
if (ev.status) seen.add(ev.status);
|
||||
}
|
||||
return Array.from(seen).sort();
|
||||
}, [events]);
|
||||
|
||||
const filteredEvents = useMemo(() => {
|
||||
if (!search.trim()) return events;
|
||||
const needle = search.trim().toLowerCase();
|
||||
return events.filter((ev) => {
|
||||
return (
|
||||
normalizeLabel(ev.title).toLowerCase().includes(needle) ||
|
||||
normalizeLabel(ev.description).toLowerCase().includes(needle) ||
|
||||
normalizeLabel(ev.machineName).toLowerCase().includes(needle) ||
|
||||
normalizeLabel(ev.location).toLowerCase().includes(needle) ||
|
||||
normalizeLabel(ev.eventType).toLowerCase().includes(needle)
|
||||
);
|
||||
});
|
||||
}, [events, search]);
|
||||
|
||||
function formatEventTypeLabel(value: string) {
|
||||
const key = `alerts.event.${value}`;
|
||||
const label = t(key);
|
||||
return label === key ? value : label;
|
||||
}
|
||||
|
||||
function formatStatusLabel(value?: string | null) {
|
||||
if (!value) return t("alerts.inbox.table.unknown");
|
||||
const key = `alerts.inbox.status.${value}`;
|
||||
const label = t(key);
|
||||
return label === key ? value : label;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 py-6 sm:px-6 sm:py-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">{t("alerts.title")}</h1>
|
||||
<p className="mt-2 text-sm text-zinc-400">{t("alerts.subtitle")}</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="text-sm font-semibold text-white">{t("alerts.inbox.filters.title")}</div>
|
||||
{loading && <div className="text-xs text-zinc-500">{t("alerts.inbox.loadingFilters")}</div>}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.range")}
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={range}
|
||||
onChange={(event) => setRange(event.target.value)}
|
||||
>
|
||||
{RANGE_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{t(option.labelKey)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{range === "custom" && (
|
||||
<>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.start")}
|
||||
<input
|
||||
type="date"
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={start}
|
||||
onChange={(event) => setStart(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.end")}
|
||||
<input
|
||||
type="date"
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={end}
|
||||
onChange={(event) => setEnd(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.machine")}
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={machineId}
|
||||
onChange={(event) => setMachineId(event.target.value)}
|
||||
>
|
||||
<option value="">{t("alerts.inbox.filters.allMachines")}</option>
|
||||
{machines.map((machine) => (
|
||||
<option key={machine.id} value={machine.id}>
|
||||
{machine.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.site")}
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={location}
|
||||
onChange={(event) => setLocation(event.target.value)}
|
||||
>
|
||||
<option value="">{t("alerts.inbox.filters.allSites")}</option>
|
||||
{locations.map((loc) => (
|
||||
<option key={loc} value={loc}>
|
||||
{loc}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.shift")}
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={shift}
|
||||
onChange={(event) => setShift(event.target.value)}
|
||||
>
|
||||
<option value="">{t("alerts.inbox.filters.allShifts")}</option>
|
||||
{shifts
|
||||
.filter((row) => row.enabled)
|
||||
.map((row) => (
|
||||
<option key={row.name} value={row.name}>
|
||||
{row.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.type")}
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={eventType}
|
||||
onChange={(event) => setEventType(event.target.value)}
|
||||
>
|
||||
<option value="">{t("alerts.inbox.filters.allTypes")}</option>
|
||||
{eventTypes.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{formatEventTypeLabel(value)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.severity")}
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={severity}
|
||||
onChange={(event) => setSeverity(event.target.value)}
|
||||
>
|
||||
<option value="">{t("alerts.inbox.filters.allSeverities")}</option>
|
||||
{severities.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{value}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.status")}
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={status}
|
||||
onChange={(event) => setStatus(event.target.value)}
|
||||
>
|
||||
<option value="">{t("alerts.inbox.filters.allStatuses")}</option>
|
||||
{statuses.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{formatStatusLabel(value)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.inbox.filters.search")}
|
||||
<input
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder={t("alerts.inbox.filters.searchPlaceholder")}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-xs text-zinc-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeUpdates}
|
||||
onChange={(event) => setIncludeUpdates(event.target.checked)}
|
||||
className="h-4 w-4 rounded border border-white/20 bg-black/20"
|
||||
/>
|
||||
{t("alerts.inbox.filters.includeUpdates")}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="text-sm font-semibold text-white">{t("alerts.inbox.title")}</div>
|
||||
{loadingEvents && <div className="text-xs text-zinc-500">{t("alerts.inbox.loading")}</div>}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-xl border border-red-500/20 bg-red-500/10 p-3 text-sm text-red-200">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loadingEvents && !filteredEvents.length && (
|
||||
<div className="text-sm text-zinc-400">{t("alerts.inbox.empty")}</div>
|
||||
)}
|
||||
|
||||
{!!filteredEvents.length && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-sm text-zinc-300">
|
||||
<thead>
|
||||
<tr className="text-xs uppercase text-zinc-500">
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.time")}</th>
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.machine")}</th>
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.site")}</th>
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.shift")}</th>
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.type")}</th>
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.severity")}</th>
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.status")}</th>
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.duration")}</th>
|
||||
<th className="border-b border-white/10 px-3 py-2 text-left">{t("alerts.inbox.table.title")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredEvents.map((ev) => (
|
||||
<tr key={ev.id} className="border-b border-white/5">
|
||||
<td className="px-3 py-3 text-xs text-zinc-400">
|
||||
{new Date(ev.ts).toLocaleString(locale)}
|
||||
</td>
|
||||
<td className="px-3 py-3">{ev.machineName || t("alerts.inbox.table.unknown")}</td>
|
||||
<td className="px-3 py-3">{ev.location || t("alerts.inbox.table.unknown")}</td>
|
||||
<td className="px-3 py-3">{ev.shift || t("alerts.inbox.table.unknown")}</td>
|
||||
<td className="px-3 py-3">{formatEventTypeLabel(ev.eventType)}</td>
|
||||
<td className="px-3 py-3">{ev.severity || t("alerts.inbox.table.unknown")}</td>
|
||||
<td className="px-3 py-3">{formatStatusLabel(ev.status)}</td>
|
||||
<td className="px-3 py-3">{formatDuration(ev.durationSec, t)}</td>
|
||||
<td className="px-3 py-3">
|
||||
<div className="text-sm text-white">{ev.title}</div>
|
||||
{ev.description && (
|
||||
<div className="mt-1 text-xs text-zinc-400">{ev.description}</div>
|
||||
)}
|
||||
{(ev.workOrderId || ev.sku) && (
|
||||
<div className="mt-1 text-[11px] text-zinc-500">
|
||||
{ev.workOrderId ? `${t("alerts.inbox.meta.workOrder")}: ${ev.workOrderId}` : null}
|
||||
{ev.workOrderId && ev.sku ? " • " : null}
|
||||
{ev.sku ? `${t("alerts.inbox.meta.sku")}: ${ev.sku}` : null}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,796 +1,46 @@
|
||||
"use client";
|
||||
import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { requireSession } from "@/lib/auth/requireSession";
|
||||
import { getAlertsInboxData } from "@/lib/alerts/getAlertsInboxData";
|
||||
import AlertsClient from "./AlertsClient";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "@/lib/i18n/useI18n";
|
||||
export default async function AlertsPage() {
|
||||
const session = await requireSession();
|
||||
if (!session) redirect("/login?next=/alerts");
|
||||
|
||||
type RoleName = "MEMBER" | "ADMIN" | "OWNER";
|
||||
type Channel = "email" | "sms";
|
||||
const [machines, shiftRows, inbox] = await Promise.all([
|
||||
prisma.machine.findMany({
|
||||
where: { orgId: session.orgId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { id: true, name: true, location: true },
|
||||
}),
|
||||
prisma.orgShift.findMany({
|
||||
where: { orgId: session.orgId },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
select: { name: true, enabled: true },
|
||||
}),
|
||||
getAlertsInboxData({
|
||||
orgId: session.orgId,
|
||||
range: "24h",
|
||||
limit: 250,
|
||||
}),
|
||||
]);
|
||||
|
||||
type RoleRule = {
|
||||
enabled: boolean;
|
||||
afterMinutes: number;
|
||||
channels: Channel[];
|
||||
};
|
||||
const initialEvents = inbox.events.map((event) => ({
|
||||
...event,
|
||||
ts: event.ts ? event.ts.toISOString() : "",
|
||||
}));
|
||||
|
||||
type AlertRule = {
|
||||
id: string;
|
||||
eventType: string;
|
||||
roles: Record<RoleName, RoleRule>;
|
||||
repeatMinutes?: number;
|
||||
};
|
||||
|
||||
type AlertPolicy = {
|
||||
version: number;
|
||||
defaults: Record<RoleName, RoleRule>;
|
||||
rules: AlertRule[];
|
||||
};
|
||||
|
||||
type AlertContact = {
|
||||
id: string;
|
||||
name: string;
|
||||
roleScope: string;
|
||||
email?: string | null;
|
||||
phone?: string | null;
|
||||
eventTypes?: string[] | null;
|
||||
isActive: boolean;
|
||||
userId?: string | null;
|
||||
};
|
||||
|
||||
type ContactDraft = {
|
||||
name: string;
|
||||
roleScope: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
eventTypes: string[];
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
const ROLE_ORDER: RoleName[] = ["MEMBER", "ADMIN", "OWNER"];
|
||||
const CHANNELS: Channel[] = ["email", "sms"];
|
||||
const EVENT_TYPES = [
|
||||
{ value: "macrostop", labelKey: "alerts.event.macrostop" },
|
||||
{ value: "microstop", labelKey: "alerts.event.microstop" },
|
||||
{ value: "slow-cycle", labelKey: "alerts.event.slow-cycle" },
|
||||
{ value: "offline", labelKey: "alerts.event.offline" },
|
||||
{ value: "error", labelKey: "alerts.event.error" },
|
||||
] as const;
|
||||
|
||||
function normalizeContactDraft(contact: AlertContact): ContactDraft {
|
||||
return {
|
||||
name: contact.name,
|
||||
roleScope: contact.roleScope,
|
||||
email: contact.email ?? "",
|
||||
phone: contact.phone ?? "",
|
||||
eventTypes: Array.isArray(contact.eventTypes) ? contact.eventTypes : [],
|
||||
isActive: contact.isActive,
|
||||
};
|
||||
}
|
||||
|
||||
export default function AlertsPage() {
|
||||
const { t } = useI18n();
|
||||
const [policy, setPolicy] = useState<AlertPolicy | null>(null);
|
||||
const [policyDraft, setPolicyDraft] = useState<AlertPolicy | null>(null);
|
||||
const [contacts, setContacts] = useState<AlertContact[]>([]);
|
||||
const [contactEdits, setContactEdits] = useState<Record<string, ContactDraft>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [role, setRole] = useState<RoleName>("MEMBER");
|
||||
const [savingPolicy, setSavingPolicy] = useState(false);
|
||||
const [policyError, setPolicyError] = useState<string | null>(null);
|
||||
const [contactsError, setContactsError] = useState<string | null>(null);
|
||||
const [savingContactId, setSavingContactId] = useState<string | null>(null);
|
||||
const [deletingContactId, setDeletingContactId] = useState<string | null>(null);
|
||||
const [selectedEventType, setSelectedEventType] = useState<string>("");
|
||||
|
||||
const [newContact, setNewContact] = useState<ContactDraft>({
|
||||
name: "",
|
||||
roleScope: "CUSTOM",
|
||||
email: "",
|
||||
phone: "",
|
||||
eventTypes: [],
|
||||
isActive: true,
|
||||
});
|
||||
const [creatingContact, setCreatingContact] = useState(false);
|
||||
const [createError, setCreateError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
setPolicyError(null);
|
||||
setContactsError(null);
|
||||
try {
|
||||
const [policyRes, contactsRes, meRes] = await Promise.all([
|
||||
fetch("/api/alerts/policy", { cache: "no-store" }),
|
||||
fetch("/api/alerts/contacts", { cache: "no-store" }),
|
||||
fetch("/api/me", { cache: "no-store" }),
|
||||
]);
|
||||
const policyJson = await policyRes.json().catch(() => ({}));
|
||||
const contactsJson = await contactsRes.json().catch(() => ({}));
|
||||
const meJson = await meRes.json().catch(() => ({}));
|
||||
|
||||
if (!alive) return;
|
||||
|
||||
if (!policyRes.ok || !policyJson?.ok) {
|
||||
setPolicyError(policyJson?.error || t("alerts.error.loadPolicy"));
|
||||
} else {
|
||||
setPolicy(policyJson.policy);
|
||||
setPolicyDraft(policyJson.policy);
|
||||
if (!selectedEventType && policyJson.policy?.rules?.length) {
|
||||
setSelectedEventType(policyJson.policy.rules[0].eventType);
|
||||
}
|
||||
}
|
||||
|
||||
if (!contactsRes.ok || !contactsJson?.ok) {
|
||||
setContactsError(contactsJson?.error || t("alerts.error.loadContacts"));
|
||||
} else {
|
||||
setContacts(contactsJson.contacts ?? []);
|
||||
const nextEdits: Record<string, ContactDraft> = {};
|
||||
for (const contact of contactsJson.contacts ?? []) {
|
||||
nextEdits[contact.id] = normalizeContactDraft(contact);
|
||||
}
|
||||
setContactEdits(nextEdits);
|
||||
}
|
||||
|
||||
if (meRes.ok && meJson?.ok && meJson?.membership?.role) {
|
||||
setRole(String(meJson.membership.role).toUpperCase() as RoleName);
|
||||
}
|
||||
} catch {
|
||||
if (!alive) return;
|
||||
setPolicyError(t("alerts.error.loadPolicy"));
|
||||
setContactsError(t("alerts.error.loadContacts"));
|
||||
} finally {
|
||||
if (alive) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!policyDraft?.rules?.length) return;
|
||||
setSelectedEventType((prev) => {
|
||||
if (prev && policyDraft.rules.some((rule) => rule.eventType === prev)) {
|
||||
return prev;
|
||||
}
|
||||
return policyDraft.rules[0].eventType;
|
||||
});
|
||||
}, [policyDraft]);
|
||||
|
||||
function updatePolicyDefaults(role: RoleName, patch: Partial<RoleRule>) {
|
||||
setPolicyDraft((prev) => {
|
||||
if (!prev) return prev;
|
||||
return {
|
||||
...prev,
|
||||
defaults: {
|
||||
...prev.defaults,
|
||||
[role]: {
|
||||
...prev.defaults[role],
|
||||
...patch,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function updateRule(eventType: string, patch: Partial<AlertRule>) {
|
||||
setPolicyDraft((prev) => {
|
||||
if (!prev) return prev;
|
||||
return {
|
||||
...prev,
|
||||
rules: prev.rules.map((rule) =>
|
||||
rule.eventType === eventType ? { ...rule, ...patch } : rule
|
||||
),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function updateRuleRole(eventType: string, role: RoleName, patch: Partial<RoleRule>) {
|
||||
setPolicyDraft((prev) => {
|
||||
if (!prev) return prev;
|
||||
return {
|
||||
...prev,
|
||||
rules: prev.rules.map((rule) => {
|
||||
if (rule.eventType !== eventType) return rule;
|
||||
return {
|
||||
...rule,
|
||||
roles: {
|
||||
...rule.roles,
|
||||
[role]: {
|
||||
...rule.roles[role],
|
||||
...patch,
|
||||
},
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function applyDefaultsToEvent(eventType: string) {
|
||||
setPolicyDraft((prev) => {
|
||||
if (!prev) return prev;
|
||||
return {
|
||||
...prev,
|
||||
rules: prev.rules.map((rule) => {
|
||||
if (rule.eventType !== eventType) return rule;
|
||||
return {
|
||||
...rule,
|
||||
roles: {
|
||||
MEMBER: { ...prev.defaults.MEMBER },
|
||||
ADMIN: { ...prev.defaults.ADMIN },
|
||||
OWNER: { ...prev.defaults.OWNER },
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
async function savePolicy() {
|
||||
if (!policyDraft) return;
|
||||
setSavingPolicy(true);
|
||||
setPolicyError(null);
|
||||
try {
|
||||
const res = await fetch("/api/alerts/policy", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ policy: policyDraft }),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !json?.ok) {
|
||||
setPolicyError(json?.error || t("alerts.error.savePolicy"));
|
||||
return;
|
||||
}
|
||||
setPolicy(policyDraft);
|
||||
} catch {
|
||||
setPolicyError(t("alerts.error.savePolicy"));
|
||||
} finally {
|
||||
setSavingPolicy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function updateContactDraft(id: string, patch: Partial<ContactDraft>) {
|
||||
setContactEdits((prev) => ({
|
||||
...prev,
|
||||
[id]: {
|
||||
...(prev[id] ?? normalizeContactDraft(contacts.find((c) => c.id === id)!)),
|
||||
...patch,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
async function saveContact(id: string) {
|
||||
const draft = contactEdits[id];
|
||||
if (!draft) return;
|
||||
setSavingContactId(id);
|
||||
try {
|
||||
const eventTypes = draft.eventTypes.length ? draft.eventTypes : null;
|
||||
const res = await fetch(`/api/alerts/contacts/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: draft.name,
|
||||
roleScope: draft.roleScope,
|
||||
email: draft.email || null,
|
||||
phone: draft.phone || null,
|
||||
eventTypes,
|
||||
isActive: draft.isActive,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !json?.ok) {
|
||||
setContactsError(json?.error || t("alerts.error.saveContacts"));
|
||||
return;
|
||||
}
|
||||
const updated = json.contact as AlertContact;
|
||||
setContacts((prev) => prev.map((c) => (c.id === id ? updated : c)));
|
||||
setContactEdits((prev) => ({ ...prev, [id]: normalizeContactDraft(updated) }));
|
||||
} catch {
|
||||
setContactsError(t("alerts.error.saveContacts"));
|
||||
} finally {
|
||||
setSavingContactId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteContact(id: string) {
|
||||
setDeletingContactId(id);
|
||||
try {
|
||||
const res = await fetch(`/api/alerts/contacts/${id}`, { method: "DELETE" });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !json?.ok) {
|
||||
setContactsError(json?.error || t("alerts.error.deleteContact"));
|
||||
return;
|
||||
}
|
||||
setContacts((prev) => prev.filter((c) => c.id !== id));
|
||||
setContactEdits((prev) => {
|
||||
const next = { ...prev };
|
||||
delete next[id];
|
||||
return next;
|
||||
});
|
||||
} catch {
|
||||
setContactsError(t("alerts.error.deleteContact"));
|
||||
} finally {
|
||||
setDeletingContactId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function createContact() {
|
||||
setCreatingContact(true);
|
||||
setCreateError(null);
|
||||
try {
|
||||
const eventTypes = newContact.eventTypes.length ? newContact.eventTypes : null;
|
||||
const res = await fetch("/api/alerts/contacts", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: newContact.name,
|
||||
roleScope: newContact.roleScope,
|
||||
email: newContact.email || null,
|
||||
phone: newContact.phone || null,
|
||||
eventTypes,
|
||||
}),
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !json?.ok) {
|
||||
setCreateError(json?.error || t("alerts.error.createContact"));
|
||||
return;
|
||||
}
|
||||
const contact = json.contact as AlertContact;
|
||||
setContacts((prev) => [contact, ...prev]);
|
||||
setContactEdits((prev) => ({ ...prev, [contact.id]: normalizeContactDraft(contact) }));
|
||||
setNewContact({
|
||||
name: "",
|
||||
roleScope: "CUSTOM",
|
||||
email: "",
|
||||
phone: "",
|
||||
eventTypes: [],
|
||||
isActive: true,
|
||||
});
|
||||
} catch {
|
||||
setCreateError(t("alerts.error.createContact"));
|
||||
} finally {
|
||||
setCreatingContact(false);
|
||||
}
|
||||
}
|
||||
|
||||
const policyDirty = useMemo(
|
||||
() => JSON.stringify(policy) !== JSON.stringify(policyDraft),
|
||||
[policy, policyDraft]
|
||||
);
|
||||
const canEdit = role === "OWNER";
|
||||
const initialShifts = shiftRows.map((shift) => ({
|
||||
name: shift.name,
|
||||
enabled: shift.enabled !== false,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 py-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">{t("alerts.title")}</h1>
|
||||
<p className="mt-2 text-sm text-zinc-400">{t("alerts.subtitle")}</p>
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
<div className="text-sm text-zinc-400">{t("alerts.loading")}</div>
|
||||
)}
|
||||
|
||||
{!loading && policyError && (
|
||||
<div className="rounded-xl border border-red-500/20 bg-red-500/10 p-3 text-sm text-red-200">
|
||||
{policyError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && policyDraft && (
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="mb-4 flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="text-sm font-semibold text-white">{t("alerts.policy.title")}</div>
|
||||
<div className="text-xs text-zinc-400">{t("alerts.policy.subtitle")}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={savePolicy}
|
||||
disabled={!canEdit || !policyDirty || savingPolicy}
|
||||
className="rounded-xl border border-white/10 bg-white/10 px-4 py-2 text-sm text-white disabled:opacity-40"
|
||||
>
|
||||
{savingPolicy ? t("alerts.policy.saving") : t("alerts.policy.save")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!canEdit && (
|
||||
<div className="mb-4 rounded-xl border border-white/10 bg-black/20 p-3 text-sm text-zinc-300">
|
||||
{t("alerts.policy.readOnly")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-xl border border-white/10 bg-black/20 p-4">
|
||||
<div className="mb-3 text-xs text-zinc-400">{t("alerts.policy.defaults")}</div>
|
||||
<div className="mb-4 text-xs text-zinc-500">{t("alerts.policy.defaultsHelp")}</div>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
{ROLE_ORDER.map((role) => {
|
||||
const rule = policyDraft.defaults[role];
|
||||
return (
|
||||
<div key={role} className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="text-sm font-semibold text-white">{role}</div>
|
||||
<label className="mt-3 flex items-center gap-2 text-xs text-zinc-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rule.enabled}
|
||||
onChange={(event) => updatePolicyDefaults(role, { enabled: event.target.checked })}
|
||||
disabled={!canEdit}
|
||||
className="h-4 w-4 rounded border border-white/20 bg-black/20"
|
||||
/>
|
||||
{t("alerts.policy.enabled")}
|
||||
</label>
|
||||
<label className="mt-3 block text-xs text-zinc-400">
|
||||
{t("alerts.policy.afterMinutes")}
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={rule.afterMinutes}
|
||||
onChange={(event) =>
|
||||
updatePolicyDefaults(role, { afterMinutes: Number(event.target.value) })
|
||||
}
|
||||
disabled={!canEdit}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<div className="mt-3 text-xs text-zinc-400">{t("alerts.policy.channels")}</div>
|
||||
<div className="mt-2 flex flex-wrap gap-3">
|
||||
{CHANNELS.map((channel) => (
|
||||
<label key={channel} className="flex items-center gap-2 text-xs text-zinc-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={rule.channels.includes(channel)}
|
||||
onChange={(event) => {
|
||||
const next = event.target.checked
|
||||
? [...rule.channels, channel]
|
||||
: rule.channels.filter((c) => c !== channel);
|
||||
updatePolicyDefaults(role, { channels: next });
|
||||
}}
|
||||
disabled={!canEdit}
|
||||
className="h-4 w-4 rounded border border-white/20 bg-black/20"
|
||||
/>
|
||||
{channel.toUpperCase()}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 grid grid-cols-1 gap-4">
|
||||
<div className="rounded-xl border border-white/10 bg-black/20 p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-sm font-semibold text-white">{t("alerts.policy.eventSelectLabel")}</div>
|
||||
<div className="text-xs text-zinc-400">{t("alerts.policy.eventSelectHelper")}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<select
|
||||
value={selectedEventType}
|
||||
onChange={(event) => setSelectedEventType(event.target.value)}
|
||||
disabled={!canEdit}
|
||||
className="rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
>
|
||||
{policyDraft.rules.map((rule) => (
|
||||
<option key={rule.eventType} value={rule.eventType}>
|
||||
{t(`alerts.event.${rule.eventType}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => applyDefaultsToEvent(selectedEventType)}
|
||||
disabled={!canEdit || !selectedEventType}
|
||||
className="rounded-lg border border-white/10 bg-white/10 px-3 py-2 text-xs text-white disabled:opacity-40"
|
||||
>
|
||||
{t("alerts.policy.applyDefaults")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{policyDraft.rules
|
||||
.filter((rule) => rule.eventType === selectedEventType)
|
||||
.map((rule) => (
|
||||
<div key={rule.eventType} className="rounded-xl border border-white/10 bg-black/20 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="text-sm font-semibold text-white">
|
||||
{t(`alerts.event.${rule.eventType}`)}
|
||||
</div>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.policy.repeatMinutes")}
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={rule.repeatMinutes ?? 0}
|
||||
onChange={(event) =>
|
||||
updateRule(rule.eventType, { repeatMinutes: Number(event.target.value) })
|
||||
}
|
||||
disabled={!canEdit}
|
||||
className="ml-2 w-20 rounded-lg border border-white/10 bg-black/30 px-2 py-1 text-xs text-white"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
{ROLE_ORDER.map((role) => {
|
||||
const roleRule = rule.roles[role];
|
||||
return (
|
||||
<div key={role} className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="text-sm font-semibold text-white">{role}</div>
|
||||
<label className="mt-2 flex items-center gap-2 text-xs text-zinc-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={roleRule.enabled}
|
||||
onChange={(event) =>
|
||||
updateRuleRole(rule.eventType, role, { enabled: event.target.checked })
|
||||
}
|
||||
disabled={!canEdit}
|
||||
className="h-4 w-4 rounded border border-white/20 bg-black/20"
|
||||
/>
|
||||
{t("alerts.policy.enabled")}
|
||||
</label>
|
||||
<label className="mt-3 block text-xs text-zinc-400">
|
||||
{t("alerts.policy.afterMinutes")}
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={roleRule.afterMinutes}
|
||||
onChange={(event) =>
|
||||
updateRuleRole(rule.eventType, role, { afterMinutes: Number(event.target.value) })
|
||||
}
|
||||
disabled={!canEdit}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<div className="mt-3 text-xs text-zinc-400">{t("alerts.policy.channels")}</div>
|
||||
<div className="mt-2 flex flex-wrap gap-3">
|
||||
{CHANNELS.map((channel) => (
|
||||
<label key={channel} className="flex items-center gap-2 text-xs text-zinc-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={roleRule.channels.includes(channel)}
|
||||
onChange={(event) => {
|
||||
const next = event.target.checked
|
||||
? [...roleRule.channels, channel]
|
||||
: roleRule.channels.filter((c) => c !== channel);
|
||||
updateRuleRole(rule.eventType, role, { channels: next });
|
||||
}}
|
||||
disabled={!canEdit}
|
||||
className="h-4 w-4 rounded border border-white/20 bg-black/20"
|
||||
/>
|
||||
{channel.toUpperCase()}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="mb-4 flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="text-sm font-semibold text-white">{t("alerts.contacts.title")}</div>
|
||||
<div className="text-xs text-zinc-400">{t("alerts.contacts.subtitle")}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!canEdit && (
|
||||
<div className="mb-4 rounded-xl border border-white/10 bg-black/20 p-3 text-sm text-zinc-300">
|
||||
{t("alerts.contacts.readOnly")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{contactsError && (
|
||||
<div className="mb-3 rounded-xl border border-red-500/20 bg-red-500/10 p-3 text-sm text-red-200">
|
||||
{contactsError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("alerts.contacts.name")}
|
||||
<input
|
||||
value={newContact.name}
|
||||
onChange={(event) => setNewContact((prev) => ({ ...prev, name: event.target.value }))}
|
||||
disabled={!canEdit}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("alerts.contacts.roleScope")}
|
||||
<select
|
||||
value={newContact.roleScope}
|
||||
onChange={(event) => setNewContact((prev) => ({ ...prev, roleScope: event.target.value }))}
|
||||
disabled={!canEdit}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
>
|
||||
<option value="CUSTOM">{t("alerts.contacts.role.custom")}</option>
|
||||
<option value="MEMBER">{t("alerts.contacts.role.member")}</option>
|
||||
<option value="ADMIN">{t("alerts.contacts.role.admin")}</option>
|
||||
<option value="OWNER">{t("alerts.contacts.role.owner")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("alerts.contacts.email")}
|
||||
<input
|
||||
value={newContact.email}
|
||||
onChange={(event) => setNewContact((prev) => ({ ...prev, email: event.target.value }))}
|
||||
disabled={!canEdit}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("alerts.contacts.phone")}
|
||||
<input
|
||||
value={newContact.phone}
|
||||
onChange={(event) => setNewContact((prev) => ({ ...prev, phone: event.target.value }))}
|
||||
disabled={!canEdit}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400 md:col-span-2">
|
||||
{t("alerts.contacts.eventTypes")}
|
||||
<div className="mt-2 flex flex-wrap gap-3">
|
||||
{EVENT_TYPES.map((eventType) => (
|
||||
<label key={eventType.value} className="flex items-center gap-2 text-xs text-zinc-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={newContact.eventTypes.includes(eventType.value)}
|
||||
onChange={(event) => {
|
||||
const next = event.target.checked
|
||||
? [...newContact.eventTypes, eventType.value]
|
||||
: newContact.eventTypes.filter((value) => value !== eventType.value);
|
||||
setNewContact((prev) => ({ ...prev, eventTypes: next }));
|
||||
}}
|
||||
disabled={!canEdit}
|
||||
className="h-4 w-4 rounded border border-white/20 bg-black/20"
|
||||
/>
|
||||
{t(eventType.labelKey)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-2 text-xs text-zinc-500">{t("alerts.contacts.eventTypesHelper")}</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{createError && (
|
||||
<div className="mt-3 rounded-xl border border-red-500/20 bg-red-500/10 p-3 text-sm text-red-200">
|
||||
{createError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={createContact}
|
||||
disabled={!canEdit || creatingContact}
|
||||
className="rounded-xl border border-white/10 bg-white/10 px-4 py-2 text-sm text-white disabled:opacity-40"
|
||||
>
|
||||
{creatingContact ? t("alerts.contacts.creating") : t("alerts.contacts.add")}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 space-y-3">
|
||||
{contacts.length === 0 && (
|
||||
<div className="text-sm text-zinc-400">{t("alerts.contacts.empty")}</div>
|
||||
)}
|
||||
{contacts.map((contact) => {
|
||||
const draft = contactEdits[contact.id] ?? normalizeContactDraft(contact);
|
||||
const locked = !!contact.userId;
|
||||
return (
|
||||
<div key={contact.id} className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.contacts.name")}
|
||||
<input
|
||||
value={draft.name}
|
||||
onChange={(event) => updateContactDraft(contact.id, { name: event.target.value })}
|
||||
disabled={!canEdit || locked}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white disabled:opacity-50"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.contacts.roleScope")}
|
||||
<select
|
||||
value={draft.roleScope}
|
||||
onChange={(event) => updateContactDraft(contact.id, { roleScope: event.target.value })}
|
||||
disabled={!canEdit}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
>
|
||||
<option value="CUSTOM">{t("alerts.contacts.role.custom")}</option>
|
||||
<option value="MEMBER">{t("alerts.contacts.role.member")}</option>
|
||||
<option value="ADMIN">{t("alerts.contacts.role.admin")}</option>
|
||||
<option value="OWNER">{t("alerts.contacts.role.owner")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.contacts.email")}
|
||||
<input
|
||||
value={draft.email}
|
||||
onChange={(event) => updateContactDraft(contact.id, { email: event.target.value })}
|
||||
disabled={!canEdit || locked}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white disabled:opacity-50"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400">
|
||||
{t("alerts.contacts.phone")}
|
||||
<input
|
||||
value={draft.phone}
|
||||
onChange={(event) => updateContactDraft(contact.id, { phone: event.target.value })}
|
||||
disabled={!canEdit || locked}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white disabled:opacity-50"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs text-zinc-400 md:col-span-2">
|
||||
{t("alerts.contacts.eventTypes")}
|
||||
<div className="mt-2 flex flex-wrap gap-3">
|
||||
{EVENT_TYPES.map((eventType) => (
|
||||
<label key={eventType.value} className="flex items-center gap-2 text-xs text-zinc-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.eventTypes.includes(eventType.value)}
|
||||
onChange={(event) => {
|
||||
const next = event.target.checked
|
||||
? [...draft.eventTypes, eventType.value]
|
||||
: draft.eventTypes.filter((value) => value !== eventType.value);
|
||||
updateContactDraft(contact.id, { eventTypes: next });
|
||||
}}
|
||||
disabled={!canEdit}
|
||||
className="h-4 w-4 rounded border border-white/20 bg-black/20"
|
||||
/>
|
||||
{t(eventType.labelKey)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-2 text-xs text-zinc-500">{t("alerts.contacts.eventTypesHelper")}</div>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-xs text-zinc-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.isActive}
|
||||
onChange={(event) => updateContactDraft(contact.id, { isActive: event.target.checked })}
|
||||
disabled={!canEdit}
|
||||
className="h-4 w-4 rounded border border-white/20 bg-black/20"
|
||||
/>
|
||||
{t("alerts.contacts.active")}
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => saveContact(contact.id)}
|
||||
disabled={!canEdit || savingContactId === contact.id}
|
||||
className="rounded-xl border border-white/10 bg-white/10 px-4 py-2 text-xs text-white disabled:opacity-40"
|
||||
>
|
||||
{savingContactId === contact.id ? t("alerts.contacts.saving") : t("alerts.contacts.save")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => deleteContact(contact.id)}
|
||||
disabled={!canEdit || deletingContactId === contact.id}
|
||||
className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-2 text-xs text-red-200 disabled:opacity-40"
|
||||
>
|
||||
{deletingContactId === contact.id ? t("alerts.contacts.deleting") : t("alerts.contacts.delete")}
|
||||
</button>
|
||||
{locked && (
|
||||
<span className="text-xs text-zinc-500">{t("alerts.contacts.linkedUser")}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<AlertsClient
|
||||
initialMachines={machines}
|
||||
initialShifts={initialShifts}
|
||||
initialEvents={initialEvents}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
388
app/(app)/financial/FinancialClient.tsx
Normal file
388
app/(app)/financial/FinancialClient.tsx
Normal file
@@ -0,0 +1,388 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
CartesianGrid,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts";
|
||||
import { useI18n } from "@/lib/i18n/useI18n";
|
||||
|
||||
type MachineRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
location?: string | null;
|
||||
};
|
||||
|
||||
type ImpactSummary = {
|
||||
currency: string;
|
||||
totals: {
|
||||
total: number;
|
||||
slowCycle: number;
|
||||
microstop: number;
|
||||
macrostop: number;
|
||||
scrap: number;
|
||||
};
|
||||
byDay: Array<{
|
||||
day: string;
|
||||
total: number;
|
||||
slowCycle: number;
|
||||
microstop: number;
|
||||
macrostop: number;
|
||||
scrap: number;
|
||||
}>;
|
||||
};
|
||||
|
||||
type ImpactResponse = {
|
||||
ok: boolean;
|
||||
currencySummaries: ImpactSummary[];
|
||||
};
|
||||
|
||||
function formatMoney(value: number, currency: string, locale: string) {
|
||||
if (!Number.isFinite(value)) return "--";
|
||||
try {
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: "currency",
|
||||
currency,
|
||||
maximumFractionDigits: 0,
|
||||
}).format(value);
|
||||
} catch {
|
||||
return `${value.toFixed(0)} ${currency}`;
|
||||
}
|
||||
}
|
||||
|
||||
export default function FinancialClient({
|
||||
initialRole = null,
|
||||
initialMachines = [],
|
||||
initialImpact = null,
|
||||
}: {
|
||||
initialRole?: string | null;
|
||||
initialMachines?: MachineRow[];
|
||||
initialImpact?: ImpactResponse | null;
|
||||
}) {
|
||||
const { locale, t } = useI18n();
|
||||
const [role, setRole] = useState<string | null>(initialRole);
|
||||
const [machines, setMachines] = useState<MachineRow[]>(() => initialMachines);
|
||||
const [impact, setImpact] = useState<ImpactResponse | null>(initialImpact);
|
||||
const [range, setRange] = useState("7d");
|
||||
const [machineFilter, setMachineFilter] = useState("");
|
||||
const [locationFilter, setLocationFilter] = useState("");
|
||||
const [skuFilter, setSkuFilter] = useState("");
|
||||
const [currencyFilter, setCurrencyFilter] = useState("");
|
||||
const [loading, setLoading] = useState(() => initialMachines.length === 0);
|
||||
const skipInitialImpactRef = useRef(true);
|
||||
|
||||
const locations = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
for (const m of machines) {
|
||||
if (!m.location) continue;
|
||||
seen.add(m.location);
|
||||
}
|
||||
return Array.from(seen).sort();
|
||||
}, [machines]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialRole != null) return;
|
||||
let alive = true;
|
||||
|
||||
async function loadMe() {
|
||||
try {
|
||||
const res = await fetch("/api/me", { cache: "no-store" });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!alive) return;
|
||||
setRole(data?.membership?.role ?? null);
|
||||
} catch {
|
||||
if (alive) setRole(null);
|
||||
}
|
||||
}
|
||||
|
||||
loadMe();
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [initialRole]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialMachines.length) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
let alive = true;
|
||||
|
||||
async function loadMachines() {
|
||||
try {
|
||||
const res = await fetch("/api/machines", { cache: "no-store" });
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!alive) return;
|
||||
setMachines(json.machines ?? []);
|
||||
} catch {
|
||||
if (!alive) return;
|
||||
} finally {
|
||||
if (alive) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
loadMachines();
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [initialMachines]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const controller = new AbortController();
|
||||
|
||||
async function loadImpact() {
|
||||
if (role == null) return;
|
||||
if (role !== "OWNER") return;
|
||||
|
||||
const isDefault =
|
||||
range === "7d" &&
|
||||
!machineFilter &&
|
||||
!locationFilter &&
|
||||
!skuFilter &&
|
||||
!currencyFilter;
|
||||
if (skipInitialImpactRef.current) {
|
||||
skipInitialImpactRef.current = false;
|
||||
if (initialImpact && isDefault) return;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.set("range", range);
|
||||
if (machineFilter) params.set("machineId", machineFilter);
|
||||
if (locationFilter) params.set("location", locationFilter);
|
||||
if (skuFilter) params.set("sku", skuFilter);
|
||||
if (currencyFilter) params.set("currency", currencyFilter);
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/financial/impact?${params.toString()}`, {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!alive) return;
|
||||
setImpact(json);
|
||||
} catch {
|
||||
if (alive) setImpact(null);
|
||||
}
|
||||
}
|
||||
|
||||
loadImpact();
|
||||
return () => {
|
||||
alive = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [currencyFilter, initialImpact, locationFilter, machineFilter, range, role, skuFilter]);
|
||||
|
||||
const selectedSummary = impact?.currencySummaries?.[0] ?? null;
|
||||
const chartData = selectedSummary?.byDay ?? [];
|
||||
const exportQuery = useMemo(() => {
|
||||
const params = new URLSearchParams();
|
||||
params.set("range", range);
|
||||
if (machineFilter) params.set("machineId", machineFilter);
|
||||
if (locationFilter) params.set("location", locationFilter);
|
||||
if (skuFilter) params.set("sku", skuFilter);
|
||||
if (currencyFilter) params.set("currency", currencyFilter);
|
||||
return params.toString();
|
||||
}, [range, machineFilter, locationFilter, skuFilter, currencyFilter]);
|
||||
|
||||
const htmlHref = `/api/financial/export/pdf?${exportQuery}`;
|
||||
const csvHref = `/api/financial/export/excel?${exportQuery}`;
|
||||
|
||||
if (role && role !== "OWNER") {
|
||||
return (
|
||||
<div className="p-4 sm:p-6">
|
||||
<div className="rounded-2xl border border-white/10 bg-black/40 p-6 text-zinc-300">
|
||||
{t("financial.ownerOnly")}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-6 space-y-6">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">{t("financial.title")}</h1>
|
||||
<p className="text-sm text-zinc-400">{t("financial.subtitle")}</p>
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-3 sm:w-auto sm:flex-row">
|
||||
<a
|
||||
className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-center text-sm text-zinc-200 hover:bg-white/10 sm:w-auto"
|
||||
href={htmlHref}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{t("financial.export.html")}
|
||||
</a>
|
||||
<a
|
||||
className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-center text-sm text-zinc-200 hover:bg-white/10 sm:w-auto"
|
||||
href={csvHref}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{t("financial.export.csv")}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-black/40 p-4 text-sm text-zinc-300">
|
||||
{t("financial.costsMoved")}{" "}
|
||||
<Link className="text-emerald-200 hover:text-emerald-100" href="/settings">
|
||||
{t("financial.costsMovedLink")}
|
||||
</Link>
|
||||
.
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-4">
|
||||
{(impact?.currencySummaries ?? []).slice(0, 4).map((summary) => (
|
||||
<div key={summary.currency} className="rounded-2xl border border-white/10 bg-black/40 p-4">
|
||||
<div className="text-xs uppercase tracking-wide text-zinc-500">{t("financial.totalLoss")}</div>
|
||||
<div className="mt-2 text-2xl font-semibold text-white">
|
||||
{formatMoney(summary.totals.total, summary.currency, locale)}
|
||||
</div>
|
||||
<div className="mt-3 text-xs text-zinc-400">
|
||||
{t("financial.currencyLabel", { currency: summary.currency })}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!impact?.currencySummaries?.length && (
|
||||
<div className="rounded-2xl border border-white/10 bg-black/40 p-4 text-sm text-zinc-400">
|
||||
{t("financial.noImpact")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[2fr_1fr]">
|
||||
<div className="rounded-2xl border border-white/10 bg-black/40 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">{t("financial.chart.title")}</h2>
|
||||
<p className="text-xs text-zinc-500">{t("financial.chart.subtitle")}</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{["24h", "7d", "30d"].map((value) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
onClick={() => setRange(value)}
|
||||
className={
|
||||
value === range
|
||||
? "rounded-full bg-emerald-500/20 px-3 py-1 text-xs text-emerald-200"
|
||||
: "rounded-full border border-white/10 px-3 py-1 text-xs text-zinc-300"
|
||||
}
|
||||
>
|
||||
{value === "24h"
|
||||
? t("financial.range.day")
|
||||
: value === "7d"
|
||||
? t("financial.range.week")
|
||||
: t("financial.range.month")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={chartData}>
|
||||
<defs>
|
||||
<linearGradient id="slowFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#facc15" stopOpacity={0.5} />
|
||||
<stop offset="95%" stopColor="#facc15" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
<linearGradient id="microFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#fb7185" stopOpacity={0.5} />
|
||||
<stop offset="95%" stopColor="#fb7185" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
<linearGradient id="macroFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#f97316" stopOpacity={0.5} />
|
||||
<stop offset="95%" stopColor="#f97316" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
<linearGradient id="scrapFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#38bdf8" stopOpacity={0.5} />
|
||||
<stop offset="95%" stopColor="#38bdf8" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--app-chart-grid)" />
|
||||
<XAxis dataKey="day" tick={{ fill: "var(--app-chart-tick)", fontSize: 10 }} />
|
||||
<YAxis tick={{ fill: "var(--app-chart-tick)", fontSize: 10 }} />
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
background: "var(--app-chart-tooltip-bg)",
|
||||
border: "1px solid var(--app-chart-tooltip-border)",
|
||||
}}
|
||||
labelStyle={{ color: "var(--app-chart-label)" }}
|
||||
/>
|
||||
<Area type="monotone" dataKey="slowCycle" stackId="1" stroke="#facc15" fill="url(#slowFill)" />
|
||||
<Area type="monotone" dataKey="microstop" stackId="1" stroke="#fb7185" fill="url(#microFill)" />
|
||||
<Area type="monotone" dataKey="macrostop" stackId="1" stroke="#f97316" fill="url(#macroFill)" />
|
||||
<Area type="monotone" dataKey="scrap" stackId="1" stroke="#38bdf8" fill="url(#scrapFill)" />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-black/40 p-4 space-y-4">
|
||||
<h2 className="text-lg font-semibold text-white">{t("financial.filters.title")}</h2>
|
||||
<div className="space-y-3 text-sm text-zinc-300">
|
||||
<div>
|
||||
<label className="text-xs uppercase text-zinc-500">{t("financial.filters.machine")}</label>
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2"
|
||||
value={machineFilter}
|
||||
onChange={(event) => setMachineFilter(event.target.value)}
|
||||
>
|
||||
<option value="">{t("financial.filters.allMachines")}</option>
|
||||
{machines.map((machine) => (
|
||||
<option key={machine.id} value={machine.id}>
|
||||
{machine.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase text-zinc-500">{t("financial.filters.location")}</label>
|
||||
<select
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2"
|
||||
value={locationFilter}
|
||||
onChange={(event) => setLocationFilter(event.target.value)}
|
||||
>
|
||||
<option value="">{t("financial.filters.allLocations")}</option>
|
||||
{locations.map((loc) => (
|
||||
<option key={loc} value={loc}>
|
||||
{loc}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase text-zinc-500">{t("financial.filters.sku")}</label>
|
||||
<input
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2"
|
||||
value={skuFilter}
|
||||
onChange={(event) => setSkuFilter(event.target.value)}
|
||||
placeholder={t("financial.filters.skuPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase text-zinc-500">{t("financial.filters.currency")}</label>
|
||||
<input
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2"
|
||||
value={currencyFilter}
|
||||
onChange={(event) => setCurrencyFilter(event.target.value.toUpperCase())}
|
||||
placeholder={t("financial.filters.currencyPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && <div className="text-xs text-zinc-500">{t("financial.loadingMachines")}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
45
app/(app)/financial/page.tsx
Normal file
45
app/(app)/financial/page.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { requireSession } from "@/lib/auth/requireSession";
|
||||
import { computeFinancialImpact } from "@/lib/financial/impact";
|
||||
import FinancialClient from "./FinancialClient";
|
||||
|
||||
const RANGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export default async function FinancialPage() {
|
||||
const session = await requireSession();
|
||||
if (!session) redirect("/login?next=/financial");
|
||||
|
||||
const membership = await prisma.orgUser.findUnique({
|
||||
where: { orgId_userId: { orgId: session.orgId, userId: session.userId } },
|
||||
select: { role: true },
|
||||
});
|
||||
|
||||
const role = membership?.role ?? null;
|
||||
if (role !== "OWNER") {
|
||||
return <FinancialClient initialRole={role ?? "GUEST"} />;
|
||||
}
|
||||
|
||||
const machines = await prisma.machine.findMany({
|
||||
where: { orgId: session.orgId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { id: true, name: true, location: true },
|
||||
});
|
||||
|
||||
const end = new Date();
|
||||
const start = new Date(end.getTime() - RANGE_MS);
|
||||
const impact = await computeFinancialImpact({
|
||||
orgId: session.orgId,
|
||||
start,
|
||||
end,
|
||||
includeEvents: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<FinancialClient
|
||||
initialRole={role}
|
||||
initialMachines={machines}
|
||||
initialImpact={{ ok: true, currencySummaries: impact.currencySummaries }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,10 @@ import { prisma } from "@/lib/prisma";
|
||||
const COOKIE_NAME = "mis_session";
|
||||
|
||||
export default async function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
const sessionId = (await cookies()).get(COOKIE_NAME)?.value;
|
||||
const cookieJar = await cookies();
|
||||
const sessionId = cookieJar.get(COOKIE_NAME)?.value;
|
||||
const themeCookie = cookieJar.get("mis_theme")?.value;
|
||||
const initialTheme = themeCookie === "light" ? "light" : "dark";
|
||||
|
||||
if (!sessionId) redirect("/login?next=/machines");
|
||||
|
||||
@@ -24,5 +27,5 @@ export default async function AppLayout({ children }: { children: React.ReactNod
|
||||
redirect("/login?next=/machines");
|
||||
}
|
||||
|
||||
return <AppShell>{children}</AppShell>;
|
||||
return <AppShell initialTheme={initialTheme}>{children}</AppShell>;
|
||||
}
|
||||
|
||||
325
app/(app)/machines/MachinesClient.tsx
Normal file
325
app/(app)/machines/MachinesClient.tsx
Normal file
@@ -0,0 +1,325 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useI18n } from "@/lib/i18n/useI18n";
|
||||
|
||||
type MachineRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
code?: string | null;
|
||||
location?: string | null;
|
||||
latestHeartbeat: null | {
|
||||
ts: string;
|
||||
tsServer?: string | null;
|
||||
status: string;
|
||||
message?: string | null;
|
||||
ip?: string | null;
|
||||
fwVersion?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
function secondsAgo(ts: string | undefined, locale: string, fallback: string) {
|
||||
if (!ts) return fallback;
|
||||
const diff = Math.floor((Date.now() - new Date(ts).getTime()) / 1000);
|
||||
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
|
||||
if (diff < 60) return rtf.format(-diff, "second");
|
||||
return rtf.format(-Math.floor(diff / 60), "minute");
|
||||
}
|
||||
|
||||
function isOffline(ts?: string) {
|
||||
if (!ts) return true;
|
||||
return Date.now() - new Date(ts).getTime() > 30000; // 30s threshold
|
||||
}
|
||||
|
||||
function normalizeStatus(status?: string) {
|
||||
const s = (status ?? "").toUpperCase();
|
||||
if (s === "ONLINE") return "RUN";
|
||||
return s;
|
||||
}
|
||||
|
||||
function badgeClass(status?: string, offline?: boolean) {
|
||||
if (offline) return "bg-white/10 text-zinc-300";
|
||||
const s = (status ?? "").toUpperCase();
|
||||
if (s === "RUN") return "bg-emerald-500/15 text-emerald-300";
|
||||
if (s === "IDLE") return "bg-yellow-500/15 text-yellow-300";
|
||||
if (s === "STOP" || s === "DOWN") return "bg-red-500/15 text-red-300";
|
||||
return "bg-white/10 text-white";
|
||||
}
|
||||
|
||||
export default function MachinesClient({ initialMachines = [] }: { initialMachines?: MachineRow[] }) {
|
||||
const { t, locale } = useI18n();
|
||||
const [machines, setMachines] = useState<MachineRow[]>(() => initialMachines);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [createName, setCreateName] = useState("");
|
||||
const [createCode, setCreateCode] = useState("");
|
||||
const [createLocation, setCreateLocation] = useState("");
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [createError, setCreateError] = useState<string | null>(null);
|
||||
const [createdMachine, setCreatedMachine] = useState<{
|
||||
id: string;
|
||||
name: string;
|
||||
pairingCode: string;
|
||||
pairingExpiresAt: string;
|
||||
} | null>(null);
|
||||
const [copyStatus, setCopyStatus] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const res = await fetch("/api/machines", { cache: "no-store" });
|
||||
const json = await res.json();
|
||||
if (alive) {
|
||||
setMachines(json.machines ?? []);
|
||||
setLoading(false);
|
||||
}
|
||||
} catch {
|
||||
if (alive) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
const t = setInterval(load, 15000);
|
||||
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function createMachine() {
|
||||
if (!createName.trim()) {
|
||||
setCreateError(t("machines.create.error.nameRequired"));
|
||||
return;
|
||||
}
|
||||
|
||||
setCreating(true);
|
||||
setCreateError(null);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/machines", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: createName,
|
||||
code: createCode,
|
||||
location: createLocation,
|
||||
}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !data.ok) {
|
||||
throw new Error(data.error || t("machines.create.error.failed"));
|
||||
}
|
||||
|
||||
const nextMachine = {
|
||||
...data.machine,
|
||||
latestHeartbeat: null,
|
||||
};
|
||||
setMachines((prev) => [nextMachine, ...prev]);
|
||||
setCreatedMachine({
|
||||
id: data.machine.id,
|
||||
name: data.machine.name,
|
||||
pairingCode: data.machine.pairingCode,
|
||||
pairingExpiresAt: data.machine.pairingCodeExpiresAt,
|
||||
});
|
||||
setCreateName("");
|
||||
setCreateCode("");
|
||||
setCreateLocation("");
|
||||
setShowCreate(false);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : null;
|
||||
setCreateError(message || t("machines.create.error.failed"));
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function copyText(text: string) {
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopyStatus(t("machines.pairing.copied"));
|
||||
} else {
|
||||
setCopyStatus(t("machines.pairing.copyUnsupported"));
|
||||
}
|
||||
} catch {
|
||||
setCopyStatus(t("machines.pairing.copyFailed"));
|
||||
}
|
||||
setTimeout(() => setCopyStatus(null), 2000);
|
||||
}
|
||||
|
||||
const showCreateCard = showCreate || (!loading && machines.length === 0);
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-6">
|
||||
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">{t("machines.title")}</h1>
|
||||
<p className="text-sm text-zinc-400">{t("machines.subtitle")}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full flex-wrap items-center gap-2 sm:w-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCreate((prev) => !prev)}
|
||||
className="w-full rounded-xl border border-emerald-400/40 bg-emerald-500/20 px-4 py-2 text-sm text-emerald-100 hover:bg-emerald-500/30 sm:w-auto"
|
||||
>
|
||||
{showCreate ? t("machines.cancel") : t("machines.addMachine")}
|
||||
</button>
|
||||
<Link
|
||||
href="/overview"
|
||||
className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-center text-sm text-white hover:bg-white/10 sm:w-auto"
|
||||
>
|
||||
{t("machines.backOverview")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showCreateCard && (
|
||||
<div className="mb-6 rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-semibold text-white">{t("machines.addCardTitle")}</div>
|
||||
<div className="text-xs text-zinc-400">{t("machines.addCardSubtitle")}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("machines.field.name")}
|
||||
<input
|
||||
value={createName}
|
||||
onChange={(event) => setCreateName(event.target.value)}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("machines.field.code")}
|
||||
<input
|
||||
value={createCode}
|
||||
onChange={(event) => setCreateCode(event.target.value)}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("machines.field.location")}
|
||||
<input
|
||||
value={createLocation}
|
||||
onChange={(event) => setCreateLocation(event.target.value)}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={createMachine}
|
||||
disabled={creating}
|
||||
className="rounded-xl border border-emerald-400/40 bg-emerald-500/20 px-4 py-2 text-sm text-emerald-100 hover:bg-emerald-500/30 disabled:opacity-60"
|
||||
>
|
||||
{creating ? t("machines.create.loading") : t("machines.create.default")}
|
||||
</button>
|
||||
{createError && <div className="text-xs text-red-200">{createError}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{createdMachine && (
|
||||
<div className="mb-6 rounded-2xl border border-emerald-500/20 bg-emerald-500/10 p-5">
|
||||
<div className="text-sm font-semibold text-white">{t("machines.pairing.title")}</div>
|
||||
<div className="mt-2 text-xs text-zinc-300">
|
||||
{t("machines.pairing.machine")} <span className="text-white">{createdMachine.name}</span>
|
||||
</div>
|
||||
<div className="mt-3 rounded-xl border border-white/10 bg-black/30 p-4">
|
||||
<div className="text-xs uppercase tracking-wide text-zinc-400">{t("machines.pairing.codeLabel")}</div>
|
||||
<div className="mt-2 text-3xl font-semibold text-white">{createdMachine.pairingCode}</div>
|
||||
<div className="mt-2 text-xs text-zinc-400">
|
||||
{t("machines.pairing.expires")}{" "}
|
||||
{createdMachine.pairingExpiresAt
|
||||
? new Date(createdMachine.pairingExpiresAt).toLocaleString(locale)
|
||||
: t("machines.pairing.soon")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 text-xs text-zinc-300">
|
||||
{t("machines.pairing.instructions")}
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copyText(createdMachine.pairingCode)}
|
||||
className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm text-white hover:bg-white/10"
|
||||
>
|
||||
{t("machines.pairing.copy")}
|
||||
</button>
|
||||
{copyStatus && <div className="text-xs text-zinc-300">{copyStatus}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && <div className="mb-4 text-sm text-zinc-400">{t("machines.loading")}</div>}
|
||||
|
||||
{!loading && machines.length === 0 && (
|
||||
<div className="mb-4 text-sm text-zinc-400">{t("machines.empty")}</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
{(!loading ? machines : []).map((m) => {
|
||||
const hb = m.latestHeartbeat;
|
||||
const hbTs = hb?.tsServer ?? hb?.ts;
|
||||
const offline = isOffline(hbTs);
|
||||
const normalizedStatus = normalizeStatus(hb?.status);
|
||||
const statusLabel = offline ? t("machines.status.offline") : (normalizedStatus || t("machines.status.unknown"));
|
||||
const lastSeen = secondsAgo(hbTs, locale, t("common.never"));
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={m.id}
|
||||
href={`/machines/${m.id}`}
|
||||
className="rounded-2xl border border-white/10 bg-white/5 p-5 hover:bg-white/10"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-lg font-semibold text-white">{m.name}</div>
|
||||
<div className="mt-1 text-xs text-zinc-400">
|
||||
{m.code ? m.code : t("common.na")} - {t("machines.lastSeen", { time: lastSeen })}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<span
|
||||
className={`shrink-0 rounded-full px-3 py-1 text-xs ${badgeClass(
|
||||
normalizedStatus,
|
||||
offline
|
||||
)}`}
|
||||
>
|
||||
{statusLabel}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 text-sm text-zinc-400">{t("machines.status")}</div>
|
||||
<div className="mt-1 flex items-center gap-2 text-sm font-semibold text-white">
|
||||
{offline ? (
|
||||
<>
|
||||
<span className="inline-flex h-2.5 w-2.5 rounded-full bg-zinc-500" aria-hidden="true" />
|
||||
<span>{t("machines.status.noHeartbeat")}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="relative flex h-2.5 w-2.5" aria-hidden="true">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
|
||||
<span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-emerald-400" />
|
||||
</span>
|
||||
<span>{t("machines.status.ok")}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type ChangeEvent } from "react";
|
||||
import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import {
|
||||
@@ -73,6 +73,7 @@ type MachineDetail = {
|
||||
name: string;
|
||||
code?: string | null;
|
||||
location?: string | null;
|
||||
effectiveCycleTime?: number | null;
|
||||
latestHeartbeat: Heartbeat | null;
|
||||
latestKpi: Kpi | null;
|
||||
};
|
||||
@@ -111,11 +112,54 @@ type WorkOrderUpload = {
|
||||
cycleTime?: number;
|
||||
};
|
||||
|
||||
type WorkOrderRow = Record<string, string | number | boolean>;
|
||||
type TooltipPayload<T> = { payload?: T; name?: string; value?: number | string };
|
||||
type SimpleTooltipProps<T> = {
|
||||
active?: boolean;
|
||||
payload?: Array<TooltipPayload<T>>;
|
||||
label?: string | number;
|
||||
};
|
||||
type ActiveRingProps = { cx?: number; cy?: number; fill?: string };
|
||||
type ScatterPointProps = { cx?: number; cy?: number; payload?: { bucket?: string } };
|
||||
|
||||
const TOL = 0.10;
|
||||
const DEFAULT_MICRO_MULT = 1.5;
|
||||
const DEFAULT_MACRO_MULT = 5;
|
||||
const NORMAL_TOL_SEC = 0.1;
|
||||
|
||||
const BUCKET = {
|
||||
normal: {
|
||||
labelKey: "machine.detail.bucket.normal",
|
||||
dot: "#12D18E",
|
||||
glow: "rgba(18,209,142,.35)",
|
||||
chip: "bg-emerald-500/15 text-emerald-300 border-emerald-500/20",
|
||||
},
|
||||
slow: {
|
||||
labelKey: "machine.detail.bucket.slow",
|
||||
dot: "#F7B500",
|
||||
glow: "rgba(247,181,0,.35)",
|
||||
chip: "bg-yellow-500/15 text-yellow-300 border-yellow-500/20",
|
||||
},
|
||||
microstop: {
|
||||
labelKey: "machine.detail.bucket.microstop",
|
||||
dot: "#FF7A00",
|
||||
glow: "rgba(255,122,0,.35)",
|
||||
chip: "bg-orange-500/15 text-orange-300 border-orange-500/20",
|
||||
},
|
||||
macrostop: {
|
||||
labelKey: "machine.detail.bucket.macrostop",
|
||||
dot: "#FF3B5C",
|
||||
glow: "rgba(255,59,92,.35)",
|
||||
chip: "bg-rose-500/15 text-rose-300 border-rose-500/20",
|
||||
},
|
||||
unknown: {
|
||||
labelKey: "machine.detail.bucket.unknown",
|
||||
dot: "#A1A1AA",
|
||||
glow: "rgba(161,161,170,.25)",
|
||||
chip: "bg-white/10 text-zinc-200 border-white/10",
|
||||
},
|
||||
} as const;
|
||||
|
||||
|
||||
function resolveMultipliers(thresholds?: Thresholds | null) {
|
||||
const micro = Number(thresholds?.stoppageMultiplier ?? DEFAULT_MICRO_MULT);
|
||||
@@ -213,14 +257,14 @@ function parseCsvText(text: string) {
|
||||
});
|
||||
}
|
||||
|
||||
function pickRowValue(row: Record<string, any>, keys: Set<string>) {
|
||||
function pickRowValue(row: WorkOrderRow, keys: Set<string>) {
|
||||
for (const [key, value] of Object.entries(row)) {
|
||||
if (keys.has(normalizeKey(key))) return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function rowsToWorkOrders(rows: Array<Record<string, any>>): WorkOrderUpload[] {
|
||||
function rowsToWorkOrders(rows: WorkOrderRow[]): WorkOrderUpload[] {
|
||||
const seen = new Set<string>();
|
||||
const out: WorkOrderUpload[] = [];
|
||||
|
||||
@@ -261,42 +305,8 @@ export default function MachineDetailClient() {
|
||||
const [open, setOpen] = useState<null | "events" | "deviation" | "impact">(null);
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [uploadState, setUploadState] = useState<UploadState>({ status: "idle" });
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
|
||||
|
||||
const BUCKET = {
|
||||
normal: {
|
||||
labelKey: "machine.detail.bucket.normal",
|
||||
dot: "#12D18E",
|
||||
glow: "rgba(18,209,142,.35)",
|
||||
chip: "bg-emerald-500/15 text-emerald-300 border-emerald-500/20",
|
||||
},
|
||||
slow: {
|
||||
labelKey: "machine.detail.bucket.slow",
|
||||
dot: "#F7B500",
|
||||
glow: "rgba(247,181,0,.35)",
|
||||
chip: "bg-yellow-500/15 text-yellow-300 border-yellow-500/20",
|
||||
},
|
||||
microstop: {
|
||||
labelKey: "machine.detail.bucket.microstop",
|
||||
dot: "#FF7A00",
|
||||
glow: "rgba(255,122,0,.35)",
|
||||
chip: "bg-orange-500/15 text-orange-300 border-orange-500/20",
|
||||
},
|
||||
macrostop: {
|
||||
labelKey: "machine.detail.bucket.macrostop",
|
||||
dot: "#FF3B5C",
|
||||
glow: "rgba(255,59,92,.35)",
|
||||
chip: "bg-rose-500/15 text-rose-300 border-rose-500/20",
|
||||
},
|
||||
unknown: {
|
||||
labelKey: "machine.detail.bucket.unknown",
|
||||
dot: "#A1A1AA",
|
||||
glow: "rgba(161,161,170,.25)",
|
||||
chip: "bg-white/10 text-zinc-200 border-white/10",
|
||||
},
|
||||
} as const;
|
||||
|
||||
useEffect(() => {
|
||||
if (!machineId) return;
|
||||
|
||||
@@ -305,9 +315,16 @@ export default function MachineDetailClient() {
|
||||
async function load() {
|
||||
try {
|
||||
const res = await fetch(`/api/machines/${machineId}?windowSec=3600&events=critical`, {
|
||||
cache: "no-store",
|
||||
cache: "no-cache",
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (res.status === 304) {
|
||||
if (!alive) return;
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const json = await res.json().catch(() => ({}));
|
||||
|
||||
if (!alive) return;
|
||||
@@ -341,31 +358,30 @@ export default function MachineDetailClient() {
|
||||
};
|
||||
}, [machineId, t]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setNowMs(Date.now()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (open !== "events" || !machineId) return;
|
||||
|
||||
let alive = true;
|
||||
setDetectedEventsLoading(true);
|
||||
|
||||
fetch(`/api/machines/${machineId}?events=all&eventsOnly=1&eventsWindowSec=21600`, {
|
||||
cache: "no-store",
|
||||
credentials: "include",
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((json) => {
|
||||
async function loadDetected() {
|
||||
try {
|
||||
const res = await fetch(`/api/machines/${machineId}?events=all&eventsOnly=1&eventsWindowSec=21600`, {
|
||||
cache: "no-cache",
|
||||
credentials: "include",
|
||||
});
|
||||
if (res.status === 304) return;
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!alive) return;
|
||||
setDetectedEvents(json.events ?? []);
|
||||
setEventsCountAll(typeof json.eventsCountAll === "number" ? json.eventsCountAll : eventsCountAll);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
} catch {
|
||||
} finally {
|
||||
if (alive) setDetectedEventsLoading(false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
loadDetected();
|
||||
|
||||
return () => {
|
||||
alive = false;
|
||||
@@ -385,15 +401,15 @@ export default function MachineDetailClient() {
|
||||
const workbook = xlsx.read(buffer, { type: "array" });
|
||||
const sheet = workbook.Sheets[workbook.SheetNames[0]];
|
||||
if (!sheet) return [];
|
||||
const rows = xlsx.utils.sheet_to_json(sheet, { defval: "" });
|
||||
return rowsToWorkOrders(rows as Array<Record<string, any>>);
|
||||
const rows = xlsx.utils.sheet_to_json<WorkOrderRow>(sheet, { defval: "" });
|
||||
return rowsToWorkOrders(rows);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function handleWorkOrderUpload(event: any) {
|
||||
const file = event?.target?.files?.[0] as File | undefined;
|
||||
async function handleWorkOrderUpload(event: ChangeEvent<HTMLInputElement>) {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
if (!machineId) {
|
||||
@@ -477,19 +493,6 @@ export default function MachineDetailClient() {
|
||||
return `${v}`;
|
||||
}
|
||||
|
||||
function formatDurationShort(totalSec?: number | null) {
|
||||
if (totalSec === null || totalSec === undefined || Number.isNaN(totalSec)) {
|
||||
return t("common.na");
|
||||
}
|
||||
const sec = Math.max(0, Math.floor(totalSec));
|
||||
const h = Math.floor(sec / 3600);
|
||||
const m = Math.floor((sec % 3600) / 60);
|
||||
const s = sec % 60;
|
||||
if (h > 0) return `${h}h ${m}m`;
|
||||
if (m > 0) return `${m}m ${s}s`;
|
||||
return `${s}s`;
|
||||
}
|
||||
|
||||
|
||||
function timeAgo(ts?: string) {
|
||||
if (!ts) return t("common.never");
|
||||
@@ -554,15 +557,14 @@ export default function MachineDetailClient() {
|
||||
const label = t(key);
|
||||
return label === key ? normalizedStatus : label;
|
||||
})();
|
||||
const cycleTarget = (machine as any)?.effectiveCycleTime ?? kpi?.cycleTime ?? null;
|
||||
const cycleTarget = machine?.effectiveCycleTime ?? kpi?.cycleTime ?? null;
|
||||
const machineCode = machine?.code ?? t("common.na");
|
||||
const machineLocation = machine?.location ?? t("common.na");
|
||||
const lastSeenLabel = t("machine.detail.lastSeen", {
|
||||
time: hbTs ? timeAgo(hbTs) : t("common.never"),
|
||||
});
|
||||
|
||||
const ActiveRing = (props: any) => {
|
||||
const { cx, cy, fill } = props;
|
||||
const ActiveRing = ({ cx, cy, fill }: ActiveRingProps) => {
|
||||
if (cx == null || cy == null) return null;
|
||||
return (
|
||||
<g>
|
||||
@@ -609,12 +611,84 @@ export default function MachineDetailClient() {
|
||||
}
|
||||
|
||||
function MachineActivityTimeline({
|
||||
segments,
|
||||
windowSec,
|
||||
cycles,
|
||||
cycleTarget,
|
||||
thresholds,
|
||||
activeStoppage,
|
||||
}: {
|
||||
segments: TimelineSeg[];
|
||||
windowSec: number;
|
||||
cycles: CycleRow[];
|
||||
cycleTarget: number | null;
|
||||
thresholds: Thresholds | null;
|
||||
activeStoppage: ActiveStoppage | null;
|
||||
}) {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setNowMs(Date.now()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
const timeline = useMemo(() => {
|
||||
const rows = cycles ?? [];
|
||||
const windowSec = rows.length < 1 ? 10800 : 3600;
|
||||
const end = nowMs;
|
||||
const start = end - windowSec * 1000;
|
||||
|
||||
if (rows.length < 1) {
|
||||
return {
|
||||
windowSec,
|
||||
segments: [] as TimelineSeg[],
|
||||
start,
|
||||
end,
|
||||
};
|
||||
}
|
||||
|
||||
const segs: TimelineSeg[] = [];
|
||||
|
||||
for (const cycle of rows) {
|
||||
const ideal = (cycle.ideal ?? cycleTarget ?? 0) as number;
|
||||
const actual = cycle.actual ?? 0;
|
||||
if (!ideal || ideal <= 0 || !actual || actual <= 0) continue;
|
||||
|
||||
const cycleEnd = cycle.t;
|
||||
const cycleStart = cycleEnd - actual * 1000;
|
||||
if (cycleEnd <= start || cycleStart >= end) continue;
|
||||
|
||||
const segStart = Math.max(cycleStart, start);
|
||||
const segEnd = Math.min(cycleEnd, end);
|
||||
if (segEnd <= segStart) continue;
|
||||
|
||||
const state = classifyCycleDuration(actual, ideal, thresholds);
|
||||
|
||||
segs.push({
|
||||
start: segStart,
|
||||
end: segEnd,
|
||||
durationSec: (segEnd - segStart) / 1000,
|
||||
state,
|
||||
});
|
||||
}
|
||||
|
||||
if (activeStoppage?.startedAt) {
|
||||
const stoppageStart = new Date(activeStoppage.startedAt).getTime();
|
||||
const segStart = Math.max(stoppageStart, start);
|
||||
const segEnd = Math.min(end, nowMs);
|
||||
if (segEnd > segStart) {
|
||||
segs.push({
|
||||
start: segStart,
|
||||
end: segEnd,
|
||||
durationSec: (segEnd - segStart) / 1000,
|
||||
state: activeStoppage.state,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
segs.sort((a, b) => a.start - b.start);
|
||||
|
||||
return { windowSec, segments: segs, start, end };
|
||||
}, [activeStoppage, cycles, cycleTarget, nowMs, thresholds]);
|
||||
|
||||
const { segments, windowSec } = timeline;
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
@@ -647,7 +721,7 @@ export default function MachineDetailClient() {
|
||||
</div>
|
||||
) : (
|
||||
segments.map((seg, idx) => {
|
||||
const wPct = Math.max(0.25, (seg.durationSec / windowSec) * 100);
|
||||
const wPct = Math.max(0, (seg.durationSec / windowSec) * 100);
|
||||
const meta = BUCKET[seg.state];
|
||||
const glow =
|
||||
seg.state === "microstop" || seg.state === "macrostop"
|
||||
@@ -718,11 +792,16 @@ export default function MachineDetailClient() {
|
||||
);
|
||||
}
|
||||
|
||||
function CycleTooltip({ active, payload, label }: any) {
|
||||
function CycleTooltip({
|
||||
active,
|
||||
payload,
|
||||
label,
|
||||
}: SimpleTooltipProps<{ actual?: number; ideal?: number; deltaPct?: number }>) {
|
||||
if (!active || !payload?.length) return null;
|
||||
|
||||
const p = payload[0]?.payload;
|
||||
if (!p) return null;
|
||||
const safeLabel = label ?? "";
|
||||
|
||||
const ideal = p.ideal ?? null;
|
||||
const actual = p.actual ?? null;
|
||||
@@ -731,7 +810,7 @@ export default function MachineDetailClient() {
|
||||
return (
|
||||
<div className="rounded-xl border border-white/10 bg-zinc-950/95 px-4 py-3 shadow-lg">
|
||||
<div className="text-sm font-semibold text-white">
|
||||
{t("machine.detail.tooltip.cycle", { label })}
|
||||
{t("machine.detail.tooltip.cycle", { label: safeLabel })}
|
||||
</div>
|
||||
<div className="mt-2 space-y-1 text-xs text-zinc-300">
|
||||
<div>
|
||||
@@ -756,7 +835,6 @@ export default function MachineDetailClient() {
|
||||
|
||||
const cycleDerived = useMemo(() => {
|
||||
const rows = cycles ?? [];
|
||||
const { micro, macro } = resolveMultipliers(thresholds);
|
||||
|
||||
const mapped: CycleDerivedRow[] = rows.map((cycle) => {
|
||||
const ideal = cycle.ideal ?? null;
|
||||
@@ -833,62 +911,15 @@ export default function MachineDetailClient() {
|
||||
|
||||
const total = rows.reduce((sum, row) => sum + row.seconds, 0);
|
||||
return { rows, total };
|
||||
}, [BUCKET, cycleDerived.mapped, t]);
|
||||
|
||||
const timeline = useMemo(() => {
|
||||
const rows = cycles ?? [];
|
||||
if (rows.length < 1) {
|
||||
return {
|
||||
windowSec: 10800,
|
||||
segments: [] as TimelineSeg[],
|
||||
start: null as number | null,
|
||||
end: null as number | null,
|
||||
};
|
||||
}
|
||||
|
||||
const windowSec = 3600;
|
||||
const end = rows[rows.length - 1].t;
|
||||
const start = end - windowSec * 1000;
|
||||
|
||||
const segs: TimelineSeg[] = [];
|
||||
|
||||
for (const cycle of rows) {
|
||||
const ideal = (cycle.ideal ?? cycleTarget ?? 0) as number;
|
||||
const actual = cycle.actual ?? 0;
|
||||
if (!ideal || ideal <= 0 || !actual || actual <= 0) continue;
|
||||
|
||||
const cycleEnd = cycle.t;
|
||||
const cycleStart = cycleEnd - actual * 1000;
|
||||
if (cycleEnd <= start || cycleStart >= end) continue;
|
||||
|
||||
const segStart = Math.max(cycleStart, start);
|
||||
const segEnd = Math.min(cycleEnd, end);
|
||||
if (segEnd <= segStart) continue;
|
||||
|
||||
const state = classifyCycleDuration(actual, ideal, thresholds);
|
||||
|
||||
|
||||
|
||||
segs.push({
|
||||
start: segStart,
|
||||
end: segEnd,
|
||||
durationSec: (segEnd - segStart) / 1000,
|
||||
state,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
return { windowSec, segments: segs, start, end };
|
||||
}, [cycles, cycleTarget, thresholds]);
|
||||
}, [cycleDerived.mapped, t]);
|
||||
|
||||
const cycleTargetLabel = cycleTarget ? `${cycleTarget}s` : t("common.na");
|
||||
const workOrderLabel = kpi?.workOrderId ?? t("common.na");
|
||||
const skuLabel = kpi?.sku ?? t("common.na");
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="mb-6 flex items-start justify-between gap-4">
|
||||
<div className="p-4 sm:p-6">
|
||||
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<h1 className="truncate text-2xl font-semibold text-white">
|
||||
@@ -903,8 +934,8 @@ export default function MachineDetailClient() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 flex-col items-end gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex w-full flex-col items-start gap-2 sm:w-auto sm:items-end">
|
||||
<div className="flex w-full flex-wrap items-center gap-2 sm:w-auto sm:flex-nowrap">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
@@ -916,18 +947,18 @@ export default function MachineDetailClient() {
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isUploading}
|
||||
className="rounded-xl border border-emerald-500/30 bg-emerald-500/10 px-4 py-2 text-sm text-emerald-100 transition hover:bg-emerald-500/20 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
className="w-full rounded-xl border border-emerald-500/30 bg-emerald-500/10 px-4 py-2 text-sm text-emerald-100 transition hover:bg-emerald-500/20 disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto"
|
||||
>
|
||||
{uploadButtonLabel}
|
||||
</button>
|
||||
<Link
|
||||
href="/machines"
|
||||
className="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-white hover:bg-white/10"
|
||||
className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-center text-sm text-white hover:bg-white/10 sm:w-auto"
|
||||
>
|
||||
{t("machine.detail.back")}
|
||||
</Link>
|
||||
</div>
|
||||
<div className="text-right text-[11px] text-zinc-500">
|
||||
<div className="text-left text-[11px] text-zinc-500 sm:text-right">
|
||||
{t("machine.detail.workOrders.uploadHint")}
|
||||
</div>
|
||||
{uploadState.status !== "idle" && uploadState.message && (
|
||||
@@ -975,7 +1006,12 @@ export default function MachineDetailClient() {
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
<MachineActivityTimeline segments={timeline.segments} windowSec={timeline.windowSec} />
|
||||
<MachineActivityTimeline
|
||||
cycles={cycles}
|
||||
cycleTarget={cycleTarget}
|
||||
thresholds={thresholds}
|
||||
activeStoppage={activeStoppage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 gap-4 xl:grid-cols-3">
|
||||
@@ -1197,9 +1233,9 @@ export default function MachineDetailClient() {
|
||||
dataKey="actual"
|
||||
isAnimationActive={false}
|
||||
activeShape={<ActiveRing />}
|
||||
shape={(props: any) => {
|
||||
const { cx, cy, payload } = props;
|
||||
const meta = BUCKET[payload.bucket as keyof typeof BUCKET] ?? BUCKET.unknown;
|
||||
shape={({ cx, cy, payload }: ScatterPointProps) => {
|
||||
const meta =
|
||||
BUCKET[(payload?.bucket as keyof typeof BUCKET) ?? "unknown"] ?? BUCKET.unknown;
|
||||
|
||||
return (
|
||||
<circle
|
||||
@@ -1259,7 +1295,10 @@ export default function MachineDetailClient() {
|
||||
border: "1px solid var(--app-chart-tooltip-border)",
|
||||
}}
|
||||
labelStyle={{ color: "var(--app-chart-label)" }}
|
||||
formatter={(val: any) => [`${Number(val).toFixed(1)}s`, t("machine.detail.modal.extraTimeLabel")]}
|
||||
formatter={(val: number | string | undefined) => [
|
||||
`${val == null ? 0 : Number(val).toFixed(1)}s`,
|
||||
t("machine.detail.modal.extraTimeLabel"),
|
||||
]}
|
||||
/>
|
||||
<Bar dataKey="seconds" radius={[10, 10, 0, 0]} isAnimationActive={false}>
|
||||
{impactAgg.rows.map((row, idx) => {
|
||||
|
||||
@@ -1,324 +1,45 @@
|
||||
"use client";
|
||||
import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { requireSession } from "@/lib/auth/requireSession";
|
||||
import MachinesClient from "./MachinesClient";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useI18n } from "@/lib/i18n/useI18n";
|
||||
|
||||
type MachineRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
code?: string | null;
|
||||
location?: string | null;
|
||||
latestHeartbeat: null | {
|
||||
ts: string;
|
||||
tsServer?: string | null;
|
||||
status: string;
|
||||
message?: string | null;
|
||||
ip?: string | null;
|
||||
fwVersion?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
function secondsAgo(ts: string | undefined, locale: string, fallback: string) {
|
||||
if (!ts) return fallback;
|
||||
const diff = Math.floor((Date.now() - new Date(ts).getTime()) / 1000);
|
||||
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
|
||||
if (diff < 60) return rtf.format(-diff, "second");
|
||||
return rtf.format(-Math.floor(diff / 60), "minute");
|
||||
function toIso(value?: Date | null) {
|
||||
return value ? value.toISOString() : null;
|
||||
}
|
||||
|
||||
function isOffline(ts?: string) {
|
||||
if (!ts) return true;
|
||||
return Date.now() - new Date(ts).getTime() > 30000; // 30s threshold
|
||||
}
|
||||
export default async function MachinesPage() {
|
||||
const session = await requireSession();
|
||||
if (!session) redirect("/login?next=/machines");
|
||||
|
||||
function normalizeStatus(status?: string) {
|
||||
const s = (status ?? "").toUpperCase();
|
||||
if (s === "ONLINE") return "RUN";
|
||||
return s;
|
||||
}
|
||||
const machines = await prisma.machine.findMany({
|
||||
where: { orgId: session.orgId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
location: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
heartbeats: {
|
||||
orderBy: { tsServer: "desc" },
|
||||
take: 1,
|
||||
select: { ts: true, tsServer: true, status: true, message: true, ip: true, fwVersion: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function badgeClass(status?: string, offline?: boolean) {
|
||||
if (offline) return "bg-white/10 text-zinc-300";
|
||||
const s = (status ?? "").toUpperCase();
|
||||
if (s === "RUN") return "bg-emerald-500/15 text-emerald-300";
|
||||
if (s === "IDLE") return "bg-yellow-500/15 text-yellow-300";
|
||||
if (s === "STOP" || s === "DOWN") return "bg-red-500/15 text-red-300";
|
||||
return "bg-white/10 text-white";
|
||||
}
|
||||
|
||||
export default function MachinesPage() {
|
||||
const { t, locale } = useI18n();
|
||||
const [machines, setMachines] = useState<MachineRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [createName, setCreateName] = useState("");
|
||||
const [createCode, setCreateCode] = useState("");
|
||||
const [createLocation, setCreateLocation] = useState("");
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [createError, setCreateError] = useState<string | null>(null);
|
||||
const [createdMachine, setCreatedMachine] = useState<{
|
||||
id: string;
|
||||
name: string;
|
||||
pairingCode: string;
|
||||
pairingExpiresAt: string;
|
||||
} | null>(null);
|
||||
const [copyStatus, setCopyStatus] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const res = await fetch("/api/machines", { cache: "no-store" });
|
||||
const json = await res.json();
|
||||
if (alive) {
|
||||
setMachines(json.machines ?? []);
|
||||
setLoading(false);
|
||||
const initialMachines = machines.map((machine) => ({
|
||||
...machine,
|
||||
latestHeartbeat: machine.heartbeats[0]
|
||||
? {
|
||||
...machine.heartbeats[0],
|
||||
ts: toIso(machine.heartbeats[0].ts) ?? "",
|
||||
tsServer: toIso(machine.heartbeats[0].tsServer),
|
||||
}
|
||||
} catch {
|
||||
if (alive) setLoading(false);
|
||||
}
|
||||
}
|
||||
: null,
|
||||
heartbeats: undefined,
|
||||
}));
|
||||
|
||||
load();
|
||||
const t = setInterval(load, 15000);
|
||||
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function createMachine() {
|
||||
if (!createName.trim()) {
|
||||
setCreateError(t("machines.create.error.nameRequired"));
|
||||
return;
|
||||
}
|
||||
|
||||
setCreating(true);
|
||||
setCreateError(null);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/machines", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: createName,
|
||||
code: createCode,
|
||||
location: createLocation,
|
||||
}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !data.ok) {
|
||||
throw new Error(data.error || t("machines.create.error.failed"));
|
||||
}
|
||||
|
||||
const nextMachine = {
|
||||
...data.machine,
|
||||
latestHeartbeat: null,
|
||||
};
|
||||
setMachines((prev) => [nextMachine, ...prev]);
|
||||
setCreatedMachine({
|
||||
id: data.machine.id,
|
||||
name: data.machine.name,
|
||||
pairingCode: data.machine.pairingCode,
|
||||
pairingExpiresAt: data.machine.pairingCodeExpiresAt,
|
||||
});
|
||||
setCreateName("");
|
||||
setCreateCode("");
|
||||
setCreateLocation("");
|
||||
setShowCreate(false);
|
||||
} catch (err: any) {
|
||||
setCreateError(err?.message || t("machines.create.error.failed"));
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function copyText(text: string) {
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopyStatus(t("machines.pairing.copied"));
|
||||
} else {
|
||||
setCopyStatus(t("machines.pairing.copyUnsupported"));
|
||||
}
|
||||
} catch {
|
||||
setCopyStatus(t("machines.pairing.copyFailed"));
|
||||
}
|
||||
setTimeout(() => setCopyStatus(null), 2000);
|
||||
}
|
||||
|
||||
const showCreateCard = showCreate || (!loading && machines.length === 0);
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">{t("machines.title")}</h1>
|
||||
<p className="text-sm text-zinc-400">{t("machines.subtitle")}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCreate((prev) => !prev)}
|
||||
className="rounded-xl border border-emerald-400/40 bg-emerald-500/20 px-4 py-2 text-sm text-emerald-100 hover:bg-emerald-500/30"
|
||||
>
|
||||
{showCreate ? t("machines.cancel") : t("machines.addMachine")}
|
||||
</button>
|
||||
<Link
|
||||
href="/overview"
|
||||
className="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-white hover:bg-white/10"
|
||||
>
|
||||
{t("machines.backOverview")}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showCreateCard && (
|
||||
<div className="mb-6 rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="text-sm font-semibold text-white">{t("machines.addCardTitle")}</div>
|
||||
<div className="text-xs text-zinc-400">{t("machines.addCardSubtitle")}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("machines.field.name")}
|
||||
<input
|
||||
value={createName}
|
||||
onChange={(event) => setCreateName(event.target.value)}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("machines.field.code")}
|
||||
<input
|
||||
value={createCode}
|
||||
onChange={(event) => setCreateCode(event.target.value)}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
<label className="rounded-xl border border-white/10 bg-black/20 p-3 text-xs text-zinc-400">
|
||||
{t("machines.field.location")}
|
||||
<input
|
||||
value={createLocation}
|
||||
onChange={(event) => setCreateLocation(event.target.value)}
|
||||
className="mt-2 w-full rounded-lg border border-white/10 bg-black/30 px-3 py-2 text-sm text-white"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={createMachine}
|
||||
disabled={creating}
|
||||
className="rounded-xl border border-emerald-400/40 bg-emerald-500/20 px-4 py-2 text-sm text-emerald-100 hover:bg-emerald-500/30 disabled:opacity-60"
|
||||
>
|
||||
{creating ? t("machines.create.loading") : t("machines.create.default")}
|
||||
</button>
|
||||
{createError && <div className="text-xs text-red-200">{createError}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{createdMachine && (
|
||||
<div className="mb-6 rounded-2xl border border-emerald-500/20 bg-emerald-500/10 p-5">
|
||||
<div className="text-sm font-semibold text-white">{t("machines.pairing.title")}</div>
|
||||
<div className="mt-2 text-xs text-zinc-300">
|
||||
{t("machines.pairing.machine")} <span className="text-white">{createdMachine.name}</span>
|
||||
</div>
|
||||
<div className="mt-3 rounded-xl border border-white/10 bg-black/30 p-4">
|
||||
<div className="text-xs uppercase tracking-wide text-zinc-400">{t("machines.pairing.codeLabel")}</div>
|
||||
<div className="mt-2 text-3xl font-semibold text-white">{createdMachine.pairingCode}</div>
|
||||
<div className="mt-2 text-xs text-zinc-400">
|
||||
{t("machines.pairing.expires")}{" "}
|
||||
{createdMachine.pairingExpiresAt
|
||||
? new Date(createdMachine.pairingExpiresAt).toLocaleString(locale)
|
||||
: t("machines.pairing.soon")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 text-xs text-zinc-300">
|
||||
{t("machines.pairing.instructions")}
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copyText(createdMachine.pairingCode)}
|
||||
className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm text-white hover:bg-white/10"
|
||||
>
|
||||
{t("machines.pairing.copy")}
|
||||
</button>
|
||||
{copyStatus && <div className="text-xs text-zinc-300">{copyStatus}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && <div className="mb-4 text-sm text-zinc-400">{t("machines.loading")}</div>}
|
||||
|
||||
{!loading && machines.length === 0 && (
|
||||
<div className="mb-4 text-sm text-zinc-400">{t("machines.empty")}</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
{(!loading ? machines : []).map((m) => {
|
||||
const hb = m.latestHeartbeat;
|
||||
const hbTs = hb?.tsServer ?? hb?.ts;
|
||||
const offline = isOffline(hbTs);
|
||||
const normalizedStatus = normalizeStatus(hb?.status);
|
||||
const statusLabel = offline ? t("machines.status.offline") : (normalizedStatus || t("machines.status.unknown"));
|
||||
const lastSeen = secondsAgo(hbTs, locale, t("common.never"));
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={m.id}
|
||||
href={`/machines/${m.id}`}
|
||||
className="rounded-2xl border border-white/10 bg-white/5 p-5 hover:bg-white/10"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-lg font-semibold text-white">{m.name}</div>
|
||||
<div className="mt-1 text-xs text-zinc-400">
|
||||
{m.code ? m.code : t("common.na")} - {t("machines.lastSeen", { time: lastSeen })}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<span
|
||||
className={`shrink-0 rounded-full px-3 py-1 text-xs ${badgeClass(
|
||||
normalizedStatus,
|
||||
offline
|
||||
)}`}
|
||||
>
|
||||
{statusLabel}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 text-sm text-zinc-400">{t("machines.status")}</div>
|
||||
<div className="mt-1 flex items-center gap-2 text-sm font-semibold text-white">
|
||||
{offline ? (
|
||||
<>
|
||||
<span className="inline-flex h-2.5 w-2.5 rounded-full bg-zinc-500" aria-hidden="true" />
|
||||
<span>{t("machines.status.noHeartbeat")}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="relative flex h-2.5 w-2.5" aria-hidden="true">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
|
||||
<span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-emerald-400" />
|
||||
</span>
|
||||
<span>{t("machines.status.ok")}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return <MachinesClient initialMachines={initialMachines} />;
|
||||
}
|
||||
|
||||
465
app/(app)/overview/OverviewClient.tsx
Normal file
465
app/(app)/overview/OverviewClient.tsx
Normal file
@@ -0,0 +1,465 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "@/lib/i18n/useI18n";
|
||||
|
||||
type Heartbeat = {
|
||||
ts: string;
|
||||
tsServer?: string | null;
|
||||
status: string;
|
||||
message?: string | null;
|
||||
ip?: string | null;
|
||||
fwVersion?: string | null;
|
||||
};
|
||||
|
||||
type Kpi = {
|
||||
ts: string;
|
||||
oee?: number | null;
|
||||
availability?: number | null;
|
||||
performance?: number | null;
|
||||
quality?: number | null;
|
||||
workOrderId?: string | null;
|
||||
sku?: string | null;
|
||||
good?: number | null;
|
||||
scrap?: number | null;
|
||||
target?: number | null;
|
||||
cycleTime?: number | null;
|
||||
};
|
||||
|
||||
type MachineRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
code?: string | null;
|
||||
location?: string | null;
|
||||
latestHeartbeat: Heartbeat | null;
|
||||
latestKpi?: Kpi | null;
|
||||
};
|
||||
|
||||
type EventRow = {
|
||||
id: string;
|
||||
ts: string;
|
||||
topic?: string;
|
||||
eventType: string;
|
||||
severity: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
requiresAck: boolean;
|
||||
machineId?: string;
|
||||
machineName?: string;
|
||||
source: "ingested";
|
||||
};
|
||||
|
||||
const OFFLINE_MS = 30000;
|
||||
const MAX_EVENT_MACHINES = 6;
|
||||
|
||||
function secondsAgo(ts: string | undefined, locale: string, fallback: string) {
|
||||
if (!ts) return fallback;
|
||||
const diff = Math.floor((Date.now() - new Date(ts).getTime()) / 1000);
|
||||
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
|
||||
if (diff < 60) return rtf.format(-diff, "second");
|
||||
if (diff < 3600) return rtf.format(-Math.floor(diff / 60), "minute");
|
||||
return rtf.format(-Math.floor(diff / 3600), "hour");
|
||||
}
|
||||
|
||||
function isOffline(ts?: string) {
|
||||
if (!ts) return true;
|
||||
return Date.now() - new Date(ts).getTime() > OFFLINE_MS;
|
||||
}
|
||||
|
||||
function normalizeStatus(status?: string) {
|
||||
const s = (status ?? "").toUpperCase();
|
||||
if (s === "ONLINE") return "RUN";
|
||||
return s;
|
||||
}
|
||||
|
||||
function heartbeatTime(hb?: Heartbeat | null) {
|
||||
return hb?.tsServer ?? hb?.ts;
|
||||
}
|
||||
|
||||
function fmtPct(v?: number | null) {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return "--";
|
||||
return `${v.toFixed(1)}%`;
|
||||
}
|
||||
|
||||
function fmtNum(v?: number | null) {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return "--";
|
||||
return `${Math.round(v)}`;
|
||||
}
|
||||
|
||||
function severityClass(sev?: string) {
|
||||
const s = (sev ?? "").toLowerCase();
|
||||
if (s === "critical") return "bg-red-500/15 text-red-300";
|
||||
if (s === "warning") return "bg-yellow-500/15 text-yellow-300";
|
||||
if (s === "info") return "bg-blue-500/15 text-blue-300";
|
||||
return "bg-white/10 text-zinc-200";
|
||||
}
|
||||
|
||||
function sourceClass(src: EventRow["source"]) {
|
||||
if (src === "ingested") return "bg-white/10 text-zinc-200";
|
||||
return "bg-white/10 text-zinc-200";
|
||||
}
|
||||
|
||||
export default function OverviewClient({
|
||||
initialMachines = [],
|
||||
initialEvents = [],
|
||||
}: {
|
||||
initialMachines?: MachineRow[];
|
||||
initialEvents?: EventRow[];
|
||||
}) {
|
||||
const { t, locale } = useI18n();
|
||||
const [machines, setMachines] = useState<MachineRow[]>(() => initialMachines);
|
||||
const [events, setEvents] = useState<EventRow[]>(() => initialEvents);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [eventsLoading, setEventsLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
setEventsLoading(true);
|
||||
const res = await fetch(`/api/overview?events=critical&eventMachines=${MAX_EVENT_MACHINES}`, {
|
||||
cache: "no-cache",
|
||||
});
|
||||
if (res.status === 304) {
|
||||
if (alive) setLoading(false);
|
||||
return;
|
||||
}
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (!alive) return;
|
||||
setMachines(json.machines ?? []);
|
||||
setEvents(json.events ?? []);
|
||||
setLoading(false);
|
||||
} catch {
|
||||
if (!alive) return;
|
||||
setMachines([]);
|
||||
setEvents([]);
|
||||
setLoading(false);
|
||||
} finally {
|
||||
if (alive) setEventsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
const t = setInterval(load, 30000);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const stats = useMemo(() => {
|
||||
const total = machines.length;
|
||||
let online = 0;
|
||||
let running = 0;
|
||||
let idle = 0;
|
||||
let stopped = 0;
|
||||
let oeeSum = 0;
|
||||
let oeeCount = 0;
|
||||
let availSum = 0;
|
||||
let availCount = 0;
|
||||
let perfSum = 0;
|
||||
let perfCount = 0;
|
||||
let qualSum = 0;
|
||||
let qualCount = 0;
|
||||
let goodSum = 0;
|
||||
let scrapSum = 0;
|
||||
let targetSum = 0;
|
||||
|
||||
for (const m of machines) {
|
||||
const hb = m.latestHeartbeat;
|
||||
const offline = isOffline(heartbeatTime(hb));
|
||||
if (!offline) online += 1;
|
||||
|
||||
const status = normalizeStatus(hb?.status);
|
||||
if (!offline) {
|
||||
if (status === "RUN") running += 1;
|
||||
else if (status === "IDLE") idle += 1;
|
||||
else if (status === "STOP" || status === "DOWN") stopped += 1;
|
||||
}
|
||||
|
||||
const k = m.latestKpi;
|
||||
if (k?.oee != null) {
|
||||
oeeSum += Number(k.oee);
|
||||
oeeCount += 1;
|
||||
}
|
||||
if (k?.availability != null) {
|
||||
availSum += Number(k.availability);
|
||||
availCount += 1;
|
||||
}
|
||||
if (k?.performance != null) {
|
||||
perfSum += Number(k.performance);
|
||||
perfCount += 1;
|
||||
}
|
||||
if (k?.quality != null) {
|
||||
qualSum += Number(k.quality);
|
||||
qualCount += 1;
|
||||
}
|
||||
if (k?.good != null) goodSum += Number(k.good);
|
||||
if (k?.scrap != null) scrapSum += Number(k.scrap);
|
||||
if (k?.target != null) targetSum += Number(k.target);
|
||||
}
|
||||
|
||||
return {
|
||||
total,
|
||||
online,
|
||||
offline: total - online,
|
||||
running,
|
||||
idle,
|
||||
stopped,
|
||||
oee: oeeCount ? oeeSum / oeeCount : null,
|
||||
availability: availCount ? availSum / availCount : null,
|
||||
performance: perfCount ? perfSum / perfCount : null,
|
||||
quality: qualCount ? qualSum / qualCount : null,
|
||||
goodSum,
|
||||
scrapSum,
|
||||
targetSum,
|
||||
};
|
||||
}, [machines]);
|
||||
|
||||
const attention = useMemo(() => {
|
||||
const list = machines
|
||||
.map((m) => {
|
||||
const hb = m.latestHeartbeat;
|
||||
const offline = isOffline(heartbeatTime(hb));
|
||||
const k = m.latestKpi;
|
||||
const oee = k?.oee ?? null;
|
||||
let score = 0;
|
||||
if (offline) score += 100;
|
||||
if (oee != null && oee < 75) score += 50;
|
||||
if (oee != null && oee < 85) score += 25;
|
||||
return { machine: m, offline, oee, score };
|
||||
})
|
||||
.filter((x) => x.score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, 6);
|
||||
|
||||
return list;
|
||||
}, [machines]);
|
||||
|
||||
const formatEventType = (eventType?: string) => {
|
||||
if (!eventType) return "";
|
||||
const key = `overview.event.${eventType}`;
|
||||
const label = t(key);
|
||||
return label === key ? eventType : label;
|
||||
};
|
||||
|
||||
const formatSource = (source?: string) => {
|
||||
if (!source) return "";
|
||||
const key = `overview.source.${source}`;
|
||||
const label = t(key);
|
||||
return label === key ? source : label;
|
||||
};
|
||||
|
||||
const formatSeverity = (severity?: string) => {
|
||||
if (!severity) return "";
|
||||
const key = `overview.severity.${severity}`;
|
||||
const label = t(key);
|
||||
return label === key ? severity.toUpperCase() : label;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-6">
|
||||
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">{t("overview.title")}</h1>
|
||||
<p className="text-sm text-zinc-400">{t("overview.subtitle")}</p>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href="/machines"
|
||||
className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-center text-sm text-white hover:bg-white/10 sm:w-auto"
|
||||
>
|
||||
{t("overview.viewMachines")}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{loading && <div className="mb-4 text-sm text-zinc-400">{t("overview.loading")}</div>}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.fleetHealth")}</div>
|
||||
<div className="mt-2 text-3xl font-semibold text-white">{stats.total}</div>
|
||||
<div className="mt-2 text-xs text-zinc-400">{t("overview.machinesTotal")}</div>
|
||||
<div className="mt-4 flex flex-wrap gap-2 text-xs">
|
||||
<span className="rounded-full bg-emerald-500/15 px-2 py-0.5 text-emerald-300">
|
||||
{t("overview.online")} {stats.online}
|
||||
</span>
|
||||
<span className="rounded-full bg-white/10 px-2 py-0.5 text-zinc-300">
|
||||
{t("overview.offline")} {stats.offline}
|
||||
</span>
|
||||
<span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-emerald-200">
|
||||
{t("overview.run")} {stats.running}
|
||||
</span>
|
||||
<span className="rounded-full bg-yellow-500/15 px-2 py-0.5 text-yellow-300">
|
||||
{t("overview.idle")} {stats.idle}
|
||||
</span>
|
||||
<span className="rounded-full bg-red-500/15 px-2 py-0.5 text-red-300">
|
||||
{t("overview.stop")} {stats.stopped}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.productionTotals")}</div>
|
||||
<div className="mt-2 grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<div className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="text-[11px] text-zinc-400">{t("overview.good")}</div>
|
||||
<div className="mt-1 text-sm font-semibold text-white">{fmtNum(stats.goodSum)}</div>
|
||||
</div>
|
||||
<div className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="text-[11px] text-zinc-400">{t("overview.scrap")}</div>
|
||||
<div className="mt-1 text-sm font-semibold text-white">{fmtNum(stats.scrapSum)}</div>
|
||||
</div>
|
||||
<div className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="text-[11px] text-zinc-400">{t("overview.target")}</div>
|
||||
<div className="mt-1 text-sm font-semibold text-white">{fmtNum(stats.targetSum)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 text-xs text-zinc-400">{t("overview.kpiSumNote")}</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.activityFeed")}</div>
|
||||
<div className="mt-2 text-3xl font-semibold text-white">{events.length}</div>
|
||||
<div className="mt-2 text-xs text-zinc-400">
|
||||
{eventsLoading ? t("overview.eventsRefreshing") : t("overview.eventsLast30")}
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
{events.slice(0, 3).map((e) => (
|
||||
<div key={e.id} className="flex items-center justify-between text-xs text-zinc-300">
|
||||
<div className="truncate">
|
||||
{e.machineName ? `${e.machineName}: ` : ""}
|
||||
{e.title}
|
||||
</div>
|
||||
<div className="shrink-0 text-zinc-500">
|
||||
{secondsAgo(e.ts, locale, t("common.never"))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{events.length === 0 && !eventsLoading ? (
|
||||
<div className="text-xs text-zinc-500">{t("overview.eventsNone")}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.oeeAvg")}</div>
|
||||
<div className="mt-2 text-3xl font-semibold text-emerald-300">{fmtPct(stats.oee)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.availabilityAvg")}</div>
|
||||
<div className="mt-2 text-2xl font-semibold text-white">{fmtPct(stats.availability)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.performanceAvg")}</div>
|
||||
<div className="mt-2 text-2xl font-semibold text-white">{fmtPct(stats.performance)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.qualityAvg")}</div>
|
||||
<div className="mt-2 text-2xl font-semibold text-white">{fmtPct(stats.quality)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 gap-4 xl:grid-cols-3">
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5 xl:col-span-1">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="text-sm font-semibold text-white">{t("overview.attentionList")}</div>
|
||||
<div className="text-xs text-zinc-400">
|
||||
{attention.length} {t("overview.shown")}
|
||||
</div>
|
||||
</div>
|
||||
{attention.length === 0 ? (
|
||||
<div className="text-sm text-zinc-400">{t("overview.noUrgent")}</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{attention.map(({ machine, offline, oee }) => (
|
||||
<div key={machine.id} className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-semibold text-white">{machine.name}</div>
|
||||
<div className="mt-1 text-xs text-zinc-400">
|
||||
{machine.code ?? ""} {machine.location ? `- ${machine.location}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-zinc-400">
|
||||
{secondsAgo(heartbeatTime(machine.latestHeartbeat), locale, t("common.never"))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 flex items-center gap-2 text-xs">
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 ${
|
||||
offline ? "bg-white/10 text-zinc-300" : "bg-emerald-500/15 text-emerald-300"
|
||||
}`}
|
||||
>
|
||||
{offline ? t("overview.status.offline") : t("overview.status.online")}
|
||||
</span>
|
||||
{oee != null && (
|
||||
<span className="rounded-full bg-yellow-500/15 px-2 py-0.5 text-yellow-300">
|
||||
OEE {fmtPct(oee)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5 xl:col-span-2">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="text-sm font-semibold text-white">{t("overview.timeline")}</div>
|
||||
<div className="text-xs text-zinc-400">
|
||||
{events.length} {t("overview.items")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{events.length === 0 && !eventsLoading ? (
|
||||
<div className="text-sm text-zinc-400">{t("overview.noEvents")}</div>
|
||||
) : (
|
||||
<div className="h-[360px] space-y-3 overflow-y-auto no-scrollbar">
|
||||
{events.map((e) => (
|
||||
<div key={`${e.id}-${e.source}`} className="rounded-xl border border-white/10 bg-black/20 p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs ${severityClass(e.severity)}`}>
|
||||
{formatSeverity(e.severity)}
|
||||
</span>
|
||||
<span className="rounded-full bg-white/10 px-2 py-0.5 text-xs text-zinc-200">
|
||||
{formatEventType(e.eventType)}
|
||||
</span>
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs ${sourceClass(e.source)}`}>
|
||||
{formatSource(e.source)}
|
||||
</span>
|
||||
{e.requiresAck ? (
|
||||
<span className="rounded-full bg-white/10 px-2 py-0.5 text-xs text-white">
|
||||
{t("overview.ack")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-2 truncate text-sm font-semibold text-white">
|
||||
{e.machineName ? `${e.machineName}: ` : ""}
|
||||
{e.title}
|
||||
</div>
|
||||
{e.description ? (
|
||||
<div className="mt-1 text-sm text-zinc-300">{e.description}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="shrink-0 text-xs text-zinc-400">
|
||||
{secondsAgo(e.ts, locale, t("common.never"))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,522 +1,47 @@
|
||||
"use client";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireSession } from "@/lib/auth/requireSession";
|
||||
import { getOverviewData } from "@/lib/overview/getOverviewData";
|
||||
import OverviewClient from "./OverviewClient";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "@/lib/i18n/useI18n";
|
||||
|
||||
type Heartbeat = {
|
||||
ts: string;
|
||||
tsServer?: string | null;
|
||||
status: string;
|
||||
message?: string | null;
|
||||
ip?: string | null;
|
||||
fwVersion?: string | null;
|
||||
};
|
||||
|
||||
type Kpi = {
|
||||
ts: string;
|
||||
oee?: number | null;
|
||||
availability?: number | null;
|
||||
performance?: number | null;
|
||||
quality?: number | null;
|
||||
workOrderId?: string | null;
|
||||
sku?: string | null;
|
||||
good?: number | null;
|
||||
scrap?: number | null;
|
||||
target?: number | null;
|
||||
cycleTime?: number | null;
|
||||
};
|
||||
|
||||
type MachineRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
code?: string | null;
|
||||
location?: string | null;
|
||||
latestHeartbeat: Heartbeat | null;
|
||||
latestKpi?: Kpi | null;
|
||||
};
|
||||
|
||||
type EventRow = {
|
||||
id: string;
|
||||
ts: string;
|
||||
topic?: string;
|
||||
eventType: string;
|
||||
severity: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
requiresAck: boolean;
|
||||
machineId?: string;
|
||||
machineName?: string;
|
||||
source: "ingested";
|
||||
};
|
||||
|
||||
const OFFLINE_MS = 30000;
|
||||
const MAX_EVENT_MACHINES = 6;
|
||||
|
||||
function secondsAgo(ts: string | undefined, locale: string, fallback: string) {
|
||||
if (!ts) return fallback;
|
||||
const diff = Math.floor((Date.now() - new Date(ts).getTime()) / 1000);
|
||||
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
|
||||
if (diff < 60) return rtf.format(-diff, "second");
|
||||
if (diff < 3600) return rtf.format(-Math.floor(diff / 60), "minute");
|
||||
return rtf.format(-Math.floor(diff / 3600), "hour");
|
||||
function toIso(value?: Date | null) {
|
||||
return value ? value.toISOString() : null;
|
||||
}
|
||||
|
||||
function isOffline(ts?: string) {
|
||||
if (!ts) return true;
|
||||
return Date.now() - new Date(ts).getTime() > OFFLINE_MS;
|
||||
}
|
||||
export default async function OverviewPage() {
|
||||
const session = await requireSession();
|
||||
if (!session) redirect("/login?next=/overview");
|
||||
|
||||
function normalizeStatus(status?: string) {
|
||||
const s = (status ?? "").toUpperCase();
|
||||
if (s === "ONLINE") return "RUN";
|
||||
return s;
|
||||
}
|
||||
|
||||
function heartbeatTime(hb?: Heartbeat | null) {
|
||||
return hb?.tsServer ?? hb?.ts;
|
||||
}
|
||||
|
||||
function fmtPct(v?: number | null) {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return "--";
|
||||
return `${v.toFixed(1)}%`;
|
||||
}
|
||||
|
||||
function fmtNum(v?: number | null) {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return "--";
|
||||
return `${Math.round(v)}`;
|
||||
}
|
||||
|
||||
function severityClass(sev?: string) {
|
||||
const s = (sev ?? "").toLowerCase();
|
||||
if (s === "critical") return "bg-red-500/15 text-red-300";
|
||||
if (s === "warning") return "bg-yellow-500/15 text-yellow-300";
|
||||
if (s === "info") return "bg-blue-500/15 text-blue-300";
|
||||
return "bg-white/10 text-zinc-200";
|
||||
}
|
||||
|
||||
function sourceClass(_src: EventRow["source"]) {
|
||||
return "bg-white/10 text-zinc-200";
|
||||
}
|
||||
|
||||
export default function OverviewPage() {
|
||||
const { t, locale } = useI18n();
|
||||
const [machines, setMachines] = useState<MachineRow[]>([]);
|
||||
const [events, setEvents] = useState<EventRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [eventsLoading, setEventsLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const res = await fetch("/api/machines", { cache: "no-store" });
|
||||
const json = await res.json();
|
||||
if (!alive) return;
|
||||
setMachines(json.machines ?? []);
|
||||
setLoading(false);
|
||||
} catch {
|
||||
if (!alive) return;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
load();
|
||||
const t = setInterval(load, 30000);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(t);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!machines.length) {
|
||||
setEvents([]);
|
||||
return;
|
||||
}
|
||||
|
||||
let alive = true;
|
||||
const controller = new AbortController();
|
||||
|
||||
async function loadEvents() {
|
||||
setEventsLoading(true);
|
||||
|
||||
const sorted = [...machines].sort((a, b) => {
|
||||
const at = heartbeatTime(a.latestHeartbeat);
|
||||
const bt = heartbeatTime(b.latestHeartbeat);
|
||||
const atMs = at ? new Date(at).getTime() : 0;
|
||||
const btMs = bt ? new Date(bt).getTime() : 0;
|
||||
return btMs - atMs;
|
||||
});
|
||||
|
||||
const targets = sorted.slice(0, MAX_EVENT_MACHINES);
|
||||
|
||||
try {
|
||||
const results = await Promise.all(
|
||||
targets.map(async (m) => {
|
||||
const res = await fetch(`/api/machines/${m.id}?events=critical&eventsOnly=1`, {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
const json = await res.json();
|
||||
return { machine: m, payload: json };
|
||||
})
|
||||
);
|
||||
|
||||
if (!alive) return;
|
||||
|
||||
const combined: EventRow[] = [];
|
||||
for (const { machine, payload } of results) {
|
||||
const ingested = Array.isArray(payload?.events) ? payload.events : [];
|
||||
for (const e of ingested) {
|
||||
if (!e?.ts) continue;
|
||||
combined.push({
|
||||
...e,
|
||||
machineId: machine.id,
|
||||
machineName: machine.name,
|
||||
source: "ingested",
|
||||
});
|
||||
}
|
||||
const { machines, events } = await getOverviewData({
|
||||
orgId: session.orgId,
|
||||
eventsMode: "critical",
|
||||
eventsWindowSec: 21600,
|
||||
eventMachines: 6,
|
||||
});
|
||||
|
||||
const initialMachines = machines.map((machine) => ({
|
||||
...machine,
|
||||
createdAt: toIso(machine.createdAt),
|
||||
updatedAt: toIso(machine.updatedAt),
|
||||
latestHeartbeat: machine.latestHeartbeat
|
||||
? {
|
||||
...machine.latestHeartbeat,
|
||||
ts: toIso(machine.latestHeartbeat.ts) ?? "",
|
||||
tsServer: toIso(machine.latestHeartbeat.tsServer),
|
||||
}
|
||||
: null,
|
||||
latestKpi: machine.latestKpi
|
||||
? {
|
||||
...machine.latestKpi,
|
||||
ts: toIso(machine.latestKpi.ts) ?? "",
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
|
||||
const seen = new Set<string>();
|
||||
const deduped = combined.filter((e) => {
|
||||
const key = `${e.machineId ?? ""}-${e.eventType}-${e.ts}-${e.title}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
const initialEvents = events.map((event) => ({
|
||||
...event,
|
||||
ts: event.ts ? event.ts.toISOString() : "",
|
||||
machineName: event.machineName ?? undefined,
|
||||
}));
|
||||
|
||||
deduped.sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime());
|
||||
setEvents(deduped.slice(0, 30));
|
||||
} catch {
|
||||
if (!alive) return;
|
||||
setEvents([]);
|
||||
} finally {
|
||||
if (alive) setEventsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
loadEvents();
|
||||
return () => {
|
||||
alive = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [machines]);
|
||||
|
||||
const stats = useMemo(() => {
|
||||
const total = machines.length;
|
||||
let online = 0;
|
||||
let running = 0;
|
||||
let idle = 0;
|
||||
let stopped = 0;
|
||||
let oeeSum = 0;
|
||||
let oeeCount = 0;
|
||||
let availSum = 0;
|
||||
let availCount = 0;
|
||||
let perfSum = 0;
|
||||
let perfCount = 0;
|
||||
let qualSum = 0;
|
||||
let qualCount = 0;
|
||||
let goodSum = 0;
|
||||
let scrapSum = 0;
|
||||
let targetSum = 0;
|
||||
|
||||
for (const m of machines) {
|
||||
const hb = m.latestHeartbeat;
|
||||
const offline = isOffline(heartbeatTime(hb));
|
||||
if (!offline) online += 1;
|
||||
|
||||
const status = normalizeStatus(hb?.status);
|
||||
if (!offline) {
|
||||
if (status === "RUN") running += 1;
|
||||
else if (status === "IDLE") idle += 1;
|
||||
else if (status === "STOP" || status === "DOWN") stopped += 1;
|
||||
}
|
||||
|
||||
const k = m.latestKpi;
|
||||
if (k?.oee != null) {
|
||||
oeeSum += Number(k.oee);
|
||||
oeeCount += 1;
|
||||
}
|
||||
if (k?.availability != null) {
|
||||
availSum += Number(k.availability);
|
||||
availCount += 1;
|
||||
}
|
||||
if (k?.performance != null) {
|
||||
perfSum += Number(k.performance);
|
||||
perfCount += 1;
|
||||
}
|
||||
if (k?.quality != null) {
|
||||
qualSum += Number(k.quality);
|
||||
qualCount += 1;
|
||||
}
|
||||
if (k?.good != null) goodSum += Number(k.good);
|
||||
if (k?.scrap != null) scrapSum += Number(k.scrap);
|
||||
if (k?.target != null) targetSum += Number(k.target);
|
||||
}
|
||||
|
||||
return {
|
||||
total,
|
||||
online,
|
||||
offline: total - online,
|
||||
running,
|
||||
idle,
|
||||
stopped,
|
||||
oee: oeeCount ? oeeSum / oeeCount : null,
|
||||
availability: availCount ? availSum / availCount : null,
|
||||
performance: perfCount ? perfSum / perfCount : null,
|
||||
quality: qualCount ? qualSum / qualCount : null,
|
||||
goodSum,
|
||||
scrapSum,
|
||||
targetSum,
|
||||
};
|
||||
}, [machines]);
|
||||
|
||||
const attention = useMemo(() => {
|
||||
const list = machines
|
||||
.map((m) => {
|
||||
const hb = m.latestHeartbeat;
|
||||
const offline = isOffline(heartbeatTime(hb));
|
||||
const k = m.latestKpi;
|
||||
const oee = k?.oee ?? null;
|
||||
let score = 0;
|
||||
if (offline) score += 100;
|
||||
if (oee != null && oee < 75) score += 50;
|
||||
if (oee != null && oee < 85) score += 25;
|
||||
return { machine: m, offline, oee, score };
|
||||
})
|
||||
.filter((x) => x.score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, 6);
|
||||
|
||||
return list;
|
||||
}, [machines]);
|
||||
|
||||
const formatEventType = (eventType?: string) => {
|
||||
if (!eventType) return "";
|
||||
const key = `overview.event.${eventType}`;
|
||||
const label = t(key);
|
||||
return label === key ? eventType : label;
|
||||
};
|
||||
|
||||
const formatSource = (source?: string) => {
|
||||
if (!source) return "";
|
||||
const key = `overview.source.${source}`;
|
||||
const label = t(key);
|
||||
return label === key ? source : label;
|
||||
};
|
||||
|
||||
const formatSeverity = (severity?: string) => {
|
||||
if (!severity) return "";
|
||||
const key = `overview.severity.${severity}`;
|
||||
const label = t(key);
|
||||
return label === key ? severity.toUpperCase() : label;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="mb-6 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">{t("overview.title")}</h1>
|
||||
<p className="text-sm text-zinc-400">{t("overview.subtitle")}</p>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href="/machines"
|
||||
className="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-white hover:bg-white/10"
|
||||
>
|
||||
{t("overview.viewMachines")}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{loading && <div className="mb-4 text-sm text-zinc-400">{t("overview.loading")}</div>}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.fleetHealth")}</div>
|
||||
<div className="mt-2 text-3xl font-semibold text-white">{stats.total}</div>
|
||||
<div className="mt-2 text-xs text-zinc-400">{t("overview.machinesTotal")}</div>
|
||||
<div className="mt-4 flex flex-wrap gap-2 text-xs">
|
||||
<span className="rounded-full bg-emerald-500/15 px-2 py-0.5 text-emerald-300">
|
||||
{t("overview.online")} {stats.online}
|
||||
</span>
|
||||
<span className="rounded-full bg-white/10 px-2 py-0.5 text-zinc-300">
|
||||
{t("overview.offline")} {stats.offline}
|
||||
</span>
|
||||
<span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-emerald-200">
|
||||
{t("overview.run")} {stats.running}
|
||||
</span>
|
||||
<span className="rounded-full bg-yellow-500/15 px-2 py-0.5 text-yellow-300">
|
||||
{t("overview.idle")} {stats.idle}
|
||||
</span>
|
||||
<span className="rounded-full bg-red-500/15 px-2 py-0.5 text-red-300">
|
||||
{t("overview.stop")} {stats.stopped}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.productionTotals")}</div>
|
||||
<div className="mt-2 grid grid-cols-3 gap-3">
|
||||
<div className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="text-[11px] text-zinc-400">{t("overview.good")}</div>
|
||||
<div className="mt-1 text-sm font-semibold text-white">{fmtNum(stats.goodSum)}</div>
|
||||
</div>
|
||||
<div className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="text-[11px] text-zinc-400">{t("overview.scrap")}</div>
|
||||
<div className="mt-1 text-sm font-semibold text-white">{fmtNum(stats.scrapSum)}</div>
|
||||
</div>
|
||||
<div className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="text-[11px] text-zinc-400">{t("overview.target")}</div>
|
||||
<div className="mt-1 text-sm font-semibold text-white">{fmtNum(stats.targetSum)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 text-xs text-zinc-400">{t("overview.kpiSumNote")}</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.activityFeed")}</div>
|
||||
<div className="mt-2 text-3xl font-semibold text-white">{events.length}</div>
|
||||
<div className="mt-2 text-xs text-zinc-400">
|
||||
{eventsLoading ? t("overview.eventsRefreshing") : t("overview.eventsLast30")}
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
{events.slice(0, 3).map((e) => (
|
||||
<div key={e.id} className="flex items-center justify-between text-xs text-zinc-300">
|
||||
<div className="truncate">
|
||||
{e.machineName ? `${e.machineName}: ` : ""}
|
||||
{e.title}
|
||||
</div>
|
||||
<div className="shrink-0 text-zinc-500">
|
||||
{secondsAgo(e.ts, locale, t("common.never"))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{events.length === 0 && !eventsLoading ? (
|
||||
<div className="text-xs text-zinc-500">{t("overview.eventsNone")}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.oeeAvg")}</div>
|
||||
<div className="mt-2 text-3xl font-semibold text-emerald-300">{fmtPct(stats.oee)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.availabilityAvg")}</div>
|
||||
<div className="mt-2 text-2xl font-semibold text-white">{fmtPct(stats.availability)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.performanceAvg")}</div>
|
||||
<div className="mt-2 text-2xl font-semibold text-white">{fmtPct(stats.performance)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5">
|
||||
<div className="text-xs text-zinc-400">{t("overview.qualityAvg")}</div>
|
||||
<div className="mt-2 text-2xl font-semibold text-white">{fmtPct(stats.quality)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 grid grid-cols-1 gap-4 xl:grid-cols-3">
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5 xl:col-span-1">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="text-sm font-semibold text-white">{t("overview.attentionList")}</div>
|
||||
<div className="text-xs text-zinc-400">
|
||||
{attention.length} {t("overview.shown")}
|
||||
</div>
|
||||
</div>
|
||||
{attention.length === 0 ? (
|
||||
<div className="text-sm text-zinc-400">{t("overview.noUrgent")}</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{attention.map(({ machine, offline, oee }) => (
|
||||
<div key={machine.id} className="rounded-xl border border-white/10 bg-black/20 p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-semibold text-white">{machine.name}</div>
|
||||
<div className="mt-1 text-xs text-zinc-400">
|
||||
{machine.code ?? ""} {machine.location ? `- ${machine.location}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-zinc-400">
|
||||
{secondsAgo(heartbeatTime(machine.latestHeartbeat), locale, t("common.never"))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 flex items-center gap-2 text-xs">
|
||||
<span
|
||||
className={`rounded-full px-2 py-0.5 ${
|
||||
offline ? "bg-white/10 text-zinc-300" : "bg-emerald-500/15 text-emerald-300"
|
||||
}`}
|
||||
>
|
||||
{offline ? t("overview.status.offline") : t("overview.status.online")}
|
||||
</span>
|
||||
{oee != null && (
|
||||
<span className="rounded-full bg-yellow-500/15 px-2 py-0.5 text-yellow-300">
|
||||
OEE {fmtPct(oee)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-white/10 bg-white/5 p-5 xl:col-span-2">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div className="text-sm font-semibold text-white">{t("overview.timeline")}</div>
|
||||
<div className="text-xs text-zinc-400">
|
||||
{events.length} {t("overview.items")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{events.length === 0 && !eventsLoading ? (
|
||||
<div className="text-sm text-zinc-400">{t("overview.noEvents")}</div>
|
||||
) : (
|
||||
<div className="h-[360px] space-y-3 overflow-y-auto no-scrollbar">
|
||||
{events.map((e) => (
|
||||
<div key={`${e.id}-${e.source}`} className="rounded-xl border border-white/10 bg-black/20 p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs ${severityClass(e.severity)}`}>
|
||||
{formatSeverity(e.severity)}
|
||||
</span>
|
||||
<span className="rounded-full bg-white/10 px-2 py-0.5 text-xs text-zinc-200">
|
||||
{formatEventType(e.eventType)}
|
||||
</span>
|
||||
<span className={`rounded-full px-2 py-0.5 text-xs ${sourceClass(e.source)}`}>
|
||||
{formatSource(e.source)}
|
||||
</span>
|
||||
{e.requiresAck ? (
|
||||
<span className="rounded-full bg-white/10 px-2 py-0.5 text-xs text-white">
|
||||
{t("overview.ack")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-2 truncate text-sm font-semibold text-white">
|
||||
{e.machineName ? `${e.machineName}: ` : ""}
|
||||
{e.title}
|
||||
</div>
|
||||
{e.description ? (
|
||||
<div className="mt-1 text-sm text-zinc-300">{e.description}</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="shrink-0 text-xs text-zinc-400">
|
||||
{secondsAgo(e.ts, locale, t("common.never"))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return <OverviewClient initialMachines={initialMachines} initialEvents={initialEvents} />;
|
||||
}
|
||||
|
||||
21
app/(app)/reports/loading.tsx
Normal file
21
app/(app)/reports/loading.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
export default function ReportsLoading() {
|
||||
return (
|
||||
<div className="p-4 sm:p-6 space-y-6">
|
||||
<div className="h-8 w-56 rounded-lg bg-white/5" />
|
||||
<div className="grid gap-4 lg:grid-cols-4">
|
||||
{Array.from({ length: 4 }).map((_, idx) => (
|
||||
<div key={idx} className="h-24 rounded-2xl border border-white/10 bg-white/5" />
|
||||
))}
|
||||
</div>
|
||||
<div className="grid gap-4 lg:grid-cols-[2fr_1fr]">
|
||||
<div className="h-80 rounded-2xl border border-white/10 bg-white/5" />
|
||||
<div className="h-80 rounded-2xl border border-white/10 bg-white/5" />
|
||||
</div>
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
{Array.from({ length: 3 }).map((_, idx) => (
|
||||
<div key={idx} className="h-24 rounded-2xl border border-white/10 bg-white/5" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -68,17 +68,19 @@ type ReportPayload = {
|
||||
type MachineOption = { id: string; name: string };
|
||||
type FilterOptions = { workOrders: string[]; skus: string[] };
|
||||
type Translator = (key: string, vars?: Record<string, string | number>) => string;
|
||||
type TooltipPayload<T> = { payload?: T; name?: string; value?: number | string };
|
||||
type SimpleTooltipProps<T> = {
|
||||
active?: boolean;
|
||||
payload?: Array<TooltipPayload<T>>;
|
||||
label?: string | number;
|
||||
};
|
||||
type CycleHistogramRow = ReportPayload["distribution"]["cycleTime"][number];
|
||||
|
||||
function fmtPct(v?: number | null) {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return "--";
|
||||
return `${v.toFixed(1)}%`;
|
||||
}
|
||||
|
||||
function fmtNum(v?: number | null) {
|
||||
if (v === null || v === undefined || Number.isNaN(v)) return "--";
|
||||
return `${Math.round(v)}`;
|
||||
}
|
||||
|
||||
function fmtDuration(sec?: number | null) {
|
||||
if (!sec) return "--";
|
||||
const h = Math.floor(sec / 3600);
|
||||
@@ -104,7 +106,7 @@ function formatTickLabel(ts: string, range: RangeKey) {
|
||||
return `${month}-${day}`;
|
||||
}
|
||||
|
||||
function CycleTooltip({ active, payload, t }: any) {
|
||||
function CycleTooltip({ active, payload, t }: SimpleTooltipProps<CycleHistogramRow> & { t: Translator }) {
|
||||
if (!active || !payload?.length) return null;
|
||||
const p = payload[0]?.payload;
|
||||
if (!p) return null;
|
||||
@@ -141,7 +143,7 @@ function CycleTooltip({ active, payload, t }: any) {
|
||||
);
|
||||
}
|
||||
|
||||
function DowntimeTooltip({ active, payload, t }: any) {
|
||||
function DowntimeTooltip({ active, payload, t }: SimpleTooltipProps<{ name?: string; value?: number }> & { t: Translator }) {
|
||||
if (!active || !payload?.length) return null;
|
||||
const row = payload[0]?.payload ?? {};
|
||||
const label = row.name ?? payload[0]?.name ?? "";
|
||||
@@ -157,6 +159,15 @@ function DowntimeTooltip({ active, payload, t }: any) {
|
||||
);
|
||||
}
|
||||
|
||||
function toMachineOption(value: unknown): MachineOption | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const id = typeof record.id === "string" ? record.id : "";
|
||||
const name = typeof record.name === "string" ? record.name : "";
|
||||
if (!id || !name) return null;
|
||||
return { id, name };
|
||||
}
|
||||
|
||||
function buildCsv(report: ReportPayload, t: Translator) {
|
||||
const rows = new Map<string, Record<string, string | number>>();
|
||||
const addSeries = (series: ReportTrendPoint[], key: string) => {
|
||||
@@ -386,13 +397,29 @@ export default function ReportsPage() {
|
||||
const res = await fetch("/api/machines", { cache: "no-store" });
|
||||
const json = await res.json();
|
||||
if (!alive) return;
|
||||
setMachines((json?.machines ?? []).map((m: any) => ({ id: m.id, name: m.name })));
|
||||
const rows: unknown[] = Array.isArray(json?.machines) ? json.machines : [];
|
||||
const options: MachineOption[] = [];
|
||||
rows.forEach((row) => {
|
||||
const option = toMachineOption(row);
|
||||
if (option) options.push(option);
|
||||
});
|
||||
setMachines(options);
|
||||
} catch {
|
||||
if (!alive) return;
|
||||
setMachines([]);
|
||||
}
|
||||
}
|
||||
|
||||
loadMachines();
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
@@ -402,7 +429,10 @@ export default function ReportsPage() {
|
||||
if (workOrderId) params.set("workOrderId", workOrderId);
|
||||
if (sku) params.set("sku", sku);
|
||||
|
||||
const res = await fetch(`/api/reports?${params.toString()}`, { cache: "no-store" });
|
||||
const res = await fetch(`/api/reports?${params.toString()}`, {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!alive) return;
|
||||
if (!res.ok || json?.ok === false) {
|
||||
@@ -420,21 +450,25 @@ export default function ReportsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
loadMachines();
|
||||
load();
|
||||
return () => {
|
||||
alive = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [range, machineId, workOrderId, sku]);
|
||||
}, [range, machineId, workOrderId, sku, t]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
const controller = new AbortController();
|
||||
|
||||
async function loadFilters() {
|
||||
try {
|
||||
const params = new URLSearchParams({ range });
|
||||
if (machineId) params.set("machineId", machineId);
|
||||
const res = await fetch(`/api/reports/filters?${params.toString()}`, { cache: "no-store" });
|
||||
const res = await fetch(`/api/reports/filters?${params.toString()}`, {
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!alive) return;
|
||||
if (!res.ok || json?.ok === false) {
|
||||
@@ -454,6 +488,7 @@ export default function ReportsPage() {
|
||||
loadFilters();
|
||||
return () => {
|
||||
alive = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [range, machineId]);
|
||||
|
||||
@@ -536,23 +571,23 @@ export default function ReportsPage() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="mb-6 flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="p-4 sm:p-6">
|
||||
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-white">{t("reports.title")}</h1>
|
||||
<p className="text-sm text-zinc-400">{t("reports.subtitle")}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex w-full flex-wrap items-center gap-2 sm:w-auto">
|
||||
<button
|
||||
onClick={handleExportCsv}
|
||||
className="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-white hover:bg-white/10"
|
||||
className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-white hover:bg-white/10 sm:w-auto"
|
||||
>
|
||||
{t("reports.exportCsv")}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleExportPdf}
|
||||
className="rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-white hover:bg-white/10"
|
||||
className="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-white hover:bg-white/10 sm:w-auto"
|
||||
>
|
||||
{t("reports.exportPdf")}
|
||||
</button>
|
||||
@@ -681,7 +716,10 @@ export default function ReportsPage() {
|
||||
const row = payload?.[0]?.payload;
|
||||
return row?.ts ? new Date(row.ts).toLocaleString(locale) : "";
|
||||
}}
|
||||
formatter={(val: any) => [`${Number(val).toFixed(1)}%`, "OEE"]}
|
||||
formatter={(val: number | string | undefined) => [
|
||||
val == null ? "--" : `${Number(val).toFixed(1)}%`,
|
||||
"OEE",
|
||||
]}
|
||||
/>
|
||||
<Line type="monotone" dataKey="value" stroke="#34d399" dot={false} strokeWidth={2} />
|
||||
</LineChart>
|
||||
@@ -761,7 +799,10 @@ export default function ReportsPage() {
|
||||
const row = payload?.[0]?.payload;
|
||||
return row?.ts ? new Date(row.ts).toLocaleString(locale) : "";
|
||||
}}
|
||||
formatter={(val: any) => [`${Number(val).toFixed(1)}%`, t("reports.scrapRate")]}
|
||||
formatter={(val: number | string | undefined) => [
|
||||
val == null ? "--" : `${Number(val).toFixed(1)}%`,
|
||||
t("reports.scrapRate"),
|
||||
]}
|
||||
/>
|
||||
<Line type="monotone" dataKey="value" stroke="#f97316" dot={false} strokeWidth={2} />
|
||||
</LineChart>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user