feat: company scoping (INS and CV, super admins see all) #25
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -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);
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-30
|
||||
@@ -0,0 +1,101 @@
|
||||
# Design
|
||||
|
||||
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-company-scoping-design.md`.
|
||||
|
||||
## Context
|
||||
|
||||
- **Identity is a string everywhere:**
|
||||
- services-auth issues the JWT with the user's `username` as subject.
|
||||
- It resolves a token back to a user through services-system `/user/findByUsernameWithPassword/{username}`.
|
||||
- mobile-api resolves the caller from the token about 40 times. It also uses `caller.getUsername()` for `doneBy`, the lockout key, the `login_audit` username and the audit actor.
|
||||
- `user.username` is globally unique (`username_UNIQUE`). Member users live in the same table.
|
||||
- **Already scoped by company:** leads, event leads, event salespersons and interests are queried by the caller's company. mobile-api passes `caller.getCompanyId()` to services-counter.
|
||||
- **Not scoped:**
|
||||
- the users search (services-system);
|
||||
- events (the Tastefully `event` table, services-counter, no `company_id`);
|
||||
- emails (service-email, no `company_id`);
|
||||
- login history and locked users (services-system; `login_audit.company_id` exists but is unused);
|
||||
- the audit log (services-log; `audit_event.company_id` exists but is unused).
|
||||
- **Super admin today:** holds role id 1. Checked in `AppAccessAspect`, `AdminUserService`, `AdminRoleService`, `AdminAclService` and `AdminEmailService`.
|
||||
- **Company today:** `company` is `(id, name, create_date)`, with one row (id 1, "Co-Lite"). No entity or API.
|
||||
- **Emails:** mobile-api `EmailService` publishes emails to `email-save-request-topic`, and service-email saves them.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Every scoped admin read and write carries the caller's company; super admins see all or a picked company.
|
||||
- Company sign-in without changing services-auth, the token format or member sign-in.
|
||||
- Adding a company needs no code, deploy or database work.
|
||||
|
||||
**Non-Goals:**
|
||||
- Members and the customer portal.
|
||||
- Company admins with their own roles or settings.
|
||||
- Stamping a super admin's audit row with the changed record's company.
|
||||
- Deleting companies.
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **The stored username of a staff user is the login name `local@code`.**
|
||||
- The portal sends `company` and `username`. mobile-api builds the login name: `username@company`, lowercased code; a blank company means the plain username, which is a super admin.
|
||||
- services-system stores `john@ins` in `user.username`. The existing unique key then gives per-company uniqueness. services-auth, tokens, `findByUsername*`, `login_audit` and the audit actor all keep working on that one string unchanged.
|
||||
- Screens show the local part (`john`) next to the company. A username input SHALL NOT contain `@`.
|
||||
- Alternative rejected: a new `login_name` column, or a lookup split across company and username. Either would touch services-auth and every token lookup for the same outcome.
|
||||
- The user's choice of approach B is preserved: per-company usernames, a separate Company field and a renamable code.
|
||||
2. **Company code change:**
|
||||
- A services-system `@Transactional` endpoint renames the code and rewrites `username = CONCAT(local, '@', newCode)` for that company's admin users.
|
||||
- Old tokens no longer resolve to a user, so those sessions end on their next request. The username column is the session's identity, so nothing else is needed.
|
||||
- Login history keeps the old names.
|
||||
3. **Company table and API:**
|
||||
- `company` gains `code varchar(20) NOT NULL UNIQUE` and `status char(1) NOT NULL DEFAULT 'A'`.
|
||||
- services-system gets a `Company` entity, repository and `/company/*` endpoints: list, find, save, rename-code.
|
||||
- mobile-api gets `AdminCompanyController` (`/api/admin/companies`), super admin only.
|
||||
4. **Super admin check, in one place:**
|
||||
- `AdminCompanyScope` (mobile-api) defines `isSuper(caller)` as "no company AND holds role 1". It replaces the role-only checks.
|
||||
- `scope(caller, requestedCompanyId)` returns the company to filter by:
|
||||
- staff: their own company, ignoring any request value;
|
||||
- super admin: the requested company, or null for all.
|
||||
- `requireCompanyForCreate(caller, requested)`: a super admin must choose one.
|
||||
- `requireSuper(caller)` answers 403.
|
||||
- Ported from babyboo's `AdminCountryScope` pattern.
|
||||
5. **Inactive company:**
|
||||
- `AdminSessionGuard`, which already loads the caller on every admin request, refuses a staff user whose company is inactive, with the same 401 as a dead session.
|
||||
- `AdminAuthController.login` refuses one with `BAD_LOGIN`.
|
||||
- The company status comes from services-system with the user, by adding `companyStatus` to the user lookup. That avoids an extra call per request.
|
||||
6. **Scoped queries:**
|
||||
- Each backend list or search endpoint takes an optional `companyId`; null means all companies, and only mobile-api decides when null is allowed.
|
||||
- Detail and edit endpoints resolve the record, then compare its company with the scope; a mismatch answers 404.
|
||||
- Where a services-counter query takes a mandatory `companyId` today, it becomes optional for lists.
|
||||
- Every write still takes a concrete company.
|
||||
7. **Events and emails get `company_id`:**
|
||||
- `event.company_id bigint NULL`, set from the scope on create and never changed by edit.
|
||||
- `email.company_id bigint NULL`, set by mobile-api `EmailService` from the user the email is for (forgot password, temporary password) and stored by service-email.
|
||||
- Public form emails and other system emails have no company and are visible to super admins only.
|
||||
8. **Interests become shared:**
|
||||
- The unique key `(company_id, name)` becomes `(name)`; queries stop filtering by company.
|
||||
- `interest.company_id` stays, unused and nullable, so no data is lost.
|
||||
- Writes are super admin only.
|
||||
9. **Login history and audit:**
|
||||
- `login_audit.company_id` is filled from the user that the login name matches; it is already done this way.
|
||||
- The audit actor's company is already stored.
|
||||
- The searches take the scope; NULL-company rows match only when the scope is "all".
|
||||
10. **Portal:**
|
||||
- `AdminAuthContext` gains `companyId`, `companyCode` and `isSuper` from the login response.
|
||||
- Super admins get a header `CompanyPicker`, persisted per tab. It feeds `companyId` into the list queries and the default of create forms.
|
||||
- A `Company` column appears on scoped lists when "All companies" is selected.
|
||||
- The login and forgot-password pages get a Company field.
|
||||
- `/companies` is gated by `isSuper`, not by a module.
|
||||
11. **One-time data step** (change folder SQL plus seed):
|
||||
- Set company 1 to `INS`/`ins`; insert `CV`/`cv`.
|
||||
- Set `admin` to company NULL.
|
||||
- Rewrite the other admin usernames to `username@ins`. First check that none contains `@`; stop if one does.
|
||||
- Set existing events and emails to company 1.
|
||||
- Move the interest unique key.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **Member usernames share the column.** A member whose username is exactly `john@ins` would block creating staff `john` in INS. Members do not exist in Co-Lite at go-live; the users API reports such a clash as "username taken".
|
||||
- **The login name is visible in history and audit.** Login history and the audit log show `john@ins`, which is clear for staff and super admins alike.
|
||||
- **A code change ends sessions.** This is intentional, and the Companies screen warns before saving.
|
||||
- **Every scoped endpoint must use the scope.** A missed endpoint is a cross-company leak.
|
||||
- Mitigation: one helper, a test per endpoint for another company's record, and a whole-branch review that checks every `/api/admin/**` handler.
|
||||
- **Tokens in flight at deploy:** their subjects (for example `sales1`) no longer match the rewritten usernames, so every session ends. Co-Lite is not deployed yet, so nobody is affected.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Co-Lite goes live on 2027-01-15 with two test-run companies, INS and CV, and more are planned. Each company's staff must see only their own company's data, and one or more super admins must see and manage everything, including creating companies. Everything built so far assumes a single company: users, events, emails, login history and the audit log are unscoped, interests are per company, and there is no way to create a company or tell companies apart at sign-in. Approved design: `docs/superpowers/specs/2026-11-30-company-scoping-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Companies:** `company` gains a unique `code` and an active/inactive `status`. A new super-admin-only Companies screen lists, creates and edits companies. An inactive company's staff cannot sign in.
|
||||
- **Sign-in:** the admin login page asks for Company, Username and Password; a super admin leaves Company empty. Usernames and emails are unique within a company. Forgot password asks for the same company and username plus the email.
|
||||
- **Super admins:** a super admin is a company-less admin user holding the super admin role. Company staff can never hold that role. There can be several super admins.
|
||||
- **Scoping:** every admin read, write, export and detail lookup is limited to the caller's company: users, events, event leads, leads, emails, login history, locked users and the audit log. Another company's record answers 404. Super admins see all companies, can narrow to one, and pick the company when creating a company-owned record.
|
||||
- **Shared data:** roles, interests, lockout settings and password rules are shared by all companies, and only super admins edit them. Interests become one shared list.
|
||||
- **Portal:** a header company picker and a Company column for super admins; Company fields on the login, forgot-password, user and event forms; the Companies screen.
|
||||
- **BREAKING (sign-in):** company staff must enter their company code to sign in. The deploy signs everyone out.
|
||||
- **Deploy SQL:** company code/status, `company_id` on `event` and `email`, the interest unique key, staff login names, INS and CV setup.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `company-scoping`: companies, the Companies screen, company sign-in identity, super admins, and the rule that limits every admin view and action to the caller's company.
|
||||
|
||||
### Modified Capabilities
|
||||
- `admin-access`: staff login and forgot password take a company.
|
||||
- `admin-users`: company membership, per-company username and email uniqueness, super admin creation.
|
||||
- `admin-roles`: editing roles becomes super admin only.
|
||||
- `lead-interests`: one shared interest list, edited by super admins only.
|
||||
- `admin-login-security`: unlock is limited to the caller's company; settings become super admin only.
|
||||
|
||||
## Impact
|
||||
|
||||
- **services-system:** company entity, repository and endpoints; user lookup, save and uniqueness by login name; user search by company; login-history and locked-user filters by company.
|
||||
- **services-counter:** `company_id` on events; event queries by company; interest queries become shared; queries accept "all companies" for super admins.
|
||||
- **service-email:** `company_id` on emails, set when an email is saved for a user; search by company.
|
||||
- **services-log:** audit search by company.
|
||||
- **mobile-api:** login and forgot password with company; one company-scope helper used by every admin service; Companies API; super-admin-only guards on roles, interests and login-security settings.
|
||||
- **admin portal:** login, forgot-password, header picker, Company column and fields, Companies screen, super-admin-only screens.
|
||||
- **Database:** additive SQL in the change folder plus a data step for existing users, events and emails; mirrored in `local/seed/03-colite.sql`.
|
||||
- **Unchanged:** services-auth, token format, members and the customer portal.
|
||||
@@ -0,0 +1,53 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Staff login
|
||||
|
||||
The system SHALL let an active admin user log in through the admin portal with company code, username and password, or with username and password and no company for a super admin, and SHALL return the user's name, roles, company, menu and whether a password change is required.
|
||||
|
||||
#### Scenario: Correct credentials
|
||||
|
||||
- **GIVEN** an active admin user `sales1` of active company `ins`
|
||||
- **WHEN** they submit company `ins`, username `sales1` and their password on the login page
|
||||
- **THEN** they are signed in and land on the portal home
|
||||
- **AND** the sidebar shows only the menu entries their roles grant
|
||||
|
||||
#### Scenario: Super admin
|
||||
|
||||
- **GIVEN** the super admin `admin`, who belongs to no company
|
||||
- **WHEN** they submit username `admin` and their password with the company left empty
|
||||
- **THEN** they are signed in
|
||||
|
||||
#### Scenario: Wrong password
|
||||
|
||||
- **WHEN** a user submits a wrong password
|
||||
- **THEN** `/api/admin/auth/login` responds 401
|
||||
- **AND** the login page shows an invalid-credentials message without saying whether the company or username exists
|
||||
|
||||
#### Scenario: Deactivated user
|
||||
|
||||
- **GIVEN** an admin user whose account is deactivated
|
||||
- **WHEN** they submit their correct password
|
||||
- **THEN** login is refused with a 401 and the page shows the same invalid-credentials message
|
||||
|
||||
#### Scenario: Member account
|
||||
|
||||
- **WHEN** a member (non-admin) account submits its correct credentials to the admin login
|
||||
- **THEN** login is refused with a 401
|
||||
|
||||
### Requirement: Forgot password
|
||||
|
||||
The system SHALL let a user request a temporary password by entering their company code, username and email on a public forgot-password page; a super admin leaves the company empty. The response SHALL be the same whether or not the details match an active admin user.
|
||||
|
||||
#### Scenario: Matching username and email
|
||||
|
||||
- **GIVEN** an active admin user `sales1` of company `ins` with email `sales1@example.com`
|
||||
- **WHEN** someone submits company `ins`, username `sales1` and `sales1@example.com`
|
||||
- **THEN** a temporary password is emailed to `sales1@example.com`
|
||||
- **AND** the user must change it at next login
|
||||
- **AND** the page shows "If the details match an account, we have emailed a temporary password."
|
||||
|
||||
#### Scenario: Non-matching details
|
||||
|
||||
- **WHEN** someone submits a company, username and email that do not match an active admin user
|
||||
- **THEN** no password changes and no email is sent
|
||||
- **AND** the page shows the same message as for a match
|
||||
@@ -0,0 +1,43 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Unlock
|
||||
|
||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames of their own company that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one of them. A super admin SHALL see and unlock locked usernames of every company, including attempts that match no company. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked.
|
||||
|
||||
#### Scenario: Unlock a locked username
|
||||
|
||||
- **GIVEN** INS user `sales1` is locked
|
||||
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` unlocks `sales1`
|
||||
- **THEN** `sales1` no longer appears in the locked list
|
||||
- **AND** `sales1` can sign in with the right password
|
||||
- **AND** an `UNLOCK_RESET` record for `sales1` names the admin
|
||||
|
||||
#### Scenario: Another company's locked user
|
||||
|
||||
- **GIVEN** CV user `sales2` is locked
|
||||
- **WHEN** an INS admin with `BO_LOGIN_SECURITY` lists locked users or unlocks `sales2` of CV
|
||||
- **THEN** `sales2` is not listed and the unlock answers 404
|
||||
|
||||
### Requirement: Lockout and password-rule settings
|
||||
|
||||
The system SHALL let an admin with `BO_LOGIN_SECURITY` read the lockout settings and the admin password rules, and SHALL let only a super admin change them, because they apply to every company. The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin.
|
||||
|
||||
#### Scenario: Change the lockout settings
|
||||
|
||||
- **WHEN** a super admin sets the maximum to 3 and the period to 30 minutes
|
||||
- **THEN** the next lock decision in every company uses 3 attempts in 30 minutes
|
||||
|
||||
#### Scenario: Invalid setting
|
||||
|
||||
- **WHEN** a super admin sets the maximum to 0
|
||||
- **THEN** the change is refused with a validation error and the settings stay as they were
|
||||
|
||||
#### Scenario: Change a password rule
|
||||
|
||||
- **WHEN** a super admin sets the minimum length rule to 10
|
||||
- **THEN** a new password of 9 characters is refused by every admin password check
|
||||
|
||||
#### Scenario: Company user changes settings
|
||||
|
||||
- **WHEN** an INS user with `BO_LOGIN_SECURITY` changes a lockout setting or a password rule
|
||||
- **THEN** the change is refused with 403 and the settings stay as they were
|
||||
@@ -0,0 +1,38 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Role list and edit
|
||||
|
||||
The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let only a super admin create and rename them, because roles are shared by every company. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
|
||||
|
||||
#### Scenario: Create role
|
||||
|
||||
- **WHEN** a super admin creates role `ROLE_SALES`
|
||||
- **THEN** it appears in the role list and can be assigned to users of any company
|
||||
|
||||
#### Scenario: Duplicate name
|
||||
|
||||
- **GIVEN** role `ROLE_SALES` exists
|
||||
- **WHEN** a super admin creates another role named `ROLE_SALES`
|
||||
- **THEN** the save is refused with a message
|
||||
|
||||
#### Scenario: Company user edits a role
|
||||
|
||||
- **WHEN** an INS user with `BO_ROLES` creates or renames a role
|
||||
- **THEN** the request is refused with 403 and nothing changes
|
||||
|
||||
### Requirement: Role permissions
|
||||
|
||||
The system SHALL let only a super admin choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. Admins with `BO_ROLES` who are not super admins SHALL see the grants read-only.
|
||||
|
||||
#### Scenario: Grant Users module
|
||||
|
||||
- **GIVEN** role `ROLE_SALES` without `BO_USERS`
|
||||
- **WHEN** a super admin grants `BO_USERS` to `ROLE_SALES` and saves
|
||||
- **THEN** users with `ROLE_SALES` in every company see Users in the sidebar after their next login or session refresh
|
||||
- **AND** `GET /api/admin/users` responds 200 for them
|
||||
|
||||
#### Scenario: Own role
|
||||
|
||||
- **GIVEN** an INS user who is not super admin and holds `ROLE_SALES` and `BO_ROLES`
|
||||
- **WHEN** they change the module grants of `ROLE_SALES`, or of any other role
|
||||
- **THEN** the save is refused with 403 and the grants stay as they were
|
||||
@@ -0,0 +1,44 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Company membership
|
||||
|
||||
Every admin user other than a super admin SHALL belong to exactly one company. A company user's new user SHALL belong to the creating user's company, whatever the request says. A super admin SHALL choose the company of a new user, or no company to create another super admin.
|
||||
|
||||
#### Scenario: Company in the request is ignored
|
||||
|
||||
- **WHEN** an INS user's create-user request carries the CV company id
|
||||
- **THEN** the new user belongs to INS
|
||||
|
||||
#### Scenario: Super admin chooses the company
|
||||
|
||||
- **WHEN** a super admin creates a user and chooses CV
|
||||
- **THEN** the new user belongs to CV
|
||||
|
||||
### Requirement: Create user
|
||||
|
||||
The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique within the user's company, so the same username or email may exist in another company. A username SHALL NOT contain `@`. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change and SHALL NOT be sent an email.
|
||||
|
||||
#### Scenario: New user
|
||||
|
||||
- **WHEN** an INS admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password
|
||||
- **THEN** the user is saved as active in INS with a pending password change
|
||||
- **AND** `sales1` can sign in with company `ins` and that password and must choose a new password before anything else
|
||||
- **AND** no email is sent
|
||||
|
||||
#### Scenario: Duplicate username
|
||||
|
||||
- **GIVEN** a user `sales1` exists in INS
|
||||
- **WHEN** an admin creates another INS user with username `sales1`
|
||||
- **THEN** the save is refused and the form shows that the username is taken
|
||||
|
||||
#### Scenario: Same username in another company
|
||||
|
||||
- **GIVEN** a user `sales1` exists in INS
|
||||
- **WHEN** a CV admin creates user `sales1` in CV
|
||||
- **THEN** the user is created
|
||||
|
||||
#### Scenario: Weak or mismatched initial password
|
||||
|
||||
- **WHEN** an admin creates a user with a password that fails the admin password rules, or that does not match its confirmation
|
||||
- **THEN** the save is refused with a message on the form
|
||||
- **AND** no user is created
|
||||
@@ -0,0 +1,128 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Companies
|
||||
|
||||
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of lowercase letters, digits and hyphens, compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
|
||||
|
||||
#### Scenario: Create a company
|
||||
|
||||
- **WHEN** a super admin creates company `CV` with code `cv`
|
||||
- **THEN** it is listed as active
|
||||
- **AND** staff can be created in it
|
||||
|
||||
#### Scenario: Duplicate code
|
||||
|
||||
- **GIVEN** a company with code `ins`
|
||||
- **WHEN** a super admin creates or renames another company to code `INS`
|
||||
- **THEN** the save is refused and the code is reported as taken
|
||||
|
||||
#### Scenario: Not a super admin
|
||||
|
||||
- **WHEN** company staff open the Companies page or call a companies endpoint
|
||||
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||
|
||||
### Requirement: Company sign-in
|
||||
|
||||
The system SHALL sign company staff in with company code, username and password, and SHALL sign super admins in with username and password and no company. The answer SHALL be the same for a wrong or unknown company, an inactive company, an unknown user and a wrong password. A user's sessions SHALL end when their company is deactivated or its code is changed.
|
||||
|
||||
#### Scenario: Staff sign-in
|
||||
|
||||
- **GIVEN** an active user `john` in active company `ins`
|
||||
- **WHEN** they sign in with company `ins`, username `john` and the right password
|
||||
- **THEN** they are signed in as `john` of INS
|
||||
|
||||
#### Scenario: Same username in two companies
|
||||
|
||||
- **GIVEN** a user `john` in INS and a different user `john` in CV
|
||||
- **WHEN** someone signs in with company `cv`, username `john` and CV John's password
|
||||
- **THEN** they are signed in as CV's John and see only CV data
|
||||
|
||||
#### Scenario: Wrong company
|
||||
|
||||
- **WHEN** INS's `john` signs in with company `cv` or a code that does not exist
|
||||
- **THEN** login is refused with the same invalid-credentials answer as a wrong password
|
||||
|
||||
#### Scenario: Inactive company
|
||||
|
||||
- **GIVEN** company CV is deactivated
|
||||
- **WHEN** a CV user signs in with the right password, or uses an existing session
|
||||
- **THEN** the sign-in is refused with the invalid-credentials answer and the session ends
|
||||
|
||||
#### Scenario: Code changed
|
||||
|
||||
- **GIVEN** a signed-in user of the company with code `ins`
|
||||
- **WHEN** a super admin changes that code to `ins-my`
|
||||
- **THEN** the user's session ends
|
||||
- **AND** they sign in again with company `ins-my`
|
||||
|
||||
### Requirement: Super admins
|
||||
|
||||
A super admin SHALL be an admin user who belongs to no company and holds the super admin role. Only a super admin SHALL create another super admin. The super admin role SHALL NOT be granted to a user who belongs to a company, and every admin user who is not a super admin SHALL belong to a company.
|
||||
|
||||
#### Scenario: Create a second super admin
|
||||
|
||||
- **WHEN** a super admin creates a user with no company
|
||||
- **THEN** the user is created as a super admin and signs in without a company
|
||||
|
||||
#### Scenario: Super admin role for company staff
|
||||
|
||||
- **WHEN** anyone assigns the super admin role to a user of INS
|
||||
- **THEN** the save is refused with a message
|
||||
|
||||
### Requirement: Company data is separated
|
||||
|
||||
The system SHALL limit every admin list, search, export, detail, create, edit and action to the caller's company for: users, events, event teams, event leads, leads, emails, login history, locked users and audit events. A record of another company SHALL answer 404, as if it did not exist.
|
||||
|
||||
#### Scenario: Lists show own company only
|
||||
|
||||
- **GIVEN** leads, events and users in INS and in CV
|
||||
- **WHEN** an INS user with the matching modules opens Leads, Events or Users
|
||||
- **THEN** only INS records are listed
|
||||
- **AND** an export contains only INS leads
|
||||
|
||||
#### Scenario: Another company's record by id
|
||||
|
||||
- **GIVEN** a CV lead, event, user or email
|
||||
- **WHEN** an INS user requests it, edits it or acts on it by its id
|
||||
- **THEN** the answer is 404 and nothing changes
|
||||
|
||||
#### Scenario: Same phone in two companies
|
||||
|
||||
- **GIVEN** INS has a lead with mobile `+60123456789`
|
||||
- **WHEN** a CV user captures a lead with the same mobile at a CV event
|
||||
- **THEN** a new CV lead is created and flagged New
|
||||
- **AND** the INS lead is unchanged
|
||||
|
||||
### Requirement: Super admin sees all companies
|
||||
|
||||
The system SHALL show super admins every company's records by default, SHALL let them narrow any scoped list to one company, and SHALL show each record's company in mixed lists. Creating a company-owned record (user, event, event lead) SHALL require a super admin to choose the company.
|
||||
|
||||
#### Scenario: Mixed list
|
||||
|
||||
- **WHEN** a super admin opens Leads with all companies selected
|
||||
- **THEN** INS and CV leads are listed together with a Company column
|
||||
|
||||
#### Scenario: Pick a company
|
||||
|
||||
- **WHEN** a super admin picks CV in the company picker
|
||||
- **THEN** scoped lists show CV records only
|
||||
|
||||
#### Scenario: Create without a company
|
||||
|
||||
- **WHEN** a super admin creates an event without choosing a company
|
||||
- **THEN** the save is refused and the form asks for a company
|
||||
|
||||
### Requirement: Company of login and audit records
|
||||
|
||||
An audit event and a login-history record SHALL belong to the company of the user who acted, or of the user who tried to sign in when the given company and username match a user. Records with no company SHALL be visible to super admins only.
|
||||
|
||||
#### Scenario: Super admin edits a company record
|
||||
|
||||
- **WHEN** a super admin edits an INS lead
|
||||
- **THEN** the audit event has no company
|
||||
- **AND** INS staff with Audit log do not see it, and super admins do
|
||||
|
||||
#### Scenario: Failed sign-in with an unknown company
|
||||
|
||||
- **WHEN** someone fails to sign in with a company code that does not exist
|
||||
- **THEN** the login-history record has no company and only super admins see it
|
||||
@@ -0,0 +1,34 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Interest list
|
||||
|
||||
The system SHALL keep one interest list shared by all companies. Admins with `BO_INTERESTS` SHALL see the list, and only a super admin SHALL add, rename, reorder, deactivate and reactivate interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case. Interests SHALL NOT be deletable.
|
||||
|
||||
#### Scenario: Add interest
|
||||
|
||||
- **WHEN** a super admin adds `Kitchen appliances`
|
||||
- **THEN** it is listed as active
|
||||
- **AND** staff of every company can tag leads with it
|
||||
|
||||
#### Scenario: Duplicate name
|
||||
|
||||
- **GIVEN** an interest `Kitchen appliances`
|
||||
- **WHEN** a super admin adds `kitchen APPLIANCES`
|
||||
- **THEN** the save is refused and the name is reported as a duplicate
|
||||
|
||||
#### Scenario: Deactivate
|
||||
|
||||
- **GIVEN** an active interest `Cookware`
|
||||
- **WHEN** a super admin deactivates it
|
||||
- **THEN** it is still listed, marked inactive
|
||||
- **AND** it is no longer offered when capturing a lead in any company
|
||||
|
||||
#### Scenario: Company user edits
|
||||
|
||||
- **WHEN** an INS user with `BO_INTERESTS` adds, renames or deactivates an interest
|
||||
- **THEN** the request is refused with 403 and the list is unchanged
|
||||
|
||||
#### Scenario: No module
|
||||
|
||||
- **WHEN** an admin without `BO_INTERESTS` opens the Interests page or calls an interests endpoint
|
||||
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Co-Lite change add-company-scoping: company code and status; INS and CV.
|
||||
-- Target: `service-system`.`company`. Run once, after the release package, before 02 and 03.
|
||||
-- DDL: run with a user that may alter tables, not the services' user.
|
||||
USE `service-system`;
|
||||
|
||||
ALTER TABLE `company`
|
||||
ADD COLUMN `code` varchar(20) NULL AFTER `name`,
|
||||
ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`;
|
||||
|
||||
-- The existing company (all current data) becomes INS.
|
||||
UPDATE `company` SET `name` = 'INS', `code` = 'ins' WHERE `id` = 1;
|
||||
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'cv', 'A');
|
||||
|
||||
ALTER TABLE `company`
|
||||
MODIFY COLUMN `code` varchar(20) NOT NULL,
|
||||
ADD UNIQUE KEY `uk_company_code` (`code`);
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Co-Lite change add-company-scoping: company on events and emails; one shared interest list.
|
||||
-- Run once, after 01. DDL: run with a user that may alter tables.
|
||||
USE `service-counter`;
|
||||
|
||||
ALTER TABLE `event` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_event_company` (`company_id`);
|
||||
UPDATE `event` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||
|
||||
-- Interests are shared by every company: unique by name (case-insensitive collation); company_id kept, unused.
|
||||
ALTER TABLE `interest`
|
||||
DROP INDEX `uk_interest_company_name`,
|
||||
MODIFY COLUMN `company_id` bigint NULL,
|
||||
ADD UNIQUE KEY `uk_interest_name` (`name`);
|
||||
|
||||
USE `service-email`;
|
||||
|
||||
ALTER TABLE `email` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_email_company` (`company_id`);
|
||||
UPDATE `email` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Co-Lite change add-company-scoping: admin sign-in names.
|
||||
-- Super admins (role 1) belong to no company and keep their username.
|
||||
-- Every other admin user keeps company 1 (INS) and is renamed username@ins; they sign in with company "ins".
|
||||
-- Ends every admin session (token subjects no longer match). Run once, after 01 and 02.
|
||||
USE `service-system`;
|
||||
|
||||
-- Stop if any admin username already contains '@': it would be ambiguous after the rename.
|
||||
DROP PROCEDURE IF EXISTS `colite_check_admin_usernames`;
|
||||
DELIMITER //
|
||||
CREATE PROCEDURE `colite_check_admin_usernames`()
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM `user` WHERE `type` = 'A' AND `username` LIKE '%@%') THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An admin username contains @; rename it before running this script';
|
||||
END IF;
|
||||
END //
|
||||
DELIMITER ;
|
||||
CALL `colite_check_admin_usernames`();
|
||||
DROP PROCEDURE `colite_check_admin_usernames`;
|
||||
|
||||
UPDATE `user` u SET u.`company_id` = NULL
|
||||
WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||
|
||||
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins')
|
||||
WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Co-Lite change add-company-scoping: rollback of 01-03. CV's data, if any, stays in its tables with company 2.
|
||||
USE `service-system`;
|
||||
UPDATE `user` SET `username` = SUBSTRING_INDEX(`username`, '@', 1) WHERE `type` = 'A' AND `username` LIKE '%@%';
|
||||
UPDATE `user` SET `company_id` = 1 WHERE `type` = 'A' AND `company_id` IS NULL;
|
||||
ALTER TABLE `company` DROP INDEX `uk_company_code`, DROP COLUMN `status`, DROP COLUMN `code`;
|
||||
UPDATE `company` SET `name` = 'Co-Lite' WHERE `id` = 1;
|
||||
|
||||
USE `service-counter`;
|
||||
ALTER TABLE `event` DROP KEY `idx_event_company`, DROP COLUMN `company_id`;
|
||||
UPDATE `interest` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||
ALTER TABLE `interest` DROP INDEX `uk_interest_name`, MODIFY COLUMN `company_id` bigint NOT NULL,
|
||||
ADD UNIQUE KEY `uk_interest_company_name` (`company_id`, `name`);
|
||||
|
||||
USE `service-email`;
|
||||
ALTER TABLE `email` DROP KEY `idx_email_company`, DROP COLUMN `company_id`;
|
||||
@@ -0,0 +1,124 @@
|
||||
# Tasks
|
||||
|
||||
Design: `design.md`. All tasks run serially, ordered so that sign-in keeps working after each one. Every scoped endpoint gets a test where another company's record answers 404 (or is absent from the list).
|
||||
|
||||
## 1. Data
|
||||
|
||||
- [x] 1.1 SQL and local seed (design decisions 3, 7, 8 and 11).
|
||||
- Files in `sql/`:
|
||||
- `01-company-code-status.sql`: add `code` and `status`; set company 1 to `INS`/`ins`; insert `CV`/`cv`.
|
||||
- `02-company-columns.sql`: add `company_id` to `event` and `email`; set existing rows to company 1; move the interest unique key to `(name)`.
|
||||
- `03-admin-login-names.sql`: stop if any admin username contains `@`; set `admin` to company NULL; rewrite the other admin usernames to `username@ins`.
|
||||
- `99-rollback.sql`.
|
||||
- Mirror them in `local/seed/03-colite.sql`, apply them locally, and confirm `admin` still signs in.
|
||||
- Scope: `local/**`, `openspec/changes/add-company-scoping/sql/**`
|
||||
- Verify: `select` shows the codes, the NULL-company `admin`, the rewritten usernames and the new columns.
|
||||
|
||||
## 2. Backend services
|
||||
|
||||
- [x] 2.1 services-system: companies, users and login security (decisions 1, 2, 3, 5 and 9).
|
||||
- Tests first:
|
||||
- company list, create, edit; duplicate code (ignoring case) refused; code format validated;
|
||||
- rename-code rewrites only that company's admin usernames, in one transaction;
|
||||
- user lookups return the company code and status;
|
||||
- the user search filters by company when given;
|
||||
- email uniqueness is per company;
|
||||
- role 1 cannot be saved on a user with a company;
|
||||
- login history and locked users filter by company, and NULL-company rows appear only for "all".
|
||||
- Scope: `solvway-services-system/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-system -am verify`
|
||||
- [x] 2.2 services-counter: events, leads, event leads and interests (decisions 6, 7 and 8).
|
||||
- Tests first:
|
||||
- an event is saved with its company and listed by company, or for all when none is given;
|
||||
- lead and event-lead lists accept "all companies";
|
||||
- detail lookups return the record's company;
|
||||
- interests are one list, unique by name ignoring case.
|
||||
- Scope: `solvway-services-counter/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-counter -am verify`
|
||||
- [x] 2.3 service-email and services-log (decisions 7 and 9).
|
||||
- Tests first:
|
||||
- an email saved with a company keeps it, and the email search filters by company;
|
||||
- the audit search filters by company, and NULL-company rows appear only for "all".
|
||||
- Scope: `solvway-services-email/src/**`, `solvway-services-log/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-email,solvway-services-log -am verify`
|
||||
|
||||
## 3. mobile-api
|
||||
|
||||
- [x] 3.1 Sign-in, company scope and Companies API (decisions 1, 3, 4 and 5).
|
||||
- Tests first:
|
||||
- login and forgot-password build the login name from company and username; a blank company means a super admin;
|
||||
- a wrong company, an inactive company and an unknown user all give `BAD_LOGIN`;
|
||||
- the session guard ends an inactive company's sessions;
|
||||
- `isSuper` needs both no company and role 1;
|
||||
- `scope` ignores a staff request's company;
|
||||
- the Companies API is super admin only;
|
||||
- the login response carries the company and `isSuper`.
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- [x] 3.2 Users, roles, interests and login-security settings (decisions 1, 4 and 8).
|
||||
- Tests first:
|
||||
- users are listed, created and edited within the scope, and another company's user answers 404;
|
||||
- a username with `@` is refused;
|
||||
- a super admin must choose a company or create a super admin;
|
||||
- role 1 is refused for company users;
|
||||
- role create, rename and grants, interest writes and lockout or password-rule changes answer 403 for company staff;
|
||||
- unlock works only within the caller's company.
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- [x] 3.3 Events, leads, event leads and exports (decision 6).
|
||||
- Tests first:
|
||||
- each list and export is limited to the scope;
|
||||
- another company's event, lead or event lead answers 404 on detail, edit, capture and export;
|
||||
- a super admin capture or event create without a company is refused;
|
||||
- the event team only offers users of the event's company.
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- [x] 3.4 Emails, login history and audit log (decisions 7 and 9).
|
||||
- Tests first:
|
||||
- each is limited to the scope;
|
||||
- emails for a user carry that user's company;
|
||||
- another company's email or audit event answers 404.
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- Live check on the local stack:
|
||||
- INS and CV users each see only their own data;
|
||||
- `admin` sees both;
|
||||
- a CV record by id answers 404 to INS.
|
||||
|
||||
## 4. Portal
|
||||
|
||||
- [x] 4.1 Sign-in, session and Companies screen (decision 10).
|
||||
- Tests first:
|
||||
- the login and forgot-password pages send company, username and password, and a blank company is allowed;
|
||||
- the auth context holds `isSuper` and the company;
|
||||
- `/companies` lists, creates and edits companies, warns before a code change, and is refused for non-super users.
|
||||
- Scope: `solvway-admin-portal/app/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||
- [x] 4.2 Company picker, Company column, company fields and super-admin-only screens (decision 10).
|
||||
- Tests first:
|
||||
- the picker is shown only to super admins and feeds the list queries;
|
||||
- the Company column appears for "All companies";
|
||||
- user, event and capture forms show Company for super admins only;
|
||||
- Roles, Interests and the Login security Settings tab are read-only or hidden for company staff.
|
||||
- Scope: `solvway-admin-portal/app/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||
|
||||
## 5. Check and docs
|
||||
|
||||
- [x] 5.1 Browser check and handover.
|
||||
- Playwright on the local stack:
|
||||
- `admin` creates CV users and a CV event, then switches the picker between all, INS and CV;
|
||||
- an INS user and a CV user with the same username each sign in with their company and see only their own leads, events, users, emails, login history and audit log;
|
||||
- an INS user opening a CV record by URL sees not-found;
|
||||
- renaming CV's code ends the CV user's session;
|
||||
- deactivating CV blocks its sign-in;
|
||||
- check at 1280 px and 360 px.
|
||||
- Docs, in `docs/deployment.md`:
|
||||
- section 3: the new SQL, and that it ends every session;
|
||||
- section 10: company sign-in and super admins.
|
||||
- Scope: `docs/deployment.md`
|
||||
- Verify: screenshots, and the steps above observed.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Whole-branch review, with every `/api/admin/**` handler checked for scoping. Then push, PR to main and merge, and archive on its own branch.
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }));
|
||||
|
||||
describe("POST /api/auth/forgot-password company", () => {
|
||||
it("forwards a trimmed company", async () => {
|
||||
await POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify({ company: " ins ", username: "john", email: "j@x.com" }) }) as never);
|
||||
expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", email: "j@x.com" });
|
||||
});
|
||||
});
|
||||
@@ -5,11 +5,15 @@ import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
// the answer must not reveal whether the account exists, so upstream errors are never forwarded.
|
||||
// Same-origin and body-size checks are enforced for every /api write by middleware.
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = (await req.json().catch(() => ({}))) as { username?: unknown; email?: unknown };
|
||||
const body = (await req.json().catch(() => ({}))) as { company?: unknown; username?: unknown; email?: unknown };
|
||||
const username = typeof body.username === "string" ? body.username.trim() : "";
|
||||
const email = typeof body.email === "string" ? body.email.trim() : "";
|
||||
const company = typeof body.company === "string" ? body.company.trim() : "";
|
||||
if (username && email) {
|
||||
await callMobileApi("/api/admin/auth/forgot-password", { method: "POST", body: { username, email } });
|
||||
await callMobileApi("/api/admin/auth/forgot-password", {
|
||||
method: "POST",
|
||||
body: { ...(company && { company }), username, email },
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), setSession: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ setSession: mocks.setSession }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
const req = (body: unknown) =>
|
||||
new Request("http://localhost/api/auth/login", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters<typeof POST>[0];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset().mockResolvedValue({
|
||||
ok: true,
|
||||
data: { token: "t", name: "N", roles: [], aclMenu: {}, resetPasswordRequired: "false" },
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/login company", () => {
|
||||
it("forwards a trimmed company", async () => {
|
||||
await POST(req({ company: " ins ", username: "john", password: "pw" }));
|
||||
expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", password: "pw" });
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ import type { AdminLoginResponse } from "@/app/lib/types";
|
||||
// echoed back here, keeping this handler's response minimal.
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const { username, password } = body as { username?: string; password?: string };
|
||||
const { company, username, password } = body as { company?: string; username?: string; password?: string };
|
||||
|
||||
const identifier = (username ?? "").trim();
|
||||
if (!identifier || !password) {
|
||||
@@ -23,7 +23,8 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
const result = await callMobileApi<AdminLoginResponse>("/api/admin/auth/login", {
|
||||
method: "POST",
|
||||
body: { username: identifier, password },
|
||||
// A blank company is a super-admin login: omit the key rather than send "".
|
||||
body: { ...(company?.trim() && { company: company.trim() }), username: identifier, password },
|
||||
// Real-client context for the login_audit trail (X-Client-Ip / X-Client-User-Agent).
|
||||
headers: clientContextHeaders(req),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: vi.fn().mockResolvedValue("jwt") }));
|
||||
vi.mock("@/app/lib/server/sessionRefresh", () => ({ maybeRefreshSession: vi.fn() }));
|
||||
|
||||
import { GET } from "./route";
|
||||
|
||||
beforeEach(() => mocks.callMobileApi.mockReset());
|
||||
|
||||
describe("GET /api/auth/session company", () => {
|
||||
it("passes companyId, companyCode and isSuper through", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({
|
||||
ok: true,
|
||||
data: { id: 1, username: "john@ins", name: "J", roles: [], aclMenu: {}, companyId: 7, companyCode: "ins", isSuper: false },
|
||||
});
|
||||
const res = await GET(new Request("http://localhost/api/auth/session") as never);
|
||||
expect(await res.json()).toMatchObject({ companyId: 7, companyCode: "ins", isSuper: false });
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,9 @@ export async function GET(req: NextRequest) {
|
||||
const result = await callMobileApi<AdminMeResponse>("/api/admin/me", { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
|
||||
const { id, username, name, roles, aclMenu, branch } = result.data;
|
||||
return NextResponse.json({ id, username, name, roles, aclMenu, branch: branch ?? null });
|
||||
const { id, username, name, roles, aclMenu, branch, companyId, companyCode, isSuper } = result.data;
|
||||
return NextResponse.json({
|
||||
id, username, name, roles, aclMenu, branch: branch ?? null,
|
||||
companyId, companyCode, isSuper,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
const call = (body: unknown) =>
|
||||
POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify(body) }) as never, { params: Promise.resolve({ id: "7" }) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("POST /api/companies/[id]/code", () => {
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await call({ code: "new" })).status).toBe(401);
|
||||
});
|
||||
|
||||
it("forwards the code to /api/admin/companies/{id}/code", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 7, code: "new" } });
|
||||
await call({ code: "new" });
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies/7/code", {
|
||||
method: "POST",
|
||||
body: { code: "new" },
|
||||
token: "jwt",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
import type { AdminCompany } from "@/app/lib/types";
|
||||
|
||||
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id } = await params;
|
||||
const { code } = (await req.json().catch(() => ({}))) as { code?: string };
|
||||
const result = await callMobileApi<AdminCompany>(`/api/admin/companies/${encodeURIComponent(id)}/code`, {
|
||||
method: "POST",
|
||||
body: { code },
|
||||
token,
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { GET, POST } from "./route";
|
||||
|
||||
const post = (body: unknown) =>
|
||||
new Request("http://localhost/api/companies", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters<typeof POST>[0];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("/api/companies", () => {
|
||||
it("GET returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await GET()).status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("GET forwards to /api/admin/companies", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] });
|
||||
await GET();
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("POST forwards id, name, code and status", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1 } });
|
||||
await POST(post({ id: 1, name: "Ins", code: "ins", status: "A", extra: "x" }));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", {
|
||||
method: "POST",
|
||||
body: { id: 1, name: "Ins", code: "ins", status: "A" },
|
||||
token: "jwt",
|
||||
});
|
||||
});
|
||||
|
||||
it("POST relays a 409 from the API", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "Code already used" });
|
||||
const res = await POST(post({ name: "Ins", code: "ins", status: "A" }));
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).error).toBe("Code already used");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
import type { AdminCompany } from "@/app/lib/types";
|
||||
|
||||
// Super admin only; the mobile-api answers 403 for anyone else, and validation (400) and duplicate codes (409) too.
|
||||
export async function GET() {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<AdminCompany[]>("/api/admin/companies", { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id, name, code, status } = (await req.json().catch(() => ({}))) as Partial<AdminCompany>;
|
||||
const result = await callMobileApi<AdminCompany>("/api/admin/companies", {
|
||||
method: "POST",
|
||||
body: { id, name, code, status },
|
||||
token,
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -16,6 +16,8 @@ export async function GET(req: NextRequest) {
|
||||
if (enabled !== "Y" && enabled !== "N") return badRequest("enabled must be Y or N.");
|
||||
qs.set("enabled", enabled);
|
||||
}
|
||||
const companyId = params.get("companyId");
|
||||
if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId);
|
||||
qs.set("page", params.get("page") ?? "0");
|
||||
qs.set("size", params.get("size") ?? "20");
|
||||
const sortBy = params.get("sortBy");
|
||||
|
||||
@@ -7,7 +7,10 @@ export async function GET(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
|
||||
const result = await callMobileApi<Record<string, unknown>>("/api/admin/events/salesperson-options", { token });
|
||||
const companyId = new URL(req.url).searchParams.get("companyId");
|
||||
const qs = new URLSearchParams();
|
||||
if (companyId && /^\d+$/.test(companyId)) qs.set("companyId", companyId);
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/events/salesperson-options${qs.size ? `?${qs}` : ""}`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("/api/login-security unlock", () => {
|
||||
it("POST forwards the companyId query to the upstream URL", async () => {
|
||||
const req = new Request("http://localhost/api/login-security/locked/a/unlock?companyId=2", { method: "POST", body: "{}", headers: { "Content-Type": "application/json" } });
|
||||
await POST(req as unknown as Parameters<typeof POST>[0], { params: Promise.resolve({ path: ["locked", "a", "unlock"] }) });
|
||||
expect(mocks.callMobileApi.mock.calls[0][0]).toBe("/api/admin/login-security/locked/a/unlock?companyId=2");
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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") => <span className={`block truncate ${max}`} title={text ?? undefined}>{text}</span>;
|
||||
const columns = useMemo<ColumnDef<AuditEvent, unknown>[]>(
|
||||
() => [
|
||||
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<AuditEvent, unknown>] : []),
|
||||
{ id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => <span className="whitespace-nowrap">{formatDate(row.original.occurredAt)}</span> },
|
||||
{ id: "actor", header: t("AuditWho"), enableSorting: false, cell: ({ row }) => cut(row.original.actor, "max-w-32") },
|
||||
{ id: "module", header: t("AuditModule"), enableSorting: false, cell: ({ row }) => (row.original.module ? t(row.original.module) : "—") },
|
||||
@@ -73,7 +78,7 @@ function AuditLogContent() {
|
||||
},
|
||||
{ accessorKey: "clientIp", header: t("LsIp"), enableSorting: false },
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import CompaniesPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
|
||||
});
|
||||
|
||||
describe("CompaniesPage fixes", () => {
|
||||
it("does not post a code change when the new code equals the current code", async () => {
|
||||
render(<CompaniesPage />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Change code" }));
|
||||
const input = screen.getByLabelText("New code");
|
||||
await userEvent.clear(input);
|
||||
await userEvent.type(input, " INS ");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Confirm" }));
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("alert")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the API error text of a failed load directly", async () => {
|
||||
mocks.apiGet.mockRejectedValue(new Error("Forbidden for you"));
|
||||
render(<CompaniesPage />);
|
||||
expect(await screen.findByText("Forbidden for you")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import CompaniesPage from "./page";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const ROWS = [
|
||||
{ id: 1, name: "Insight", code: "ins", status: "A" },
|
||||
{ id: 2, name: "Clever", code: "cv", status: "I" },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue(ROWS);
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
|
||||
});
|
||||
|
||||
describe("CompaniesPage", () => {
|
||||
it("lists name, code and status", async () => {
|
||||
render(<CompaniesPage />);
|
||||
const row = (await screen.findByText("Insight")).closest("tr")!;
|
||||
expect(within(row).getByText("ins")).toBeInTheDocument();
|
||||
expect(within(row).getByText("Active")).toBeInTheDocument();
|
||||
expect(within(screen.getByText("Clever").closest("tr")!).getByText("Inactive")).toBeInTheDocument();
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/companies");
|
||||
});
|
||||
|
||||
it("creates a company with name, code and status", async () => {
|
||||
mocks.apiPost.mockResolvedValue({ id: 3 });
|
||||
render(<CompaniesPage />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /add company/i }));
|
||||
await userEvent.type(screen.getByLabelText("Name"), " Acme ");
|
||||
await userEvent.type(screen.getByLabelText("Code"), "acme");
|
||||
await userEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { name: "Acme", code: "acme", status: "A" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("edits name and status only, with no code field", async () => {
|
||||
mocks.apiPost.mockResolvedValue({ id: 1 });
|
||||
render(<CompaniesPage />);
|
||||
const row = (await screen.findByText("Insight")).closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: "Edit" }));
|
||||
expect(screen.queryByLabelText("Code")).toBeNull();
|
||||
const name = screen.getByLabelText("Name");
|
||||
await userEvent.clear(name);
|
||||
await userEvent.type(name, "Insight Ltd");
|
||||
await userEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
await waitFor(() =>
|
||||
expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { id: 1, name: "Insight Ltd", status: "A" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("shows an API 409 message on the form", async () => {
|
||||
mocks.apiPost.mockRejectedValue(new ApiError("Code already used", 409));
|
||||
render(<CompaniesPage />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /add company/i }));
|
||||
await userEvent.type(screen.getByLabelText("Name"), "Acme");
|
||||
await userEvent.type(screen.getByLabelText("Code"), "ins");
|
||||
await userEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
expect(await screen.findByText("Code already used")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("warns before a code change, then posts the new code", async () => {
|
||||
mocks.apiPost.mockResolvedValue({ id: 1, code: "new" });
|
||||
render(<CompaniesPage />);
|
||||
const row = (await screen.findByText("Insight")).closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /change code/i }));
|
||||
expect(
|
||||
screen.getByText("Changing the code changes every staff login name of this company and signs them out."),
|
||||
).toBeInTheDocument();
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
const code = screen.getByLabelText("New code");
|
||||
await userEvent.clear(code);
|
||||
await userEvent.type(code, "new");
|
||||
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
|
||||
await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies/1/code", { code: "new" }));
|
||||
});
|
||||
|
||||
it("is refused for non-super users", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false });
|
||||
render(<CompaniesPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.apiGet).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { NotAuthorized } from "@/app/lib/RequireModule";
|
||||
import { changeAdminCompanyCode, listAdminCompanies, saveAdminCompany } from "@/app/lib/services/adminCompanies";
|
||||
import type { AdminCompany } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
type Mode = "form" | "code";
|
||||
type DialogState = { mode: Mode; company: AdminCompany };
|
||||
|
||||
const NEW_COMPANY: AdminCompany = { name: "", code: "", status: "A" };
|
||||
|
||||
// ponytail: the API message is shown as returned (not translated); add codes to the API if that matters.
|
||||
function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClose: () => void; onSaved: () => void }) {
|
||||
const t = useT();
|
||||
const { mode, company } = state;
|
||||
const [form, setForm] = useState<AdminCompany>(company);
|
||||
const [newCode, setNewCode] = useState(company.code);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (mode === "form" && !form.name.trim()) return setError(t("CompNameRequired"));
|
||||
if ((mode === "code" ? newCode : form.code).trim() === "" && (mode === "code" || !form.id)) {
|
||||
return setError(t("CompCodeRequired"));
|
||||
}
|
||||
if (mode === "code" && newCode.trim().toLowerCase() === company.code.toLowerCase()) {
|
||||
return setError(t("CompCodeUnchanged"));
|
||||
}
|
||||
setError(null);
|
||||
setSaving(true);
|
||||
try {
|
||||
if (mode === "code") await changeAdminCompanyCode(company.id!, newCode.trim());
|
||||
else if (form.id) await saveAdminCompany({ id: form.id, name: form.name.trim(), status: form.status });
|
||||
else await saveAdminCompany({ name: form.name.trim(), code: form.code.trim(), status: form.status });
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error && err.message ? err.message : t("CompSaveFailed"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{mode === "code" ? t("CompChangeCode") : form.id ? t("CompEdit") : t("CompAdd")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{error && (
|
||||
<div className="text-sm text-destructive" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
{mode === "code" ? (
|
||||
<>
|
||||
<p className="text-sm">{t("CompChangeCodeWarning")}</p>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company-new-code">{t("CompNewCode")}</Label>
|
||||
<Input id="company-new-code" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company-name">{t("Name")}</Label>
|
||||
<Input id="company-name" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} disabled={saving} />
|
||||
</div>
|
||||
{!form.id && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company-code">{t("Code")}</Label>
|
||||
<Input id="company-code" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company-status">{t("Status")}</Label>
|
||||
<select
|
||||
id="company-status"
|
||||
value={form.status}
|
||||
onChange={(e) => setForm((f) => ({ ...f, status: e.target.value as AdminCompany["status"] }))}
|
||||
disabled={saving}
|
||||
className="h-9 w-full rounded-md border border-input bg-transparent px-3 text-sm"
|
||||
>
|
||||
<option value="A">{t("CompActive")}</option>
|
||||
<option value="I">{t("CompInactive")}</option>
|
||||
</select>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={saving}>
|
||||
{mode === "code" ? t("CompConfirm") : t("Save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function CompaniesPageContent() {
|
||||
const t = useT();
|
||||
const [companies, setCompanies] = useState<AdminCompany[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const [dialog, setDialog] = useState<DialogState | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const size = pageSize ?? MIN_PAGE_SIZE;
|
||||
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the reloadKey-triggered fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listAdminCompanies()
|
||||
.then((result) => !cancelled && setCompanies(result))
|
||||
.catch((err: unknown) => !cancelled && setError(err instanceof Error && err.message ? err.message : t("CompLoadFailed")))
|
||||
.finally(() => !cancelled && setLoading(false));
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [reloadKey, t]);
|
||||
|
||||
const columns = useMemo<ColumnDef<AdminCompany, unknown>[]>(
|
||||
() => [
|
||||
{ accessorKey: "name", header: t("Name") },
|
||||
{ accessorKey: "code", header: t("Code") },
|
||||
{
|
||||
accessorKey: "status",
|
||||
header: t("Status"),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.status === "A" ? "positive" : "neutral"}>
|
||||
{row.original.status === "A" ? t("CompActive") : t("CompInactive")}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: t("CatActions"),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "form", company: row.original })}>
|
||||
{t("Edit")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setDialog({ mode: "code", company: row.original })}>
|
||||
{t("CompChangeCode")}
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("BO_COMPANIES")}
|
||||
actions={
|
||||
<Button onClick={() => setDialog({ mode: "form", company: NEW_COMPANY })}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("CompAdd")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={error} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
<DataTable
|
||||
label={t("BO_COMPANIES")}
|
||||
columns={columns}
|
||||
data={companies.slice((page - 1) * size, page * size)}
|
||||
total={companies.length}
|
||||
page={page}
|
||||
pageSize={size}
|
||||
onPageChange={setPage}
|
||||
tableRef={tableRef}
|
||||
isLoading={loading}
|
||||
rowKey={(r) => String(r.id)}
|
||||
empty={<EmptyState title={t("CompNone")} />}
|
||||
/>
|
||||
|
||||
{dialog && <CompanyDialog state={dialog} onClose={() => setDialog(null)} onSaved={refetch} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Gated by isSuper (UX only; the API refuses everyone else), not by a module.
|
||||
export default function CompaniesPage() {
|
||||
const { isSuper, loading } = useAdminAuth();
|
||||
if (loading) return null;
|
||||
return isSuper ? <CompaniesPageContent /> : <NotAuthorized />;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
matchLead: vi.fn(),
|
||||
listEventSalespeople: vi.fn(),
|
||||
listEventLeadEvents: vi.fn(),
|
||||
listEventLeadInterests: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
useCompanyScope: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
matchLead: mocks.matchLead,
|
||||
listEventSalespeople: mocks.listEventSalespeople,
|
||||
listEventLeadEvents: mocks.listEventLeadEvents,
|
||||
listEventLeadInterests: mocks.listEventLeadInterests,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => ({
|
||||
...(await import("@/test/memoryRouter")).navigationMock,
|
||||
useParams: () => ({ eventUuid: "evt-1" }),
|
||||
}));
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import NewEventLeadPage from "./event-leads/[eventUuid]/new/page";
|
||||
|
||||
const COMPANIES = [
|
||||
{ id: 1, name: "Ins Co", code: "INS", status: "A" },
|
||||
{ id: 2, name: "CV Co", code: "CV", status: "A" },
|
||||
];
|
||||
const scope = (companyId?: number) => ({ companyId, companies: COMPANIES, showCompanyColumn: false, codeOf: () => "", setCompanyId: vi.fn() });
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads/evt-1/new");
|
||||
mocks.matchLead.mockReset().mockResolvedValue({ mobile: "+65911", email: "a@b.com", candidates: [] });
|
||||
mocks.listEventSalespeople.mockReset().mockResolvedValue([]);
|
||||
mocks.listEventLeadEvents.mockReset().mockResolvedValue([{ uuid: "evt-1", name: "Expo", companyId: 2 }]);
|
||||
mocks.listEventLeadInterests.mockReset().mockResolvedValue([]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
|
||||
mocks.useCompanyScope.mockReset().mockReturnValue(scope(2));
|
||||
});
|
||||
|
||||
describe("event-lead capture company", () => {
|
||||
it("shows no Company picker to a super admin and sends the event's own company with the lead match", async () => {
|
||||
mocks.useCompanyScope.mockReturnValue(scope());
|
||||
const user = userEvent.setup();
|
||||
render(<NewEventLeadPage />);
|
||||
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "Next" })).toBeEnabled());
|
||||
await user.type(screen.getByLabelText("Mobile"), "91111111");
|
||||
await user.type(screen.getByLabelText("Email"), "a@b.com");
|
||||
await user.click(screen.getByRole("button", { name: "Next" }));
|
||||
await waitFor(() => expect(mocks.matchLead).toHaveBeenCalledWith("evt-1", expect.objectContaining({ email: "a@b.com" }), 2));
|
||||
});
|
||||
|
||||
it("does not show Company to staff and sends no companyId", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true });
|
||||
mocks.useCompanyScope.mockReturnValue(scope());
|
||||
const user = userEvent.setup();
|
||||
render(<NewEventLeadPage />);
|
||||
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
|
||||
await user.type(screen.getByLabelText("Mobile"), "91111111");
|
||||
await user.click(screen.getByRole("button", { name: "Next" }));
|
||||
await waitFor(() => expect(mocks.matchLead).toHaveBeenCalled());
|
||||
expect(mocks.matchLead.mock.calls[0]).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listAdminRoles: vi.fn(),
|
||||
listSalespersonOptions: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
useCompanyScope: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: mocks.listAdminRoles }));
|
||||
vi.mock("@/app/lib/services/adminEvents", () => ({ listSalespersonOptions: mocks.listSalespersonOptions }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
|
||||
import { UserForm } from "@/app/components/users/UserForm";
|
||||
import { EventForm } from "@/app/components/events/EventForm";
|
||||
import { pickDate } from "@/test/pickDate";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const COMPANIES = [
|
||||
{ id: 1, name: "Ins Co", code: "INS", status: "A" },
|
||||
{ id: 2, name: "CV Co", code: "CV", status: "A" },
|
||||
];
|
||||
const scope = (companyId?: number) => ({ companyId, companies: COMPANIES, showCompanyColumn: false, codeOf: () => "", setCompanyId: vi.fn() });
|
||||
const ROLES = [
|
||||
{ id: 1, name: "ROLE_SUPER_ADMIN", level: 1, parent: { id: 0 } },
|
||||
{ id: 2, name: "ROLE_HQ", level: 1, parent: { id: 0 } },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.listAdminRoles.mockReset().mockResolvedValue(ROLES);
|
||||
mocks.listSalespersonOptions.mockReset().mockResolvedValue([{ id: 1, name: "Alice", username: "alice" }]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ id: 9, isSuper: true });
|
||||
mocks.useCompanyScope.mockReset().mockReturnValue(scope(2));
|
||||
});
|
||||
|
||||
async function fillUser(user: ReturnType<typeof userEvent.setup>) {
|
||||
await screen.findByLabelText("HQ");
|
||||
await user.type(screen.getByLabelText("Name"), "Jane");
|
||||
await user.type(screen.getByLabelText("Surname"), "Doe");
|
||||
await user.type(screen.getByLabelText("Username"), "jane");
|
||||
await user.type(screen.getByLabelText("Email"), "jane@x.test");
|
||||
}
|
||||
|
||||
describe("UserForm company", () => {
|
||||
it("shows Company to a super admin, defaulted to the picker, and sends it", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
const user = userEvent.setup();
|
||||
render(<UserForm onSubmit={onSubmit} />);
|
||||
const company = await screen.findByRole("combobox", { name: "Company" });
|
||||
expect(company).toHaveValue("2");
|
||||
await fillUser(user);
|
||||
await user.click(screen.getByLabelText("HQ"));
|
||||
await user.click(screen.getByRole("button", { name: /create|save/i }));
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ companyId: 2 })));
|
||||
});
|
||||
|
||||
it("offers Super admin (no company), which sends superAdmin and requires role 1", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
const user = userEvent.setup();
|
||||
render(<UserForm onSubmit={onSubmit} />);
|
||||
await user.selectOptions(await screen.findByRole("combobox", { name: "Company" }), "super");
|
||||
await fillUser(user);
|
||||
await user.click(screen.getByLabelText("HQ"));
|
||||
await user.click(screen.getByRole("button", { name: /create|save/i }));
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
await user.click(screen.getByLabelText("Super admin"));
|
||||
await user.click(screen.getByRole("button", { name: /create|save/i }));
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ superAdmin: true })));
|
||||
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("companyId", expect.anything());
|
||||
});
|
||||
|
||||
it("requires a company when none is chosen", async () => {
|
||||
mocks.useCompanyScope.mockReturnValue(scope());
|
||||
const onSubmit = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
render(<UserForm onSubmit={onSubmit} />);
|
||||
await fillUser(user);
|
||||
await user.click(screen.getByLabelText("HQ"));
|
||||
await user.click(screen.getByRole("button", { name: /create|save/i }));
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not show Company to staff or send it", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false });
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
const user = userEvent.setup();
|
||||
render(<UserForm onSubmit={onSubmit} />);
|
||||
await fillUser(user);
|
||||
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
|
||||
await user.click(screen.getByLabelText("HQ"));
|
||||
await user.click(screen.getByRole("button", { name: /create|save/i }));
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalled());
|
||||
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("companyId");
|
||||
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty("superAdmin");
|
||||
});
|
||||
|
||||
it("shows the server's COMPANY_REQUIRED message", async () => {
|
||||
const onSubmit = vi.fn().mockRejectedValue(new ApiError("Choose a company.", 400, { code: "COMPANY_REQUIRED" }));
|
||||
const user = userEvent.setup();
|
||||
render(<UserForm onSubmit={onSubmit} />);
|
||||
await fillUser(user);
|
||||
await user.click(screen.getByLabelText("HQ"));
|
||||
await user.click(screen.getByRole("button", { name: /create|save/i }));
|
||||
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("EventForm company", () => {
|
||||
it("shows Company to a super admin, defaulted to the picker, and sends it on create", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
const user = userEvent.setup();
|
||||
render(<EventForm onSubmit={onSubmit} />);
|
||||
expect(await screen.findByRole("combobox", { name: "Company" })).toHaveValue("2");
|
||||
await user.type(screen.getByLabelText("Name"), "Expo");
|
||||
await user.type(screen.getByLabelText("Location"), "KL");
|
||||
pickDate("Start date", "2026-12-01");
|
||||
pickDate("End date", "2026-12-02");
|
||||
await user.click(screen.getByRole("button", { name: /create|save/i }));
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ companyId: 2 })));
|
||||
});
|
||||
|
||||
it("does not show Company to staff", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ id: 9, isSuper: false });
|
||||
render(<EventForm onSubmit={vi.fn()} />);
|
||||
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenCalled());
|
||||
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("asks for salesperson options with the company chosen, and with the event's own company on edit", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { unmount } = render(<EventForm onSubmit={vi.fn()} />);
|
||||
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(2));
|
||||
await user.selectOptions(screen.getByRole("combobox", { name: "Company" }), "1");
|
||||
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(1));
|
||||
unmount();
|
||||
mocks.useCompanyScope.mockReturnValue(scope(1));
|
||||
render(
|
||||
<EventForm
|
||||
initial={{ uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, companyId: 2, salespersons: [] } as never}
|
||||
onSubmit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
await waitFor(() => expect(mocks.listSalespersonOptions).toHaveBeenLastCalledWith(2));
|
||||
});
|
||||
});
|
||||
|
||||
describe("EventForm company required", () => {
|
||||
it("refuses a super-admin create with no company chosen", async () => {
|
||||
mocks.useCompanyScope.mockReturnValue(scope());
|
||||
const onSubmit = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
render(<EventForm onSubmit={onSubmit} />);
|
||||
await user.type(await screen.findByLabelText("Name"), "Expo");
|
||||
await user.type(screen.getByLabelText("Location"), "KL");
|
||||
pickDate("Start date", "2026-12-01");
|
||||
pickDate("End date", "2026-12-02");
|
||||
await user.click(screen.getByRole("button", { name: /create|save/i }));
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
expect(await screen.findByText("Choose a company.")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// The companies list usually arrives after the first page of rows; the Company column must still fill in.
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listAdminEvents: vi.fn(),
|
||||
listEmails: vi.fn(),
|
||||
searchAuditLog: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
useCompanyScope: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i<object>()), listAdminEvents: mocks.listAdminEvents }));
|
||||
vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i<object>()), listEmails: mocks.listEmails }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i<object>()), searchAuditLog: mocks.searchAuditLog }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventsPage from "./events/page";
|
||||
import EmailsPage from "./emails/page";
|
||||
import AuditLogPage from "./audit-log/page";
|
||||
|
||||
const scope = (codes: Record<number, string>) => ({
|
||||
companyId: undefined,
|
||||
companies: [],
|
||||
showCompanyColumn: true,
|
||||
codeOf: (id?: number) => (id ? codes[id] ?? "" : ""),
|
||||
setCompanyId: vi.fn(),
|
||||
});
|
||||
|
||||
const PAGES = [
|
||||
{ name: "events", Page: EventsPage, list: mocks.listAdminEvents, row: { uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, companyId: 2 } },
|
||||
{ name: "emails", Page: EmailsPage, list: mocks.listEmails, row: { id: 9, datetime: "2026-11-30T11:44:26", recipients: ["a@x.test"], subject: "Hello", status: "Y", companyId: 2 } },
|
||||
{ name: "audit log", Page: AuditLogPage, list: mocks.searchAuditLog, row: { id: 2, companyId: 2, occurredAt: "2026-11-30T15:52:00", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/x", targetId: "4", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null } },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/x");
|
||||
for (const p of PAGES) p.list.mockReset().mockResolvedValue({ items: [p.row], total: 1 });
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe.each(PAGES)("$name Company column", ({ Page, row }) => {
|
||||
it("shows the code once the companies arrive after the rows", async () => {
|
||||
mocks.useCompanyScope.mockReturnValue(scope({}));
|
||||
const { rerender } = render(<Page />);
|
||||
await screen.findAllByText(String("name" in row ? row.name : "subject" in row ? row.subject : row.actor));
|
||||
|
||||
mocks.useCompanyScope.mockReturnValue(scope({ 2: "CV" }));
|
||||
rerender(<Page />);
|
||||
expect(await screen.findByText("CV")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listAdminUsers: vi.fn(),
|
||||
listAdminEvents: vi.fn(),
|
||||
listEmails: vi.fn(),
|
||||
searchAuditLog: vi.fn(),
|
||||
listLeads: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
useCompanyScope: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminUsers", async (i) => ({ ...(await i<object>()), listAdminUsers: mocks.listAdminUsers }));
|
||||
vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i<object>()), listAdminEvents: mocks.listAdminEvents }));
|
||||
vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i<object>()), listEmails: mocks.listEmails }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i<object>()), searchAuditLog: mocks.searchAuditLog }));
|
||||
vi.mock("@/app/lib/services/adminLeads", async (i) => ({ ...(await i<object>()), listLeads: mocks.listLeads }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import UsersPage from "./users/page";
|
||||
import EventsPage from "./events/page";
|
||||
import EmailsPage from "./emails/page";
|
||||
import AuditLogPage from "./audit-log/page";
|
||||
import LeadsPage from "./leads/page";
|
||||
|
||||
const CODES: Record<number, string> = { 1: "INS", 2: "CV" };
|
||||
const scope = (companyId?: number, isShown = companyId === undefined) => ({
|
||||
companyId,
|
||||
companies: [],
|
||||
showCompanyColumn: isShown,
|
||||
codeOf: (id?: number) => (id ? CODES[id] ?? "" : ""),
|
||||
setCompanyId: vi.fn(),
|
||||
});
|
||||
const headers = async () => within(await screen.findByRole("table")).getAllByRole("columnheader").map((h) => h.textContent);
|
||||
|
||||
const PAGES = [
|
||||
{
|
||||
name: "users",
|
||||
Page: UsersPage,
|
||||
list: mocks.listAdminUsers,
|
||||
row: { id: 5, username: "jane", name: "Jane", email: "j@x.test", enabled: true, status: "A", roles: [], companyId: 2, companyCode: "CV", loginName: "jane@cv" },
|
||||
},
|
||||
{
|
||||
name: "events",
|
||||
Page: EventsPage,
|
||||
list: mocks.listAdminEvents,
|
||||
row: { uuid: "e1", name: "Expo", location: "KL", startDate: "2026-12-01", endDate: "2026-12-02", enabled: true, companyId: 2 },
|
||||
},
|
||||
{
|
||||
name: "emails",
|
||||
Page: EmailsPage,
|
||||
list: mocks.listEmails,
|
||||
row: { id: 9, datetime: "2026-11-30T11:44:26", recipients: ["a@x.test"], subject: "Hello", status: "Y", companyId: 2 },
|
||||
},
|
||||
{
|
||||
name: "audit log",
|
||||
Page: AuditLogPage,
|
||||
list: mocks.searchAuditLog,
|
||||
row: { id: 2, companyId: 2, occurredAt: "2026-11-30T15:52:00", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/x", targetId: "4", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null },
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/x");
|
||||
for (const p of [...PAGES.map((x) => x.list), mocks.listLeads]) p.mockReset();
|
||||
for (const p of PAGES) p.list.mockResolvedValue({ items: [p.row], total: 1 });
|
||||
mocks.listLeads.mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
|
||||
mocks.useCompanyScope.mockReset().mockReturnValue(scope());
|
||||
});
|
||||
|
||||
describe.each(PAGES)("$name list company scope", ({ Page, list, row }) => {
|
||||
it("shows the Company column with the code for a super admin on All companies, and sends no companyId", async () => {
|
||||
render(<Page />);
|
||||
expect(await headers()).toContain("Company");
|
||||
expect(await screen.findByText("CV")).toBeInTheDocument();
|
||||
expect(list.mock.calls.at(-1)?.[0]).not.toHaveProperty("companyId", expect.anything());
|
||||
expect(row).toBeTruthy();
|
||||
});
|
||||
|
||||
it("hides the Company column and sends the picked companyId when one company is chosen", async () => {
|
||||
mocks.useCompanyScope.mockReturnValue(scope(2));
|
||||
render(<Page />);
|
||||
expect(await headers()).not.toContain("Company");
|
||||
await waitFor(() => expect(list).toHaveBeenLastCalledWith(expect.objectContaining({ companyId: 2 })));
|
||||
});
|
||||
|
||||
it("hides the Company column for staff and never sends companyId", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true });
|
||||
mocks.useCompanyScope.mockReturnValue(scope(undefined, false));
|
||||
render(<Page />);
|
||||
expect(await headers()).not.toContain("Company");
|
||||
expect(list.mock.calls.every((c) => (c[0] as { companyId?: number }).companyId === undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("users list names", () => {
|
||||
it("shows the local username, not the login name with @code", async () => {
|
||||
render(<UsersPage />);
|
||||
expect(await screen.findByText("jane")).toBeInTheDocument();
|
||||
expect(screen.queryByText("jane@cv")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("leads list company scope", () => {
|
||||
it("adds a tenant Company column only on All companies, and sends the picked companyId", async () => {
|
||||
const count = async () => (await headers()).filter((h) => h === "Company").length;
|
||||
const { unmount } = render(<LeadsPage />);
|
||||
const withAll = await count();
|
||||
unmount();
|
||||
mocks.useCompanyScope.mockReturnValue(scope(2));
|
||||
render(<LeadsPage />);
|
||||
expect(withAll).toBe((await count()) + 1);
|
||||
await waitFor(() => expect(mocks.listLeads).toHaveBeenLastCalledWith(expect.objectContaining({ companyId: 2 })));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listAdminRoles: vi.fn(),
|
||||
listInterests: vi.fn(),
|
||||
apiGet: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/clientApi", async (i) => ({ ...(await i<object>()), apiGet: mocks.apiGet, apiPost: vi.fn(), apiPut: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminRoles", async (i) => ({ ...(await i<object>()), listAdminRoles: mocks.listAdminRoles }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import RolesPage from "./roles/page";
|
||||
import InterestsPage from "./interests/page";
|
||||
import LoginSecurityPage from "./login-security/page";
|
||||
|
||||
const as = (isSuper: boolean) => mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper, hasModule: () => true });
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/x");
|
||||
mocks.listAdminRoles.mockReset().mockResolvedValue([{ id: 4, name: "ROLE_HQ", parent: { id: 1 } }]);
|
||||
mocks.apiGet.mockReset().mockImplementation(async (path: string) => {
|
||||
if (path.includes("/interests")) return [{ id: 3, name: "Product A", active: true }];
|
||||
if (path.includes("/config")) return { enabled: true, maxAttempts: 5, period: 15, unit: "M" };
|
||||
if (path.includes("/password-rules")) return [];
|
||||
return [];
|
||||
});
|
||||
mocks.useAdminAuth.mockReset();
|
||||
});
|
||||
|
||||
describe("Roles read-only for staff", () => {
|
||||
it("hides Add role, Edit and Manage access for staff", async () => {
|
||||
as(false);
|
||||
render(<RolesPage />);
|
||||
await screen.findByText("ROLE_HQ");
|
||||
expect(screen.queryByRole("button", { name: /add role/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /^edit/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: /manage access/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps them for a super admin", async () => {
|
||||
as(true);
|
||||
render(<RolesPage />);
|
||||
await screen.findByText("ROLE_HQ");
|
||||
expect(screen.getByRole("button", { name: /add role/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Interests read-only for staff", () => {
|
||||
it("hides Add interest and row actions for staff", async () => {
|
||||
as(false);
|
||||
render(<InterestsPage />);
|
||||
await screen.findByText("Product A");
|
||||
expect(screen.queryByRole("button", { name: /add interest/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /^edit/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /deactivate/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps Add interest for a super admin", async () => {
|
||||
as(true);
|
||||
render(<InterestsPage />);
|
||||
await screen.findByText("Product A");
|
||||
expect(screen.getByRole("button", { name: /add interest/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Login security Settings read-only for staff", () => {
|
||||
async function openSettings() {
|
||||
const user = userEvent.setup();
|
||||
render(<LoginSecurityPage />);
|
||||
await user.click(await screen.findByRole("tab", { name: /settings/i }));
|
||||
return user;
|
||||
}
|
||||
|
||||
it("hides the Save buttons for staff", async () => {
|
||||
as(false);
|
||||
await openSettings();
|
||||
await waitFor(() => expect(mocks.apiGet).toHaveBeenCalledWith(expect.stringContaining("/config")));
|
||||
expect(screen.queryByRole("button", { name: /save lockout settings/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /save password rules/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the Save buttons to a super admin", async () => {
|
||||
as(true);
|
||||
await openSettings();
|
||||
expect(await screen.findByRole("button", { name: /save lockout settings/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listAdminUsers: vi.fn(),
|
||||
listAdminEvents: vi.fn(),
|
||||
listEmails: vi.fn(),
|
||||
searchAuditLog: vi.fn(),
|
||||
listLeads: vi.fn(),
|
||||
listAudit: vi.fn(),
|
||||
listLocked: vi.fn(),
|
||||
getConfig: vi.fn(),
|
||||
getPasswordRules: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
useCompanyScope: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminUsers", async (i) => ({ ...(await i<object>()), listAdminUsers: mocks.listAdminUsers }));
|
||||
vi.mock("@/app/lib/services/adminEvents", async (i) => ({ ...(await i<object>()), listAdminEvents: mocks.listAdminEvents }));
|
||||
vi.mock("@/app/lib/services/adminEmails", async (i) => ({ ...(await i<object>()), listEmails: mocks.listEmails }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (i) => ({ ...(await i<object>()), searchAuditLog: mocks.searchAuditLog }));
|
||||
vi.mock("@/app/lib/services/adminLeads", async (i) => ({ ...(await i<object>()), listLeads: mocks.listLeads }));
|
||||
vi.mock("@/app/lib/services/loginSecurity", async (i) => ({
|
||||
...(await i<object>()),
|
||||
listAudit: mocks.listAudit,
|
||||
listLocked: mocks.listLocked,
|
||||
getConfig: mocks.getConfig,
|
||||
getPasswordRules: mocks.getPasswordRules,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import UsersPage from "./users/page";
|
||||
import EventsPage from "./events/page";
|
||||
import EmailsPage from "./emails/page";
|
||||
import AuditLogPage from "./audit-log/page";
|
||||
import LeadsPage from "./leads/page";
|
||||
import LoginSecurityPage from "./login-security/page";
|
||||
|
||||
const scope = (companyId?: number) => ({ companyId, companies: [], showCompanyColumn: companyId === undefined, codeOf: () => "CV", setCompanyId: vi.fn() });
|
||||
const EMPTY = { items: [], total: 0 };
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/x", "page=3");
|
||||
for (const m of [mocks.listAdminUsers, mocks.listAdminEvents, mocks.listEmails, mocks.searchAuditLog, mocks.listLeads, mocks.listAudit]) m.mockReset().mockResolvedValue(EMPTY);
|
||||
mocks.listLocked.mockReset().mockResolvedValue([{ username: "jane", failures: 5, lastFailure: "2026-11-30T10:00:00", lockedUntil: "2026-11-30T11:00:00" }]);
|
||||
mocks.getConfig.mockReset().mockResolvedValue({ enabled: true, maxAttempts: 5, period: 15, unit: "M" });
|
||||
mocks.getPasswordRules.mockReset().mockResolvedValue([{ id: 1, param: "MIN_LENGTH", status: "Y", value: "8" }]);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true, hasModule: () => true });
|
||||
mocks.useCompanyScope.mockReset().mockReturnValue(scope(1));
|
||||
});
|
||||
|
||||
describe.each([
|
||||
["users", UsersPage, mocks.listAdminUsers],
|
||||
["events", EventsPage, mocks.listAdminEvents],
|
||||
["emails", EmailsPage, mocks.listEmails],
|
||||
["audit log", AuditLogPage, mocks.searchAuditLog],
|
||||
["leads", LeadsPage, mocks.listLeads],
|
||||
])("%s picker change resets paging", (_name, Page, list) => {
|
||||
it("returns to the first page when the company changes, not on first render", async () => {
|
||||
const { rerender } = render(<Page />);
|
||||
await waitFor(() => expect(list).toHaveBeenCalled());
|
||||
expect(memoryRouter.getSearch().get("page")).toBe("3");
|
||||
mocks.useCompanyScope.mockReturnValue(scope(2));
|
||||
rerender(<Page />);
|
||||
await waitFor(() => expect(memoryRouter.getSearch().get("page")).toBeNull());
|
||||
});
|
||||
});
|
||||
|
||||
describe("login security", () => {
|
||||
it("history returns to the first page when the company changes", async () => {
|
||||
const { rerender } = render(<LoginSecurityPage />);
|
||||
await waitFor(() => expect(mocks.listAudit).toHaveBeenCalled());
|
||||
expect(memoryRouter.getSearch().get("page")).toBe("3");
|
||||
mocks.useCompanyScope.mockReturnValue(scope(2));
|
||||
rerender(<LoginSecurityPage />);
|
||||
await waitFor(() => expect(memoryRouter.getSearch().get("page")).toBeNull());
|
||||
});
|
||||
|
||||
it("Locked tab has no Company column on All companies", async () => {
|
||||
mocks.useCompanyScope.mockReturnValue(scope());
|
||||
const user = userEvent.setup();
|
||||
render(<LoginSecurityPage />);
|
||||
await user.click(screen.getByRole("tab", { name: "Locked" }));
|
||||
await screen.findByText("jane");
|
||||
expect(screen.queryByRole("columnheader", { name: "Company" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("disables the settings inputs for a non-super user", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true });
|
||||
const user = userEvent.setup();
|
||||
render(<LoginSecurityPage />);
|
||||
await user.click(screen.getByRole("tab", { name: "Settings" }));
|
||||
expect(await screen.findByLabelText(/max/i)).toBeDisabled();
|
||||
expect(screen.getByRole("switch", { name: /min/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import { useEffect } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { isPublicPath } from "@/app/lib/routeGuard";
|
||||
import { CompanyScopeProvider } from "@/app/lib/CompanyScope";
|
||||
import Header from "./Header";
|
||||
import Sidebar from "./Sidebar";
|
||||
import PoweredBy from "./PoweredBy";
|
||||
@@ -45,6 +46,7 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<CompanyScopeProvider>
|
||||
<div className="flex min-h-svh bg-background">
|
||||
<SessionKeepAlive />
|
||||
<Sidebar />
|
||||
@@ -63,5 +65,6 @@ export default function AppShell({ children }: { children: React.ReactNode }) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CompanyScopeProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
// Header company filter; super admins only (staff are always scoped by the server).
|
||||
export default function CompanyPicker() {
|
||||
const { isSuper } = useAdminAuth();
|
||||
const { companyId, setCompanyId, companies } = useCompanyScope();
|
||||
const t = useT();
|
||||
if (!isSuper) return null;
|
||||
return (
|
||||
<select
|
||||
aria-label={t("Company")}
|
||||
value={companyId ?? ""}
|
||||
onChange={(e) => setCompanyId(e.target.value ? Number(e.target.value) : undefined)}
|
||||
className="h-9 rounded-md border bg-background px-2 text-sm"
|
||||
>
|
||||
<option value="">{t("AllCompanies")}</option>
|
||||
{companies.map((c) => (
|
||||
<option key={c.id} value={c.id}>{c.code}</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }), usePathname: () => "/" }));
|
||||
vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => [] }));
|
||||
const auth = vi.hoisted(() => ({ companyCode: "ins" as string | null }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({
|
||||
useAdminAuth: () => ({ name: "Admin User", companyCode: auth.companyCode, hasModule: () => false }),
|
||||
}));
|
||||
vi.mock("@/app/lib/theme", () => ({ useTheme: () => ({ theme: "light", toggleTheme: vi.fn() }) }));
|
||||
|
||||
import Header from "./Header";
|
||||
|
||||
describe("Header company code", () => {
|
||||
it("shows the company code next to the name", () => {
|
||||
render(<Header />);
|
||||
expect(screen.getByTestId("company-code")).toHaveTextContent("ins");
|
||||
});
|
||||
|
||||
it("shows nothing for a super admin", () => {
|
||||
auth.companyCode = null;
|
||||
render(<Header />);
|
||||
expect(screen.queryByTestId("company-code")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }), usePathname: () => "/" }));
|
||||
vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => [] }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ name: "Admin User", companyCode: null, hasModule: () => false }) }));
|
||||
vi.mock("@/app/lib/theme", () => ({ useTheme: () => ({ theme: "light", toggleTheme: vi.fn() }) }));
|
||||
|
||||
import Header from "./Header";
|
||||
|
||||
describe("Header logout", () => {
|
||||
it("clears the stored company choice", async () => {
|
||||
sessionStorage.setItem("company-scope", "2");
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 204 })));
|
||||
const user = userEvent.setup();
|
||||
render(<Header />);
|
||||
await user.click(screen.getByRole("button", { name: /admin user/i }));
|
||||
await user.click(await screen.findByText(/logout/i));
|
||||
await waitFor(() => expect(sessionStorage.getItem("company-scope")).toBeNull());
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
import { Sheet, SheetContent, SheetTitle } from "@/app/components/ui/sheet";
|
||||
import Breadcrumbs from "./Breadcrumbs";
|
||||
import { BrandLink, SidebarNav } from "./Sidebar";
|
||||
import CompanyPicker from "./CompanyPicker";
|
||||
import { clearStoredCompany } from "@/app/lib/CompanyScope";
|
||||
import LocaleSwitcher from "./LocaleSwitcher";
|
||||
import ChangePasswordDialog from "./ChangePasswordDialog";
|
||||
|
||||
@@ -27,7 +29,7 @@ import ChangePasswordDialog from "./ChangePasswordDialog";
|
||||
// same-origin /api/auth/logout route handler — never the mobile-api directly
|
||||
// (spec: "The Admin Portal Is A Next.js Backend-For-Frontend").
|
||||
export default function Header() {
|
||||
const { name } = useAdminAuth();
|
||||
const { name, companyCode } = useAdminAuth();
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
@@ -41,6 +43,7 @@ export default function Header() {
|
||||
// app/api/auth/logout/route.ts), so the browser always ends up signed out
|
||||
// locally even if this request itself fails.
|
||||
try {
|
||||
clearStoredCompany();
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
} catch {
|
||||
// Network failure: still sign out locally below.
|
||||
@@ -73,6 +76,7 @@ export default function Header() {
|
||||
</Sheet>
|
||||
<Breadcrumbs />
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<CompanyPicker />
|
||||
<LocaleSwitcher />
|
||||
|
||||
<Button
|
||||
@@ -96,6 +100,7 @@ export default function Header() {
|
||||
<AvatarFallback className="bg-primary text-xs text-primary-foreground">{initial}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="hidden sm:inline">{name}</span>
|
||||
{companyCode && <span data-testid="company-code" className="hidden text-xs text-muted-foreground sm:inline">{companyCode}</span>}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
|
||||
@@ -8,6 +8,8 @@ import { Label } from "@/app/components/ui/label";
|
||||
import { Switch } from "@/app/components/ui/switch";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { listSalespersonOptions } from "@/app/lib/services/adminEvents";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import type { AdminEvent, AdminEventPayload, SalespersonOption } from "@/app/lib/types";
|
||||
@@ -31,10 +33,16 @@ const REQUIRED_MESSAGE: Record<string, string> = {
|
||||
endDate: "EvtEndRequired",
|
||||
};
|
||||
/** Fields the form can show an API error under; anything else goes to the top of the form. */
|
||||
const FIELD_ERROR_SLOTS = ["name", "location", "startDate", "endDate", "salespersonIds"];
|
||||
const FIELD_ERROR_SLOTS = ["company", "name", "location", "startDate", "endDate", "salespersonIds"];
|
||||
|
||||
export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
const t = useT();
|
||||
const { isSuper } = useAdminAuth();
|
||||
const scope = useCompanyScope();
|
||||
// Super admins choose the company on create; on edit it is the event's own (it cannot move).
|
||||
const showCompany = isSuper === true && !initial;
|
||||
const [companyChoice, setCompanyChoice] = useState(scope.companyId ? String(scope.companyId) : "");
|
||||
const optionsCompanyId = isSuper === true ? (initial ? initial.companyId : Number(companyChoice) || undefined) : undefined;
|
||||
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
const [location, setLocation] = useState(initial?.location ?? "");
|
||||
@@ -55,7 +63,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- loading/picker reset is the actual synchronization; initial is in the deps below.
|
||||
setLoadingPickers(true);
|
||||
setPickersError(null);
|
||||
listSalespersonOptions()
|
||||
(optionsCompanyId ? listSalespersonOptions(optionsCompanyId) : listSalespersonOptions())
|
||||
.then((opts) => {
|
||||
if (cancelled) return;
|
||||
const activeOpts = opts.map((o) => ({ ...o, active: true } as SalespersonOptionExtended));
|
||||
@@ -86,7 +94,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [initial]);
|
||||
}, [initial, optionsCompanyId]);
|
||||
|
||||
// Build the set of initially selected team member IDs.
|
||||
// Members from initial.team that are also in the active options → checked.
|
||||
@@ -118,6 +126,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
if (!endDate) errors.endDate = t("EvtEndRequired");
|
||||
if (endDate && startDate && endDate < startDate) errors.endDate = t("EvtEndBeforeStart");
|
||||
if (trimmedName.length > 100) errors.name = t("EvtNameTooLong");
|
||||
if (showCompany && !companyChoice) errors.company = t("ChooseCompany");
|
||||
if (trimmedLocation.length > 200) errors.location = t("EvtLocationTooLong");
|
||||
|
||||
setFieldErrors(errors);
|
||||
@@ -133,6 +142,7 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
endDate,
|
||||
salespersonIds: Array.from(selectedIds).filter((id): id is number => id != null),
|
||||
};
|
||||
if (showCompany) payload.companyId = Number(companyChoice);
|
||||
// `enabled` is only sent on edit (when initial exists).
|
||||
if (initial) {
|
||||
payload.enabled = enabled;
|
||||
@@ -166,6 +176,33 @@ export function EventForm({ initial, onSubmit, submitLabel }: EventFormProps) {
|
||||
{formError && <ErrorState message={t(formError)} />}
|
||||
{pickersError && <ErrorState message={t(pickersError)} />}
|
||||
|
||||
{showCompany && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="evt-company">{t("Company")}</Label>
|
||||
<select
|
||||
id="evt-company"
|
||||
value={companyChoice}
|
||||
onChange={(e) => {
|
||||
setCompanyChoice(e.target.value);
|
||||
setSelectedIds(new Set()); // the team is company-specific
|
||||
}}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.company}
|
||||
className="h-9 w-full rounded-md border bg-background px-2 text-sm"
|
||||
>
|
||||
<option value="" />
|
||||
{scope.companies.map((c) => (
|
||||
<option key={c.id} value={c.id}>{c.code}</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldErrors.company && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.company}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="evt-name">{t("Name")}</Label>
|
||||
<Input
|
||||
|
||||
@@ -13,6 +13,7 @@ import { roleLabel } from "@/app/lib/roleLabel";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { listAdminRoles } from "@/app/lib/services/adminRoles";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import type { AdminUser } from "@/app/lib/types";
|
||||
import { PasswordFields } from "./PasswordFields";
|
||||
@@ -31,7 +32,7 @@ interface RoleOption {
|
||||
}
|
||||
|
||||
/** On create the payload also carries the admin-typed first password and its confirmation. */
|
||||
export type UserFormPayload = AdminUser & { password?: string; confirmPassword?: string };
|
||||
export type UserFormPayload = AdminUser & { password?: string; confirmPassword?: string; companyId?: number; superAdmin?: boolean };
|
||||
|
||||
export interface UserFormProps {
|
||||
initial?: AdminUser;
|
||||
@@ -43,7 +44,11 @@ export interface UserFormProps {
|
||||
|
||||
export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserFormProps) {
|
||||
const t = useT();
|
||||
const { id: myId } = useAdminAuth();
|
||||
const { id: myId, isSuper } = useAdminAuth();
|
||||
const scope = useCompanyScope();
|
||||
// Super admins pick the new user's company on create; "super" makes another company-less super admin.
|
||||
const showCompany = isSuper === true && initial?.id == null;
|
||||
const [company, setCompany] = useState(scope.companyId ? String(scope.companyId) : "");
|
||||
// The server refuses SELF_DEACTIVATION; this keeps the switch from offering it.
|
||||
const isOwnAccount = initial?.id != null && initial.id === myId;
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
@@ -114,6 +119,8 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
if (!username.trim()) errors.username = t("UsrUsernameRequired");
|
||||
if (!email.trim()) errors.email = t("UsrEmailRequired");
|
||||
else if (!EMAIL_RE.test(email.trim())) errors.email = t("UsrEmailInvalid");
|
||||
if (showCompany && !company) errors.company = t("ChooseCompany");
|
||||
else if (showCompany && company === "super" && !selectedRoleIds.has(1)) errors.company = t("SuperAdminNeedsRole");
|
||||
if (withPassword && !password) errors.password = t("UsrPasswordRequired");
|
||||
else if (withPassword && password !== confirmPassword) errors.confirmPassword = t("UsrPasswordMismatch");
|
||||
setFieldErrors(errors);
|
||||
@@ -133,6 +140,7 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
status: enabled ? "Y" : "N",
|
||||
roles: selectedRoles.map((r) => ({ id: r.id, name: r.name })),
|
||||
...(withPassword ? { password, confirmPassword } : {}),
|
||||
...(showCompany ? (company === "super" ? { superAdmin: true } : { companyId: Number(company) }) : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
setFormError(err instanceof Error ? err.message : "UsrSaveFailed");
|
||||
@@ -209,6 +217,31 @@ export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserF
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showCompany && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="user-company">{t("Company")}</Label>
|
||||
<select
|
||||
id="user-company"
|
||||
value={company}
|
||||
onChange={(e) => setCompany(e.target.value)}
|
||||
disabled={saving}
|
||||
aria-invalid={!!fieldErrors.company}
|
||||
className="h-9 w-full rounded-md border bg-background px-2 text-sm"
|
||||
>
|
||||
<option value="" />
|
||||
{scope.companies.map((c) => (
|
||||
<option key={c.id} value={c.id}>{c.code}</option>
|
||||
))}
|
||||
<option value="super">{t("CompanySuperAdmin")}</option>
|
||||
</select>
|
||||
{fieldErrors.company && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{fieldErrors.company}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{withPassword && (
|
||||
<PasswordFields
|
||||
password={password}
|
||||
|
||||
@@ -10,7 +10,9 @@ 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 { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { EMAIL_STATUS_KEYS, formatEmailDate, listEmails, type EmailRow } from "@/app/lib/services/adminEmails";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -20,8 +22,10 @@ const DEFAULTS = { recipient: "", subject: "", from: "", to: "" };
|
||||
|
||||
function EmailsPageContent() {
|
||||
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: EmailRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
@@ -41,12 +45,13 @@ function EmailsPageContent() {
|
||||
to: filters.to || undefined,
|
||||
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 columns = useMemo<ColumnDef<EmailRow, unknown>[]>(
|
||||
() => [
|
||||
@@ -62,9 +67,10 @@ function EmailsPageContent() {
|
||||
},
|
||||
{ id: "recipients", header: t("EmlRecipient"), enableSorting: false, cell: ({ row }) => row.original.recipients.join(", ") },
|
||||
{ id: "datetime", header: t("EmlDate"), enableSorting: false, cell: ({ row }) => formatEmailDate(row.original.datetime) },
|
||||
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<EmailRow, unknown>] : []),
|
||||
{ id: "status", header: t("Status"), enableSorting: false, cell: ({ row }) => t(EMAIL_STATUS_KEYS[row.original.status] ?? row.original.status) },
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -12,7 +12,7 @@ import { ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { captureEventLead, listEventLeadInterests, listEventSalespeople, matchLead } from "@/app/lib/services/adminEventLeads";
|
||||
import { captureEventLead, listEventLeadEvents, listEventLeadInterests, listEventSalespeople, matchLead } from "@/app/lib/services/adminEventLeads";
|
||||
import type { InterestOption, LeadCandidate, LeadMatchResult, LeadStatus, LeadTemperature, SalespersonOption } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -66,7 +66,11 @@ function readError(err: unknown, t: (k: string) => string, fallbackKey: string,
|
||||
function NewEventLead() {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { id: myId } = useAdminAuth();
|
||||
const { id: myId, isSuper } = useAdminAuth();
|
||||
// A super admin's lead belongs to the event's own company; staff are scoped by the server.
|
||||
const needsCompany = isSuper === true;
|
||||
const [eventCompanyId, setEventCompanyId] = useState<number | undefined>();
|
||||
const companyId = needsCompany ? eventCompanyId : undefined;
|
||||
const { eventUuid } = useParams<{ eventUuid: string }>();
|
||||
const [step, setStep] = useState<Step>("match");
|
||||
const [candidates, setCandidates] = useState<LeadCandidate[] | null>(null);
|
||||
@@ -103,6 +107,15 @@ function NewEventLead() {
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, t, myId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!needsCompany) return;
|
||||
let cancelled = false;
|
||||
listEventLeadEvents()
|
||||
.then((events) => { if (!cancelled) setEventCompanyId(events.find((e) => e.uuid === eventUuid)?.companyId ?? undefined); })
|
||||
.catch(() => { if (!cancelled) setOptionsError(t("LeadOptionsLoadFailed")); });
|
||||
return () => { cancelled = true; };
|
||||
}, [needsCompany, eventUuid, t]);
|
||||
|
||||
const fieldProps = (f: string) => ({
|
||||
id: `lead-${f}`,
|
||||
"aria-invalid": fieldErrors[f] ? (true as const) : undefined,
|
||||
@@ -122,7 +135,8 @@ function NewEventLead() {
|
||||
setFormError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await matchLead(eventUuid, { mobile: mobile.trim() || null, email: email.trim() || null });
|
||||
const body = { mobile: mobile.trim() || null, email: email.trim() || null };
|
||||
const result = await (companyId ? matchLead(eventUuid, body, companyId) : matchLead(eventUuid, body));
|
||||
setMatch(result);
|
||||
if (result.candidates.length === 0) startDetails(result, null);
|
||||
else setCandidates(result.candidates);
|
||||
@@ -168,6 +182,7 @@ function NewEventLead() {
|
||||
interestIds,
|
||||
nextFollowUpDate: nextFollowUpDate || null,
|
||||
notes: notes.trim() || null,
|
||||
...(companyId ? { companyId } : {}),
|
||||
});
|
||||
router.push(`/event-leads/${eventUuid}`);
|
||||
} catch (err) {
|
||||
@@ -204,7 +219,7 @@ function NewEventLead() {
|
||||
<form onSubmit={onMatch} className="space-y-4" noValidate>
|
||||
{textInput("mobile", t("LeadMobile"), mobile, setMobile, { type: "tel", inputMode: "tel", autoComplete: "tel" })}
|
||||
{textInput("email", t("Email"), email, setEmail, { type: "email", autoComplete: "email" })}
|
||||
<Button type="submit" className={`${TALL} w-full sm:w-auto`} disabled={busy}>{t("LeadNext")}</Button>
|
||||
<Button type="submit" className={`${TALL} w-full sm:w-auto`} disabled={busy || (needsCompany && !companyId)}>{t("LeadNext")}</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
||||
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { exportEventLeads, listEventLeads, listEventSalespeople, listEventLeadInterests, listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
|
||||
import type { EventLeadRow, InterestOption, SalespersonOption } from "@/app/lib/types";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
|
||||
@@ -30,6 +31,7 @@ const STATUS_BADGE = { OPEN: "neutral", CONTACTED: "neutral", QUALIFIED: "contra
|
||||
|
||||
function EventLeadsDetailPageContent() {
|
||||
const t = useT();
|
||||
const { companyId, showCompanyColumn, codeOf } = useCompanyScope();
|
||||
const { hasModule } = useAdminAuth();
|
||||
const { eventUuid } = useParams<{ eventUuid: string }>();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
@@ -46,7 +48,7 @@ function EventLeadsDetailPageContent() {
|
||||
// Load event name from the events list
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
listEventLeadEvents()
|
||||
(companyId ? listEventLeadEvents(companyId) : listEventLeadEvents())
|
||||
.then((events) => {
|
||||
if (!cancelled) {
|
||||
const found = events.find((e) => e.uuid === eventUuid);
|
||||
@@ -55,7 +57,7 @@ function EventLeadsDetailPageContent() {
|
||||
})
|
||||
.catch(() => { if (!cancelled) setEventName(null); });
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid]);
|
||||
}, [eventUuid, companyId]);
|
||||
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [exportError, setExportError] = useState<string | null>(null);
|
||||
@@ -63,7 +65,7 @@ function EventLeadsDetailPageContent() {
|
||||
const runExport = () => {
|
||||
setExporting(true);
|
||||
setExportError(null);
|
||||
exportEventLeads(eventUuid, filters)
|
||||
(companyId ? exportEventLeads(eventUuid, filters, companyId) : exportEventLeads(eventUuid, filters))
|
||||
.catch((err: unknown) => {
|
||||
const tooLarge = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "EXPORT_TOO_LARGE";
|
||||
setExportError(tooLarge ? t("LeadsExportTooLarge") : err instanceof Error ? err.message : t("LeadListLoadFailed"));
|
||||
@@ -96,7 +98,7 @@ function EventLeadsDetailPageContent() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setExportError(null);
|
||||
listEventLeads(eventUuid, { page, pageSize, ...filters })
|
||||
listEventLeads(eventUuid, { page, pageSize, ...filters, companyId })
|
||||
.then((result) => {
|
||||
if (!cancelled) setData(result);
|
||||
})
|
||||
@@ -107,7 +109,7 @@ function EventLeadsDetailPageContent() {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [eventUuid, filters, page, pageSize, reloadKey]);
|
||||
}, [eventUuid, filters, page, pageSize, reloadKey, companyId]);
|
||||
|
||||
const salespersonOptions = useMemo(
|
||||
() => salespeople.map((o) => ({ value: String(o.id), label: o.name })),
|
||||
@@ -136,6 +138,7 @@ function EventLeadsDetailPageContent() {
|
||||
|
||||
const columns = useMemo<ColumnDef<EventLeadRow, unknown>[]>(
|
||||
() => [
|
||||
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<EventLeadRow, unknown>] : []),
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("LeadName"),
|
||||
@@ -206,7 +209,7 @@ function EventLeadsDetailPageContent() {
|
||||
cell: ({ row }) => <span>{row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}</span>,
|
||||
},
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -8,6 +8,7 @@ import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
|
||||
import type { EventLeadEvent } from "@/app/lib/types";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
|
||||
@@ -18,6 +19,7 @@ const isoToday = () => {
|
||||
|
||||
function EventLeadsPageContent() {
|
||||
const t = useT();
|
||||
const { companyId } = useCompanyScope();
|
||||
const [events, setEvents] = useState<EventLeadEvent[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -28,7 +30,7 @@ function EventLeadsPageContent() {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the triggered fetch below, which is the actual synchronization.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listEventLeadEvents()
|
||||
(companyId ? listEventLeadEvents(companyId) : listEventLeadEvents())
|
||||
.then((data) => {
|
||||
if (!cancelled) setEvents(data);
|
||||
})
|
||||
@@ -39,7 +41,7 @@ function EventLeadsPageContent() {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [reloadKey]);
|
||||
}, [reloadKey, companyId]);
|
||||
|
||||
const today = isoToday();
|
||||
const sorted = events
|
||||
|
||||
@@ -14,10 +14,12 @@ import { RowActions } from "@/app/components/ui/row-actions";
|
||||
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 { listAdminEvents } from "@/app/lib/services/adminEvents";
|
||||
import type { AdminEvent } from "@/app/lib/types";
|
||||
import { useTableSort } from "@/app/lib/hooks/useTableSort";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
|
||||
@@ -27,9 +29,11 @@ export const EVENT_STATUS_FILTER_OPTIONS = [{ value: "Y", label: "Enabled" }, {
|
||||
|
||||
function EventsPageContent() {
|
||||
const t = useT();
|
||||
const { companyId, showCompanyColumn, codeOf } = useCompanyScope();
|
||||
const router = useRouter();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
useResetPageOnCompany(setPage);
|
||||
const { sorting, onSortingChange, sortBy, sortDir } = useTableSort();
|
||||
const [data, setData] = useState<{ items: AdminEvent[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -44,7 +48,7 @@ function EventsPageContent() {
|
||||
// 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);
|
||||
setError(null);
|
||||
listAdminEvents({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir })
|
||||
listAdminEvents({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir, companyId })
|
||||
.then((result) => {
|
||||
if (!cancelled) setData(result);
|
||||
})
|
||||
@@ -57,7 +61,7 @@ function EventsPageContent() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [filters, page, reloadKey, pageSize, sortBy, sortDir]);
|
||||
}, [filters, page, reloadKey, pageSize, sortBy, sortDir, companyId]);
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => EVENT_STATUS_FILTER_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
@@ -75,6 +79,7 @@ function EventsPageContent() {
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<AdminEvent, unknown>] : []),
|
||||
{ accessorKey: "location", header: t("Location"), enableSorting: false },
|
||||
{
|
||||
accessorKey: "startDate",
|
||||
@@ -118,7 +123,7 @@ function EventsPageContent() {
|
||||
),
|
||||
},
|
||||
],
|
||||
[t, router],
|
||||
[t, router, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/app/lib/clientApi", () => ({ apiPost: vi.fn() }));
|
||||
|
||||
import ForgotPasswordPage from "./page";
|
||||
import { apiPost } from "@/app/lib/clientApi";
|
||||
|
||||
const mockPost = apiPost as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset().mockResolvedValue({ ok: true });
|
||||
});
|
||||
|
||||
function fill(company: string) {
|
||||
if (company) fireEvent.change(screen.getByLabelText("Company"), { target: { value: company } });
|
||||
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "john" } });
|
||||
fireEvent.change(screen.getByLabelText("Email"), { target: { value: "john@x.com" } });
|
||||
fireEvent.submit(screen.getByRole("button", { name: /temporary password/i }));
|
||||
}
|
||||
|
||||
describe("ForgotPasswordPage company field", () => {
|
||||
it("sends company, username and email", async () => {
|
||||
render(<ForgotPasswordPage />);
|
||||
fill(" ins ");
|
||||
await waitFor(() =>
|
||||
expect(mockPost).toHaveBeenCalledWith("/api/auth/forgot-password", { company: "ins", username: "john", email: "john@x.com" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("allows a blank company", async () => {
|
||||
render(<ForgotPasswordPage />);
|
||||
fill("");
|
||||
await waitFor(() => expect(mockPost).toHaveBeenCalled());
|
||||
expect(mockPost.mock.calls[0][1].company ?? "").toBe("");
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import PoweredBy from "@/app/components/app/PoweredBy";
|
||||
// failure) the visitor sees the same message, so the page never reveals whether an account exists.
|
||||
export default function ForgotPasswordPage() {
|
||||
const t = useT();
|
||||
const [company, setCompany] = useState("");
|
||||
const [username, setUsername] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [required, setRequired] = useState(false);
|
||||
@@ -31,7 +32,7 @@ export default function ForgotPasswordPage() {
|
||||
setRequired(false);
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await apiPost("/api/auth/forgot-password", { username: username.trim(), email: email.trim() });
|
||||
await apiPost("/api/auth/forgot-password", { company: company.trim() || undefined, username: username.trim(), email: email.trim() });
|
||||
} catch {
|
||||
// Deliberately ignored: a failure must look the same as success.
|
||||
}
|
||||
@@ -53,6 +54,11 @@ export default function ForgotPasswordPage() {
|
||||
<>
|
||||
{required && <ErrorState message={t("ForgotRequired")} />}
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company">{t("Company")}</Label>
|
||||
<Input id="company" autoComplete="organization" placeholder={t("CompanyBlankForSuper")} value={company}
|
||||
onChange={(e) => setCompany(e.target.value)} disabled={submitting} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">{t("Username")}</Label>
|
||||
<Input id="username" autoComplete="username" required value={username}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
@@ -136,6 +137,7 @@ function InterestFormDialog({
|
||||
|
||||
function InterestsPageContent() {
|
||||
const t = useT();
|
||||
const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway
|
||||
const [interests, setInterests] = useState<AdminInterestEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -185,10 +187,10 @@ function InterestsPageContent() {
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
...(readOnly ? [] : [{
|
||||
id: "actions",
|
||||
header: t("CatActions"),
|
||||
cell: ({ row }) => (
|
||||
cell: ({ row }: { row: { original: AdminInterestEntity } }) => (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -236,21 +238,21 @@ function InterestsPageContent() {
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
}]),
|
||||
],
|
||||
[t, refetch],
|
||||
[t, refetch, readOnly],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("BO_INTERESTS")}
|
||||
actions={
|
||||
actions={readOnly ? undefined : (
|
||||
<Button onClick={() => setDialog(EMPTY_FORM)}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("IntAddInterest")}
|
||||
</Button>
|
||||
}
|
||||
)}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
@@ -13,7 +13,9 @@ import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
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 { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { exportLeads, listLeads } from "@/app/lib/services/adminLeads";
|
||||
import type { LeadRow } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
@@ -22,9 +24,11 @@ const DEFAULTS = { q: "" };
|
||||
|
||||
function LeadsPageContent() {
|
||||
const t = useT();
|
||||
const { companyId, showCompanyColumn, codeOf } = useCompanyScope();
|
||||
const { hasModule } = useAdminAuth();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
useResetPageOnCompany(setPage);
|
||||
const [data, setData] = useState<{ items: LeadRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
@@ -36,7 +40,7 @@ function LeadsPageContent() {
|
||||
const runExport = () => {
|
||||
setExporting(true);
|
||||
setExportError(null);
|
||||
exportLeads({ q: filters.q || undefined })
|
||||
exportLeads({ q: filters.q || undefined, companyId })
|
||||
.catch((err: unknown) => {
|
||||
const tooLarge = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "EXPORT_TOO_LARGE";
|
||||
setExportError(tooLarge ? t("LeadsExportTooLarge") : err instanceof Error ? err.message : t("LeadListLoadFailed"));
|
||||
@@ -53,12 +57,12 @@ function LeadsPageContent() {
|
||||
setLoading(true);
|
||||
setFailed(false);
|
||||
setExportError(null);
|
||||
listLeads({ q: filters.q || undefined, page, pageSize })
|
||||
listLeads({ q: filters.q || undefined, 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 columns = useMemo<ColumnDef<LeadRow, unknown>[]>(
|
||||
() => [
|
||||
@@ -72,6 +76,7 @@ function LeadsPageContent() {
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<LeadRow, unknown>] : []),
|
||||
{ accessorKey: "mobile", header: t("LeadMobile"), enableSorting: false },
|
||||
{ accessorKey: "email", header: t("Email"), enableSorting: false },
|
||||
{ accessorKey: "companyName", header: t("LeadCompany"), enableSorting: false },
|
||||
@@ -79,7 +84,7 @@ function LeadsPageContent() {
|
||||
{ id: "lastEvent", header: t("LeadsLastEvent"), enableSorting: false, cell: ({ row }) => row.original.lastEvent?.name ?? "" },
|
||||
{ id: "latestSalesperson", header: t("LeadsLatestSalesperson"), enableSorting: false, cell: ({ row }) => row.original.latestSalesperson?.name ?? "" },
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { AdminAuthProvider, useAdminAuth } from "./AdminAuthContext";
|
||||
|
||||
function Probe() {
|
||||
const { companyId, companyCode, isSuper, loading } = useAdminAuth();
|
||||
return <div data-testid="p">{loading ? "loading" : `${companyId}|${companyCode}|${isSuper}`}</div>;
|
||||
}
|
||||
|
||||
function stub(body: unknown, ok = true) {
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok, status: ok ? 200 : 401, json: async () => body }));
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe("AdminAuthContext company", () => {
|
||||
it("holds the company and isSuper from the session", async () => {
|
||||
stub({ name: "J", roles: [], aclMenu: null, companyId: 7, companyCode: "ins", isSuper: false });
|
||||
render(<AdminAuthProvider><Probe /></AdminAuthProvider>);
|
||||
await waitFor(() => expect(screen.getByTestId("p")).toHaveTextContent("7|ins|false"));
|
||||
});
|
||||
|
||||
it("holds isSuper for a super admin with no company", async () => {
|
||||
stub({ name: "R", roles: [], aclMenu: null, companyId: null, companyCode: null, isSuper: true });
|
||||
render(<AdminAuthProvider><Probe /></AdminAuthProvider>);
|
||||
await waitFor(() => expect(screen.getByTestId("p")).toHaveTextContent("null|null|true"));
|
||||
});
|
||||
|
||||
it("clears them when the session fails", async () => {
|
||||
stub({}, false);
|
||||
render(<AdminAuthProvider><Probe /></AdminAuthProvider>);
|
||||
await waitFor(() => expect(screen.getByTestId("p")).toHaveTextContent("null|null|false"));
|
||||
});
|
||||
});
|
||||
@@ -20,6 +20,10 @@ interface AdminAuthCtx {
|
||||
/** The signed-in admin's assigned branch (add-branch-counter-sale). Null when unassigned —
|
||||
* the Branch Counter POS page must show an empty state and suppress Place-sale. */
|
||||
branch: AdminBranchRef | null;
|
||||
/** The signed-in admin's company; null for a super admin. */
|
||||
companyId: number | null;
|
||||
companyCode: string | null;
|
||||
isSuper: boolean;
|
||||
loading: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
/** Matches over roles[].name, e.g. hasRole("ROLE_ADMIN"). */
|
||||
@@ -37,6 +41,9 @@ const AdminAuthContext = createContext<AdminAuthCtx>({
|
||||
roles: [],
|
||||
aclMenu: null,
|
||||
branch: null,
|
||||
companyId: null,
|
||||
companyCode: null,
|
||||
isSuper: false,
|
||||
loading: true,
|
||||
refresh: async () => {},
|
||||
hasRole: () => false,
|
||||
@@ -64,6 +71,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
const [aclMenu, setAclMenu] = useState<AdminModule | null>(null);
|
||||
const [grantedMenu, setGrantedMenu] = useState<AdminModule | null>(null);
|
||||
const [branch, setBranch] = useState<AdminBranchRef | null>(null);
|
||||
const [companyId, setCompanyId] = useState<number | null>(null);
|
||||
const [companyCode, setCompanyCode] = useState<string | null>(null);
|
||||
const [isSuper, setIsSuper] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
@@ -79,6 +89,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
setAclMenu(null);
|
||||
setGrantedMenu(null);
|
||||
setBranch(null);
|
||||
setCompanyId(null);
|
||||
setCompanyCode(null);
|
||||
setIsSuper(false);
|
||||
return;
|
||||
}
|
||||
const data = (await res.json()) as {
|
||||
@@ -88,6 +101,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
roles: AdminRole[];
|
||||
aclMenu: AdminModule;
|
||||
branch?: AdminBranchRef | null;
|
||||
companyId?: number | null;
|
||||
companyCode?: string | null;
|
||||
isSuper?: boolean;
|
||||
};
|
||||
setId(data.id ?? null);
|
||||
setUsername(data.username ?? null);
|
||||
@@ -96,6 +112,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
setAclMenu(data.aclMenu ?? null);
|
||||
setGrantedMenu(data.aclMenu ?? null);
|
||||
setBranch(data.branch ?? null);
|
||||
setCompanyId(data.companyId ?? null);
|
||||
setCompanyCode(data.companyCode ?? null);
|
||||
setIsSuper(data.isSuper === true);
|
||||
} catch {
|
||||
setId(null);
|
||||
setUsername(null);
|
||||
@@ -104,6 +123,9 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
setAclMenu(null);
|
||||
setGrantedMenu(null);
|
||||
setBranch(null);
|
||||
setCompanyId(null);
|
||||
setCompanyCode(null);
|
||||
setIsSuper(false);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -130,7 +152,7 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
return (
|
||||
<AdminAuthContext.Provider
|
||||
value={{ id, username, name, roles, aclMenu, branch, loading, refresh: load, hasRole, hasModule, hasGrantedModule }}
|
||||
value={{ id, username, name, roles, aclMenu, branch, companyId, companyCode, isSuper, loading, refresh: load, hasRole, hasModule, hasGrantedModule }}
|
||||
>
|
||||
{children}
|
||||
</AdminAuthContext.Provider>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ useAdminAuth: vi.fn(), listAdminCompanies: vi.fn() }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/services/adminCompanies", () => ({ listAdminCompanies: mocks.listAdminCompanies }));
|
||||
|
||||
import { CompanyScopeProvider, useCompanyScope } from "./CompanyScope";
|
||||
|
||||
function Probe() {
|
||||
const s = useCompanyScope();
|
||||
return <p data-testid="probe">{String(s.companyId)}</p>;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ isSuper: true });
|
||||
mocks.listAdminCompanies.mockReset().mockResolvedValue([{ id: 1, name: "Ins Co", code: "INS", status: "A" }]);
|
||||
});
|
||||
|
||||
describe("stored company choice", () => {
|
||||
it("falls back to All companies when the stored id is not in the companies list", async () => {
|
||||
sessionStorage.setItem("company-scope", "99");
|
||||
render(<CompanyScopeProvider><Probe /></CompanyScopeProvider>);
|
||||
await waitFor(() => expect(mocks.listAdminCompanies).toHaveBeenCalled());
|
||||
await waitFor(() => expect(screen.getByTestId("probe")).toHaveTextContent("undefined"));
|
||||
expect(sessionStorage.getItem("company-scope")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ useAdminAuth: vi.fn(), listAdminCompanies: vi.fn() }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/services/adminCompanies", () => ({ listAdminCompanies: mocks.listAdminCompanies }));
|
||||
|
||||
import { CompanyScopeProvider, useCompanyScope } from "./CompanyScope";
|
||||
import CompanyPicker from "@/app/components/app/CompanyPicker";
|
||||
|
||||
const COMPANIES = [
|
||||
{ id: 1, name: "Ins Co", code: "INS", status: "A" },
|
||||
{ id: 2, name: "CV Co", code: "CV", status: "A" },
|
||||
];
|
||||
|
||||
function Probe() {
|
||||
const s = useCompanyScope();
|
||||
return <p data-testid="probe">{String(s.companyId)}|{String(s.showCompanyColumn)}|{s.codeOf(2)}</p>;
|
||||
}
|
||||
const renderScope = () =>
|
||||
render(
|
||||
<CompanyScopeProvider>
|
||||
<CompanyPicker />
|
||||
<Probe />
|
||||
</CompanyScopeProvider>,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
mocks.listAdminCompanies.mockReset().mockResolvedValue(COMPANIES);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ isSuper: true });
|
||||
});
|
||||
|
||||
describe("CompanyPicker", () => {
|
||||
it("is shown to a super admin with All companies plus each company", async () => {
|
||||
renderScope();
|
||||
const picker = await screen.findByRole("combobox", { name: "Company" });
|
||||
await waitFor(() => expect(picker.querySelectorAll("option")).toHaveLength(3));
|
||||
expect([...picker.querySelectorAll("option")].map((o) => o.textContent)).toEqual(["All companies", "INS", "CV"]);
|
||||
expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV");
|
||||
});
|
||||
|
||||
it("is not shown to staff, who never load companies or get a companyId", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: false });
|
||||
sessionStorage.setItem("company-scope", "2");
|
||||
renderScope();
|
||||
expect(screen.queryByRole("combobox", { name: "Company" })).not.toBeInTheDocument();
|
||||
expect(mocks.listAdminCompanies).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId("probe")).toHaveTextContent("undefined|false|");
|
||||
});
|
||||
|
||||
it("feeds the chosen company into the scope and keeps it for the tab; All companies clears it", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderScope();
|
||||
const picker = await screen.findByRole("combobox", { name: "Company" });
|
||||
await waitFor(() => expect(picker.querySelectorAll("option")).toHaveLength(3));
|
||||
await user.selectOptions(picker, "2");
|
||||
expect(screen.getByTestId("probe")).toHaveTextContent("2|false|CV");
|
||||
expect(sessionStorage.getItem("company-scope")).toBe("2");
|
||||
await user.selectOptions(picker, "");
|
||||
expect(screen.getByTestId("probe")).toHaveTextContent("undefined|true|CV");
|
||||
expect(sessionStorage.getItem("company-scope")).toBeNull();
|
||||
});
|
||||
|
||||
it("restores the choice from sessionStorage", async () => {
|
||||
sessionStorage.setItem("company-scope", "1");
|
||||
renderScope();
|
||||
await waitFor(() => expect(screen.getByTestId("probe")).toHaveTextContent("1|false|CV"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { listAdminCompanies } from "@/app/lib/services/adminCompanies";
|
||||
import type { AdminCompany } from "@/app/lib/types";
|
||||
|
||||
// A super admin's company picker choice, kept per tab. Staff get no scope at all:
|
||||
// companyId stays undefined for them, so they never send the query param.
|
||||
const KEY = "company-scope";
|
||||
|
||||
interface CompanyScope {
|
||||
/** The picked company; undefined for "All companies" and for staff. */
|
||||
companyId: number | undefined;
|
||||
setCompanyId: (id: number | undefined) => void;
|
||||
companies: AdminCompany[];
|
||||
/** True for a super admin looking at All companies: lists then show a Company column. */
|
||||
showCompanyColumn: boolean;
|
||||
/** Company code for a row's companyId ("" when unknown). */
|
||||
codeOf: (id?: number | null) => string;
|
||||
}
|
||||
|
||||
const Ctx = createContext<CompanyScope>({
|
||||
companyId: undefined,
|
||||
setCompanyId: () => {},
|
||||
companies: [],
|
||||
showCompanyColumn: false,
|
||||
codeOf: () => "",
|
||||
});
|
||||
|
||||
export const useCompanyScope = () => useContext(Ctx);
|
||||
|
||||
function readStored(): number | undefined {
|
||||
try {
|
||||
const n = Number(sessionStorage.getItem(KEY));
|
||||
return n > 0 ? n : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function clearStoredCompany() {
|
||||
try {
|
||||
sessionStorage.removeItem(KEY);
|
||||
} catch {
|
||||
// Storage blocked: nothing was stored.
|
||||
}
|
||||
}
|
||||
|
||||
export function CompanyScopeProvider({ children }: { children: ReactNode }) {
|
||||
const { isSuper } = useAdminAuth();
|
||||
const [picked, setPicked] = useState<number | undefined>(readStored);
|
||||
const [companies, setCompanies] = useState<AdminCompany[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSuper) return;
|
||||
let live = true;
|
||||
listAdminCompanies()
|
||||
.then((c) => {
|
||||
if (!live) return;
|
||||
setCompanies(c);
|
||||
// A stored choice that is no longer a company (removed, or another login's) means All companies.
|
||||
const stored = readStored();
|
||||
if (stored !== undefined && !c.some((x) => x.id === stored)) {
|
||||
clearStoredCompany();
|
||||
setPicked(undefined);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => { live = false; };
|
||||
}, [isSuper]);
|
||||
|
||||
const value = useMemo<CompanyScope>(() => {
|
||||
const companyId = isSuper ? picked : undefined;
|
||||
return {
|
||||
companyId,
|
||||
setCompanyId: (id) => {
|
||||
setPicked(id);
|
||||
try {
|
||||
if (id === undefined) clearStoredCompany();
|
||||
else sessionStorage.setItem(KEY, String(id));
|
||||
} catch {
|
||||
// Storage blocked: the choice just lasts until reload.
|
||||
}
|
||||
},
|
||||
companies,
|
||||
showCompanyColumn: !!isSuper && companyId === undefined,
|
||||
codeOf: (id) => companies.find((c) => c.id === id)?.code ?? "",
|
||||
};
|
||||
}, [isSuper, picked, companies]);
|
||||
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
"use client";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
|
||||
/** A different company is a different list: go back to page 1 when the picker changes (not on first render). */
|
||||
export function useResetPageOnCompany(setPage: (p: number) => void) {
|
||||
const { companyId } = useCompanyScope();
|
||||
const last = useRef(companyId);
|
||||
useEffect(() => {
|
||||
if (last.current === companyId) return;
|
||||
last.current = companyId;
|
||||
setPage(1);
|
||||
}, [companyId, setPage]);
|
||||
}
|
||||
@@ -16,6 +16,27 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
BackOfficePanelEvents: "Events and attendees",
|
||||
BackOfficePanelLeads: "Leads captured at every event",
|
||||
BackOfficePanelFollowUps: "Follow-ups for your sales team",
|
||||
Company: "Company",
|
||||
AllCompanies: "All companies",
|
||||
CompanySuperAdmin: "Super admin (no company)",
|
||||
ChooseCompany: "Choose a company.",
|
||||
SuperAdminNeedsRole: "A super admin must have the Super admin role.",
|
||||
CompanyBlankForSuper: "Leave blank for super admin",
|
||||
BO_COMPANIES: "Companies",
|
||||
CompAdd: "Add company",
|
||||
CompEdit: "Edit company",
|
||||
CompNewCode: "New code",
|
||||
CompChangeCode: "Change code",
|
||||
CompChangeCodeWarning: "Changing the code changes every staff login name of this company and signs them out.",
|
||||
CompConfirm: "Confirm",
|
||||
CompActive: "Active",
|
||||
CompInactive: "Inactive",
|
||||
CompNone: "No companies found",
|
||||
CompLoadFailed: "Failed to load companies",
|
||||
CompSaveFailed: "Failed to save company.",
|
||||
CompNameRequired: "Name is required.",
|
||||
CompCodeUnchanged: "The new code is the same as the current code.",
|
||||
CompCodeRequired: "Code is required.",
|
||||
Username: "Username",
|
||||
Password: "Password",
|
||||
LogIn: "Log in",
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { apiGet, apiPost } from "@/app/lib/clientApi";
|
||||
import type { AdminCompany } from "@/app/lib/types";
|
||||
|
||||
export const listAdminCompanies = () => apiGet<AdminCompany[]>("/api/companies");
|
||||
|
||||
/** Create when `id` is absent; otherwise edit name and status. */
|
||||
export const saveAdminCompany = (company: Partial<AdminCompany>) => apiPost<AdminCompany>("/api/companies", company);
|
||||
|
||||
export const changeAdminCompanyCode = (id: number, code: string) =>
|
||||
apiPost<AdminCompany>(`/api/companies/${id}/code`, { code });
|
||||
@@ -9,6 +9,7 @@ export interface EmailRow {
|
||||
subject: string;
|
||||
/** P pending, N failed, Y success. */
|
||||
status: string;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface EmailDetail extends Omit<EmailRow, "recipients"> {
|
||||
@@ -26,11 +27,13 @@ export interface EmailListParams {
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export async function listEmails(params: EmailListParams): Promise<{ items: EmailRow[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of ["recipient", "subject", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
|
||||
if (params.companyId) qs.set("companyId", String(params.companyId));
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: EmailRow[]; totalElements?: number } | null>(`/api/emails?${qs}`);
|
||||
|
||||
@@ -18,9 +18,11 @@ export interface EventLeadListParams extends EventLeadFilters {
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export const listEventLeadEvents = () => apiGet<EventLeadEvent[]>(`${BASE}/events`);
|
||||
export const listEventLeadEvents = (companyId?: number) =>
|
||||
apiGet<EventLeadEvent[]>(`${BASE}/events${companyId ? `?companyId=${companyId}` : ""}`);
|
||||
export const listEventLeadInterests = () => apiGet<InterestOption[]>(`${BASE}/interest-options`);
|
||||
export const listEventSalespeople = (eventUuid: string) =>
|
||||
apiGet<SalespersonOption[]>(`${BASE}/${eventUuid}/salesperson-options`);
|
||||
@@ -28,6 +30,7 @@ export const listEventSalespeople = (eventUuid: string) =>
|
||||
export async function listEventLeads(eventUuid: string, params: EventLeadListParams): Promise<{ items: EventLeadRow[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of FILTERS) if (params[key]) qs.set(key, params[key]);
|
||||
if (params.companyId) qs.set("companyId", String(params.companyId));
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: EventLeadRow[]; totalElements?: number } | null>(`${BASE}/${eventUuid}/leads?${qs}`);
|
||||
@@ -35,8 +38,8 @@ export async function listEventLeads(eventUuid: string, params: EventLeadListPar
|
||||
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
|
||||
}
|
||||
|
||||
export const matchLead = (eventUuid: string, contact: { mobile: string | null; email: string | null }) =>
|
||||
apiPost<LeadMatchResult>(`${BASE}/${eventUuid}/match`, contact);
|
||||
export const matchLead = (eventUuid: string, contact: { mobile: string | null; email: string | null }, companyId?: number) =>
|
||||
apiPost<LeadMatchResult>(`${BASE}/${eventUuid}/match`, companyId ? { ...contact, companyId } : contact);
|
||||
export const captureEventLead = (eventUuid: string, payload: EventLeadCapturePayload) =>
|
||||
apiPost<EventLeadRow>(`${BASE}/${eventUuid}`, payload);
|
||||
export const getEventLead = (eventUuid: string, eventLeadUuid: string) =>
|
||||
@@ -44,8 +47,9 @@ export const getEventLead = (eventUuid: string, eventLeadUuid: string) =>
|
||||
export const updateEventLead = (eventUuid: string, eventLeadUuid: string, payload: EventLeadUpdatePayload) =>
|
||||
apiPut<EventLeadRow>(`${BASE}/${eventUuid}/leads/${eventLeadUuid}`, payload);
|
||||
|
||||
export function exportEventLeads(eventUuid: string, filters: EventLeadFilters) {
|
||||
export function exportEventLeads(eventUuid: string, filters: EventLeadFilters, companyId?: number) {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of FILTERS) if (filters[key]) qs.set(key, filters[key]);
|
||||
if (companyId) qs.set("companyId", String(companyId));
|
||||
return apiDownload(`${BASE}/${eventUuid}/export${qs.size ? `?${qs}` : ""}`, "event-leads.xlsx");
|
||||
}
|
||||
@@ -8,6 +8,7 @@ export interface AdminEventListParams {
|
||||
pageSize: number;
|
||||
sortBy?: string;
|
||||
sortDir?: "asc" | "desc";
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface AdminEventListResult {
|
||||
@@ -27,6 +28,7 @@ export async function listAdminEvents(params: AdminEventListParams): Promise<Adm
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.enabled) qs.set("enabled", params.enabled);
|
||||
if (params.companyId) qs.set("companyId", String(params.companyId));
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
if (params.sortBy) qs.set("sortBy", params.sortBy);
|
||||
@@ -45,6 +47,6 @@ export async function saveAdminEvent(payload: AdminEventPayload, uuid?: string):
|
||||
: apiPost<AdminEvent>("/api/events", payload);
|
||||
}
|
||||
|
||||
export async function listSalespersonOptions(): Promise<SalespersonOption[]> {
|
||||
return apiGet<SalespersonOption[]>("/api/events/salesperson-options");
|
||||
export async function listSalespersonOptions(companyId?: number): Promise<SalespersonOption[]> {
|
||||
return apiGet<SalespersonOption[]>(`/api/events/salesperson-options${companyId ? `?companyId=${companyId}` : ""}`);
|
||||
}
|
||||
@@ -3,9 +3,10 @@ import type { LeadDetail, LeadRow, LeadUpdatePayload } from "@/app/lib/types";
|
||||
|
||||
const BASE = "/api/leads";
|
||||
|
||||
export async function listLeads(params: { q?: string; /** 1-based. */ page: number; pageSize: number }): Promise<{ items: LeadRow[]; total: number }> {
|
||||
export async function listLeads(params: { q?: string; /** 1-based. */ page: number; pageSize: number; companyId?: number }): Promise<{ items: LeadRow[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.companyId) qs.set("companyId", String(params.companyId));
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: LeadRow[]; totalElements?: number } | null>(`${BASE}?${qs}`);
|
||||
@@ -16,5 +17,9 @@ export async function listLeads(params: { q?: string; /** 1-based. */ page: numb
|
||||
export const getLead = (uuid: string) => apiGet<LeadDetail>(`${BASE}/${uuid}`);
|
||||
export const updateLead = (uuid: string, payload: LeadUpdatePayload) => apiPut<LeadDetail>(`${BASE}/${uuid}`, payload);
|
||||
|
||||
export const exportLeads = (params: { q?: string }) =>
|
||||
apiDownload(`${BASE}/export${params.q ? `?${new URLSearchParams({ q: params.q })}` : ""}`, "leads.xlsx");
|
||||
export function exportLeads(params: { q?: string; companyId?: number }) {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.companyId) qs.set("companyId", String(params.companyId));
|
||||
return apiDownload(`${BASE}/export${qs.size ? `?${qs}` : ""}`, "leads.xlsx");
|
||||
}
|
||||
@@ -15,6 +15,8 @@ export interface AdminUserListParams {
|
||||
/** Server-side sort: attribute name + direction; sent only when present. */
|
||||
sortBy?: string;
|
||||
sortDir?: "asc" | "desc";
|
||||
/** Super admin's company choice; omitted for All companies. */
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface AdminUserListResult {
|
||||
@@ -45,6 +47,7 @@ export async function listAdminUsers(params: AdminUserListParams): Promise<Admin
|
||||
if (params.searchKey) qs.set("searchKey", params.searchKey);
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.enabled) qs.set("enabled", params.enabled);
|
||||
if (params.companyId) qs.set("companyId", String(params.companyId));
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
if (params.sortBy) qs.set("sortBy", params.sortBy);
|
||||
|
||||
@@ -29,6 +29,7 @@ export interface AuditLogParams {
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
const BASE = "/api/audit-log";
|
||||
@@ -36,6 +37,7 @@ const BASE = "/api/audit-log";
|
||||
export async function searchAuditLog(params: AuditLogParams): Promise<{ items: AuditEvent[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of ["actor", "module", "action", "outcome", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
|
||||
if (params.companyId) qs.set("companyId", String(params.companyId));
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: AuditEvent[]; totalElements?: number } | null>(`${BASE}?${qs}`);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn(), apiDownload: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import { listAdminUsers } from "./adminUsers";
|
||||
import { listAdminEvents, listSalespersonOptions } from "./adminEvents";
|
||||
import { exportLeads, listLeads } from "./adminLeads";
|
||||
import { exportEventLeads, listEventLeadEvents, listEventLeads, matchLead } from "./adminEventLeads";
|
||||
import { listEmails } from "./adminEmails";
|
||||
import { searchAuditLog } from "./auditLog";
|
||||
import { listAudit, listLocked, unlock } from "./loginSecurity";
|
||||
|
||||
const url = (m: { mock: { calls: unknown[][] } }) => String(m.mock.calls.at(-1)?.[0]);
|
||||
|
||||
beforeEach(() => {
|
||||
for (const m of Object.values(mocks)) m.mockReset().mockResolvedValue({ content: [], totalElements: 0, items: [], total: 0 });
|
||||
});
|
||||
|
||||
describe("companyId on list and export queries", () => {
|
||||
it("adds it to the users list only when set", async () => {
|
||||
await listAdminUsers({ page: 1, pageSize: 20, companyId: 2 });
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await listAdminUsers({ page: 1, pageSize: 20 });
|
||||
expect(url(mocks.apiGet)).not.toContain("companyId");
|
||||
});
|
||||
|
||||
it("adds it to events list and salesperson options", async () => {
|
||||
await listAdminEvents({ page: 1, pageSize: 20, companyId: 2 });
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await listSalespersonOptions(3);
|
||||
expect(mocks.apiGet).toHaveBeenLastCalledWith("/api/events/salesperson-options?companyId=3");
|
||||
await listSalespersonOptions();
|
||||
expect(mocks.apiGet).toHaveBeenLastCalledWith("/api/events/salesperson-options");
|
||||
});
|
||||
|
||||
it("adds it to leads list and export", async () => {
|
||||
await listLeads({ page: 1, pageSize: 20, companyId: 2 });
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await exportLeads({ q: "x", companyId: 2 });
|
||||
expect(url(mocks.apiDownload)).toContain("companyId=2");
|
||||
await exportLeads({});
|
||||
expect(url(mocks.apiDownload)).not.toContain("companyId");
|
||||
});
|
||||
|
||||
it("adds it to event-lead events, leads and export", async () => {
|
||||
await listEventLeadEvents(2);
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await listEventLeadEvents();
|
||||
expect(url(mocks.apiGet)).not.toContain("companyId");
|
||||
await listEventLeads("e1", { page: 1, pageSize: 20, companyId: 2 });
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await exportEventLeads("e1", {}, 2);
|
||||
expect(url(mocks.apiDownload)).toContain("companyId=2");
|
||||
});
|
||||
|
||||
it("adds it to emails, audit log, login history, locked list and unlock", async () => {
|
||||
await listEmails({ page: 1, pageSize: 20, companyId: 2 });
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await searchAuditLog({ page: 1, pageSize: 20, companyId: 2 });
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await listAudit({ page: 1, pageSize: 20, companyId: 2 });
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await listLocked(2);
|
||||
expect(url(mocks.apiGet)).toContain("companyId=2");
|
||||
await unlock("jane", 2);
|
||||
expect(url(mocks.apiPost)).toContain("companyId=2");
|
||||
});
|
||||
|
||||
it("puts companyId in the lead match body only when given", async () => {
|
||||
await matchLead("e1", { mobile: "1", email: null }, 2);
|
||||
expect(mocks.apiPost).toHaveBeenLastCalledWith(expect.any(String), { mobile: "1", email: null, companyId: 2 });
|
||||
await matchLead("e1", { mobile: "1", email: null });
|
||||
expect(mocks.apiPost.mock.calls.at(-1)?.[1]).toEqual({ mobile: "1", email: null });
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ export interface AuditRow {
|
||||
ipAddress: string | null;
|
||||
userAgent: string | null;
|
||||
message: string | null;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface AuditParams {
|
||||
@@ -23,6 +24,7 @@ export interface AuditParams {
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface LockedAccount {
|
||||
@@ -30,6 +32,7 @@ export interface LockedAccount {
|
||||
failures: number;
|
||||
lastFailure: string | null;
|
||||
lockedUntil: string | null;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface LockoutConfig {
|
||||
@@ -53,6 +56,7 @@ const BASE = "/api/login-security";
|
||||
export async function listAudit(params: AuditParams): Promise<{ items: AuditRow[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of ["username", "event", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
|
||||
if (params.companyId) qs.set("companyId", String(params.companyId));
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: AuditRow[]; totalElements?: number } | null>(`${BASE}/audit?${qs}`);
|
||||
@@ -60,8 +64,10 @@ export async function listAudit(params: AuditParams): Promise<{ items: AuditRow[
|
||||
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
|
||||
}
|
||||
|
||||
export const listLocked = () => apiGet<LockedAccount[]>(`${BASE}/locked`);
|
||||
export const unlock = (username: string) => apiPost<void>(`${BASE}/locked/${encodeURIComponent(username)}/unlock`);
|
||||
const scoped = (companyId?: number) => (companyId ? `?companyId=${companyId}` : "");
|
||||
export const listLocked = (companyId?: number) => apiGet<LockedAccount[]>(`${BASE}/locked${scoped(companyId)}`);
|
||||
export const unlock = (username: string, companyId?: number) =>
|
||||
apiPost<void>(`${BASE}/locked/${encodeURIComponent(username)}/unlock${scoped(companyId)}`);
|
||||
export const getConfig = () => apiGet<LockoutConfig>(`${BASE}/config`);
|
||||
export const saveConfig = (cfg: LockoutConfig) => apiPut<LockoutConfig>(`${BASE}/config`, cfg);
|
||||
export const getPasswordRules = () => apiGet<PasswordRule[]>(`${BASE}/password-rules`);
|
||||
|
||||
@@ -60,6 +60,9 @@ export interface AdminLoginResponse {
|
||||
aclMenu: AdminModule;
|
||||
/** The mobile-api serializes this as the string "true"/"false", not a boolean. */
|
||||
resetPasswordRequired: string;
|
||||
companyId?: number | null;
|
||||
companyCode?: string | null;
|
||||
isSuper?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,6 +85,9 @@ export interface AdminMeResponse {
|
||||
roles: AdminRole[];
|
||||
aclMenu: AdminModule;
|
||||
branch?: AdminBranchRef | null;
|
||||
companyId?: number | null;
|
||||
companyCode?: string | null;
|
||||
isSuper?: boolean;
|
||||
}
|
||||
|
||||
/** Session payload returned by GET /api/auth/session after hydration. */
|
||||
@@ -90,6 +96,17 @@ export interface AdminSession {
|
||||
roles: AdminRole[];
|
||||
aclMenu: AdminModule;
|
||||
branch?: AdminBranchRef | null;
|
||||
companyId?: number | null;
|
||||
companyCode?: string | null;
|
||||
isSuper?: boolean;
|
||||
}
|
||||
|
||||
/** A company, as served by /api/admin/companies; status is "A" (active) or "I" (inactive). */
|
||||
export interface AdminCompany {
|
||||
id?: number;
|
||||
name: string;
|
||||
code: string;
|
||||
status: "A" | "I";
|
||||
}
|
||||
|
||||
/** Mirrors solvway-mobile-api's com.solvway.mobile.api.model.AdminUser. Deliberately has no
|
||||
@@ -103,6 +120,13 @@ export interface AdminUser {
|
||||
enabled: boolean;
|
||||
status?: "Y" | "N" | "P";
|
||||
roles: AdminRole[];
|
||||
/** Set by the server on rows; sent on create by super admins. */
|
||||
companyId?: number;
|
||||
companyCode?: string;
|
||||
/** Full "local@code"; `username` is the local part. */
|
||||
loginName?: string;
|
||||
/** Create only: a super admin with no company. */
|
||||
superAdmin?: boolean;
|
||||
}
|
||||
|
||||
/** One flat row of the ACL grant matrix for a role (GET/PUT
|
||||
@@ -125,6 +149,7 @@ export interface AdminEvent {
|
||||
endDate: string;
|
||||
enabled: boolean;
|
||||
team?: AdminEventMember[];
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface AdminEventMember {
|
||||
@@ -142,6 +167,7 @@ export interface AdminEventPayload {
|
||||
endDate: string;
|
||||
enabled?: boolean;
|
||||
salespersonIds: number[];
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
/** A salesperson row from the salesperson-options endpoint. */
|
||||
@@ -171,6 +197,7 @@ export interface EventLeadEvent {
|
||||
location: string | null;
|
||||
startDate: string | null;
|
||||
endDate: string | null;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface InterestOption {
|
||||
@@ -213,6 +240,7 @@ export interface EventLeadRow {
|
||||
nextFollowUpDate: string | null;
|
||||
notes: string | null;
|
||||
capturedAt: string;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
export interface EventLeadUpdatePayload {
|
||||
@@ -232,6 +260,7 @@ export interface EventLeadCapturePayload extends EventLeadUpdatePayload {
|
||||
email?: string | null;
|
||||
companyName?: string | null;
|
||||
jobTitle?: string | null;
|
||||
companyId?: number;
|
||||
}
|
||||
|
||||
/** Lead records (`/api/admin/leads`). */
|
||||
@@ -241,6 +270,7 @@ export interface LeadRow {
|
||||
mobile: string | null;
|
||||
email: string | null;
|
||||
companyName: string | null;
|
||||
companyId?: number;
|
||||
jobTitle: string | null;
|
||||
eventCount: number;
|
||||
lastEvent: { uuid: string; name: string | null } | null;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ isSuper: false }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({
|
||||
useAdminAuth: () => ({ aclMenu: { name: "root", type: "R", children: [{ name: "BO_DASHBOARD", type: "M", url: "/" }] }, isSuper: mocks.isSuper }),
|
||||
}));
|
||||
|
||||
import { useAclSidebar } from "./useAclSidebar";
|
||||
|
||||
function Probe() {
|
||||
return <div data-testid="n">{useAclSidebar().map((l) => `${l.name}:${l.url}`).join(",")}</div>;
|
||||
}
|
||||
|
||||
describe("useAclSidebar Companies link", () => {
|
||||
it("is added for super admins", () => {
|
||||
mocks.isSuper = true;
|
||||
render(<Probe />);
|
||||
expect(screen.getByTestId("n")).toHaveTextContent("BO_DASHBOARD:/,BO_COMPANIES:/companies");
|
||||
});
|
||||
|
||||
it("is absent for everyone else", () => {
|
||||
mocks.isSuper = false;
|
||||
render(<Probe />);
|
||||
expect(screen.getByTestId("n").textContent).toBe("BO_DASHBOARD:/");
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,13 @@ import { sidebarFromAclMenu, type SidebarLink } from "@/app/lib/aclSidebar";
|
||||
* Order and grouping follow the aclMenu tree (siblings by module id);
|
||||
*/
|
||||
export function useAclSidebar(): SidebarLink[] {
|
||||
const { aclMenu } = useAdminAuth();
|
||||
return useMemo(() => sidebarFromAclMenu(aclMenu), [aclMenu]);
|
||||
const { aclMenu, isSuper } = useAdminAuth();
|
||||
// Companies is gated by isSuper, not by a module, so it is not in the aclMenu tree.
|
||||
return useMemo(
|
||||
() => [
|
||||
...sidebarFromAclMenu(aclMenu),
|
||||
...(isSuper ? [{ name: "BO_COMPANIES", url: "/companies", iconName: "Store", children: [] }] : []),
|
||||
],
|
||||
[aclMenu, isSuper],
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
@@ -17,6 +19,7 @@ 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 { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails";
|
||||
import {
|
||||
@@ -31,8 +34,10 @@ const errMessage = (err: unknown, fallback: string) => (err instanceof Error ? e
|
||||
|
||||
function HistoryTab() {
|
||||
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: AuditRow[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
@@ -52,17 +57,19 @@ function HistoryTab() {
|
||||
to: filters.to || undefined,
|
||||
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 eventOptions = useMemo(() => LOGIN_EVENTS.map((e) => ({ value: e, label: t(LOGIN_EVENT_KEYS[e]) })), [t]);
|
||||
const columns = useMemo<ColumnDef<AuditRow, unknown>[]>(
|
||||
() => [
|
||||
{ id: "datetime", header: t("LsTime"), enableSorting: false, cell: ({ row }) => formatDate(row.original.datetime) },
|
||||
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<AuditRow, unknown>] : []),
|
||||
{ accessorKey: "username", header: t("Username"), enableSorting: false },
|
||||
{ id: "event", header: t("LsEvent"), enableSorting: false, cell: ({ row }) => t(LOGIN_EVENT_KEYS[row.original.event] ?? row.original.event) },
|
||||
{ accessorKey: "ipAddress", header: t("LsIp"), enableSorting: false },
|
||||
@@ -74,7 +81,7 @@ function HistoryTab() {
|
||||
},
|
||||
{ accessorKey: "message", header: t("LsNote"), enableSorting: false },
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn, codeOf],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -113,6 +120,7 @@ function HistoryTab() {
|
||||
|
||||
function LockedTab() {
|
||||
const t = useT();
|
||||
const { companyId } = useCompanyScope();
|
||||
const [rows, setRows] = useState<LockedAccount[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -125,18 +133,18 @@ function LockedTab() {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading ahead of the reloadKey-triggered fetch below.
|
||||
setLoading(true);
|
||||
listLocked()
|
||||
(companyId ? listLocked(companyId) : listLocked())
|
||||
.then((result) => { if (!cancelled) { setRows(result); setError(null); } })
|
||||
.catch((err: unknown) => { if (!cancelled) setError(errMessage(err, "LsLockedLoadFailed")); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
}, [reloadKey]);
|
||||
}, [reloadKey, companyId]);
|
||||
|
||||
async function confirmUnlock() {
|
||||
if (!target) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await unlock(target);
|
||||
await (companyId ? unlock(target, companyId) : unlock(target));
|
||||
setError(null);
|
||||
refetch();
|
||||
} catch (err) {
|
||||
@@ -208,6 +216,7 @@ function NoticeLine({ notice }: { notice: Notice }) {
|
||||
|
||||
function LockoutForm() {
|
||||
const t = useT();
|
||||
const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway
|
||||
const [cfg, setCfg] = useState<LockoutConfig | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
@@ -241,21 +250,21 @@ function LockoutForm() {
|
||||
<section className="space-y-4 rounded-xl border bg-card p-4">
|
||||
<h2 className="text-base font-semibold">{t("LsLockoutTitle")}</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch id="ls-enabled" checked={cfg.enabled} onCheckedChange={(enabled) => setCfg({ ...cfg, enabled })} />
|
||||
<Switch id="ls-enabled" disabled={readOnly} checked={cfg.enabled} onCheckedChange={(enabled) => setCfg({ ...cfg, enabled })} />
|
||||
<Label htmlFor="ls-enabled">{t("LsLockoutOn")}</Label>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ls-max">{t("LsMaxAttempts")}</Label>
|
||||
<Input id="ls-max" type="number" min={1} value={cfg.maxAttempts || ""} onChange={(e) => setCfg({ ...cfg, maxAttempts: num(e.target.value) })} />
|
||||
<Input id="ls-max" disabled={readOnly} type="number" min={1} value={cfg.maxAttempts || ""} onChange={(e) => setCfg({ ...cfg, maxAttempts: num(e.target.value) })} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ls-period">{t("LsPeriod")}</Label>
|
||||
<Input id="ls-period" type="number" min={1} value={cfg.period || ""} onChange={(e) => setCfg({ ...cfg, period: num(e.target.value) })} />
|
||||
<Input id="ls-period" disabled={readOnly} type="number" min={1} value={cfg.period || ""} onChange={(e) => setCfg({ ...cfg, period: num(e.target.value) })} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>{t("LsUnit")}</Label>
|
||||
<Select value={cfg.unit} onValueChange={(unit) => setCfg({ ...cfg, unit: unit as LockoutConfig["unit"] })}>
|
||||
<Select disabled={readOnly} value={cfg.unit} onValueChange={(unit) => setCfg({ ...cfg, unit: unit as LockoutConfig["unit"] })}>
|
||||
<SelectTrigger aria-label={t("LsUnit")} className="w-full"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{LOCKOUT_UNITS.map((u) => <SelectItem key={u} value={u}>{t(`LsUnit${u}`)}</SelectItem>)}
|
||||
@@ -264,7 +273,7 @@ function LockoutForm() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button onClick={save} disabled={saving}>{t("LsSaveLockout")}</Button>
|
||||
{!readOnly && <Button onClick={save} disabled={saving}>{t("LsSaveLockout")}</Button>}
|
||||
<NoticeLine notice={notice} />
|
||||
</div>
|
||||
</section>
|
||||
@@ -275,6 +284,7 @@ type RuleEdit = { status: "Y" | "N"; value: string | null };
|
||||
|
||||
function PasswordRulesForm() {
|
||||
const t = useT();
|
||||
const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway
|
||||
const [rules, setRules] = useState<PasswordRule[] | null>(null);
|
||||
const [edits, setEdits] = useState<Record<number, RuleEdit>>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -329,11 +339,11 @@ function PasswordRulesForm() {
|
||||
<TableRow key={r.id}>
|
||||
<TableCell>{label}</TableCell>
|
||||
<TableCell>
|
||||
<Switch aria-label={label} checked={e.status === "Y"} onCheckedChange={(on) => edit(r.id, { status: on ? "Y" : "N" })} />
|
||||
<Switch aria-label={label} disabled={readOnly} checked={e.status === "Y"} onCheckedChange={(on) => edit(r.id, { status: on ? "Y" : "N" })} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{!FLAG_RULE_PARAMS.includes(r.param) && (
|
||||
<Input aria-label={`${label} ${t("LsRuleValue").toLowerCase()}`} type="number" min={0} className="w-24" value={e.value ?? ""} onChange={(ev) => edit(r.id, { value: ev.target.value })} />
|
||||
<Input aria-label={`${label} ${t("LsRuleValue").toLowerCase()}`} disabled={readOnly} type="number" min={0} className="w-24" value={e.value ?? ""} onChange={(ev) => edit(r.id, { value: ev.target.value })} />
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -342,7 +352,7 @@ function PasswordRulesForm() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button onClick={save} disabled={saving}>{t("LsSaveRules")}</Button>
|
||||
{!readOnly && <Button onClick={save} disabled={saving}>{t("LsSaveRules")}</Button>}
|
||||
<NoticeLine notice={notice} />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }));
|
||||
vi.mock("@/app/lib/clientApi", () => ({ apiPost: vi.fn(), ApiError: class ApiError extends Error {} }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn().mockResolvedValue(undefined) }) }));
|
||||
|
||||
import LoginPage from "./page";
|
||||
import { apiPost } from "@/app/lib/clientApi";
|
||||
|
||||
const mockPost = apiPost as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset().mockResolvedValue({ name: "A", resetPasswordRequired: false });
|
||||
});
|
||||
|
||||
describe("LoginPage company field", () => {
|
||||
it("sends the company with the username and password", async () => {
|
||||
render(<LoginPage />);
|
||||
fireEvent.change(screen.getByLabelText("Company"), { target: { value: " ins " } });
|
||||
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "john" } });
|
||||
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "secret" } });
|
||||
fireEvent.submit(screen.getByRole("button", { name: /log in/i }));
|
||||
await waitFor(() =>
|
||||
expect(mockPost).toHaveBeenCalledWith("/api/auth/login", { company: "ins", username: "john", password: "secret" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("allows a blank company (super admin)", async () => {
|
||||
render(<LoginPage />);
|
||||
fireEvent.change(screen.getByLabelText("Username"), { target: { value: "root" } });
|
||||
fireEvent.change(screen.getByLabelText("Password"), { target: { value: "secret" } });
|
||||
fireEvent.submit(screen.getByRole("button", { name: /log in/i }));
|
||||
await waitFor(() => expect(mockPost).toHaveBeenCalled());
|
||||
expect(mockPost.mock.calls[0][1]).toMatchObject({ username: "root", password: "secret" });
|
||||
expect(mockPost.mock.calls[0][1].company ?? "").toBe("");
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,7 @@ export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const { refresh } = useAdminAuth();
|
||||
const t = useT();
|
||||
const [company, setCompany] = useState("");
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
@@ -49,6 +50,7 @@ export default function LoginPage() {
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const res = await apiPost<{ name: string; resetPasswordRequired: boolean }>("/api/auth/login", {
|
||||
company: company.trim() || undefined,
|
||||
username,
|
||||
password,
|
||||
});
|
||||
@@ -125,6 +127,20 @@ export default function LoginPage() {
|
||||
{error ? <ErrorState message={t(error)} /> : elsewhere && <ErrorState message={t("SignedInElsewhere")} />}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company">{t("Company")}</Label>
|
||||
<Input
|
||||
id="company"
|
||||
type="text"
|
||||
autoComplete="organization"
|
||||
placeholder={t("CompanyBlankForSuper")}
|
||||
value={company}
|
||||
onChange={(e) => setCompany(e.target.value)}
|
||||
disabled={submitting}
|
||||
className="h-11 bg-card"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">{t("Username")}</Label>
|
||||
<Input
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getRoleGrantTree: vi.fn(), updateRoleGrantTree: vi.fn(), useAdminAuth: vi.fn(), getAdminRole: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminAcl", () => mocks);
|
||||
vi.mock("@/app/lib/services/adminRoles", () => ({ getAdminRole: mocks.getAdminRole }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", () => ({ useParams: () => ({ id: "4" }) }));
|
||||
|
||||
import RoleAccessPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getRoleGrantTree.mockReset().mockResolvedValue([
|
||||
{ id: 1, name: "BO_ROOT", parentId: null, granted: true },
|
||||
{ id: 2, name: "BO_USERS", parentId: 1, granted: false },
|
||||
]);
|
||||
mocks.getAdminRole.mockReset().mockResolvedValue({ id: 4, name: "Test Role", parent: { id: 1 } });
|
||||
});
|
||||
|
||||
describe("RoleAccessPage for staff", () => {
|
||||
it("hides Save for a non-super user and shows it for a super admin", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false, hasModule: () => true, roles: [{ name: "ROLE_HQ" }] });
|
||||
const { unmount } = render(<RoleAccessPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Users")).toBeInTheDocument());
|
||||
expect(screen.queryByRole("button", { name: /save/i })).not.toBeInTheDocument();
|
||||
unmount();
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: true, hasModule: () => true, roles: [{ name: "ROLE_HQ" }] });
|
||||
render(<RoleAccessPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Users")).toBeInTheDocument());
|
||||
expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -77,7 +77,7 @@ function GrantTreeNode({
|
||||
function RoleAccessPageContent() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const roleId = Number(id);
|
||||
const { roles: myRoles } = useAdminAuth();
|
||||
const { roles: myRoles, isSuper } = useAdminAuth();
|
||||
const t = useT();
|
||||
|
||||
const [rows, setRows] = useState<ModuleGrantRow[]>([]);
|
||||
@@ -226,9 +226,11 @@ function RoleAccessPageContent() {
|
||||
<Button variant="outline" disabled={!hasChanges} onClick={() => setChecked(new Set(original))}>
|
||||
{t("RolReset")}
|
||||
</Button>
|
||||
<Button disabled={!hasChanges} onClick={() => setConfirming(true)}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
{isSuper !== false && (
|
||||
<Button disabled={!hasChanges} onClick={() => setConfirming(true)}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{confirming && (
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { ColumnDef, SortingState } from "@tanstack/react-table";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
@@ -88,6 +89,7 @@ function RoleFormDialog({
|
||||
|
||||
function RolesPageContent() {
|
||||
const t = useT();
|
||||
const readOnly = useAdminAuth().isSuper === false; // super-admin-only writes; server returns 403 anyway
|
||||
const [roles, setRoles] = useState<AdminRoleEntity[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -148,10 +150,10 @@ function RolesPageContent() {
|
||||
header: t("ModulesParent"),
|
||||
cell: ({ row }) => parentLabel(row.original),
|
||||
},
|
||||
{
|
||||
...(readOnly ? [] : [{
|
||||
id: "actions",
|
||||
header: t("CatActions"),
|
||||
cell: ({ row }) => (
|
||||
cell: ({ row }: { row: { original: AdminRoleEntity } }) => (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -165,21 +167,21 @@ function RolesPageContent() {
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
}]),
|
||||
],
|
||||
[parentLabel, t],
|
||||
[parentLabel, t, readOnly],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("BO_ROLES")}
|
||||
actions={
|
||||
actions={readOnly ? undefined : (
|
||||
<Button onClick={() => setDialog(EMPTY_FORM)}>
|
||||
<Plus aria-hidden="true" className="size-4" />
|
||||
{t("RolAddRole")}
|
||||
</Button>
|
||||
}
|
||||
)}
|
||||
/>
|
||||
|
||||
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
||||
|
||||
@@ -15,10 +15,12 @@ import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { roleLabel } from "@/app/lib/roleLabel";
|
||||
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 { listAdminUsers, sendAdminUserPasswordReset, USER_STATUS_FILTER_OPTIONS } from "@/app/lib/services/adminUsers";
|
||||
import type { AdminUser } from "@/app/lib/types";
|
||||
import { useTableSort } from "@/app/lib/hooks/useTableSort";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import type { MessageParams } from "@/app/lib/i18n/t";
|
||||
|
||||
@@ -26,8 +28,10 @@ const DEFAULTS = { q: "", enabled: "" };
|
||||
|
||||
function UsersPageContent() {
|
||||
const t = useT();
|
||||
const { companyId, showCompanyColumn } = useCompanyScope();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
useResetPageOnCompany(setPage);
|
||||
const { sorting, onSortingChange, sortBy, sortDir } = useTableSort();
|
||||
const [data, setData] = useState<{ items: AdminUser[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -68,7 +72,7 @@ function UsersPageContent() {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the filter/page/reloadKey-triggered fetch below.
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
listAdminUsers({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir })
|
||||
listAdminUsers({ q: filters.q || undefined, enabled: filters.enabled || undefined, page, pageSize, sortBy, sortDir, companyId })
|
||||
.then((result) => {
|
||||
if (!cancelled) setData(result);
|
||||
})
|
||||
@@ -81,7 +85,7 @@ function UsersPageContent() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [filters, page, reloadKey, pageSize, sortBy, sortDir]);
|
||||
}, [filters, page, reloadKey, pageSize, sortBy, sortDir, companyId]);
|
||||
|
||||
const statusOptions = useMemo(
|
||||
() => USER_STATUS_FILTER_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
||||
@@ -99,6 +103,7 @@ function UsersPageContent() {
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
...(showCompanyColumn ? [{ id: "company", accessorFn: (u: AdminUser) => u.companyCode ?? "", header: t("Company"), enableSorting: false } as ColumnDef<AdminUser, unknown>] : []),
|
||||
{ accessorKey: "name", header: t("Name") },
|
||||
{ accessorKey: "email", header: t("Email") },
|
||||
{
|
||||
@@ -154,7 +159,7 @@ function UsersPageContent() {
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
[t, showCompanyColumn],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -152,6 +152,10 @@ spring:
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
- Path=/loginSecurity/**
|
||||
- id: company
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
- Path=/company/**
|
||||
- id: passwordAging
|
||||
uri: http://${app.services.name.system}
|
||||
predicates:
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.solvway.gateway;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** mobile-api reaches services-system's /company/* endpoints through the gateway. */
|
||||
class CompanyRouteTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void companyPathsRouteToServicesSystem() throws Exception {
|
||||
try (InputStream in = getClass().getResourceAsStream("/application.yml")) {
|
||||
Map<String, Object> yml = new Yaml().load(in);
|
||||
Map<String, Object> gateway = (Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) yml.get("spring")).get("cloud")).get("gateway");
|
||||
List<Map<String, Object>> routes = (List<Map<String, Object>>) gateway.get("routes");
|
||||
assertThat(routes).anySatisfy(r -> {
|
||||
assertThat(r.get("uri")).isEqualTo("http://${app.services.name.system}");
|
||||
assertThat((List<String>) r.get("predicates")).contains("Path=/company/**");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,9 @@ public class Email {
|
||||
|
||||
private List<Long> attachmentId;
|
||||
|
||||
/** Set for an admin user's email; member and system emails stay null. */
|
||||
private Long companyId;
|
||||
|
||||
public Email() {
|
||||
super();
|
||||
// TODO Auto-generated constructor stub
|
||||
|
||||
@@ -89,6 +89,8 @@ public class User implements Serializable{
|
||||
private String aclHtml;
|
||||
private String uuid;
|
||||
private Long companyId;
|
||||
private String companyCode;
|
||||
private String companyStatus;
|
||||
public User() {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.solvway.core.model;
|
||||
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class UserCompanyTest {
|
||||
|
||||
private final PubSubUtil util = new PubSubUtil();
|
||||
|
||||
@Test
|
||||
void companyCodeAndStatusRoundTripThroughJson() {
|
||||
User u = new User();
|
||||
u.setCompanyId(2L);
|
||||
u.setCompanyCode("cv");
|
||||
u.setCompanyStatus("A");
|
||||
|
||||
String json = util.convertToString(u);
|
||||
assertThat(json).contains("\"companyCode\":\"cv\"").contains("\"companyStatus\":\"A\"");
|
||||
|
||||
User back = util.convertToOriginalObject(json.getBytes(StandardCharsets.UTF_8), User.class);
|
||||
assertThat(back.getCompanyCode()).isEqualTo("cv");
|
||||
assertThat(back.getCompanyStatus()).isEqualTo("A");
|
||||
assertThat(back.getCompanyId()).isEqualTo(2L);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -42,10 +42,10 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_INTEREST_FIND_BY_IDS="/counter/interest/findByIds";
|
||||
public static final String API_REST_COUNTER_LEAD_FIND_MATCHES="/counter/lead/findMatches";
|
||||
public static final String API_REST_COUNTER_LEAD_SEARCH="/counter/lead/search";
|
||||
public static final String API_REST_COUNTER_LEAD_DETAIL="/counter/lead/detail/{companyId}/{leadUuid}";
|
||||
public static final String API_REST_COUNTER_LEAD_DETAIL="/counter/lead/detail/{leadUuid}";
|
||||
public static final String API_REST_COUNTER_LEAD_UPDATE="/counter/lead/update";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_CAPTURE="/counter/eventLead/capture";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_UUID="/counter/eventLead/findByUuid/{eventLeadUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_UPDATE="/counter/eventLead/update";
|
||||
public static final String API_REST_COUNTER_EVENT_LEAD_FIND_BY_EVENT="/counter/eventLead/findByEvent";
|
||||
|
||||
|
||||
+8
@@ -8,6 +8,8 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY = "/user/findByEmailAndCompanyId/{email}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY_AND_ID_NOT = "/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE = "/user/findByPropertyAndPageable";
|
||||
public static final String API_REST_SYSTEM_ROLE_FIND_ALL = "/role/findAll";
|
||||
public static final String API_REST_SYSTEM_ROLE_SAVE = "/role/save";
|
||||
@@ -92,6 +94,12 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_GENERIC_POST_FIND_BY_UUID = "/system/genericPost/findByUuid/{uuid}";
|
||||
public static final String API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE = "/system/genericPost/content/findByPostUuidAndLocale/{uuid}/{locale}";
|
||||
|
||||
//Company
|
||||
public static final String API_REST_COMPANY_FIND_ALL = "/company/findAll";
|
||||
public static final String API_REST_COMPANY_FIND_BY_ID = "/company/findById/{id}";
|
||||
public static final String API_REST_COMPANY_SAVE = "/company/save";
|
||||
public static final String API_REST_COMPANY_RENAME_CODE = "/company/{id}/code";
|
||||
|
||||
//LoginSecurity (admin sign-in lock check and history)
|
||||
public static final String API_REST_LOGIN_SECURITY_IS_LOCKED = "/loginSecurity/isLocked/{username}";
|
||||
public static final String API_REST_LOGIN_SECURITY_RECORD = "/loginSecurity/record";
|
||||
|
||||
+3
-2
@@ -32,8 +32,9 @@ public class AdminAuditLogController {
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(auditLog.search(actor, module, action, outcome, from, to, page, size));
|
||||
@RequestParam(defaultValue = "20") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(auditLog.search(actor, module, action, outcome, from, to, page, size, companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
|
||||
+29
-7
@@ -7,12 +7,14 @@ import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminChangePasswordRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminFirstLoginRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminForgotPasswordRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLoginRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLoginResponse;
|
||||
import com.solvway.mobile.api.dto.admin.AdminMeResponse;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -43,12 +45,15 @@ public class AdminAuthController {
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/auth/login")
|
||||
public ResponseEntity<?> login(@RequestBody AuthRequest request) {
|
||||
public ResponseEntity<?> login(@RequestBody AdminLoginRequest in) {
|
||||
// Blank fields never reach services-auth: it fails differently for known and unknown usernames.
|
||||
if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) {
|
||||
String username = loginName(in.company(), in.username());
|
||||
if (username == null || !StringUtils.hasText(in.password())) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN);
|
||||
}
|
||||
String username = request.getUsername().trim();
|
||||
AuthRequest request = new AuthRequest();
|
||||
request.setUsername(username);
|
||||
request.setPassword(in.password());
|
||||
if (adminAuthenticationService.isLocked(username)) {
|
||||
adminAuthenticationService.record(username, "LOGIN_LOCKED", null);
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ACCOUNT_LOCKED);
|
||||
@@ -64,6 +69,11 @@ public class AdminAuthController {
|
||||
authenticationService.logoutToken(token);
|
||||
u = null;
|
||||
}
|
||||
if (u != null && u.getCompanyId() != null && !AdminCompanyScope.isSuper(u) && !"A".equals(u.getCompanyStatus())) {
|
||||
// an inactive company cannot sign in; same revoke as a disabled admin
|
||||
authenticationService.logoutToken(token);
|
||||
u = null;
|
||||
}
|
||||
} catch (RestClientException ex) {
|
||||
u = null; // any upstream failure is a refused login; never echo why
|
||||
token = null;
|
||||
@@ -74,7 +84,8 @@ public class AdminAuthController {
|
||||
}
|
||||
adminAuthenticationService.record(username, "LOGIN_SUCCESS", null);
|
||||
return ResponseEntity.ok(new AdminLoginResponse(token, u.getName(), u.getRoles(), u.getAclMenu(),
|
||||
GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false"));
|
||||
GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false",
|
||||
u.getCompanyId(), u.getCompanyCode(), AdminCompanyScope.isSuper(u)));
|
||||
}
|
||||
|
||||
@AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true)
|
||||
@@ -143,8 +154,9 @@ public class AdminAuthController {
|
||||
@PostMapping("/auth/forgot-password")
|
||||
public ResponseEntity<Map<String, String>> forgotPassword(@RequestBody AdminForgotPasswordRequest request) {
|
||||
try {
|
||||
if (StringUtils.hasText(request.username()) && StringUtils.hasText(request.email())) {
|
||||
adminAuthenticationService.resetAdminPassword(request.username().trim(), request.email().trim());
|
||||
String username = loginName(request.company(), request.username());
|
||||
if (username != null && StringUtils.hasText(request.email())) {
|
||||
adminAuthenticationService.resetAdminPassword(username, request.email().trim());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Admin forgot-password failed downstream: {}", e.getClass().getSimpleName());
|
||||
@@ -186,6 +198,16 @@ public class AdminAuthController {
|
||||
if (u == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(new AdminMeResponse(u.getId(), u.getUsername(), u.getName(), u.getRoles(), u.getAclMenu()));
|
||||
return ResponseEntity.ok(new AdminMeResponse(u.getId(), u.getUsername(), u.getName(), u.getRoles(), u.getAclMenu(),
|
||||
u.getCompanyId(), u.getCompanyCode(), AdminCompanyScope.isSuper(u)));
|
||||
}
|
||||
|
||||
/** Stored login name: {@code username@company}, or the plain username for a blank company (super admin). Null when unusable. */
|
||||
private static String loginName(String company, String username) {
|
||||
if (!StringUtils.hasText(username) || username.contains("@")) {
|
||||
return null;
|
||||
}
|
||||
String code = company == null ? "" : company.trim().toLowerCase();
|
||||
return code.isEmpty() ? username.trim() : username.trim() + "@" + code;
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AdminCompanyService;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Companies screen, super admin only. No @AdminModule on purpose: AppAccessAspect then lets only role 1 through, and requireSuper rejects company staff holding it. Must stay under {@code controller..}. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/companies")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminCompanyController {
|
||||
|
||||
private final AdminCompanyService companies;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
private final AdminCompanyScope scope;
|
||||
|
||||
@AppAuth
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Map<String, Object>>> list() {
|
||||
requireSuper();
|
||||
return ResponseEntity.ok(companies.list());
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<Map<String, Object>> get(@PathVariable Long id) {
|
||||
requireSuper();
|
||||
return ResponseEntity.ok(companies.get(id));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PostMapping
|
||||
public ResponseEntity<Map<String, Object>> save(@RequestBody Map<String, Object> body) {
|
||||
requireSuper();
|
||||
return ResponseEntity.ok(companies.save(body));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PostMapping("/{id}/code")
|
||||
public ResponseEntity<Map<String, Object>> renameCode(@PathVariable Long id, @RequestBody Map<String, String> body) {
|
||||
requireSuper();
|
||||
return ResponseEntity.ok(companies.renameCode(id, body.get("code")));
|
||||
}
|
||||
|
||||
/** Portal body is just {"message"}; the exception still reaches AppAccessAspect first, so the audit has the real status. */
|
||||
@ExceptionHandler(CodedResponseStatusException.class)
|
||||
public ResponseEntity<Map<String, String>> upstream(CodedResponseStatusException e) {
|
||||
return ResponseEntity.status(e.getStatusCode()).body(Map.of("message", String.valueOf(e.getReason())));
|
||||
}
|
||||
|
||||
private void requireSuper() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
||||
scope.requireSuper(caller);
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -31,8 +31,9 @@ public class AdminEmailController {
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(adminEmailService.list(recipient, subject, from, to, page, size));
|
||||
@RequestParam(defaultValue = "20") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminEmailService.list(recipient, subject, from, to, page, size, companyId));
|
||||
}
|
||||
|
||||
@Audited(action = "EMAIL_VIEW")
|
||||
|
||||
+5
-4
@@ -26,14 +26,15 @@ public class AdminEventController {
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size,
|
||||
@RequestParam(required = false) String sortBy,
|
||||
@RequestParam(required = false) String sortDir) {
|
||||
return ResponseEntity.ok(adminEventService.list(q, enabled, page, size, sortBy, sortDir));
|
||||
@RequestParam(required = false) String sortDir,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminEventService.list(q, enabled, page, size, sortBy, sortDir, companyId));
|
||||
}
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENTS")
|
||||
@GetMapping("/events/salesperson-options")
|
||||
public ResponseEntity<List<Map<String, Object>>> salespersonOptions() {
|
||||
return ResponseEntity.ok(adminEventService.salespersonOptions());
|
||||
public ResponseEntity<List<Map<String, Object>>> salespersonOptions(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminEventService.salespersonOptions(companyId));
|
||||
}
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENTS")
|
||||
|
||||
+5
-4
@@ -31,8 +31,8 @@ public class AdminEventLeadController {
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@GetMapping("/events")
|
||||
public ResponseEntity<List<Map<String, Object>>> events() {
|
||||
return ResponseEntity.ok(adminEventLeadService.events());
|
||||
public ResponseEntity<List<Map<String, Object>>> events(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminEventLeadService.events(companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@@ -74,8 +74,9 @@ public class AdminEventLeadController {
|
||||
@RequestParam(required = false) Long interestId,
|
||||
@RequestParam(required = false) String leadType,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(adminEventLeadService.list(eventUuid, salespersonId, temperature, status, interestId, leadType, page, size));
|
||||
@RequestParam(defaultValue = "20") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminEventLeadService.list(eventUuid, salespersonId, temperature, status, interestId, leadType, page, size, companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
|
||||
+3
-2
@@ -30,8 +30,9 @@ public class AdminEventLeadExportController {
|
||||
@RequestParam(required = false) String temperature,
|
||||
@RequestParam(required = false) String status,
|
||||
@RequestParam(required = false) Long interestId,
|
||||
@RequestParam(required = false) String leadType) {
|
||||
byte[] file = adminEventLeadService.export(eventUuid, salespersonId, temperature, status, interestId, leadType);
|
||||
@RequestParam(required = false) String leadType,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
byte[] file = adminEventLeadService.export(eventUuid, salespersonId, temperature, status, interestId, leadType, companyId);
|
||||
// The service has already parsed the uuid as a number, so its digits are the canonical uuid; nothing else reaches the header.
|
||||
return xlsx("event-leads-" + eventUuid.replaceAll("\\D", ""), file);
|
||||
}
|
||||
|
||||
+6
-4
@@ -31,16 +31,18 @@ public class AdminLeadController {
|
||||
@GetMapping
|
||||
public ResponseEntity<Map<String, Object>> list(@RequestParam(required = false) String q,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(adminLeadService.list(q, page, size));
|
||||
@RequestParam(defaultValue = "20") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(adminLeadService.list(q, page, size, companyId));
|
||||
}
|
||||
|
||||
@Audited(action = "LEAD_EXPORT")
|
||||
@AppAuth
|
||||
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_LEADS")
|
||||
@GetMapping("/export")
|
||||
public ResponseEntity<byte[]> export(@RequestParam(required = false) String q) {
|
||||
return xlsx("leads", adminLeadService.export(q));
|
||||
public ResponseEntity<byte[]> export(@RequestParam(required = false) String q,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return xlsx("leads", adminLeadService.export(q, companyId));
|
||||
}
|
||||
|
||||
private static ResponseEntity<byte[]> xlsx(String prefix, byte[] bytes) {
|
||||
|
||||
+7
-6
@@ -35,21 +35,22 @@ public class AdminLoginSecurityController {
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(loginSecurity.audit(username, event, from, to, page, size));
|
||||
@RequestParam(defaultValue = "20") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(loginSecurity.audit(username, event, from, to, page, size, companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/locked")
|
||||
public ResponseEntity<List<Map<String, Object>>> locked() {
|
||||
return ResponseEntity.ok(loginSecurity.locked());
|
||||
public ResponseEntity<List<Map<String, Object>>> locked(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(loginSecurity.locked(companyId));
|
||||
}
|
||||
|
||||
@Audited(target = false) // the username is whatever was typed at sign-in, possibly a password
|
||||
@AppAuth
|
||||
@PostMapping("/locked/{username}/unlock")
|
||||
public ResponseEntity<Void> unlock(@PathVariable String username) {
|
||||
loginSecurity.unlock(username);
|
||||
public ResponseEntity<Void> unlock(@PathVariable String username, @RequestParam(required = false) Long companyId) {
|
||||
loginSecurity.unlock(username, companyId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 215 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user