Compare commits

..

35 Commits

Author SHA1 Message Date
bcf0e3f3d1 fix: reduce PDF margins and remove redundant puppeteer footer 2026-03-06 23:40:49 -06:00
3977c3652f feat: redesign PDF template - clean modern layout with inline logo 2026-03-06 23:34:45 -06:00
f4f191518c fix: dark mode colors in ViolationHistory component 2026-03-06 23:26:39 -06:00
69272f71a3 docs: add roadmap section with completed features and proposed enhancements 2026-03-06 23:21:24 -06:00
a6447970ac docs: update README to reflect current codebase (phases 1-4 complete) 2026-03-06 23:18:28 -06:00
e0170d71f5 Merge pull request 'Upload files to "/"' (#19) from p4-hotfixes into master
Reviewed-on: #19
2026-03-06 18:00:01 -06:00
4bb09997ee Upload files to "/" 2026-03-06 17:59:48 -06:00
52a57f21b0 Merge pull request 'Upload files to "client/src/components"' (#18) from p4-hotfixes into master
Reviewed-on: #18
2026-03-06 17:43:31 -06:00
3cc62c2746 Upload files to "client/src/components" 2026-03-06 17:43:14 -06:00
47e14ae23b Merge pull request 'Upload files to "client/src/components"' (#17) from p4-hotfixes into master
Reviewed-on: #17
2026-03-06 17:20:42 -06:00
a6d4885a53 Upload files to "client/src/components" 2026-03-06 17:19:57 -06:00
f4869b42b4 Merge pull request 'p4-hotfixes' (#16) from p4-hotfixes into master
Reviewed-on: http://10.2.0.2:3000/jason/cpas/pulls/16
2026-03-06 15:44:34 -06:00
98fe9d4a79 Upload files to "client/src/components" 2026-03-06 15:44:15 -06:00
f52af27114 Upload files to "client/src/components" 2026-03-06 15:38:20 -06:00
7ff066011d Merge pull request 'Upload files to "client/src/components"' (#15) from p4-hotfixes into master
Reviewed-on: http://10.2.0.2:3000/jason/cpas/pulls/15
2026-03-06 15:26:06 -06:00
35b4ded10c Upload files to "client/src/components" 2026-03-06 15:25:48 -06:00
5ef61f6590 Merge pull request 'p4-hotfixes' (#14) from p4-hotfixes into master
Reviewed-on: http://10.2.0.2:3000/jason/cpas/pulls/14
2026-03-06 15:01:04 -06:00
cb8c56adfa Upload files to "pdf" 2026-03-06 15:00:27 -06:00
accb24a286 Upload files to "db" 2026-03-06 14:59:55 -06:00
fdfa0bcf2f Upload files to "/" 2026-03-06 14:42:12 -06:00
2ac330904d Merge pull request 'p4-hotfixes' (#13) from p4-hotfixes into master
Reviewed-on: http://10.2.0.2:3000/jason/cpas/pulls/13
2026-03-06 14:38:57 -06:00
60e9da488c Upload files to "pdf" 2026-03-06 14:38:43 -06:00
1a09efbfe5 Upload files to "client/src/components" 2026-03-06 14:38:29 -06:00
de07e77e07 Merge pull request 'Update client/src/components/ViolationForm.jsx' (#12) from p4-hotfixes into master
Reviewed-on: http://10.2.0.2:3000/jason/cpas/pulls/12
2026-03-06 14:23:44 -06:00
722f404269 Update client/src/components/ViolationForm.jsx 2026-03-06 14:23:19 -06:00
7db080bd2a Merge pull request 'Upload files to "client/src/components"' (#11) from p4-hotfixes into master
Reviewed-on: http://10.2.0.2:3000/jason/cpas/pulls/11
2026-03-06 14:21:26 -06:00
571c8f2838 Upload files to "client/src/components" 2026-03-06 14:20:57 -06:00
eb07832cc7 Upload files to "client/public/static" 2026-03-06 14:15:05 -06:00
6305cedb14 Delete client/public 2026-03-06 14:14:27 -06:00
f006c015b0 Add client/public 2026-03-06 14:14:11 -06:00
ecc9f3b9f6 Merge pull request 'p4-hotfixes' (#10) from p4-hotfixes into master
Reviewed-on: http://10.2.0.2:3000/jason/cpas/pulls/10
2026-03-06 14:13:15 -06:00
066f95cc88 Upload files to "pdf" 2026-03-06 14:12:00 -06:00
2383e3cc94 Upload files to "client/src/components" 2026-03-06 14:11:46 -06:00
8bbfd90f48 Upload files to "client/src" 2026-03-06 14:11:36 -06:00
590aae5cca Upload files to "/" 2026-03-06 14:11:19 -06:00
14 changed files with 1807 additions and 1187 deletions

View File

@@ -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 FROM node:20-alpine AS builder
WORKDIR /build WORKDIR /build
# Install backend deps
COPY package.json ./ COPY package.json ./
RUN npm install RUN npm install
# Install frontend deps and build React app
COPY client/package.json ./client/ COPY client/package.json ./client/
RUN cd client && npm install RUN cd client && npm install
COPY client/ ./client/ COPY client/ ./client/
RUN cd client && npm run build RUN cd client && npm run build
# ─────────────────────────────────────────────────────────────────────────────
# Stage 2: Production image
# ─────────────────────────────────────────────────────────────────────────────
FROM node:20-alpine AS production FROM node:20-alpine AS production
RUN apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont
# Chromium for Puppeteer PDF generation
RUN apk add --no-cache \
chromium \
nss \
freetype \
harfbuzz \
ca-certificates \
ttf-freefont
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
ENV NODE_ENV=production ENV NODE_ENV=production
ENV PORT=3001 ENV PORT=3001
ENV DB_PATH=/data/cpas.db ENV DB_PATH=/data/cpas.db
WORKDIR /app WORKDIR /app
# Copy backend node_modules and compiled frontend from builder
COPY --from=builder /build/node_modules ./node_modules COPY --from=builder /build/node_modules ./node_modules
COPY --from=builder /build/client/dist ./client/dist COPY --from=builder /build/client/dist ./client/dist
# Copy all backend source files
COPY server.js ./ COPY server.js ./
COPY package.json ./ COPY package.json ./
COPY db/ ./db/ COPY db/ ./db/
COPY pdf/ ./pdf/ COPY pdf/ ./pdf/
COPY client/public/static ./client/dist/static
# Ensure data directory exists
RUN mkdir -p /data RUN mkdir -p /data
EXPOSE 3001 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"] CMD ["node", "server.js"]

178
README.md
View File

@@ -1,11 +1,13 @@
# CPAS Violation Tracker # CPAS Violation Tracker
Single-container Dockerized web app for CPAS violation documentation. Single-container Dockerized web app for CPAS violation documentation and workforce standing management.
Built with React + Vite (frontend), Node.js + Express (backend), SQLite (database). Built with **React + Vite** (frontend), **Node.js + Express** (backend), **SQLite** (database), and **Puppeteer** (PDF generation).
---
## The only requirement on your machine: Docker Desktop ## 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,18 +43,88 @@ docker stop cpas-tracker && docker rm cpas-tracker
docker run -d --name cpas-tracker -p 3001:3001 -v cpas-data:/data 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
### 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
- Negate / restore individual violations (soft delete with resolution type + notes)
- Hard delete option for data entry errors
- PDF download for any historical violation record
### CPAS Tier System
| Points | Tier | Label |
|--------|------|-------|
| 04 | 01 | Elite Standing |
| 59 | 1 | Realignment |
| 1014 | 2 | Administrative Lockdown |
| 1519 | 3 | Verification |
| 2024 | 4 | Risk Mitigation |
| 2529 | 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 |
| 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) |
| PATCH | `/api/violations/:id/negate` | Negate a violation (soft delete + resolution record) |
| PATCH | `/api/violations/:id/restore` | Restore a negated violation |
| DELETE | `/api/violations/:id` | Hard delete a violation |
| GET | `/api/violations/:id/pdf` | Download violation PDF |
---
## Project Structure ## Project Structure
``` ```
cpas-violation-tracker/ cpas/
├── Dockerfile # Multi-stage: builds React + runs Express ├── Dockerfile # Multi-stage: builds React + runs Express w/ Chromium
├── .dockerignore ├── .dockerignore
├── package.json # Backend (Express) deps ├── package.json # Backend (Express) deps
├── server.js # API + static file server ├── server.js # API + static file server
├── db/ ├── db/
│ ├── schema.sql # Tables + 90-day score view │ ├── schema.sql # Tables + 90-day active score view
│ └── database.js # SQLite connection │ └── database.js # SQLite connection (better-sqlite3)
── client/ # React frontend (Vite) ── pdf/
│ └── generator.js # Puppeteer PDF generation
└── client/ # React frontend (Vite)
├── package.json ├── package.json
├── vite.config.js ├── vite.config.js
├── index.html ├── index.html
@@ -60,14 +132,84 @@ cpas-violation-tracker/
├── main.jsx ├── main.jsx
├── App.jsx ├── App.jsx
├── data/ ├── data/
│ └── violations.js # All CPAS violation definitions │ └── violations.js # All CPAS violation definitions + groups
├── hooks/
│ └── useEmployeeIntelligence.js # Score + history hook
└── components/ └── components/
── ViolationForm.jsx ── CpasBadge.jsx # Tier badge + color logic
├── TierWarning.jsx # Pre-submit tier crossing alert
├── Dashboard.jsx # Company-wide leaderboard
├── ViolationForm.jsx # Violation entry form
├── EmployeeModal.jsx # Employee profile + history modal
├── 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 ## Database Schema
- [ ] Phase 3 — Puppeteer PDF generation
- [ ] Phase 4 — Dashboard, CPAS scores, tier warnings Three tables + one view:
- [ ] Phase 5 — Recidivist point auto-suggest
- **`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)
- **`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 |
---
### 🔲 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
- **Expiration timeline** — visual showing which active violations will roll off the 90-day window and when, so supervisors can anticipate tier drops
- **CSV / Excel export** — bulk export of violations or dashboard data for external reporting or payroll integration
#### Employee Management
- **Employee edit / merge** — ability to update employee name, department, or supervisor without losing history; merge duplicate records created by name typos
- **Supervisor view** — scoped dashboard showing only the employees under a given supervisor, useful for multi-supervisor environments
- **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
#### 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
- **Violation amendment** — edit a submitted violation's details (not points) with an audit trail, rather than delete-and-resubmit
- **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
- **Audit log** — immutable log of all creates, negates, restores, and deletes with timestamp and acting user, stored separately from the violations table
- **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.*

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

View File

@@ -3,38 +3,44 @@ import ViolationForm from './components/ViolationForm';
import Dashboard from './components/Dashboard'; import Dashboard from './components/Dashboard';
const tabs = [ const tabs = [
{ id: 'dashboard', label: '📊 Dashboard' }, { id: 'dashboard', label: '📊 Dashboard' },
{ id: 'violation', label: '+ New Violation' }, { id: 'violation', label: '+ New Violation' },
]; ];
const s = { const s = {
app: { minHeight: '100vh', background: '#f5f6fa', fontFamily: "'Segoe UI', Arial, sans-serif" }, app: { minHeight: '100vh', background: '#050608', fontFamily: "'Segoe UI', Arial, sans-serif", color: '#f8f9fa' },
nav: { background: 'linear-gradient(135deg, #2c3e50, #34495e)', padding: '0 40px', display: 'flex', alignItems: 'center', gap: 0 }, nav: { background: '#000000', padding: '0 40px', display: 'flex', alignItems: 'center', gap: 0, borderBottom: '1px solid #333' },
logo: { color: 'white', fontWeight: 800, fontSize: '18px', letterSpacing: '0.5px', marginRight: '32px', padding: '18px 0' }, logoWrap: { display: 'flex', alignItems: 'center', marginRight: '32px', padding: '14px 0' },
tab: (active) => ({ logoImg: { height: '28px', marginRight: '10px' },
padding: '18px 22px', color: active ? 'white' : 'rgba(255,255,255,0.6)', logoText: { color: '#f8f9fa', fontWeight: 800, fontSize: '18px', letterSpacing: '0.5px' },
borderBottom: active ? '3px solid #667eea' : '3px solid transparent', tab: (active) => ({
cursor: 'pointer', fontWeight: active ? 700 : 400, fontSize: '14px', padding: '18px 22px',
background: 'none', border: 'none', borderBottom: active ? '3px solid #667eea' : '3px solid transparent', color: active ? '#f8f9fa' : 'rgba(248,249,250,0.6)',
}), borderBottom: active ? '3px solid #d4af37' : '3px solid transparent',
card: { maxWidth: '1100px', margin: '30px auto', background: 'white', borderRadius: '10px', boxShadow: '0 2px 12px rgba(0,0,0,0.08)' }, cursor: 'pointer', fontWeight: active ? 700 : 400, fontSize: '14px',
background: 'none', border: 'none',
}),
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() { export default function App() {
const [tab, setTab] = useState('dashboard'); const [tab, setTab] = useState('dashboard');
return ( return (
<div style={s.app}> <div style={s.app}>
<nav style={s.nav}> <nav style={s.nav}>
<div style={s.logo}>CPAS Tracker</div> <div style={s.logoWrap}>
{tabs.map(t => ( <img src="/static/mpm-logo.png" alt="MPM" style={s.logoImg} />
<button key={t.id} style={s.tab(tab === t.id)} onClick={() => setTab(t.id)}> <div style={s.logoText}>CPAS Tracker</div>
{t.label}
</button>
))}
</nav>
<div style={s.card}>
{tab === 'dashboard' ? <Dashboard /> : <ViolationForm />}
</div>
</div> </div>
); {tabs.map(t => (
<button key={t.id} style={s.tab(tab === t.id)} onClick={() => setTab(t.id)}>
{t.label}
</button>
))}
</nav>
<div style={s.card}>
{tab === 'dashboard' ? <Dashboard /> : <ViolationForm />}
</div>
</div>
);
} }

View File

@@ -3,171 +3,191 @@ import axios from 'axios';
import CpasBadge, { getTier } from './CpasBadge'; import CpasBadge, { getTier } from './CpasBadge';
import EmployeeModal from './EmployeeModal'; import EmployeeModal from './EmployeeModal';
const AT_RISK_THRESHOLD = 2; // points within next tier boundary const AT_RISK_THRESHOLD = 2;
const TIERS = [ const TIERS = [
{ min: 0, max: 4 }, { min: 0, max: 4 },
{ min: 5, max: 9 }, { min: 5, max: 9 },
{ min: 10, max: 14 }, { min: 10, max: 14 },
{ min: 15, max: 19 }, { min: 15, max: 19 },
{ min: 20, max: 24 }, { min: 20, max: 24 },
{ min: 25, max: 29 }, { min: 25, max: 29 },
{ min: 30, max: 999}, { min: 30, max: 999 },
]; ];
function nextTierBoundary(points) { function nextTierBoundary(points) {
for (const t of TIERS) { for (const t of TIERS) {
if (points >= t.min && points <= t.max && t.max < 999) if (points >= t.min && points <= t.max && t.max < 999) return t.max + 1;
return t.max + 1; }
} return null;
return null;
} }
function isAtRisk(points) { function isAtRisk(points) {
const boundary = nextTierBoundary(points); const boundary = nextTierBoundary(points);
return boundary !== null && (boundary - points) <= AT_RISK_THRESHOLD; return boundary !== null && (boundary - points) <= AT_RISK_THRESHOLD;
} }
const s = { 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' }, header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '12px' },
title: { fontSize: '24px', fontWeight: 700, color: '#2c3e50' }, title: { fontSize: '24px', fontWeight: 700, color: '#f8f9fa' },
subtitle: { fontSize: '13px', color: '#888', marginTop: '3px' }, subtitle: { fontSize: '13px', color: '#b5b5c0', marginTop: '3px' },
statsRow: { display: 'flex', gap: '16px', flexWrap: 'wrap', marginBottom: '28px' }, 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' }, statCard: { flex: '1', minWidth: '140px', background: '#181924', border: '1px solid #30313f', borderRadius: '8px', padding: '16px', textAlign: 'center' },
statNum: { fontSize: '28px', fontWeight: 800, color: '#2c3e50' }, statNum: { fontSize: '28px', fontWeight: 800, color: '#f8f9fa' },
statLbl: { fontSize: '11px', color: '#888', marginTop: '4px' }, statLbl: { fontSize: '11px', color: '#b5b5c0', marginTop: '4px' },
search: { padding: '10px 14px', border: '1px solid #ddd', borderRadius: '6px', fontSize: '14px', width: '260px' }, search: { padding: '10px 14px', border: '1px solid #333544', borderRadius: '6px', fontSize: '14px', width: '260px', background: '#050608', color: '#f8f9fa' },
table: { width: '100%', borderCollapse: 'collapse', background: 'white', borderRadius: '8px', overflow: 'hidden', boxShadow: '0 1px 4px rgba(0,0,0,0.08)' }, 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: '#34495e', color: 'white', padding: '10px 14px', textAlign: 'left', fontSize: '12px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }, 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 #f0f0f0', fontSize: '13px', verticalAlign: 'middle' }, td: { padding: '11px 14px', borderBottom: '1px solid #1c1d29', fontSize: '13px', verticalAlign: 'middle', color: '#f8f9fa' },
nameBtn: { background: 'none', border: 'none', cursor: 'pointer', fontWeight: 600, color: '#667eea', fontSize: '14px', padding: 0, textDecoration: 'underline dotted' }, 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: '#fff3cd', color: '#856404', border: '1px solid #ffc107', verticalAlign: 'middle' }, 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: '#aaa', fontStyle: 'italic', fontSize: '12px' }, zeroRow: { color: '#77798a', fontStyle: 'italic', fontSize: '12px' },
refreshBtn:{ padding: '9px 18px', background: '#667eea', color: 'white', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' }, refreshBtn: { padding: '9px 18px', background: '#d4af37', color: '#000', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
}; };
export default function Dashboard() { export default function Dashboard() {
const [employees, setEmployees] = useState([]); const [employees, setEmployees] = useState([]);
const [filtered, setFiltered] = useState([]); const [filtered, setFiltered] = useState([]);
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const [selectedId, setSelectedId] = useState(null); const [selectedId, setSelectedId] = useState(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const load = useCallback(() => { const load = useCallback(() => {
setLoading(true); setLoading(true);
axios.get('/api/dashboard') axios.get('/api/dashboard')
.then(r => { setEmployees(r.data); setFiltered(r.data); }) .then(r => { setEmployees(r.data); setFiltered(r.data); })
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}, []); }, []);
useEffect(() => { load(); }, [load]); useEffect(() => { load(); }, [load]);
useEffect(() => { useEffect(() => {
const q = search.toLowerCase(); const q = search.toLowerCase();
setFiltered(employees.filter(e => setFiltered(employees.filter(e =>
e.name.toLowerCase().includes(q) || e.name.toLowerCase().includes(q) ||
(e.department || '').toLowerCase().includes(q) || (e.department || '').toLowerCase().includes(q) ||
(e.supervisor || '').toLowerCase().includes(q) (e.supervisor || '').toLowerCase().includes(q)
)); ));
}, [search, employees]); }, [search, employees]);
const atRiskCount = employees.filter(e => isAtRisk(e.active_points)).length; const atRiskCount = employees.filter(e => isAtRisk(e.active_points)).length;
const activeCount = employees.filter(e => e.active_points > 0).length; const activeCount = employees.filter(e => e.active_points > 0).length;
const cleanCount = employees.filter(e => e.active_points === 0).length; const cleanCount = employees.filter(e => e.active_points === 0).length;
const maxPoints = employees.reduce((m, e) => Math.max(m, e.active_points), 0); const maxPoints = employees.reduce((m, e) => Math.max(m, e.active_points), 0);
return ( return (
<div style={s.wrap}> // FIX: Fragment wraps both s.wrap AND EmployeeModal so the modal is
<div style={s.header}> // outside the s.wrap div — React synthetic events will no longer bubble
<div> // from inside the modal up through the Dashboard's DOM tree.
<div style={s.title}>Company Dashboard</div> <>
<div style={s.subtitle}>Click any employee name to view their full profile</div> <div style={s.wrap}>
</div> <div style={s.header}>
<div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}> <div>
<input style={s.search} placeholder="Search name, dept, supervisor…" value={search} onChange={e => setSearch(e.target.value)} /> <div style={s.title}>Company Dashboard</div>
<button style={s.refreshBtn} onClick={load}> Refresh</button> <div style={s.subtitle}>Click any employee name to view their full profile</div>
</div> </div>
</div> <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
<input
{/* ── Stat cards ───────────────────────────────────────── */} style={s.search}
<div style={s.statsRow}> placeholder="Search name, dept, supervisor…"
<div style={s.statCard}> value={search}
<div style={s.statNum}>{employees.length}</div> onChange={e => setSearch(e.target.value)}
<div style={s.statLbl}>Total Employees</div> />
</div> <button style={s.refreshBtn} onClick={load}> Refresh</button>
<div style={{ ...s.statCard, borderTop: '3px solid #28a745' }}> </div>
<div style={{ ...s.statNum, color: '#28a745' }}>{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.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.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.statLbl}>Highest Active Score</div>
</div>
</div>
{/* ── Scoreboard table ─────────────────────────────────── */}
{loading ? (
<p style={{ color: '#aaa', textAlign: 'center', padding: '40px' }}>Loading</p>
) : (
<table style={s.table}>
<thead>
<tr>
<th style={s.th}>#</th>
<th style={s.th}>Employee</th>
<th style={s.th}>Department</th>
<th style={s.th}>Supervisor</th>
<th style={s.th}>Tier / Standing</th>
<th style={s.th}>Active Points</th>
<th style={s.th}>90-Day Violations</th>
</tr>
</thead>
<tbody>
{filtered.length === 0 && (
<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>
<td style={s.td}>
<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}><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>
</tr>
);
})}
</tbody>
</table>
)}
{/* ── Employee profile modal ───────────────────────────── */}
{selectedId && (
<EmployeeModal
employeeId={selectedId}
onClose={() => { setSelectedId(null); load(); }}
/>
)}
</div> </div>
);
<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: '#6ee7b7' }}>{cleanCount}</div>
<div style={s.statLbl}>Elite Standing (0 pts)</div>
</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 #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: '#ff8a80' }}>{maxPoints}</div>
<div style={s.statLbl}>Highest Active Score</div>
</div>
</div>
{loading ? (
<p style={{ color: '#77798a', textAlign: 'center', padding: '40px' }}>Loading</p>
) : (
<table style={s.table}>
<thead>
<tr>
<th style={s.th}>#</th>
<th style={s.th}>Employee</th>
<th style={s.th}>Department</th>
<th style={s.th}>Supervisor</th>
<th style={s.th}>Tier / Standing</th>
<th style={s.th}>Active Points</th>
<th style={s.th}>90-Day Violations</th>
</tr>
</thead>
<tbody>
{filtered.length === 0 && (
<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 ? '#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>
{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: '#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: '#c0c2d6' }}>{emp.violation_count}</td>
</tr>
);
})}
</tbody>
</table>
)}
</div>
{/* FIX: EmployeeModal is now OUTSIDE <div style={s.wrap}>.
React synthetic events no longer bubble from modal buttons
up through Dashboard's component tree. */}
{selectedId && (
<EmployeeModal
employeeId={selectedId}
onClose={() => { setSelectedId(null); load(); }}
/>
)}
</>
);
} }

View File

@@ -4,237 +4,359 @@ import CpasBadge, { getTier } from './CpasBadge';
import NegateModal from './NegateModal'; import NegateModal from './NegateModal';
const s = { const s = {
overlay: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', zIndex: 1000, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end' }, overlay: {
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' }, position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)',
header: { background: 'linear-gradient(135deg, #2c3e50, #34495e)', color: 'white', padding: '24px 28px', position: 'sticky', top: 0, zIndex: 10 }, zIndex: 1000, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end',
closeBtn: { float: 'right', background: 'none', border: 'none', color: 'white', fontSize: '22px', cursor: 'pointer', lineHeight: 1, marginTop: '-2px' }, },
body: { padding: '24px 28px', flex: 1 }, panel: {
scoreRow: { display: 'flex', gap: '12px', flexWrap: 'wrap', marginBottom: '24px' }, background: '#111217', color: '#f8f9fa', width: '680px', maxWidth: '95vw',
scoreCard: { flex: '1', minWidth: '100px', background: '#f8f9fa', borderRadius: '8px', padding: '14px', textAlign: 'center', border: '1px solid #dee2e6' }, height: '100vh', overflowY: 'auto', boxShadow: '-4px 0 24px rgba(0,0,0,0.7)',
scoreNum: { fontSize: '26px', fontWeight: 800 }, display: 'flex', flexDirection: 'column',
scoreLbl: { fontSize: '11px', color: '#888', marginTop: '3px' }, },
sectionHd: { fontSize: '13px', fontWeight: 700, color: '#34495e', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '10px', marginTop: '24px' }, header: {
table: { width: '100%', borderCollapse: 'collapse', fontSize: '12px' }, background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
th: { background: '#f1f3f5', padding: '8px 10px', textAlign: 'left', color: '#555', fontWeight: 600, fontSize: '11px', textTransform: 'uppercase' }, padding: '24px 28px', position: 'sticky', top: 0, zIndex: 10,
td: { padding: '9px 10px', borderBottom: '1px solid #f0f0f0', verticalAlign: 'top' }, borderBottom: '1px solid #222',
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 }), closeBtn: {
resTag: { display: 'inline-block', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#d4edda', color: '#155724', border: '1px solid #c3e6cb' }, float: 'right', background: 'none', border: 'none', color: 'white',
pdfBtn: { background: 'none', border: '1px solid #667eea', color: '#667eea', borderRadius: '4px', padding: '3px 8px', fontSize: '11px', cursor: 'pointer', fontWeight: 600 }, fontSize: '22px', cursor: 'pointer', lineHeight: 1, marginTop: '-2px',
deleteConfirm: { background: '#f8d7da', border: '1px solid #f5c6cb', borderRadius: '6px', padding: '12px', marginTop: '8px', fontSize: '12px' }, },
body: { padding: '24px 28px', flex: 1 },
scoreRow: { display: 'flex', gap: '12px', flexWrap: 'wrap', marginBottom: '24px' },
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: '#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,
},
deleteConfirm: {
background: '#3c1114', border: '1px solid #f5c6cb', borderRadius: '6px',
padding: '12px', marginTop: '8px', fontSize: '12px', color: '#ffb3b8',
},
}; };
export default function EmployeeModal({ employeeId, onClose }) { export default function EmployeeModal({ employeeId, onClose }) {
const [employee, setEmployee] = useState(null); const [employee, setEmployee] = useState(null);
const [score, setScore] = useState(null); const [score, setScore] = useState(null);
const [violations, setViolations] = useState([]); const [violations, setViolations] = useState([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [negating, setNegating] = useState(null); const [negating, setNegating] = useState(null);
const [confirmDel, setConfirmDel] = useState(null); const [confirmDel, setConfirmDel] = useState(null);
const load = useCallback(() => { const load = useCallback(() => {
setLoading(true); setLoading(true);
Promise.all([ Promise.all([
axios.get('/api/employees'), axios.get('/api/employees'),
axios.get(`/api/employees/${employeeId}/score`), axios.get(`/api/employees/${employeeId}/score`),
axios.get(`/api/violations/employee/${employeeId}?limit=100`), axios.get(`/api/violations/employee/${employeeId}?limit=100`),
]).then(([empRes, scoreRes, violRes]) => { ])
const emp = empRes.data.find(e => e.id === employeeId); .then(([empRes, scoreRes, violRes]) => {
setEmployee(emp || null); const emp = empRes.data.find((e) => e.id === employeeId);
setScore(scoreRes.data); setEmployee(emp || null);
setViolations(violRes.data); setScore(scoreRes.data);
}).finally(() => setLoading(false)); setViolations(violRes.data);
}, [employeeId]); })
.finally(() => setLoading(false));
}, [employeeId]);
useEffect(() => { load(); }, [load]); useEffect(() => { load(); }, [load]);
const handleDownloadPdf = async (violId, empName, date) => { const handleDownloadPdf = async (violId, empName, date) => {
const response = await axios.get(`/api/violations/${violId}/pdf`, { responseType: 'blob' }); const response = await axios.get(`/api/violations/${violId}/pdf`, { responseType: 'blob' });
const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' })); const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }));
const link = document.createElement('a'); const link = document.createElement('a');
link.href = url; link.href = url;
link.download = `CPAS_${(empName||'').replace(/[^a-z0-9]/gi,'_')}_${date}.pdf`; link.download = `CPAS_${(empName || '').replace(/[^a-z0-9]/gi, '_')}_${date}.pdf`;
document.body.appendChild(link); document.body.appendChild(link);
link.click(); link.click();
link.remove(); link.remove();
window.URL.revokeObjectURL(url); window.URL.revokeObjectURL(url);
}; };
const handleHardDelete = async (id) => { const handleHardDelete = async (id) => {
await axios.delete(`/api/violations/${id}`); await axios.delete(`/api/violations/${id}`);
setConfirmDel(null); setConfirmDel(null);
load(); // ← refetch employee list, score, and violations load();
}; };
const handleRestore = async (id) => { const handleRestore = async (id) => {
await axios.patch(`/api/violations/${id}/restore`); 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 }) => { const handleNegate = async ({ resolution_type, details, resolved_by }) => {
await axios.patch(`/api/violations/${negating.id}/negate`, { resolution_type, details, resolved_by }); await axios.patch(`/api/violations/${negating.id}/negate`, {
setNegating(null); resolution_type, details, resolved_by,
load(); // ← CRITICAL FIX: refetch score immediately after negation });
}; setNegating(null);
setConfirmDel(null);
load();
};
const tier = score ? getTier(score.active_points) : null; const tier = score ? getTier(score.active_points) : null;
const active = violations.filter(v => !v.negated); const active = violations.filter((v) => !v.negated);
const negated = violations.filter(v => v.negated); const negated = violations.filter((v) => v.negated);
return ( // FIX: overlay click only closes if clicking the backdrop itself, NOT children
<div style={s.overlay} onClick={e => { if (e.target === e.currentTarget) onClose(); }}> const handleOverlayClick = (e) => {
<div style={s.panel}> if (e.target === e.currentTarget) onClose();
};
{/* ── Header ──────────────────────────────────── */} return (
<div style={s.header}> // FIX: panel uses onClick stopPropagation to prevent bubbling to overlay
<button style={s.closeBtn} onClick={onClose}></button> <div style={s.overlay} onClick={handleOverlayClick}>
<div style={{ fontSize: '20px', fontWeight: 700 }}> <div style={s.panel} onClick={(e) => e.stopPropagation()}>
{loading ? 'Loading…' : (employee?.name || 'Employee Profile')}
</div>
{employee && (
<div style={{ fontSize: '12px', opacity: 0.75, marginTop: '4px' }}>
{[employee.department, employee.supervisor ? `Supervisor: ${employee.supervisor}` : null].filter(Boolean).join(' · ')}
</div>
)}
</div>
<div style={s.body}> {/* ── Header ── */}
{loading ? ( <div style={s.header}>
<p style={{ color: '#aaa', textAlign: 'center', paddingTop: '40px' }}>Loading</p> <button style={s.closeBtn} onClick={onClose}></button>
) : (<> <div style={{ fontSize: '18px', fontWeight: 700 }}>
{employee ? employee.name : 'Employee'}
{/* ── Score cards ───────────────────────── */} </div>
<div style={s.scoreRow}> {employee && (
<div style={{ ...s.scoreCard, borderTop: `3px solid ${tier?.color}` }}> <div style={{ fontSize: '12px', color: '#b5b5c0', marginTop: '4px' }}>
<div style={{ ...s.scoreNum, color: tier?.color }}>{score?.active_points ?? 0}</div> {employee.department} {employee.supervisor && `· Supervisor: ${employee.supervisor}`}
<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>
<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.scoreLbl}>Negated</div>
</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>
)}
{/* ── 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>
) : (
<table style={s.table}>
<thead>
<tr>
<th style={s.th}>Date</th>
<th style={s.th}>Violation</th>
<th style={s.th}>Pts</th>
<th style={s.th}>Actions</th>
</tr>
</thead>
<tbody>
{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>}
</td>
<td style={{ ...s.td, fontWeight: 700, color: '#c0392b' }}>{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 ? (
<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>
</div>
</div>
) : (
<button style={{ ...s.actionBtn('#c0392b'), marginTop: '4px' }} onClick={() => setConfirmDel(v.id)}> Delete</button>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
{/* ── Negated violations ────────────────── */}
{negated.length > 0 && (<>
<div style={s.sectionHd}>Negated / Resolved Violations</div>
<table style={s.table}>
<thead>
<tr>
<th style={s.th}>Date</th>
<th style={s.th}>Violation</th>
<th style={s.th}>Pts</th>
<th style={s.th}>Resolution</th>
<th style={s.th}>Actions</th>
</tr>
</thead>
<tbody>
{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>
</td>
<td style={{ ...s.td, textDecoration: 'line-through', color: '#aaa' }}>{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>}
</td>
<td style={s.td}>
<button style={s.actionBtn('#28a745')} onClick={() => handleRestore(v.id)}> Restore</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>
</div>
</div>
) : (
<button style={s.actionBtn('#c0392b')} onClick={() => setConfirmDel(v.id)}> Delete</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</>)}
</>)}
</div>
</div> </div>
)}
{/* ── Negate sub-modal ────────────────────────────────── */}
{negating && (
<NegateModal
violation={negating}
onConfirm={handleNegate}
onCancel={() => setNegating(null)}
/>
)}
</div> </div>
);
{/* ── Body ── */}
<div style={s.body}>
{loading ? (
<div style={{ padding: '40px', textAlign: 'center', color: '#b5b5c0' }}>Loading</div>
) : (
<>
{/* Score Cards */}
{score && (
<div style={s.scoreRow}>
<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.total_violations}</div>
<div style={s.scoreLbl}>Total Violations</div>
</div>
<div style={s.scoreCard}>
<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>
</div>
)}
{score && <CpasBadge points={score.active_points} style={{ marginBottom: '20px' }} />}
{/* ── Active Violations ── */}
<div style={s.sectionHd}>Active Violations</div>
{active.length === 0 ? (
<div style={{ color: '#77798a', fontStyle: 'italic', fontSize: '12px' }}>
No active violations on record.
</div>
) : (
<table style={s.table}>
<thead>
<tr>
<th style={s.th}>Date</th>
<th style={s.th}>Violation</th>
<th style={s.th}>Pts</th>
<th style={s.th}>Actions</th>
</tr>
</thead>
<tbody>
{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={{ 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 }}>{v.points}</td>
<td style={s.td}>
{/* FIX: All buttons use e.stopPropagation() to prevent overlay close */}
<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}>
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>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
{/* ── Negated / Resolved Violations ── */}
{negated.length > 0 && (
<>
<div style={s.sectionHd}>Negated / Resolved</div>
<table style={s.table}>
<thead>
<tr>
<th style={s.th}>Date</th>
<th style={s.th}>Violation</th>
<th style={s.th}>Pts</th>
<th style={s.th}>Resolution</th>
<th style={s.th}>Actions</th>
</tr>
</thead>
<tbody>
{negated.map((v) => (
<tr key={v.id} style={s.negatedRow}>
<td style={s.td}>{v.incident_date}</td>
<td style={s.td}>
<div style={{ fontWeight: 600 }}>{v.violation_name}</div>
<div style={{ fontSize: '10px', color: '#9ca0b8' }}>{v.category}</div>
</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: '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('#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}>
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>
)}
</td>
</tr>
))}
</tbody>
</table>
</>
)}
</>
)}
</div>
</div>
{/* FIX: NegateModal rendered OUTSIDE the panel so it sits at root z-index:2000 */}
{negating && (
<NegateModal
violation={negating}
onConfirm={handleNegate}
onCancel={() => setNegating(null)}
/>
)}
</div>
);
} }

View File

@@ -1,68 +1,138 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
const RESOLUTION_TYPES = [
'Corrective Training Completed',
'Management Discretion',
'Data Entry Error',
'Successfully Appealed',
];
const s = { const s = {
overlay: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center' }, overlay: {
box: { background: 'white', borderRadius: '10px', padding: '28px', width: '440px', maxWidth: '95vw', boxShadow: '0 8px 32px rgba(0,0,0,0.22)' }, position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)',
title: { fontSize: '17px', fontWeight: 700, color: '#2c3e50', marginBottom: '6px' }, display: 'flex', alignItems: 'center', justifyContent: 'center',
sub: { fontSize: '12px', color: '#888', marginBottom: '20px' }, zIndex: 2000,
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' }, modal: {
btnRow: { display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '8px' }, width: '480px', maxWidth: '95vw', background: '#111217', borderRadius: '12px',
btnOk: { padding: '10px 22px', background: '#856404', color: 'white', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 700, fontSize: '13px' }, boxShadow: '0 16px 40px rgba(0,0,0,0.8)', color: '#f8f9fa',
btnCancel:{ padding: '10px 22px', background: '#f1f3f5', color: '#555', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' }, overflow: 'hidden', border: '1px solid #2a2b3a',
violBox: { background: '#fff3cd', border: '1px solid #ffc107', borderRadius: '6px', padding: '10px 14px', marginBottom: '18px', fontSize: '13px' }, },
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 }) { export default function NegateModal({ violation, onConfirm, onCancel }) {
const [resType, setResType] = useState(''); const [resolutionType, setResolutionType] = useState('Corrective Training Completed');
const [details, setDetails] = useState(''); const [details, setDetails] = useState('');
const [resolvedBy, setResolvedBy] = useState(''); const [resolvedBy, setResolvedBy] = useState('');
const [error, setError] = useState('');
const handleSubmit = () => { if (!violation) return null;
if (!resType) { setError('Please select a resolution type.'); return; }
onConfirm({ resolution_type: resType, details, resolved_by: resolvedBy });
};
return ( const handleConfirm = () => {
<div style={s.overlay}> if (!onConfirm) return;
<div style={s.box}> onConfirm({
<div style={s.title}> Negate Violation Points</div> resolution_type: resolutionType,
<div style={s.sub}>This will zero out the points from this incident. The record remains in the audit log.</div> details,
resolved_by: resolvedBy,
});
};
<div style={s.violBox}> // FIX: overlay click only closes on backdrop, NOT modal children
<strong>{violation.violation_name}</strong> &nbsp;·&nbsp; {violation.points} pts &nbsp;·&nbsp; {violation.incident_date} const handleOverlayClick = (e) => {
</div> if (e.target === e.currentTarget && onCancel) onCancel();
};
<label style={s.label}>Resolution Type *</label> return (
<select style={s.input} value={resType} onChange={e => { setResType(e.target.value); setError(''); }}> <div style={s.overlay} onClick={handleOverlayClick}>
<option value="">-- Select Resolution --</option> {/* FIX: stopPropagation prevents modal clicks from bubbling to overlay */}
{RESOLUTION_TYPES.map(r => <option key={r} value={r}>{r}</option>)} <div style={s.modal} onClick={(e) => e.stopPropagation()}>
</select>
<label style={s.label}>Additional Details</label> <div style={s.header}>
<textarea style={{ ...s.input, resize: 'vertical', minHeight: '70px' }} <div style={s.title}>Negate Violation</div>
placeholder="Training course completed, specific context, approving manager notes…" <div style={s.subtitle}>
value={details} onChange={e => setDetails(e.target.value)} /> Record resolution for: <strong>{violation.violation_name}</strong>
</div>
<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)} />
{error && <div style={{ color: '#c0392b', fontSize: '12px', marginBottom: '10px' }}>{error}</div>}
<div style={s.btnRow}>
<button style={s.btnCancel} onClick={onCancel}>Cancel</button>
<button style={s.btnOk} onClick={handleSubmit}>Confirm Negation</button>
</div>
</div>
</div> </div>
);
<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>
<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)}
/>
<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>
<div style={s.footer}>
<button style={s.btnCancel} onClick={onCancel}>Cancel</button>
<button style={s.btnConfirm} onClick={handleConfirm}>Confirm Negation</button>
</div>
</div>
</div>
);
} }

