Phase 2: core domain, policy engine, packet API, Clerical screen
Migration 0003: projects, aliases, renumbers, units, packets and every child table, change orders, assets, documents, ITPs, station limits, department weld flag. Policy package: Principal, PacketState, Action rules, custody, preconditions, CO hold, order of checks, can/blocked/holder on reads. docs/POLICY.md with the tightenings table for Seth. Write pipeline: FOR UPDATE, CAS on status and dept, If-Match row versions, server-assigned numbers, field CAS, version bump, packet log, audit, NOTIFY, signatures, IT reasons, filed lock and HMAC seal. API: /api/packets (header, transitions, work orders, pages, docs, move, remove, BOM, shorts, welds, heat tags, heat table, stage, checklist, clock, warehouse stage, Q.C., change orders, log, seal), /api/projects, /api/units, /api/assets, /_blob. Frontend: Clerical home, projects and units, packet page with pdf.js and QR codes, hand draft, heat map, send to warehouse, department or Q.C. Tests: policy matrix, API, concurrency, schema, projects; Playwright Clerical draft scenario. Verified on docker-1 with the CI stack and the Samba DC. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
// What the screens offer. The server decides on every request; this only hides what cannot work.
|
||||
|
||||
/** Clerical (or a Clerical supervisor) sets up projects and units. Admin can, with an IT reason. */
|
||||
export function canEditProjects(roles: readonly string[]): boolean {
|
||||
return roles.some((r) => r === "clerical" || r === "clerical_supervisor" || r === "admin");
|
||||
}
|
||||
|
||||
/** Renumbering a project or unit needs a Clerical supervisor, or admin. */
|
||||
export function canRenumber(roles: readonly string[]): boolean {
|
||||
return roles.some((r) => r === "clerical_supervisor" || r === "admin");
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// The `changed` events from /api/events, fanned out to the open screens.
|
||||
// AuthProvider owns the one EventSource and feeds every payload in here.
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export interface ChangedEvent {
|
||||
event?: string;
|
||||
packet_id?: number;
|
||||
version?: number;
|
||||
status?: string;
|
||||
dept?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
type Listener = (ev: ChangedEvent) => void;
|
||||
const listeners = new Set<Listener>();
|
||||
|
||||
export function emitChanged(payload: unknown): void {
|
||||
const ev: ChangedEvent = payload && typeof payload === "object" ? (payload as ChangedEvent) : {};
|
||||
for (const fn of listeners) fn(ev);
|
||||
}
|
||||
|
||||
export function onChanged(fn: Listener): () => void {
|
||||
listeners.add(fn);
|
||||
return () => {
|
||||
listeners.delete(fn);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls `fn` after `changed` events. With `delayMs`, a burst of events gives one call
|
||||
* `delayMs` after the last one. `filter` drops events the screen does not care about.
|
||||
*/
|
||||
export function useChanged(fn: () => void, opts: { delayMs?: number; filter?: (ev: ChangedEvent) => boolean } = {}): void {
|
||||
const fnRef = useRef(fn);
|
||||
const filterRef = useRef(opts.filter);
|
||||
useEffect(() => {
|
||||
fnRef.current = fn;
|
||||
filterRef.current = opts.filter;
|
||||
});
|
||||
const delay = opts.delayMs ?? 500;
|
||||
useEffect(() => {
|
||||
let t: number | undefined;
|
||||
const off = onChanged((ev) => {
|
||||
if (filterRef.current && !filterRef.current(ev)) return;
|
||||
window.clearTimeout(t);
|
||||
t = window.setTimeout(() => fnRef.current(), delay);
|
||||
});
|
||||
return () => {
|
||||
off();
|
||||
window.clearTimeout(t);
|
||||
};
|
||||
}, [delay]);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// Status labels, pills, job names and due dates. Copy from the old build where it had one.
|
||||
import type { PacketCard, PacketRead, PacketStatus, ProjectStatus, StageCounts } from "../api/types";
|
||||
|
||||
export const STATUS_LABEL: Record<PacketStatus, string> = {
|
||||
draft: "Ready to release",
|
||||
warehouse: "With warehouse",
|
||||
ready: "Ready to assign",
|
||||
assigned: "Sent to station",
|
||||
in_progress: "Working",
|
||||
review: "Supervisor review",
|
||||
qc: "Q.C. inspection",
|
||||
complete: "Routed",
|
||||
filed: "Filed in data book",
|
||||
};
|
||||
|
||||
export function statusLabel(s: string): string {
|
||||
return (STATUS_LABEL as Record<string, string>)[s] ?? s;
|
||||
}
|
||||
|
||||
/** The pill class for a status: "pill st-<status>". */
|
||||
export function pillClass(s: string): string {
|
||||
return `pill st-${s}`;
|
||||
}
|
||||
|
||||
export const SHOP: readonly PacketStatus[] = ["ready", "assigned", "in_progress", "review"];
|
||||
export const IN_SHOP_OR_QC: readonly PacketStatus[] = [...SHOP, "qc"];
|
||||
|
||||
/** "L999001 · WELD-PART". */
|
||||
export function jobName(p: Pick<PacketCard, "unit" | "op"> | Pick<PacketRead, "unit" | "op">): string {
|
||||
return p.op ? `${p.unit.number} · ${p.op}` : p.unit.number;
|
||||
}
|
||||
|
||||
export const PROJECT_STATUS_LABEL: Record<ProjectStatus, string> = { open: "Open", hold: "On hold", closed: "Closed" };
|
||||
|
||||
/** The old projPill colours: open green, on hold pink, closed grey. */
|
||||
export function projectPillClass(s: ProjectStatus): string {
|
||||
return `pill ${s === "open" ? "st-in_progress" : s === "hold" ? "st-review" : "st-filed"}`;
|
||||
}
|
||||
|
||||
/** A flag text that names a hard problem shows in pink, the rest in amber. */
|
||||
export function flagClass(flag: string): string {
|
||||
return /couldn't|not in|mismatch|No approved|Not released/i.test(flag) ? "due over" : "due soon";
|
||||
}
|
||||
|
||||
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
|
||||
/** The old dueInfo(): "Due Oct 20 '26 · 4 d left", with a class for colour. */
|
||||
export function dueInfo(due: string | null | undefined, closed = false, today: Date = new Date()): { txt: string; cls: string } {
|
||||
if (!due) return { txt: "No due date", cls: "due muted" };
|
||||
const d = new Date(`${due.slice(0, 10)}T12:00:00`);
|
||||
if (Number.isNaN(d.getTime())) return { txt: `Due ${due}`, cls: "due" };
|
||||
const noon = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12);
|
||||
const days = Math.round((d.getTime() - noon.getTime()) / 86_400_000);
|
||||
const lab = `${MONTHS[d.getMonth()] ?? ""} ${d.getDate()} '${String(d.getFullYear()).slice(2)}`;
|
||||
if (closed) return { txt: `Due ${lab}`, cls: "due muted" };
|
||||
if (days < 0) return { txt: `Due ${lab} · ${-days} d overdue`, cls: "due over" };
|
||||
if (days <= 7) return { txt: `Due ${lab} · ${days === 0 ? "today" : `${days} d left`}`, cls: "due soon" };
|
||||
return { txt: `Due ${lab} · ${days} d left`, cls: "due" };
|
||||
}
|
||||
|
||||
/** The open change orders on a card, as a count. */
|
||||
export function openCoCount(p: Pick<PacketCard, "open_cos">): number {
|
||||
return Array.isArray(p.open_cos) ? p.open_cos.length : Number(p.open_cos) || 0;
|
||||
}
|
||||
|
||||
/** Sum of the work orders' target hours. */
|
||||
export function targetHours(p: Pick<PacketRead, "work_orders">): number {
|
||||
return p.work_orders.reduce((a, w) => a + (Number(w.target_hrs) || 0), 0);
|
||||
}
|
||||
|
||||
/** "001" from "1", "7A" stays "7A". The server does the same. */
|
||||
export function normLot(v: string): string {
|
||||
const t = v.trim().toUpperCase();
|
||||
return /^\d{1,3}$/.test(t) ? t.padStart(3, "0") : t;
|
||||
}
|
||||
|
||||
export const RX_LOT = /^[A-Z0-9]{1,3}$/;
|
||||
export const RX_PROJECT = /^[A-Z0-9][A-Z0-9-]{0,19}$/;
|
||||
|
||||
/** Lots counting up from a numeric start: ("008", 3) -> 008, 009, 010. Null when the start is not digits. */
|
||||
export function lotSequence(start: string, count: number): string[] | null {
|
||||
const s = start.trim();
|
||||
if (!/^\d{1,3}$/.test(s) || !Number.isInteger(count) || count < 1) return null;
|
||||
const b = Number(s);
|
||||
if (b + count - 1 > 999) return null;
|
||||
return Array.from({ length: count }, (_, i) => String(b + i).padStart(3, "0"));
|
||||
}
|
||||
|
||||
/** The next free numeric lot after the ones in use. */
|
||||
export function nextLot(lots: readonly string[]): string {
|
||||
const nums = lots.filter((l) => /^\d+$/.test(l)).map(Number);
|
||||
const n = nums.length ? Math.max(...nums) + 1 : 1;
|
||||
return String(Math.min(n, 999)).padStart(3, "0");
|
||||
}
|
||||
|
||||
/** Packet counts with every stage present. */
|
||||
export function stageCounts(c: Partial<StageCounts> | undefined | null): StageCounts {
|
||||
return { draft: 0, warehouse: 0, shop: 0, qc: 0, complete: 0, filed: 0, total: 0, ...(c ?? {}) };
|
||||
}
|
||||
|
||||
/** Counts of a list of cards, the same way. */
|
||||
export function countCards(list: readonly Pick<PacketCard, "status">[]): StageCounts {
|
||||
const c = stageCounts(null);
|
||||
for (const p of list) {
|
||||
c.total++;
|
||||
if (p.status === "draft") c.draft++;
|
||||
else if (p.status === "warehouse") c.warehouse++;
|
||||
else if ((SHOP as readonly string[]).includes(p.status)) c.shop++;
|
||||
else if (p.status === "qc") c.qc++;
|
||||
else if (p.status === "complete") c.complete++;
|
||||
else if (p.status === "filed") c.filed++;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// pdf.js, loaded on first use. The worker is a same-origin file from the build (CSP worker-src 'self').
|
||||
import type { PDFDocumentProxy } from "pdfjs-dist";
|
||||
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
|
||||
|
||||
type PdfJs = typeof import("pdfjs-dist");
|
||||
|
||||
let lib: Promise<PdfJs> | null = null;
|
||||
|
||||
export function loadPdfJs(): Promise<PdfJs> {
|
||||
if (!lib) {
|
||||
lib = import("pdfjs-dist").then((m) => {
|
||||
m.GlobalWorkerOptions.workerSrc = workerUrl;
|
||||
return m;
|
||||
});
|
||||
lib.catch(() => {
|
||||
lib = null;
|
||||
});
|
||||
}
|
||||
return lib;
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
promise: Promise<PDFDocumentProxy>;
|
||||
destroy: () => void;
|
||||
}
|
||||
|
||||
const docs = new Map<string, Entry>();
|
||||
const MAX_DOCS = 6;
|
||||
|
||||
/**
|
||||
* Opens a PDF from a same-origin URL, once per URL. The session cookie rides along.
|
||||
* WebAssembly decoders stay off: the CSP does not allow wasm, and drawings rarely need them.
|
||||
*/
|
||||
export function openPdf(url: string): Promise<PDFDocumentProxy> {
|
||||
const hit = docs.get(url);
|
||||
if (hit) return hit.promise;
|
||||
let destroy = () => undefined as void;
|
||||
const promise = loadPdfJs().then((m) => {
|
||||
const task = m.getDocument({ url, withCredentials: true, useWasm: false });
|
||||
destroy = () => void task.destroy().catch(() => undefined);
|
||||
return task.promise;
|
||||
});
|
||||
const entry: Entry = { promise, destroy: () => destroy() };
|
||||
docs.set(url, entry);
|
||||
promise.catch(() => docs.delete(url));
|
||||
// Keep a few documents open; drop the oldest.
|
||||
while (docs.size > MAX_DOCS) {
|
||||
const first = docs.keys().next().value;
|
||||
if (first === undefined) break;
|
||||
docs.get(first)?.destroy();
|
||||
docs.delete(first);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { departmentsApi } from "../auth/api";
|
||||
import type { Department } from "../auth/types";
|
||||
import { useAuth } from "../auth/useAuth";
|
||||
|
||||
/** The shop departments from /api/departments, in code order. */
|
||||
export function useShopDepartments(): Department[] {
|
||||
const { departments } = useAuth();
|
||||
const [own, setOwn] = useState<Department[] | null>(null);
|
||||
useEffect(() => {
|
||||
if (departments.length) return;
|
||||
const ctl = new AbortController();
|
||||
departmentsApi
|
||||
.list(ctl.signal)
|
||||
.then((d) => {
|
||||
if (!ctl.signal.aborted) setOwn(Array.isArray(d) ? d : []);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => ctl.abort();
|
||||
}, [departments.length]);
|
||||
const list = departments.length ? departments : (own ?? []);
|
||||
return list.filter((d) => d.kind === "shop").sort((a, b) => a.code.localeCompare(b.code));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user