File size: 10,502 Bytes
af1bee9
fb43301
af1bee9
 
fb43301
af1bee9
 
fb43301
 
 
 
af1bee9
 
fb43301
af1bee9
fb43301
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Anchor, Button, CopyButton, Group, Skeleton, Stack, Text, Title } from '@mantine/core';
import { IconCheck, IconFileReport, IconFileSpreadsheet, IconFileTypePdf, IconLink, IconListNumbers } from '@/components/icons';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { MODULE_NAMES } from '../../domain/agents';
import { useGate, useReport, useRun, useRunReadiness, useRunScenarios, useScenario } from '../../api/hooks';
import type { ApproveGate } from '../../api/types';
import { scriptUrl } from '../../pages/run/RunGuide';
import { RunScripts } from '../../pages/run/RunData';
import { OUTCOME, ScenarioBody } from '../../pages/run/ScenarioReview';
import { decisionSentence } from '../../pages/run/SignOffReport';
import { AiText, Can, DecisionBadge, ErrorAlert, Prio } from '../common';
import { CoworkerAvatar } from '../CoworkerAvatar';
import { coworkerForNode } from '../../domain/coworkers';
import { EmptyState } from './EmptyState';
import '../../pages/run/report.css';

const ORIGIN: Record<string, { label: string; tone: string }> = {
  library: { label: 'Library', tone: 'neutral' }, generated: { label: 'New', tone: 'lav' }, ai: { label: 'Written by the AI model', tone: 'lav' },
};

/** Panel Report tab: the verdict per business area, the counts, the downloads and the way to the full report. */
export function ReportSummary({ runId, hideVerdict = false }: { runId: string; hideVerdict?: boolean }) {
  const run = useRun(runId);
  const done = run.data?.status === 'completed';
  const rep = useReport(runId);
  const rd = useRunReadiness(runId);
  const stopped = ['failed', 'killed', 'cancelled', 'interrupted'].includes(run.data?.status ?? '');
  if (stopped) {   // no coworker is on it any more: say so, never "Scout is on the run now"
    return <EmptyState icon={<IconFileReport size={28} />} title="This test run stopped before it finished, so it has no report."

      body="The run guide says why it stopped and lets you carry on from where it stopped."

      action={<Button component={Link} to={`/runs/${runId}`} size="xs" variant="default">Open the run guide</Button>} />;
  }
  if (!done) {
    const who = coworkerForNode(run.data?.pending_gate === 'approve_cases' ? 'approval_gate' : run.data?.pending_gate === 'human_review' ? 'human_review' : run.data?.current_node);
    return <EmptyState icon={<IconFileReport size={28} />} title="The report appears when the test run has finished."

      body={who ? `${who.name} is on the run now. The guide shows each step.` : 'The run guide shows each step meanwhile.'}

      action={<Button component={Link} to={`/runs/${runId}`} size="xs" variant="default">Open the run guide</Button>} />;
  }
  const mods = rd.data?.modules ?? [];
  const tested = mods.reduce((n, m) => n + m.counts.passed + m.counts.passed_on_retry + m.counts.failing, 0);
  const failing = mods.reduce((n, m) => n + m.counts.failing, 0);
  const notRun = mods.reduce((n, m) => n + m.counts.not_run, 0);
  const defects = mods.reduce((n, m) => n + m.confirmed_defects.length, 0);
  const gaps = mods.reduce((n, m) => n + m.steps.filter((s) => s.state === 'gap').length, 0);
  const link = typeof window !== 'undefined' ? `${window.location.origin}/runs/${runId}/report` : '';
  const decisions = rep.data?.decisions ?? run.data?.decisions ?? {};
  const writer = coworkerForNode('reporter');
  return (
    <Stack gap="sm" className="rpt-panel">

      <ErrorAlert error={rep.error} />

      {Object.entries(decisions).map(([m, d]) => (

        <div key={m}>

          {!hideVerdict && (

            <Group justify="space-between" wrap="nowrap" gap={8}>

              <Text fw={600} size="sm">{MODULE_NAMES[m] ?? m}</Text>

              <DecisionBadge decision={d} size="sm" />

            </Group>

          )}

          {!hideVerdict && <Text size="sm" mt={6}>{decisionSentence(d, rep.data?.criteria?.[m] ?? {}, rep.data?.target)}</Text>}

          {rep.data?.files?.[m]?.pdf && (

            <Button component="a" href={`/api/runs/${encodeURIComponent(runId)}/report/${m}/pdf`} download variant="default" size="xs" mt={8}

              leftSection={<IconFileTypePdf size={13} />} data-testid="panel-pdf-link">Download PDF{Object.keys(decisions).length > 1 ? ` (${m})` : ''}</Button>

          )}

        </div>

      ))}

      <dl className="rpt-mini fpt-num">

        <div><dt>Tested</dt><dd>{tested}</dd></div>

        <div><dt>Failing</dt><dd>{failing}</dd></div>

        <div><dt>Not run</dt><dd>{notRun}</dd></div>

        <div><dt>Defects</dt><dd>{defects ? <Link to="/tickets">{defects}</Link> : 0}</dd></div>

        <div><dt>Not covered yet</dt><dd>{gaps}</dd></div>

      </dl>

      {writer && <p className="rpt-writer"><CoworkerAvatar name={writer.name} size={20} /><span><b>{writer.name}</b> wrote this report.</span></p>}

      <Group gap={6} wrap="wrap">

        <CopyButton value={link}>{({ copied, copy }) => <Button size="xs" variant="default" onClick={copy} leftSection={copied ? <IconCheck size={13} /> : <IconLink size={13} />}>{copied ? 'Link copied' : 'Share'}</Button>}</CopyButton>

        <Button component="a" href={scriptUrl(runId)} download variant="default" size="xs" leftSection={<IconFileSpreadsheet size={13} />} data-testid="panel-results-excel">Download the results (Excel)</Button>

      </Group>

      <Button component={Link} to={`/runs/${runId}/report`} leftSection={<IconFileReport size={14} />}>{rd.data?.signoff ? 'Open the full report' : 'Open the full report and sign off'}</Button>

    </Stack>
  );
}

