Compare commits
60 Commits
1533d9aeab
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 431f31b857 | |||
| d4638783a4 | |||
| 9d4d465755 | |||
| f8810e1ae5 | |||
| 57d0ac9755 | |||
| 328fc6f307 | |||
| 37efd596dd | |||
| b02464330b | |||
| be2d1fa68e | |||
| 0a8b6e44d8 | |||
| 9b80afd54d | |||
| 970bc0efea | |||
| 7ee76468c4 | |||
| 2525cce03e | |||
| 15d3f02884 | |||
| ee91a16506 | |||
| 5004c56915 | |||
| 9b6f2353be | |||
| 5140dbbc25 | |||
| bcf0e3f3d1 | |||
| 2bc1740e02 | |||
| 3977c3652f | |||
| e19ef255ac | |||
| f4f191518c | |||
| 69272f71a3 | |||
| a6447970ac | |||
| e0170d71f5 | |||
| 4bb09997ee | |||
| 52a57f21b0 | |||
| 3cc62c2746 | |||
| 47e14ae23b | |||
| a6d4885a53 | |||
| f4869b42b4 | |||
| 98fe9d4a79 | |||
| f52af27114 | |||
| 7ff066011d | |||
| 35b4ded10c | |||
| 5ef61f6590 | |||
| cb8c56adfa | |||
| accb24a286 | |||
| fdfa0bcf2f | |||
| 2ac330904d | |||
| 60e9da488c | |||
| 1a09efbfe5 | |||
| de07e77e07 | |||
| 722f404269 | |||
| 7db080bd2a | |||
| 571c8f2838 | |||
| eb07832cc7 | |||
| 6305cedb14 | |||
| f006c015b0 | |||
| ecc9f3b9f6 | |||
| 066f95cc88 | |||
| 2383e3cc94 | |||
| 8bbfd90f48 | |||
| 590aae5cca | |||
| 39738ed3e1 | |||
| 821192e879 | |||
| 610d72ab66 | |||
| 5bcd6d07dc |
39
Dockerfile
39
Dockerfile
@@ -1,61 +1,28 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Stage 1: Builder
|
||||
# Installs ALL dependencies and compiles the React frontend inside Docker.
|
||||
# Nothing needs to be installed on the host machine except Docker itself.
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# Install backend deps
|
||||
COPY package.json ./
|
||||
RUN npm install
|
||||
|
||||
# Install frontend deps and build React app
|
||||
COPY client/package.json ./client/
|
||||
RUN cd client && npm install
|
||||
|
||||
COPY client/ ./client/
|
||||
RUN cd client && npm run build
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Stage 2: Production image
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
FROM node:20-alpine AS production
|
||||
|
||||
# Chromium for Puppeteer PDF generation
|
||||
RUN apk add --no-cache \
|
||||
chromium \
|
||||
nss \
|
||||
freetype \
|
||||
harfbuzz \
|
||||
ca-certificates \
|
||||
ttf-freefont
|
||||
|
||||
RUN apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont
|
||||
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
|
||||
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3001
|
||||
ENV DB_PATH=/data/cpas.db
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy backend node_modules and compiled frontend from builder
|
||||
COPY --from=builder /build/node_modules ./node_modules
|
||||
COPY --from=builder /build/client/dist ./client/dist
|
||||
|
||||
# Copy all backend source files
|
||||
COPY server.js ./
|
||||
COPY package.json ./
|
||||
COPY db/ ./db/
|
||||
COPY pdf/ ./pdf/
|
||||
|
||||
# Ensure data directory exists
|
||||
COPY client/public/static ./client/dist/static
|
||||
RUN mkdir -p /data
|
||||
|
||||
EXPOSE 3001
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD wget -qO- http://localhost:3001/api/health || exit 1
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD wget -qO- http://localhost:3001/api/health || exit 1
|
||||
CMD ["node", "server.js"]
|
||||
|
||||
202
README.md
202
README.md
@@ -1,11 +1,13 @@
|
||||
# CPAS Violation Tracker
|
||||
|
||||
Single-container Dockerized web app for CPAS violation documentation.
|
||||
Built with React + Vite (frontend), Node.js + Express (backend), SQLite (database).
|
||||
Single-container Dockerized web app for CPAS violation documentation and workforce standing management.
|
||||
Built with **React + Vite** (frontend), **Node.js + Express** (backend), **SQLite** (database), and **Puppeteer** (PDF generation).
|
||||
|
||||
---
|
||||
|
||||
## The only requirement on your machine: Docker Desktop
|
||||
|
||||
Everything else — Node.js, npm, React build — happens inside Docker.
|
||||
Everything else — Node.js, npm, React build, Chromium for PDF — happens inside Docker.
|
||||
|
||||
---
|
||||
|
||||
@@ -41,17 +43,106 @@ docker stop cpas-tracker && docker rm cpas-tracker
|
||||
docker run -d --name cpas-tracker -p 3001:3001 -v cpas-data:/data cpas-tracker
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
### Company Dashboard
|
||||
- Live table of all employees sorted by active CPAS points (highest risk first)
|
||||
- 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
|
||||
- Click any employee name to open their full profile modal
|
||||
- **📋 Audit Log** button — filterable, paginated view of all system write actions
|
||||
|
||||
### Violation Form
|
||||
- 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
|
||||
- **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
|
||||
- **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
|
||||
- One-click PDF download immediately after submission
|
||||
|
||||
### Employee Profile Modal
|
||||
- Full violation history with resolution status and **amendment count badge** per record
|
||||
- **✎ Edit Employee** button — update name, department, or supervisor inline
|
||||
- **Merge Duplicate** tab — reassign all violations from a duplicate record and delete it
|
||||
- **Amend** button per active violation — edit non-scoring fields (location, notes, witness, etc.) with a full field-level diff history
|
||||
- Negate / restore individual violations (soft delete with resolution type + notes)
|
||||
- Hard delete option for data entry errors
|
||||
- PDF download for any historical violation record
|
||||
|
||||
### Audit Log
|
||||
- Append-only log of every write action: employee created/edited/merged, violation logged/amended/negated/restored/deleted
|
||||
- Filterable by entity type (employee / violation) and action
|
||||
- Paginated with load-more; accessible from the Dashboard toolbar
|
||||
|
||||
### Violation Amendment
|
||||
- Edit submitted violations' non-scoring fields without delete-and-resubmit
|
||||
- Point values, violation type, and incident date are immutable
|
||||
- Every change is stored as a field-level diff (old → new value) with timestamp and actor
|
||||
|
||||
### CPAS Tier System
|
||||
|
||||
| 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 |
|
||||
|
||||
Scores are computed over a **rolling 90-day window** (negated violations excluded).
|
||||
|
||||
### PDF Generation
|
||||
- Puppeteer + system Chromium (bundled in Docker image)
|
||||
- Generated on-demand per violation via `GET /api/violations/:id/pdf`
|
||||
- Filename: `CPAS_<EmployeeName>_<IncidentDate>.pdf`
|
||||
- PDF captures prior active points **at the time of the incident** (snapshot stored on insert)
|
||||
|
||||
---
|
||||
|
||||
## API Reference
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| GET | `/api/health` | Health check |
|
||||
| GET | `/api/employees` | List all employees |
|
||||
| POST | `/api/employees` | Create or upsert employee |
|
||||
| PATCH | `/api/employees/:id` | Edit employee name, department, or supervisor |
|
||||
| POST | `/api/employees/:id/merge` | Merge duplicate employee into target; reassigns all violations |
|
||||
| GET | `/api/employees/:id/score` | Get active CPAS score for employee |
|
||||
| GET | `/api/dashboard` | All employees with active points + violation counts |
|
||||
| POST | `/api/violations` | Log a new violation |
|
||||
| GET | `/api/violations/employee/:id` | Get violation history for employee (with resolutions + amendment counts) |
|
||||
| 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/audit` | Paginated audit log (filterable by entity_type, entity_id) |
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
cpas-violation-tracker/
|
||||
├── Dockerfile # Multi-stage: builds React + runs Express
|
||||
cpas/
|
||||
├── Dockerfile # Multi-stage: builds React + runs Express w/ Chromium
|
||||
├── .dockerignore
|
||||
├── package.json # Backend (Express) deps
|
||||
├── server.js # API + static file server
|
||||
├── db/
|
||||
│ ├── schema.sql # Tables + 90-day score view
|
||||
│ └── database.js # SQLite connection
|
||||
│ ├── schema.sql # Tables + 90-day active score view
|
||||
│ └── database.js # SQLite connection (better-sqlite3) + auto-migrations
|
||||
├── pdf/
|
||||
│ └── generator.js # Puppeteer PDF generation
|
||||
└── client/ # React frontend (Vite)
|
||||
├── package.json
|
||||
├── vite.config.js
|
||||
@@ -60,14 +151,95 @@ cpas-violation-tracker/
|
||||
├── main.jsx
|
||||
├── App.jsx
|
||||
├── data/
|
||||
│ └── violations.js # All CPAS violation definitions
|
||||
│ └── violations.js # All CPAS violation definitions + groups
|
||||
├── hooks/
|
||||
│ └── useEmployeeIntelligence.js # Score + history hook
|
||||
└── components/
|
||||
└── ViolationForm.jsx
|
||||
├── 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
|
||||
├── 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
|
||||
```
|
||||
|
||||
## Phases
|
||||
- [x] Phase 1 — Container scaffold, SQLite schema, base React form
|
||||
- [ ] Phase 2 — Employee history, prior violation highlighting
|
||||
- [ ] Phase 3 — Puppeteer PDF generation
|
||||
- [ ] Phase 4 — Dashboard, CPAS scores, tier warnings
|
||||
- [ ] Phase 5 — Recidivist point auto-suggest
|
||||
---
|
||||
|
||||
## Database Schema
|
||||
|
||||
Six tables + one view:
|
||||
|
||||
- **`employees`** — id, name, department, supervisor
|
||||
- **`violations`** — full incident record including `prior_active_points` snapshot at time of logging
|
||||
- **`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
|
||||
- **`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
|
||||
|
||||
---
|
||||
|
||||
## Roadmap
|
||||
|
||||
### ✅ Completed
|
||||
|
||||
| Phase | Feature | Description |
|
||||
|-------|---------|-------------|
|
||||
| 1 | Container scaffold | Docker multi-stage build, Express server, SQLite schema |
|
||||
| 1 | Base violation form | Employee fields, violation type, incident date, point submission |
|
||||
| 2 | Employee intelligence | Live CPAS standing badge and 90-day count shown before submitting |
|
||||
| 2 | Prior violation highlighting | Violation dropdown annotates types with 90-day recurrence counts |
|
||||
| 2 | Recidivist auto-escalation | Points slider auto-maximizes on repeat same-type violations |
|
||||
| 2 | Violation history | Per-employee history list with resolution status |
|
||||
| 3 | PDF generation | Puppeteer/Chromium PDF per violation, downloadable immediately post-submit |
|
||||
| 3 | Prior-points snapshot | `prior_active_points` captured at insert time for accurate historical PDFs |
|
||||
| 4 | Company dashboard | Sortable employee table with live tier badges and at-risk flags |
|
||||
| 4 | Stat cards | Summary counts: total, clean, active, at-risk, highest score |
|
||||
| 4 | Tier crossing warning | Pre-submit alert when new points push employee to next tier |
|
||||
| 4 | Employee profile modal | Full history, negate/restore, hard delete, per-record PDF download |
|
||||
| 4 | Negate & restore | Soft-delete violations with resolution type + notes, fully reversible |
|
||||
| 5 | Employee edit / merge | Update employee name/dept/supervisor; merge duplicate records without losing history |
|
||||
| 5 | Violation amendment | Edit non-scoring fields with field-level audit trail |
|
||||
| 5 | Audit log | Append-only log of all system writes; filterable panel in the dashboard |
|
||||
|
||||
---
|
||||
|
||||
### 📋 In Progress
|
||||
|
||||
#### Reporting & Visibility
|
||||
- **Expiration timeline** — per-employee view showing which active violations roll off the 90-day window and when; lets supervisors anticipate tier drops before they happen
|
||||
- **Employee notes / flags** — free-text notes attached to an employee record (e.g. "on PIP", "union member") visible in the profile modal without affecting scoring
|
||||
|
||||
---
|
||||
|
||||
### 💡 Proposed
|
||||
|
||||
#### Reporting & Analytics
|
||||
- **Violation trends chart** — line/bar chart of violations per day/week/month, filterable by department or supervisor; useful for identifying systemic patterns vs. individual incidents
|
||||
- **Department heat map** — grid view showing violation density and average CPAS score by department; helps supervisors identify team-level risk
|
||||
- **CSV / Excel export** — bulk export of violations or dashboard data for external reporting or payroll integration
|
||||
|
||||
#### Employee Management
|
||||
- **Supervisor view** — scoped dashboard showing only the employees under a given supervisor, useful for multi-supervisor environments
|
||||
|
||||
#### Violation Workflow
|
||||
- **Acknowledgment signature field** — a "received by employee" name/date field on the violation form that prints on the PDF, replacing the blank signature line
|
||||
- **Draft / pending violations** — save a violation as draft before finalizing, useful when incidents need review before being officially logged
|
||||
- **Bulk violation import** — CSV import for migrating historical records from paper logs or a prior system
|
||||
|
||||
#### Notifications & Escalation
|
||||
- **Tier escalation alerts** — email or in-app notification when an employee crosses into Tier 2+ so the relevant supervisor is automatically informed
|
||||
- **Scheduled summary digest** — weekly email to supervisors listing their employees' current standings and any approaching tier thresholds
|
||||
- **At-risk threshold configuration** — make the "at-risk" warning threshold (currently hardcoded at 2 pts) configurable per deployment
|
||||
|
||||
#### Infrastructure & Ops
|
||||
- **Multi-user auth** — simple login with role-based access (admin, supervisor, read-only); currently the app has no auth and is assumed to run on a trusted internal network
|
||||
- **Automated DB backup** — cron job or Docker health hook to snapshot `/data/cpas.db` to a mounted backup volume or remote location on a schedule
|
||||
- **Dark/light theme toggle** — the UI is currently dark-only; a toggle would improve usability in bright environments
|
||||
|
||||
---
|
||||
|
||||
*Proposed features are suggestions based on common HR documentation workflows. Priority and implementation order should be driven by actual operational needs.*
|
||||
|
||||
BIN
client/public/static/mpm-logo.png
Normal file
BIN
client/public/static/mpm-logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.1 KiB |
@@ -1,6 +1,7 @@
|
||||
import React, { useState } from 'react';
|
||||
import ViolationForm from './components/ViolationForm';
|
||||
import Dashboard from './components/Dashboard';
|
||||
import ReadmeModal from './components/ReadmeModal';
|
||||
|
||||
const tabs = [
|
||||
{ id: 'dashboard', label: '📊 Dashboard' },
|
||||
@@ -8,33 +9,65 @@ const tabs = [
|
||||
];
|
||||
|
||||
const s = {
|
||||
app: { minHeight: '100vh', background: '#f5f6fa', fontFamily: "'Segoe UI', Arial, sans-serif" },
|
||||
nav: { background: 'linear-gradient(135deg, #2c3e50, #34495e)', padding: '0 40px', display: 'flex', alignItems: 'center', gap: 0 },
|
||||
logo: { color: 'white', fontWeight: 800, fontSize: '18px', letterSpacing: '0.5px', marginRight: '32px', padding: '18px 0' },
|
||||
app: { minHeight: '100vh', background: '#050608', fontFamily: "'Segoe UI', Arial, sans-serif", color: '#f8f9fa' },
|
||||
nav: { background: '#000000', padding: '0 40px', display: 'flex', alignItems: 'center', gap: 0, borderBottom: '1px solid #333' },
|
||||
logoWrap: { display: 'flex', alignItems: 'center', marginRight: '32px', padding: '14px 0' },
|
||||
logoImg: { height: '28px', marginRight: '10px' },
|
||||
logoText: { color: '#f8f9fa', fontWeight: 800, fontSize: '18px', letterSpacing: '0.5px' },
|
||||
tab: (active) => ({
|
||||
padding: '18px 22px', color: active ? 'white' : 'rgba(255,255,255,0.6)',
|
||||
borderBottom: active ? '3px solid #667eea' : '3px solid transparent',
|
||||
padding: '18px 22px',
|
||||
color: active ? '#f8f9fa' : 'rgba(248,249,250,0.6)',
|
||||
borderBottom: active ? '3px solid #d4af37' : '3px solid transparent',
|
||||
cursor: 'pointer', fontWeight: active ? 700 : 400, fontSize: '14px',
|
||||
background: 'none', border: 'none', borderBottom: active ? '3px solid #667eea' : '3px solid transparent',
|
||||
background: 'none', border: 'none',
|
||||
}),
|
||||
card: { maxWidth: '1100px', margin: '30px auto', background: 'white', borderRadius: '10px', boxShadow: '0 2px 12px rgba(0,0,0,0.08)' },
|
||||
// Docs button sits flush-right in the nav
|
||||
docsBtn: {
|
||||
marginLeft: 'auto',
|
||||
background: 'none',
|
||||
border: '1px solid #2a2b3a',
|
||||
color: '#9ca0b8',
|
||||
borderRadius: '6px',
|
||||
padding: '6px 14px',
|
||||
fontSize: '12px',
|
||||
cursor: 'pointer',
|
||||
fontWeight: 600,
|
||||
letterSpacing: '0.3px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '6px',
|
||||
},
|
||||
card: { maxWidth: '1100px', margin: '30px auto', background: '#111217', borderRadius: '10px', boxShadow: '0 2px 16px rgba(0,0,0,0.6)', border: '1px solid #222' },
|
||||
};
|
||||
|
||||
export default function App() {
|
||||
const [tab, setTab] = useState('dashboard');
|
||||
const [showReadme, setShowReadme] = useState(false);
|
||||
|
||||
return (
|
||||
<div style={s.app}>
|
||||
<nav style={s.nav}>
|
||||
<div style={s.logo}>CPAS Tracker</div>
|
||||
<div style={s.logoWrap}>
|
||||
<img src="/static/mpm-logo.png" alt="MPM" style={s.logoImg} />
|
||||
<div style={s.logoText}>CPAS Tracker</div>
|
||||
</div>
|
||||
|
||||
{tabs.map(t => (
|
||||
<button key={t.id} style={s.tab(tab === t.id)} onClick={() => setTab(t.id)}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
|
||||
<button style={s.docsBtn} onClick={() => setShowReadme(true)} title="Open admin documentation">
|
||||
<span>?</span> Docs
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<div style={s.card}>
|
||||
{tab === 'dashboard' ? <Dashboard /> : <ViolationForm />}
|
||||
</div>
|
||||
|
||||
{showReadme && <ReadmeModal onClose={() => setShowReadme(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
205
client/src/components/AmendViolationModal.jsx
Normal file
205
client/src/components/AmendViolationModal.jsx
Normal file
@@ -0,0 +1,205 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const FIELD_LABELS = {
|
||||
incident_time: 'Incident Time',
|
||||
location: 'Location / Context',
|
||||
details: 'Incident Notes',
|
||||
submitted_by: 'Submitted By',
|
||||
witness_name: 'Witness / Documenting Officer',
|
||||
};
|
||||
|
||||
const s = {
|
||||
overlay: {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)',
|
||||
zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
},
|
||||
modal: {
|
||||
background: '#111217', color: '#f8f9fa', width: '520px', maxWidth: '95vw',
|
||||
maxHeight: '90vh', overflowY: 'auto',
|
||||
borderRadius: '10px', boxShadow: '0 8px 40px rgba(0,0,0,0.8)',
|
||||
border: '1px solid #222',
|
||||
},
|
||||
header: {
|
||||
background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
|
||||
padding: '18px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
borderBottom: '1px solid #222', position: 'sticky', top: 0, zIndex: 10,
|
||||
},
|
||||
headerLeft: {},
|
||||
title: { fontSize: '15px', fontWeight: 700 },
|
||||
subtitle: { fontSize: '11px', color: '#9ca0b8', marginTop: '2px' },
|
||||
closeBtn: {
|
||||
background: 'none', border: 'none', color: 'white', fontSize: '20px',
|
||||
cursor: 'pointer', lineHeight: 1,
|
||||
},
|
||||
body: { padding: '22px' },
|
||||
notice: {
|
||||
background: '#0e1a30', border: '1px solid #1e3a5f', borderRadius: '6px',
|
||||
padding: '10px 14px', fontSize: '12px', color: '#7eb8f7', marginBottom: '18px',
|
||||
},
|
||||
label: { fontSize: '11px', color: '#9ca0b8', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '5px' },
|
||||
input: {
|
||||
width: '100%', background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '9px 12px', fontSize: '13px', marginBottom: '14px',
|
||||
outline: 'none', boxSizing: 'border-box',
|
||||
},
|
||||
textarea: {
|
||||
width: '100%', background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '9px 12px', fontSize: '13px', marginBottom: '14px',
|
||||
outline: 'none', boxSizing: 'border-box', minHeight: '80px', resize: 'vertical',
|
||||
},
|
||||
divider: { borderTop: '1px solid #1c1d29', margin: '16px 0' },
|
||||
sectionTitle: {
|
||||
fontSize: '11px', fontWeight: 700, color: '#9ca0b8', textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px', marginBottom: '12px',
|
||||
},
|
||||
amendRow: {
|
||||
background: '#0d0e14', border: '1px solid #1c1d29', borderRadius: '6px',
|
||||
padding: '10px 12px', marginBottom: '8px', fontSize: '12px',
|
||||
},
|
||||
amendField: { fontWeight: 700, color: '#c0c2d6', marginBottom: '4px' },
|
||||
amendOld: { color: '#ff7070', textDecoration: 'line-through', marginRight: '6px' },
|
||||
amendNew: { color: '#9ef7c1' },
|
||||
amendMeta: { fontSize: '10px', color: '#555a7a', marginTop: '4px' },
|
||||
row: { display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '6px' },
|
||||
btn: (color, bg) => ({
|
||||
padding: '8px 18px', borderRadius: '6px', fontWeight: 700, fontSize: '13px',
|
||||
cursor: 'pointer', border: `1px solid ${color}`, color, background: bg || 'none',
|
||||
}),
|
||||
error: {
|
||||
background: '#3c1114', border: '1px solid #f5c6cb', borderRadius: '6px',
|
||||
padding: '10px 12px', fontSize: '12px', color: '#ffb3b8', marginBottom: '14px',
|
||||
},
|
||||
};
|
||||
|
||||
function fmtDt(iso) {
|
||||
if (!iso) return '—';
|
||||
return new Date(iso).toLocaleString('en-US', { timeZone: 'America/Chicago', dateStyle: 'medium', timeStyle: 'short' });
|
||||
}
|
||||
|
||||
export default function AmendViolationModal({ violation, onClose, onSaved }) {
|
||||
const [fields, setFields] = useState({
|
||||
incident_time: violation.incident_time || '',
|
||||
location: violation.location || '',
|
||||
details: violation.details || '',
|
||||
submitted_by: violation.submitted_by || '',
|
||||
witness_name: violation.witness_name || '',
|
||||
});
|
||||
const [changedBy, setChangedBy] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [amendments, setAmendments] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
axios.get(`/api/violations/${violation.id}/amendments`)
|
||||
.then(r => setAmendments(r.data))
|
||||
.catch(() => {});
|
||||
}, [violation.id]);
|
||||
|
||||
const hasChanges = Object.entries(fields).some(
|
||||
([k, v]) => v !== (violation[k] || '')
|
||||
);
|
||||
|
||||
const handleSave = async () => {
|
||||
setError('');
|
||||
setSaving(true);
|
||||
try {
|
||||
// Only send fields that actually changed
|
||||
const patch = Object.fromEntries(
|
||||
Object.entries(fields).filter(([k, v]) => v !== (violation[k] || ''))
|
||||
);
|
||||
await axios.patch(`/api/violations/${violation.id}/amend`, { ...patch, changed_by: changedBy || null });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError(e.response?.data?.error || 'Failed to save amendment');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const set = (field, value) => setFields(prev => ({ ...prev, [field]: value }));
|
||||
|
||||
return (
|
||||
<div style={s.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
|
||||
<div style={s.modal}>
|
||||
<div style={s.header}>
|
||||
<div style={s.headerLeft}>
|
||||
<div style={s.title}>Amend Violation</div>
|
||||
<div style={s.subtitle}>
|
||||
CPAS-{String(violation.id).padStart(5, '0')} · {violation.violation_name} · {violation.incident_date}
|
||||
</div>
|
||||
</div>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
</div>
|
||||
|
||||
<div style={s.body}>
|
||||
<div style={s.notice}>
|
||||
Only non-scoring fields can be amended. Point values, violation type, and incident date
|
||||
are immutable — delete and re-submit if those need to change.
|
||||
</div>
|
||||
|
||||
{error && <div style={s.error}>{error}</div>}
|
||||
|
||||
{Object.entries(FIELD_LABELS).map(([field, label]) => (
|
||||
<div key={field}>
|
||||
<div style={s.label}>{label}</div>
|
||||
{field === 'details' ? (
|
||||
<textarea
|
||||
style={s.textarea}
|
||||
value={fields[field]}
|
||||
onChange={e => set(field, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
style={s.input}
|
||||
value={fields[field]}
|
||||
onChange={e => set(field, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div style={s.label}>Your Name (recorded in amendment log)</div>
|
||||
<input
|
||||
style={s.input}
|
||||
value={changedBy}
|
||||
onChange={e => setChangedBy(e.target.value)}
|
||||
placeholder="Optional but recommended"
|
||||
/>
|
||||
|
||||
<div style={s.row}>
|
||||
<button style={s.btn('#888')} onClick={onClose}>Cancel</button>
|
||||
<button
|
||||
style={s.btn('#fff', hasChanges ? '#667eea' : '#333')}
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || saving}
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save Amendment'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{amendments.length > 0 && (
|
||||
<>
|
||||
<div style={s.divider} />
|
||||
<div style={s.sectionTitle}>Amendment History ({amendments.length})</div>
|
||||
{amendments.map(a => (
|
||||
<div key={a.id} style={s.amendRow}>
|
||||
<div style={s.amendField}>{FIELD_LABELS[a.field_name] || a.field_name}</div>
|
||||
<div>
|
||||
<span style={s.amendOld}>{a.old_value || '(empty)'}</span>
|
||||
<span style={{ color: '#555', marginRight: '6px' }}>→</span>
|
||||
<span style={s.amendNew}>{a.new_value || '(empty)'}</span>
|
||||
</div>
|
||||
<div style={s.amendMeta}>
|
||||
{a.changed_by ? `by ${a.changed_by} · ` : ''}{fmtDt(a.created_at)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
200
client/src/components/AuditLog.jsx
Normal file
200
client/src/components/AuditLog.jsx
Normal file
@@ -0,0 +1,200 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const ACTION_COLORS = {
|
||||
employee_created: '#667eea',
|
||||
employee_edited: '#9b8af8',
|
||||
employee_merged: '#f0a500',
|
||||
violation_created: '#28a745',
|
||||
violation_amended: '#4db6ac',
|
||||
violation_negated: '#ffc107',
|
||||
violation_restored:'#17a2b8',
|
||||
violation_deleted: '#dc3545',
|
||||
};
|
||||
|
||||
const ACTION_LABELS = {
|
||||
employee_created: 'Employee Created',
|
||||
employee_edited: 'Employee Edited',
|
||||
employee_merged: 'Employee Merged',
|
||||
violation_created: 'Violation Logged',
|
||||
violation_amended: 'Violation Amended',
|
||||
violation_negated: 'Violation Negated',
|
||||
violation_restored:'Violation Restored',
|
||||
violation_deleted: 'Violation Deleted',
|
||||
};
|
||||
|
||||
const ENTITY_LABELS = {
|
||||
employee: 'Employee',
|
||||
violation: 'Violation',
|
||||
};
|
||||
|
||||
const s = {
|
||||
overlay: {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)',
|
||||
zIndex: 1000, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end',
|
||||
},
|
||||
panel: {
|
||||
background: '#111217', color: '#f8f9fa', width: '680px', maxWidth: '95vw',
|
||||
height: '100vh', overflowY: 'auto', boxShadow: '-4px 0 24px rgba(0,0,0,0.7)',
|
||||
display: 'flex', flexDirection: 'column',
|
||||
},
|
||||
header: {
|
||||
background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
|
||||
padding: '22px 26px', position: 'sticky', top: 0, zIndex: 10,
|
||||
borderBottom: '1px solid #222',
|
||||
},
|
||||
headerRow: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
|
||||
title: { fontSize: '17px', fontWeight: 700 },
|
||||
subtitle: { fontSize: '12px', color: '#9ca0b8', marginTop: '3px' },
|
||||
closeBtn: {
|
||||
background: 'none', border: 'none', color: 'white', fontSize: '22px',
|
||||
cursor: 'pointer', lineHeight: 1,
|
||||
},
|
||||
filters: {
|
||||
padding: '14px 26px', borderBottom: '1px solid #1c1d29',
|
||||
display: 'flex', gap: '10px', flexWrap: 'wrap',
|
||||
},
|
||||
select: {
|
||||
background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '7px 12px', fontSize: '12px', outline: 'none',
|
||||
},
|
||||
body: { padding: '16px 26px', flex: 1 },
|
||||
entry: {
|
||||
borderBottom: '1px solid #1c1d29', padding: '12px 0',
|
||||
display: 'flex', gap: '12px', alignItems: 'flex-start',
|
||||
},
|
||||
dot: (action) => ({
|
||||
width: '8px', height: '8px', borderRadius: '50%', marginTop: '5px', flexShrink: 0,
|
||||
background: ACTION_COLORS[action] || '#555',
|
||||
}),
|
||||
entryMain: { flex: 1, minWidth: 0 },
|
||||
actionBadge: (action) => ({
|
||||
display: 'inline-block', padding: '2px 8px', borderRadius: '10px',
|
||||
fontSize: '10px', fontWeight: 700, letterSpacing: '0.3px', marginRight: '6px',
|
||||
background: (ACTION_COLORS[action] || '#555') + '22',
|
||||
color: ACTION_COLORS[action] || '#aaa',
|
||||
border: `1px solid ${(ACTION_COLORS[action] || '#555')}44`,
|
||||
}),
|
||||
entityRef: { fontSize: '11px', color: '#9ca0b8' },
|
||||
details: { fontSize: '11px', color: '#667', marginTop: '4px', fontFamily: 'monospace', wordBreak: 'break-all' },
|
||||
meta: { fontSize: '10px', color: '#555a7a', marginTop: '4px' },
|
||||
empty: { textAlign: 'center', color: '#555a7a', padding: '60px 0', fontSize: '13px' },
|
||||
loadMore: {
|
||||
width: '100%', background: 'none', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#9ca0b8', padding: '10px', cursor: 'pointer', fontSize: '12px', marginTop: '16px',
|
||||
},
|
||||
};
|
||||
|
||||
function fmtDt(iso) {
|
||||
if (!iso) return '—';
|
||||
return new Date(iso).toLocaleString('en-US', {
|
||||
timeZone: 'America/Chicago', dateStyle: 'medium', timeStyle: 'short',
|
||||
});
|
||||
}
|
||||
|
||||
function renderDetails(detailsStr) {
|
||||
if (!detailsStr) return null;
|
||||
try {
|
||||
const obj = JSON.parse(detailsStr);
|
||||
return JSON.stringify(obj, null, 0)
|
||||
.replace(/^\{/, '').replace(/\}$/, '').replace(/","/g, ' ');
|
||||
} catch {
|
||||
return detailsStr;
|
||||
}
|
||||
}
|
||||
|
||||
export default function AuditLog({ onClose }) {
|
||||
const [entries, setEntries] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [filterType, setFilterType] = useState('');
|
||||
const [filterAction, setFilterAction] = useState('');
|
||||
const LIMIT = 50;
|
||||
|
||||
const load = useCallback((reset = false) => {
|
||||
setLoading(true);
|
||||
const o = reset ? 0 : offset;
|
||||
const params = { limit: LIMIT, offset: o };
|
||||
if (filterType) params.entity_type = filterType;
|
||||
if (filterAction) params.action = filterAction; // future: server-side action filter
|
||||
axios.get('/api/audit', { params })
|
||||
.then(r => {
|
||||
const data = r.data;
|
||||
// Client-side action filter (cheap enough at this scale)
|
||||
const filtered = filterAction ? data.filter(e => e.action === filterAction) : data;
|
||||
setEntries(prev => reset ? filtered : [...prev, ...filtered]);
|
||||
setHasMore(data.length === LIMIT);
|
||||
setOffset(o + LIMIT);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [offset, filterType, filterAction]);
|
||||
|
||||
useEffect(() => { load(true); }, [filterType, filterAction]); // eslint-disable-line
|
||||
|
||||
const handleOverlay = e => { if (e.target === e.currentTarget) onClose(); };
|
||||
|
||||
return (
|
||||
<div style={s.overlay} onClick={handleOverlay}>
|
||||
<div style={s.panel} onClick={e => e.stopPropagation()}>
|
||||
<div style={s.header}>
|
||||
<div style={s.headerRow}>
|
||||
<div>
|
||||
<div style={s.title}>Audit Log</div>
|
||||
<div style={s.subtitle}>All system write actions — append-only</div>
|
||||
</div>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={s.filters}>
|
||||
<select style={s.select} value={filterType} onChange={e => { setFilterType(e.target.value); setOffset(0); }}>
|
||||
<option value="">All entity types</option>
|
||||
{Object.entries(ENTITY_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
<select style={s.select} value={filterAction} onChange={e => { setFilterAction(e.target.value); setOffset(0); }}>
|
||||
<option value="">All actions</option>
|
||||
{Object.entries(ACTION_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style={s.body}>
|
||||
{loading && entries.length === 0 ? (
|
||||
<div style={s.empty}>Loading…</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div style={s.empty}>No audit entries found.</div>
|
||||
) : (
|
||||
entries.map(e => (
|
||||
<div key={e.id} style={s.entry}>
|
||||
<div style={s.dot(e.action)} />
|
||||
<div style={s.entryMain}>
|
||||
<div>
|
||||
<span style={s.actionBadge(e.action)}>
|
||||
{ACTION_LABELS[e.action] || e.action}
|
||||
</span>
|
||||
<span style={s.entityRef}>
|
||||
{ENTITY_LABELS[e.entity_type] || e.entity_type}
|
||||
{e.entity_id ? ` #${e.entity_id}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
{e.details && (
|
||||
<div style={s.details}>{renderDetails(e.details)}</div>
|
||||
)}
|
||||
<div style={s.meta}>
|
||||
{e.performed_by ? `by ${e.performed_by} · ` : ''}{fmtDt(e.created_at)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
{hasMore && (
|
||||
<button style={s.loadMore} onClick={() => load(false)}>
|
||||
Load more
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,9 @@ import React, { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import CpasBadge, { getTier } from './CpasBadge';
|
||||
import EmployeeModal from './EmployeeModal';
|
||||
import AuditLog from './AuditLog';
|
||||
|
||||
const AT_RISK_THRESHOLD = 2; // points within next tier boundary
|
||||
const AT_RISK_THRESHOLD = 2;
|
||||
|
||||
const TIERS = [
|
||||
{ min: 0, max: 4 },
|
||||
@@ -17,8 +18,7 @@ const TIERS = [
|
||||
|
||||
function nextTierBoundary(points) {
|
||||
for (const t of TIERS) {
|
||||
if (points >= t.min && points <= t.max && t.max < 999)
|
||||
return t.max + 1;
|
||||
if (points >= t.min && points <= t.max && t.max < 999) return t.max + 1;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -29,22 +29,24 @@ function isAtRisk(points) {
|
||||
}
|
||||
|
||||
const s = {
|
||||
wrap: { padding: '40px' },
|
||||
wrap: { padding: '32px 40px', color: '#f8f9fa' },
|
||||
header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '12px' },
|
||||
title: { fontSize: '24px', fontWeight: 700, color: '#2c3e50' },
|
||||
subtitle: { fontSize: '13px', color: '#888', marginTop: '3px' },
|
||||
title: { fontSize: '24px', fontWeight: 700, color: '#f8f9fa' },
|
||||
subtitle: { fontSize: '13px', color: '#b5b5c0', marginTop: '3px' },
|
||||
statsRow: { display: 'flex', gap: '16px', flexWrap: 'wrap', marginBottom: '28px' },
|
||||
statCard: { flex: '1', minWidth: '140px', background: '#f8f9fa', border: '1px solid #dee2e6', borderRadius: '8px', padding: '16px', textAlign: 'center' },
|
||||
statNum: { fontSize: '28px', fontWeight: 800, color: '#2c3e50' },
|
||||
statLbl: { fontSize: '11px', color: '#888', marginTop: '4px' },
|
||||
search: { padding: '10px 14px', border: '1px solid #ddd', borderRadius: '6px', fontSize: '14px', width: '260px' },
|
||||
table: { width: '100%', borderCollapse: 'collapse', background: 'white', borderRadius: '8px', overflow: 'hidden', boxShadow: '0 1px 4px rgba(0,0,0,0.08)' },
|
||||
th: { background: '#34495e', color: 'white', padding: '10px 14px', textAlign: 'left', fontSize: '12px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' },
|
||||
td: { padding: '11px 14px', borderBottom: '1px solid #f0f0f0', fontSize: '13px', verticalAlign: 'middle' },
|
||||
nameBtn: { background: 'none', border: 'none', cursor: 'pointer', fontWeight: 600, color: '#667eea', fontSize: '14px', padding: 0, textDecoration: 'underline dotted' },
|
||||
atRiskBadge: { display: 'inline-block', marginLeft: '8px', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#fff3cd', color: '#856404', border: '1px solid #ffc107', verticalAlign: 'middle' },
|
||||
zeroRow: { color: '#aaa', fontStyle: 'italic', fontSize: '12px' },
|
||||
refreshBtn:{ padding: '9px 18px', background: '#667eea', color: 'white', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
|
||||
statCard: { flex: '1', minWidth: '140px', background: '#181924', border: '1px solid #30313f', borderRadius: '8px', padding: '16px', textAlign: 'center' },
|
||||
statNum: { fontSize: '28px', fontWeight: 800, color: '#f8f9fa' },
|
||||
statLbl: { fontSize: '11px', color: '#b5b5c0', marginTop: '4px' },
|
||||
search: { padding: '10px 14px', border: '1px solid #333544', borderRadius: '6px', fontSize: '14px', width: '260px', background: '#050608', color: '#f8f9fa' },
|
||||
table: { width: '100%', borderCollapse: 'collapse', background: '#111217', borderRadius: '8px', overflow: 'hidden', boxShadow: '0 1px 8px rgba(0,0,0,0.6)', border: '1px solid #222' },
|
||||
th: { background: '#000000', color: '#f8f9fa', padding: '10px 14px', textAlign: 'left', fontSize: '12px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' },
|
||||
td: { padding: '11px 14px', borderBottom: '1px solid #1c1d29', fontSize: '13px', verticalAlign: 'middle', color: '#f8f9fa' },
|
||||
nameBtn: { background: 'none', border: 'none', cursor: 'pointer', fontWeight: 600, color: '#d4af37', fontSize: '14px', padding: 0, textDecoration: 'underline dotted' },
|
||||
atRiskBadge: { display: 'inline-block', marginLeft: '8px', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#3b2e00', color: '#ffd666', border: '1px solid #d4af37', verticalAlign: 'middle' },
|
||||
zeroRow: { color: '#77798a', fontStyle: 'italic', fontSize: '12px' },
|
||||
toolbarRight: { display: 'flex', gap: '10px', alignItems: 'center' },
|
||||
refreshBtn: { padding: '9px 18px', background: '#d4af37', color: '#000', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
|
||||
auditBtn: { padding: '9px 18px', background: 'none', color: '#9ca0b8', border: '1px solid #2a2b3a', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
|
||||
};
|
||||
|
||||
export default function Dashboard() {
|
||||
@@ -52,6 +54,7 @@ export default function Dashboard() {
|
||||
const [filtered, setFiltered] = useState([]);
|
||||
const [search, setSearch] = useState('');
|
||||
const [selectedId, setSelectedId] = useState(null);
|
||||
const [showAudit, setShowAudit] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const load = useCallback(() => {
|
||||
@@ -78,45 +81,50 @@ export default function Dashboard() {
|
||||
const maxPoints = employees.reduce((m, e) => Math.max(m, e.active_points), 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={s.wrap}>
|
||||
<div style={s.header}>
|
||||
<div>
|
||||
<div style={s.title}>Company Dashboard</div>
|
||||
<div style={s.subtitle}>Click any employee name to view their full profile</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
|
||||
<input style={s.search} placeholder="Search name, dept, supervisor…" value={search} onChange={e => setSearch(e.target.value)} />
|
||||
<div style={s.toolbarRight}>
|
||||
<input
|
||||
style={s.search}
|
||||
placeholder="Search name, dept, supervisor…"
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
/>
|
||||
<button style={s.auditBtn} onClick={() => setShowAudit(true)}>📋 Audit Log</button>
|
||||
<button style={s.refreshBtn} onClick={load}>↻ Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Stat cards ───────────────────────────────────────── */}
|
||||
<div style={s.statsRow}>
|
||||
<div style={s.statCard}>
|
||||
<div style={s.statNum}>{employees.length}</div>
|
||||
<div style={s.statLbl}>Total Employees</div>
|
||||
</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #28a745' }}>
|
||||
<div style={{ ...s.statNum, color: '#28a745' }}>{cleanCount}</div>
|
||||
<div style={{ ...s.statNum, color: '#6ee7b7' }}>{cleanCount}</div>
|
||||
<div style={s.statLbl}>Elite Standing (0 pts)</div>
|
||||
</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #856404' }}>
|
||||
<div style={{ ...s.statNum, color: '#856404' }}>{activeCount}</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #d4af37' }}>
|
||||
<div style={{ ...s.statNum, color: '#ffd666' }}>{activeCount}</div>
|
||||
<div style={s.statLbl}>With Active Points</div>
|
||||
</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #ffc107' }}>
|
||||
<div style={{ ...s.statNum, color: '#856404' }}>{atRiskCount}</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #ffb020' }}>
|
||||
<div style={{ ...s.statNum, color: '#ffdf8a' }}>{atRiskCount}</div>
|
||||
<div style={s.statLbl}>At Risk (≤{AT_RISK_THRESHOLD} pts to next tier)</div>
|
||||
</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #c0392b' }}>
|
||||
<div style={{ ...s.statNum, color: '#c0392b' }}>{maxPoints}</div>
|
||||
<div style={{ ...s.statNum, color: '#ff8a80' }}>{maxPoints}</div>
|
||||
<div style={s.statLbl}>Highest Active Score</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Scoreboard table ─────────────────────────────────── */}
|
||||
{loading ? (
|
||||
<p style={{ color: '#aaa', textAlign: 'center', padding: '40px' }}>Loading…</p>
|
||||
<p style={{ color: '#77798a', textAlign: 'center', padding: '40px' }}>Loading…</p>
|
||||
) : (
|
||||
<table style={s.table}>
|
||||
<thead>
|
||||
@@ -132,42 +140,54 @@ export default function Dashboard() {
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.length === 0 && (
|
||||
<tr><td colSpan={7} style={{ ...s.td, textAlign: 'center', ...s.zeroRow }}>No employees found.</td></tr>
|
||||
<tr>
|
||||
<td colSpan={7} style={{ ...s.td, textAlign: 'center', ...s.zeroRow }}>
|
||||
No employees found.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{filtered.map((emp, i) => {
|
||||
const risk = isAtRisk(emp.active_points);
|
||||
const tier = getTier(emp.active_points);
|
||||
const boundary = nextTierBoundary(emp.active_points);
|
||||
return (
|
||||
<tr key={emp.id} style={{ background: risk ? '#fffdf0' : i % 2 === 0 ? 'white' : '#fafafa' }}>
|
||||
<td style={{ ...s.td, color: '#aaa', fontSize: '12px' }}>{i + 1}</td>
|
||||
<tr
|
||||
key={emp.id}
|
||||
style={{ background: risk ? '#181200' : i % 2 === 0 ? '#111217' : '#151622' }}
|
||||
>
|
||||
<td style={{ ...s.td, color: '#77798a', fontSize: '12px' }}>{i + 1}</td>
|
||||
<td style={s.td}>
|
||||
<button style={s.nameBtn} onClick={() => setSelectedId(emp.id)}>{emp.name}</button>
|
||||
<button style={s.nameBtn} onClick={() => setSelectedId(emp.id)}>
|
||||
{emp.name}
|
||||
</button>
|
||||
{risk && (
|
||||
<span style={s.atRiskBadge}>
|
||||
⚠ {boundary - emp.active_points} pt{boundary - emp.active_points > 1 ? 's' : ''} to {getTier(boundary).label.split('—')[0].trim()}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td style={{ ...s.td, color: '#666' }}>{emp.department || '—'}</td>
|
||||
<td style={{ ...s.td, color: '#666' }}>{emp.supervisor || '—'}</td>
|
||||
<td style={{ ...s.td, color: '#c0c2d6' }}>{emp.department || '—'}</td>
|
||||
<td style={{ ...s.td, color: '#c0c2d6' }}>{emp.supervisor || '—'}</td>
|
||||
<td style={s.td}><CpasBadge points={emp.active_points} /></td>
|
||||
<td style={{ ...s.td, fontWeight: 700, color: tier.color, fontSize: '16px' }}>{emp.active_points}</td>
|
||||
<td style={{ ...s.td, color: '#666' }}>{emp.violation_count}</td>
|
||||
<td style={{ ...s.td, fontWeight: 700, color: tier.color, fontSize: '16px' }}>
|
||||
{emp.active_points}
|
||||
</td>
|
||||
<td style={{ ...s.td, color: '#c0c2d6' }}>{emp.violation_count}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Employee profile modal ───────────────────────────── */}
|
||||
{selectedId && (
|
||||
<EmployeeModal
|
||||
employeeId={selectedId}
|
||||
onClose={() => { setSelectedId(null); load(); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{showAudit && <AuditLog onClose={() => setShowAudit(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
189
client/src/components/EditEmployeeModal.jsx
Normal file
189
client/src/components/EditEmployeeModal.jsx
Normal file
@@ -0,0 +1,189 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const s = {
|
||||
overlay: {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)',
|
||||
zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
},
|
||||
modal: {
|
||||
background: '#111217', color: '#f8f9fa', width: '480px', maxWidth: '95vw',
|
||||
borderRadius: '10px', boxShadow: '0 8px 40px rgba(0,0,0,0.8)',
|
||||
border: '1px solid #222', overflow: 'hidden',
|
||||
},
|
||||
header: {
|
||||
background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
|
||||
padding: '18px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
borderBottom: '1px solid #222',
|
||||
},
|
||||
title: { fontSize: '15px', fontWeight: 700 },
|
||||
closeBtn: {
|
||||
background: 'none', border: 'none', color: 'white', fontSize: '20px',
|
||||
cursor: 'pointer', lineHeight: 1,
|
||||
},
|
||||
body: { padding: '22px' },
|
||||
tabs: { display: 'flex', gap: '4px', marginBottom: '20px' },
|
||||
tab: (active) => ({
|
||||
flex: 1, padding: '8px', borderRadius: '6px', cursor: 'pointer', fontSize: '12px',
|
||||
fontWeight: 700, textAlign: 'center', border: '1px solid',
|
||||
background: active ? '#1a1c2e' : 'none',
|
||||
borderColor: active ? '#667eea' : '#2a2b3a',
|
||||
color: active ? '#667eea' : '#777',
|
||||
}),
|
||||
label: { fontSize: '11px', color: '#9ca0b8', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '5px' },
|
||||
input: {
|
||||
width: '100%', background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '9px 12px', fontSize: '13px', marginBottom: '14px',
|
||||
outline: 'none', boxSizing: 'border-box',
|
||||
},
|
||||
select: {
|
||||
width: '100%', background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '9px 12px', fontSize: '13px', marginBottom: '14px',
|
||||
outline: 'none', boxSizing: 'border-box',
|
||||
},
|
||||
row: { display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '6px' },
|
||||
btn: (color, bg) => ({
|
||||
padding: '8px 18px', borderRadius: '6px', fontWeight: 700, fontSize: '13px',
|
||||
cursor: 'pointer', border: `1px solid ${color}`, color, background: bg || 'none',
|
||||
}),
|
||||
error: {
|
||||
background: '#3c1114', border: '1px solid #f5c6cb', borderRadius: '6px',
|
||||
padding: '10px 12px', fontSize: '12px', color: '#ffb3b8', marginBottom: '14px',
|
||||
},
|
||||
success: {
|
||||
background: '#0a2e1f', border: '1px solid #0f5132', borderRadius: '6px',
|
||||
padding: '10px 12px', fontSize: '12px', color: '#9ef7c1', marginBottom: '14px',
|
||||
},
|
||||
mergeWarning: {
|
||||
background: '#2a1f00', border: '1px solid #7a5000', borderRadius: '6px',
|
||||
padding: '12px', fontSize: '12px', color: '#ffc107', marginBottom: '14px', lineHeight: 1.5,
|
||||
},
|
||||
};
|
||||
|
||||
export default function EditEmployeeModal({ employee, onClose, onSaved }) {
|
||||
const [tab, setTab] = useState('edit');
|
||||
|
||||
// Edit state
|
||||
const [name, setName] = useState(employee.name);
|
||||
const [department, setDepartment] = useState(employee.department || '');
|
||||
const [supervisor, setSupervisor] = useState(employee.supervisor || '');
|
||||
const [editError, setEditError] = useState('');
|
||||
const [editSaving, setEditSaving] = useState(false);
|
||||
|
||||
// Merge state
|
||||
const [allEmployees, setAllEmployees] = useState([]);
|
||||
const [sourceId, setSourceId] = useState('');
|
||||
const [mergeError, setMergeError] = useState('');
|
||||
const [mergeResult, setMergeResult] = useState(null);
|
||||
const [merging, setMerging] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (tab === 'merge') {
|
||||
axios.get('/api/employees').then(r => setAllEmployees(r.data));
|
||||
}
|
||||
}, [tab]);
|
||||
|
||||
const handleEdit = async () => {
|
||||
setEditError('');
|
||||
setEditSaving(true);
|
||||
try {
|
||||
await axios.patch(`/api/employees/${employee.id}`, { name, department, supervisor });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setEditError(e.response?.data?.error || 'Failed to save changes');
|
||||
} finally {
|
||||
setEditSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMerge = async () => {
|
||||
if (!sourceId) return setMergeError('Select an employee to merge in');
|
||||
setMergeError('');
|
||||
setMerging(true);
|
||||
try {
|
||||
const r = await axios.post(`/api/employees/${employee.id}/merge`, { source_id: parseInt(sourceId) });
|
||||
setMergeResult(r.data);
|
||||
onSaved(); // refresh dashboard / parent list
|
||||
} catch (e) {
|
||||
setMergeError(e.response?.data?.error || 'Merge failed');
|
||||
} finally {
|
||||
setMerging(false);
|
||||
}
|
||||
};
|
||||
|
||||
const otherEmployees = allEmployees.filter(e => e.id !== employee.id);
|
||||
|
||||
return (
|
||||
<div style={s.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
|
||||
<div style={s.modal}>
|
||||
<div style={s.header}>
|
||||
<div style={s.title}>Edit Employee</div>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
</div>
|
||||
<div style={s.body}>
|
||||
<div style={s.tabs}>
|
||||
<button style={s.tab(tab === 'edit')} onClick={() => setTab('edit')}>Edit Details</button>
|
||||
<button style={s.tab(tab === 'merge')} onClick={() => setTab('merge')}>Merge Duplicate</button>
|
||||
</div>
|
||||
|
||||
{tab === 'edit' && (
|
||||
<>
|
||||
{editError && <div style={s.error}>{editError}</div>}
|
||||
<div style={s.label}>Full Name</div>
|
||||
<input style={s.input} value={name} onChange={e => setName(e.target.value)} />
|
||||
<div style={s.label}>Department</div>
|
||||
<input style={s.input} value={department} onChange={e => setDepartment(e.target.value)} placeholder="Optional" />
|
||||
<div style={s.label}>Supervisor</div>
|
||||
<input style={s.input} value={supervisor} onChange={e => setSupervisor(e.target.value)} placeholder="Optional" />
|
||||
<div style={s.row}>
|
||||
<button style={s.btn('#888')} onClick={onClose}>Cancel</button>
|
||||
<button style={s.btn('#fff', '#667eea')} onClick={handleEdit} disabled={editSaving}>
|
||||
{editSaving ? 'Saving…' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === 'merge' && (
|
||||
<>
|
||||
{mergeResult ? (
|
||||
<div style={s.success}>
|
||||
✓ Merge complete — {mergeResult.violations_reassigned} violation{mergeResult.violations_reassigned !== 1 ? 's' : ''} reassigned
|
||||
to <strong>{employee.name}</strong>. The duplicate record has been removed.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div style={s.mergeWarning}>
|
||||
⚠ This will reassign <strong>all violations</strong> from the selected employee into{' '}
|
||||
<strong>{employee.name}</strong>, then permanently delete the duplicate record.
|
||||
This cannot be undone.
|
||||
</div>
|
||||
{mergeError && <div style={s.error}>{mergeError}</div>}
|
||||
<div style={s.label}>Duplicate to merge into {employee.name}</div>
|
||||
<select style={s.select} value={sourceId} onChange={e => setSourceId(e.target.value)}>
|
||||
<option value="">— select employee —</option>
|
||||
{otherEmployees.map(e => (
|
||||
<option key={e.id} value={e.id}>{e.name}{e.department ? ` (${e.department})` : ''}</option>
|
||||
))}
|
||||
</select>
|
||||
<div style={s.row}>
|
||||
<button style={s.btn('#888')} onClick={onClose}>Cancel</button>
|
||||
<button style={s.btn('#fff', '#c0392b')} onClick={handleMerge} disabled={merging || !sourceId}>
|
||||
{merging ? 'Merging…' : 'Merge & Delete Duplicate'}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mergeResult && (
|
||||
<div style={s.row}>
|
||||
<button style={s.btn('#fff', '#667eea')} onClick={onClose}>Done</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,26 +2,89 @@ import React, { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import CpasBadge, { getTier } from './CpasBadge';
|
||||
import NegateModal from './NegateModal';
|
||||
import EditEmployeeModal from './EditEmployeeModal';
|
||||
import AmendViolationModal from './AmendViolationModal';
|
||||
import ExpirationTimeline from './ExpirationTimeline';
|
||||
import EmployeeNotes from './EmployeeNotes';
|
||||
|
||||
const s = {
|
||||
overlay: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', zIndex: 1000, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end' },
|
||||
panel: { background: 'white', width: '680px', maxWidth: '95vw', height: '100vh', overflowY: 'auto', boxShadow: '-4px 0 24px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column' },
|
||||
header: { background: 'linear-gradient(135deg, #2c3e50, #34495e)', color: 'white', padding: '24px 28px', position: 'sticky', top: 0, zIndex: 10 },
|
||||
closeBtn: { float: 'right', background: 'none', border: 'none', color: 'white', fontSize: '22px', cursor: 'pointer', lineHeight: 1, marginTop: '-2px' },
|
||||
overlay: {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)',
|
||||
zIndex: 1000, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end',
|
||||
},
|
||||
panel: {
|
||||
background: '#111217', color: '#f8f9fa', width: '680px', maxWidth: '95vw',
|
||||
height: '100vh', overflowY: 'auto', boxShadow: '-4px 0 24px rgba(0,0,0,0.7)',
|
||||
display: 'flex', flexDirection: 'column',
|
||||
},
|
||||
header: {
|
||||
background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
|
||||
padding: '24px 28px', position: 'sticky', top: 0, zIndex: 10,
|
||||
borderBottom: '1px solid #222',
|
||||
},
|
||||
headerRow: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' },
|
||||
closeBtn: {
|
||||
float: 'right', background: 'none', border: 'none', color: 'white',
|
||||
fontSize: '22px', cursor: 'pointer', lineHeight: 1, marginTop: '-2px',
|
||||
},
|
||||
editEmpBtn: {
|
||||
background: 'none', border: '1px solid #555', color: '#ccc', borderRadius: '5px',
|
||||
padding: '4px 10px', fontSize: '11px', cursor: 'pointer', marginTop: '8px', fontWeight: 600,
|
||||
},
|
||||
body: { padding: '24px 28px', flex: 1 },
|
||||
scoreRow: { display: 'flex', gap: '12px', flexWrap: 'wrap', marginBottom: '24px' },
|
||||
scoreCard: { flex: '1', minWidth: '100px', background: '#f8f9fa', borderRadius: '8px', padding: '14px', textAlign: 'center', border: '1px solid #dee2e6' },
|
||||
scoreCard: {
|
||||
flex: '1', minWidth: '100px', background: '#181924', borderRadius: '8px',
|
||||
padding: '14px', textAlign: 'center', border: '1px solid #2a2b3a',
|
||||
},
|
||||
scoreNum: { fontSize: '26px', fontWeight: 800 },
|
||||
scoreLbl: { fontSize: '11px', color: '#888', marginTop: '3px' },
|
||||
sectionHd: { fontSize: '13px', fontWeight: 700, color: '#34495e', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '10px', marginTop: '24px' },
|
||||
table: { width: '100%', borderCollapse: 'collapse', fontSize: '12px' },
|
||||
th: { background: '#f1f3f5', padding: '8px 10px', textAlign: 'left', color: '#555', fontWeight: 600, fontSize: '11px', textTransform: 'uppercase' },
|
||||
td: { padding: '9px 10px', borderBottom: '1px solid #f0f0f0', verticalAlign: 'top' },
|
||||
negatedRow: { background: '#f8f8f8', color: '#aaa' },
|
||||
actionBtn: (color) => ({ background: 'none', border: `1px solid ${color}`, color, borderRadius: '4px', padding: '3px 8px', fontSize: '11px', cursor: 'pointer', marginRight: '4px', fontWeight: 600 }),
|
||||
resTag: { display: 'inline-block', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#d4edda', color: '#155724', border: '1px solid #c3e6cb' },
|
||||
pdfBtn: { background: 'none', border: '1px solid #667eea', color: '#667eea', borderRadius: '4px', padding: '3px 8px', fontSize: '11px', cursor: 'pointer', fontWeight: 600 },
|
||||
deleteConfirm: { background: '#f8d7da', border: '1px solid #f5c6cb', borderRadius: '6px', padding: '12px', marginTop: '8px', fontSize: '12px' },
|
||||
scoreLbl: { fontSize: '11px', color: '#b5b5c0', marginTop: '3px' },
|
||||
sectionHd: {
|
||||
fontSize: '13px', fontWeight: 700, color: '#f8f9fa', textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px', marginBottom: '10px', marginTop: '24px',
|
||||
},
|
||||
table: {
|
||||
width: '100%', borderCollapse: 'collapse', fontSize: '12px', background: '#181924',
|
||||
borderRadius: '6px', overflow: 'hidden', border: '1px solid #2a2b3a',
|
||||
},
|
||||
th: {
|
||||
background: '#050608', padding: '8px 10px', textAlign: 'left', color: '#f8f9fa',
|
||||
fontWeight: 600, fontSize: '11px', textTransform: 'uppercase',
|
||||
},
|
||||
td: {
|
||||
padding: '9px 10px', borderBottom: '1px solid #202231',
|
||||
verticalAlign: 'top', color: '#f8f9fa',
|
||||
},
|
||||
negatedRow: { background: '#151622', color: '#9ca0b8' },
|
||||
actionBtn: (color) => ({
|
||||
background: 'none', border: `1px solid ${color}`, color,
|
||||
borderRadius: '4px', padding: '3px 8px', fontSize: '11px',
|
||||
cursor: 'pointer', marginRight: '4px', fontWeight: 600,
|
||||
}),
|
||||
resTag: {
|
||||
display: 'inline-block', padding: '2px 8px', borderRadius: '10px',
|
||||
fontSize: '10px', fontWeight: 700, background: '#053321',
|
||||
color: '#9ef7c1', border: '1px solid #0f5132',
|
||||
},
|
||||
pdfBtn: {
|
||||
background: 'none', border: '1px solid #d4af37', color: '#ffd666',
|
||||
borderRadius: '4px', padding: '3px 8px', fontSize: '11px',
|
||||
cursor: 'pointer', fontWeight: 600,
|
||||
},
|
||||
amendBtn: {
|
||||
background: 'none', border: '1px solid #4db6ac', color: '#4db6ac',
|
||||
borderRadius: '4px', padding: '3px 8px', fontSize: '11px',
|
||||
cursor: 'pointer', marginRight: '4px', fontWeight: 600,
|
||||
},
|
||||
deleteConfirm: {
|
||||
background: '#3c1114', border: '1px solid #f5c6cb', borderRadius: '6px',
|
||||
padding: '12px', marginTop: '8px', fontSize: '12px', color: '#ffb3b8',
|
||||
},
|
||||
amendBadge: {
|
||||
display: 'inline-block', marginLeft: '4px', padding: '1px 5px', borderRadius: '8px',
|
||||
fontSize: '9px', fontWeight: 700, background: '#0e2a2a', color: '#4db6ac',
|
||||
border: '1px solid #1a4a4a', verticalAlign: 'middle',
|
||||
},
|
||||
};
|
||||
|
||||
export default function EmployeeModal({ employeeId, onClose }) {
|
||||
@@ -31,6 +94,8 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [negating, setNegating] = useState(null);
|
||||
const [confirmDel, setConfirmDel] = useState(null);
|
||||
const [editingEmp, setEditingEmp] = useState(false);
|
||||
const [amending, setAmending] = useState(null); // violation object
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
@@ -38,12 +103,14 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
axios.get('/api/employees'),
|
||||
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);
|
||||
])
|
||||
.then(([empRes, scoreRes, violRes]) => {
|
||||
const emp = empRes.data.find((e) => e.id === employeeId);
|
||||
setEmployee(emp || null);
|
||||
setScore(scoreRes.data);
|
||||
setViolations(violRes.data);
|
||||
}).finally(() => setLoading(false));
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [employeeId]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
@@ -63,77 +130,110 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
const handleHardDelete = async (id) => {
|
||||
await axios.delete(`/api/violations/${id}`);
|
||||
setConfirmDel(null);
|
||||
load(); // ← refetch employee list, score, and violations
|
||||
load();
|
||||
};
|
||||
|
||||
const handleRestore = async (id) => {
|
||||
await axios.patch(`/api/violations/${id}/restore`);
|
||||
load(); // ← refetch employee list, score, and violations
|
||||
setConfirmDel(null);
|
||||
load();
|
||||
};
|
||||
|
||||
const handleNegate = async ({ resolution_type, details, resolved_by }) => {
|
||||
await axios.patch(`/api/violations/${negating.id}/negate`, { resolution_type, details, resolved_by });
|
||||
setNegating(null);
|
||||
load(); // ← CRITICAL FIX: refetch score immediately after negation
|
||||
setConfirmDel(null);
|
||||
load();
|
||||
};
|
||||
|
||||
const tier = score ? getTier(score.active_points) : null;
|
||||
const active = violations.filter(v => !v.negated);
|
||||
const negated = violations.filter(v => v.negated);
|
||||
const active = violations.filter((v) => !v.negated);
|
||||
const negated = violations.filter((v) => v.negated);
|
||||
|
||||
const handleOverlayClick = (e) => { if (e.target === e.currentTarget) onClose(); };
|
||||
|
||||
return (
|
||||
<div style={s.overlay} onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div style={s.panel}>
|
||||
<div style={s.overlay} onClick={handleOverlayClick}>
|
||||
<div style={s.panel} onClick={(e) => e.stopPropagation()}>
|
||||
|
||||
{/* ── Header ──────────────────────────────────── */}
|
||||
{/* ── Header ── */}
|
||||
<div style={s.header}>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
<div style={{ fontSize: '20px', fontWeight: 700 }}>
|
||||
{loading ? 'Loading…' : (employee?.name || 'Employee Profile')}
|
||||
<div style={s.headerRow}>
|
||||
<div>
|
||||
<div style={{ fontSize: '18px', fontWeight: 700 }}>
|
||||
{employee ? employee.name : 'Employee'}
|
||||
</div>
|
||||
{employee && (
|
||||
<div style={{ fontSize: '12px', opacity: 0.75, marginTop: '4px' }}>
|
||||
{[employee.department, employee.supervisor ? `Supervisor: ${employee.supervisor}` : null].filter(Boolean).join(' · ')}
|
||||
<div style={{ fontSize: '12px', color: '#b5b5c0', marginTop: '4px' }}>
|
||||
{employee.department} {employee.supervisor && `· Supervisor: ${employee.supervisor}`}
|
||||
</div>
|
||||
)}
|
||||
{employee && (
|
||||
<button style={s.editEmpBtn} onClick={() => setEditingEmp(true)}>
|
||||
✎ Edit Employee
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Body ── */}
|
||||
<div style={s.body}>
|
||||
{loading ? (
|
||||
<p style={{ color: '#aaa', textAlign: 'center', paddingTop: '40px' }}>Loading…</p>
|
||||
) : (<>
|
||||
|
||||
{/* ── Score cards ───────────────────────── */}
|
||||
<div style={{ padding: '40px', textAlign: 'center', color: '#b5b5c0' }}>Loading…</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Score Cards */}
|
||||
{score && (
|
||||
<div style={s.scoreRow}>
|
||||
<div style={{ ...s.scoreCard, borderTop: `3px solid ${tier?.color}` }}>
|
||||
<div style={{ ...s.scoreNum, color: tier?.color }}>{score?.active_points ?? 0}</div>
|
||||
<div style={s.scoreCard}>
|
||||
<div style={{ ...s.scoreNum, color: tier?.color || '#f8f9fa' }}>
|
||||
{score.active_points}
|
||||
</div>
|
||||
<div style={s.scoreLbl}>Active Points</div>
|
||||
</div>
|
||||
<div style={s.scoreCard}>
|
||||
<div style={s.scoreNum}>{score?.violation_count ?? 0}</div>
|
||||
<div style={s.scoreLbl}>90-Day Violations</div>
|
||||
<div style={s.scoreNum}>{score.total_violations}</div>
|
||||
<div style={s.scoreLbl}>Total Violations</div>
|
||||
</div>
|
||||
<div style={s.scoreCard}>
|
||||
<div style={s.scoreNum}>{active.length}</div>
|
||||
<div style={s.scoreLbl}>Total On Record</div>
|
||||
</div>
|
||||
<div style={s.scoreCard}>
|
||||
<div style={{ ...s.scoreNum, color: '#888' }}>{negated.length}</div>
|
||||
<div style={s.scoreNum}>{score.negated_count}</div>
|
||||
<div style={s.scoreLbl}>Negated</div>
|
||||
</div>
|
||||
<div style={{ ...s.scoreCard, minWidth: '140px' }}>
|
||||
<div style={{ fontSize: '13px', fontWeight: 700, color: tier?.color || '#f8f9fa' }}>
|
||||
{tier ? tier.label : '–'}
|
||||
</div>
|
||||
<div style={s.scoreLbl}>Current Tier</div>
|
||||
</div>
|
||||
|
||||
{tier && (
|
||||
<div style={{ background: '#f8f9fa', borderRadius: '6px', padding: '10px 14px', marginBottom: '16px', fontSize: '13px', border: `1px solid ${tier.color}33` }}>
|
||||
<strong style={{ color: tier.color }}>{tier.label}</strong>
|
||||
<span style={{ color: '#888', marginLeft: '10px', fontSize: '12px' }}>Rolling 90-day window · Points expire automatically</span>
|
||||
</div>
|
||||
)}
|
||||
{score && <CpasBadge points={score.active_points} style={{ marginBottom: '20px' }} />}
|
||||
|
||||
{/* ── Active violations ─────────────────── */}
|
||||
{/* ── Employee Notes ── */}
|
||||
{employee && (
|
||||
<EmployeeNotes
|
||||
employeeId={employeeId}
|
||||
initialNotes={employee.notes}
|
||||
onSaved={(notes) => setEmployee(prev => ({ ...prev, notes }))}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Expiration Timeline ── */}
|
||||
{score && score.active_points > 0 && (
|
||||
<ExpirationTimeline
|
||||
employeeId={employeeId}
|
||||
currentPoints={score.active_points}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ── Active Violations ── */}
|
||||
<div style={s.sectionHd}>Active Violations</div>
|
||||
{active.length === 0 ? (
|
||||
<p style={{ color: '#aaa', fontSize: '13px', fontStyle: 'italic' }}>No active violations on record.</p>
|
||||
<div style={{ color: '#777990', fontStyle: 'italic', fontSize: '12px' }}>
|
||||
No active violations on record.
|
||||
</div>
|
||||
) : (
|
||||
<table style={s.table}>
|
||||
<thead>
|
||||
@@ -145,29 +245,62 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{active.map(v => (
|
||||
{active.map((v) => (
|
||||
<tr key={v.id}>
|
||||
<td style={s.td}>{v.incident_date}</td>
|
||||
<td style={s.td}>
|
||||
<div style={{ fontWeight: 600 }}>{v.violation_name}</div>
|
||||
<div style={{ color: '#888', fontSize: '11px' }}>{v.category}</div>
|
||||
{v.details && <div style={{ color: '#666', fontSize: '11px', marginTop: '3px', fontStyle: 'italic' }}>{v.details}</div>}
|
||||
<div style={{ fontWeight: 600 }}>
|
||||
{v.violation_name}
|
||||
{v.amendment_count > 0 && (
|
||||
<span style={s.amendBadge}>{v.amendment_count} edit{v.amendment_count !== 1 ? 's' : ''}</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ fontSize: '10px', color: '#9ca0b8' }}>{v.category}</div>
|
||||
{v.details && (
|
||||
<div style={{ fontSize: '10px', color: '#b5b5c0', marginTop: '2px' }}>{v.details}</div>
|
||||
)}
|
||||
</td>
|
||||
<td style={{ ...s.td, fontWeight: 700, color: '#c0392b' }}>{v.points}</td>
|
||||
<td style={{ ...s.td, fontWeight: 700 }}>{v.points}</td>
|
||||
<td style={s.td}>
|
||||
<button style={s.actionBtn('#856404')} onClick={() => setNegating(v)}>⊘ Negate</button>
|
||||
<button style={s.pdfBtn} onClick={() => handleDownloadPdf(v.id, employee?.name, v.incident_date)}>PDF</button>
|
||||
<br />
|
||||
{confirmDel === v.id ? (
|
||||
<button style={s.amendBtn} onClick={(e) => { e.stopPropagation(); setAmending(v); }}>
|
||||
Amend
|
||||
</button>
|
||||
<button
|
||||
style={s.actionBtn('#ffc107')}
|
||||
onClick={(e) => { e.stopPropagation(); setNegating(v); setConfirmDel(null); }}
|
||||
>
|
||||
Negate
|
||||
</button>
|
||||
<button
|
||||
style={s.actionBtn('#ff4d4f')}
|
||||
onClick={(e) => { e.stopPropagation(); setConfirmDel(confirmDel === v.id ? null : v.id); }}
|
||||
>
|
||||
{confirmDel === v.id ? 'Cancel' : 'Delete'}
|
||||
</button>
|
||||
<button
|
||||
style={s.pdfBtn}
|
||||
onClick={(e) => { e.stopPropagation(); handleDownloadPdf(v.id, employee?.name, v.incident_date); }}
|
||||
>
|
||||
PDF
|
||||
</button>
|
||||
{confirmDel === v.id && (
|
||||
<div style={s.deleteConfirm}>
|
||||
<strong>Permanently delete?</strong> This cannot be undone.
|
||||
<div style={{ marginTop: '8px', display: 'flex', gap: '8px' }}>
|
||||
<button style={s.actionBtn('#c0392b')} onClick={() => handleHardDelete(v.id)}>Confirm Delete</button>
|
||||
<button style={s.actionBtn('#666')} onClick={() => setConfirmDel(null)}>Cancel</button>
|
||||
Permanently delete? This cannot be undone.
|
||||
<div style={{ marginTop: '8px' }}>
|
||||
<button
|
||||
style={s.actionBtn('#ff4d4f')}
|
||||
onClick={(e) => { e.stopPropagation(); handleHardDelete(v.id); }}
|
||||
>
|
||||
Confirm Delete
|
||||
</button>
|
||||
<button
|
||||
style={s.actionBtn('#888')}
|
||||
onClick={(e) => { e.stopPropagation(); setConfirmDel(null); }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button style={{ ...s.actionBtn('#c0392b'), marginTop: '4px' }} onClick={() => setConfirmDel(v.id)}>✕ Delete</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
@@ -176,9 +309,10 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
</table>
|
||||
)}
|
||||
|
||||
{/* ── Negated violations ────────────────── */}
|
||||
{negated.length > 0 && (<>
|
||||
<div style={s.sectionHd}>Negated / Resolved Violations</div>
|
||||
{/* ── Negated / Resolved Violations ── */}
|
||||
{negated.length > 0 && (
|
||||
<>
|
||||
<div style={s.sectionHd}>Negated / Resolved</div>
|
||||
<table style={s.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -190,44 +324,76 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{negated.map(v => (
|
||||
{negated.map((v) => (
|
||||
<tr key={v.id} style={s.negatedRow}>
|
||||
<td style={s.td}>{v.incident_date}</td>
|
||||
<td style={s.td}>
|
||||
<div style={{ textDecoration: 'line-through' }}>{v.violation_name}</div>
|
||||
<div style={{ fontSize: '11px', color: '#aaa' }}>{v.category}</div>
|
||||
<div style={{ fontWeight: 600 }}>{v.violation_name}</div>
|
||||
<div style={{ fontSize: '10px', color: '#9ca0b8' }}>{v.category}</div>
|
||||
</td>
|
||||
<td style={{ ...s.td, textDecoration: 'line-through', color: '#aaa' }}>{v.points}</td>
|
||||
<td style={s.td}>{v.points}</td>
|
||||
<td style={s.td}>
|
||||
<span style={s.resTag}>{v.resolution_type}</span>
|
||||
{v.resolution_details && <div style={{ fontSize: '11px', marginTop: '3px', color: '#666' }}>{v.resolution_details}</div>}
|
||||
{v.resolved_by && <div style={{ fontSize: '10px', color: '#aaa' }}>by {v.resolved_by}</div>}
|
||||
{v.resolution_details && (
|
||||
<div style={{ fontSize: '10px', color: '#b5b5c0', marginTop: '2px' }}>
|
||||
{v.resolution_details}
|
||||
</div>
|
||||
)}
|
||||
{v.resolved_by && (
|
||||
<div style={{ fontSize: '10px', color: '#9ca0b8' }}>by {v.resolved_by}</div>
|
||||
)}
|
||||
</td>
|
||||
<td style={s.td}>
|
||||
<button style={s.actionBtn('#28a745')} onClick={() => handleRestore(v.id)}>↩ Restore</button>
|
||||
{confirmDel === v.id ? (
|
||||
<button
|
||||
style={s.actionBtn('#4db6ac')}
|
||||
onClick={(e) => { e.stopPropagation(); handleRestore(v.id); }}
|
||||
>
|
||||
Restore
|
||||
</button>
|
||||
<button
|
||||
style={s.actionBtn('#ff4d4f')}
|
||||
onClick={(e) => { e.stopPropagation(); setConfirmDel(confirmDel === v.id ? null : v.id); }}
|
||||
>
|
||||
{confirmDel === v.id ? 'Cancel' : 'Delete'}
|
||||
</button>
|
||||
<button
|
||||
style={s.pdfBtn}
|
||||
onClick={(e) => { e.stopPropagation(); handleDownloadPdf(v.id, employee?.name, v.incident_date); }}
|
||||
>
|
||||
PDF
|
||||
</button>
|
||||
{confirmDel === v.id && (
|
||||
<div style={s.deleteConfirm}>
|
||||
<strong>Permanently delete?</strong>
|
||||
<div style={{ marginTop: '8px', display: 'flex', gap: '8px' }}>
|
||||
<button style={s.actionBtn('#c0392b')} onClick={() => handleHardDelete(v.id)}>Confirm</button>
|
||||
<button style={s.actionBtn('#666')} onClick={() => setConfirmDel(null)}>Cancel</button>
|
||||
Permanently delete? This cannot be undone.
|
||||
<div style={{ marginTop: '8px' }}>
|
||||
<button
|
||||
style={s.actionBtn('#ff4d4f')}
|
||||
onClick={(e) => { e.stopPropagation(); handleHardDelete(v.id); }}
|
||||
>
|
||||
Confirm Delete
|
||||
</button>
|
||||
<button
|
||||
style={s.actionBtn('#888')}
|
||||
onClick={(e) => { e.stopPropagation(); setConfirmDel(null); }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button style={s.actionBtn('#c0392b')} onClick={() => setConfirmDel(v.id)}>✕ Delete</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</>)}
|
||||
|
||||
</>)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Negate sub-modal ────────────────────────────────── */}
|
||||
{/* Modals rendered outside panel to avoid z-index nesting issues */}
|
||||
{negating && (
|
||||
<NegateModal
|
||||
violation={negating}
|
||||
@@ -235,6 +401,20 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
onCancel={() => setNegating(null)}
|
||||
/>
|
||||
)}
|
||||
{editingEmp && employee && (
|
||||
<EditEmployeeModal
|
||||
employee={employee}
|
||||
onClose={() => setEditingEmp(false)}
|
||||
onSaved={load}
|
||||
/>
|
||||
)}
|
||||
{amending && (
|
||||
<AmendViolationModal
|
||||
violation={amending}
|
||||
onClose={() => setAmending(null)}
|
||||
onSaved={load}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
146
client/src/components/EmployeeNotes.jsx
Normal file
146
client/src/components/EmployeeNotes.jsx
Normal file
@@ -0,0 +1,146 @@
|
||||
import React, { useState } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const s = {
|
||||
wrapper: { marginTop: '20px' },
|
||||
sectionHd: {
|
||||
fontSize: '13px', fontWeight: 700, color: '#f8f9fa', textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px', marginBottom: '8px',
|
||||
},
|
||||
display: {
|
||||
background: '#181924', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
padding: '10px 12px', fontSize: '13px', color: '#f8f9fa', minHeight: '36px',
|
||||
cursor: 'pointer', position: 'relative',
|
||||
},
|
||||
displayEmpty: {
|
||||
color: '#555770', fontStyle: 'italic',
|
||||
},
|
||||
editHint: {
|
||||
position: 'absolute', right: '8px', top: '8px',
|
||||
fontSize: '10px', color: '#555770',
|
||||
},
|
||||
textarea: {
|
||||
width: '100%', background: '#0d1117', border: '1px solid #4d6fa8',
|
||||
borderRadius: '6px', color: '#f8f9fa', fontSize: '13px',
|
||||
padding: '10px 12px', resize: 'vertical', minHeight: '80px',
|
||||
boxSizing: 'border-box', fontFamily: 'inherit', outline: 'none',
|
||||
},
|
||||
actions: { display: 'flex', gap: '8px', marginTop: '8px' },
|
||||
saveBtn: {
|
||||
background: '#1a3a6b', border: '1px solid #4d6fa8', color: '#90caf9',
|
||||
borderRadius: '5px', padding: '5px 14px', fontSize: '12px',
|
||||
cursor: 'pointer', fontWeight: 600,
|
||||
},
|
||||
cancelBtn: {
|
||||
background: 'none', border: '1px solid #444', color: '#888',
|
||||
borderRadius: '5px', padding: '5px 14px', fontSize: '12px',
|
||||
cursor: 'pointer',
|
||||
},
|
||||
saving: { fontSize: '12px', color: '#9ca0b8', alignSelf: 'center' },
|
||||
tagRow: { display: 'flex', flexWrap: 'wrap', gap: '6px', marginBottom: '8px' },
|
||||
tag: {
|
||||
display: 'inline-block', padding: '2px 8px', borderRadius: '10px',
|
||||
fontSize: '11px', fontWeight: 600, background: '#1a2a3a',
|
||||
color: '#90caf9', border: '1px solid #2a3a5a', cursor: 'default',
|
||||
},
|
||||
};
|
||||
|
||||
// Quick-add tags for common HR flags
|
||||
const QUICK_TAGS = ['On PIP', 'Union member', 'Probationary', 'Pending investigation', 'FMLA', 'ADA'];
|
||||
|
||||
export default function EmployeeNotes({ employeeId, initialNotes, onSaved }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(initialNotes || '');
|
||||
const [saved, setSaved] = useState(initialNotes || '');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await axios.patch(`/api/employees/${employeeId}/notes`, { notes: draft });
|
||||
setSaved(draft);
|
||||
setEditing(false);
|
||||
if (onSaved) onSaved(draft);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setDraft(saved);
|
||||
setEditing(false);
|
||||
};
|
||||
|
||||
const addTag = (tag) => {
|
||||
const current = draft.trim();
|
||||
// Don't add a tag that's already present
|
||||
if (current.includes(tag)) return;
|
||||
setDraft(current ? `${current}\n${tag}` : tag);
|
||||
};
|
||||
|
||||
// Parse saved notes into display lines
|
||||
const lines = saved ? saved.split('\n').filter(Boolean) : [];
|
||||
|
||||
return (
|
||||
<div style={s.wrapper}>
|
||||
<div style={s.sectionHd}>Notes & Flags</div>
|
||||
|
||||
{!editing ? (
|
||||
<div
|
||||
style={s.display}
|
||||
onClick={() => { setDraft(saved); setEditing(true); }}
|
||||
title="Click to edit"
|
||||
>
|
||||
<span style={s.editHint}>✎ edit</span>
|
||||
{lines.length === 0 ? (
|
||||
<span style={s.displayEmpty}>No notes — click to add</span>
|
||||
) : (
|
||||
<div style={s.tagRow}>
|
||||
{lines.map((line, i) => (
|
||||
<span key={i} style={s.tag}>{line}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{/* Quick-add tag buttons */}
|
||||
<div style={{ ...s.tagRow, marginBottom: '6px' }}>
|
||||
{QUICK_TAGS.map(tag => (
|
||||
<button
|
||||
key={tag}
|
||||
style={{
|
||||
...s.tag,
|
||||
cursor: 'pointer',
|
||||
background: draft.includes(tag) ? '#0e2a3a' : '#1a2a3a',
|
||||
opacity: draft.includes(tag) ? 0.5 : 1,
|
||||
}}
|
||||
onClick={() => addTag(tag)}
|
||||
title="Add tag"
|
||||
>
|
||||
+ {tag}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
style={s.textarea}
|
||||
value={draft}
|
||||
onChange={e => setDraft(e.target.value)}
|
||||
placeholder="Free-text notes — one per line or comma-separated. Does not affect CPAS scoring."
|
||||
autoFocus
|
||||
/>
|
||||
<div style={s.actions}>
|
||||
<button style={s.saveBtn} onClick={handleSave} disabled={saving}>
|
||||
{saving ? 'Saving…' : 'Save Notes'}
|
||||
</button>
|
||||
<button style={s.cancelBtn} onClick={handleCancel} disabled={saving}>
|
||||
Cancel
|
||||
</button>
|
||||
{saving && <span style={s.saving}>Saving…</span>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
159
client/src/components/ExpirationTimeline.jsx
Normal file
159
client/src/components/ExpirationTimeline.jsx
Normal file
@@ -0,0 +1,159 @@
|
||||
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.
|
||||
const TIER_THRESHOLDS = [
|
||||
{ min: 30, label: 'Separation', color: '#ff1744' },
|
||||
{ min: 25, label: 'Final Decision', color: '#ff6d00' },
|
||||
{ min: 20, label: 'Risk Mitigation', color: '#ff9100' },
|
||||
{ min: 15, label: 'Verification', color: '#ffc400' },
|
||||
{ min: 10, label: 'Administrative Lockdown', color: '#ffea00' },
|
||||
{ min: 5, label: 'Realignment', color: '#b2ff59' },
|
||||
{ min: 0, label: 'Elite Standing', color: '#69f0ae' },
|
||||
];
|
||||
|
||||
function getTier(pts) {
|
||||
return TIER_THRESHOLDS.find(t => pts >= t.min) || TIER_THRESHOLDS[TIER_THRESHOLDS.length - 1];
|
||||
}
|
||||
|
||||
function urgencyColor(days) {
|
||||
if (days <= 7) return '#ff4d4f';
|
||||
if (days <= 14) return '#ffa940';
|
||||
if (days <= 30) return '#fadb14';
|
||||
return '#52c41a';
|
||||
}
|
||||
|
||||
const s = {
|
||||
wrapper: { marginTop: '24px' },
|
||||
sectionHd: {
|
||||
fontSize: '13px', fontWeight: 700, color: '#f8f9fa', textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px', marginBottom: '10px',
|
||||
},
|
||||
empty: { color: '#777990', fontStyle: 'italic', fontSize: '12px' },
|
||||
row: {
|
||||
display: 'flex', alignItems: 'center', gap: '12px',
|
||||
padding: '10px 12px', background: '#181924', borderRadius: '6px',
|
||||
border: '1px solid #2a2b3a', marginBottom: '6px',
|
||||
},
|
||||
bar: (pct, color) => ({
|
||||
flex: 1, height: '6px', background: '#2a2b3a', borderRadius: '3px', overflow: 'hidden',
|
||||
position: 'relative',
|
||||
}),
|
||||
barFill: (pct, color) => ({
|
||||
position: 'absolute', left: 0, top: 0, bottom: 0,
|
||||
width: `${Math.min(100, Math.max(0, 100 - pct))}%`,
|
||||
background: color, borderRadius: '3px',
|
||||
transition: 'width 0.3s ease',
|
||||
}),
|
||||
pill: (color) => ({
|
||||
display: 'inline-block', padding: '2px 8px', borderRadius: '10px',
|
||||
fontSize: '11px', fontWeight: 700, background: `${color}22`,
|
||||
color, border: `1px solid ${color}55`, whiteSpace: 'nowrap',
|
||||
}),
|
||||
pts: { fontSize: '13px', fontWeight: 700, color: '#f8f9fa', minWidth: '28px', textAlign: 'right' },
|
||||
name: { fontSize: '12px', color: '#f8f9fa', fontWeight: 600, flex: '0 0 160px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
|
||||
date: { fontSize: '11px', color: '#9ca0b8', minWidth: '88px' },
|
||||
projBox: {
|
||||
marginTop: '16px', padding: '12px 14px', background: '#0d1117',
|
||||
border: '1px solid #2a2b3a', borderRadius: '6px', fontSize: '12px', color: '#b5b5c0',
|
||||
},
|
||||
projRow: { display: 'flex', justifyContent: 'space-between', marginBottom: '4px' },
|
||||
};
|
||||
|
||||
export default function ExpirationTimeline({ employeeId, currentPoints }) {
|
||||
const [items, setItems] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
axios.get(`/api/employees/${employeeId}/expiration`)
|
||||
.then(r => setItems(r.data))
|
||||
.finally(() => setLoading(false));
|
||||
}, [employeeId]);
|
||||
|
||||
if (loading) return (
|
||||
<div style={s.wrapper}>
|
||||
<div style={s.sectionHd}>Point Expiration Timeline</div>
|
||||
<div style={{ ...s.empty }}>Loading…</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (items.length === 0) return (
|
||||
<div style={s.wrapper}>
|
||||
<div style={s.sectionHd}>Point Expiration Timeline</div>
|
||||
<div style={s.empty}>No active violations — nothing to expire.</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Build running totals: after each violation expires, what's the remaining score?
|
||||
let running = currentPoints || 0;
|
||||
const projected = items.map(item => {
|
||||
const before = running;
|
||||
running = Math.max(0, running - item.points);
|
||||
const tierBefore = getTier(before);
|
||||
const tierAfter = getTier(running);
|
||||
const dropped = tierAfter.min < tierBefore.min;
|
||||
return { ...item, pointsBefore: before, pointsAfter: running, tierBefore, tierAfter, tierDropped: dropped };
|
||||
});
|
||||
|
||||
return (
|
||||
<div style={s.wrapper}>
|
||||
<div style={s.sectionHd}>Point Expiration Timeline</div>
|
||||
|
||||
{projected.map((item) => {
|
||||
const color = urgencyColor(item.days_remaining);
|
||||
const pct = (item.days_remaining / 90) * 100;
|
||||
return (
|
||||
<div key={item.id} style={s.row}>
|
||||
{/* Violation name */}
|
||||
<div style={s.name} title={item.violation_name}>{item.violation_name}</div>
|
||||
|
||||
{/* Points badge */}
|
||||
<div style={s.pts}>−{item.points}</div>
|
||||
|
||||
{/* Progress bar: how much of the 90 days has elapsed */}
|
||||
<div style={s.bar(pct, color)}>
|
||||
<div style={s.barFill(pct, color)} />
|
||||
</div>
|
||||
|
||||
{/* Days remaining pill */}
|
||||
<div style={s.pill(color)}>
|
||||
{item.days_remaining <= 0 ? 'Expiring today' : `${item.days_remaining}d`}
|
||||
</div>
|
||||
|
||||
{/* Expiry date */}
|
||||
<div style={s.date}>{item.expires_on}</div>
|
||||
|
||||
{/* Tier drop indicator */}
|
||||
{item.tierDropped && (
|
||||
<div style={{ fontSize: '10px', color: '#69f0ae', whiteSpace: 'nowrap' }}>
|
||||
↓ {item.tierAfter.label}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Projection summary */}
|
||||
<div style={s.projBox}>
|
||||
<div style={{ fontWeight: 700, color: '#f8f9fa', marginBottom: '8px', fontSize: '12px' }}>
|
||||
Projected score after each expiration
|
||||
</div>
|
||||
{projected.map((item, i) => (
|
||||
<div key={item.id} style={s.projRow}>
|
||||
<span style={{ color: '#9ca0b8' }}>{item.expires_on} — {item.violation_name}</span>
|
||||
<span>
|
||||
<span style={{ color: '#f8f9fa', fontWeight: 700 }}>{item.pointsAfter} pts</span>
|
||||
{item.tierDropped && (
|
||||
<span style={{ marginLeft: '8px', color: item.tierAfter.color, fontWeight: 700 }}>
|
||||
→ {item.tierAfter.label}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,66 +1,136 @@
|
||||
import React, { useState } from 'react';
|
||||
|
||||
const RESOLUTION_TYPES = [
|
||||
'Corrective Training Completed',
|
||||
'Management Discretion',
|
||||
'Data Entry Error',
|
||||
'Successfully Appealed',
|
||||
];
|
||||
|
||||
const s = {
|
||||
overlay: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center' },
|
||||
box: { background: 'white', borderRadius: '10px', padding: '28px', width: '440px', maxWidth: '95vw', boxShadow: '0 8px 32px rgba(0,0,0,0.22)' },
|
||||
title: { fontSize: '17px', fontWeight: 700, color: '#2c3e50', marginBottom: '6px' },
|
||||
sub: { fontSize: '12px', color: '#888', marginBottom: '20px' },
|
||||
label: { fontWeight: 600, color: '#555', fontSize: '12px', marginBottom: '5px', display: 'block' },
|
||||
input: { width: '100%', padding: '9px 12px', border: '1px solid #ddd', borderRadius: '5px', fontSize: '13px', fontFamily: 'inherit', marginBottom: '14px' },
|
||||
btnRow: { display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '8px' },
|
||||
btnOk: { padding: '10px 22px', background: '#856404', color: 'white', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 700, fontSize: '13px' },
|
||||
btnCancel:{ padding: '10px 22px', background: '#f1f3f5', color: '#555', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
|
||||
violBox: { background: '#fff3cd', border: '1px solid #ffc107', borderRadius: '6px', padding: '10px 14px', marginBottom: '18px', fontSize: '13px' },
|
||||
overlay: {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
zIndex: 2000,
|
||||
},
|
||||
modal: {
|
||||
width: '480px', maxWidth: '95vw', background: '#111217', borderRadius: '12px',
|
||||
boxShadow: '0 16px 40px rgba(0,0,0,0.8)', color: '#f8f9fa',
|
||||
overflow: 'hidden', border: '1px solid #2a2b3a',
|
||||
},
|
||||
header: {
|
||||
padding: '18px 24px', borderBottom: '1px solid #222',
|
||||
background: 'linear-gradient(135deg, #000000, #151622)',
|
||||
},
|
||||
title: { fontSize: '18px', fontWeight: 700 },
|
||||
subtitle: { fontSize: '12px', color: '#c0c2d6', marginTop: '4px' },
|
||||
body: { padding: '18px 24px 8px 24px' },
|
||||
pill: {
|
||||
background: '#3b2e00', borderRadius: '6px', padding: '8px 10px',
|
||||
fontSize: '12px', color: '#ffd666', border: '1px solid #d4af37', marginBottom: '14px',
|
||||
},
|
||||
label: { fontSize: '13px', fontWeight: 600, marginBottom: '4px', color: '#e5e7f1' },
|
||||
input: {
|
||||
width: '100%', padding: '9px 10px', borderRadius: '6px',
|
||||
border: '1px solid #333544', background: '#050608', color: '#f8f9fa',
|
||||
fontSize: '13px', fontFamily: 'inherit', marginBottom: '14px',
|
||||
boxSizing: 'border-box',
|
||||
},
|
||||
textarea: {
|
||||
width: '100%', minHeight: '80px', resize: 'vertical',
|
||||
padding: '9px 10px', borderRadius: '6px', border: '1px solid #333544',
|
||||
background: '#050608', color: '#f8f9fa', fontSize: '13px',
|
||||
fontFamily: 'inherit', marginBottom: '14px', boxSizing: 'border-box',
|
||||
},
|
||||
footer: {
|
||||
display: 'flex', justifyContent: 'flex-end', gap: '10px',
|
||||
padding: '16px 24px 20px 24px', background: '#0c0d14', borderTop: '1px solid #222',
|
||||
},
|
||||
btnCancel: {
|
||||
padding: '10px 20px', borderRadius: '6px', border: '1px solid #333544',
|
||||
background: '#050608', color: '#f8f9fa', fontWeight: 600,
|
||||
fontSize: '13px', cursor: 'pointer',
|
||||
},
|
||||
btnConfirm: {
|
||||
padding: '10px 22px', borderRadius: '6px', border: 'none',
|
||||
background: 'linear-gradient(135deg, #d4af37 0%, #ffdf8a 100%)',
|
||||
color: '#000', fontWeight: 700, fontSize: '13px',
|
||||
cursor: 'pointer', textTransform: 'uppercase',
|
||||
},
|
||||
};
|
||||
|
||||
const RESOLUTION_OPTIONS = [
|
||||
'Corrective Training Completed',
|
||||
'Verbal Warning Issued',
|
||||
'Written Warning Issued',
|
||||
'Management Review',
|
||||
'Policy Exception Approved',
|
||||
'Data Entry Error',
|
||||
'Other',
|
||||
];
|
||||
|
||||
export default function NegateModal({ violation, onConfirm, onCancel }) {
|
||||
const [resType, setResType] = useState('');
|
||||
const [resolutionType, setResolutionType] = useState('Corrective Training Completed');
|
||||
const [details, setDetails] = useState('');
|
||||
const [resolvedBy, setResolvedBy] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!resType) { setError('Please select a resolution type.'); return; }
|
||||
onConfirm({ resolution_type: resType, details, resolved_by: resolvedBy });
|
||||
if (!violation) return null;
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (!onConfirm) return;
|
||||
onConfirm({
|
||||
resolution_type: resolutionType,
|
||||
details,
|
||||
resolved_by: resolvedBy,
|
||||
});
|
||||
};
|
||||
|
||||
// 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}>
|
||||
<div style={s.box}>
|
||||
<div style={s.title}>⊘ Negate Violation Points</div>
|
||||
<div style={s.sub}>This will zero out the points from this incident. The record remains in the audit log.</div>
|
||||
<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.violBox}>
|
||||
<strong>{violation.violation_name}</strong> · {violation.points} pts · {violation.incident_date}
|
||||
<div style={s.header}>
|
||||
<div style={s.title}>Negate Violation</div>
|
||||
<div style={s.subtitle}>
|
||||
Record resolution for: <strong>{violation.violation_name}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label style={s.label}>Resolution Type *</label>
|
||||
<select style={s.input} value={resType} onChange={e => { setResType(e.target.value); setError(''); }}>
|
||||
<option value="">-- Select Resolution --</option>
|
||||
{RESOLUTION_TYPES.map(r => <option key={r} value={r}>{r}</option>)}
|
||||
<div style={s.body}>
|
||||
<div style={s.pill}>
|
||||
⚠ {violation.points} pt{violation.points !== 1 ? 's' : ''} · {violation.incident_date} · {violation.category}
|
||||
</div>
|
||||
|
||||
<div style={s.label}>Resolution Type</div>
|
||||
<select
|
||||
style={s.input}
|
||||
value={resolutionType}
|
||||
onChange={(e) => setResolutionType(e.target.value)}
|
||||
>
|
||||
{RESOLUTION_OPTIONS.map((opt) => (
|
||||
<option key={opt} value={opt}>{opt}</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<label style={s.label}>Additional Details</label>
|
||||
<textarea style={{ ...s.input, resize: 'vertical', minHeight: '70px' }}
|
||||
placeholder="Training course completed, specific context, approving manager notes…"
|
||||
value={details} onChange={e => setDetails(e.target.value)} />
|
||||
<div style={s.label}>Details / Notes</div>
|
||||
<textarea
|
||||
style={s.textarea}
|
||||
placeholder="Describe the resolution or context…"
|
||||
value={details}
|
||||
onChange={(e) => setDetails(e.target.value)}
|
||||
/>
|
||||
|
||||
<label style={s.label}>Resolved By</label>
|
||||
<input style={s.input} type="text" placeholder="Officer / Manager name"
|
||||
value={resolvedBy} onChange={e => setResolvedBy(e.target.value)} />
|
||||
<div style={s.label}>Resolved By</div>
|
||||
<input
|
||||
style={s.input}
|
||||
placeholder="Manager or HR name…"
|
||||
value={resolvedBy}
|
||||
onChange={(e) => setResolvedBy(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <div style={{ color: '#c0392b', fontSize: '12px', marginBottom: '10px' }}>{error}</div>}
|
||||
|
||||
<div style={s.btnRow}>
|
||||
<div style={s.footer}>
|
||||
<button style={s.btnCancel} onClick={onCancel}>Cancel</button>
|
||||
<button style={s.btnOk} onClick={handleSubmit}>Confirm Negation</button>
|
||||
<button style={s.btnConfirm} onClick={handleConfirm}>Confirm Negation</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
451
client/src/components/ReadmeModal.jsx
Normal file
451
client/src/components/ReadmeModal.jsx
Normal file
@@ -0,0 +1,451 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
|
||||
// ─── Minimal Markdown → HTML renderer ────────────────────────────────────────
|
||||
// Handles: headings, bold, inline-code, fenced code blocks, tables, hr,
|
||||
// unordered lists, ordered lists, and paragraphs.
|
||||
function mdToHtml(md) {
|
||||
const lines = md.split('\n');
|
||||
const out = [];
|
||||
let i = 0;
|
||||
let inUl = false;
|
||||
let inOl = false;
|
||||
let inTable = false;
|
||||
let tableHead = false;
|
||||
|
||||
const closeOpenLists = () => {
|
||||
if (inUl) { out.push('</ul>'); inUl = false; }
|
||||
if (inOl) { out.push('</ol>'); inOl = false; }
|
||||
if (inTable) { out.push('</tbody></table>'); inTable = false; tableHead = false; }
|
||||
};
|
||||
|
||||
const inline = (s) =>
|
||||
s
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||
.replace(/`([^`]+)`/g, '<code>$1</code>');
|
||||
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
|
||||
// Fenced code block
|
||||
if (line.startsWith('```')) {
|
||||
closeOpenLists();
|
||||
const lang = line.slice(3).trim();
|
||||
const codeLines = [];
|
||||
i++;
|
||||
while (i < lines.length && !lines[i].startsWith('```')) {
|
||||
codeLines.push(lines[i].replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'));
|
||||
i++;
|
||||
}
|
||||
out.push(`<pre><code class="lang-${lang}">${codeLines.join('\n')}</code></pre>`);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// HR
|
||||
if (/^---+$/.test(line.trim())) {
|
||||
closeOpenLists();
|
||||
out.push('<hr>');
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Headings
|
||||
const hMatch = line.match(/^(#{1,4})\s+(.+)/);
|
||||
if (hMatch) {
|
||||
closeOpenLists();
|
||||
const level = hMatch[1].length;
|
||||
const id = hMatch[2].toLowerCase().replace(/[^a-z0-9]+/g, '-');
|
||||
out.push(`<h${level} id="${id}">${inline(hMatch[2])}</h${level}>`);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Table row
|
||||
if (line.trim().startsWith('|')) {
|
||||
const cells = line.trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim());
|
||||
if (!inTable) {
|
||||
closeOpenLists();
|
||||
inTable = true;
|
||||
tableHead = true;
|
||||
out.push('<table><thead><tr>');
|
||||
cells.forEach(c => out.push(`<th>${inline(c)}</th>`));
|
||||
out.push('</tr></thead><tbody>');
|
||||
i++;
|
||||
// skip separator row
|
||||
if (i < lines.length && lines[i].trim().startsWith('|') && /^[\|\s\-:]+$/.test(lines[i])) i++;
|
||||
continue;
|
||||
} else {
|
||||
out.push('<tr>');
|
||||
cells.forEach(c => out.push(`<td>${inline(c)}</td>`));
|
||||
out.push('</tr>');
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Unordered list
|
||||
const ulMatch = line.match(/^[-*]\s+(.*)/);
|
||||
if (ulMatch) {
|
||||
if (inTable) closeOpenLists();
|
||||
if (!inUl) { if (inOl) { out.push('</ol>'); inOl = false; } out.push('<ul>'); inUl = true; }
|
||||
out.push(`<li>${inline(ulMatch[1])}</li>`);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ordered list
|
||||
const olMatch = line.match(/^\d+\.\s+(.*)/);
|
||||
if (olMatch) {
|
||||
if (inTable) closeOpenLists();
|
||||
if (!inOl) { if (inUl) { out.push('</ul>'); inUl = false; } out.push('<ol>'); inOl = true; }
|
||||
out.push(`<li>${inline(olMatch[1])}</li>`);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Blank line
|
||||
if (line.trim() === '') {
|
||||
closeOpenLists();
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Paragraph
|
||||
closeOpenLists();
|
||||
out.push(`<p>${inline(line)}</p>`);
|
||||
i++;
|
||||
}
|
||||
|
||||
closeOpenLists();
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
// ─── Styles ───────────────────────────────────────────────────────────────────
|
||||
const overlay = {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)',
|
||||
zIndex: 2000, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end',
|
||||
};
|
||||
|
||||
const panel = {
|
||||
background: '#111217', color: '#f8f9fa', width: '760px', maxWidth: '95vw',
|
||||
height: '100vh', overflowY: 'auto', boxShadow: '-4px 0 32px rgba(0,0,0,0.8)',
|
||||
display: 'flex', flexDirection: 'column',
|
||||
};
|
||||
|
||||
const header = {
|
||||
background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
|
||||
padding: '22px 28px', position: 'sticky', top: 0, zIndex: 10,
|
||||
borderBottom: '1px solid #222', display: 'flex', alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
};
|
||||
|
||||
const closeBtn = {
|
||||
background: 'none', border: 'none', color: 'white',
|
||||
fontSize: '22px', cursor: 'pointer', lineHeight: 1,
|
||||
};
|
||||
|
||||
const body = {
|
||||
padding: '28px 32px', flex: 1, fontSize: '13px', lineHeight: '1.7',
|
||||
};
|
||||
|
||||
// Injected <style> for rendered markdown elements
|
||||
const CSS = `
|
||||
.readme-body h1 { font-size: 22px; font-weight: 800; color: #f8f9fa; margin: 28px 0 10px; border-bottom: 1px solid #2a2b3a; padding-bottom: 8px; }
|
||||
.readme-body h2 { font-size: 17px; font-weight: 700; color: #d4af37; margin: 26px 0 8px; }
|
||||
.readme-body h3 { font-size: 14px; font-weight: 700; color: #90caf9; margin: 20px 0 6px; text-transform: uppercase; letter-spacing: 0.4px; }
|
||||
.readme-body h4 { font-size: 13px; font-weight: 700; color: #9ca0b8; margin: 14px 0 4px; }
|
||||
.readme-body p { color: #c8ccd8; margin: 6px 0 10px; }
|
||||
.readme-body hr { border: none; border-top: 1px solid #2a2b3a; margin: 20px 0; }
|
||||
.readme-body strong { color: #f8f9fa; }
|
||||
.readme-body code {
|
||||
background: #0d1117; color: #79c0ff; border: 1px solid #2a2b3a;
|
||||
border-radius: 4px; padding: 1px 6px; font-family: 'Consolas', 'Fira Code', monospace; font-size: 12px;
|
||||
}
|
||||
.readme-body pre {
|
||||
background: #0d1117; border: 1px solid #2a2b3a; border-radius: 6px;
|
||||
padding: 14px 16px; overflow-x: auto; margin: 10px 0 16px;
|
||||
}
|
||||
.readme-body pre code {
|
||||
background: none; border: none; padding: 0; color: #e6edf3;
|
||||
font-size: 12px; line-height: 1.6;
|
||||
}
|
||||
.readme-body ul { padding-left: 22px; margin: 6px 0 10px; color: #c8ccd8; }
|
||||
.readme-body ol { padding-left: 22px; margin: 6px 0 10px; color: #c8ccd8; }
|
||||
.readme-body li { margin: 3px 0; }
|
||||
.readme-body table {
|
||||
width: 100%; border-collapse: collapse; font-size: 12px;
|
||||
background: #181924; border-radius: 6px; overflow: hidden;
|
||||
border: 1px solid #2a2b3a; margin: 10px 0 16px;
|
||||
}
|
||||
.readme-body th {
|
||||
background: #050608; padding: 8px 12px; text-align: left;
|
||||
color: #f8f9fa; font-weight: 600; font-size: 11px; text-transform: uppercase;
|
||||
border-bottom: 1px solid #2a2b3a;
|
||||
}
|
||||
.readme-body td {
|
||||
padding: 8px 12px; border-bottom: 1px solid #202231; color: #c8ccd8;
|
||||
}
|
||||
.readme-body tr:last-child td { border-bottom: none; }
|
||||
.readme-body tr:hover td { background: #1e1f2e; }
|
||||
`;
|
||||
|
||||
// ─── Table-of-contents builder ────────────────────────────────────────────────
|
||||
function buildToc(md) {
|
||||
const headings = [];
|
||||
for (const line of md.split('\n')) {
|
||||
const m = line.match(/^(#{1,3})\s+(.+)/);
|
||||
if (m) {
|
||||
headings.push({
|
||||
level: m[1].length,
|
||||
text: m[2],
|
||||
id: m[2].toLowerCase().replace(/[^a-z0-9]+/g, '-'),
|
||||
});
|
||||
}
|
||||
}
|
||||
return headings;
|
||||
}
|
||||
|
||||
// ─── README content ───────────────────────────────────────────────────────────
|
||||
// Embedded at build time — no extra fetch needed.
|
||||
const README_MD = `# CPAS Violation Tracker
|
||||
|
||||
Single-container Dockerized web app for CPAS violation documentation and workforce standing management.
|
||||
Built with **React + Vite** (frontend), **Node.js + Express** (backend), **SQLite** (database), and **Puppeteer** (PDF generation).
|
||||
|
||||
---
|
||||
|
||||
## Quickstart (Local)
|
||||
|
||||
\`\`\`bash
|
||||
# 1. Build the image
|
||||
docker build -t cpas-tracker .
|
||||
|
||||
# 2. Run it
|
||||
docker run -d --name cpas-tracker \\
|
||||
-p 3001:3001 \\
|
||||
-v cpas-data:/data \\
|
||||
cpas-tracker
|
||||
\`\`\`
|
||||
|
||||
Open **http://localhost:3001**
|
||||
|
||||
## Update After Code Changes
|
||||
|
||||
\`\`\`bash
|
||||
docker build -t cpas-tracker .
|
||||
docker stop cpas-tracker && docker rm cpas-tracker
|
||||
docker run -d --name cpas-tracker -p 3001:3001 -v cpas-data:/data cpas-tracker
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
### Company Dashboard
|
||||
- Live employee table sorted by active CPAS points (highest risk first)
|
||||
- Stat cards: total employees, elite standing, active points, at-risk count, highest score
|
||||
- **At-risk badge** — flags employees within 2 points of the next tier escalation
|
||||
- Search/filter by name, department, or supervisor
|
||||
- **Audit Log** button — filterable, paginated view of all system write actions
|
||||
|
||||
### Violation Form
|
||||
- Select existing employee or enter new by name
|
||||
- **Employee intelligence** — shows current CPAS standing before submitting
|
||||
- Violation type dropdown grouped by category with 90-day recurrence counts
|
||||
- **Recidivist auto-escalation** — points slider auto-maximizes on repeat violations
|
||||
- **Tier crossing warning** — previews tier impact before submission
|
||||
- One-click PDF download after submission
|
||||
|
||||
### Employee Profile Modal
|
||||
- Full violation history with resolution status and amendment count badges
|
||||
- **Edit Employee** — update name, department, or supervisor inline
|
||||
- **Merge Duplicate** — reassign all violations from a duplicate record
|
||||
- **Amend** per active violation — edit non-scoring fields with full diff history
|
||||
- Negate / restore individual violations (soft delete with resolution type + notes)
|
||||
- Hard delete option for data entry errors
|
||||
- **Notes & Flags** — free-text notes (e.g. "on PIP", "union member") visible in the profile
|
||||
- **Point Expiration Timeline** — shows when each active violation rolls off the 90-day window with tier-drop projections
|
||||
|
||||
### Audit Log
|
||||
- Append-only log of every write action
|
||||
- Filterable by entity type and action; paginated with load-more
|
||||
|
||||
### Violation Amendment
|
||||
- Edit submitted violations' non-scoring fields without delete-and-resubmit
|
||||
- Point values, violation type, and incident date are immutable
|
||||
- Every change stored as a field-level diff (old → new) with timestamp
|
||||
|
||||
---
|
||||
|
||||
## CPAS Tier System
|
||||
|
||||
| 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 |
|
||||
|
||||
Scores are computed over a **rolling 90-day window** (negated violations excluded).
|
||||
|
||||
---
|
||||
|
||||
## API Reference
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| GET | \`/api/health\` | Health check |
|
||||
| GET | \`/api/employees\` | List all employees (includes notes) |
|
||||
| POST | \`/api/employees\` | Create or upsert employee |
|
||||
| PATCH | \`/api/employees/:id\` | Edit name, department, supervisor, or notes |
|
||||
| POST | \`/api/employees/:id/merge\` | Merge duplicate employee |
|
||||
| GET | \`/api/employees/:id/score\` | Active CPAS score |
|
||||
| GET | \`/api/employees/:id/expiration\` | Active violation roll-off timeline |
|
||||
| PATCH | \`/api/employees/:id/notes\` | Save employee notes only |
|
||||
| GET | \`/api/dashboard\` | All employees with active points |
|
||||
| POST | \`/api/violations\` | Log a new violation |
|
||||
| GET | \`/api/violations/employee/:id\` | Violation history with resolutions + amendment counts |
|
||||
| PATCH | \`/api/violations/:id/negate\` | Soft delete + resolution record |
|
||||
| PATCH | \`/api/violations/:id/restore\` | Restore a negated violation |
|
||||
| PATCH | \`/api/violations/:id/amend\` | Amend non-scoring fields |
|
||||
| GET | \`/api/violations/:id/amendments\` | Amendment history |
|
||||
| DELETE | \`/api/violations/:id\` | Hard delete |
|
||||
| GET | \`/api/violations/:id/pdf\` | Download violation PDF |
|
||||
| GET | \`/api/audit\` | Paginated audit log |
|
||||
|
||||
---
|
||||
|
||||
## Database Schema
|
||||
|
||||
Six tables + one view:
|
||||
|
||||
- **\`employees\`** — id, name, department, supervisor, **notes**
|
||||
- **\`violations\`** — full incident record including \`prior_active_points\` snapshot
|
||||
- **\`violation_resolutions\`** — resolution type, details, resolved_by
|
||||
- **\`violation_amendments\`** — field-level diff log per amendment
|
||||
- **\`audit_log\`** — append-only record of every write action
|
||||
- **\`active_cpas_scores\`** (view) — rolling 90-day score per employee
|
||||
|
||||
---
|
||||
|
||||
## Amendable Fields
|
||||
|
||||
The following violation fields can be edited after submission. Points, type, and incident date are **immutable**.
|
||||
|
||||
| Field | Notes |
|
||||
|-------|-------|
|
||||
| \`incident_time\` | Time of day the incident occurred |
|
||||
| \`location\` | Where the incident took place |
|
||||
| \`details\` | Narrative description |
|
||||
| \`submitted_by\` | Supervisor who submitted |
|
||||
| \`witness_name\` | Witness on record |
|
||||
|
||||
---
|
||||
|
||||
## Docker Quick Reference
|
||||
|
||||
\`\`\`bash
|
||||
# Build
|
||||
docker build -t cpas-tracker .
|
||||
|
||||
# Run
|
||||
docker run -d --name cpas-tracker -p 3001:3001 -v cpas-data:/data cpas-tracker
|
||||
|
||||
# Stop / remove
|
||||
docker stop cpas-tracker && docker rm cpas-tracker
|
||||
|
||||
# Export for Unraid
|
||||
docker save cpas-tracker | gzip > cpas-tracker.tar.gz
|
||||
|
||||
# View logs
|
||||
docker logs -f cpas-tracker
|
||||
\`\`\`
|
||||
`;
|
||||
|
||||
// ─── Component ────────────────────────────────────────────────────────────────
|
||||
export default function ReadmeModal({ onClose }) {
|
||||
const bodyRef = useRef(null);
|
||||
const html = mdToHtml(README_MD);
|
||||
const toc = buildToc(README_MD);
|
||||
|
||||
// Close on Escape
|
||||
useEffect(() => {
|
||||
const handler = (e) => { if (e.key === 'Escape') onClose(); };
|
||||
window.addEventListener('keydown', handler);
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, [onClose]);
|
||||
|
||||
const scrollTo = (id) => {
|
||||
const el = bodyRef.current?.querySelector(`#${id}`);
|
||||
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
};
|
||||
|
||||
const handleOverlay = (e) => { if (e.target === e.currentTarget) onClose(); };
|
||||
|
||||
return (
|
||||
<div style={overlay} onClick={handleOverlay}>
|
||||
{/* Inject markdown CSS once */}
|
||||
<style>{CSS}</style>
|
||||
|
||||
<div style={panel} onClick={(e) => e.stopPropagation()}>
|
||||
|
||||
{/* Header */}
|
||||
<div style={header}>
|
||||
<div>
|
||||
<div style={{ fontSize: '17px', fontWeight: 800, letterSpacing: '0.3px' }}>
|
||||
📋 CPAS Tracker — Documentation
|
||||
</div>
|
||||
<div style={{ fontSize: '11px', color: '#9ca0b8', marginTop: '3px' }}>
|
||||
Admin reference · use Esc or click outside to close
|
||||
</div>
|
||||
</div>
|
||||
<button style={closeBtn} onClick={onClose} aria-label="Close">✕</button>
|
||||
</div>
|
||||
|
||||
{/* TOC strip */}
|
||||
<div style={{
|
||||
background: '#0d1117', borderBottom: '1px solid #1e1f2e',
|
||||
padding: '10px 32px', display: 'flex', flexWrap: 'wrap', gap: '4px 16px',
|
||||
fontSize: '11px',
|
||||
}}>
|
||||
{toc.filter(h => h.level <= 2).map((h) => (
|
||||
<button
|
||||
key={h.id}
|
||||
onClick={() => scrollTo(h.id)}
|
||||
style={{
|
||||
background: 'none', border: 'none', cursor: 'pointer', padding: '2px 0',
|
||||
color: h.level === 1 ? '#f8f9fa' : '#90caf9',
|
||||
fontWeight: h.level === 1 ? 700 : 400,
|
||||
fontSize: '11px',
|
||||
}}
|
||||
>
|
||||
{h.level === 2 ? '↳ ' : ''}{h.text}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div
|
||||
ref={bodyRef}
|
||||
style={body}
|
||||
className="readme-body"
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
|
||||
{/* Footer */}
|
||||
<div style={{
|
||||
padding: '14px 32px', borderTop: '1px solid #1e1f2e',
|
||||
fontSize: '11px', color: '#555770', textAlign: 'center',
|
||||
}}>
|
||||
CPAS Violation Tracker · internal admin use only
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,27 +7,27 @@ import TierWarning from './TierWarning';
|
||||
import ViolationHistory from './ViolationHistory';
|
||||
|
||||
const s = {
|
||||
content: { padding: '40px' },
|
||||
section: { background: '#f8f9fa', borderLeft: '4px solid #667eea', padding: '20px', marginBottom: '30px', borderRadius: '4px' },
|
||||
sectionTitle: { color: '#2c3e50', fontSize: '20px', marginBottom: '15px' },
|
||||
content: { padding: '32px 40px', background: '#111217', borderRadius: '10px', color: '#f8f9fa' },
|
||||
section: { background: '#181924', borderLeft: '4px solid #d4af37', padding: '20px', marginBottom: '30px', borderRadius: '4px', border: '1px solid #2a2b3a' },
|
||||
sectionTitle: { color: '#f8f9fa', fontSize: '20px', marginBottom: '15px', fontWeight: 700 },
|
||||
grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '15px', marginTop: '15px' },
|
||||
item: { display: 'flex', flexDirection: 'column' },
|
||||
label: { fontWeight: 600, color: '#555', marginBottom: '5px', fontSize: '13px' },
|
||||
input: { padding: '10px', border: '1px solid #ddd', borderRadius: '4px', fontSize: '14px', fontFamily: 'inherit' },
|
||||
label: { fontWeight: 600, color: '#e5e7f1', marginBottom: '5px', fontSize: '13px' },
|
||||
input: { padding: '10px', border: '1px solid #333544', borderRadius: '4px', fontSize: '14px', fontFamily: 'inherit', background: '#050608', color: '#f8f9fa' },
|
||||
fullCol: { gridColumn: '1 / -1' },
|
||||
contextBox: { background: '#f1f3f5', border: '1px solid #ced4da', borderRadius: '4px', padding: '10px', fontSize: '12px', color: '#444', marginTop: '4px' },
|
||||
repeatBadge: { display: 'inline-block', marginLeft: '8px', padding: '1px 7px', borderRadius: '10px', fontSize: '11px', fontWeight: 700, background: '#fff3cd', color: '#856404', border: '1px solid #ffc107' },
|
||||
repeatWarn: { background: '#fff3cd', border: '1px solid #ffc107', borderRadius: '4px', padding: '8px 12px', marginTop: '6px', fontSize: '12px', color: '#856404' },
|
||||
pointBox: { background: '#fff3cd', border: '2px solid #ffc107', padding: '15px', borderRadius: '6px', marginTop: '15px', textAlign: 'center' },
|
||||
pointValue: { fontSize: '24px', fontWeight: 'bold', color: '#667eea', margin: '10px 0' },
|
||||
contextBox: { background: '#141623', border: '1px solid #333544', borderRadius: '4px', padding: '10px', fontSize: '12px', color: '#d1d3e0', marginTop: '4px' },
|
||||
repeatBadge: { display: 'inline-block', marginLeft: '8px', padding: '1px 7px', borderRadius: '10px', fontSize: '11px', fontWeight: 700, background: '#3b2e00', color: '#ffd666', border: '1px solid #d4af37' },
|
||||
repeatWarn: { background: '#3b2e00', border: '1px solid #d4af37', borderRadius: '4px', padding: '8px 12px', marginTop: '6px', fontSize: '12px', color: '#ffdf8a' },
|
||||
pointBox: { background: '#181200', border: '2px solid #d4af37', padding: '15px', borderRadius: '6px', marginTop: '15px', textAlign: 'center' },
|
||||
pointValue: { fontSize: '24px', fontWeight: 'bold', color: '#ffd666', margin: '10px 0' },
|
||||
scoreRow: { display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '14px', flexWrap: 'wrap' },
|
||||
btnRow: { display: 'flex', gap: '15px', justifyContent: 'center', marginTop: '30px', flexWrap: 'wrap' },
|
||||
btnPrimary: { padding: '15px 40px', fontSize: '16px', fontWeight: 600, border: 'none', borderRadius: '6px', cursor: 'pointer', background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', color: 'white', textTransform: 'uppercase' },
|
||||
btnPrimary: { padding: '15px 40px', fontSize: '16px', fontWeight: 600, border: 'none', borderRadius: '6px', cursor: 'pointer', background: 'linear-gradient(135deg, #d4af37 0%, #ffdf8a 100%)', color: '#000', textTransform: 'uppercase' },
|
||||
btnPdf: { padding: '15px 40px', fontSize: '16px', fontWeight: 600, border: 'none', borderRadius: '6px', cursor: 'pointer', background: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)', color: 'white', textTransform: 'uppercase' },
|
||||
btnSecondary: { padding: '15px 40px', fontSize: '16px', fontWeight: 600, border: 'none', borderRadius: '6px', cursor: 'pointer', background: '#6c757d', color: 'white', textTransform: 'uppercase' },
|
||||
note: { background: '#e7f3ff', borderLeft: '4px solid #2196F3', padding: '15px', margin: '20px 0', borderRadius: '4px' },
|
||||
statusOk: { marginTop: '15px', padding: '15px', borderRadius: '6px', textAlign: 'center', fontWeight: 600, background: '#d4edda', color: '#155724', border: '1px solid #c3e6cb' },
|
||||
statusErr: { marginTop: '15px', padding: '15px', borderRadius: '6px', textAlign: 'center', fontWeight: 600, background: '#f8d7da', color: '#721c24', border: '1px solid #f5c6cb' },
|
||||
btnSecondary: { padding: '15px 40px', fontSize: '16px', fontWeight: 600, border: '1px solid #333544', borderRadius: '6px', cursor: 'pointer', background: '#050608', color: '#f8f9fa', textTransform: 'uppercase' },
|
||||
note: { background: '#141623', borderLeft: '4px solid #2196F3', padding: '15px', margin: '20px 0', borderRadius: '4px', fontSize: '13px', color: '#d1d3e0' },
|
||||
statusOk: { marginTop: '15px', padding: '15px', borderRadius: '6px', textAlign: 'center', fontWeight: 600, background: '#053321', color: '#9ef7c1', border: '1px solid #0f5132' },
|
||||
statusErr: { marginTop: '15px', padding: '15px', borderRadius: '6px', textAlign: 'center', fontWeight: 600, background: '#3c1114', color: '#ffb3b8', border: '1px solid #f5c6cb' },
|
||||
};
|
||||
|
||||
const EMPTY_FORM = {
|
||||
@@ -41,7 +41,7 @@ export default function ViolationForm() {
|
||||
const [form, setForm] = useState(EMPTY_FORM);
|
||||
const [violation, setViolation] = useState(null);
|
||||
const [status, setStatus] = useState(null);
|
||||
const [lastViolId, setLastViolId] = useState(null); // ID of most recently saved violation
|
||||
const [lastViolId, setLastViolId] = useState(null);
|
||||
const [pdfLoading, setPdfLoading] = useState(false);
|
||||
|
||||
const intel = useEmployeeIntelligence(form.employeeId || null);
|
||||
@@ -113,9 +113,7 @@ export default function ViolationForm() {
|
||||
if (!lastViolId) return;
|
||||
setPdfLoading(true);
|
||||
try {
|
||||
const response = await axios.get(`/api/violations/${lastViolId}/pdf`, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
const response = await axios.get(`/api/violations/${lastViolId}/pdf`, { responseType: 'blob' });
|
||||
const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
@@ -138,15 +136,14 @@ export default function ViolationForm() {
|
||||
return (
|
||||
<div style={s.content}>
|
||||
|
||||
{/* ── Employee Information ─────────────────────────────── */}
|
||||
<div style={s.section}>
|
||||
<h2 style={s.sectionTitle}>Employee Information</h2>
|
||||
|
||||
{intel.score && form.employeeId && (
|
||||
<div style={s.scoreRow}>
|
||||
<span style={{ fontSize: '13px', color: '#555', fontWeight: 600 }}>Current Standing:</span>
|
||||
<span style={{ fontSize: '13px', color: '#d1d3e0', fontWeight: 600 }}>Current Standing:</span>
|
||||
<CpasBadge points={intel.score.active_points} />
|
||||
<span style={{ fontSize: '12px', color: '#888' }}>
|
||||
<span style={{ fontSize: '12px', color: '#9ca0b8' }}>
|
||||
{intel.score.violation_count} violation{intel.score.violation_count !== 1 ? 's' : ''} in last 90 days
|
||||
</span>
|
||||
</div>
|
||||
@@ -174,7 +171,6 @@ export default function ViolationForm() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Violation Details ────────────────────────────────── */}
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={s.section}>
|
||||
<h2 style={s.sectionTitle}>Violation Details</h2>
|
||||
@@ -207,7 +203,7 @@ export default function ViolationForm() {
|
||||
</span>
|
||||
)}
|
||||
<br />{violation.description}<br />
|
||||
<span style={{ fontSize: '11px', color: '#666' }}>{violation.chapter}</span>
|
||||
<span style={{ fontSize: '11px', color: '#a0a3ba' }}>{violation.chapter}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -264,7 +260,7 @@ export default function ViolationForm() {
|
||||
|
||||
{violation && (
|
||||
<div style={s.pointBox}>
|
||||
<h4 style={{ color: '#856404', marginBottom: '10px' }}>CPAS Point Assessment</h4>
|
||||
<h4 style={{ color: '#ffdf8a', marginBottom: '10px' }}>CPAS Point Assessment</h4>
|
||||
<p style={{ margin: 0 }}>
|
||||
{violation.name}: {violation.minPoints === violation.maxPoints
|
||||
? `${violation.minPoints} Points (Fixed)`
|
||||
@@ -274,7 +270,7 @@ export default function ViolationForm() {
|
||||
min={violation.minPoints} max={violation.maxPoints}
|
||||
value={form.points} onChange={handleChange} />
|
||||
<div style={s.pointValue}>{form.points} Points</div>
|
||||
<p style={{ fontSize: '12px', color: '#666' }}>Adjust to reflect severity and context</p>
|
||||
<p style={{ fontSize: '12px', color: '#d1d3e0' }}>Adjust to reflect severity and context</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -286,7 +282,6 @@ export default function ViolationForm() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* PDF download — appears after successful submission */}
|
||||
{lastViolId && status?.ok && (
|
||||
<div style={{ textAlign: 'center', marginTop: '16px' }}>
|
||||
<button
|
||||
@@ -297,7 +292,7 @@ export default function ViolationForm() {
|
||||
>
|
||||
{pdfLoading ? '⏳ Generating PDF...' : '⬇ Download PDF'}
|
||||
</button>
|
||||
<p style={{ fontSize: '11px', color: '#888', marginTop: '6px' }}>
|
||||
<p style={{ fontSize: '11px', color: '#9ca0b8', marginTop: '6px' }}>
|
||||
Violation #{lastViolId} — click to download the signed violation document
|
||||
</p>
|
||||
</div>
|
||||
@@ -306,7 +301,6 @@ export default function ViolationForm() {
|
||||
{status && <div style={status.ok ? s.statusOk : s.statusErr}>{status.msg}</div>}
|
||||
</form>
|
||||
|
||||
{/* ── Violation History Panel ──────────────────────────── */}
|
||||
{form.employeeId && (
|
||||
<div style={s.section}>
|
||||
<h2 style={s.sectionTitle}>Violation History</h2>
|
||||
|
||||
@@ -2,19 +2,19 @@ import React, { useState } from 'react';
|
||||
|
||||
const s = {
|
||||
wrapper: { marginTop: '24px' },
|
||||
title: { color: '#2c3e50', fontSize: '16px', fontWeight: 700, marginBottom: '10px' },
|
||||
table: { width: '100%', borderCollapse: 'collapse', fontSize: '13px' },
|
||||
th: { background: '#2c3e50', color: 'white', padding: '8px 10px', textAlign: 'left' },
|
||||
td: { padding: '8px 10px', borderBottom: '1px solid #dee2e6' },
|
||||
trEven: { background: '#f8f9fa' },
|
||||
trOdd: { background: 'white' },
|
||||
title: { color: '#b5b5c0', fontSize: '16px', fontWeight: 700, marginBottom: '10px' },
|
||||
table: { width: '100%', borderCollapse: 'collapse', fontSize: '13px', background: '#111217', borderRadius: '6px', overflow: 'hidden', border: '1px solid #222' },
|
||||
th: { background: '#000000', color: '#f8f9fa', padding: '8px 10px', textAlign: 'left', fontSize: '12px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' },
|
||||
td: { padding: '8px 10px', borderBottom: '1px solid #1c1d29', color: '#f8f9fa', verticalAlign: 'middle' },
|
||||
trEven: { background: '#111217' },
|
||||
trOdd: { background: '#151622' },
|
||||
pts: { fontWeight: 700, color: '#667eea' },
|
||||
toggle: { background: 'none', border: 'none', color: '#667eea', cursor: 'pointer', fontSize: '13px', padding: 0, textDecoration: 'underline' },
|
||||
empty: { color: '#888', fontStyle: 'italic', fontSize: '13px', marginTop: '8px' },
|
||||
empty: { color: '#77798a', fontStyle: 'italic', fontSize: '13px', marginTop: '8px' },
|
||||
};
|
||||
|
||||
function formatDate(d) {
|
||||
if (!d) return '—';
|
||||
if (!d) return '–';
|
||||
const dt = new Date(d + 'T12:00:00');
|
||||
return dt.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'America/Chicago' });
|
||||
}
|
||||
@@ -44,9 +44,9 @@ export default function ViolationHistory({ history, loading }) {
|
||||
<tr key={v.id} style={i % 2 === 0 ? s.trEven : s.trOdd}>
|
||||
<td style={s.td}>{formatDate(v.incident_date)}</td>
|
||||
<td style={s.td}>{v.violation_name}</td>
|
||||
<td style={s.td}>{v.category}</td>
|
||||
<td style={{ ...s.td, color: '#c0c2d6' }}>{v.category}</td>
|
||||
<td style={{ ...s.td, ...s.pts }}>{v.points}</td>
|
||||
<td style={s.td}>{v.details || '—'}</td>
|
||||
<td style={{ ...s.td, color: '#c0c2d6' }}>{v.details || '–'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
|
||||
@@ -13,12 +13,18 @@ db.pragma('foreign_keys = ON');
|
||||
const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8');
|
||||
db.exec(schema);
|
||||
|
||||
// Migrate: add negated columns if upgrading from Phase 1-3
|
||||
const cols = db.prepare("PRAGMA table_info(violations)").all().map(c => c.name);
|
||||
// ── Migrations for existing DBs ──────────────────────────────────────────────
|
||||
const cols = db.prepare('PRAGMA table_info(violations)').all().map(c => c.name);
|
||||
if (!cols.includes('negated')) db.exec("ALTER TABLE violations ADD COLUMN negated INTEGER NOT NULL DEFAULT 0");
|
||||
if (!cols.includes('negated_at')) db.exec("ALTER TABLE violations ADD COLUMN negated_at DATETIME");
|
||||
if (!cols.includes('prior_active_points')) db.exec("ALTER TABLE violations ADD COLUMN prior_active_points INTEGER");
|
||||
if (!cols.includes('prior_tier_label')) db.exec("ALTER TABLE violations ADD COLUMN prior_tier_label TEXT");
|
||||
|
||||
// Ensure resolutions table exists on upgrade
|
||||
// Employee notes column (free-text, does not affect scoring)
|
||||
const empCols = db.prepare('PRAGMA table_info(employees)').all().map(c => c.name);
|
||||
if (!empCols.includes('notes')) db.exec("ALTER TABLE employees ADD COLUMN notes TEXT");
|
||||
|
||||
// Ensure resolutions table exists
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS violation_resolutions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
violation_id INTEGER NOT NULL REFERENCES violations(id) ON DELETE CASCADE,
|
||||
@@ -28,5 +34,41 @@ db.exec(`CREATE TABLE IF NOT EXISTS violation_resolutions (
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
|
||||
// ── Feature: Violation Amendments ────────────────────────────────────────────
|
||||
// Stores a field-level diff every time a violation's editable fields are changed.
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS violation_amendments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
violation_id INTEGER NOT NULL REFERENCES violations(id) ON DELETE CASCADE,
|
||||
changed_by TEXT,
|
||||
field_name TEXT NOT NULL,
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
|
||||
// ── Feature: Audit Log ───────────────────────────────────────────────────────
|
||||
// Append-only record of every write action across the system.
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
action TEXT NOT NULL,
|
||||
entity_type TEXT NOT NULL,
|
||||
entity_id INTEGER,
|
||||
performed_by TEXT,
|
||||
details TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
|
||||
// Recreate view so it always filters negated rows
|
||||
db.exec(`DROP VIEW IF EXISTS active_cpas_scores;
|
||||
CREATE VIEW active_cpas_scores AS
|
||||
SELECT
|
||||
employee_id,
|
||||
SUM(points) AS active_points,
|
||||
COUNT(*) AS violation_count
|
||||
FROM violations
|
||||
WHERE negated = 0
|
||||
AND incident_date >= DATE('now', '-90 days')
|
||||
GROUP BY employee_id;`);
|
||||
|
||||
console.log('[DB] Connected:', dbPath);
|
||||
module.exports = db;
|
||||
|
||||
@@ -21,6 +21,8 @@ CREATE TABLE IF NOT EXISTS violations (
|
||||
witness_name TEXT,
|
||||
negated INTEGER NOT NULL DEFAULT 0,
|
||||
negated_at DATETIME,
|
||||
prior_active_points INTEGER, -- snapshot at time of logging
|
||||
prior_tier_label TEXT, -- optional human-readable tier
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
|
||||
@@ -30,18 +30,12 @@ async function generatePdf(violation, score) {
|
||||
format: 'Letter',
|
||||
printBackground: true,
|
||||
margin: {
|
||||
top: '0.6in',
|
||||
bottom: '0.7in',
|
||||
left: '0.75in',
|
||||
right: '0.75in',
|
||||
top: '0.35in',
|
||||
bottom: '0.35in',
|
||||
left: '0.4in',
|
||||
right: '0.4in',
|
||||
},
|
||||
displayHeaderFooter: true,
|
||||
headerTemplate: '<div></div>',
|
||||
footerTemplate: `
|
||||
<div style="font-size:9px; color:#888; width:100%; text-align:center; padding:0 0.75in;">
|
||||
CONFIDENTIAL — MPM Internal HR Document |
|
||||
Page <span class="pageNumber"></span> of <span class="totalPages"></span>
|
||||
</div>`,
|
||||
displayHeaderFooter: false,
|
||||
});
|
||||
|
||||
return pdf;
|
||||
|
||||
620
pdf/template.js
620
pdf/template.js
File diff suppressed because one or more lines are too long
356
server.js
356
server.js
@@ -11,12 +11,25 @@ app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.static(path.join(__dirname, 'client', 'dist')));
|
||||
|
||||
// ── Health ──────────────────────────────────────────────────────────────────
|
||||
// ── Audit helper ─────────────────────────────────────────────────────────────
|
||||
function audit(action, entityType, entityId, performedBy, details) {
|
||||
try {
|
||||
db.prepare(`
|
||||
INSERT INTO audit_log (action, entity_type, entity_id, performed_by, details)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`).run(action, entityType, entityId || null, performedBy || null,
|
||||
typeof details === 'object' ? JSON.stringify(details) : (details || null));
|
||||
} catch (e) {
|
||||
console.error('[AUDIT]', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Health
|
||||
app.get('/api/health', (req, res) => res.json({ status: 'ok', timestamp: new Date().toISOString() }));
|
||||
|
||||
// ── Employees ───────────────────────────────────────────────────────────────
|
||||
// ── Employees ─────────────────────────────────────────────────────────────────
|
||||
app.get('/api/employees', (req, res) => {
|
||||
const rows = db.prepare('SELECT id, name, department, supervisor FROM employees ORDER BY name ASC').all();
|
||||
const rows = db.prepare('SELECT id, name, department, supervisor, notes FROM employees ORDER BY name ASC').all();
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
@@ -25,26 +38,133 @@ app.post('/api/employees', (req, res) => {
|
||||
if (!name) return res.status(400).json({ error: 'name is required' });
|
||||
const existing = db.prepare('SELECT * FROM employees WHERE LOWER(name) = LOWER(?)').get(name);
|
||||
if (existing) {
|
||||
if (department || supervisor)
|
||||
if (department || supervisor) {
|
||||
db.prepare('UPDATE employees SET department = COALESCE(?, department), supervisor = COALESCE(?, supervisor) WHERE id = ?')
|
||||
.run(department || null, supervisor || null, existing.id);
|
||||
}
|
||||
return res.json({ ...existing, department, supervisor });
|
||||
}
|
||||
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)').run(name, department || null, supervisor || null);
|
||||
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)')
|
||||
.run(name, department || null, supervisor || null);
|
||||
audit('employee_created', 'employee', result.lastInsertRowid, null, { name });
|
||||
res.status(201).json({ id: result.lastInsertRowid, name, department, supervisor });
|
||||
});
|
||||
|
||||
// ── Employee CPAS Score ─────────────────────────────────────────────────────
|
||||
// ── Employee Edit ─────────────────────────────────────────────────────────────
|
||||
// PATCH /api/employees/:id — update name, department, supervisor, or notes
|
||||
app.patch('/api/employees/:id', (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
const emp = db.prepare('SELECT * FROM employees WHERE id = ?').get(id);
|
||||
if (!emp) return res.status(404).json({ error: 'Employee not found' });
|
||||
|
||||
const { name, department, supervisor, notes, performed_by } = req.body;
|
||||
|
||||
// Prevent name collision with a different employee
|
||||
if (name && name.trim() !== emp.name) {
|
||||
const clash = db.prepare('SELECT id FROM employees WHERE LOWER(name) = LOWER(?) AND id != ?').get(name.trim(), id);
|
||||
if (clash) return res.status(409).json({ error: 'An employee with that name already exists', conflictId: clash.id });
|
||||
}
|
||||
|
||||
const newName = (name || emp.name).trim();
|
||||
const newDept = department !== undefined ? (department || null) : emp.department;
|
||||
const newSupervisor = supervisor !== undefined ? (supervisor || null) : emp.supervisor;
|
||||
const newNotes = notes !== undefined ? (notes || null) : emp.notes;
|
||||
|
||||
db.prepare('UPDATE employees SET name = ?, department = ?, supervisor = ?, notes = ? WHERE id = ?')
|
||||
.run(newName, newDept, newSupervisor, newNotes, id);
|
||||
|
||||
audit('employee_edited', 'employee', id, performed_by, {
|
||||
before: { name: emp.name, department: emp.department, supervisor: emp.supervisor, notes: emp.notes },
|
||||
after: { name: newName, department: newDept, supervisor: newSupervisor, notes: newNotes },
|
||||
});
|
||||
|
||||
res.json({ id, name: newName, department: newDept, supervisor: newSupervisor, notes: newNotes });
|
||||
});
|
||||
|
||||
// ── Employee Merge ────────────────────────────────────────────────────────────
|
||||
// POST /api/employees/:id/merge — reassign all violations from sourceId → id, then delete source
|
||||
app.post('/api/employees/:id/merge', (req, res) => {
|
||||
const targetId = parseInt(req.params.id);
|
||||
const { source_id, performed_by } = req.body;
|
||||
if (!source_id) return res.status(400).json({ error: 'source_id is required' });
|
||||
|
||||
const target = db.prepare('SELECT * FROM employees WHERE id = ?').get(targetId);
|
||||
const source = db.prepare('SELECT * FROM employees WHERE id = ?').get(source_id);
|
||||
if (!target) return res.status(404).json({ error: 'Target employee not found' });
|
||||
if (!source) return res.status(404).json({ error: 'Source employee not found' });
|
||||
if (targetId === parseInt(source_id)) return res.status(400).json({ error: 'Cannot merge an employee into themselves' });
|
||||
|
||||
const mergeTransaction = db.transaction(() => {
|
||||
// Move all violations
|
||||
const moved = db.prepare('UPDATE violations SET employee_id = ? WHERE employee_id = ?').run(targetId, source_id);
|
||||
// Delete the source employee
|
||||
db.prepare('DELETE FROM employees WHERE id = ?').run(source_id);
|
||||
return moved.changes;
|
||||
});
|
||||
|
||||
const violationsMoved = mergeTransaction();
|
||||
|
||||
audit('employee_merged', 'employee', targetId, performed_by, {
|
||||
source: { id: source.id, name: source.name },
|
||||
target: { id: target.id, name: target.name },
|
||||
violations_reassigned: violationsMoved,
|
||||
});
|
||||
|
||||
res.json({ success: true, violations_reassigned: violationsMoved });
|
||||
});
|
||||
|
||||
// ── Employee notes (PATCH shorthand) ─────────────────────────────────────────
|
||||
// PATCH /api/employees/:id/notes — save free-text notes only
|
||||
app.patch('/api/employees/:id/notes', (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
const emp = db.prepare('SELECT * FROM employees WHERE id = ?').get(id);
|
||||
if (!emp) return res.status(404).json({ error: 'Employee not found' });
|
||||
|
||||
const { notes, performed_by } = req.body;
|
||||
const newNotes = notes !== undefined ? (notes || null) : emp.notes;
|
||||
|
||||
db.prepare('UPDATE employees SET notes = ? WHERE id = ?').run(newNotes, id);
|
||||
audit('employee_notes_updated', 'employee', id, performed_by, { notes: newNotes });
|
||||
res.json({ id, notes: newNotes });
|
||||
});
|
||||
|
||||
// Employee score (current snapshot)
|
||||
app.get('/api/employees/:id/score', (req, res) => {
|
||||
const row = db.prepare('SELECT * FROM active_cpas_scores WHERE employee_id = ?').get(req.params.id);
|
||||
res.json(row || { employee_id: req.params.id, active_points: 0, violation_count: 0 });
|
||||
});
|
||||
|
||||
// ── Dashboard — all employees with scores ───────────────────────────────────
|
||||
app.get('/api/dashboard', (req, res) => {
|
||||
// ── Expiration Timeline ───────────────────────────────────────────────────────
|
||||
// GET /api/employees/:id/expiration — active violations sorted by roll-off date
|
||||
// Returns each active violation with days_remaining until it exits the 90-day window.
|
||||
app.get('/api/employees/:id/expiration', (req, res) => {
|
||||
const rows = db.prepare(`
|
||||
SELECT
|
||||
e.id, e.name, e.department, e.supervisor,
|
||||
v.id,
|
||||
v.violation_name,
|
||||
v.violation_type,
|
||||
v.category,
|
||||
v.points,
|
||||
v.incident_date,
|
||||
DATE(v.incident_date, '+90 days') AS expires_on,
|
||||
CAST(
|
||||
JULIANDAY(DATE(v.incident_date, '+90 days')) -
|
||||
JULIANDAY(DATE('now'))
|
||||
AS INTEGER
|
||||
) AS days_remaining
|
||||
FROM violations v
|
||||
WHERE v.employee_id = ?
|
||||
AND v.negated = 0
|
||||
AND v.incident_date >= DATE('now', '-90 days')
|
||||
ORDER BY v.incident_date ASC
|
||||
`).all(req.params.id);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// Dashboard
|
||||
app.get('/api/dashboard', (req, res) => {
|
||||
const rows = db.prepare(`
|
||||
SELECT e.id, e.name, e.department, e.supervisor,
|
||||
COALESCE(s.active_points, 0) AS active_points,
|
||||
COALESCE(s.violation_count,0) AS violation_count
|
||||
FROM employees e
|
||||
@@ -54,36 +174,13 @@ app.get('/api/dashboard', (req, res) => {
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// ── Violation counts (90-day) ───────────────────────────────────────────────
|
||||
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 map = {};
|
||||
rows.forEach(r => { map[r.violation_type] = r.count; });
|
||||
res.json(map);
|
||||
});
|
||||
|
||||
// ── Violation counts (all-time) ─────────────────────────────────────────────
|
||||
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 map = {};
|
||||
rows.forEach(r => { map[r.violation_type] = { count: r.count, max_points_used: r.max_points_used }; });
|
||||
res.json(map);
|
||||
});
|
||||
|
||||
// ── Violation history (per employee) ───────────────────────────────────────
|
||||
// Violation history (per employee) with resolutions + amendment count
|
||||
app.get('/api/violations/employee/:id', (req, res) => {
|
||||
const limit = parseInt(req.query.limit) || 50;
|
||||
const rows = db.prepare(`
|
||||
SELECT v.*, r.resolution_type, r.details AS resolution_details,
|
||||
r.resolved_by, r.created_at AS resolved_at
|
||||
r.resolved_by, r.created_at AS resolved_at,
|
||||
(SELECT COUNT(*) FROM violation_amendments a WHERE a.violation_id = v.id) AS amendment_count
|
||||
FROM violations v
|
||||
LEFT JOIN violation_resolutions r ON r.violation_id = v.id
|
||||
WHERE v.employee_id = ?
|
||||
@@ -93,75 +190,212 @@ app.get('/api/violations/employee/:id', (req, res) => {
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// ── POST new violation ──────────────────────────────────────────────────────
|
||||
// ── Violation amendment history ───────────────────────────────────────────────
|
||||
app.get('/api/violations/:id/amendments', (req, res) => {
|
||||
const rows = db.prepare(`
|
||||
SELECT * FROM violation_amendments WHERE violation_id = ? ORDER BY created_at DESC
|
||||
`).all(req.params.id);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// Helper: compute prior_active_points at time of insert
|
||||
function getPriorActivePoints(employeeId, incidentDate) {
|
||||
const row = db.prepare(
|
||||
`SELECT COALESCE(SUM(points),0) AS pts
|
||||
FROM violations
|
||||
WHERE employee_id = ?
|
||||
AND negated = 0
|
||||
AND incident_date >= DATE(?, '-90 days')
|
||||
AND incident_date < ?`
|
||||
).get(employeeId, incidentDate, incidentDate);
|
||||
return row ? row.pts : 0;
|
||||
}
|
||||
|
||||
// POST new violation
|
||||
app.post('/api/violations', (req, res) => {
|
||||
const {
|
||||
employee_id, violation_type, violation_name, category,
|
||||
points, incident_date, incident_time, location,
|
||||
details, submitted_by, witness_name
|
||||
} = req.body;
|
||||
if (!employee_id || !violation_type || !points || !incident_date)
|
||||
|
||||
if (!employee_id || !violation_type || !points || !incident_date) {
|
||||
return res.status(400).json({ error: 'Missing required fields' });
|
||||
}
|
||||
|
||||
const ptsInt = parseInt(points);
|
||||
const priorPts = getPriorActivePoints(employee_id, incident_date);
|
||||
|
||||
const result = db.prepare(`
|
||||
INSERT INTO violations (employee_id, violation_type, violation_name, category,
|
||||
points, incident_date, incident_time, location, details, submitted_by, witness_name)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(employee_id, violation_type, violation_name || violation_type,
|
||||
category || 'General', points, incident_date,
|
||||
INSERT INTO violations (
|
||||
employee_id, violation_type, violation_name, category,
|
||||
points, incident_date, incident_time, location,
|
||||
details, submitted_by, witness_name,
|
||||
prior_active_points
|
||||
) 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);
|
||||
details || null, submitted_by || null, witness_name || null,
|
||||
priorPts
|
||||
);
|
||||
|
||||
audit('violation_created', 'violation', result.lastInsertRowid, submitted_by, {
|
||||
employee_id, violation_type, points: ptsInt, incident_date,
|
||||
});
|
||||
|
||||
res.status(201).json({ id: result.lastInsertRowid });
|
||||
});
|
||||
|
||||
// ── PATCH — Soft Negate (add resolution) ───────────────────────────────────
|
||||
// ── 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'];
|
||||
|
||||
app.patch('/api/violations/:id/amend', (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
const { changed_by, ...updates } = req.body;
|
||||
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
if (!violation) return res.status(404).json({ error: 'Violation not found' });
|
||||
if (violation.negated) return res.status(400).json({ error: 'Cannot amend a negated violation' });
|
||||
|
||||
// Only allow whitelisted fields to be amended
|
||||
const allowed = Object.fromEntries(
|
||||
Object.entries(updates).filter(([k]) => AMENDABLE_FIELDS.includes(k))
|
||||
);
|
||||
if (Object.keys(allowed).length === 0) {
|
||||
return res.status(400).json({ error: 'No amendable fields provided', amendable: AMENDABLE_FIELDS });
|
||||
}
|
||||
|
||||
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];
|
||||
if (String(oldVal) !== String(newVal)) {
|
||||
insertAmendment.run(id, changed_by || null, field, oldVal ?? null, newVal ?? null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
amendTransaction();
|
||||
|
||||
audit('violation_amended', 'violation', id, changed_by, { fields: Object.keys(allowed) });
|
||||
|
||||
const updated = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
// ── Negate a violation ────────────────────────────────────────────────────────
|
||||
app.patch('/api/violations/:id/negate', (req, res) => {
|
||||
const { resolution_type, details, resolved_by } = req.body;
|
||||
if (!resolution_type) return res.status(400).json({ error: 'resolution_type is required' });
|
||||
const id = req.params.id;
|
||||
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(req.params.id);
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
if (!violation) return res.status(404).json({ error: 'Violation not found' });
|
||||
|
||||
db.prepare('UPDATE violations SET negated = 1, negated_at = CURRENT_TIMESTAMP WHERE id = ?').run(req.params.id);
|
||||
db.prepare('UPDATE violations SET negated = 1 WHERE id = ?').run(id);
|
||||
|
||||
const existing = db.prepare('SELECT id FROM violation_resolutions WHERE violation_id = ?').get(id);
|
||||
if (existing) {
|
||||
db.prepare(`
|
||||
UPDATE violation_resolutions
|
||||
SET resolution_type = ?, details = ?, resolved_by = ?, created_at = datetime('now')
|
||||
WHERE violation_id = ?
|
||||
`).run(resolution_type || 'Resolved', details || null, resolved_by || null, id);
|
||||
} else {
|
||||
db.prepare(`
|
||||
INSERT INTO violation_resolutions (violation_id, resolution_type, details, resolved_by)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`).run(req.params.id, resolution_type, details || null, resolved_by || null);
|
||||
`).run(id, resolution_type || 'Resolved', details || null, resolved_by || null);
|
||||
}
|
||||
|
||||
audit('violation_negated', 'violation', id, resolved_by, { resolution_type });
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ── PATCH — Restore negated violation ──────────────────────────────────────
|
||||
// ── Restore a negated violation ───────────────────────────────────────────────
|
||||
app.patch('/api/violations/:id/restore', (req, res) => {
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(req.params.id);
|
||||
const id = req.params.id;
|
||||
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
if (!violation) return res.status(404).json({ error: 'Violation not found' });
|
||||
db.prepare('UPDATE violations SET negated = 0, negated_at = NULL WHERE id = ?').run(req.params.id);
|
||||
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(req.params.id);
|
||||
|
||||
db.prepare('UPDATE violations SET negated = 0 WHERE id = ?').run(id);
|
||||
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(id);
|
||||
|
||||
audit('violation_restored', 'violation', id, req.body?.performed_by, {});
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ── DELETE — Hard Delete ────────────────────────────────────────────────────
|
||||
// ── Hard delete a violation ───────────────────────────────────────────────────
|
||||
app.delete('/api/violations/:id', (req, res) => {
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(req.params.id);
|
||||
const id = req.params.id;
|
||||
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
if (!violation) return res.status(404).json({ error: 'Violation not found' });
|
||||
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(req.params.id);
|
||||
db.prepare('DELETE FROM violations WHERE id = ?').run(req.params.id);
|
||||
|
||||
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(id);
|
||||
db.prepare('DELETE FROM violations WHERE id = ?').run(id);
|
||||
|
||||
audit('violation_deleted', 'violation', id, req.body?.performed_by, {
|
||||
violation_type: violation.violation_type, employee_id: violation.employee_id,
|
||||
});
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ── PDF ─────────────────────────────────────────────────────────────────────
|
||||
// ── Audit log ─────────────────────────────────────────────────────────────────
|
||||
app.get('/api/audit', (req, res) => {
|
||||
const limit = Math.min(parseInt(req.query.limit) || 100, 500);
|
||||
const offset = parseInt(req.query.offset) || 0;
|
||||
const type = req.query.entity_type;
|
||||
const id = req.query.entity_id;
|
||||
|
||||
let sql = 'SELECT * FROM audit_log';
|
||||
const args = [];
|
||||
const where = [];
|
||||
if (type) { where.push('entity_type = ?'); args.push(type); }
|
||||
if (id) { where.push('entity_id = ?'); args.push(id); }
|
||||
if (where.length) sql += ' WHERE ' + where.join(' AND ');
|
||||
sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
|
||||
args.push(limit, offset);
|
||||
|
||||
res.json(db.prepare(sql).all(...args));
|
||||
});
|
||||
|
||||
// ── PDF endpoint ──────────────────────────────────────────────────────────────
|
||||
app.get('/api/violations/:id/pdf', async (req, res) => {
|
||||
try {
|
||||
const violation = db.prepare(`
|
||||
SELECT v.*, e.name as employee_name, e.department, e.supervisor
|
||||
FROM violations v JOIN employees e ON e.id = v.employee_id
|
||||
FROM violations v
|
||||
JOIN employees e ON e.id = v.employee_id
|
||||
WHERE v.id = ?
|
||||
`).get(req.params.id);
|
||||
|
||||
if (!violation) return res.status(404).json({ error: 'Violation not found' });
|
||||
const score = db.prepare('SELECT * FROM active_cpas_scores WHERE employee_id = ?').get(violation.employee_id) || { active_points: 0, violation_count: 0 };
|
||||
const pdfBuffer = await generatePdf(violation, score);
|
||||
|
||||
const active = db.prepare('SELECT * FROM active_cpas_scores WHERE employee_id = ?')
|
||||
.get(violation.employee_id) || { active_points: 0, violation_count: 0 };
|
||||
|
||||
const scoreForPdf = {
|
||||
employee_id: violation.employee_id,
|
||||
active_points: violation.prior_active_points != null ? violation.prior_active_points : active.active_points,
|
||||
violation_count: active.violation_count,
|
||||
};
|
||||
|
||||
const pdfBuffer = await generatePdf(violation, scoreForPdf);
|
||||
const safeName = violation.employee_name.replace(/[^a-z0-9]/gi, '_');
|
||||
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Disposition': `attachment; filename="CPAS_${safeName}_${violation.incident_date}.pdf"`,
|
||||
@@ -174,7 +408,7 @@ app.get('/api/violations/:id/pdf', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ── SPA fallback ────────────────────────────────────────────────────────────
|
||||
// SPA fallback
|
||||
app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'client', 'dist', 'index.html')));
|
||||
|
||||
app.listen(PORT, '0.0.0.0', () => console.log(`[CPAS] Server running on port ${PORT}`));
|
||||
|
||||
Reference in New Issue
Block a user