5 Commits

Author SHA1 Message Date
jason ba2b631e23 documentation
Build and Push Docker Image / build (push) Successful in 6s
2026-05-11 13:28:02 -05:00
jason 3220ee70c4 financial data entry
Build and Push Docker Image / build (push) Successful in 1m4s
2026-05-11 12:04:34 -05:00
jason 5a2b581c71 Add .gitea/workflows/docker-build.yml 2026-05-11 11:48:51 -05:00
jason 3a0934bdc6 Merge pull request 'feat: custom violation types — persist, manage, and use in violation form' (#46) from claude/musing-bell into master
Reviewed-on: #46
2026-03-18 16:25:53 -05:00
jason 95d56b5018 feat: custom violation types — persist, manage, and use in violation form
Adds a full CRUD system for user-defined violation types stored in a new
violation_types table. Custom types appear in the violation dropdown alongside
hardcoded types, grouped by category, with ✦ marker and a green Custom badge.

- db/database.js: auto-migration adds violation_types table on startup
- server.js: GET/POST/PUT/DELETE /api/violation-types; type_key auto-generated
  as custom_<slug>; DELETE blocked if any violations reference the type
- ViolationTypeModal.jsx: create/edit modal with name, category (datalist
  autocomplete from existing categories), handbook chapter reference,
  description/reference text, fixed vs sliding point toggle, context field
  checkboxes; delete with usage guard
- ViolationForm.jsx: fetches custom types on mount; merges into dropdown via
  mergedGroups memo; resolveViolation() checks hardcoded then custom; '+ Add
  Type' button above dropdown; 'Edit Type' button appears when a custom type is
  selected; newly created type auto-selects; all audit calls flow through
  existing audit() helper

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-18 16:23:21 -05:00
10 changed files with 612 additions and 35 deletions
+25
View File
@@ -0,0 +1,25 @@
name: Build and Push Docker Image
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
container:
image: catthehacker/ubuntu:act-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Log in to Gitea Container Registry
uses: docker/login-action@v3
with:
registry: registry.alwisp.com
username: ${{ secrets.REGISTRY_USER }}
password: ${{ secrets.REGISTRY_TOKEN }}
- name: Build and Push
run: |
docker build -t registry.alwisp.com/${{ gitea.repository_owner }}/${{ gitea.repository }}:latest .
docker push registry.alwisp.com/${{ gitea.repository_owner }}/${{ gitea.repository }}:latest
+1 -1
View File
@@ -82,7 +82,7 @@ The following fields on `violations` are locked after submission. They are the b
- `prior_active_points` (snapshot at insert time)
- `prior_tier_label`
Amendable fields (non-scoring): `location`, `details`, `witness_name`, `acknowledged_by`, `acknowledged_date`
Amendable fields (non-scoring): `incident_time`, `location`, `details`, `submitted_by`, `witness_name`, `acknowledged_by`, `acknowledged_date`, `amount`
### Soft-Delete Pattern
+27 -10
View File
@@ -130,7 +130,6 @@ Useful for showing the app to stakeholders without exposing live employee data.
- Summary stat cards: total employees, elite standing (0 pts), with active points, at-risk count, highest active score
- **At-risk badge**: flags employees within 2 points of the next tier escalation
- Search/filter by name, department, or supervisor
- **Department filter**: pre-loaded dropdown of all departments for quick scoped views
- Click any employee name to open their full profile modal
- **📋 Audit Log** button — filterable, paginated view of all system write actions
@@ -138,9 +137,11 @@ Useful for showing the app to stakeholders without exposing live employee data.
- Select existing employee or enter new employee by name
- **Employee intelligence**: shows current CPAS standing badge and 90-day violation count before submitting
- Violation type dropdown grouped by category; shows prior 90-day counts inline
- **Custom violation types**: add or edit user-defined types directly from the form (`+ Add Type` / `Edit Type` buttons); persisted to the database and merged into the dropdown alongside hardcoded types
- **Recidivist auto-escalation**: if an employee has prior violations of the same type, points slider auto-sets to maximum per policy
- Repeat offense badge with prior count displayed
- Context-sensitive fields (time, minutes late, amount, location, description) shown only when relevant to violation type
- **Financial amount tracking**: dollar amount in question recorded for chargeback / receipt / custom financial violations; surfaces on the PDF for repayment records and is audit-logged on edit
- **Tier crossing warning** (TierWarning component): previews what tier the new points would push the employee into before submission
- Point slider for discretionary adjustments within the violation's min/max range
- **Employee Acknowledgment section**: optional "received by employee" name and date fields; when filled, the PDF signature block shows the recorded acknowledgment instead of a blank signature line
@@ -214,23 +215,30 @@ Scores are computed over a **rolling 90-day window** (negated violations exclude
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/health` | Health check |
| GET | `/api/health` | Health check (returns build SHA + timestamp) |
| GET | `/api/employees` | List all employees (includes `notes`) |
| GET | `/api/employees/:id` | Single employee record |
| POST | `/api/employees` | Create or upsert employee |
| PATCH | `/api/employees/:id` | Edit name, department, supervisor, or notes |
| PATCH | `/api/employees/:id/notes` | Save employee notes only (shorthand) |
| POST | `/api/employees/:id/merge` | Merge duplicate employee; reassigns all violations |
| GET | `/api/employees/:id/score` | Get active CPAS score for employee |
| GET | `/api/employees/:id/expiration` | Active violation roll-off timeline with days remaining |
| PATCH | `/api/employees/:id/notes` | Save employee notes only (shorthand) |
| GET | `/api/employees/:id/violation-counts` | 90-day non-negated counts grouped by violation type |
| GET | `/api/employees/:id/violation-counts/alltime` | All-time non-negated counts + max points used per type |
| GET | `/api/dashboard` | All employees with active points + violation counts |
| POST | `/api/violations` | Log a new violation (accepts `acknowledged_by`, `acknowledged_date`) |
| POST | `/api/violations` | Log a new violation (accepts `acknowledged_by`, `acknowledged_date`, `amount`) |
| GET | `/api/violations/employee/:id` | Violation history with resolutions + amendment counts |
| PATCH | `/api/violations/:id/negated` | Negate a violation (soft delete + resolution record) |
| PATCH | `/api/violations/:id/negate` | Negate a violation (soft delete + resolution record) |
| PATCH | `/api/violations/:id/restore` | Restore a negated violation |
| PATCH | `/api/violations/:id/amend` | Amend non-scoring fields with field-level diff logging |
| GET | `/api/violations/:id/amendments` | Get amendment history for a violation |
| DELETE | `/api/violations/:id` | Hard delete a violation |
| GET | `/api/violations/:id/pdf` | Download violation PDF |
| GET | `/api/violation-types` | List custom violation types |
| POST | `/api/violation-types` | Create a custom violation type |
| PUT | `/api/violation-types/:id` | Update a custom violation type |
| DELETE | `/api/violation-types/:id` | Delete a custom violation type (blocked if any violation references it) |
| GET | `/api/audit` | Paginated audit log (filterable by `entity_type`, `entity_id`) |
---
@@ -258,14 +266,19 @@ cpas/
├── main.jsx
├── App.jsx # Root app + AppFooter (copyright, dev ticker, Gitea link)
├── data/
── violations.js # All CPAS violation definitions + groups
── violations.js # All hardcoded CPAS violation definitions + groups
│ └── departments.js # DEPARTMENTS constant; single source of truth
├── hooks/
│ └── useEmployeeIntelligence.js # Score + history hook
├── styles/
│ └── mobile.css # Mobile breakpoint overrides only
└── components/
├── CpasBadge.jsx # Tier badge + color logic
├── CpasBadge.jsx # Tier badge + color logic (canonical TIERS, getTier)
├── TierWarning.jsx # Pre-submit tier crossing alert
├── Dashboard.jsx # Company-wide leaderboard + audit log trigger
├── ViolationForm.jsx # Violation entry form + ack signature fields
├── DashboardMobile.jsx # Mobile-optimized dashboard layout
├── ViolationForm.jsx # Violation entry form + ack signature + amount field
├── ViolationTypeModal.jsx # Create / edit / delete custom violation types
├── EmployeeModal.jsx # Employee profile + history modal
├── EditEmployeeModal.jsx # Employee edit + merge duplicate
├── AmendViolationModal.jsx # Non-scoring field amendment + diff history
@@ -284,10 +297,11 @@ cpas/
Six tables + one view:
- **`employees`** — id, name, department, supervisor, **notes**
- **`violations`** — full incident record including `prior_active_points` snapshot at time of logging, `acknowledged_by` and `acknowledged_date` for employee acknowledgment
- **`employees`** — id, name, department, supervisor, notes
- **`violations`** — full incident record including `prior_active_points` snapshot, `acknowledged_by` / `acknowledged_date`, and `amount` (financial amount in question for chargeback/repayment)
- **`violation_resolutions`** — resolution type, details, resolved_by (linked to violations)
- **`violation_amendments`** — field-level diff log for violation edits; one row per changed field per amendment
- **`violation_types`** — persisted custom violation type definitions added via the UI; `type_key` is prefixed `custom_` to prevent collisions with hardcoded keys
- **`audit_log`** — append-only record of every write action (action, entity_type, entity_id, performed_by, details, timestamp)
- **`active_cpas_scores`** (view) — sum of points for non-negated violations in rolling 90 days, grouped by employee
@@ -306,6 +320,7 @@ Point values, violation type, and incident date are **immutable** after submissi
| `witness_name` | Witness on record |
| `acknowledged_by` | Employee who acknowledged receipt |
| `acknowledged_date` | Date of employee acknowledgment |
| `amount` | Dollar amount in question (financial violations); typo-correctable for repayment records |
---
@@ -339,6 +354,8 @@ Point values, violation type, and incident date are **immutable** after submissi
| 7 | Department dropdown | Pre-loaded select on the violation form replacing free-text department input; shared `DEPARTMENTS` constant |
| 8 | Stakeholder demo page | Standalone `/demo` route with synthetic data; static HTML served before SPA catch-all; useful for non-live presentations |
| 8 | App footer | Copyright (© Jason Stedwell), live dev ticker since first commit, Gitea repo icon+link |
| 9 | Custom violation types | Persisted user-defined violation types created from the form; `+ Add Type` / `Edit Type` UI; merged into the dropdown alongside hardcoded types; delete blocked when in use |
| 9 | Financial amount tracking | `amount` field on financial violations (chargeback, receipt negligence, custom types with the field enabled); stored on `violations`, rendered prominently on the PDF, amendable with audit-logged diffs |
---
@@ -7,6 +7,7 @@ const FIELD_LABELS = {
details: 'Incident Notes',
submitted_by: 'Submitted By',
witness_name: 'Witness / Documenting Officer',
amount: 'Amount in Question',
};
const s = {
@@ -84,6 +85,7 @@ export default function AmendViolationModal({ violation, onClose, onSaved }) {
details: violation.details || '',
submitted_by: violation.submitted_by || '',
witness_name: violation.witness_name || '',
amount: violation.amount || '',
});
const [changedBy, setChangedBy] = useState('');
const [saving, setSaving] = useState(false);
+125 -6
View File
@@ -1,10 +1,11 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useMemo } from 'react';
import axios from 'axios';
import { violationData, violationGroups } from '../data/violations';
import useEmployeeIntelligence from '../hooks/useEmployeeIntelligence';
import CpasBadge from './CpasBadge';
import TierWarning from './TierWarning';
import ViolationHistory from './ViolationHistory';
import ViolationTypeModal from './ViolationTypeModal';
import { useToast } from './ToastProvider';
import { DEPARTMENTS } from '../data/departments';
@@ -35,7 +36,6 @@ const s = {
const EMPTY_FORM = {
employeeId: '', employeeName: '', department: '', supervisor: '', witnessName: '',
violationType: '', incidentDate: '', incidentTime: '',
// TODO [MAJOR #6]: `amount` and `minutesLate` are rendered but never sent to the API
amount: '', minutesLate: '', location: '', additionalDetails: '', points: 1,
acknowledgedBy: '', acknowledgedDate: '',
};
@@ -47,14 +47,72 @@ export default function ViolationForm() {
const [status, setStatus] = useState(null); // TODO [MAJOR #7]: remove — toast covers this
const [lastViolId, setLastViolId] = useState(null);
const [pdfLoading, setPdfLoading] = useState(false);
const [customTypes, setCustomTypes] = useState([]);
const [typeModal, setTypeModal] = useState(null); // null | 'create' | <editing object>
const toast = useToast();
const intel = useEmployeeIntelligence(form.employeeId || null);
useEffect(() => {
axios.get('/api/employees').then(r => setEmployees(r.data)).catch(() => {});
fetchCustomTypes();
}, []);
const fetchCustomTypes = () => {
axios.get('/api/violation-types').then(r => setCustomTypes(r.data)).catch(() => {});
};
// Build a map of custom types keyed by type_key for fast lookup
const customTypeMap = useMemo(() =>
Object.fromEntries(customTypes.map(t => [t.type_key, t])),
[customTypes]
);
// Merge hardcoded and custom violation groups for the dropdown
const mergedGroups = useMemo(() => {
const groups = {};
// Start with all hardcoded groups
Object.entries(violationGroups).forEach(([cat, items]) => {
groups[cat] = [...items];
});
// Add custom types into their respective category, or create new group
customTypes.forEach(t => {
const item = {
key: t.type_key,
name: t.name,
category: t.category,
minPoints: t.min_points,
maxPoints: t.max_points,
chapter: t.chapter || '',
description: t.description || '',
fields: t.fields,
isCustom: true,
customId: t.id,
};
if (!groups[t.category]) groups[t.category] = [];
groups[t.category].push(item);
});
return groups;
}, [customTypes]);
// Resolve a violation definition from either the hardcoded registry or custom types
const resolveViolation = key => {
if (violationData[key]) return violationData[key];
const ct = customTypeMap[key];
if (ct) return {
name: ct.name,
category: ct.category,
chapter: ct.chapter || '',
description: ct.description || '',
minPoints: ct.min_points,
maxPoints: ct.max_points,
fields: ct.fields,
isCustom: true,
customId: ct.id,
};
return null;
};
useEffect(() => {
if (!violation || !form.violationType) return;
const allTime = intel.countsAllTime[form.violationType];
@@ -73,7 +131,7 @@ export default function ViolationForm() {
const handleViolationChange = e => {
const key = e.target.value;
const v = violationData[key] || null;
const v = resolveViolation(key);
setViolation(v);
setForm(prev => ({ ...prev, violationType: key, points: v ? v.minPoints : 1 }));
};
@@ -100,6 +158,7 @@ export default function ViolationForm() {
witness_name: form.witnessName || null,
acknowledged_by: form.acknowledgedBy || null,
acknowledged_date: form.acknowledgedDate || null,
amount: form.amount || null,
});
const newId = violRes.data.id;
@@ -198,16 +257,37 @@ export default function ViolationForm() {
<div style={s.grid}>
<div style={{ ...s.item, ...s.fullCol }}>
<label style={s.label}>Violation Type:</label>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '5px' }}>
<label style={{ ...s.label, marginBottom: 0 }}>Violation Type:</label>
<div style={{ display: 'flex', gap: '6px' }}>
{violation?.isCustom && (
<button
type="button"
onClick={() => setTypeModal(customTypeMap[form.violationType])}
style={{ fontSize: '11px', padding: '3px 10px', borderRadius: '4px', border: '1px solid #4caf50', background: '#1a2e1a', color: '#4caf50', cursor: 'pointer', fontWeight: 600 }}
>
Edit Type
</button>
)}
<button
type="button"
onClick={() => setTypeModal('create')}
style={{ fontSize: '11px', padding: '3px 10px', borderRadius: '4px', border: '1px solid #d4af37', background: '#181200', color: '#ffd666', cursor: 'pointer', fontWeight: 600 }}
title="Add a new custom violation type"
>
+ Add Type
</button>
</div>
</div>
<select style={s.input} value={form.violationType} onChange={handleViolationChange} required>
<option value="">-- Select Violation Type --</option>
{Object.entries(violationGroups).map(([group, items]) => (
{Object.entries(mergedGroups).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` : ''}
{v.name}{v.isCustom ? ' ✦' : ''}{prior > 0 ? `${prior}x in 90 days` : ''}
</option>
);
})}
@@ -218,6 +298,11 @@ export default function ViolationForm() {
{violation && (
<div style={s.contextBox}>
<strong>{violation.name}</strong>
{violation.isCustom && (
<span style={{ display: 'inline-block', marginLeft: '8px', padding: '1px 7px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#1a2e1a', color: '#4caf50', border: '1px solid #4caf50' }}>
Custom
</span>
)}
{isRepeat(form.violationType) && form.employeeId && (
<span style={s.repeatBadge}>
Repeat {intel.countsAllTime[form.violationType]?.count}x prior
@@ -350,6 +435,40 @@ export default function ViolationForm() {
</div>
)}
{typeModal && (
<ViolationTypeModal
editing={typeModal === 'create' ? null : typeModal}
onClose={() => setTypeModal(null)}
onSaved={saved => {
fetchCustomTypes();
setTypeModal(null);
// Auto-select the newly created type; do nothing on delete (saved === null)
if (saved) {
const v = {
name: saved.name,
category: saved.category,
chapter: saved.chapter || '',
description: saved.description || '',
minPoints: saved.min_points,
maxPoints: saved.max_points,
fields: saved.fields,
isCustom: true,
customId: saved.id,
};
setViolation(v);
setForm(prev => ({ ...prev, violationType: saved.type_key, points: saved.min_points }));
} else {
// Type was deleted — clear selection if it was the active type
setForm(prev => {
const stillExists = violationData[prev.violationType] || false;
return stillExists ? prev : { ...prev, violationType: '', points: 1 };
});
setViolation(null);
}
}}
/>
)}
</div>
);
}
@@ -0,0 +1,292 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useToast } from './ToastProvider';
// Existing hardcoded categories — used for datalist autocomplete
const KNOWN_CATEGORIES = [
'Attendance & Punctuality',
'Administrative Integrity',
'Financial Stewardship',
'Operational Response',
'Professional Conduct',
'Work From Home',
'Safety & Security',
];
const CONTEXT_FIELDS = [
{ key: 'time', label: 'Incident Time' },
{ key: 'minutes', label: 'Minutes Late' },
{ key: 'amount', label: 'Amount / Value' },
{ key: 'location', label: 'Location / Context' },
{ key: 'description', label: 'Additional Details' },
];
const s = {
overlay: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' },
modal: { background: '#111217', border: '1px solid #2a2b3a', borderRadius: '10px', width: '100%', maxWidth: '620px', maxHeight: '90vh', overflowY: 'auto', padding: '32px' },
title: { color: '#f8f9fa', fontSize: '20px', fontWeight: 700, marginBottom: '24px', borderBottom: '1px solid #2a2b3a', paddingBottom: '12px' },
label: { fontWeight: 600, color: '#e5e7f1', marginBottom: '5px', fontSize: '13px', display: 'block' },
input: { width: '100%', padding: '10px', border: '1px solid #333544', borderRadius: '4px', fontSize: '14px', fontFamily: 'inherit', background: '#050608', color: '#f8f9fa', boxSizing: 'border-box' },
textarea: { width: '100%', padding: '10px', border: '1px solid #333544', borderRadius: '4px', fontSize: '13px', fontFamily: 'inherit', background: '#050608', color: '#f8f9fa', resize: 'vertical', minHeight: '80px', boxSizing: 'border-box' },
group: { marginBottom: '18px' },
hint: { fontSize: '11px', color: '#9ca0b8', marginTop: '4px', fontStyle: 'italic' },
row: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' },
toggle: { display: 'flex', gap: '8px', marginTop: '6px' },
toggleBtn: (active) => ({
padding: '7px 18px', borderRadius: '4px', fontSize: '13px', fontWeight: 600, cursor: 'pointer', border: '1px solid',
background: active ? '#d4af37' : '#050608',
color: active ? '#000' : '#9ca0b8',
borderColor: active ? '#d4af37' : '#333544',
}),
fieldGrid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginTop: '8px' },
checkbox: { display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', color: '#d1d3e0', cursor: 'pointer' },
btnRow: { display: 'flex', gap: '12px', justifyContent: 'flex-end', marginTop: '28px', paddingTop: '16px', borderTop: '1px solid #2a2b3a' },
btnSave: { padding: '10px 28px', fontSize: '14px', fontWeight: 600, border: 'none', borderRadius: '6px', cursor: 'pointer', background: 'linear-gradient(135deg, #d4af37 0%, #ffdf8a 100%)', color: '#000' },
btnDanger: { padding: '10px 18px', fontSize: '14px', fontWeight: 600, border: '1px solid #721c24', borderRadius: '6px', cursor: 'pointer', background: '#3c1114', color: '#ffb3b8' },
btnCancel: { padding: '10px 18px', fontSize: '14px', fontWeight: 600, border: '1px solid #333544', borderRadius: '6px', cursor: 'pointer', background: '#050608', color: '#f8f9fa' },
section: { background: '#181924', border: '1px solid #2a2b3a', borderRadius: '6px', padding: '16px', marginBottom: '18px' },
secTitle: { color: '#d4af37', fontSize: '13px', fontWeight: 700, marginBottom: '12px', textTransform: 'uppercase', letterSpacing: '0.05em' },
customBadge: { display: 'inline-block', marginLeft: '8px', padding: '1px 7px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#1a2e1a', color: '#4caf50', border: '1px solid #4caf50', verticalAlign: 'middle' },
};
const EMPTY = {
name: '', category: '', chapter: '', description: '',
pointType: 'fixed', // 'fixed' | 'sliding'
fixedPoints: 1,
minPoints: 1,
maxPoints: 5,
fields: ['description'],
};
export default function ViolationTypeModal({ onClose, onSaved, editing = null }) {
const [form, setForm] = useState(EMPTY);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState(false);
const toast = useToast();
// Populate form when editing an existing type
useEffect(() => {
if (editing) {
const isSliding = editing.min_points !== editing.max_points;
setForm({
name: editing.name,
category: editing.category,
chapter: editing.chapter || '',
description: editing.description || '',
pointType: isSliding ? 'sliding' : 'fixed',
fixedPoints: isSliding ? editing.min_points : editing.min_points,
minPoints: editing.min_points,
maxPoints: editing.max_points,
fields: editing.fields || ['description'],
});
}
}, [editing]);
const set = (key, val) => setForm(prev => ({ ...prev, [key]: val }));
const toggleField = key => {
setForm(prev => ({
...prev,
fields: prev.fields.includes(key)
? prev.fields.filter(f => f !== key)
: [...prev.fields, key],
}));
};
const handleSave = async () => {
if (!form.name.trim()) { toast.warning('Violation name is required.'); return; }
if (!form.category.trim()) { toast.warning('Category is required.'); return; }
const minPts = form.pointType === 'fixed' ? parseInt(form.fixedPoints) || 1 : parseInt(form.minPoints) || 1;
const maxPts = form.pointType === 'fixed' ? minPts : parseInt(form.maxPoints) || 1;
if (maxPts < minPts) { toast.warning('Max points must be >= min points.'); return; }
if (form.fields.length === 0) { toast.warning('Select at least one context field.'); return; }
const payload = {
name: form.name.trim(),
category: form.category.trim(),
chapter: form.chapter.trim() || null,
description: form.description.trim() || null,
min_points: minPts,
max_points: maxPts,
fields: form.fields,
};
setSaving(true);
try {
let saved;
if (editing) {
const res = await axios.put(`/api/violation-types/${editing.id}`, payload);
saved = res.data;
toast.success(`"${saved.name}" updated.`);
} else {
const res = await axios.post('/api/violation-types', payload);
saved = res.data;
toast.success(`"${saved.name}" added to violation types.`);
}
onSaved(saved);
} catch (err) {
toast.error(err.response?.data?.error || err.message);
} finally {
setSaving(false);
}
};
const handleDelete = async () => {
if (!editing) return;
if (!window.confirm(`Delete "${editing.name}"? This cannot be undone and will fail if any violations reference this type.`)) return;
setDeleting(true);
try {
await axios.delete(`/api/violation-types/${editing.id}`);
toast.success(`"${editing.name}" deleted.`);
onSaved(null); // null signals a deletion to the parent
} catch (err) {
toast.error(err.response?.data?.error || err.message);
} finally {
setDeleting(false);
}
};
return (
<div style={s.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
<div style={s.modal}>
<div style={s.title}>
{editing ? 'Edit Violation Type' : 'Add Violation Type'}
{editing && <span style={s.customBadge}>CUSTOM</span>}
</div>
{/* Basic Info */}
<div style={s.section}>
<div style={s.secTitle}>Violation Definition</div>
<div style={s.group}>
<label style={s.label}>Violation Name *</label>
<input
style={s.input}
type="text"
value={form.name}
onChange={e => set('name', e.target.value)}
placeholder="e.g. Unauthorized System Access"
/>
</div>
<div style={s.group}>
<label style={s.label}>Category *</label>
<input
style={s.input}
type="text"
list="vt-categories"
value={form.category}
onChange={e => set('category', e.target.value)}
placeholder="Select existing or type new category"
/>
<datalist id="vt-categories">
{KNOWN_CATEGORIES.map(c => <option key={c} value={c} />)}
</datalist>
<div style={s.hint}>Choose an existing category or type a new one to create a new group in the dropdown.</div>
</div>
<div style={s.group}>
<label style={s.label}>Handbook Reference / Chapter</label>
<input
style={s.input}
type="text"
value={form.chapter}
onChange={e => set('chapter', e.target.value)}
placeholder="e.g. Chapter 4, Section 6"
/>
</div>
<div style={s.group}>
<label style={s.label}>Description / Reference Text</label>
<textarea
style={s.textarea}
value={form.description}
onChange={e => set('description', e.target.value)}
placeholder="Paste the relevant handbook language or describe the infraction in plain terms..."
/>
<div style={s.hint}>Shown in the context box on the violation form and printed on the PDF.</div>
</div>
</div>
{/* Point Assignment */}
<div style={s.section}>
<div style={s.secTitle}>Point Assignment</div>
<label style={s.label}>Point Type</label>
<div style={s.toggle}>
<button type="button" style={s.toggleBtn(form.pointType === 'fixed')} onClick={() => set('pointType', 'fixed')}>Fixed</button>
<button type="button" style={s.toggleBtn(form.pointType === 'sliding')} onClick={() => set('pointType', 'sliding')}>Sliding Range</button>
</div>
<div style={{ ...s.hint, marginTop: '6px' }}>
Fixed = exact value every time. Sliding = supervisor adjusts within a min/max range.
</div>
{form.pointType === 'fixed' ? (
<div style={{ ...s.group, marginTop: '14px' }}>
<label style={s.label}>Points (Fixed)</label>
<input
style={{ ...s.input, width: '120px' }}
type="number" min="1" max="30"
value={form.fixedPoints}
onChange={e => set('fixedPoints', e.target.value)}
/>
</div>
) : (
<div style={{ ...s.row, marginTop: '14px' }}>
<div style={s.group}>
<label style={s.label}>Min Points</label>
<input
style={s.input}
type="number" min="1" max="30"
value={form.minPoints}
onChange={e => set('minPoints', e.target.value)}
/>
</div>
<div style={s.group}>
<label style={s.label}>Max Points</label>
<input
style={s.input}
type="number" min="1" max="30"
value={form.maxPoints}
onChange={e => set('maxPoints', e.target.value)}
/>
</div>
</div>
)}
</div>
{/* Context Fields */}
<div style={s.section}>
<div style={s.secTitle}>Context Fields</div>
<div style={s.hint}>Select which additional fields appear on the violation form for this type.</div>
<div style={s.fieldGrid}>
{CONTEXT_FIELDS.map(({ key, label }) => (
<label key={key} style={s.checkbox}>
<input
type="checkbox"
checked={form.fields.includes(key)}
onChange={() => toggleField(key)}
/>
{label}
</label>
))}
</div>
</div>
<div style={s.btnRow}>
{editing && (
<button type="button" style={s.btnDanger} onClick={handleDelete} disabled={deleting}>
{deleting ? 'Deleting…' : 'Delete Type'}
</button>
)}
<button type="button" style={s.btnCancel} onClick={onClose}>Cancel</button>
<button type="button" style={s.btnSave} onClick={handleSave} disabled={saving}>
{saving ? 'Saving…' : editing ? 'Save Changes' : 'Add Violation Type'}
</button>
</div>
</div>
</div>
);
}
+19
View File
@@ -21,6 +21,8 @@ if (!cols.includes('prior_active_points')) db.exec("ALTER TABLE violations ADD C
if (!cols.includes('prior_tier_label')) db.exec("ALTER TABLE violations ADD COLUMN prior_tier_label TEXT");
if (!cols.includes('acknowledged_by')) db.exec("ALTER TABLE violations ADD COLUMN acknowledged_by TEXT");
if (!cols.includes('acknowledged_date')) db.exec("ALTER TABLE violations ADD COLUMN acknowledged_date TEXT");
// Financial amount in question (record-keeping / repayment for chargeback, receipt negligence, etc.)
if (!cols.includes('amount')) db.exec("ALTER TABLE violations ADD COLUMN amount TEXT");
// Employee notes column (free-text, does not affect scoring)
const empCols = db.prepare('PRAGMA table_info(employees)').all().map(c => c.name);
@@ -60,6 +62,23 @@ db.exec(`CREATE TABLE IF NOT EXISTS audit_log (
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
// ── Feature: Custom Violation Types ──────────────────────────────────────────
// Persisted violation type definitions created via the UI. type_key is prefixed
// with 'custom_' to prevent collisions with hardcoded violation keys.
db.exec(`CREATE TABLE IF NOT EXISTS violation_types (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type_key TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'Custom',
chapter TEXT,
description TEXT,
min_points INTEGER NOT NULL DEFAULT 1,
max_points INTEGER NOT NULL DEFAULT 1,
fields TEXT NOT NULL DEFAULT '["description"]',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
// Recreate view so it always filters negated rows
db.exec(`DROP VIEW IF EXISTS active_cpas_scores;
CREATE VIEW active_cpas_scores AS
+1
View File
@@ -25,6 +25,7 @@ CREATE TABLE IF NOT EXISTS violations (
prior_tier_label TEXT, -- optional human-readable tier
acknowledged_by TEXT, -- employee name who acknowledged receipt
acknowledged_date TEXT, -- date of acknowledgment (YYYY-MM-DD)
amount TEXT, -- dollar amount in question for financial violations (record-keeping / repayment)
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
+5
View File
@@ -243,6 +243,11 @@ function buildHtml(v, score) {
<div class="field-label">Submitted By</div>
<div class="field-value">${v.submitted_by || 'System'}</div>
</div>
${v.amount ? `
<div class="field" style="grid-column: 1 / -1;">
<div class="field-label">Amount in Question</div>
<div class="field-value prominent">${v.amount}</div>
</div>` : ''}
${v.location ? `
<div class="field" style="grid-column: 1 / -1;">
<div class="field-label">Location / Context</div>
+102 -5
View File
@@ -266,7 +266,8 @@ app.post('/api/violations', (req, res) => {
employee_id, violation_type, violation_name, category,
points, incident_date, incident_time, location,
details, submitted_by, witness_name,
acknowledged_by, acknowledged_date
acknowledged_by, acknowledged_date,
amount
} = req.body;
if (!employee_id || !violation_type || !points || !incident_date) {
@@ -282,15 +283,17 @@ app.post('/api/violations', (req, res) => {
points, incident_date, incident_time, location,
details, submitted_by, witness_name,
prior_active_points,
acknowledged_by, acknowledged_date
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
acknowledged_by, acknowledged_date,
amount
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
employee_id, violation_type, violation_name || violation_type,
category || 'General', ptsInt, incident_date,
incident_time || null, location || null,
details || null, submitted_by || null, witness_name || null,
priorPts,
acknowledged_by || null, acknowledged_date || null
acknowledged_by || null, acknowledged_date || null,
amount || null
);
audit('violation_created', 'violation', result.lastInsertRowid, submitted_by, {
@@ -302,7 +305,7 @@ app.post('/api/violations', (req, res) => {
// ── Violation Amendment (edit) ───────────────────────────────────────────────
// PATCH /api/violations/:id/amend — edit mutable fields; logs a diff per changed field
const AMENDABLE_FIELDS = ['incident_time', 'location', 'details', 'submitted_by', 'witness_name', 'acknowledged_by', 'acknowledged_date'];
const AMENDABLE_FIELDS = ['incident_time', 'location', 'details', 'submitted_by', 'witness_name', 'acknowledged_by', 'acknowledged_date', 'amount'];
// Pre-build one prepared UPDATE statement per amendable field combination is not
// practical (2^n combos), so instead we validate columns against the static
@@ -463,6 +466,100 @@ app.get('/api/audit', (req, res) => {
res.json(db.prepare(sql).all(...args));
});
// ── Custom Violation Types ────────────────────────────────────────────────────
// Persisted violation type definitions stored in violation_types table.
// type_key is auto-generated (custom_<slug>) to avoid collisions with hardcoded keys.
app.get('/api/violation-types', (req, res) => {
const rows = db.prepare('SELECT * FROM violation_types ORDER BY category ASC, name ASC').all();
res.json(rows.map(r => ({ ...r, fields: JSON.parse(r.fields) })));
});
app.post('/api/violation-types', (req, res) => {
const { name, category, chapter, description, min_points, max_points, fields, created_by } = req.body;
if (!name || !name.trim()) return res.status(400).json({ error: 'name is required' });
const minPts = parseInt(min_points) || 1;
const maxPts = parseInt(max_points) || minPts;
if (maxPts < minPts) return res.status(400).json({ error: 'max_points must be >= min_points' });
// Generate a unique type_key from the name, prefixed with 'custom_'
const base = 'custom_' + name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
let typeKey = base;
let suffix = 2;
while (db.prepare('SELECT id FROM violation_types WHERE type_key = ?').get(typeKey)) {
typeKey = `${base}_${suffix++}`;
}
try {
const result = db.prepare(`
INSERT INTO violation_types (type_key, name, category, chapter, description, min_points, max_points, fields)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`).run(
typeKey,
name.trim(),
(category || 'Custom').trim(),
chapter || null,
description || null,
minPts,
maxPts,
JSON.stringify(fields && fields.length ? fields : ['description'])
);
const row = db.prepare('SELECT * FROM violation_types WHERE id = ?').get(result.lastInsertRowid);
audit('violation_type_created', 'violation_type', result.lastInsertRowid, created_by || null, { name: row.name, category: row.category });
res.status(201).json({ ...row, fields: JSON.parse(row.fields) });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.put('/api/violation-types/:id', (req, res) => {
const id = parseInt(req.params.id);
const row = db.prepare('SELECT * FROM violation_types WHERE id = ?').get(id);
if (!row) return res.status(404).json({ error: 'Violation type not found' });
const { name, category, chapter, description, min_points, max_points, fields, updated_by } = req.body;
if (!name || !name.trim()) return res.status(400).json({ error: 'name is required' });
const minPts = parseInt(min_points) || 1;
const maxPts = parseInt(max_points) || minPts;
if (maxPts < minPts) return res.status(400).json({ error: 'max_points must be >= min_points' });
db.prepare(`
UPDATE violation_types
SET name=?, category=?, chapter=?, description=?, min_points=?, max_points=?, fields=?, updated_at=CURRENT_TIMESTAMP
WHERE id=?
`).run(
name.trim(),
(category || 'Custom').trim(),
chapter || null,
description || null,
minPts,
maxPts,
JSON.stringify(fields && fields.length ? fields : ['description']),
id
);
const updated = db.prepare('SELECT * FROM violation_types WHERE id = ?').get(id);
audit('violation_type_updated', 'violation_type', id, updated_by || null, { name: updated.name, category: updated.category });
res.json({ ...updated, fields: JSON.parse(updated.fields) });
});
app.delete('/api/violation-types/:id', (req, res) => {
const id = parseInt(req.params.id);
const row = db.prepare('SELECT * FROM violation_types WHERE id = ?').get(id);
if (!row) return res.status(404).json({ error: 'Violation type not found' });
const usage = db.prepare('SELECT COUNT(*) as count FROM violations WHERE violation_type = ?').get(row.type_key);
if (usage.count > 0) {
return res.status(409).json({ error: `Cannot delete: ${usage.count} violation(s) reference this type. Negate those violations first.` });
}
db.prepare('DELETE FROM violation_types WHERE id = ?').run(id);
audit('violation_type_deleted', 'violation_type', id, null, { name: row.name, type_key: row.type_key });
res.json({ ok: true });
});
// ── PDF endpoint ─────────────────────────────────────────────────────────────
app.get('/api/violations/:id/pdf', async (req, res) => {
try {