# PROG.md

## 1) Current Project Status

This project now implements **Phases 1 through 7** fully, and includes key **Phase 8 QA/polish updates**:

- Next.js App Router + TypeScript + Tailwind + npm
- Prisma + Postgres schema + seed
- Real email/password auth + verification token + session cookie + logout
- Onboarding wizard persisted to `Organization`
- Diagnostic engine with DB questions, autosave, and resume
- Scoring engine persisted to `AssessmentResult`
- Results and Dashboard fed from computed DB scores (not mock data)
- Recommendations generated from low-scoring modules
- Manual/FAQ loaded from `ContentPage` in DB
- Added global loading and error UI states
- Added baseline tests for scoring and session-token logic

Validation currently passes:

- `npm test`
- `npm run lint`
- `npx prisma validate`
- `npm run build`

---

## 2) What Was Implemented (Phase-by-Phase)

### Phase 1: Scaffold + UI shell

Implemented in:
- `src/components/ui/*`
- `src/components/app/page-shell.tsx`
- route pages under `src/app/*`

Delivered:
- Custom UI kit (`Button`, `Card`, `Input`, `Label`, `Badge`, `Progress`, `Tabs`, `Dialog`, `Accordion`, `Stepper`)
- Shell styling (light gray background, card layout, navy buttons, success greens)
- Static versions of all required routes

### Phase 2: Prisma + schema + seed

Implemented in:
- `prisma/schema.prisma`
- `prisma/seed.mjs`
- `src/lib/prisma.ts`
- `src/app/dev/db/page.tsx`

Delivered:
- Full data model (`User`, `Organization`, `DiagnosticModule`, `Question`, `AnswerOption`, `Response`, `AssessmentResult`, `Recommendation`, `ContentPage`, `EmailVerificationToken`)
- Seed script for modules/questions/options/recommendations/manual+faq
- Dev DB viewer route

### Phase 3: Auth + email verification + session gating

Implemented in:
- `src/lib/auth/*`
- `src/app/api/auth/*`
- `src/app/register/page.tsx`
- `src/app/login/page.tsx`
- `src/app/verify/page.tsx`
- `src/components/app/page-shell.tsx`

Delivered:
- Signup/login with password hashing
- Verification token issue/consume flow
- Dev verification link logging in server console
- Signed HttpOnly session cookie
- Route protection and logout

### Phase 4: Onboarding persistence

Implemented in:
- `src/components/app/onboarding-wizard.tsx`
- `src/app/onboarding/page.tsx`
- `src/app/api/onboarding/route.ts`
- `src/lib/auth/user.ts`

Delivered:
- Multi-step onboarding wizard
- Persist/upsert to `Organization` linked to authenticated user
- Redirect to `/diagnostic` after successful onboarding
- Gating so non-onboarded users are redirected to `/onboarding`

### Phase 5: Diagnostic engine

Implemented in:
- `src/lib/diagnostic.ts`
- `src/app/diagnostic/page.tsx`
- `src/app/diagnostic/[moduleId]/page.tsx`
- `src/components/app/module-questionnaire.tsx`
- `src/app/api/diagnostic/response/route.ts`

Delivered:
- DB-driven module list and progress metrics
- Resume links by module/question index
- Per-question autosave into `Response`
- Next/back navigation + save-and-exit + resume

### Phase 6: Scoring + Results + Dashboard

Implemented in:
- `src/lib/scoring.ts`
- `src/lib/scoring-core.ts`
- `src/app/results/page.tsx`
- `src/app/dashboard/page.tsx`
- `src/components/app/dashboard-view.tsx`

Delivered:
- Recompute module and overall scores from response weights
- Persist module and overall snapshots in `AssessmentResult`
- Results page with global score and strengths/weaknesses
- Dashboard page with progress/bars/radar + module status detail

### Phase 7: Recommendations + Manual/FAQ

Implemented in:
- `src/lib/recommendations.ts`
- `src/lib/content-pages.ts`
- `src/app/recommendations/page.tsx`
- `src/app/manual/page.tsx`

Delivered:
- Recommendations generated from low-scoring modules
- Manual and FAQ loaded from DB `ContentPage`
- Download report placeholder button on recommendations

### Phase 8 (partial but substantive): QA/polish

Implemented in:
- `src/app/loading.tsx`
- `src/app/error.tsx`
- tests under `src/lib/__tests__/*`
- `vitest.config.ts`

Delivered:
- Global loading state
- Global error boundary UI
- Unit tests for scoring core and session-token logic

---

## 3) Assumptions Made

1. **Email delivery in development**: verification is valid if token links are logged to server console (real SMTP not required yet).
2. **Scoring model**:
   - Module score normalized by answered questions only (selected weight / max possible for answered questions).
   - Overall score computed as equal-weight average across modules.
3. **Recommendation model**:
   - Primary recommendations come from low-scoring modules (`score < 70`) with answered questions.
   - Fallback to global (`moduleId = null`) recommendations if no module-targeted suggestions apply.
