File size: 23,748 Bytes
cdfb5de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { Accordion, Anchor, Button, CopyButton, Group, Menu, Modal, Skeleton, Stack, Table, Text, Textarea, Title } from '@mantine/core';
import { IconAlertTriangle, IconBug, IconCheck, IconChecklist, IconChevronDown, IconDownload, IconFileSpreadsheet, IconFileTypePdf, IconLink, IconPlayerPause, IconSignature } from '@/components/icons';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { MODULE_NAMES, STEP_WORDS } from '../../domain/agents';
import { useReport, useRun, useRunReadiness, useSignOff, useTickets } from '../../api/hooks';
import { Can, DecisionBadge, ErrorAlert, fmtTs, RuleResult } from '../../components/common';
import { CoworkerAvatar } from '../../components/CoworkerAvatar';
import { DataTable } from '../../components/states';
import { coworkerForNode } from '../../domain/coworkers';
import './report.css';
import { shortWhen } from '../../domain/runName';
import { scriptUrl } from './RunGuide';
import { DECISION_WORDS, plainReason, RUN_STATUS_WORDS } from '../../domain/glossary';
import type { Criterion } from '../../api/types';

const CHECK_NAMES: Record<string, string> = { C1: 'Coverage', C2: 'Critical and High scenarios', C3: 'Stability', C4: 'False failures', C5: 'Independent recount', C6: 'Honest labelling' };
const CRITERIA_WORDS: Record<string, string> = {
  C1: 'Every scenario in scope has a test and was run',
  C2: 'Every Critical scenario passed; High-priority failures are explained and no High defect is open without a waiver',
  C3: 'Unstable scenarios stay under 5% and each has an owner',
  C4: 'False-failure rate is reported',
  C5: 'The counts in this report match the independent QA recount',
  C6: 'The report states it is from the mock app and lists open gaps',
};

/** One sentence that explains a business area's decision from the QA rule's checks. */
export function decisionSentence(d: string, crit: Record<string, Criterion>, target?: string | null): string {
  const failed = Object.entries(crit).filter(([, c]) => !c.ok);
  return d === 'GO' ? `${DECISION_WORDS[d]}: every required check passed${target?.startsWith('Oracle Fusion') ? ' on the Oracle Fusion pod' : ' on the mock app'}.`
    : d === 'HELD' ? `${DECISION_WORDS[d]}: the scenarios of this area are on hold, so no decision is made.`
      : `${DECISION_WORDS[d] ?? d}: ${failed.length} required ${failed.length === 1 ? 'check' : 'checks'} not met: ${failed.map(([k]) => CRITERIA_WORDS[k] ?? k).join('; ')}.`;
}

const STOPPED = ['failed', 'killed', 'cancelled', 'interrupted'];

function ReportSkeleton() {
  return (
    <Stack gap="md" aria-busy="true" aria-label="Loading the report" data-testid="report-loading">
      <Skeleton height={34} radius="md" />
      <Skeleton height={110} radius="md" />
      <Skeleton height={180} radius="md" />
      <Skeleton height={70} radius="md" />
    </Stack>
  );
}