View File

@@ -7,313 +7,307 @@ import TierWarning from './TierWarning';
import ViolationHistory from './ViolationHistory'; import ViolationHistory from './ViolationHistory';
const s = { const s = {
content: { padding: '40px' }, content: { padding: '32px 40px', background: '#111217', borderRadius: '10px', color: '#f8f9fa' },
section: { background: '#f8f9fa', borderLeft: '4px solid #667eea', padding: '20px', marginBottom: '30px', borderRadius: '4px' }, section: { background: '#181924', borderLeft: '4px solid #d4af37', padding: '20px', marginBottom: '30px', borderRadius: '4px', border: '1px solid #2a2b3a' },
sectionTitle: { color: '#2c3e50', fontSize: '20px', marginBottom: '15px' }, sectionTitle: { color: '#f8f9fa', fontSize: '20px', marginBottom: '15px', fontWeight: 700 },
grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '15px', marginTop: '15px' }, grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '15px', marginTop: '15px' },
item: { display: 'flex', flexDirection: 'column' }, item: { display: 'flex', flexDirection: 'column' },
label: { fontWeight: 600, color: '#555', marginBottom: '5px', fontSize: '13px' }, label: { fontWeight: 600, color: '#e5e7f1', marginBottom: '5px', fontSize: '13px' },
input: { padding: '10px', border: '1px solid #ddd', borderRadius: '4px', fontSize: '14px', fontFamily: 'inherit' }, input: { padding: '10px', border: '1px solid #333544', borderRadius: '4px', fontSize: '14px', fontFamily: 'inherit', background: '#050608', color: '#f8f9fa' },
fullCol: { gridColumn: '1 / -1' }, fullCol: { gridColumn: '1 / -1' },
contextBox: { background: '#f1f3f5', border: '1px solid #ced4da', borderRadius: '4px', padding: '10px', fontSize: '12px', color: '#444', marginTop: '4px' }, 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: '#fff3cd', color: '#856404', border: '1px solid #ffc107' }, 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: '#fff3cd', border: '1px solid #ffc107', borderRadius: '4px', padding: '8px 12px', marginTop: '6px', fontSize: '12px', color: '#856404' }, repeatWarn: { background: '#3b2e00', border: '1px solid #d4af37', borderRadius: '4px', padding: '8px 12px', marginTop: '6px', fontSize: '12px', color: '#ffdf8a' },
pointBox: { background: '#fff3cd', border: '2px solid #ffc107', padding: '15px', borderRadius: '6px', marginTop: '15px', textAlign: 'center' }, pointBox: { background: '#181200', border: '2px solid #d4af37', padding: '15px', borderRadius: '6px', marginTop: '15px', textAlign: 'center' },
pointValue: { fontSize: '24px', fontWeight: 'bold', color: '#667eea', margin: '10px 0' }, pointValue: { fontSize: '24px', fontWeight: 'bold', color: '#ffd666', margin: '10px 0' },
scoreRow: { display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '14px', flexWrap: 'wrap' }, scoreRow: { display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '14px', flexWrap: 'wrap' },
btnRow: { display: 'flex', gap: '15px', justifyContent: 'center', marginTop: '30px', 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' }, 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' }, btnSecondary: { padding: '15px 40px', fontSize: '16px', fontWeight: 600, border: '1px solid #333544', borderRadius: '6px', cursor: 'pointer', background: '#050608', color: '#f8f9fa', textTransform: 'uppercase' },
note: { background: '#e7f3ff', borderLeft: '4px solid #2196F3', padding: '15px', margin: '20px 0', borderRadius: '4px' }, 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: '#d4edda', color: '#155724', border: '1px solid #c3e6cb' }, 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: '#f8d7da', color: '#721c24', border: '1px solid #f5c6cb' }, statusErr: { marginTop: '15px', padding: '15px', borderRadius: '6px', textAlign: 'center', fontWeight: 600, background: '#3c1114', color: '#ffb3b8', border: '1px solid #f5c6cb' },
}; };
const EMPTY_FORM = { const EMPTY_FORM = {
employeeId: '', employeeName: '', department: '', supervisor: '', witnessName: '', employeeId: '', employeeName: '', department: '', supervisor: '', witnessName: '',
violationType: '', incidentDate: '', incidentTime: '', violationType: '', incidentDate: '', incidentTime: '',
amount: '', minutesLate: '', location: '', additionalDetails: '', points: 1, amount: '', minutesLate: '', location: '', additionalDetails: '', points: 1,
}; };
export default function ViolationForm() { export default function ViolationForm() {
const [employees, setEmployees] = useState([]); const [employees, setEmployees] = useState([]);
const [form, setForm] = useState(EMPTY_FORM); const [form, setForm] = useState(EMPTY_FORM);
const [violation, setViolation] = useState(null); const [violation, setViolation] = useState(null);
const [status, setStatus] = useState(null); const [status, setStatus] = useState(null);
const [lastViolId, setLastViolId] = useState(null); // ID of most recently saved violation const [lastViolId, setLastViolId] = useState(null);
const [pdfLoading, setPdfLoading] = useState(false); const [pdfLoading, setPdfLoading] = useState(false);
const intel = useEmployeeIntelligence(form.employeeId || null); const intel = useEmployeeIntelligence(form.employeeId || null);
useEffect(() => { useEffect(() => {
axios.get('/api/employees').then(r => setEmployees(r.data)).catch(() => {}); axios.get('/api/employees').then(r => setEmployees(r.data)).catch(() => {});
}, []); }, []);
useEffect(() => { useEffect(() => {
if (!violation || !form.violationType) return; if (!violation || !form.violationType) return;
const allTime = intel.countsAllTime[form.violationType]; const allTime = intel.countsAllTime[form.violationType];
if (allTime && allTime.count >= 1 && violation.minPoints !== violation.maxPoints) { if (allTime && allTime.count >= 1 && violation.minPoints !== violation.maxPoints) {
setForm(prev => ({ ...prev, points: violation.maxPoints })); setForm(prev => ({ ...prev, points: violation.maxPoints }));
} else { } else {
setForm(prev => ({ ...prev, points: violation.minPoints })); setForm(prev => ({ ...prev, points: violation.minPoints }));
} }
}, [form.violationType, violation, intel.countsAllTime]); }, [form.violationType, violation, intel.countsAllTime]);
const handleEmployeeSelect = e => { const handleEmployeeSelect = e => {
const emp = employees.find(x => x.id === parseInt(e.target.value)); const emp = employees.find(x => x.id === parseInt(e.target.value));
if (!emp) return; if (!emp) return;
setForm(prev => ({ ...prev, employeeId: emp.id, employeeName: emp.name, department: emp.department || '', supervisor: emp.supervisor || '' })); setForm(prev => ({ ...prev, employeeId: emp.id, employeeName: emp.name, department: emp.department || '', supervisor: emp.supervisor || '' }));
}; };
const handleViolationChange = e => { const handleViolationChange = e => {
const key = e.target.value; const key = e.target.value;
const v = violationData[key] || null; const v = violationData[key] || null;
setViolation(v); setViolation(v);
setForm(prev => ({ ...prev, violationType: key, points: v ? v.minPoints : 1 })); setForm(prev => ({ ...prev, violationType: key, points: v ? v.minPoints : 1 }));
}; };
const handleChange = e => setForm(prev => ({ ...prev, [e.target.name]: e.target.value })); const handleChange = e => setForm(prev => ({ ...prev, [e.target.name]: e.target.value }));
const handleSubmit = async e => { const handleSubmit = async e => {
e.preventDefault(); e.preventDefault();
if (!form.violationType) return setStatus({ ok: false, msg: 'Please select a violation type.' }); if (!form.violationType) return setStatus({ ok: false, msg: 'Please select a violation type.' });
if (!form.employeeName) return setStatus({ ok: false, msg: 'Please enter an employee name.' }); if (!form.employeeName) return setStatus({ ok: false, msg: 'Please enter an employee name.' });
try { try {
const empRes = await axios.post('/api/employees', { name: form.employeeName, department: form.department, supervisor: form.supervisor }); const empRes = await axios.post('/api/employees', { name: form.employeeName, department: form.department, supervisor: form.supervisor });
const employeeId = empRes.data.id; const employeeId = empRes.data.id;
const violRes = await axios.post('/api/violations', { const violRes = await axios.post('/api/violations', {
employee_id: employeeId, employee_id: employeeId,
violation_type: form.violationType, violation_type: form.violationType,
violation_name: violation?.name || form.violationType, violation_name: violation?.name || form.violationType,
category: violation?.category || 'General', category: violation?.category || 'General',
points: parseInt(form.points), points: parseInt(form.points),
incident_date: form.incidentDate, incident_date: form.incidentDate,
incident_time: form.incidentTime || null, incident_time: form.incidentTime || null,
location: form.location || null, location: form.location || null,
details: form.additionalDetails || null, details: form.additionalDetails || null,
witness_name: form.witnessName || null, witness_name: form.witnessName || null,
}); });
const newId = violRes.data.id; const newId = violRes.data.id;
setLastViolId(newId); setLastViolId(newId);
const empList = await axios.get('/api/employees'); const empList = await axios.get('/api/employees');
setEmployees(empList.data); setEmployees(empList.data);
setStatus({ ok: true, msg: `✓ Violation #${newId} recorded — click Download PDF to save the document.` }); setStatus({ ok: true, msg: `✓ Violation #${newId} recorded — click Download PDF to save the document.` });
setForm(EMPTY_FORM); setForm(EMPTY_FORM);
setViolation(null); setViolation(null);
} catch (err) { } catch (err) {
setStatus({ ok: false, msg: '✗ Error: ' + (err.response?.data?.error || err.message) }); setStatus({ ok: false, msg: '✗ Error: ' + (err.response?.data?.error || err.message) });
} }
}; };
const handleDownloadPdf = async () => { const handleDownloadPdf = async () => {
if (!lastViolId) return; if (!lastViolId) return;
setPdfLoading(true); setPdfLoading(true);
try { try {
const response = await axios.get(`/api/violations/${lastViolId}/pdf`, { const response = await axios.get(`/api/violations/${lastViolId}/pdf`, { responseType: 'blob' });
responseType: 'blob', const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }));
}); const link = document.createElement('a');
const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' })); link.href = url;
const link = document.createElement('a'); link.download = `CPAS_Violation_${lastViolId}.pdf`;
link.href = url; document.body.appendChild(link);
link.download = `CPAS_Violation_${lastViolId}.pdf`; link.click();
document.body.appendChild(link); link.remove();
link.click(); window.URL.revokeObjectURL(url);
link.remove(); } catch (err) {
window.URL.revokeObjectURL(url); setStatus({ ok: false, msg: '✗ PDF generation failed: ' + err.message });
} catch (err) { } finally {
setStatus({ ok: false, msg: '✗ PDF generation failed: ' + err.message }); setPdfLoading(false);
} finally { }
setPdfLoading(false); };
}
};
const showField = f => violation?.fields?.includes(f); const showField = f => violation?.fields?.includes(f);
const priorCount90 = key => intel.counts90[key] || 0; const priorCount90 = key => intel.counts90[key] || 0;
const isRepeat = key => (intel.countsAllTime[key]?.count || 0) >= 1; const isRepeat = key => (intel.countsAllTime[key]?.count || 0) >= 1;
return ( return (
<div style={s.content}> <div style={s.content}>
{/* ── Employee Information ─────────────────────────────── */} <div style={s.section}>
<div style={s.section}> <h2 style={s.sectionTitle}>Employee Information</h2>
<h2 style={s.sectionTitle}>Employee Information</h2>
{intel.score && form.employeeId && ( {intel.score && form.employeeId && (
<div style={s.scoreRow}> <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} /> <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 {intel.score.violation_count} violation{intel.score.violation_count !== 1 ? 's' : ''} in last 90 days
</span> </span>
</div> </div>
)} )}
{employees.length > 0 && ( {employees.length > 0 && (
<div style={{ marginBottom: '12px' }}> <div style={{ marginBottom: '12px' }}>
<label style={s.label}>Quick-Select Existing Employee:</label> <label style={s.label}>Quick-Select Existing Employee:</label>
<select style={s.input} onChange={handleEmployeeSelect} value={form.employeeId || ''}> <select style={s.input} onChange={handleEmployeeSelect} value={form.employeeId || ''}>
<option value="">-- Select existing or enter new below --</option> <option value="">-- Select existing or enter new below --</option>
{employees.map(e => ( {employees.map(e => (
<option key={e.id} value={e.id}>{e.name}{e.department ? `${e.department}` : ''}</option> <option key={e.id} value={e.id}>{e.name}{e.department ? `${e.department}` : ''}</option>
))} ))}
</select> </select>
</div> </div>
)} )}
<div style={s.grid}> <div style={s.grid}>
{[['employeeName','Employee Name','text','John Doe'],['department','Department','text','Engineering'],['supervisor','Supervisor Name','text','Jane Smith'],['witnessName','Witness Name (Officer)','text','Officer Name']].map(([name,label,type,ph]) => ( {[['employeeName','Employee Name','text','John Doe'],['department','Department','text','Engineering'],['supervisor','Supervisor Name','text','Jane Smith'],['witnessName','Witness Name (Officer)','text','Officer Name']].map(([name,label,type,ph]) => (
<div key={name} style={s.item}> <div key={name} style={s.item}>
<label style={s.label}>{label}:</label> <label style={s.label}>{label}:</label>
<input style={s.input} type={type} name={name} value={form[name]} onChange={handleChange} placeholder={ph} /> <input style={s.input} type={type} name={name} value={form[name]} onChange={handleChange} placeholder={ph} />
</div> </div>
))} ))}
</div>
</div>
<form onSubmit={handleSubmit}>
<div style={s.section}>
<h2 style={s.sectionTitle}>Violation Details</h2>
<div style={s.grid}>
<div style={{ ...s.item, ...s.fullCol }}>
<label style={s.label}>Violation Type:</label>
<select style={s.input} value={form.violationType} onChange={handleViolationChange} required>
<option value="">-- Select Violation Type --</option>
{Object.entries(violationGroups).map(([group, items]) => (
<optgroup key={group} label={group}>
{items.map(v => {
const prior = priorCount90(v.key);
return (
<option key={v.key} value={v.key}>
{v.name}{prior > 0 ? `${prior}x in 90 days` : ''}
</option>
);
})}
</optgroup>
))}
</select>
{violation && (
<div style={s.contextBox}>
<strong>{violation.name}</strong>
{isRepeat(form.violationType) && form.employeeId && (
<span style={s.repeatBadge}>
Repeat {intel.countsAllTime[form.violationType]?.count}x prior
</span>
)}
<br />{violation.description}<br />
<span style={{ fontSize: '11px', color: '#a0a3ba' }}>{violation.chapter}</span>
</div> </div>
)}
{violation && isRepeat(form.violationType) && form.employeeId && violation.minPoints !== violation.maxPoints && (
<div style={s.repeatWarn}>
<strong>Repeat offense detected.</strong> Point slider set to maximum ({violation.maxPoints} pts) per recidivist policy. Adjust if needed.
</div>
)}
</div> </div>
{/* ── Violation Details ────────────────────────────────── */} <div style={s.item}>
<form onSubmit={handleSubmit}> <label style={s.label}>Incident Date:</label>
<div style={s.section}> <input style={s.input} type="date" name="incidentDate" value={form.incidentDate} onChange={handleChange} required />
<h2 style={s.sectionTitle}>Violation Details</h2> </div>
<div style={s.grid}>
<div style={{ ...s.item, ...s.fullCol }}> {showField('time') && (
<label style={s.label}>Violation Type:</label> <div style={s.item}>
<select style={s.input} value={form.violationType} onChange={handleViolationChange} required> <label style={s.label}>Incident Time:</label>
<option value="">-- Select Violation Type --</option> <input style={s.input} type="time" name="incidentTime" value={form.incidentTime} onChange={handleChange} />
{Object.entries(violationGroups).map(([group, items]) => ( </div>
<optgroup key={group} label={group}>
{items.map(v => {
const prior = priorCount90(v.key);
return (
<option key={v.key} value={v.key}>
{v.name}{prior > 0 ? `${prior}x in 90 days` : ''}
</option>
);
})}
</optgroup>
))}
</select>
{violation && (
<div style={s.contextBox}>
<strong>{violation.name}</strong>
{isRepeat(form.violationType) && form.employeeId && (
<span style={s.repeatBadge}>
Repeat {intel.countsAllTime[form.violationType]?.count}x prior
</span>
)}
<br />{violation.description}<br />
<span style={{ fontSize: '11px', color: '#666' }}>{violation.chapter}</span>
</div>
)}
{violation && isRepeat(form.violationType) && form.employeeId && violation.minPoints !== violation.maxPoints && (
<div style={s.repeatWarn}>
<strong>Repeat offense detected.</strong> Point slider set to maximum ({violation.maxPoints} pts) per recidivist policy. Adjust if needed.
</div>
)}
</div>
<div style={s.item}>
<label style={s.label}>Incident Date:</label>
<input style={s.input} type="date" name="incidentDate" value={form.incidentDate} onChange={handleChange} required />
</div>
{showField('time') && (
<div style={s.item}>
<label style={s.label}>Incident Time:</label>
<input style={s.input} type="time" name="incidentTime" value={form.incidentTime} onChange={handleChange} />
</div>
)}
{showField('minutes') && (
<div style={s.item}>
<label style={s.label}>Minutes Late:</label>
<input style={s.input} type="number" name="minutesLate" value={form.minutesLate} onChange={handleChange} placeholder="15" />
</div>
)}
{showField('amount') && (
<div style={s.item}>
<label style={s.label}>Amount / Value:</label>
<input style={s.input} type="text" name="amount" value={form.amount} onChange={handleChange} placeholder="$150.00" />
</div>
)}
{showField('location') && (
<div style={{ ...s.item, ...s.fullCol }}>
<label style={s.label}>Location / Context:</label>
<input style={s.input} type="text" name="location" value={form.location} onChange={handleChange} placeholder="Office, vehicle, facility area, etc." />
</div>
)}
{showField('description') && (
<div style={{ ...s.item, ...s.fullCol }}>
<label style={s.label}>Additional Details:</label>
<textarea style={{ ...s.input, resize: 'vertical', minHeight: '80px' }} name="additionalDetails" value={form.additionalDetails} onChange={handleChange} placeholder="Provide specific context, observations, or details..." />
</div>
)}
</div>
{intel.score && violation && (
<TierWarning
currentPoints={intel.score.active_points}
addingPoints={parseInt(form.points) || 0}
/>
)}
{violation && (
<div style={s.pointBox}>
<h4 style={{ color: '#856404', marginBottom: '10px' }}>CPAS Point Assessment</h4>
<p style={{ margin: 0 }}>
{violation.name}: {violation.minPoints === violation.maxPoints
? `${violation.minPoints} Points (Fixed)`
: `${violation.minPoints}${violation.maxPoints} Points`}
</p>
<input style={{ width: '100%', marginTop: '10px' }} type="range" name="points"
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>
</div>
)}
</div>
<div style={s.btnRow}>
<button type="submit" style={s.btnPrimary}>Submit Violation</button>
<button type="button" style={s.btnSecondary} onClick={() => { setForm(EMPTY_FORM); setViolation(null); setStatus(null); setLastViolId(null); }}>
Clear Form
</button>
</div>
{/* PDF download — appears after successful submission */}
{lastViolId && status?.ok && (
<div style={{ textAlign: 'center', marginTop: '16px' }}>
<button
type="button"
style={{ ...s.btnPdf, opacity: pdfLoading ? 0.7 : 1 }}
onClick={handleDownloadPdf}
disabled={pdfLoading}
>
{pdfLoading ? '⏳ Generating PDF...' : '⬇ Download PDF'}
</button>
<p style={{ fontSize: '11px', color: '#888', marginTop: '6px' }}>
Violation #{lastViolId} click to download the signed violation document
</p>
</div>
)}
{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>
<ViolationHistory history={intel.history} loading={intel.loading} />
</div>
)} )}
{showField('minutes') && (
<div style={s.item}>
<label style={s.label}>Minutes Late:</label>
<input style={s.input} type="number" name="minutesLate" value={form.minutesLate} onChange={handleChange} placeholder="15" />
</div>
)}
{showField('amount') && (
<div style={s.item}>
<label style={s.label}>Amount / Value:</label>
<input style={s.input} type="text" name="amount" value={form.amount} onChange={handleChange} placeholder="$150.00" />
</div>
)}
{showField('location') && (
<div style={{ ...s.item, ...s.fullCol }}>
<label style={s.label}>Location / Context:</label>
<input style={s.input} type="text" name="location" value={form.location} onChange={handleChange} placeholder="Office, vehicle, facility area, etc." />
</div>
)}
{showField('description') && (
<div style={{ ...s.item, ...s.fullCol }}>
<label style={s.label}>Additional Details:</label>
<textarea style={{ ...s.input, resize: 'vertical', minHeight: '80px' }} name="additionalDetails" value={form.additionalDetails} onChange={handleChange} placeholder="Provide specific context, observations, or details..." />
</div>
)}
</div>
{intel.score && violation && (
<TierWarning
currentPoints={intel.score.active_points}
addingPoints={parseInt(form.points) || 0}
/>
)}
{violation && (
<div style={s.pointBox}>
<h4 style={{ color: '#ffdf8a', marginBottom: '10px' }}>CPAS Point Assessment</h4>
<p style={{ margin: 0 }}>
{violation.name}: {violation.minPoints === violation.maxPoints
? `${violation.minPoints} Points (Fixed)`
: `${violation.minPoints}${violation.maxPoints} Points`}
</p>
<input style={{ width: '100%', marginTop: '10px' }} type="range" name="points"
min={violation.minPoints} max={violation.maxPoints}
value={form.points} onChange={handleChange} />
<div style={s.pointValue}>{form.points} Points</div>
<p style={{ fontSize: '12px', color: '#d1d3e0' }}>Adjust to reflect severity and context</p>
</div>
)}
</div> </div>
);
<div style={s.btnRow}>
<button type="submit" style={s.btnPrimary}>Submit Violation</button>
<button type="button" style={s.btnSecondary} onClick={() => { setForm(EMPTY_FORM); setViolation(null); setStatus(null); setLastViolId(null); }}>
Clear Form
</button>
</div>
{lastViolId && status?.ok && (
<div style={{ textAlign: 'center', marginTop: '16px' }}>
<button
type="button"
style={{ ...s.btnPdf, opacity: pdfLoading ? 0.7 : 1 }}
onClick={handleDownloadPdf}
disabled={pdfLoading}
>
{pdfLoading ? '⏳ Generating PDF...' : '⬇ Download PDF'}
</button>
<p style={{ fontSize: '11px', color: '#9ca0b8', marginTop: '6px' }}>
Violation #{lastViolId} click to download the signed violation document
</p>
</div>
)}
{status && <div style={status.ok ? s.statusOk : s.statusErr}>{status.msg}</div>}
</form>
{form.employeeId && (
<div style={s.section}>
<h2 style={s.sectionTitle}>Violation History</h2>
<ViolationHistory history={intel.history} loading={intel.loading} />
</div>
)}
</div>
);
} }

