Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86d907afda | ||
|
|
bbe038e3aa |
@@ -5,53 +5,67 @@ HSE Incident Management System for Setia Corporation (3PL warehouse).
|
|||||||
Replaces WhatsApp/Excel safety reporting. Client: Ms. Agnes, Mr. Terence, Mr. Yap, Mr. Jensen.
|
Replaces WhatsApp/Excel safety reporting. Client: Ms. Agnes, Mr. Terence, Mr. Yap, Mr. Jensen.
|
||||||
|
|
||||||
## Stack
|
## Stack
|
||||||
- **Frontend + API routes:** Next.js (App Router)
|
- **Frontend + API routes:** Next.js 16 (App Router)
|
||||||
- **DB + Auth + Storage:** Supabase (Postgres + RLS + pgvector)
|
- **Database:** self-hosted PostgreSQL on the production server (`127.0.0.1:5433`, db `ims`) with RLS and pgvector. Access through Drizzle ORM + `pg`. Supabase is no longer used (migrated 2026-09-30).
|
||||||
- **Hosting:** VPS at `http://64.176.82.100/ims/` + Supabase cloud
|
- **Auth:** own email + password. `bcryptjs` hashes, `jose` JWT in the `ims_session` cookie (8h), checked in `middleware.ts`. No Supabase GoTrue.
|
||||||
- **AI:** Claude API — server-side only, never client-side
|
- **Storage:** evidence files on the server filesystem (`EVIDENCE_DIR`, `/var/lib/ims-evidence`), served through `/api/evidence/...` with HMAC-signed URLs (`EVIDENCE_URL_SECRET`). Backed up nightly.
|
||||||
- **Email:** Resend
|
- **Hosting:** own server `175.136.239.121` (SSH port 9321), nginx → systemd service `ims` on port 3003 at https://ims.setia.com.my
|
||||||
|
- **AI:** DeepSeek via the OpenAI-compatible client (`lib/claude/client.ts`; key set in Settings or `DEEPSEEK_API_KEY`) for quality check, triage, RCA, risk flags and bulk import. Embeddings (similar incidents) use Google `text-embedding-004` (`GOOGLE_AI_API_KEY`). Server-side only, never client-side.
|
||||||
|
- **Email:** Brevo (`BREVO_API_KEY`, `BREVO_FROM_EMAIL`, `BREVO_FROM_NAME`). Resend is no longer used.
|
||||||
- **WhatsApp:** Meta WhatsApp Business Cloud API
|
- **WhatsApp:** Meta WhatsApp Business Cloud API
|
||||||
- **PDF:** pdf-lib (JKKP form fill)
|
- **PDF:** pdf-lib (JKKP form fill, incident report)
|
||||||
- **QR:** qrcode npm package
|
- **QR:** qrcode npm package
|
||||||
|
|
||||||
## Current Phase
|
## Current Phase
|
||||||
**All phases (0–6) complete as of 2026-07-12.** Remaining work is ops: production env vars (`SUPABASE_SERVICE_ROLE_KEY`, Meta WhatsApp, Resend, `CRON_SECRET`), VPS cron registration (`docs/vps-cron.md`), optional Supabase Pro for image thumbnails.
|
**All phases (0–6) complete as of 2026-07-12.** Supabase to local PostgreSQL migration completed and live 2026-09-30.
|
||||||
|
**UI refresh in progress:** follow `design-system/design.md` §8 build order (tokens → ui primitives → TableCard → shells → migrate Incidents list → remaining screens).
|
||||||
|
Legacy leftovers to remove when convenient: `lib/supabase/*`, the `@supabase/*` dependencies and the `supabase/` folder (the app no longer imports them; `db/schema.sql` + `db/rls.sql` are the schema source of truth).
|
||||||
See `[[phases]]` memory for full phase breakdown and deliverables.
|
See `[[phases]]` memory for full phase breakdown and deliverables.
|
||||||
|
|
||||||
## Deployment (Production)
|
## Deployment (Production)
|
||||||
|
|
||||||
**Deploy path for ims.setia.com.my is `/var/www/ims` on 175.136.239.121:9321.**
|
Host `ims.setia.com.my` (175.136.239.121), SSH port 9321, user `setia`. The server holds **build output only, no source**.
|
||||||
|
|
||||||
```bash
|
- **NEVER run `next build`, `pnpm build` or `npm ci` on the server.** A build without source deletes the working `.next` (took production down on 2026-09-30).
|
||||||
# Correct deployment:
|
- App files: `/srv/apps/ims/app` (`/var/www/ims` is a symlink to it). Service: systemd `ims` (`node server.js`, port 3003). Restart: `sudo systemctl restart ims`.
|
||||||
tar -czf - package.json package-lock.json .next | \
|
- Env files live in `/srv/apps/ims/shared/` (`.env`, `.env.production`); `app/.env*` are links to them. Never overwrite, delete or ship `.env*`.
|
||||||
ssh -p 9321 setia@175.136.239.121 "cd /var/www/ims && tar -xzf -"
|
- Evidence files: `/var/lib/ims-evidence` (do not touch). A deploy never runs DB migrations; ask before changing the DB.
|
||||||
pm2 restart wsims
|
- Cron: two daily jobs call `http://127.0.0.1:3003/api/cron/...` with `CRON_SECRET` from `shared/.env` (`docs/vps-cron.md`).
|
||||||
```
|
|
||||||
|
|
||||||
PM2 process `wsims` runs from `/var/www/ims`. Nginx proxies `ims.setia.com.my` → `http://127.0.0.1:3003`.
|
Deploy steps:
|
||||||
|
1. Build locally: `npm run build` (`output: 'standalone'`).
|
||||||
|
2. Stage and upload without any `.env*` or macOS `._*` files (use `COPYFILE_DISABLE=1 tar --exclude='.env*' --exclude='._*'`). Only `server.js`, `package.json`, `node_modules`, `.next` (standalone `.next` plus `.next/static`) and `public` are needed, since the standalone output otherwise drags in the whole project.
|
||||||
|
3. On the server confirm `/srv/apps/ims/app/.next/BUILD_ID` exists, then `sudo systemctl restart ims`. Never restart if `BUILD_ID` is missing.
|
||||||
|
4. Verify https://ims.setia.com.my/login returns 200 and `systemctl is-active ims` is `active`. Keep a rollback copy first: `tar -czf /srv/apps/ims/next-backup-<date>.tgz .next`.
|
||||||
|
|
||||||
## Dev Conventions
|
## Dev Conventions
|
||||||
- Never commit `.env` or API keys. All secrets in env vars only.
|
- Never commit `.env` or API keys. All secrets in env vars only.
|
||||||
- RLS enforced at DB level for every table — never rely on UI-only hiding.
|
- RLS enforced at DB level for every table (`db/rls.sql`) — never rely on UI-only hiding. Query through `withUser` (RLS as the signed-in user) or `asAdmin` from `lib/db/with-user.ts`; do the write and its `audit_log` entry in one transaction.
|
||||||
- Claude API calls: server-side API routes only (`/app/api/...`).
|
- AI calls: server-side API routes only (`/app/api/...`).
|
||||||
- Incident reference format: `SITE-YYYYMM-####`
|
- Incident reference format: `SITE-YYYYMM-####`
|
||||||
- Every DB mutation writes to `audit_log` (table, record_id, action, changed_by, changed_at, old/new value).
|
- Every DB mutation writes to `audit_log` (table, record_id, action, changed_by, changed_at, old/new value).
|
||||||
- Evidence files: never hard-delete; retain minimum 5 years (DOSH JKKP 8 requirement).
|
- Evidence files: never hard-delete; retain minimum 5 years (DOSH JKKP 8 requirement).
|
||||||
- AI suggestions logged to `audit_log` — capture what Claude suggested + what human chose.
|
- AI suggestions logged to `audit_log` — capture what the AI suggested + what the human chose.
|
||||||
|
- Schema changes: edit `db/schema.sql` / `db/rls.sql` and apply by hand to the server database with the owner's go-ahead.
|
||||||
|
|
||||||
## File Structure (target)
|
## File Structure
|
||||||
```
|
```
|
||||||
IMS/
|
IMS/
|
||||||
├── docs/ # PRD, tech spec, roadmap, specs — source of truth
|
├── docs/ # PRD, tech spec, roadmap, specs — source of truth
|
||||||
|
├── design-system/ # design.md (UI source of truth) + .dc.html references
|
||||||
├── app/ # Next.js App Router pages + API routes
|
├── app/ # Next.js App Router pages + API routes
|
||||||
├── components/ # Shared UI components
|
├── components/
|
||||||
|
│ ├── ui/ # Button, StatusTag, TableCard, … (design.md §4)
|
||||||
|
│ └── layout/ # AppShell, MobileShell
|
||||||
├── lib/
|
├── lib/
|
||||||
│ ├── supabase/ # Supabase client + server helpers
|
│ ├── db/ # Drizzle schema, withUser/asAdmin, audit helper
|
||||||
│ ├── claude/ # Claude API wrappers (server-side)
|
│ ├── auth/ # bcryptjs passwords, jose sessions, roles
|
||||||
│ └── notifications/ # Resend + WhatsApp senders
|
│ ├── storage/ # evidence files on disk + signed URLs
|
||||||
├── supabase/
|
│ ├── claude/ # AI client (DeepSeek) + Google embeddings
|
||||||
│ └── migrations/ # SQL migration files
|
│ ├── notifications/ # Brevo email + WhatsApp senders, in-app
|
||||||
|
│ └── supabase/ # LEGACY, unused, to be removed
|
||||||
|
├── db/ # schema.sql, rls.sql, migration/ops scripts
|
||||||
|
├── supabase/ # LEGACY migrations, to be removed
|
||||||
└── public/
|
└── public/
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -62,20 +76,22 @@ IMS/
|
|||||||
- `[[phases]]` — 4 phases + deliverables, current phase
|
- `[[phases]]` — 4 phases + deliverables, current phase
|
||||||
- `[[compliance]]` — NADOPOD 2004, JKKP 6/7/8 rules
|
- `[[compliance]]` — NADOPOD 2004, JKKP 6/7/8 rules
|
||||||
|
|
||||||
## Design system (Modernist)
|
## Design system (IMS Admin refresh)
|
||||||
|
|
||||||
Source of truth: the Modernist `readme.md` and `styles.css` under `design-system/_ds/`. Tokens live in `app/globals.css` (`@theme static`). Do not use `design-system/IMS Admin.dc.html` as a style reference.
|
Source of truth: `design-system/design.md`. Visual references: `design-system/IMS Admin.dc.html` (screens) and `design-system/IMS Admin Spec.dc.html` (patterns). Tokens live in `app/globals.css` (`@theme static`) and mirror design.md §2. The Modernist files under `design-system/_ds/` are retired; do not use them as a style reference.
|
||||||
|
|
||||||
- Flat and architectural: Archivo, ink on a `#f3f2f2` ground, one accent `#ec3013`. Zero corner radius, visible grid, strong 2px rules between major sections (`border-divider`, `border-b-2`).
|
- Neutral commerce-admin style: Geist (`--font-geist`, `--font-geist-mono`), ink `#1f1f1f` on `#f1f1f1` ground, white cards radius 12 with the `shadow-card` ring, one teal accent `#0f766e`. Rules are 1px (`border-rule`), never 2px.
|
||||||
- Use tokens, never hard-coded hex, font names or px values the tokens carry: `bg-ground`, `bg-surface`, `text-ink`, `bg-accent`, `border-divider`, `accent-100…900`, `neutral-100…900`. `gray-*`, `blue-*` and `red-*` are remapped onto the neutral and accent ramps.
|
- Use tokens, never hard-coded hex, font names or px values the tokens carry: `bg-ground`, `bg-surface`, `bg-surface-2`, `text-ink`, `text-muted`, `text-faint`, `border-rule`, `border-ring`, `bg-accent`, `bg-accent-tint`, `text-danger`, and the `st-*` status pairs. `gray-*`/`blue-*`/`red-*` remaps stay only until legacy pages are migrated.
|
||||||
- No `rounded-*` (except circular avatars, allowlisted in `scripts/check-design-gates.mjs`). Labels and headings are flush left, including button labels. No centered hero copy.
|
- Radius comes from the scale: `rounded-md` (8) buttons, chips, inputs, pills; `rounded-xl` (12) cards and mobile controls; `rounded-[5px]` checkbox. Headings and labels are flush left.
|
||||||
- Body-size accent text uses `accent-700`; the accent itself is for buttons, icons and large text.
|
- Status and priority colours only via `StatusTag` / `PriorityTag` (design.md §4.2): dark text on a light tint, text label always present, no icon required. Add new statuses in `components/ui/status-tag.tsx`, not per page.
|
||||||
- Icons: Lucide (`lucide-react`). Interaction: hover tint, pressed step from the accent ramp, `:focus-visible` 2px accent ring (global), disabled at 45% opacity.
|
- Every list is a `TableCard` (design.md §4.9): saved views, toolbar, sortable header, row hover quick actions, selected tint, footer pager, floating bulk bar, empty state, mobile stacked variant. Do not hand-build tables.
|
||||||
- Build UI with `components/ui/*`: `Button`, `Tag`, `StatusTag`, `PriorityTag`, `Field`/`Input`/`Select`/`Textarea`, `Card`, `Modal`, and the `TABLE/TH/TR/TD` class constants.
|
- Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (reporter / CAPA owner).
|
||||||
- Status is never color alone. Needs attention, open, overdue, reported or severity 4-5 = accent tag; in progress = outline tag; done, closed, verified, low = neutral tag. Always keep the text label and an icon. Add new statuses in `components/ui/status-tag.tsx`, not per page.
|
- Icons: Lucide (`lucide-react`), 16px stroke 2 in UI, 12px stroke 2.5 inside chips and checks, 22px stroke 1.8 in the mobile tab bar.
|
||||||
- Incident evidence photos stay full color. `.grayscale` is for decorative photography only.
|
- Interaction: hover/active values per component in design.md §4; `:focus-visible` 2px accent ring is global; transitions 120ms on bg/shadow only; mobile hit targets ≥ 44px.
|
||||||
- Gotcha: never write `*/` inside a CSS comment in `globals.css` (for example a glob like `modernist-*/`); it ends the comment and silently swallows the `@theme` block.
|
- Incident evidence photos stay full colour.
|
||||||
- Run `npm run check:design` before committing UI changes; it must print `design gates: clean`.
|
- New pattern needed? Check design.md first. If it isn't there, design it in the design tool, then add it to design.md in the same PR as the component.
|
||||||
|
- Gotcha: never write `*/` inside a CSS comment in `globals.css`; it ends the comment and silently swallows the `@theme` block.
|
||||||
|
- Run `npm run check:design` before committing UI changes; it must print `design gates: clean`. Update `scripts/check-design-gates.mjs` first: allow `rounded-*`, flag `border-b-2`/`border-2`, flag Archivo and `#ec3013`.
|
||||||
|
|
||||||
## graphify
|
## graphify
|
||||||
When graphify-out/graph.json exists:
|
When graphify-out/graph.json exists:
|
||||||
|
|||||||
+1
-1
@@ -47,5 +47,5 @@ export async function middleware(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
|
matcher: ['/((?!_next/static|_next/image|favicon.ico|manifest\\.json$|sw\\.js$|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'],
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { describe, it, expect } from 'vitest'
|
||||||
|
import { config } from '@/middleware'
|
||||||
|
|
||||||
|
const re = new RegExp(`^${config.matcher[0]}$`)
|
||||||
|
|
||||||
|
describe('middleware matcher', () => {
|
||||||
|
it.each(['/manifest.json', '/sw.js', '/_next/static/chunks/a.js', '/favicon.ico', '/icons/icon-192.png'])(
|
||||||
|
'skips public asset %s so PWA files load without a session',
|
||||||
|
path => {
|
||||||
|
expect(re.test(path)).toBe(false)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
it.each(['/', '/login', '/hse/incidents', '/api/incidents', '/manifest.jsonx', '/app/sw.js'])(
|
||||||
|
'still guards %s',
|
||||||
|
path => {
|
||||||
|
expect(re.test(path)).toBe(true)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user