File size: 16,372 Bytes
3391d8f
2effee4
a289b2a
3391d8f
a289b2a
 
4545bb3
 
 
 
 
a289b2a
4545bb3
3391d8f
2effee4
 
 
 
1825659
2effee4
 
a289b2a
4545bb3
 
 
 
 
 
 
 
 
 
a289b2a
 
2effee4
4545bb3
a289b2a
 
 
 
2effee4
 
 
a289b2a
 
 
2effee4
 
 
4545bb3
 
 
1825659
 
2effee4
 
 
a289b2a
1825659
4545bb3
3391d8f
 
 
 
2effee4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92d45ee
2effee4
 
 
4545bb3
2effee4
 
 
 
 
 
 
 
 
 
 
4545bb3
 
2effee4
 
 
a289b2a
2effee4
 
4545bb3
2effee4
 
a289b2a
 
 
 
4545bb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a289b2a
 
2effee4
a289b2a
 
4545bb3
2effee4
1825659
 
33ce28f
2effee4
 
33ce28f
2effee4
1825659
33ce28f
 
 
 
 
 
2effee4
33ce28f
2effee4
33ce28f
2effee4
1825659
2effee4
 
1825659
a289b2a
 
 
 
 
 
 
 
2effee4
a289b2a
 
 
 
 
 
 
 
4545bb3
a289b2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Anchor, Button, CloseButton, Drawer, Group, Select, Skeleton, Stack, Table, Text, TextInput, UnstyledButton } from '@mantine/core';
import { useMediaQuery } from '@mantine/hooks';
import {
  IconAdjustments, IconBooks, IconBrain, IconCalendarTime, IconChevronRight, IconFileReport, IconPower, IconRobot, IconShieldCheck, IconUpload, IconUsers, IconWand,
} from '@tabler/icons-react';
import { useState, type ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link, useParams, useSearchParams } from 'react-router-dom';
import { getJson } from '../api/client';
import type { Pattern } from '../api/types';
import { ScenarioBody } from './ScenarioReview';
import { MODULE_NAMES } from '../agents';
import { useHistory, usePods, useRuns, useScenario, useScenarioLibrary, useTickets } from '../api/hooks';
import { Can, ErrorAlert, GlossaryButton, PageHeader, Pager, Prio } from '../components/common';
import { envKind } from '../components/shell/EnvSwitcher';
import { ScenarioSteps } from '../components/shell/panelTabs';
import { decisionWords } from '../glossary';
import { runTitle, shortWhen } from '../runName';
import './admin.css';

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

const MODULES = ['P2P', 'AP', 'O2C', 'R2R', 'A2R', 'EXP', 'HCM', 'P2M', 'PPM', 'SCM', 'SCP', 'CX'];

/** A library status in plain words. */
export function libraryStatusWords(status: string): { words: string; tone: string } {
  const known: Record<string, { words: string; tone: string }> = {
    approved: { words: 'Approved', tone: 'green' }, draft: { words: 'Awaiting approval', tone: 'amber' }, active: { words: 'In use', tone: 'green' },
    staged: { words: 'Being checked', tone: 'neutral' }, retired: { words: 'No longer used', tone: 'neutral' }, deprecated: { words: 'No longer used', tone: 'neutral' },
  };
  return known[status] ?? { words: status ? status.charAt(0).toUpperCase() + status.slice(1).replace(/_/g, ' ') : 'Unknown', tone: 'neutral' };
}