/** Panel Excel tab: the test script (and, once finished, the results) as Excel; scripts for admins. */
export function ExcelPanel({ runId, finished }: { runId: string; finished: boolean }) {
  return (
    <Stack gap="sm">

      <div className="pw-card rpt-file">

        <Group gap={8} wrap="nowrap" align="flex-start">

          <IconFileSpreadsheet size={22} className="rpt-file-icon" aria-hidden />

          <div className="rpt-file-body">

            <Text fw={600} size="sm">Test script (Excel)</Text>

            <Text size="xs" c="dimmed">Every step and the result we expect, with columns for your verdict and comments.</Text>

            <Button component="a" href={scriptUrl(runId)} download variant="default" size="xs" mt={8} data-testid="panel-excel-script">Download the test script (Excel)</Button>

          </div>

        </Group>

      </div>

      {finished && (

        <div className="pw-card rpt-file">

          <Group gap={8} wrap="nowrap" align="flex-start">

            <IconFileSpreadsheet size={22} className="rpt-file-icon" aria-hidden />

            <div className="rpt-file-body">

              <Text fw={600} size="sm">Results (Excel)</Text>

              <Text size="xs" c="dimmed">The same workbook, with the outcome of every scenario in this test run.</Text>

              <Button component="a" href={scriptUrl(runId)} download variant="default" size="xs" mt={8}>Download the results (Excel)</Button>

            </div>

          </Group>

        </div>

      )}

      <Can perm="admin">

        <Text fw={600} size="sm" mt="xs">Automation scripts (admin)</Text>

        <RunScripts id={runId} />

        <Anchor component={Link} to={`/runs/${runId}/scripts`} size="sm">Open the Scripts view</Anchor>

      </Can>

    </Stack>
  );
}

/** Panel Steps tab: one scenario, in the words of the review rows, for the selected `?scenario=`. */
export function ScenarioSteps({ runId, scenarioId }: { runId?: string; scenarioId: string | null }) {
  // The run's full scenario list is large (~250 KB) and slow on a busy machine; the Steps tab must not wait for it.
  // Use it when it is already loaded, and otherwise fetch the one selected scenario directly (a few KB).
  const sc = useRunScenarios(runId ?? '');
  const gate = useGate(runId ?? '', !!runId);
  const inRun = (sc.data?.scenarios ?? []).find((x) => x.id === scenarioId);
  const lib = useScenario(scenarioId && !inRun ? scenarioId : null, runId);
  const found = inRun ?? lib.data;
  const loading = !!scenarioId && !found && !lib.isError;
  // a scenario that has not loaded in 10 s gets an error line with Try again (never an endless spinner)
  const [slow, setSlow] = useState(false);
  useEffect(() => {
    setSlow(false);
    if (!loading) return;
    const t = window.setTimeout(() => setSlow(true), 10_000);
    return () => window.clearTimeout(t);
  }, [loading, scenarioId]);
  const retry = () => { setSlow(false); if (scenarioId && !inRun) void lib.refetch(); };
  if (!scenarioId) return <EmptyState icon={<IconListNumbers size={28} />} title="Pick a scenario to see its steps here" body="Use “Show steps” on a scenario or a screen." />;
  const s = found;
  if ((loading && slow) || (!loading && !s && lib.isError)) {
    return (
      <Stack gap={8} role="alert">

        <Text size="sm">{slow ? 'The scenario is taking too long to load.' : 'The scenario could not be loaded.'}</Text>

        <Button size="xs" variant="default" w="fit-content" onClick={retry}>Try again</Button>

      </Stack>
    );
  }
  if (loading) {
    return (
      <Stack gap={10} aria-busy="true" aria-label="Loading the scenario">

        <Skeleton height={14} width="40%" radius="xl" /><Skeleton height={18} width="85%" radius="xl" /><Skeleton height={60} radius="md" />

      </Stack>
    );
  }
  if (!s) return <ErrorAlert error={lib.error ?? new Error(`Scenario ${scenarioId} not found`)} />;
  const g = gate.data?.gate === 'approve_cases' ? (gate.data as ApproveGate) : null;
  const p = g?.pending.find((x) => x.id === s.id);
  const origin = ORIGIN[p?.origin ?? s.origin ?? 'library'] ?? ORIGIN.library;
  const out = s.outcome ? OUTCOME[s.outcome] : undefined;
  return (
    <Stack gap={8}>

      <Text size="xs" c="dimmed">Steps of <span className="fpt-idpill">{s.id}</span></Text>

      <Title order={2} className="rpt-h3">{s.title}</Title>

      <Group gap={10} wrap="wrap">

        <Prio words={s.priority_words} />

        {origin.tone === 'lav' && origin.label !== 'New' ? <AiText>{origin.label}</AiText> : <span className="fpt-dimtext">{origin.label}</span>}

        {out && <span className="fpt-dimtext">In this run: <span className="fpt-statustext" data-tone={out.tone}>{out.label}</span></span>}

      </Group>

      <ScenarioBody s={s} p={p} />

    </Stack>
  );
}