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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user