export function ScenariosLibraryPage() {
  const [params, setParams] = useSearchParams();
  const [module, setModule] = useState<string | null>(params.get('area'));
  const [step, setStep] = useState<string | null>(null);
  const [priority, setPriority] = useState<string | null>(null);
  const [q, setQ] = useState('');
  const [offset, setOffset] = useState(0);
  const wide = useMediaQuery('(min-width: 1280px)');
  const open = params.get('scenario');
  const setOpen = (id: string | null) => { const p = new URLSearchParams(params); if (id) p.set('scenario', id); else p.delete('scenario'); setParams(p, { replace: true }); };
  const limit = 25;
  const lib = useScenarioLibrary({ module: module ?? undefined, step: step ?? undefined, priority: priority ?? undefined, q: q || undefined, limit, offset });
  const reset = () => setOffset(0);
  const items = lib.data?.items ?? [];
  const filters = (
    <div className={wide ? 'fpt-libfilters' : 'fpt-libfilterbar'} role="group" aria-label="Filter the scenarios">

      <Select label="Business area" w={wide ? undefined : 210} data={[{ value: 'ALL', label: 'All business areas' }, ...MODULES.map((m) => ({ value: m, label: `${MODULE_NAMES[m] ?? m} (${m})` }))]}

        value={module ?? 'ALL'} allowDeselect={false}

        onChange={(v) => { setModule(v === 'ALL' ? null : v); setStep(null); reset(); }} />

      <Select label="Process step" placeholder="All process steps" w={wide ? undefined : 230} data={lib.data?.steps ?? []} value={step} clearable onChange={(v) => { setStep(v); reset(); }} />

      <Select label="Priority" placeholder="All priorities" w={wide ? undefined : 160} data={['Critical', 'High', 'Medium', 'Low']} value={priority} clearable onChange={(v) => { setPriority(v); reset(); }} />

      <TextInput label="Search" placeholder="title or ID" value={q} onChange={(e) => { setQ(e.currentTarget.value); reset(); }} />

    </div>
  );
  return (
    <Stack gap="md" className="adm-wide">

      <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Scenarios' }]} title="Scenarios"

        extra={<span className="fpt-pagedesc fpt-num">{lib.data?.total ?? 0} scenario{lib.data?.total === 1 ? '' : 's'}</span>}>

        <GlossaryButton />

        <Can perm="run.start"><Button component={Link} to="/scenarios/import" variant="default" leftSection={<IconUpload size={15} aria-hidden />}>Import your test cases</Button></Can>

      </PageHeader>

      <div className="fpt-lib" data-wide={wide || undefined} data-open={(wide && !!open) || undefined}>

        {filters}

        <div style={{ minWidth: 0 }}>

          <ErrorAlert error={lib.error} />

          <div className="fpt-card" style={{ overflow: 'hidden' }}>

            <Table.ScrollContainer minWidth={600}>

              <Table aria-label="scenarios library" className="fpt-table">

                <Table.Thead><Table.Tr><Table.Th>Scenario</Table.Th><Table.Th>Process step</Table.Th><Table.Th>Priority</Table.Th><Table.Th>Status</Table.Th><Table.Th>Automated</Table.Th></Table.Tr></Table.Thead>

                <Table.Tbody>

                  {lib.isLoading && [0, 1, 2, 3].map((i) => <Table.Tr key={i}><Table.Td colSpan={5}><Skeleton height={28} /></Table.Td></Table.Tr>)}

                  {!lib.isLoading && items.length === 0 && <Table.Tr><Table.Td colSpan={5}><Text size="sm" c="dimmed">No scenarios match these filters.</Text></Table.Td></Table.Tr>}

                  {items.map((s) => (

                    <Table.Tr key={s.id} data-selected={open === s.id || undefined} className="fpt-libro">

                      <Table.Td>

                        <UnstyledButton onClick={() => setOpen(open === s.id ? null : s.id)} aria-pressed={open === s.id} className="fpt-libtitle">{s.title}</UnstyledButton>

                        <Text size="xs" c="dimmed"><Link to={`/scenarios/${encodeURIComponent(s.id)}`} className="fpt-idpill" aria-label={`${s.id}: open the page of ${s.title}`}>{s.id}</Link> {!module && <span>{MODULE_NAMES[s.module] ?? s.module} </span>}<span className="fpt-aitext"><IconBooks size={13} aria-hidden />Library</span></Text>

                      </Table.Td>

                      <Table.Td>{s.step ?? <span className="fpt-nocov">No process step</span>}</Table.Td>

                      <Table.Td><Prio words={s.priority_words} /></Table.Td>

                      <Table.Td><span className="fpt-dotword" data-tone={libraryStatusWords(s.status).tone}>{libraryStatusWords(s.status).words}</span></Table.Td>

                      <Table.Td>{s.automated ? 'Yes' : 'Not yet'}</Table.Td>

                    </Table.Tr>

                  ))}

                </Table.Tbody>

              </Table>

            </Table.ScrollContainer>

          </div>

          {lib.data && <Pager total={lib.data.total} limit={limit} offset={offset} onChange={setOffset} />}

        </div>

        {wide && open && (

          <aside className="fpt-card fpt-libpanel" aria-label="Scenario steps">

            <Group justify="space-between" mb={6}><Text size="sm" fw={600}>Steps</Text>

              <Group gap={6}><Anchor component={Link} to={`/scenarios/${encodeURIComponent(open)}`} size="sm">Open the full page</Anchor><CloseButton aria-label="Close the steps" onClick={() => setOpen(null)} /></Group></Group>

            <ScenarioSteps scenarioId={open} />

          </aside>

        )}

      </div>

      {!wide && (

        <Drawer opened={!!open} onClose={() => setOpen(null)} position="right" size="xl" title="Steps">

          {open && <><Anchor component={Link} to={`/scenarios/${encodeURIComponent(open)}`} size="sm">Open the full page</Anchor><ScenarioSteps scenarioId={open} /></>}

        </Drawer>
      )}
    </Stack>
  );
}

