Initial commit: PESCO NCR system

Complete Non-Conformance Report system replacing the PowerApps/SharePoint
prototype: FastAPI + SQLAlchemy 2 (async) + Alembic + MySQL 8 backend,
React 18 + Vite + TypeScript + MUI frontend, Entra ID auth (MSAL / JWKS,
group-gated), Microsoft Graph delegated Mail.Send notifications (OBO),
six-stage workflow state machine with server-side enforcement, atomic
NCR-YYYY-NNNN numbering, attachments with camera capture, immutable
field-level audit trail, admin reopen, reports + CSV export, WeasyPrint
PDF traveler, Power BI reporting views + read-only DB user, documented
VISUAL ERP job-lookup stub, pytest suite (26 tests), docker-compose
deployment.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
ang3l12
2026-07-13 11:41:22 -06:00
commit dea316b113
111 changed files with 13817 additions and 0 deletions

View File

@@ -0,0 +1,414 @@
import DownloadIcon from "@mui/icons-material/Download";
import TableChartIcon from "@mui/icons-material/TableChart";
import {
Box,
Button,
Card,
CardContent,
CardHeader,
CircularProgress,
Divider,
Grid,
MenuItem,
Stack,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
TextField,
ToggleButton,
Typography,
} from "@mui/material";
import { useState } from "react";
import {
Bar,
BarChart,
CartesianGrid,
Legend,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { useLookups, useReportsSummary } from "../api/hooks";
/* Validated categorical palette (dataviz reference instance, light mode).
* Fixed slot order — color follows the entity: labor=1 material=2 service=3
* other=4. Aqua/yellow sit below 3:1 on white, so the cost chart ships a
* table view (relief rule). */
const SERIES = {
labor: "#2a78d6",
material: "#1baf7a",
service: "#eda100",
other: "#008300",
};
const SINGLE_HUE = "#2a78d6";
const GRID = "#eceff1";
const TICK = { fill: "#52514e", fontSize: 12 };
function money(n: number): string {
return n.toLocaleString(undefined, {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
});
}
function csvDownload(filename: string, rows: Record<string, unknown>[]): void {
if (rows.length === 0) return;
const headers = Object.keys(rows[0]);
const esc = (v: unknown) => `"${String(v ?? "").replace(/"/g, '""')}"`;
const csv = [
headers.join(","),
...rows.map((r) => headers.map((h) => esc(r[h])).join(",")),
].join("\n");
const url = URL.createObjectURL(new Blob([csv], { type: "text/csv" }));
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
function StatTile({ label, value }: { label: string; value: string }) {
return (
<Card sx={{ flexGrow: 1, minWidth: 150 }}>
<CardContent sx={{ py: 1.5, "&:last-child": { pb: 1.5 } }}>
<Typography variant="caption" color="text.secondary">
{label}
</Typography>
<Typography variant="h5">{value}</Typography>
</CardContent>
</Card>
);
}
function ChartCard({
title,
subheader,
action,
children,
}: {
title: string;
subheader?: string;
action?: React.ReactNode;
children: React.ReactNode;
}) {
return (
<Card sx={{ height: "100%" }}>
<CardHeader
title={title}
subheader={subheader}
action={action}
titleTypographyProps={{ variant: "subtitle1", fontWeight: 700 }}
subheaderTypographyProps={{ variant: "caption" }}
/>
<Divider />
<CardContent>{children}</CardContent>
</Card>
);
}
export function ReportsPage() {
const lookups = useLookups();
const [dateFrom, setDateFrom] = useState("");
const [dateTo, setDateTo] = useState("");
const [departmentId, setDepartmentId] = useState<number | "">("");
const [categoryId, setCategoryId] = useState<number | "">("");
const [costAsTable, setCostAsTable] = useState(false);
const summary = useReportsSummary({
date_from: dateFrom || undefined,
date_to: dateTo || undefined,
department_id: departmentId || undefined,
category_id: categoryId || undefined,
});
const data = summary.data;
const costRows = (data?.cost_over_time ?? []).map((c) => ({
month: c.month,
Labor: Number(c.labor),
Material: Number(c.material),
Service: Number(c.service),
Other: Number(c.other),
Total: Number(c.total),
}));
return (
<Box>
<Typography variant="h5" gutterBottom>
Reports
</Typography>
{/* Filters — one row above the charts */}
<Card sx={{ mb: 2 }}>
<CardContent sx={{ py: 1.5, "&:last-child": { pb: 1.5 } }}>
<Stack direction={{ xs: "column", sm: "row" }} spacing={1.5}>
<TextField
size="small"
type="date"
label="From"
InputLabelProps={{ shrink: true }}
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
/>
<TextField
size="small"
type="date"
label="To"
InputLabelProps={{ shrink: true }}
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
/>
<TextField
size="small"
select
label="Department"
value={departmentId}
onChange={(e) =>
setDepartmentId(e.target.value === "" ? "" : Number(e.target.value))
}
sx={{ minWidth: 180 }}
>
<MenuItem value="">All departments</MenuItem>
{(lookups.data?.departments ?? []).map((d) => (
<MenuItem key={d.id} value={d.id}>
{d.name}
</MenuItem>
))}
</TextField>
<TextField
size="small"
select
label="Category"
value={categoryId}
onChange={(e) =>
setCategoryId(e.target.value === "" ? "" : Number(e.target.value))
}
sx={{ minWidth: 180 }}
>
<MenuItem value="">All categories</MenuItem>
{(lookups.data?.deviation_categories ?? []).map((c) => (
<MenuItem key={c.id} value={c.id}>
{c.name}
</MenuItem>
))}
</TextField>
</Stack>
</CardContent>
</Card>
{summary.isLoading || !data ? (
<Box sx={{ textAlign: "center", py: 8 }}>
<CircularProgress />
</Box>
) : (
<>
<Stack direction="row" spacing={1.5} sx={{ mb: 2 }} flexWrap="wrap" useFlexGap>
<StatTile label="Total NCRs" value={String(data.total_ncrs)} />
<StatTile label="Open" value={String(data.open_ncrs)} />
<StatTile label="Closed" value={String(data.closed_ncrs)} />
<StatTile label="Cost of Nonconformance" value={money(Number(data.total_cost))} />
<StatTile
label="Avg End-to-End"
value={
data.end_to_end_avg_days !== null
? `${data.end_to_end_avg_days} days`
: "—"
}
/>
</Stack>
<Grid container spacing={2}>
<Grid item xs={12} md={6}>
<ChartCard title="NCRs by Month">
<ResponsiveContainer width="100%" height={260}>
<BarChart data={data.by_month}>
<CartesianGrid stroke={GRID} vertical={false} />
<XAxis dataKey="month" tick={TICK} tickLine={false} />
<YAxis allowDecimals={false} tick={TICK} tickLine={false} axisLine={false} />
<Tooltip />
<Bar dataKey="count" name="NCRs" fill={SINGLE_HUE} radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</ChartCard>
</Grid>
<Grid item xs={12} md={6}>
<ChartCard
title="Cost of Nonconformance Over Time"
subheader="Closed NCRs, by month closed"
action={
<Stack direction="row" spacing={0.5}>
<ToggleButton
value="table"
size="small"
selected={costAsTable}
onChange={() => setCostAsTable(!costAsTable)}
title="Toggle table view"
>
<TableChartIcon fontSize="small" />
</ToggleButton>
<Button
size="small"
startIcon={<DownloadIcon />}
onClick={() => csvDownload("cost-of-nonconformance.csv", costRows)}
>
CSV
</Button>
</Stack>
}
>
{costAsTable ? (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Month</TableCell>
<TableCell align="right">Labor</TableCell>
<TableCell align="right">Material</TableCell>
<TableCell align="right">Service</TableCell>
<TableCell align="right">Other</TableCell>
<TableCell align="right">Total</TableCell>
</TableRow>
</TableHead>
<TableBody>
{costRows.map((r) => (
<TableRow key={r.month}>
<TableCell>{r.month}</TableCell>
<TableCell align="right">{money(r.Labor)}</TableCell>
<TableCell align="right">{money(r.Material)}</TableCell>
<TableCell align="right">{money(r.Service)}</TableCell>
<TableCell align="right">{money(r.Other)}</TableCell>
<TableCell align="right" sx={{ fontWeight: 700 }}>
{money(r.Total)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<ResponsiveContainer width="100%" height={260}>
<BarChart data={costRows}>
<CartesianGrid stroke={GRID} vertical={false} />
<XAxis dataKey="month" tick={TICK} tickLine={false} />
<YAxis
tick={TICK}
tickLine={false}
axisLine={false}
tickFormatter={(v: number) => money(v)}
width={72}
/>
<Tooltip formatter={(v: number) => money(v)} />
<Legend />
{/* 2px surface gap between stacked segments via stroke */}
<Bar dataKey="Labor" stackId="cost" fill={SERIES.labor} stroke="#fff" strokeWidth={1} />
<Bar dataKey="Material" stackId="cost" fill={SERIES.material} stroke="#fff" strokeWidth={1} />
<Bar dataKey="Service" stackId="cost" fill={SERIES.service} stroke="#fff" strokeWidth={1} />
<Bar dataKey="Other" stackId="cost" fill={SERIES.other} stroke="#fff" strokeWidth={1} radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
)}
</ChartCard>
</Grid>
<Grid item xs={12} md={6}>
<ChartCard title="NCRs by Department">
<ResponsiveContainer width="100%" height={Math.max(200, data.by_department.length * 34)}>
<BarChart data={data.by_department} layout="vertical">
<CartesianGrid stroke={GRID} horizontal={false} />
<XAxis type="number" allowDecimals={false} tick={TICK} tickLine={false} />
<YAxis type="category" dataKey="name" width={130} tick={TICK} tickLine={false} axisLine={false} />
<Tooltip />
<Bar dataKey="count" name="NCRs" fill={SINGLE_HUE} radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
</ChartCard>
</Grid>
<Grid item xs={12} md={6}>
<ChartCard title="NCRs by Deviation Category">
<ResponsiveContainer width="100%" height={Math.max(200, data.by_category.length * 34)}>
<BarChart data={data.by_category} layout="vertical">
<CartesianGrid stroke={GRID} horizontal={false} />
<XAxis type="number" allowDecimals={false} tick={TICK} tickLine={false} />
<YAxis type="category" dataKey="name" width={160} tick={TICK} tickLine={false} axisLine={false} />
<Tooltip />
<Bar dataKey="count" name="NCRs" fill={SINGLE_HUE} radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
</ChartCard>
</Grid>
<Grid item xs={12} md={6}>
<ChartCard title="Open NCR Aging" subheader="Days in current stage">
<ResponsiveContainer width="100%" height={240}>
<BarChart data={data.aging}>
<CartesianGrid stroke={GRID} vertical={false} />
<XAxis dataKey="bucket" tick={TICK} tickLine={false} />
<YAxis allowDecimals={false} tick={TICK} tickLine={false} axisLine={false} />
<Tooltip />
<Bar dataKey="count" name="Open NCRs" fill={SINGLE_HUE} radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</ChartCard>
</Grid>
<Grid item xs={12} md={6}>
<ChartCard title="Average Cycle Time per Stage" subheader="Days spent in each stage">
<ResponsiveContainer width="100%" height={240}>
<BarChart data={data.cycle_times} layout="vertical">
<CartesianGrid stroke={GRID} horizontal={false} />
<XAxis type="number" tick={TICK} tickLine={false} />
<YAxis type="category" dataKey="stage_label" width={150} tick={TICK} tickLine={false} axisLine={false} />
<Tooltip formatter={(v: number) => `${v} days`} />
<Bar dataKey="avg_days" name="Avg days" fill={SINGLE_HUE} radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
</ChartCard>
</Grid>
<Grid item xs={12} md={6}>
<ChartCard
title="Top Job Numbers by NCR Count"
action={
<Button
size="small"
startIcon={<DownloadIcon />}
onClick={() => csvDownload("top-jobs.csv", data.top_jobs)}
>
CSV
</Button>
}
>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Job Number</TableCell>
<TableCell align="right">NCRs</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.top_jobs.map((j) => (
<TableRow key={j.job_number}>
<TableCell>{j.job_number}</TableCell>
<TableCell align="right">{j.count}</TableCell>
</TableRow>
))}
{data.top_jobs.length === 0 && (
<TableRow>
<TableCell colSpan={2}>
<Typography color="text.secondary">No data.</Typography>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</ChartCard>
</Grid>
</Grid>
</>
)}
</Box>
);
}