Docs consolidation + audit-log timezone fix + PTO-Exhausted sliding scale
Build and Push Docker Image / build (push) Successful in 49s

Documentation:
- Consolidate 6 doc surfaces to 3. Merge Unraid guide into README and
  fold durable mobile rules into AGENTS.md; remove README_UNRAID_INSTALL.md,
  MOBILE_RESPONSIVE.md, and the misplaced "CPAS Violation Tracker.md" vault note.
- Fix drift across README/AGENTS/in-app guide: clean-cycle roll-off model
  (not per-violation 90-day window), auth documented as shipped, dropped
  active_cpas_scores view, correct table count (8 tables/0 views), auth
  endpoints + ADMIN_PASSWORD in run commands, roadmap updated.

Fixes:
- Audit log / amendment timestamps: SQLite CURRENT_TIMESTAMP is UTC with no
  zone marker; new Date() parsed the space-separated form as local time,
  shifting entries +5h in Chicago/CDT. Pin the bare form to UTC before
  formatting in AuditLog.jsx and AmendViolationModal.jsx.
- Absence - PTO Exhausted: fixed 5 pts -> sliding scale 1-5.

Rebuild client bundle to include the above.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jason Stedwell
2026-07-10 17:07:51 -05:00
parent cd0064ce5b
commit aef4ae60cb
11 changed files with 206 additions and 779 deletions
+52 -13
View File
@@ -31,6 +31,9 @@ CPAS (Corrective & Progressive Accountability System) is an internal HR tool for
cpas/
├── Dockerfile # Multi-stage: builder (Node+React) → production (Alpine+Chromium)
├── server.js # All API routes + audit helper; single Express entry point
├── auth.js # scrypt hashing, sessions, bootstrap admin, requireAuth/requireAdmin
├── lib/
│ └── rolloff.js # Clean-cycle point roll-off model (computeStanding); SoT for scores
├── db/
│ ├── schema.sql # Base table + view definitions (CREATE TABLE IF NOT EXISTS)
│ └── database.js # DB connection, WAL/FK pragmas, auto-migrations on startup
@@ -52,7 +55,7 @@ cpas/
│ │ ├── components/ # One file per component; no barrel index
│ │ └── styles/
│ │ └── mobile.css # Media query overrides only; all other styles are inline
└── README.md / README_UNRAID_INSTALL.md
└── README.md # Install (local + Unraid), features, API reference, schema, roadmap
```
---
@@ -68,7 +71,11 @@ cpas/
| `violation_resolutions` | Soft-delete records (resolution type, reason, resolver) |
| `violation_amendments` | Field-level diff per amendment (old → new, changed_by, timestamp) |
| `audit_log` | Append-only write action log; never delete from this table |
| `active_cpas_scores` | VIEW: SUM(points) for negated=0 AND incident_date >= 90 days |
| `violation_types` | Persisted custom violation type definitions (UI-created; `type_key` prefixed `custom_`) |
| `users` | Auth accounts: username, scrypt `password_hash`, role (`admin`/`user`) |
| `sessions` | Bearer-token login sessions: token, user_id, expires_at (7-day TTL) |
> **Historical note:** an `active_cpas_scores` SQL view once computed a naive per-violation 90-day sum. It has been **dropped** (see `db/database.js`). CPAS standing is now computed in JavaScript by the clean-cycle roll-off model in `lib/rolloff.js` — see the CPAS Tier System section below.
### Immutable Fields (DO NOT allow amendment of these)
@@ -122,7 +129,15 @@ These thresholds are the authoritative values. Any feature touching tiers must u
The canonical tier logic lives in `client/src/components/CpasBadge.jsx` (`TIERS` array, `getTier()`, `getNextTier()`). Do not duplicate this logic elsewhere — import from `CpasBadge`.
The 90-day rolling window is computed by the `active_cpas_scores` view. This view is **dropped and recreated** in `database.js` on every startup to ensure it always reflects the correct `negated=0` filter.
### Point roll-off model (clean-cycle)
Active-point math lives in **`lib/rolloff.js`** (`computeStanding()`), not in SQL. The rule is a **clean-cycle roll-off**, NOT a per-violation 90-day window:
- Points retire only after the employee goes a full **90 consecutive days with no new non-negated violation**.
- **Any new violation resets that 90-day clock for the employee's entire balance.**
- Each completed clean cycle removes **5 points, oldest violation first**; each further roll-off requires another fresh 90-day clean stretch.
This is deliberately not "each violation expires 90 days after its own incident date" — one new violation pushes roll-off back for everything. Because the model is order-dependent, it is computed in JS and is the single source of truth for point totals. Do not reintroduce a SQL view or sum points client-side.
---
@@ -146,6 +161,21 @@ To add a new violation type: add an entry to `violationData` with a unique camel
---
## Authentication
All auth logic lives in **`auth.js`** (backend) and **`client/src/auth.js`** (token storage + axios interceptors). It is intentionally lightweight for a trusted-LAN deployment.
- **Password hashing**: scrypt, no external dependency. Stored format `scrypt$<saltHex>$<hashHex>`; verified with `crypto.timingSafeEqual`.
- **Sessions**: opaque 32-byte bearer tokens in the `sessions` table, **7-day TTL**. The client stores the token in `localStorage` (`cpas_token`) and an axios request interceptor attaches `Authorization: Bearer <token>`; a response interceptor clears the token and bounces to the login screen on any `401`.
- **Route guard**: `app.use('/api', auth.requireAuth)` protects every `/api/*` route registered after it. The only public routes are `GET /api/health` and `POST /api/auth/login`, registered *before* the guard. Admin-only routes add `auth.requireAdmin`.
- **Bootstrap admin**: created/re-synced every startup from `ADMIN_USERNAME` / `ADMIN_PASSWORD` env vars. Its password is owned by the environment — it cannot be changed from the UI (a UI change is overwritten on next restart). Rotate by changing `ADMIN_PASSWORD` and restarting. The Docker image ships a placeholder `changeme` that **must** be overridden at deploy time.
- **UI-managed users**: admins create/delete users and reset passwords via `/api/users*` (min 6-char passwords, `admin`/`user` roles). These accounts are unaffected by restarts.
- **Audit**: `login_success`, `login_failed`, `user_created`, `user_password_reset`, and `user_deleted` are all written to `audit_log`.
Do not weaken or bypass the global guard, and do not persist tokens anywhere but the existing `localStorage` key.
---
## Coding Standards
### Backend (`server.js`)
@@ -157,7 +187,7 @@ To add a new violation type: add an entry to `violationData` with a unique camel
2. Call `audit()` on success.
3. Return `{ error: '...' }` (not HTML) on all error paths.
- Group routes by resource (Employees, Violations, Dashboard, Audit). Match the existing comment banner style: `// ── Resource Name ───`.
- Do not add authentication middleware. This runs on a trusted internal network by design.
- **Auth is global, not per-route.** `app.use('/api', auth.requireAuth)` guards every `/api/*` route registered after it in `server.js`. The only public routes are `GET /api/health` and `POST /api/auth/login`, both registered *before* the guard. Admin-only routes add `auth.requireAdmin` as a second middleware. When adding a route, register it after the guard and let it inherit auth — do not add ad-hoc token checks. See the Authentication section below.
### Frontend (React)
@@ -166,9 +196,18 @@ To add a new violation type: add an entry to `violationData` with a unique camel
- **Toasts**: Use `useToast()` from `ToastProvider` for all user-facing feedback. Do not use `alert()` or `console.log` for user messages.
- **HTTP**: Use `axios` (already imported in form/modal components). Do not introduce `fetch` unless there is a compelling reason — keep it consistent.
- **State**: Prefer local `useState` over lifting state unless data is needed by multiple unrelated components. The only global context is `ToastProvider`.
- **Mobile**: Test layout at 768px breakpoint. Use the `isMobile` media query pattern already in `Dashboard.jsx` / `DashboardMobile.jsx`. Add breakpoint rules to `mobile.css`, not inline styles.
- **Component files**: One component per file. Name the file to match the export. No barrel `index.js` files.
### Mobile / responsive
The UI targets phones **375px and up** with no external CSS framework. Durable rules:
- **Breakpoints**: `768px` (phones → card layouts, stacked nav), `480px` (small phones → single-column stats), `375px` (minimum supported width). Tablet tweaks at `1024px`. Put breakpoint rules in `mobile.css`, not inline styles.
- **Layout switch**: at ≤768px the dashboard table swaps to a card layout — desktop renders `<table>` in `Dashboard.jsx`; mobile renders `DashboardMobile.jsx`. Gate with the `isMobile` media-query pattern.
- **Touch & iOS**: tap targets ≥ **44px**; form inputs use **16px** font to stop iOS focus-zoom; use `-webkit-overflow-scrolling: touch` for momentum scroll.
- **`useMediaQuery` hook**: currently defined inline in both `App.jsx` and `Dashboard.jsx` (see TODO #8 to extract to `src/hooks/useMediaQuery.js`). Reuse the extracted hook once it lands rather than copying it a third time.
- Test on a real device — Chrome DevTools device mode does not exercise touch behavior.
### Database Migrations
New columns are added via the auto-migration pattern in `database.js`. Do not modify `schema.sql` for columns that already exist in production. Instead:
@@ -191,7 +230,7 @@ Before adding a column or table, answer:
2. **Does it need audit trail?** If it tracks a change to an existing record, add a corresponding entry pattern to `violation_amendments` or `audit_log`.
3. **Is it soft-deletable?** Prefer `negated`/flag patterns over hard deletes for anything HR might need to reverse.
4. **Does it appear on PDFs?** Update `pdf/template.js` to reflect it. Test PDF output after schema changes.
5. **Does `active_cpas_scores` view need updating?** If the new column affects point calculations, update the view recreation block in `database.js`.
5. **Does it affect point calculations?** If so, update `computeStanding()` in `lib/rolloff.js` — that function is the single source of truth for active-point totals. (There is no longer a SQL scoring view.)
---
@@ -230,7 +269,7 @@ docker build -t cpas .
docker run -d --name cpas -p 3001:3001 -v cpas-data:/data cpas
# Unraid: build → save → transfer → load → run with --pids-limit 2048
# See README_UNRAID_INSTALL.md for full Unraid instructions
# See the "Deploying on Unraid" section of README.md for full instructions
```
**Unraid PID limit is critical.** Chromium spawns many child processes for PDF generation. Always include `--pids-limit 2048` on Unraid containers or PDF generation will fail silently.
@@ -245,16 +284,16 @@ docker run -d --name cpas -p 3001:3001 -v cpas-data:/data cpas
### Adding New Features
- **Score-affecting logic belongs in SQL**, not JavaScript. The `active_cpas_scores` view is the single source of truth for point totals. If you need a new score variant (e.g., 30-day window, category-filtered), add a new SQL view — don't compute it in a route handler.
- **Score-affecting logic belongs in `lib/rolloff.js`**, not scattered across route handlers or duplicated in SQL. `computeStanding()` is the single source of truth for point totals. If you need a new score variant (e.g., 30-day window, category-filtered), add it as an option/variant of the roll-off model — don't sum points ad hoc in a route.
- **New violation fields**: Add to `schema.sql` for fresh installs AND to the migration block in `database.js` for existing databases. Both are required.
- **Reporting features**: Future aggregate queries should join against `active_cpas_scores` view and `audit_log` rather than re-implementing point logic. Structure new API endpoints under `/api/reports/` namespace.
- **Notifications/alerts**: Any future alerting feature (email, Slack) should read from `audit_log` or query `active_cpas_scores` — do not add side effects directly into violation insert routes.
- **Authentication**: If auth is ever added, implement it as Express middleware applied globally before all `/api` routes. Do not add per-route auth checks. Session data (user identity) should flow into `performed_by` fields on audit and amendment records.
- **Reporting features**: Future aggregate queries should call `computeStanding()` (or join against `audit_log`) rather than re-implementing point logic. Structure new API endpoints under `/api/reports/` namespace, registered after the auth guard.
- **Notifications/alerts**: Any future alerting feature (email, Slack) should read from `audit_log` or call `computeStanding()` — do not add side effects directly into violation insert routes.
- **Auth is already implemented** (see the Authentication section). It is global middleware (`app.use('/api', auth.requireAuth)`) applied before all `/api` routes, exactly as this guidance recommends — do not add per-route auth checks. When wiring identity into records, pass the signed-in user into `performed_by`/`changed_by` fields on audit and amendment records.
- **Multi-tenant / multi-site**: The schema is single-tenant. If site isolation is ever needed, add a `site_id` foreign key to `employees` and `violations` as a migration column, then scope all queries with a `WHERE site_id = ?` clause.
### What NOT to Do
- Do not compute active CPAS scores in JavaScript by summing violations client-side. Always fetch from the `active_cpas_scores` view.
- Do not compute active CPAS scores by summing violation points client-side. Always fetch the server-computed standing (`/api/employees/:id/score`, `/api/dashboard`, etc.), which runs the clean-cycle model in `lib/rolloff.js`. A naive client-side sum ignores roll-off and will be wrong.
- Do not modify `prior_active_points` after a violation is inserted, EXCEPT via one of the two sanctioned paths: automatic recompute on a back-dated insert (`recomputeSnapshotsAfter()`), or manual admin backfill (`recomputeAllSnapshotsForEmployee()` behind `POST /api/employees/:id/recompute-snapshots` and the **↻ Backfill Snapshots** UI button). Both are audit-logged as `violation_snapshots_recomputed`. Never recompute snapshots on negate, restore, amend, or hard delete.
- Do not add columns to `audit_log`. It is append-only with a fixed schema.
- Do not add a framework or ORM. Raw SQL with prepared statements is intentional — it keeps the query behavior explicit and the dependency surface small.
@@ -295,7 +334,7 @@ Do not add implementation details to README — that belongs in code comments or
## Constraints & Non-Goals
- **No authentication.** This is intentional. The app runs on a trusted LAN. Do not add auth without explicit direction from the project owner.
- **Authentication is intentionally minimal.** A login gate, scrypt-hashed passwords, bearer-token sessions, and an admin/user role split exist (see the Authentication section) — but the app still runs on a trusted LAN. Do not layer on OAuth, SSO, password-reset email flows, or finer-grained permission tiers without explicit direction from the project owner. There is no CSRF/rate-limiting hardening by design; keep it deployed behind the LAN.
- **No external dependencies beyond what's in `package.json`.** Avoid introducing new npm packages unless they solve a clearly scoped problem. Prefer using existing stack capabilities.
- **No client-side routing library.** Navigation between Violation Form, Dashboard, and modals is handled via `App.jsx` state (`view` prop). Do not introduce React Router unless the navigation model meaningfully grows beyond 34 views.
- **No test suite currently.** If adding tests, use Vitest for frontend and a lightweight assertion library for backend routes. Do not add a full testing framework without discussion.