View File

@@ -2,19 +2,19 @@ import React, { useState } from 'react';
const s = { const s = {
wrapper: { marginTop: '24px' }, wrapper: { marginTop: '24px' },
title: { color: '#2c3e50', fontSize: '16px', fontWeight: 700, marginBottom: '10px' }, title: { color: '#b5b5c0', fontSize: '16px', fontWeight: 700, marginBottom: '10px' },
table: { width: '100%', borderCollapse: 'collapse', fontSize: '13px' }, table: { width: '100%', borderCollapse: 'collapse', fontSize: '13px', background: '#111217', borderRadius: '6px', overflow: 'hidden', border: '1px solid #222' },
th: { background: '#2c3e50', color: 'white', padding: '8px 10px', textAlign: 'left' }, 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 #dee2e6' }, td: { padding: '8px 10px', borderBottom: '1px solid #1c1d29', color: '#f8f9fa', verticalAlign: 'middle' },
trEven: { background: '#f8f9fa' }, trEven: { background: '#111217' },
trOdd: { background: 'white' }, trOdd: { background: '#151622' },
pts: { fontWeight: 700, color: '#667eea' }, pts: { fontWeight: 700, color: '#667eea' },
toggle: { background: 'none', border: 'none', color: '#667eea', cursor: 'pointer', fontSize: '13px', padding: 0, textDecoration: 'underline' }, 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) { function formatDate(d) {
if (!d) return ''; if (!d) return '';
const dt = new Date(d + 'T12:00:00'); const dt = new Date(d + 'T12:00:00');
return dt.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'America/Chicago' }); 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}> <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}>{formatDate(v.incident_date)}</td>
<td style={s.td}>{v.violation_name}</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, ...s.pts }}>{v.points}</td>
<td style={s.td}>{v.details || ''}</td> <td style={{ ...s.td, color: '#c0c2d6' }}>{v.details || ''}</td>
</tr> </tr>
))} ))}
</tbody> </tbody>

