Merge pull request 'roadmap' (#23) from roadmap into master
Reviewed-on: #23
This commit was merged in pull request #23.
This commit is contained in:
205
client/src/components/AmendViolationModal.jsx
Normal file
205
client/src/components/AmendViolationModal.jsx
Normal file
@@ -0,0 +1,205 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const FIELD_LABELS = {
|
||||
incident_time: 'Incident Time',
|
||||
location: 'Location / Context',
|
||||
details: 'Incident Notes',
|
||||
submitted_by: 'Submitted By',
|
||||
witness_name: 'Witness / Documenting Officer',
|
||||
};
|
||||
|
||||
const s = {
|
||||
overlay: {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)',
|
||||
zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
},
|
||||
modal: {
|
||||
background: '#111217', color: '#f8f9fa', width: '520px', maxWidth: '95vw',
|
||||
maxHeight: '90vh', overflowY: 'auto',
|
||||
borderRadius: '10px', boxShadow: '0 8px 40px rgba(0,0,0,0.8)',
|
||||
border: '1px solid #222',
|
||||
},
|
||||
header: {
|
||||
background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
|
||||
padding: '18px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
borderBottom: '1px solid #222', position: 'sticky', top: 0, zIndex: 10,
|
||||
},
|
||||
headerLeft: {},
|
||||
title: { fontSize: '15px', fontWeight: 700 },
|
||||
subtitle: { fontSize: '11px', color: '#9ca0b8', marginTop: '2px' },
|
||||
closeBtn: {
|
||||
background: 'none', border: 'none', color: 'white', fontSize: '20px',
|
||||
cursor: 'pointer', lineHeight: 1,
|
||||
},
|
||||
body: { padding: '22px' },
|
||||
notice: {
|
||||
background: '#0e1a30', border: '1px solid #1e3a5f', borderRadius: '6px',
|
||||
padding: '10px 14px', fontSize: '12px', color: '#7eb8f7', marginBottom: '18px',
|
||||
},
|
||||
label: { fontSize: '11px', color: '#9ca0b8', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '5px' },
|
||||
input: {
|
||||
width: '100%', background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '9px 12px', fontSize: '13px', marginBottom: '14px',
|
||||
outline: 'none', boxSizing: 'border-box',
|
||||
},
|
||||
textarea: {
|
||||
width: '100%', background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '9px 12px', fontSize: '13px', marginBottom: '14px',
|
||||
outline: 'none', boxSizing: 'border-box', minHeight: '80px', resize: 'vertical',
|
||||
},
|
||||
divider: { borderTop: '1px solid #1c1d29', margin: '16px 0' },
|
||||
sectionTitle: {
|
||||
fontSize: '11px', fontWeight: 700, color: '#9ca0b8', textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px', marginBottom: '12px',
|
||||
},
|
||||
amendRow: {
|
||||
background: '#0d0e14', border: '1px solid #1c1d29', borderRadius: '6px',
|
||||
padding: '10px 12px', marginBottom: '8px', fontSize: '12px',
|
||||
},
|
||||
amendField: { fontWeight: 700, color: '#c0c2d6', marginBottom: '4px' },
|
||||
amendOld: { color: '#ff7070', textDecoration: 'line-through', marginRight: '6px' },
|
||||
amendNew: { color: '#9ef7c1' },
|
||||
amendMeta: { fontSize: '10px', color: '#555a7a', marginTop: '4px' },
|
||||
row: { display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '6px' },
|
||||
btn: (color, bg) => ({
|
||||
padding: '8px 18px', borderRadius: '6px', fontWeight: 700, fontSize: '13px',
|
||||
cursor: 'pointer', border: `1px solid ${color}`, color, background: bg || 'none',
|
||||
}),
|
||||
error: {
|
||||
background: '#3c1114', border: '1px solid #f5c6cb', borderRadius: '6px',
|
||||
padding: '10px 12px', fontSize: '12px', color: '#ffb3b8', marginBottom: '14px',
|
||||
},
|
||||
};
|
||||
|
||||
function fmtDt(iso) {
|
||||
if (!iso) return '—';
|
||||
return new Date(iso).toLocaleString('en-US', { timeZone: 'America/Chicago', dateStyle: 'medium', timeStyle: 'short' });
|
||||
}
|
||||
|
||||
export default function AmendViolationModal({ violation, onClose, onSaved }) {
|
||||
const [fields, setFields] = useState({
|
||||
incident_time: violation.incident_time || '',
|
||||
location: violation.location || '',
|
||||
details: violation.details || '',
|
||||
submitted_by: violation.submitted_by || '',
|
||||
witness_name: violation.witness_name || '',
|
||||
});
|
||||
const [changedBy, setChangedBy] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [amendments, setAmendments] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
axios.get(`/api/violations/${violation.id}/amendments`)
|
||||
.then(r => setAmendments(r.data))
|
||||
.catch(() => {});
|
||||
}, [violation.id]);
|
||||
|
||||
const hasChanges = Object.entries(fields).some(
|
||||
([k, v]) => v !== (violation[k] || '')
|
||||
);
|
||||
|
||||
const handleSave = async () => {
|
||||
setError('');
|
||||
setSaving(true);
|
||||
try {
|
||||
// Only send fields that actually changed
|
||||
const patch = Object.fromEntries(
|
||||
Object.entries(fields).filter(([k, v]) => v !== (violation[k] || ''))
|
||||
);
|
||||
await axios.patch(`/api/violations/${violation.id}/amend`, { ...patch, changed_by: changedBy || null });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError(e.response?.data?.error || 'Failed to save amendment');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const set = (field, value) => setFields(prev => ({ ...prev, [field]: value }));
|
||||
|
||||
return (
|
||||
<div style={s.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
|
||||
<div style={s.modal}>
|
||||
<div style={s.header}>
|
||||
<div style={s.headerLeft}>
|
||||
<div style={s.title}>Amend Violation</div>
|
||||
<div style={s.subtitle}>
|
||||
CPAS-{String(violation.id).padStart(5, '0')} · {violation.violation_name} · {violation.incident_date}
|
||||
</div>
|
||||
</div>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
</div>
|
||||
|
||||
<div style={s.body}>
|
||||
<div style={s.notice}>
|
||||
Only non-scoring fields can be amended. Point values, violation type, and incident date
|
||||
are immutable — delete and re-submit if those need to change.
|
||||
</div>
|
||||
|
||||
{error && <div style={s.error}>{error}</div>}
|
||||
|
||||
{Object.entries(FIELD_LABELS).map(([field, label]) => (
|
||||
<div key={field}>
|
||||
<div style={s.label}>{label}</div>
|
||||
{field === 'details' ? (
|
||||
<textarea
|
||||
style={s.textarea}
|
||||
value={fields[field]}
|
||||
onChange={e => set(field, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
style={s.input}
|
||||
value={fields[field]}
|
||||
onChange={e => set(field, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div style={s.label}>Your Name (recorded in amendment log)</div>
|
||||
<input
|
||||
style={s.input}
|
||||
value={changedBy}
|
||||
onChange={e => setChangedBy(e.target.value)}
|
||||
placeholder="Optional but recommended"
|
||||
/>
|
||||
|
||||
<div style={s.row}>
|
||||
<button style={s.btn('#888')} onClick={onClose}>Cancel</button>
|
||||
<button
|
||||
style={s.btn('#fff', hasChanges ? '#667eea' : '#333')}
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || saving}
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save Amendment'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{amendments.length > 0 && (
|
||||
<>
|
||||
<div style={s.divider} />
|
||||
<div style={s.sectionTitle}>Amendment History ({amendments.length})</div>
|
||||
{amendments.map(a => (
|
||||
<div key={a.id} style={s.amendRow}>
|
||||
<div style={s.amendField}>{FIELD_LABELS[a.field_name] || a.field_name}</div>
|
||||
<div>
|
||||
<span style={s.amendOld}>{a.old_value || '(empty)'}</span>
|
||||
<span style={{ color: '#555', marginRight: '6px' }}>→</span>
|
||||
<span style={s.amendNew}>{a.new_value || '(empty)'}</span>
|
||||
</div>
|
||||
<div style={s.amendMeta}>
|
||||
{a.changed_by ? `by ${a.changed_by} · ` : ''}{fmtDt(a.created_at)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
200
client/src/components/AuditLog.jsx
Normal file
200
client/src/components/AuditLog.jsx
Normal file
@@ -0,0 +1,200 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const ACTION_COLORS = {
|
||||
employee_created: '#667eea',
|
||||
employee_edited: '#9b8af8',
|
||||
employee_merged: '#f0a500',
|
||||
violation_created: '#28a745',
|
||||
violation_amended: '#4db6ac',
|
||||
violation_negated: '#ffc107',
|
||||
violation_restored:'#17a2b8',
|
||||
violation_deleted: '#dc3545',
|
||||
};
|
||||
|
||||
const ACTION_LABELS = {
|
||||
employee_created: 'Employee Created',
|
||||
employee_edited: 'Employee Edited',
|
||||
employee_merged: 'Employee Merged',
|
||||
violation_created: 'Violation Logged',
|
||||
violation_amended: 'Violation Amended',
|
||||
violation_negated: 'Violation Negated',
|
||||
violation_restored:'Violation Restored',
|
||||
violation_deleted: 'Violation Deleted',
|
||||
};
|
||||
|
||||
const ENTITY_LABELS = {
|
||||
employee: 'Employee',
|
||||
violation: 'Violation',
|
||||
};
|
||||
|
||||
const s = {
|
||||
overlay: {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)',
|
||||
zIndex: 1000, display: 'flex', alignItems: 'flex-start', justifyContent: 'flex-end',
|
||||
},
|
||||
panel: {
|
||||
background: '#111217', color: '#f8f9fa', width: '680px', maxWidth: '95vw',
|
||||
height: '100vh', overflowY: 'auto', boxShadow: '-4px 0 24px rgba(0,0,0,0.7)',
|
||||
display: 'flex', flexDirection: 'column',
|
||||
},
|
||||
header: {
|
||||
background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
|
||||
padding: '22px 26px', position: 'sticky', top: 0, zIndex: 10,
|
||||
borderBottom: '1px solid #222',
|
||||
},
|
||||
headerRow: { display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
|
||||
title: { fontSize: '17px', fontWeight: 700 },
|
||||
subtitle: { fontSize: '12px', color: '#9ca0b8', marginTop: '3px' },
|
||||
closeBtn: {
|
||||
background: 'none', border: 'none', color: 'white', fontSize: '22px',
|
||||
cursor: 'pointer', lineHeight: 1,
|
||||
},
|
||||
filters: {
|
||||
padding: '14px 26px', borderBottom: '1px solid #1c1d29',
|
||||
display: 'flex', gap: '10px', flexWrap: 'wrap',
|
||||
},
|
||||
select: {
|
||||
background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '7px 12px', fontSize: '12px', outline: 'none',
|
||||
},
|
||||
body: { padding: '16px 26px', flex: 1 },
|
||||
entry: {
|
||||
borderBottom: '1px solid #1c1d29', padding: '12px 0',
|
||||
display: 'flex', gap: '12px', alignItems: 'flex-start',
|
||||
},
|
||||
dot: (action) => ({
|
||||
width: '8px', height: '8px', borderRadius: '50%', marginTop: '5px', flexShrink: 0,
|
||||
background: ACTION_COLORS[action] || '#555',
|
||||
}),
|
||||
entryMain: { flex: 1, minWidth: 0 },
|
||||
actionBadge: (action) => ({
|
||||
display: 'inline-block', padding: '2px 8px', borderRadius: '10px',
|
||||
fontSize: '10px', fontWeight: 700, letterSpacing: '0.3px', marginRight: '6px',
|
||||
background: (ACTION_COLORS[action] || '#555') + '22',
|
||||
color: ACTION_COLORS[action] || '#aaa',
|
||||
border: `1px solid ${(ACTION_COLORS[action] || '#555')}44`,
|
||||
}),
|
||||
entityRef: { fontSize: '11px', color: '#9ca0b8' },
|
||||
details: { fontSize: '11px', color: '#667', marginTop: '4px', fontFamily: 'monospace', wordBreak: 'break-all' },
|
||||
meta: { fontSize: '10px', color: '#555a7a', marginTop: '4px' },
|
||||
empty: { textAlign: 'center', color: '#555a7a', padding: '60px 0', fontSize: '13px' },
|
||||
loadMore: {
|
||||
width: '100%', background: 'none', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#9ca0b8', padding: '10px', cursor: 'pointer', fontSize: '12px', marginTop: '16px',
|
||||
},
|
||||
};
|
||||
|
||||
function fmtDt(iso) {
|
||||
if (!iso) return '—';
|
||||
return new Date(iso).toLocaleString('en-US', {
|
||||
timeZone: 'America/Chicago', dateStyle: 'medium', timeStyle: 'short',
|
||||
});
|
||||
}
|
||||
|
||||
function renderDetails(detailsStr) {
|
||||
if (!detailsStr) return null;
|
||||
try {
|
||||
const obj = JSON.parse(detailsStr);
|
||||
return JSON.stringify(obj, null, 0)
|
||||
.replace(/^\{/, '').replace(/\}$/, '').replace(/","/g, ' ');
|
||||
} catch {
|
||||
return detailsStr;
|
||||
}
|
||||
}
|
||||
|
||||
export default function AuditLog({ onClose }) {
|
||||
const [entries, setEntries] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [filterType, setFilterType] = useState('');
|
||||
const [filterAction, setFilterAction] = useState('');
|
||||
const LIMIT = 50;
|
||||
|
||||
const load = useCallback((reset = false) => {
|
||||
setLoading(true);
|
||||
const o = reset ? 0 : offset;
|
||||
const params = { limit: LIMIT, offset: o };
|
||||
if (filterType) params.entity_type = filterType;
|
||||
if (filterAction) params.action = filterAction; // future: server-side action filter
|
||||
axios.get('/api/audit', { params })
|
||||
.then(r => {
|
||||
const data = r.data;
|
||||
// Client-side action filter (cheap enough at this scale)
|
||||
const filtered = filterAction ? data.filter(e => e.action === filterAction) : data;
|
||||
setEntries(prev => reset ? filtered : [...prev, ...filtered]);
|
||||
setHasMore(data.length === LIMIT);
|
||||
setOffset(o + LIMIT);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, [offset, filterType, filterAction]);
|
||||
|
||||
useEffect(() => { load(true); }, [filterType, filterAction]); // eslint-disable-line
|
||||
|
||||
const handleOverlay = e => { if (e.target === e.currentTarget) onClose(); };
|
||||
|
||||
return (
|
||||
<div style={s.overlay} onClick={handleOverlay}>
|
||||
<div style={s.panel} onClick={e => e.stopPropagation()}>
|
||||
<div style={s.header}>
|
||||
<div style={s.headerRow}>
|
||||
<div>
|
||||
<div style={s.title}>Audit Log</div>
|
||||
<div style={s.subtitle}>All system write actions — append-only</div>
|
||||
</div>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={s.filters}>
|
||||
<select style={s.select} value={filterType} onChange={e => { setFilterType(e.target.value); setOffset(0); }}>
|
||||
<option value="">All entity types</option>
|
||||
{Object.entries(ENTITY_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
<select style={s.select} value={filterAction} onChange={e => { setFilterAction(e.target.value); setOffset(0); }}>
|
||||
<option value="">All actions</option>
|
||||
{Object.entries(ACTION_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style={s.body}>
|
||||
{loading && entries.length === 0 ? (
|
||||
<div style={s.empty}>Loading…</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div style={s.empty}>No audit entries found.</div>
|
||||
) : (
|
||||
entries.map(e => (
|
||||
<div key={e.id} style={s.entry}>
|
||||
<div style={s.dot(e.action)} />
|
||||
<div style={s.entryMain}>
|
||||
<div>
|
||||
<span style={s.actionBadge(e.action)}>
|
||||
{ACTION_LABELS[e.action] || e.action}
|
||||
</span>
|
||||
<span style={s.entityRef}>
|
||||
{ENTITY_LABELS[e.entity_type] || e.entity_type}
|
||||
{e.entity_id ? ` #${e.entity_id}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
{e.details && (
|
||||
<div style={s.details}>{renderDetails(e.details)}</div>
|
||||
)}
|
||||
<div style={s.meta}>
|
||||
{e.performed_by ? `by ${e.performed_by} · ` : ''}{fmtDt(e.created_at)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
{hasMore && (
|
||||
<button style={s.loadMore} onClick={() => load(false)}>
|
||||
Load more
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import React, { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import CpasBadge, { getTier } from './CpasBadge';
|
||||
import EmployeeModal from './EmployeeModal';
|
||||
import AuditLog from './AuditLog';
|
||||
|
||||
const AT_RISK_THRESHOLD = 2;
|
||||
|
||||
@@ -28,30 +29,33 @@ function isAtRisk(points) {
|
||||
}
|
||||
|
||||
const s = {
|
||||
wrap: { padding: '32px 40px', color: '#f8f9fa' },
|
||||
header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '12px' },
|
||||
title: { fontSize: '24px', fontWeight: 700, color: '#f8f9fa' },
|
||||
subtitle: { fontSize: '13px', color: '#b5b5c0', marginTop: '3px' },
|
||||
statsRow: { display: 'flex', gap: '16px', flexWrap: 'wrap', marginBottom: '28px' },
|
||||
statCard: { flex: '1', minWidth: '140px', background: '#181924', border: '1px solid #30313f', borderRadius: '8px', padding: '16px', textAlign: 'center' },
|
||||
statNum: { fontSize: '28px', fontWeight: 800, color: '#f8f9fa' },
|
||||
statLbl: { fontSize: '11px', color: '#b5b5c0', marginTop: '4px' },
|
||||
search: { padding: '10px 14px', border: '1px solid #333544', borderRadius: '6px', fontSize: '14px', width: '260px', background: '#050608', color: '#f8f9fa' },
|
||||
table: { width: '100%', borderCollapse: 'collapse', background: '#111217', borderRadius: '8px', overflow: 'hidden', boxShadow: '0 1px 8px rgba(0,0,0,0.6)', border: '1px solid #222' },
|
||||
th: { background: '#000000', color: '#f8f9fa', padding: '10px 14px', textAlign: 'left', fontSize: '12px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' },
|
||||
td: { padding: '11px 14px', borderBottom: '1px solid #1c1d29', fontSize: '13px', verticalAlign: 'middle', color: '#f8f9fa' },
|
||||
nameBtn: { background: 'none', border: 'none', cursor: 'pointer', fontWeight: 600, color: '#d4af37', fontSize: '14px', padding: 0, textDecoration: 'underline dotted' },
|
||||
atRiskBadge: { display: 'inline-block', marginLeft: '8px', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#3b2e00', color: '#ffd666', border: '1px solid #d4af37', verticalAlign: 'middle' },
|
||||
zeroRow: { color: '#77798a', fontStyle: 'italic', fontSize: '12px' },
|
||||
refreshBtn: { padding: '9px 18px', background: '#d4af37', color: '#000', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
|
||||
wrap: { padding: '32px 40px', color: '#f8f9fa' },
|
||||
header: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '12px' },
|
||||
title: { fontSize: '24px', fontWeight: 700, color: '#f8f9fa' },
|
||||
subtitle: { fontSize: '13px', color: '#b5b5c0', marginTop: '3px' },
|
||||
statsRow: { display: 'flex', gap: '16px', flexWrap: 'wrap', marginBottom: '28px' },
|
||||
statCard: { flex: '1', minWidth: '140px', background: '#181924', border: '1px solid #30313f', borderRadius: '8px', padding: '16px', textAlign: 'center' },
|
||||
statNum: { fontSize: '28px', fontWeight: 800, color: '#f8f9fa' },
|
||||
statLbl: { fontSize: '11px', color: '#b5b5c0', marginTop: '4px' },
|
||||
search: { padding: '10px 14px', border: '1px solid #333544', borderRadius: '6px', fontSize: '14px', width: '260px', background: '#050608', color: '#f8f9fa' },
|
||||
table: { width: '100%', borderCollapse: 'collapse', background: '#111217', borderRadius: '8px', overflow: 'hidden', boxShadow: '0 1px 8px rgba(0,0,0,0.6)', border: '1px solid #222' },
|
||||
th: { background: '#000000', color: '#f8f9fa', padding: '10px 14px', textAlign: 'left', fontSize: '12px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' },
|
||||
td: { padding: '11px 14px', borderBottom: '1px solid #1c1d29', fontSize: '13px', verticalAlign: 'middle', color: '#f8f9fa' },
|
||||
nameBtn: { background: 'none', border: 'none', cursor: 'pointer', fontWeight: 600, color: '#d4af37', fontSize: '14px', padding: 0, textDecoration: 'underline dotted' },
|
||||
atRiskBadge: { display: 'inline-block', marginLeft: '8px', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: '#3b2e00', color: '#ffd666', border: '1px solid #d4af37', verticalAlign: 'middle' },
|
||||
zeroRow: { color: '#77798a', fontStyle: 'italic', fontSize: '12px' },
|
||||
toolbarRight: { display: 'flex', gap: '10px', alignItems: 'center' },
|
||||
refreshBtn: { padding: '9px 18px', background: '#d4af37', color: '#000', border: 'none', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
|
||||
auditBtn: { padding: '9px 18px', background: 'none', color: '#9ca0b8', border: '1px solid #2a2b3a', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
|
||||
};
|
||||
|
||||
export default function Dashboard() {
|
||||
const [employees, setEmployees] = useState([]);
|
||||
const [filtered, setFiltered] = useState([]);
|
||||
const [search, setSearch] = useState('');
|
||||
const [selectedId, setSelectedId] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [employees, setEmployees] = useState([]);
|
||||
const [filtered, setFiltered] = useState([]);
|
||||
const [search, setSearch] = useState('');
|
||||
const [selectedId, setSelectedId] = useState(null);
|
||||
const [showAudit, setShowAudit] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
@@ -77,9 +81,6 @@ export default function Dashboard() {
|
||||
const maxPoints = employees.reduce((m, e) => Math.max(m, e.active_points), 0);
|
||||
|
||||
return (
|
||||
// FIX: Fragment wraps both s.wrap AND EmployeeModal so the modal is
|
||||
// outside the s.wrap div — React synthetic events will no longer bubble
|
||||
// from inside the modal up through the Dashboard's DOM tree.
|
||||
<>
|
||||
<div style={s.wrap}>
|
||||
<div style={s.header}>
|
||||
@@ -87,13 +88,14 @@ export default function Dashboard() {
|
||||
<div style={s.title}>Company Dashboard</div>
|
||||
<div style={s.subtitle}>Click any employee name to view their full profile</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
|
||||
<div style={s.toolbarRight}>
|
||||
<input
|
||||
style={s.search}
|
||||
placeholder="Search name, dept, supervisor…"
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
/>
|
||||
<button style={s.auditBtn} onClick={() => setShowAudit(true)}>📋 Audit Log</button>
|
||||
<button style={s.refreshBtn} onClick={load}>↻ Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -179,15 +181,13 @@ export default function Dashboard() {
|
||||
)}
|
||||
</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(); }}
|
||||
/>
|
||||
)}
|
||||
{showAudit && <AuditLog onClose={() => setShowAudit(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
189
client/src/components/EditEmployeeModal.jsx
Normal file
189
client/src/components/EditEmployeeModal.jsx
Normal file
@@ -0,0 +1,189 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
const s = {
|
||||
overlay: {
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)',
|
||||
zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
},
|
||||
modal: {
|
||||
background: '#111217', color: '#f8f9fa', width: '480px', maxWidth: '95vw',
|
||||
borderRadius: '10px', boxShadow: '0 8px 40px rgba(0,0,0,0.8)',
|
||||
border: '1px solid #222', overflow: 'hidden',
|
||||
},
|
||||
header: {
|
||||
background: 'linear-gradient(135deg, #000000, #151622)', color: 'white',
|
||||
padding: '18px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
borderBottom: '1px solid #222',
|
||||
},
|
||||
title: { fontSize: '15px', fontWeight: 700 },
|
||||
closeBtn: {
|
||||
background: 'none', border: 'none', color: 'white', fontSize: '20px',
|
||||
cursor: 'pointer', lineHeight: 1,
|
||||
},
|
||||
body: { padding: '22px' },
|
||||
tabs: { display: 'flex', gap: '4px', marginBottom: '20px' },
|
||||
tab: (active) => ({
|
||||
flex: 1, padding: '8px', borderRadius: '6px', cursor: 'pointer', fontSize: '12px',
|
||||
fontWeight: 700, textAlign: 'center', border: '1px solid',
|
||||
background: active ? '#1a1c2e' : 'none',
|
||||
borderColor: active ? '#667eea' : '#2a2b3a',
|
||||
color: active ? '#667eea' : '#777',
|
||||
}),
|
||||
label: { fontSize: '11px', color: '#9ca0b8', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '5px' },
|
||||
input: {
|
||||
width: '100%', background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '9px 12px', fontSize: '13px', marginBottom: '14px',
|
||||
outline: 'none', boxSizing: 'border-box',
|
||||
},
|
||||
select: {
|
||||
width: '100%', background: '#0d0e14', border: '1px solid #2a2b3a', borderRadius: '6px',
|
||||
color: '#f8f9fa', padding: '9px 12px', fontSize: '13px', marginBottom: '14px',
|
||||
outline: 'none', boxSizing: 'border-box',
|
||||
},
|
||||
row: { display: 'flex', gap: '10px', justifyContent: 'flex-end', marginTop: '6px' },
|
||||
btn: (color, bg) => ({
|
||||
padding: '8px 18px', borderRadius: '6px', fontWeight: 700, fontSize: '13px',
|
||||
cursor: 'pointer', border: `1px solid ${color}`, color, background: bg || 'none',
|
||||
}),
|
||||
error: {
|
||||
background: '#3c1114', border: '1px solid #f5c6cb', borderRadius: '6px',
|
||||
padding: '10px 12px', fontSize: '12px', color: '#ffb3b8', marginBottom: '14px',
|
||||
},
|
||||
success: {
|
||||
background: '#0a2e1f', border: '1px solid #0f5132', borderRadius: '6px',
|
||||
padding: '10px 12px', fontSize: '12px', color: '#9ef7c1', marginBottom: '14px',
|
||||
},
|
||||
mergeWarning: {
|
||||
background: '#2a1f00', border: '1px solid #7a5000', borderRadius: '6px',
|
||||
padding: '12px', fontSize: '12px', color: '#ffc107', marginBottom: '14px', lineHeight: 1.5,
|
||||
},
|
||||
};
|
||||
|
||||
export default function EditEmployeeModal({ employee, onClose, onSaved }) {
|
||||
const [tab, setTab] = useState('edit');
|
||||
|
||||
// Edit state
|
||||
const [name, setName] = useState(employee.name);
|
||||
const [department, setDepartment] = useState(employee.department || '');
|
||||
const [supervisor, setSupervisor] = useState(employee.supervisor || '');
|
||||
const [editError, setEditError] = useState('');
|
||||
const [editSaving, setEditSaving] = useState(false);
|
||||
|
||||
// Merge state
|
||||
const [allEmployees, setAllEmployees] = useState([]);
|
||||
const [sourceId, setSourceId] = useState('');
|
||||
const [mergeError, setMergeError] = useState('');
|
||||
const [mergeResult, setMergeResult] = useState(null);
|
||||
const [merging, setMerging] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (tab === 'merge') {
|
||||
axios.get('/api/employees').then(r => setAllEmployees(r.data));
|
||||
}
|
||||
}, [tab]);
|
||||
|
||||
const handleEdit = async () => {
|
||||
setEditError('');
|
||||
setEditSaving(true);
|
||||
try {
|
||||
await axios.patch(`/api/employees/${employee.id}`, { name, department, supervisor });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setEditError(e.response?.data?.error || 'Failed to save changes');
|
||||
} finally {
|
||||
setEditSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMerge = async () => {
|
||||
if (!sourceId) return setMergeError('Select an employee to merge in');
|
||||
setMergeError('');
|
||||
setMerging(true);
|
||||
try {
|
||||
const r = await axios.post(`/api/employees/${employee.id}/merge`, { source_id: parseInt(sourceId) });
|
||||
setMergeResult(r.data);
|
||||
onSaved(); // refresh dashboard / parent list
|
||||
} catch (e) {
|
||||
setMergeError(e.response?.data?.error || 'Merge failed');
|
||||
} finally {
|
||||
setMerging(false);
|
||||
}
|
||||
};
|
||||
|
||||
const otherEmployees = allEmployees.filter(e => e.id !== employee.id);
|
||||
|
||||
return (
|
||||
<div style={s.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
|
||||
<div style={s.modal}>
|
||||
<div style={s.header}>
|
||||
<div style={s.title}>Edit Employee</div>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
</div>
|
||||
<div style={s.body}>
|
||||
<div style={s.tabs}>
|
||||
<button style={s.tab(tab === 'edit')} onClick={() => setTab('edit')}>Edit Details</button>
|
||||
<button style={s.tab(tab === 'merge')} onClick={() => setTab('merge')}>Merge Duplicate</button>
|
||||
</div>
|
||||
|
||||
{tab === 'edit' && (
|
||||
<>
|
||||
{editError && <div style={s.error}>{editError}</div>}
|
||||
<div style={s.label}>Full Name</div>
|
||||
<input style={s.input} value={name} onChange={e => setName(e.target.value)} />
|
||||
<div style={s.label}>Department</div>
|
||||
<input style={s.input} value={department} onChange={e => setDepartment(e.target.value)} placeholder="Optional" />
|
||||
<div style={s.label}>Supervisor</div>
|
||||
<input style={s.input} value={supervisor} onChange={e => setSupervisor(e.target.value)} placeholder="Optional" />
|
||||
<div style={s.row}>
|
||||
<button style={s.btn('#888')} onClick={onClose}>Cancel</button>
|
||||
<button style={s.btn('#fff', '#667eea')} onClick={handleEdit} disabled={editSaving}>
|
||||
{editSaving ? 'Saving…' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === 'merge' && (
|
||||
<>
|
||||
{mergeResult ? (
|
||||
<div style={s.success}>
|
||||
✓ Merge complete — {mergeResult.violations_reassigned} violation{mergeResult.violations_reassigned !== 1 ? 's' : ''} reassigned
|
||||
to <strong>{employee.name}</strong>. The duplicate record has been removed.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div style={s.mergeWarning}>
|
||||
⚠ This will reassign <strong>all violations</strong> from the selected employee into{' '}
|
||||
<strong>{employee.name}</strong>, then permanently delete the duplicate record.
|
||||
This cannot be undone.
|
||||
</div>
|
||||
{mergeError && <div style={s.error}>{mergeError}</div>}
|
||||
<div style={s.label}>Duplicate to merge into {employee.name}</div>
|
||||
<select style={s.select} value={sourceId} onChange={e => setSourceId(e.target.value)}>
|
||||
<option value="">— select employee —</option>
|
||||
{otherEmployees.map(e => (
|
||||
<option key={e.id} value={e.id}>{e.name}{e.department ? ` (${e.department})` : ''}</option>
|
||||
))}
|
||||
</select>
|
||||
<div style={s.row}>
|
||||
<button style={s.btn('#888')} onClick={onClose}>Cancel</button>
|
||||
<button style={s.btn('#fff', '#c0392b')} onClick={handleMerge} disabled={merging || !sourceId}>
|
||||
{merging ? 'Merging…' : 'Merge & Delete Duplicate'}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mergeResult && (
|
||||
<div style={s.row}>
|
||||
<button style={s.btn('#fff', '#667eea')} onClick={onClose}>Done</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import React, { useState, useEffect, useCallback } from 'react';
|
||||
import axios from 'axios';
|
||||
import CpasBadge, { getTier } from './CpasBadge';
|
||||
import NegateModal from './NegateModal';
|
||||
import EditEmployeeModal from './EditEmployeeModal';
|
||||
import AmendViolationModal from './AmendViolationModal';
|
||||
|
||||
const s = {
|
||||
overlay: {
|
||||
@@ -18,10 +20,15 @@ const s = {
|
||||
padding: '24px 28px', position: 'sticky', top: 0, zIndex: 10,
|
||||
borderBottom: '1px solid #222',
|
||||
},
|
||||
headerRow: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' },
|
||||
closeBtn: {
|
||||
float: 'right', background: 'none', border: 'none', color: 'white',
|
||||
fontSize: '22px', cursor: 'pointer', lineHeight: 1, marginTop: '-2px',
|
||||
},
|
||||
editEmpBtn: {
|
||||
background: 'none', border: '1px solid #555', color: '#ccc', borderRadius: '5px',
|
||||
padding: '4px 10px', fontSize: '11px', cursor: 'pointer', marginTop: '8px', fontWeight: 600,
|
||||
},
|
||||
body: { padding: '24px 28px', flex: 1 },
|
||||
scoreRow: { display: 'flex', gap: '12px', flexWrap: 'wrap', marginBottom: '24px' },
|
||||
scoreCard: {
|
||||
@@ -62,19 +69,31 @@ const s = {
|
||||
borderRadius: '4px', padding: '3px 8px', fontSize: '11px',
|
||||
cursor: 'pointer', fontWeight: 600,
|
||||
},
|
||||
amendBtn: {
|
||||
background: 'none', border: '1px solid #4db6ac', color: '#4db6ac',
|
||||
borderRadius: '4px', padding: '3px 8px', fontSize: '11px',
|
||||
cursor: 'pointer', marginRight: '4px', fontWeight: 600,
|
||||
},
|
||||
deleteConfirm: {
|
||||
background: '#3c1114', border: '1px solid #f5c6cb', borderRadius: '6px',
|
||||
padding: '12px', marginTop: '8px', fontSize: '12px', color: '#ffb3b8',
|
||||
},
|
||||
amendBadge: {
|
||||
display: 'inline-block', marginLeft: '4px', padding: '1px 5px', borderRadius: '8px',
|
||||
fontSize: '9px', fontWeight: 700, background: '#0e2a2a', color: '#4db6ac',
|
||||
border: '1px solid #1a4a4a', verticalAlign: 'middle',
|
||||
},
|
||||
};
|
||||
|
||||
export default function EmployeeModal({ employeeId, onClose }) {
|
||||
const [employee, setEmployee] = useState(null);
|
||||
const [score, setScore] = useState(null);
|
||||
const [employee, setEmployee] = useState(null);
|
||||
const [score, setScore] = useState(null);
|
||||
const [violations, setViolations] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [negating, setNegating] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [negating, setNegating] = useState(null);
|
||||
const [confirmDel, setConfirmDel] = useState(null);
|
||||
const [editingEmp, setEditingEmp] = useState(false);
|
||||
const [amending, setAmending] = useState(null); // violation object
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
@@ -96,9 +115,9 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
|
||||
const handleDownloadPdf = async (violId, empName, date) => {
|
||||
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');
|
||||
link.href = url;
|
||||
link.href = url;
|
||||
link.download = `CPAS_${(empName || '').replace(/[^a-z0-9]/gi, '_')}_${date}.pdf`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
@@ -119,39 +138,42 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
};
|
||||
|
||||
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`, { resolution_type, details, resolved_by });
|
||||
setNegating(null);
|
||||
setConfirmDel(null);
|
||||
load();
|
||||
};
|
||||
|
||||
const tier = score ? getTier(score.active_points) : null;
|
||||
const active = violations.filter((v) => !v.negated);
|
||||
const tier = score ? getTier(score.active_points) : null;
|
||||
const active = violations.filter((v) => !v.negated);
|
||||
const negated = violations.filter((v) => v.negated);
|
||||
|
||||
// FIX: overlay click only closes if clicking the backdrop itself, NOT children
|
||||
const handleOverlayClick = (e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
};
|
||||
const handleOverlayClick = (e) => { if (e.target === e.currentTarget) onClose(); };
|
||||
|
||||
return (
|
||||
// FIX: panel uses onClick stopPropagation to prevent bubbling to overlay
|
||||
<div style={s.overlay} onClick={handleOverlayClick}>
|
||||
<div style={s.panel} onClick={(e) => e.stopPropagation()}>
|
||||
|
||||
{/* ── Header ── */}
|
||||
<div style={s.header}>
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
<div style={{ fontSize: '18px', fontWeight: 700 }}>
|
||||
{employee ? employee.name : 'Employee'}
|
||||
</div>
|
||||
{employee && (
|
||||
<div style={{ fontSize: '12px', color: '#b5b5c0', marginTop: '4px' }}>
|
||||
{employee.department} {employee.supervisor && `· Supervisor: ${employee.supervisor}`}
|
||||
<div style={s.headerRow}>
|
||||
<div>
|
||||
<div style={{ fontSize: '18px', fontWeight: 700 }}>
|
||||
{employee ? employee.name : 'Employee'}
|
||||
</div>
|
||||
{employee && (
|
||||
<div style={{ fontSize: '12px', color: '#b5b5c0', marginTop: '4px' }}>
|
||||
{employee.department} {employee.supervisor && `· Supervisor: ${employee.supervisor}`}
|
||||
</div>
|
||||
)}
|
||||
{employee && (
|
||||
<button style={s.editEmpBtn} onClick={() => setEditingEmp(true)}>
|
||||
✎ Edit Employee
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<button style={s.closeBtn} onClick={onClose}>✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Body ── */}
|
||||
@@ -190,7 +212,7 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
{/* ── Active Violations ── */}
|
||||
<div style={s.sectionHd}>Active Violations</div>
|
||||
{active.length === 0 ? (
|
||||
<div style={{ color: '#77798a', fontStyle: 'italic', fontSize: '12px' }}>
|
||||
<div style={{ color: '#777990', fontStyle: 'italic', fontSize: '12px' }}>
|
||||
No active violations on record.
|
||||
</div>
|
||||
) : (
|
||||
@@ -208,17 +230,22 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
<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={{ fontWeight: 600 }}>
|
||||
{v.violation_name}
|
||||
{v.amendment_count > 0 && (
|
||||
<span style={s.amendBadge}>{v.amendment_count} edit{v.amendment_count !== 1 ? 's' : ''}</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ fontSize: '10px', color: '#9ca0b8' }}>{v.category}</div>
|
||||
{v.details && (
|
||||
<div style={{ fontSize: '10px', color: '#b5b5c0', marginTop: '2px' }}>
|
||||
{v.details}
|
||||
</div>
|
||||
<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.amendBtn} onClick={(e) => { e.stopPropagation(); setAmending(v); }}>
|
||||
Amend
|
||||
</button>
|
||||
<button
|
||||
style={s.actionBtn('#ffc107')}
|
||||
onClick={(e) => { e.stopPropagation(); setNegating(v); setConfirmDel(null); }}
|
||||
@@ -294,9 +321,7 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
</div>
|
||||
)}
|
||||
{v.resolved_by && (
|
||||
<div style={{ fontSize: '10px', color: '#9ca0b8' }}>
|
||||
by {v.resolved_by}
|
||||
</div>
|
||||
<div style={{ fontSize: '10px', color: '#9ca0b8' }}>by {v.resolved_by}</div>
|
||||
)}
|
||||
</td>
|
||||
<td style={s.td}>
|
||||
@@ -349,7 +374,7 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* FIX: NegateModal rendered OUTSIDE the panel so it sits at root z-index:2000 */}
|
||||
{/* Modals rendered outside panel to avoid z-index nesting issues */}
|
||||
{negating && (
|
||||
<NegateModal
|
||||
violation={negating}
|
||||
@@ -357,6 +382,20 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
onCancel={() => setNegating(null)}
|
||||
/>
|
||||
)}
|
||||
{editingEmp && employee && (
|
||||
<EditEmployeeModal
|
||||
employee={employee}
|
||||
onClose={() => setEditingEmp(false)}
|
||||
onSaved={load}
|
||||
/>
|
||||
)}
|
||||
{amending && (
|
||||
<AmendViolationModal
|
||||
violation={amending}
|
||||
onClose={() => setAmending(null)}
|
||||
onSaved={load}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,12 +13,12 @@ db.pragma('foreign_keys = ON');
|
||||
const schema = fs.readFileSync(path.join(__dirname, 'schema.sql'), 'utf8');
|
||||
db.exec(schema);
|
||||
|
||||
// ── Migrations for existing DBs ─────────────────────────────────────────────
|
||||
// ── Migrations for existing DBs ──────────────────────────────────────────────
|
||||
const cols = db.prepare('PRAGMA table_info(violations)').all().map(c => c.name);
|
||||
if (!cols.includes('negated')) db.exec("ALTER TABLE violations ADD COLUMN negated INTEGER NOT NULL DEFAULT 0");
|
||||
if (!cols.includes('negated_at')) db.exec("ALTER TABLE violations ADD COLUMN negated_at DATETIME");
|
||||
if (!cols.includes('prior_active_points')) db.exec("ALTER TABLE violations ADD COLUMN prior_active_points INTEGER");
|
||||
if (!cols.includes('prior_tier_label')) db.exec("ALTER TABLE violations ADD COLUMN prior_tier_label TEXT");
|
||||
if (!cols.includes('negated')) db.exec("ALTER TABLE violations ADD COLUMN negated INTEGER NOT NULL DEFAULT 0");
|
||||
if (!cols.includes('negated_at')) db.exec("ALTER TABLE violations ADD COLUMN negated_at DATETIME");
|
||||
if (!cols.includes('prior_active_points')) db.exec("ALTER TABLE violations ADD COLUMN prior_active_points INTEGER");
|
||||
if (!cols.includes('prior_tier_label')) db.exec("ALTER TABLE violations ADD COLUMN prior_tier_label TEXT");
|
||||
|
||||
// Ensure resolutions table exists
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS violation_resolutions (
|
||||
@@ -30,6 +30,30 @@ db.exec(`CREATE TABLE IF NOT EXISTS violation_resolutions (
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
|
||||
// ── Feature: Violation Amendments ────────────────────────────────────────────
|
||||
// Stores a field-level diff every time a violation's editable fields are changed.
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS violation_amendments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
violation_id INTEGER NOT NULL REFERENCES violations(id) ON DELETE CASCADE,
|
||||
changed_by TEXT,
|
||||
field_name TEXT NOT NULL,
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
|
||||
// ── Feature: Audit Log ───────────────────────────────────────────────────────
|
||||
// Append-only record of every write action across the system.
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
action TEXT NOT NULL,
|
||||
entity_type TEXT NOT NULL,
|
||||
entity_id INTEGER,
|
||||
performed_by TEXT,
|
||||
details TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`);
|
||||
|
||||
// Recreate view so it always filters negated rows
|
||||
db.exec(`DROP VIEW IF EXISTS active_cpas_scores;
|
||||
CREATE VIEW active_cpas_scores AS
|
||||
|
||||
177
server.js
177
server.js
@@ -11,10 +11,23 @@ app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.static(path.join(__dirname, 'client', 'dist')));
|
||||
|
||||
// ── Audit helper ─────────────────────────────────────────────────────────────
|
||||
function audit(action, entityType, entityId, performedBy, details) {
|
||||
try {
|
||||
db.prepare(`
|
||||
INSERT INTO audit_log (action, entity_type, entity_id, performed_by, details)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`).run(action, entityType, entityId || null, performedBy || null,
|
||||
typeof details === 'object' ? JSON.stringify(details) : (details || null));
|
||||
} catch (e) {
|
||||
console.error('[AUDIT]', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Health
|
||||
app.get('/api/health', (req, res) => res.json({ status: 'ok', timestamp: new Date().toISOString() }));
|
||||
|
||||
// Employees
|
||||
// ── Employees ─────────────────────────────────────────────────────────────────
|
||||
app.get('/api/employees', (req, res) => {
|
||||
const rows = db.prepare('SELECT id, name, department, supervisor FROM employees ORDER BY name ASC').all();
|
||||
res.json(rows);
|
||||
@@ -33,9 +46,72 @@ app.post('/api/employees', (req, res) => {
|
||||
}
|
||||
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)')
|
||||
.run(name, department || null, supervisor || null);
|
||||
audit('employee_created', 'employee', result.lastInsertRowid, null, { name });
|
||||
res.status(201).json({ id: result.lastInsertRowid, name, department, supervisor });
|
||||
});
|
||||
|
||||
// ── Employee Edit ─────────────────────────────────────────────────────────────
|
||||
// PATCH /api/employees/:id — update name, department, or supervisor
|
||||
app.patch('/api/employees/:id', (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
const emp = db.prepare('SELECT * FROM employees WHERE id = ?').get(id);
|
||||
if (!emp) return res.status(404).json({ error: 'Employee not found' });
|
||||
|
||||
const { name, department, supervisor, performed_by } = req.body;
|
||||
|
||||
// Prevent name collision with a different employee
|
||||
if (name && name.trim() !== emp.name) {
|
||||
const clash = db.prepare('SELECT id FROM employees WHERE LOWER(name) = LOWER(?) AND id != ?').get(name.trim(), id);
|
||||
if (clash) return res.status(409).json({ error: 'An employee with that name already exists', conflictId: clash.id });
|
||||
}
|
||||
|
||||
const newName = (name || emp.name).trim();
|
||||
const newDept = department !== undefined ? (department || null) : emp.department;
|
||||
const newSupervisor = supervisor !== undefined ? (supervisor || null) : emp.supervisor;
|
||||
|
||||
db.prepare('UPDATE employees SET name = ?, department = ?, supervisor = ? WHERE id = ?')
|
||||
.run(newName, newDept, newSupervisor, id);
|
||||
|
||||
audit('employee_edited', 'employee', id, performed_by, {
|
||||
before: { name: emp.name, department: emp.department, supervisor: emp.supervisor },
|
||||
after: { name: newName, department: newDept, supervisor: newSupervisor },
|
||||
});
|
||||
|
||||
res.json({ id, name: newName, department: newDept, supervisor: newSupervisor });
|
||||
});
|
||||
|
||||
// ── Employee Merge ────────────────────────────────────────────────────────────
|
||||
// POST /api/employees/:id/merge — reassign all violations from sourceId → id, then delete source
|
||||
app.post('/api/employees/:id/merge', (req, res) => {
|
||||
const targetId = parseInt(req.params.id);
|
||||
const { source_id, performed_by } = req.body;
|
||||
if (!source_id) return res.status(400).json({ error: 'source_id is required' });
|
||||
|
||||
const target = db.prepare('SELECT * FROM employees WHERE id = ?').get(targetId);
|
||||
const source = db.prepare('SELECT * FROM employees WHERE id = ?').get(source_id);
|
||||
if (!target) return res.status(404).json({ error: 'Target employee not found' });
|
||||
if (!source) return res.status(404).json({ error: 'Source employee not found' });
|
||||
if (targetId === parseInt(source_id)) return res.status(400).json({ error: 'Cannot merge an employee into themselves' });
|
||||
|
||||
const mergeTransaction = db.transaction(() => {
|
||||
// Move all violations
|
||||
const moved = db.prepare('UPDATE violations SET employee_id = ? WHERE employee_id = ?').run(targetId, source_id);
|
||||
// Delete the source employee
|
||||
db.prepare('DELETE FROM employees WHERE id = ?').run(source_id);
|
||||
return moved.changes;
|
||||
});
|
||||
|
||||
const violationsMoved = mergeTransaction();
|
||||
|
||||
audit('employee_merged', 'employee', targetId, performed_by, {
|
||||
source: { id: source.id, name: source.name },
|
||||
target: { id: target.id, name: target.name },
|
||||
violations_reassigned: violationsMoved,
|
||||
});
|
||||
|
||||
res.json({ success: true, violations_reassigned: violationsMoved });
|
||||
});
|
||||
|
||||
// Employee score (current snapshot)
|
||||
app.get('/api/employees/:id/score', (req, res) => {
|
||||
const row = db.prepare('SELECT * FROM active_cpas_scores WHERE employee_id = ?').get(req.params.id);
|
||||
@@ -55,12 +131,13 @@ app.get('/api/dashboard', (req, res) => {
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// Violation history (per employee) with resolutions
|
||||
// Violation history (per employee) with resolutions + amendment count
|
||||
app.get('/api/violations/employee/:id', (req, res) => {
|
||||
const limit = parseInt(req.query.limit) || 50;
|
||||
const rows = db.prepare(`
|
||||
SELECT v.*, r.resolution_type, r.details AS resolution_details,
|
||||
r.resolved_by, r.created_at AS resolved_at
|
||||
r.resolved_by, r.created_at AS resolved_at,
|
||||
(SELECT COUNT(*) FROM violation_amendments a WHERE a.violation_id = v.id) AS amendment_count
|
||||
FROM violations v
|
||||
LEFT JOIN violation_resolutions r ON r.violation_id = v.id
|
||||
WHERE v.employee_id = ?
|
||||
@@ -70,6 +147,14 @@ app.get('/api/violations/employee/:id', (req, res) => {
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// ── Violation amendment history ───────────────────────────────────────────────
|
||||
app.get('/api/violations/:id/amendments', (req, res) => {
|
||||
const rows = db.prepare(`
|
||||
SELECT * FROM violation_amendments WHERE violation_id = ? ORDER BY created_at DESC
|
||||
`).all(req.params.id);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// Helper: compute prior_active_points at time of insert
|
||||
function getPriorActivePoints(employeeId, incidentDate) {
|
||||
const row = db.prepare(
|
||||
@@ -113,10 +198,61 @@ app.post('/api/violations', (req, res) => {
|
||||
priorPts
|
||||
);
|
||||
|
||||
audit('violation_created', 'violation', result.lastInsertRowid, submitted_by, {
|
||||
employee_id, violation_type, points: ptsInt, incident_date,
|
||||
});
|
||||
|
||||
res.status(201).json({ id: result.lastInsertRowid });
|
||||
});
|
||||
|
||||
// ── Negate a violation ──────────────────────────────────────────────────────
|
||||
// ── Violation Amendment (edit) ────────────────────────────────────────────────
|
||||
// PATCH /api/violations/:id/amend — edit mutable fields; logs a diff per changed field
|
||||
const AMENDABLE_FIELDS = ['incident_time', 'location', 'details', 'submitted_by', 'witness_name'];
|
||||
|
||||
app.patch('/api/violations/:id/amend', (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
const { changed_by, ...updates } = req.body;
|
||||
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
if (!violation) return res.status(404).json({ error: 'Violation not found' });
|
||||
if (violation.negated) return res.status(400).json({ error: 'Cannot amend a negated violation' });
|
||||
|
||||
// Only allow whitelisted fields to be amended
|
||||
const allowed = Object.fromEntries(
|
||||
Object.entries(updates).filter(([k]) => AMENDABLE_FIELDS.includes(k))
|
||||
);
|
||||
if (Object.keys(allowed).length === 0) {
|
||||
return res.status(400).json({ error: 'No amendable fields provided', amendable: AMENDABLE_FIELDS });
|
||||
}
|
||||
|
||||
const amendTransaction = db.transaction(() => {
|
||||
// Build UPDATE
|
||||
const setClauses = Object.keys(allowed).map(k => `${k} = ?`).join(', ');
|
||||
const values = [...Object.values(allowed), id];
|
||||
db.prepare(`UPDATE violations SET ${setClauses} WHERE id = ?`).run(...values);
|
||||
|
||||
// Insert an amendment record per changed field
|
||||
const insertAmendment = db.prepare(`
|
||||
INSERT INTO violation_amendments (violation_id, changed_by, field_name, old_value, new_value)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`);
|
||||
for (const [field, newVal] of Object.entries(allowed)) {
|
||||
const oldVal = violation[field];
|
||||
if (String(oldVal) !== String(newVal)) {
|
||||
insertAmendment.run(id, changed_by || null, field, oldVal ?? null, newVal ?? null);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
amendTransaction();
|
||||
|
||||
audit('violation_amended', 'violation', id, changed_by, { fields: Object.keys(allowed) });
|
||||
|
||||
const updated = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
res.json(updated);
|
||||
});
|
||||
|
||||
// ── Negate a violation ────────────────────────────────────────────────────────
|
||||
app.patch('/api/violations/:id/negate', (req, res) => {
|
||||
const { resolution_type, details, resolved_by } = req.body;
|
||||
const id = req.params.id;
|
||||
@@ -124,10 +260,8 @@ app.patch('/api/violations/:id/negate', (req, res) => {
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
if (!violation) return res.status(404).json({ error: 'Violation not found' });
|
||||
|
||||
// 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(`
|
||||
@@ -142,10 +276,11 @@ app.patch('/api/violations/:id/negate', (req, res) => {
|
||||
`).run(id, resolution_type || 'Resolved', details || null, resolved_by || null);
|
||||
}
|
||||
|
||||
audit('violation_negated', 'violation', id, resolved_by, { resolution_type });
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ── Restore a negated violation ─────────────────────────────────────────────
|
||||
// ── Restore a negated violation ───────────────────────────────────────────────
|
||||
app.patch('/api/violations/:id/restore', (req, res) => {
|
||||
const id = req.params.id;
|
||||
|
||||
@@ -155,24 +290,46 @@ app.patch('/api/violations/:id/restore', (req, res) => {
|
||||
db.prepare('UPDATE violations SET negated = 0 WHERE id = ?').run(id);
|
||||
db.prepare('DELETE FROM violation_resolutions WHERE violation_id = ?').run(id);
|
||||
|
||||
audit('violation_restored', 'violation', id, req.body?.performed_by, {});
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ── Hard delete a violation ─────────────────────────────────────────────────
|
||||
// ── Hard delete a violation ───────────────────────────────────────────────────
|
||||
app.delete('/api/violations/:id', (req, res) => {
|
||||
const id = req.params.id;
|
||||
|
||||
const violation = db.prepare('SELECT * FROM violations WHERE id = ?').get(id);
|
||||
if (!violation) return res.status(404).json({ error: 'Violation not found' });
|
||||
|
||||
// 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);
|
||||
|
||||
audit('violation_deleted', 'violation', id, req.body?.performed_by, {
|
||||
violation_type: violation.violation_type, employee_id: violation.employee_id,
|
||||
});
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ── PDF endpoint ─────────────────────────────────────────────────────────────
|
||||
// ── Audit log ─────────────────────────────────────────────────────────────────
|
||||
app.get('/api/audit', (req, res) => {
|
||||
const limit = Math.min(parseInt(req.query.limit) || 100, 500);
|
||||
const offset = parseInt(req.query.offset) || 0;
|
||||
const type = req.query.entity_type;
|
||||
const id = req.query.entity_id;
|
||||
|
||||
let sql = 'SELECT * FROM audit_log';
|
||||
const args = [];
|
||||
const where = [];
|
||||
if (type) { where.push('entity_type = ?'); args.push(type); }
|
||||
if (id) { where.push('entity_id = ?'); args.push(id); }
|
||||
if (where.length) sql += ' WHERE ' + where.join(' AND ');
|
||||
sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
|
||||
args.push(limit, offset);
|
||||
|
||||
res.json(db.prepare(sql).all(...args));
|
||||
});
|
||||
|
||||
// ── PDF endpoint ──────────────────────────────────────────────────────────────
|
||||
app.get('/api/violations/:id/pdf', async (req, res) => {
|
||||
try {
|
||||
const violation = db.prepare(`
|
||||
|
||||
Reference in New Issue
Block a user