Compare commits
29 Commits
87649b59d0
...
cpas-check
| Author | SHA1 | Date | |
|---|---|---|---|
| da36edbba6 | |||
|
|
d6585c01c6 | ||
| eccb105340 | |||
| b656c970f0 | |||
| f8c0fcd441 | |||
| 91ba19d038 | |||
| b7753d492d | |||
| e0cb66af46 | |||
| 0769a39491 | |||
| 15a2b89350 | |||
| 74492142a1 | |||
| 602f371d67 | |||
| c86b070db3 | |||
| f4ed8c49ce | |||
| 51bf176f96 | |||
| 20be30318f | |||
| b02026f8a9 | |||
| 87cf48e77e | |||
| 2348336b0f | |||
| 995e607003 | |||
| d613c92970 | |||
| 981fa3bea4 | |||
| dc45cb7d83 | |||
| 7326ffec6e | |||
| 5f0ae959ed | |||
| 917f5a24af | |||
| 9aa27d7598 | |||
| 7e1164af13 | |||
| 232814db93 |
4
.vscode/settings.json
vendored
Normal file
4
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"giteaActions.baseUrl": "https://git.alwisp.com",
|
||||
"giteaActions.discovery.mode": "allAccessible"
|
||||
}
|
||||
12
Dockerfile
12
Dockerfile
@@ -7,6 +7,15 @@ RUN cd client && npm install
|
||||
COPY client/ ./client/
|
||||
RUN cd client && npm run build
|
||||
|
||||
# ── Version metadata ──────────────────────────────────────────────────────────
|
||||
# Pass these at build time:
|
||||
# docker build --build-arg GIT_SHA=$(git rev-parse HEAD) \
|
||||
# --build-arg BUILD_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ) .
|
||||
ARG GIT_SHA=dev
|
||||
ARG BUILD_TIME=unknown
|
||||
RUN echo "{\"sha\":\"${GIT_SHA}\",\"shortSha\":\"${GIT_SHA:0:7}\",\"buildTime\":\"${BUILD_TIME}\"}" \
|
||||
> /build/client/dist/version.json
|
||||
|
||||
FROM node:20-alpine AS production
|
||||
RUN apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont
|
||||
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
|
||||
@@ -25,5 +34,6 @@ COPY demo/ ./demo/
|
||||
COPY client/public/static ./client/dist/static
|
||||
RUN mkdir -p /data
|
||||
EXPOSE 3001
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD wget -qO- http://localhost:3001/api/health || exit 1
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD wget -qO- http://localhost:3001/api/health || exit 1
|
||||
CMD ["node", "server.js"]
|
||||
|
||||
314
MOBILE_RESPONSIVE.md
Normal file
314
MOBILE_RESPONSIVE.md
Normal file
@@ -0,0 +1,314 @@
|
||||
# Mobile-Responsive Implementation Guide
|
||||
|
||||
## Overview
|
||||
|
||||
This document describes the mobile-responsive updates implemented for the CPAS Tracker application. The design targets **standard phones (375px+ width)** with graceful degradation for smaller devices.
|
||||
|
||||
## Key Changes
|
||||
|
||||
### 1. **Responsive Utility Stylesheet** (`client/src/styles/mobile.css`)
|
||||
|
||||
A centralized CSS file providing:
|
||||
- Media query breakpoints (768px, 480px)
|
||||
- Touch-friendly tap targets (min 44px height)
|
||||
- iOS input zoom prevention (16px font size)
|
||||
- Utility classes for mobile layouts
|
||||
- Card-based layout helpers
|
||||
- Horizontal scroll containers
|
||||
|
||||
**Utility Classes:**
|
||||
- `.hide-mobile` - Hide on screens ≤768px
|
||||
- `.hide-tablet` - Hide on screens ≤1024px
|
||||
- `.mobile-full-width` - Full width on mobile
|
||||
- `.mobile-stack` - Stack flex items vertically
|
||||
- `.mobile-scroll-x` - Enable horizontal scrolling
|
||||
- `.mobile-card` - Card layout container
|
||||
- `.mobile-sticky-top` - Sticky header positioning
|
||||
|
||||
### 2. **App Navigation** (`client/src/App.jsx`)
|
||||
|
||||
**Desktop Behavior:**
|
||||
- Horizontal navigation bar
|
||||
- Logo left, tabs center, docs button right
|
||||
- Full tab labels displayed
|
||||
|
||||
**Mobile Behavior (768px):**
|
||||
- Logo centered with full width
|
||||
- Tabs stacked horizontally below logo
|
||||
- Docs button positioned absolutely top-right
|
||||
- Shortened tab labels ("📊 Dashboard" → "📊")
|
||||
- Flexible padding (40px → 16px)
|
||||
|
||||
**Features:**
|
||||
- `useMediaQuery()` hook for responsive detection
|
||||
- Dynamic style injection via `<style>` tag
|
||||
- Separate mobile CSS classes for targeted overrides
|
||||
|
||||
### 3. **Dashboard Layout** (`client/src/components/Dashboard.jsx`)
|
||||
|
||||
**Desktop View:**
|
||||
- Traditional HTML table layout
|
||||
- 7 columns (Index, Employee, Dept, Supervisor, Tier, Points, Violations)
|
||||
- Horizontal scrolling for overflow
|
||||
|
||||
**Mobile View (768px):**
|
||||
- Switches to card-based layout (DashboardMobile component)
|
||||
- Each employee = one card with vertical data rows
|
||||
- Touch-optimized tap targets
|
||||
- Improved readability with larger fonts
|
||||
|
||||
**Mobile Stat Cards:**
|
||||
- 2 columns on phones (480px+)
|
||||
- 1 column on small phones (<480px)
|
||||
- Reduced font sizes (28px → 24px)
|
||||
- Compact padding
|
||||
|
||||
**Toolbar Adjustments:**
|
||||
- Search input: 260px → 100% width
|
||||
- Buttons stack vertically
|
||||
- Full-width button styling
|
||||
|
||||
### 4. **Mobile Dashboard Component** (`client/src/components/DashboardMobile.jsx`)
|
||||
|
||||
A dedicated mobile-optimized employee card component:
|
||||
|
||||
**Card Structure:**
|
||||
```
|
||||
+--------------------------------+
|
||||
| Employee Name [Button] |
|
||||
| [At Risk Badge if applicable] |
|
||||
|--------------------------------|
|
||||
| Tier / Standing: [Badge] |
|
||||
| Active Points: [Large #] |
|
||||
| 90-Day Violations: [#] |
|
||||
| Department: [Name] |
|
||||
| Supervisor: [Name] |
|
||||
+--------------------------------+
|
||||
```
|
||||
|
||||
**Visual Features:**
|
||||
- At-risk employees: Gold border + dark gold background
|
||||
- Touch-friendly employee name buttons
|
||||
- Color-coded point displays matching tier colors
|
||||
- Compact spacing (12px margins)
|
||||
- Subtle shadows for depth
|
||||
|
||||
### 5. **Responsive Breakpoints**
|
||||
|
||||
| Breakpoint | Target Devices | Layout Changes |
|
||||
|------------|----------------|----------------|
|
||||
| **1024px** | Tablets & below | Reduced padding, simplified nav |
|
||||
| **768px** | Phones (landscape) | Card layouts, stacked navigation |
|
||||
| **480px** | Small phones | Single-column stats, minimal spacing |
|
||||
| **375px** | iPhone SE/6/7/8 | Optimized for minimum supported width |
|
||||
|
||||
### 6. **Touch Optimization**
|
||||
|
||||
**Tap Target Sizes:**
|
||||
- All buttons: 44px minimum height (iOS/Android guidelines)
|
||||
- Form inputs: 44px minimum height
|
||||
- Navigation tabs: 44px touch area
|
||||
|
||||
**Typography:**
|
||||
- Form inputs: 16px font size (prevents iOS zoom-in on focus)
|
||||
- Readable body text: 13-14px
|
||||
- Headers scale down appropriately
|
||||
|
||||
**Scrolling:**
|
||||
- `-webkit-overflow-scrolling: touch` for smooth momentum scrolling
|
||||
- Horizontal scroll on tables (desktop fallback)
|
||||
- Vertical card scrolling on mobile
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Media Query Hook
|
||||
|
||||
```javascript
|
||||
function useMediaQuery(query) {
|
||||
const [matches, setMatches] = useState(false);
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(query);
|
||||
if (media.matches !== matches) setMatches(media.matches);
|
||||
const listener = () => setMatches(media.matches);
|
||||
media.addEventListener('change', listener);
|
||||
return () => media.removeEventListener('change', listener);
|
||||
}, [matches, query]);
|
||||
return matches;
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
```javascript
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
```
|
||||
|
||||
### Conditional Rendering Pattern
|
||||
|
||||
```javascript
|
||||
{isMobile ? (
|
||||
<DashboardMobile employees={filtered} onEmployeeClick={setSelectedId} />
|
||||
) : (
|
||||
<table style={s.table}>
|
||||
{/* Desktop table layout */}
|
||||
</table>
|
||||
)}
|
||||
```
|
||||
|
||||
### Dynamic Style Injection
|
||||
|
||||
```javascript
|
||||
const mobileStyles = `
|
||||
@media (max-width: 768px) {
|
||||
.dashboard-wrap {
|
||||
padding: 16px !important;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{mobileStyles}</style>
|
||||
{/* Component JSX */}
|
||||
</>
|
||||
);
|
||||
```
|
||||
|
||||
## Testing Checklist
|
||||
|
||||
### Desktop (>768px)
|
||||
- [ ] Navigation displays horizontally
|
||||
- [ ] Dashboard shows full table
|
||||
- [ ] All columns visible
|
||||
- [ ] Docs button on right side
|
||||
- [ ] Full tab labels visible
|
||||
|
||||
### Tablet (768px - 1024px)
|
||||
- [ ] Reduced padding maintains readability
|
||||
- [ ] Stats cards wrap to 2-3 columns
|
||||
- [ ] Table scrolls horizontally if needed
|
||||
|
||||
### Mobile Portrait (375px - 768px)
|
||||
- [ ] Logo centered, tabs stacked
|
||||
- [ ] Dashboard shows card layout
|
||||
- [ ] Search input full width
|
||||
- [ ] Buttons stack vertically
|
||||
- [ ] Employee cards display all data
|
||||
- [ ] Tap targets ≥44px
|
||||
- [ ] No horizontal scroll required
|
||||
|
||||
### Small Mobile (<480px)
|
||||
- [ ] Stat cards single column
|
||||
- [ ] Text remains readable
|
||||
- [ ] No layout breakage
|
||||
- [ ] Footer wraps properly
|
||||
|
||||
### iOS-Specific
|
||||
- [ ] Input focus doesn't zoom page (16px font)
|
||||
- [ ] Smooth momentum scrolling
|
||||
- [ ] Tap highlights work correctly
|
||||
|
||||
### Android-Specific
|
||||
- [ ] Touch feedback visible
|
||||
- [ ] Back button behavior correct
|
||||
- [ ] Keyboard doesn't break layout
|
||||
|
||||
## Browser Support
|
||||
|
||||
- **Chrome/Edge:** 88+
|
||||
- **Firefox:** 85+
|
||||
- **Safari:** 14+
|
||||
- **iOS Safari:** 14+
|
||||
- **Chrome Android:** 88+
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
1. **Media query hook** re-renders only on breakpoint changes, not continuous resize
|
||||
2. **Card layout** renders fewer DOM elements than table on mobile
|
||||
3. **CSS injection** happens once per component mount
|
||||
4. **No external CSS libraries** (zero KB bundle increase)
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Phase 2 (Optional)
|
||||
- [ ] ViolationForm mobile optimization with multi-step wizard
|
||||
- [ ] Modal responsive sizing and animations
|
||||
- [ ] Swipe gestures for employee cards
|
||||
- [ ] Pull-to-refresh on mobile
|
||||
- [ ] Offline support with service workers
|
||||
|
||||
### Phase 3 (Advanced)
|
||||
- [ ] Progressive Web App (PWA) capabilities
|
||||
- [ ] Native app shell with Capacitor
|
||||
- [ ] Biometric authentication
|
||||
- [ ] Push notifications
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
client/src/
|
||||
├── App.jsx # Updated with mobile nav
|
||||
├── components/
|
||||
│ ├── Dashboard.jsx # Responsive table/card switch
|
||||
│ ├── DashboardMobile.jsx # Mobile card layout (NEW)
|
||||
│ └── ... # Other components
|
||||
└── styles/
|
||||
└── mobile.css # Responsive utilities (NEW)
|
||||
```
|
||||
|
||||
## Maintenance Notes
|
||||
|
||||
### Adding New Components
|
||||
|
||||
When creating new components, follow this pattern:
|
||||
|
||||
1. **Import mobile.css utility classes:**
|
||||
```javascript
|
||||
import '../styles/mobile.css';
|
||||
```
|
||||
|
||||
2. **Use media query hook:**
|
||||
```javascript
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
```
|
||||
|
||||
3. **Provide mobile-specific styles:**
|
||||
```javascript
|
||||
const mobileStyles = `
|
||||
@media (max-width: 768px) {
|
||||
.my-component { /* mobile overrides */ }
|
||||
}
|
||||
`;
|
||||
```
|
||||
|
||||
4. **Test on real devices** (Chrome DevTools is insufficient for touch testing)
|
||||
|
||||
### Debugging Tips
|
||||
|
||||
- Use Chrome DevTools Device Mode (Ctrl+Shift+M)
|
||||
- Test on actual devices when possible
|
||||
- Check console for media query match state
|
||||
- Verify tap target sizes with Chrome Lighthouse audit
|
||||
- Test keyboard behavior on Android
|
||||
|
||||
## Deployment
|
||||
|
||||
1. Merge `feature/mobile-responsive` into `master`
|
||||
2. Rebuild client bundle: `cd client && npm run build`
|
||||
3. Restart server
|
||||
4. Clear browser cache (Ctrl+Shift+R)
|
||||
5. Test on production URL with mobile devices
|
||||
|
||||
## Support
|
||||
|
||||
For issues or questions about mobile-responsive implementation:
|
||||
- Check browser console for errors
|
||||
- Verify `mobile.css` is loaded
|
||||
- Test with different screen sizes
|
||||
- Review media query breakpoints
|
||||
|
||||
---
|
||||
|
||||
**Branch:** `feature/mobile-responsive`
|
||||
**Target Width:** 375px+ (standard phones)
|
||||
**Last Updated:** March 8, 2026
|
||||
**Maintainer:** Jason Stedwell
|
||||
116
README.md
116
README.md
@@ -3,6 +3,8 @@
|
||||
Single-container Dockerized web app for CPAS violation documentation and workforce standing management.
|
||||
Built with **React + Vite** (frontend), **Node.js + Express** (backend), **SQLite** (database), and **Puppeteer** (PDF generation).
|
||||
|
||||
> © Jason Stedwell · [git.alwisp.com/jason/cpas](https://git.alwisp.com/jason/cpas)
|
||||
|
||||
---
|
||||
|
||||
## The only requirement on your machine: Docker Desktop
|
||||
@@ -113,6 +115,14 @@ Access the app at `http://10.2.0.14:3001` (or whatever static IP you assigned).
|
||||
|
||||
---
|
||||
|
||||
## Stakeholder Demo
|
||||
|
||||
A standalone demo page with synthetic data is available at `/demo` (e.g. `http://localhost:3001/demo`).
|
||||
It is served as a static route before the SPA catch-all and requires no authentication.
|
||||
Useful for showing the app to stakeholders without exposing live employee data.
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
### Company Dashboard
|
||||
@@ -120,8 +130,9 @@ Access the app at `http://10.2.0.14:3001` (or whatever static IP you assigned).
|
||||
- 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
|
||||
- **📋 Audit Log** button — filterable, paginated view of all system write actions
|
||||
|
||||
### Violation Form
|
||||
- Select existing employee or enter new employee by name
|
||||
@@ -170,6 +181,11 @@ Access the app at `http://10.2.0.14:3001` (or whatever static IP you assigned).
|
||||
- Slide-in animation; stacks up to 5 notifications simultaneously
|
||||
- Consistent dark theme styling matching the rest of the UI
|
||||
|
||||
### App Footer
|
||||
- **© Jason Stedwell** copyright with auto-advancing year
|
||||
- **Live dev ticker**: real-time elapsed counter since first commit (`2026-03-06`), ticking every second in `Xd HHh MMm SSs` format with a pulsing green dot
|
||||
- **Gitea repo link** with icon — links directly to `git.alwisp.com/jason/cpas`
|
||||
|
||||
### CPAS Tier System
|
||||
|
||||
| Points | Tier | Label |
|
||||
@@ -209,7 +225,7 @@ Scores are computed over a **rolling 90-day window** (negated violations exclude
|
||||
| GET | `/api/dashboard` | All employees with active points + violation counts |
|
||||
| POST | `/api/violations` | Log a new violation (accepts `acknowledged_by`, `acknowledged_date`) |
|
||||
| GET | `/api/violations/employee/:id` | Violation history with resolutions + amendment counts |
|
||||
| PATCH | `/api/violations/:id/negate` | Negate a violation (soft delete + resolution record) |
|
||||
| PATCH | `/api/violations/:id/negated` | 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 |
|
||||
@@ -223,42 +239,43 @@ Scores are computed over a **rolling 90-day window** (negated violations exclude
|
||||
|
||||
```
|
||||
cpas/
|
||||
├── Dockerfile # Multi-stage: builds React + runs Express w/ Chromium
|
||||
├── Dockerfile # Multi-stage: builds React + runs Express w/ Chromium
|
||||
├── .dockerignore
|
||||
├── package.json # Backend (Express) deps
|
||||
├── server.js # API + static file server
|
||||
├── package.json # Backend (Express) deps
|
||||
├── server.js # API + static file server
|
||||
├── db/
|
||||
│ ├── schema.sql # Tables + 90-day active score view
|
||||
│ ├── schema.sql # Tables + 90-day active score view
|
||||
│ └── database.js # SQLite connection (better-sqlite3) + auto-migrations
|
||||
├── pdf/
|
||||
│ ├── generator.js # Puppeteer PDF generation
|
||||
│ └── template.js # HTML template (loads logo from disk, ack signature rendering)
|
||||
├── demo/ # Static stakeholder demo page (served at /demo)
|
||||
└── client/ # React frontend (Vite)
|
||||
├── package.json
|
||||
├── vite.config.js
|
||||
├── index.html
|
||||
└── src/
|
||||
├── main.jsx
|
||||
├── App.jsx
|
||||
├── App.jsx # Root app + AppFooter (copyright, dev ticker, Gitea link)
|
||||
├── data/
|
||||
│ └── violations.js # All CPAS violation definitions + groups
|
||||
│ └── violations.js # All CPAS violation definitions + groups
|
||||
├── hooks/
|
||||
│ └── useEmployeeIntelligence.js # Score + history hook
|
||||
│ └── useEmployeeIntelligence.js # Score + history hook
|
||||
└── components/
|
||||
├── CpasBadge.jsx # Tier badge + color logic
|
||||
├── TierWarning.jsx # Pre-submit tier crossing alert
|
||||
├── Dashboard.jsx # Company-wide leaderboard + audit log trigger
|
||||
├── ViolationForm.jsx # Violation entry form + ack signature fields
|
||||
├── EmployeeModal.jsx # Employee profile + history modal
|
||||
├── EditEmployeeModal.jsx # Employee edit + merge duplicate
|
||||
├── AmendViolationModal.jsx # Non-scoring field amendment + diff history
|
||||
├── AuditLog.jsx # Filterable audit log panel
|
||||
├── NegateModal.jsx # Negate/resolve violation dialog
|
||||
├── ViolationHistory.jsx # Violation list component
|
||||
├── ExpirationTimeline.jsx # Per-violation 90-day roll-off countdown
|
||||
├── EmployeeNotes.jsx # Inline notes editor with quick-add HR tags
|
||||
├── ToastProvider.jsx # Global toast notification system + useToast hook
|
||||
└── ReadmeModal.jsx # In-app admin documentation panel
|
||||
├── CpasBadge.jsx # Tier badge + color logic
|
||||
├── TierWarning.jsx # Pre-submit tier crossing alert
|
||||
├── Dashboard.jsx # Company-wide leaderboard + audit log trigger
|
||||
├── ViolationForm.jsx # Violation entry form + ack signature fields
|
||||
├── EmployeeModal.jsx # Employee profile + history modal
|
||||
├── EditEmployeeModal.jsx # Employee edit + merge duplicate
|
||||
├── AmendViolationModal.jsx # Non-scoring field amendment + diff history
|
||||
├── AuditLog.jsx # Filterable audit log panel
|
||||
├── NegateModal.jsx # Negate/resolve violation dialog
|
||||
├── ViolationHistory.jsx # Violation list component
|
||||
├── ExpirationTimeline.jsx # Per-violation 90-day roll-off countdown
|
||||
├── EmployeeNotes.jsx # Inline notes editor with quick-add HR tags
|
||||
├── ToastProvider.jsx # Global toast notification system + useToast hook
|
||||
└── ReadmeModal.jsx # In-app admin documentation panel
|
||||
```
|
||||
|
||||
---
|
||||
@@ -319,32 +336,61 @@ Point values, violation type, and incident date are **immutable** after submissi
|
||||
| 6 | In-app documentation | Admin usage guide and feature map accessible from the navbar |
|
||||
| 7 | Acknowledgment signature field | "Received by employee" name + date on the violation form; renders on the PDF replacing blank signature lines with recorded acknowledgment |
|
||||
| 7 | Toast notification system | Global success/error/warning/info notifications for all user actions; auto-dismiss with progress bar; consistent dark theme |
|
||||
| 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 |
|
||||
|
||||
---
|
||||
|
||||
### 📋 Proposed
|
||||
|
||||
Effort ratings: 🟢 Low · 🟡 Medium · 🔴 High
|
||||
|
||||
#### Quick Wins (High value, low effort)
|
||||
|
||||
| Feature | Effort | Description |
|
||||
|---------|--------|-------------|
|
||||
| Column sort on dashboard | 🟢 | Click `Tier`, `Active Points`, or `Department` headers to sort in-place; one `useState` + comparator, no API changes |
|
||||
| Department filter on dashboard | 🟢 | Multi-select dropdown to scope the employee table by department; `DEPARTMENTS` constant already exists |
|
||||
| Keyboard shortcut: New Violation | 🟢 | `N` key triggers tab switch to the violation form; ~5 lines of code |
|
||||
|
||||
#### Reporting & Analytics
|
||||
- **Violation trends chart** — line/bar chart of violations per day/week/month, filterable by department or supervisor; useful for identifying systemic patterns vs. individual incidents
|
||||
- **Department heat map** — grid view showing violation density and average CPAS score by department; helps supervisors identify team-level risk
|
||||
- **CSV / Excel export** — bulk export of violations or dashboard data for external reporting or payroll integration
|
||||
|
||||
| Feature | Effort | Description |
|
||||
|---------|--------|-------------|
|
||||
| Violation trend chart | 🟡 | Line/bar chart of violations per day/week/month, filterable by department or supervisor; useful for identifying systemic patterns |
|
||||
| Department heat map | 🟡 | Grid view showing violation density and average CPAS score by department; helps supervisors identify team-level risk |
|
||||
| Violation sparklines per employee | 🟡 | Tiny inline bar chart of points over the last 6 months in the employee modal |
|
||||
|
||||
#### Employee Management
|
||||
- **Supervisor view** — scoped dashboard showing only the employees under a given supervisor, useful for multi-supervisor environments
|
||||
|
||||
| Feature | Effort | Description |
|
||||
|---------|--------|-------------|
|
||||
| Supervisor scoped view | 🟡 | Dashboard filtered to a supervisor's direct reports, accessible via URL param (`?supervisor=Name`); no schema changes required |
|
||||
| Employee photo / avatar | 🟢 | Optional avatar upload stored alongside the employee record; shown in the profile modal and dashboard row |
|
||||
|
||||
#### Violation Workflow
|
||||
- **Draft / pending violations** — save a violation as draft before finalizing, useful when incidents need review before being officially logged
|
||||
- **Bulk violation import** — CSV import for migrating historical records from paper logs or a prior system
|
||||
|
||||
| Feature | Effort | Description |
|
||||
|---------|--------|-------------|
|
||||
| Draft / pending violations | 🟡 | Save a violation as draft before finalizing; useful when incidents need review before being officially logged |
|
||||
| Violation templates | 🟢 | Pre-fill the form with a saved violation type + common details for frequently logged incidents |
|
||||
|
||||
#### Notifications & Escalation
|
||||
- **Tier escalation alerts** — email or in-app notification when an employee crosses into Tier 2+ so the relevant supervisor is automatically informed
|
||||
- **Scheduled summary digest** — weekly email to supervisors listing their employees' current standings and any approaching tier thresholds
|
||||
- **At-risk threshold configuration** — make the "at-risk" warning threshold (currently hardcoded at 2 pts) configurable per deployment
|
||||
|
||||
| Feature | Effort | Description |
|
||||
|---------|--------|-------------|
|
||||
| Tier escalation alerts | 🟡 | Email or in-app notification when an employee crosses into Tier 2+ so the relevant supervisor is automatically informed |
|
||||
| At-risk threshold config | 🟢 | Make the "at-risk" warning threshold (currently hardcoded at 2 pts) configurable per deployment via an env var |
|
||||
| version.json / build badge | 🟢 | Inject git SHA + build timestamp into a static file during `docker build`; surfaced in the footer and `/api/health` |
|
||||
|
||||
#### Infrastructure & Ops
|
||||
- **Multi-user auth** — simple login with role-based access (admin, supervisor, read-only); currently the app has no auth and is assumed to run on a trusted internal network
|
||||
- **Automated DB backup** — cron job or Docker health hook to snapshot `/data/cpas.db` to a mounted backup volume or remote location on a schedule
|
||||
- **Dark/light theme toggle** — the UI is currently dark-only; a toggle would improve usability in bright environments
|
||||
|
||||
| Feature | Effort | Description |
|
||||
|---------|--------|-------------|
|
||||
| Multi-user auth | 🔴 | Simple login with role-based access (admin, supervisor, read-only); currently the app runs on a trusted internal network with no auth |
|
||||
| Automated DB backup | 🟡 | Cron job or Docker health hook to snapshot `/data/cpas.db` to a mounted backup volume or remote location on a schedule |
|
||||
| Dark/light theme toggle | 🟡 | The UI is currently dark-only; a toggle would improve usability in bright environments |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CPAS Violation Tracker</title>
|
||||
<style>
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
html, body { margin: 0; padding: 0; height: 100%; }
|
||||
#root { height: 100%; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
5
client/public/version.json
Normal file
5
client/public/version.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"sha": "dev",
|
||||
"shortSha": "dev",
|
||||
"buildTime": null
|
||||
}
|
||||
@@ -1,17 +1,126 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import ViolationForm from './components/ViolationForm';
|
||||
import Dashboard from './components/Dashboard';
|
||||
import ReadmeModal from './components/ReadmeModal';
|
||||
import ToastProvider from './components/ToastProvider';
|
||||
import './styles/mobile.css';
|
||||
|
||||
const REPO_URL = 'https://git.alwisp.com/jason/cpas';
|
||||
// TODO [CLEANUP #18]: DevTicker is a dev vanity widget that ships to prod.
|
||||
// Either gate with `import.meta.env.DEV` or remove from the footer.
|
||||
const PROJECT_START = new Date('2026-03-06T11:33:32-06:00');
|
||||
|
||||
function elapsed(from) {
|
||||
const totalSec = Math.floor((Date.now() - from.getTime()) / 1000);
|
||||
const d = Math.floor(totalSec / 86400);
|
||||
const h = Math.floor((totalSec % 86400) / 3600);
|
||||
const m = Math.floor((totalSec % 3600) / 60);
|
||||
const s = totalSec % 60;
|
||||
return `${d}d ${String(h).padStart(2,'0')}h ${String(m).padStart(2,'0')}m ${String(s).padStart(2,'0')}s`;
|
||||
}
|
||||
|
||||
function DevTicker() {
|
||||
const [tick, setTick] = useState(() => elapsed(PROJECT_START));
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setTick(elapsed(PROJECT_START)), 1000);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
return (
|
||||
<span title="Time since first commit" style={{ display: 'inline-flex', alignItems: 'center', gap: '5px' }}>
|
||||
<span style={{
|
||||
width: '7px', height: '7px', borderRadius: '50%',
|
||||
background: '#22c55e', display: 'inline-block',
|
||||
animation: 'cpas-pulse 1.4s ease-in-out infinite',
|
||||
}} />
|
||||
{tick}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function GiteaIcon() {
|
||||
return (
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style={{ verticalAlign: 'middle' }}>
|
||||
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z"/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function AppFooter({ version }) {
|
||||
const year = new Date().getFullYear();
|
||||
const sha = version?.shortSha || null;
|
||||
const built = version?.buildTime
|
||||
? new Date(version.buildTime).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
|
||||
: null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`
|
||||
@keyframes cpas-pulse {
|
||||
0%, 100% { opacity: 1; transform: scale(1); }
|
||||
50% { opacity: 0.4; transform: scale(0.75); }
|
||||
}
|
||||
|
||||
/* Mobile-specific footer adjustments */
|
||||
@media (max-width: 768px) {
|
||||
.footer-content {
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
font-size: 10px;
|
||||
padding: 10px 16px;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
<footer style={sf.footer} className="footer-content">
|
||||
<span style={sf.copy}>© {year} Jason Stedwell</span>
|
||||
<span style={sf.sep}>·</span>
|
||||
<DevTicker />
|
||||
<span style={sf.sep}>·</span>
|
||||
<a href={REPO_URL} target="_blank" rel="noopener noreferrer" style={sf.link}>
|
||||
<GiteaIcon /> cpas
|
||||
</a>
|
||||
{sha && sha !== 'dev' && (
|
||||
<>
|
||||
<span style={sf.sep}>·</span>
|
||||
<a
|
||||
href={`${REPO_URL}/commit/${version.sha}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
style={sf.link}
|
||||
title={built ? `Built ${built}` : 'View commit'}
|
||||
>
|
||||
{sha}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</footer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const tabs = [
|
||||
{ id: 'dashboard', label: '📊 Dashboard' },
|
||||
{ id: 'violation', label: '+ New Violation' },
|
||||
];
|
||||
|
||||
// TODO [MAJOR #8]: Move to src/hooks/useMediaQuery.js — this hook is duplicated
|
||||
// verbatim in Dashboard.jsx. Also remove `matches` from the useEffect dep array
|
||||
// (it changes inside the effect, which can cause a loop on strict-mode mount).
|
||||
function useMediaQuery(query) {
|
||||
const [matches, setMatches] = useState(false);
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(query);
|
||||
if (media.matches !== matches) setMatches(media.matches);
|
||||
const listener = () => setMatches(media.matches);
|
||||
media.addEventListener('change', listener);
|
||||
return () => media.removeEventListener('change', listener);
|
||||
}, [matches, query]);
|
||||
return matches;
|
||||
}
|
||||
|
||||
const s = {
|
||||
app: { minHeight: '100vh', background: '#050608', fontFamily: "'Segoe UI', Arial, sans-serif", color: '#f8f9fa' },
|
||||
nav: { background: '#000000', padding: '0 40px', display: 'flex', alignItems: 'center', gap: 0, borderBottom: '1px solid #333' },
|
||||
app: { minHeight: '100vh', background: '#050608', fontFamily: "'Segoe UI', Arial, sans-serif", color: '#f8f9fa', display: 'flex', flexDirection: 'column' },
|
||||
nav: { background: '#000000', padding: '0 40px', display: 'flex', alignItems: 'center', gap: 0, borderBottom: '1px solid #333' },
|
||||
logoWrap: { display: 'flex', alignItems: 'center', marginRight: '32px', padding: '14px 0' },
|
||||
logoImg: { height: '28px', marginRight: '10px' },
|
||||
logoText: { color: '#f8f9fa', fontWeight: 800, fontSize: '18px', letterSpacing: '0.5px' },
|
||||
@@ -22,7 +131,6 @@ const s = {
|
||||
cursor: 'pointer', fontWeight: active ? 700 : 400, fontSize: '14px',
|
||||
background: 'none', border: 'none',
|
||||
}),
|
||||
// Docs button sits flush-right in the nav
|
||||
docsBtn: {
|
||||
marginLeft: 'auto',
|
||||
background: 'none',
|
||||
@@ -38,37 +146,133 @@ const s = {
|
||||
alignItems: 'center',
|
||||
gap: '6px',
|
||||
},
|
||||
main: { flex: 1 },
|
||||
card: { maxWidth: '1100px', margin: '30px auto', background: '#111217', borderRadius: '10px', boxShadow: '0 2px 16px rgba(0,0,0,0.6)', border: '1px solid #222' },
|
||||
};
|
||||
|
||||
// Mobile-responsive style overrides
|
||||
const mobileStyles = `
|
||||
@media (max-width: 768px) {
|
||||
.app-nav {
|
||||
padding: 0 16px !important;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
}
|
||||
.logo-wrap {
|
||||
margin-right: 0 !important;
|
||||
padding: 12px 0 !important;
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
border-bottom: 1px solid #1a1b22;
|
||||
}
|
||||
.nav-tabs {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
justify-content: space-around;
|
||||
}
|
||||
.nav-tab {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
padding: 14px 8px !important;
|
||||
font-size: 13px !important;
|
||||
}
|
||||
.docs-btn {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
padding: 4px 10px !important;
|
||||
font-size: 11px !important;
|
||||
}
|
||||
.docs-btn span:first-child {
|
||||
display: none;
|
||||
}
|
||||
.main-card {
|
||||
margin: 12px !important;
|
||||
border-radius: 8px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.logo-text {
|
||||
font-size: 16px !important;
|
||||
}
|
||||
.logo-img {
|
||||
height: 24px !important;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const sf = {
|
||||
footer: {
|
||||
borderTop: '1px solid #1a1b22',
|
||||
padding: '12px 40px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '12px',
|
||||
fontSize: '11px',
|
||||
color: 'rgba(248,249,250,0.35)',
|
||||
background: '#000',
|
||||
flexShrink: 0,
|
||||
},
|
||||
copy: { color: 'rgba(248,249,250,0.35)' },
|
||||
sep: { color: 'rgba(248,249,250,0.15)' },
|
||||
link: {
|
||||
color: 'rgba(248,249,250,0.35)',
|
||||
textDecoration: 'none',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
gap: '4px',
|
||||
transition: 'color 0.15s',
|
||||
},
|
||||
};
|
||||
|
||||
export default function App() {
|
||||
const [tab, setTab] = useState('dashboard');
|
||||
const [showReadme, setShowReadme] = useState(false);
|
||||
const [version, setVersion] = useState(null);
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/version.json')
|
||||
.then(r => r.ok ? r.json() : null)
|
||||
.then(v => { if (v) setVersion(v); })
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
{/* TODO [MAJOR #9]: Inline <style> tags re-inject on every render and duplicate
|
||||
the same block from Dashboard.jsx. Move all shared mobile CSS to mobile.css */}
|
||||
<style>{mobileStyles}</style>
|
||||
<div style={s.app}>
|
||||
<nav style={s.nav}>
|
||||
<div style={s.logoWrap}>
|
||||
<img src="/static/mpm-logo.png" alt="MPM" style={s.logoImg} />
|
||||
<div style={s.logoText}>CPAS Tracker</div>
|
||||
<nav style={s.nav} className="app-nav">
|
||||
<div style={s.logoWrap} className="logo-wrap">
|
||||
<img src="/static/mpm-logo.png" alt="MPM" style={s.logoImg} className="logo-img" />
|
||||
<div style={s.logoText} className="logo-text">CPAS Tracker</div>
|
||||
</div>
|
||||
|
||||
{tabs.map(t => (
|
||||
<button key={t.id} style={s.tab(tab === t.id)} onClick={() => setTab(t.id)}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
<div className="nav-tabs">
|
||||
{tabs.map(t => (
|
||||
<button key={t.id} style={s.tab(tab === t.id)} className="nav-tab" onClick={() => setTab(t.id)}>
|
||||
{/* TODO [MINOR #17]: first .replace('📊 ', '📊 ') replaces string with itself — no-op. Remove it. */}
|
||||
{isMobile ? t.label.replace('📊 ', '📊 ').replace('+ New ', '+ ') : t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button style={s.docsBtn} onClick={() => setShowReadme(true)} title="Open admin documentation">
|
||||
<button style={s.docsBtn} className="docs-btn" onClick={() => setShowReadme(true)} title="Open admin documentation">
|
||||
<span>?</span> Docs
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<div style={s.card}>
|
||||
{tab === 'dashboard' ? <Dashboard /> : <ViolationForm />}
|
||||
<div style={s.main}>
|
||||
<div style={s.card} className="main-card">
|
||||
{tab === 'dashboard' ? <Dashboard /> : <ViolationForm />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AppFooter version={version} />
|
||||
|
||||
{showReadme && <ReadmeModal onClose={() => setShowReadme(false)} />}
|
||||
</div>
|
||||
</ToastProvider>
|
||||
|
||||
@@ -112,6 +112,9 @@ export default function AuditLog({ onClose }) {
|
||||
const [filterAction, setFilterAction] = useState('');
|
||||
const LIMIT = 50;
|
||||
|
||||
// TODO [MAJOR #5]: `offset` in useCallback deps causes the callback to be
|
||||
// re-created on each load-more, which triggers the filterType/filterAction
|
||||
// useEffect unexpectedly. Track offset in a useRef instead.
|
||||
const load = useCallback((reset = false) => {
|
||||
setLoading(true);
|
||||
const o = reset ? 0 : offset;
|
||||
@@ -121,7 +124,8 @@ export default function AuditLog({ onClose }) {
|
||||
axios.get('/api/audit', { params })
|
||||
.then(r => {
|
||||
const data = r.data;
|
||||
// Client-side action filter (cheap enough at this scale)
|
||||
// TODO [MINOR]: client-side action filter means server still fetches LIMIT
|
||||
// rows before filtering — add server-side `action` param to /api/audit.
|
||||
const filtered = filterAction ? data.filter(e => e.action === filterAction) : data;
|
||||
setEntries(prev => reset ? filtered : [...prev, ...filtered]);
|
||||
setHasMore(data.length === LIMIT);
|
||||
|
||||
@@ -3,6 +3,7 @@ import axios from 'axios';
|
||||
import CpasBadge, { getTier } from './CpasBadge';
|
||||
import EmployeeModal from './EmployeeModal';
|
||||
import AuditLog from './AuditLog';
|
||||
import DashboardMobile from './DashboardMobile';
|
||||
|
||||
const AT_RISK_THRESHOLD = 2;
|
||||
|
||||
@@ -28,15 +29,38 @@ function isAtRisk(points) {
|
||||
return boundary !== null && (boundary - points) <= AT_RISK_THRESHOLD;
|
||||
}
|
||||
|
||||
// TODO [MAJOR #8]: Same hook is defined in App.jsx — extract to src/hooks/useMediaQuery.js
|
||||
// Also: `matches` in the dep array can cause a loop on strict-mode initial mount.
|
||||
function useMediaQuery(query) {
|
||||
const [matches, setMatches] = useState(false);
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(query);
|
||||
if (media.matches !== matches) setMatches(media.matches);
|
||||
const listener = () => setMatches(media.matches);
|
||||
media.addEventListener('change', listener);
|
||||
return () => media.removeEventListener('change', listener);
|
||||
}, [matches, query]);
|
||||
return matches;
|
||||
}
|
||||
|
||||
// Filter keys
|
||||
const FILTER_NONE = null;
|
||||
const FILTER_TOTAL = 'total';
|
||||
const FILTER_ELITE = 'elite';
|
||||
const FILTER_ACTIVE = 'active';
|
||||
const FILTER_AT_RISK = 'at_risk';
|
||||
|
||||
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' },
|
||||
statCard: { flex: '1', minWidth: '140px', background: '#181924', border: '1px solid #303136', borderRadius: '8px', padding: '16px', textAlign: 'center', cursor: 'pointer', transition: 'border-color 0.15s, box-shadow 0.15s' },
|
||||
statCardActive: { boxShadow: '0 0 0 2px #d4af37', border: '1px solid #d4af37' },
|
||||
statNum: { fontSize: '28px', fontWeight: 800, color: '#f8f9fa' },
|
||||
statLbl: { fontSize: '11px', color: '#b5b5c0', marginTop: '4px' },
|
||||
filterBadge: { fontSize: '10px', color: '#d4af37', marginTop: '4px', fontWeight: 600 },
|
||||
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' },
|
||||
@@ -49,6 +73,55 @@ const s = {
|
||||
auditBtn: { padding: '9px 18px', background: 'none', color: '#9ca0b8', border: '1px solid #2a2b3a', borderRadius: '6px', cursor: 'pointer', fontWeight: 600, fontSize: '13px' },
|
||||
};
|
||||
|
||||
// Mobile styles
|
||||
const mobileStyles = `
|
||||
@media (max-width: 768px) {
|
||||
.dashboard-wrap {
|
||||
padding: 16px !important;
|
||||
}
|
||||
.dashboard-header {
|
||||
flex-direction: column;
|
||||
align-items: flex-start !important;
|
||||
}
|
||||
.dashboard-title {
|
||||
font-size: 20px !important;
|
||||
}
|
||||
.dashboard-subtitle {
|
||||
font-size: 12px !important;
|
||||
}
|
||||
.dashboard-stats {
|
||||
gap: 10px !important;
|
||||
}
|
||||
.dashboard-stat-card {
|
||||
min-width: calc(50% - 5px) !important;
|
||||
padding: 12px !important;
|
||||
}
|
||||
.stat-num {
|
||||
font-size: 24px !important;
|
||||
}
|
||||
.stat-lbl {
|
||||
font-size: 10px !important;
|
||||
}
|
||||
.toolbar-right {
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
}
|
||||
.search-input {
|
||||
width: 100% !important;
|
||||
}
|
||||
.toolbar-btn {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.dashboard-stat-card {
|
||||
min-width: 100% !important;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export default function Dashboard() {
|
||||
const [employees, setEmployees] = useState([]);
|
||||
const [filtered, setFiltered] = useState([]);
|
||||
@@ -56,6 +129,8 @@ export default function Dashboard() {
|
||||
const [selectedId, setSelectedId] = useState(null);
|
||||
const [showAudit, setShowAudit] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [activeFilter, setActiveFilter] = useState(FILTER_NONE);
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
@@ -66,65 +141,148 @@ export default function Dashboard() {
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
// Apply search + badge filter together
|
||||
useEffect(() => {
|
||||
const q = search.toLowerCase();
|
||||
setFiltered(employees.filter(e =>
|
||||
e.name.toLowerCase().includes(q) ||
|
||||
(e.department || '').toLowerCase().includes(q) ||
|
||||
(e.supervisor || '').toLowerCase().includes(q)
|
||||
));
|
||||
}, [search, employees]);
|
||||
let base = employees;
|
||||
|
||||
if (activeFilter === FILTER_ELITE) {
|
||||
base = base.filter(e => e.active_points >= 0 && e.active_points <= 4);
|
||||
} else if (activeFilter === FILTER_ACTIVE) {
|
||||
base = base.filter(e => e.active_points > 0);
|
||||
} else if (activeFilter === FILTER_AT_RISK) {
|
||||
base = base.filter(e => isAtRisk(e.active_points));
|
||||
}
|
||||
// FILTER_TOTAL and FILTER_NONE show all
|
||||
|
||||
if (q) {
|
||||
base = base.filter(e =>
|
||||
e.name.toLowerCase().includes(q) ||
|
||||
(e.department || '').toLowerCase().includes(q) ||
|
||||
(e.supervisor || '').toLowerCase().includes(q)
|
||||
);
|
||||
}
|
||||
|
||||
setFiltered(base);
|
||||
}, [search, employees, activeFilter]);
|
||||
|
||||
const atRiskCount = employees.filter(e => isAtRisk(e.active_points)).length;
|
||||
const activeCount = employees.filter(e => e.active_points > 0).length;
|
||||
const cleanCount = employees.filter(e => e.active_points === 0).length;
|
||||
// Elite Standing: 0–4 pts (Tier 0-1)
|
||||
const eliteCount = employees.filter(e => e.active_points >= 0 && e.active_points <= 4).length;
|
||||
const maxPoints = employees.reduce((m, e) => Math.max(m, e.active_points), 0);
|
||||
|
||||
function handleBadgeClick(filterKey) {
|
||||
setActiveFilter(prev => prev === filterKey ? FILTER_NONE : filterKey);
|
||||
}
|
||||
|
||||
function cardStyle(filterKey, extra = {}) {
|
||||
const isActive = activeFilter === filterKey;
|
||||
return {
|
||||
...s.statCard,
|
||||
...(isActive ? s.statCardActive : {}),
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={s.wrap}>
|
||||
<div style={s.header}>
|
||||
{/* TODO [MAJOR #9]: Same mobileStyles block exists in App.jsx. Move to mobile.css */}
|
||||
<style>{mobileStyles}</style>
|
||||
<div style={s.wrap} className="dashboard-wrap">
|
||||
<div style={s.header} className="dashboard-header">
|
||||
<div>
|
||||
<div style={s.title}>Company Dashboard</div>
|
||||
<div style={s.subtitle}>Click any employee name to view their full profile</div>
|
||||
<div style={s.title} className="dashboard-title">Company Dashboard</div>
|
||||
<div style={s.subtitle} className="dashboard-subtitle">
|
||||
Click any employee name to view their full profile
|
||||
{activeFilter && activeFilter !== FILTER_NONE && (
|
||||
<span style={{ marginLeft: '10px', color: '#d4af37', fontWeight: 600 }}>
|
||||
· Filtered: {activeFilter === FILTER_ELITE ? 'Elite Standing (0–4 pts)' : activeFilter === FILTER_ACTIVE ? 'With Active Points' : activeFilter === FILTER_AT_RISK ? 'At Risk' : 'All'}
|
||||
<button
|
||||
onClick={() => setActiveFilter(FILTER_NONE)}
|
||||
style={{ marginLeft: '6px', background: 'none', border: 'none', color: '#9ca0b8', cursor: 'pointer', fontSize: '12px' }}
|
||||
title="Clear filter"
|
||||
>✕</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div style={s.toolbarRight}>
|
||||
<div style={s.toolbarRight} className="toolbar-right">
|
||||
<input
|
||||
style={s.search}
|
||||
className="search-input"
|
||||
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>
|
||||
<button style={s.auditBtn} className="toolbar-btn" onClick={() => setShowAudit(true)}>📋 Audit Log</button>
|
||||
<button style={s.refreshBtn} className="toolbar-btn" onClick={load}>↻ Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={s.statsRow}>
|
||||
<div style={s.statCard}>
|
||||
<div style={s.statNum}>{employees.length}</div>
|
||||
<div style={s.statLbl}>Total Employees</div>
|
||||
<div style={s.statsRow} className="dashboard-stats">
|
||||
{/* Total Employees — clicking shows all */}
|
||||
<div
|
||||
style={cardStyle(FILTER_TOTAL)}
|
||||
className="dashboard-stat-card"
|
||||
onClick={() => handleBadgeClick(FILTER_TOTAL)}
|
||||
title="Click to show all employees"
|
||||
>
|
||||
<div style={s.statNum} className="stat-num">{employees.length}</div>
|
||||
<div style={s.statLbl} className="stat-lbl">Total Employees</div>
|
||||
{activeFilter === FILTER_TOTAL && <div style={s.filterBadge}>▼ Showing All</div>}
|
||||
</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #28a745' }}>
|
||||
<div style={{ ...s.statNum, color: '#6ee7b7' }}>{cleanCount}</div>
|
||||
<div style={s.statLbl}>Elite Standing (0 pts)</div>
|
||||
|
||||
{/* Elite Standing: 0–4 pts */}
|
||||
<div
|
||||
style={cardStyle(FILTER_ELITE, { borderTop: '3px solid #28a745' })}
|
||||
className="dashboard-stat-card"
|
||||
onClick={() => handleBadgeClick(FILTER_ELITE)}
|
||||
title="Click to filter: Elite Standing (0–4 pts)"
|
||||
>
|
||||
<div style={{ ...s.statNum, color: '#6ee7b7' }} className="stat-num">{eliteCount}</div>
|
||||
<div style={s.statLbl} className="stat-lbl">Elite Standing (0–4 pts)</div>
|
||||
{activeFilter === FILTER_ELITE && <div style={s.filterBadge}>▼ Filtered</div>}
|
||||
</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #d4af37' }}>
|
||||
<div style={{ ...s.statNum, color: '#ffd666' }}>{activeCount}</div>
|
||||
<div style={s.statLbl}>With Active Points</div>
|
||||
|
||||
{/* With Active Points */}
|
||||
<div
|
||||
style={cardStyle(FILTER_ACTIVE, { borderTop: '3px solid #d4af37' })}
|
||||
className="dashboard-stat-card"
|
||||
onClick={() => handleBadgeClick(FILTER_ACTIVE)}
|
||||
title="Click to filter: employees with active points"
|
||||
>
|
||||
<div style={{ ...s.statNum, color: '#ffd666' }} className="stat-num">{activeCount}</div>
|
||||
<div style={s.statLbl} className="stat-lbl">With Active Points</div>
|
||||
{activeFilter === FILTER_ACTIVE && <div style={s.filterBadge}>▼ Filtered</div>}
|
||||
</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #ffb020' }}>
|
||||
<div style={{ ...s.statNum, color: '#ffdf8a' }}>{atRiskCount}</div>
|
||||
<div style={s.statLbl}>At Risk (≤{AT_RISK_THRESHOLD} pts to next tier)</div>
|
||||
|
||||
{/* At Risk */}
|
||||
<div
|
||||
style={cardStyle(FILTER_AT_RISK, { borderTop: '3px solid #ffb020' })}
|
||||
className="dashboard-stat-card"
|
||||
onClick={() => handleBadgeClick(FILTER_AT_RISK)}
|
||||
title={`Click to filter: at risk (≤${AT_RISK_THRESHOLD} pts to next tier)`}
|
||||
>
|
||||
<div style={{ ...s.statNum, color: '#ffdf8a' }} className="stat-num">{atRiskCount}</div>
|
||||
<div style={s.statLbl} className="stat-lbl">At Risk (≤{AT_RISK_THRESHOLD} pts to next tier)</div>
|
||||
{activeFilter === FILTER_AT_RISK && <div style={s.filterBadge}>▼ Filtered</div>}
|
||||
</div>
|
||||
<div style={{ ...s.statCard, borderTop: '3px solid #c0392b' }}>
|
||||
<div style={{ ...s.statNum, color: '#ff8a80' }}>{maxPoints}</div>
|
||||
<div style={s.statLbl}>Highest Active Score</div>
|
||||
|
||||
{/* Highest Score — display only, no filter */}
|
||||
<div
|
||||
style={{ ...s.statCard, borderTop: '3px solid #c0392b', cursor: 'default' }}
|
||||
className="dashboard-stat-card"
|
||||
>
|
||||
<div style={{ ...s.statNum, color: '#ff8a80' }} className="stat-num">{maxPoints}</div>
|
||||
<div style={s.statLbl} className="stat-lbl">Highest Active Score</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<p style={{ color: '#77798a', textAlign: 'center', padding: '40px' }}>Loading…</p>
|
||||
) : isMobile ? (
|
||||
<DashboardMobile employees={filtered} onEmployeeClick={setSelectedId} />
|
||||
) : (
|
||||
<table style={s.table}>
|
||||
<thead>
|
||||
|
||||
157
client/src/components/DashboardMobile.jsx
Normal file
157
client/src/components/DashboardMobile.jsx
Normal file
@@ -0,0 +1,157 @@
|
||||
import React from 'react';
|
||||
import CpasBadge, { getTier } from './CpasBadge';
|
||||
|
||||
const AT_RISK_THRESHOLD = 2;
|
||||
|
||||
const TIERS = [
|
||||
{ min: 0, max: 4 },
|
||||
{ min: 5, max: 9 },
|
||||
{ min: 10, max: 14 },
|
||||
{ min: 15, max: 19 },
|
||||
{ min: 20, max: 24 },
|
||||
{ min: 25, max: 29 },
|
||||
{ min: 30, max: 999 },
|
||||
];
|
||||
|
||||
function nextTierBoundary(points) {
|
||||
for (const t of TIERS) {
|
||||
if (points >= t.min && points <= t.max && t.max < 999) return t.max + 1;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isAtRisk(points) {
|
||||
const boundary = nextTierBoundary(points);
|
||||
return boundary !== null && (boundary - points) <= AT_RISK_THRESHOLD;
|
||||
}
|
||||
|
||||
const s = {
|
||||
card: {
|
||||
background: '#181924',
|
||||
border: '1px solid #2a2b3a',
|
||||
borderRadius: '10px',
|
||||
padding: '16px',
|
||||
marginBottom: '12px',
|
||||
boxShadow: '0 1px 4px rgba(0,0,0,0.4)',
|
||||
},
|
||||
cardAtRisk: {
|
||||
background: '#181200',
|
||||
border: '1px solid #d4af37',
|
||||
},
|
||||
row: {
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: '8px 0',
|
||||
borderBottom: '1px solid rgba(255,255,255,0.05)',
|
||||
},
|
||||
rowLast: {
|
||||
borderBottom: 'none',
|
||||
},
|
||||
label: {
|
||||
fontSize: '11px',
|
||||
fontWeight: 600,
|
||||
color: '#9ca0b8',
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px',
|
||||
},
|
||||
value: {
|
||||
fontSize: '14px',
|
||||
fontWeight: 600,
|
||||
color: '#f8f9fa',
|
||||
textAlign: 'right',
|
||||
},
|
||||
name: {
|
||||
fontSize: '16px',
|
||||
fontWeight: 700,
|
||||
color: '#d4af37',
|
||||
marginBottom: '8px',
|
||||
cursor: 'pointer',
|
||||
textDecoration: 'underline dotted',
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
padding: 0,
|
||||
textAlign: 'left',
|
||||
width: '100%',
|
||||
},
|
||||
atRiskBadge: {
|
||||
display: 'inline-block',
|
||||
marginTop: '4px',
|
||||
padding: '3px 8px',
|
||||
borderRadius: '10px',
|
||||
fontSize: '10px',
|
||||
fontWeight: 700,
|
||||
background: '#3b2e00',
|
||||
color: '#ffd666',
|
||||
border: '1px solid #d4af37',
|
||||
},
|
||||
points: {
|
||||
fontSize: '28px',
|
||||
fontWeight: 800,
|
||||
textAlign: 'center',
|
||||
margin: '8px 0',
|
||||
},
|
||||
};
|
||||
|
||||
export default function DashboardMobile({ employees, onEmployeeClick }) {
|
||||
if (!employees || employees.length === 0) {
|
||||
return (
|
||||
<div style={{ padding: '20px', textAlign: 'center', color: '#77798a', fontStyle: 'italic' }}>
|
||||
No employees found.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ padding: '12px' }}>
|
||||
{employees.map((emp) => {
|
||||
const risk = isAtRisk(emp.active_points);
|
||||
const tier = getTier(emp.active_points);
|
||||
const boundary = nextTierBoundary(emp.active_points);
|
||||
const cardStyle = risk ? { ...s.card, ...s.cardAtRisk } : s.card;
|
||||
|
||||
return (
|
||||
<div key={emp.id} style={cardStyle}>
|
||||
<button style={s.name} onClick={() => onEmployeeClick(emp.id)}>
|
||||
{emp.name}
|
||||
</button>
|
||||
{risk && (
|
||||
<div style={s.atRiskBadge}>
|
||||
⚠ {boundary - emp.active_points} pt{boundary - emp.active_points > 1 ? 's' : ''} to {getTier(boundary).label.split('—')[0].trim()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ ...s.row, marginTop: '12px' }}>
|
||||
<span style={s.label}>Tier / Standing</span>
|
||||
<span style={s.value}><CpasBadge points={emp.active_points} /></span>
|
||||
</div>
|
||||
|
||||
<div style={s.row}>
|
||||
<span style={s.label}>Active Points</span>
|
||||
<span style={{ ...s.points, color: tier.color }}>{emp.active_points}</span>
|
||||
</div>
|
||||
|
||||
<div style={s.row}>
|
||||
<span style={s.label}>90-Day Violations</span>
|
||||
<span style={s.value}>{emp.violation_count}</span>
|
||||
</div>
|
||||
|
||||
{emp.department && (
|
||||
<div style={s.row}>
|
||||
<span style={s.label}>Department</span>
|
||||
<span style={{ ...s.value, color: '#c0c2d6' }}>{emp.department}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{emp.supervisor && (
|
||||
<div style={{ ...s.row, ...s.rowLast }}>
|
||||
<span style={s.label}>Supervisor</span>
|
||||
<span style={{ ...s.value, color: '#c0c2d6' }}>{emp.supervisor}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -103,13 +103,12 @@ export default function EmployeeModal({ employeeId, onClose }) {
|
||||
const load = useCallback(() => {
|
||||
setLoading(true);
|
||||
Promise.all([
|
||||
axios.get('/api/employees'),
|
||||
axios.get(`/api/employees/${employeeId}`),
|
||||
axios.get(`/api/employees/${employeeId}/score`),
|
||||
axios.get(`/api/violations/employee/${employeeId}?limit=100`),
|
||||
])
|
||||
.then(([empRes, scoreRes, violRes]) => {
|
||||
const emp = empRes.data.find((e) => e.id === employeeId);
|
||||
setEmployee(emp || null);
|
||||
setEmployee(empRes.data || null);
|
||||
setScore(scoreRes.data);
|
||||
setViolations(violRes.data);
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useState } from 'react';
|
||||
import axios from 'axios';
|
||||
import { useToast } from './ToastProvider';
|
||||
|
||||
const s = {
|
||||
wrapper: { marginTop: '20px' },
|
||||
@@ -53,14 +54,23 @@ export default function EmployeeNotes({ employeeId, initialNotes, onSaved }) {
|
||||
const [draft, setDraft] = useState(initialNotes || '');
|
||||
const [saved, setSaved] = useState(initialNotes || '');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveErr, setSaveErr] = useState('');
|
||||
|
||||
const toast = useToast();
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
setSaveErr('');
|
||||
try {
|
||||
await axios.patch(`/api/employees/${employeeId}/notes`, { notes: draft });
|
||||
setSaved(draft);
|
||||
setEditing(false);
|
||||
if (onSaved) onSaved(draft);
|
||||
} catch (err) {
|
||||
const msg = err.response?.data?.error || err.message || 'Failed to save notes';
|
||||
setSaveErr(msg);
|
||||
toast.error('Notes save failed: ' + msg);
|
||||
// Keep editing open so the user doesn't lose their changes
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -130,6 +140,11 @@ export default function EmployeeNotes({ employeeId, initialNotes, onSaved }) {
|
||||
placeholder="Free-text notes — one per line or comma-separated. Does not affect CPAS scoring."
|
||||
autoFocus
|
||||
/>
|
||||
{saveErr && (
|
||||
<div style={{ fontSize: '12px', color: '#ff7070', marginBottom: '6px' }}>
|
||||
✗ {saveErr}
|
||||
</div>
|
||||
)}
|
||||
<div style={s.actions}>
|
||||
<button style={s.saveBtn} onClick={handleSave} disabled={saving}>
|
||||
{saving ? 'Saving…' : 'Save Notes'}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
// Tier thresholds used to compute what tier an employee would drop to
|
||||
// after a given violation rolls off.
|
||||
// TODO [MINOR #10]: This TIER_THRESHOLDS array duplicates tiers defined in CpasBadge.jsx
|
||||
// and Dashboard.jsx. Export TIERS from CpasBadge.jsx and import here instead.
|
||||
const TIER_THRESHOLDS = [
|
||||
{ min: 30, label: 'Separation', color: '#ff1744' },
|
||||
{ min: 25, label: 'Final Decision', color: '#ff6d00' },
|
||||
|
||||
@@ -78,14 +78,12 @@ export default function NegateModal({ violation, onConfirm, onCancel }) {
|
||||
});
|
||||
};
|
||||
|
||||
// FIX: overlay click only closes on backdrop, NOT modal children
|
||||
const handleOverlayClick = (e) => {
|
||||
if (e.target === e.currentTarget && onCancel) onCancel();
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={s.overlay} onClick={handleOverlayClick}>
|
||||
{/* FIX: stopPropagation prevents modal clicks from bubbling to overlay */}
|
||||
<div style={s.modal} onClick={(e) => e.stopPropagation()}>
|
||||
|
||||
<div style={s.header}>
|
||||
|
||||
@@ -17,14 +17,15 @@ export default function TierWarning({ currentPoints, addingPoints }) {
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
background: '#fff3cd',
|
||||
border: '2px solid #ffc107',
|
||||
background: '#3b2e00',
|
||||
border: '2px solid #d4af37',
|
||||
borderRadius: '6px',
|
||||
padding: '12px 16px',
|
||||
margin: '12px 0',
|
||||
fontSize: '13px',
|
||||
color: '#ffdf8a',
|
||||
}}>
|
||||
<strong>⚠ Tier Escalation Warning</strong><br />
|
||||
<strong style={{ color: '#ffd666' }}>⚠ Tier Escalation Warning</strong><br />
|
||||
Adding <strong>{addingPoints} point{addingPoints !== 1 ? 's' : ''}</strong> will move this employee
|
||||
from <strong>{current.label}</strong> to <strong>{projected.label}</strong>.
|
||||
{tierUp && (
|
||||
|
||||
@@ -35,6 +35,7 @@ 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: '',
|
||||
};
|
||||
@@ -43,7 +44,7 @@ export default function ViolationForm() {
|
||||
const [employees, setEmployees] = useState([]);
|
||||
const [form, setForm] = useState(EMPTY_FORM);
|
||||
const [violation, setViolation] = useState(null);
|
||||
const [status, setStatus] = useState(null);
|
||||
const [status, setStatus] = useState(null); // TODO [MAJOR #7]: remove — toast covers this
|
||||
const [lastViolId, setLastViolId] = useState(null);
|
||||
const [pdfLoading, setPdfLoading] = useState(false);
|
||||
|
||||
@@ -108,6 +109,7 @@ export default function ViolationForm() {
|
||||
setEmployees(empList.data);
|
||||
|
||||
toast.success(`Violation #${newId} recorded — click Download PDF to save the document.`);
|
||||
// TODO [MAJOR #7]: remove setStatus — toast above already covers this message
|
||||
setStatus({ ok: true, msg: `✓ Violation #${newId} recorded — click Download PDF to save the document.` });
|
||||
setForm(EMPTY_FORM);
|
||||
setViolation(null);
|
||||
|
||||
113
client/src/styles/mobile.css
Normal file
113
client/src/styles/mobile.css
Normal file
@@ -0,0 +1,113 @@
|
||||
/* Mobile-Responsive Utilities for CPAS Tracker */
|
||||
/* Target: Standard phones 375px+ with graceful degradation */
|
||||
|
||||
/* Base responsive utilities */
|
||||
@media (max-width: 768px) {
|
||||
/* Hide scrollbars but keep functionality */
|
||||
* {
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* Touch-friendly tap targets (min 44px) */
|
||||
button, a, input, select {
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
/* Improve form input sizing on mobile */
|
||||
input, select, textarea {
|
||||
font-size: 16px !important; /* Prevents iOS zoom on focus */
|
||||
}
|
||||
}
|
||||
|
||||
/* Tablet and below */
|
||||
@media (max-width: 1024px) {
|
||||
.hide-tablet {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Mobile portrait and landscape */
|
||||
@media (max-width: 768px) {
|
||||
.hide-mobile {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.mobile-full-width {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
.mobile-text-center {
|
||||
text-align: center !important;
|
||||
}
|
||||
|
||||
.mobile-no-padding {
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
.mobile-small-padding {
|
||||
padding: 12px !important;
|
||||
}
|
||||
|
||||
/* Stack flex containers vertically */
|
||||
.mobile-stack {
|
||||
flex-direction: column !important;
|
||||
}
|
||||
|
||||
/* Allow horizontal scroll for tables */
|
||||
.mobile-scroll-x {
|
||||
overflow-x: auto !important;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* Card-based layout helpers */
|
||||
.mobile-card {
|
||||
display: block !important;
|
||||
padding: 16px;
|
||||
margin-bottom: 12px;
|
||||
border-radius: 8px;
|
||||
background: #181924;
|
||||
border: 1px solid #2a2b3a;
|
||||
}
|
||||
|
||||
.mobile-card-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid #1c1d29;
|
||||
}
|
||||
|
||||
.mobile-card-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.mobile-card-label {
|
||||
font-weight: 600;
|
||||
color: #9ca0b8;
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.mobile-card-value {
|
||||
font-weight: 600;
|
||||
color: #f8f9fa;
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
|
||||
/* Small mobile phones */
|
||||
@media (max-width: 480px) {
|
||||
.hide-small-mobile {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Utility for sticky positioning on mobile */
|
||||
@media (max-width: 768px) {
|
||||
.mobile-sticky-top {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
background: #000000;
|
||||
}
|
||||
}
|
||||
209
demo/index.html
209
demo/index.html
@@ -10,27 +10,27 @@
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
:root {
|
||||
--gold: #d4af37;
|
||||
--gold-lt: #ffdf8a;
|
||||
--gold-dk: #a88520;
|
||||
--bg: #050608;
|
||||
--bg-nav: #000000;
|
||||
--bg-card: #111217;
|
||||
--bg-section:#181924;
|
||||
--border: #222;
|
||||
--border-lt: #2a2b3a;
|
||||
--text: #f8f9fa;
|
||||
--text-muted:#9ca0b8;
|
||||
--text-dim: #d1d3e0;
|
||||
--green: #28a745;
|
||||
--green-bg: #d4edda;
|
||||
--yellow: #856404;
|
||||
--yellow-bg: #fff3cd;
|
||||
--red: #d9534f;
|
||||
--red-bg: #f8d7da;
|
||||
--red-dk: #721c24;
|
||||
--red-dk-bg: #f5c6cb;
|
||||
--sep: #721c24;
|
||||
--gold: #d4af37;
|
||||
--gold-lt: #ffdf8a;
|
||||
--gold-dk: #a88520;
|
||||
--bg: #050608;
|
||||
--bg-nav: #000000;
|
||||
--bg-card: #111217;
|
||||
--bg-section: #181924;
|
||||
--border: #222;
|
||||
--border-lt: #2a2b3a;
|
||||
--text: #f8f9fa;
|
||||
--text-muted: #9ca0b8;
|
||||
--text-dim: #d1d3e0;
|
||||
--green: #28a745;
|
||||
--green-bg: #d4edda;
|
||||
--yellow: #856404;
|
||||
--yellow-bg: #fff3cd;
|
||||
--red: #d9534f;
|
||||
--red-bg: #f8d7da;
|
||||
--red-dk: #721c24;
|
||||
--red-dk-bg: #f5c6cb;
|
||||
--sep: #721c24;
|
||||
}
|
||||
|
||||
html { scroll-behavior: smooth; }
|
||||
@@ -407,8 +407,94 @@
|
||||
.feature-desc { font-size: 12px; color: var(--text-muted); line-height: 1.6; }
|
||||
|
||||
/* ── FOOTER ── */
|
||||
footer { border-top: 1px solid var(--border); padding: 24px 40px; display: flex; align-items: center; justify-content: space-between; font-size: 11px; color: var(--text-muted); font-family: 'DM Mono', monospace; }
|
||||
.footer-brand { font-family: 'Syne', sans-serif; font-size: 13px; font-weight: 700; color: var(--text-dim); }
|
||||
footer {
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 20px 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
font-family: 'DM Mono', monospace;
|
||||
background: var(--bg-nav);
|
||||
}
|
||||
.footer-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 18px;
|
||||
}
|
||||
.footer-brand {
|
||||
font-family: 'Syne', sans-serif;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.footer-copy {
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
.footer-gitea {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--text-muted);
|
||||
text-decoration: none;
|
||||
padding: 4px 10px;
|
||||
border: 1px solid var(--border-lt);
|
||||
border-radius: 5px;
|
||||
transition: border-color 0.2s, color 0.2s;
|
||||
font-size: 11px;
|
||||
}
|
||||
.footer-gitea:hover {
|
||||
border-color: var(--gold-dk);
|
||||
color: var(--gold-lt);
|
||||
}
|
||||
.footer-gitea svg {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
fill: currentColor;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.footer-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 18px;
|
||||
}
|
||||
.footer-ticker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
background: rgba(212,175,55,0.06);
|
||||
border: 1px solid rgba(212,175,55,0.2);
|
||||
border-radius: 5px;
|
||||
padding: 4px 12px;
|
||||
}
|
||||
.footer-ticker-label {
|
||||
font-size: 10px;
|
||||
color: var(--text-muted);
|
||||
letter-spacing: 0.5px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.footer-ticker-time {
|
||||
font-family: 'DM Mono', monospace;
|
||||
font-size: 12px;
|
||||
color: var(--gold);
|
||||
font-weight: 500;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
.footer-ticker-dot {
|
||||
width: 5px; height: 5px; border-radius: 50%;
|
||||
background: var(--gold);
|
||||
animation: pulse 2s infinite;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.footer-divider {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
background: var(--border-lt);
|
||||
}
|
||||
|
||||
/* ── ANIMATIONS ── */
|
||||
.fade-in { opacity: 0; transform: translateY(16px); animation: fadeUp 0.5s ease forwards; }
|
||||
@@ -429,6 +515,8 @@
|
||||
.hero h1 { font-size: 26px; }
|
||||
nav { padding: 0 16px; }
|
||||
.main { padding: 0 12px 60px; }
|
||||
footer { padding: 16px 20px; flex-direction: column; align-items: flex-start; }
|
||||
.footer-right { flex-wrap: wrap; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
@@ -531,7 +619,7 @@
|
||||
<div class="viol-item">
|
||||
<div class="viol-dot viol-dot-red"></div>
|
||||
<div class="viol-info">
|
||||
<div class="viol-name">Marcus T. <span class="repeat-tag">★ REPEAT</span></div>
|
||||
<div class="viol-name">Marcus T. <span class="repeat-tag">☆ REPEAT</span></div>
|
||||
<div class="viol-type">Unauthorized Absence — Operations</div>
|
||||
<div class="viol-meta"><span>Mar 6</span><span>·</span><span>D. Williams</span></div>
|
||||
</div>
|
||||
@@ -643,8 +731,8 @@
|
||||
<div class="features-grid">
|
||||
<div class="feature-card fade-in"><span class="feature-icon">⚡</span><div class="feature-title">Repeat Offense Detection</div><div class="feature-desc">Automatically flags prior violations for the same type and escalates point recommendations per recidivist policy.</div></div>
|
||||
<div class="feature-card fade-in"><span class="feature-icon">📄</span><div class="feature-title">One-Click PDF Generation</div><div class="feature-desc">Generates signed, professional violation documents instantly — with or without employee acknowledgment signatures.</div></div>
|
||||
<div class="feature-card fade-in"><span class="feature-icon">🔀</span><div class="feature-title">Duplicate Record Merge</div><div class="feature-desc">Consolidate duplicate employee records while preserving full violation history under the canonical profile.</div></div>
|
||||
<div class="feature-card fade-in"><span class="feature-icon">📊</span><div class="feature-title">90-Day Rolling Window</div><div class="feature-desc">Points automatically expire after 90 days. Active standing reflects only the current compliance window.</div></div>
|
||||
<div class="feature-card fade-in"><span class="feature-icon">📀</span><div class="feature-title">Duplicate Record Merge</div><div class="feature-desc">Consolidate duplicate employee records while preserving full violation history under the canonical profile.</div></div>
|
||||
<div class="feature-card fade-in"><span class="feature-icon">🕊</span><div class="feature-title">90-Day Rolling Window</div><div class="feature-desc">Points automatically expire after 90 days. Active standing reflects only the current compliance window.</div></div>
|
||||
<div class="feature-card fade-in"><span class="feature-icon">🏷️</span><div class="feature-title">Tier Escalation Warnings</div><div class="feature-desc">Real-time alerts when a new violation would push an employee across a tier boundary before you submit.</div></div>
|
||||
<div class="feature-card fade-in"><span class="feature-icon">🗂️</span><div class="feature-title">Full Audit Trail</div><div class="feature-desc">Every create, amendment, merge, and PDF generation is logged with timestamp and operator attribution.</div></div>
|
||||
</div>
|
||||
@@ -656,7 +744,7 @@
|
||||
|
||||
<div style="margin-bottom:20px;">
|
||||
<div style="background:#181200;border:1px solid var(--gold-dk);border-radius:8px;padding:12px 18px;font-size:12px;color:var(--gold-lt);font-family:'DM Mono',monospace;letter-spacing:0.4px;">
|
||||
⚠ DEMO VIEW — Form fields shown with sample data. Submission is disabled in demo mode.
|
||||
⚡ DEMO VIEW — Form fields shown with sample data. Submission is disabled in demo mode.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -688,10 +776,10 @@
|
||||
<div class="form-item" style="grid-column:1 / -1;">
|
||||
<div class="form-label">Violation Type:</div>
|
||||
<div class="form-input filled" style="display:flex;align-items:center;justify-content:space-between;">
|
||||
<span>Unauthorized Absence ★ 2x in 90 days</span><span style="color:var(--text-muted);font-size:11px;">▼</span>
|
||||
<span>Unauthorized Absence ☆ 2x in 90 days</span><span style="color:var(--text-muted);font-size:11px;">▼</span>
|
||||
</div>
|
||||
<div style="background:#141623;border:1px solid var(--border-lt);border-radius:4px;padding:10px;font-size:12px;color:var(--text-dim);margin-top:6px;">
|
||||
<strong>Unauthorized Absence</strong> <span class="repeat-tag">★ Repeat — 2x prior</span><br/>
|
||||
<strong>Unauthorized Absence</strong> <span class="repeat-tag">☆ Repeat — 2x prior</span><br/>
|
||||
Absence from scheduled work without prior approval or acceptable documentation.<br/>
|
||||
<span style="font-size:10px;color:#a0a3ba;">Chapter 4, Section 4.1 — Attendance & Punctuality</span>
|
||||
</div>
|
||||
@@ -702,7 +790,7 @@
|
||||
<div class="form-item"><div class="form-label">Incident Date:</div><div class="form-input filled">2026-03-06</div></div>
|
||||
</div>
|
||||
<div style="background:#2d1a00;border:1px solid #a06000;border-radius:6px;padding:12px 16px;margin-top:16px;font-size:13px;color:#ffc107;">
|
||||
⚠ <strong>Tier escalation warning:</strong> Adding 5 pts will bring Marcus to <strong>27 pts (Tier 5 — Final Decision)</strong>. This is one tier below Separation. Review carefully.
|
||||
⚡ <strong>Tier escalation warning:</strong> Adding 5 pts will bring Marcus to <strong>27 pts (Tier 5 — Final Decision)</strong>. This is one tier below Separation. Review carefully.
|
||||
</div>
|
||||
<div style="background:#181200;border:2px solid var(--gold);padding:14px;border-radius:6px;margin:16px 0 0;text-align:center;">
|
||||
<div style="color:#ffdf8a;font-weight:700;margin-bottom:8px;">CPAS Point Assessment</div>
|
||||
@@ -733,9 +821,28 @@
|
||||
</div><!-- /main -->
|
||||
|
||||
<footer>
|
||||
<div class="footer-brand">CPAS Tracker</div>
|
||||
<div>DEMO BUILD — All data synthetic — Not for operational use</div>
|
||||
<div>© 2026 MPM</div>
|
||||
<div class="footer-left">
|
||||
<div class="footer-brand">CPAS Tracker</div>
|
||||
<div class="footer-divider"></div>
|
||||
<div class="footer-copy">© 2026 Jason Stedwell</div>
|
||||
<div class="footer-divider"></div>
|
||||
<div style="font-size:11px;color:var(--text-muted);">DEMO BUILD — All data synthetic</div>
|
||||
</div>
|
||||
<div class="footer-right">
|
||||
<a class="footer-gitea" href="https://git.alwisp.com/jason/cpas" target="_blank" rel="noopener">
|
||||
<!-- Gitea logo SVG -->
|
||||
<svg viewBox="0 0 640 640" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M321.6 3.2C146.4 3.2 3.2 146.4 3.2 321.6c0 141.6 91.8 261.9 219.7 304.1 16.1 3 22-7 22-15.5 0-7.6-.3-32.8-.4-59.5-89.5 19.4-108.4-38.4-108.4-38.4-14.6-37.2-35.7-47.1-35.7-47.1-29.2-20 2.2-19.6 2.2-19.6 32.3 2.3 49.3 33.1 49.3 33.1 28.7 49.2 75.3 35 93.7 26.7 2.9-20.8 11.2-35 20.4-43-71.4-8.1-146.5-35.7-146.5-158.9 0-35.1 12.5-63.8 33.1-86.3-3.3-8.1-14.4-40.8 3.1-85.1 0 0 27-8.7 88.4 32.9 25.6-7.1 53.1-10.7 80.4-10.8 27.3.1 54.8 3.7 80.5 10.8 61.3-41.6 88.3-32.9 88.3-32.9 17.6 44.3 6.5 77 3.2 85.1 20.6 22.5 33 51.2 33 86.3 0 123.5-75.2 150.7-146.8 158.7 11.5 10 21.8 29.7 21.8 59.8 0 43.2-.4 78-0.4 88.6 0 8.6 5.8 18.6 22.1 15.5C524.8 583.2 616.8 463.1 616.8 321.6 616.8 146.4 473.6 3.2 298.4 3.2z"/>
|
||||
</svg>
|
||||
jason/cpas
|
||||
</a>
|
||||
<div class="footer-divider"></div>
|
||||
<div class="footer-ticker">
|
||||
<div class="footer-ticker-dot"></div>
|
||||
<div class="footer-ticker-label">Dev Time</div>
|
||||
<div class="footer-ticker-time" id="dev-ticker">—</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
@@ -745,6 +852,42 @@
|
||||
document.getElementById('tab-' + name).classList.add('active');
|
||||
el.classList.add('active');
|
||||
}
|
||||
|
||||
// ── DEV TIME TICKER ──────────────────────────────────────────────────────────
|
||||
// Base dev time calculated from real commit sessions (30-min gap = new session).
|
||||
// Each session timed as (last_commit - first_commit) + 15min overhead.
|
||||
//
|
||||
// Session 1: 2026-03-06 11:33 → 12:05 = 32min + 15 = 47min
|
||||
// Session 2: 2026-03-06 12:19 → 18:00 = 341min + 15 = 356min
|
||||
// Session 3: 2026-03-06 23:18 → 23:41 = 23min + 15 = 38min
|
||||
// Session 4: 2026-03-07 09:22 → 09:53 = 31min + 15 = 46min
|
||||
// Session 5: 2026-03-07 18:31 → 19:02 = 31min + 15 = 46min
|
||||
// Session 6: 2026-03-07 21:28 → 22:02 = 34min + 15 = 49min
|
||||
// Session 7: 2026-03-07 23:13 → 23:59 = 46min + 15 = 61min
|
||||
// Session 8: 2026-03-08 00:11 → 00:12 = 1min + 15 = 16min
|
||||
// Total: 659min = 39,540 seconds
|
||||
//
|
||||
// Anchor: last commit timestamp 2026-03-08T06:12:11Z (UTC)
|
||||
// Ticker ticks up every second from that base.
|
||||
|
||||
const BASE_SECONDS = 39540;
|
||||
const ANCHOR_UTC = new Date('2026-03-08T06:12:11Z').getTime();
|
||||
|
||||
function formatDevTime(totalSec) {
|
||||
const h = Math.floor(totalSec / 3600);
|
||||
const m = Math.floor((totalSec % 3600) / 60);
|
||||
const s = totalSec % 60;
|
||||
return `${String(h).padStart(2,'0')}h ${String(m).padStart(2,'0')}m ${String(s).padStart(2,'0')}s`;
|
||||
}
|
||||
|
||||
function updateTicker() {
|
||||
const elapsed = Math.floor((Date.now() - ANCHOR_UTC) / 1000);
|
||||
const total = BASE_SECONDS + Math.max(0, elapsed);
|
||||
document.getElementById('dev-ticker').textContent = formatDevTime(total);
|
||||
}
|
||||
|
||||
updateTicker();
|
||||
setInterval(updateTicker, 1000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
78
server.js
78
server.js
@@ -11,6 +11,10 @@ app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.static(path.join(__dirname, 'client', 'dist')));
|
||||
|
||||
// TODO [CRITICAL #1]: No authentication on any route. Add an auth middleware
|
||||
// (e.g. express-session + password, or JWT) before all /api/* routes.
|
||||
// Anyone on the network can currently create, delete, or negate violations.
|
||||
|
||||
// ── Demo static route ─────────────────────────────────────────────────────────
|
||||
// Serves the standalone stakeholder demo page at /demo/index.html
|
||||
// Must be registered before the SPA catch-all below.
|
||||
@@ -29,8 +33,19 @@ function audit(action, entityType, entityId, performedBy, details) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Version info (written by Dockerfile at build time) ───────────────────────
|
||||
// Falls back to { sha: 'dev' } when running outside a Docker build (local dev).
|
||||
let BUILD_VERSION = { sha: 'dev', shortSha: 'dev', buildTime: null };
|
||||
try {
|
||||
BUILD_VERSION = require('./client/dist/version.json');
|
||||
} catch (_) { /* pre-build or local dev — stub values are fine */ }
|
||||
|
||||
// Health
|
||||
app.get('/api/health', (req, res) => res.json({ status: 'ok', timestamp: new Date().toISOString() }));
|
||||
app.get('/api/health', (req, res) => res.json({
|
||||
status: 'ok',
|
||||
timestamp: new Date().toISOString(),
|
||||
version: BUILD_VERSION,
|
||||
}));
|
||||
|
||||
// ── Employees ────────────────────────────────────────────────────────────────
|
||||
app.get('/api/employees', (req, res) => {
|
||||
@@ -38,6 +53,13 @@ app.get('/api/employees', (req, res) => {
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// GET /api/employees/:id — single employee record
|
||||
app.get('/api/employees/:id', (req, res) => {
|
||||
const emp = db.prepare('SELECT id, name, department, supervisor, notes FROM employees WHERE id = ?').get(req.params.id);
|
||||
if (!emp) return res.status(404).json({ error: 'Employee not found' });
|
||||
res.json(emp);
|
||||
});
|
||||
|
||||
app.post('/api/employees', (req, res) => {
|
||||
const { name, department, supervisor } = req.body;
|
||||
if (!name) return res.status(400).json({ error: 'name is required' });
|
||||
@@ -47,6 +69,9 @@ app.post('/api/employees', (req, res) => {
|
||||
db.prepare('UPDATE employees SET department = COALESCE(?, department), supervisor = COALESCE(?, supervisor) WHERE id = ?')
|
||||
.run(department || null, supervisor || null, existing.id);
|
||||
}
|
||||
// TODO [MINOR #16]: Spreading `existing` then overwriting with possibly-undefined
|
||||
// `department`/`supervisor` returns `undefined` for unset fields.
|
||||
// Re-query after update or only spread defined values.
|
||||
return res.json({ ...existing, department, supervisor });
|
||||
}
|
||||
const result = db.prepare('INSERT INTO employees (name, department, supervisor) VALUES (?, ?, ?)')
|
||||
@@ -279,6 +304,17 @@ app.post('/api/violations', (req, res) => {
|
||||
// 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'];
|
||||
|
||||
// Pre-build one prepared UPDATE statement per amendable field combination is not
|
||||
// practical (2^n combos), so instead we validate columns against the static
|
||||
// whitelist and build the clause only from known-safe names at startup.
|
||||
// The whitelist itself is the guard; no user-supplied column name ever enters SQL.
|
||||
const AMEND_UPDATE_STMTS = Object.fromEntries(
|
||||
AMENDABLE_FIELDS.map(f => [
|
||||
f,
|
||||
db.prepare(`UPDATE violations SET ${f} = ? WHERE id = ?`)
|
||||
])
|
||||
);
|
||||
|
||||
app.patch('/api/violations/:id/amend', (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
const { changed_by, ...updates } = req.body;
|
||||
@@ -296,18 +332,14 @@ app.patch('/api/violations/:id/amend', (req, res) => {
|
||||
}
|
||||
|
||||
const amendTransaction = db.transaction(() => {
|
||||
// Build UPDATE
|
||||
const setClauses = Object.keys(allowed).map(k => `${k} = ?`).join(', ');
|
||||
const values = [...Object.values(allowed), id];
|
||||
db.prepare(`UPDATE violations SET ${setClauses} WHERE id = ?`).run(...values);
|
||||
|
||||
// Insert an amendment record per changed field
|
||||
const insertAmendment = db.prepare(`
|
||||
INSERT INTO violation_amendments (violation_id, changed_by, field_name, old_value, new_value)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`);
|
||||
for (const [field, newVal] of Object.entries(allowed)) {
|
||||
const oldVal = violation[field];
|
||||
// Use the pre-built statement for this field — no runtime interpolation
|
||||
AMEND_UPDATE_STMTS[field].run(newVal, id);
|
||||
if (String(oldVal) !== String(newVal)) {
|
||||
insertAmendment.run(id, changed_by || null, field, oldVal ?? null, newVal ?? null);
|
||||
}
|
||||
@@ -380,6 +412,38 @@ app.delete('/api/violations/:id', (req, res) => {
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ── Violation counts per employee ────────────────────────────────────────────
|
||||
// GET /api/employees/:id/violation-counts
|
||||
// Returns { violation_type: count } for the rolling 90-day window (non-negated).
|
||||
app.get('/api/employees/:id/violation-counts', (req, res) => {
|
||||
const rows = db.prepare(`
|
||||
SELECT violation_type, COUNT(*) AS count
|
||||
FROM violations
|
||||
WHERE employee_id = ?
|
||||
AND negated = 0
|
||||
AND incident_date >= DATE('now', '-90 days')
|
||||
GROUP BY violation_type
|
||||
`).all(req.params.id);
|
||||
const result = {};
|
||||
for (const r of rows) result[r.violation_type] = r.count;
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
// GET /api/employees/:id/violation-counts/alltime
|
||||
// Returns { violation_type: { count, max_points_used } } across all time (non-negated).
|
||||
app.get('/api/employees/:id/violation-counts/alltime', (req, res) => {
|
||||
const rows = db.prepare(`
|
||||
SELECT violation_type, COUNT(*) AS count, MAX(points) AS max_points_used
|
||||
FROM violations
|
||||
WHERE employee_id = ?
|
||||
AND negated = 0
|
||||
GROUP BY violation_type
|
||||
`).all(req.params.id);
|
||||
const result = {};
|
||||
for (const r of rows) result[r.violation_type] = { count: r.count, max_points_used: r.max_points_used };
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
// ── Audit log ────────────────────────────────────────────────────────────────
|
||||
app.get('/api/audit', (req, res) => {
|
||||
const limit = Math.min(parseInt(req.query.limit) || 100, 500);
|
||||
|
||||
Reference in New Issue
Block a user