4. **Onboarding gating**:
   - Users must be authenticated and onboarded to access diagnostic/results/dashboard/recommendations/manual.
5. **Data availability**:
   - Seed data provides required baseline modules/questions/options/manual/recommendations.

---

## 4) How to Modify Logic / Implement New Specs

### A) Change scoring formula

Primary files:
- `src/lib/scoring-core.ts`
- `src/lib/scoring.ts`

What to change:
- Update `computeAssessmentSnapshot(...)` for new formulas (weighted modules, penalties, thresholds, etc.)
- Keep DB persistence in `recomputeAssessmentResults(...)` synchronized with new output fields

### B) Change low-score threshold or recommendation strategy

Primary file:
- `src/lib/recommendations.ts`

What to change:
- Modify filter condition (`moduleScore.score < 70`)
- Adjust ranking/prioritization and number of recommendations per module
- Add role/industry/context-aware filtering if needed

### C) Add onboarding fields

Primary files:
- `prisma/schema.prisma` (`Organization` model)
- `src/components/app/onboarding-wizard.tsx`
- `src/app/api/onboarding/route.ts`

What to change:
- Add DB columns + migrate
- Add step inputs/state
- Persist and validate in API route

### D) Add or modify diagnostic modules/questions/options

Primary file:
- `prisma/seed.mjs`

What to change:
- Add new module/question/option seed definitions (`key` values must be unique)
- Rerun migrate/seed

### E) Swap verification transport to real email provider

Primary files:
- `src/lib/auth/verification.ts`
- `src/app/api/auth/register/route.ts`
- `src/app/api/auth/login/route.ts`
- `src/app/api/auth/resend/route.ts`

What to change:
- Keep token generation/consumption as-is
- Replace console logging with provider API call (SES/SendGrid/Postmark)

### F) Customize dashboard charts and result blocks

Primary files:
- `src/components/app/dashboard-view.tsx`
- `src/components/app/module-bars-card.tsx`
- `src/components/app/radar-chart-card.tsx`
- `src/app/results/page.tsx`

What to change:
- Adjust chart labels, colors, ranges, and data mapping
- Add additional cards/insights from `AssessmentResult` or response-level analytics

### G) Session hardening

Primary files:
- `src/lib/auth/session-token.ts`
- `src/lib/auth/session.ts`
- `src/lib/auth/constants.ts`

What to change:
- Rotate `SESSION_SECRET`
- Add token versioning/invalidations
- Add shorter TTL + refresh logic

---

## 5) Full Diagnosis vs Original Plan (and Fixes Applied)

### Summary

The implementation now satisfies all required Phase 1-7 deliverables. The original gap found during this diagnosis was Phase 8 hardening depth (loading/error/test baseline), which has now been addressed.

### Detailed checklist

- Phase 1 scaffold + UI kit + static route shell: **Done**
- Phase 2 schema + seed + DB viewer: **Done**
- Phase 3 real auth + verify + session + logout: **Done**
- Phase 4 onboarding wizard + persistence + redirect: **Done**
- Phase 5 diagnostic autosave + resume + progress: **Done**
- Phase 6 scoring persistence + results + dashboard charts: **Done**
- Phase 7 recommendations from low scores + manual/faq from DB + report placeholder: **Done**
- Phase 8 required polish subset:
  - consistency baseline: **Done**
  - loading/empty/error states: **Done**
  - validation/friendly errors baseline: **Done**
  - optional tests: **Done (added baseline unit tests)**

### Differences discovered and fixed during this pass

1. **No baseline automated tests existed** -> Added Vitest + 5 unit tests:
   - `src/lib/__tests__/scoring-core.test.ts`
   - `src/lib/__tests__/session-token.test.ts`
2. **No global loading/error route states** -> Added:
   - `src/app/loading.tsx`
   - `src/app/error.tsx`
3. **Residual mock file not used** -> Removed:
   - `src/lib/mock-data.ts`

---

## 6) Runbook

From ` /var/opt/assessment-app `:

1. Install deps:
   - `npm install`
2. Generate Prisma client:
   - `npm run prisma:generate`
3. Run migration(s):
   - `npm run prisma:migrate -- --name init`
4. Seed data:
   - `npm run prisma:seed`
5. Start app:
   - `npm run dev`
6. Quality checks:
   - `npm test`
   - `npm run lint`
   - `npm run build`

---

## 7) External Dependencies / Pending Inputs

- A working Postgres connection string is required in `.env`:
  - `DATABASE_URL=...`
- Session secret should be set to a secure value in non-dev:
  - `SESSION_SECRET=...`
- Email verification currently logs links in server console; production email delivery is not wired yet.

---

## 8) Suggested Next Implementation Targets

1. Add integration tests for register/login/verify and diagnostic autosave flow.
2. Add role-based access controls (admin/viewer) for organization scope.
3. Add report generation endpoint (PDF) behind the current placeholder button.
4. Add analytics/versioned scoring snapshots to compare improvements over time.