export function SignOffReport({ id }: { id: string }) {
  const run = useRun(id);
  const rd = useRunReadiness(id);
  const rep = useReport(id);
  const tickets = useTickets(id);
  const sign = useSignOff(id);
  const [comment, setComment] = useState('');
  const [confirmNotReady, setConfirmNotReady] = useState(false);
  const signRef = useRef<HTMLElement>(null);
  const commentRef = useRef<HTMLTextAreaElement>(null);
  // "Go to sign-off": scroll to the sign-off form and put the cursor in its comment (one accent action in the header)
  const goToSignOff = () => {
    signRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
    window.setTimeout(() => commentRef.current?.focus({ preventScroll: true }), 300);
  };
  const r = run.data;
  const mods = rd.data?.modules ?? [];
  const decisions = rep.data?.decisions ?? {};
  const done = r?.status === 'completed';
  const refetchReport = rep.refetch;
  const refetchTickets = tickets.refetch;
  useEffect(() => { if (done) { void refetchReport(); void refetchTickets(); } }, [done, refetchReport, refetchTickets]);
  const signed = rd.data?.signoff;
  const rows = mods.flatMap((m) => m.steps.filter((s) => s.scenarios > 0 || s.state === 'gap'));
  const patchCol = new Set(rows.map((s) => s.touched)).size > 1;   // only worth a column when the steps differ
  const gapSteps = mods.flatMap((m) => m.steps.filter((s) => s.state === 'gap').map((s) => (mods.length > 1 ? `${MODULE_NAMES[m.module] ?? m.module}: ${s.name}` : s.name)));
  const gapChanges = mods.flatMap((m) => m.changes.filter((c) => c.gap).map((c) => c.area));
  const allGaps = Object.values(rep.data?.gaps ?? {}).reduce((n, g) => n + g.length, 0);
  const link = typeof window !== 'undefined' ? `${window.location.origin}/runs/${id}/report` : '';

  if (run.isLoading) return <ReportSkeleton />;
  if (run.error) return <ErrorAlert error={run.error} title="The test run could not be loaded" />;
  if (r && STOPPED.includes(r.status)) {
    return (
      <div className="pw-card rpt-pending rpt-pending-body" data-testid="report-none" role="status">
        <Title order={2} className="rpt-h2">This run did not finish, so there is no report</Title>
        <Text size="sm" c="dimmed" mt={4}>
          {r.status === 'cancelled' ? 'It was cancelled' : r.status === 'killed' ? 'It was stopped by the emergency stop' : r.status === 'interrupted' ? 'It was paused before the end' : 'It stopped with an error'}
          {plainReason(r.error) ? `: ${plainReason(r.error).replace(/[.!?]$/, '')}.` : '.'} Start a new test run to get a report{r.status === 'interrupted' || r.status === 'failed' ? ', or carry on from where it stopped on the test run page' : ''}.
        </Text>
        <Anchor component={Link} to={`/runs/${id}`} size="sm">Back to the test run</Anchor>
      </div>
    );
  }
  if (!done) return <ReportPending id={id} status={r?.status} node={r?.current_node} gate={r?.pending_gate} />;
  if (rep.isLoading || rd.isLoading) return <ReportSkeleton />;
  const fusionTarget = !!rep.data?.target?.startsWith('Oracle Fusion');
  const notReady = Object.values(decisions).some((d) => d !== 'GO');
  const base = (m: string) => `/api/runs/${encodeURIComponent(id)}/report/${m}`;
  const label = (m: string) => MODULE_NAMES[m] ?? m;
  const pdfs = Object.keys(decisions).filter((m) => rep.data?.files?.[m]?.pdf);
  const passed = mods.reduce((n, m) => n + m.counts.passed + m.counts.passed_on_retry, 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 openDefects = (tickets.data?.items ?? []).filter((t) => t.status === 'open').length;
  const writer = coworkerForNode('reporter');
  const doSign = () => sign.mutate(comment.trim(), { onSuccess: () => setConfirmNotReady(false) });
  const trySign = () => { if (notReady) setConfirmNotReady(true); else doSign(); };
  return (
    <Stack gap="md" className="fpt-report">
      <div className="fpt-reportbar" role="toolbar" aria-label="Report actions" data-testid="report-toolbar">
        {!signed && <Can perm="run.signoff"><Button size="xs" variant="filled" leftSection={<IconSignature size={13} />} onClick={goToSignOff}>Sign off</Button></Can>}
        {signed && <span className="fpt-dotword" data-tone="green">Signed off by {signed.by}</span>}
        <span className="fpt-reportbar-sp" />
        {pdfs.length === 1 && (
          <Button component="a" href={`${base(pdfs[0])}/pdf`} download variant="default" size="xs" leftSection={<IconFileTypePdf size={13} />} data-testid="pdf-link">Download PDF</Button>
        )}
        {pdfs.length > 1 && (
          <Menu position="bottom-end" withArrow>
            <Menu.Target><Button size="xs" variant="default" leftSection={<IconFileTypePdf size={13} />} rightSection={<IconChevronDown size={12} />}>Download PDF</Button></Menu.Target>
            <Menu.Dropdown>{pdfs.map((m, i) => <Menu.Item key={m} component="a" href={`${base(m)}/pdf`} download data-testid={i === 0 ? 'pdf-link' : undefined}>{label(m)}</Menu.Item>)}</Menu.Dropdown>
          </Menu>
        )}
        <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>
        <Menu position="bottom-end" withArrow>
          <Menu.Target>
            <Button size="xs" variant="default" leftSection={<IconDownload size={13} />} rightSection={<IconChevronDown size={12} />}>Downloads</Button>
          </Menu.Target>
          <Menu.Dropdown>
            {Object.keys(decisions).map((m) => (
              <div key={m}>
                {Object.keys(decisions).length > 1 && <Menu.Label>{label(m)}</Menu.Label>}
                {rep.data?.files?.[m]?.pdf && <Menu.Item component="a" href={`${base(m)}/pdf`} download leftSection={<IconFileTypePdf size={14} />}>PDF report</Menu.Item>}
                <Menu.Item component="a" href={`${base(m)}/html?download=true`} download>Web page report (HTML)</Menu.Item>
                <Menu.Item component="a" href={`${base(m)}/bundle`} target="_blank" rel="noopener noreferrer">Open the report in a new tab</Menu.Item>
                <Menu.Item component="a" href={`${base(m)}/md?download=true`} download>Text report (Markdown)</Menu.Item>
              </div>
            ))}
            <Menu.Divider />
            <Menu.Item component="a" href={scriptUrl(id)} download leftSection={<IconFileSpreadsheet size={14} />}>Results (Excel)</Menu.Item>
          </Menu.Dropdown>
        </Menu>
      </div>
      {/* the verdict first: one header card per business area, the decision as a large word with its reason */}
      {Object.entries(decisions).map(([m, d]) => {
        const crit = rep.data?.criteria?.[m] ?? {};
        return (
          <section key={m} className="pw-card rpt-head" data-tone={VERDICT_TONE[d] ?? 'neutral'} aria-label={`decision ${m}`}>
            <div className="pw-hatch-diag rpt-strip" aria-hidden />
            <div className="rpt-head-body">
              <div className="rpt-head-top">
                <Title order={2} className="rpt-area">{MODULE_NAMES[m] ?? m}</Title>
                <div className="rpt-verdict"><DecisionBadge decision={d} size="xl" /></div>
              </div>
              <Text className="rpt-sentence" data-testid="decision-explained">{decisionSentence(d, crit, rep.data?.target)}</Text>
              <Text size="xs" c="dimmed">{rep.data?.target?.startsWith('Oracle Fusion') ? `Results are from the ${rep.data.target}.` : 'Results are from the local mock app, not Oracle Fusion.'}</Text>
              {writer && (
                <p className="rpt-writer">
                  <CoworkerAvatar name={writer.name} size={22} />
                  <span><b>{writer.name}</b> wrote this report{r?.created_at ? `, from the test run started ${shortWhen(r.created_at)}` : ''}.</span>
                </p>
              )}
            </div>
          </section>
        );
      })}

      <div className="rpt-stats" role="group" aria-label="Counts">
        <Stat icon={<IconChecklist size={14} aria-hidden />} k="Scenarios tested" v={passed + failing} foot={`${passed} passed`} />
        <Stat icon={<IconAlertTriangle size={14} aria-hidden />} k="Failing" v={failing} foot={failing ? 'See the failures' : 'Nothing failed'} to={failing ? `/runs/${id}/failures` : undefined} />
        <Stat icon={<IconPlayerPause size={14} aria-hidden />} k="Not run" v={notRun} foot={notRun ? 'Blocked or skipped' : 'Every scenario ran'} />
        <Stat icon={<IconBug size={14} aria-hidden />} k="Open defects" v={openDefects} foot={openDefects ? 'See the defects' : 'None open'} to={openDefects ? '/tickets' : undefined} />
      </div>
      <div className="pw-hatch" aria-hidden />

      <section className="pw-card rpt-section" aria-labelledby="rpt-process-h">
        <Title order={2} className="rpt-h2" id="rpt-process-h">Results by business process</Title>
        <div className="rpt-process" data-testid="process-summary">
          <DataTable label="Process summary" className="pw-table" fz="sm" minWidth={560} rowCount={rows.length} empty="No process steps in this test run."
            columns={['Process step', 'Scenarios', 'Passed', 'Failed', 'Not run', ...(patchCol ? ['In patch'] : [])]}>
            {mods.flatMap((m) => m.steps.filter((s) => s.scenarios > 0 || s.state === 'gap').map((s) => (
              <Table.Tr key={`${m.module}-${s.key}`}>
                <Table.Td>{mods.length > 1 ? `${MODULE_NAMES[m.module] ?? m.module}: ` : ''}{s.name}</Table.Td>
                <Table.Td className="pw-num">{s.state === 'gap' && s.scenarios === 0 ? <span className="fpt-nocov">No scenario</span> : s.scenarios}</Table.Td>
                <Table.Td className="pw-num">{s.passed + s.flaky}</Table.Td><Table.Td className="pw-num">{s.failed}</Table.Td><Table.Td className="pw-num">{s.not_run}</Table.Td>
                {patchCol && <Table.Td>{s.touched ? 'Yes' : 'No'}</Table.Td>}
              </Table.Tr>
            )))}
          </DataTable>
        </div>
      </section>

      <div className="rpt-two">
      <section className="pw-card rpt-section" aria-labelledby="rpt-defects-h">
        <Title order={2} className="rpt-h2" id="rpt-defects-h">Open defects</Title>
        {tickets.isLoading ? <Skeleton height={18} width="50%" /> : tickets.error ? <ErrorAlert error={tickets.error} title="The defects could not be loaded" /> : (tickets.data?.items ?? []).length === 0 ? <Text size="sm" c="dimmed">No defects raised in this test run.</Text> : (
          <Stack gap={4}>{tickets.data!.items.map((t) => <Text key={t.ticket_id} size="sm"><Anchor component={Link} to={`/tickets?defect=${encodeURIComponent(t.ticket_id)}`}>{t.ticket_id}</Anchor>, scenario {t.case_id}: {t.status === 'open' ? 'open' : t.status.replace(/_/g, ' ')}</Text>)}</Stack>
        )}
      </section>

      <section className="pw-card rpt-section" aria-labelledby="rpt-gaps-h">
        <Title order={2} className="rpt-h2" id="rpt-gaps-h">Not covered yet</Title>
        <Stack gap={4} data-testid="gaps-summary">
          {gapSteps.length > 0 && <Text size="sm">Process steps with no scenario: {gapSteps.join(', ')}.</Text>}
          {gapChanges.length > 0 && <Text size="sm">Changes in this patch that no scenario tests yet ({gapChanges.length}): {gapChanges.slice(0, 8).join(', ')}{gapChanges.length > 8 ? ', …' : ''}. <Anchor component={Link} to={`/runs/${id}/changes`}>See what this patch changes</Anchor></Text>}
          {gapSteps.length === 0 && gapChanges.length === 0 && <Text size="sm" c="dimmed">No open coverage gaps for the steps in this test run.</Text>}
          {allGaps > 0 && <Text size="xs" c="dimmed">The full list of {allGaps} open {allGaps === 1 ? 'point' : 'points'} is under Audit details below.</Text>}
        </Stack>
      </section>
      </div>
      <div className="pw-hatch" aria-hidden />

      <section className="pw-card rpt-sign" data-signed={signed ? 'true' : undefined} aria-label="sign-off" ref={signRef}>
        <Title order={2} className="rpt-h2 rpt-sign-h"><IconSignature size={16} aria-hidden /> Sign-off</Title>
        {signed ? (
          <Text size="sm" data-testid="signoff" className="fpt-signed rpt-signed" title={fmtTs(signed.at)}><IconCheck size={14} aria-hidden /> Signed off by <b>{signed.by}</b> on {shortWhen(signed.at)}{signed.comment ? `, with the comment “${signed.comment}”` : ''}. Decision at sign-off: {Object.entries(signed.decisions).map(([m, d]) => `${MODULE_NAMES[m] ?? m} ${DECISION_WORDS[d] ?? d}`).join(', ')}.</Text>
        ) : (
          <Can perm="run.signoff" fallback={<Text size="sm" c="dimmed">Not signed off yet. A QA approver signs off finished test runs.</Text>}>
            <Text size="xs" c="dimmed" mb={6}>Signing off records who reviewed this report and when (audit log). It does not change the decision.
              {notReady ? ' This result is Not ready: say why you sign it off anyway.' : ''}</Text>
            <Textarea ref={commentRef} size="xs" aria-label="sign-off comment" placeholder={notReady ? 'Why you sign off a Not ready result (required)' : 'Comment (optional)'}
              required={notReady} value={comment} onChange={(e) => setComment(e.currentTarget.value)} autosize minRows={notReady ? 2 : 1} />
            <Group mt="sm" className="rpt-sign-row">
              <Button variant="filled" onClick={trySign} loading={sign.isPending && !confirmNotReady} disabled={notReady && !comment.trim()} leftSection={<IconSignature size={13} />}
                title={notReady && !comment.trim() ? 'Add a comment first' : undefined}>Sign off this report</Button>
              {notReady && !comment.trim() && <Text size="xs" c="dimmed">A comment is required to sign off a Not ready result.</Text>}
            </Group>
            <ErrorAlert error={sign.error} title="The sign-off was not saved" />
            <Modal opened={confirmNotReady} onClose={() => setConfirmNotReady(false)} title="Sign off a Not ready result?" centered size={480}>
              <Stack gap="sm">
                <Text size="sm">The QA rule says {Object.entries(decisions).filter(([, d]) => d !== 'GO').map(([m]) => label(m)).join(', ')} {Object.values(decisions).filter((d) => d !== 'GO').length === 1 ? 'is' : 'are'} not ready for the patch. Signing off records that you reviewed this anyway; it does not change the result.</Text>
                <Text size="sm" c="dimmed">Your comment: “{comment.trim()}”</Text>
                <div className="trio-sheet-foot">
                  <Button variant="default" onClick={() => setConfirmNotReady(false)}>Go back</Button><span className="trio-sheet-sp" />
                  <Button variant="filled" loading={sign.isPending} onClick={doSign} data-testid="confirm-signoff">Sign off anyway</Button>
                </div>
              </Stack>
            </Modal>
          </Can>
        )}
      </section>

      <Accordion variant="separated" radius="md" className="rpt-audit">
        <Accordion.Item value="audit">
          <Accordion.Control><Text size="sm">Audit details: the exact rule result, the checks behind it and the full technical report</Text></Accordion.Control>
          <Accordion.Panel>
            {Object.entries(decisions).map(([m, d]) => (
              <Group key={m} gap={8} mb={6}>
                <Text size="sm" fw={600}>{MODULE_NAMES[m] ?? m} ({m})</Text><RuleResult decision={d} />
                <Text size="xs" c="dimmed">computed by reports/generate_report.py (QA rule C1–C6); this page never recalculates it</Text>
              </Group>
            ))}
            {Object.entries(decisions).map(([m]) => <Text key={m} size="xs" c="dimmed" mb={6} data-testid="exec-summary">{rep.data?.executive_summary?.[m]}</Text>)}
            {Object.keys(decisions).map((m) => { const u = rep.data?.usage_coverage?.[m]; return u ? <Text key={m} size="xs" c="dimmed" mb={6} data-testid="usage-coverage">{u.line}{u.read && u.covered_share != null ? ` Scenarios cover ${Math.round(u.covered_share * 100)}% of the client's volume (details in the report below).` : ''}</Text> : null; })}
            <Group gap={12} mb={8}>{Object.keys(decisions).map((m) => <Anchor key={m} size="xs" href={`${base(m)}/summary?download=true`} download>run-summary.json{Object.keys(decisions).length > 1 ? ` (${m})` : ''}</Anchor>)}</Group>
            {Object.entries(rep.data?.criteria ?? {}).map(([m, crit]) => (
              <Table key={m} aria-label="criteria" fz="xs" mb="sm" className="pw-table">
                <Table.Thead><Table.Tr><Table.Th>{m} check</Table.Th><Table.Th>Met</Table.Th><Table.Th>Detail</Table.Th></Table.Tr></Table.Thead>
                <Table.Tbody>{Object.entries(crit).map(([k, c]) => <Table.Tr key={k}><Table.Td>{k} {CHECK_NAMES[k] ?? ''}</Table.Td><Table.Td><span className="pw-status" data-tone={c.ok ? 'green' : 'red'}>{c.ok ? 'Met' : 'Not met'}</span></Table.Td><Table.Td>{c.detail}</Table.Td></Table.Tr>)}</Table.Tbody>
              </Table>
            ))}
            {allGaps > 0 && (
              <details className="rpt-details">
                <summary>All {allGaps} open {allGaps === 1 ? 'point' : 'points'} listed by the report</summary>
                <Stack gap={2} mt={6}>{Object.entries(rep.data?.gaps ?? {}).flatMap(([m, gs]) => gs.map((g, i) => <Text key={`${m}${i}`} size="xs">• {g}</Text>))}</Stack>
              </details>
            )}
            {Object.keys(decisions).map((m) => (
              <iframe key={m} title={`${m} go/no-go report`} src={`/api/runs/${encodeURIComponent(id)}/report/${m}/bundle`} sandbox="" className="rpt-frame" />
            ))}
          </Accordion.Panel>
        </Accordion.Item>
      </Accordion>
      <ErrorAlert error={rep.error} />
      <Text size="sm" className="fpt-report-honesty" data-tone={fusionTarget ? 'fusion' : 'practice'}>
        {fusionTarget ? `Oracle Fusion pod: these results come from the ${rep.data?.target}.` : 'Practice environment: these results come from the mock app, not Oracle Fusion.'}
      </Text>
    </Stack>
  );
}

const VERDICT_TONE: Record<string, string> = { GO: 'green', 'NO-GO': 'red', HELD: 'orange' };

/** One count of the report: a label with a small icon, the number, and one line under it (a link when there is a place to go). */
function Stat({ icon, k, v, foot, to }: { icon: ReactNode; k: string; v: number; foot: string; to?: string }) {
  return (
    <div className="pw-stat">
      <div className="pw-stat-body">
        <div className="pw-stat-k">{icon}{k}</div>
        <div className="pw-stat-v pw-num">{v}</div>
      </div>
      <div className="pw-stat-foot">{to ? <Link to={to}>{foot}</Link> : foot}</div>
    </div>
  );
}

/** Before the run has finished: what the report will hold, where the run is now, and the way back to the run guide. */
function ReportPending({ id, status, node, gate }: { id: string; status?: string; node?: string | null; gate?: string | null }) {
  const who = coworkerForNode(gate === 'approve_cases' ? 'approval_gate' : gate === 'human_review' ? 'human_review' : node);
  const step = node ? (STEP_WORDS[node]?.[1] ?? node.replace(/_/g, ' ')) : null;
  const now = gate === 'approve_cases' ? 'waiting for you to approve the scenarios'
    : gate === 'human_review' ? 'waiting for your decision on a failure'
      : status ? (RUN_STATUS_WORDS[status] ?? status.replace(/_/g, ' ')) : 'starting';
  return (
    <section className="pw-card rpt-pending" aria-labelledby="rpt-pending-h" data-testid="report-pending">
      <div className="pw-hatch-diag rpt-strip" aria-hidden />
      <div className="rpt-pending-body">
        <Title order={2} className="rpt-h2" id="rpt-pending-h">The report is written when the test run finishes</Title>
        <Text size="sm">It will hold the Ready or Not ready decision for each business area, the results by process step, the open defects and what is not covered yet. You sign it off here.</Text>
        <div className="rpt-now">
          {who && <CoworkerAvatar name={who.name} size={28} working={!gate} />}
          <div>
            <div className="rpt-now-k">Where the run is now</div>
            <div className="rpt-now-v">{who ? `${who.name}: ` : ''}{now}{step && !gate ? ` (${step})` : ''}</div>
          </div>
        </div>
        <Group gap="sm">
          <Button component={Link} to={`/runs/${id}`} variant="filled">Back to the run guide</Button>
          {gate === 'approve_cases' && <Button component={Link} to={`/runs/${id}/scenarios`} variant="default">Review the scenarios</Button>}
          {gate === 'human_review' && <Button component={Link} to={`/runs/${id}/failures`} variant="default">Decide on the failures</Button>}
        </Group>
      </div>
    </section>
  );
}