View File

@@ -13,27 +13,14 @@ db.pragma('foreign_keys = ON');
const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8'); const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8');
db.exec(schema); db.exec(schema);
// Migrate: add negated columns if upgrading from Phase 1-3 // ── Migrations for existing DBs ─────────────────────────────────────────────
const cols = db.prepare("PRAGMA table_info(violations)").all().map(c => c.name); 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')) 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('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");
// After adding columns + resolutions table, ensure view is correct // Ensure resolutions table exists
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;
`);
// Ensure resolutions table exists on upgrade
db.exec(`CREATE TABLE IF NOT EXISTS violation_resolutions ( db.exec(`CREATE TABLE IF NOT EXISTS violation_resolutions (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
violation_id INTEGER NOT NULL REFERENCES violations(id) ON DELETE CASCADE, violation_id INTEGER NOT NULL REFERENCES violations(id) ON DELETE CASCADE,
@@ -43,5 +30,17 @@ db.exec(`CREATE TABLE IF NOT EXISTS violation_resolutions (
created_at DATETIME DEFAULT CURRENT_TIMESTAMP 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); console.log('[DB] Connected:', dbPath);
module.exports = db; module.exports = db;

View File

@@ -7,21 +7,23 @@ CREATE TABLE IF NOT EXISTS employees (
); );
CREATE TABLE IF NOT EXISTS violations ( CREATE TABLE IF NOT EXISTS violations (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
employee_id INTEGER NOT NULL REFERENCES employees(id), employee_id INTEGER NOT NULL REFERENCES employees(id),
violation_type TEXT NOT NULL, violation_type TEXT NOT NULL,
violation_name TEXT NOT NULL, violation_name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'General', category TEXT NOT NULL DEFAULT 'General',
points INTEGER NOT NULL, points INTEGER NOT NULL,
incident_date TEXT NOT NULL, incident_date TEXT NOT NULL,
incident_time TEXT, incident_time TEXT,
location TEXT, location TEXT,
details TEXT, details TEXT,
submitted_by TEXT, submitted_by TEXT,
witness_name TEXT, witness_name TEXT,
negated INTEGER NOT NULL DEFAULT 0, negated INTEGER NOT NULL DEFAULT 0,
negated_at DATETIME, negated_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP prior_active_points INTEGER, -- snapshot at time of logging
prior_tier_label TEXT, -- optional human-readable tier
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
); );
CREATE TABLE IF NOT EXISTS violation_resolutions ( CREATE TABLE IF NOT EXISTS violation_resolutions (

View File

@@ -30,18 +30,12 @@ async function generatePdf(violation, score) {
format: 'Letter', format: 'Letter',
printBackground: true, printBackground: true,
margin: { margin: {
top: '0.6in', top: '0.35in',
bottom: '0.7in', bottom: '0.35in',
left: '0.75in', left: '0.4in',
right: '0.75in', right: '0.4in',
}, },
displayHeaderFooter: true, displayHeaderFooter: false,
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 &nbsp;|&nbsp;
Page <span class="pageNumber"></span> of <span class="totalPages"></span>
</div>`,
}); });
return pdf; return pdf;

File diff suppressed because one or more lines are too long

284
server.js
View File

@@ -11,170 +11,204 @@ app.use(cors());
app.use(express.json()); app.use(express.json());
app.use(express.static(path.join(__dirname, 'client', 'dist'))); app.use(express.static(path.join(__dirname, 'client', 'dist')));
// ── Health ────────────────────────────────────────────────────────────────── // Health
app.get('/api/health', (req, res) => res.json({ status: 'ok', timestamp: new Date().toISOString() })); app.get('/api/health', (req, res) => res.json({ status: 'ok', timestamp: new Date().toISOString() }));
// ── Employees ─────────────────────────────────────────────────────────────── // Employees
app.get('/api/employees', (req, res) => { 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 FROM employees ORDER BY name ASC').all();
res.json(rows); res.json(rows);
}); });
app.post('/api/employees', (req, res) => { app.post('/api/employees', (req, res) => {
const { name, department, supervisor } = req.body; const { name, department, supervisor } = req.body;
if (!name) return res.status(400).json({ error: 'name is required' }); if (!name) return res.status(400).json({ error: 'name is required' });
const existing = db.prepare('SELECT * FROM employees WHERE LOWER(name) = LOWER(?)').get(name); const existing = db.prepare('SELECT * FROM employees WHERE LOWER(name) = LOWER(?)').get(name);
if (existing) { if (existing) {
if (department || supervisor) if (department || supervisor) {
db.prepare('UPDATE employees SET department = COALESCE(?, department), supervisor = COALESCE(?, supervisor) WHERE id = ?') db.prepare('UPDATE employees SET department = COALESCE(?, department), supervisor = COALESCE(?, supervisor) WHERE id = ?')
.run(department || null, supervisor || null, existing.id); .run(department || null, supervisor || null, existing.id);
return res.json({ ...existing, department, supervisor });
} }
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)').run(name, department || null, supervisor || null); return res.json({ ...existing, department, supervisor });
res.status(201).json({ id: result.lastInsertRowid, name, department, supervisor }); }
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)')
.run(name, department || null, supervisor || null);
res.status(201).json({ id: result.lastInsertRowid, name, department, supervisor });
}); });
// ── Employee CPAS Score ───────────────────────────────────────────────────── // Employee score (current snapshot)
app.get('/api/employees/:id/score', (req, res) => { app.get('/api/employees/:id/score', (req, res) => {
const row = db.prepare('SELECT * FROM active_cpas_scores WHERE employee_id = ?').get(req.params.id); 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 }); res.json(row || { employee_id: req.params.id, active_points: 0, violation_count: 0 });
}); });
// ── Dashboard — all employees with scores ─────────────────────────────────── // Dashboard
app.get('/api/dashboard', (req, res) => { app.get('/api/dashboard', (req, res) => {
const rows = db.prepare(` const rows = db.prepare(`
SELECT SELECT e.id, e.name, e.department, e.supervisor,
e.id, e.name, e.department, e.supervisor, COALESCE(s.active_points, 0) AS active_points,
COALESCE(s.active_points, 0) AS active_points, COALESCE(s.violation_count,0) AS violation_count
COALESCE(s.violation_count,0) AS violation_count FROM employees e
FROM employees e LEFT JOIN active_cpas_scores s ON s.employee_id = e.id
LEFT JOIN active_cpas_scores s ON s.employee_id = e.id ORDER BY active_points DESC, e.name ASC
ORDER BY active_points DESC, e.name ASC `).all();
`).all(); res.json(rows);
res.json(rows);
}); });
// ── Violation counts (90-day) ─────────────────────────────────────────────── // Violation history (per employee) with resolutions
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) ───────────────────────────────────────
app.get('/api/violations/employee/:id', (req, res) => { app.get('/api/violations/employee/:id', (req, res) => {
const limit = parseInt(req.query.limit) || 50; const limit = parseInt(req.query.limit) || 50;
const rows = db.prepare(` const rows = db.prepare(`
SELECT v.*, r.resolution_type, r.details AS resolution_details, 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
FROM violations v FROM violations v
LEFT JOIN violation_resolutions r ON r.violation_id = v.id LEFT JOIN violation_resolutions r ON r.violation_id = v.id
WHERE v.employee_id = ? WHERE v.employee_id = ?
ORDER BY v.incident_date DESC, v.created_at DESC ORDER BY v.incident_date DESC, v.created_at DESC
LIMIT ? LIMIT ?
`).all(req.params.id, limit); `).all(req.params.id, limit);
res.json(rows); res.json(rows);
}); });
// ── POST new violation ────────────────────────────────────────────────────── // 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) => { app.post('/api/violations', (req, res) => {
const { const {
employee_id, violation_type, violation_name, category, employee_id, violation_type, violation_name, category,
points, incident_date, incident_time, location, points, incident_date, incident_time, location,
details, submitted_by, witness_name details, submitted_by, witness_name
} = req.body; } = req.body;
if (!employee_id || !violation_type || !points || !incident_date)
return res.status(400).json({ error: 'Missing required fields' });
const result = db.prepare(` if (!employee_id || !violation_type || !points || !incident_date) {
INSERT INTO violations (employee_id, violation_type, violation_name, category, return res.status(400).json({ error: 'Missing required fields' });
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,
incident_time || null, location || null,
details || null, submitted_by || null, witness_name || null);
res.status(201).json({ id: result.lastInsertRowid }); 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,
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,
priorPts
);
res.status(201).json({ id: result.lastInsertRowid });
}); });
// ── PATCH — Soft Negate (add resolution) ─────────────────────────────────── // ── Negate a violation ──────────────────────────────────────────────────────
app.patch('/api/violations/:id/negate', (req, res) => { app.patch('/api/violations/:id/negate', (req, res) => {
const { resolution_type, details, resolved_by } = req.body; 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' }); 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); // Mark negated
db.prepare('UPDATE violations SET negated = 1 WHERE id = ?').run(id);
// Upsert resolution record
const existing = db.prepare('SELECT id FROM violation_resolutions WHERE violation_id = ?').get(id);
if (existing) {
db.prepare(` db.prepare(`
INSERT INTO violation_resolutions (violation_id, resolution_type, details, resolved_by) UPDATE violation_resolutions
VALUES (?, ?, ?, ?) SET resolution_type = ?, details = ?, resolved_by = ?, created_at = datetime('now')
`).run(req.params.id, resolution_type, details || null, resolved_by || null); 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(id, resolution_type || 'Resolved', details || null, resolved_by || null);
}
res.json({ success: true }); res.json({ success: true });
}); });
// ── PATCH — Restore negated violation ────────────────────────────────────── // ── Restore a negated violation ─────────────────────────────────────────────
app.patch('/api/violations/:id/restore', (req, res) => { 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;
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); const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(req.params.id); if (!violation) return res.status(404).json({ error: 'Violation not found' });
res.json({ success: true });
db.prepare('UPDATE violations SET negated = 0 WHERE id = ?').run(id);
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(id);
res.json({ success: true });
}); });
// ── DELETE — Hard Delete ──────────────────────────────────────────────────── // ── Hard delete a violation ─────────────────────────────────────────────────
app.delete('/api/violations/:id', (req, res) => { 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;
if (!violation) return res.status(404).json({ error: 'Violation not found' });
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(req.params.id); const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
db.prepare('DELETE FROM violations WHERE id = ?').run(req.params.id); if (!violation) return res.status(404).json({ error: 'Violation not found' });
res.json({ success: true });
// Delete resolution first (FK safety)
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(id);
db.prepare('DELETE FROM violations WHERE id = ?').run(id);
res.json({ success: true });
}); });
// ── PDF ───────────────────────────────────────────────────────────────────── // ── PDF endpoint ─────────────────────────────────────────────────────────────
app.get('/api/violations/:id/pdf', async (req, res) => { app.get('/api/violations/:id/pdf', async (req, res) => {
try { try {
const violation = db.prepare(` const violation = db.prepare(`
SELECT v.*, e.name as employee_name, e.department, e.supervisor 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
WHERE v.id = ? JOIN employees e ON e.id = v.employee_id
`).get(req.params.id); WHERE v.id = ?
if (!violation) return res.status(404).json({ error: 'Violation not found' }); `).get(req.params.id);
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); if (!violation) return res.status(404).json({ error: 'Violation not found' });
const safeName = violation.employee_name.replace(/[^a-z0-9]/gi, '_');
res.set({ const active = db.prepare('SELECT * FROM active_cpas_scores WHERE employee_id = ?')
'Content-Type': 'application/pdf', .get(violation.employee_id) || { active_points: 0, violation_count: 0 };
'Content-Disposition': `attachment; filename="CPAS_${safeName}_${violation.incident_date}.pdf"`,
'Content-Length': pdfBuffer.length, const scoreForPdf = {
}); employee_id: violation.employee_id,
res.end(pdfBuffer); active_points: violation.prior_active_points != null ? violation.prior_active_points : active.active_points,
} catch (err) { violation_count: active.violation_count,
console.error('[PDF]', err); };
res.status(500).json({ error: 'PDF generation failed', detail: err.message });
} 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"`,
'Content-Length': pdfBuffer.length,
});
res.end(pdfBuffer);
} catch (err) {
console.error('[PDF]', err);
res.status(500).json({ error: 'PDF generation failed', detail: err.message });
}
}); });
// ── SPA fallback ──────────────────────────────────────────────────────────── // SPA fallback
app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'client', 'dist', 'index.html'))); 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}`)); app.listen(PORT, '0.0.0.0', () => console.log(`[CPAS] Server running on port ${PORT}`));