diff --git a/docs/deployment.md b/docs/deployment.md index 0f6bee1..421ac2b 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -89,6 +89,14 @@ After running `04`, `SELECT LENGTH(password) FROM \`service-system\`.\`user\` WH `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. + **Database user:** - Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function. - Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`. @@ -284,6 +292,7 @@ data: - **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. - **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. diff --git a/docs/superpowers/specs/2026-11-30-company-scoping-design.md b/docs/superpowers/specs/2026-11-30-company-scoping-design.md new file mode 100644 index 0000000..8e2feda --- /dev/null +++ b/docs/superpowers/specs/2026-11-30-company-scoping-design.md @@ -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. diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index b6d608c..5b6f765 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -177,3 +177,54 @@ CREATE TABLE IF NOT EXISTS `audit_event` ( 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); diff --git a/openspec/changes/add-company-scoping/.openspec.yaml b/openspec/changes/add-company-scoping/.openspec.yaml new file mode 100644 index 0000000..4a154df --- /dev/null +++ b/openspec/changes/add-company-scoping/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-30 diff --git a/openspec/changes/add-company-scoping/design.md b/openspec/changes/add-company-scoping/design.md new file mode 100644 index 0000000..1d19f73 --- /dev/null +++ b/openspec/changes/add-company-scoping/design.md @@ -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. diff --git a/openspec/changes/add-company-scoping/proposal.md b/openspec/changes/add-company-scoping/proposal.md new file mode 100644 index 0000000..fe8a0a4 --- /dev/null +++ b/openspec/changes/add-company-scoping/proposal.md @@ -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. diff --git a/openspec/changes/add-company-scoping/specs/admin-access/spec.md b/openspec/changes/add-company-scoping/specs/admin-access/spec.md new file mode 100644 index 0000000..1e75990 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/admin-access/spec.md @@ -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 diff --git a/openspec/changes/add-company-scoping/specs/admin-login-security/spec.md b/openspec/changes/add-company-scoping/specs/admin-login-security/spec.md new file mode 100644 index 0000000..b8bb953 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/admin-login-security/spec.md @@ -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 diff --git a/openspec/changes/add-company-scoping/specs/admin-roles/spec.md b/openspec/changes/add-company-scoping/specs/admin-roles/spec.md new file mode 100644 index 0000000..f7718d8 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/admin-roles/spec.md @@ -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 diff --git a/openspec/changes/add-company-scoping/specs/admin-users/spec.md b/openspec/changes/add-company-scoping/specs/admin-users/spec.md new file mode 100644 index 0000000..3b0e124 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/admin-users/spec.md @@ -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 diff --git a/openspec/changes/add-company-scoping/specs/company-scoping/spec.md b/openspec/changes/add-company-scoping/specs/company-scoping/spec.md new file mode 100644 index 0000000..65f6ada --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/company-scoping/spec.md @@ -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 diff --git a/openspec/changes/add-company-scoping/specs/lead-interests/spec.md b/openspec/changes/add-company-scoping/specs/lead-interests/spec.md new file mode 100644 index 0000000..bfab899 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/lead-interests/spec.md @@ -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 diff --git a/openspec/changes/add-company-scoping/sql/01-company-code-status.sql b/openspec/changes/add-company-scoping/sql/01-company-code-status.sql new file mode 100644 index 0000000..76372cf --- /dev/null +++ b/openspec/changes/add-company-scoping/sql/01-company-code-status.sql @@ -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`); diff --git a/openspec/changes/add-company-scoping/sql/02-company-columns.sql b/openspec/changes/add-company-scoping/sql/02-company-columns.sql new file mode 100644 index 0000000..04f1fc5 --- /dev/null +++ b/openspec/changes/add-company-scoping/sql/02-company-columns.sql @@ -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; diff --git a/openspec/changes/add-company-scoping/sql/03-admin-login-names.sql b/openspec/changes/add-company-scoping/sql/03-admin-login-names.sql new file mode 100644 index 0000000..1ebcc1e --- /dev/null +++ b/openspec/changes/add-company-scoping/sql/03-admin-login-names.sql @@ -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); diff --git a/openspec/changes/add-company-scoping/sql/99-rollback.sql b/openspec/changes/add-company-scoping/sql/99-rollback.sql new file mode 100644 index 0000000..af240a1 --- /dev/null +++ b/openspec/changes/add-company-scoping/sql/99-rollback.sql @@ -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`; diff --git a/openspec/changes/add-company-scoping/tasks.md b/openspec/changes/add-company-scoping/tasks.md new file mode 100644 index 0000000..1008eb2 --- /dev/null +++ b/openspec/changes/add-company-scoping/tasks.md @@ -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. diff --git a/solvway-admin-portal/app/api/auth/forgot-password/route.company.test.ts b/solvway-admin-portal/app/api/auth/forgot-password/route.company.test.ts new file mode 100644 index 0000000..58e26ec --- /dev/null +++ b/solvway-admin-portal/app/api/auth/forgot-password/route.company.test.ts @@ -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" }); + }); +}); diff --git a/solvway-admin-portal/app/api/auth/forgot-password/route.ts b/solvway-admin-portal/app/api/auth/forgot-password/route.ts index 9964eaa..5436284 100644 --- a/solvway-admin-portal/app/api/auth/forgot-password/route.ts +++ b/solvway-admin-portal/app/api/auth/forgot-password/route.ts @@ -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 }); } diff --git a/solvway-admin-portal/app/api/auth/login/route.company.test.ts b/solvway-admin-portal/app/api/auth/login/route.company.test.ts new file mode 100644 index 0000000..81d8974 --- /dev/null +++ b/solvway-admin-portal/app/api/auth/login/route.company.test.ts @@ -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[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" }); + }); +}); diff --git a/solvway-admin-portal/app/api/auth/login/route.ts b/solvway-admin-portal/app/api/auth/login/route.ts index e275364..d89473a 100644 --- a/solvway-admin-portal/app/api/auth/login/route.ts +++ b/solvway-admin-portal/app/api/auth/login/route.ts @@ -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("/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), }); diff --git a/solvway-admin-portal/app/api/auth/session/route.company.test.ts b/solvway-admin-portal/app/api/auth/session/route.company.test.ts new file mode 100644 index 0000000..a23907f --- /dev/null +++ b/solvway-admin-portal/app/api/auth/session/route.company.test.ts @@ -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 }); + }); +}); diff --git a/solvway-admin-portal/app/api/auth/session/route.ts b/solvway-admin-portal/app/api/auth/session/route.ts index dc1c70f..1a94bd9 100644 --- a/solvway-admin-portal/app/api/auth/session/route.ts +++ b/solvway-admin-portal/app/api/auth/session/route.ts @@ -25,6 +25,9 @@ export async function GET(req: NextRequest) { const result = await callMobileApi("/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, + }); } diff --git a/solvway-admin-portal/app/api/companies/[id]/code/route.test.ts b/solvway-admin-portal/app/api/companies/[id]/code/route.test.ts new file mode 100644 index 0000000..3501216 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/[id]/code/route.test.ts @@ -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", + }); + }); +}); diff --git a/solvway-admin-portal/app/api/companies/[id]/code/route.ts b/solvway-admin-portal/app/api/companies/[id]/code/route.ts new file mode 100644 index 0000000..5f34bf2 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/[id]/code/route.ts @@ -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(`/api/admin/companies/${encodeURIComponent(id)}/code`, { + method: "POST", + body: { code }, + token, + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/companies/route.test.ts b/solvway-admin-portal/app/api/companies/route.test.ts new file mode 100644 index 0000000..9734a71 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/route.test.ts @@ -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[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"); + }); +}); diff --git a/solvway-admin-portal/app/api/companies/route.ts b/solvway-admin-portal/app/api/companies/route.ts new file mode 100644 index 0000000..3d242e4 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/route.ts @@ -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("/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; + const result = await callMobileApi("/api/admin/companies", { + method: "POST", + body: { id, name, code, status }, + token, + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/events/route.ts b/solvway-admin-portal/app/api/events/route.ts index dae3a6a..5146cf9 100644 --- a/solvway-admin-portal/app/api/events/route.ts +++ b/solvway-admin-portal/app/api/events/route.ts @@ -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"); diff --git a/solvway-admin-portal/app/api/events/salesperson-options/route.ts b/solvway-admin-portal/app/api/events/salesperson-options/route.ts index 97ce01c..4e127a6 100644 --- a/solvway-admin-portal/app/api/events/salesperson-options/route.ts +++ b/solvway-admin-portal/app/api/events/salesperson-options/route.ts @@ -7,7 +7,10 @@ export async function GET(req: NextRequest) { const token = await getToken(); if (!token) return unauthorized(); - const result = await callMobileApi>("/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>(`/api/admin/events/salesperson-options${qs.size ? `?${qs}` : ""}`, { token }); if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } diff --git a/solvway-admin-portal/app/api/login-security/[[...path]]/route.companyId.test.ts b/solvway-admin-portal/app/api/login-security/[[...path]]/route.companyId.test.ts new file mode 100644 index 0000000..6e9e996 --- /dev/null +++ b/solvway-admin-portal/app/api/login-security/[[...path]]/route.companyId.test.ts @@ -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[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"); + }); +}); diff --git a/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts b/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts index 0d121fa..0578741 100644 --- a/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts +++ b/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts @@ -11,7 +11,7 @@ async function forward(method: "GET" | "POST" | "PUT", req: NextRequest, { param 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("")}${method === "GET" ? new URL(req.url).search : ""}`; + 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(); diff --git a/solvway-admin-portal/app/api/users/route.ts b/solvway-admin-portal/app/api/users/route.ts index 5d66c83..2c93d78 100644 --- a/solvway-admin-portal/app/api/users/route.ts +++ b/solvway-admin-portal/app/api/users/route.ts @@ -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"); diff --git a/solvway-admin-portal/app/audit-log/page.tsx b/solvway-admin-portal/app/audit-log/page.tsx index 8cd9839..3004c23 100644 --- a/solvway-admin-portal/app/audit-log/page.tsx +++ b/solvway-admin-portal/app/audit-log/page.tsx @@ -11,10 +11,12 @@ 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: "" }; @@ -23,8 +25,10 @@ const MODULES = [...Object.values(ROUTE_MODULES).filter((m) => m !== "BO_AUDIT_L 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); @@ -37,18 +41,19 @@ function AuditLogContent() { // 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 }) + 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]); + }, [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") => {text}; const columns = useMemo[]>( () => [ + ...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef] : []), { id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => {formatDate(row.original.occurredAt)} }, { 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) : "—") }, @@ -73,7 +78,7 @@ function AuditLogContent() { }, { accessorKey: "clientIp", header: t("LsIp"), enableSorting: false }, ], - [t], + [t, showCompanyColumn, codeOf], ); return ( diff --git a/solvway-admin-portal/app/companies/page.fixes.test.tsx b/solvway-admin-portal/app/companies/page.fixes.test.tsx new file mode 100644 index 0000000..554e350 --- /dev/null +++ b/solvway-admin-portal/app/companies/page.fixes.test.tsx @@ -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()).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(); + 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(); + expect(await screen.findByText("Forbidden for you")).toBeInTheDocument(); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.test.tsx b/solvway-admin-portal/app/companies/page.test.tsx new file mode 100644 index 0000000..be61ac8 --- /dev/null +++ b/solvway-admin-portal/app/companies/page.test.tsx @@ -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()).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(); + 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(); + 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(); + 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(); + 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(); + 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(); + expect(screen.getByTestId("not-authorized")).toBeInTheDocument(); + expect(mocks.apiGet).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.tsx b/solvway-admin-portal/app/companies/page.tsx new file mode 100644 index 0000000..451c8bf --- /dev/null +++ b/solvway-admin-portal/app/companies/page.tsx @@ -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(company); + const [newCode, setNewCode] = useState(company.code); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + + async function handleSubmit(event: FormEvent) { + 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 ( + !open && onClose()}> + + + {mode === "code" ? t("CompChangeCode") : form.id ? t("CompEdit") : t("CompAdd")} + + {error && ( +
+ {error} +
+ )} +
+ {mode === "code" ? ( + <> +

{t("CompChangeCodeWarning")}

+
+ + setNewCode(e.target.value)} disabled={saving} /> +
+ + ) : ( + <> +
+ + setForm((f) => ({ ...f, name: e.target.value }))} disabled={saving} /> +
+ {!form.id && ( +
+ + setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} /> +
+ )} +
+ + +
+ + )} + + + +
+
+
+ ); +} + +function CompaniesPageContent() { + const t = useT(); + const [companies, setCompanies] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [reloadKey, setReloadKey] = useState(0); + const [dialog, setDialog] = useState(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[]>( + () => [ + { accessorKey: "name", header: t("Name") }, + { accessorKey: "code", header: t("Code") }, + { + accessorKey: "status", + header: t("Status"), + cell: ({ row }) => ( + + {row.original.status === "A" ? t("CompActive") : t("CompInactive")} + + ), + }, + { + id: "actions", + header: t("CatActions"), + cell: ({ row }) => ( +
+ + +
+ ), + }, + ], + [t], + ); + + return ( + <> + setDialog({ mode: "form", company: NEW_COMPANY })}> +