Compare commits
2 Commits
claude/mus
...
cpas-check
| Author | SHA1 | Date | |
|---|---|---|---|
| da36edbba6 | |||
|
|
d6585c01c6 |
4
.vscode/settings.json
vendored
Normal file
4
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"giteaActions.baseUrl": "https://git.alwisp.com",
|
||||||
|
"giteaActions.discovery.mode": "allAccessible"
|
||||||
|
}
|
||||||
294
AGENTS.md
294
AGENTS.md
@@ -1,294 +0,0 @@
|
|||||||
# AGENTS.md — CPAS Violation Tracker
|
|
||||||
|
|
||||||
Developer and AI agent guidance for working on this codebase. Read this before making changes.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Project Purpose
|
|
||||||
|
|
||||||
CPAS (Corrective & Progressive Accountability System) is an internal HR tool for documenting employee violations, managing disciplinary tier escalation via a rolling 90-day point system, and producing auditable PDF records. It is a single-container Docker app deployed on a trusted internal network.
|
|
||||||
|
|
||||||
**This is a compliance tool.** Data integrity, auditability, and reversibility are first-class concerns. Every architectural decision below exists for a reason.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Stack at a Glance
|
|
||||||
|
|
||||||
| Layer | Tech |
|
|
||||||
|---|---|
|
|
||||||
| Frontend | React 18 + Vite (SPA, served statically by Express) |
|
|
||||||
| Backend | Node.js + Express (REST API, `server.js`) |
|
|
||||||
| Database | SQLite via `better-sqlite3` (synchronous, WAL mode, FK enforcement) |
|
|
||||||
| PDF | Puppeteer + system Chromium (Alpine-bundled in Docker) |
|
|
||||||
| Styling | Inline React style objects; `client/src/styles/mobile.css` for breakpoints only |
|
|
||||||
| Deploy | Docker multi-stage build (Alpine); single container + volume mount at `/data` |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Repository Layout
|
|
||||||
|
|
||||||
```
|
|
||||||
cpas/
|
|
||||||
├── Dockerfile # Multi-stage: builder (Node+React) → production (Alpine+Chromium)
|
|
||||||
├── server.js # All API routes + audit helper; single Express entry point
|
|
||||||
├── db/
|
|
||||||
│ ├── schema.sql # Base table + view definitions (CREATE TABLE IF NOT EXISTS)
|
|
||||||
│ └── database.js # DB connection, WAL/FK pragmas, auto-migrations on startup
|
|
||||||
├── pdf/
|
|
||||||
│ ├── generator.js # Puppeteer launcher; --no-sandbox for Docker
|
|
||||||
│ └── template.js # HTML template builder; loads logo from disk
|
|
||||||
├── demo/ # Static stakeholder demo page served at /demo
|
|
||||||
│ └── index.html # Synthetic data, no live API calls; registered before SPA catch-all
|
|
||||||
├── client/
|
|
||||||
│ ├── vite.config.js
|
|
||||||
│ ├── src/
|
|
||||||
│ │ ├── App.jsx # Root component + AppFooter
|
|
||||||
│ │ ├── main.jsx # React DOM mount
|
|
||||||
│ │ ├── data/
|
|
||||||
│ │ │ ├── violations.js # Canonical violation type registry (type key → metadata)
|
|
||||||
│ │ │ └── departments.js # DEPARTMENTS constant; single source of truth
|
|
||||||
│ │ ├── hooks/
|
|
||||||
│ │ │ └── useEmployeeIntelligence.js # Score + history fetch hook
|
|
||||||
│ │ ├── components/ # One file per component; no barrel index
|
|
||||||
│ │ └── styles/
|
|
||||||
│ │ └── mobile.css # Media query overrides only; all other styles are inline
|
|
||||||
└── README.md / README_UNRAID_INSTALL.md
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Data Model & Compliance Rules
|
|
||||||
|
|
||||||
### Tables
|
|
||||||
|
|
||||||
| Table | Purpose |
|
|
||||||
|---|---|
|
|
||||||
| `employees` | id, name, department, supervisor, notes |
|
|
||||||
| `violations` | Full incident record; contains immutable scoring fields |
|
|
||||||
| `violation_resolutions` | Soft-delete records (resolution type, reason, resolver) |
|
|
||||||
| `violation_amendments` | Field-level diff per amendment (old → new, changed_by, timestamp) |
|
|
||||||
| `audit_log` | Append-only write action log; never delete from this table |
|
|
||||||
| `active_cpas_scores` | VIEW: SUM(points) for negated=0 AND incident_date >= 90 days |
|
|
||||||
|
|
||||||
### Immutable Fields (DO NOT allow amendment of these)
|
|
||||||
|
|
||||||
The following fields on `violations` are locked after submission. They are the basis for tier calculation and PDF accuracy. **Never expose them to amendment endpoints:**
|
|
||||||
|
|
||||||
- `points`
|
|
||||||
- `violation_type`
|
|
||||||
- `violation_name`
|
|
||||||
- `category`
|
|
||||||
- `incident_date`
|
|
||||||
- `prior_active_points` (snapshot at insert time)
|
|
||||||
- `prior_tier_label`
|
|
||||||
|
|
||||||
Amendable fields (non-scoring): `location`, `details`, `witness_name`, `acknowledged_by`, `acknowledged_date`
|
|
||||||
|
|
||||||
### Soft-Delete Pattern
|
|
||||||
|
|
||||||
Violations are **never hard-deleted** in normal workflow. Use the `negated` flag + `violation_resolutions` record. Hard delete is reserved for confirmed data-entry errors and requires explicit user confirmation in the UI.
|
|
||||||
|
|
||||||
### Prior-Points Snapshot
|
|
||||||
|
|
||||||
Every `INSERT` into `violations` must compute and store `prior_active_points` (the employee's current active score before this violation is added). This snapshot ensures PDFs always reflect the accurate historical tier state regardless of subsequent negate/restore actions.
|
|
||||||
|
|
||||||
### Audit Log
|
|
||||||
|
|
||||||
Every write action (employee created/edited/merged, violation logged/amended/negated/restored/deleted) must call the `audit()` helper in `server.js`. Never skip audit calls on write routes. The audit log is append-only — no UPDATE or DELETE against `audit_log`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## CPAS Tier System
|
|
||||||
|
|
||||||
These thresholds are the authoritative values. Any feature touching tiers must use them.
|
|
||||||
|
|
||||||
| Points | Tier | Label |
|
|
||||||
|---|---|---|
|
|
||||||
| 0–4 | 0-1 | Elite Standing |
|
|
||||||
| 5–9 | 1 | Realignment |
|
|
||||||
| 10–14 | 2 | Administrative Lockdown |
|
|
||||||
| 15–19 | 3 | Verification |
|
|
||||||
| 20–24 | 4 | Risk Mitigation |
|
|
||||||
| 25–29 | 5 | Final Decision |
|
|
||||||
| 30+ | 6 | Separation |
|
|
||||||
|
|
||||||
The canonical tier logic lives in `client/src/components/CpasBadge.jsx` (`TIERS` array, `getTier()`, `getNextTier()`). Do not duplicate this logic elsewhere — import from `CpasBadge`.
|
|
||||||
|
|
||||||
The 90-day rolling window is computed by the `active_cpas_scores` view. This view is **dropped and recreated** in `database.js` on every startup to ensure it always reflects the correct `negated=0` filter.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Violation Type Registry
|
|
||||||
|
|
||||||
All violation types are defined in `client/src/data/violations.js` as `violationData`. Each entry includes:
|
|
||||||
|
|
||||||
```js
|
|
||||||
{
|
|
||||||
name: string, // Display name
|
|
||||||
category: string, // Grouping for UI display
|
|
||||||
minPoints: number, // Slider minimum
|
|
||||||
maxPoints: number, // Slider maximum (min === max means fixed, no slider)
|
|
||||||
chapter: string, // Policy chapter reference
|
|
||||||
fields: string[], // Which context fields to show ('time', 'minutes', 'amount', 'location', 'description')
|
|
||||||
description: string, // Plain-language definition shown in UI
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
To add a new violation type: add an entry to `violationData` with a unique camelCase key. Do not add new categories without confirming with the project owner — categories appear in UI groupings.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Coding Standards
|
|
||||||
|
|
||||||
### Backend (`server.js`)
|
|
||||||
|
|
||||||
- Use `better-sqlite3` synchronous API. No async DB calls. This is intentional — it simplifies route handlers and matches Express's sync error handling.
|
|
||||||
- All prepared statements use positional `?` parameters. Never interpolate user input into SQL strings.
|
|
||||||
- Every POST/PUT/PATCH/DELETE route must:
|
|
||||||
1. Validate required inputs and return `400` with a descriptive `{ error: '...' }` body on failure.
|
|
||||||
2. Call `audit()` on success.
|
|
||||||
3. Return `{ error: '...' }` (not HTML) on all error paths.
|
|
||||||
- Group routes by resource (Employees, Violations, Dashboard, Audit). Match the existing comment banner style: `// ── Resource Name ───`.
|
|
||||||
- Do not add authentication middleware. This runs on a trusted internal network by design.
|
|
||||||
|
|
||||||
### Frontend (React)
|
|
||||||
|
|
||||||
- **Styling**: Use inline style objects defined as a `const s = { ... }` block at the top of each component file. Do not add CSS classes or CSS modules — except for responsive breakpoints which go in `mobile.css`.
|
|
||||||
- **Data constants**: Import violation types from `../data/violations`, departments from `../data/departments`, tier logic from `./CpasBadge`. Do not hardcode these values in components.
|
|
||||||
- **Toasts**: Use `useToast()` from `ToastProvider` for all user-facing feedback. Do not use `alert()` or `console.log` for user messages.
|
|
||||||
- **HTTP**: Use `axios` (already imported in form/modal components). Do not introduce `fetch` unless there is a compelling reason — keep it consistent.
|
|
||||||
- **State**: Prefer local `useState` over lifting state unless data is needed by multiple unrelated components. The only global context is `ToastProvider`.
|
|
||||||
- **Mobile**: Test layout at 768px breakpoint. Use the `isMobile` media query pattern already in `Dashboard.jsx` / `DashboardMobile.jsx`. Add breakpoint rules to `mobile.css`, not inline styles.
|
|
||||||
- **Component files**: One component per file. Name the file to match the export. No barrel `index.js` files.
|
|
||||||
|
|
||||||
### Database Migrations
|
|
||||||
|
|
||||||
New columns are added via the auto-migration pattern in `database.js`. Do not modify `schema.sql` for columns that already exist in production. Instead:
|
|
||||||
|
|
||||||
```js
|
|
||||||
// Example: adding a new column to violations
|
|
||||||
const cols = db.prepare('PRAGMA table_info(violations)').all().map(c => c.name);
|
|
||||||
if (!cols.includes('new_column')) db.exec("ALTER TABLE violations ADD COLUMN new_column TEXT");
|
|
||||||
```
|
|
||||||
|
|
||||||
Add a comment describing the feature the column enables. `schema.sql` is only for base tables — use it only for brand-new tables.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Schema Changes: Decision Checklist
|
|
||||||
|
|
||||||
Before adding a column or table, answer:
|
|
||||||
|
|
||||||
1. **Does it affect scoring?** If yes, it must be immutable after insert and included in `prior_active_points` computation logic.
|
|
||||||
2. **Does it need audit trail?** If it tracks a change to an existing record, add a corresponding entry pattern to `violation_amendments` or `audit_log`.
|
|
||||||
3. **Is it soft-deletable?** Prefer `negated`/flag patterns over hard deletes for anything HR might need to reverse.
|
|
||||||
4. **Does it appear on PDFs?** Update `pdf/template.js` to reflect it. Test PDF output after schema changes.
|
|
||||||
5. **Does `active_cpas_scores` view need updating?** If the new column affects point calculations, update the view recreation block in `database.js`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## PDF Generation
|
|
||||||
|
|
||||||
- PDFs are generated on-demand via `GET /api/violations/:id/pdf`. No pre-caching.
|
|
||||||
- Template is built in `pdf/template.js`. It receives the full violation + employee record. Logo is loaded from disk at startup and embedded as base64.
|
|
||||||
- Puppeteer launches with `--no-sandbox --disable-setuid-sandbox` (required for Docker; safe in this deployment context).
|
|
||||||
- Acknowledgment rendering: if `acknowledged_by` is set, show name + date in signature block. If not, render blank wet-ink signature lines.
|
|
||||||
- After any schema change that adds user-visible fields, update the template to include the new field where appropriate.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Development Workflow
|
|
||||||
|
|
||||||
### Local Development (without Docker)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Terminal 1 — backend
|
|
||||||
npm install
|
|
||||||
node server.js # Serves API on :3001 and client/dist statically
|
|
||||||
|
|
||||||
# Terminal 2 — frontend (hot reload)
|
|
||||||
cd client
|
|
||||||
npm install
|
|
||||||
npm run dev # Vite dev server on :5173 (proxy to :3001 configured in vite.config.js)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Build & Deploy
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Build Docker image (compiles React inside container)
|
|
||||||
docker build -t cpas .
|
|
||||||
|
|
||||||
# Run (local)
|
|
||||||
docker run -d --name cpas -p 3001:3001 -v cpas-data:/data cpas
|
|
||||||
|
|
||||||
# Unraid: build → save → transfer → load → run with --pids-limit 2048
|
|
||||||
# See README_UNRAID_INSTALL.md for full Unraid instructions
|
|
||||||
```
|
|
||||||
|
|
||||||
**Unraid PID limit is critical.** Chromium spawns many child processes for PDF generation. Always include `--pids-limit 2048` on Unraid containers or PDF generation will fail silently.
|
|
||||||
|
|
||||||
### Health Check
|
|
||||||
|
|
||||||
`GET /api/health` returns `{ status: 'ok', timestamp, version }`. The `version` field is populated by the Dockerfile at build time from git commit SHA. In local dev it returns `{ sha: 'dev' }` — this is expected.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Forward-Thinking Development Guidelines
|
|
||||||
|
|
||||||
### Adding New Features
|
|
||||||
|
|
||||||
- **Score-affecting logic belongs in SQL**, not JavaScript. The `active_cpas_scores` view is the single source of truth for point totals. If you need a new score variant (e.g., 30-day window, category-filtered), add a new SQL view — don't compute it in a route handler.
|
|
||||||
- **New violation fields**: Add to `schema.sql` for fresh installs AND to the migration block in `database.js` for existing databases. Both are required.
|
|
||||||
- **Reporting features**: Future aggregate queries should join against `active_cpas_scores` view and `audit_log` rather than re-implementing point logic. Structure new API endpoints under `/api/reports/` namespace.
|
|
||||||
- **Notifications/alerts**: Any future alerting feature (email, Slack) should read from `audit_log` or query `active_cpas_scores` — do not add side effects directly into violation insert routes.
|
|
||||||
- **Authentication**: If auth is ever added, implement it as Express middleware applied globally before all `/api` routes. Do not add per-route auth checks. Session data (user identity) should flow into `performed_by` fields on audit and amendment records.
|
|
||||||
- **Multi-tenant / multi-site**: The schema is single-tenant. If site isolation is ever needed, add a `site_id` foreign key to `employees` and `violations` as a migration column, then scope all queries with a `WHERE site_id = ?` clause.
|
|
||||||
|
|
||||||
### What NOT to Do
|
|
||||||
|
|
||||||
- Do not compute active CPAS scores in JavaScript by summing violations client-side. Always fetch from the `active_cpas_scores` view.
|
|
||||||
- Do not modify `prior_active_points` after a violation is inserted. It is a historical snapshot, not a live value.
|
|
||||||
- Do not add columns to `audit_log`. It is append-only with a fixed schema.
|
|
||||||
- Do not add a framework or ORM. Raw SQL with prepared statements is intentional — it keeps the query behavior explicit and the dependency surface small.
|
|
||||||
- Do not add a build step beyond `vite build`. The backend is plain CommonJS `require()`; do not transpile it.
|
|
||||||
- Do not use `alert()`, `console.log` for user messages, or `document.querySelector` inside React components.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Documentation Standards
|
|
||||||
|
|
||||||
### Code Comments
|
|
||||||
|
|
||||||
- Comment **why**, not **what**. If the reason for a decision is not obvious from the code, explain it.
|
|
||||||
- Use the existing banner style for section groupings in `server.js`:
|
|
||||||
```js
|
|
||||||
// ── Section Name ─────────────────────────────────────────────────────────────
|
|
||||||
```
|
|
||||||
- Mark non-obvious schema columns with inline SQL comments (see `schema.sql` for examples).
|
|
||||||
- When adding a migration block, include a comment naming the feature it enables.
|
|
||||||
|
|
||||||
### In-App Documentation
|
|
||||||
|
|
||||||
The `ReadmeModal.jsx` component renders an admin reference panel accessible via the `? Docs` button. When adding a significant new feature:
|
|
||||||
- Add it to the feature map section of the docs modal.
|
|
||||||
- Update the tier system table if thresholds change.
|
|
||||||
- Move completed roadmap items from the "Proposed" section to the "Completed" section.
|
|
||||||
|
|
||||||
### README
|
|
||||||
|
|
||||||
Update `README.md` when:
|
|
||||||
- A new environment variable is introduced.
|
|
||||||
- The Docker run command changes (new volume, port, or flag).
|
|
||||||
- A new top-level feature is added that HR administrators need to know about.
|
|
||||||
|
|
||||||
Do not add implementation details to README — that belongs in code comments or AGENTS.md.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Constraints & Non-Goals
|
|
||||||
|
|
||||||
- **No authentication.** This is intentional. The app runs on a trusted LAN. Do not add auth without explicit direction from the project owner.
|
|
||||||
- **No external dependencies beyond what's in `package.json`.** Avoid introducing new npm packages unless they solve a clearly scoped problem. Prefer using existing stack capabilities.
|
|
||||||
- **No client-side routing library.** Navigation between Violation Form, Dashboard, and modals is handled via `App.jsx` state (`view` prop). Do not introduce React Router unless the navigation model meaningfully grows beyond 3–4 views.
|
|
||||||
- **No test suite currently.** If adding tests, use Vitest for frontend and a lightweight assertion library for backend routes. Do not add a full testing framework without discussion.
|
|
||||||
- **SQLite only.** Do not introduce Postgres, Redis, or other datastores. The single-file DB on a Docker volume is the correct solution for this scale.
|
|
||||||
@@ -6,6 +6,8 @@ import ToastProvider from './components/ToastProvider';
|
|||||||
import './styles/mobile.css';
|
import './styles/mobile.css';
|
||||||
|
|
||||||
const REPO_URL = 'https://git.alwisp.com/jason/cpas';
|
const REPO_URL = 'https://git.alwisp.com/jason/cpas';
|
||||||
|
// TODO [CLEANUP #18]: DevTicker is a dev vanity widget that ships to prod.
|
||||||
|
// Either gate with `import.meta.env.DEV` or remove from the footer.
|
||||||
const PROJECT_START = new Date('2026-03-06T11:33:32-06:00');
|
const PROJECT_START = new Date('2026-03-06T11:33:32-06:00');
|
||||||
|
|
||||||
function elapsed(from) {
|
function elapsed(from) {
|
||||||
@@ -101,7 +103,9 @@ const tabs = [
|
|||||||
{ id: 'violation', label: '+ New Violation' },
|
{ id: 'violation', label: '+ New Violation' },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Responsive utility hook
|
// TODO [MAJOR #8]: Move to src/hooks/useMediaQuery.js — this hook is duplicated
|
||||||
|
// verbatim in Dashboard.jsx. Also remove `matches` from the useEffect dep array
|
||||||
|
// (it changes inside the effect, which can cause a loop on strict-mode mount).
|
||||||
function useMediaQuery(query) {
|
function useMediaQuery(query) {
|
||||||
const [matches, setMatches] = useState(false);
|
const [matches, setMatches] = useState(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -237,6 +241,8 @@ export default function App() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ToastProvider>
|
<ToastProvider>
|
||||||
|
{/* TODO [MAJOR #9]: Inline <style> tags re-inject on every render and duplicate
|
||||||
|
the same block from Dashboard.jsx. Move all shared mobile CSS to mobile.css */}
|
||||||
<style>{mobileStyles}</style>
|
<style>{mobileStyles}</style>
|
||||||
<div style={s.app}>
|
<div style={s.app}>
|
||||||
<nav style={s.nav} className="app-nav">
|
<nav style={s.nav} className="app-nav">
|
||||||
@@ -248,7 +254,8 @@ export default function App() {
|
|||||||
<div className="nav-tabs">
|
<div className="nav-tabs">
|
||||||
{tabs.map(t => (
|
{tabs.map(t => (
|
||||||
<button key={t.id} style={s.tab(tab === t.id)} className="nav-tab" onClick={() => setTab(t.id)}>
|
<button key={t.id} style={s.tab(tab === t.id)} className="nav-tab" onClick={() => setTab(t.id)}>
|
||||||
{isMobile ? t.label.replace('📊 ', '📊 ').replace('+ New ', '+ ') : t.label}
|
{/* TODO [MINOR #17]: first .replace('📊 ', '📊 ') replaces string with itself — no-op. Remove it. */}
|
||||||
|
{isMobile ? t.label.replace('📊 ', '📊 ').replace('+ New ', '+ ') : t.label}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -112,6 +112,9 @@ export default function AuditLog({ onClose }) {
|
|||||||
const [filterAction, setFilterAction] = useState('');
|
const [filterAction, setFilterAction] = useState('');
|
||||||
const LIMIT = 50;
|
const LIMIT = 50;
|
||||||
|
|
||||||
|
// TODO [MAJOR #5]: `offset` in useCallback deps causes the callback to be
|
||||||
|
// re-created on each load-more, which triggers the filterType/filterAction
|
||||||
|
// useEffect unexpectedly. Track offset in a useRef instead.
|
||||||
const load = useCallback((reset = false) => {
|
const load = useCallback((reset = false) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const o = reset ? 0 : offset;
|
const o = reset ? 0 : offset;
|
||||||
@@ -121,7 +124,8 @@ export default function AuditLog({ onClose }) {
|
|||||||
axios.get('/api/audit', { params })
|
axios.get('/api/audit', { params })
|
||||||
.then(r => {
|
.then(r => {
|
||||||
const data = r.data;
|
const data = r.data;
|
||||||
// Client-side action filter (cheap enough at this scale)
|
// TODO [MINOR]: client-side action filter means server still fetches LIMIT
|
||||||
|
// rows before filtering — add server-side `action` param to /api/audit.
|
||||||
const filtered = filterAction ? data.filter(e => e.action === filterAction) : data;
|
const filtered = filterAction ? data.filter(e => e.action === filterAction) : data;
|
||||||
setEntries(prev => reset ? filtered : [...prev, ...filtered]);
|
setEntries(prev => reset ? filtered : [...prev, ...filtered]);
|
||||||
setHasMore(data.length === LIMIT);
|
setHasMore(data.length === LIMIT);
|
||||||
|
|||||||
@@ -29,7 +29,8 @@ function isAtRisk(points) {
|
|||||||
return boundary !== null && (boundary - points) <= AT_RISK_THRESHOLD;
|
return boundary !== null && (boundary - points) <= AT_RISK_THRESHOLD;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Media query hook
|
// TODO [MAJOR #8]: Same hook is defined in App.jsx — extract to src/hooks/useMediaQuery.js
|
||||||
|
// Also: `matches` in the dep array can cause a loop on strict-mode initial mount.
|
||||||
function useMediaQuery(query) {
|
function useMediaQuery(query) {
|
||||||
const [matches, setMatches] = useState(false);
|
const [matches, setMatches] = useState(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -186,6 +187,7 @@ export default function Dashboard() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
{/* TODO [MAJOR #9]: Same mobileStyles block exists in App.jsx. Move to mobile.css */}
|
||||||
<style>{mobileStyles}</style>
|
<style>{mobileStyles}</style>
|
||||||
<div style={s.wrap} className="dashboard-wrap">
|
<div style={s.wrap} className="dashboard-wrap">
|
||||||
<div style={s.header} className="dashboard-header">
|
<div style={s.header} className="dashboard-header">
|
||||||
|
|||||||
@@ -103,13 +103,12 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
|||||||
const load = useCallback(() => {
|
const load = useCallback(() => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
Promise.all([
|
Promise.all([
|
||||||
axios.get('/api/employees'),
|
axios.get(`/api/employees/${employeeId}`),
|
||||||
axios.get(`/api/employees/${employeeId}/score`),
|
axios.get(`/api/employees/${employeeId}/score`),
|
||||||
axios.get(`/api/violations/employee/${employeeId}?limit=100`),
|
axios.get(`/api/violations/employee/${employeeId}?limit=100`),
|
||||||
])
|
])
|
||||||
.then(([empRes, scoreRes, violRes]) => {
|
.then(([empRes, scoreRes, violRes]) => {
|
||||||
const emp = empRes.data.find((e) => e.id === employeeId);
|
setEmployee(empRes.data || null);
|
||||||
setEmployee(emp || null);
|
|
||||||
setScore(scoreRes.data);
|
setScore(scoreRes.data);
|
||||||
setViolations(violRes.data);
|
setViolations(violRes.data);
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
import { useToast } from './ToastProvider';
|
||||||
|
|
||||||
const s = {
|
const s = {
|
||||||
wrapper: { marginTop: '20px' },
|
wrapper: { marginTop: '20px' },
|
||||||
@@ -53,14 +54,23 @@ export default function EmployeeNotes({ employeeId, initialNotes, onSaved }) {
|
|||||||
const [draft, setDraft] = useState(initialNotes || '');
|
const [draft, setDraft] = useState(initialNotes || '');
|
||||||
const [saved, setSaved] = useState(initialNotes || '');
|
const [saved, setSaved] = useState(initialNotes || '');
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [saveErr, setSaveErr] = useState('');
|
||||||
|
|
||||||
|
const toast = useToast();
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
|
setSaveErr('');
|
||||||
try {
|
try {
|
||||||
await axios.patch(`/api/employees/${employeeId}/notes`, { notes: draft });
|
await axios.patch(`/api/employees/${employeeId}/notes`, { notes: draft });
|
||||||
setSaved(draft);
|
setSaved(draft);
|
||||||
setEditing(false);
|
setEditing(false);
|
||||||
if (onSaved) onSaved(draft);
|
if (onSaved) onSaved(draft);
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err.response?.data?.error || err.message || 'Failed to save notes';
|
||||||
|
setSaveErr(msg);
|
||||||
|
toast.error('Notes save failed: ' + msg);
|
||||||
|
// Keep editing open so the user doesn't lose their changes
|
||||||
} finally {
|
} finally {
|
||||||
setSaving(false);
|
setSaving(false);
|
||||||
}
|
}
|
||||||
@@ -130,6 +140,11 @@ export default function EmployeeNotes({ employeeId, initialNotes, onSaved }) {
|
|||||||
placeholder="Free-text notes — one per line or comma-separated. Does not affect CPAS scoring."
|
placeholder="Free-text notes — one per line or comma-separated. Does not affect CPAS scoring."
|
||||||
autoFocus
|
autoFocus
|
||||||
/>
|
/>
|
||||||
|
{saveErr && (
|
||||||
|
<div style={{ fontSize: '12px', color: '#ff7070', marginBottom: '6px' }}>
|
||||||
|
✗ {saveErr}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div style={s.actions}>
|
<div style={s.actions}>
|
||||||
<button style={s.saveBtn} onClick={handleSave} disabled={saving}>
|
<button style={s.saveBtn} onClick={handleSave} disabled={saving}>
|
||||||
{saving ? 'Saving…' : 'Save Notes'}
|
{saving ? 'Saving…' : 'Save Notes'}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
|
||||||
// Tier thresholds used to compute what tier an employee would drop to
|
// TODO [MINOR #10]: This TIER_THRESHOLDS array duplicates tiers defined in CpasBadge.jsx
|
||||||
// after a given violation rolls off.
|
// and Dashboard.jsx. Export TIERS from CpasBadge.jsx and import here instead.
|
||||||
const TIER_THRESHOLDS = [
|
const TIER_THRESHOLDS = [
|
||||||
{ min: 30, label: 'Separation', color: '#ff1744' },
|
{ min: 30, label: 'Separation', color: '#ff1744' },
|
||||||
{ min: 25, label: 'Final Decision', color: '#ff6d00' },
|
{ min: 25, label: 'Final Decision', color: '#ff6d00' },
|
||||||
|
|||||||
@@ -78,14 +78,12 @@ export default function NegateModal({ violation, onConfirm, onCancel }) {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// FIX: overlay click only closes on backdrop, NOT modal children
|
|
||||||
const handleOverlayClick = (e) => {
|
const handleOverlayClick = (e) => {
|
||||||
if (e.target === e.currentTarget && onCancel) onCancel();
|
if (e.target === e.currentTarget && onCancel) onCancel();
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={s.overlay} onClick={handleOverlayClick}>
|
<div style={s.overlay} onClick={handleOverlayClick}>
|
||||||
{/* FIX: stopPropagation prevents modal clicks from bubbling to overlay */}
|
|
||||||
<div style={s.modal} onClick={(e) => e.stopPropagation()}>
|
<div style={s.modal} onClick={(e) => e.stopPropagation()}>
|
||||||
|
|
||||||
<div style={s.header}>
|
<div style={s.header}>
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import React, { useState, useEffect, useMemo } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import { violationData, violationGroups } from '../data/violations';
|
import { violationData, violationGroups } from '../data/violations';
|
||||||
import useEmployeeIntelligence from '../hooks/useEmployeeIntelligence';
|
import useEmployeeIntelligence from '../hooks/useEmployeeIntelligence';
|
||||||
import CpasBadge from './CpasBadge';
|
import CpasBadge from './CpasBadge';
|
||||||
import TierWarning from './TierWarning';
|
import TierWarning from './TierWarning';
|
||||||
import ViolationHistory from './ViolationHistory';
|
import ViolationHistory from './ViolationHistory';
|
||||||
import ViolationTypeModal from './ViolationTypeModal';
|
|
||||||
import { useToast } from './ToastProvider';
|
import { useToast } from './ToastProvider';
|
||||||
import { DEPARTMENTS } from '../data/departments';
|
import { DEPARTMENTS } from '../data/departments';
|
||||||
|
|
||||||
@@ -36,6 +35,7 @@ const s = {
|
|||||||
const EMPTY_FORM = {
|
const EMPTY_FORM = {
|
||||||
employeeId: '', employeeName: '', department: '', supervisor: '', witnessName: '',
|
employeeId: '', employeeName: '', department: '', supervisor: '', witnessName: '',
|
||||||
violationType: '', incidentDate: '', incidentTime: '',
|
violationType: '', incidentDate: '', incidentTime: '',
|
||||||
|
// TODO [MAJOR #6]: `amount` and `minutesLate` are rendered but never sent to the API
|
||||||
amount: '', minutesLate: '', location: '', additionalDetails: '', points: 1,
|
amount: '', minutesLate: '', location: '', additionalDetails: '', points: 1,
|
||||||
acknowledgedBy: '', acknowledgedDate: '',
|
acknowledgedBy: '', acknowledgedDate: '',
|
||||||
};
|
};
|
||||||
@@ -44,75 +44,17 @@ export default function ViolationForm() {
|
|||||||
const [employees, setEmployees] = useState([]);
|
const [employees, setEmployees] = useState([]);
|
||||||
const [form, setForm] = useState(EMPTY_FORM);
|
const [form, setForm] = useState(EMPTY_FORM);
|
||||||
const [violation, setViolation] = useState(null);
|
const [violation, setViolation] = useState(null);
|
||||||
const [status, setStatus] = useState(null);
|
const [status, setStatus] = useState(null); // TODO [MAJOR #7]: remove — toast covers this
|
||||||
const [lastViolId, setLastViolId] = useState(null);
|
const [lastViolId, setLastViolId] = useState(null);
|
||||||
const [pdfLoading, setPdfLoading] = useState(false);
|
const [pdfLoading, setPdfLoading] = useState(false);
|
||||||
const [customTypes, setCustomTypes] = useState([]);
|
|
||||||
const [typeModal, setTypeModal] = useState(null); // null | 'create' | <editing object>
|
|
||||||
|
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const intel = useEmployeeIntelligence(form.employeeId || null);
|
const intel = useEmployeeIntelligence(form.employeeId || null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
axios.get('/api/employees').then(r => setEmployees(r.data)).catch(() => {});
|
axios.get('/api/employees').then(r => setEmployees(r.data)).catch(() => {});
|
||||||
fetchCustomTypes();
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const fetchCustomTypes = () => {
|
|
||||||
axios.get('/api/violation-types').then(r => setCustomTypes(r.data)).catch(() => {});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Build a map of custom types keyed by type_key for fast lookup
|
|
||||||
const customTypeMap = useMemo(() =>
|
|
||||||
Object.fromEntries(customTypes.map(t => [t.type_key, t])),
|
|
||||||
[customTypes]
|
|
||||||
);
|
|
||||||
|
|
||||||
// Merge hardcoded and custom violation groups for the dropdown
|
|
||||||
const mergedGroups = useMemo(() => {
|
|
||||||
const groups = {};
|
|
||||||
// Start with all hardcoded groups
|
|
||||||
Object.entries(violationGroups).forEach(([cat, items]) => {
|
|
||||||
groups[cat] = [...items];
|
|
||||||
});
|
|
||||||
// Add custom types into their respective category, or create new group
|
|
||||||
customTypes.forEach(t => {
|
|
||||||
const item = {
|
|
||||||
key: t.type_key,
|
|
||||||
name: t.name,
|
|
||||||
category: t.category,
|
|
||||||
minPoints: t.min_points,
|
|
||||||
maxPoints: t.max_points,
|
|
||||||
chapter: t.chapter || '',
|
|
||||||
description: t.description || '',
|
|
||||||
fields: t.fields,
|
|
||||||
isCustom: true,
|
|
||||||
customId: t.id,
|
|
||||||
};
|
|
||||||
if (!groups[t.category]) groups[t.category] = [];
|
|
||||||
groups[t.category].push(item);
|
|
||||||
});
|
|
||||||
return groups;
|
|
||||||
}, [customTypes]);
|
|
||||||
|
|
||||||
// Resolve a violation definition from either the hardcoded registry or custom types
|
|
||||||
const resolveViolation = key => {
|
|
||||||
if (violationData[key]) return violationData[key];
|
|
||||||
const ct = customTypeMap[key];
|
|
||||||
if (ct) return {
|
|
||||||
name: ct.name,
|
|
||||||
category: ct.category,
|
|
||||||
chapter: ct.chapter || '',
|
|
||||||
description: ct.description || '',
|
|
||||||
minPoints: ct.min_points,
|
|
||||||
maxPoints: ct.max_points,
|
|
||||||
fields: ct.fields,
|
|
||||||
isCustom: true,
|
|
||||||
customId: ct.id,
|
|
||||||
};
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!violation || !form.violationType) return;
|
if (!violation || !form.violationType) return;
|
||||||
const allTime = intel.countsAllTime[form.violationType];
|
const allTime = intel.countsAllTime[form.violationType];
|
||||||
@@ -131,7 +73,7 @@ export default function ViolationForm() {
|
|||||||
|
|
||||||
const handleViolationChange = e => {
|
const handleViolationChange = e => {
|
||||||
const key = e.target.value;
|
const key = e.target.value;
|
||||||
const v = resolveViolation(key);
|
const v = violationData[key] || null;
|
||||||
setViolation(v);
|
setViolation(v);
|
||||||
setForm(prev => ({ ...prev, violationType: key, points: v ? v.minPoints : 1 }));
|
setForm(prev => ({ ...prev, violationType: key, points: v ? v.minPoints : 1 }));
|
||||||
};
|
};
|
||||||
@@ -167,6 +109,7 @@ export default function ViolationForm() {
|
|||||||
setEmployees(empList.data);
|
setEmployees(empList.data);
|
||||||
|
|
||||||
toast.success(`Violation #${newId} recorded — click Download PDF to save the document.`);
|
toast.success(`Violation #${newId} recorded — click Download PDF to save the document.`);
|
||||||
|
// TODO [MAJOR #7]: remove setStatus — toast above already covers this message
|
||||||
setStatus({ ok: true, msg: `✓ Violation #${newId} recorded — click Download PDF to save the document.` });
|
setStatus({ ok: true, msg: `✓ Violation #${newId} recorded — click Download PDF to save the document.` });
|
||||||
setForm(EMPTY_FORM);
|
setForm(EMPTY_FORM);
|
||||||
setViolation(null);
|
setViolation(null);
|
||||||
@@ -255,37 +198,16 @@ export default function ViolationForm() {
|
|||||||
<div style={s.grid}>
|
<div style={s.grid}>
|
||||||
|
|
||||||
<div style={{ ...s.item, ...s.fullCol }}>
|
<div style={{ ...s.item, ...s.fullCol }}>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '5px' }}>
|
<label style={s.label}>Violation Type:</label>
|
||||||
<label style={{ ...s.label, marginBottom: 0 }}>Violation Type:</label>
|
|
||||||
<div style={{ display: 'flex', gap: '6px' }}>
|
|
||||||
{violation?.isCustom && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setTypeModal(customTypeMap[form.violationType])}
|
|
||||||
style={{ fontSize: '11px', padding: '3px 10px', borderRadius: '4px', border: '1px solid #4caf50', background: '#1a2e1a', color: '#4caf50', cursor: 'pointer', fontWeight: 600 }}
|
|
||||||
>
|
|
||||||
Edit Type
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setTypeModal('create')}
|
|
||||||
style={{ fontSize: '11px', padding: '3px 10px', borderRadius: '4px', border: '1px solid #d4af37', background: '#181200', color: '#ffd666', cursor: 'pointer', fontWeight: 600 }}
|
|
||||||
title="Add a new custom violation type"
|
|
||||||
>
|
|
||||||
+ Add Type
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<select style={s.input} value={form.violationType} onChange={handleViolationChange} required>
|
<select style={s.input} value={form.violationType} onChange={handleViolationChange} required>
|
||||||
<option value="">-- Select Violation Type --</option>
|
<option value="">-- Select Violation Type --</option>
|
||||||
{Object.entries(mergedGroups).map(([group, items]) => (
|
{Object.entries(violationGroups).map(([group, items]) => (
|
||||||
<optgroup key={group} label={group}>
|
<optgroup key={group} label={group}>
|
||||||
{items.map(v => {
|
{items.map(v => {
|
||||||
const prior = priorCount90(v.key);
|
const prior = priorCount90(v.key);
|
||||||
return (
|
return (
|
||||||
<option key={v.key} value={v.key}>
|
<option key={v.key} value={v.key}>
|
||||||
{v.name}{v.isCustom ? ' ✦' : ''}{prior > 0 ? ` ★ ${prior}x in 90 days` : ''}
|
{v.name}{prior > 0 ? ` ★ ${prior}x in 90 days` : ''}
|
||||||
</option>
|
</option>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
@@ -296,11 +218,6 @@ export default function ViolationForm() {
|
|||||||
{violation && (
|
{violation && (
|
||||||
<div style={s.contextBox}>
|
<div style={s.contextBox}>
|
||||||
<strong>{violation.name}</strong>
|
<strong>{violation.name}</strong>
|
||||||
{violation.isCustom && (
|
|
||||||
<span style={{ display: 'inline-block', marginLeft: '8px', padding: '1px 7px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#1a2e1a', color: '#4caf50', border: '1px solid #4caf50' }}>
|
|
||||||
Custom
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{isRepeat(form.violationType) && form.employeeId && (
|
{isRepeat(form.violationType) && form.employeeId && (
|
||||||
<span style={s.repeatBadge}>
|
<span style={s.repeatBadge}>
|
||||||
★ Repeat — {intel.countsAllTime[form.violationType]?.count}x prior
|
★ Repeat — {intel.countsAllTime[form.violationType]?.count}x prior
|
||||||
@@ -433,40 +350,6 @@ export default function ViolationForm() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{typeModal && (
|
|
||||||
<ViolationTypeModal
|
|
||||||
editing={typeModal === 'create' ? null : typeModal}
|
|
||||||
onClose={() => setTypeModal(null)}
|
|
||||||
onSaved={saved => {
|
|
||||||
fetchCustomTypes();
|
|
||||||
setTypeModal(null);
|
|
||||||
// Auto-select the newly created type; do nothing on delete (saved === null)
|
|
||||||
if (saved) {
|
|
||||||
const v = {
|
|
||||||
name: saved.name,
|
|
||||||
category: saved.category,
|
|
||||||
chapter: saved.chapter || '',
|
|
||||||
description: saved.description || '',
|
|
||||||
minPoints: saved.min_points,
|
|
||||||
maxPoints: saved.max_points,
|
|
||||||
fields: saved.fields,
|
|
||||||
isCustom: true,
|
|
||||||
customId: saved.id,
|
|
||||||
};
|
|
||||||
setViolation(v);
|
|
||||||
setForm(prev => ({ ...prev, violationType: saved.type_key, points: saved.min_points }));
|
|
||||||
} else {
|
|
||||||
// Type was deleted — clear selection if it was the active type
|
|
||||||
setForm(prev => {
|
|
||||||
const stillExists = violationData[prev.violationType] || false;
|
|
||||||
return stillExists ? prev : { ...prev, violationType: '', points: 1 };
|
|
||||||
});
|
|
||||||
setViolation(null);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,292 +0,0 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
|
||||||
import axios from 'axios';
|
|
||||||
import { useToast } from './ToastProvider';
|
|
||||||
|
|
||||||
// Existing hardcoded categories — used for datalist autocomplete
|
|
||||||
const KNOWN_CATEGORIES = [
|
|
||||||
'Attendance & Punctuality',
|
|
||||||
'Administrative Integrity',
|
|
||||||
'Financial Stewardship',
|
|
||||||
'Operational Response',
|
|
||||||
'Professional Conduct',
|
|
||||||
'Work From Home',
|
|
||||||
'Safety & Security',
|
|
||||||
];
|
|
||||||
|
|
||||||
const CONTEXT_FIELDS = [
|
|
||||||
{ key: 'time', label: 'Incident Time' },
|
|
||||||
{ key: 'minutes', label: 'Minutes Late' },
|
|
||||||
{ key: 'amount', label: 'Amount / Value' },
|
|
||||||
{ key: 'location', label: 'Location / Context' },
|
|
||||||
{ key: 'description', label: 'Additional Details' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const s = {
|
|
||||||
overlay: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' },
|
|
||||||
modal: { background: '#111217', border: '1px solid #2a2b3a', borderRadius: '10px', width: '100%', maxWidth: '620px', maxHeight: '90vh', overflowY: 'auto', padding: '32px' },
|
|
||||||
title: { color: '#f8f9fa', fontSize: '20px', fontWeight: 700, marginBottom: '24px', borderBottom: '1px solid #2a2b3a', paddingBottom: '12px' },
|
|
||||||
label: { fontWeight: 600, color: '#e5e7f1', marginBottom: '5px', fontSize: '13px', display: 'block' },
|
|
||||||
input: { width: '100%', padding: '10px', border: '1px solid #333544', borderRadius: '4px', fontSize: '14px', fontFamily: 'inherit', background: '#050608', color: '#f8f9fa', boxSizing: 'border-box' },
|
|
||||||
textarea: { width: '100%', padding: '10px', border: '1px solid #333544', borderRadius: '4px', fontSize: '13px', fontFamily: 'inherit', background: '#050608', color: '#f8f9fa', resize: 'vertical', minHeight: '80px', boxSizing: 'border-box' },
|
|
||||||
group: { marginBottom: '18px' },
|
|
||||||
hint: { fontSize: '11px', color: '#9ca0b8', marginTop: '4px', fontStyle: 'italic' },
|
|
||||||
row: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' },
|
|
||||||
toggle: { display: 'flex', gap: '8px', marginTop: '6px' },
|
|
||||||
toggleBtn: (active) => ({
|
|
||||||
padding: '7px 18px', borderRadius: '4px', fontSize: '13px', fontWeight: 600, cursor: 'pointer', border: '1px solid',
|
|
||||||
background: active ? '#d4af37' : '#050608',
|
|
||||||
color: active ? '#000' : '#9ca0b8',
|
|
||||||
borderColor: active ? '#d4af37' : '#333544',
|
|
||||||
}),
|
|
||||||
fieldGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginTop: '8px' },
|
|
||||||
checkbox: { display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', color: '#d1d3e0', cursor: 'pointer' },
|
|
||||||
btnRow: { display: 'flex', gap: '12px', justifyContent: 'flex-end', marginTop: '28px', paddingTop: '16px', borderTop: '1px solid #2a2b3a' },
|
|
||||||
btnSave: { padding: '10px 28px', fontSize: '14px', fontWeight: 600, border: 'none', borderRadius: '6px', cursor: 'pointer', background: 'linear-gradient(135deg, #d4af37 0%, #ffdf8a 100%)', color: '#000' },
|
|
||||||
btnDanger: { padding: '10px 18px', fontSize: '14px', fontWeight: 600, border: '1px solid #721c24', borderRadius: '6px', cursor: 'pointer', background: '#3c1114', color: '#ffb3b8' },
|
|
||||||
btnCancel: { padding: '10px 18px', fontSize: '14px', fontWeight: 600, border: '1px solid #333544', borderRadius: '6px', cursor: 'pointer', background: '#050608', color: '#f8f9fa' },
|
|
||||||
section: { background: '#181924', border: '1px solid #2a2b3a', borderRadius: '6px', padding: '16px', marginBottom: '18px' },
|
|
||||||
secTitle: { color: '#d4af37', fontSize: '13px', fontWeight: 700, marginBottom: '12px', textTransform: 'uppercase', letterSpacing: '0.05em' },
|
|
||||||
customBadge: { display: 'inline-block', marginLeft: '8px', padding: '1px 7px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#1a2e1a', color: '#4caf50', border: '1px solid #4caf50', verticalAlign: 'middle' },
|
|
||||||
};
|
|
||||||
|
|
||||||
const EMPTY = {
|
|
||||||
name: '', category: '', chapter: '', description: '',
|
|
||||||
pointType: 'fixed', // 'fixed' | 'sliding'
|
|
||||||
fixedPoints: 1,
|
|
||||||
minPoints: 1,
|
|
||||||
maxPoints: 5,
|
|
||||||
fields: ['description'],
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function ViolationTypeModal({ onClose, onSaved, editing = null }) {
|
|
||||||
const [form, setForm] = useState(EMPTY);
|
|
||||||
const [saving, setSaving] = useState(false);
|
|
||||||
const [deleting, setDeleting] = useState(false);
|
|
||||||
const toast = useToast();
|
|
||||||
|
|
||||||
// Populate form when editing an existing type
|
|
||||||
useEffect(() => {
|
|
||||||
if (editing) {
|
|
||||||
const isSliding = editing.min_points !== editing.max_points;
|
|
||||||
setForm({
|
|
||||||
name: editing.name,
|
|
||||||
category: editing.category,
|
|
||||||
chapter: editing.chapter || '',
|
|
||||||
description: editing.description || '',
|
|
||||||
pointType: isSliding ? 'sliding' : 'fixed',
|
|
||||||
fixedPoints: isSliding ? editing.min_points : editing.min_points,
|
|
||||||
minPoints: editing.min_points,
|
|
||||||
maxPoints: editing.max_points,
|
|
||||||
fields: editing.fields || ['description'],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [editing]);
|
|
||||||
|
|
||||||
const set = (key, val) => setForm(prev => ({ ...prev, [key]: val }));
|
|
||||||
|
|
||||||
const toggleField = key => {
|
|
||||||
setForm(prev => ({
|
|
||||||
...prev,
|
|
||||||
fields: prev.fields.includes(key)
|
|
||||||
? prev.fields.filter(f => f !== key)
|
|
||||||
: [...prev.fields, key],
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
if (!form.name.trim()) { toast.warning('Violation name is required.'); return; }
|
|
||||||
if (!form.category.trim()) { toast.warning('Category is required.'); return; }
|
|
||||||
|
|
||||||
const minPts = form.pointType === 'fixed' ? parseInt(form.fixedPoints) || 1 : parseInt(form.minPoints) || 1;
|
|
||||||
const maxPts = form.pointType === 'fixed' ? minPts : parseInt(form.maxPoints) || 1;
|
|
||||||
|
|
||||||
if (maxPts < minPts) { toast.warning('Max points must be >= min points.'); return; }
|
|
||||||
if (form.fields.length === 0) { toast.warning('Select at least one context field.'); return; }
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
name: form.name.trim(),
|
|
||||||
category: form.category.trim(),
|
|
||||||
chapter: form.chapter.trim() || null,
|
|
||||||
description: form.description.trim() || null,
|
|
||||||
min_points: minPts,
|
|
||||||
max_points: maxPts,
|
|
||||||
fields: form.fields,
|
|
||||||
};
|
|
||||||
|
|
||||||
setSaving(true);
|
|
||||||
try {
|
|
||||||
let saved;
|
|
||||||
if (editing) {
|
|
||||||
const res = await axios.put(`/api/violation-types/${editing.id}`, payload);
|
|
||||||
saved = res.data;
|
|
||||||
toast.success(`"${saved.name}" updated.`);
|
|
||||||
} else {
|
|
||||||
const res = await axios.post('/api/violation-types', payload);
|
|
||||||
saved = res.data;
|
|
||||||
toast.success(`"${saved.name}" added to violation types.`);
|
|
||||||
}
|
|
||||||
onSaved(saved);
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err.response?.data?.error || err.message);
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDelete = async () => {
|
|
||||||
if (!editing) return;
|
|
||||||
if (!window.confirm(`Delete "${editing.name}"? This cannot be undone and will fail if any violations reference this type.`)) return;
|
|
||||||
setDeleting(true);
|
|
||||||
try {
|
|
||||||
await axios.delete(`/api/violation-types/${editing.id}`);
|
|
||||||
toast.success(`"${editing.name}" deleted.`);
|
|
||||||
onSaved(null); // null signals a deletion to the parent
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err.response?.data?.error || err.message);
|
|
||||||
} finally {
|
|
||||||
setDeleting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div style={s.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
|
|
||||||
<div style={s.modal}>
|
|
||||||
<div style={s.title}>
|
|
||||||
{editing ? 'Edit Violation Type' : 'Add Violation Type'}
|
|
||||||
{editing && <span style={s.customBadge}>CUSTOM</span>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Basic Info */}
|
|
||||||
<div style={s.section}>
|
|
||||||
<div style={s.secTitle}>Violation Definition</div>
|
|
||||||
|
|
||||||
<div style={s.group}>
|
|
||||||
<label style={s.label}>Violation Name *</label>
|
|
||||||
<input
|
|
||||||
style={s.input}
|
|
||||||
type="text"
|
|
||||||
value={form.name}
|
|
||||||
onChange={e => set('name', e.target.value)}
|
|
||||||
placeholder="e.g. Unauthorized System Access"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style={s.group}>
|
|
||||||
<label style={s.label}>Category *</label>
|
|
||||||
<input
|
|
||||||
style={s.input}
|
|
||||||
type="text"
|
|
||||||
list="vt-categories"
|
|
||||||
value={form.category}
|
|
||||||
onChange={e => set('category', e.target.value)}
|
|
||||||
placeholder="Select existing or type new category"
|
|
||||||
/>
|
|
||||||
<datalist id="vt-categories">
|
|
||||||
{KNOWN_CATEGORIES.map(c => <option key={c} value={c} />)}
|
|
||||||
</datalist>
|
|
||||||
<div style={s.hint}>Choose an existing category or type a new one to create a new group in the dropdown.</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style={s.group}>
|
|
||||||
<label style={s.label}>Handbook Reference / Chapter</label>
|
|
||||||
<input
|
|
||||||
style={s.input}
|
|
||||||
type="text"
|
|
||||||
value={form.chapter}
|
|
||||||
onChange={e => set('chapter', e.target.value)}
|
|
||||||
placeholder="e.g. Chapter 4, Section 6"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style={s.group}>
|
|
||||||
<label style={s.label}>Description / Reference Text</label>
|
|
||||||
<textarea
|
|
||||||
style={s.textarea}
|
|
||||||
value={form.description}
|
|
||||||
onChange={e => set('description', e.target.value)}
|
|
||||||
placeholder="Paste the relevant handbook language or describe the infraction in plain terms..."
|
|
||||||
/>
|
|
||||||
<div style={s.hint}>Shown in the context box on the violation form and printed on the PDF.</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Point Assignment */}
|
|
||||||
<div style={s.section}>
|
|
||||||
<div style={s.secTitle}>Point Assignment</div>
|
|
||||||
|
|
||||||
<label style={s.label}>Point Type</label>
|
|
||||||
<div style={s.toggle}>
|
|
||||||
<button type="button" style={s.toggleBtn(form.pointType === 'fixed')} onClick={() => set('pointType', 'fixed')}>Fixed</button>
|
|
||||||
<button type="button" style={s.toggleBtn(form.pointType === 'sliding')} onClick={() => set('pointType', 'sliding')}>Sliding Range</button>
|
|
||||||
</div>
|
|
||||||
<div style={{ ...s.hint, marginTop: '6px' }}>
|
|
||||||
Fixed = exact value every time. Sliding = supervisor adjusts within a min/max range.
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{form.pointType === 'fixed' ? (
|
|
||||||
<div style={{ ...s.group, marginTop: '14px' }}>
|
|
||||||
<label style={s.label}>Points (Fixed)</label>
|
|
||||||
<input
|
|
||||||
style={{ ...s.input, width: '120px' }}
|
|
||||||
type="number" min="1" max="30"
|
|
||||||
value={form.fixedPoints}
|
|
||||||
onChange={e => set('fixedPoints', e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div style={{ ...s.row, marginTop: '14px' }}>
|
|
||||||
<div style={s.group}>
|
|
||||||
<label style={s.label}>Min Points</label>
|
|
||||||
<input
|
|
||||||
style={s.input}
|
|
||||||
type="number" min="1" max="30"
|
|
||||||
value={form.minPoints}
|
|
||||||
onChange={e => set('minPoints', e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div style={s.group}>
|
|
||||||
<label style={s.label}>Max Points</label>
|
|
||||||
<input
|
|
||||||
style={s.input}
|
|
||||||
type="number" min="1" max="30"
|
|
||||||
value={form.maxPoints}
|
|
||||||
onChange={e => set('maxPoints', e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Context Fields */}
|
|
||||||
<div style={s.section}>
|
|
||||||
<div style={s.secTitle}>Context Fields</div>
|
|
||||||
<div style={s.hint}>Select which additional fields appear on the violation form for this type.</div>
|
|
||||||
<div style={s.fieldGrid}>
|
|
||||||
{CONTEXT_FIELDS.map(({ key, label }) => (
|
|
||||||
<label key={key} style={s.checkbox}>
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={form.fields.includes(key)}
|
|
||||||
onChange={() => toggleField(key)}
|
|
||||||
/>
|
|
||||||
{label}
|
|
||||||
</label>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style={s.btnRow}>
|
|
||||||
{editing && (
|
|
||||||
<button type="button" style={s.btnDanger} onClick={handleDelete} disabled={deleting}>
|
|
||||||
{deleting ? 'Deleting…' : 'Delete Type'}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
<button type="button" style={s.btnCancel} onClick={onClose}>Cancel</button>
|
|
||||||
<button type="button" style={s.btnSave} onClick={handleSave} disabled={saving}>
|
|
||||||
{saving ? 'Saving…' : editing ? 'Save Changes' : 'Add Violation Type'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -60,23 +60,6 @@ db.exec(`CREATE TABLE IF NOT EXISTS audit_log (
|
|||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||||
)`);
|
)`);
|
||||||
|
|
||||||
// ── Feature: Custom Violation Types ──────────────────────────────────────────
|
|
||||||
// Persisted violation type definitions created via the UI. type_key is prefixed
|
|
||||||
// with 'custom_' to prevent collisions with hardcoded violation keys.
|
|
||||||
db.exec(`CREATE TABLE IF NOT EXISTS violation_types (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
type_key TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
category TEXT NOT NULL DEFAULT 'Custom',
|
|
||||||
chapter TEXT,
|
|
||||||
description TEXT,
|
|
||||||
min_points INTEGER NOT NULL DEFAULT 1,
|
|
||||||
max_points INTEGER NOT NULL DEFAULT 1,
|
|
||||||
fields TEXT NOT NULL DEFAULT '["description"]',
|
|
||||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)`);
|
|
||||||
|
|
||||||
// Recreate view so it always filters negated rows
|
// Recreate view so it always filters negated rows
|
||||||
db.exec(`DROP VIEW IF EXISTS active_cpas_scores;
|
db.exec(`DROP VIEW IF EXISTS active_cpas_scores;
|
||||||
CREATE VIEW active_cpas_scores AS
|
CREATE VIEW active_cpas_scores AS
|
||||||
|
|||||||
159
server.js
159
server.js
@@ -11,6 +11,10 @@ app.use(cors());
|
|||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
app.use(express.static(path.join(__dirname, 'client', 'dist')));
|
app.use(express.static(path.join(__dirname, 'client', 'dist')));
|
||||||
|
|
||||||
|
// TODO [CRITICAL #1]: No authentication on any route. Add an auth middleware
|
||||||
|
// (e.g. express-session + password, or JWT) before all /api/* routes.
|
||||||
|
// Anyone on the network can currently create, delete, or negate violations.
|
||||||
|
|
||||||
// ── Demo static route ─────────────────────────────────────────────────────────
|
// ── Demo static route ─────────────────────────────────────────────────────────
|
||||||
// Serves the standalone stakeholder demo page at /demo/index.html
|
// Serves the standalone stakeholder demo page at /demo/index.html
|
||||||
// Must be registered before the SPA catch-all below.
|
// Must be registered before the SPA catch-all below.
|
||||||
@@ -49,6 +53,13 @@ app.get('/api/employees', (req, res) => {
|
|||||||
res.json(rows);
|
res.json(rows);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GET /api/employees/:id — single employee record
|
||||||
|
app.get('/api/employees/:id', (req, res) => {
|
||||||
|
const emp = db.prepare('SELECT id, name, department, supervisor, notes FROM employees WHERE id = ?').get(req.params.id);
|
||||||
|
if (!emp) return res.status(404).json({ error: 'Employee not found' });
|
||||||
|
res.json(emp);
|
||||||
|
});
|
||||||
|
|
||||||
app.post('/api/employees', (req, res) => {
|
app.post('/api/employees', (req, res) => {
|
||||||
const { name, department, supervisor } = req.body;
|
const { name, department, supervisor } = req.body;
|
||||||
if (!name) return res.status(400).json({ error: 'name is required' });
|
if (!name) return res.status(400).json({ error: 'name is required' });
|
||||||
@@ -58,6 +69,9 @@ app.post('/api/employees', (req, res) => {
|
|||||||
db.prepare('UPDATE employees SET department = COALESCE(?, department), supervisor = COALESCE(?, supervisor) WHERE id = ?')
|
db.prepare('UPDATE employees SET department = COALESCE(?, department), supervisor = COALESCE(?, supervisor) WHERE id = ?')
|
||||||
.run(department || null, supervisor || null, existing.id);
|
.run(department || null, supervisor || null, existing.id);
|
||||||
}
|
}
|
||||||
|
// TODO [MINOR #16]: Spreading `existing` then overwriting with possibly-undefined
|
||||||
|
// `department`/`supervisor` returns `undefined` for unset fields.
|
||||||
|
// Re-query after update or only spread defined values.
|
||||||
return res.json({ ...existing, department, supervisor });
|
return res.json({ ...existing, department, supervisor });
|
||||||
}
|
}
|
||||||
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)')
|
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)')
|
||||||
@@ -290,6 +304,17 @@ app.post('/api/violations', (req, res) => {
|
|||||||
// PATCH /api/violations/:id/amend — edit mutable fields; logs a diff per changed field
|
// PATCH /api/violations/:id/amend — edit mutable fields; logs a diff per changed field
|
||||||
const AMENDABLE_FIELDS = ['incident_time', 'location', 'details', 'submitted_by', 'witness_name', 'acknowledged_by', 'acknowledged_date'];
|
const AMENDABLE_FIELDS = ['incident_time', 'location', 'details', 'submitted_by', 'witness_name', 'acknowledged_by', 'acknowledged_date'];
|
||||||
|
|
||||||
|
// Pre-build one prepared UPDATE statement per amendable field combination is not
|
||||||
|
// practical (2^n combos), so instead we validate columns against the static
|
||||||
|
// whitelist and build the clause only from known-safe names at startup.
|
||||||
|
// The whitelist itself is the guard; no user-supplied column name ever enters SQL.
|
||||||
|
const AMEND_UPDATE_STMTS = Object.fromEntries(
|
||||||
|
AMENDABLE_FIELDS.map(f => [
|
||||||
|
f,
|
||||||
|
db.prepare(`UPDATE violations SET ${f} = ? WHERE id = ?`)
|
||||||
|
])
|
||||||
|
);
|
||||||
|
|
||||||
app.patch('/api/violations/:id/amend', (req, res) => {
|
app.patch('/api/violations/:id/amend', (req, res) => {
|
||||||
const id = parseInt(req.params.id);
|
const id = parseInt(req.params.id);
|
||||||
const { changed_by, ...updates } = req.body;
|
const { changed_by, ...updates } = req.body;
|
||||||
@@ -307,18 +332,14 @@ app.patch('/api/violations/:id/amend', (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const amendTransaction = db.transaction(() => {
|
const amendTransaction = db.transaction(() => {
|
||||||
// Build UPDATE
|
|
||||||
const setClauses = Object.keys(allowed).map(k => `${k} = ?`).join(', ');
|
|
||||||
const values = [...Object.values(allowed), id];
|
|
||||||
db.prepare(`UPDATE violations SET ${setClauses} WHERE id = ?`).run(...values);
|
|
||||||
|
|
||||||
// Insert an amendment record per changed field
|
|
||||||
const insertAmendment = db.prepare(`
|
const insertAmendment = db.prepare(`
|
||||||
INSERT INTO violation_amendments (violation_id, changed_by, field_name, old_value, new_value)
|
INSERT INTO violation_amendments (violation_id, changed_by, field_name, old_value, new_value)
|
||||||
VALUES (?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?)
|
||||||
`);
|
`);
|
||||||
for (const [field, newVal] of Object.entries(allowed)) {
|
for (const [field, newVal] of Object.entries(allowed)) {
|
||||||
const oldVal = violation[field];
|
const oldVal = violation[field];
|
||||||
|
// Use the pre-built statement for this field — no runtime interpolation
|
||||||
|
AMEND_UPDATE_STMTS[field].run(newVal, id);
|
||||||
if (String(oldVal) !== String(newVal)) {
|
if (String(oldVal) !== String(newVal)) {
|
||||||
insertAmendment.run(id, changed_by || null, field, oldVal ?? null, newVal ?? null);
|
insertAmendment.run(id, changed_by || null, field, oldVal ?? null, newVal ?? null);
|
||||||
}
|
}
|
||||||
@@ -391,6 +412,38 @@ app.delete('/api/violations/:id', (req, res) => {
|
|||||||
res.json({ success: true });
|
res.json({ success: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Violation counts per employee ────────────────────────────────────────────
|
||||||
|
// GET /api/employees/:id/violation-counts
|
||||||
|
// Returns { violation_type: count } for the rolling 90-day window (non-negated).
|
||||||
|
app.get('/api/employees/:id/violation-counts', (req, res) => {
|
||||||
|
const rows = db.prepare(`
|
||||||
|
SELECT violation_type, COUNT(*) AS count
|
||||||
|
FROM violations
|
||||||
|
WHERE employee_id = ?
|
||||||
|
AND negated = 0
|
||||||
|
AND incident_date >= DATE('now', '-90 days')
|
||||||
|
GROUP BY violation_type
|
||||||
|
`).all(req.params.id);
|
||||||
|
const result = {};
|
||||||
|
for (const r of rows) result[r.violation_type] = r.count;
|
||||||
|
res.json(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/employees/:id/violation-counts/alltime
|
||||||
|
// Returns { violation_type: { count, max_points_used } } across all time (non-negated).
|
||||||
|
app.get('/api/employees/:id/violation-counts/alltime', (req, res) => {
|
||||||
|
const rows = db.prepare(`
|
||||||
|
SELECT violation_type, COUNT(*) AS count, MAX(points) AS max_points_used
|
||||||
|
FROM violations
|
||||||
|
WHERE employee_id = ?
|
||||||
|
AND negated = 0
|
||||||
|
GROUP BY violation_type
|
||||||
|
`).all(req.params.id);
|
||||||
|
const result = {};
|
||||||
|
for (const r of rows) result[r.violation_type] = { count: r.count, max_points_used: r.max_points_used };
|
||||||
|
res.json(result);
|
||||||
|
});
|
||||||
|
|
||||||
// ── Audit log ────────────────────────────────────────────────────────────────
|
// ── Audit log ────────────────────────────────────────────────────────────────
|
||||||
app.get('/api/audit', (req, res) => {
|
app.get('/api/audit', (req, res) => {
|
||||||
const limit = Math.min(parseInt(req.query.limit) || 100, 500);
|
const limit = Math.min(parseInt(req.query.limit) || 100, 500);
|
||||||
@@ -410,100 +463,6 @@ app.get('/api/audit', (req, res) => {
|
|||||||
res.json(db.prepare(sql).all(...args));
|
res.json(db.prepare(sql).all(...args));
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Custom Violation Types ────────────────────────────────────────────────────
|
|
||||||
// Persisted violation type definitions stored in violation_types table.
|
|
||||||
// type_key is auto-generated (custom_<slug>) to avoid collisions with hardcoded keys.
|
|
||||||
|
|
||||||
app.get('/api/violation-types', (req, res) => {
|
|
||||||
const rows = db.prepare('SELECT * FROM violation_types ORDER BY category ASC, name ASC').all();
|
|
||||||
res.json(rows.map(r => ({ ...r, fields: JSON.parse(r.fields) })));
|
|
||||||
});
|
|
||||||
|
|
||||||
app.post('/api/violation-types', (req, res) => {
|
|
||||||
const { name, category, chapter, description, min_points, max_points, fields, created_by } = req.body;
|
|
||||||
if (!name || !name.trim()) return res.status(400).json({ error: 'name is required' });
|
|
||||||
|
|
||||||
const minPts = parseInt(min_points) || 1;
|
|
||||||
const maxPts = parseInt(max_points) || minPts;
|
|
||||||
if (maxPts < minPts) return res.status(400).json({ error: 'max_points must be >= min_points' });
|
|
||||||
|
|
||||||
// Generate a unique type_key from the name, prefixed with 'custom_'
|
|
||||||
const base = 'custom_' + name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
|
|
||||||
let typeKey = base;
|
|
||||||
let suffix = 2;
|
|
||||||
while (db.prepare('SELECT id FROM violation_types WHERE type_key = ?').get(typeKey)) {
|
|
||||||
typeKey = `${base}_${suffix++}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = db.prepare(`
|
|
||||||
INSERT INTO violation_types (type_key, name, category, chapter, description, min_points, max_points, fields)
|
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
||||||
`).run(
|
|
||||||
typeKey,
|
|
||||||
name.trim(),
|
|
||||||
(category || 'Custom').trim(),
|
|
||||||
chapter || null,
|
|
||||||
description || null,
|
|
||||||
minPts,
|
|
||||||
maxPts,
|
|
||||||
JSON.stringify(fields && fields.length ? fields : ['description'])
|
|
||||||
);
|
|
||||||
const row = db.prepare('SELECT * FROM violation_types WHERE id = ?').get(result.lastInsertRowid);
|
|
||||||
audit('violation_type_created', 'violation_type', result.lastInsertRowid, created_by || null, { name: row.name, category: row.category });
|
|
||||||
res.status(201).json({ ...row, fields: JSON.parse(row.fields) });
|
|
||||||
} catch (err) {
|
|
||||||
res.status(500).json({ error: err.message });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.put('/api/violation-types/:id', (req, res) => {
|
|
||||||
const id = parseInt(req.params.id);
|
|
||||||
const row = db.prepare('SELECT * FROM violation_types WHERE id = ?').get(id);
|
|
||||||
if (!row) return res.status(404).json({ error: 'Violation type not found' });
|
|
||||||
|
|
||||||
const { name, category, chapter, description, min_points, max_points, fields, updated_by } = req.body;
|
|
||||||
if (!name || !name.trim()) return res.status(400).json({ error: 'name is required' });
|
|
||||||
|
|
||||||
const minPts = parseInt(min_points) || 1;
|
|
||||||
const maxPts = parseInt(max_points) || minPts;
|
|
||||||
if (maxPts < minPts) return res.status(400).json({ error: 'max_points must be >= min_points' });
|
|
||||||
|
|
||||||
db.prepare(`
|
|
||||||
UPDATE violation_types
|
|
||||||
SET name=?, category=?, chapter=?, description=?, min_points=?, max_points=?, fields=?, updated_at=CURRENT_TIMESTAMP
|
|
||||||
WHERE id=?
|
|
||||||
`).run(
|
|
||||||
name.trim(),
|
|
||||||
(category || 'Custom').trim(),
|
|
||||||
chapter || null,
|
|
||||||
description || null,
|
|
||||||
minPts,
|
|
||||||
maxPts,
|
|
||||||
JSON.stringify(fields && fields.length ? fields : ['description']),
|
|
||||||
id
|
|
||||||
);
|
|
||||||
|
|
||||||
const updated = db.prepare('SELECT * FROM violation_types WHERE id = ?').get(id);
|
|
||||||
audit('violation_type_updated', 'violation_type', id, updated_by || null, { name: updated.name, category: updated.category });
|
|
||||||
res.json({ ...updated, fields: JSON.parse(updated.fields) });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.delete('/api/violation-types/:id', (req, res) => {
|
|
||||||
const id = parseInt(req.params.id);
|
|
||||||
const row = db.prepare('SELECT * FROM violation_types WHERE id = ?').get(id);
|
|
||||||
if (!row) return res.status(404).json({ error: 'Violation type not found' });
|
|
||||||
|
|
||||||
const usage = db.prepare('SELECT COUNT(*) as count FROM violations WHERE violation_type = ?').get(row.type_key);
|
|
||||||
if (usage.count > 0) {
|
|
||||||
return res.status(409).json({ error: `Cannot delete: ${usage.count} violation(s) reference this type. Negate those violations first.` });
|
|
||||||
}
|
|
||||||
|
|
||||||
db.prepare('DELETE FROM violation_types WHERE id = ?').run(id);
|
|
||||||
audit('violation_type_deleted', 'violation_type', id, null, { name: row.name, type_key: row.type_key });
|
|
||||||
res.json({ ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
// ── PDF endpoint ─────────────────────────────────────────────────────────────
|
// ── PDF endpoint ─────────────────────────────────────────────────────────────
|
||||||
app.get('/api/violations/:id/pdf', async (req, res) => {
|
app.get('/api/violations/:id/pdf', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
Reference in New Issue
Block a user