Compare commits

..
Author SHA1 Message Date
ngqileandClaude Opus 5.5 07c3ecb7ad fix(db): status backfill skips event leads whose current status is already recorded
A second run after go-live no longer adds a fake OPEN->status row for a
lead captured with another status, which would move its win date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:51:05 +08:00
ngqileandClaude Opus 5.5 ee5fe6d15b docs: lead dashboard SQL and release notes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:44:58 +08:00
ngqileandClaude Opus 5.5 db7f218a71 fix(portal): keep the last dashboard card's border on phones
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:42:12 +08:00
ngqileandClaude Opus 5.5 0a5d5a229b fix(portal): label the Dashboard module in the sidebar
The sidebar shows a module by its name as a message key; BO_DASHBOARD had
no default, so the raw code showed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:38:52 +08:00
ngqileandClaude Opus 5.5 5ffd4176ec fix(mobile-api): tell Spring which AdminDashboardService constructor to use
With a second, package-private constructor for a test clock, Spring found
no default constructor and mobile-api failed to start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:32:25 +08:00
ngqileandClaude Opus 5.5 5eead327a6 feat(portal): lead dashboard on the home page
Users with BO_DASHBOARD get period presets, capture and win tiles, the
status funnel, a captures/wins trend and breakdowns by event,
salesperson and interest; everyone else keeps the welcome.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:25:47 +08:00
ngqileandClaude Opus 5.5 7ff5c77b78 feat(mobile-api): GET /api/admin/dashboard/leads
BO_DASHBOARD-gated lead dashboard: Malaysian-month default period, at
most 731 days, DAY or MONTH buckets, company scope, salesperson names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:22:35 +08:00
ngqileandClaude Opus 5.5 a482a3a6d0 feat(counter): event lead status history and lead dashboard endpoint
Capture and status edits append to event_lead_status_change. POST
/counter/dashboard/leads aggregates captures, wins, overdue follow-ups
and the breakdowns for a Malaysian-day period (at most 731 days).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:21:36 +08:00
ngqileandClaude Opus 5.5 8d5f3747bf docs(openspec): lead dashboard task 4.1 includes the portal proxy route
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:18:06 +08:00
ngqileandClaude Opus 5.5 8177c08540 docs(openspec): cap the lead dashboard range at 731 days
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:12:08 +08:00
ngqileandClaude Opus 5.5 044b746f0b docs: tick lead dashboard wave 0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:02:02 +08:00
ngqileandClaude Opus 5.5 5b63e19550 chore(portal): add recharts and the shadcn chart wrapper
recharts 3.10.1 (same as babyboo's portal) for the lead dashboard trend.
The chart wrapper's <style> is built from its colour config only, so it
joins the HTML-sink allow list as in babyboo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 10:02:01 +08:00
ngqileandClaude Opus 5.5 a2a369aa19 feat(db): event lead status history table and Dashboard module
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 09:54:34 +08:00
ngqileandClaude Opus 5.5 6a512bea8e docs: lead dashboard design and OpenSpec change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 09:54:15 +08:00
ngqile 05ff2e9b74 Merge pull request 'docs(openspec): archive fix-company-scope-fail-closed' (#28) from archive-fix-company-scope-fail-closed into main
CI / build-and-publish (push) Failing after 0s
2026-12-01 01:32:28 +00:00
ngqileandClaude Opus 5.5 b6b05f12df docs(openspec): archive fix-company-scope-fail-closed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 09:32:21 +08:00
ngqile a1aa906a66 Merge pull request 'fix: fail closed for admins outside the company model' (#27) from fix-company-scope-fail-closed into main
CI / build-and-publish (push) Failing after 0s
2026-12-01 01:32:09 +00:00
ngqileandClaude Opus 5.5 998e04b844 fix(mobile-api): fail closed for admins outside the company model
An admin with no company who is not a super admin now gets 403
COMPANY_REQUIRED on every company-scoped request instead of seeing all
companies. The module check and the email detail treat only a real super
admin (no company and role 1) as super; a company user still holding
role 1 gets only what their other roles grant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-12-01 09:31:55 +08:00
ngqile 7d29d89b3f Merge pull request 'docs(openspec): archive add-company-scoping' (#26) from archive-add-company-scoping into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 13:38:36 +00:00
ngqileandClaude Opus 5.5 3c30e0d629 docs(openspec): archive add-company-scoping
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 21:38:27 +08:00
ngqile 66904869cf Merge pull request 'feat: company scoping (INS and CV, super admins see all)' (#25) from add-company-scoping into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 13:38:08 +00:00
ngqileandClaude Opus 5.5 2c6cf7bdde docs: company code reuse caveat; tick company-scoping task 5.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 21:33:30 +08:00
ngqileandClaude Opus 5.5 df70306c9a fix(portal): fill the Company column when the companies load after the rows
The table caches accessor values per row, so a code looked up before the
companies list arrived stayed blank; render it in the cell instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 21:26:44 +08:00
ngqileandClaude Opus 5.5 869d7d5894 docs(openspec): tick company-scoping task 4.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 21:21:02 +08:00
ngqileandClaude Opus 5.5 c8ffc6aede feat(portal): company picker, Company column, company fields and super-admin-only screens
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 21:19:22 +08:00
ngqileandClaude Opus 5.5 57e187a992 docs: company-scoping SQL and company sign-in in the deployment guide
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 21:03:34 +08:00
ngqileandClaude Opus 5.5 ebf5177543 docs(openspec): tick company-scoping task 3.4 after the live check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 20:46:35 +08:00
ngqileandClaude Opus 5.5 f0629192f2 fix: show the company on login history rows without letting callers set it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 20:46:35 +08:00
ngqileandClaude Opus 5.5 bb39e6b805 fix: send companyId as a string in backend property filters
The services-system and services-counter property maps are String-valued;
a numeric companyId failed the cast there and the scoped lists came back empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 20:46:35 +08:00
ngqileandClaude Opus 5.5 8f80f52c04 fix: route /company/** through the gateway to services-system
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 20:38:01 +08:00
ngqileandClaude Opus 5.5 bb9d4357af docs(openspec): tick company-scoping tasks 3.2 and 3.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 20:32:02 +08:00
ngqileandClaude Opus 5.5 ec504fd529 feat: company-scoped events, leads, event leads and exports
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 20:30:46 +08:00
ngqileandClaude Opus 5.5 de2ae63cea feat: company-scoped users and login security, super-admin-only roles, interests and settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 20:29:34 +08:00
ngqileandClaude Opus 5.5 00ce47bc49 feat: company-scoped emails and audit log, company on admin password emails
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 20:03:19 +08:00
ngqileandClaude Opus 5.5 b7d9da8ec0 docs(openspec): tick company-scoping task 4.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 19:49:51 +08:00
ngqileandClaude Opus 5.5 5526294e69 feat(portal): company sign-in, session company and Companies screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 19:48:30 +08:00
ngqileandClaude Opus 5.5 de007b5328 docs(openspec): tick company-scoping task 3.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 19:43:56 +08:00
ngqileandClaude Opus 5.5 69d3ebc58c feat: company sign-in, company scope and super-admin Companies API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 19:42:40 +08:00
ngqileandClaude Opus 5.5 91a0f339a5 docs(openspec): tick company-scoping tasks 2.2 and 2.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 19:21:58 +08:00
ngqileandClaude Opus 5.5 118c57c0ea feat: company on emails and audit search
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 19:21:21 +08:00
ngqileandClaude Opus 5.5 a6996841ac feat: company on events, all-company lead lists, shared interests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 19:20:16 +08:00
ngqileandClaude Opus 5.5 c9c0745955 feat: companies API, company on user lookups, company filters for users and login security
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 19:16:54 +08:00
ngqileandClaude Opus 5.5 840b5a3bae feat: company code and status, company on events and emails, admin login names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 18:44:50 +08:00
ngqileandClaude Opus 5.5 4243a2d6cd docs(openspec): propose add-company-scoping
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 18:23:08 +08:00
ngqileandClaude Opus 5.5 628d885261 docs: company scoping design
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 18:17:16 +08:00
ngqile 3ed713d2cb Merge pull request 'docs: two companies at go-live, super admins see all' (#24) from docs-tenancy-decision into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 09:58:59 +00:00
ngqileandClaude Opus 5.5 b070358446 docs: two companies at go-live, super admins see all
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 17:58:47 +08:00
ngqile cd1034e962 Merge pull request 'docs: record answers to feature-list open questions' (#23) from docs-feature-list-answers into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 09:58:09 +00:00
ngqileandClaude Opus 5.5 bd881ada09 docs: record answers to feature-list open questions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 17:58:03 +08:00
ngqile e62c83a187 Merge pull request 'docs(openspec): archive add-admin-audit-log' (#22) from archive-add-admin-audit-log into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 09:18:08 +00:00
ngqileandClaude Opus 5.5 4f38f6b167 docs(openspec): archive add-admin-audit-log
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 17:18:02 +08:00
ngqile 518901a6d8 Merge pull request 'feat: admin audit log (recording, storage, Audit log screen)' (#21) from add-admin-audit-log into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 09:17:38 +00:00
ngqileandClaude Opus 5.5 7aa5c4b921 fix: audit target is the record acted on, never a typed username; guard retention
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 17:16:29 +08:00
ngqileandClaude Opus 5.5 81ef54f996 docs: audit log deploy SQL, topic and retention setting
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 17:01:55 +08:00
ngqileandClaude Opus 5.5 7fc3adfe05 feat: admin portal Audit log list and detail
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 17:01:55 +08:00
ngqileandClaude Opus 5.5 8a527e9ffe feat: admin audit-log read API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 16:44:09 +08:00
ngqileandClaude Opus 5.5 adc62ac436 feat: admin services supply allow-listed audit changes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 16:36:37 +08:00
ngqileandClaude Opus 5.5 1523dc566b feat: mobile-api records admin writes and sensitive reads as audit events
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 16:10:14 +08:00
ngqileandClaude Opus 5.5 d715073ab2 feat: services-log stores, purges and serves admin audit events
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 15:53:17 +08:00
ngqileandClaude Opus 5.5 10f59c5ca8 feat: core-libs AuditEvent contract and audit-event topic names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 15:44:32 +08:00
ngqileandClaude Opus 5.5 b9912478e0 feat: audit_event table, Audit log module and audit Pub/Sub topic
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 15:40:26 +08:00
ngqileandClaude Opus 5.5 01603e9ece docs(openspec): propose add-admin-audit-log
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 15:35:35 +08:00
ngqileandClaude Opus 5.5 9d811df86a docs: admin audit log design
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 15:11:52 +08:00
ngqile 877a6b07ad Merge pull request 'docs(openspec): archive add-admin-login-security' (#20) from archive-add-admin-login-security into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 07:01:36 +00:00
ngqileandClaude Opus 5.5 c4ff538a8a docs(openspec): archive add-admin-login-security
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 15:01:28 +08:00
ngqile 256ad936f8 Merge pull request 'feat: admin login security (history, lockout, unlock) and own password change' (#19) from add-admin-login-security into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 07:01:02 +00:00
ngqileandClaude Opus 5.5 059107fbaa fix: harden the lockout after the branch review
Settings get upper limits (a huge period made every lock check fail
open), the lock check uses the same 191-character key the history
stores, login_audit.username compares like user.username, and the
module gets its own icon. Docs and design notes follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:59:06 +08:00
ngqileandClaude Opus 5.5 e240a9c37f docs: login security SQL and lockout notes in the deployment guide
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:52:15 +08:00
ngqileandClaude Opus 5.5 dd9bbbe036 fix: browser context on password-change history, plain settings errors, New password label
Found in the browser check: change-password history rows had no browser
or IP, settings errors named internal fields, and the dialog's new
password field read just "Password".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:52:15 +08:00
ngqileandClaude Opus 5.5 091503a820 feat: Login security screen with history, locked accounts and settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:33:53 +08:00
ngqileandClaude Opus 5.5 6598b58cb8 feat: locked sign-in message and Change password dialog in the portal
mobile-api now records the browser user agent the portal forwards as
X-Client-User-Agent instead of the portal server's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:16:11 +08:00
ngqileandClaude Opus 5.5 5ce684168a feat: admin API for login history, locked accounts, unlock and settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 14:01:04 +08:00
ngqileandClaude Opus 5.5 6c6734baa3 feat: admin change-password endpoint with lockout on wrong current password
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 13:51:57 +08:00
ngqileandClaude Opus 5.5 39708224ad feat: lock check and login history on admin sign-in and sign-out
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 13:43:42 +08:00
ngqileandClaude Opus 5.5 f6fe246ad0 feat: services-system endpoint for an admin changing their own password
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 13:34:26 +08:00
ngqileandClaude Opus 5.5 f7ec74c7f0 feat: login history and lockout rule in services-system
LoginSecurityService derives the admin lock from login_audit and the
ADMIN_LOGIN_BLOCK settings; /loginSecurity exposes lock check, record,
history, locked list, unlock, lockout settings and password rules. The
gateway routes /loginSecurity/** and lets the lock check and record
through without a user token for the sign-in path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 13:26:20 +08:00
ngqileandClaude Opus 5.5 a0146be325 feat: login_audit table, lockout settings and Login security module SQL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 12:29:09 +08:00
ngqileandClaude Opus 5.5 bbf268e00a docs(openspec): propose add-admin-login-security
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 12:27:14 +08:00
ngqileandClaude Opus 5.5 c82498e5d8 docs: admin login security and own password change design
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-30 12:23:34 +08:00
ngqile 8f301e0ce5 Merge pull request 'docs(openspec): archive add-admin-email-listing' (#18) from archive-add-admin-email-listing into main
CI / build-and-publish (push) Failing after 0s
2026-11-30 04:15:01 +00:00
344 changed files with 19094 additions and 488 deletions

No files matched your search

+38
View File
@@ -76,6 +76,34 @@ After running `04`, `SELECT LENGTH(password) FROM \`service-system\`.\`user\` WH
| File | What it does |
|---|---|
| `openspec/changes/archive/2026-11-30-add-admin-email-listing/sql/01-email-module.sql` | Adds the Emails back-office module (`BO_EMAILS`). |
| `openspec/changes/archive/2026-11-30-add-admin-login-security/sql/01-login-audit.sql` | Creates the `login_audit` table (admin login history; the lockout reads it). DDL: run it with a user that may create tables, not the services' user. |
| `openspec/changes/archive/2026-11-30-add-admin-login-security/sql/02-lockout-settings.sql` | Adds `ADMIN_LOGIN_MAX_ATTEMPT` (5) and sets the admin block period to 15 minutes: 5 failed sign-ins in 15 minutes lock the username. |
| `openspec/changes/archive/2026-11-30-add-admin-login-security/sql/03-login-security-module.sql` | Adds the Login security back-office module (`BO_LOGIN_SECURITY`). |
`99-rollback.sql` in the same folder undoes the three and deletes the login history.
| File | What it does |
|---|---|
| `openspec/changes/archive/2026-11-30-add-admin-audit-log/sql/01-audit-event.sql` | Creates `service-log`.`audit_event` (the admin audit trail). DDL: run it with a user that may create tables, not the services' user. |
| `openspec/changes/archive/2026-11-30-add-admin-audit-log/sql/02-audit-log-module.sql` | Adds the Audit log back-office module (`BO_AUDIT_LOG`). No role gets it; super admins grant it under Roles. |
`99-rollback.sql` in the same folder undoes the two and deletes the audit trail.
| File | What it does |
|---|---|
| `openspec/changes/archive/2026-11-30-add-company-scoping/sql/01-company-code-status.sql` | Gives each company a sign-in code and a status. Company 1 becomes `INS` (code `ins`) and a second company `CV` (code `cv`) is added. DDL. |
| `openspec/changes/archive/2026-11-30-add-company-scoping/sql/02-company-columns.sql` | Adds the company to events and emails (existing rows go to INS) and makes interests one list shared by every company. DDL. |
| `openspec/changes/archive/2026-11-30-add-company-scoping/sql/03-admin-login-names.sql` | Super admins (role 1) get no company and keep their username. Every other admin moves to INS and is renamed `username@ins`. It stops without changing anything if an admin username already contains `@`. |
Run the three in order, with a user that may alter tables. File `03` ends every admin session: everyone signs in again, staff with company `ins`. `99-rollback.sql` in the same folder undoes the three. It fails on the username unique key once two companies have a user with the same username; rename one of them first.
| File | What it does |
|---|---|
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/01-status-change.sql` | Creates `service-counter`.`event_lead_status_change` (every event-lead status change with its time and user) and an index on `event_lead` for the dashboard. DDL. |
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/02-status-change-backfill.sql` | Gives event leads captured before this release a history: OPEN at capture, and the current status at the last update. These times are approximate. Safe to run twice. |
| `openspec/changes/archive/2026-12-01-add-lead-dashboard/sql/03-dashboard-module.sql` | Adds the Dashboard back-office module (`BO_DASHBOARD`). No role gets it; super admins grant it under Roles. |
Run the three in order before the new images go live: the new services-counter writes to the table from `01` on every capture and status edit, and fails without it. `01` needs a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the status history.
**Database user:**
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
@@ -93,6 +121,7 @@ The services publish and subscribe through Google Pub/Sub. It is not replaced in
- **Project:** use a Google Cloud project, and give its id as `GCP_PROJECT`.
- **Service account:** create one with the Pub/Sub Publisher and Pub/Sub Subscriber roles, and download a JSON key. Mount the key into every Java image except `api-gateway` (section 7), and set `GCP_CREDENTIAL_FILE=file:/var/secrets/gcp/key.json`.
- **Topics and subscriptions:** use `local/pubsub/topics.txt`. Each line is a topic name, optionally followed by a subscription name. Some topics appear on several lines with different subscriptions (e.g. `update-sync-topic`): create each topic once, then every subscription listed for it. Subscriptions use default settings.
- **Audit log:** `audit-event-topic` with `audit-event-subscription` carries admin audit events from mobile-api to service-log. It is in `topics.txt`; service-log also creates both at startup if they are missing. Keep the subscription's default of not retaining acknowledged messages: the events carry admin usernames and IPs. `AUDIT_RETENTION_DAYS` (section 6) must be at least 1, or service-log does not start.
## 6. Environment variables
@@ -155,6 +184,12 @@ The keys:
| `JWT_SECRET` | Secret | Same value as `JWT_TOKEN` |
| `CUSTOMER_PORTAL_BASE_URL` | Plain | The customer portal is not deployed in phase 1. When unset, it falls back to a Tastefully address that only the member referral link uses, which Co-Lite does not use. Set it once a customer portal exists. |
**`service-log`:**
| Variable | Kind | Value |
|---|---|---|
| `AUDIT_RETENTION_DAYS` | Plain | Optional (default 730). Admin audit events older than this many days are deleted daily at 03:30. |
**`api-gateway`:** only `JWT_TOKEN` (same value as everywhere). No Pub/Sub, Redis or database settings, and no `key.json` mount. It reads its client keys from the mounted `appkeys.json` (section 7).
**`admin-portal`:**
@@ -264,6 +299,9 @@ data:
## 10. Known gaps at go-live
- **No email provider yet.** Staff onboarding does not need one: the admin types each new user's first password, and "Set temporary password" on a user's page unlocks a user who forgot theirs. Both force a password change at the next sign-in. Forgot-password and "Send password reset" still create an email with a temporary password. Nobody receives it, but `service-email` saves every email first, so a super admin (or a role granted Emails) can read it under **Emails** and pass the password on in person. The user must change it at the next sign-in. Grant Emails narrowly: it shows every saved email, including other users' temporary passwords, member email-verification codes, and contact or distributor form submissions with the sender's personal data.
- **Sign-in lockout.** 5 failed sign-ins within 15 minutes lock a username, even with the right password, until 15 minutes after the first of those failures, and unknown usernames are counted too. Anyone who knows a username can therefore lock it on purpose. An admin with **Login security** can unlock it at once (Locked tab), and can change the limits there. If every super admin is locked, wait out the period. The lock check fails open: if `service-system` is down, sign-in still works without the lockout.
- **Companies and super admins.** INS and CV each see only their own leads, events, event leads, users, emails, login history and audit log. Staff sign in with their company code, username and password. A super admin leaves Company blank, sees every company (with a company picker in the header), and is the only one who can manage companies, roles, interests, lockout settings and password rules. Changing a company's code renames its staff's sign-in names and signs them out; deactivating a company blocks its staff from signing in. Emails sent from public forms and other system emails have no company, so only super admins see them. Do not give a company's old code to another company while sessions opened under the old code may still be valid: such a session token would resolve to the new company's user of the same name. When in doubt, never reuse a code.
- **Lead dashboard.** Users whose role has the Dashboard module see lead captures, wins, conversion and overdue follow-ups on the home page, for this month, last month or a custom range of up to two years in Malaysian time. A lead counts as converted when its status at an event is WON. Wins and days to win come from the status history, which starts with this release; for older leads it is approximate (see section 3).
- **Reference data from Tastefully.** It still holds some Tastefully business text (message templates with a phone number, bank account and form links; a public image bucket URL; Tastefully usernames in audit columns). Review it before go-live.
- **Other Tastefully defaults.** The sender addresses in `service-email` and the `CUSTOMER_PORTAL_BASE_URL` fallback point at Tastefully. Override them as described in section 6.
- **Leaked SMS key.** An SMS360 API key from Tastefully was in `service-email`'s config and is in git history. It has been removed from the config, but it must be rotated with SMS360 before go-live, by whoever owns that Tastefully account.
+10 -7
View File
@@ -20,7 +20,7 @@ Source: whiteboard session (transcribed 2026-11-26). Items marked **[?]** were u
| 2 | Leads module | Assign leads to sales team | ✓ |
| 3 | Built-in WhatsApp | WhatsApp messaging inside the system | ✓ |
| 4 | Home — create event | Create event per lead | not ticked |
| 5 | QR | Show event details? / scan QR | ✓ |
| 5 | QR | Multi-purpose QR: event details, event check-in, later other uses (see Answered) | ✓ |
| 6 | Voucher | INS own voucher; partner voucher | ✓ |
| 7 | Event milestone | Track events joined (Achievement Board) | ✓ |
| 8 | Gamification | Experience / service giveaway: (i) Spin & Win, (ii) Blindbox. Prizes: IPTV test kit, Omada, CCTV? | ✓ |
@@ -36,16 +36,19 @@ Source: whiteboard session (transcribed 2026-11-26). Items marked **[?]** were u
## Open Questions
- "Tastetuny" **[?]** written under the deadline — project or client name?
- QR: should scanning show event details, check the member in, or both?
- Gamification prizes: confirm IPTV test kit, Omada, CCTV.
- Who are "INS" and "CV" — the two partnering brands (CV = Containerverse?)?
- Left edge of the board was cut off — any missing items?
- Gamification prizes: none chosen yet (IPTV test kit, Omada, CCTV were ideas only). To be confirmed.
## Answered (2026-11-30)
- **"Tastetuny"** on the board is Tastefully, the platform Co-Lite is cloned from.
- **QR:** a QR code can carry different purposes: event details, an event check-in, and later other uses. Scanning does what the code is for. This improves on Tastefully's existing QR feature, which is only a starting point.
- **INS and CV** are the two companies that will use the system as a test run. Each sees only its own data at go-live; super admins see all (see Tenancy below).
- **Left edge of the board:** nothing missing for now.
## Decisions (2026-11-26)
- **Base:** Clone of Tastefully (`~/Projects/tastefully`, Solvway platform).
- **Tenancy:** Single company at go-live. No second company planned soon. New tables still carry a company id so a later SaaS move is a migration, not a rebuild.
- **Tenancy:** ~~Single company at go-live.~~ Changed 2026-11-30: two companies (INS and CV) at go-live, each seeing only its own data (leads, events, users and the rest). Super admins see every company's data. New tables carry a company id; admin APIs and screens must filter by it.
- **Modules dropped:** MLM modules (bonus, stockist, tree, inventory, related jobs).
- **Admin portal:** Rebuild as a Next.js admin portal, modelled on babyboo's `solvway-admin-portal` (shell, auth, roles, tables). The Tastefully Thymeleaf backoffice is ported over for reference only; it is not deployed or extended.
- Every admin screen needs a JSON admin API in `mobile-api` (`/api/admin/**`). Tastefully has none today; babyboo's admin controllers for auth, users, roles, audit log and content are adaptable. Events, check-in, rewards and vouchers admin APIs must be built new.
@@ -0,0 +1,133 @@
# Admin Audit Log — Design
Date: 2026-11-30. Change id: `add-admin-audit-log`.
## Intent
Nothing in Co-Lite records who did what in the admin portal. When an admin edits a user, changes a role's grants, edits or exports leads, or opens a saved email (which can hold a temporary password), the only trace is a line in the application log. Sign-ins are the exception: the `login_audit` table covers them (`add-admin-login-security`).
The user wants an audit trail before go-live (2027-01-15) and a screen to read it. Scope was agreed on 2026-11-30, with lead edits recording field names only, not values.
Reference: babyboo's `add-portal-audit-log` (archive `2026-11-19`) and `audit-log-readable-actions` (`2026-11-20`). This design ports the admin half of that work, trimmed.
## Goals
- Record an audit event for every admin write through mobile-api, and for chosen sensitive reads.
- Record refused attempts (a missing module grant, for example) when the token is valid, so the actor is known.
- Store before/after values only for an allow-list of fields.
- Provide an `/audit-log` screen in the admin portal with filters and a detail view, behind its own module.
- Delete events after 2 years, automatically.
## Non-goals
- Member and public calls. The customer portal's public lead capture has no actor.
- Sign-in, sign-out and own password change. `login_audit` already records these; the audit log neither duplicates nor links to them.
- Page views and ordinary reads (the existing response-time log covers traffic).
- Reviving or cleaning up the legacy `back_office_access_log`, `/log/save` and similar. They are unused; removing them belongs in a separate change.
## Anti-goals
- Any password, token, raw request body, or lead personal data (name, phone, email, notes) in an audit row.
- An audit write that slows down or fails the admin's action.
- Audit rows that anyone without `BO_AUDIT_LOG` can read.
## Approaches considered
- **A. Pub/Sub from mobile-api's `AppAccessAspect` to services-log (chosen).** The aspect already sees every admin call (the user, its `@AdminModule` code, the outcome) and already publishes a `ResponseTime` record per call to services-log over Pub/Sub. One more message type on the same path is the smallest change. It is asynchronous, and losing an event is acceptable.
- **B. A synchronous REST call from mobile-api to services-log, like `login_audit`.** Simpler to test, but it adds a network hop to every admin write, and it needs its own error handling.
- **C. Explicit calls inside each service method.** Easy to forget on new endpoints. Rejected: the aspect covers new endpoints by default.
## Design
### Event table `service-log`.`audit_event`
| Column | Meaning |
|---|---|
| `id` | PK |
| `company_id` | the actor's company (nullable) |
| `occurred_at` | server time of the call |
| `actor` | admin username |
| `module` | the handler's `@AdminModule` code (for example `BO_USERS`) |
| `action` | readable action code (see below) |
| `http_method`, `path_template` | for example `PUT /api/admin/users/{id}`: the template, never the concrete path or the query |
| `target_id` | the record acted on: the first path variable, when there is one |
| `outcome`, `http_status` | `SUCCESS` or `FAILURE`, plus the status code |
| `client_ip` | forwarded browser IP (nullable) |
| `changes` | JSON, nullable: `{field: {before, after}}` for allow-listed fields, or `{fields: [..]}` for lead edits |
Indexes: `occurred_at`, `(actor, occurred_at)`, `(module, action, occurred_at)`. The DDL and the module row go in the change's `sql/` folder and in `local/seed/03-colite.sql`.
### What is recorded
- **Every non-GET handler under `/api/admin/**`,** except:
- `AdminAuthController`'s login, logout, refresh, forgot-password and change-password. Sign-in history covers these, or they have no actor.
- `first-login` is recorded.
- POSTs that only read, marked with `@Audited(skip = true)`. Today that is event-lead `match`.
- **Sensitive GETs, marked with `@Audited`:**
- the lead export;
- the event-lead export;
- the email detail (opening an email).
- **Refusals:** a valid admin token refused by the access check (missing module, not super admin, pending first login) is recorded as `FAILURE` with the status. Calls without a valid token are not recorded, because there is no actor.
### Action codes
`@Audited(action = "...")` names an action explicitly. Without one, the code is derived from the handler: drop an `Admin` prefix and a `Controller` suffix, then convert both parts to UPPER_SNAKE. For example, `AdminUserController.update` becomes `USER_UPDATE`. Explicit names are used where the derived one would be unclear:
- `USER_SET_TEMPORARY_PASSWORD`;
- `USER_SEND_PASSWORD_RESET`;
- `ROLE_SET_MODULES`;
- `LEAD_EXPORT`;
- `EVENT_LEAD_EXPORT`;
- `EMAIL_VIEW`.
### Before/after (allow-listed)
The handler's service supplies the values through a small request-scoped holder (babyboo's `AuditChanges`). Nothing is diffed generically from request bodies.
- **Admin user update and create:** `roles` (role names) and `enabled`.
- **Role module grants:** module codes added and removed.
- **Lead edit and event-lead edit:** the names of the fields that changed, no values. This was the user's call.
- **Login-security settings** (lockout and password rules): the changed setting names with before and after. These are not personal data.
### Write path
- After the handler returns or throws, `AppAccessAspect` builds an `AuditEvent` and publishes it to the new Pub/Sub topic `audit-event`. The `AuditEvent` message class lives in core-libs, shared by mobile-api and services-log.
- services-log subscribes on `audit-event-log`, which it creates at startup like its existing subscriptions, and saves the event.
- A publish failure is logged at WARN and swallowed. The existing response-time publishing is unchanged.
### Client IP
- The portal's server-side calls to mobile-api already send `X-Client-Ip` on every request (`app/lib/server/mobileApi.ts`, the last `x-forwarded-for` hop), so the portal needs no change.
- mobile-api stores the value for reading only.
### Retention
A scheduled purge in services-log deletes events older than `audit.retention-days` (default 730) in batches, modelled on the existing response-time archive scheduler. The setting is an environment variable.
### Reading
- services-log gets `POST /log/audit/search`. It takes filters (actor, module, action, outcome, date range) and paging, returns newest first, and caps the page size at 100.
- services-log also gets `GET /log/audit/{id}`.
- Both are reached through the gateway with the admin's token, like the other services. Only mobile-api holds a gateway key (`docs/deployment.md` section 7).
- mobile-api adds `GET /api/admin/audit-log` and `GET /api/admin/audit-log/{id}` under `@AdminModule("BO_AUDIT_LOG")`.
### Admin portal
- **`/audit-log`:** a paged list (newest first) with columns time, who, module, action, target, outcome and IP.
- **Filters:** who, module (select), action, outcome and From/To date.
- **Detail page:** the event, plus a before/after table, or a list of changed field names for lead edits.
- **Copy and gating:** all copy goes through `t()`. The page is gated by `RequireModule` and `ROUTE_MODULES`.
- **Module row:** `(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText')`. It has no role grants, so only super admins see it until it is granted.
## My calls (check these)
- Pub/Sub, asynchronous, best-effort. A lost event is acceptable, as in babyboo.
- Reads go through the gateway with the admin's token. babyboo switched to in-cluster calls because other api-key holders existed; Co-Lite has only mobile-api.
- `first-login` is recorded and the other auth endpoints are not.
- The login-security settings record values, since they are not personal data. User changes record role names and the enabled flag only.
- Retention is 730 days, set by environment variable rather than on a screen.
- Legacy `/log/save` and the old access-log tables are left alone.
## Left to the builder
- The exact JSON shape of `changes`, as long as the detail view can render it.
- Column widths, so the list fits at 1280 px without horizontal scrolling (babyboo hit this).
@@ -0,0 +1,150 @@
# Admin Login Security and Own Password Change — Design
Date: 2026-11-30. Change id: `add-admin-login-security`.
## Intent
Before go-live (2027-01-15), staff must be able to change their own password, and the admin login must resist password guessing. Today nothing counts failed logins: anyone who reaches the login page can try passwords without limit. The admin portal has no way to change your own password, and no way to see or unlock locked staff.
The user chose a persisted login history (babyboo's `login_audit` approach) over a Redis counter, because the history also serves the later audit-log viewer.
## Goals
- Every admin login attempt, logout and unlock is recorded with time, username, outcome, client IP and user agent.
- After a configured number of failed attempts in a configured period, the username is locked. A locked username is refused even with the right password.
- An admin can see locked staff and unlock them.
- An admin can read the login history, filtered by username, outcome and date.
- An admin can edit the lockout settings and the admin password rules.
- Any signed-in admin can change their own password from the user menu.
## Non-goals
- Session policy (logout revocation, sliding sessions, single session). babyboo bundled this; it stays out.
- MFA, CAPTCHA, password aging and password history.
- Member, stockist and customer logins. Admin (type A) only.
- Purging old `login_audit` rows. The volume is small for one company; add a purge when it matters.
## Anti-goals
- A services-system outage must not lock out every admin. The lock check fails open on infrastructure errors.
- The login answer must not reveal whether a username exists.
- A failed audit write must not block a valid login.
## Approaches considered
- **A. Redis counter:** one key per username with a TTL. Cheapest, but keeps no history.
- **B. Persisted `login_audit` table (chosen):** lock state is derived from the history. It costs a new table and deploy SQL, and it gives the history the audit viewer needs.
- **C. In-memory counter like the legacy backoffice:** lost on restart and not shared between instances. Rejected.
## Design
### Where it is enforced
In mobile-api `AdminAuthController.login`, not in services-auth (babyboo's choice). Reason: in Co-Lite only the admin portal is public (Traefik, `docs/deployment.md` section 8), and only mobile-api holds a gateway key (`appkeys.json`, section 7). Every admin login therefore passes through `AdminAuthController.login`. Enforcing there leaves the shared services-auth credential path untouched.
### Table
`service-system`.`login_audit`, created by SQL in the change folder and in `local/seed/03-colite.sql`:
| Column | Type | Note |
|---|---|---|
| `id` | BIGINT PK auto | |
| `company_id` | BIGINT NULL | the user's company when the username matches a user, else NULL |
| `username` | VARCHAR(191) | as typed, trimmed, cut to 191 |
| `datetime` | DATETIME | server time |
| `event` | VARCHAR(20) | `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOGIN_LOCKED`, `LOGOUT`, `UNLOCK_RESET`, `PASSWORD_CHANGED` |
| `ip_address` | VARCHAR(64) | |
| `user_agent` | VARCHAR(512) | cut to 512 |
| `message` | VARCHAR(255) | for example who unlocked |
Indexes: `(username, datetime)` for the lock count and `(event, datetime)` for the listing.
### Lock rule
Settings live in `system_property`:
- `ADMIN_LOGIN_BLOCK_PERIOD` (type `ADMIN_LOGIN_BLOCK`): the value is the period length. Status `Y` turns lockout on.
- `ADMIN_LOGIN_BLOCK_TIME_UNIT`: S, M, H or D.
- **New row** `ADMIN_LOGIN_MAX_ATTEMPT` (type `ADMIN_LOGIN_BLOCK`): the number of failures that locks.
The seeded period is 1 minute, which is too weak. Deploy SQL sets the defaults to **5 attempts in 15 minutes**.
A username is locked when lockout is on and the number of `LOGIN_FAIL` rows meets both conditions below, and that number is at least the maximum:
- the row is newer than (now minus period);
- the row is newer than the latest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED` for that username.
The lock ends by itself once the failures age out of the period. Logout does not reset the count.
Failures are counted for any username, known or not. A locked answer therefore does not show that the account exists. Trade-off: anyone can lock a real admin out for one period by guessing wrong. The Unlock button and the expiry limit the damage.
### services-system `/loginSecurity`
All rules are read and written here:
- `GET /loginSecurity/isLocked/{username}`: `{locked: boolean}`.
- `POST /loginSecurity/record`: `{username, event, ip, userAgent, message}`. Fills `company_id` from the user table.
- `POST /loginSecurity/audit`: paged and filtered (username contains, event, from, to), newest first.
- `GET /loginSecurity/locked`: the usernames locked now, with failure count, last failure time and when the lock ends.
- `POST /loginSecurity/unlock/{username}`: writes `UNLOCK_RESET` with the unlocking admin in `message`.
- `GET` and `POST /loginSecurity/config`: lockout on/off, max attempts, period and unit.
- Password rules: `GET` and `POST` for the `ADMIN_PWD_FORMAT` rows. Only status and value can change; rows cannot be added or removed.
### mobile-api login flow
1. Blank username or password returns 401 `BAD_LOGIN`, as today, and nothing is recorded.
2. Call `isLocked`. If the answer is locked, record `LOGIN_LOCKED` and return 401 with code `ACCOUNT_LOCKED` and the message "Too many failed sign-ins. Try again later or ask an administrator to unlock your account." If services-system errors, log a warning and carry on (fail open).
3. Run the existing credential check. A bad password, an unknown user or a disabled user records `LOGIN_FAIL`. A success records `LOGIN_SUCCESS`.
4. Recording is best-effort: a failure is logged and never changes the answer.
Logout records `LOGOUT`.
The client IP and user agent come from the portal: its login and logout routes forward `X-Forwarded-For` (first hop, as set by Traefik) and `User-Agent`. mobile-api uses them for the audit only, never for any decision.
### Own password change
`POST /api/admin/auth/change-password` takes `{currentPassword, newPassword, confirmPassword}`. Any signed-in admin may call it, except one with a pending first-login change, who uses first-login instead.
- A missing field returns 400 `REQUIRED_FIELD`.
- New and confirm differ: 400 `PASSWORD_MISMATCH`.
- New equals current: 400 `PASSWORD_SAME`.
- New fails `ADMIN_PWD_FORMAT`: 400 `PASSWORD_POLICY`.
- A wrong current password records `LOGIN_FAIL` and returns 400 `CURRENT_PASSWORD_WRONG`. A stolen session therefore cannot guess the password without limit: the failures lock the username like failed logins do.
- If the username is locked: 400 `ACCOUNT_LOCKED`, checked before the current password.
- On success: save the bcrypt of the new password, keep `login = Y`, record `PASSWORD_CHANGED`, return 204. The session stays signed in.
The builder decides how to check the current password. Prefer the bcrypt match services-auth already uses over issuing and revoking a throwaway token.
### Admin portal
- **User menu:** a "Change password" item opens a dialog with current, new and confirm fields, reusing `PasswordFields`. On success it shows a toast and closes. Errors show the server message through `t()`.
- **Login page:** shows the `ACCOUNT_LOCKED` message when the server returns that code.
- **New screen `/login-security`:** module `BO_LOGIN_SECURITY`, id `41000000`, url `/login-security`, a shield-style icon. It has three tabs:
1. **History:** a DataTable with time, username, event, IP and user agent. Filters: username, event, from date, to date.
2. **Locked:** username, failures, last failure and lock end, with an Unlock button that asks for confirmation.
3. **Settings:** lockout on/off, max attempts, period and unit; then each admin password rule with an on/off switch and a value.
- Settings changes and unlocks log `{action} by {admin}` in mobile-api.
### Deploy SQL (in the change folder; also in the local seed)
1. `CREATE TABLE login_audit`.
2. Insert `ADMIN_LOGIN_MAX_ATTEMPT` = 5, status Y. Update the period to 15, keeping unit `M`.
3. Insert the module row `BO_LOGIN_SECURITY`.
A rollback script drops the table and both rows.
## My calls (check these)
- Enforcement sits in mobile-api, not services-auth, because mobile-api is the only path in.
- Defaults: 5 attempts in 15 minutes.
- Failures are counted for unknown usernames too, so a lock does not reveal which accounts exist.
- A wrong current password on change-password counts as a failed login.
- Changing your password does not sign out your other sessions. That belongs to session policy, which is a non-goal.
- The Settings tab is gated only by the module grant, like the other screens, and every change is logged. It is not limited to super admins.
- There is no purge of `login_audit`.
## Left to the builder
- The exact DataTable columns on phone widths and the icon choice.
- Pagination limits: follow `AdminEmailService` (max 100).
- Whether the lock query is a single SQL query or a JPA query plus code, as long as the rule above holds.
@@ -0,0 +1,143 @@
# Company Scoping — Design
Date: 2026-11-30. Change id: `add-company-scoping`.
## Intent
Co-Lite goes live on 2027-01-15 with two test-run companies, INS and CV. This replaces the earlier "single company at go-live" decision (`docs/feature-list.md`, Tenancy). Each company's staff must see only their own company's data. One super admin sees and manages everything, including creating companies. More companies will follow, and adding one must need no code change, no deploy and no database work: the super admin creates it on a screen.
Everything built so far assumes one company. Some of it is already scoped: leads, event leads, interests and event salespersons are queried by the caller's company. The rest is not: users, events, emails, login history and the audit log. The super admin cannot see across companies at all.
## Decisions taken with the user (2026-11-30)
- **Separated per company:** leads, event leads, events, users, emails, login history, audit events.
- **Shared by all companies:** roles, interests, lockout settings, password rules.
- **Super admin:** a super admin can do everything. It sees every company's data, through a company picker and through mixed lists with a Company column. It creates the companies.
- A super admin is an account with **no company** that holds the super admin role. There can be more than one (a second one is kept for recovery); only a super admin can create another.
- Company staff can never hold the super admin role.
- **Sign-in:** the login page asks for **Company** (for example `ins`), **Username** and **Password**. A super admin leaves Company empty. Usernames are unique **within a company**, so INS and CV can each have a `john` (approach B below).
- **Editing shared data:** only a super admin edits roles, interests, lockout settings and password rules.
- **Leads:** the same phone at two companies is two separate leads, each with its own New/Existing history. This is already how leads work.
## Goals
- A Companies screen where the super admin creates and edits companies.
- Company + username sign-in for company staff; username only (Company empty) for super admins.
- Every admin API and screen returns only the caller's company data, unless the caller is the super admin.
- The super admin can see all companies at once or pick one, and can create data in a chosen company.
- Interests become one shared list.
## Non-goals
- Members and the customer portal. Member accounts and member sign-in are unchanged.
- A company admin who manages their own company's roles, interests or settings. These are shared, so only a super admin edits them.
- Per-company branding, logos, web addresses or settings.
- Moving or splitting existing data between companies beyond the one-time setup below.
- Deleting a company. A company can be deactivated.
## Anti-goals
- Any path where a company's staff can read or change another company's data: list, detail, export, edit by id, or audit.
- A change to how members sign in.
- A sign-in answer that reveals whether a company code or a username exists.
- A cross-company leak through a shared table (interests, roles) or through the audit log.
## Approaches considered (for `username@account`)
- **A. The suffix is part of the stored username** (`john@ins` saved as the username, globally unique). Smallest change; the sign-in path is untouched. A company's code could never change once users exist. Not chosen.
- **B. Usernames unique per company; the company is given at sign-in (chosen by the user).** `john` is stored with company INS. Sign-in finds company `ins`, then the user `john` in it. A company's code can change later. It touches the sign-in lookup, the uniqueness rule, token identity, lockout keys and password reset.
- **Login page shape (chosen by the user):** a separate Company field, rather than one `john@ins` field or a company dropdown. A dropdown was rejected because the public login page would list every customer company.
## Design
### Companies
- `company` gains `code` (lowercase letters, digits and hyphens, 2 to 20 characters, unique) and `status` (`A` active, `I` inactive). `name` stays.
- **Companies screen** `/companies` in the admin portal, **super admin only** (not a grantable module): list, create, edit name, code and status. Changing a code changes every staff sign-in for that company; the screen warns before saving.
- An inactive company's staff cannot sign in. Their data is kept and the super admin still sees it.
### Identity: the login name
- The login page sends company code, username and password. Internally a staff user's **login name** is `username@code`; a super admin's login name is its plain username (`admin`), and it belongs to no company (`company_id` NULL). The login name is never typed by staff; it is how the system refers to them.
- The login name is the one string that identifies a staff user everywhere the system uses a string today:
- the JWT subject;
- every `findByUsername`-style lookup from a token (mobile-api resolves the caller about 40 times this way);
- the lockout key and the `login_audit` username;
- the audit event actor;
- forgot-password and the temporary-password flows.
- **Lookup rule (one place, services-system):** a login name with an `@` splits at the **last** `@` into username and code; the user is found by company code and username, and must be type `A` in an active company. A login name without `@` matches only a user with no company, which is the super admin.
- **Uniqueness:** staff usernames are unique per company; the super admin's username is unique among company-less admin users. Member usernames keep their current global uniqueness. The database enforces it (left to the builder: for example a maintained, uniquely indexed `login_name` column, rewritten in one transaction when a company's code changes).
- Changing a company's code changes its users' login names. Existing sessions of those users end; they sign in again with the new code.
- Sign-in errors stay as they are: a wrong or inactive company, an unknown user and a wrong password all give the same `BAD_LOGIN` answer.
- **Forgot password** takes company, username and email, like sign-in. **Email** is unique per company, not across companies, so one person can have an account at INS and at CV.
### Super admins
- Cross-company access means: the caller has **no company and holds the super admin role** (role id 1). Both are required.
- The role cannot be granted to a user who has a company, and a company-less user must hold it: every other user belongs to a company. The Users screen enforces this, and services-system rejects it too.
- A super admin creates another super admin from the Users screen by leaving the company empty.
### Scoping rule
- **Company staff:** every admin read, write, export and detail lookup is limited to the caller's company. A record of another company answers 404, as if it did not exist.
- **Super admin:** sees all companies by default. Lists take an optional company filter. Creating a company-owned record (user, event, event lead capture) requires a company: the super admin picks one in the form.
- Enforcement is server-side in mobile-api's admin services, which already pass the caller's company to services-counter. The portal only reflects it.
### What is scoped where
| Data | Today | Change |
|---|---|---|
| Leads, event leads, event salespersons | scoped by caller company | super admin: all or the picked company |
| Interests | per company | **shared**: one list for all companies; editing super admin only |
| Events (`event`) | no company | add `company_id`; scope like leads |
| Users | no scoping | scope by company; staff manage only their own company's users |
| Roles | global | stay shared; editing becomes super admin only |
| Emails (`email`) | no company | add `company_id` (the company of the user the email is for); scope; emails with no company are visible to the super admin only |
| Login history, locked users | `login_audit.company_id` exists, not used | scope by company; staff with Login security unlock only their own company's users |
| Lockout settings, password rules | global | stay shared; editing becomes super admin only |
| Audit log | `company_id` stored, not used | scope by company |
### Interests become shared
- `interest.company_id` is no longer used for scoping; the unique key moves from `(company_id, name)` to `name`.
- Existing interests: at go-live there is one company, so its list becomes the shared list.
- Only a super admin adds, renames or deactivates interests. Company staff pick from the list when capturing leads.
### Which company an audit row belongs to
- An audit event and a login-history row carry the **actor's** company, as stored today.
- A super admin's actions therefore have no company and are visible to super admins only, even when they changed a company's record. Resolving the changed record's company for every audited endpoint is out of scope.
- A failed sign-in carries the company when the code matches a company, and none otherwise; rows with no company are visible to super admins only.
### Admin portal
- **Header company picker, super admin only:** "All companies", then each company. It sets the company filter for lists and the default company for create forms. Company staff do not see it.
- **Lists, super admin with "All companies":** a Company column on users, events, leads, event leads, emails, login history and audit log.
- **Create forms, super admin:** a Company field, prefilled from the picker. Company staff never see it.
- **Sign-in page:** Company, Username and Password fields. A super admin leaves Company empty. Forgot password asks for the same Company and Username plus the email.
- **Users screen:** company staff create users in their own company. A super admin picks the company, or leaves it empty to create another super admin.
- **Screens that become super admin only:** Companies, Roles, Interests, and the Login security Settings tab.
### One-time setup (deploy SQL)
- Add `code` and `status` to `company`; add `company_id` to `event` and `email`; move the interest unique key; add the user uniqueness change.
- Create INS and CV with their codes. The existing company row (id 1, "Co-Lite") becomes INS, so existing local and test data lands there.
- The existing super admin account (`admin`) gets `company_id` NULL. Every other existing admin user stays in company 1 (INS).
- Existing events and emails get company 1.
- Co-Lite is not deployed anywhere yet, so the setup runs on a fresh database. The deploy ends every existing session, because the token identity changes. No existing admin username contains `@`; the deploy SQL checks this and stops if one does.
## My calls (check these)
- Another company's record answers 404, not 403, so its existence is not revealed.
- Audit and login-history rows belong to the actor's company; a super admin's actions are visible to super admins only.
- Email is unique per company; forgot password takes company, username and email.
- The existing company becomes INS; CV starts empty.
- Inactive companies block their staff's sign-in; there is no delete.
- Changing a company's code or deactivating it ends its staff's sessions.
## Left to the builder
- How login-name uniqueness is enforced in MySQL (a maintained `login_name` column is one way).
- Whether the company code is cached or looked up per request.
- Exact column widths for the Company column, and how the picker looks in the header.
- Splitting the work into tasks, ordered so that sign-in keeps working at every step.
@@ -0,0 +1,103 @@
# Lead Dashboard — Design
Date: 2026-12-01. Status: draft for approval.
## Why
Co-Lite exists to generate leads for INS and CV marketing. Managers need to see which events, salespeople and interests produce leads and which of those leads convert. Today the portal home page is a welcome line, and the system keeps only each event lead's current status, so it cannot say when a lead was won or how long it took.
## Goals
- A dashboard on the portal home page showing lead capture and conversion for a chosen period.
- Record every event-lead status change with its time, so the dashboard can count wins in a period and time to win.
- Gate the dashboard with a new ACL module, `BO_DASHBOARD`, assigned to roles like every other module.
- Company scoping as everywhere else: staff see their company, super admins see all or the one picked.
## Non-goals
- New lead statuses or a pipeline editor. The existing statuses stay: OPEN, CONTACTED, QUALIFIED, WON, LOST.
- Member-app conversion (option 2). It comes later as its own change.
- Showing the status timeline on the lead or event-lead screens. The data will exist; a later change can show it.
- Excel export of the dashboard.
- Demographics (age, gender, state) as in the legacy event statistics: Co-Lite leads carry none of those fields.
## Anti-goals
- Numbers that disagree with the Leads and Event Leads listings for the same filter.
- SQL built by string replacement (the legacy report service does this; it is an injection risk).
- A slow home page: every user lands there after sign-in.
## Definitions
- **Capture:** one event lead (a person captured at one event). A person captured at two events is two captures. Conversion is per capture, because the question is which events convert.
- **Won:** an event lead whose current status is WON.
- **Won in period:** a won event lead whose latest change into WON falls in the period.
- **Conversion rate:** of the captures made in the period, the share that are now WON.
- **Days to win:** from capture to the latest change into WON, in whole days. Reported as the median.
- **Overdue follow-up:** an event lead that is not WON or LOST and whose next follow-up date is before today. This is a current count, not tied to the period.
- **Clock:** Asia/Kuala_Lumpur, as in the legacy dashboard.
## What the dashboard shows
- **Period:** This month (the default), Last month, or a custom range. A range of up to 62 days is charted by day; a longer one by month (legacy rule).
- **Company picker:** the existing picker, for super admins only.
- **Tiles:**
- Captures.
- New leads (lead type NEW).
- Won in period.
- Conversion rate.
- Median days to win.
- Overdue follow-ups.
- **Funnel:** the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST).
- **Trend chart:** captures and wins per day or month.
- **By event:** each event with captures in the period.
- Columns: event, captures, new, won, conversion rate.
- A super admin viewing all companies also gets a Company column.
- Each row links to that event's leads.
- **By salesperson:** for the period's captures, per salesperson.
- Columns: assigned, worked (status beyond OPEN), won, lost, conversion rate, overdue follow-ups.
- Captures with no salesperson appear as an "Unassigned" row.
- **By interest:** per interest, the captures and wins. A capture with two interests counts under both.
- **Phone width:** tiles stack, and the tables become cards, as on the other listings.
## Status timing
- **New table** `event_lead_status_change` in services-counter, append-only. Columns:
- `id`, `company_id`, `event_lead_id`;
- `from_status` (null for the first row), `to_status`;
- `changed_at`, `changed_by`.
- **Capture** writes the first row: null → initial status, at `captured_at`.
- **An edit that changes status** writes one row in the same transaction. An edit that keeps the status writes nothing.
- **Backfill** for existing event leads, in the change's SQL:
- one row null → OPEN at `captured_at`;
- when the current status is not OPEN, a second row OPEN → status at `updated_at`, or at `captured_at` when `updated_at` is null.
These times are approximate, and the deployment notes say so.
## Access
- **New module** `BO_DASHBOARD`, type M, URL `/`, id `40050000`. The sidebar shows a "Dashboard" link.
- **The home page** shows the dashboard to users with `BO_DASHBOARD`. Everyone else sees today's welcome, not a not-authorised page, because every user lands at home after sign-in.
- **The endpoint** answers 403 without the module.
- **Super admins** pass as they do for every module.
## Approach
Aggregate in services-counter SQL:
- services-counter gets one endpoint, `/counter/dashboard/leads`. It takes `companyId` (null = all), `from`, `to` and the bucket, and runs grouped native queries with bind parameters over `event_lead`, `event_lead_status_change`, `event_lead_interest` and `event`.
- mobile-api adds `GET /api/admin/dashboard/leads` under `@AdminModule("BO_DASHBOARD")`. It applies the company scope, resolves salesperson names in one batch call to services-system, and returns one JSON payload.
Rejected:
- **Aggregating in mobile-api from paged listings:** too many calls, and it gets slower as leads grow.
- **A separate report service like legacy:** a new deployable for one screen.
## Portal
- **Charts:** add `recharts` and copy babyboo's `chart.tsx` wrapper. babyboo already uses both, and the look then matches.
- **The funnel and tables** use existing components (Card, Table, data-table).
## Left to the builder
- Indexes for the dashboard queries, chosen from EXPLAIN on realistic local data: likely `event_lead(company_id, captured_at)` and `event_lead_status_change(event_lead_id, changed_at)`.
- Exact tile layout and copy.
- Message keys for every label (English, as for other screens).
+1
View File
@@ -1,5 +1,6 @@
# topic [subscription] - one per line; created in the Pub/Sub emulator before services start
activate-member-topic activate-member-subscription
audit-event-topic audit-event-subscription
backoffice-topic backoffice-subscription
batch-transfer-member-topic batch-transfer-member-subscription
camunda-new-registration-topic camunda-new-registration-subscription
+129
View File
@@ -124,3 +124,132 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic
-- add-admin-email-listing/sql/01-email-module.sql
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(40900000, 'BO_EMAILS', 'Emails', 'BO', 'M', 40000000, '/emails', 'Mail');
-- add-admin-login-security/sql/01-login-audit.sql
CREATE TABLE IF NOT EXISTS `login_audit` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NULL COMMENT 'the user''s company when the username matches a user',
`username` varchar(191) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'compared like `user`.`username`',
`datetime` datetime NOT NULL,
`event` varchar(20) NOT NULL COMMENT 'LOGIN_SUCCESS | LOGIN_FAIL | LOGIN_LOCKED | LOGOUT | UNLOCK_RESET | PASSWORD_CHANGED',
`ip_address` varchar(64) NULL,
`user_agent` varchar(512) NULL,
`message` varchar(255) NULL,
PRIMARY KEY (`id`),
KEY `idx_login_audit_username_dt` (`username`, `datetime`),
KEY `idx_login_audit_event_dt` (`event`, `datetime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- add-admin-login-security/sql/02-lockout-settings.sql
INSERT INTO `system_property` (`param`, `status`, `type`, `value`)
SELECT 'ADMIN_LOGIN_MAX_ATTEMPT', 'Y', 'ADMIN_LOGIN_BLOCK', '5'
WHERE NOT EXISTS (SELECT 1 FROM `system_property` WHERE `param` = 'ADMIN_LOGIN_MAX_ATTEMPT' AND `type` = 'ADMIN_LOGIN_BLOCK');
UPDATE `system_property` SET `value` = '15', `status` = 'Y'
WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
-- add-admin-login-security/sql/03-login-security-module.sql
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
-- add-admin-audit-log/sql/02-audit-log-module.sql (still USE `service-system` from above)
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText');
-- add-admin-audit-log/sql/01-audit-event.sql
USE `service-log`;
CREATE TABLE IF NOT EXISTS `audit_event` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NULL,
`occurred_at` datetime(6) NOT NULL,
`actor` varchar(191) NOT NULL,
`module` varchar(64) NULL,
`action` varchar(128) NOT NULL,
`http_method` varchar(16) NULL,
`path_template` varchar(255) NULL,
`target_id` varchar(128) NULL,
`outcome` varchar(16) NOT NULL COMMENT 'SUCCESS | FAILURE',
`http_status` int NULL,
`client_ip` varchar(64) NULL,
`changes` text NULL COMMENT 'JSON: allow-listed before/after, or changed field names',
PRIMARY KEY (`id`),
KEY `idx_audit_event_occurred_at` (`occurred_at`),
KEY `idx_audit_event_actor` (`actor`, `occurred_at`),
KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- add-company-scoping/sql/01-company-code-status.sql
USE `service-system`;
ALTER TABLE `company`
ADD COLUMN `code` varchar(20) NULL AFTER `name`,
ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`;
UPDATE `company` SET `name` = 'INS', `code` = 'ins' WHERE `id` = 1;
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'cv', 'A');
ALTER TABLE `company`
MODIFY COLUMN `code` varchar(20) NOT NULL,
ADD UNIQUE KEY `uk_company_code` (`code`);
-- add-company-scoping/sql/02-company-columns.sql
USE `service-counter`;
ALTER TABLE `event` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_event_company` (`company_id`);
UPDATE `event` SET `company_id` = 1 WHERE `company_id` IS NULL;
ALTER TABLE `interest`
DROP INDEX `uk_interest_company_name`,
MODIFY COLUMN `company_id` bigint NULL,
ADD UNIQUE KEY `uk_interest_name` (`name`);
USE `service-email`;
ALTER TABLE `email` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_email_company` (`company_id`);
UPDATE `email` SET `company_id` = 1 WHERE `company_id` IS NULL;
-- add-company-scoping/sql/03-admin-login-names.sql
USE `service-system`;
DROP PROCEDURE IF EXISTS `colite_check_admin_usernames`;
DELIMITER //
CREATE PROCEDURE `colite_check_admin_usernames`()
BEGIN
IF EXISTS (SELECT 1 FROM `user` WHERE `type` = 'A' AND `username` LIKE '%@%') THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An admin username contains @; rename it before running this script';
END IF;
END //
DELIMITER ;
CALL `colite_check_admin_usernames`();
DROP PROCEDURE `colite_check_admin_usernames`;
UPDATE `user` u SET u.`company_id` = NULL
WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins')
WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
-- add-lead-dashboard/sql/01-status-change.sql (02 backfill has nothing to do on an empty volume)
USE `service-counter`;
CREATE TABLE IF NOT EXISTS `event_lead_status_change` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_lead_id` bigint NOT NULL,
`from_status` varchar(10) NULL,
`to_status` varchar(10) NOT NULL,
`changed_at` datetime NOT NULL,
`changed_by` varchar(255) NULL,
PRIMARY KEY (`id`),
KEY `idx_elsc_event_lead` (`event_lead_id`, `changed_at`),
KEY `idx_elsc_company_to_changed` (`company_id`, `to_status`, `changed_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Dashboard capture query: captures by company and capture time.
ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_captured` (`company_id`, `captured_at`);
-- add-lead-dashboard/sql/03-dashboard-module.sql
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard');
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-01
@@ -0,0 +1,95 @@
## Context
Approved product design: `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md` (definitions, figures, access). This file fixes the technical contract so the services-counter, mobile-api and portal tasks can be built in parallel.
Facts the design relies on:
- `event_lead.status` already holds OPEN / CONTACTED / QUALIFIED / WON / LOST (event-lead-capture). Only the current value is stored.
- `event_lead.captured_at` and `updated_at` are `LocalDateTime.now()` in the services-counter JVM, i.e. wall time in the JVM's default zone (UTC in the containers). There is no zone column.
- services-counter has no database tests; every existing test is a Mockito unit test.
- Salesperson names live in services-system; mobile-api already resolves them per user id with a per-request map (`AdminLeadService.salesperson`).
## Decisions
### 1. Status history table
`service-counter.event_lead_status_change`:
- columns `id` bigint PK auto, `company_id` bigint NOT NULL, `event_lead_id` bigint NOT NULL, `from_status` varchar(10) NULL, `to_status` varchar(10) NOT NULL, `changed_at` datetime NOT NULL, `changed_by` varchar(255) NULL;
- key `idx_elsc_event_lead (event_lead_id, changed_at)` and key `idx_elsc_company_to_changed (company_id, to_status, changed_at)`.
`EventLeadService.capture` saves one row (null → initial status, `changed_at` = the event lead's `captured_at`, `changed_by` = doneBy) in the capture transaction. `update` saves one row when the requested status differs from the stored one (`changed_at` = the new `updated_at`). Entity `EventLeadStatusChange`, repository `EventLeadStatusChangeRepository`. Nothing deletes or updates these rows.
Backfill (`sql/02-status-change-backfill.sql`, idempotent: only event leads with no history rows):
- one row null → OPEN at `captured_at`, `changed_by` = `captured_by`;
- where `status <> 'OPEN'`, one row OPEN → status at `COALESCE(updated_at, captured_at)`, `changed_by` = `COALESCE(updated_by, captured_by)`.
### 2. Aggregate in Java over lean rows, not in SQL
services-counter runs three plain native queries with bind parameters and aggregates the rows in a pure Java class (`LeadDashboardCalculator`), which is unit-tested without a database:
1. **Captures:** event leads with `captured_at` in [fromUtc, toUtc) and the company filter, joined to `event` for name and company: `event_lead.id, event_uuid, event name, company_id, salesperson_user_id, lead_type, status, captured_at`.
2. **Wins:** event leads with `status = 'WON'` whose latest history row with `to_status = 'WON'` has `changed_at` in [fromUtc, toUtc): `event_lead.id, captured_at, won_at`.
3. **Overdue:** `salesperson_user_id, COUNT(*)` for status not in (WON, LOST) and `next_follow_up_date < today`, grouped by salesperson.
Interests for the captures come from the existing `EventLeadInterestRepository.findByIdEventLeadIdIn`, in chunks of 1000 ids, and interest names from `InterestRepository`.
Rejected: one grouped SQL query per figure. Its correctness could only be checked against a live database (no DB tests here), and adding Testcontainers is a new build dependency for one screen.
`ponytail:` row volume is one row per capture in the period. Fine for thousands per period; move the sums into SQL when one company captures hundreds of thousands of leads a year.
### 3. Time zone
mobile-api turns the period into dates; services-counter turns `[from 00:00, to+1 00:00)` in Asia/Kuala_Lumpur into the JVM default zone's wall time for the queries, and turns each stored time back to a Malaysian date for bucketing. "Today" for overdue is today in Asia/Kuala_Lumpur.
### 4. services-counter contract
`POST /counter/dashboard/leads` (route already under `/counter/**`), body:
```json
{ "companyId": 2, "from": "2026-11-01", "to": "2026-11-30", "bucket": "DAY" }
```
`companyId` null = all companies. `bucket` is `DAY` or `MONTH`. `from` after `to` → 400 `INVALID_PERIOD`. Response:
```json
{
"captures": 10, "newLeads": 6, "wonInPeriod": 3, "medianDaysToWin": 5, "overdueFollowUps": 4,
"funnel": { "OPEN": 3, "CONTACTED": 1, "QUALIFIED": 1, "WON": 3, "LOST": 2 },
"trend": [ { "bucket": "2026-11-01", "captures": 2, "wins": 0 } ],
"events": [ { "eventUuid": "123", "name": "KL Expo", "companyId": 2, "captures": 10, "newLeads": 6, "won": 3 } ],
"salespeople": [ { "userId": 7, "assigned": 4, "worked": 3, "won": 1, "lost": 1, "overdue": 2 } ],
"interests": [ { "interestId": 5, "name": "Cookware", "captures": 4, "won": 1 } ]
}
```
- `medianDaysToWin` is null when there are no wins; with an even count it is the lower middle value (whole days).
- `trend` lists every bucket in the period, zero-filled; a month bucket is the month's first day.
- `events` is ordered by captures descending, then name; `salespeople` by assigned descending, with `userId` null for Unassigned; `salespeople` also includes a salesperson with overdue follow-ups but no captures in the period (assigned 0). `interests` by captures descending, then name.
- `eventUuid` is a string (JavaScript loses precision on snowflake ids).
Rates are not sent; the portal divides.
### 5. mobile-api contract
`GET /api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2` under `@AdminModule("BO_DASHBOARD")`:
- `from`/`to` optional; when absent, from = first day of the current Malaysian month, to = today (Malaysia).
- Bad date format, from after to, or a range of more than 731 days (two years) → 400 `INVALID_PERIOD` (ProblemDetail: `code`, `detail`). The cap keeps one request from building an unbounded bucket list in services-counter, which also refuses a range over 731 days.
- bucket = `DAY` when `to - from + 1 <= 62` days, else `MONTH`.
- company from `AdminCompanyScope.scope(caller, companyId)`.
- Response: the counter response plus `from`, `to`, `bucket`, and each salesperson row gains `name` (the user's name, or null for Unassigned and for a user that no longer exists). Salesperson names are resolved with the existing per-request map pattern.
### 6. Module
`service-system.module` row `(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard')`. No role grant: super admins grant it under Roles. Id 40050000 sorts it first in the sidebar, which orders by module id. The portal's route gate (`ROUTE_MODULES`) does not list `/`: the home page itself decides between the dashboard and the welcome, using `hasModule("BO_DASHBOARD")`.
### 7. Portal
- `recharts` added to `package.json`; `app/components/ui/chart.tsx` copied from babyboo's portal.
- `app/lib/services/adminDashboard.ts`: types for decision 5 and `getLeadDashboard({from, to, companyId})`.
- `app/page.tsx`: welcome for users without the module; otherwise the dashboard with a period control (This month / Last month / Custom with the existing date picker), the company picker for super admins (via `useCompanyScope`), tiles, funnel bars, a recharts line or bar chart of captures and wins, and three tables (cards below `md`). Event rows link to `/event-leads/{eventUuid}`. The Company column on the event table shows only when `showCompanyColumn`.
- Rates show as whole percent; a null median or zero captures shows "–".
- All labels are message keys with English defaults, as on other screens.
## Risks
- Backfilled history times are approximate (deployment notes say so).
- A lead whose status was set by a direct DB edit has no history row for that change; the dashboard then misses that win. Nothing in the app does this.
- `captured_at` stored in the JVM zone: if production pods ever run in a different zone from when rows were written, older rows shift. Same risk already exists for every listing.
@@ -0,0 +1,33 @@
## Why
Co-Lite exists to generate leads for INS and CV marketing. Managers need to see which events, salespeople and interests produce leads and which of those leads convert (status WON). Today the portal home page is a welcome line, and the system keeps only each event lead's current status, so it cannot say when a lead was won or how long it took. Approved design: `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md`.
## What Changes
- Every event-lead status change is recorded with its time and who made it. Capture records the first status. Existing event leads are backfilled with approximate times.
- A lead dashboard on the portal home page for a chosen period (this month, last month, or a custom range):
- tiles: captures, new leads, won in period, conversion rate, median days to win, overdue follow-ups;
- a status funnel;
- a trend of captures and wins;
- tables by event, by salesperson and by interest.
- A new back-office module `BO_DASHBOARD` gates the dashboard. Users without it keep the welcome page.
- Company scoping as on every other admin screen.
- The admin portal gains the `recharts` dependency (already used by babyboo's portal) for the trend chart.
## Capabilities
### New Capabilities
- `lead-dashboard`: the dashboard, its definitions, period rules, access and company scope.
### Modified Capabilities
- `event-lead-capture`: adds the status change history requirement.
## Impact
- Database `service-counter`: new table `event_lead_status_change`, a backfill, and an index on `event_lead`. `service-system`: one `module` row. SQL in `sql/`, mirrored in `local/seed/03-colite.sql`.
- `solvway-services-counter`: history writes on capture and edit; a new dashboard endpoint.
- `solvway-mobile-api`: `GET /api/admin/dashboard/leads`.
- `solvway-admin-portal`: home page, sidebar link, `recharts`.
- `docs/deployment.md`: the new SQL files.
@@ -0,0 +1,22 @@
## ADDED Requirements
### Requirement: Event lead status history
The system SHALL record every change of an event lead's status with the previous status, the new status, the time and the user who made it. Capturing an event lead SHALL record its first status with no previous status, at the capture time. An edit that leaves the status unchanged SHALL record nothing. The history SHALL never be edited or deleted through the application.
#### Scenario: Capture records the first status
- **WHEN** staff capture a lead at an event with no status chosen
- **THEN** the history holds one entry from no status to OPEN at the capture time, by that user
#### Scenario: Status change recorded
- **GIVEN** an OPEN event lead
- **WHEN** staff change its status to CONTACTED and later to WON
- **THEN** the history holds OPEN to CONTACTED and CONTACTED to WON, each with its time and user
#### Scenario: Edit without a status change
- **GIVEN** a CONTACTED event lead
- **WHEN** staff change only its temperature and notes
- **THEN** no history entry is added
@@ -0,0 +1,152 @@
## ADDED Requirements
### Requirement: Dashboard access
The system SHALL show the lead dashboard on the back-office home page to users granted the `BO_DASHBOARD` module, and SHALL show users without it the welcome message instead of a not-authorised page. The dashboard endpoint SHALL answer 403 to a user without `BO_DASHBOARD`. The sidebar SHALL show a Dashboard link to users with the module.
#### Scenario: Granted user
- **GIVEN** a role holding `BO_DASHBOARD` is assigned to `sales1`
- **WHEN** `sales1` signs in
- **THEN** the home page shows the lead dashboard and the sidebar shows Dashboard
#### Scenario: User without the module
- **WHEN** a user without `BO_DASHBOARD` opens the home page or calls the dashboard endpoint
- **THEN** the page shows the welcome message and the endpoint responds 403
### Requirement: Dashboard period
The dashboard SHALL cover a period of whole days in Malaysia time (Asia/Kuala_Lumpur): this month up to today (the default), last month, or a custom range from one date to another, both included. A range whose start is after its end, or that spans more than 731 days, SHALL be refused with a message. The trend SHALL be counted by day for a period of up to 62 days and by month for a longer one, and SHALL list every day or month in the period, with zero where nothing happened.
#### Scenario: Default period
- **WHEN** a user opens the dashboard on 2026-12-10
- **THEN** it covers 2026-12-01 to 2026-12-10, with one trend point per day
#### Scenario: Long range counted by month
- **WHEN** the user picks 2026-01-01 to 2026-12-31
- **THEN** the trend has one point per month, January to December
#### Scenario: Day boundary in Malaysia time
- **GIVEN** a lead captured at 2026-11-30 23:30 Malaysia time
- **WHEN** the user views 2026-11-01 to 2026-11-30
- **THEN** the capture is counted on 30 November
#### Scenario: Reversed range
- **WHEN** the user picks a start date after the end date
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
#### Scenario: Range too long
- **WHEN** the user picks 2024-01-01 to 2026-12-31
- **THEN** the dashboard shows a message and no figures, and the endpoint responds 400
### Requirement: Capture figures
For the chosen period the dashboard SHALL show the captures (event leads captured in the period, so a person captured at two events counts twice), the new leads (captures whose lead type is NEW), the conversion rate (the share of the period's captures whose current status is WON, shown as a dash when there are no captures), a funnel of the period's captures by current status (OPEN, CONTACTED, QUALIFIED, WON, LOST) and the captures in the trend.
#### Scenario: Conversion of the period's captures
- **GIVEN** 10 leads captured in November, 3 of them now WON and 2 LOST
- **WHEN** the user views November
- **THEN** captures show 10, conversion rate 30%, and the funnel shows WON 3 and LOST 2
#### Scenario: No captures
- **WHEN** the user views a period with no captures
- **THEN** captures show 0 and the conversion rate shows a dash
### Requirement: Win figures
The dashboard SHALL count as won in the period every event lead whose current status is WON and whose latest change to WON falls in the period, whenever it was captured. It SHALL show that count, the wins in the trend, and the median of whole days from capture to the latest change to WON over those event leads, shown as a dash when there are none.
#### Scenario: Win of an older capture
- **GIVEN** a lead captured in October and changed to WON on 5 November
- **WHEN** the user views November
- **THEN** won in period counts it and the November captures do not
#### Scenario: Reopened lead
- **GIVEN** a lead changed to WON on 3 November, back to QUALIFIED on 4 November, and to WON again on 20 November
- **WHEN** the user views 1 to 10 November
- **THEN** won in period does not count it, because its latest change to WON is 20 November
#### Scenario: Median days to win
- **GIVEN** three leads won in November, 2, 5 and 30 days after capture
- **WHEN** the user views November
- **THEN** median days to win shows 5
### Requirement: Overdue follow-ups
The dashboard SHALL show the event leads that are not WON or LOST and whose next follow-up date is before today in Malaysia time, whatever the chosen period.
#### Scenario: Overdue counted regardless of period
- **GIVEN** an OPEN lead captured in August with next follow-up 2026-12-01
- **WHEN** the user views November on 2026-12-05
- **THEN** overdue follow-ups count it
### Requirement: Breakdown by event
The dashboard SHALL list each event with captures in the period, most captures first, with its captures, new leads, won and conversion rate, and each row SHALL open that event's leads listing.
#### Scenario: Event drill-down
- **WHEN** the user selects an event row
- **THEN** that event's leads listing opens
### Requirement: Breakdown by salesperson
The dashboard SHALL list, for the period's captures, each salesperson's assigned, worked (status other than OPEN), won, lost and conversion rate, with their current overdue follow-ups, and SHALL show captures with no salesperson as Unassigned.
#### Scenario: Salesperson row
- **GIVEN** in November `sales1` was assigned 4 captures: 1 OPEN, 1 CONTACTED, 1 WON and 1 LOST
- **WHEN** the user views November
- **THEN** sales1's row shows assigned 4, worked 3, won 1, lost 1 and conversion rate 25%
#### Scenario: Unassigned captures
- **GIVEN** 2 November captures have no salesperson
- **WHEN** the user views November
- **THEN** an Unassigned row shows assigned 2
### Requirement: Breakdown by interest
The dashboard SHALL list each interest with the period's captures tagged with it and how many of them are now WON. A capture with two interests SHALL count under both.
#### Scenario: Two interests
- **GIVEN** a November capture tagged `Cookware` and `Kitchen appliances`, now WON
- **WHEN** the user views November
- **THEN** both interests count 1 capture and 1 won
### Requirement: Phone width
The dashboard SHALL be usable on a 360 px wide screen without sideways scrolling.
#### Scenario: Phone
- **WHEN** a user opens the dashboard at 360 px
- **THEN** the tiles stack and the breakdowns show as cards
### Requirement: Dashboard company scope
The dashboard SHALL count only the records of the caller's company for company staff. A super admin SHALL see every company's records by default and SHALL be able to narrow the dashboard to one company with the company picker; while all companies are shown, the by-event list SHALL show each event's company.
#### Scenario: Staff see their company
- **GIVEN** leads captured at INS and at CV events in November
- **WHEN** an INS user with `BO_DASHBOARD` views November
- **THEN** every figure counts INS records only
#### Scenario: Super admin picks a company
- **WHEN** a super admin picks CV in the company picker
- **THEN** every figure counts CV records only
@@ -0,0 +1,19 @@
-- Co-Lite change add-lead-dashboard: event lead status history (design decision 1).
-- Target: `service-counter`. Additive only. Run before the new images go live (services-counter writes this table), then 02.
USE `service-counter`;
CREATE TABLE IF NOT EXISTS `event_lead_status_change` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NOT NULL,
`event_lead_id` bigint NOT NULL,
`from_status` varchar(10) NULL,
`to_status` varchar(10) NOT NULL,
`changed_at` datetime NOT NULL,
`changed_by` varchar(255) NULL,
PRIMARY KEY (`id`),
KEY `idx_elsc_event_lead` (`event_lead_id`, `changed_at`),
KEY `idx_elsc_company_to_changed` (`company_id`, `to_status`, `changed_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Dashboard capture query: captures by company and capture time.
ALTER TABLE `event_lead` ADD KEY `idx_event_lead_company_captured` (`company_id`, `captured_at`);
@@ -0,0 +1,15 @@
-- Co-Lite change add-lead-dashboard: history for event leads captured before the history existed.
-- Target: `service-counter`. Idempotent: touches only event leads with no history row. Times are approximate:
-- the first status at capture, the current status (if not OPEN) at the last update.
USE `service-counter`;
INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`)
SELECT el.company_id, el.id, NULL, 'OPEN', el.captured_at, el.captured_by
FROM `event_lead` el
WHERE NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id);
INSERT INTO `event_lead_status_change` (`company_id`, `event_lead_id`, `from_status`, `to_status`, `changed_at`, `changed_by`)
SELECT el.company_id, el.id, 'OPEN', el.status, COALESCE(el.updated_at, el.captured_at), COALESCE(el.updated_by, el.captured_by)
FROM `event_lead` el
WHERE el.status <> 'OPEN'
AND NOT EXISTS (SELECT 1 FROM `event_lead_status_change` s WHERE s.event_lead_id = el.id AND s.to_status = el.status);
@@ -0,0 +1,7 @@
-- Co-Lite change add-lead-dashboard: the Dashboard back-office module (area BO).
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
-- No role grant: super admins see every module; they grant BO_DASHBOARD to other roles under Roles.
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(40050000, 'BO_DASHBOARD', 'Dashboard', 'BO', 'M', 40000000, '/', 'LayoutDashboard');
@@ -0,0 +1,8 @@
-- Co-Lite change add-lead-dashboard: rollback. Drops the status history (its data is lost).
USE `service-system`;
DELETE FROM `modules_roles` WHERE `module_id` = 40050000;
DELETE FROM `module` WHERE `id` = 40050000;
USE `service-counter`;
ALTER TABLE `event_lead` DROP KEY `idx_event_lead_company_captured`;
DROP TABLE IF EXISTS `event_lead_status_change`;
@@ -0,0 +1,63 @@
# Tasks
Design: `design.md` (technical contract) and `docs/superpowers/specs/2026-12-01-lead-dashboard-design.md` (product).
Waves:
- Wave 0 (serial, controller): 1.1 and 1.2 touch hotspots (SQL, seed, `package.json`).
- Wave 1 (parallel, 3 implementers): 2.1, 3.1 and 4.1 build against the fixed contracts in design decisions 4 and 5. Scopes do not overlap: each touches one module.
- Wave 2 (serial, controller): 5.1.
## 1. Data, module and chart dependency
- [x] 1.1 SQL `sql/01..03` and `99-rollback.sql`; mirror 01 and 03 in `local/seed/03-colite.sql` (02 has nothing to backfill on an empty volume); apply 01, 02 and 03 to the local database.
- Depends on: none
- Scope: `local/seed/**`, `openspec/changes/add-lead-dashboard/sql/**`
- Verify: `SELECT` shows the table, the index, the backfilled rows and the module row.
- [x] 1.2 Portal: add `recharts` (same major as babyboo's portal) with `npm install`, and copy babyboo's `app/components/ui/chart.tsx`.
- Depends on: none
- Scope: `solvway-admin-portal/package.json`, `solvway-admin-portal/package-lock.json`, `solvway-admin-portal/app/components/ui/chart.tsx`
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
## 2. services-counter
- [x] 2.1 Status history writes (decision 1) and the dashboard endpoint (decisions 2 to 4).
- Tests first:
- capture saves one history row null → initial status at the capture time, by doneBy;
- update saves one row when the status changes and none when it stays;
- the calculator, from in-memory rows: captures, new leads, funnel, won in period (latest WON only), median days (odd, even, none), overdue per salesperson, Unassigned, salesperson with overdue only, interest double-count, event ordering, zero-filled day and month trend, Malaysia day boundary from JVM-zone times;
- the endpoint rejects from after to with 400 `INVALID_PERIOD` and passes a null company as all companies.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -q -pl solvway-services-counter verify`
## 3. mobile-api
- [x] 3.1 `GET /api/admin/dashboard/leads` (decision 5).
- Tests first:
- default period is this Malaysian month to today; DAY bucket up to 62 days, MONTH above;
- bad date and from after to → 400 `INVALID_PERIOD`;
- staff are scoped to their company, a super admin's `companyId` is passed through, null for all;
- salesperson names resolved, null for Unassigned and for a missing user;
- the endpoint is gated by `BO_DASHBOARD` (aspect test with the annotation).
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
## 4. Portal
- [x] 4.1 Home page dashboard (decision 7).
- Tests first:
- without `BO_DASHBOARD` the welcome shows and the dashboard API is not called;
- with it: tiles, funnel, chart container, the three tables with Unassigned, whole-percent rates and "–" for null median and zero captures;
- period presets send the right `from`/`to`; a reversed custom range shows the error message;
- a super admin's picker sends `companyId` and shows the Company column only for all companies;
- an event row links to `/event-leads/{eventUuid}`;
- the hard-coded copy sweep stays green (labels as message keys).
- Includes the Next proxy route `app/api/dashboard/leads/route.ts` (added after review: the first plan left it out).
- Scope: `solvway-admin-portal/app/api/dashboard/**`, `solvway-admin-portal/app/page.tsx`, `solvway-admin-portal/app/page*.test.tsx`, `solvway-admin-portal/app/components/dashboard/**`, `solvway-admin-portal/app/lib/services/adminDashboard*.ts`, `solvway-admin-portal/app/lib/i18n/defaultMessages.ts`
- Verify: `cd solvway-admin-portal && npm run lint && npx tsc --noEmit && npx vitest run`
## 5. Release
- [x] 5.1 `docs/deployment.md` lists the SQL; live check against the local stack (seeded INS and CV event leads with status changes), and Playwright at 1280 and 360 px for a granted user, a user without the module, and a super admin switching company.
- Depends on: 1.1 to 4.1
- Scope: `docs/deployment.md`, `openspec/changes/add-lead-dashboard/tasks.md`
- Verify: full `mvn -T 1C -q verify` of the three touched Maven modules and the portal verify.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-30
@@ -0,0 +1,100 @@
# Design
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-admin-audit-log-design.md`.
## Context
- **`AppAccessAspect`** (`solvway-mobile-api/.../useraccess/AppAccessAspect.java`) wraps every controller method. It already:
- knows the admin from the JWT;
- resolves `@AdminModule` from the method, falling back to the class;
- refuses with 403 on a missing module, super admin required or pending reset;
- publishes a `ResponseTime` record per call to services-log over Pub/Sub (`response-time-log-topic`).
- **services-log** stores in MySQL schema `service-log` with JPA. It creates its topics and subscriptions at startup (`configuration/PubSubConfig.java`), listens in `pubsub/PubSubListener.java`, and archives response times on a schedule (`scheduler/ResponseTimeLogArchiveScheduler.java`).
- **Local Pub/Sub:** the emulator creates the topics listed in `local/pubsub/topics.txt`.
- **Client IP:** the portal already forwards `X-Client-Ip` on every call (`app/lib/server/mobileApi.ts`).
- **babyboo reference:**
- core-libs `model/AuditEvent.java`;
- mobile-api `useraccess/Audited.java`, `useraccess/AuditChanges.java` and the audit part of `useraccess/AppAccessAspect.java`;
- `service/AuditLogService.java` and `controller/AdminAuditLogController.java`;
- services-log `controller/AuditEventController.java`, `model/AuditEventLog.java`, `repo/AuditEventLogRepository.java` and `service/AuditEventLogPurge.java`;
- portal `app/audit-log/page.tsx` and `app/api/audit-log/**`.
## Goals / Non-Goals
**Goals:**
- record admin writes, refusals and three sensitive reads;
- record allow-listed changes;
- delete events after 730 days;
- an Audit log screen.
**Non-Goals:**
- member and public calls;
- page views;
- sign-ins (covered by `login_audit`);
- legacy `/log/save` cleanup.
## Decisions
1. **`AuditEvent` in core-libs:** fields `companyId`, `occurredAt`, `actor`, `module`, `action`, `httpMethod`, `pathTemplate`, `targetId`, `outcome`, `httpStatus`, `clientIp` and `changes` (a JSON string). It is the shared contract, so it lands first.
2. **Table `service-log`.`audit_event`:**
- Columns follow the event fields.
- `changes` is TEXT.
- Indexes: `occurred_at`, `(actor, occurred_at)` and `(module, action, occurred_at)`.
3. **What the aspect records:**
- **Writes:** every handler under a class mapped to `/api/admin` whose HTTP method is not GET.
- **Sensitive GETs:** handlers annotated `@Audited` (lead export, event-lead export, email detail).
- **Skipped:** handlers annotated `@Audited(skip = true)` (event-lead `match`) and every `AdminAuthController` handler except `firstLogin`.
- **Actor required:** only calls whose admin token resolved to a user are recorded. A refusal at the access check (403 from the module or super-admin check, or `PASSWORD_RESET_REQUIRED`) for such a user is recorded as `FAILURE`.
4. **Event fields, as the aspect builds them:**
- **Action:** `@Audited(action)`; otherwise derived from the handler: drop an `Admin` prefix and a `Controller` suffix, then UPPER_SNAKE both parts and join them, so `AdminUserController.update` becomes `USER_UPDATE`.
- **Path template:** the class `@RequestMapping` plus the method mapping, for example `/api/admin/users/{id}`.
- **Target id:** the last path variable (the record acted on, e.g. the event lead in `/event-leads/{eventUuid}/leads/{eventLeadUuid}`). `@Audited(target = false)` records none: the unlock path carries a username as typed at a failed sign-in, which can be a mistyped password.
- **Outcome:**
- `SUCCESS` for a 2xx `ResponseEntity`, or when there is no `ResponseEntity`;
- otherwise `FAILURE` with the status, taken from a non-2xx `ResponseEntity` or from a thrown `ResponseStatusException`;
- any other exception is `FAILURE` with 500.
- **Client IP:** the `X-Client-Ip` header.
5. **`AuditChanges`:** a request-scoped holder. Services call `AuditChanges.put(field, before, after)` or `AuditChanges.fields(names...)`, and the aspect serialises the result into `changes`. The allow-list is enforced where the values are supplied:
- `AdminUserService` create and update: `roles` (role names) and `enabled`;
- `AdminRoleService` set modules: `modules` with the codes added and removed;
- `AdminLeadService` and `AdminEventLeadService` edits: changed field names only;
- `AdminLoginSecurityService` config and password rules: the changed settings with before and after.
6. **Publishing:** to `audit-event-topic`, after the handler finishes, through the existing `PubSubUtil` and `PubSubTemplate` pattern used for `ResponseTime`. Any exception is logged at WARN and swallowed.
7. **services-log:**
- Creates `audit-event-topic` and `audit-event-subscription` at startup, like the other topics.
- The listener saves each `AuditEvent` as an `AuditEventLog`.
- A scheduled purge (daily) deletes rows with `occurred_at` older than `audit.retention-days` (env `AUDIT_RETENTION_DAYS`, default 730), in batches.
- **`POST /log/audit/search`:** body `{actor, module, action, outcome, from, to, page, size}`. `actor` and `action` match exactly; `from` and `to` are `yyyy-MM-dd` and inclusive. It returns newest first, caps the size at 100, and answers `{content, totalElements, number, size}`.
- **`GET /log/audit/{id}`.**
- Both need the admin's token at the gateway, like the other `/log/**` routes.
8. **mobile-api read API:** `AdminAuditLogController` (`@AdminModule("BO_AUDIT_LOG")`):
- `GET /api/admin/audit-log?actor&module&action&outcome&from&to&page&size`;
- `GET /api/admin/audit-log/{id}` (404 when missing).
- The reads themselves are not audited (GET without `@Audited`).
9. **Portal `/audit-log`:**
- **List:** time, who, module (label from the module's i18n key), action, target, outcome with status, and IP.
- **Filters:** who, module select, action, outcome, and From/To `DatePicker`.
- **Detail `/audit-log/[id]`:** the event fields, then a changes table (field, before, after), or a list of changed fields when only names were recorded.
- **Gating:** `RequireModule` and `ROUTE_MODULES`.
- **Proxy:** `app/api/audit-log/[[...path]]/route.ts`, GET only.
10. **Module row:** `(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText')`, with no role grants.
## Risks / Trade-offs
- **Lost events:** Pub/Sub publishing is best-effort, so a broker outage loses events. This is accepted, as in babyboo; the application log still carries the existing `... by ...` lines.
- **Role names and settings stored as values:** these are not personal data. Lead personal data is never stored; lead edits keep field names only.
- **Path variables as targets:** the last path variable is a UUID or id, except the unlock username, which is not recorded. The concrete path is never stored, so no query string, and therefore no search text, ends up in the log.
- **Requests refused before the handler:** malformed JSON or a binding error is answered before `AppAccessAspect` runs, so such calls are not recorded.
- **Extra reads for before-values:** a lead edit and a login-security settings save read the current values once before saving, only for the audit. The read is best-effort and cannot fail the save; it adds one internal call.
- **One company:** reads do not filter by `company_id`. Add the filter when Co-Lite becomes multi-company.
- **Retention:** `AUDIT_RETENTION_DAYS` below 1 stops service-log at startup rather than deleting the whole trail.
- **Volume:** one row per admin write. With one company and a handful of admins, 730 days is small.
@@ -0,0 +1,60 @@
# Proposal
## Why
Nothing in Co-Lite records who did what in the admin portal. When an admin edits a user, changes a role's grants, edits or exports leads, or opens a saved email (which can hold a temporary password), the only trace is a line in the application log. Sign-ins are the exception: `login_audit` covers them. Go-live is 2027-01-15, and the company needs an audit trail and a screen to read it.
babyboo built the same thing (`add-portal-audit-log`, archive 2026-11-19, plus `audit-log-readable-actions`, 2026-11-20). This change ports the admin half of that work, trimmed.
Design: `docs/superpowers/specs/2026-11-30-admin-audit-log-design.md`.
## What Changes
- **Recording:**
- mobile-api's `AppAccessAspect` publishes an audit event for every admin write under `/api/admin/**`, every refusal of a valid admin token, and three sensitive reads: the lead export, the event-lead export and opening an email.
- Sign-in, sign-out, refresh, forgot-password and own password change are not recorded, because `login_audit` covers them or there is no actor.
- **Each event:**
- who and when; the module and a readable action code;
- the method and the path template; the target id;
- the outcome and status, and the browser IP.
- Before/after values only for an allow-list:
- a user's role names and enabled flag;
- role module grants;
- login-security settings;
- for lead edits and event-lead edits, the names of the changed fields only, never the values.
- **Transport:** a new Pub/Sub topic `audit-event-topic`. services-log subscribes on `audit-event-subscription` and saves to a new `service-log`.`audit_event` table. Publishing is best-effort: a failure never blocks the admin's action.
- **Retention:** services-log deletes events older than `AUDIT_RETENTION_DAYS` (default 730) on a schedule.
- **Reading:** services-log gets search and detail endpoints. mobile-api gets `GET /api/admin/audit-log` and `GET /api/admin/audit-log/{id}` under the new module `BO_AUDIT_LOG`.
- **Portal:** a new `/audit-log` page with a list, filters and a detail view that shows the changes.
- **Not in this change:**
- member and public calls;
- page views;
- removing the unused legacy `/log/save` and `back_office_access_log`.
## Capabilities
### New Capabilities
- `admin-audit-log`: recording admin actions, refusals and sensitive reads; the allow-listed changes; retention; and the Audit log screen.
### Modified Capabilities
None.
## Impact
- **`solvway-core-libs`:** a new `AuditEvent` message class shared by mobile-api and services-log.
- **`solvway-services-log`:**
- `AuditEventLog` entity and repository;
- the topic and subscription setup and the listener;
- the purge;
- `/log/audit/search` and `/log/audit/{id}`.
- **`solvway-mobile-api`:**
- the `Audited` annotation and the `AuditChanges` request holder;
- publishing in `AppAccessAspect`;
- annotations on the sensitive reads and the read-only POST;
- changes supplied by the user, role, lead, event-lead and login-security services;
- `AdminAuditLogController`.
- **`solvway-admin-portal`:** the `/audit-log` pages, a proxy, a service and i18n keys. Client IP is already forwarded on every call.
- **Pub/Sub:** a new topic and subscription. They go in `local/pubsub/topics.txt` and `docs/deployment.md` section 5.
- **Database:** `sql/01-audit-event.sql` (DDL in `service-log`) and `sql/02-audit-log-module.sql`, mirrored in `local/seed/03-colite.sql`, plus a rollback script.
- **Privacy:** no passwords, tokens, request bodies or lead personal data are stored. User role names and login-security settings are stored as values.
- No new dependency.
@@ -0,0 +1,105 @@
## ADDED Requirements
### Requirement: Admin writes are recorded
The system SHALL record an audit event for every state-changing admin API call made with a valid admin token, successful or not, holding the time, admin username, module, readable action code, HTTP method, path template (never the concrete path or query), target id, outcome with HTTP status, and client IP. Sign-in, sign-out, token refresh, forgot-password, own password change from the user menu, and calls without a valid admin token SHALL NOT be recorded.
#### Scenario: A user edit is recorded
- **WHEN** admin `admin` updates user 4
- **THEN** an audit event is saved with actor `admin`, module `BO_USERS`, action `USER_UPDATE`, path template `PUT /api/admin/users/{id}`, target `4`, outcome `SUCCESS`, and the client IP
#### Scenario: A failed write is recorded
- **WHEN** an admin's role update is refused with status 400
- **THEN** an audit event is saved with outcome `FAILURE` and status 400
#### Scenario: Sign-in is not recorded
- **WHEN** an admin signs in or signs out
- **THEN** no audit event is saved
#### Scenario: First-login password change is recorded
- **WHEN** a new admin sets their password at first login
- **THEN** an audit event with action `AUTH_FIRST_LOGIN` is saved
### Requirement: Refused access is recorded
The system SHALL record an audit event with outcome `FAILURE` when a valid admin token is refused by the access check (missing module, super admin required, or pending first-login change).
#### Scenario: Missing module
- **GIVEN** admin `noevents` has no `BO_EVENTS`
- **WHEN** `noevents` tries to create an event
- **THEN** the request is refused with 403
- **AND** an audit event with actor `noevents`, module `BO_EVENTS` and outcome `FAILURE` is saved
### Requirement: Sensitive reads are recorded
The system SHALL record an audit event when an admin exports leads, exports event leads, or opens a saved email. Read-only POST calls marked as such SHALL NOT be recorded.
#### Scenario: Opening an email
- **WHEN** an admin opens email 12
- **THEN** an audit event with action `EMAIL_VIEW` and target `12` is saved
#### Scenario: Lead export
- **WHEN** an admin downloads the lead export
- **THEN** an audit event with action `LEAD_EXPORT` is saved
### Requirement: Allow-listed changes
The system SHALL attach before and after values only for these fields: a user's role names and enabled flag, a role's granted module codes, and the login-security lockout settings and password rules. For lead and event-lead edits the system SHALL record only the names of the fields that changed, never their values. No audit event SHALL contain a password, token, raw request body, or lead name, phone, email or notes.
#### Scenario: Role change on a user
- **WHEN** an admin changes user 4's roles from `Sales` to `Sales, Manager`
- **THEN** the event's changes show roles before `Sales` and after `Sales, Manager`
#### Scenario: Lead edit records field names only
- **WHEN** an admin changes a lead's phone and notes
- **THEN** the event's changes list the fields `phone` and `notes`
- **AND** neither the old nor the new phone or notes appear in the event
### Requirement: Recording never blocks the action
Recording SHALL be best-effort. A failure to publish or save an audit event MUST NOT change the response of the admin call.
#### Scenario: Publish failure
- **GIVEN** the audit event cannot be published
- **WHEN** an admin updates a user
- **THEN** the update succeeds as usual
- **AND** the failure is logged
### Requirement: Retention
The system SHALL delete audit events older than the configured retention period, 730 days by default, on a schedule.
#### Scenario: Old events are purged
- **WHEN** the purge runs with a retention of 730 days
- **THEN** events older than 730 days are deleted
- **AND** newer events are kept
### Requirement: Audit log screen
The system SHALL let an admin with `BO_AUDIT_LOG` list audit events newest first, paged, filtered by actor, module, action, outcome and date range, and open one event to see its details and changes. An admin without `BO_AUDIT_LOG` SHALL be refused.
#### Scenario: Filter by actor
- **WHEN** an admin with `BO_AUDIT_LOG` filters the audit log by actor `admin`
- **THEN** only events by `admin` are listed, newest first
#### Scenario: Event detail
- **WHEN** an admin opens an event for a role grant change
- **THEN** the detail shows the event's fields and the modules added and removed
#### Scenario: Without the module
- **WHEN** an admin without `BO_AUDIT_LOG` calls the audit log API or opens `/audit-log`
- **THEN** the API answers 403 and the page shows Not authorised
@@ -0,0 +1,25 @@
-- Co-Lite change add-admin-audit-log: the admin audit trail.
-- Target: `service-log`.`audit_event`. Additive only. Run once, after the release package.
-- DDL: run with a user that may create tables, not the services' user.
-- Written by services-log from the audit-event-topic Pub/Sub messages that mobile-api publishes.
USE `service-log`;
CREATE TABLE IF NOT EXISTS `audit_event` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NULL,
`occurred_at` datetime(6) NOT NULL,
`actor` varchar(191) NOT NULL,
`module` varchar(64) NULL,
`action` varchar(128) NOT NULL,
`http_method` varchar(16) NULL,
`path_template` varchar(255) NULL,
`target_id` varchar(128) NULL,
`outcome` varchar(16) NOT NULL COMMENT 'SUCCESS | FAILURE',
`http_status` int NULL,
`client_ip` varchar(64) NULL,
`changes` text NULL COMMENT 'JSON: allow-listed before/after, or changed field names',
PRIMARY KEY (`id`),
KEY `idx_audit_event_occurred_at` (`occurred_at`),
KEY `idx_audit_event_actor` (`actor`, `occurred_at`),
KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -0,0 +1,7 @@
-- Co-Lite change add-admin-audit-log: the Audit log back-office module (area BO).
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
-- No role grant: super admins see every module; they grant BO_AUDIT_LOG to other roles under Roles.
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText');
@@ -0,0 +1,7 @@
-- Co-Lite change add-admin-audit-log: rollback of 01-02. Destroys the audit trail.
USE `service-system`;
DELETE FROM `modules_roles` WHERE `module_id` = 41100000;
DELETE FROM `module` WHERE `id` = 41100000;
USE `service-log`;
DROP TABLE IF EXISTS `audit_event`;
@@ -0,0 +1,96 @@
# Tasks
Design: `design.md`. All tasks run serially: each builds on the one before.
## 1. Data and contract
- [x] 1.1 SQL and Pub/Sub topic.
- Files:
- `sql/01-audit-event.sql`: `CREATE TABLE IF NOT EXISTS service-log.audit_event` (design decision 2).
- `sql/02-audit-log-module.sql`: the module row (design decision 10).
- `sql/99-rollback.sql`.
- Mirror 01 and 02 in `local/seed/03-colite.sql`, and add `audit-event-topic audit-event-subscription` to `local/pubsub/topics.txt`.
- Apply them to the local database and emulator. This is local only.
- Scope: `local/**`, `openspec/changes/add-admin-audit-log/sql/**`
- Verify: `select` shows the table and the module row.
- [x] 1.2 core-libs `AuditEvent` (design decision 1).
- Tests first: JSON round trip through the same `PubSubUtil` used for `ResponseTime`.
- Scope: `solvway-core-libs/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-core-libs verify`
## 2. services-log
- [x] 2.1 Storage, listener, purge and read endpoints (design decision 7).
- Tests first:
- the listener saves an event with every field;
- search filters by actor, module, action, outcome and dates, returns newest first, caps the size at 100, and rejects a bad date with 400;
- detail answers 404 for an unknown id;
- the purge deletes only rows older than the retention and reads the env setting.
- Scope: `solvway-services-log/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-services-log -am verify`
## 3. mobile-api
- [x] 3.1 Recording in `AppAccessAspect`, with `Audited` and `AuditChanges` (design decisions 3, 4 and 6).
- Add annotations on the lead export, the event-lead export, the email detail (sensitive) and event-lead `match` (skip).
- Tests first:
- a write records every field: actor, module, action, method, template, target, outcome and IP;
- the derived and the explicit action codes;
- a non-2xx response and a thrown status exception record `FAILURE` with the status;
- a 403 refusal for a valid user is recorded;
- plain GETs, skipped POSTs and the auth endpoints (except first-login) are not recorded;
- a call without a user is not recorded;
- a publish failure does not change the response;
- `AuditChanges` content lands in `changes` and is cleared between requests.
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- [x] 3.2 Allow-listed changes from the services (design decision 5).
- Tests first, one per service:
- user role names and enabled flag before and after;
- role modules added and removed;
- lead and event-lead edits record field names only, and no value appears anywhere in `changes`;
- login-security config and rules before and after.
- Scope: `solvway-mobile-api/src/main/java/**/service/**` plus their tests
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- [x] 3.3 `AdminAuditLogController` and the read service (design decision 8).
- Tests first:
- the class-level module;
- parameter mapping;
- a 404 for an unknown id;
- only the given filters are forwarded.
- Scope: `solvway-mobile-api/src/**` (new audit-log files, constants, tests)
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- Live check through the stack:
- edit a user and see the event with its changes;
- `noevents` creating an event is recorded as `FAILURE`;
- opening an email is recorded.
## 4. Portal
- [x] 4.1 `/audit-log` list and `/audit-log/[id]` detail, with a proxy, a service and i18n keys (design decision 9).
- Tests first:
- rows and filters go into the query;
- the detail shows a before/after table and a field-name list;
- `RequireModule` gates the page;
- the proxy is GET only and refuses dot segments.
- Scope: `solvway-admin-portal/app/audit-log/**`, `solvway-admin-portal/app/api/audit-log/**`, `solvway-admin-portal/app/lib/**`
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
## 5. Check and docs
- [x] 5.1 Browser check and handover.
- Playwright on the local stack:
- as admin, change a user's roles, change a role's grants, edit a lead, open an email and export leads, then see each in Audit log with its changes;
- as `noevents`, try a forbidden action and see it as `FAILURE`;
- `noevents` has no Audit log menu entry and sees Not authorized at `/audit-log`;
- the list fits at 1280 px, and the pages work at 360 px.
- Docs, in `docs/deployment.md`:
- section 3: the new SQL;
- section 5: the new topic and subscription;
- section 6: `AUDIT_RETENTION_DAYS`.
- Scope: `docs/deployment.md`
- Verify: screenshots, and the steps above observed.
## Workflow follow-up
- Whole-branch review, push, PR to main and merge, then archive on its own branch.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-30
@@ -0,0 +1,115 @@
# Design
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-admin-login-security-design.md`.
## Context
- **Admin sign-in path:** the portal's `/api/auth/login` route calls mobile-api `POST /api/admin/auth/login` (`AdminAuthController`). That calls the gateway, then services-auth `/auth/authenticate`, then `loadUserByToken`. Nothing is counted or recorded.
- **Only one way in:** only the admin portal is public (Traefik; `docs/deployment.md` section 8). Only mobile-api holds a gateway key (`appkeys.json`, section 7). So `AdminAuthController.login` sees every admin sign-in.
- **Existing settings rows** in `service-system`.`system_property`:
- `ADMIN_LOGIN_BLOCK_PERIOD` (type `ADMIN_LOGIN_BLOCK`, value 1, status Y);
- `ADMIN_LOGIN_BLOCK_TIME_UNIT` (value M);
- the `ADMIN_PWD_FORMAT` rules (active: minimum length 8, 1 uppercase, 1 lowercase).
- Nothing reads the block rows today.
- **Password checks:** services-system `UserController.adminPasswordRuleFailures` applies `ADMIN_PWD_FORMAT`. services-system owns `BCryptPasswordEncoder` (`Config`), and `/setAdminPassword` hashes there.
- **Reference:** babyboo archive `2026-09-28-add-admin-login-security`. It enforces in services-auth and adds session policy; Co-Lite does neither.
## Goals / Non-Goals
**Goals:** login history, lockout with unlock, editable lockout and password rules, own password change.
**Non-Goals:**
- session policy;
- MFA and CAPTCHA;
- password aging;
- non-admin logins;
- purging history.
## Decisions
1. **Table `login_audit`** in `service-system`:
- Columns: `id`, `company_id` NULL, `username` VARCHAR(191), `datetime`, `event` VARCHAR(20), `ip_address` VARCHAR(64), `user_agent` VARCHAR(512), `message` VARCHAR(255).
- Keys: `(username, datetime)` and `(event, datetime)`.
- Values are cut to the column sizes before saving.
- `company_id` is filled from the user whose `username` matches, else NULL.
2. **Lock rule, owned by services-system** (`LoginSecurityService`):
- **Settings:**
- `on` is the status `Y` on `ADMIN_LOGIN_BLOCK_PERIOD`;
- `period` is its value;
- `unit` is `ADMIN_LOGIN_BLOCK_TIME_UNIT` (S, M, H or D);
- `max` is the new row `ADMIN_LOGIN_MAX_ATTEMPT` (type `ADMIN_LOGIN_BLOCK`).
- **Locked** means `on` and `count(LOGIN_FAIL where username = ? and datetime > greatest(now - period, latestReset)) >= max`. `latestReset` is the newest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED` for that username.
- **Lock end** is the datetime of the oldest counted failure that keeps the count at `max`, plus the period. The locked list uses it, and so do the tests.
- **Username matching:** the lock rule uses the trimmed username, cut to 191 characters, the same key the history stores. `login_audit.username` uses `utf8mb4_general_ci`, so it compares like `user.username` (case-insensitive).
3. **services-system endpoints** (`LoginSecurityController`, under `/loginSecurity`; the gateway gets a matching route):
- `GET isLocked/{username}` returns `{locked}`.
- `POST record` takes `{username, event, ip, userAgent, message}`.
- `POST audit` takes `{username, event, from, to, page, size}`. Dates are `yyyy-MM-dd`. It returns newest first, with size capped at 100.
- `GET locked` returns `[{username, failures, lastFailure, lockedUntil}]`. It considers usernames with a `LOGIN_FAIL` inside the period.
- `POST unlock` takes `{username, by}` and writes `UNLOCK_RESET` with `message = "unlocked by <by>"`.
- `GET config` and `POST config` take `{enabled, maxAttempts, period, unit}`. They validate `maxAttempts` between 1 and 1000, `period` between 1 and 10000, and the unit in S, M, H or D, and return 400 otherwise. The upper limits keep the lock window computable.
- `GET passwordRules` and `POST passwordRules` take `[{id, status, value}]`. They only update existing `ADMIN_PWD_FORMAT` rows, and refuse any id outside that type with 400.
4. **services-system `/user/changeAdminPassword`** takes `{id, currentPassword, newPassword}` and returns one result string:
- `OK`;
- `NOT_FOUND`: not a type A user, or not enabled;
- `CURRENT_PASSWORD_WRONG`: the bcrypt match fails;
- `PASSWORD_SAME`;
- `PASSWORD_POLICY`: `adminPasswordRuleFailures` is not empty.
- On `OK` it saves the bcrypt of the new password and keeps `login = Y`.
5. **mobile-api sign-in** (`AdminAuthController.login`):
- Blank fields: 401 `BAD_LOGIN`, nothing recorded.
- Then `isLocked`:
- **Locked:** record `LOGIN_LOCKED` and return 401 `{result: "false", code: "ACCOUNT_LOCKED", message: "Too many failed sign-ins. Try again later or ask an administrator to unlock your account."}`.
- **Error:** log a warning and continue (fail open).
- Then the existing check:
- an unknown, wrong, disabled or upstream-failed check records `LOGIN_FAIL`;
- a success records `LOGIN_SUCCESS`.
- The lock check and recording are methods on `AdminAuthenticationService` (`isLocked`, which fails open, and `record`, which catches and logs every exception). No new class, so the existing controller tests and their mocks stay unchanged.
- Logout records `LOGOUT` for the token's user.
6. **Client IP and user agent:**
- The portal's login and logout routes already send `X-Client-Ip` (the last `x-forwarded-for` hop, the one the ingress adds, else `x-real-ip`) and `X-Client-User-Agent` (the browser's user agent) to mobile-api, through `app/lib/server/clientContext.ts`, which was ported from babyboo.
- mobile-api reads them from the request for the record only.
- They are never used for any decision, since a client can forge them.
7. **mobile-api `POST /api/admin/auth/change-password`** (`@AdminModule(ANY_ADMIN)`, not `allowPendingReset`, so a pending user gets the existing 403 `PASSWORD_RESET_REQUIRED`):
- Missing field: 400 `REQUIRED_FIELD`.
- New and confirm differ: 400 `PASSWORD_MISMATCH`.
- Locked: 400 `ACCOUNT_LOCKED`.
- Otherwise call `/user/changeAdminPassword`:
- `CURRENT_PASSWORD_WRONG`: record `LOGIN_FAIL` (message `change-password`) and return 400.
- `PASSWORD_SAME` or `PASSWORD_POLICY`: return 400 with that code.
- `OK`: record `PASSWORD_CHANGED` and return 204.
- Error bodies follow the existing `{code, message}` shape the portal shows through `t()`.
8. **mobile-api `AdminLoginSecurityController`** (`@AdminModule("BO_LOGIN_SECURITY")`, `/api/admin/login-security`):
- `GET audit`;
- `GET locked`;
- `POST locked/{username}/unlock` (204);
- `GET` and `PUT config`;
- `GET` and `PUT password-rules`.
- Unlock and settings changes log `"{action} by {admin}"`.
9. **Portal:**
- **Header user menu:** a "Change password" item opens `ChangePasswordDialog` (current, new, confirm). It reuses the `PasswordFields` patterns and calls `/api/auth/change-password`.
- **Login page:** maps `code === "ACCOUNT_LOCKED"` to the locked message.
- **`/login-security`:** gated by `RequireModule` and `ROUTE_MODULES["/login-security"] = "BO_LOGIN_SECURITY"`. Three tabs:
- History: a DataTable with `useListFilters` and `useFitPageSize`, filtered by username, event and From/To `DatePicker`.
- Locked: rows with an Unlock button and a confirm dialog.
- Settings: a lockout form, then a rules table with an on/off switch and a value.
- Proxy: `app/api/login-security/[[...path]]/route.ts` for GET, POST and PUT, refusing dot segments. `app/api/auth/change-password/route.ts`.
10. **Module row:** `(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield')`. No role grants, so only super admins see it until granted.
## Risks / Trade-offs
- **Targeted lockout:** anyone can lock a real username for one period by failing on purpose. Mitigations: the lock expires, and admins can unlock. Counting unknown usernames keeps locks from revealing which accounts exist.
- **Fail open:** when services-system is down, the lock is not enforced. Accepted: an outage must not lock every admin out, and the password check still runs.
- **Concurrency:** two simultaneous wrong guesses may both pass the pre-check, so the count can exceed `max` by the number of parallel requests. Accepted; it is a limit, not a security boundary.
- **History growth:** no purge. One company and a handful of staff make this small. A purge can come with the audit viewer.
- **Forged IP or user agent:** these are stored for reading only, and never trusted.
- **Unauthenticated writes behind the gateway key:** `/loginSecurity/record` needs no user token, so it can write `LOGIN_SUCCESS` or `PASSWORD_CHANGED` rows, and both clear a lock. The older `/blockLoginPeriod/**` routes also skip the token, and their save can rewrite the `ADMIN_LOGIN_BLOCK` rows. Both are reachable only with a gateway api-key from an allowed IP, which today only mobile-api holds (`docs/deployment.md` section 7). A later change can narrow the `/blockLoginPeriod/` bypass to its read endpoints.
@@ -0,0 +1,59 @@
# Proposal
## Why
Go-live is 2027-01-15. Today the admin login counts nothing: anyone who reaches the login page can guess passwords without limit, and nothing records who signed in. Staff also cannot change their own password; only an admin can set a temporary one for them.
The legacy backoffice blocked a username after 3 failed logins, using an in-memory counter. Co-Lite's new login path (portal, then mobile-api, then services-auth) never ported that rule. babyboo solved the same gap with a persisted `login_audit` table, and this change follows it, trimmed to what Co-Lite needs. The history it keeps will also serve the later audit-log viewer.
Design: `docs/superpowers/specs/2026-11-30-admin-login-security-design.md`.
## What Changes
- **Login history:** every admin login success, failure, locked refusal, logout, unlock and own password change is saved to a new `service-system`.`login_audit` table. Each row has the time, username, client IP and user agent.
- **Lockout:**
- After a set number of failed logins inside a set period, the username is locked. The defaults are 5 attempts in 15 minutes.
- A locked username is refused even with the right password.
- The lock ends by itself when the failures age out, or when an admin unlocks it.
- The settings reuse the existing `ADMIN_LOGIN_BLOCK` rows in `system_property`, plus one new row for the maximum attempts.
- **Enforcement point:** mobile-api `AdminAuthController.login`, the only way in (only the admin portal is public). services-auth is not changed.
- **Change my password:** a new `POST /api/admin/auth/change-password` and a dialog in the portal's user menu. It needs the current password and applies the admin password rules. A wrong current password counts as a failed login.
- **Login security screen** (`/login-security`, module `BO_LOGIN_SECURITY`):
- History tab: login history with filters.
- Locked tab: locked usernames with an Unlock button.
- Settings tab: edits the lockout settings and the admin password rules (`ADMIN_PWD_FORMAT`).
- **Login page:** shows a clear message when the username is locked.
- **Not in this change:** session policy (logout revocation, sliding sessions, single session), MFA, CAPTCHA, password aging, member or other non-admin logins, and purging old history.
## Capabilities
### New Capabilities
- `admin-login-security`: the login history, the lock rule and its enforcement on admin login, unlock, the lockout and password-rule settings, and the Login security screen.
- `admin-own-password`: an admin changing their own password.
### Modified Capabilities
None.
## Impact
- **`solvway-services-system`:**
- A new `LoginAudit` entity and repository, a service and a `/loginSecurity` controller (isLocked, record, audit, locked, unlock, config, password rules).
- A new `/user/changeAdminPassword` endpoint that checks the current password with the existing `BCryptPasswordEncoder`.
- **`solvway-mobile-api`:**
- `AdminAuthController` login and logout record events and check the lock.
- New `change-password` endpoint.
- New `AdminLoginSecurityController` under `BO_LOGIN_SECURITY`.
- **`solvway-admin-portal`:**
- The login and logout proxy routes forward the client IP and user agent.
- The login page shows the locked message.
- Change-password dialog in the header.
- New `/login-security` page with proxy routes, a service and i18n keys.
- **Database (`sql/` in this change, mirrored in `local/seed/03-colite.sql`):**
- Create `login_audit`, with `company_id`.
- Insert `ADMIN_LOGIN_MAX_ATTEMPT`.
- Set the block period to 15 minutes.
- Insert the `BO_LOGIN_SECURITY` module row.
- A rollback script.
- **Security:** this changes the admin sign-in path. The lock check fails open when services-system errors, so an outage cannot lock everyone out. The audit write is best-effort.
- **Docs:** `docs/deployment.md` lists the new SQL.
- No new dependency.
@@ -0,0 +1,127 @@
## ADDED Requirements
### Requirement: Login history
The system SHALL record every admin sign-in attempt, sign-out, unlock and own password change, with the time, trimmed username, event, client IP, user agent and, for a known username, the user's company. Events: `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOGIN_LOCKED`, `LOGOUT`, `UNLOCK_RESET`, `PASSWORD_CHANGED`. Recording SHALL be best-effort and MUST NOT change the sign-in answer. A blank username or password SHALL NOT be recorded.
#### Scenario: Successful sign-in is recorded
- **WHEN** `sales1` signs in with the right password
- **THEN** a `LOGIN_SUCCESS` record for `sales1` is saved with the time, client IP and user agent
#### Scenario: Failed sign-in is recorded
- **WHEN** someone signs in as `sales1` with a wrong password
- **THEN** a `LOGIN_FAIL` record for `sales1` is saved
#### Scenario: Unknown username is recorded
- **WHEN** someone signs in as `nobody1`, which matches no user
- **THEN** a `LOGIN_FAIL` record for `nobody1` is saved with no company
#### Scenario: Sign-out is recorded
- **WHEN** `sales1` signs out
- **THEN** a `LOGOUT` record for `sales1` is saved
#### Scenario: History write failure does not block sign-in
- **GIVEN** the history cannot be written
- **WHEN** `sales1` signs in with the right password
- **THEN** the sign-in succeeds
- **AND** the write failure is logged
### Requirement: Lockout after repeated failures
The system SHALL lock a username when lockout is on and its `LOGIN_FAIL` records reach the configured maximum, counting only records inside the configured period and after its latest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED`. The maximum, period, unit and on/off switch SHALL come from settings. Failures SHALL count for unknown usernames too, so a lock does not reveal whether an account exists. The lock SHALL end once the counted failures leave the period.
#### Scenario: Maximum reached locks the username
- **GIVEN** lockout is on with a maximum of 5 in 15 minutes
- **WHEN** `sales1` fails to sign in 5 times within 15 minutes
- **THEN** `sales1` is locked
#### Scenario: Old failures do not count
- **GIVEN** lockout is on with a maximum of 5 in 15 minutes
- **WHEN** `sales1` has 4 failures within the last 15 minutes and 3 older ones
- **THEN** `sales1` is not locked
#### Scenario: A success resets the count
- **WHEN** `sales1` fails 4 times, signs in successfully, then fails 4 more times within 15 minutes
- **THEN** `sales1` is not locked
#### Scenario: Lockout switched off
- **GIVEN** lockout is off
- **WHEN** `sales1` fails 10 times within 15 minutes
- **THEN** `sales1` is not locked
### Requirement: Locked username is refused
The system SHALL refuse sign-in for a locked username before checking the password, with the code `ACCOUNT_LOCKED` and a message telling the user to try later or ask an administrator, and SHALL record `LOGIN_LOCKED`. When the lock state cannot be read because of an infrastructure error, sign-in SHALL proceed to the normal password check.
#### Scenario: Right password while locked
- **GIVEN** `sales1` is locked
- **WHEN** `sales1` signs in with the right password
- **THEN** sign-in is refused with `ACCOUNT_LOCKED`
- **AND** no session is issued
- **AND** a `LOGIN_LOCKED` record is saved
#### Scenario: Lock check unavailable
- **GIVEN** the lock state cannot be read
- **WHEN** `sales1` signs in with the right password
- **THEN** the sign-in succeeds
#### Scenario: Portal shows the locked message
- **WHEN** sign-in is refused with `ACCOUNT_LOCKED`
- **THEN** the login page shows the locked message instead of "Invalid username or password"
### Requirement: Unlock
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
#### Scenario: Unlock a locked username
- **GIVEN** `sales1` is locked
- **WHEN** an admin with `BO_LOGIN_SECURITY` unlocks `sales1`
- **THEN** `sales1` no longer appears in the locked list
- **AND** `sales1` can sign in with the right password
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
### Requirement: Login history screen
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, newest first and paged, filtered by username, event and date range.
#### Scenario: Filter by event
- **WHEN** an admin filters the history by event `LOGIN_FAIL`
- **THEN** only `LOGIN_FAIL` records are listed, newest first
#### Scenario: Without the module
- **WHEN** an admin without `BO_LOGIN_SECURITY` calls the login-security API
- **THEN** the request is refused with 403
### Requirement: Lockout and password-rule settings
The system SHALL let an admin with `BO_LOGIN_SECURITY` read and change the lockout settings (on/off, maximum attempts, period, time unit) and the admin password rules (each rule's on/off status and value). The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
#### Scenario: Change the lockout settings
- **WHEN** an admin sets the maximum to 3 and the period to 30 minutes
- **THEN** the next lock decision uses 3 attempts in 30 minutes
#### Scenario: Invalid setting
- **WHEN** an admin sets the maximum to 0
- **THEN** the change is refused with a validation error and the settings stay as they were
#### Scenario: Change a password rule
- **WHEN** an admin sets the minimum length rule to 10
- **THEN** a new password of 9 characters is refused by every admin password check
@@ -0,0 +1,50 @@
## ADDED Requirements
### Requirement: Change own password
The system SHALL let a signed-in admin change their own password by giving the current password, a new password and its confirmation. The new password SHALL pass the admin password rules and SHALL differ from the current one. On success the system SHALL keep the admin signed in, keep their first-login state complete, and record `PASSWORD_CHANGED`. An admin whose first-login password change is still pending SHALL use the first-login flow instead.
#### Scenario: Successful change
- **WHEN** `sales1` gives the right current password and a new password that passes the rules, twice
- **THEN** the new password works at the next sign-in and the old one does not
- **AND** `sales1` stays signed in
- **AND** a `PASSWORD_CHANGED` record is saved
#### Scenario: Confirmation differs
- **WHEN** the new password and its confirmation differ
- **THEN** the change is refused with `PASSWORD_MISMATCH`
#### Scenario: Same as current
- **WHEN** the new password equals the current password
- **THEN** the change is refused with `PASSWORD_SAME`
#### Scenario: Fails the rules
- **WHEN** the new password breaks an admin password rule
- **THEN** the change is refused with `PASSWORD_POLICY`
#### Scenario: Pending first login
- **GIVEN** `sales1` must still complete the first-login password change
- **WHEN** `sales1` calls change password
- **THEN** the request is refused and `sales1` is sent to the first-login flow
### Requirement: Wrong current password counts as a failed sign-in
The system SHALL refuse a change whose current password is wrong with `CURRENT_PASSWORD_WRONG`, and SHALL record it as `LOGIN_FAIL` so that repeated wrong guesses lock the username. A locked username SHALL be refused with `ACCOUNT_LOCKED` before the current password is checked.
#### Scenario: Wrong current password
- **WHEN** `sales1` gives a wrong current password
- **THEN** the change is refused with `CURRENT_PASSWORD_WRONG`
- **AND** a `LOGIN_FAIL` record for `sales1` is saved
#### Scenario: Locked while changing
- **GIVEN** `sales1` is locked
- **WHEN** `sales1` calls change password with the right current password
- **THEN** the change is refused with `ACCOUNT_LOCKED`
- **AND** the password is unchanged
@@ -0,0 +1,19 @@
-- Co-Lite change add-admin-login-security: the admin login history.
-- Target: `service-system`.`login_audit`. Additive only. Run once, after the release package.
-- Lock state is derived from this table (LOGIN_FAIL rows inside the block period, after the latest
-- LOGIN_SUCCESS / UNLOCK_RESET / PASSWORD_CHANGED); there is no stored lock flag.
USE `service-system`;
CREATE TABLE IF NOT EXISTS `login_audit` (
`id` bigint NOT NULL AUTO_INCREMENT,
`company_id` bigint NULL COMMENT 'the user''s company when the username matches a user',
`username` varchar(191) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'compared like `user`.`username`',
`datetime` datetime NOT NULL,
`event` varchar(20) NOT NULL COMMENT 'LOGIN_SUCCESS | LOGIN_FAIL | LOGIN_LOCKED | LOGOUT | UNLOCK_RESET | PASSWORD_CHANGED',
`ip_address` varchar(64) NULL,
`user_agent` varchar(512) NULL,
`message` varchar(255) NULL,
PRIMARY KEY (`id`),
KEY `idx_login_audit_username_dt` (`username`, `datetime`),
KEY `idx_login_audit_event_dt` (`event`, `datetime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -0,0 +1,11 @@
-- Co-Lite change add-admin-login-security: admin lockout settings.
-- Target: `service-system`.`system_property`. Run once, after the release package.
-- Default: 5 failed sign-ins within 15 minutes lock the username. Editable on the Login security screen.
USE `service-system`;
INSERT INTO `system_property` (`param`, `status`, `type`, `value`)
SELECT 'ADMIN_LOGIN_MAX_ATTEMPT', 'Y', 'ADMIN_LOGIN_BLOCK', '5'
WHERE NOT EXISTS (SELECT 1 FROM `system_property` WHERE `param` = 'ADMIN_LOGIN_MAX_ATTEMPT' AND `type` = 'ADMIN_LOGIN_BLOCK');
UPDATE `system_property` SET `value` = '15', `status` = 'Y'
WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
@@ -0,0 +1,7 @@
-- Co-Lite change add-admin-login-security: the Login security back-office module (area BO).
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
-- No role grant: super admins see every module; they grant BO_LOGIN_SECURITY to other roles under Roles.
USE `service-system`;
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
@@ -0,0 +1,9 @@
-- Co-Lite change add-admin-login-security: rollback of 01-03. Destroys the login history.
USE `service-system`;
DELETE FROM `modules_roles` WHERE `module_id` = 41000000;
DELETE FROM `module` WHERE `id` = 41000000;
DELETE FROM `system_property` WHERE `param` = 'ADMIN_LOGIN_MAX_ATTEMPT' AND `type` = 'ADMIN_LOGIN_BLOCK';
UPDATE `system_property` SET `value` = '1'
WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
DROP TABLE IF EXISTS `login_audit`;
@@ -0,0 +1,130 @@
# Tasks
Design: `design.md`. All tasks run serially: each builds on the one before.
## 1. Data
- [x] 1.1 SQL for the table, settings and module (design decisions 1, 2 and 10).
- Files:
- `sql/01-login-audit.sql`: `CREATE TABLE IF NOT EXISTS login_audit`.
- `sql/02-lockout-settings.sql`: insert `ADMIN_LOGIN_MAX_ATTEMPT` = 5, status Y, type `ADMIN_LOGIN_BLOCK`. Set `ADMIN_LOGIN_BLOCK_PERIOD` to 15.
- `sql/03-login-security-module.sql`: the module row.
- `sql/99-rollback.sql`: drops the table, deletes both rows, and sets the period back to 1.
- Mirror 01 to 03 in `local/seed/03-colite.sql`.
- Apply them to the running local database. This is a local-only, additive change.
- Scope: `local/seed/03-colite.sql`, `openspec/changes/add-admin-login-security/sql/**`
- Verify: `select` shows the table, both settings and the module row.
## 2. services-system
- [x] 2.1 `LoginAudit` entity and repository, `LoginSecurityService` and `LoginSecurityController` (design decisions 2 and 3), plus the gateway route `/loginSecurity/**` to services-system.
- Before coding: check how mobile-api reaches services-system before a user has a token (the forgot-password path). Match that for `isLocked` and `record`, and note the finding in the task report.
- **Tests first:**
- locked at `max` failures inside the period;
- not locked when older failures fall outside it;
- a `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED` resets the count;
- lockout off means never locked;
- settings are read from `system_property`, with S, M, H and D handled;
- `lockedUntil` is computed as the design says;
- the locked list includes only locked usernames;
- unlock writes `UNLOCK_RESET` with who unlocked;
- `record` cuts long values and fills `company_id` for a known username, NULL otherwise;
- `audit` filters by username, event and dates, returns newest first, and caps the size at 100;
- `config` rejects a max or period below 1 and an unknown unit;
- `passwordRules` updates only `ADMIN_PWD_FORMAT` rows and refuses other ids.
- Scope: `solvway-services-system/src/**` (new login-security files, tests), `solvway-api-gateway/src/main/resources/application.yml`
- Verify: `mvn -T 1C -B -q -pl solvway-services-system,solvway-api-gateway -am verify`
- [x] 2.2 `/user/changeAdminPassword` (design decision 4).
- **Tests first,** one for each result:
- `OK` saves the bcrypt hash and keeps `login = Y`;
- `NOT_FOUND` for a non-type-A or disabled user;
- `CURRENT_PASSWORD_WRONG`;
- `PASSWORD_SAME`;
- `PASSWORD_POLICY`.
- Scope: `solvway-services-system/src/main/java/**/controller/UserController.java`, its tests
- Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify`
## 3. mobile-api
- [x] 3.1 Sign-in and sign-out enforcement and recording (design decisions 5 and 6).
- **Tests first:**
- blank fields record nothing;
- locked returns 401 `ACCOUNT_LOCKED`, records `LOGIN_LOCKED`, and never calls services-auth;
- a lock-check error continues to the password check;
- a wrong password, an unknown user or a disabled user records `LOGIN_FAIL`;
- a success records `LOGIN_SUCCESS`;
- a record failure does not change the answer;
- logout records `LOGOUT`;
- the IP and user agent are taken from `X-Client-Ip` and `X-Client-User-Agent`.
- Scope: `solvway-mobile-api/src/**` (`AdminAuthController`, a new login-audit client, constants, tests)
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- [x] 3.2 `POST /api/admin/auth/change-password` (design decision 7).
- **Tests first:**
- each 400 code;
- `CURRENT_PASSWORD_WRONG` records `LOGIN_FAIL`;
- locked is refused before the services-system call;
- success records `PASSWORD_CHANGED` and returns 204;
- a pending first-login user gets 403 `PASSWORD_RESET_REQUIRED`.
- Scope: `solvway-mobile-api/src/**` (`AdminAuthController`, `AdminAuthenticationService`, request record, tests)
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- [x] 3.3 `AdminLoginSecurityController` and service (design decision 8).
- **Tests first:**
- class-level `@AdminModule("BO_LOGIN_SECURITY")`;
- each endpoint maps its parameters;
- unlock passes the admin's username as `by` and returns 204;
- a services-system 400 on config or rules passes through as 400 with its message;
- unlock and settings changes write the log line.
- Scope: `solvway-mobile-api/src/**` (new login-security files, tests)
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- Live check through the stack, as the dev admin and made-up local users:
- fail 5 times and see the lock;
- unlock and sign in;
- change a password;
- edit and restore the settings.
## 4. Portal
- [x] 4.1 Sign-in pieces (design decisions 6 and 9).
- The login and logout routes forward `X-Client-Ip` and `X-Client-User-Agent`.
- The login page shows the locked message on `ACCOUNT_LOCKED`.
- Header "Change password" item opens `ChangePasswordDialog`, using the `/api/auth/change-password` route.
- **Tests first:**
- header forwarding;
- the locked message;
- the dialog: validation, the server code shown through `t()`, close on 204;
- the route passes refusals through with their code.
- Scope: `solvway-admin-portal/app/api/auth/**`, `solvway-admin-portal/app/login/**`, `solvway-admin-portal/app/components/app/**`, `solvway-admin-portal/app/components/users/**`, `solvway-admin-portal/app/lib/**`
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
- [x] 4.2 `/login-security` page with History, Locked and Settings tabs, the proxy route, a service and i18n keys (design decision 9).
- **Tests first:**
- History rows and filters go into the query;
- Locked rows, with Unlock behind a confirm, refreshing the list;
- Settings loads, saves, and shows a server validation error;
- the rules table saves status and value;
- `RequireModule` gates the page;
- the proxy refuses dot segments.
- Scope: `solvway-admin-portal/app/login-security/**`, `solvway-admin-portal/app/api/login-security/**`, `solvway-admin-portal/app/lib/**`
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
## 5. Check and docs
- [x] 5.1 Browser check and handover.
- **Playwright on the local stack, with made-up local users:**
- fail sign-in until locked and see the locked message;
- as admin, see the user under Locked, unlock them, and they sign in;
- History shows the events;
- change own password from the header, with a wrong current password first, then success;
- edit Settings and see a validation error, then restore;
- as `noevents`, see no Login security menu entry, and Not authorized at `/login-security`;
- check the pages at 360px.
- **Docs:** `docs/deployment.md` section 3 lists the new SQL files.
- Scope: `docs/deployment.md`
- Verify: screenshots, and the steps above observed.
## Workflow follow-up
- Whole-branch review, push, PR to main and merge, then archive on its own branch.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-30
@@ -0,0 +1,101 @@
# Design
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-company-scoping-design.md`.
## Context
- **Identity is a string everywhere:**
- services-auth issues the JWT with the user's `username` as subject.
- It resolves a token back to a user through services-system `/user/findByUsernameWithPassword/{username}`.
- mobile-api resolves the caller from the token about 40 times. It also uses `caller.getUsername()` for `doneBy`, the lockout key, the `login_audit` username and the audit actor.
- `user.username` is globally unique (`username_UNIQUE`). Member users live in the same table.
- **Already scoped by company:** leads, event leads, event salespersons and interests are queried by the caller's company. mobile-api passes `caller.getCompanyId()` to services-counter.
- **Not scoped:**
- the users search (services-system);
- events (the Tastefully `event` table, services-counter, no `company_id`);
- emails (service-email, no `company_id`);
- login history and locked users (services-system; `login_audit.company_id` exists but is unused);
- the audit log (services-log; `audit_event.company_id` exists but is unused).
- **Super admin today:** holds role id 1. Checked in `AppAccessAspect`, `AdminUserService`, `AdminRoleService`, `AdminAclService` and `AdminEmailService`.
- **Company today:** `company` is `(id, name, create_date)`, with one row (id 1, "Co-Lite"). No entity or API.
- **Emails:** mobile-api `EmailService` publishes emails to `email-save-request-topic`, and service-email saves them.
## Goals / Non-Goals
**Goals:**
- Every scoped admin read and write carries the caller's company; super admins see all or a picked company.
- Company sign-in without changing services-auth, the token format or member sign-in.
- Adding a company needs no code, deploy or database work.
**Non-Goals:**
- Members and the customer portal.
- Company admins with their own roles or settings.
- Stamping a super admin's audit row with the changed record's company.
- Deleting companies.
## Decisions
1. **The stored username of a staff user is the login name `local@code`.**
- The portal sends `company` and `username`. mobile-api builds the login name: `username@company`, lowercased code; a blank company means the plain username, which is a super admin.
- services-system stores `john@ins` in `user.username`. The existing unique key then gives per-company uniqueness. services-auth, tokens, `findByUsername*`, `login_audit` and the audit actor all keep working on that one string unchanged.
- Screens show the local part (`john`) next to the company. A username input SHALL NOT contain `@`.
- Alternative rejected: a new `login_name` column, or a lookup split across company and username. Either would touch services-auth and every token lookup for the same outcome.
- The user's choice of approach B is preserved: per-company usernames, a separate Company field and a renamable code.
2. **Company code change:**
- A services-system `@Transactional` endpoint renames the code and rewrites `username = CONCAT(local, '@', newCode)` for that company's admin users.
- Old tokens no longer resolve to a user, so those sessions end on their next request. The username column is the session's identity, so nothing else is needed.
- Login history keeps the old names.
3. **Company table and API:**
- `company` gains `code varchar(20) NOT NULL UNIQUE` and `status char(1) NOT NULL DEFAULT 'A'`.
- services-system gets a `Company` entity, repository and `/company/*` endpoints: list, find, save, rename-code.
- mobile-api gets `AdminCompanyController` (`/api/admin/companies`), super admin only.
4. **Super admin check, in one place:**
- `AdminCompanyScope` (mobile-api) defines `isSuper(caller)` as "no company AND holds role 1". It replaces the role-only checks.
- `scope(caller, requestedCompanyId)` returns the company to filter by:
- staff: their own company, ignoring any request value;
- super admin: the requested company, or null for all.
- `requireCompanyForCreate(caller, requested)`: a super admin must choose one.
- `requireSuper(caller)` answers 403.
- Ported from babyboo's `AdminCountryScope` pattern.
5. **Inactive company:**
- `AdminSessionGuard`, which already loads the caller on every admin request, refuses a staff user whose company is inactive, with the same 401 as a dead session.
- `AdminAuthController.login` refuses one with `BAD_LOGIN`.
- The company status comes from services-system with the user, by adding `companyStatus` to the user lookup. That avoids an extra call per request.
6. **Scoped queries:**
- Each backend list or search endpoint takes an optional `companyId`; null means all companies, and only mobile-api decides when null is allowed.
- Detail and edit endpoints resolve the record, then compare its company with the scope; a mismatch answers 404.
- Where a services-counter query takes a mandatory `companyId` today, it becomes optional for lists.
- Every write still takes a concrete company.
7. **Events and emails get `company_id`:**
- `event.company_id bigint NULL`, set from the scope on create and never changed by edit.
- `email.company_id bigint NULL`, set by mobile-api `EmailService` from the user the email is for (forgot password, temporary password) and stored by service-email.
- Public form emails and other system emails have no company and are visible to super admins only.
8. **Interests become shared:**
- The unique key `(company_id, name)` becomes `(name)`; queries stop filtering by company.
- `interest.company_id` stays, unused and nullable, so no data is lost.
- Writes are super admin only.
9. **Login history and audit:**
- `login_audit.company_id` is filled from the user that the login name matches; it is already done this way.
- The audit actor's company is already stored.
- The searches take the scope; NULL-company rows match only when the scope is "all".
10. **Portal:**
- `AdminAuthContext` gains `companyId`, `companyCode` and `isSuper` from the login response.
- Super admins get a header `CompanyPicker`, persisted per tab. It feeds `companyId` into the list queries and the default of create forms.
- A `Company` column appears on scoped lists when "All companies" is selected.
- The login and forgot-password pages get a Company field.
- `/companies` is gated by `isSuper`, not by a module.
11. **One-time data step** (change folder SQL plus seed):
- Set company 1 to `INS`/`ins`; insert `CV`/`cv`.
- Set `admin` to company NULL.
- Rewrite the other admin usernames to `username@ins`. First check that none contains `@`; stop if one does.
- Set existing events and emails to company 1.
- Move the interest unique key.
## Risks / Trade-offs
- **Member usernames share the column.** A member whose username is exactly `john@ins` would block creating staff `john` in INS. Members do not exist in Co-Lite at go-live; the users API reports such a clash as "username taken".
- **The login name is visible in history and audit.** Login history and the audit log show `john@ins`, which is clear for staff and super admins alike.
- **A code change ends sessions.** This is intentional, and the Companies screen warns before saving.
- **Every scoped endpoint must use the scope.** A missed endpoint is a cross-company leak.
- Mitigation: one helper, a test per endpoint for another company's record, and a whole-branch review that checks every `/api/admin/**` handler.
- **Tokens in flight at deploy:** their subjects (for example `sales1`) no longer match the rewritten usernames, so every session ends. Co-Lite is not deployed yet, so nobody is affected.
@@ -0,0 +1,39 @@
# Proposal
## Why
Co-Lite goes live on 2027-01-15 with two test-run companies, INS and CV, and more are planned. Each company's staff must see only their own company's data, and one or more super admins must see and manage everything, including creating companies. Everything built so far assumes a single company: users, events, emails, login history and the audit log are unscoped, interests are per company, and there is no way to create a company or tell companies apart at sign-in. Approved design: `docs/superpowers/specs/2026-11-30-company-scoping-design.md`.
## What Changes
- **Companies:** `company` gains a unique `code` and an active/inactive `status`. A new super-admin-only Companies screen lists, creates and edits companies. An inactive company's staff cannot sign in.
- **Sign-in:** the admin login page asks for Company, Username and Password; a super admin leaves Company empty. Usernames and emails are unique within a company. Forgot password asks for the same company and username plus the email.
- **Super admins:** a super admin is a company-less admin user holding the super admin role. Company staff can never hold that role. There can be several super admins.
- **Scoping:** every admin read, write, export and detail lookup is limited to the caller's company: users, events, event leads, leads, emails, login history, locked users and the audit log. Another company's record answers 404. Super admins see all companies, can narrow to one, and pick the company when creating a company-owned record.
- **Shared data:** roles, interests, lockout settings and password rules are shared by all companies, and only super admins edit them. Interests become one shared list.
- **Portal:** a header company picker and a Company column for super admins; Company fields on the login, forgot-password, user and event forms; the Companies screen.
- **BREAKING (sign-in):** company staff must enter their company code to sign in. The deploy signs everyone out.
- **Deploy SQL:** company code/status, `company_id` on `event` and `email`, the interest unique key, staff login names, INS and CV setup.
## Capabilities
### New Capabilities
- `company-scoping`: companies, the Companies screen, company sign-in identity, super admins, and the rule that limits every admin view and action to the caller's company.
### Modified Capabilities
- `admin-access`: staff login and forgot password take a company.
- `admin-users`: company membership, per-company username and email uniqueness, super admin creation.
- `admin-roles`: editing roles becomes super admin only.
- `lead-interests`: one shared interest list, edited by super admins only.
- `admin-login-security`: unlock is limited to the caller's company; settings become super admin only.
## Impact
- **services-system:** company entity, repository and endpoints; user lookup, save and uniqueness by login name; user search by company; login-history and locked-user filters by company.
- **services-counter:** `company_id` on events; event queries by company; interest queries become shared; queries accept "all companies" for super admins.
- **service-email:** `company_id` on emails, set when an email is saved for a user; search by company.
- **services-log:** audit search by company.
- **mobile-api:** login and forgot password with company; one company-scope helper used by every admin service; Companies API; super-admin-only guards on roles, interests and login-security settings.
- **admin portal:** login, forgot-password, header picker, Company column and fields, Companies screen, super-admin-only screens.
- **Database:** additive SQL in the change folder plus a data step for existing users, events and emails; mirrored in `local/seed/03-colite.sql`.
- **Unchanged:** services-auth, token format, members and the customer portal.
@@ -0,0 +1,53 @@
## MODIFIED Requirements
### Requirement: Staff login
The system SHALL let an active admin user log in through the admin portal with company code, username and password, or with username and password and no company for a super admin, and SHALL return the user's name, roles, company, menu and whether a password change is required.
#### Scenario: Correct credentials
- **GIVEN** an active admin user `sales1` of active company `ins`
- **WHEN** they submit company `ins`, username `sales1` and their password on the login page
- **THEN** they are signed in and land on the portal home
- **AND** the sidebar shows only the menu entries their roles grant
#### Scenario: Super admin
- **GIVEN** the super admin `admin`, who belongs to no company
- **WHEN** they submit username `admin` and their password with the company left empty
- **THEN** they are signed in
#### Scenario: Wrong password
- **WHEN** a user submits a wrong password
- **THEN** `/api/admin/auth/login` responds 401
- **AND** the login page shows an invalid-credentials message without saying whether the company or username exists
#### Scenario: Deactivated user
- **GIVEN** an admin user whose account is deactivated
- **WHEN** they submit their correct password
- **THEN** login is refused with a 401 and the page shows the same invalid-credentials message
#### Scenario: Member account
- **WHEN** a member (non-admin) account submits its correct credentials to the admin login
- **THEN** login is refused with a 401
### Requirement: Forgot password
The system SHALL let a user request a temporary password by entering their company code, username and email on a public forgot-password page; a super admin leaves the company empty. The response SHALL be the same whether or not the details match an active admin user.
#### Scenario: Matching username and email
- **GIVEN** an active admin user `sales1` of company `ins` with email `sales1@example.com`
- **WHEN** someone submits company `ins`, username `sales1` and `sales1@example.com`
- **THEN** a temporary password is emailed to `sales1@example.com`
- **AND** the user must change it at next login
- **AND** the page shows "If the details match an account, we have emailed a temporary password."
#### Scenario: Non-matching details
- **WHEN** someone submits a company, username and email that do not match an active admin user
- **THEN** no password changes and no email is sent
- **AND** the page shows the same message as for a match
@@ -0,0 +1,43 @@
## MODIFIED Requirements
### Requirement: Unlock
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames of their own company that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one of them. A super admin SHALL see and unlock locked usernames of every company, including attempts that match no company. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
#### Scenario: Unlock a locked username
- **GIVEN** INS user `sales1` is locked
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` unlocks `sales1`
- **THEN** `sales1` no longer appears in the locked list
- **AND** `sales1` can sign in with the right password
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
#### Scenario: Another company's locked user
- **GIVEN** CV user `sales2` is locked
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` lists locked users or unlocks `sales2` of CV
- **THEN** `sales2` is not listed and the unlock answers 404
### Requirement: Lockout and password-rule settings
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the lockout settings and the admin password rules, and SHALL let only a super admin change them, because they apply to every company. The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
#### Scenario: Change the lockout settings
- **WHEN** a super admin sets the maximum to 3 and the period to 30 minutes
- **THEN** the next lock decision in every company uses 3 attempts in 30 minutes
#### Scenario: Invalid setting
- **WHEN** a super admin sets the maximum to 0
- **THEN** the change is refused with a validation error and the settings stay as they were
#### Scenario: Change a password rule
- **WHEN** a super admin sets the minimum length rule to 10
- **THEN** a new password of 9 characters is refused by every admin password check
#### Scenario: Company user changes settings
- **WHEN** an INS user with `BO_LOGIN_SECURITY` changes a lockout setting or a password rule
- **THEN** the change is refused with 403 and the settings stay as they were
@@ -0,0 +1,38 @@
## MODIFIED Requirements
### Requirement: Role list and edit
The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let only a super admin create and rename them, because roles are shared by every company. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
#### Scenario: Create role
- **WHEN** a super admin creates role `ROLE_SALES`
- **THEN** it appears in the role list and can be assigned to users of any company
#### Scenario: Duplicate name
- **GIVEN** role `ROLE_SALES` exists
- **WHEN** a super admin creates another role named `ROLE_SALES`
- **THEN** the save is refused with a message
#### Scenario: Company user edits a role
- **WHEN** an INS user with `BO_ROLES` creates or renames a role
- **THEN** the request is refused with 403 and nothing changes
### Requirement: Role permissions
The system SHALL let only a super admin choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. Admins with `BO_ROLES` who are not super admins SHALL see the grants read-only.
#### Scenario: Grant Users module
- **GIVEN** role `ROLE_SALES` without `BO_USERS`
- **WHEN** a super admin grants `BO_USERS` to `ROLE_SALES` and saves
- **THEN** users with `ROLE_SALES` in every company see Users in the sidebar after their next login or session refresh
- **AND** `GET /api/admin/users` responds 200 for them
#### Scenario: Own role
- **GIVEN** an INS user who is not super admin and holds `ROLE_SALES` and `BO_ROLES`
- **WHEN** they change the module grants of `ROLE_SALES`, or of any other role
- **THEN** the save is refused with 403 and the grants stay as they were
@@ -0,0 +1,44 @@
## MODIFIED Requirements
### Requirement: Company membership
Every admin user other than a super admin SHALL belong to exactly one company. A company user's new user SHALL belong to the creating user's company, whatever the request says. A super admin SHALL choose the company of a new user, or no company to create another super admin.
#### Scenario: Company in the request is ignored
- **WHEN** an INS user's create-user request carries the CV company id
- **THEN** the new user belongs to INS
#### Scenario: Super admin chooses the company
- **WHEN** a super admin creates a user and chooses CV
- **THEN** the new user belongs to CV
### Requirement: Create user
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique within the user's company, so the same username or email may exist in another company. A username SHALL NOT contain `@`. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change and SHALL NOT be sent an email.
#### Scenario: New user
- **WHEN** an INS admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
- **THEN** the user is saved as active in INS with a pending password change
- **AND** `sales1` can sign in with company `ins` and that password and must choose a new password before anything else
- **AND** no email is sent
#### Scenario: Duplicate username
- **GIVEN** a user `sales1` exists in INS
- **WHEN** an admin creates another INS user with username `sales1`
- **THEN** the save is refused and the form shows that the username is taken
#### Scenario: Same username in another company
- **GIVEN** a user `sales1` exists in INS
- **WHEN** a CV admin creates user `sales1` in CV
- **THEN** the user is created
#### Scenario: Weak or mismatched initial password
- **WHEN** an admin creates a user with a password that fails the admin password rules, or that does not match its confirmation
- **THEN** the save is refused with a message on the form
- **AND** no user is created
@@ -0,0 +1,128 @@
## ADDED Requirements
### Requirement: Companies
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of lowercase letters, digits and hyphens, compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
#### Scenario: Create a company
- **WHEN** a super admin creates company `CV` with code `cv`
- **THEN** it is listed as active
- **AND** staff can be created in it
#### Scenario: Duplicate code
- **GIVEN** a company with code `ins`
- **WHEN** a super admin creates or renames another company to code `INS`
- **THEN** the save is refused and the code is reported as taken
#### Scenario: Not a super admin
- **WHEN** company staff open the Companies page or call a companies endpoint
- **THEN** the page shows not-authorised and the endpoint responds 403
### Requirement: Company sign-in
The system SHALL sign company staff in with company code, username and password, and SHALL sign super admins in with username and password and no company. The answer SHALL be the same for a wrong or unknown company, an inactive company, an unknown user and a wrong password. A user's sessions SHALL end when their company is deactivated or its code is changed.
#### Scenario: Staff sign-in
- **GIVEN** an active user `john` in active company `ins`
- **WHEN** they sign in with company `ins`, username `john` and the right password
- **THEN** they are signed in as `john` of INS
#### Scenario: Same username in two companies
- **GIVEN** a user `john` in INS and a different user `john` in CV
- **WHEN** someone signs in with company `cv`, username `john` and CV John's password
- **THEN** they are signed in as CV's John and see only CV data
#### Scenario: Wrong company
- **WHEN** INS's `john` signs in with company `cv` or a code that does not exist
- **THEN** login is refused with the same invalid-credentials answer as a wrong password
#### Scenario: Inactive company
- **GIVEN** company CV is deactivated
- **WHEN** a CV user signs in with the right password, or uses an existing session
- **THEN** the sign-in is refused with the invalid-credentials answer and the session ends
#### Scenario: Code changed
- **GIVEN** a signed-in user of the company with code `ins`
- **WHEN** a super admin changes that code to `ins-my`
- **THEN** the user's session ends
- **AND** they sign in again with company `ins-my`
### Requirement: Super admins
A super admin SHALL be an admin user who belongs to no company and holds the super admin role. Only a super admin SHALL create another super admin. The super admin role SHALL NOT be granted to a user who belongs to a company, and every admin user who is not a super admin SHALL belong to a company.
#### Scenario: Create a second super admin
- **WHEN** a super admin creates a user with no company
- **THEN** the user is created as a super admin and signs in without a company
#### Scenario: Super admin role for company staff
- **WHEN** anyone assigns the super admin role to a user of INS
- **THEN** the save is refused with a message
### Requirement: Company data is separated
The system SHALL limit every admin list, search, export, detail, create, edit and action to the caller's company for: users, events, event teams, event leads, leads, emails, login history, locked users and audit events. A record of another company SHALL answer 404, as if it did not exist.
#### Scenario: Lists show own company only
- **GIVEN** leads, events and users in INS and in CV
- **WHEN** an INS user with the matching modules opens Leads, Events or Users
- **THEN** only INS records are listed
- **AND** an export contains only INS leads
#### Scenario: Another company's record by id
- **GIVEN** a CV lead, event, user or email
- **WHEN** an INS user requests it, edits it or acts on it by its id
- **THEN** the answer is 404 and nothing changes
#### Scenario: Same phone in two companies
- **GIVEN** INS has a lead with mobile `+60123456789`
- **WHEN** a CV user captures a lead with the same mobile at a CV event
- **THEN** a new CV lead is created and flagged New
- **AND** the INS lead is unchanged
### Requirement: Super admin sees all companies
The system SHALL show super admins every company's records by default, SHALL let them narrow any scoped list to one company, and SHALL show each record's company in mixed lists. Creating a company-owned record (user, event, event lead) SHALL require a super admin to choose the company.
#### Scenario: Mixed list
- **WHEN** a super admin opens Leads with all companies selected
- **THEN** INS and CV leads are listed together with a Company column
#### Scenario: Pick a company
- **WHEN** a super admin picks CV in the company picker
- **THEN** scoped lists show CV records only
#### Scenario: Create without a company
- **WHEN** a super admin creates an event without choosing a company
- **THEN** the save is refused and the form asks for a company
### Requirement: Company of login and audit records
An audit event and a login-history record SHALL belong to the company of the user who acted, or of the user who tried to sign in when the given company and username match a user. Records with no company SHALL be visible to super admins only.
#### Scenario: Super admin edits a company record
- **WHEN** a super admin edits an INS lead
- **THEN** the audit event has no company
- **AND** INS staff with Audit log do not see it, and super admins do
#### Scenario: Failed sign-in with an unknown company
- **WHEN** someone fails to sign in with a company code that does not exist
- **THEN** the login-history record has no company and only super admins see it
@@ -0,0 +1,34 @@
## MODIFIED Requirements
### Requirement: Interest list
The system SHALL keep one interest list shared by all companies. Admins with `BO_INTERESTS` SHALL see the list, and only a super admin SHALL add, rename, reorder, deactivate and reactivate interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case. Interests SHALL NOT be deletable.
#### Scenario: Add interest
- **WHEN** a super admin adds `Kitchen appliances`
- **THEN** it is listed as active
- **AND** staff of every company can tag leads with it
#### Scenario: Duplicate name
- **GIVEN** an interest `Kitchen appliances`
- **WHEN** a super admin adds `kitchen APPLIANCES`
- **THEN** the save is refused and the name is reported as a duplicate
#### Scenario: Deactivate
- **GIVEN** an active interest `Cookware`
- **WHEN** a super admin deactivates it
- **THEN** it is still listed, marked inactive
- **AND** it is no longer offered when capturing a lead in any company
#### Scenario: Company user edits
- **WHEN** an INS user with `BO_INTERESTS` adds, renames or deactivates an interest
- **THEN** the request is refused with 403 and the list is unchanged
#### Scenario: No module
- **WHEN** an admin without `BO_INTERESTS` opens the Interests page or calls an interests endpoint
- **THEN** the page shows not-authorised and the endpoint responds 403
@@ -0,0 +1,16 @@
-- Co-Lite change add-company-scoping: company code and status; INS and CV.
-- Target: `service-system`.`company`. Run once, after the release package, before 02 and 03.
-- DDL: run with a user that may alter tables, not the services' user.
USE `service-system`;
ALTER TABLE `company`
ADD COLUMN `code` varchar(20) NULL AFTER `name`,
ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`;
-- The existing company (all current data) becomes INS.
UPDATE `company` SET `name` = 'INS', `code` = 'ins' WHERE `id` = 1;
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'cv', 'A');
ALTER TABLE `company`
MODIFY COLUMN `code` varchar(20) NOT NULL,
ADD UNIQUE KEY `uk_company_code` (`code`);
@@ -0,0 +1,17 @@
-- Co-Lite change add-company-scoping: company on events and emails; one shared interest list.
-- Run once, after 01. DDL: run with a user that may alter tables.
USE `service-counter`;
ALTER TABLE `event` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_event_company` (`company_id`);
UPDATE `event` SET `company_id` = 1 WHERE `company_id` IS NULL;
-- Interests are shared by every company: unique by name (case-insensitive collation); company_id kept, unused.
ALTER TABLE `interest`
DROP INDEX `uk_interest_company_name`,
MODIFY COLUMN `company_id` bigint NULL,
ADD UNIQUE KEY `uk_interest_name` (`name`);
USE `service-email`;
ALTER TABLE `email` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_email_company` (`company_id`);
UPDATE `email` SET `company_id` = 1 WHERE `company_id` IS NULL;
@@ -0,0 +1,24 @@
-- Co-Lite change add-company-scoping: admin sign-in names.
-- Super admins (role 1) belong to no company and keep their username.
-- Every other admin user keeps company 1 (INS) and is renamed username@ins; they sign in with company "ins".
-- Ends every admin session (token subjects no longer match). Run once, after 01 and 02.
USE `service-system`;
-- Stop if any admin username already contains '@': it would be ambiguous after the rename.
DROP PROCEDURE IF EXISTS `colite_check_admin_usernames`;
DELIMITER //
CREATE PROCEDURE `colite_check_admin_usernames`()
BEGIN
IF EXISTS (SELECT 1 FROM `user` WHERE `type` = 'A' AND `username` LIKE '%@%') THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An admin username contains @; rename it before running this script';
END IF;
END //
DELIMITER ;
CALL `colite_check_admin_usernames`();
DROP PROCEDURE `colite_check_admin_usernames`;
UPDATE `user` u SET u.`company_id` = NULL
WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins')
WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
@@ -0,0 +1,15 @@
-- Co-Lite change add-company-scoping: rollback of 01-03. CV's data, if any, stays in its tables with company 2.
USE `service-system`;
UPDATE `user` SET `username` = SUBSTRING_INDEX(`username`, '@', 1) WHERE `type` = 'A' AND `username` LIKE '%@%';
UPDATE `user` SET `company_id` = 1 WHERE `type` = 'A' AND `company_id` IS NULL;
ALTER TABLE `company` DROP INDEX `uk_company_code`, DROP COLUMN `status`, DROP COLUMN `code`;
UPDATE `company` SET `name` = 'Co-Lite' WHERE `id` = 1;
USE `service-counter`;
ALTER TABLE `event` DROP KEY `idx_event_company`, DROP COLUMN `company_id`;
UPDATE `interest` SET `company_id` = 1 WHERE `company_id` IS NULL;
ALTER TABLE `interest` DROP INDEX `uk_interest_name`, MODIFY COLUMN `company_id` bigint NOT NULL,
ADD UNIQUE KEY `uk_interest_company_name` (`company_id`, `name`);
USE `service-email`;
ALTER TABLE `email` DROP KEY `idx_email_company`, DROP COLUMN `company_id`;
@@ -0,0 +1,124 @@
# Tasks
Design: `design.md`. All tasks run serially, ordered so that sign-in keeps working after each one. Every scoped endpoint gets a test where another company's record answers 404 (or is absent from the list).
## 1. Data
- [x] 1.1 SQL and local seed (design decisions 3, 7, 8 and 11).
- Files in `sql/`:
- `01-company-code-status.sql`: add `code` and `status`; set company 1 to `INS`/`ins`; insert `CV`/`cv`.
- `02-company-columns.sql`: add `company_id` to `event` and `email`; set existing rows to company 1; move the interest unique key to `(name)`.
- `03-admin-login-names.sql`: stop if any admin username contains `@`; set `admin` to company NULL; rewrite the other admin usernames to `username@ins`.
- `99-rollback.sql`.
- Mirror them in `local/seed/03-colite.sql`, apply them locally, and confirm `admin` still signs in.
- Scope: `local/**`, `openspec/changes/add-company-scoping/sql/**`
- Verify: `select` shows the codes, the NULL-company `admin`, the rewritten usernames and the new columns.
## 2. Backend services
- [x] 2.1 services-system: companies, users and login security (decisions 1, 2, 3, 5 and 9).
- Tests first:
- company list, create, edit; duplicate code (ignoring case) refused; code format validated;
- rename-code rewrites only that company's admin usernames, in one transaction;
- user lookups return the company code and status;
- the user search filters by company when given;
- email uniqueness is per company;
- role 1 cannot be saved on a user with a company;
- login history and locked users filter by company, and NULL-company rows appear only for "all".
- Scope: `solvway-services-system/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify`
- [x] 2.2 services-counter: events, leads, event leads and interests (decisions 6, 7 and 8).
- Tests first:
- an event is saved with its company and listed by company, or for all when none is given;
- lead and event-lead lists accept "all companies";
- detail lookups return the record's company;
- interests are one list, unique by name ignoring case.
- Scope: `solvway-services-counter/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`
- [x] 2.3 service-email and services-log (decisions 7 and 9).
- Tests first:
- an email saved with a company keeps it, and the email search filters by company;
- the audit search filters by company, and NULL-company rows appear only for "all".
- Scope: `solvway-services-email/src/**`, `solvway-services-log/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-services-email,solvway-services-log -am verify`
## 3. mobile-api
- [x] 3.1 Sign-in, company scope and Companies API (decisions 1, 3, 4 and 5).
- Tests first:
- login and forgot-password build the login name from company and username; a blank company means a super admin;
- a wrong company, an inactive company and an unknown user all give `BAD_LOGIN`;
- the session guard ends an inactive company's sessions;
- `isSuper` needs both no company and role 1;
- `scope` ignores a staff request's company;
- the Companies API is super admin only;
- the login response carries the company and `isSuper`.
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- [x] 3.2 Users, roles, interests and login-security settings (decisions 1, 4 and 8).
- Tests first:
- users are listed, created and edited within the scope, and another company's user answers 404;
- a username with `@` is refused;
- a super admin must choose a company or create a super admin;
- role 1 is refused for company users;
- role create, rename and grants, interest writes and lockout or password-rule changes answer 403 for company staff;
- unlock works only within the caller's company.
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- [x] 3.3 Events, leads, event leads and exports (decision 6).
- Tests first:
- each list and export is limited to the scope;
- another company's event, lead or event lead answers 404 on detail, edit, capture and export;
- a super admin capture or event create without a company is refused;
- the event team only offers users of the event's company.
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- [x] 3.4 Emails, login history and audit log (decisions 7 and 9).
- Tests first:
- each is limited to the scope;
- emails for a user carry that user's company;
- another company's email or audit event answers 404.
- Scope: `solvway-mobile-api/src/**`
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- Live check on the local stack:
- INS and CV users each see only their own data;
- `admin` sees both;
- a CV record by id answers 404 to INS.
## 4. Portal
- [x] 4.1 Sign-in, session and Companies screen (decision 10).
- Tests first:
- the login and forgot-password pages send company, username and password, and a blank company is allowed;
- the auth context holds `isSuper` and the company;
- `/companies` lists, creates and edits companies, warns before a code change, and is refused for non-super users.
- Scope: `solvway-admin-portal/app/**`
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
- [x] 4.2 Company picker, Company column, company fields and super-admin-only screens (decision 10).
- Tests first:
- the picker is shown only to super admins and feeds the list queries;
- the Company column appears for "All companies";
- user, event and capture forms show Company for super admins only;
- Roles, Interests and the Login security Settings tab are read-only or hidden for company staff.
- Scope: `solvway-admin-portal/app/**`
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
## 5. Check and docs
- [x] 5.1 Browser check and handover.
- Playwright on the local stack:
- `admin` creates CV users and a CV event, then switches the picker between all, INS and CV;
- an INS user and a CV user with the same username each sign in with their company and see only their own leads, events, users, emails, login history and audit log;
- an INS user opening a CV record by URL sees not-found;
- renaming CV's code ends the CV user's session;
- deactivating CV blocks its sign-in;
- check at 1280 px and 360 px.
- Docs, in `docs/deployment.md`:
- section 3: the new SQL, and that it ends every session;
- section 10: company sign-in and super admins.
- Scope: `docs/deployment.md`
- Verify: screenshots, and the steps above observed.
## Workflow follow-up
- Whole-branch review, with every `/api/admin/**` handler checked for scoping. Then push, PR to main and merge, and archive on its own branch.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-01
@@ -0,0 +1,23 @@
## Why
The whole-branch review of add-company-scoping (PR #25) found that the code trusts the "every non-super admin belongs to a company" rule instead of enforcing it. An admin user with no company who is not a super admin (left over from before companies, or created by a direct DB edit) is scoped to all companies. A company user who still holds role 1 skips every module check and is treated as a super admin when reading super admins' emails.
## What Changes
- Company scope fails closed: an admin with no company who is not a super admin gets 403 `COMPANY_REQUIRED` on every company-scoped admin endpoint instead of seeing all companies.
- The admin module check grants all modules only to a super admin (no company and role 1), not to any holder of role 1.
- The email detail hides super admins' emails from every caller who is not a super admin, using the same super-admin test.
## Capabilities
### New Capabilities
### Modified Capabilities
- `company-scoping`: adds the "Invalid admins fail closed" requirement for the two invalid states.
## Impact
- `solvway-mobile-api`: `AdminCompanyScope`, `AppAccessAspect`, `AdminEmailService`.
- No API shape, schema or portal change. Valid users (super admins, and staff with a company) see no difference.
- Deferred: the capture event list still loads only the first 100 enabled events (marked `ponytail:` in `AdminEventLeadService`).
@@ -0,0 +1,18 @@
## ADDED Requirements
### Requirement: Invalid admins fail closed
The system SHALL refuse every company-scoped request from an admin with no company who is not a super admin, and SHALL grant a company user who holds the super admin role only the modules and records their company and other roles allow.
#### Scenario: Admin without a company who is not a super admin
- **GIVEN** an admin user with no company and no super admin role
- **WHEN** they open Leads, Events, Users or any other company-scoped list or record
- **THEN** the request is refused with 403
- **AND** no company's records are returned
#### Scenario: Company user still holding the super admin role
- **GIVEN** a user of INS who holds the super admin role and a role granting only Leads
- **WHEN** they open Users or another super admin's email
- **THEN** the request is refused with 403
@@ -0,0 +1,10 @@
## 1. Fail closed
- [x] 1.1 `AdminCompanyScope.scope` and `requireCompanyForCreate` refuse (403 `COMPANY_REQUIRED`) an admin with no company who is not a super admin
- Depends on: none
- Scope: `solvway-mobile-api/src/**/useraccess/AdminCompanyScope*.java`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
- [x] 1.2 `AppAccessAspect` skips the module check only for `AdminCompanyScope.isSuper`; `AdminEmailService` uses the same test
- Depends on: 1.1
- Scope: `solvway-mobile-api/src/**/useraccess/AppAccessAspect*.java`, `solvway-mobile-api/src/**/service/AdminEmailService*.java`
- Verify: `mvn -T 1C -q -pl solvway-mobile-api verify`
+14 -8
View File
@@ -8,20 +8,26 @@ Staff log in to the Co-Lite admin portal, and every admin page and `/api/admin/*
### Requirement: Staff login
The system SHALL let an active admin user log in with username and password through the admin portal, and SHALL return the user's name, roles, menu and whether a password change is required.
The system SHALL let an active admin user log in through the admin portal with company code, username and password, or with username and password and no company for a super admin, and SHALL return the user's name, roles, company, menu and whether a password change is required.
#### Scenario: Correct credentials
- **GIVEN** an active admin user `admin` with password `colite-dev-admin`
- **WHEN** they submit those credentials on the login page
- **GIVEN** an active admin user `sales1` of active company `ins`
- **WHEN** they submit company `ins`, username `sales1` and their password on the login page
- **THEN** they are signed in and land on the portal home
- **AND** the sidebar shows only the menu entries their roles grant
#### Scenario: Super admin
- **GIVEN** the super admin `admin`, who belongs to no company
- **WHEN** they submit username `admin` and their password with the company left empty
- **THEN** they are signed in
#### Scenario: Wrong password
- **WHEN** a user submits a wrong password
- **THEN** `/api/admin/auth/login` responds 401
- **AND** the login page shows an invalid-credentials message without saying whether the username exists
- **AND** the login page shows an invalid-credentials message without saying whether the company or username exists
#### Scenario: Deactivated user
@@ -53,19 +59,19 @@ The system SHALL require a user whose password is temporary (new user or reset)
### Requirement: Forgot password
The system SHALL let a user request a temporary password by entering their username and email on a public forgot-password page. The response SHALL be the same whether or not the username and email match an active admin user.
The system SHALL let a user request a temporary password by entering their company code, username and email on a public forgot-password page; a super admin leaves the company empty. The response SHALL be the same whether or not the details match an active admin user.
#### Scenario: Matching username and email
- **GIVEN** an active admin user with username `sales1` and email `sales1@example.com`
- **WHEN** someone submits `sales1` and `sales1@example.com`
- **GIVEN** an active admin user `sales1` of company `ins` with email `sales1@example.com`
- **WHEN** someone submits company `ins`, username `sales1` and `sales1@example.com`
- **THEN** a temporary password is emailed to `sales1@example.com`
- **AND** the user must change it at next login
- **AND** the page shows "If the details match an account, we have emailed a temporary password."
#### Scenario: Non-matching details
- **WHEN** someone submits a username and email that do not match an active admin user
- **WHEN** someone submits a company, username and email that do not match an active admin user
- **THEN** no password changes and no email is sent
- **AND** the page shows the same message as for a match
+111
View File
@@ -0,0 +1,111 @@
# admin-audit-log Specification
## Purpose
Record who did what in the admin portal: every admin write, chosen sensitive reads and refused attempts, with allow-listed before/after values and no personal data, kept for a configurable retention and readable on the Audit log screen by admins granted `BO_AUDIT_LOG`.
## Requirements
### Requirement: Admin writes are recorded
The system SHALL record an audit event for every state-changing admin API call made with a valid admin token, successful or not, holding the time, admin username, module, readable action code, HTTP method, path template (never the concrete path or query), target id, outcome with HTTP status, and client IP. Sign-in, sign-out, token refresh, forgot-password, own password change from the user menu, and calls without a valid admin token SHALL NOT be recorded.
#### Scenario: A user edit is recorded
- **WHEN** admin `admin` updates user 4
- **THEN** an audit event is saved with actor `admin`, module `BO_USERS`, action `USER_UPDATE`, path template `PUT /api/admin/users/{id}`, target `4`, outcome `SUCCESS`, and the client IP
#### Scenario: A failed write is recorded
- **WHEN** an admin's role update is refused with status 400
- **THEN** an audit event is saved with outcome `FAILURE` and status 400
#### Scenario: Sign-in is not recorded
- **WHEN** an admin signs in or signs out
- **THEN** no audit event is saved
#### Scenario: First-login password change is recorded
- **WHEN** a new admin sets their password at first login
- **THEN** an audit event with action `AUTH_FIRST_LOGIN` is saved
### Requirement: Refused access is recorded
The system SHALL record an audit event with outcome `FAILURE` when a valid admin token is refused by the access check (missing module, super admin required, or pending first-login change).
#### Scenario: Missing module
- **GIVEN** admin `noevents` has no `BO_EVENTS`
- **WHEN** `noevents` tries to create an event
- **THEN** the request is refused with 403
- **AND** an audit event with actor `noevents`, module `BO_EVENTS` and outcome `FAILURE` is saved
### Requirement: Sensitive reads are recorded
The system SHALL record an audit event when an admin exports leads, exports event leads, or opens a saved email. Read-only POST calls marked as such SHALL NOT be recorded.
#### Scenario: Opening an email
- **WHEN** an admin opens email 12
- **THEN** an audit event with action `EMAIL_VIEW` and target `12` is saved
#### Scenario: Lead export
- **WHEN** an admin downloads the lead export
- **THEN** an audit event with action `LEAD_EXPORT` is saved
### Requirement: Allow-listed changes
The system SHALL attach before and after values only for these fields: a user's role names and enabled flag, a role's granted module codes, and the login-security lockout settings and password rules. For lead and event-lead edits the system SHALL record only the names of the fields that changed, never their values. No audit event SHALL contain a password, token, raw request body, or lead name, phone, email or notes.
#### Scenario: Role change on a user
- **WHEN** an admin changes user 4's roles from `Sales` to `Sales, Manager`
- **THEN** the event's changes show roles before `Sales` and after `Sales, Manager`
#### Scenario: Lead edit records field names only
- **WHEN** an admin changes a lead's phone and notes
- **THEN** the event's changes list the fields `phone` and `notes`
- **AND** neither the old nor the new phone or notes appear in the event
### Requirement: Recording never blocks the action
Recording SHALL be best-effort. A failure to publish or save an audit event MUST NOT change the response of the admin call.
#### Scenario: Publish failure
- **GIVEN** the audit event cannot be published
- **WHEN** an admin updates a user
- **THEN** the update succeeds as usual
- **AND** the failure is logged
### Requirement: Retention
The system SHALL delete audit events older than the configured retention period, 730 days by default, on a schedule.
#### Scenario: Old events are purged
- **WHEN** the purge runs with a retention of 730 days
- **THEN** events older than 730 days are deleted
- **AND** newer events are kept
### Requirement: Audit log screen
The system SHALL let an admin with `BO_AUDIT_LOG` list audit events newest first, paged, filtered by actor, module, action, outcome and date range, and open one event to see its details and changes. An admin without `BO_AUDIT_LOG` SHALL be refused.
#### Scenario: Filter by actor
- **WHEN** an admin with `BO_AUDIT_LOG` filters the audit log by actor `admin`
- **THEN** only events by `admin` are listed, newest first
#### Scenario: Event detail
- **WHEN** an admin opens an event for a role grant change
- **THEN** the detail shows the event's fields and the modules added and removed
#### Scenario: Without the module
- **WHEN** an admin without `BO_AUDIT_LOG` calls the audit log API or opens `/audit-log`
- **THEN** the API answers 403 and the page shows Not authorised
+144
View File
@@ -0,0 +1,144 @@
# admin-login-security Specification
## Purpose
Protect admin sign-in against password guessing: record every admin sign-in, sign-out, unlock and own password change, lock a username after repeated failures, and let authorised admins read the history, unlock staff and edit the lockout and password-rule settings.
## Requirements
### Requirement: Login history
The system SHALL record every admin sign-in attempt, sign-out, unlock and own password change, with the time, trimmed username, event, client IP, user agent and, for a known username, the user's company. Events: `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOGIN_LOCKED`, `LOGOUT`, `UNLOCK_RESET`, `PASSWORD_CHANGED`. Recording SHALL be best-effort and MUST NOT change the sign-in answer. A blank username or password SHALL NOT be recorded.
#### Scenario: Successful sign-in is recorded
- **WHEN** `sales1` signs in with the right password
- **THEN** a `LOGIN_SUCCESS` record for `sales1` is saved with the time, client IP and user agent
#### Scenario: Failed sign-in is recorded
- **WHEN** someone signs in as `sales1` with a wrong password
- **THEN** a `LOGIN_FAIL` record for `sales1` is saved
#### Scenario: Unknown username is recorded
- **WHEN** someone signs in as `nobody1`, which matches no user
- **THEN** a `LOGIN_FAIL` record for `nobody1` is saved with no company
#### Scenario: Sign-out is recorded
- **WHEN** `sales1` signs out
- **THEN** a `LOGOUT` record for `sales1` is saved
#### Scenario: History write failure does not block sign-in
- **GIVEN** the history cannot be written
- **WHEN** `sales1` signs in with the right password
- **THEN** the sign-in succeeds
- **AND** the write failure is logged
### Requirement: Lockout after repeated failures
The system SHALL lock a username when lockout is on and its `LOGIN_FAIL` records reach the configured maximum, counting only records inside the configured period and after its latest `LOGIN_SUCCESS`, `UNLOCK_RESET` or `PASSWORD_CHANGED`. The maximum, period, unit and on/off switch SHALL come from settings. Failures SHALL count for unknown usernames too, so a lock does not reveal whether an account exists. The lock SHALL end once the counted failures leave the period.
#### Scenario: Maximum reached locks the username
- **GIVEN** lockout is on with a maximum of 5 in 15 minutes
- **WHEN** `sales1` fails to sign in 5 times within 15 minutes
- **THEN** `sales1` is locked
#### Scenario: Old failures do not count
- **GIVEN** lockout is on with a maximum of 5 in 15 minutes
- **WHEN** `sales1` has 4 failures within the last 15 minutes and 3 older ones
- **THEN** `sales1` is not locked
#### Scenario: A success resets the count
- **WHEN** `sales1` fails 4 times, signs in successfully, then fails 4 more times within 15 minutes
- **THEN** `sales1` is not locked
#### Scenario: Lockout switched off
- **GIVEN** lockout is off
- **WHEN** `sales1` fails 10 times within 15 minutes
- **THEN** `sales1` is not locked
### Requirement: Locked username is refused
The system SHALL refuse sign-in for a locked username before checking the password, with the code `ACCOUNT_LOCKED` and a message telling the user to try later or ask an administrator, and SHALL record `LOGIN_LOCKED`. When the lock state cannot be read because of an infrastructure error, sign-in SHALL proceed to the normal password check.
#### Scenario: Right password while locked
- **GIVEN** `sales1` is locked
- **WHEN** `sales1` signs in with the right password
- **THEN** sign-in is refused with `ACCOUNT_LOCKED`
- **AND** no session is issued
- **AND** a `LOGIN_LOCKED` record is saved
#### Scenario: Lock check unavailable
- **GIVEN** the lock state cannot be read
- **WHEN** `sales1` signs in with the right password
- **THEN** the sign-in succeeds
#### Scenario: Portal shows the locked message
- **WHEN** sign-in is refused with `ACCOUNT_LOCKED`
- **THEN** the login page shows the locked message instead of "Invalid username or password"
### Requirement: Unlock
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames of their own company that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one of them. A super admin SHALL see and unlock locked usernames of every company, including attempts that match no company. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
#### Scenario: Unlock a locked username
- **GIVEN** INS user `sales1` is locked
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` unlocks `sales1`
- **THEN** `sales1` no longer appears in the locked list
- **AND** `sales1` can sign in with the right password
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
#### Scenario: Another company's locked user
- **GIVEN** CV user `sales2` is locked
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` lists locked users or unlocks `sales2` of CV
- **THEN** `sales2` is not listed and the unlock answers 404
### Requirement: Login history screen
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the login history, newest first and paged, filtered by username, event and date range.
#### Scenario: Filter by event
- **WHEN** an admin filters the history by event `LOGIN_FAIL`
- **THEN** only `LOGIN_FAIL` records are listed, newest first
#### Scenario: Without the module
- **WHEN** an admin without `BO_LOGIN_SECURITY` calls the login-security API
- **THEN** the request is refused with 403
### Requirement: Lockout and password-rule settings
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the lockout settings and the admin password rules, and SHALL let only a super admin change them, because they apply to every company. The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
#### Scenario: Change the lockout settings
- **WHEN** a super admin sets the maximum to 3 and the period to 30 minutes
- **THEN** the next lock decision in every company uses 3 attempts in 30 minutes
#### Scenario: Invalid setting
- **WHEN** a super admin sets the maximum to 0
- **THEN** the change is refused with a validation error and the settings stay as they were
#### Scenario: Change a password rule
- **WHEN** a super admin sets the minimum length rule to 10
- **THEN** a new password of 9 characters is refused by every admin password check
#### Scenario: Company user changes settings
- **WHEN** an INS user with `BO_LOGIN_SECURITY` changes a lockout setting or a password rule
- **THEN** the change is refused with 403 and the settings stay as they were
+56
View File
@@ -0,0 +1,56 @@
# admin-own-password Specification
## Purpose
Let a signed-in admin change their own password, checked against the current password and the admin password rules, without an administrator.
## Requirements
### Requirement: Change own password
The system SHALL let a signed-in admin change their own password by giving the current password, a new password and its confirmation. The new password SHALL pass the admin password rules and SHALL differ from the current one. On success the system SHALL keep the admin signed in, keep their first-login state complete, and record `PASSWORD_CHANGED`. An admin whose first-login password change is still pending SHALL use the first-login flow instead.
#### Scenario: Successful change
- **WHEN** `sales1` gives the right current password and a new password that passes the rules, twice
- **THEN** the new password works at the next sign-in and the old one does not
- **AND** `sales1` stays signed in
- **AND** a `PASSWORD_CHANGED` record is saved
#### Scenario: Confirmation differs
- **WHEN** the new password and its confirmation differ
- **THEN** the change is refused with `PASSWORD_MISMATCH`
#### Scenario: Same as current
- **WHEN** the new password equals the current password
- **THEN** the change is refused with `PASSWORD_SAME`
#### Scenario: Fails the rules
- **WHEN** the new password breaks an admin password rule
- **THEN** the change is refused with `PASSWORD_POLICY`
#### Scenario: Pending first login
- **GIVEN** `sales1` must still complete the first-login password change
- **WHEN** `sales1` calls change password
- **THEN** the request is refused and `sales1` is sent to the first-login flow
### Requirement: Wrong current password counts as a failed sign-in
The system SHALL refuse a change whose current password is wrong with `CURRENT_PASSWORD_WRONG`, and SHALL record it as `LOGIN_FAIL` so that repeated wrong guesses lock the username. A locked username SHALL be refused with `ACCOUNT_LOCKED` before the current password is checked.
#### Scenario: Wrong current password
- **WHEN** `sales1` gives a wrong current password
- **THEN** the change is refused with `CURRENT_PASSWORD_WRONG`
- **AND** a `LOGIN_FAIL` record for `sales1` is saved
#### Scenario: Locked while changing
- **GIVEN** `sales1` is locked
- **WHEN** `sales1` calls change password with the right current password
- **THEN** the change is refused with `ACCOUNT_LOCKED`
- **AND** the password is unchanged
+15 -10
View File
@@ -8,35 +8,40 @@ Admins with the Roles module define roles and choose which back-office modules e
### Requirement: Role list and edit
The system SHALL let an admin with `BO_ROLES` list, create and rename admin roles. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let only a super admin create and rename them, because roles are shared by every company. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
#### Scenario: Create role
- **WHEN** an admin with `BO_ROLES` creates role `ROLE_SALES`
- **THEN** it appears in the role list and can be assigned to users
- **WHEN** a super admin creates role `ROLE_SALES`
- **THEN** it appears in the role list and can be assigned to users of any company
#### Scenario: Duplicate name
- **GIVEN** role `ROLE_SALES` exists
- **WHEN** an admin creates another role named `ROLE_SALES`
- **WHEN** a super admin creates another role named `ROLE_SALES`
- **THEN** the save is refused with a message
#### Scenario: Company user edits a role
- **WHEN** an INS user with `BO_ROLES` creates or renames a role
- **THEN** the request is refused with 403 and nothing changes
### Requirement: Role permissions
The system SHALL let an admin with `BO_ROLES` choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. An admin who is not super admin SHALL NOT change the grants of a role they hold.
The system SHALL let only a super admin choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. Admins with `BO_ROLES` who are not super admins SHALL see the grants read-only.
#### Scenario: Grant Users module
- **GIVEN** role `ROLE_SALES` without `BO_USERS`
- **WHEN** an admin grants `BO_USERS` to `ROLE_SALES` and saves
- **THEN** users with `ROLE_SALES` see Users in the sidebar after their next login or session refresh
- **WHEN** a super admin grants `BO_USERS` to `ROLE_SALES` and saves
- **THEN** users with `ROLE_SALES` in every company see Users in the sidebar after their next login or session refresh
- **AND** `GET /api/admin/users` responds 200 for them
#### Scenario: Own role
- **GIVEN** an admin who is not super admin and holds `ROLE_SALES`
- **WHEN** they change the module grants of `ROLE_SALES` and save
- **THEN** the save is refused with a message, so no admin can widen their own access or lock themselves out of role management
- **GIVEN** an INS user who is not super admin and holds `ROLE_SALES` and `BO_ROLES`
- **WHEN** they change the module grants of `ROLE_SALES`, or of any other role
- **THEN** the save is refused with 403 and the grants stay as they were
### Requirement: Back-office module set
+20 -10
View File
@@ -18,22 +18,27 @@ The system SHALL list admin users only (never members), paginated on the server,
### Requirement: Create user
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change, SHALL belong to the creating admin's company, and SHALL NOT be sent an email.
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique within the user's company, so the same username or email may exist in another company. A username SHALL NOT contain `@`. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change and SHALL NOT be sent an email.
#### Scenario: New user
- **WHEN** an admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
- **THEN** the user is saved as active with a pending password change
- **AND** `sales1` can sign in with that password and must choose a new password before anything else
- **WHEN** an INS admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
- **THEN** the user is saved as active in INS with a pending password change
- **AND** `sales1` can sign in with company `ins` and that password and must choose a new password before anything else
- **AND** no email is sent
- **AND** the user's company is the creating admin's company
#### Scenario: Duplicate username
- **GIVEN** a user `sales1` exists
- **WHEN** an admin creates another user with username `sales1`
- **GIVEN** a user `sales1` exists in INS
- **WHEN** an admin creates another INS user with username `sales1`
- **THEN** the save is refused and the form shows that the username is taken
#### Scenario: Same username in another company
- **GIVEN** a user `sales1` exists in INS
- **WHEN** a CV admin creates user `sales1` in CV
- **THEN** the user is created
#### Scenario: Weak or mismatched initial password
- **WHEN** an admin creates a user with a password that fails the admin password rules, or that does not match its confirmation
@@ -97,12 +102,17 @@ The system SHALL let an admin with `BO_USERS` give an active admin user a new pa
### Requirement: Company membership
Every admin user SHALL belong to exactly one company. The company SHALL be set by the system from the creating admin, never from the request.
Every admin user other than a super admin SHALL belong to exactly one company. A company user's new user SHALL belong to the creating user's company, whatever the request says. A super admin SHALL choose the company of a new user, or no company to create another super admin.
#### Scenario: Company in the request is ignored
- **WHEN** a create-user request carries a company id different from the admin's own
- **THEN** the new user gets the admin's company
- **WHEN** an INS user's create-user request carries the CV company id
- **THEN** the new user belongs to INS
#### Scenario: Super admin chooses the company
- **WHEN** a super admin creates a user and chooses CV
- **THEN** the new user belongs to CV
### Requirement: Temporary password refusals
+151
View File
@@ -0,0 +1,151 @@
# company-scoping Specification
## Purpose
Separate the data of each company using Co-Lite (INS and CV at go-live): staff sign in with their company code and see only their own company's records, while company-less super admins manage companies and see every company.
## Requirements
### Requirement: Companies
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of lowercase letters, digits and hyphens, compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
#### Scenario: Create a company
- **WHEN** a super admin creates company `CV` with code `cv`
- **THEN** it is listed as active
- **AND** staff can be created in it
#### Scenario: Duplicate code
- **GIVEN** a company with code `ins`
- **WHEN** a super admin creates or renames another company to code `INS`
- **THEN** the save is refused and the code is reported as taken
#### Scenario: Not a super admin
- **WHEN** company staff open the Companies page or call a companies endpoint
- **THEN** the page shows not-authorised and the endpoint responds 403
### Requirement: Company sign-in
The system SHALL sign company staff in with company code, username and password, and SHALL sign super admins in with username and password and no company. The answer SHALL be the same for a wrong or unknown company, an inactive company, an unknown user and a wrong password. A user's sessions SHALL end when their company is deactivated or its code is changed.
#### Scenario: Staff sign-in
- **GIVEN** an active user `john` in active company `ins`
- **WHEN** they sign in with company `ins`, username `john` and the right password
- **THEN** they are signed in as `john` of INS
#### Scenario: Same username in two companies
- **GIVEN** a user `john` in INS and a different user `john` in CV
- **WHEN** someone signs in with company `cv`, username `john` and CV John's password
- **THEN** they are signed in as CV's John and see only CV data
#### Scenario: Wrong company
- **WHEN** INS's `john` signs in with company `cv` or a code that does not exist
- **THEN** login is refused with the same invalid-credentials answer as a wrong password
#### Scenario: Inactive company
- **GIVEN** company CV is deactivated
- **WHEN** a CV user signs in with the right password, or uses an existing session
- **THEN** the sign-in is refused with the invalid-credentials answer and the session ends
#### Scenario: Code changed
- **GIVEN** a signed-in user of the company with code `ins`
- **WHEN** a super admin changes that code to `ins-my`
- **THEN** the user's session ends
- **AND** they sign in again with company `ins-my`
### Requirement: Super admins
A super admin SHALL be an admin user who belongs to no company and holds the super admin role. Only a super admin SHALL create another super admin. The super admin role SHALL NOT be granted to a user who belongs to a company, and every admin user who is not a super admin SHALL belong to a company.
#### Scenario: Create a second super admin
- **WHEN** a super admin creates a user with no company
- **THEN** the user is created as a super admin and signs in without a company
#### Scenario: Super admin role for company staff
- **WHEN** anyone assigns the super admin role to a user of INS
- **THEN** the save is refused with a message
### Requirement: Company data is separated
The system SHALL limit every admin list, search, export, detail, create, edit and action to the caller's company for: users, events, event teams, event leads, leads, emails, login history, locked users and audit events. A record of another company SHALL answer 404, as if it did not exist.
#### Scenario: Lists show own company only
- **GIVEN** leads, events and users in INS and in CV
- **WHEN** an INS user with the matching modules opens Leads, Events or Users
- **THEN** only INS records are listed
- **AND** an export contains only INS leads
#### Scenario: Another company's record by id
- **GIVEN** a CV lead, event, user or email
- **WHEN** an INS user requests it, edits it or acts on it by its id
- **THEN** the answer is 404 and nothing changes
#### Scenario: Same phone in two companies
- **GIVEN** INS has a lead with mobile `+60123456789`
- **WHEN** a CV user captures a lead with the same mobile at a CV event
- **THEN** a new CV lead is created and flagged New
- **AND** the INS lead is unchanged
### Requirement: Super admin sees all companies
The system SHALL show super admins every company's records by default, SHALL let them narrow any scoped list to one company, and SHALL show each record's company in mixed lists. Creating a company-owned record (user, event, event lead) SHALL require a super admin to choose the company.
#### Scenario: Mixed list
- **WHEN** a super admin opens Leads with all companies selected
- **THEN** INS and CV leads are listed together with a Company column
#### Scenario: Pick a company
- **WHEN** a super admin picks CV in the company picker
- **THEN** scoped lists show CV records only
#### Scenario: Create without a company
- **WHEN** a super admin creates an event without choosing a company
- **THEN** the save is refused and the form asks for a company
### Requirement: Company of login and audit records
An audit event and a login-history record SHALL belong to the company of the user who acted, or of the user who tried to sign in when the given company and username match a user. Records with no company SHALL be visible to super admins only.
#### Scenario: Super admin edits a company record
- **WHEN** a super admin edits an INS lead
- **THEN** the audit event has no company
- **AND** INS staff with Audit log do not see it, and super admins do
#### Scenario: Failed sign-in with an unknown company
- **WHEN** someone fails to sign in with a company code that does not exist
- **THEN** the login-history record has no company and only super admins see it
### Requirement: Invalid admins fail closed
The system SHALL refuse every company-scoped request from an admin with no company who is not a super admin, and SHALL grant a company user who holds the super admin role only the modules and records their company and other roles allow.
#### Scenario: Admin without a company who is not a super admin
- **GIVEN** an admin user with no company and no super admin role
- **WHEN** they open Leads, Events, Users or any other company-scoped list or record
- **THEN** the request is refused with 403
- **AND** no company's records are returned
#### Scenario: Company user still holding the super admin role
- **GIVEN** a user of INS who holds the super admin role and a role granting only Leads
- **WHEN** they open Users or another super admin's email
- **THEN** the request is refused with 403
+11 -5
View File
@@ -8,25 +8,31 @@ Admins with the Interests module maintain the list of products and services that
### Requirement: Interest list
The system SHALL let an admin with `BO_INTERESTS` list, add, rename, reorder, deactivate and reactivate interests for their company. An interest name SHALL be required, at most 100 characters, and unique within the company ignoring case. Interests SHALL NOT be deletable.
The system SHALL keep one interest list shared by all companies. Admins with `BO_INTERESTS` SHALL see the list, and only a super admin SHALL add, rename, reorder, deactivate and reactivate interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case. Interests SHALL NOT be deletable.
#### Scenario: Add interest
- **WHEN** an admin with `BO_INTERESTS` adds `Kitchen appliances`
- **WHEN** a super admin adds `Kitchen appliances`
- **THEN** it is listed as active
- **AND** staff of every company can tag leads with it
#### Scenario: Duplicate name
- **GIVEN** an interest `Kitchen appliances`
- **WHEN** an admin adds `kitchen APPLIANCES`
- **WHEN** a super admin adds `kitchen APPLIANCES`
- **THEN** the save is refused and the name is reported as a duplicate
#### Scenario: Deactivate
- **GIVEN** an active interest `Cookware`
- **WHEN** an admin deactivates it
- **WHEN** a super admin deactivates it
- **THEN** it is still listed, marked inactive
- **AND** it is no longer offered when capturing a lead
- **AND** it is no longer offered when capturing a lead in any company
#### Scenario: Company user edits
- **WHEN** an INS user with `BO_INTERESTS` adds, renames or deactivates an interest
- **THEN** the request is refused with 403 and the list is unchanged
#### Scenario: No module
@@ -0,0 +1,47 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import * as route from "./route";
const { GET } = route;
const req = (url: string) => new Request(url) as unknown as Parameters<typeof GET>[0];
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("/api/audit-log/[[...path]]", () => {
it("is GET only", () => {
expect(Object.keys(route).filter((k) => /^(GET|POST|PUT|PATCH|DELETE)$/.test(k))).toEqual(["GET"]);
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET(req("http://localhost/api/audit-log"), ctx())).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("refuses dot segments", async () => {
expect((await GET(req("http://localhost/api/audit-log/.."), ctx([".."]))).status).toBe(400);
expect((await GET(req("http://localhost/api/audit-log/."), ctx(["."]))).status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the query to the list", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
const res = await GET(req("http://localhost/api/audit-log?actor=a&page=0&size=20"), ctx());
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log?actor=a&page=0&size=20", { token: "jwt" });
});
it("forwards one event by encoded id", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: "a/b" } });
await GET(req("http://localhost/api/audit-log/a%2Fb"), ctx(["a/b"]));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log/a%2Fb", { token: "jwt" });
});
});
@@ -0,0 +1,18 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// Read-only proxy for /api/admin/audit-log[/<id>]; mobile-api owns the BO_AUDIT_LOG guard. Audit events are never writable from the portal, so GET is the only method.
type Ctx = { params: Promise<{ path?: string[] }> };
export async function GET(req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { path = [] } = await params;
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
const target = `/api/admin/audit-log${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
const result = await callMobileApi<unknown>(target, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,29 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/auth/change-password: client context", () => {
it("forwards the browser IP and user agent for the login history", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
const req = new Request("http://localhost/api/auth/change-password", {
method: "POST",
headers: { "x-forwarded-for": "198.51.100.7", "user-agent": "Browser/1.0" },
body: JSON.stringify({ currentPassword: "a", newPassword: "b", confirmPassword: "b" }),
}) as unknown as Parameters<typeof POST>[0];
await POST(req);
expect(mocks.callMobileApi.mock.calls[0][1].headers).toEqual({
"X-Client-Ip": "198.51.100.7",
"X-Client-User-Agent": "Browser/1.0",
});
});
});
@@ -0,0 +1,49 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function req(body: unknown) {
return new Request("http://localhost/api/auth/change-password", {
method: "POST",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/auth/change-password", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(req({}));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards only the three password fields and answers 204", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
const res = await POST(req({ currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1", extra: 1 }));
expect(res.status).toBe(204);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/auth/change-password", {
method: "POST",
body: { currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1" },
token: "jwt-abc",
headers: {},
});
});
it("passes a refusal through with its code", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "Current password is wrong", code: "CURRENT_PASSWORD_WRONG" });
const res = await POST(req({}));
expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ error: "Current password is wrong", code: "CURRENT_PASSWORD_WRONG" });
});
});
@@ -0,0 +1,25 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { clientContextHeaders } from "@/app/lib/server/clientContext";
/** The signed-in admin changes their own password; only the three fields are forwarded, and nothing is logged. */
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const { currentPassword, newPassword, confirmPassword } = (await req.json().catch(() => ({}))) as {
currentPassword?: string;
newPassword?: string;
confirmPassword?: string;
};
const result = await callMobileApi<null>("/api/admin/auth/change-password", {
method: "POST",
body: { currentPassword, newPassword, confirmPassword },
token,
// The browser IP and user agent go into the login history rows this call writes.
headers: clientContextHeaders(req),
});
if (!result.ok) return errorResponse(result);
return new NextResponse(null, { status: 204 });
}
@@ -0,0 +1,15 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
import { POST } from "./route";
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }));
describe("POST /api/auth/forgot-password company", () => {
it("forwards a trimmed company", async () => {
await POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify({ company: " ins ", username: "john", email: "j@x.com" }) }) as never);
expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", email: "j@x.com" });
});
});
@@ -5,11 +5,15 @@ import { callMobileApi } from "@/app/lib/server/mobileApi";
// the answer must not reveal whether the account exists, so upstream errors are never forwarded.
// Same-origin and body-size checks are enforced for every /api write by middleware.
export async function POST(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as { username?: unknown; email?: unknown };
const body = (await req.json().catch(() => ({}))) as { company?: unknown; username?: unknown; email?: unknown };
const username = typeof body.username === "string" ? body.username.trim() : "";
const email = typeof body.email === "string" ? body.email.trim() : "";
const company = typeof body.company === "string" ? body.company.trim() : "";
if (username && email) {
await callMobileApi("/api/admin/auth/forgot-password", { method: "POST", body: { username, email } });
await callMobileApi("/api/admin/auth/forgot-password", {
method: "POST",
body: { ...(company && { company }), username, email },
});
}
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,24 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), setSession: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ setSession: mocks.setSession }));
import { POST } from "./route";
const req = (body: unknown) =>
new Request("http://localhost/api/auth/login", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters<typeof POST>[0];
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({
ok: true,
data: { token: "t", name: "N", roles: [], aclMenu: {}, resetPasswordRequired: "false" },
});
});
describe("POST /api/auth/login company", () => {
it("forwards a trimmed company", async () => {
await POST(req({ company: " ins ", username: "john", password: "pw" }));
expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", password: "pw" });
});
});
@@ -0,0 +1,34 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), setSession: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ setSession: mocks.setSession }));
import { POST } from "./route";
function req() {
return new Request("http://localhost/api/auth/login", {
method: "POST",
body: JSON.stringify({ username: "sales1", password: "x" }),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
});
describe("POST /api/auth/login: locked account", () => {
it("keeps the ACCOUNT_LOCKED code on the 401", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 401, error: "Too many failed sign-ins.", code: "ACCOUNT_LOCKED" });
const res = await POST(req());
expect(res.status).toBe(401);
expect(await res.json()).toMatchObject({ error: "Too many failed sign-ins.", code: "ACCOUNT_LOCKED" });
});
it("leaves other 401s without a code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 401, error: "Invalid username or password" });
const res = await POST(req());
expect(res.status).toBe(401);
expect((await res.json()).code).toBeUndefined();
});
});
@@ -14,7 +14,7 @@ import type { AdminLoginResponse } from "@/app/lib/types";
// echoed back here, keeping this handler's response minimal.
export async function POST(req: NextRequest) {
const body = await req.json().catch(() => ({}));
const { username, password } = body as { username?: string; password?: string };
const { company, username, password } = body as { company?: string; username?: string; password?: string };
const identifier = (username ?? "").trim();
if (!identifier || !password) {
@@ -23,7 +23,8 @@ export async function POST(req: NextRequest) {
const result = await callMobileApi<AdminLoginResponse>("/api/admin/auth/login", {
method: "POST",
body: { username: identifier, password },
// A blank company is a super-admin login: omit the key rather than send "".
body: { ...(company?.trim() && { company: company.trim() }), username: identifier, password },
// Real-client context for the login_audit trail (X-Client-Ip / X-Client-User-Agent).
headers: clientContextHeaders(req),
});
@@ -31,9 +32,9 @@ export async function POST(req: NextRequest) {
if (!result.ok) {
// The mobile-api answers bad credentials with HTTP 401 directly (not the
// expired-token signal), so surface it as 401 rather than the generic 400.
// A confirmed-locked account comes back as 423 with its own message, which
// errorResponse forwards as-is (4xx passthrough).
if (result.status === 401) return unauthorized(result.error);
// A locked account is also a 401, but carries code ACCOUNT_LOCKED, which the
// login page needs to show its own message; errorResponse keeps the code.
if (result.status === 401 && result.code !== "ACCOUNT_LOCKED") return unauthorized(result.error);
return errorResponse(result);
}
@@ -0,0 +1,21 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: vi.fn().mockResolvedValue("jwt") }));
vi.mock("@/app/lib/server/sessionRefresh", () => ({ maybeRefreshSession: vi.fn() }));
import { GET } from "./route";
beforeEach(() => mocks.callMobileApi.mockReset());
describe("GET /api/auth/session company", () => {
it("passes companyId, companyCode and isSuper through", async () => {
mocks.callMobileApi.mockResolvedValue({
ok: true,
data: { id: 1, username: "john@ins", name: "J", roles: [], aclMenu: {}, companyId: 7, companyCode: "ins", isSuper: false },
});
const res = await GET(new Request("http://localhost/api/auth/session") as never);
expect(await res.json()).toMatchObject({ companyId: 7, companyCode: "ins", isSuper: false });
});
});
@@ -25,6 +25,9 @@ export async function GET(req: NextRequest) {
const result = await callMobileApi<AdminMeResponse>("/api/admin/me", { token });
if (!result.ok) return errorResponse(result);
const { id, username, name, roles, aclMenu, branch } = result.data;
return NextResponse.json({ id, username, name, roles, aclMenu, branch: branch ?? null });
const { id, username, name, roles, aclMenu, branch, companyId, companyCode, isSuper } = result.data;
return NextResponse.json({
id, username, name, roles, aclMenu, branch: branch ?? null,
companyId, companyCode, isSuper,
});
}
@@ -0,0 +1,32 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
const call = (body: unknown) =>
POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify(body) }) as never, { params: Promise.resolve({ id: "7" }) });
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("POST /api/companies/[id]/code", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await call({ code: "new" })).status).toBe(401);
});
it("forwards the code to /api/admin/companies/{id}/code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 7, code: "new" } });
await call({ code: "new" });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies/7/code", {
method: "POST",
body: { code: "new" },
token: "jwt",
});
});
});
@@ -0,0 +1,19 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminCompany } from "@/app/lib/types";
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { id } = await params;
const { code } = (await req.json().catch(() => ({}))) as { code?: string };
const result = await callMobileApi<AdminCompany>(`/api/admin/companies/${encodeURIComponent(id)}/code`, {
method: "POST",
body: { code },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,46 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, POST } from "./route";
const post = (body: unknown) =>
new Request("http://localhost/api/companies", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters<typeof POST>[0];
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("/api/companies", () => {
it("GET returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET()).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("GET forwards to /api/admin/companies", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] });
await GET();
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", { token: "jwt" });
});
it("POST forwards id, name, code and status", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1 } });
await POST(post({ id: 1, name: "Ins", code: "ins", status: "A", extra: "x" }));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", {
method: "POST",
body: { id: 1, name: "Ins", code: "ins", status: "A" },
token: "jwt",
});
});
it("POST relays a 409 from the API", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "Code already used" });
const res = await POST(post({ name: "Ins", code: "ins", status: "A" }));
expect(res.status).toBe(409);
expect((await res.json()).error).toBe("Code already used");
});
});
@@ -0,0 +1,27 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminCompany } from "@/app/lib/types";
// Super admin only; the mobile-api answers 403 for anyone else, and validation (400) and duplicate codes (409) too.
export async function GET() {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<AdminCompany[]>("/api/admin/companies", { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const { id, name, code, status } = (await req.json().catch(() => ({}))) as Partial<AdminCompany>;
const result = await callMobileApi<AdminCompany>("/api/admin/companies", {
method: "POST",
body: { id, name, code, status },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,38 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
type Req = Parameters<typeof GET>[0];
const req = (url: string) => new Request(`http://localhost${url}`) as unknown as Req;
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { captures: 1 } });
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("/api/dashboard/leads", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(req("/api/dashboard/leads"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the query string to mobile-api", async () => {
const res = await GET(req("/api/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ captures: 1 });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/leads?from=2026-11-01&to=2026-11-30&companyId=2", { token: "jwt-abc" });
});
it("passes an upstream INVALID_PERIOD with its code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Start date must be on or before end date.", status: 400, code: "INVALID_PERIOD" });
const res = await GET(req("/api/dashboard/leads?from=2026-11-30&to=2026-11-01"));
expect(res.status).toBe(400);
expect(((await res.json()) as Record<string, unknown>).code).toBe("INVALID_PERIOD");
});
});
@@ -0,0 +1,13 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// Proxy for /api/admin/dashboard/leads; mobile-api owns period validation and the BO_DASHBOARD guard.
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<unknown>(`/api/admin/dashboard/leads${new URL(req.url).search}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -16,6 +16,8 @@ export async function GET(req: NextRequest) {
if (enabled !== "Y" && enabled !== "N") return badRequest("enabled must be Y or N.");
qs.set("enabled", enabled);
}
const companyId = params.get("companyId");
if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId);
qs.set("page", params.get("page") ?? "0");
qs.set("size", params.get("size") ?? "20");
const sortBy = params.get("sortBy");
@@ -7,7 +7,10 @@ export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<Record<string, unknown>>("/api/admin/events/salesperson-options", { token });
const companyId = new URL(req.url).searchParams.get("companyId");
const qs = new URLSearchParams();
if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId);
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/salesperson-options${qs.size ? `?${qs}` : ""}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,20 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("/api/login-security unlock", () => {
it("POST forwards the companyId query to the upstream URL", async () => {
const req = new Request("http://localhost/api/login-security/locked/a/unlock?companyId=2", { method: "POST", body: "{}", headers: { "Content-Type": "application/json" } });
await POST(req as unknown as Parameters<typeof POST>[0], { params: Promise.resolve({ path: ["locked", "a", "unlock"] }) });
expect(mocks.callMobileApi.mock.calls[0][0]).toBe("/api/admin/login-security/locked/a/unlock?companyId=2");
});
});
@@ -0,0 +1,74 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, POST, PUT } from "./route";
const req = (url: string, body?: unknown) =>
new Request(url, body === undefined ? undefined : { method: "PUT", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } }) as unknown as Parameters<typeof GET>[0];
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("/api/login-security/[[...path]]", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET(req("http://localhost/api/login-security/locked"), ctx(["locked"]))).status).toBe(401);
expect((await PUT(req("http://localhost/api/login-security/config", {}), ctx(["config"]))).status).toBe(401);
expect((await POST(req("http://localhost/api/login-security/locked/a/unlock", {}), ctx(["locked", "a", "unlock"]))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("refuses dot segments", async () => {
expect((await GET(req("http://localhost/api/login-security/.."), ctx([".."]))).status).toBe(400);
expect((await POST(req("http://localhost/api/login-security/locked/./unlock"), ctx(["locked", ".", "unlock"]))).status).toBe(400);
expect((await PUT(req("http://localhost/api/login-security/.."), ctx([".."]))).status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("GET forwards the path and query", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
const res = await GET(req("http://localhost/api/login-security/audit?username=a&page=0&size=20"), ctx(["audit"]));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/audit?username=a&page=0&size=20", { token: "jwt" });
});
it("encodes each segment", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
await POST(req("http://localhost/api/login-security/locked/a%2Fb/unlock"), ctx(["locked", "a/b", "unlock"]));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/locked/a%2Fb/unlock", { token: "jwt", method: "POST", body: undefined });
});
it("PUT forwards the JSON body", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { enabled: true } });
const body = { enabled: true, maxAttempts: 5, period: 15, unit: "M" };
const res = await PUT(req("http://localhost/api/login-security/config", body), ctx(["config"]));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/config", { token: "jwt", method: "PUT", body });
expect(await res.json()).toEqual({ enabled: true });
});
it("POST forwards the JSON body", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { x: 1 } });
const r = new Request("http://localhost/api/login-security/x", { method: "POST", body: JSON.stringify({ a: 1 }) }) as unknown as Parameters<typeof GET>[0];
await POST(r, ctx(["x"]));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/x", { token: "jwt", method: "POST", body: { a: 1 } });
});
it("passes an empty upstream body through as 204", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
const res = await POST(req("http://localhost/api/login-security/locked/a/unlock"), ctx(["locked", "a", "unlock"]));
expect(res.status).toBe(204);
});
it("passes a refusal through with its code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "Max attempts must be at least 1", code: "INVALID_SETTING" });
const res = await PUT(req("http://localhost/api/login-security/config", { maxAttempts: 0 }), ctx(["config"]));
expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ code: "INVALID_SETTING", error: "Max attempts must be at least 1" });
});
});
@@ -0,0 +1,30 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// Proxy for /api/admin/login-security/**; mobile-api owns the BO_LOGIN_SECURITY guard. Bodies are forwarded, never logged.
type Ctx = { params: Promise<{ path?: string[] }> };
async function forward(method: "GET" | "POST" | "PUT", req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { path = [] } = await params;
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
const target = `/api/admin/login-security${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
let body: unknown;
if (method !== "GET") {
const text = await req.text();
if (text) {
try { body = JSON.parse(text); } catch { return badRequest("Invalid request body."); }
}
}
const result = await callMobileApi<unknown>(target, method === "GET" ? { token } : { token, method, body });
if (!result.ok) return errorResponse(result);
if (result.data === null || result.data === undefined) return new NextResponse(null, { status: 204 });
return NextResponse.json(result.data);
}
export const GET = (req: NextRequest, ctx: Ctx) => forward("GET", req, ctx);
export const POST = (req: NextRequest, ctx: Ctx) => forward("POST", req, ctx);
export const PUT = (req: NextRequest, ctx: Ctx) => forward("PUT", req, ctx);
@@ -19,6 +19,8 @@ export async function GET(req: NextRequest) {
if (enabled !== "true" && enabled !== "false") return badRequest("enabled must be true or false.");
qs.set("enabled", enabled);
}
const companyId = params.get("companyId");
if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId);
qs.set("page", params.get("page") ?? "0");
qs.set("size", params.get("size") ?? "20");
const sortBy = params.get("sortBy");
@@ -0,0 +1,84 @@
import { render, screen, within } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({ getAuditEvent: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/services/auditLog", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/auditLog")>()),
getAuditEvent: mocks.getAuditEvent,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", () => ({ useParams: () => ({ id: "e2" }) }));
import AuditEventPage from "./page";
const EVENT = {
id: 2, companyId: 1, occurredAt: "2026-11-30T15:52:00.5", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE",
httpMethod: "PUT", pathTemplate: "/api/admin/users/{id}", targetId: "42", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null as string | null,
};
beforeEach(() => {
mocks.getAuditEvent.mockReset();
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
});
describe("AuditEventPage", () => {
it("gates on BO_AUDIT_LOG", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<AuditEventPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(mocks.getAuditEvent).not.toHaveBeenCalled();
});
it("shows a before/after table for put-style changes", async () => {
const changes = JSON.stringify({
roles: { before: ["A"], after: ["A", "B"] },
enabled: { before: false, after: true },
lockout: { before: { status: "Y", value: 5 }, after: null },
});
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes });
render(<AuditEventPage />);
const table = await screen.findByRole("table");
expect(within(table).getAllByRole("columnheader").map((h) => h.textContent)).toEqual(["Field", "Before", "After"]);
const rows = within(table).getAllByRole("row").slice(1);
expect(rows[0]).toHaveTextContent("rolesAA, B");
expect(rows[1]).toHaveTextContent("enabledfalsetrue");
expect(rows[2]).toHaveTextContent("lockoutstatus: Y, value: 5—");
expect(screen.getByText("sales1")).toBeInTheDocument();
expect(screen.getByText("/api/admin/users/{id}", { exact: false })).toBeInTheDocument();
});
it("renders module grants with a dash before and joined codes after", async () => {
const changes = JSON.stringify({
modulesAdded: { before: null, after: ["BO_USERS", "BO_LEADS"] },
modulesRemoved: { before: null, after: ["BO_EVENTS"] },
});
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes });
render(<AuditEventPage />);
const rows = within(await screen.findByRole("table")).getAllByRole("row").slice(1);
expect(rows[0]).toHaveTextContent("modulesAdded—BO_USERS, BO_LEADS");
expect(rows[1]).toHaveTextContent("modulesRemoved—BO_EVENTS");
});
it("lists field names only for {fields: [...]}", async () => {
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes: JSON.stringify({ fields: ["phone", "notes"] }) });
render(<AuditEventPage />);
expect(await screen.findByText("phone")).toBeInTheDocument();
expect(screen.getByText("notes")).toBeInTheDocument();
expect(screen.getByText("Values are not recorded for these fields.")).toBeInTheDocument();
expect(screen.queryByRole("table")).not.toBeInTheDocument();
});
it("shows unparsable changes as plain text", async () => {
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes: "not json {" });
render(<AuditEventPage />);
expect(await screen.findByText("not json {")).toBeInTheDocument();
});
it("shows a message when the event is not found", async () => {
mocks.getAuditEvent.mockRejectedValue(new ApiError("NOT_FOUND", 404));
render(<AuditEventPage />);
expect(await screen.findByText("Audit event not found")).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Back to audit log" })).toHaveAttribute("href", "/audit-log");
});
});
@@ -0,0 +1,150 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { Badge } from "@/app/components/ui/badge";
import { PageHeader } from "@/app/components/ui/page-header";
import { Skeleton } from "@/app/components/ui/skeleton";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import { RequireModule } from "@/app/lib/RequireModule";
import { ApiError } from "@/app/lib/clientApi";
import { formatEmailDate } from "@/app/lib/services/adminEmails";
import { getAuditEvent, type AuditEvent } from "@/app/lib/services/auditLog";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type Parsed = { kind: "fields"; fields: string[] } | { kind: "diff"; rows: [string, unknown, unknown][] } | { kind: "text"; text: string };
function parseChanges(raw: string): Parsed {
try {
const obj: unknown = JSON.parse(raw);
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
const rec = obj as Record<string, unknown>;
if (Array.isArray(rec.fields)) return { kind: "fields", fields: rec.fields.map(String) };
const rows = Object.entries(rec).map(([k, v]): [string, unknown, unknown] => {
const c = (v ?? {}) as { before?: unknown; after?: unknown };
return [k, c.before, c.after];
});
return { kind: "diff", rows };
}
} catch { /* shown as plain text below */ }
return { kind: "text", text: raw };
}
const show = (v: unknown): string => {
if (v === null || v === undefined) return "—";
if (Array.isArray(v)) return v.map(show).join(", ");
if (typeof v === "object") return Object.entries(v).map(([k, x]) => `${k}: ${show(x)}`).join(", ");
return String(v);
};
function Changes({ raw }: { raw: string | null }) {
const t = useT();
const parsed = useMemo(() => (raw ? parseChanges(raw) : null), [raw]);
if (!parsed) return <p className="text-sm text-muted-foreground">{t("AuditNoChanges")}</p>;
if (parsed.kind === "text") return <pre className="overflow-x-auto whitespace-pre-wrap break-all text-sm">{parsed.text}</pre>;
if (parsed.kind === "fields") {
return (
<div className="space-y-2 text-sm">
<ul className="list-disc pl-5">{parsed.fields.map((f) => <li key={f}>{f}</li>)}</ul>
<p className="text-muted-foreground">{t("AuditFieldsOnly")}</p>
</div>
);
}
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("AuditField")}</TableHead>
<TableHead>{t("AuditBefore")}</TableHead>
<TableHead>{t("AuditAfter")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{parsed.rows.map(([field, before, after]) => (
<TableRow key={field}>
<TableCell className="font-medium">{field}</TableCell>
<TableCell className="break-words whitespace-normal">{show(before)}</TableCell>
<TableCell className="break-words whitespace-normal">{show(after)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}
function AuditEventContent() {
const t = useT();
const { id } = useParams<{ id: string }>();
const [event, setEvent] = useState<AuditEvent | null>(null);
const [error, setError] = useState<"notFound" | "failed" | null>(null);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- clears the previous event/error before the id-triggered fetch below.
setEvent(null);
setError(null);
getAuditEvent(id)
.then((e) => { if (!cancelled) setEvent(e); })
.catch((err: unknown) => { if (!cancelled) setError(err instanceof ApiError && err.status === 404 ? "notFound" : "failed"); });
return () => { cancelled = true; };
}, [id]);
const back = <Link href="/audit-log" className="mt-4 inline-block text-primary underline-offset-4 hover:underline">{t("AuditBack")}</Link>;
if (error) {
return (
<>
<PageHeader title={t("BO_AUDIT_LOG")} />
{error === "notFound" ? <EmptyState title={t("AuditNotFound")} /> : <ErrorState message={t("AuditLoadFailed")} className="mb-4" />}
{back}
</>
);
}
if (!event) {
return (
<>
<PageHeader title={t("BO_AUDIT_LOG")} />
<Skeleton className="h-64 w-full" />
</>
);
}
return (
<div className="space-y-4">
<PageHeader title={event.action} />
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-sm">
<dt className="text-muted-foreground">{t("LsTime")}</dt>
<dd>{formatEmailDate(event.occurredAt)}</dd>
<dt className="text-muted-foreground">{t("AuditWho")}</dt>
<dd className="break-all">{event.actor}</dd>
<dt className="text-muted-foreground">{t("AuditModule")}</dt>
<dd>{event.module ? t(event.module) : "—"}</dd>
<dt className="text-muted-foreground">{t("AuditAction")}</dt>
<dd>{event.action}</dd>
<dt className="text-muted-foreground">{t("AuditRequest")}</dt>
<dd className="break-all">{event.httpMethod} {event.pathTemplate}</dd>
<dt className="text-muted-foreground">{t("AuditTarget")}</dt>
<dd className="break-all">{event.targetId ?? "—"}</dd>
<dt className="text-muted-foreground">{t("AuditOutcome")}</dt>
<dd><Badge variant={event.outcome === "SUCCESS" ? "positive" : "negative"}>{event.outcome} {event.httpStatus}</Badge></dd>
<dt className="text-muted-foreground">{t("LsIp")}</dt>
<dd>{event.clientIp ?? "—"}</dd>
</dl>
<section className="space-y-2">
<h2 className="text-base font-semibold">{t("AuditChanges")}</h2>
<Changes raw={event.changes} />
</section>
{back}
</div>
);
}
export default function AuditEventPage() {
return (
<RequireModule pathname="/audit-log">
<AuditEventContent />
</RequireModule>
);
}
@@ -0,0 +1,84 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ searchAuditLog: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/services/auditLog", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/auditLog")>()),
searchAuditLog: mocks.searchAuditLog,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import AuditLogPage from "./page";
const EVENTS = [
{ id: 2, companyId: 1, occurredAt: "2026-11-30T15:52:00.5", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/api/admin/users/{id}", targetId: "42", outcome: "FAILURE", httpStatus: 403, clientIp: "10.0.0.5", changes: null },
{ id: 1, companyId: 1, occurredAt: "2026-11-29T09:05:00", actor: "admin", module: null, action: "LEAD_EXPORT", httpMethod: "GET", pathTemplate: "/api/admin/leads/export", targetId: null, outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.6", changes: null },
];
beforeEach(() => {
memoryRouter.reset("/audit-log");
mocks.searchAuditLog.mockReset().mockResolvedValue({ items: EVENTS, total: 2 });
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
});
describe("AuditLogPage", () => {
it("renders NotAuthorized without BO_AUDIT_LOG", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<AuditLogPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(mocks.searchAuditLog).not.toHaveBeenCalled();
});
it("lists rows with module label, outcome badge with status, and a link to the detail", async () => {
render(<AuditLogPage />);
const table = await screen.findByRole("table");
const rows = within(table).getAllByRole("row").slice(1);
expect(rows[0]).toHaveTextContent("30/11/2026 15:52");
expect(rows[0]).toHaveTextContent("sales1");
expect(rows[0]).toHaveTextContent("Users");
expect(rows[0]).toHaveTextContent("USER_UPDATE");
expect(rows[0]).toHaveTextContent("FAILURE 403");
expect(rows[0]).toHaveTextContent("10.0.0.5");
expect(within(rows[0]).getByRole("link", { name: "USER_UPDATE" })).toHaveAttribute("href", "/audit-log/2");
expect(rows[1]).toHaveTextContent("SUCCESS 200");
});
it("labels lead modules and offers them in the module filter, without BO_AUDIT_LOG", async () => {
mocks.searchAuditLog.mockResolvedValue({ items: [{ ...EVENTS[1], module: "BO_LEADS_EXPORT" }], total: 1 });
render(<AuditLogPage />);
const table = await screen.findByRole("table");
expect(within(table).getAllByRole("row")[1]).toHaveTextContent("Lead export");
await userEvent.click(screen.getByRole("combobox", { name: "Module" }));
expect(await screen.findByRole("option", { name: "Lead editing" })).toBeInTheDocument();
expect(screen.getByRole("option", { name: "Lead export" })).toBeInTheDocument();
expect(screen.queryByRole("option", { name: "Audit log" })).not.toBeInTheDocument();
});
it("shows a dash for a null module", async () => {
render(<AuditLogPage />);
const table = await screen.findByRole("table");
expect(within(table).getAllByRole("row")[2]).toHaveTextContent("admin—LEAD_EXPORT");
});
it("puts the filters in the query", async () => {
memoryRouter.reset("/audit-log", "outcome=FAILURE&from=2026-11-01&module=BO_USERS");
render(<AuditLogPage />);
await screen.findByRole("table");
expect(mocks.searchAuditLog).toHaveBeenCalledWith(expect.objectContaining({ outcome: "FAILURE", from: "2026-11-01", module: "BO_USERS", page: 1, pageSize: 20 }));
await userEvent.type(screen.getByRole("searchbox", { name: "Who" }), "sales");
await waitFor(() => expect(mocks.searchAuditLog).toHaveBeenLastCalledWith(expect.objectContaining({ actor: "sales", outcome: "FAILURE" })));
});
it("shows an empty state and an error state", async () => {
mocks.searchAuditLog.mockResolvedValue({ items: [], total: 0 });
const { unmount } = render(<AuditLogPage />);
expect(await screen.findByText("No audit events found")).toBeInTheDocument();
unmount();
mocks.searchAuditLog.mockRejectedValue(new Error("x"));
render(<AuditLogPage />);
expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the audit log");
});
});
+131
View File
@@ -0,0 +1,131 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import type { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/app/components/ui/badge";
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
import { DataTable } from "@/app/components/ui/data-table";
import { DatePicker } from "@/app/components/ui/date-picker";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { useListFilters } from "@/app/lib/hooks/useListFilters";
import { useResetPageOnCompany } from "@/app/lib/hooks/useResetPageOnCompany";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { ROUTE_MODULES } from "@/app/lib/routeModules";
import { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails";
import { searchAuditLog, type AuditEvent } from "@/app/lib/services/auditLog";
import { useCompanyScope } from "@/app/lib/CompanyScope";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const DEFAULTS = { actor: "", module: "", action: "", outcome: "", from: "", to: "" };
// The backend stores the handler's @AdminModule code, so the filter lists those: the route modules plus the lead edit/export codes. Audit-log reads are never recorded.
const MODULES = [...Object.values(ROUTE_MODULES).filter((m) => m !== "BO_AUDIT_LOG"), "BO_LEADS_EDIT", "BO_LEADS_EXPORT"];
function AuditLogContent() {
const t = useT();
const { companyId, showCompanyColumn, codeOf } = useCompanyScope();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
useResetPageOnCompany(setPage);
const [data, setData] = useState<{ items: AuditEvent[]; total: number }>({ items: [], total: 0 });
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
if (pageSize == null) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
setLoading(true);
setFailed(false);
searchAuditLog({ ...filters, page, pageSize, companyId })
.then((result) => { if (!cancelled) setData(result); })
.catch(() => { if (!cancelled) setFailed(true); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [filters, page, reloadKey, pageSize, companyId]);
const moduleOptions = useMemo(() => MODULES.map((m) => ({ value: m, label: t(m) })), [t]);
const outcomeOptions = useMemo(() => [{ value: "SUCCESS", label: t("AuditSuccess") }, { value: "FAILURE", label: t("AuditFailure") }], [t]);
const cut = (text: string | null | undefined, max = "max-w-40") => <span className={`block truncate ${max}`} title={text ?? undefined}>{text}</span>;
const columns = useMemo<ColumnDef<AuditEvent, unknown>[]>(
() => [
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<AuditEvent, unknown>] : []),
{ id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => <span className="whitespace-nowrap">{formatDate(row.original.occurredAt)}</span> },
{ id: "actor", header: t("AuditWho"), enableSorting: false, cell: ({ row }) => cut(row.original.actor, "max-w-32") },
{ id: "module", header: t("AuditModule"), enableSorting: false, cell: ({ row }) => (row.original.module ? t(row.original.module) : "—") },
{
id: "action",
header: t("AuditAction"),
enableSorting: false,
cell: ({ row }) => (
<Link href={`/audit-log/${row.original.id}`} title={row.original.action} className="block max-w-48 truncate font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
{row.original.action}
</Link>
),
},
{ id: "target", header: t("AuditTarget"), enableSorting: false, cell: ({ row }) => cut(row.original.targetId, "max-w-28") },
{
id: "outcome",
header: t("AuditOutcome"),
enableSorting: false,
cell: ({ row }) => (
<Badge variant={row.original.outcome === "SUCCESS" ? "positive" : "negative"}>{row.original.outcome} {row.original.httpStatus}</Badge>
),
},
{ accessorKey: "clientIp", header: t("LsIp"), enableSorting: false },
],
[t, showCompanyColumn, codeOf],
);
return (
<>
<PageHeader title={t("BO_AUDIT_LOG")} />
{failed && <ErrorState message={t("AuditLoadFailed")} onRetry={refetch} className="mb-4" />}
<FilterPanel activeCount={activeCount} onClear={clear}>
<FilterField label={t("AuditWho")}>
<FilterSearch className="w-full" aria-label={t("AuditWho")} value={filters.actor} onChange={(actor) => set({ actor })} />
</FilterField>
<FilterField label={t("AuditModule")}>
<FilterSelect className="w-full" aria-label={t("AuditModule")} allLabel={t("AuditAllModules")} options={moduleOptions} value={filters.module} onChange={(module) => set({ module })} />
</FilterField>
<FilterField label={t("AuditAction")}>
<FilterSearch className="w-full" aria-label={t("AuditAction")} value={filters.action} onChange={(action) => set({ action })} />
</FilterField>
<FilterField label={t("AuditOutcome")}>
<FilterSelect className="w-full" aria-label={t("AuditOutcome")} allLabel={t("AuditAllOutcomes")} options={outcomeOptions} value={filters.outcome} onChange={(outcome) => set({ outcome })} />
</FilterField>
<FilterField label={t("LsFrom")}>
<DatePicker aria-label={t("LsFrom")} value={filters.from} onChange={(from) => set({ from })} max={filters.to || undefined} />
</FilterField>
<FilterField label={t("LsTo")}>
<DatePicker aria-label={t("LsTo")} value={filters.to} onChange={(to) => set({ to })} min={filters.from || undefined} />
</FilterField>
</FilterPanel>
<DataTable
label={t("BO_AUDIT_LOG")}
columns={columns}
data={data.items}
total={data.total}
page={page}
pageSize={pageSize ?? MIN_PAGE_SIZE}
tableRef={tableRef}
onPageChange={setPage}
isLoading={loading}
rowKey={(r) => String(r.id)}
empty={<EmptyState title={activeCount > 0 ? t("AuditNoMatch") : t("AuditNoEvents")} />}
/>
</>
);
}
export default function AuditLogPage() {
return (
<RequireModule pathname="/audit-log">
<AuditLogContent />
</RequireModule>
);
}
@@ -0,0 +1,38 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
apiGet: mocks.apiGet,
apiPost: mocks.apiPost,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import CompaniesPage from "./page";
beforeEach(() => {
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
mocks.apiPost.mockReset();
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
});
describe("CompaniesPage fixes", () => {
it("does not post a code change when the new code equals the current code", async () => {
render(<CompaniesPage />);
await userEvent.click(await screen.findByRole("button", { name: "Change code" }));
const input = screen.getByLabelText("New code");
await userEvent.clear(input);
await userEvent.type(input, " INS ");
await userEvent.click(screen.getByRole("button", { name: "Confirm" }));
expect(mocks.apiPost).not.toHaveBeenCalled();
expect(screen.getByRole("alert")).toBeInTheDocument();
});
it("shows the API error text of a failed load directly", async () => {
mocks.apiGet.mockRejectedValue(new Error("Forbidden for you"));
render(<CompaniesPage />);
expect(await screen.findByText("Forbidden for you")).toBeInTheDocument();
});
});
@@ -0,0 +1,96 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
apiGet: mocks.apiGet,
apiPost: mocks.apiPost,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
import CompaniesPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
const ROWS = [
{ id: 1, name: "Insight", code: "ins", status: "A" },
{ id: 2, name: "Clever", code: "cv", status: "I" },
];
beforeEach(() => {
mocks.apiGet.mockReset().mockResolvedValue(ROWS);
mocks.apiPost.mockReset();
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
});
describe("CompaniesPage", () => {
it("lists name, code and status", async () => {
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
expect(within(row).getByText("ins")).toBeInTheDocument();
expect(within(row).getByText("Active")).toBeInTheDocument();
expect(within(screen.getByText("Clever").closest("tr")!).getByText("Inactive")).toBeInTheDocument();
expect(mocks.apiGet).toHaveBeenCalledWith("/api/companies");
});
it("creates a company with name, code and status", async () => {
mocks.apiPost.mockResolvedValue({ id: 3 });
render(<CompaniesPage />);
await userEvent.click(await screen.findByRole("button", { name: /add company/i }));
await userEvent.type(screen.getByLabelText("Name"), " Acme ");
await userEvent.type(screen.getByLabelText("Code"), "acme");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() =>
expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { name: "Acme", code: "acme", status: "A" }),
);
});
it("edits name and status only, with no code field", async () => {
mocks.apiPost.mockResolvedValue({ id: 1 });
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: "Edit" }));
expect(screen.queryByLabelText("Code")).toBeNull();
const name = screen.getByLabelText("Name");
await userEvent.clear(name);
await userEvent.type(name, "Insight Ltd");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
await waitFor(() =>
expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { id: 1, name: "Insight Ltd", status: "A" }),
);
});
it("shows an API 409 message on the form", async () => {
mocks.apiPost.mockRejectedValue(new ApiError("Code already used", 409));
render(<CompaniesPage />);
await userEvent.click(await screen.findByRole("button", { name: /add company/i }));
await userEvent.type(screen.getByLabelText("Name"), "Acme");
await userEvent.type(screen.getByLabelText("Code"), "ins");
await userEvent.click(screen.getByRole("button", { name: /save/i }));
expect(await screen.findByText("Code already used")).toBeInTheDocument();
});
it("warns before a code change, then posts the new code", async () => {
mocks.apiPost.mockResolvedValue({ id: 1, code: "new" });
render(<CompaniesPage />);
const row = (await screen.findByText("Insight")).closest("tr")!;
await userEvent.click(within(row).getByRole("button", { name: /change code/i }));
expect(
screen.getByText("Changing the code changes every staff login name of this company and signs them out."),
).toBeInTheDocument();
expect(mocks.apiPost).not.toHaveBeenCalled();
const code = screen.getByLabelText("New code");
await userEvent.clear(code);
await userEvent.type(code, "new");
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies/1/code", { code: "new" }));
});
it("is refused for non-super users", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false });
render(<CompaniesPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(mocks.apiGet).not.toHaveBeenCalled();
});
});
+213
View File
@@ -0,0 +1,213 @@
"use client";
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
import { Plus } from "lucide-react";
import type { ColumnDef } from "@tanstack/react-table";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { DataTable } from "@/app/components/ui/data-table";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { Badge } from "@/app/components/ui/badge";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { NotAuthorized } from "@/app/lib/RequireModule";
import { changeAdminCompanyCode, listAdminCompanies, saveAdminCompany } from "@/app/lib/services/adminCompanies";
import type { AdminCompany } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type Mode = "form" | "code";
type DialogState = { mode: Mode; company: AdminCompany };
const NEW_COMPANY: AdminCompany = { name: "", code: "", status: "A" };
// ponytail: the API message is shown as returned (not translated); add codes to the API if that matters.
function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClose: () => void; onSaved: () => void }) {
const t = useT();
const { mode, company } = state;
const [form, setForm] = useState<AdminCompany>(company);
const [newCode, setNewCode] = useState(company.code);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (mode === "form" && !form.name.trim()) return setError(t("CompNameRequired"));
if ((mode === "code" ? newCode : form.code).trim() === "" && (mode === "code" || !form.id)) {
return setError(t("CompCodeRequired"));
}
if (mode === "code" && newCode.trim().toLowerCase() === company.code.toLowerCase()) {
return setError(t("CompCodeUnchanged"));
}
setError(null);
setSaving(true);
try {
if (mode === "code") await changeAdminCompanyCode(company.id!, newCode.trim());
else if (form.id) await saveAdminCompany({ id: form.id, name: form.name.trim(), status: form.status });
else await saveAdminCompany({ name: form.name.trim(), code: form.code.trim(), status: form.status });
onSaved();
onClose();
} catch (err) {
setError(err instanceof Error && err.message ? err.message : t("CompSaveFailed"));
} finally {
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{mode === "code" ? t("CompChangeCode") : form.id ? t("CompEdit") : t("CompAdd")}</DialogTitle>
</DialogHeader>
{error && (
<div className="text-sm text-destructive" role="alert">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
{mode === "code" ? (
<>
<p className="text-sm">{t("CompChangeCodeWarning")}</p>
<div className="space-y-1.5">
<Label htmlFor="company-new-code">{t("CompNewCode")}</Label>
<Input id="company-new-code" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
</div>
</>
) : (
<>
<div className="space-y-1.5">
<Label htmlFor="company-name">{t("Name")}</Label>
<Input id="company-name" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} disabled={saving} />
</div>
{!form.id && (
<div className="space-y-1.5">
<Label htmlFor="company-code">{t("Code")}</Label>
<Input id="company-code" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="company-status">{t("Status")}</Label>
<select
id="company-status"
value={form.status}
onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as AdminCompany["status"] }))}
disabled={saving}
className="h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm"
>
<option value="A">{t("CompActive")}</option>
<option value="I">{t("CompInactive")}</option>
</select>
</div>
</>
)}
<DialogFooter>
<Button type="submit" disabled={saving}>
{mode === "code" ? t("CompConfirm") : t("Save")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
function CompaniesPageContent() {
const t = useT();
const [companies, setCompanies] = useState<AdminCompany[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [dialog, setDialog] = useState<DialogState | null>(null);
const [page, setPage] = useState(1);
const { tableRef, pageSize } = useFitPageSize();
const size = pageSize ?? MIN_PAGE_SIZE;
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the reloadKey-triggered fetch below.
setLoading(true);
setError(null);
listAdminCompanies()
.then((result) => !cancelled && setCompanies(result))
.catch((err: unknown) => !cancelled && setError(err instanceof Error && err.message ? err.message : t("CompLoadFailed")))
.finally(() => !cancelled && setLoading(false));
return () => {
cancelled = true;
};
}, [reloadKey, t]);
const columns = useMemo<ColumnDef<AdminCompany, unknown>[]>(
() => [
{ accessorKey: "name", header: t("Name") },
{ accessorKey: "code", header: t("Code") },
{
accessorKey: "status",
header: t("Status"),
cell: ({ row }) => (
<Badge variant={row.original.status === "A" ? "positive" : "neutral"}>
{row.original.status === "A" ? t("CompActive") : t("CompInactive")}
</Badge>
),
},
{
id: "actions",
header: t("CatActions"),
cell: ({ row }) => (
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "form", company: row.original })}>
{t("Edit")}
</Button>
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "code", company: row.original })}>
{t("CompChangeCode")}
</Button>
</div>
),
},
],
[t],
);
return (
<>
<PageHeader
title={t("BO_COMPANIES")}
actions={
<Button onClick={() => setDialog({ mode: "form", company: NEW_COMPANY })}>
<Plus aria-hidden="true" className="size-4" />
{t("CompAdd")}
</Button>
}
/>
{error && <ErrorState message={error} onRetry={refetch} className="mb-4" />}
<DataTable
label={t("BO_COMPANIES")}
columns={columns}
data={companies.slice((page - 1) * size, page * size)}
total={companies.length}
page={page}
pageSize={size}
onPageChange={setPage}
tableRef={tableRef}
isLoading={loading}
rowKey={(r) => String(r.id)}
empty={<EmptyState title={t("CompNone")} />}
/>
{dialog && <CompanyDialog state={dialog} onClose={() => setDialog(null)} onSaved={refetch} />}
</>
);
}
// Gated by isSuper (UX only; the API refuses everyone else), not by a module.
export default function CompaniesPage() {
const { isSuper, loading } = useAdminAuth();
if (loading) return null;
return isSuper ? <CompaniesPageContent /> : <NotAuthorized />;
}
@@ -0,0 +1,70 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
matchLead: vi.fn(),
listEventSalespeople: vi.fn(),
listEventLeadEvents: vi.fn(),
listEventLeadInterests: vi.fn(),
useAdminAuth: vi.fn(),
useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
matchLead: mocks.matchLead,
listEventSalespeople: mocks.listEventSalespeople,
listEventLeadEvents: mocks.listEventLeadEvents,
listEventLeadInterests: mocks.listEventLeadInterests,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => ({
...(await import("@/test/memoryRouter")).navigationMock,
useParams: () => ({ eventUuid: "evt-1" }),
}));
import { memoryRouter } from "@/test/memoryRouter";
import NewEventLeadPage from "./event-leads/[eventUuid]/new/page";
const COMPANIES = [
{ id: 1, name: "Ins Co", code: "INS", status: "A" },
{ id: 2, name: "CV Co", code: "CV", status: "A" },
];
const scope = (companyId?: number) => ({ companyId, companies: COMPANIES, showCompanyColumn: false, codeOf: () => "", setCompanyId: vi.fn() });
beforeEach(() => {
memoryRouter.reset("/event-leads/evt-1/new");
mocks.matchLead.mockReset().mockResolvedValue({ mobile: "+65911", email: "a@b.com", candidates: [] });
mocks.listEventSalespeople.mockReset().mockResolvedValue([]);
mocks.listEventLeadEvents.mockReset().mockResolvedValue([{ uuid: "evt-1", name: "Expo", companyId: 2 }]);
mocks.listEventLeadInterests.mockReset().mockResolvedValue([]);
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
mocks.useCompanyScope.mockReset().mockReturnValue(scope(2));
});
describe("event-lead capture company", () => {
it("shows no Company picker to a super admin and sends the event's own company with the lead match", async () => {
mocks.useCompanyScope.mockReturnValue(scope());
const user = userEvent.setup();
render(<NewEventLeadPage />);
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
await waitFor(() => expect(screen.getByRole("button", { name: "Next" })).toBeEnabled());
await user.type(screen.getByLabelText("Mobile"), "91111111");
await user.type(screen.getByLabelText("Email"), "a@b.com");
await user.click(screen.getByRole("button", { name: "Next" }));
await waitFor(() => expect(mocks.matchLead).toHaveBeenCalledWith("evt-1", expect.objectContaining({ email: "a@b.com" }), 2));
});
it("does not show Company to staff and sends no companyId", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true });
mocks.useCompanyScope.mockReturnValue(scope());
const user = userEvent.setup();
render(<NewEventLeadPage />);
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
await user.type(screen.getByLabelText("Mobile"), "91111111");
await user.click(screen.getByRole("button", { name: "Next" }));
await waitFor(() => expect(mocks.matchLead).toHaveBeenCalled());
expect(mocks.matchLead.mock.calls[0]).toHaveLength(2);
});
});
@@ -0,0 +1,164 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAdminRoles: vi.fn(),
listSalespersonOptions: vi.fn(),
useAdminAuth: vi.fn(),
useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: mocks.listAdminRoles }));
vi.mock("@/app/lib/services/adminEvents", () => ({ listSalespersonOptions: mocks.listSalespersonOptions }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
import { UserForm } from "@/app/components/users/UserForm";
import { EventForm } from "@/app/components/events/EventForm";
import { pickDate } from "@/test/pickDate";
import { ApiError } from "@/app/lib/clientApi";
const COMPANIES = [
{ id: 1, name: "Ins Co", code: "INS", status: "A" },
{ id: 2, name: "CV Co", code: "CV", status: "A" },
];
const scope = (companyId?: number) => ({ companyId, companies: COMPANIES, showCompanyColumn: false, codeOf: () => "", setCompanyId: vi.fn() });
const ROLES = [
{ id: 1, name: "ROLE_SUPER_ADMIN", level: 1, parent: { id: 0 } },
{ id: 2, name: "ROLE_HQ", level: 1, parent: { id: 0 } },
];
beforeEach(() => {
mocks.listAdminRoles.mockReset().mockResolvedValue(ROLES);
mocks.listSalespersonOptions.mockReset().mockResolvedValue([{ id: 1, name: "Alice", username: "alice" }]);
mocks.useAdminAuth.mockReset().mockReturnValue({ id: 9, isSuper: true });
mocks.useCompanyScope.mockReset().mockReturnValue(scope(2));
});
async function fillUser(user: ReturnType<typeof userEvent.setup>) {
await screen.findByLabelText("HQ");
await user.type(screen.getByLabelText("Name"), "Jane");
await user.type(screen.getByLabelText("Surname"), "Doe");
await user.type(screen.getByLabelText("Username"), "jane");
await user.type(screen.getByLabelText("Email"), "jane@x.test");
}
describe("UserForm company", () => {
it("shows Company to a super admin, defaulted to the picker, and sends it", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<UserForm onSubmit={onSubmit} />);
const company = await screen.findByRole("combobox", { name: "Company" });
expect(company).toHaveValue("2");
await fillUser(user);
await user.click(screen.getByLabelText("HQ"));
await user.click(screen.getByRole("button", { name: /create|save/i }));
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ companyId: 2 })));
});
it("offers Super admin (no company), which sends superAdmin and requires role 1", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<UserForm onSubmit={onSubmit} />);
await user.selectOptions(await screen.findByRole("combobox", { name: "Company" }), "super");
await fillUser(user);
await user.click(screen.getByLabelText("HQ"));
await user.click(screen.getByRole("button", { name: /create|save/i }));
expect(onSubmit).not.toHaveBeenCalled();
await user.click(screen.getByLabelText("Super admin"));
await user.click(screen.getByRole("button", { name: /create|save/i }));
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ superAdmin: true })));
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("companyId", expect.anything());
});
it("requires a company when none is chosen", async () => {
mocks.useCompanyScope.mockReturnValue(scope());
const onSubmit = vi.fn();
const user = userEvent.setup();
render(<UserForm onSubmit={onSubmit} />);
await fillUser(user);
await user.click(screen.getByLabelText("HQ"));
await user.click(screen.getByRole("button", { name: /create|save/i }));
expect(onSubmit).not.toHaveBeenCalled();
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
});
it("does not show Company to staff or send it", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false });
const onSubmit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<UserForm onSubmit={onSubmit} />);
await fillUser(user);
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
await user.click(screen.getByLabelText("HQ"));
await user.click(screen.getByRole("button", { name: /create|save/i }));
await waitFor(() => expect(onSubmit).toHaveBeenCalled());
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("companyId");
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("superAdmin");
});
it("shows the server's COMPANY_REQUIRED message", async () => {
const onSubmit = vi.fn().mockRejectedValue(new ApiError("Choose a company.", 400, { code: "COMPANY_REQUIRED" }));
const user = userEvent.setup();
render(<UserForm onSubmit={onSubmit} />);
await fillUser(user);
await user.click(screen.getByLabelText("HQ"));
await user.click(screen.getByRole("button", { name: /create|save/i }));
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
});
});
describe("EventForm company", () => {
it("shows Company to a super admin, defaulted to the picker, and sends it on create", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
const user = userEvent.setup();
render(<EventForm onSubmit={onSubmit} />);
expect(await screen.findByRole("combobox", { name: "Company" })).toHaveValue("2");
await user.type(screen.getByLabelText("Name"), "Expo");
await user.type(screen.getByLabelText("Location"), "KL");
pickDate("Start date", "2026-12-01");
pickDate("End date", "2026-12-02");
await user.click(screen.getByRole("button", { name: /create|save/i }));
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ companyId: 2 })));
});
it("does not show Company to staff", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false });
render(<EventForm onSubmit={vi.fn()} />);
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenCalled());
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
});
it("asks for salesperson options with the company chosen, and with the event's own company on edit", async () => {
const user = userEvent.setup();
const { unmount } = render(<EventForm onSubmit={vi.fn()} />);
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(2));
await user.selectOptions(screen.getByRole("combobox", { name: "Company" }), "1");
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(1));
unmount();
mocks.useCompanyScope.mockReturnValue(scope(1));
render(
<EventForm
initial={{ uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, companyId: 2, salespersons: [] } as never}
onSubmit={vi.fn()}
/>,
);
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(2));
});
});
describe("EventForm company required", () => {
it("refuses a super-admin create with no company chosen", async () => {
mocks.useCompanyScope.mockReturnValue(scope());
const onSubmit = vi.fn();
const user = userEvent.setup();
render(<EventForm onSubmit={onSubmit} />);
await user.type(await screen.findByLabelText("Name"), "Expo");
await user.type(screen.getByLabelText("Location"), "KL");
pickDate("Start date", "2026-12-01");
pickDate("End date", "2026-12-02");
await user.click(screen.getByRole("button", { name: /create|save/i }));
expect(onSubmit).not.toHaveBeenCalled();
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
});
});
@@ -0,0 +1,54 @@
import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
// The companies list usually arrives after the first page of rows; the Company column must still fill in.
const mocks = vi.hoisted(() => ({
listAdminEvents: vi.fn(),
listEmails: vi.fn(),
searchAuditLog: vi.fn(),
useAdminAuth: vi.fn(),
useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i<object>()), listAdminEvents: mocks.listAdminEvents }));
vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i<object>()), listEmails: mocks.listEmails }));
vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i<object>()), searchAuditLog: mocks.searchAuditLog }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import EventsPage from "./events/page";
import EmailsPage from "./emails/page";
import AuditLogPage from "./audit-log/page";
const scope = (codes: Record<number, string>) => ({
companyId: undefined,
companies: [],
showCompanyColumn: true,
codeOf: (id?: number) => (id ? codes[id] ?? "" : ""),
setCompanyId: vi.fn(),
});
const PAGES = [
{ name: "events", Page: EventsPage, list: mocks.listAdminEvents, row: { uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, companyId: 2 } },
{ name: "emails", Page: EmailsPage, list: mocks.listEmails, row: { id: 9, datetime: "2026-11-30T11:44:26", recipients: ["a@x.test"], subject: "Hello", status: "Y", companyId: 2 } },
{ name: "audit log", Page: AuditLogPage, list: mocks.searchAuditLog, row: { id: 2, companyId: 2, occurredAt: "2026-11-30T15:52:00", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/x", targetId: "4", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null } },
];
beforeEach(() => {
memoryRouter.reset("/x");
for (const p of PAGES) p.list.mockReset().mockResolvedValue({ items: [p.row], total: 1 });
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
});
describe.each(PAGES)("$name Company column", ({ Page, row }) => {
it("shows the code once the companies arrive after the rows", async () => {
mocks.useCompanyScope.mockReturnValue(scope({}));
const { rerender } = render(<Page />);
await screen.findAllByText(String("name" in row ? row.name : "subject" in row ? row.subject : row.actor));
mocks.useCompanyScope.mockReturnValue(scope({ 2: "CV" }));
rerender(<Page />);
expect(await screen.findByText("CV")).toBeInTheDocument();
});
});
@@ -0,0 +1,119 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAdminUsers: vi.fn(),
listAdminEvents: vi.fn(),
listEmails: vi.fn(),
searchAuditLog: vi.fn(),
listLeads: vi.fn(),
useAdminAuth: vi.fn(),
useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminUsers", async (i) => ({ ...(await i<object>()), listAdminUsers: mocks.listAdminUsers }));
vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i<object>()), listAdminEvents: mocks.listAdminEvents }));
vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i<object>()), listEmails: mocks.listEmails }));
vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i<object>()), searchAuditLog: mocks.searchAuditLog }));
vi.mock("@/app/lib/services/adminLeads", async (i) => ({ ...(await i<object>()), listLeads: mocks.listLeads }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import UsersPage from "./users/page";
import EventsPage from "./events/page";
import EmailsPage from "./emails/page";
import AuditLogPage from "./audit-log/page";
import LeadsPage from "./leads/page";
const CODES: Record<number, string> = { 1: "INS", 2: "CV" };
const scope = (companyId?: number, isShown = companyId === undefined) => ({
companyId,
companies: [],
showCompanyColumn: isShown,
codeOf: (id?: number) => (id ? CODES[id] ?? "" : ""),
setCompanyId: vi.fn(),
});
const headers = async () => within(await screen.findByRole("table")).getAllByRole("columnheader").map((h) => h.textContent);
const PAGES = [
{
name: "users",
Page: UsersPage,
list: mocks.listAdminUsers,
row: { id: 5, username: "jane", name: "Jane", email: "j@x.test", enabled: true, status: "A", roles: [], companyId: 2, companyCode: "CV", loginName: "jane@cv" },
},
{
name: "events",
Page: EventsPage,
list: mocks.listAdminEvents,
row: { uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, companyId: 2 },
},
{
name: "emails",
Page: EmailsPage,
list: mocks.listEmails,
row: { id: 9, datetime: "2026-11-30T11:44:26", recipients: ["a@x.test"], subject: "Hello", status: "Y", companyId: 2 },
},
{
name: "audit log",
Page: AuditLogPage,
list: mocks.searchAuditLog,
row: { id: 2, companyId: 2, occurredAt: "2026-11-30T15:52:00", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/x", targetId: "4", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null },
},
];
beforeEach(() => {
memoryRouter.reset("/x");
for (const p of [...PAGES.map((x) => x.list), mocks.listLeads]) p.mockReset();
for (const p of PAGES) p.list.mockResolvedValue({ items: [p.row], total: 1 });
mocks.listLeads.mockResolvedValue({ items: [], total: 0 });
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
mocks.useCompanyScope.mockReset().mockReturnValue(scope());
});
describe.each(PAGES)("$name list company scope", ({ Page, list, row }) => {
it("shows the Company column with the code for a super admin on All companies, and sends no companyId", async () => {
render(<Page />);
expect(await headers()).toContain("Company");
expect(await screen.findByText("CV")).toBeInTheDocument();
expect(list.mock.calls.at(-1)?.[0]).not.toHaveProperty("companyId", expect.anything());
expect(row).toBeTruthy();
});
it("hides the Company column and sends the picked companyId when one company is chosen", async () => {
mocks.useCompanyScope.mockReturnValue(scope(2));
render(<Page />);
expect(await headers()).not.toContain("Company");
await waitFor(() => expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ companyId: 2 })));
});
it("hides the Company column for staff and never sends companyId", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true });
mocks.useCompanyScope.mockReturnValue(scope(undefined, false));
render(<Page />);
expect(await headers()).not.toContain("Company");
expect(list.mock.calls.every((c) => (c[0] as { companyId?: number }).companyId === undefined)).toBe(true);
});
});
describe("users list names", () => {
it("shows the local username, not the login name with @code", async () => {
render(<UsersPage />);
expect(await screen.findByText("jane")).toBeInTheDocument();
expect(screen.queryByText("jane@cv")).not.toBeInTheDocument();
});
});
describe("leads list company scope", () => {
it("adds a tenant Company column only on All companies, and sends the picked companyId", async () => {
const count = async () => (await headers()).filter((h) => h === "Company").length;
const { unmount } = render(<LeadsPage />);
const withAll = await count();
unmount();
mocks.useCompanyScope.mockReturnValue(scope(2));
render(<LeadsPage />);
expect(withAll).toBe((await count()) + 1);
await waitFor(() => expect(mocks.listLeads).toHaveBeenLastCalledWith(expect.objectContaining({ companyId: 2 })));
});
});
@@ -0,0 +1,92 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAdminRoles: vi.fn(),
listInterests: vi.fn(),
apiGet: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/clientApi", async (i) => ({ ...(await i<object>()), apiGet: mocks.apiGet, apiPost: vi.fn(), apiPut: vi.fn() }));
vi.mock("@/app/lib/services/adminRoles", async (i) => ({ ...(await i<object>()), listAdminRoles: mocks.listAdminRoles }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import RolesPage from "./roles/page";
import InterestsPage from "./interests/page";
import LoginSecurityPage from "./login-security/page";
const as = (isSuper: boolean) => mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper, hasModule: () => true });
beforeEach(() => {
memoryRouter.reset("/x");
mocks.listAdminRoles.mockReset().mockResolvedValue([{ id: 4, name: "ROLE_HQ", parent: { id: 1 } }]);
mocks.apiGet.mockReset().mockImplementation(async (path: string) => {
if (path.includes("/interests")) return [{ id: 3, name: "Product A", active: true }];
if (path.includes("/config")) return { enabled: true, maxAttempts: 5, period: 15, unit: "M" };
if (path.includes("/password-rules")) return [];
return [];
});
mocks.useAdminAuth.mockReset();
});
describe("Roles read-only for staff", () => {
it("hides Add role, Edit and Manage access for staff", async () => {
as(false);
render(<RolesPage />);
await screen.findByText("ROLE_HQ");
expect(screen.queryByRole("button", { name: /add role/i })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /^edit/i })).not.toBeInTheDocument();
expect(screen.queryByRole("link", { name: /manage access/i })).not.toBeInTheDocument();
});
it("keeps them for a super admin", async () => {
as(true);
render(<RolesPage />);
await screen.findByText("ROLE_HQ");
expect(screen.getByRole("button", { name: /add role/i })).toBeInTheDocument();
});
});
describe("Interests read-only for staff", () => {
it("hides Add interest and row actions for staff", async () => {
as(false);
render(<InterestsPage />);
await screen.findByText("Product A");
expect(screen.queryByRole("button", { name: /add interest/i })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /^edit/i })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /deactivate/i })).not.toBeInTheDocument();
});
it("keeps Add interest for a super admin", async () => {
as(true);
render(<InterestsPage />);
await screen.findByText("Product A");
expect(screen.getByRole("button", { name: /add interest/i })).toBeInTheDocument();
});
});
describe("Login security Settings read-only for staff", () => {
async function openSettings() {
const user = userEvent.setup();
render(<LoginSecurityPage />);
await user.click(await screen.findByRole("tab", { name: /settings/i }));
return user;
}
it("hides the Save buttons for staff", async () => {
as(false);
await openSettings();
await waitFor(() => expect(mocks.apiGet).toHaveBeenCalledWith(expect.stringContaining("/config")));
expect(screen.queryByRole("button", { name: /save lockout settings/i })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /save password rules/i })).not.toBeInTheDocument();
});
it("shows the Save buttons to a super admin", async () => {
as(true);
await openSettings();
expect(await screen.findByRole("button", { name: /save lockout settings/i })).toBeInTheDocument();
});
});
@@ -0,0 +1,99 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAdminUsers: vi.fn(),
listAdminEvents: vi.fn(),
listEmails: vi.fn(),
searchAuditLog: vi.fn(),
listLeads: vi.fn(),
listAudit: vi.fn(),
listLocked: vi.fn(),
getConfig: vi.fn(),
getPasswordRules: vi.fn(),
useAdminAuth: vi.fn(),
useCompanyScope: vi.fn(),
}));
vi.mock("@/app/lib/services/adminUsers", async (i) => ({ ...(await i<object>()), listAdminUsers: mocks.listAdminUsers }));
vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i<object>()), listAdminEvents: mocks.listAdminEvents }));
vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i<object>()), listEmails: mocks.listEmails }));
vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i<object>()), searchAuditLog: mocks.searchAuditLog }));
vi.mock("@/app/lib/services/adminLeads", async (i) => ({ ...(await i<object>()), listLeads: mocks.listLeads }));
vi.mock("@/app/lib/services/loginSecurity", async (i) => ({
...(await i<object>()),
listAudit: mocks.listAudit,
listLocked: mocks.listLocked,
getConfig: mocks.getConfig,
getPasswordRules: mocks.getPasswordRules,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import UsersPage from "./users/page";
import EventsPage from "./events/page";
import EmailsPage from "./emails/page";
import AuditLogPage from "./audit-log/page";
import LeadsPage from "./leads/page";
import LoginSecurityPage from "./login-security/page";
const scope = (companyId?: number) => ({ companyId, companies: [], showCompanyColumn: companyId === undefined, codeOf: () => "CV", setCompanyId: vi.fn() });
const EMPTY = { items: [], total: 0 };
beforeEach(() => {
memoryRouter.reset("/x", "page=3");
for (const m of [mocks.listAdminUsers, mocks.listAdminEvents, mocks.listEmails, mocks.searchAuditLog, mocks.listLeads, mocks.listAudit]) m.mockReset().mockResolvedValue(EMPTY);
mocks.listLocked.mockReset().mockResolvedValue([{ username: "jane", failures: 5, lastFailure: "2026-11-30T10:00:00", lockedUntil: "2026-11-30T11:00:00" }]);
mocks.getConfig.mockReset().mockResolvedValue({ enabled: true, maxAttempts: 5, period: 15, unit: "M" });
mocks.getPasswordRules.mockReset().mockResolvedValue([{ id: 1, param: "MIN_LENGTH", status: "Y", value: "8" }]);
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
mocks.useCompanyScope.mockReset().mockReturnValue(scope(1));
});
describe.each([
["users", UsersPage, mocks.listAdminUsers],
["events", EventsPage, mocks.listAdminEvents],
["emails", EmailsPage, mocks.listEmails],
["audit log", AuditLogPage, mocks.searchAuditLog],
["leads", LeadsPage, mocks.listLeads],
])("%s picker change resets paging", (_name, Page, list) => {
it("returns to the first page when the company changes, not on first render", async () => {
const { rerender } = render(<Page />);
await waitFor(() => expect(list).toHaveBeenCalled());
expect(memoryRouter.getSearch().get("page")).toBe("3");
mocks.useCompanyScope.mockReturnValue(scope(2));
rerender(<Page />);
await waitFor(() => expect(memoryRouter.getSearch().get("page")).toBeNull());
});
});
describe("login security", () => {
it("history returns to the first page when the company changes", async () => {
const { rerender } = render(<LoginSecurityPage />);
await waitFor(() => expect(mocks.listAudit).toHaveBeenCalled());
expect(memoryRouter.getSearch().get("page")).toBe("3");
mocks.useCompanyScope.mockReturnValue(scope(2));
rerender(<LoginSecurityPage />);
await waitFor(() => expect(memoryRouter.getSearch().get("page")).toBeNull());
});
it("Locked tab has no Company column on All companies", async () => {
mocks.useCompanyScope.mockReturnValue(scope());
const user = userEvent.setup();
render(<LoginSecurityPage />);
await user.click(screen.getByRole("tab", { name: "Locked" }));
await screen.findByText("jane");
expect(screen.queryByRole("columnheader", { name: "Company" })).not.toBeInTheDocument();
});
it("disables the settings inputs for a non-super user", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true });
const user = userEvent.setup();
render(<LoginSecurityPage />);
await user.click(screen.getByRole("tab", { name: "Settings" }));
expect(await screen.findByLabelText(/max/i)).toBeDisabled();
expect(screen.getByRole("switch", { name: /min/i })).toBeDisabled();
});
});
@@ -4,6 +4,7 @@ import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { isPublicPath } from "@/app/lib/routeGuard";
import { CompanyScopeProvider } from "@/app/lib/CompanyScope";
import Header from "./Header";
import Sidebar from "./Sidebar";
import PoweredBy from "./PoweredBy";
@@ -45,6 +46,7 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
}
return (
<CompanyScopeProvider>
<div className="flex min-h-svh bg-background">
<SessionKeepAlive />
<Sidebar />
@@ -63,5 +65,6 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
</div>
</div>
</div>
</CompanyScopeProvider>
);
}
Loaded 100 of 344 files, more files were not shown because too many files have changed in this diff. Show more