25 Commits
Author SHA1 Message Date
tiennm99 7b51fee404 fix(ci): apply Prettier formatting and pin line endings
CI has been red on every push: the workflow runs `pnpm format:check`, which I
never included in local validation (I only gated typecheck/lint/build), so 54
files were committed unformatted.

- ran `pnpm format` — all changes are Prettier line-reflow, no logic touched
  (verified: `git diff -w` flags exactly the same 54 files CI reported)
- added .gitattributes (`* text=auto eol=lf` + binary rules for fonts/images):
  with core.autocrlf and no attributes file, `format:check` counted 141 files
  locally vs 54 in CI, which is what let this slip through

All six CI gates now pass locally in workflow order: secret-leak, format:check,
test (97), lint, typecheck, build.
2026-07-25 15:43:23 +07:00
tiennm99 ca8739dc01 feat(ux): doctor ergonomics — call-next, live-queue indicator, guards
Implements the deferred NEXT items from the clinician UX review, which
targeted the doctor's core loop:

- call_next_patient RPC (advisory-locked so two staff can't double-call) with
  a prominent per-shift button and an Alt+N shortcut that lands straight on
  the checkup screen
- realtime queue indicator: live/disconnected as colour + icon + text plus a
  last-updated time, so a frozen queue is never trusted silently
- unsaved-changes guard on the checkup form (beforeunload + in-app marker)
- diagnosis quick-pick sourced from recent diagnoses, and Vietnamese dose
  presets on every prescription row, so the doctor types almost nothing

typecheck/lint/build green; 97 unit tests still passing.
2026-07-25 15:27:44 +07:00
tiennm99 5ddf11ac4a test: add Vitest unit + Playwright E2E suites (PLAN §7)
The repo had zero tests despite PLAN §7 mandating them.

- 97 unit tests over the pure logic: checkup/customer/catalog/template Zod
  schemas, parseNum, computeAge, and invoice math
- extracted lib/billing/totals.ts (sumLineTotals/formatVnd) so invoice math is
  testable, and refactored the invoice route + dashboard to use it
- 16 Playwright smoke tests that need no database: auth gates redirect to
  sign-in, VI-default rendering, password-reveal toggle, /en locale, 404
- playwright.config passes placeholder env inline via webServer.env so no
  env file is ever needed; pnpm test wired into CI (E2E stays local)

tests/e2e/README.md documents the seeded-data prerequisites for the full
queue -> checkup -> prescription -> paid -> invoice happy path, which is
blocked on a provisioned Supabase project rather than faked with skipped tests.
2026-07-25 15:16:48 +07:00
tiennm99 d91515c36e feat(queue): manual counter control + apply checkup templates
Closes the last two original-app feature gaps:

- set_queue_counter RPC (admin/receptionist, advisory-locked, VN-local day)
  plus per-shift counter display for all staff and a set/reset form for
  admin/receptionist (orig SetCounterRequest/GetCounterRequest)
- checkup templates are now actually applied: pick a template on the checkup
  screen (filtered to the patient's gender), its fields render as inputs and
  persist to the new checkups.template_values jsonb; the ultrasound report PDF
  already reads the template title

daily_queue_counters gains a SELECT policy (reads only) — writes stay inside
the DEFINER RPCs.
2026-07-25 15:05:20 +07:00
tiennm99 86046ace4f feat(reports): prescription & ultrasound PDFs, wider Excel exports, print CSS
Restores the original's full print/report surface (it had three JasperReports
templates; only the invoice existed):

- prescription PDF: dosage-prominent, no prices, doctor + signature line
- ultrasound/imaging report PDF: template title, diagnosis/conclusion, up to
  4 embedded images (downloaded server-side via signed URL)
- Excel exports added for patient roster, medicine+service catalog (2 sheets),
  and monthly paid-revenue with a grand-total row
- browser print CSS (@page A4, chrome hidden via data-print-hidden)

All PDFs use the bundled Be Vietnam Pro family so diacritics render.
2026-07-25 14:57:23 +07:00
tiennm99 9f6eb24fb4 feat(reminders): recheck reminders + nightly media sweep (Phase 7)
- in-app reminders page: patients with recheck_date due/overdue or within 7
  days (clinical-gated, VN-local); sidebar nav + vi/en
- nightly Vercel Cron (/api/cron/nightly, CRON_SECRET-gated) enforces the
  7-day image retention window: removes stale Storage objects + soft-deletes
  rows, keeping the free-tier storage budget bounded
- CRON_SECRET added to env schema + .env.example; vercel.json cron 01:00 VN
2026-07-25 13:23:24 +07:00
tiennm99 f4840b8000 feat(reports): Excel export + revenue dashboard (Phase 6)
- visits Excel export route (admin/cashier, Node runtime, xlsx): month range,
  per-visit totals + payment status
- dashboard: today waiting/completed tiles + 7-day paid-revenue chart
  (recharts, admin/cashier only); VN-local dates, server-summed VND
- admin reports page (month -> Excel); sidebar nav; vi/en
2026-07-25 13:19:54 +07:00
tiennm99 540f3e0fa6 feat(reports): Vietnamese-capable PDF invoice (Phase 6 slice)
- react-pdf invoice route (Node runtime) — clinic header, medicines + services
  tables, server-summed VND total, payment status
- bundled Be Vietnam Pro (Regular+Bold) so diacritics render; fonts registered
  once per process
- "Print invoice" link on the prescription page (locale-prefix aware)
- reports i18n namespace (vi/en); xlsx + recharts deps added for next slices
2026-07-25 13:15:24 +07:00
tiennm99 e718547332 feat(imaging): checkup media capture, gallery & barcode (Phase 5)
- private bsk-checkup-media bucket + checkup_images table; RLS: enrolled read,
  clinical write; storage.objects policies scoped to the bucket
- webcam (getUserMedia) + file capture, client canvas JPEG compression to
  <=200KB; upload via browser client, metadata recorded server-side with a
  path-ownership guard; audit-logged
- gallery with 1h signed URLs + soft-delete; code128 barcode of the checkup id
  (no PII); linked from the checkup page; vi/en; bwip-js added
2026-07-25 12:36:49 +07:00
tiennm99 354f5fd4a7 feat(billing): prescriptions & invoicing (Phase 4b)
- order_items + checkup_services + medicine_orders (payment per checkup);
  integer-VND, server-authoritative totals
- save_prescription / save_checkup_services RPCs snapshot catalog prices and
  compute line_total server-side (clinical-gated, SECURITY DEFINER)
- mark_order_paid RPC gated to admin/cashier; clinical roles cannot flip payment
- prescription composer: dynamic medicine + service rows, live total, save;
  payment status + mark-paid; linked from the checkup page; vi/en
2026-07-25 12:19:59 +07:00
tiennm99 835b5237ab feat(catalog): medicine & service catalogs (Phase 4 slice)
- bsk.medicines + bsk.services; integer-VND money (no floats); RLS enrolled
  read, admin write; soft-delete
- medicines: list + new/edit form (name, unit, sale/cost price, company, route)
- services: inline list + add form (name, price)
- admin-gated, audit-logged; sidebar nav + vi/en
2026-07-25 12:03:04 +07:00
tiennm99 1dc1e946a4 feat(queue): queue & checkup workflow with realtime (Phase 3)
- shifts + daily_queue_counters + checkups (status enum, vitals, diagnosis,
  conclusion, recheck); VN-local checkup_date so the daily queue rolls over
  correctly
- register_checkup RPC assigns queue numbers atomically (concurrency-safe);
  role-gated to clinical staff
- queue page: register form + today's list by shift + call-patient, with
  Supabase Realtime live refresh (RLS-authorized, bsk:queue channel)
- checkup form: single keyboard-tabbable screen (vitals -> diagnosis ->
  conclusion -> recheck -> status), audit-logged
- clinical-role route gates; nav + vi/en; Phase 3-8 roadmap under plans/
2026-07-25 11:56:02 +07:00
tiennm99 481259c08e feat(staff): staff management — roles + access removal (Phase 2 slice)
- admin staff list (email + role) over bsk.app_users; invite stays the
  create path
- change role / remove access via admin-client Server Actions (audit-logged)
- guards: no self role-change or self-removal; the last admin cannot be
  demoted or removed
- sidebar nav + vi/en; completes Phase 2 core entities
2026-07-25 11:45:23 +07:00
tiennm99 46d5ff9bd1 feat(templates): checkup template management (Phase 2 slice)
- bsk.checkup_templates (gender + jsonb field layout, soft-delete); RLS:
  enrolled read, admin write
- create/edit/deactivate Server Actions (admin-gated, audit-logged); field
  layout edited one-label-per-line, serialized to jsonb
- admin templates list + new + edit pages; sidebar nav; vi/en
2026-07-25 11:41:55 +07:00
tiennm99 4273cba2bb feat(patients): patient management with VN geo + accent search (Phase 2 slice)
- bsk.customers (soft-delete) + provinces/wards geo tables; RLS: enrolled
  read, clinical-role write; geo read-only
- accent-insensitive search via unaccent wrapper + search_customers RPC
  (SECURITY INVOKER so RLS applies); name/phone contains
- patients list+search, create, edit; shared form with cascading
  province -> ward dropdown; clinical-role route gate; nav + vi/en
- audit-logged mutations; seed-geo script (db:seed-geo) for the geo dataset
2026-07-25 11:33:40 +07:00
tiennm99 b9ff387a6d feat(settings): clinic information management (Phase 2 slice)
- bsk.clinic_settings singleton (boolean PK pinned true) with name,
  address, phone, barcode prefix; seeded blank row
- RLS: enrolled staff read, admin write; user-client upsert so RLS gates
- admin settings page + form; audit-logged; sidebar nav entry; vi/en
2026-07-25 02:30:42 +07:00
tiennm99 e2fb601b2a feat(doctors): admin doctor management (Phase 2 slice)
- bsk.doctors table (soft-delete) with RLS: reads for enrolled staff,
  writes admin-only; user-client writes so RLS is the enforcement point
- add / edit / deactivate Server Actions — admin-gated, Zod-validated,
  audit-logged via log_audit, revalidate the list
- doctors admin page (RSC list + inline edit + deactivate) and add form
- sidebar nav entry + vi/en strings

Establishes the Phase 2 CRUD pattern (RLS gate + defense-in-depth role
check + Zod + audit + revalidate) for the remaining core entities.
2026-07-25 01:57:01 +07:00
tiennm99 164c6125c2 feat(auth): allowlist-gated admin bootstrap, rate limiting, audit log
- claim_first_admin: no-arg, inserts auth.uid(), gated on an email allowlist
  table so an arbitrary shared-pool principal can no longer claim admin
- revoke direct writes on app_users from authenticated (least privilege)
- rate-limit sign-in (by platform IP) and invite (by admin id); fail open
  on Redis outage so an outage cannot lock staff out
- audit_log table + SECURITY DEFINER log_audit writer, admin-only reads
- invite: map existing-email to a clear error, roll back orphaned auth row
- session: read role + full_name in one own-row query
2026-07-25 01:51:35 +07:00
tiennm99 9afd68a741 feat(phase-1): role-gated app shell + dashboard placeholder
- app/[locale]/(app)/layout.tsx: Server gate — getServerSession()
  redirects unauth users (defense in depth) and signs out + redirects
  the authed-but-no-role edge case. Renders AppShell with user/role/locale.
- app/[locale]/(app)/admin/layout.tsx: second gate via requireRole;
  non-admin → /[locale]/dashboard (not 404 — avoids confirming routes).
- app/[locale]/(app)/dashboard/page.tsx: placeholder showing email +
  role badge.
- lib/auth/role-menu.ts: ROLE_MENU mapping per AppRole → MenuItem[]
  with href + i18n labelKey + lucide icon.
- lib/auth/require-role.ts: server helper for the admin gate.
- components/app-shell/{app-shell,sidebar,sign-out-button,locale-switcher}.tsx:
  Server-rendered shell + sidebar that reads ROLE_MENU[role]; client
  locale switcher (native <select> fallback) and sign-out (<form action>
  with useFormStatus pending UX).
- components/ui/{badge,separator}.tsx: shadcn primitives.
- messages/{vi,en}.json: nav.*, app.*, dashboard.* keys (parity).

Gating chain: proxy.ts redirects unauth → /sign-in for /dashboard +
/admin prefixes; (app) layout enforces session+role; (app)/admin layout
additionally enforces role === 'admin'.
2026-05-25 17:53:44 +07:00
tiennm99 eb1af9013e feat(phase-1): admin enrollment (first-admin claim + invite flow)
- supabase/migrations/20260525163400_bsk_admin.sql:
  bsk.claim_first_admin(uuid) -> boolean, VOLATILE SECURITY DEFINER.
  Advisory lock keyed by hashtext('bsk:claim_first_admin')::bigint
  serializes concurrent first-sign-ins; EXISTS-guarded INSERT means
  only the first caller wins.
- types/supabase-bsk.ts: added claim_first_admin to bsk.Functions.
- lib/auth/invite-schema.ts: InviteUserSchema (Zod v4: email + role
  enum derived from appRoles) + InviteUserState discriminated union.
- app/[locale]/(app)/admin/invite/{actions,page,form}.tsx: admin-only
  invite Server Action + page + RHF/useActionState client form.
  Caller-role check via getServerSession() (defense in depth; the
  (app)/admin layout in phase 06 will gate at the route level).
  Insert uses createSupabaseAdminClient() because app_users has no
  INSERT RLS policy by design.
- app/[locale]/(auth)/sign-in/actions.ts: extended enrollment-check
  branch — when no row AND count == 0, calls claim_first_admin RPC.
  On true, re-fetches enrollment row and proceeds; on false (race
  lost) or count > 0, falls through to existing sign-out + generic
  error (enumeration defense preserved).
- messages/{vi,en}.json: admin.invite.* keys (parity).
- docs/runbooks/first-admin-setup.md: happy path + manual psql
  fallback bootstrap procedure.

No audit_log refs — trimmed plan respected.
2026-05-25 17:47:47 +07:00
tiennm99 e514d710c4 feat(phase-1): sign-in/sign-out server actions + zod schema
- lib/auth/schemas.ts: SignInSchema (Zod v4, email + password 8-72),
  SignInState discriminated union (idle | error), parseSignIn helper.
  Framework-agnostic — no 'use server' so client RHF resolver can import.
- app/[locale]/(auth)/sign-in/actions.ts: signInAction (RHF/useActionState
  shape) + signOutAction. Flow: safeParse → signInWithPassword → enrollment
  check via bsk.app_users → redirect to /[locale]/dashboard. Wrong-password
  and unenrolled paths return the SAME generic error (auth.users
  enumeration defense). redirect() called outside try/catch per
  React 19 / Next 16 semantics.
- messages/{vi,en}.json: auth.signIn.* keys in parity.

Scope honored: no rate limit, no next= guard, no IP extraction.
2026-05-25 17:36:09 +07:00
tiennm99 129cbb7bf0 feat(phase-1): auth session wiring (proxy + layout + helpers)
- proxy.ts: composes Supabase session refresh + next-intl middleware
  into a single NextResponse via copyCookies helper. Coarse auth gate
  on /dashboard + /admin prefixes redirects unauth users to
  /[locale]/sign-in (no ?next= per trimmed plan).
- lib/supabase/session.ts: implements updateSupabaseSession() returning
  { response, user }. Cookies written onto both request.cookies (for
  downstream reads) and response.cookies (for browser). PROTECTED_PATH_PREFIXES
  exported as the gate list.
- lib/proxy/copy-cookies.ts: small helper that ports Set-Cookie entries
  between two NextResponses.
- lib/auth/get-server-session.ts: getServerSession() returning
  { user, role } | null. Derives User type from the factory's return
  type so @supabase/supabase-js stays out of allow-listed lib/auth/*
  per ESLint no-restricted-imports.
- lib/auth/session-provider.tsx: client-side context exposing user to
  client components via useSession() — populated once per request in
  the locale layout.
- app/[locale]/layout.tsx: reads user via getUser() outside any
  'use cache' scope; wraps children in SessionProvider; explicit
  'use cache' warning comment.
2026-05-25 17:30:41 +07:00
tiennm99 0a08f80450 feat(phase-1): db schema init (bsk_init migration + roles)
- supabase/migrations/20260525163300_bsk_init.sql: bsk schema, app_role
  enum, app_users enrollment table, current_role() SECURITY DEFINER
  STABLE helper, RLS enabled with two SELECT policies (own row + admin)
- types/supabase-bsk.ts: hand-written placeholder mirroring canonical
  supabase gen output; regenerate via pnpm db:gen-types after migration
  applied
- lib/db/roles.ts: appRoles tuple + AppRole union + satisfies guard
  against generated enum + isAppRole type guard
- package.json: db:gen-types script
- README: one-line note on regenerating types after db:push
- plans/: include phase 02/04/06 detail files alongside the existing
  01/03/05 (planner output that wasn't committed with the trim)
2026-05-25 17:23:08 +07:00
tiennm99 10a3693f1b fix(scaffold): apply phase-0 review findings
- env: cross-check VERCEL_ENV against NEXT_PUBLIC_APP_ENV at boot so prod
  credentials cannot silently write into a dev keyspace
- upstash: tighten cache-key regex (kebab + colon only); split SCAN
  patterns into their own validator so glob '*' is allowed only there
- eslint: forbid raw @upstash/redis, @upstash/ratelimit, @supabase/supabase-js
  imports outside the named factory files
- supabase/admin: harmonize 'use cache' guidance with CONTRIBUTING.md
  (safe inside cache; partition key on identity for user-specific reads)
- app/layout: clarify global-error.tsx vs error.tsx shell requirements
  given the passthrough root layout
- readme: Next.js 15 -> 16 (matches scaffolded version)
2026-05-25 15:56:54 +07:00
tiennm99 b88147059e feat: scaffold Phase 0 foundation (Next.js 16 + Tailwind v4 + Supabase/Upstash)
Initial code drop for the BSK educational rewrite. Repo previously held only
docs (PLAN.md, README, NOTICE, LICENSE, RESEARCH_REPORT). This commit lands
the App Router shell, i18n route group, and shared-infra factories per the
Phase 0 plan.

Scaffold:
- Next.js 16 + React 19 + TypeScript 5.9, App Router, Turbopack defaults
- Tailwind v4 via @tailwindcss/postcss with CSS-first @theme block
- shadcn/ui CLI v4 (components.json + cn helper); components install lazily
- next-intl v4 with vi default + en fallback; async-params-aware routing
- proxy.ts (Next 16's renamed middleware) wired to next-intl
- lib/supabase/{server,client,admin,session}.ts on @supabase/ssr, schema-scoped
  to 'bsk', async cookies(), server factory unsafe inside 'use cache'
- lib/upstash.ts: prefixed cache helpers and Ratelimit v2, QStash signature
  verifier; future code cannot write unprefixed Redis keys
- lib/env/{client,server}.ts split so the secret key types stay server-side
- ESLint flat config (eslint-config-next/core-web-vitals + typescript +
  prettier), Prettier with tailwindcss plugin, .npmrc + pnpm-workspace.yaml
  for pnpm 11 native-build approval
- CI runs format:check, lint, typecheck, build on PR with dummy env

PLAN.md updates:
- §1 reconciled to TypeScript 5.9 (TS 6 is GA but lacks ecosystem support)
- §3.1 notes middleware → proxy file rename and removal of `next lint`

All four gates pass locally: format:check, lint, typecheck, build (SSG for
/vi and /en, Proxy detected). Code-reviewer findings applied: env split,
session helper renamed and docstring fixed, cache.set/del types tightened,
prettierignore scope reduced, bilingual GlobalNotFound, explanatory comments
on no-op layouts and duplicate setRequestLocale.

Deferred to Phase 1: wiring updateSupabaseSession into proxy.ts (needs auth
flow first), schema migrations, sign-in form.
2026-05-25 10:58:04 +07:00