/** /scenarios/:id: one library scenario with its steps and what is known about its recent results. */
export function ScenarioDetailPage() {
  const id = useParams().id ?? '';
  const sc = useScenario(id || null);
  const s = sc.data;
  const area = s?.module ?? id.split('-')[0];
  const patterns = useQuery({ queryKey: ['patterns', 'case', id], enabled: !!id, retry: false,
    queryFn: () => getJson<Pattern[]>(`/api/learner/patterns?case_id=${encodeURIComponent(id)}`) });
  const history = useHistory(area || undefined);
  const tickets = useTickets();
  const defects = (tickets.data?.items ?? []).filter((t) => t.case_id === id);
  const fails = (patterns.data ?? []).filter((p) => p.case_id === id);
  const recent = (history.data?.items ?? []).slice(0, 6);
  return (
    <Stack gap="md">

      <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Scenarios', to: '/scenarios' }, { label: s?.title ?? id }]} title={s?.title ?? (sc.isLoading ? 'Scenario' : id)}

        extra={<span className="fpt-pagedesc"><span className="fpt-idpill">{id}</span> {MODULE_NAMES[area] ?? area}{s?.step ? ` · ${s.step}` : ''}</span>}>

        {s && <Prio words={s.priority_words} />}

      </PageHeader>

      {sc.isLoading && <Stack gap={8} aria-busy="true"><Skeleton height={18} width="50%" /><Skeleton height={120} /></Stack>}

      {sc.error && <><ErrorAlert error={sc.error} title="This scenario could not be loaded" /><Anchor component={Link} to="/scenarios">Back to Scenarios</Anchor></>}
      {s && (
        <div className="fpt-scdetail">

          <section className="fpt-card" style={{ padding: 18 }} aria-label="Steps">

            <Stack gap={8}><ScenarioBody s={s} /></Stack>

          </section>

          <aside className="fpt-card" style={{ padding: 18 }} aria-label="Recent results">

            <Text fw={600} mb={8}>Recent results</Text>

            <Stack gap={10}>

              <div>

                <Text size="sm" fw={600}>Defects for this scenario</Text>

                {tickets.isLoading ? <Skeleton height={16} mt={4} /> : defects.length === 0 ? <Text size="sm" c="dimmed">None raised.</Text> : (

                  <Stack gap={2} mt={2}>{defects.map((t) => (

                    <Text key={t.ticket_id} size="sm"><Anchor component={Link} to={`/tickets?defect=${encodeURIComponent(t.ticket_id)}`}>{t.ticket_id}</Anchor>, {t.status === 'open' ? 'open' : t.status.replace(/_/g, ' ')}, {shortWhen(t.created_at)}. <Anchor component={Link} to={`/runs/${t.run_id}`}>Test run</Anchor></Text>

                  ))}</Stack>

                )}

              </div>

              <div>

                <Text size="sm" fw={600}>Repeated failures</Text>

                {patterns.isLoading ? <Skeleton height={16} mt={4} /> : fails.length === 0 ? <Text size="sm" c="dimmed">No repeated failure recorded.</Text> : (

                  <Stack gap={2} mt={2}>{fails.map((p) => <Text key={p.signature} size="sm">Failed {p.count} time{p.count === 1 ? '' : 's'} the same way, last {shortWhen(p.last_seen)}.</Text>)}</Stack>

                )}

              </div>

              <div>

                <Text size="sm" fw={600}>Recent test runs of {MODULE_NAMES[area] ?? area}</Text>

                {history.isLoading ? <Skeleton height={16} mt={4} /> : recent.length === 0 ? <Text size="sm" c="dimmed">No finished test run yet.</Text> : (

                  <Stack gap={2} mt={2}>{recent.map((h) => (

                    <Text key={h.id} size="sm"><Anchor component={Link} to={`/runs/${h.run_id}`}>{shortWhen(h.ts)}</Anchor>{h.patch_id ? `, patch ${h.patch_id}` : ''}: {decisionWords(h.decision)}</Text>

                  ))}</Stack>

                )}

                <Text size="xs" c="dimmed" mt={4}>The result of this one scenario in each run is on that run&apos;s Scenarios view.</Text>

              </div>

            </Stack>

          </aside>

        </div>
      )}
    </Stack>
  );
}

