SPB Git

Repository Public

WindowDetail.tsx 11.3 KB 179 lines tsx

1"use client";2import Link from "next/link";3import { useQueryClient } from "@tanstack/react-query";4import { useRouter, useSearchParams } from "next/navigation";5import { Suspense, useMemo, useState } from "react";6import { apiDelete, apiPost } from "@/api/client";7import { invalidatePaths, useApiQuery } from "@/api/query";8import { NodeLink, useNodeOptions } from "@/features/shared/nodes";9import { useI18n } from "@/i18n";10import { Page, RequirePermission } from "@/shell/AppShell";11import { useSession } from "@/shell/session";12import { Banner, Button, ConfirmDialog, DataStamp, Dialog, EmptyState, ErrorState, Icon, KeyValue, LinkButton, Linkified, QueryBoundary, Segmented, Skeleton, TextAreaField, useErrorMessage, useToast } from "@/ui";13import { isValidZone, zoneLabel } from "./calendar";14import { NotesPanel } from "./NotesPanel";15import { CategoryBadge, StatusDot, occurrenceStatus } from "./parts";16import { WindowDialog, browserZone } from "./WindowDialog";17import type { Window } from "./windowForm";1819export function WindowDetail({ id }: { id: string }) {20  return (21    <RequirePermission permission="maintenance.read">22      <Suspense fallback={null}>23        <Inner id={id} />24      </Suspense>25    </RequirePermission>26  );27}2829function Inner({ id }: { id: string }) {30  const { t } = useI18n();31  const q = useApiQuery("/maintenance/windows/{id}", { path: { id } }, { refetchInterval: 60_000 });32  return (33    <div data-testid="screen-maintenance-window">34      <Page title={q.data?.title ?? t("maintenance.detail.title")} sub={<Link href="/maintenance" className="row"><Icon name="chevron-left" size={13} />{t("maintenance.detail.back")}</Link>}>35        <QueryBoundary query={q}>{(w) => <Body w={w} updatedAt={q.dataUpdatedAt} />}</QueryBoundary>36      </Page>37    </div>38  );39}4041function Body({ w, updatedAt }: { w: Window; updatedAt: number }) {42  const { t, fmt } = useI18n();43  const router = useRouter();44  const params = useSearchParams();45  const session = useSession();46  const qc = useQueryClient();47  const toast = useToast();48  const explain = useErrorMessage();49  const nodes = useNodeOptions();50  const canWrite = session.can("maintenance.write");51  const open = w.status === "scheduled" || w.status === "in_progress";52  const zone = isValidZone(w.timezone) ? w.timezone : "UTC";53  const viewer = browserZone();54  const rawOcc = params.get("occurrence");55  const occurrence = rawOcc && Number.isFinite(Date.parse(rawOcc)) ? new Date(rawOcc).toISOString() : null;56  const [noteScope, setNoteScope] = useState<"occurrence" | "window">("occurrence");57  const [dialog, setDialog] = useState<"edit" | "complete" | "cancel" | null>(null);58  const [closing, setClosing] = useState("");59  const [busy, setBusy] = useState(false);6061  const [range] = useState(() => {62    const now = Date.now();63    return { from: new Date(now - 86400_000).toISOString(), to: new Date(now + 90 * 86400_000).toISOString() };64  });65  const upcoming = useApiQuery("/maintenance/windows", { query: range });66  const mine = useMemo(() => (upcoming.data?.items ?? []).filter((o) => o.window.id === w.id), [upcoming.data, w.id]);6768  const run = async (fn: () => Promise<unknown>, done: string, after?: () => void) => {69    setBusy(true);70    try {71      await fn();72      await invalidatePaths(qc, "/maintenance", "/silences", "/nodes");73      toast({ tone: "ok", title: done });74      setDialog(null);75      setClosing("");76      after?.();77    } catch (e) {78      toast({ tone: "critical", ...explain(e) });79    } finally {80      setBusy(false);81    }82  };83  const span = (a: string, b: string, z: string) => `${fmt.dateTime(a, { timeZone: z })} → ${fmt.dateTime(b, { timeZone: z })}`;84  const selectOccurrence = (start: string | null) => router.replace(start ? `/maintenance/${w.id}?occurrence=${encodeURIComponent(start)}` : `/maintenance/${w.id}`, { scroll: false });85  const same = (a: string, b: string) => Date.parse(a) === Date.parse(b);8687  return (88    <>89      <div className="row-between">90        <div className="row-wrap" data-testid="mt-window-status" data-status={w.status}>91          <StatusDot status={w.status} />92          <CategoryBadge category={w.category} />93          {w.recurrence !== "none" ? <span className="row muted"><Icon name="restart" size={14} />{t(`states.recurrence.${w.recurrence}`)}</span> : null}94        </div>95        <div className="row-wrap">96          <DataStamp at={updatedAt} />97          {canWrite && open ? (98            <>99              <Button icon="edit" onClick={() => setDialog("edit")} data-testid="mt-window-edit">{t("common.edit")}</Button>100              <Button icon="check" onClick={() => setDialog("complete")} data-testid="mt-window-complete">{t("maintenance.detail.complete")}</Button>101              <Button variant="danger" icon="close" onClick={() => setDialog("cancel")} data-testid="mt-window-cancel">{t("maintenance.detail.cancel")}</Button>102            </>103          ) : null}104        </div>105      </div>106      {!open ? <Banner tone={w.status === "completed" ? "ok" : "offline"}>{w.status === "completed" ? t("maintenance.detail.closedCompleted") : t("maintenance.detail.closedCancelled")}</Banner> : null}107      {w.activated_occurrence ? <Banner tone="maintenance" icon="wrench">{t("maintenance.detail.activeNow", { time: fmt.dateTime(w.activated_occurrence, { timeZone: viewer }) })}</Banner> : null}108109      <div className="cols-2">110        <section className="section" aria-labelledby="mt-d-sched">111          <h2 id="mt-d-sched">{t("maintenance.detail.schedule")}</h2>112          <KeyValue113            items={[114              { label: t("maintenance.detail.firstOccurrence", { zone: zoneLabel(zone, Date.parse(w.starts_at)) }), value: <span className="num">{span(w.starts_at, w.ends_at, zone)}</span> },115              ...(viewer !== zone ? [{ label: t("maintenance.detail.yourZone", { zone: zoneLabel(viewer, Date.parse(w.starts_at)) }), value: <span className="num">{span(w.starts_at, w.ends_at, viewer)}</span> }] : []),116              { label: t("common.utc"), value: <span className="num">{fmt.utc(w.starts_at)} → {fmt.utc(w.ends_at)}</span> },117              { label: t("maintenance.detail.duration"), value: fmt.duration((Date.parse(w.ends_at) - Date.parse(w.starts_at)) / 1000) },118              { label: t("maintenance.form.recurrence"), value: <>{t(`states.recurrence.${w.recurrence}`)}{w.recurrence !== "none" ? <span className="muted"> · {w.recurrence_until ? t("maintenance.detail.until", { date: fmt.dateTime(w.recurrence_until, { timeZone: zone }) }) : t("maintenance.detail.noEnd")}</span> : null}</> },119              { label: t("maintenance.form.setMode"), value: w.set_maintenance_mode ? t("common.yes") : t("common.no") },120              { label: t("maintenance.form.silence"), value: w.silence_alerts ? t("common.yes") : t("common.no") },121              { label: t("common.created"), value: <span>{w.created_by_display_name ? `${w.created_by_display_name} · ` : ""}<span className="num">{fmt.dateTime(w.created_at)}</span></span> },122              { label: t("common.updated"), value: <span className="num">{fmt.dateTime(w.updated_at)}</span> },123            ]}124          />125          {w.description ? <div className="stack-sm"><h3>{t("common.description")}</h3><p><Linkified text={w.description} /></p></div> : null}126        </section>127128        <section className="section" aria-labelledby="mt-d-nodes">129          <h2 id="mt-d-nodes">{t("maintenance.detail.nodes")} <span className="mcc-count">{w.scope.node_ids.length}</span></h2>130          {w.scope.node_ids.length === 0 ? <p className="muted">{t("maintenance.detail.noNodes")}</p> : (131            <ul className="mt-nodes" data-testid="mt-window-nodes">132              {w.scope.node_ids.map((nid) => <li key={nid} className="mcc-chip"><NodeLink id={nid} alias={nodes.byId.get(nid)} /></li>)}133            </ul>134          )}135          <h2 id="mt-d-occ">{t("maintenance.detail.occurrences")}</h2>136          {upcoming.isError ? <ErrorState error={upcoming.error} compact onRetry={() => void upcoming.refetch()} /> : !upcoming.data ? <Skeleton width="60" label={t("common.loading")} /> : mine.length === 0 ? (137            <EmptyState compact icon="calendar" title={t("maintenance.detail.noOccurrences")} />138          ) : (139            <ul className="mt-occ-list" aria-labelledby="mt-d-occ">140              {mine.slice(0, 12).map((o) => {141                const sel = occurrence !== null && same(o.occurrence_start, occurrence);142                return (143                  <li key={o.occurrence_start}>144                    <button type="button" className="mt-occ-btn" aria-pressed={sel} onClick={() => selectOccurrence(sel ? null : o.occurrence_start)} data-testid="mt-occurrence-select">145                      <span className="num">{span(o.occurrence_start, o.occurrence_end, viewer)}</span>146                      <StatusDot status={occurrenceStatus(o)} subtle />147                      {o.note_count > 0 ? <span className="row muted"><Icon name="note" size={13} />{o.note_count}</span> : null}148                    </button>149                  </li>150                );151              })}152            </ul>153          )}154          {upcoming.data?.truncated ? <p className="mcc-hint">{t("maintenance.calendar.truncated")}</p> : null}155          <p className="mcc-hint">{t("maintenance.detail.occurrencesHint", { zone: zoneLabel(viewer, Date.parse(range.to)) })}</p>156        </section>157      </div>158159      <div className="section">160        {occurrence ? (161          <div className="row-wrap">162            <Segmented label={t("maintenance.detail.notesScope")} value={noteScope} onChange={setNoteScope} options={[{ value: "occurrence", label: t("maintenance.detail.notesOccurrence", { time: fmt.dateTime(occurrence, { timeZone: viewer, zone: false }) }) }, { value: "window", label: t("maintenance.detail.notesWindow") }]} />163            <LinkButton href={`/maintenance/${w.id}`} variant="ghost" size="sm">{t("maintenance.detail.clearOccurrence")}</LinkButton>164          </div>165        ) : null}166        <NotesPanel scope={occurrence && noteScope === "occurrence" ? { windowId: w.id, occurrence } : { windowId: w.id }} />167      </div>168169      <WindowDialog open={dialog === "edit"} onClose={() => setDialog(null)} window={w} loaded={upcoming.data?.items ?? []} />170      <Dialog open={dialog === "complete"} onClose={() => setDialog(null)} dismissable={!busy} title={t("maintenance.detail.completeTitle")} description={w.recurrence === "none" ? t("maintenance.detail.completeBody") : t("maintenance.detail.completeBodyRecurring")}171        footer={<><Button onClick={() => setDialog(null)} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} onClick={() => void run(() => apiPost("/maintenance/windows/{id}/complete", { path: { id: w.id }, body: closing.trim() ? { note: closing.trim() } : {} }), t("maintenance.detail.completed"))} data-testid="mt-complete-confirm">{t("maintenance.detail.complete")}</Button></>}>172        <TextAreaField label={t("maintenance.detail.closingNote")} hint={t("maintenance.detail.closingNoteHint")} value={closing} onChange={setClosing} maxLength={20000} rows={4} />173      </Dialog>174      <ConfirmDialog open={dialog === "cancel"} onClose={() => setDialog(null)} danger busy={busy} title={t("maintenance.detail.cancelTitle")} body={t("maintenance.detail.cancelBody")} confirmLabel={t("maintenance.detail.cancel")}175        onConfirm={() => void run(() => apiDelete("/maintenance/windows/{id}", { path: { id: w.id } }), t("maintenance.detail.cancelled"))} />176    </>177  );178}179
Files main
Menu

Theme