8 Commits

Author SHA1 Message Date
jason ba2b631e23 documentation
Build and Push Docker Image / build (push) Successful in 6s
2026-05-11 13:28:02 -05:00
jason 3220ee70c4 financial data entry
Build and Push Docker Image / build (push) Successful in 1m4s
2026-05-11 12:04:34 -05:00
jason 5a2b581c71 Add .gitea/workflows/docker-build.yml 2026-05-11 11:48:51 -05:00
jason 3a0934bdc6 Merge pull request 'feat: custom violation types — persist, manage, and use in violation form' (#46) from claude/musing-bell into master
Reviewed-on: #46
2026-03-18 16:25:53 -05:00
jason 1c4494dd28 Merge pull request 'docs: add AGENTS.md with coding, compliance, and architecture guidance' (#45) from claude/musing-bell into master
Reviewed-on: #45
2026-03-18 16:15:54 -05:00
jason 0c057ef0e4 Merge pull request 'Code review and fixes' (#44) from cpas-checking into master
Reviewed-on: #44
2026-03-18 16:01:40 -05:00
jason da36edbba6 vscode 2026-03-11 22:58:53 -05:00
jason d6585c01c6 Code review and fixes 2026-03-11 16:33:38 -05:00
17 changed files with 186 additions and 47 deletions
+25
View File
@@ -0,0 +1,25 @@
name: Build and Push Docker Image
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
container:
image: catthehacker/ubuntu:act-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Log in to Gitea Container Registry
uses: docker/login-action@v3
with:
registry: registry.alwisp.com
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Build and Push
run: |
docker build -t registry.alwisp.com/${{ gitea.repository_owner }}/${{ gitea.repository }}:latest .
docker push registry.alwisp.com/${{ gitea.repository_owner }}/${{ gitea.repository }}:latest
+4
View File
@@ -0,0 +1,4 @@
{
"giteaActions.baseUrl": "https://git.alwisp.com",
"giteaActions.discovery.mode": "allAccessible"
}
+1 -1
View File
@@ -82,7 +82,7 @@ The following fields on `violations` are locked after submission. They are the b
- `prior_active_points` (snapshot at insert time)
- `prior_tier_label`
Amendable fields (non-scoring): `location`, `details`, `witness_name`, `acknowledged_by`, `acknowledged_date`
Amendable fields (non-scoring): `incident_time`, `location`, `details`, `submitted_by`, `witness_name`, `acknowledged_by`, `acknowledged_date`, `amount`
### Soft-Delete Pattern
+40 -23
View File
@@ -130,7 +130,6 @@ Useful for showing the app to stakeholders without exposing live employee data.
- Summary stat cards: total employees, elite standing (0 pts), with active points, at-risk count, highest active score
- **At-risk badge**: flags employees within 2 points of the next tier escalation
- Search/filter by name, department, or supervisor
- **Department filter**: pre-loaded dropdown of all departments for quick scoped views
- Click any employee name to open their full profile modal
- **📋 Audit Log** button — filterable, paginated view of all system write actions
@@ -138,9 +137,11 @@ Useful for showing the app to stakeholders without exposing live employee data.
- Select existing employee or enter new employee by name
- **Employee intelligence**: shows current CPAS standing badge and 90-day violation count before submitting
- Violation type dropdown grouped by category; shows prior 90-day counts inline
- **Custom violation types**: add or edit user-defined types directly from the form (`+ Add Type` / `Edit Type` buttons); persisted to the database and merged into the dropdown alongside hardcoded types
- **Recidivist auto-escalation**: if an employee has prior violations of the same type, points slider auto-sets to maximum per policy
- Repeat offense badge with prior count displayed
- Context-sensitive fields (time, minutes late, amount, location, description) shown only when relevant to violation type
- **Financial amount tracking**: dollar amount in question recorded for chargeback / receipt / custom financial violations; surfaces on the PDF for repayment records and is audit-logged on edit
- **Tier crossing warning** (TierWarning component): previews what tier the new points would push the employee into before submission
- Point slider for discretionary adjustments within the violation's min/max range
- **Employee Acknowledgment section**: optional "received by employee" name and date fields; when filled, the PDF signature block shows the recorded acknowledgment instead of a blank signature line
@@ -214,23 +215,30 @@ Scores are computed over a **rolling 90-day window** (negated violations exclude
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/health` | Health check |
| GET | `/api/health` | Health check (returns build SHA + timestamp) |
| GET | `/api/employees` | List all employees (includes `notes`) |
| GET | `/api/employees/:id` | Single employee record |
| POST | `/api/employees` | Create or upsert employee |
| PATCH | `/api/employees/:id` | Edit name, department, supervisor, or notes |
| PATCH | `/api/employees/:id/notes` | Save employee notes only (shorthand) |
| POST | `/api/employees/:id/merge` | Merge duplicate employee; reassigns all violations |
| GET | `/api/employees/:id/score` | Get active CPAS score for employee |
| GET | `/api/employees/:id/expiration` | Active violation roll-off timeline with days remaining |
| PATCH | `/api/employees/:id/notes` | Save employee notes only (shorthand) |
| GET | `/api/employees/:id/violation-counts` | 90-day non-negated counts grouped by violation type |
| GET | `/api/employees/:id/violation-counts/alltime` | All-time non-negated counts + max points used per type |
| GET | `/api/dashboard` | All employees with active points + violation counts |
| POST | `/api/violations` | Log a new violation (accepts `acknowledged_by`, `acknowledged_date`) |
| POST | `/api/violations` | Log a new violation (accepts `acknowledged_by`, `acknowledged_date`, `amount`) |
| GET | `/api/violations/employee/:id` | Violation history with resolutions + amendment counts |
| PATCH | `/api/violations/:id/negated` | Negate a violation (soft delete + resolution record) |
| PATCH | `/api/violations/:id/negate` | Negate a violation (soft delete + resolution record) |
| PATCH | `/api/violations/:id/restore` | Restore a negated violation |
| PATCH | `/api/violations/:id/amend` | Amend non-scoring fields with field-level diff logging |
| GET | `/api/violations/:id/amendments` | Get amendment history for a violation |
| DELETE | `/api/violations/:id` | Hard delete a violation |
| GET | `/api/violations/:id/pdf` | Download violation PDF |
| GET | `/api/violation-types` | List custom violation types |
| POST | `/api/violation-types` | Create a custom violation type |
| PUT | `/api/violation-types/:id` | Update a custom violation type |
| DELETE | `/api/violation-types/:id` | Delete a custom violation type (blocked if any violation references it) |
| GET | `/api/audit` | Paginated audit log (filterable by `entity_type`, `entity_id`) |
---
@@ -258,24 +266,29 @@ cpas/
├── main.jsx
├── App.jsx # Root app + AppFooter (copyright, dev ticker, Gitea link)
├── data/
── violations.js # All CPAS violation definitions + groups
── violations.js # All hardcoded CPAS violation definitions + groups
│ └── departments.js # DEPARTMENTS constant; single source of truth
├── hooks/
│ └── useEmployeeIntelligence.js # Score + history hook
│ └── useEmployeeIntelligence.js # Score + history hook
├── styles/
│ └── mobile.css # Mobile breakpoint overrides only
└── components/
├── CpasBadge.jsx # Tier badge + color logic
├── TierWarning.jsx # Pre-submit tier crossing alert
├── Dashboard.jsx # Company-wide leaderboard + audit log trigger
├── ViolationForm.jsx # Violation entry form + ack signature fields
├── EmployeeModal.jsx # Employee profile + history modal
├── EditEmployeeModal.jsx # Employee edit + merge duplicate
├── AmendViolationModal.jsx # Non-scoring field amendment + diff history
├── AuditLog.jsx # Filterable audit log panel
├── NegateModal.jsx # Negate/resolve violation dialog
├── ViolationHistory.jsx # Violation list component
├── ExpirationTimeline.jsx # Per-violation 90-day roll-off countdown
├── EmployeeNotes.jsx # Inline notes editor with quick-add HR tags
├── ToastProvider.jsx # Global toast notification system + useToast hook
── ReadmeModal.jsx # In-app admin documentation panel
├── CpasBadge.jsx # Tier badge + color logic (canonical TIERS, getTier)
├── TierWarning.jsx # Pre-submit tier crossing alert
├── Dashboard.jsx # Company-wide leaderboard + audit log trigger
├── DashboardMobile.jsx # Mobile-optimized dashboard layout
├── ViolationForm.jsx # Violation entry form + ack signature + amount field
├── ViolationTypeModal.jsx # Create / edit / delete custom violation types
├── EmployeeModal.jsx # Employee profile + history modal
├── EditEmployeeModal.jsx # Employee edit + merge duplicate
├── AmendViolationModal.jsx # Non-scoring field amendment + diff history
├── AuditLog.jsx # Filterable audit log panel
├── NegateModal.jsx # Negate/resolve violation dialog
├── ViolationHistory.jsx # Violation list component
├── ExpirationTimeline.jsx # Per-violation 90-day roll-off countdown
── EmployeeNotes.jsx # Inline notes editor with quick-add HR tags
├── ToastProvider.jsx # Global toast notification system + useToast hook
└── ReadmeModal.jsx # In-app admin documentation panel
```
---
@@ -284,10 +297,11 @@ cpas/
Six tables + one view:
- **`employees`** — id, name, department, supervisor, **notes**
- **`violations`** — full incident record including `prior_active_points` snapshot at time of logging, `acknowledged_by` and `acknowledged_date` for employee acknowledgment
- **`employees`** — id, name, department, supervisor, notes
- **`violations`** — full incident record including `prior_active_points` snapshot, `acknowledged_by` / `acknowledged_date`, and `amount` (financial amount in question for chargeback/repayment)
- **`violation_resolutions`** — resolution type, details, resolved_by (linked to violations)
- **`violation_amendments`** — field-level diff log for violation edits; one row per changed field per amendment
- **`violation_types`** — persisted custom violation type definitions added via the UI; `type_key` is prefixed `custom_` to prevent collisions with hardcoded keys
- **`audit_log`** — append-only record of every write action (action, entity_type, entity_id, performed_by, details, timestamp)
- **`active_cpas_scores`** (view) — sum of points for non-negated violations in rolling 90 days, grouped by employee
@@ -306,6 +320,7 @@ Point values, violation type, and incident date are **immutable** after submissi
| `witness_name` | Witness on record |
| `acknowledged_by` | Employee who acknowledged receipt |
| `acknowledged_date` | Date of employee acknowledgment |
| `amount` | Dollar amount in question (financial violations); typo-correctable for repayment records |
---
@@ -339,6 +354,8 @@ Point values, violation type, and incident date are **immutable** after submissi
| 7 | Department dropdown | Pre-loaded select on the violation form replacing free-text department input; shared `DEPARTMENTS` constant |
| 8 | Stakeholder demo page | Standalone `/demo` route with synthetic data; static HTML served before SPA catch-all; useful for non-live presentations |
| 8 | App footer | Copyright (© Jason Stedwell), live dev ticker since first commit, Gitea repo icon+link |
| 9 | Custom violation types | Persisted user-defined violation types created from the form; `+ Add Type` / `Edit Type` UI; merged into the dropdown alongside hardcoded types; delete blocked when in use |
| 9 | Financial amount tracking | `amount` field on financial violations (chargeback, receipt negligence, custom types with the field enabled); stored on `violations`, rendered prominently on the PDF, amendable with audit-logged diffs |
---
+9 -2
View File
@@ -6,6 +6,8 @@ import ToastProvider from './components/ToastProvider';
import './styles/mobile.css';
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');
function elapsed(from) {
@@ -101,7 +103,9 @@ const tabs = [
{ 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) {
const [matches, setMatches] = useState(false);
useEffect(() => {
@@ -237,6 +241,8 @@ export default function App() {
return (
<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>
<div style={s.app}>
<nav style={s.nav} className="app-nav">
@@ -248,7 +254,8 @@ export default function App() {
<div className="nav-tabs">
{tabs.map(t => (
<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>
))}
</div>
@@ -7,6 +7,7 @@ const FIELD_LABELS = {
details: 'Incident Notes',
submitted_by: 'Submitted By',
witness_name: 'Witness / Documenting Officer',
amount: 'Amount in Question',
};
const s = {
@@ -84,6 +85,7 @@ export default function AmendViolationModal({ violation, onClose, onSaved }) {
details: violation.details || '',
submitted_by: violation.submitted_by || '',
witness_name: violation.witness_name || '',
amount: violation.amount || '',
});
const [changedBy, setChangedBy] = useState('');
const [saving, setSaving] = useState(false);
+5 -1
View File
@@ -112,6 +112,9 @@ export default function AuditLog({ onClose }) {
const [filterAction, setFilterAction] = useState('');
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) => {
setLoading(true);
const o = reset ? 0 : offset;
@@ -121,7 +124,8 @@ export default function AuditLog({ onClose }) {
axios.get('/api/audit', { params })
.then(r => {
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;
setEntries(prev => reset ? filtered : [...prev, ...filtered]);
setHasMore(data.length === LIMIT);
+3 -1
View File
@@ -29,7 +29,8 @@ function isAtRisk(points) {
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) {
const [matches, setMatches] = useState(false);
useEffect(() => {
@@ -186,6 +187,7 @@ export default function Dashboard() {
return (
<>
{/* TODO [MAJOR #9]: Same mobileStyles block exists in App.jsx. Move to mobile.css */}
<style>{mobileStyles}</style>
<div style={s.wrap} className="dashboard-wrap">
<div style={s.header} className="dashboard-header">
+2 -3
View File
@@ -103,13 +103,12 @@ export default function EmployeeModal({ employeeId, onClose }) {
const load = useCallback(() => {
setLoading(true);
Promise.all([
axios.get('/api/employees'),
axios.get(`/api/employees/${employeeId}`),
axios.get(`/api/employees/${employeeId}/score`),
axios.get(`/api/violations/employee/${employeeId}?limit=100`),
])
.then(([empRes, scoreRes, violRes]) => {
const emp = empRes.data.find((e) => e.id === employeeId);
setEmployee(emp || null);
setEmployee(empRes.data || null);
setScore(scoreRes.data);
setViolations(violRes.data);
})
+15
View File
@@ -1,5 +1,6 @@
import React, { useState } from 'react';
import axios from 'axios';
import { useToast } from './ToastProvider';
const s = {
wrapper: { marginTop: '20px' },
@@ -53,14 +54,23 @@ export default function EmployeeNotes({ employeeId, initialNotes, onSaved }) {
const [draft, setDraft] = useState(initialNotes || '');
const [saved, setSaved] = useState(initialNotes || '');
const [saving, setSaving] = useState(false);
const [saveErr, setSaveErr] = useState('');
const toast = useToast();
const handleSave = async () => {
setSaving(true);
setSaveErr('');
try {
await axios.patch(`/api/employees/${employeeId}/notes`, { notes: draft });
setSaved(draft);
setEditing(false);
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 {
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."
autoFocus
/>
{saveErr && (
<div style={{ fontSize: '12px', color: '#ff7070', marginBottom: '6px' }}>
{saveErr}
</div>
)}
<div style={s.actions}>
<button style={s.saveBtn} onClick={handleSave} disabled={saving}>
{saving ? 'Saving…' : 'Save Notes'}
+2 -2
View File
@@ -1,8 +1,8 @@
import React, { useEffect, useState } from 'react';
import axios from 'axios';
// Tier thresholds used to compute what tier an employee would drop to
// after a given violation rolls off.
// TODO [MINOR #10]: This TIER_THRESHOLDS array duplicates tiers defined in CpasBadge.jsx
// and Dashboard.jsx. Export TIERS from CpasBadge.jsx and import here instead.
const TIER_THRESHOLDS = [
{ min: 30, label: 'Separation', color: '#ff1744' },
{ min: 25, label: 'Final Decision', color: '#ff6d00' },
-2
View File
@@ -78,14 +78,12 @@ export default function NegateModal({ violation, onConfirm, onCancel }) {
});
};
// FIX: overlay click only closes on backdrop, NOT modal children
const handleOverlayClick = (e) => {
if (e.target === e.currentTarget && onCancel) onCancel();
};
return (
<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.header}>
+3 -1
View File
@@ -44,7 +44,7 @@ export default function ViolationForm() {
const [employees, setEmployees] = useState([]);
const [form, setForm] = useState(EMPTY_FORM);
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 [pdfLoading, setPdfLoading] = useState(false);
const [customTypes, setCustomTypes] = useState([]);
@@ -158,6 +158,7 @@ export default function ViolationForm() {
witness_name: form.witnessName || null,
acknowledged_by: form.acknowledgedBy || null,
acknowledged_date: form.acknowledgedDate || null,
amount: form.amount || null,
});
const newId = violRes.data.id;
@@ -167,6 +168,7 @@ export default function ViolationForm() {
setEmployees(empList.data);
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.` });
setForm(EMPTY_FORM);
setViolation(null);
+2
View File
@@ -21,6 +21,8 @@ if (!cols.includes('prior_active_points')) db.exec("ALTER TABLE violations ADD C
if (!cols.includes('prior_tier_label')) db.exec("ALTER TABLE violations ADD COLUMN prior_tier_label TEXT");
if (!cols.includes('acknowledged_by')) db.exec("ALTER TABLE violations ADD COLUMN acknowledged_by TEXT");
if (!cols.includes('acknowledged_date')) db.exec("ALTER TABLE violations ADD COLUMN acknowledged_date TEXT");
// Financial amount in question (record-keeping / repayment for chargeback, receipt negligence, etc.)
if (!cols.includes('amount')) db.exec("ALTER TABLE violations ADD COLUMN amount TEXT");
// Employee notes column (free-text, does not affect scoring)
const empCols = db.prepare('PRAGMA table_info(employees)').all().map(c => c.name);
+1
View File
@@ -25,6 +25,7 @@ CREATE TABLE IF NOT EXISTS violations (
prior_tier_label TEXT, -- optional human-readable tier
acknowledged_by TEXT, -- employee name who acknowledged receipt
acknowledged_date TEXT, -- date of acknowledgment (YYYY-MM-DD)
amount TEXT, -- dollar amount in question for financial violations (record-keeping / repayment)
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
+5
View File
@@ -243,6 +243,11 @@ function buildHtml(v, score) {
<div class="field-label">Submitted By</div>
<div class="field-value">${v.submitted_by || 'System'}</div>
</div>
${v.amount ? `
<div class="field" style="grid-column: 1 / -1;">
<div class="field-label">Amount in Question</div>
<div class="field-value prominent">${v.amount}</div>
</div>` : ''}
${v.location ? `
<div class="field" style="grid-column: 1 / -1;">
<div class="field-label">Location / Context</div>
+67 -11
View File
@@ -11,6 +11,10 @@ app.use(cors());
app.use(express.json());
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 ─────────────────────────────────────────────────────────
// Serves the standalone stakeholder demo page at /demo/index.html
// Must be registered before the SPA catch-all below.
@@ -49,6 +53,13 @@ app.get('/api/employees', (req, res) => {
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) => {
const { name, department, supervisor } = req.body;
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 = ?')
.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 });
}
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)')
@@ -252,7 +266,8 @@ app.post('/api/violations', (req, res) => {
employee_id, violation_type, violation_name, category,
points, incident_date, incident_time, location,
details, submitted_by, witness_name,
acknowledged_by, acknowledged_date
acknowledged_by, acknowledged_date,
amount
} = req.body;
if (!employee_id || !violation_type || !points || !incident_date) {
@@ -268,15 +283,17 @@ app.post('/api/violations', (req, res) => {
points, incident_date, incident_time, location,
details, submitted_by, witness_name,
prior_active_points,
acknowledged_by, acknowledged_date
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
acknowledged_by, acknowledged_date,
amount
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
employee_id, violation_type, violation_name || violation_type,
category || 'General', ptsInt, incident_date,
incident_time || null, location || null,
details || null, submitted_by || null, witness_name || null,
priorPts,
acknowledged_by || null, acknowledged_date || null
acknowledged_by || null, acknowledged_date || null,
amount || null
);
audit('violation_created', 'violation', result.lastInsertRowid, submitted_by, {
@@ -288,7 +305,18 @@ app.post('/api/violations', (req, res) => {
// ── Violation Amendment (edit) ───────────────────────────────────────────────
// 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', 'amount'];
// 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) => {
const id = parseInt(req.params.id);
@@ -307,18 +335,14 @@ app.patch('/api/violations/:id/amend', (req, res) => {
}
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(`
INSERT INTO violation_amendments (violation_id, changed_by, field_name, old_value, new_value)
VALUES (?, ?, ?, ?, ?)
`);
for (const [field, newVal] of Object.entries(allowed)) {
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)) {
insertAmendment.run(id, changed_by || null, field, oldVal ?? null, newVal ?? null);
}
@@ -391,6 +415,38 @@ app.delete('/api/violations/:id', (req, res) => {
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 ────────────────────────────────────────────────────────────────
app.get('/api/audit', (req, res) => {
const limit = Math.min(parseInt(req.query.limit) || 100, 500);