export function ReportsPage() {
  const runs = useRuns(50, 0, 'completed');
  const pods = usePods().data ?? [];
  return (
    <Stack gap="md">

      <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Reports' }]} title="Reports"

        extra={<span className="fpt-pagedesc">Finished test runs. Open one to read the report, download the PDF and sign it off.</span>} />

      {(runs.data?.items ?? []).length === 0 && <div className="trio-group"><div className="trio-empty">{runs.isLoading ? 'Loading the reports.' : 'Reports appear here when a test run finishes.'}</div></div>}

      {(runs.data?.items ?? []).length > 0 && <div className="trio-group" role="list" aria-label="reports">

        {(runs.data?.items ?? []).map((r) => {

          const fusion = envKind(pods.find((p) => p.id === r.pod_id)?.kind) === 'fusion';

          const ds = Object.entries(r.decisions ?? {});

          const tone = ds.some(([, d]) => d === 'NO-GO') ? 'red' : ds.some(([, d]) => d === 'HELD') ? 'orange' : ds.length ? 'green' : undefined;

          return (

            <div key={r.run_id} role="listitem"><Link to={`/runs/${r.run_id}/report`} className="trio-row fpt-reportrow">

              <span className="trio-tile" data-tone={tone} aria-hidden><IconFileReport size={19} stroke={1.7} /></span>

              <span className="trio-row-body">

                <b>{runTitle(r)}</b>

                <span>{fusion ? `Oracle Fusion pod: ${r.pod_name ?? 'unnamed'}` : 'Practice environment'}. {shortWhen(r.created_at)}. {r.modules.map((m) => MODULE_NAMES[m] ?? m).join(', ') || 'All areas'}.</span>

              </span>

              <span className="fpt-reportverdicts trio-row-trail">

                {ds.length === 0 ? <span className="fpt-verdictword">No decision</span> : ds.map(([m, d]) => (

                  <span key={m} className="fpt-dotword" data-tone={DECISION_TONE[d] ?? 'neutral'} data-rule={d} title={`Rule result: ${d}`}>{ds.length > 1 ? `${m} ` : ''}{decisionWords(d)}</span>

                ))}

                <IconChevronRight size={16} className="trio-chev" aria-hidden />

              </span>

            </Link></div>

          );

        })}

      </div>}

    </Stack>
  );
}

function HubCard({ to, icon, title, body }: { to: string; icon: ReactNode; title: string; body: string }) {
  return (
    <Link to={to} className="fpt-card fpt-tile" style={{ alignItems: 'flex-start' }}>

      <span className="fpt-iconbtn" style={{ width: 34, height: 34, borderRadius: 10 }} aria-hidden>{icon}</span>

      <span><Text size="sm" fw={600}>{title}</Text><Text size="xs" c="dimmed">{body}</Text></span>

    </Link>
  );
}

/** Engineering pages, for admins only: how the co-worker works under the hood. */
export function AdminHubPage() {
  return (
    <Stack gap="md">

      <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Admin & under the hood' }]} title="Admin & under the hood" />

      <Text size="sm" c="dimmed">Engineering views of the co-worker: its agents, automation internals, safety controls and users. Functional consultants do not need these pages.</Text>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 12 }}>

        <HubCard to="/agents" icon={<IconRobot size={17} />} title="Agent team" body="The agents, their engines and the workflow." />

        <HubCard to="/heal" icon={<IconWand size={17} />} title="Self-heal review" body="Proposed locator fixes from failed scripts." />

        <HubCard to="/scripts" icon={<IconBooks size={17} />} title="Scripts & drafts" body="Automation scripts, generated drafts, library history." />

        <HubCard to="/learner" icon={<IconBrain size={17} />} title="Learner" body="Run history, failure patterns, agreement metrics." />

        <HubCard to="/audit" icon={<IconShieldCheck size={17} />} title="Audit log" body="Append-only, hash-chained record of every action." />

        <HubCard to="/admin/autonomy" icon={<IconAdjustments size={17} />} title="Autonomy" body="Earned automatic approval per business area." />

        <HubCard to="/admin/scheduler" icon={<IconCalendarTime size={17} />} title="Scheduler & patch watch" body="Scheduled test runs and new-release detection." />

        <HubCard to="/admin/kill-switch" icon={<IconPower size={17} />} title="Kill switch" body="Emergency stop for all agent activity." />

        <HubCard to="/admin/users" icon={<IconUsers size={17} />} title="Users" body="Accounts and roles." />

      </div>

    </Stack>
  );
}