All files / src/pages TaskDetailPage.tsx

98.72% Statements 155/157
89.18% Branches 33/37
100% Functions 3/3
98.72% Lines 155/157

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 1801x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 26x 26x 26x 26x 26x 26x 26x 26x 26x   26x 26x 26x 21x 21x 21x 21x 21x 26x 26x   26x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x   1x 1x 2x 2x 2x 2x   26x 1x 1x 1x   1x 1x 1x   1x   26x 11x 11x   14x 14x   14x 14x 14x   14x   14x 14x 14x 14x 14x 14x 26x 26x 26x   26x 26x     26x 26x 26x 26x 26x 26x 26x   26x 1x 1x 1x 13x   26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x   26x 1x 1x 1x 1x 13x   26x 14x 14x 14x 14x   26x   26x 26x 1x   13x   26x 26x   26x  
import { useMemo, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { useApi } from "../hooks/useApi";
import { useResource } from "../hooks/useResource";
import { ErrorBanner } from "../components/ErrorBanner";
import { EventTimeline } from "../components/EventTimeline";
import { Panel } from "../components/KpiCards";
import { StatusBadge } from "../components/StatusBadge";
import { ApiError } from "../api/client";
import { formatDateTime, formatDuration, formatLease, formatRelative } from "../lib/format";
import { isTerminalStatus, taskStatusLabel, taskStatusTone } from "../lib/status";
import { canCancelTasks, denyReason } from "../lib/permissions";
import { useRole } from "../auth/RoleContext";
import { useToast } from "../components/Toasts";
import { countIgnoredResults, countRetries, executionSeconds, transitionPath } from "../lib/timeline";
 
export function TaskDetailPage() {
  const { taskId = "" } = useParams();
  const api = useApi();
  const role = useRole();
  const allowCancel = canCancelTasks(role);
  const toast = useToast();
  const task = useResource(() => api.getTask(taskId), [taskId], 3000);
  const events = useResource(() => api.getTaskEvents(taskId), [taskId], 3000);
  const [actionError, setActionError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
 
  const eventList = useMemo(() => events.data ?? [], [events.data]);
  const meta = useMemo(
    () => ({
      retries: countRetries(eventList),
      ignored: countIgnoredResults(eventList),
      path: transitionPath(eventList),
      executed: executionSeconds(eventList),
    }),
    [eventList],
  );
 
  async function cancel() {
    setBusy(true);
    setActionError(null);
    try {
      await api.cancelTask(taskId);
      toast("Задача отменена");
      task.reload();
      events.reload();
    } catch (error) {
      const message =
        error instanceof ApiError
          ? `${error.message}${error.status ? ` (код ${error.status})` : ""}`
          : String(error);
      setActionError(message);
    } finally {
      setBusy(false);
    }
  }
 
  if (task.error) {
    return (
      <div className="stack">
        <Link to="/tasks" className="link">
          ← ко всем задачам
        </Link>
        <ErrorBanner message={task.error} onRetry={task.reload} />
      </div>
    );
  }
 
  if (!task.data) {
    return <p className="muted">Загрузка задачи…</p>;
  }
 
  const current = task.data;
  const now = new Date();
 
  return (
    <div className="stack">
      <Link to="/tasks" className="link">
        ← ко всем задачам
      </Link>
 
      <Panel
        title={`Задача ${current.type}`}
        actions={
          <button
            type="button"
            className="button button--danger"
            disabled={busy || isTerminalStatus(current.status) || !allowCancel}
            title={allowCancel ? "Отменить задачу" : denyReason(role)}
            onClick={() => void cancel()}
          >
            {isTerminalStatus(current.status) ? "Завершена" : busy ? "Отменяем…" : "Отменить"}
          </button>
        }
      >
        <div className="detail-head">
          <StatusBadge tone={taskStatusTone(current.status)}>{taskStatusLabel(current.status)}</StatusBadge>
          <span className="mono">{current.id}</span>
          <span className="muted">
            попытка {current.attempts} из {current.max_attempts}
          </span>
        </div>
 
        {actionError ? (
          <p className="error-text" role="alert">
            {actionError}
          </p>
        ) : null}
 
        <dl className="detail-grid">
          <div>
            <dt>Приоритет</dt>
            <dd>{current.priority}</dd>
          </div>
          <div>
            <dt>Робот</dt>
            <dd className="mono">{current.robot_id ? current.robot_id.slice(0, 8) : "не назначен"}</dd>
          </div>
          <div>
            <dt>Аренда</dt>
            <dd>{formatLease(current.lease_expires_at, now)}</dd>
          </div>
          <div>
            <dt>Лимит попытки</dt>
            <dd>{formatDuration(current.timeout_seconds)}</dd>
          </div>
          <div>
            <dt>Создана</dt>
            <dd>{formatDateTime(current.created_at)}</dd>
          </div>
          <div>
            <dt>Обновлена</dt>
            <dd>{formatRelative(current.updated_at, now)}</dd>
          </div>
          <div>
            <dt>Внешний ключ</dt>
            <dd className="mono">{current.external_id ?? "—"}</dd>
          </div>
          <div>
            <dt>Переходы</dt>
            <dd className="mono">{meta.path || "—"}</dd>
          </div>
          <div>
            <dt>Повторы по событиям</dt>
            <dd>
              {meta.retries} · проигнорировано результатов: {meta.ignored}
            </dd>
          </div>
          <div>
            <dt>Время выполнения</dt>
            <dd>{meta.executed === null ? "—" : formatDuration(meta.executed)}</dd>
          </div>
        </dl>
 
        {current.last_error ? (
          <div className="callout callout--danger">
            <strong>Последняя ошибка</strong>
            <p>{current.last_error}</p>
          </div>
        ) : null}
 
        {current.payload && Object.keys(current.payload).length > 0 ? (
          <details className="details">
            <summary>Payload</summary>
            <pre className="code">{JSON.stringify(current.payload, null, 2)}</pre>
          </details>
        ) : null}
      </Panel>
 
      <Panel title="История событий" actions={<span className="muted">{eventList.length} событий</span>}>
        {events.error ? (
          <ErrorBanner message={events.error} onRetry={events.reload} />
        ) : (
          <EventTimeline events={eventList} now={now} />
        )}
      </Panel>
    </div>
  );
}