From 628d885261f1477eb51487870fde55c7c9f017e9 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 18:17:16 +0800 Subject: [PATCH 01/24] docs: company scoping design Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../2026-11-30-company-scoping-design.md | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-30-company-scoping-design.md diff --git a/docs/superpowers/specs/2026-11-30-company-scoping-design.md b/docs/superpowers/specs/2026-11-30-company-scoping-design.md new file mode 100644 index 0000000..8e2feda --- /dev/null +++ b/docs/superpowers/specs/2026-11-30-company-scoping-design.md @@ -0,0 +1,143 @@ +# Company Scoping — Design + +Date: 2026-11-30. Change id: `add-company-scoping`. + +## Intent + +Co-Lite goes live on 2027-01-15 with two test-run companies, INS and CV. This replaces the earlier "single company at go-live" decision (`docs/feature-list.md`, Tenancy). Each company's staff must see only their own company's data. One super admin sees and manages everything, including creating companies. More companies will follow, and adding one must need no code change, no deploy and no database work: the super admin creates it on a screen. + +Everything built so far assumes one company. Some of it is already scoped: leads, event leads, interests and event salespersons are queried by the caller's company. The rest is not: users, events, emails, login history and the audit log. The super admin cannot see across companies at all. + +## Decisions taken with the user (2026-11-30) + +- **Separated per company:** leads, event leads, events, users, emails, login history, audit events. +- **Shared by all companies:** roles, interests, lockout settings, password rules. +- **Super admin:** a super admin can do everything. It sees every company's data, through a company picker and through mixed lists with a Company column. It creates the companies. + - A super admin is an account with **no company** that holds the super admin role. There can be more than one (a second one is kept for recovery); only a super admin can create another. + - Company staff can never hold the super admin role. +- **Sign-in:** the login page asks for **Company** (for example `ins`), **Username** and **Password**. A super admin leaves Company empty. Usernames are unique **within a company**, so INS and CV can each have a `john` (approach B below). +- **Editing shared data:** only a super admin edits roles, interests, lockout settings and password rules. +- **Leads:** the same phone at two companies is two separate leads, each with its own New/Existing history. This is already how leads work. + +## Goals + +- A Companies screen where the super admin creates and edits companies. +- Company + username sign-in for company staff; username only (Company empty) for super admins. +- Every admin API and screen returns only the caller's company data, unless the caller is the super admin. +- The super admin can see all companies at once or pick one, and can create data in a chosen company. +- Interests become one shared list. + +## Non-goals + +- Members and the customer portal. Member accounts and member sign-in are unchanged. +- A company admin who manages their own company's roles, interests or settings. These are shared, so only a super admin edits them. +- Per-company branding, logos, web addresses or settings. +- Moving or splitting existing data between companies beyond the one-time setup below. +- Deleting a company. A company can be deactivated. + +## Anti-goals + +- Any path where a company's staff can read or change another company's data: list, detail, export, edit by id, or audit. +- A change to how members sign in. +- A sign-in answer that reveals whether a company code or a username exists. +- A cross-company leak through a shared table (interests, roles) or through the audit log. + +## Approaches considered (for `username@account`) + +- **A. The suffix is part of the stored username** (`john@ins` saved as the username, globally unique). Smallest change; the sign-in path is untouched. A company's code could never change once users exist. Not chosen. +- **B. Usernames unique per company; the company is given at sign-in (chosen by the user).** `john` is stored with company INS. Sign-in finds company `ins`, then the user `john` in it. A company's code can change later. It touches the sign-in lookup, the uniqueness rule, token identity, lockout keys and password reset. +- **Login page shape (chosen by the user):** a separate Company field, rather than one `john@ins` field or a company dropdown. A dropdown was rejected because the public login page would list every customer company. + +## Design + +### Companies + +- `company` gains `code` (lowercase letters, digits and hyphens, 2 to 20 characters, unique) and `status` (`A` active, `I` inactive). `name` stays. +- **Companies screen** `/companies` in the admin portal, **super admin only** (not a grantable module): list, create, edit name, code and status. Changing a code changes every staff sign-in for that company; the screen warns before saving. +- An inactive company's staff cannot sign in. Their data is kept and the super admin still sees it. + +### Identity: the login name + +- The login page sends company code, username and password. Internally a staff user's **login name** is `username@code`; a super admin's login name is its plain username (`admin`), and it belongs to no company (`company_id` NULL). The login name is never typed by staff; it is how the system refers to them. +- The login name is the one string that identifies a staff user everywhere the system uses a string today: + - the JWT subject; + - every `findByUsername`-style lookup from a token (mobile-api resolves the caller about 40 times this way); + - the lockout key and the `login_audit` username; + - the audit event actor; + - forgot-password and the temporary-password flows. +- **Lookup rule (one place, services-system):** a login name with an `@` splits at the **last** `@` into username and code; the user is found by company code and username, and must be type `A` in an active company. A login name without `@` matches only a user with no company, which is the super admin. +- **Uniqueness:** staff usernames are unique per company; the super admin's username is unique among company-less admin users. Member usernames keep their current global uniqueness. The database enforces it (left to the builder: for example a maintained, uniquely indexed `login_name` column, rewritten in one transaction when a company's code changes). +- Changing a company's code changes its users' login names. Existing sessions of those users end; they sign in again with the new code. +- Sign-in errors stay as they are: a wrong or inactive company, an unknown user and a wrong password all give the same `BAD_LOGIN` answer. +- **Forgot password** takes company, username and email, like sign-in. **Email** is unique per company, not across companies, so one person can have an account at INS and at CV. + +### Super admins + +- Cross-company access means: the caller has **no company and holds the super admin role** (role id 1). Both are required. +- The role cannot be granted to a user who has a company, and a company-less user must hold it: every other user belongs to a company. The Users screen enforces this, and services-system rejects it too. +- A super admin creates another super admin from the Users screen by leaving the company empty. + +### Scoping rule + +- **Company staff:** every admin read, write, export and detail lookup is limited to the caller's company. A record of another company answers 404, as if it did not exist. +- **Super admin:** sees all companies by default. Lists take an optional company filter. Creating a company-owned record (user, event, event lead capture) requires a company: the super admin picks one in the form. +- Enforcement is server-side in mobile-api's admin services, which already pass the caller's company to services-counter. The portal only reflects it. + +### What is scoped where + +| Data | Today | Change | +|---|---|---| +| Leads, event leads, event salespersons | scoped by caller company | super admin: all or the picked company | +| Interests | per company | **shared**: one list for all companies; editing super admin only | +| Events (`event`) | no company | add `company_id`; scope like leads | +| Users | no scoping | scope by company; staff manage only their own company's users | +| Roles | global | stay shared; editing becomes super admin only | +| Emails (`email`) | no company | add `company_id` (the company of the user the email is for); scope; emails with no company are visible to the super admin only | +| Login history, locked users | `login_audit.company_id` exists, not used | scope by company; staff with Login security unlock only their own company's users | +| Lockout settings, password rules | global | stay shared; editing becomes super admin only | +| Audit log | `company_id` stored, not used | scope by company | + +### Interests become shared + +- `interest.company_id` is no longer used for scoping; the unique key moves from `(company_id, name)` to `name`. +- Existing interests: at go-live there is one company, so its list becomes the shared list. +- Only a super admin adds, renames or deactivates interests. Company staff pick from the list when capturing leads. + +### Which company an audit row belongs to + +- An audit event and a login-history row carry the **actor's** company, as stored today. +- A super admin's actions therefore have no company and are visible to super admins only, even when they changed a company's record. Resolving the changed record's company for every audited endpoint is out of scope. +- A failed sign-in carries the company when the code matches a company, and none otherwise; rows with no company are visible to super admins only. + +### Admin portal + +- **Header company picker, super admin only:** "All companies", then each company. It sets the company filter for lists and the default company for create forms. Company staff do not see it. +- **Lists, super admin with "All companies":** a Company column on users, events, leads, event leads, emails, login history and audit log. +- **Create forms, super admin:** a Company field, prefilled from the picker. Company staff never see it. +- **Sign-in page:** Company, Username and Password fields. A super admin leaves Company empty. Forgot password asks for the same Company and Username plus the email. +- **Users screen:** company staff create users in their own company. A super admin picks the company, or leaves it empty to create another super admin. +- **Screens that become super admin only:** Companies, Roles, Interests, and the Login security Settings tab. + +### One-time setup (deploy SQL) + +- Add `code` and `status` to `company`; add `company_id` to `event` and `email`; move the interest unique key; add the user uniqueness change. +- Create INS and CV with their codes. The existing company row (id 1, "Co-Lite") becomes INS, so existing local and test data lands there. +- The existing super admin account (`admin`) gets `company_id` NULL. Every other existing admin user stays in company 1 (INS). +- Existing events and emails get company 1. +- Co-Lite is not deployed anywhere yet, so the setup runs on a fresh database. The deploy ends every existing session, because the token identity changes. No existing admin username contains `@`; the deploy SQL checks this and stops if one does. + +## My calls (check these) + +- Another company's record answers 404, not 403, so its existence is not revealed. +- Audit and login-history rows belong to the actor's company; a super admin's actions are visible to super admins only. +- Email is unique per company; forgot password takes company, username and email. +- The existing company becomes INS; CV starts empty. +- Inactive companies block their staff's sign-in; there is no delete. +- Changing a company's code or deactivating it ends its staff's sessions. + +## Left to the builder + +- How login-name uniqueness is enforced in MySQL (a maintained `login_name` column is one way). +- Whether the company code is cached or looked up per request. +- Exact column widths for the Company column, and how the picker looks in the header. +- Splitting the work into tasks, ordered so that sign-in keeps working at every step. -- 2.54.1 From 4243a2d6cd046e84719c46fff5662cb3736ddd82 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 18:23:08 +0800 Subject: [PATCH 02/24] docs(openspec): propose add-company-scoping Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-company-scoping/.openspec.yaml | 2 + .../changes/add-company-scoping/design.md | 101 ++++++++++++++ .../changes/add-company-scoping/proposal.md | 39 ++++++ .../specs/admin-access/spec.md | 53 ++++++++ .../specs/admin-login-security/spec.md | 43 ++++++ .../specs/admin-roles/spec.md | 38 ++++++ .../specs/admin-users/spec.md | 44 ++++++ .../specs/company-scoping/spec.md | 128 ++++++++++++++++++ .../specs/lead-interests/spec.md | 34 +++++ openspec/changes/add-company-scoping/tasks.md | 124 +++++++++++++++++ 10 files changed, 606 insertions(+) create mode 100644 openspec/changes/add-company-scoping/.openspec.yaml create mode 100644 openspec/changes/add-company-scoping/design.md create mode 100644 openspec/changes/add-company-scoping/proposal.md create mode 100644 openspec/changes/add-company-scoping/specs/admin-access/spec.md create mode 100644 openspec/changes/add-company-scoping/specs/admin-login-security/spec.md create mode 100644 openspec/changes/add-company-scoping/specs/admin-roles/spec.md create mode 100644 openspec/changes/add-company-scoping/specs/admin-users/spec.md create mode 100644 openspec/changes/add-company-scoping/specs/company-scoping/spec.md create mode 100644 openspec/changes/add-company-scoping/specs/lead-interests/spec.md create mode 100644 openspec/changes/add-company-scoping/tasks.md diff --git a/openspec/changes/add-company-scoping/.openspec.yaml b/openspec/changes/add-company-scoping/.openspec.yaml new file mode 100644 index 0000000..4a154df --- /dev/null +++ b/openspec/changes/add-company-scoping/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-30 diff --git a/openspec/changes/add-company-scoping/design.md b/openspec/changes/add-company-scoping/design.md new file mode 100644 index 0000000..1d19f73 --- /dev/null +++ b/openspec/changes/add-company-scoping/design.md @@ -0,0 +1,101 @@ +# Design + +Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-company-scoping-design.md`. + +## Context + +- **Identity is a string everywhere:** + - services-auth issues the JWT with the user's `username` as subject. + - It resolves a token back to a user through services-system `/user/findByUsernameWithPassword/{username}`. + - mobile-api resolves the caller from the token about 40 times. It also uses `caller.getUsername()` for `doneBy`, the lockout key, the `login_audit` username and the audit actor. + - `user.username` is globally unique (`username_UNIQUE`). Member users live in the same table. +- **Already scoped by company:** leads, event leads, event salespersons and interests are queried by the caller's company. mobile-api passes `caller.getCompanyId()` to services-counter. +- **Not scoped:** + - the users search (services-system); + - events (the Tastefully `event` table, services-counter, no `company_id`); + - emails (service-email, no `company_id`); + - login history and locked users (services-system; `login_audit.company_id` exists but is unused); + - the audit log (services-log; `audit_event.company_id` exists but is unused). +- **Super admin today:** holds role id 1. Checked in `AppAccessAspect`, `AdminUserService`, `AdminRoleService`, `AdminAclService` and `AdminEmailService`. +- **Company today:** `company` is `(id, name, create_date)`, with one row (id 1, "Co-Lite"). No entity or API. +- **Emails:** mobile-api `EmailService` publishes emails to `email-save-request-topic`, and service-email saves them. + +## Goals / Non-Goals + +**Goals:** +- Every scoped admin read and write carries the caller's company; super admins see all or a picked company. +- Company sign-in without changing services-auth, the token format or member sign-in. +- Adding a company needs no code, deploy or database work. + +**Non-Goals:** +- Members and the customer portal. +- Company admins with their own roles or settings. +- Stamping a super admin's audit row with the changed record's company. +- Deleting companies. + +## Decisions + +1. **The stored username of a staff user is the login name `local@code`.** + - The portal sends `company` and `username`. mobile-api builds the login name: `username@company`, lowercased code; a blank company means the plain username, which is a super admin. + - services-system stores `john@ins` in `user.username`. The existing unique key then gives per-company uniqueness. services-auth, tokens, `findByUsername*`, `login_audit` and the audit actor all keep working on that one string unchanged. + - Screens show the local part (`john`) next to the company. A username input SHALL NOT contain `@`. + - Alternative rejected: a new `login_name` column, or a lookup split across company and username. Either would touch services-auth and every token lookup for the same outcome. + - The user's choice of approach B is preserved: per-company usernames, a separate Company field and a renamable code. +2. **Company code change:** + - A services-system `@Transactional` endpoint renames the code and rewrites `username = CONCAT(local, '@', newCode)` for that company's admin users. + - Old tokens no longer resolve to a user, so those sessions end on their next request. The username column is the session's identity, so nothing else is needed. + - Login history keeps the old names. +3. **Company table and API:** + - `company` gains `code varchar(20) NOT NULL UNIQUE` and `status char(1) NOT NULL DEFAULT 'A'`. + - services-system gets a `Company` entity, repository and `/company/*` endpoints: list, find, save, rename-code. + - mobile-api gets `AdminCompanyController` (`/api/admin/companies`), super admin only. +4. **Super admin check, in one place:** + - `AdminCompanyScope` (mobile-api) defines `isSuper(caller)` as "no company AND holds role 1". It replaces the role-only checks. + - `scope(caller, requestedCompanyId)` returns the company to filter by: + - staff: their own company, ignoring any request value; + - super admin: the requested company, or null for all. + - `requireCompanyForCreate(caller, requested)`: a super admin must choose one. + - `requireSuper(caller)` answers 403. + - Ported from babyboo's `AdminCountryScope` pattern. +5. **Inactive company:** + - `AdminSessionGuard`, which already loads the caller on every admin request, refuses a staff user whose company is inactive, with the same 401 as a dead session. + - `AdminAuthController.login` refuses one with `BAD_LOGIN`. + - The company status comes from services-system with the user, by adding `companyStatus` to the user lookup. That avoids an extra call per request. +6. **Scoped queries:** + - Each backend list or search endpoint takes an optional `companyId`; null means all companies, and only mobile-api decides when null is allowed. + - Detail and edit endpoints resolve the record, then compare its company with the scope; a mismatch answers 404. + - Where a services-counter query takes a mandatory `companyId` today, it becomes optional for lists. + - Every write still takes a concrete company. +7. **Events and emails get `company_id`:** + - `event.company_id bigint NULL`, set from the scope on create and never changed by edit. + - `email.company_id bigint NULL`, set by mobile-api `EmailService` from the user the email is for (forgot password, temporary password) and stored by service-email. + - Public form emails and other system emails have no company and are visible to super admins only. +8. **Interests become shared:** + - The unique key `(company_id, name)` becomes `(name)`; queries stop filtering by company. + - `interest.company_id` stays, unused and nullable, so no data is lost. + - Writes are super admin only. +9. **Login history and audit:** + - `login_audit.company_id` is filled from the user that the login name matches; it is already done this way. + - The audit actor's company is already stored. + - The searches take the scope; NULL-company rows match only when the scope is "all". +10. **Portal:** + - `AdminAuthContext` gains `companyId`, `companyCode` and `isSuper` from the login response. + - Super admins get a header `CompanyPicker`, persisted per tab. It feeds `companyId` into the list queries and the default of create forms. + - A `Company` column appears on scoped lists when "All companies" is selected. + - The login and forgot-password pages get a Company field. + - `/companies` is gated by `isSuper`, not by a module. +11. **One-time data step** (change folder SQL plus seed): + - Set company 1 to `INS`/`ins`; insert `CV`/`cv`. + - Set `admin` to company NULL. + - Rewrite the other admin usernames to `username@ins`. First check that none contains `@`; stop if one does. + - Set existing events and emails to company 1. + - Move the interest unique key. + +## Risks / Trade-offs + +- **Member usernames share the column.** A member whose username is exactly `john@ins` would block creating staff `john` in INS. Members do not exist in Co-Lite at go-live; the users API reports such a clash as "username taken". +- **The login name is visible in history and audit.** Login history and the audit log show `john@ins`, which is clear for staff and super admins alike. +- **A code change ends sessions.** This is intentional, and the Companies screen warns before saving. +- **Every scoped endpoint must use the scope.** A missed endpoint is a cross-company leak. + - Mitigation: one helper, a test per endpoint for another company's record, and a whole-branch review that checks every `/api/admin/**` handler. +- **Tokens in flight at deploy:** their subjects (for example `sales1`) no longer match the rewritten usernames, so every session ends. Co-Lite is not deployed yet, so nobody is affected. diff --git a/openspec/changes/add-company-scoping/proposal.md b/openspec/changes/add-company-scoping/proposal.md new file mode 100644 index 0000000..fe8a0a4 --- /dev/null +++ b/openspec/changes/add-company-scoping/proposal.md @@ -0,0 +1,39 @@ +# Proposal + +## Why + +Co-Lite goes live on 2027-01-15 with two test-run companies, INS and CV, and more are planned. Each company's staff must see only their own company's data, and one or more super admins must see and manage everything, including creating companies. Everything built so far assumes a single company: users, events, emails, login history and the audit log are unscoped, interests are per company, and there is no way to create a company or tell companies apart at sign-in. Approved design: `docs/superpowers/specs/2026-11-30-company-scoping-design.md`. + +## What Changes + +- **Companies:** `company` gains a unique `code` and an active/inactive `status`. A new super-admin-only Companies screen lists, creates and edits companies. An inactive company's staff cannot sign in. +- **Sign-in:** the admin login page asks for Company, Username and Password; a super admin leaves Company empty. Usernames and emails are unique within a company. Forgot password asks for the same company and username plus the email. +- **Super admins:** a super admin is a company-less admin user holding the super admin role. Company staff can never hold that role. There can be several super admins. +- **Scoping:** every admin read, write, export and detail lookup is limited to the caller's company: users, events, event leads, leads, emails, login history, locked users and the audit log. Another company's record answers 404. Super admins see all companies, can narrow to one, and pick the company when creating a company-owned record. +- **Shared data:** roles, interests, lockout settings and password rules are shared by all companies, and only super admins edit them. Interests become one shared list. +- **Portal:** a header company picker and a Company column for super admins; Company fields on the login, forgot-password, user and event forms; the Companies screen. +- **BREAKING (sign-in):** company staff must enter their company code to sign in. The deploy signs everyone out. +- **Deploy SQL:** company code/status, `company_id` on `event` and `email`, the interest unique key, staff login names, INS and CV setup. + +## Capabilities + +### New Capabilities +- `company-scoping`: companies, the Companies screen, company sign-in identity, super admins, and the rule that limits every admin view and action to the caller's company. + +### Modified Capabilities +- `admin-access`: staff login and forgot password take a company. +- `admin-users`: company membership, per-company username and email uniqueness, super admin creation. +- `admin-roles`: editing roles becomes super admin only. +- `lead-interests`: one shared interest list, edited by super admins only. +- `admin-login-security`: unlock is limited to the caller's company; settings become super admin only. + +## Impact + +- **services-system:** company entity, repository and endpoints; user lookup, save and uniqueness by login name; user search by company; login-history and locked-user filters by company. +- **services-counter:** `company_id` on events; event queries by company; interest queries become shared; queries accept "all companies" for super admins. +- **service-email:** `company_id` on emails, set when an email is saved for a user; search by company. +- **services-log:** audit search by company. +- **mobile-api:** login and forgot password with company; one company-scope helper used by every admin service; Companies API; super-admin-only guards on roles, interests and login-security settings. +- **admin portal:** login, forgot-password, header picker, Company column and fields, Companies screen, super-admin-only screens. +- **Database:** additive SQL in the change folder plus a data step for existing users, events and emails; mirrored in `local/seed/03-colite.sql`. +- **Unchanged:** services-auth, token format, members and the customer portal. diff --git a/openspec/changes/add-company-scoping/specs/admin-access/spec.md b/openspec/changes/add-company-scoping/specs/admin-access/spec.md new file mode 100644 index 0000000..1e75990 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/admin-access/spec.md @@ -0,0 +1,53 @@ +## MODIFIED Requirements + +### Requirement: Staff login + +The system SHALL let an active admin user log in through the admin portal with company code, username and password, or with username and password and no company for a super admin, and SHALL return the user's name, roles, company, menu and whether a password change is required. + +#### Scenario: Correct credentials + +- **GIVEN** an active admin user `sales1` of active company `ins` +- **WHEN** they submit company `ins`, username `sales1` and their password on the login page +- **THEN** they are signed in and land on the portal home +- **AND** the sidebar shows only the menu entries their roles grant + +#### Scenario: Super admin + +- **GIVEN** the super admin `admin`, who belongs to no company +- **WHEN** they submit username `admin` and their password with the company left empty +- **THEN** they are signed in + +#### Scenario: Wrong password + +- **WHEN** a user submits a wrong password +- **THEN** `/api/admin/auth/login` responds 401 +- **AND** the login page shows an invalid-credentials message without saying whether the company or username exists + +#### Scenario: Deactivated user + +- **GIVEN** an admin user whose account is deactivated +- **WHEN** they submit their correct password +- **THEN** login is refused with a 401 and the page shows the same invalid-credentials message + +#### Scenario: Member account + +- **WHEN** a member (non-admin) account submits its correct credentials to the admin login +- **THEN** login is refused with a 401 + +### Requirement: Forgot password + +The system SHALL let a user request a temporary password by entering their company code, username and email on a public forgot-password page; a super admin leaves the company empty. The response SHALL be the same whether or not the details match an active admin user. + +#### Scenario: Matching username and email + +- **GIVEN** an active admin user `sales1` of company `ins` with email `sales1@example.com` +- **WHEN** someone submits company `ins`, username `sales1` and `sales1@example.com` +- **THEN** a temporary password is emailed to `sales1@example.com` +- **AND** the user must change it at next login +- **AND** the page shows "If the details match an account, we have emailed a temporary password." + +#### Scenario: Non-matching details + +- **WHEN** someone submits a company, username and email that do not match an active admin user +- **THEN** no password changes and no email is sent +- **AND** the page shows the same message as for a match diff --git a/openspec/changes/add-company-scoping/specs/admin-login-security/spec.md b/openspec/changes/add-company-scoping/specs/admin-login-security/spec.md new file mode 100644 index 0000000..b8bb953 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/admin-login-security/spec.md @@ -0,0 +1,43 @@ +## MODIFIED Requirements + +### Requirement: Unlock + +The system SHALL let an admin with `BO_LOGIN_SECURITY` list the usernames of their own company that are locked now, with their failure count, last failure time and when the lock ends, and SHALL let that admin unlock one of them. A super admin SHALL see and unlock locked usernames of every company, including attempts that match no company. Unlocking SHALL save an `UNLOCK_RESET` record naming the admin who unlocked. + +#### Scenario: Unlock a locked username + +- **GIVEN** INS user `sales1` is locked +- **WHEN** an INS admin with `BO_LOGIN_SECURITY` unlocks `sales1` +- **THEN** `sales1` no longer appears in the locked list +- **AND** `sales1` can sign in with the right password +- **AND** an `UNLOCK_RESET` record for `sales1` names the admin + +#### Scenario: Another company's locked user + +- **GIVEN** CV user `sales2` is locked +- **WHEN** an INS admin with `BO_LOGIN_SECURITY` lists locked users or unlocks `sales2` of CV +- **THEN** `sales2` is not listed and the unlock answers 404 + +### Requirement: Lockout and password-rule settings + +The system SHALL let an admin with `BO_LOGIN_SECURITY` read the lockout settings and the admin password rules, and SHALL let only a super admin change them, because they apply to every company. The system SHALL reject a maximum below 1 or above 1000, a period below 1 or above 10000, and a time unit other than S, M, H or D. Password rules SHALL only be edited, never added or removed. Every change SHALL write a log line naming the admin. + +#### Scenario: Change the lockout settings + +- **WHEN** a super admin sets the maximum to 3 and the period to 30 minutes +- **THEN** the next lock decision in every company uses 3 attempts in 30 minutes + +#### Scenario: Invalid setting + +- **WHEN** a super admin sets the maximum to 0 +- **THEN** the change is refused with a validation error and the settings stay as they were + +#### Scenario: Change a password rule + +- **WHEN** a super admin sets the minimum length rule to 10 +- **THEN** a new password of 9 characters is refused by every admin password check + +#### Scenario: Company user changes settings + +- **WHEN** an INS user with `BO_LOGIN_SECURITY` changes a lockout setting or a password rule +- **THEN** the change is refused with 403 and the settings stay as they were diff --git a/openspec/changes/add-company-scoping/specs/admin-roles/spec.md b/openspec/changes/add-company-scoping/specs/admin-roles/spec.md new file mode 100644 index 0000000..f7718d8 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/admin-roles/spec.md @@ -0,0 +1,38 @@ +## MODIFIED Requirements + +### Requirement: Role list and edit + +The system SHALL let any admin with `BO_ROLES` list admin roles, and SHALL let only a super admin create and rename them, because roles are shared by every company. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules). + +#### Scenario: Create role + +- **WHEN** a super admin creates role `ROLE_SALES` +- **THEN** it appears in the role list and can be assigned to users of any company + +#### Scenario: Duplicate name + +- **GIVEN** role `ROLE_SALES` exists +- **WHEN** a super admin creates another role named `ROLE_SALES` +- **THEN** the save is refused with a message + +#### Scenario: Company user edits a role + +- **WHEN** an INS user with `BO_ROLES` creates or renames a role +- **THEN** the request is refused with 403 and nothing changes + +### Requirement: Role permissions + +The system SHALL let only a super admin choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. Admins with `BO_ROLES` who are not super admins SHALL see the grants read-only. + +#### Scenario: Grant Users module + +- **GIVEN** role `ROLE_SALES` without `BO_USERS` +- **WHEN** a super admin grants `BO_USERS` to `ROLE_SALES` and saves +- **THEN** users with `ROLE_SALES` in every company see Users in the sidebar after their next login or session refresh +- **AND** `GET /api/admin/users` responds 200 for them + +#### Scenario: Own role + +- **GIVEN** an INS user who is not super admin and holds `ROLE_SALES` and `BO_ROLES` +- **WHEN** they change the module grants of `ROLE_SALES`, or of any other role +- **THEN** the save is refused with 403 and the grants stay as they were diff --git a/openspec/changes/add-company-scoping/specs/admin-users/spec.md b/openspec/changes/add-company-scoping/specs/admin-users/spec.md new file mode 100644 index 0000000..3b0e124 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/admin-users/spec.md @@ -0,0 +1,44 @@ +## MODIFIED Requirements + +### Requirement: Company membership + +Every admin user other than a super admin SHALL belong to exactly one company. A company user's new user SHALL belong to the creating user's company, whatever the request says. A super admin SHALL choose the company of a new user, or no company to create another super admin. + +#### Scenario: Company in the request is ignored + +- **WHEN** an INS user's create-user request carries the CV company id +- **THEN** the new user belongs to INS + +#### Scenario: Super admin chooses the company + +- **WHEN** a super admin creates a user and chooses CV +- **THEN** the new user belongs to CV + +### Requirement: Create user + +The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email, one or more roles, and an initial password with its confirmation. Username and email SHALL be unique within the user's company, so the same username or email may exist in another company. A username SHALL NOT contain `@`. The password SHALL match its confirmation and pass the admin password rules. The new user SHALL be saved with a pending password change and SHALL NOT be sent an email. + +#### Scenario: New user + +- **WHEN** an INS admin creates user `sales1` with email `sales1@example.com`, role Sales and a valid initial password +- **THEN** the user is saved as active in INS with a pending password change +- **AND** `sales1` can sign in with company `ins` and that password and must choose a new password before anything else +- **AND** no email is sent + +#### Scenario: Duplicate username + +- **GIVEN** a user `sales1` exists in INS +- **WHEN** an admin creates another INS user with username `sales1` +- **THEN** the save is refused and the form shows that the username is taken + +#### Scenario: Same username in another company + +- **GIVEN** a user `sales1` exists in INS +- **WHEN** a CV admin creates user `sales1` in CV +- **THEN** the user is created + +#### Scenario: Weak or mismatched initial password + +- **WHEN** an admin creates a user with a password that fails the admin password rules, or that does not match its confirmation +- **THEN** the save is refused with a message on the form +- **AND** no user is created diff --git a/openspec/changes/add-company-scoping/specs/company-scoping/spec.md b/openspec/changes/add-company-scoping/specs/company-scoping/spec.md new file mode 100644 index 0000000..65f6ada --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/company-scoping/spec.md @@ -0,0 +1,128 @@ +## ADDED Requirements + +### Requirement: Companies + +The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of lowercase letters, digits and hyphens, compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only. + +#### Scenario: Create a company + +- **WHEN** a super admin creates company `CV` with code `cv` +- **THEN** it is listed as active +- **AND** staff can be created in it + +#### Scenario: Duplicate code + +- **GIVEN** a company with code `ins` +- **WHEN** a super admin creates or renames another company to code `INS` +- **THEN** the save is refused and the code is reported as taken + +#### Scenario: Not a super admin + +- **WHEN** company staff open the Companies page or call a companies endpoint +- **THEN** the page shows not-authorised and the endpoint responds 403 + +### Requirement: Company sign-in + +The system SHALL sign company staff in with company code, username and password, and SHALL sign super admins in with username and password and no company. The answer SHALL be the same for a wrong or unknown company, an inactive company, an unknown user and a wrong password. A user's sessions SHALL end when their company is deactivated or its code is changed. + +#### Scenario: Staff sign-in + +- **GIVEN** an active user `john` in active company `ins` +- **WHEN** they sign in with company `ins`, username `john` and the right password +- **THEN** they are signed in as `john` of INS + +#### Scenario: Same username in two companies + +- **GIVEN** a user `john` in INS and a different user `john` in CV +- **WHEN** someone signs in with company `cv`, username `john` and CV John's password +- **THEN** they are signed in as CV's John and see only CV data + +#### Scenario: Wrong company + +- **WHEN** INS's `john` signs in with company `cv` or a code that does not exist +- **THEN** login is refused with the same invalid-credentials answer as a wrong password + +#### Scenario: Inactive company + +- **GIVEN** company CV is deactivated +- **WHEN** a CV user signs in with the right password, or uses an existing session +- **THEN** the sign-in is refused with the invalid-credentials answer and the session ends + +#### Scenario: Code changed + +- **GIVEN** a signed-in user of the company with code `ins` +- **WHEN** a super admin changes that code to `ins-my` +- **THEN** the user's session ends +- **AND** they sign in again with company `ins-my` + +### Requirement: Super admins + +A super admin SHALL be an admin user who belongs to no company and holds the super admin role. Only a super admin SHALL create another super admin. The super admin role SHALL NOT be granted to a user who belongs to a company, and every admin user who is not a super admin SHALL belong to a company. + +#### Scenario: Create a second super admin + +- **WHEN** a super admin creates a user with no company +- **THEN** the user is created as a super admin and signs in without a company + +#### Scenario: Super admin role for company staff + +- **WHEN** anyone assigns the super admin role to a user of INS +- **THEN** the save is refused with a message + +### Requirement: Company data is separated + +The system SHALL limit every admin list, search, export, detail, create, edit and action to the caller's company for: users, events, event teams, event leads, leads, emails, login history, locked users and audit events. A record of another company SHALL answer 404, as if it did not exist. + +#### Scenario: Lists show own company only + +- **GIVEN** leads, events and users in INS and in CV +- **WHEN** an INS user with the matching modules opens Leads, Events or Users +- **THEN** only INS records are listed +- **AND** an export contains only INS leads + +#### Scenario: Another company's record by id + +- **GIVEN** a CV lead, event, user or email +- **WHEN** an INS user requests it, edits it or acts on it by its id +- **THEN** the answer is 404 and nothing changes + +#### Scenario: Same phone in two companies + +- **GIVEN** INS has a lead with mobile `+60123456789` +- **WHEN** a CV user captures a lead with the same mobile at a CV event +- **THEN** a new CV lead is created and flagged New +- **AND** the INS lead is unchanged + +### Requirement: Super admin sees all companies + +The system SHALL show super admins every company's records by default, SHALL let them narrow any scoped list to one company, and SHALL show each record's company in mixed lists. Creating a company-owned record (user, event, event lead) SHALL require a super admin to choose the company. + +#### Scenario: Mixed list + +- **WHEN** a super admin opens Leads with all companies selected +- **THEN** INS and CV leads are listed together with a Company column + +#### Scenario: Pick a company + +- **WHEN** a super admin picks CV in the company picker +- **THEN** scoped lists show CV records only + +#### Scenario: Create without a company + +- **WHEN** a super admin creates an event without choosing a company +- **THEN** the save is refused and the form asks for a company + +### Requirement: Company of login and audit records + +An audit event and a login-history record SHALL belong to the company of the user who acted, or of the user who tried to sign in when the given company and username match a user. Records with no company SHALL be visible to super admins only. + +#### Scenario: Super admin edits a company record + +- **WHEN** a super admin edits an INS lead +- **THEN** the audit event has no company +- **AND** INS staff with Audit log do not see it, and super admins do + +#### Scenario: Failed sign-in with an unknown company + +- **WHEN** someone fails to sign in with a company code that does not exist +- **THEN** the login-history record has no company and only super admins see it diff --git a/openspec/changes/add-company-scoping/specs/lead-interests/spec.md b/openspec/changes/add-company-scoping/specs/lead-interests/spec.md new file mode 100644 index 0000000..bfab899 --- /dev/null +++ b/openspec/changes/add-company-scoping/specs/lead-interests/spec.md @@ -0,0 +1,34 @@ +## MODIFIED Requirements + +### Requirement: Interest list + +The system SHALL keep one interest list shared by all companies. Admins with `BO_INTERESTS` SHALL see the list, and only a super admin SHALL add, rename, reorder, deactivate and reactivate interests. An interest name SHALL be required, at most 100 characters, and unique ignoring case. Interests SHALL NOT be deletable. + +#### Scenario: Add interest + +- **WHEN** a super admin adds `Kitchen appliances` +- **THEN** it is listed as active +- **AND** staff of every company can tag leads with it + +#### Scenario: Duplicate name + +- **GIVEN** an interest `Kitchen appliances` +- **WHEN** a super admin adds `kitchen APPLIANCES` +- **THEN** the save is refused and the name is reported as a duplicate + +#### Scenario: Deactivate + +- **GIVEN** an active interest `Cookware` +- **WHEN** a super admin deactivates it +- **THEN** it is still listed, marked inactive +- **AND** it is no longer offered when capturing a lead in any company + +#### Scenario: Company user edits + +- **WHEN** an INS user with `BO_INTERESTS` adds, renames or deactivates an interest +- **THEN** the request is refused with 403 and the list is unchanged + +#### Scenario: No module + +- **WHEN** an admin without `BO_INTERESTS` opens the Interests page or calls an interests endpoint +- **THEN** the page shows not-authorised and the endpoint responds 403 diff --git a/openspec/changes/add-company-scoping/tasks.md b/openspec/changes/add-company-scoping/tasks.md new file mode 100644 index 0000000..b24c8d5 --- /dev/null +++ b/openspec/changes/add-company-scoping/tasks.md @@ -0,0 +1,124 @@ +# Tasks + +Design: `design.md`. All tasks run serially, ordered so that sign-in keeps working after each one. Every scoped endpoint gets a test where another company's record answers 404 (or is absent from the list). + +## 1. Data + +- [ ] 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 + +- [ ] 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` +- [ ] 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` +- [ ] 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 + +- [ ] 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` +- [ ] 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` +- [ ] 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` +- [ ] 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 + +- [ ] 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` +- [ ] 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 + +- [ ] 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. -- 2.54.1 From 840b5a3baee7d2bca8602450457d5cc9bfbc505e Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 18:44:50 +0800 Subject: [PATCH 03/24] feat: company code and status, company on events and emails, admin login names Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 51 +++++++++++++++++++ .../sql/01-company-code-status.sql | 16 ++++++ .../sql/02-company-columns.sql | 17 +++++++ .../sql/03-admin-login-names.sql | 24 +++++++++ .../add-company-scoping/sql/99-rollback.sql | 15 ++++++ openspec/changes/add-company-scoping/tasks.md | 2 +- 6 files changed, 124 insertions(+), 1 deletion(-) create mode 100644 openspec/changes/add-company-scoping/sql/01-company-code-status.sql create mode 100644 openspec/changes/add-company-scoping/sql/02-company-columns.sql create mode 100644 openspec/changes/add-company-scoping/sql/03-admin-login-names.sql create mode 100644 openspec/changes/add-company-scoping/sql/99-rollback.sql diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index b6d608c..5b6f765 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -177,3 +177,54 @@ CREATE TABLE IF NOT EXISTS `audit_event` ( KEY `idx_audit_event_actor` (`actor`, `occurred_at`), KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- add-company-scoping/sql/01-company-code-status.sql +USE `service-system`; + +ALTER TABLE `company` + ADD COLUMN `code` varchar(20) NULL AFTER `name`, + ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`; + +UPDATE `company` SET `name` = 'INS', `code` = 'ins' WHERE `id` = 1; +INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'cv', 'A'); + +ALTER TABLE `company` + MODIFY COLUMN `code` varchar(20) NOT NULL, + ADD UNIQUE KEY `uk_company_code` (`code`); + +-- add-company-scoping/sql/02-company-columns.sql +USE `service-counter`; + +ALTER TABLE `event` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_event_company` (`company_id`); +UPDATE `event` SET `company_id` = 1 WHERE `company_id` IS NULL; + +ALTER TABLE `interest` + DROP INDEX `uk_interest_company_name`, + MODIFY COLUMN `company_id` bigint NULL, + ADD UNIQUE KEY `uk_interest_name` (`name`); + +USE `service-email`; + +ALTER TABLE `email` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_email_company` (`company_id`); +UPDATE `email` SET `company_id` = 1 WHERE `company_id` IS NULL; + +-- add-company-scoping/sql/03-admin-login-names.sql +USE `service-system`; + +DROP PROCEDURE IF EXISTS `colite_check_admin_usernames`; +DELIMITER // +CREATE PROCEDURE `colite_check_admin_usernames`() +BEGIN + IF EXISTS (SELECT 1 FROM `user` WHERE `type` = 'A' AND `username` LIKE '%@%') THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An admin username contains @; rename it before running this script'; + END IF; +END // +DELIMITER ; +CALL `colite_check_admin_usernames`(); +DROP PROCEDURE `colite_check_admin_usernames`; + +UPDATE `user` u SET u.`company_id` = NULL +WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1); + +UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins') +WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1); diff --git a/openspec/changes/add-company-scoping/sql/01-company-code-status.sql b/openspec/changes/add-company-scoping/sql/01-company-code-status.sql new file mode 100644 index 0000000..76372cf --- /dev/null +++ b/openspec/changes/add-company-scoping/sql/01-company-code-status.sql @@ -0,0 +1,16 @@ +-- Co-Lite change add-company-scoping: company code and status; INS and CV. +-- Target: `service-system`.`company`. Run once, after the release package, before 02 and 03. +-- DDL: run with a user that may alter tables, not the services' user. +USE `service-system`; + +ALTER TABLE `company` + ADD COLUMN `code` varchar(20) NULL AFTER `name`, + ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`; + +-- The existing company (all current data) becomes INS. +UPDATE `company` SET `name` = 'INS', `code` = 'ins' WHERE `id` = 1; +INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'cv', 'A'); + +ALTER TABLE `company` + MODIFY COLUMN `code` varchar(20) NOT NULL, + ADD UNIQUE KEY `uk_company_code` (`code`); diff --git a/openspec/changes/add-company-scoping/sql/02-company-columns.sql b/openspec/changes/add-company-scoping/sql/02-company-columns.sql new file mode 100644 index 0000000..04f1fc5 --- /dev/null +++ b/openspec/changes/add-company-scoping/sql/02-company-columns.sql @@ -0,0 +1,17 @@ +-- Co-Lite change add-company-scoping: company on events and emails; one shared interest list. +-- Run once, after 01. DDL: run with a user that may alter tables. +USE `service-counter`; + +ALTER TABLE `event` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_event_company` (`company_id`); +UPDATE `event` SET `company_id` = 1 WHERE `company_id` IS NULL; + +-- Interests are shared by every company: unique by name (case-insensitive collation); company_id kept, unused. +ALTER TABLE `interest` + DROP INDEX `uk_interest_company_name`, + MODIFY COLUMN `company_id` bigint NULL, + ADD UNIQUE KEY `uk_interest_name` (`name`); + +USE `service-email`; + +ALTER TABLE `email` ADD COLUMN `company_id` bigint NULL, ADD KEY `idx_email_company` (`company_id`); +UPDATE `email` SET `company_id` = 1 WHERE `company_id` IS NULL; diff --git a/openspec/changes/add-company-scoping/sql/03-admin-login-names.sql b/openspec/changes/add-company-scoping/sql/03-admin-login-names.sql new file mode 100644 index 0000000..1ebcc1e --- /dev/null +++ b/openspec/changes/add-company-scoping/sql/03-admin-login-names.sql @@ -0,0 +1,24 @@ +-- Co-Lite change add-company-scoping: admin sign-in names. +-- Super admins (role 1) belong to no company and keep their username. +-- Every other admin user keeps company 1 (INS) and is renamed username@ins; they sign in with company "ins". +-- Ends every admin session (token subjects no longer match). Run once, after 01 and 02. +USE `service-system`; + +-- Stop if any admin username already contains '@': it would be ambiguous after the rename. +DROP PROCEDURE IF EXISTS `colite_check_admin_usernames`; +DELIMITER // +CREATE PROCEDURE `colite_check_admin_usernames`() +BEGIN + IF EXISTS (SELECT 1 FROM `user` WHERE `type` = 'A' AND `username` LIKE '%@%') THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An admin username contains @; rename it before running this script'; + END IF; +END // +DELIMITER ; +CALL `colite_check_admin_usernames`(); +DROP PROCEDURE `colite_check_admin_usernames`; + +UPDATE `user` u SET u.`company_id` = NULL +WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1); + +UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins') +WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1); diff --git a/openspec/changes/add-company-scoping/sql/99-rollback.sql b/openspec/changes/add-company-scoping/sql/99-rollback.sql new file mode 100644 index 0000000..af240a1 --- /dev/null +++ b/openspec/changes/add-company-scoping/sql/99-rollback.sql @@ -0,0 +1,15 @@ +-- Co-Lite change add-company-scoping: rollback of 01-03. CV's data, if any, stays in its tables with company 2. +USE `service-system`; +UPDATE `user` SET `username` = SUBSTRING_INDEX(`username`, '@', 1) WHERE `type` = 'A' AND `username` LIKE '%@%'; +UPDATE `user` SET `company_id` = 1 WHERE `type` = 'A' AND `company_id` IS NULL; +ALTER TABLE `company` DROP INDEX `uk_company_code`, DROP COLUMN `status`, DROP COLUMN `code`; +UPDATE `company` SET `name` = 'Co-Lite' WHERE `id` = 1; + +USE `service-counter`; +ALTER TABLE `event` DROP KEY `idx_event_company`, DROP COLUMN `company_id`; +UPDATE `interest` SET `company_id` = 1 WHERE `company_id` IS NULL; +ALTER TABLE `interest` DROP INDEX `uk_interest_name`, MODIFY COLUMN `company_id` bigint NOT NULL, + ADD UNIQUE KEY `uk_interest_company_name` (`company_id`, `name`); + +USE `service-email`; +ALTER TABLE `email` DROP KEY `idx_email_company`, DROP COLUMN `company_id`; diff --git a/openspec/changes/add-company-scoping/tasks.md b/openspec/changes/add-company-scoping/tasks.md index b24c8d5..072c8b9 100644 --- a/openspec/changes/add-company-scoping/tasks.md +++ b/openspec/changes/add-company-scoping/tasks.md @@ -4,7 +4,7 @@ Design: `design.md`. All tasks run serially, ordered so that sign-in keeps worki ## 1. Data -- [ ] 1.1 SQL and local seed (design decisions 3, 7, 8 and 11). +- [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)`. -- 2.54.1 From c9c0745955f396f9c6e61cbb1acc2c9583fbea3c Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 19:16:54 +0800 Subject: [PATCH 04/24] feat: companies API, company on user lookups, company filters for users and login security Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-company-scoping/tasks.md | 2 +- .../java/com/solvway/core/model/User.java | 2 + .../solvway/core/model/UserCompanyTest.java | 29 +++ .../system/controller/CompanyController.java | 51 +++++ .../controller/LoginSecurityController.java | 15 +- .../system/controller/UserController.java | 24 ++ .../services/system/model/Company.java | 23 ++ .../solvway/services/system/model/User.java | 6 + .../system/repo/CompanyRepository.java | 16 ++ .../system/repo/LoginAuditRepository.java | 12 + .../services/system/repo/UserRepository.java | 10 + .../system/repo/UserRepositoryImpl.java | 4 + .../system/service/CompanyService.java | 108 +++++++++ .../system/service/LoginSecurityService.java | 38 +++- .../services/system/service/UserService.java | 10 + .../controller/CompanyControllerTest.java | 103 +++++++++ .../LoginSecurityControllerCompanyTest.java | 75 +++++++ .../UserControllerCompanyGuardTest.java | 139 ++++++++++++ .../system/model/UserCompanyMappingTest.java | 20 ++ .../repo/UserRepositoryImplCompanyTest.java | 81 +++++++ .../system/service/CompanyServiceTest.java | 207 ++++++++++++++++++ .../LoginSecurityServiceCompanyTest.java | 169 ++++++++++++++ .../service/UserServiceCompanyTest.java | 50 +++++ 23 files changed, 1181 insertions(+), 13 deletions(-) create mode 100644 solvway-core-libs/src/test/java/com/solvway/core/model/UserCompanyTest.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/controller/CompanyController.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/model/Company.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/repo/CompanyRepository.java create mode 100644 solvway-services-system/src/main/java/com/solvway/services/system/service/CompanyService.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/CompanyControllerTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/LoginSecurityControllerCompanyTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerCompanyGuardTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/model/UserCompanyMappingTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/repo/UserRepositoryImplCompanyTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/service/CompanyServiceTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/service/LoginSecurityServiceCompanyTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/service/UserServiceCompanyTest.java diff --git a/openspec/changes/add-company-scoping/tasks.md b/openspec/changes/add-company-scoping/tasks.md index 072c8b9..e7f3fb5 100644 --- a/openspec/changes/add-company-scoping/tasks.md +++ b/openspec/changes/add-company-scoping/tasks.md @@ -16,7 +16,7 @@ Design: `design.md`. All tasks run serially, ordered so that sign-in keeps worki ## 2. Backend services -- [ ] 2.1 services-system: companies, users and login security (decisions 1, 2, 3, 5 and 9). +- [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; diff --git a/solvway-core-libs/src/main/java/com/solvway/core/model/User.java b/solvway-core-libs/src/main/java/com/solvway/core/model/User.java index 4799c87..22236bb 100644 --- a/solvway-core-libs/src/main/java/com/solvway/core/model/User.java +++ b/solvway-core-libs/src/main/java/com/solvway/core/model/User.java @@ -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() { } diff --git a/solvway-core-libs/src/test/java/com/solvway/core/model/UserCompanyTest.java b/solvway-core-libs/src/test/java/com/solvway/core/model/UserCompanyTest.java new file mode 100644 index 0000000..b44e47b --- /dev/null +++ b/solvway-core-libs/src/test/java/com/solvway/core/model/UserCompanyTest.java @@ -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); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/CompanyController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/CompanyController.java new file mode 100644 index 0000000..43e654e --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/CompanyController.java @@ -0,0 +1,51 @@ +package com.solvway.services.system.controller; + +import com.solvway.services.system.model.Company; +import com.solvway.services.system.service.CompanyService; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/company") +public class CompanyController { + + private final CompanyService service; + + public CompanyController(CompanyService service) { + this.service = service; + } + + @GetMapping("/findAll") + public List findAll() { + return service.findAll(); + } + + @GetMapping("/findById/{id}") + public Company findById(@PathVariable Long id) { + return service.findById(id); + } + + @GetMapping("/findByCode/{code}") + public Company findByCode(@PathVariable String code) { + return service.findByCode(code); + } + + @PostMapping("/save") + public Company save(@RequestBody Company c) { + return service.save(c); + } + + @PostMapping("/{id}/code") + public Company renameCode(@PathVariable Long id, @RequestBody Map body) { + return service.renameCode(id, body.get("code")); + } + + @ExceptionHandler({IllegalArgumentException.class, HttpMessageNotReadableException.class}) + public ResponseEntity> badRequest(RuntimeException e) { + return ResponseEntity.badRequest().body(Map.of("message", String.valueOf(e.getMessage()))); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/LoginSecurityController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/LoginSecurityController.java index 7e25273..c28ccff 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/LoginSecurityController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/LoginSecurityController.java @@ -18,8 +18,8 @@ import java.util.Map; public class LoginSecurityController { record RecordBody(String username, String event, String ip, String userAgent, String message) {} - record AuditBody(String username, String event, String from, String to, Integer page, Integer size) {} - record UnlockBody(String username, String by) {} + record AuditBody(String username, String event, String from, String to, Integer page, Integer size, Long companyId) {} + record UnlockBody(String username, String by, Long companyId) {} private final LoginSecurityService service; @@ -41,18 +41,21 @@ public class LoginSecurityController { @PostMapping("/audit") public Map audit(@RequestBody AuditBody b) { body(b); - return service.audit(b.username(), b.event(), date(b.from()), date(b.to()), b.page(), b.size()); + return b.companyId() == null + ? service.audit(b.username(), b.event(), date(b.from()), date(b.to()), b.page(), b.size()) + : service.audit(b.username(), b.event(), date(b.from()), date(b.to()), b.page(), b.size(), b.companyId()); } @GetMapping("/locked") - public List locked() { - return service.lockedUsers(); + public List locked(@RequestParam(required = false) Long companyId) { + return companyId == null ? service.lockedUsers() : service.lockedUsers(companyId); } @PostMapping("/unlock") public void unlock(@RequestBody UnlockBody b) { body(b); - service.unlock(b.username(), b.by()); + if (b.companyId() == null) service.unlock(b.username(), b.by()); + else service.unlock(b.username(), b.by(), b.companyId()); } @GetMapping("/config") diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java index d8b8b2b..94a27a9 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java @@ -239,6 +239,16 @@ public class UserController { return user; } + @RequestMapping("/findByEmailAndCompanyId/{email}") + public User findByEmailAndCompanyId(@PathVariable("email") String email, @org.springframework.web.bind.annotation.RequestParam(value = "companyId", required = false) Long companyId) { + return userService.findByEmailAndCompanyId(email, companyId); + } + + @RequestMapping("/findByEmailAndCompanyIdAndIdNot/{email}/{id}") + public User findByEmailAndCompanyIdAndIdNot(@PathVariable("email") String email, @PathVariable("id") Long id, @org.springframework.web.bind.annotation.RequestParam(value = "companyId", required = false) Long companyId) { + return userService.findByEmailAndCompanyIdAndIdNot(email, companyId, id); + } + @RequestMapping("/findByUsernameAndIdNot/{username}/{id}") public User findByUsernameAndIdNot(@PathVariable("username") String username, @PathVariable("id") Long id) { User user = userService.findByUsernameAndIdNot(username, id); @@ -298,6 +308,20 @@ public class UserController { @RequestMapping("/save") public User save(@RequestBody User user) { + // Guard the EFFECTIVE company and type: an edit that omits them keeps the stored values. + User stored = user.getId() == null ? null : userService.findById(user.getId()).orElse(null); + Long companyId = user.getCompanyId() != null || stored == null ? user.getCompanyId() : stored.getCompanyId(); + UserType type = user.getType() != null || stored == null ? user.getType() : stored.getType(); + if (type == UserType.A) { + List roles = user.getRoles() != null || stored == null ? user.getRoles() : stored.getRoles(); + boolean superAdmin = roles != null && roles.stream().anyMatch(r -> Long.valueOf(1L).equals(r.getId())); + if (companyId != null && superAdmin) { + throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.BAD_REQUEST, "A user with a company cannot be a super admin"); + } + if (companyId == null && !superAdmin) { + throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.BAD_REQUEST, "An admin without a company must be a super admin"); + } + } try { if(user.getId()!=null) { User persistedUser = findByIdWithPassword(user.getId()); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/Company.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/Company.java new file mode 100644 index 0000000..0ffb630 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/Company.java @@ -0,0 +1,23 @@ +package com.solvway.services.system.model; + +import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; + +@Entity +@Table(name = "company") +@Getter +@Setter +public class Company { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + + private String code; + + /** A active, I inactive. */ + private String status; +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/User.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/User.java index 9ab4b9a..dacbe9f 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/model/User.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/User.java @@ -131,6 +131,12 @@ public class User { private Long companyId; + @org.hibernate.annotations.Formula("(select c.code from company c where c.id = company_id)") + private String companyCode; + + @org.hibernate.annotations.Formula("(select c.status from company c where c.id = company_id)") + private String companyStatus; + @Transient private List linkedAccounts; diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/CompanyRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/CompanyRepository.java new file mode 100644 index 0000000..e81d503 --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/CompanyRepository.java @@ -0,0 +1,16 @@ +package com.solvway.services.system.repo; + +import com.solvway.services.system.model.Company; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface CompanyRepository extends JpaRepository { + + List findAllByOrderByNameAsc(); + + Optional findByCodeIgnoreCase(String code); +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/LoginAuditRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/LoginAuditRepository.java index 4078a8d..b7fc4f2 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/repo/LoginAuditRepository.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/LoginAuditRepository.java @@ -23,6 +23,18 @@ public interface LoginAuditRepository extends JpaRepository { @Query("SELECT DISTINCT a.username FROM LoginAudit a WHERE a.event = 'LOGIN_FAIL' AND a.datetime > :since") List findUsernamesWithFailuresAfter(@Param("since") LocalDateTime since); + @Query("SELECT DISTINCT a.username FROM LoginAudit a WHERE a.event = 'LOGIN_FAIL' AND a.datetime > :since AND a.companyId = :companyId") + List findUsernamesWithFailuresAfterInCompany(@Param("since") LocalDateTime since, @Param("companyId") Long companyId); + + @Query("SELECT a FROM LoginAudit a WHERE (:pattern IS NULL OR a.username LIKE :pattern) " + + "AND (:event IS NULL OR a.event = :event) " + + "AND (:from IS NULL OR a.datetime >= :from) " + + "AND (:toExclusive IS NULL OR a.datetime < :toExclusive) " + + "AND a.companyId = :companyId") + Page searchInCompany(@Param("pattern") String pattern, @Param("event") String event, + @Param("from") LocalDateTime from, @Param("toExclusive") LocalDateTime toExclusive, + @Param("companyId") Long companyId, Pageable pageable); + /** Null arguments are ignored; {@code pattern} is a LIKE pattern, {@code toExclusive} an exclusive upper bound. */ @Query("SELECT a FROM LoginAudit a WHERE (:pattern IS NULL OR a.username LIKE :pattern) " + "AND (:event IS NULL OR a.event = :event) " diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepository.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepository.java index f0dfa68..881e163 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepository.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepository.java @@ -24,6 +24,16 @@ public interface UserRepository extends JpaRepository, JpaRepository User findByEmailAndIdNot(String email, Long id); + User findByEmailAndCompanyIdAndType(String email, Long companyId, com.solvway.core.enums.UserEnum.UserType type); + + User findByEmailAndCompanyIdIsNullAndType(String email, com.solvway.core.enums.UserEnum.UserType type); + + User findByEmailAndCompanyIdAndTypeAndIdNot(String email, Long companyId, com.solvway.core.enums.UserEnum.UserType type, Long id); + + User findByEmailAndCompanyIdIsNullAndTypeAndIdNot(String email, com.solvway.core.enums.UserEnum.UserType type, Long id); + + java.util.List findByCompanyIdAndType(Long companyId, com.solvway.core.enums.UserEnum.UserType type); + User findByUsernameAndIdNot(String username, Long id); Page findByUsernameContainingOrderByIdAsc(String username, Pageable pageable); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepositoryImpl.java b/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepositoryImpl.java index 4639549..6f9782b 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepositoryImpl.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/repo/UserRepositoryImpl.java @@ -73,6 +73,10 @@ public class UserRepositoryImpl implements JpaRepositoryCustom{ predicates.add(cb.equal(root.get(k), UserType.valueOf(value))); predicatesCount.add(cb.equal(rootCount.get(k), UserType.valueOf(value))); } + case "companyId" -> { + predicates.add(cb.equal(root.get("companyId"), Long.valueOf(value))); + predicatesCount.add(cb.equal(rootCount.get("companyId"), Long.valueOf(value))); + } case "userGroupId" -> { predicates.add(cb.equal(root.get("userGroup").get("id"), Long.valueOf(value))); predicatesCount.add(cb.equal(rootCount.get("userGroup").get("id"), Long.valueOf(value))); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/CompanyService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/CompanyService.java new file mode 100644 index 0000000..a93e86c --- /dev/null +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/CompanyService.java @@ -0,0 +1,108 @@ +package com.solvway.services.system.service; + +import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.model.Company; +import com.solvway.services.system.model.User; +import com.solvway.services.system.repo.CompanyRepository; +import com.solvway.services.system.repo.UserRepository; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.regex.Pattern; + +@Service +public class CompanyService { + + private static final int USERNAME_MAX = 255; // user.username column length + private static final Pattern CODE = Pattern.compile("^[a-z0-9-]{2,20}$"); + + private final CompanyRepository companies; + private final UserRepository users; + + public CompanyService(CompanyRepository companies, UserRepository users) { + this.companies = companies; + this.users = users; + } + + public List findAll() { + return companies.findAllByOrderByNameAsc(); + } + + public Company findById(Long id) { + return companies.findById(id).orElse(null); + } + + public Company findByCode(String code) { + return companies.findByCodeIgnoreCase(code).orElse(null); + } + + /** Create (id null) or edit name and status; the code of an existing company changes only through renameCode. */ + @Transactional + public Company save(Company in) { + String name = in.getName() == null ? "" : in.getName().trim(); + if (name.isEmpty()) throw new IllegalArgumentException("Name is required"); + String status = in.getStatus() == null ? "A" : in.getStatus(); + if (!status.equals("A") && !status.equals("I")) throw new IllegalArgumentException("Status must be A or I"); + if (in.getId() == null) { + Company c = new Company(); + c.setName(name); + c.setStatus(status); + c.setCode(freeCode(in.getCode(), null)); + return saveUnique(c); + } + Company c = companies.findById(in.getId()).orElseThrow(() -> notFound()); + c.setName(name); + c.setStatus(status); + return saveUnique(c); + } + + /** Changes the code and the login name (local@code) of every admin of the company, atomically. */ + @Transactional + public Company renameCode(Long id, String code) { + String newCode = validCode(code); + Company c = companies.findById(id).orElseThrow(() -> notFound()); + c.setCode(freeCode(newCode, id)); + List admins = users.findByCompanyIdAndType(id, UserType.A); + for (User u : admins) { + String name = u.getUsername(); + String renamed = name.substring(0, name.lastIndexOf('@') < 0 ? name.length() : name.lastIndexOf('@')) + "@" + newCode; + if (renamed.length() > USERNAME_MAX) throw new IllegalArgumentException("Login name too long for " + name + " with the new code"); + u.setUsername(renamed); + } + saveUnique(c); + users.saveAll(admins); + return c; + } + + /** Flushes so a unique-key race on code surfaces here as 409, not at commit. */ + private Company saveUnique(Company c) { + try { + Company saved = companies.save(c); + companies.flush(); + return saved; + } catch (DataIntegrityViolationException e) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "Code is already taken"); + } + } + + private String freeCode(String code, Long ownId) { + String v = validCode(code); + companies.findByCodeIgnoreCase(v).filter(o -> !o.getId().equals(ownId)) + .ifPresent(o -> { throw new ResponseStatusException(HttpStatus.CONFLICT, "Code is already taken"); }); + return v; + } + + private static String validCode(String code) { + String v = code == null ? "" : code.trim().toLowerCase(); + if (!CODE.matcher(v).matches()) throw new IllegalArgumentException("Code must be 2 to 20 characters: a-z, 0-9 or -"); + return v; + } + + private static ResponseStatusException notFound() { + return new ResponseStatusException(HttpStatus.NOT_FOUND, "Company not found"); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/LoginSecurityService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/LoginSecurityService.java index 6e39f06..cfc58a2 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/service/LoginSecurityService.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/LoginSecurityService.java @@ -9,7 +9,9 @@ import com.solvway.services.system.repo.UserRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; import org.springframework.transaction.annotation.Transactional; import java.time.Clock; @@ -78,10 +80,17 @@ public class LoginSecurityService { } public List lockedUsers() { + return lockedUsers(null); + } + + /** companyId null means every row, including those without a company. */ + public List lockedUsers(Long companyId) { Config c = config(); if (!c.enabled() || !c.valid()) return List.of(); LocalDateTime now = LocalDateTime.now(clock); - return audits.findUsernamesWithFailuresAfter(now.minus(c.length())).stream() + List names = companyId == null ? audits.findUsernamesWithFailuresAfter(now.minus(c.length())) + : audits.findUsernamesWithFailuresAfterInCompany(now.minus(c.length()), companyId); + return names.stream() .map(u -> evaluate(u, c, now)).filter(l -> l != null).toList(); } @@ -94,16 +103,33 @@ public class LoginSecurityService { write(username, "UNLOCK_RESET", null, null, cut("unlocked by " + by, 255)); } + public void unlock(String username, String by, Long companyId) { + String name = username == null ? "" : username.trim(); + if (name.isEmpty()) throw new IllegalArgumentException("username is required"); + User u = companyId == null ? null : users.findByUsername(name); + if (companyId != null && (u == null || !companyId.equals(u.getCompanyId()))) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"); + } + unlock(name, by); + } + public Map audit(String username, String event, LocalDate from, LocalDate to, Integer page, Integer size) { + return audit(username, event, from, to, page, size, null); + } + + /** companyId null means every row, including those without a company. */ + public Map audit(String username, String event, LocalDate from, LocalDate to, Integer page, Integer size, Long companyId) { int p = page == null || page < 0 ? 0 : page; int s = size == null || size < 1 ? 20 : Math.min(size, 100); String name = username == null ? "" : username.trim(); // ponytail: % and _ in the username filter are not escaped (admin-only filter); escape in the query if it matters - Page r = audits.search(name.isEmpty() ? null : "%" + name + "%", - event == null || event.isBlank() ? null : event, - from == null ? null : from.atStartOfDay(), - to == null ? null : to.plusDays(1).atStartOfDay(), - PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "datetime", "id"))); + String pattern = name.isEmpty() ? null : "%" + name + "%"; + String ev = event == null || event.isBlank() ? null : event; + LocalDateTime f = from == null ? null : from.atStartOfDay(); + LocalDateTime t = to == null ? null : to.plusDays(1).atStartOfDay(); + PageRequest pr = PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "datetime", "id")); + Page r = companyId == null ? audits.search(pattern, ev, f, t, pr) + : audits.searchInCompany(pattern, ev, f, t, companyId, pr); return Map.of("content", r.getContent(), "totalElements", r.getTotalElements(), "number", p, "size", s); } diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/service/UserService.java b/solvway-services-system/src/main/java/com/solvway/services/system/service/UserService.java index 5b103b7..56166f2 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/service/UserService.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/service/UserService.java @@ -52,6 +52,16 @@ public class UserService { return userRepository.findByEmailAndIdNot(email, id); } + public User findByEmailAndCompanyId(String email, Long companyId) { + return companyId == null ? userRepository.findByEmailAndCompanyIdIsNullAndType(email, UserType.A) + : userRepository.findByEmailAndCompanyIdAndType(email, companyId, UserType.A); + } + + public User findByEmailAndCompanyIdAndIdNot(String email, Long companyId, Long id) { + return companyId == null ? userRepository.findByEmailAndCompanyIdIsNullAndTypeAndIdNot(email, UserType.A, id) + : userRepository.findByEmailAndCompanyIdAndTypeAndIdNot(email, companyId, UserType.A, id); + } + public User findByUsernameAndIdNot(String username, Long id){ return userRepository.findByUsernameAndIdNot(username, id); } diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/CompanyControllerTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/CompanyControllerTest.java new file mode 100644 index 0000000..531020c --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/CompanyControllerTest.java @@ -0,0 +1,103 @@ +package com.solvway.services.system.controller; + +import com.solvway.services.system.model.Company; +import com.solvway.services.system.service.CompanyService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class CompanyControllerTest { + + @Mock private CompanyService service; + @InjectMocks private CompanyController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + private static Company company(Long id, String name, String code) { + Company c = new Company(); + c.setId(id); + c.setName(name); + c.setCode(code); + c.setStatus("A"); + return c; + } + + @Test + void findAllReturnsCompanies() throws Exception { + when(service.findAll()).thenReturn(List.of(company(2L, "CV", "cv"), company(1L, "INS", "ins"))); + + mvc.perform(get("/company/findAll")).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].code").value("cv")).andExpect(jsonPath("$[1].status").value("A")); + } + + @Test + void findByIdAndCode() throws Exception { + when(service.findById(1L)).thenReturn(company(1L, "INS", "ins")); + when(service.findByCode("INS")).thenReturn(company(1L, "INS", "ins")); + + mvc.perform(get("/company/findById/1")).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("INS")); + mvc.perform(get("/company/findByCode/INS")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1)); + } + + @Test + void saveReturnsSavedCompany() throws Exception { + when(service.save(any(Company.class))).thenReturn(company(3L, "New", "new")); + + mvc.perform(post("/company/save").contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"New\",\"code\":\"NEW\",\"status\":\"A\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(3)); + } + + @Test + void invalidCodeIs400WithMessage() throws Exception { + when(service.save(any(Company.class))).thenThrow(new IllegalArgumentException("Code must be 2 to 20 characters")); + + mvc.perform(post("/company/save").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"X\",\"code\":\"a\"}")) + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("Code must be 2 to 20 characters")); + } + + @Test + void duplicateCodeIs409() throws Exception { + when(service.save(any(Company.class))).thenThrow(new ResponseStatusException(HttpStatus.CONFLICT, "Code is already taken")); + + mvc.perform(post("/company/save").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"X\",\"code\":\"ins\"}")) + .andExpect(status().isConflict()); + } + + @Test + void renameCodePostsToService() throws Exception { + when(service.renameCode(2L, "cvx")).thenReturn(company(2L, "CV", "cvx")); + + mvc.perform(post("/company/2/code").contentType(MediaType.APPLICATION_JSON).content("{\"code\":\"cvx\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.code").value("cvx")); + verify(service).renameCode(2L, "cvx"); + } + + @Test + void missingBodyIs400() throws Exception { + mvc.perform(post("/company/save").contentType(MediaType.APPLICATION_JSON).content("")).andExpect(status().isBadRequest()); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/LoginSecurityControllerCompanyTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/LoginSecurityControllerCompanyTest.java new file mode 100644 index 0000000..acf06e5 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/LoginSecurityControllerCompanyTest.java @@ -0,0 +1,75 @@ +package com.solvway.services.system.controller; + +import com.solvway.services.system.service.LoginSecurityService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class LoginSecurityControllerCompanyTest { + + @Mock private LoginSecurityService service; + @InjectMocks private LoginSecurityController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void auditPassesCompanyId() throws Exception { + when(service.audit(any(), any(), any(), any(), any(), any(), any())).thenReturn(Map.of()); + + mvc.perform(post("/loginSecurity/audit").contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"bo\",\"from\":\"2025-06-01\",\"page\":1,\"size\":50,\"companyId\":2}")) + .andExpect(status().isOk()); + + verify(service).audit("bo", null, LocalDate.of(2025, 6, 1), null, 1, 50, 2L); + } + + @Test + void lockedPassesCompanyIdQueryParam() throws Exception { + when(service.lockedUsers(2L)).thenReturn(List.of()); + + mvc.perform(get("/loginSecurity/locked").param("companyId", "2")).andExpect(status().isOk()); + + verify(service).lockedUsers(2L); + } + + @Test + void unlockPassesCompanyId() throws Exception { + mvc.perform(post("/loginSecurity/unlock").contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"a@cv\",\"by\":\"boss\",\"companyId\":2}")).andExpect(status().isOk()); + + verify(service).unlock("a@cv", "boss", 2L); + } + + @Test + void unlockOfAnotherCompanysUserIs404() throws Exception { + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "user not found")).when(service).unlock("a@ins", "boss", 2L); + + mvc.perform(post("/loginSecurity/unlock").contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"a@ins\",\"by\":\"boss\",\"companyId\":2}")).andExpect(status().isNotFound()); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerCompanyGuardTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerCompanyGuardTest.java new file mode 100644 index 0000000..f9fa1a5 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerCompanyGuardTest.java @@ -0,0 +1,139 @@ +package com.solvway.services.system.controller; + +import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.model.Role; +import com.solvway.services.system.model.User; +import com.solvway.services.system.service.UserService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.web.server.ResponseStatusException; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class UserControllerCompanyGuardTest { + + @Mock private UserService userService; + @InjectMocks private UserController controller; + + private static User user(UserType type, Long companyId, Long... roleIds) { + User u = new User(); + u.setType(type); + u.setCompanyId(companyId); + List roles = new ArrayList<>(); + for (Long id : roleIds) { + Role r = new Role(); + r.setId(id); + roles.add(r); + } + u.setRoles(roles); + return u; + } + + private void refused(User u, String message) { + assertThatThrownBy(() -> controller.save(u)).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode().value()).isEqualTo(400); + assertThat(e.getReason()).contains(message); + }); + verify(userService, never()).save(any()); + } + + @Test + void adminWithCompanyCannotHoldSuperAdminRole() { + refused(user(UserType.A, 2L, 1L, 5L), "super admin"); + } + + @Test + void companylessAdminMustHoldSuperAdminRole() { + refused(user(UserType.A, null, 5L), "company"); + } + + @Test + void companylessAdminWithRoleOneIsSaved() { + when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); + + assertThat(controller.save(user(UserType.A, null, 1L)).getCompanyId()).isNull(); + } + + @Test + void adminWithCompanyAndOtherRoleIsSaved() { + when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); + + assertThat(controller.save(user(UserType.A, 2L, 5L)).getCompanyId()).isEqualTo(2L); + } + + @Test + void membersAreUnaffected() { + when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); + + assertThat(controller.save(user(UserType.M, null)).getType()).isEqualTo(UserType.M); + assertThat(controller.save(user(UserType.M, 2L, 1L)).getCompanyId()).isEqualTo(2L); + } + + private void stored(Long id, UserType type, Long companyId, Long... roleIds) { + User s = user(type, companyId, roleIds); + s.setId(id); + when(userService.findById(id)).thenReturn(java.util.Optional.of(s)); + } + + private static User edit(Long id, UserType type, Long companyId, Long... roleIds) { + User u = user(type, companyId, roleIds); + u.setId(id); + return u; + } + + @Test + void editOmittingCompanyKeepsStoredCompanyAndRefusesSuperAdminRole() { + stored(7L, UserType.A, 2L, 5L); + refused(edit(7L, null, null, 1L), "super admin"); + } + + @Test + void editOmittingCompanyOfStoredCompanyAdminWithOtherRoleIsSaved() { + stored(7L, UserType.A, 2L, 5L); + when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); + + assertThat(controller.save(edit(7L, null, null, 5L))).isNotNull(); + verify(userService).save(any()); + } + + @Test + void editOmittingTypeOfStoredAdminStillAppliesGuard() { + stored(7L, UserType.A, null, 1L); + refused(edit(7L, null, null, 5L), "company"); + } + + @Test + void editOmittingRolesKeepsStoredRoles() { + stored(7L, UserType.A, null, 1L); + when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); + User u = edit(7L, UserType.A, null); + u.setRoles(null); + + assertThat(controller.save(u)).isNotNull(); + } + + @Test + void emailFindersPassTheCompany() { + User other = new User(); + when(userService.findByEmailAndCompanyId("a@x.com", 2L)).thenReturn(other); + when(userService.findByEmailAndCompanyIdAndIdNot("a@x.com", null, 9L)).thenReturn(other); + + assertThat(controller.findByEmailAndCompanyId("a@x.com", 2L)).isSameAs(other); + assertThat(controller.findByEmailAndCompanyIdAndIdNot("a@x.com", 9L, null)).isSameAs(other); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/model/UserCompanyMappingTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/model/UserCompanyMappingTest.java new file mode 100644 index 0000000..6ef50ba --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/model/UserCompanyMappingTest.java @@ -0,0 +1,20 @@ +package com.solvway.services.system.model; + +import org.hibernate.annotations.Formula; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class UserCompanyMappingTest { + + @Test + void companyCodeAndStatusAreReadOnlyFormulasOverTheCompanyTable() throws Exception { + for (String field : new String[]{"companyCode", "companyStatus"}) { + Formula f = User.class.getDeclaredField(field).getAnnotation(Formula.class); + assertThat(f).as(field).isNotNull(); + assertThat(f.value()).contains("from company c where c.id = company_id"); + } + assertThat(User.class.getDeclaredField("companyCode").getAnnotation(Formula.class).value()).contains("c.code"); + assertThat(User.class.getDeclaredField("companyStatus").getAnnotation(Formula.class).value()).contains("c.status"); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/repo/UserRepositoryImplCompanyTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/repo/UserRepositoryImplCompanyTest.java new file mode 100644 index 0000000..9b9dd80 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/repo/UserRepositoryImplCompanyTest.java @@ -0,0 +1,81 @@ +package com.solvway.services.system.repo; + +import com.solvway.services.system.model.User; +import com.solvway.services.system.util.paging.PageableRest; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Root; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; + +import java.util.HashMap; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class UserRepositoryImplCompanyTest { + + private final EntityManager em = mock(EntityManager.class); + private final CriteriaBuilder cb = mock(CriteriaBuilder.class); + private final Path companyPath = mock(Path.class); + private UserRepositoryImpl repo; + + @BeforeEach + void setUp() { + CriteriaQuery cq = mock(CriteriaQuery.class, Answers.RETURNS_SELF); + CriteriaQuery count = mock(CriteriaQuery.class, Answers.RETURNS_SELF); + Root root = mock(Root.class); + Root rootCount = mock(Root.class); + TypedQuery q = mock(TypedQuery.class, Answers.RETURNS_SELF); + TypedQuery qc = mock(TypedQuery.class); + when(qc.getSingleResult()).thenReturn(0L); + when(em.getCriteriaBuilder()).thenReturn(cb); + when(cb.createQuery(User.class)).thenReturn(cq); + when(cb.createQuery(Long.class)).thenReturn(count); + when(cq.from(User.class)).thenReturn(root); + when(count.from(User.class)).thenReturn(rootCount); + when(root.get("companyId")).thenReturn(companyPath); + when(rootCount.get("companyId")).thenReturn(companyPath); + when(em.createQuery(cq)).thenReturn(q); + when(em.createQuery(count)).thenReturn(qc); + repo = new UserRepositoryImpl(); + repo.em = em; + } + + private static PageableRest page() { + PageableRest p = new PageableRest(); + p.setNumber(0); + p.setSize(10); + PageableRest.SortRest sort = new PageableRest.SortRest(); + sort.setDirection("ASC"); + sort.setProperty("name"); + p.setSorts(new java.util.ArrayList<>(java.util.List.of(sort))); + return p; + } + + @Test + void companyIdFiltersListAndCount() { + HashMap property = new HashMap<>(); + property.put("companyId", "2"); + + repo.findByPropertyAndPageable(property, page()); + + verify(cb, times(2)).equal(companyPath, 2L); // data query and count query + } + + @Test + void withoutCompanyIdNothingIsFiltered() { + repo.findByPropertyAndPageable(new HashMap<>(), page()); + + verify(cb, never()).equal(any(), any(Object.class)); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/CompanyServiceTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/CompanyServiceTest.java new file mode 100644 index 0000000..173e8be --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/CompanyServiceTest.java @@ -0,0 +1,207 @@ +package com.solvway.services.system.service; + +import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.model.Company; +import com.solvway.services.system.model.User; +import com.solvway.services.system.repo.CompanyRepository; +import com.solvway.services.system.repo.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class CompanyServiceTest { + + @Mock private CompanyRepository companies; + @Mock private UserRepository users; + private CompanyService service; + + @BeforeEach + void setUp() { + service = new CompanyService(companies, users); + when(companies.save(any(Company.class))).thenAnswer(i -> i.getArgument(0)); + } + + private static Company company(Long id, String name, String code, String status) { + Company c = new Company(); + c.setId(id); + c.setName(name); + c.setCode(code); + c.setStatus(status); + return c; + } + + private static User admin(Long id, String username) { + User u = new User(); + u.setId(id); + u.setUsername(username); + u.setType(UserType.A); + return u; + } + + @Test + void listsAllOrderedByName() { + List all = List.of(company(2L, "CV", "cv", "A"), company(1L, "INS", "ins", "A")); + when(companies.findAllByOrderByNameAsc()).thenReturn(all); + + assertThat(service.findAll()).isSameAs(all); + } + + @Test + void createLowercasesCodeAndDefaultsToActive() { + Company saved = service.save(company(null, " CV ", " CV-2 ", null)); + + assertThat(saved.getName()).isEqualTo("CV"); + assertThat(saved.getCode()).isEqualTo("cv-2"); + assertThat(saved.getStatus()).isEqualTo("A"); + } + + @Test + void duplicateCodeIgnoringCaseIsRefused() { + when(companies.findByCodeIgnoreCase("ins")).thenReturn(Optional.of(company(1L, "INS", "ins", "A"))); + + assertThatThrownBy(() -> service.save(company(null, "Other", "INS", "A"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(409)); + verify(companies, never()).save(any()); + } + + @ParameterizedTest + @ValueSource(strings = {"", "a", "UPPER_case", "has space", "under_score", "abcdefghijklmnopqrstu"}) + void badCodeFormatIsRefused(String code) { + assertThatThrownBy(() -> service.save(company(null, "X", code, "A"))).isInstanceOf(IllegalArgumentException.class); + verify(companies, never()).save(any()); + } + + @Test + void nameIsRequiredAndStatusMustBeAOrI() { + assertThatThrownBy(() -> service.save(company(null, " ", "ok", "A"))).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> service.save(company(null, "X", "ok", "Z"))).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void editChangesNameAndStatusButNotCode() { + Company existing = company(2L, "CV", "cv", "A"); + when(companies.findById(2L)).thenReturn(Optional.of(existing)); + + Company saved = service.save(company(2L, "CV Ltd", "other", "I")); + + assertThat(saved.getName()).isEqualTo("CV Ltd"); + assertThat(saved.getStatus()).isEqualTo("I"); + assertThat(saved.getCode()).isEqualTo("cv"); + } + + @Test + void editOfUnknownCompanyIs404() { + when(companies.findById(9L)).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.save(company(9L, "X", "xx", "A"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404)); + } + + @Test + void renameCodeRewritesOnlyThatCompanysAdminUsernames() throws Exception { + Company cv = company(2L, "CV", "cv", "A"); + when(companies.findById(2L)).thenReturn(Optional.of(cv)); + User a = admin(10L, "sales@cv"); + User b = admin(11L, "odd@name@cv"); // last '@' splits local from code + when(users.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(a, b)); + + Company renamed = service.renameCode(2L, "CVX"); + + assertThat(renamed.getCode()).isEqualTo("cvx"); + assertThat(a.getUsername()).isEqualTo("sales@cvx"); + assertThat(b.getUsername()).isEqualTo("odd@name@cvx"); + verify(users).findByCompanyIdAndType(2L, UserType.A); // only that company, only admins + verify(users).saveAll(List.of(a, b)); + // one transaction: company update and username rewrite share one @Transactional method + assertThat(CompanyService.class.getMethod("renameCode", Long.class, String.class) + .isAnnotationPresent(Transactional.class)).isTrue(); + } + + @Test + void renameToTakenCodeIsRefusedAndRewritesNothing() { + when(companies.findById(2L)).thenReturn(Optional.of(company(2L, "CV", "cv", "A"))); + when(companies.findByCodeIgnoreCase("ins")).thenReturn(Optional.of(company(1L, "INS", "ins", "A"))); + + assertThatThrownBy(() -> service.renameCode(2L, "INS")).isInstanceOf(ResponseStatusException.class); + verify(users, never()).saveAll(any()); + } + + @Test + void createRaceOnUniqueCodeIs409() { + when(companies.save(any(Company.class))).thenThrow(new DataIntegrityViolationException("uk_company_code")); + + assertThatThrownBy(() -> service.save(company(null, "New", "new", "A"))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode().value()).isEqualTo(409); + assertThat(e.getReason()).isEqualTo("Code is already taken"); + }); + } + + @Test + void renameRaceOnUniqueCodeIs409() { + when(companies.findById(2L)).thenReturn(Optional.of(company(2L, "CV", "cv", "A"))); + doThrow(new DataIntegrityViolationException("uk_company_code")).when(companies).flush(); + + assertThatThrownBy(() -> service.renameCode(2L, "cvx")) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(409)); + verify(users, never()).saveAll(any()); + } + + @Test + void renameThatOverflowsUsernameColumnIsRefusedBeforeAnyWrite() { + when(companies.findById(2L)).thenReturn(Optional.of(company(2L, "CV", "cv", "A"))); + User longName = admin(10L, "x".repeat(252) + "@cv"); // 255 now, 256 after rename to cvx + when(users.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(longName)); + + assertThatThrownBy(() -> service.renameCode(2L, "cvx")).isInstanceOf(IllegalArgumentException.class); + assertThat(longName.getUsername()).endsWith("@cv"); + verify(companies, never()).save(any()); + verify(users, never()).saveAll(any()); + } + + @Test + void renameToBadCodeIsRefused() { + assertThatThrownBy(() -> service.renameCode(2L, "Bad Code")).isInstanceOf(IllegalArgumentException.class); + verify(users, never()).saveAll(any()); + } + + @Test + void renameToOwnCodeIgnoringCaseIsAllowed() { + Company cv = company(2L, "CV", "cv", "A"); + when(companies.findById(2L)).thenReturn(Optional.of(cv)); + when(companies.findByCodeIgnoreCase("cv")).thenReturn(Optional.of(cv)); + when(users.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of()); + + assertThat(service.renameCode(2L, "CV").getCode()).isEqualTo("cv"); + } + + @Test + void findByCodeIgnoresCase() { + Company ins = company(1L, "INS", "ins", "A"); + when(companies.findByCodeIgnoreCase("INS")).thenReturn(Optional.of(ins)); + + assertThat(service.findByCode("INS")).isSameAs(ins); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/LoginSecurityServiceCompanyTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/LoginSecurityServiceCompanyTest.java new file mode 100644 index 0000000..1f7e896 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/LoginSecurityServiceCompanyTest.java @@ -0,0 +1,169 @@ +package com.solvway.services.system.service; + +import com.solvway.services.system.model.LoginAudit; +import com.solvway.services.system.model.PasswordRuleProperty; +import com.solvway.services.system.model.User; +import com.solvway.services.system.repo.LoginAuditRepository; +import com.solvway.services.system.repo.PasswordRuleRepository; +import com.solvway.services.system.repo.UserRepository; +import com.solvway.services.system.service.LoginSecurityService.Locked; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class LoginSecurityServiceCompanyTest { + + private static final LocalDateTime NOW = LocalDateTime.of(2025, 6, 15, 12, 0); + + @Mock private LoginAuditRepository audits; + @Mock private UserRepository users; + @Mock private PasswordRuleRepository properties; + private LoginSecurityService service; + + @BeforeEach + void setUp() { + service = new LoginSecurityService(audits, users, properties); + service.clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC); + } + + private static PasswordRuleProperty prop(String param, String type, String status, String value) { + PasswordRuleProperty p = new PasswordRuleProperty(); + p.setParam(param); + p.setType(type); + p.setStatus(status); + p.setValue(value); + return p; + } + + private void lockoutOn() { // 3 failures in 10 minutes + when(properties.findByType("ADMIN_LOGIN_BLOCK")).thenReturn(List.of( + prop("ADMIN_LOGIN_BLOCK_PERIOD", "ADMIN_LOGIN_BLOCK", "Y", "10"), + prop("ADMIN_LOGIN_MAX_ATTEMPT", "ADMIN_LOGIN_BLOCK", "Y", "3"))); + when(properties.findByType("ADMIN_LOGIN_BLOCK_TIME_UNIT")).thenReturn(List.of( + prop("ADMIN_LOGIN_BLOCK_TIME_UNIT", "ADMIN_LOGIN_BLOCK_TIME_UNIT", "Y", "M"))); + } + + private static LoginAudit fail(LocalDateTime at) { + LoginAudit a = new LoginAudit(); + a.setEvent("LOGIN_FAIL"); + a.setDatetime(at); + return a; + } + + private void threeFailures(String username) { + when(audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(eq(username), anyList())).thenReturn(Optional.empty()); + when(audits.findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(eq(username), eq("LOGIN_FAIL"), any())) + .thenReturn(List.of(fail(NOW.minusMinutes(3)), fail(NOW.minusMinutes(2)), fail(NOW.minusMinutes(1)))); + } + + @Test + void lockedUsersOfACompanyUseOnlyThatCompanysFailures() { + lockoutOn(); + threeFailures("a@cv"); + when(audits.findUsernamesWithFailuresAfterInCompany(NOW.minusMinutes(10), 2L)).thenReturn(List.of("a@cv")); + + assertThat(service.lockedUsers(2L)).extracting(Locked::username).containsExactly("a@cv"); + verify(audits, never()).findUsernamesWithFailuresAfter(any()); + } + + @Test + void lockedUsersWithoutCompanyIncludeEveryRowEvenNullCompany() { + lockoutOn(); + threeFailures("admin"); + when(audits.findUsernamesWithFailuresAfter(NOW.minusMinutes(10))).thenReturn(List.of("admin")); + + assertThat(service.lockedUsers(null)).extracting(Locked::username).containsExactly("admin"); + verify(audits, never()).findUsernamesWithFailuresAfterInCompany(any(), any()); + } + + @Test + void auditOfACompanyFiltersByCompanyId() { + when(audits.searchInCompany(any(), any(), any(), any(), eq(2L), any(Pageable.class))).thenReturn(new PageImpl<>(List.of(fail(NOW)))); + + assertThat(service.audit("bo", "LOGIN_FAIL", null, null, 0, 20, 2L)).containsEntry("totalElements", 1L); + verify(audits).searchInCompany(eq("%bo%"), eq("LOGIN_FAIL"), eq(null), eq(null), eq(2L), any(Pageable.class)); + verify(audits, never()).search(any(), any(), any(), any(), any()); + } + + @Test + void auditWithoutCompanyIsTheUnfilteredSearch() { + when(audits.search(any(), any(), any(), any(), any())).thenReturn(Page.empty()); + + service.audit(null, null, null, null, null, null, null); + + verify(audits).search(eq(null), eq(null), eq(null), eq(null), any(Pageable.class)); + verify(audits, never()).searchInCompany(any(), any(), any(), any(), any(), any()); + } + + @Test + void unlockOfAnotherCompanysUsernameIs404AndWritesNothing() { + User u = new User(); + u.setCompanyId(1L); + when(users.findByUsername("a@ins")).thenReturn(u); + + assertThatThrownBy(() -> service.unlock("a@ins", "boss", 2L)) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404)); + verify(audits, never()).save(any()); + } + + @Test + void unlockOfUnknownUsernameWithCompanyIs404() { + assertThatThrownBy(() -> service.unlock("ghost@cv", "boss", 2L)).isInstanceOf(ResponseStatusException.class); + verify(audits, never()).save(any()); + } + + @Test + void unlockOfOwnCompanysUsernameWritesResetRowWithThatCompany() { + User u = new User(); + u.setCompanyId(2L); + when(users.findByUsername("a@cv")).thenReturn(u); + + service.unlock(" a@cv ", "boss", 2L); + + ArgumentCaptor c = ArgumentCaptor.forClass(LoginAudit.class); + verify(audits).save(c.capture()); + assertThat(c.getValue().getUsername()).isEqualTo("a@cv"); + assertThat(c.getValue().getEvent()).isEqualTo("UNLOCK_RESET"); + assertThat(c.getValue().getCompanyId()).isEqualTo(2L); + } + + @Test + void auditRowsTakeTheCompanyOfTheUserFoundByTheFullLoginName() { + User u = new User(); + u.setCompanyId(2L); + when(users.findByUsername("a@cv")).thenReturn(u); + + service.record("a@cv", "LOGIN_FAIL", null, null, null); + + verify(users).findByUsername("a@cv"); + ArgumentCaptor c = ArgumentCaptor.forClass(LoginAudit.class); + verify(audits).save(c.capture()); + assertThat(c.getValue().getCompanyId()).isEqualTo(2L); + } +} diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/service/UserServiceCompanyTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/service/UserServiceCompanyTest.java new file mode 100644 index 0000000..9b3d27a --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/service/UserServiceCompanyTest.java @@ -0,0 +1,50 @@ +package com.solvway.services.system.service; + +import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.model.User; +import com.solvway.services.system.repo.UserRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UserServiceCompanyTest { + + @Mock private UserRepository repo; + @InjectMocks private UserService service; + + @Test + void emailIsCheckedWithinTheGivenCompany() { + User other = new User(); + when(repo.findByEmailAndCompanyIdAndType("a@x.com", 2L, UserType.A)).thenReturn(other); + + assertThat(service.findByEmailAndCompanyId("a@x.com", 2L)).isSameAs(other); + verify(repo).findByEmailAndCompanyIdAndType("a@x.com", 2L, UserType.A); + verifyNoMoreInteractions(repo); + } + + @Test + void nullCompanyComparesAmongCompanylessUsers() { + User other = new User(); + when(repo.findByEmailAndCompanyIdIsNullAndType("a@x.com", UserType.A)).thenReturn(other); + + assertThat(service.findByEmailAndCompanyId("a@x.com", null)).isSameAs(other); + } + + @Test + void emailAndIdNotWithinCompany() { + User other = new User(); + when(repo.findByEmailAndCompanyIdAndTypeAndIdNot("a@x.com", 2L, UserType.A, 9L)).thenReturn(other); + when(repo.findByEmailAndCompanyIdIsNullAndTypeAndIdNot("a@x.com", UserType.A, 9L)).thenReturn(null); + + assertThat(service.findByEmailAndCompanyIdAndIdNot("a@x.com", 2L, 9L)).isSameAs(other); + assertThat(service.findByEmailAndCompanyIdAndIdNot("a@x.com", null, 9L)).isNull(); + } +} -- 2.54.1 From a6996841ac528ee6797b3abdeac304bb14e4bbe2 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 19:20:16 +0800 Subject: [PATCH 05/24] feat: company on events, all-company lead lists, shared interests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../controller/EventLeadController.java | 5 + .../counter/controller/LeadController.java | 3 + .../counter/dto/EventLeadCaptureRequest.java | 2 +- .../services/counter/dto/EventLeadDetail.java | 3 +- .../counter/dto/EventLeadSearchRequest.java | 4 +- .../counter/dto/EventLeadUpdateRequest.java | 2 +- .../services/counter/dto/LeadDetail.java | 2 +- .../counter/dto/LeadMatchRequest.java | 2 +- .../counter/dto/LeadSearchRequest.java | 4 +- .../counter/dto/LeadUpdateRequest.java | 2 +- .../solvway/services/counter/model/Event.java | 2 + .../services/counter/model/Interest.java | 5 +- .../counter/repo/EventLeadRepository.java | 6 +- .../counter/repo/EventRepositoryImpl.java | 4 + .../counter/repo/InterestRepository.java | 6 +- .../services/counter/repo/LeadRepository.java | 12 +- .../counter/service/EventLeadService.java | 17 +- .../counter/service/EventService.java | 9 + .../counter/service/InterestService.java | 17 +- .../services/counter/service/LeadService.java | 16 +- .../repo/EventRepositoryImplCompanyTest.java | 71 +++++++ .../service/EventServiceCompanyTest.java | 82 ++++++++ .../counter/service/InterestServiceTest.java | 97 ++++----- .../counter/service/LeadCompanyScopeTest.java | 185 ++++++++++++++++++ 24 files changed, 472 insertions(+), 86 deletions(-) create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/repo/EventRepositoryImplCompanyTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventServiceCompanyTest.java create mode 100644 solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadCompanyScopeTest.java diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java index 9da6d13..00aee22 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/EventLeadController.java @@ -40,6 +40,11 @@ public class EventLeadController { return eventLeadService.findByUuid(companyId, eventLeadUuid); } + @GetMapping("/eventLead/findByUuid/{eventLeadUuid}") + public EventLeadDetail findByUuid(@PathVariable("eventLeadUuid") long eventLeadUuid) { + return eventLeadService.findByUuid(null, eventLeadUuid); + } + @PostMapping("/eventLead/findByEvent") public Page findByEvent(@RequestBody EventLeadSearchRequest req) { return eventLeadService.search(req); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java index 316ca7d..21efd54 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/controller/LeadController.java @@ -20,6 +20,9 @@ public class LeadController { return leadService.detail(companyId, leadUuid); } + @GetMapping("/lead/detail/{leadUuid}") + public LeadDetail detail(@PathVariable("leadUuid") long leadUuid) { return leadService.detail(null, leadUuid); } + @PostMapping("/lead/update") public LeadDetail update(@RequestBody LeadUpdateRequest req) { return leadService.update(req); } } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java index efd6eff..6ed34b4 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadCaptureRequest.java @@ -5,7 +5,7 @@ import java.util.List; /** Capture a lead at an event. leadUuid null means a new person. Values arrive validated and normalised by mobile-api. */ public record EventLeadCaptureRequest( - long companyId, + Long companyId, long eventUuid, Long leadUuid, String name, diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java index 40c6cda..97ee41d 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadDetail.java @@ -21,5 +21,6 @@ public record EventLeadDetail( LocalDate nextFollowUpDate, String notes, LocalDateTime capturedAt, - List interestIds + List interestIds, + Long companyId ) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java index 17ee57e..58028ae 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadSearchRequest.java @@ -1,5 +1,5 @@ package com.solvway.services.counter.dto; -/** One event's leads, filtered; null or blank filters are ignored. page is 0-based. */ -public record EventLeadSearchRequest(long companyId, long eventUuid, Long salespersonUserId, String temperature, +/** One event's leads, filtered; null or blank filters are ignored. page is 0-based. companyId null means all companies. */ +public record EventLeadSearchRequest(Long companyId, long eventUuid, Long salespersonUserId, String temperature, String status, Long interestId, String leadType, int page, int size) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java index 2bda50a..0e46885 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/EventLeadUpdateRequest.java @@ -4,6 +4,6 @@ import java.time.LocalDate; import java.util.List; /** Replaces an event lead's working fields and its interest set. Values arrive validated by mobile-api. */ -public record EventLeadUpdateRequest(long companyId, long eventLeadUuid, Long salespersonUserId, String temperature, +public record EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature, String status, List interestIds, LocalDate nextFollowUpDate, String notes, String doneBy) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadDetail.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadDetail.java index e9843b0..70c7f57 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadDetail.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadDetail.java @@ -5,4 +5,4 @@ import java.util.List; public record LeadDetail(long leadUuid, String name, String mobileE164, String email, String companyName, String jobTitle, String notes, LocalDateTime createdAt, LocalDateTime updatedAt, - String updatedBy, List history, List sharedContacts) {} + String updatedBy, List history, List sharedContacts, Long companyId) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java index 5938529..02b85c7 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadMatchRequest.java @@ -1,4 +1,4 @@ package com.solvway.services.counter.dto; /** Find the company's leads whose mobile or email matches; blank values are ignored. */ -public record LeadMatchRequest(long companyId, long eventUuid, String mobileE164, String email) {} +public record LeadMatchRequest(Long companyId, long eventUuid, String mobileE164, String email) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSearchRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSearchRequest.java index a316658..09bd076 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSearchRequest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadSearchRequest.java @@ -1,4 +1,4 @@ package com.solvway.services.counter.dto; -/** q is free text (name or email); mobileDigits is digits only. Both optional. */ -public record LeadSearchRequest(long companyId, String q, String mobileDigits, int page, int size) {} +/** q is free text (name or email); mobileDigits is digits only. Both optional. companyId null means all companies. */ +public record LeadSearchRequest(Long companyId, String q, String mobileDigits, int page, int size) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadUpdateRequest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadUpdateRequest.java index f5ccb07..1dcca18 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadUpdateRequest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/dto/LeadUpdateRequest.java @@ -1,4 +1,4 @@ package com.solvway.services.counter.dto; -public record LeadUpdateRequest(long companyId, long leadUuid, String name, String mobileE164, String email, +public record LeadUpdateRequest(Long companyId, long leadUuid, String name, String mobileE164, String email, String companyName, String jobTitle, String notes, String doneBy) {} diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java index f94120e..58ab73f 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Event.java @@ -22,6 +22,8 @@ public class Event implements Serializable { private String location; private LocalDateTime dateStart; private LocalDateTime dateEnd; + @Column(name = "company_id", updatable = false) + private Long companyId; private String uploadFloorPlan; private String uploadStageActivities; private String uploadLuckyDraw; diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java index caaab7b..3701179 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/model/Interest.java @@ -7,13 +7,14 @@ import lombok.Setter; @Getter @Setter @Entity -@Table(name = "interest", uniqueConstraints = @UniqueConstraint(columnNames = {"company_id", "name"})) +@Table(name = "interest", uniqueConstraints = @UniqueConstraint(columnNames = {"name"})) public class Interest { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - private long companyId; + /** Unused: interests are one shared list. */ + private Long companyId; private String name; diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java index 0c93dbc..8e2276b 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventLeadRepository.java @@ -21,8 +21,10 @@ public interface EventLeadRepository extends JpaRepository { Optional findByUuidAndCompanyId(long uuid, long companyId); + Optional findByUuid(long uuid); + String SEARCH_WHERE = " WHERE l.uuid = e.leadUuid AND l.companyId = e.companyId" - + " AND e.companyId = :companyId AND e.eventUuid = :eventUuid" + + " AND (:companyId IS NULL OR e.companyId = :companyId) AND e.eventUuid = :eventUuid" + " AND (:salespersonUserId IS NULL OR e.salespersonUserId = :salespersonUserId)" + " AND (:temperature IS NULL OR e.temperature = :temperature)" + " AND (:status IS NULL OR e.status = :status)" @@ -33,7 +35,7 @@ public interface EventLeadRepository extends JpaRepository { /** Rows are [EventLead, Lead]; the caller supplies the sort through the pageable. */ @Query(value = "SELECT e, l FROM EventLead e, Lead l" + SEARCH_WHERE, countQuery = "SELECT COUNT(e) FROM EventLead e, Lead l" + SEARCH_WHERE) - Page search(@Param("companyId") long companyId, @Param("eventUuid") long eventUuid, + Page search(@Param("companyId") Long companyId, @Param("eventUuid") long eventUuid, @Param("salespersonUserId") Long salespersonUserId, @Param("temperature") String temperature, @Param("status") String status, @Param("interestId") Long interestId, @Param("leadType") String leadType, Pageable pageable); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepositoryImpl.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepositoryImpl.java index 7832e68..88ec304 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepositoryImpl.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/EventRepositoryImpl.java @@ -53,6 +53,10 @@ public class EventRepositoryImpl implements JpaRepositoryCustom{ case "name", "location" -> { predicates.add(cb.like(root.get(k), "%"+value+"%")); predicatesCount.add(cb.like(rootCount.get(k), "%"+value+"%")); + } + case "companyId" -> { + predicates.add(cb.equal(root.get("companyId"), Long.valueOf(value))); + predicatesCount.add(cb.equal(rootCount.get("companyId"), Long.valueOf(value))); } case "enabled" -> { predicates.add(cb.equal(root.get(k), GeneralEnum.FlagYesNo.valueOf(value))); diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java index 6801136..5f17eb1 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/InterestRepository.java @@ -9,9 +9,9 @@ import java.util.List; @Repository public interface InterestRepository extends JpaRepository { - List findByCompanyIdOrderBySortOrderAscNameAsc(long companyId); + List findAllByOrderBySortOrderAscNameAsc(); - boolean existsByCompanyIdAndNameIgnoreCase(long companyId, String name); + boolean existsByNameIgnoreCase(String name); - List findByIdInAndCompanyId(Collection ids, long companyId); + List findByIdIn(Collection ids); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java index a2ba928..3e12cf6 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/repo/LeadRepository.java @@ -21,6 +21,8 @@ public interface LeadRepository extends JpaRepository { Optional findByUuidAndCompanyId(long uuid, long companyId); + Optional findByUuid(long uuid); + interface SummaryRow { long getLeadUuid(); String getName(); @@ -36,16 +38,16 @@ public interface LeadRepository extends JpaRepository { } /** The search condition uses only `lead` columns, so the count skips the aggregate joins. */ - String SEARCH_WHERE = " WHERE l.company_id = :companyId AND ((:q IS NULL AND :digits IS NULL) OR LOWER(l.name) LIKE :q ESCAPE '\\\\'" + String SEARCH_WHERE = " WHERE (:companyId IS NULL OR l.company_id = :companyId) AND ((:q IS NULL AND :digits IS NULL) OR LOWER(l.name) LIKE :q ESCAPE '\\\\'" + " OR l.email_normalised LIKE :q ESCAPE '\\\\' OR (:digits IS NOT NULL AND l.mobile_e164 LIKE :digits))"; String SEARCH_FROM = " FROM `lead` l" - + " LEFT JOIN (SELECT lead_uuid, COUNT(*) cnt FROM event_lead WHERE company_id = :companyId GROUP BY lead_uuid) c ON c.lead_uuid = l.uuid" + + " LEFT JOIN (SELECT lead_uuid, COUNT(*) cnt FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) GROUP BY lead_uuid) c ON c.lead_uuid = l.uuid" + " LEFT JOIN (SELECT lead_uuid, event_uuid, captured_at, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn" - + " FROM event_lead WHERE company_id = :companyId) last ON last.lead_uuid = l.uuid AND last.rn = 1" + + " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId)) last ON last.lead_uuid = l.uuid AND last.rn = 1" + " LEFT JOIN `event` ev ON ev.uuid = last.event_uuid" + " LEFT JOIN (SELECT lead_uuid, salesperson_user_id, ROW_NUMBER() OVER (PARTITION BY lead_uuid ORDER BY captured_at DESC, id DESC) rn" - + " FROM event_lead WHERE company_id = :companyId AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1" + + " FROM event_lead WHERE (:companyId IS NULL OR company_id = :companyId) AND salesperson_user_id IS NOT NULL) sp ON sp.lead_uuid = l.uuid AND sp.rn = 1" + SEARCH_WHERE; /** @@ -60,6 +62,6 @@ public interface LeadRepository extends JpaRepository { + " sp.salesperson_user_id AS latestSalespersonUserId" + SEARCH_FROM + " ORDER BY last.captured_at IS NULL, last.captured_at DESC, l.id DESC", countQuery = "SELECT COUNT(*) FROM `lead` l" + SEARCH_WHERE) - Page search(@Param("companyId") long companyId, @Param("q") String q, + Page search(@Param("companyId") Long companyId, @Param("q") String q, @Param("digits") String digits, Pageable pageable); } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java index 62f27fb..7dc15c1 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventLeadService.java @@ -47,6 +47,7 @@ public class EventLeadService { private final EventLeadInterestRepository eventLeadInterestRepository; public List findMatches(LeadMatchRequest req) { + requireCompany(req.companyId()); String mobile = blankToNull(req.mobileE164()); String email = blankToNull(req.email()); if (mobile == null && email == null) return List.of(); @@ -64,6 +65,7 @@ public class EventLeadService { @Transactional public EventLeadDetail capture(EventLeadCaptureRequest req) { + requireCompany(req.companyId()); Lead lead; String leadType; if (req.leadUuid() == null) { @@ -117,10 +119,12 @@ public class EventLeadService { return detail(eventLead, lead, interestIds); } - public EventLeadDetail findByUuid(long companyId, long eventLeadUuid) { - EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(eventLeadUuid, companyId) + /** A null company looks the event lead up across all companies; the detail reports the record's own company. */ + public EventLeadDetail findByUuid(Long companyId, long eventLeadUuid) { + EventLead eventLead = (companyId == null ? eventLeadRepository.findByUuid(eventLeadUuid) + : eventLeadRepository.findByUuidAndCompanyId(eventLeadUuid, companyId)) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); - Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), companyId) + Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), eventLead.getCompanyId()) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); List interestIds = eventLeadInterestRepository.findByIdEventLeadId(eventLead.getId()).stream() .map(r -> r.getId().getInterestId()).toList(); @@ -145,6 +149,7 @@ public class EventLeadService { @Transactional public EventLeadDetail update(EventLeadUpdateRequest req) { + requireCompany(req.companyId()); EventLead eventLead = eventLeadRepository.findByUuidAndCompanyId(req.eventLeadUuid(), req.companyId()) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); eventLead.setSalespersonUserId(req.salespersonUserId()); @@ -162,6 +167,10 @@ public class EventLeadService { return detail(eventLead, lead, interestIds); } + private static void requireCompany(Long companyId) { + if (companyId == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + } + private List saveInterests(long eventLeadId, long companyId, List requested) { List ids = requested == null ? List.of() : requested.stream().filter(Objects::nonNull).distinct().toList(); if (!ids.isEmpty()) { @@ -178,7 +187,7 @@ public class EventLeadService { private static EventLeadDetail detail(EventLead e, Lead l, List interestIds) { return new EventLeadDetail(e.getUuid(), e.getEventUuid(), l.getUuid(), l.getName(), l.getMobileE164(), l.getEmailNormalised(), l.getCompanyName(), l.getJobTitle(), e.getLeadType(), e.getSalespersonUserId(), - e.getTemperature(), e.getStatus(), e.getNextFollowUpDate(), e.getNotes(), e.getCapturedAt(), interestIds); + e.getTemperature(), e.getStatus(), e.getNextFollowUpDate(), e.getNotes(), e.getCapturedAt(), interestIds, e.getCompanyId()); } private static void fillBlank(String current, String offered, Consumer setter) { diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java index 4264125..b873dbf 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/EventService.java @@ -12,6 +12,8 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; import org.springframework.stereotype.Service; import java.time.LocalDateTime; @@ -36,6 +38,13 @@ public class EventService { } @Transactional public Event save(Event event) { + if (event.getId() == null) { + if (event.getCompanyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + } else { + // company is immutable: always carry the stored one so entity and cache match the DB + Optional stored = eventRepository.findById(event.getId()); + if (stored.isPresent()) event.setCompanyId(stored.get().getCompanyId()); + } event = eventRepository.save(event); updateEventCache(event); return event; diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java index 150be28..bcc74a5 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/InterestService.java @@ -17,7 +17,7 @@ public class InterestService { private final InterestRepository interestRepository; public List findByCompany(long companyId) { - return interestRepository.findByCompanyIdOrderBySortOrderAscNameAsc(companyId); + return interestRepository.findAllByOrderBySortOrderAscNameAsc(); } @Transactional @@ -36,21 +36,18 @@ public class InterestService { try { if (interest.getId() == null) { - // Create: check duplicate name for this company - if (interestRepository.existsByCompanyIdAndNameIgnoreCase(interest.getCompanyId(), trimmedName)) { + // Create: names are unique across the one shared list + interest.setCompanyId(null); + if (interestRepository.existsByNameIgnoreCase(trimmedName)) { throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME"); } return interestRepository.saveAndFlush(interest); } else { - // Update: verify the row belongs to this company Interest existing = interestRepository.findById(interest.getId()) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); - if (existing.getCompanyId() != interest.getCompanyId()) { - throw new ResponseStatusException(HttpStatus.NOT_FOUND); - } - // Check duplicate name within the same company, excluding this row + interest.setCompanyId(existing.getCompanyId()); if (!existing.getName().equalsIgnoreCase(trimmedName) - && interestRepository.existsByCompanyIdAndNameIgnoreCase(interest.getCompanyId(), trimmedName)) { + && interestRepository.existsByNameIgnoreCase(trimmedName)) { throw new ResponseStatusException(HttpStatus.CONFLICT, "DUPLICATE_NAME"); } return interestRepository.saveAndFlush(interest); @@ -64,6 +61,6 @@ public class InterestService { if (ids == null || ids.isEmpty()) { return List.of(); } - return interestRepository.findByIdInAndCompanyId(ids, companyId); + return interestRepository.findByIdIn(ids); } } diff --git a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java index a24e431..12387f9 100644 --- a/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java +++ b/solvway-services-counter/src/main/java/com/solvway/services/counter/service/LeadService.java @@ -44,12 +44,16 @@ public class LeadService { r.getLastCapturedAt(), r.getLatestSalespersonUserId())); } - public LeadDetail detail(long companyId, long leadUuid) { - return detail(find(companyId, leadUuid)); + /** A null company looks the lead up across all companies; the detail reports the lead's own company. */ + public LeadDetail detail(Long companyId, long leadUuid) { + return detail(companyId == null + ? leadRepository.findByUuid(leadUuid).orElseThrow(LeadService::notFound) + : find(companyId, leadUuid)); } @Transactional public LeadDetail update(LeadUpdateRequest req) { + if (req.companyId() == null) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); Lead lead = find(req.companyId(), req.leadUuid()); lead.setName(req.name()); lead.setMobileE164(req.mobileE164()); @@ -64,7 +68,11 @@ public class LeadService { private Lead find(long companyId, long leadUuid) { return leadRepository.findByUuidAndCompanyId(leadUuid, companyId) - .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND")); + .orElseThrow(LeadService::notFound); + } + + private static ResponseStatusException notFound() { + return new ResponseStatusException(HttpStatus.NOT_FOUND, "LEAD_NOT_FOUND"); } private LeadDetail detail(Lead l) { @@ -85,6 +93,6 @@ public class LeadService { l.getEmailNormalised() != null && Objects.equals(l.getEmailNormalised(), o.getEmailNormalised()))) .toList(); return new LeadDetail(l.getUuid(), l.getName(), l.getMobileE164(), l.getEmailNormalised(), l.getCompanyName(), - l.getJobTitle(), l.getNotes(), l.getCreatedAt(), l.getUpdatedAt(), l.getUpdatedBy(), history, shared); + l.getJobTitle(), l.getNotes(), l.getCreatedAt(), l.getUpdatedAt(), l.getUpdatedBy(), history, shared, l.getCompanyId()); } } diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/repo/EventRepositoryImplCompanyTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/repo/EventRepositoryImplCompanyTest.java new file mode 100644 index 0000000..ecb479a --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/repo/EventRepositoryImplCompanyTest.java @@ -0,0 +1,71 @@ +package com.solvway.services.counter.repo; + +import com.solvway.services.counter.util.paging.PageableRest; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Expression; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Answers; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Event list search: the optional companyId property filters both the page query and the count query. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class EventRepositoryImplCompanyTest { + + private CriteriaBuilder cb; + private EventRepositoryImpl repo; + + @BeforeEach + void setUp() { + EntityManager em = mock(EntityManager.class, Answers.RETURNS_DEEP_STUBS); + cb = em.getCriteriaBuilder(); + TypedQuery query = mock(TypedQuery.class, Answers.RETURNS_SELF); + when(query.getResultList()).thenReturn(List.of()); + when(query.getSingleResult()).thenReturn(0L); + when(em.createQuery(any(CriteriaQuery.class))).thenReturn((TypedQuery) query); + repo = new EventRepositoryImpl(); + repo.em = em; + } + + private void search(HashMap property) { + PageableRest page = new PageableRest(); + page.setNumber(0); + page.setSize(10); + PageableRest.SortRest sort = new PageableRest.SortRest(); + sort.setDirection("ASC"); + sort.setProperty("id"); + page.setSorts(new ArrayList<>(java.util.List.of(sort))); + repo.findByPropertyAndPageable(property, page); + } + + @Test + void companyIdFiltersPageAndCountQueries() { + HashMap p = new HashMap<>(); + p.put("companyId", "7"); + search(p); + verify(cb, times(2)).equal(any(Expression.class), eq(7L)); + } + + @Test + void blankOrMissingCompanyIdAddsNoFilter() { + HashMap p = new HashMap<>(); + p.put("companyId", ""); + search(p); + search(new HashMap<>()); + verify(cb, never()).equal(any(Expression.class), any(Object.class)); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventServiceCompanyTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventServiceCompanyTest.java new file mode 100644 index 0000000..830735b --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/EventServiceCompanyTest.java @@ -0,0 +1,82 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.model.Event; +import com.solvway.services.counter.repo.EventRepository; +import com.solvway.services.counter.util.redis.RedisUtil; +import jakarta.persistence.Column; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.web.server.ResponseStatusException; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** EventService: an event keeps the company it was created in. */ +@ExtendWith(MockitoExtension.class) +class EventServiceCompanyTest { + + @Mock private EventRepository eventRepository; + @Mock private RedisUtil redisUtil; + + private EventService service; + + @BeforeEach + void setUp() { + service = new EventService(eventRepository, redisUtil); + lenient().when(eventRepository.save(any(Event.class))).thenAnswer(i -> i.getArgument(0)); + } + + private static Event event(Long id, Long companyId) { + Event e = new Event(); + e.setId(id); + e.setCompanyId(companyId); + return e; + } + + @Test + void newEventIsSavedWithItsCompany() { + assertThat(service.save(event(null, 7L)).getCompanyId()).isEqualTo(7L); + } + + @Test + void editWithoutCompanyKeepsStoredCompany() { + when(eventRepository.findById(5L)).thenReturn(Optional.of(event(5L, 7L))); + assertThat(service.save(event(5L, null)).getCompanyId()).isEqualTo(7L); + } + + @Test + void newEventWithoutCompanyIsRefused() { + assertThatThrownBy(() -> service.save(event(null, null))) + .isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode().value()).isEqualTo(400); + assertThat(e.getReason()).isEqualTo("COMPANY_REQUIRED"); + }); + verify(eventRepository, never()).save(any(Event.class)); + } + + @Test + void editAlwaysUsesStoredCompany() { + when(eventRepository.findById(5L)).thenReturn(Optional.of(event(5L, 7L))); + assertThat(service.save(event(5L, 9L)).getCompanyId()).isEqualTo(7L); + } + + @Test + void companyColumnIsNotUpdatable() throws Exception { + // The column is non-updatable, so a company change can never reach the database. + assertThat(Event.class.getDeclaredField("companyId").getAnnotation(Column.class)) + .isNotNull() + .extracting(Column::updatable, Column::name) + .containsExactly(false, "company_id"); + } +} diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceTest.java index ed7b6d8..e0b77cc 100644 --- a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceTest.java +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/InterestServiceTest.java @@ -44,11 +44,11 @@ class InterestServiceTest { // --- Test 1: findByCompany orders by sortOrder asc, then name asc --- @Test - void findByCompanyOrdersBySortOrderThenName() { + void findAllOrdersBySortOrderThenName() { Interest b = makeInterest(2L, COMPANY_A, "banana", true, 5); Interest a = makeInterest(1L, COMPANY_A, "apple", true, 10); Interest c = makeInterest(3L, COMPANY_A, "apricot", true, 10); - when(repository.findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A)) + when(repository.findAllByOrderBySortOrderAscNameAsc()) .thenReturn(List.of(b, a, c)); List result = service.findByCompany(COMPANY_A); @@ -58,7 +58,7 @@ class InterestServiceTest { assertThat(result.get(0).getName()).isEqualTo("banana"); assertThat(result.get(1).getName()).isEqualTo("apple"); assertThat(result.get(2).getName()).isEqualTo("apricot"); - verify(repository).findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A); + verify(repository).findAllByOrderBySortOrderAscNameAsc(); } // --- Test 2: save creates a new row (id is null) --- @@ -69,7 +69,7 @@ class InterestServiceTest { input.setName(" tech "); input.setActive(true); input.setSortOrder(0); - when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false); + when(repository.existsByNameIgnoreCase("tech")).thenReturn(false); when(repository.saveAndFlush(any())).thenAnswer(inv -> { Interest saved = inv.getArgument(0); saved.setId(99L); @@ -95,7 +95,7 @@ class InterestServiceTest { input.setName(" new "); input.setActive(false); input.setSortOrder(5); - when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "new")).thenReturn(false); + when(repository.existsByNameIgnoreCase("new")).thenReturn(false); when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); Interest result = service.save(input); @@ -106,20 +106,23 @@ class InterestServiceTest { verify(repository).saveAndFlush(any()); } - // --- Test 4: save updates other company's row -> 404 --- + // --- Test 4: any company's user-saved row can be updated: the list is shared, the stored company is kept --- @Test - void saveUpdatesOtherCompanyRow() { + void saveUpdatesRowOfAnyCompany() { Interest existing = makeInterest(10L, COMPANY_B, "other", true, 1); when(repository.findById(10L)).thenReturn(Optional.of(existing)); + when(repository.existsByNameIgnoreCase("mine")).thenReturn(false); + when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); Interest input = new Interest(); input.setId(10L); input.setCompanyId(COMPANY_A); input.setName(" mine "); - assertThatThrownBy(() -> service.save(input)) - .isInstanceOf(ResponseStatusException.class) - .hasFieldOrPropertyWithValue("statusCode", HttpStatus.NOT_FOUND); + Interest result = service.save(input); + + assertThat(result.getName()).isEqualTo("mine"); + assertThat(result.getCompanyId()).isEqualTo(COMPANY_B); } // --- Test 5: save duplicate name ignoring case in same company -> 409 --- @@ -128,7 +131,7 @@ class InterestServiceTest { Interest input = new Interest(); input.setCompanyId(COMPANY_A); input.setName(" Tech "); - when(repository.existsByCompanyIdAndNameIgnoreCase(eq(COMPANY_A), any())).thenReturn(true); + when(repository.existsByNameIgnoreCase(any())).thenReturn(true); assertThatThrownBy(() -> service.save(input)) .isInstanceOf(ResponseStatusException.class) @@ -136,28 +139,32 @@ class InterestServiceTest { .hasMessageContaining("DUPLICATE_NAME"); } - // --- Test 6: same name in different company allowed --- + // --- Test 6: same name is refused whichever company asks --- @Test - void sameNameDifferentCompanyAllowed() { - Interest inputA = new Interest(); - inputA.setCompanyId(COMPANY_A); - inputA.setName("tech"); - when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false); - when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); - + void sameNameRefusedRegardlessOfCompany() { Interest inputB = new Interest(); inputB.setCompanyId(COMPANY_B); inputB.setName("tech"); - when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_B, "tech")).thenReturn(false); + when(repository.existsByNameIgnoreCase("tech")).thenReturn(true); + + assertThatThrownBy(() -> service.save(inputB)) + .isInstanceOf(ResponseStatusException.class) + .hasFieldOrPropertyWithValue("statusCode", HttpStatus.CONFLICT) + .hasMessageContaining("DUPLICATE_NAME"); + verify(repository).existsByNameIgnoreCase("tech"); + verify(repository, org.mockito.Mockito.never()).saveAndFlush(any()); + } + + // --- New: a new interest is saved with no company --- + @Test + void newInterestSavedWithNullCompany() { + Interest input = new Interest(); + input.setCompanyId(COMPANY_A); + input.setName("fresh"); + when(repository.existsByNameIgnoreCase("fresh")).thenReturn(false); when(repository.saveAndFlush(any())).thenAnswer(inv -> inv.getArgument(0)); - // Company A: no duplicate -> succeeds - service.save(inputA); - // Company B: no duplicate for B -> succeeds - service.save(inputB); - - verify(repository).existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech"); - verify(repository).existsByCompanyIdAndNameIgnoreCase(COMPANY_B, "tech"); + assertThat(service.save(input).getCompanyId()).isNull(); } // --- Test 7: updating row with same name unchanged is allowed --- @@ -188,7 +195,7 @@ class InterestServiceTest { input.setId(10L); input.setCompanyId(COMPANY_A); input.setName(" tech "); - when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(true); + when(repository.existsByNameIgnoreCase("tech")).thenReturn(true); assertThatThrownBy(() -> service.save(input)) .isInstanceOf(ResponseStatusException.class) @@ -202,7 +209,7 @@ class InterestServiceTest { List result = service.findByIds(COMPANY_A, null); assertThat(result).isEmpty(); - verify(repository, org.mockito.Mockito.never()).findByIdInAndCompanyId(any(), eq(COMPANY_A)); + verify(repository, org.mockito.Mockito.never()).findByIdIn(any()); } // --- Test 10: findByIds with empty ids returns empty --- @@ -211,33 +218,31 @@ class InterestServiceTest { List result = service.findByIds(COMPANY_A, Collections.emptyList()); assertThat(result).isEmpty(); - verify(repository, org.mockito.Mockito.never()).findByIdInAndCompanyId(any(), eq(COMPANY_A)); + verify(repository, org.mockito.Mockito.never()).findByIdIn(any()); } - // --- Test 11: findByIds returns only company's rows --- + // --- Test 11: findByIds returns the matching rows --- @Test - void findByIdsFiltersByCompany() { + void findByIdsReturnsMatchingRows() { Interest row = makeInterest(5L, COMPANY_A, "filter", true, 0); - when(repository.findByIdInAndCompanyId(List.of(5L), COMPANY_A)) + when(repository.findByIdIn(List.of(5L))) .thenReturn(List.of(row)); List result = service.findByIds(COMPANY_A, List.of(5L)); assertThat(result).hasSize(1).first().isSameAs(row); - verify(repository).findByIdInAndCompanyId(List.of(5L), COMPANY_A); + verify(repository).findByIdIn(List.of(5L)); } - // --- Test 12: findByIds filters by company — row not in company --- + // --- Test 12: findByIds returns rows of any company; the company argument is ignored --- @Test - void findByIdsExcludesOtherCompany() { + void findByIdsReturnsRowsOfAnyCompany() { Interest row = makeInterest(5L, COMPANY_B, "other", true, 0); - when(repository.findByIdInAndCompanyId(List.of(5L), COMPANY_A)) - .thenReturn(List.of()); + when(repository.findByIdIn(List.of(5L))).thenReturn(List.of(row)); List result = service.findByIds(COMPANY_A, List.of(5L)); - assertThat(result).isEmpty(); - verify(repository).findByIdInAndCompanyId(List.of(5L), COMPANY_A); + assertThat(result).hasSize(1).first().isSameAs(row); } // --- Test 13: creating interest with active left unset defaults to true --- @@ -247,7 +252,7 @@ class InterestServiceTest { input.setCompanyId(COMPANY_A); input.setName("default"); // active is left at JVM default (false) - when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "default")).thenReturn(false); + when(repository.existsByNameIgnoreCase("default")).thenReturn(false); when(repository.saveAndFlush(any())).thenAnswer(inv -> { Interest saved = inv.getArgument(0); saved.setId(99L); @@ -261,17 +266,17 @@ class InterestServiceTest { // --- Test 14: save then find returns saved interest with trimmed name --- @Test - void saveThenFindByCompanyReturnsTrimmedName() { + void saveThenFindReturnsTrimmedName() { Interest input = new Interest(); input.setCompanyId(COMPANY_A); input.setName(" tech "); - when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false); + when(repository.existsByNameIgnoreCase("tech")).thenReturn(false); when(repository.saveAndFlush(any())).thenAnswer(inv -> { Interest saved = inv.getArgument(0); saved.setId(99L); return saved; }); - when(repository.findByCompanyIdOrderBySortOrderAscNameAsc(COMPANY_A)) + when(repository.findAllByOrderBySortOrderAscNameAsc()) .thenAnswer(inv -> List.of(input)); service.save(input); @@ -327,7 +332,7 @@ class InterestServiceTest { Interest input = new Interest(); input.setCompanyId(COMPANY_A); input.setName("raced"); - when(repository.existsByCompanyIdAndNameIgnoreCase(eq(COMPANY_A), any())).thenReturn(false); + when(repository.existsByNameIgnoreCase(any())).thenReturn(false); when(repository.saveAndFlush(any())).thenThrow(new DataIntegrityViolationException("duplicate key")); assertThatThrownBy(() -> service.save(input)) @@ -341,7 +346,7 @@ class InterestServiceTest { void updateRaceOnUniqueKeyReturns409() { Interest existing = makeInterest(10L, COMPANY_A, "original", true, 1); when(repository.findById(10L)).thenReturn(Optional.of(existing)); - when(repository.existsByCompanyIdAndNameIgnoreCase(COMPANY_A, "tech")).thenReturn(false); + when(repository.existsByNameIgnoreCase("tech")).thenReturn(false); when(repository.saveAndFlush(any())).thenThrow(new DataIntegrityViolationException("duplicate key")); Interest input = new Interest(); diff --git a/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadCompanyScopeTest.java b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadCompanyScopeTest.java new file mode 100644 index 0000000..31b4f3d --- /dev/null +++ b/solvway-services-counter/src/test/java/com/solvway/services/counter/service/LeadCompanyScopeTest.java @@ -0,0 +1,185 @@ +package com.solvway.services.counter.service; + +import com.solvway.services.counter.dto.EventLeadCaptureRequest; +import com.solvway.services.counter.dto.EventLeadDetail; +import com.solvway.services.counter.dto.EventLeadSearchRequest; +import com.solvway.services.counter.dto.EventLeadUpdateRequest; +import com.solvway.services.counter.dto.LeadDetail; +import com.solvway.services.counter.dto.LeadMatchRequest; +import com.solvway.services.counter.dto.LeadSearchRequest; +import com.solvway.services.counter.dto.LeadUpdateRequest; +import com.solvway.services.counter.model.EventLead; +import com.solvway.services.counter.model.Lead; +import com.solvway.services.counter.repo.EventLeadInterestRepository; +import com.solvway.services.counter.repo.EventLeadRepository; +import com.solvway.services.counter.repo.LeadRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** Leads and event leads: lists take an optional company, details report the record's company, writes need one. */ +@ExtendWith(MockitoExtension.class) +class LeadCompanyScopeTest { + + private static final long COMPANY = 42L; + + @Mock private LeadRepository leadRepository; + @Mock private EventLeadRepository eventLeadRepository; + @Mock private EventLeadInterestRepository eventLeadInterestRepository; + + private LeadService leadService; + private EventLeadService eventLeadService; + + @BeforeEach + void setUp() { + leadService = new LeadService(leadRepository, eventLeadRepository); + eventLeadService = new EventLeadService(leadRepository, eventLeadRepository, eventLeadInterestRepository); + } + + private static Lead lead(long uuid, long companyId) { + Lead l = new Lead(); + l.setUuid(uuid); + l.setCompanyId(companyId); + l.setName("Ann"); + return l; + } + + private static EventLead eventLead(long uuid, long leadUuid, long companyId) { + EventLead e = new EventLead(); + e.setId(1L); + e.setUuid(uuid); + e.setCompanyId(companyId); + e.setLeadUuid(leadUuid); + e.setEventUuid(9L); + return e; + } + + // --- lead list --- + + @Test + void leadSearchWithoutCompanyPassesNullMeaningAll() { + when(leadRepository.search(any(), any(), any(), any(Pageable.class))).thenReturn(Page.empty()); + leadService.search(new LeadSearchRequest(null, "a", null, 0, 20)); + verify(leadRepository).search(eq(null), any(), any(), any(Pageable.class)); + } + + @Test + void leadSearchWithCompanyStillFilters() { + when(leadRepository.search(any(), any(), any(), any(Pageable.class))).thenReturn(Page.empty()); + leadService.search(new LeadSearchRequest(COMPANY, "a", null, 0, 20)); + verify(leadRepository).search(eq(COMPANY), any(), any(), any(Pageable.class)); + } + + // --- event lead list --- + + @Test + void eventLeadSearchWithoutCompanyPassesNullMeaningAll() { + when(eventLeadRepository.search(any(), anyLong(), any(), any(), any(), any(), any(), any(Pageable.class))) + .thenReturn(Page.empty()); + eventLeadService.search(new EventLeadSearchRequest(null, 9L, null, null, null, null, null, 0, 20)); + verify(eventLeadRepository).search(eq(null), eq(9L), any(), any(), any(), any(), any(), any(Pageable.class)); + } + + @Test + void eventLeadSearchWithCompanyStillFilters() { + when(eventLeadRepository.search(any(), anyLong(), any(), any(), any(), any(), any(), any(Pageable.class))) + .thenReturn(Page.empty()); + eventLeadService.search(new EventLeadSearchRequest(COMPANY, 9L, null, null, null, null, null, 0, 20)); + verify(eventLeadRepository).search(eq(COMPANY), eq(9L), any(), any(), any(), any(), any(), any(Pageable.class)); + } + + // --- detail --- + + @Test + void leadDetailWithNullCompanyReturnsRecordsCompany() { + when(leadRepository.findByUuid(5L)).thenReturn(Optional.of(lead(5L, 7L))); + when(eventLeadRepository.history(anyLong(), anyLong())).thenReturn(List.of()); + when(leadRepository.findMatches(anyLong(), any(), any(), any(Pageable.class))).thenReturn(List.of()); + + LeadDetail d = leadService.detail(null, 5L); + + assertThat(d.companyId()).isEqualTo(7L); + verify(leadRepository, never()).findByUuidAndCompanyId(anyLong(), anyLong()); + } + + @Test + void leadDetailWithCompanyReturnsRecordsCompany() { + when(leadRepository.findByUuidAndCompanyId(5L, COMPANY)).thenReturn(Optional.of(lead(5L, COMPANY))); + when(eventLeadRepository.history(anyLong(), anyLong())).thenReturn(List.of()); + when(leadRepository.findMatches(anyLong(), any(), any(), any(Pageable.class))).thenReturn(List.of()); + assertThat(leadService.detail(COMPANY, 5L).companyId()).isEqualTo(COMPANY); + } + + @Test + void leadDetailWithNullCompanyAndUnknownLeadIs404() { + when(leadRepository.findByUuid(5L)).thenReturn(Optional.empty()); + assertThatThrownBy(() -> leadService.detail(null, 5L)) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void eventLeadDetailWithNullCompanyReturnsRecordsCompany() { + when(eventLeadRepository.findByUuid(3L)).thenReturn(Optional.of(eventLead(3L, 5L, 7L))); + when(leadRepository.findByUuidAndCompanyId(5L, 7L)).thenReturn(Optional.of(lead(5L, 7L))); + when(eventLeadInterestRepository.findByIdEventLeadId(1L)).thenReturn(List.of()); + + EventLeadDetail d = eventLeadService.findByUuid(null, 3L); + + assertThat(d.companyId()).isEqualTo(7L); + assertThat(d.leadUuid()).isEqualTo(5L); + } + + // --- writes need a company --- + + private static void assertBadRequest(Runnable call) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST)); + } + + @Test + void captureWithNullCompanyIsRefused() { + assertBadRequest(() -> eventLeadService.capture(new EventLeadCaptureRequest(null, 9L, null, "Ann", null, null, + null, null, null, null, null, null, null, null, "me"))); + verifyNoInteractions(leadRepository, eventLeadRepository); + } + + @Test + void matchWithNullCompanyIsRefused() { + assertBadRequest(() -> eventLeadService.findMatches(new LeadMatchRequest(null, 9L, "+6012", null))); + verifyNoInteractions(leadRepository); + } + + @Test + void eventLeadUpdateWithNullCompanyIsRefused() { + assertBadRequest(() -> eventLeadService.update(new EventLeadUpdateRequest(null, 3L, null, null, null, null, null, + null, "me"))); + verifyNoInteractions(eventLeadRepository); + } + + @Test + void leadUpdateWithNullCompanyIsRefused() { + assertBadRequest(() -> leadService.update(new LeadUpdateRequest(null, 5L, "Ann", null, null, null, null, null, "me"))); + verifyNoInteractions(leadRepository); + } +} -- 2.54.1 From 118c57c0eaaa572b389c8f716a298a42c8e03b6f Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 19:05:41 +0800 Subject: [PATCH 06/24] feat: company on emails and audit search Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../solvway/services/email/model/Email.java | 2 + .../email/repo/EmailRepositoryImpl.java | 4 ++ .../email/repo/EmailCompanyScopingTest.java | 67 +++++++++++++++++++ .../log/controller/AuditEventController.java | 16 +++-- .../log/repo/AuditEventLogRepository.java | 10 +++ .../AuditEventControllerCompanyTest.java | 52 ++++++++++++++ 6 files changed, 147 insertions(+), 4 deletions(-) create mode 100644 solvway-services-email/src/test/java/com/solvway/services/email/repo/EmailCompanyScopingTest.java create mode 100644 solvway-services-log/src/test/java/com/solvway/services/log/controller/AuditEventControllerCompanyTest.java diff --git a/solvway-services-email/src/main/java/com/solvway/services/email/model/Email.java b/solvway-services-email/src/main/java/com/solvway/services/email/model/Email.java index c5c82b9..f74a3bb 100644 --- a/solvway-services-email/src/main/java/com/solvway/services/email/model/Email.java +++ b/solvway-services-email/src/main/java/com/solvway/services/email/model/Email.java @@ -22,6 +22,8 @@ public class Email implements Cloneable{ private String sender = EmailConstant.EMAIL_SENDER; private String subject; private String body; + /** Null for system emails with no company (visible to super admins only). */ + private Long companyId; @Column(updatable = false) private LocalDateTime datetime = LocalDateTime.now(); diff --git a/solvway-services-email/src/main/java/com/solvway/services/email/repo/EmailRepositoryImpl.java b/solvway-services-email/src/main/java/com/solvway/services/email/repo/EmailRepositoryImpl.java index 7db599c..ef8f865 100644 --- a/solvway-services-email/src/main/java/com/solvway/services/email/repo/EmailRepositoryImpl.java +++ b/solvway-services-email/src/main/java/com/solvway/services/email/repo/EmailRepositoryImpl.java @@ -59,6 +59,10 @@ public class EmailRepositoryImpl implements JpaRepositoryCustom{ predicates.add(cb.equal(root.get(k), Long.parseLong(value))); predicatesCount.add(cb.equal(rootCount.get(k), Long.parseLong(value))); } + case "companyId" -> { + predicates.add(cb.equal(root.get(k), Long.parseLong(value))); + predicatesCount.add(cb.equal(rootCount.get(k), Long.parseLong(value))); + } case "sender" -> { predicates.add(cb.like(root.get(k), "%" + value + "%")); predicatesCount.add(cb.like(rootCount.get(k), "%" + value + "%")); diff --git a/solvway-services-email/src/test/java/com/solvway/services/email/repo/EmailCompanyScopingTest.java b/solvway-services-email/src/test/java/com/solvway/services/email/repo/EmailCompanyScopingTest.java new file mode 100644 index 0000000..ebf302f --- /dev/null +++ b/solvway-services-email/src/test/java/com/solvway/services/email/repo/EmailCompanyScopingTest.java @@ -0,0 +1,67 @@ +package com.solvway.services.email.repo; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.email.model.Email; +import com.solvway.services.email.util.paging.PageableRest; +import jakarta.persistence.EntityManager; +import jakarta.persistence.criteria.CriteriaBuilder; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.HashMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +@SuppressWarnings({"rawtypes", "unchecked"}) +class EmailCompanyScopingTest { + + private final EntityManager em = mock(EntityManager.class, RETURNS_DEEP_STUBS); + private final CriteriaBuilder cb = em.getCriteriaBuilder(); + private final EmailRepositoryImpl repo = new EmailRepositoryImpl(); + + EmailCompanyScopingTest() { + ReflectionTestUtils.setField(repo, "em", em); + jakarta.persistence.TypedQuery query = mock(jakarta.persistence.TypedQuery.class, org.mockito.Mockito.RETURNS_SELF); + org.mockito.Mockito.doReturn(java.util.List.of()).when(query).getResultList(); + org.mockito.Mockito.doReturn(0L).when(query).getSingleResult(); + org.mockito.Mockito.doReturn(query).when(em).createQuery(any(jakarta.persistence.criteria.CriteriaQuery.class)); + } + + private PageableRest pageable() { + PageableRest p = new PageableRest(); + p.setNumber(0); + p.setSize(10); + PageableRest.SortRest sr = new PageableRest.SortRest(); + sr.setDirection("DESC"); + sr.setProperty("id"); + p.setSorts(new java.util.ArrayList<>(java.util.List.of(sr))); + return p; + } + + @Test + void emailKeepsCompanyFromPayload() throws Exception { + Email e = new ObjectMapper().readValue("{\"subject\":\"s\",\"companyId\":2}", Email.class); + assertThat(e.getCompanyId()).isEqualTo(2L); + assertThat(new ObjectMapper().readValue("{\"subject\":\"s\"}", Email.class).getCompanyId()).isNull(); + } + + @Test + void searchFiltersByCompanyWhenGiven() { + HashMap property = new HashMap<>(); + property.put("companyId", "2"); + repo.findByPropertyAndPageable(property, pageable()); + // once for the page query, once for the count query + verify(cb, org.mockito.Mockito.times(2)).equal(any(), org.mockito.ArgumentMatchers.eq(2L)); + } + + @Test + void searchDoesNotFilterByCompanyWhenAbsent() { + repo.findByPropertyAndPageable(new HashMap<>(), pageable()); + verify(cb, never()).equal(any(), any(Object.class)); + } +} diff --git a/solvway-services-log/src/main/java/com/solvway/services/log/controller/AuditEventController.java b/solvway-services-log/src/main/java/com/solvway/services/log/controller/AuditEventController.java index dc5617f..bc4d7cf 100644 --- a/solvway-services-log/src/main/java/com/solvway/services/log/controller/AuditEventController.java +++ b/solvway-services-log/src/main/java/com/solvway/services/log/controller/AuditEventController.java @@ -24,7 +24,12 @@ import java.util.Map; public class AuditEventController { public record SearchRequest(String actor, String module, String action, String outcome, - String from, String to, Integer page, Integer size) { + String from, String to, Integer page, Integer size, Long companyId) { + /** Keeps the pre-company body shape: no companyId means all companies. */ + public SearchRequest(String actor, String module, String action, String outcome, + String from, String to, Integer page, Integer size) { + this(actor, module, action, outcome, from, to, page, size, null); + } } private final AuditEventLogRepository repository; @@ -39,9 +44,12 @@ public class AuditEventController { int s = r.size() == null || r.size() < 1 ? 20 : Math.min(r.size(), 100); LocalDateTime from = day(r.from(), 0); LocalDateTime to = day(r.to(), 1); - Page page = repository.search(blankToNull(r.actor()), blankToNull(r.module()), - blankToNull(r.action()), blankToNull(r.outcome()), from, to, - PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "occurredAt", "id"))); + PageRequest paging = PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "occurredAt", "id")); + Page page = r.companyId() == null + ? repository.search(blankToNull(r.actor()), blankToNull(r.module()), + blankToNull(r.action()), blankToNull(r.outcome()), from, to, paging) + : repository.searchInCompany(r.companyId(), blankToNull(r.actor()), blankToNull(r.module()), + blankToNull(r.action()), blankToNull(r.outcome()), from, to, paging); return Map.of("content", page.getContent(), "totalElements", page.getTotalElements(), "number", p, "size", s); } diff --git a/solvway-services-log/src/main/java/com/solvway/services/log/repo/AuditEventLogRepository.java b/solvway-services-log/src/main/java/com/solvway/services/log/repo/AuditEventLogRepository.java index b6b64f4..daf6214 100644 --- a/solvway-services-log/src/main/java/com/solvway/services/log/repo/AuditEventLogRepository.java +++ b/solvway-services-log/src/main/java/com/solvway/services/log/repo/AuditEventLogRepository.java @@ -23,6 +23,16 @@ public interface AuditEventLogRepository extends JpaRepository= :from)" + + " and (:to is null or e.occurredAt < :to)") + Page searchInCompany(@Param("companyId") Long companyId, @Param("actor") String actor, + @Param("module") String module, @Param("action") String action, @Param("outcome") String outcome, + @Param("from") LocalDateTime from, @Param("to") LocalDateTime to, Pageable pageable); + /** Deletes up to {@code limit} old rows; each call is its own transaction. */ @Transactional @Modifying diff --git a/solvway-services-log/src/test/java/com/solvway/services/log/controller/AuditEventControllerCompanyTest.java b/solvway-services-log/src/test/java/com/solvway/services/log/controller/AuditEventControllerCompanyTest.java new file mode 100644 index 0000000..630bd32 --- /dev/null +++ b/solvway-services-log/src/test/java/com/solvway/services/log/controller/AuditEventControllerCompanyTest.java @@ -0,0 +1,52 @@ +package com.solvway.services.log.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.log.model.AuditEventLog; +import com.solvway.services.log.repo.AuditEventLogRepository; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.PageImpl; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.assertj.core.api.Assertions.assertThat; + +class AuditEventControllerCompanyTest { + + private final AuditEventLogRepository repository = mock(AuditEventLogRepository.class); + private final AuditEventController controller = new AuditEventController(repository); + + @Test + void companyIdGivenSearchesOnlyThatCompany() { + when(repository.searchInCompany(eq(2L), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new PageImpl<>(List.of(new AuditEventLog()))); + controller.search(new AuditEventController.SearchRequest( + null, null, null, null, null, null, null, null, 2L)); + verify(repository).searchInCompany(eq(2L), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), any()); + verify(repository, never()).search(any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void companyIdAbsentSearchesAllRows() { + when(repository.search(any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new PageImpl<>(List.of(new AuditEventLog()))); + controller.search(new AuditEventController.SearchRequest( + null, null, null, null, null, null, null, null, null)); + verify(repository).search(any(), any(), any(), any(), any(), any(), any()); + verify(repository, never()).searchInCompany(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void companyIdIsReadFromJsonBodyAndOldBodiesStillWork() throws Exception { + var m = new ObjectMapper(); + assertThat(m.readValue("{\"companyId\":3,\"actor\":\"a\"}", AuditEventController.SearchRequest.class) + .companyId()).isEqualTo(3L); + assertThat(m.readValue("{\"actor\":\"a\"}", AuditEventController.SearchRequest.class).companyId()).isNull(); + } +} -- 2.54.1 From 91a0f339a5e4d8b7056e9addfba36d2d24b94fb1 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 19:21:58 +0800 Subject: [PATCH 07/24] docs(openspec): tick company-scoping tasks 2.2 and 2.3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-company-scoping/tasks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/add-company-scoping/tasks.md b/openspec/changes/add-company-scoping/tasks.md index e7f3fb5..732991e 100644 --- a/openspec/changes/add-company-scoping/tasks.md +++ b/openspec/changes/add-company-scoping/tasks.md @@ -27,7 +27,7 @@ Design: `design.md`. All tasks run serially, ordered so that sign-in keeps worki - 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` -- [ ] 2.2 services-counter: events, leads, event leads and interests (decisions 6, 7 and 8). +- [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"; @@ -35,7 +35,7 @@ Design: `design.md`. All tasks run serially, ordered so that sign-in keeps worki - 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` -- [ ] 2.3 service-email and services-log (decisions 7 and 9). +- [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". -- 2.54.1 From 69d3ebc58c44ee2cbafddc7a7f84eb928a8840e5 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 19:42:40 +0800 Subject: [PATCH 08/24] feat: company sign-in, company scope and super-admin Companies API Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../api/RestApiSystemServiceConstants.java | 6 + .../controller/admin/AdminAuthController.java | 36 +++- .../admin/AdminCompanyController.java | 73 ++++++++ .../dto/admin/AdminForgotPasswordRequest.java | 4 +- .../api/dto/admin/AdminLoginRequest.java | 5 + .../api/dto/admin/AdminLoginResponse.java | 4 +- .../mobile/api/dto/admin/AdminMeResponse.java | 4 +- .../mobile/api/service/AdminAclService.java | 3 +- .../api/service/AdminCompanyService.java | 74 ++++++++ .../api/useraccess/AdminCompanyScope.java | 40 +++++ .../api/useraccess/AdminSessionGuard.java | 4 + .../admin/AdminAuthControllerCompanyTest.java | 163 ++++++++++++++++++ .../admin/AdminCompanyControllerTest.java | 120 +++++++++++++ .../api/service/AdminCompanyServiceTest.java | 59 +++++++ .../api/useraccess/AdminCompanyScopeTest.java | 69 ++++++++ .../AdminSessionGuardCompanyTest.java | 50 ++++++ 16 files changed, 702 insertions(+), 12 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminCompanyScope.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerCompanyTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminCompanyControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminCompanyServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminCompanyScopeTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardCompanyTest.java diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index ed33eee..f65dc5d 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -92,6 +92,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"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java index a9414d4..7c9bdfc 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java @@ -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> 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; } } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java new file mode 100644 index 0000000..2c86c38 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminCompanyController.java @@ -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() { + requireSuper(); + return ResponseEntity.ok(companies.list()); + } + + @AppAuth + @GetMapping("/{id}") + public ResponseEntity> get(@PathVariable Long id) { + requireSuper(); + return ResponseEntity.ok(companies.get(id)); + } + + @AppAuth + @PostMapping + public ResponseEntity> save(@RequestBody Map body) { + requireSuper(); + return ResponseEntity.ok(companies.save(body)); + } + + @AppAuth + @PostMapping("/{id}/code") + public ResponseEntity> renameCode(@PathVariable Long id, @RequestBody Map 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> 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); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminForgotPasswordRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminForgotPasswordRequest.java index 17274f7..78d2fbc 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminForgotPasswordRequest.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminForgotPasswordRequest.java @@ -1,5 +1,5 @@ package com.solvway.mobile.api.dto.admin; -/** Body of {@code POST /api/admin/auth/forgot-password}. */ -public record AdminForgotPasswordRequest(String username, String email) { +/** Body of {@code POST /api/admin/auth/forgot-password}. A blank company means a super admin. */ +public record AdminForgotPasswordRequest(String company, String username, String email) { } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginRequest.java new file mode 100644 index 0000000..5b64716 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginRequest.java @@ -0,0 +1,5 @@ +package com.solvway.mobile.api.dto.admin; + +/** Body of {@code POST /api/admin/auth/login}. A blank company means a super admin. */ +public record AdminLoginRequest(String company, String username, String password) { +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginResponse.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginResponse.java index 88dc43b..39b9319 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginResponse.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginResponse.java @@ -1,10 +1,12 @@ package com.solvway.mobile.api.dto.admin; +import com.fasterxml.jackson.annotation.JsonProperty; import com.solvway.core.model.Module; import com.solvway.core.model.Role; import java.util.List; /** Body of {@code POST /api/admin/auth/login}. Declares no password field on purpose: the upstream user carries hashes. */ -public record AdminLoginResponse(String token, String name, List roles, Module aclMenu, String resetPasswordRequired) { +public record AdminLoginResponse(String token, String name, List roles, Module aclMenu, String resetPasswordRequired, + Long companyId, String companyCode, @JsonProperty("isSuper") boolean isSuper) { } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminMeResponse.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminMeResponse.java index 2eb226e..72fab03 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminMeResponse.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminMeResponse.java @@ -1,10 +1,12 @@ package com.solvway.mobile.api.dto.admin; +import com.fasterxml.jackson.annotation.JsonProperty; import com.solvway.core.model.Module; import com.solvway.core.model.Role; import java.util.List; /** Body of {@code GET /api/admin/me}. No token or password fields. */ -public record AdminMeResponse(Long id, String username, String name, List roles, Module aclMenu) { +public record AdminMeResponse(Long id, String username, String name, List roles, Module aclMenu, + Long companyId, String companyCode, @JsonProperty("isSuper") boolean isSuper) { } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java index e71417f..360f98d 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java @@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils; import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; import com.solvway.mobile.api.dto.admin.AdminModuleGrant; import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.useraccess.AdminCompanyScope; import com.solvway.mobile.api.useraccess.AuditChanges; import com.solvway.mobile.api.util.RestTemplateCustomUtil; import lombok.RequiredArgsConstructor; @@ -45,7 +46,7 @@ public class AdminAclService { User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); - boolean isSuper = caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID); + boolean isSuper = AdminCompanyScope.isSuper(caller); if (!isSuper && caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() != ROLE_ADMIN_ID && r.getId().equals(roleId))) { throw error(HttpStatus.FORBIDDEN, "You cannot change the access of a role you hold", "OWN_ROLE"); } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java new file mode 100644 index 0000000..fc0bf3a --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminCompanyService.java @@ -0,0 +1,74 @@ +package com.solvway.mobile.api.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +/** Passes the Companies screen's calls to services-system, turning its 400/409/404 into coded admin errors. */ +@Service +@RequiredArgsConstructor +public class AdminCompanyService { + + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> LIST = new ParameterizedTypeReference<>() {}; + + private static final ObjectMapper JSON = new ObjectMapper(); + + private final RestTemplateCustomUtil restTemplateUtil; + + public List> list() { + return call(() -> restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_ALL), LIST).getBody()); + } + + public Map get(Long id) { + return call(() -> restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_BY_ID).replace("{id}", String.valueOf(id)), MAP).getBody()); + } + + public Map save(Map company) { + return call(() -> restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_SAVE), MAP, company).getBody()); + } + + public Map renameCode(Long id, String code) { + if (!StringUtils.hasText(code)) throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "Code is required", "INVALID_COMPANY"); + return call(() -> restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_RENAME_CODE).replace("{id}", String.valueOf(id)), MAP, + Map.of("code", code)).getBody()); + } + + private static T call(Supplier call) { + try { + return call.get(); + } catch (HttpClientErrorException e) { + HttpStatus status = HttpStatus.resolve(e.getStatusCode().value()); + if (status == HttpStatus.BAD_REQUEST) throw new CodedResponseStatusException(status, reason(e, "Invalid request"), "INVALID_COMPANY"); + if (status == HttpStatus.CONFLICT) throw new CodedResponseStatusException(status, reason(e, "Code is already taken"), "COMPANY_CODE_TAKEN"); + if (status == HttpStatus.NOT_FOUND) throw new CodedResponseStatusException(status, reason(e, "Company not found"), "COMPANY_NOT_FOUND"); + throw e; + } + } + + private static String reason(HttpClientErrorException e, String fallback) { + try { + JsonNode message = JSON.readTree(e.getResponseBodyAsString()).get("message"); + if (message != null && message.isTextual() && StringUtils.hasText(message.asText())) return message.asText(); + } catch (Exception ignored) { + // empty or unparsable body: use the fallback + } + return fallback; + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminCompanyScope.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminCompanyScope.java new file mode 100644 index 0000000..eb5189b --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminCompanyScope.java @@ -0,0 +1,40 @@ +package com.solvway.mobile.api.useraccess; + +import com.solvway.core.model.User; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; + +/** Which company an admin request may see or write. Every admin handler that reads or writes company data routes through here. */ +@Component +public class AdminCompanyScope { + private static final long SUPER_ADMIN_ROLE_ID = 1L; + + /** Super admin = no company and the super-admin role. A company user holding role 1 is still staff. */ + public static boolean isSuper(User caller) { + return caller.getCompanyId() == null && caller.getRoles() != null + && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID); + } + + /** Staff: their own company, whatever was requested. Super: the requested company, null = all companies. */ + public Long scope(User caller, Long requestedCompanyId) { + return isSuper(caller) ? requestedCompanyId : caller.getCompanyId(); + } + + /** Writes need a concrete company: staff get their own, a super admin must choose one. */ + public Long requireCompanyForCreate(User caller, Long requestedCompanyId) { + Long company = scope(caller, requestedCompanyId); + if (company == null) throw coded(HttpStatus.BAD_REQUEST, "Choose a company.", "COMPANY_REQUIRED"); + return company; + } + + public void requireSuper(User caller) { + if (!isSuper(caller)) throw coded(HttpStatus.FORBIDDEN, "Super admin only", "SUPER_ADMIN_REQUIRED"); + } + + private static CodedResponseStatusException coded(HttpStatus status, String reason, String code) { + CodedResponseStatusException ex = new CodedResponseStatusException(status, reason, code); + ex.getBody().setProperty("message", reason); // the portal reads {"message"} + return ex; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java index 394f6e5..d70571d 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java @@ -23,6 +23,10 @@ public class AdminSessionGuard { if (!user.isEnabled()) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Account disabled"); } + // Same reason as a dead session, so the response does not reveal an inactive company. Super admin has no company. + if (user.getCompanyId() != null && !"A".equals(user.getCompanyStatus())) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token"); + } if (user.getLogin() == LoginStatus.N && !allowPendingReset) { throw new CodedResponseStatusException(HttpStatus.FORBIDDEN, "Password change required", "PASSWORD_RESET_REQUIRED"); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerCompanyTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerCompanyTest.java new file mode 100644 index 0000000..91b8cb8 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerCompanyTest.java @@ -0,0 +1,163 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.model.AuthRequest; +import com.solvway.mobile.api.service.AdminAuthenticationService; +import com.solvway.mobile.api.service.AuthenticationService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminAuthControllerCompanyTest { + + @Mock private AdminAuthenticationService auth; + @Mock private AuthenticationService authenticationService; + @InjectMocks private AdminAuthController controller; + + private MockMvc mvc; + private MockedStatic http; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + } + + @AfterEach + void close() { http.close(); } + + private static User user(Long companyId, String code, String status, long roleId) { + User u = new User(); + u.setId(9L); + u.setUsername(code == null ? "root" : "john@" + code); + u.setName("John"); + u.setEnabled(true); + u.setLogin(GeneralEnum.LoginStatus.Y); + u.setCompanyId(companyId); + u.setCompanyCode(code); + u.setCompanyStatus(status); + Role r = new Role("R"); + r.setId(roleId); + u.setRoles(List.of(r)); + return u; + } + + private ResultActions login(String body) throws Exception { + return mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON).content(body)); + } + + @Test + void login_buildsLoginNameFromCompanyAndUsername() throws Exception { + when(auth.getToken(any())).thenReturn("tok"); + when(auth.loadUserByToken("tok")).thenReturn(user(5L, "ins", "A", 4)); + + login("{\"company\":\" INS \",\"username\":\"john\",\"password\":\"pw\"}").andExpect(status().isOk()); + + ArgumentCaptor sent = ArgumentCaptor.forClass(AuthRequest.class); + verify(auth).getToken(sent.capture()); + assertThat(sent.getValue().getUsername()).isEqualTo("john@ins"); + verify(auth).isLocked("john@ins"); + verify(auth).record("john@ins", "LOGIN_SUCCESS", null); + } + + @Test + void login_blankOrAbsentCompany_isSuperAdminPlainUsername() throws Exception { + when(auth.getToken(any())).thenReturn("tok"); + when(auth.loadUserByToken("tok")).thenReturn(user(null, null, null, 1)); + + login("{\"company\":\"\",\"username\":\"root\",\"password\":\"pw\"}").andExpect(status().isOk()); + login("{\"username\":\"root\",\"password\":\"pw\"}").andExpect(status().isOk()); + + ArgumentCaptor sent = ArgumentCaptor.forClass(AuthRequest.class); + verify(auth, org.mockito.Mockito.times(2)).getToken(sent.capture()); + assertThat(sent.getAllValues()).allMatch(r -> r.getUsername().equals("root")); + } + + @Test + void login_atSignInUsername_isBadLoginWithoutDownstreamCall() throws Exception { + login("{\"company\":\"ins\",\"username\":\"john@cv\",\"password\":\"pw\"}") + .andExpect(status().isUnauthorized()).andExpect(jsonPath("$.message").value("Invalid username or password")); + verify(auth, never()).getToken(any()); + verify(auth, never()).isLocked(anyString()); + } + + @Test + void login_wrongCompanyOrUnknownUser_isBadLogin() throws Exception { + when(auth.getToken(any())).thenReturn(null); + login("{\"company\":\"nope\",\"username\":\"john\",\"password\":\"pw\"}").andExpect(status().isUnauthorized()); + verify(auth).record("john@nope", "LOGIN_FAIL", null); + } + + @Test + void login_inactiveCompany_isBadLoginAndRecordedAndTokenRevoked() throws Exception { + when(auth.getToken(any())).thenReturn("tok"); + when(auth.loadUserByToken("tok")).thenReturn(user(5L, "ins", "I", 4)); + + login("{\"company\":\"ins\",\"username\":\"john\",\"password\":\"pw\"}") + .andExpect(status().isUnauthorized()).andExpect(jsonPath("$.message").value("Invalid username or password")); + verify(auth).record("john@ins", "LOGIN_FAIL", null); + verify(authenticationService).logoutToken("tok"); + } + + @Test + void login_response_carriesCompanyFieldsAndIsSuperKey() throws Exception { + when(auth.getToken(any())).thenReturn("tok"); + when(auth.loadUserByToken("tok")).thenReturn(user(5L, "ins", "A", 4)); + login("{\"company\":\"ins\",\"username\":\"john\",\"password\":\"pw\"}") + .andExpect(jsonPath("$.companyId").value(5)).andExpect(jsonPath("$.companyCode").value("ins")) + .andExpect(jsonPath("$.isSuper").value(false)); + + when(auth.loadUserByToken("tok")).thenReturn(user(null, null, null, 1)); + login("{\"username\":\"root\",\"password\":\"pw\"}") + .andExpect(jsonPath("$.companyId").doesNotExist()).andExpect(jsonPath("$.isSuper").value(true)); + } + + @Test + void me_carriesCompanyFieldsAndIsSuperKey() throws Exception { + when(auth.loadUserByToken("tok")).thenReturn(user(5L, "ins", "A", 4)); + mvc.perform(get("/api/admin/me")).andExpect(jsonPath("$.companyId").value(5)) + .andExpect(jsonPath("$.companyCode").value("ins")).andExpect(jsonPath("$.isSuper").value(false)) + .andExpect(jsonPath("$.username").value("john@ins")); + } + + @Test + void forgotPassword_buildsLoginName_andIgnoresAtSign() throws Exception { + mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON) + .content("{\"company\":\"INS\",\"username\":\"john\",\"email\":\"j@x.com\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.result").value("true")); + verify(auth).resetAdminPassword("john@ins", "j@x.com"); + + mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON) + .content("{\"company\":\"ins\",\"username\":\"a@b\",\"email\":\"j@x.com\"}")).andExpect(status().isOk()); + verify(auth, never()).resetAdminPassword(org.mockito.ArgumentMatchers.eq("a@b@ins"), anyString()); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminCompanyControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminCompanyControllerTest.java new file mode 100644 index 0000000..334c884 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminCompanyControllerTest.java @@ -0,0 +1,120 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.core.model.Role; +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 org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminCompanyControllerTest { + + @Mock private AdminCompanyService companies; + @Mock private AdminAuthenticationService auth; + private MockMvc mvc; + private MockedStatic http; + private static final String BODY = "{\"name\":\"Ins\",\"code\":\"ins\",\"status\":\"A\"}"; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(new AdminCompanyController(companies, auth, new AdminCompanyScope())).build(); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + } + + @AfterEach + void close() { http.close(); } + + private void caller(Long companyId, long roleId) { + User u = new User(); + u.setCompanyId(companyId); + Role r = new Role("R"); + r.setId(roleId); + u.setRoles(List.of(r)); + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private static CodedResponseStatusException coded(HttpStatus s, String reason) { + return new CodedResponseStatusException(s, reason, "X"); + } + + @Test + void everyHandlerIsAuthenticated() { + for (Method m : AdminCompanyController.class.getDeclaredMethods()) { + if (m.isSynthetic() || !java.lang.reflect.Modifier.isPublic(m.getModifiers())) continue; + if (m.getName().equals("upstream")) continue; + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName()).isTrue(); + } + } + + @Test + void companyStaff_get403_onEveryHandler_andNothingIsCalled() throws Exception { + caller(5L, 1); + mvc.perform(get("/api/admin/companies")).andExpect(status().isForbidden()); + mvc.perform(get("/api/admin/companies/1")).andExpect(status().isForbidden()); + mvc.perform(post("/api/admin/companies").contentType(MediaType.APPLICATION_JSON).content(BODY)).andExpect(status().isForbidden()); + mvc.perform(post("/api/admin/companies/1/code").contentType(MediaType.APPLICATION_JSON).content("{\"code\":\"x1\"}")) + .andExpect(status().isForbidden()); + verifyNoInteractions(companies); + } + + @Test + void superAdmin_listsGetsAndSaves() throws Exception { + caller(null, 1); + when(companies.list()).thenReturn(List.of(Map.of("id", 1, "name", "Ins", "code", "ins", "status", "A"))); + when(companies.get(1L)).thenReturn(Map.of("id", 1, "code", "ins")); + when(companies.save(any())).thenReturn(Map.of("id", 2, "code", "cv")); + when(companies.renameCode(1L, "new1")).thenReturn(Map.of("id", 1, "code", "new1")); + mvc.perform(get("/api/admin/companies")).andExpect(status().isOk()).andExpect(jsonPath("$[0].code").value("ins")); + mvc.perform(get("/api/admin/companies/1")).andExpect(jsonPath("$.code").value("ins")); + mvc.perform(post("/api/admin/companies").contentType(MediaType.APPLICATION_JSON).content(BODY)) + .andExpect(status().isOk()).andExpect(jsonPath("$.code").value("cv")); + mvc.perform(post("/api/admin/companies/1/code").contentType(MediaType.APPLICATION_JSON).content("{\"code\":\"new1\"}")) + .andExpect(jsonPath("$.code").value("new1")); + } + + @Test + void upstream400_409_404_areMappedWithMessage() throws Exception { + caller(null, 1); + when(companies.save(any())).thenThrow(coded(HttpStatus.BAD_REQUEST, "Name is required")); + mvc.perform(post("/api/admin/companies").contentType(MediaType.APPLICATION_JSON).content(BODY)) + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("Name is required")); + + when(companies.renameCode(1L, "taken")).thenThrow(coded(HttpStatus.CONFLICT, "Code is already taken")); + mvc.perform(post("/api/admin/companies/1/code").contentType(MediaType.APPLICATION_JSON).content("{\"code\":\"taken\"}")) + .andExpect(status().isConflict()).andExpect(jsonPath("$.message").value("Code is already taken")); + + when(companies.get(9L)).thenThrow(coded(HttpStatus.NOT_FOUND, "Company not found")); + mvc.perform(get("/api/admin/companies/9")).andExpect(status().isNotFound()) + .andExpect(jsonPath("$.message").value("Company not found")); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminCompanyServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminCompanyServiceTest.java new file mode 100644 index 0000000..3dcd933 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminCompanyServiceTest.java @@ -0,0 +1,59 @@ +package com.solvway.mobile.api.service; + +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.Test; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + +import java.nio.charset.StandardCharsets; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +class AdminCompanyServiceTest { + + private final RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class); + private final AdminCompanyService service = new AdminCompanyService(rest); + + private static HttpClientErrorException upstream(HttpStatus s, String body) { + return HttpClientErrorException.create(s, s.name(), null, body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); + } + + private void assertCoded(Runnable call, HttpStatus status, String message) { + assertThatThrownBy(call::run).isInstanceOf(CodedResponseStatusException.class).satisfies(ex -> { + CodedResponseStatusException c = (CodedResponseStatusException) ex; + assertThat(c.getStatusCode()).isEqualTo(status); + assertThat(c.getReason()).isEqualTo(message); + }); + } + + @Test + void upstream400_409_404_becomeCodedExceptions() { + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + when(rest.postForEntity(any(String.class), any(ParameterizedTypeReference.class), any())) + .thenThrow(upstream(HttpStatus.BAD_REQUEST, "{\"message\":\"Name is required\"}")); + assertCoded(() -> service.save(Map.of("name", "")), HttpStatus.BAD_REQUEST, "Name is required"); + + when(rest.postForEntity(any(String.class), any(ParameterizedTypeReference.class), any())) + .thenThrow(upstream(HttpStatus.CONFLICT, "")); + assertCoded(() -> service.renameCode(1L, "taken"), HttpStatus.CONFLICT, "Code is already taken"); + + when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class))).thenThrow(upstream(HttpStatus.NOT_FOUND, "")); + assertCoded(() -> service.get(9L), HttpStatus.NOT_FOUND, "Company not found"); + } + + @Test + void blankOrMissingCode_is400_beforeAnyDownstreamCall() { + assertCoded(() -> service.renameCode(1L, null), HttpStatus.BAD_REQUEST, "Code is required"); + assertCoded(() -> service.renameCode(1L, " "), HttpStatus.BAD_REQUEST, "Code is required"); + verifyNoMoreInteractions(rest); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminCompanyScopeTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminCompanyScopeTest.java new file mode 100644 index 0000000..acc39b2 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminCompanyScopeTest.java @@ -0,0 +1,69 @@ +package com.solvway.mobile.api.useraccess; + +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class AdminCompanyScopeTest { + + private final AdminCompanyScope scope = new AdminCompanyScope(); + + private static User user(Long companyId, long... roleIds) { + User u = new User(); + u.setCompanyId(companyId); + u.setRoles(java.util.Arrays.stream(roleIds).mapToObj(id -> { + Role r = new Role("R" + id); + r.setId(id); + return r; + }).toList()); + return u; + } + + private static void assertStatus(Runnable call, HttpStatus expected) { + assertThatThrownBy(call::run).isInstanceOf(ResponseStatusException.class) + .satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode()).isEqualTo(expected)); + } + + @Test + void isSuper_needsNoCompanyAndRoleOne() { + assertThat(AdminCompanyScope.isSuper(user(null, 1))).isTrue(); + assertThat(AdminCompanyScope.isSuper(user(5L, 1))).isFalse(); + assertThat(AdminCompanyScope.isSuper(user(null, 2, 4))).isFalse(); + assertThat(AdminCompanyScope.isSuper(user(null))).isFalse(); + } + + @Test + void scope_staffIgnoresRequest_superGetsRequestedOrNull() { + assertThat(scope.scope(user(5L, 4), 9L)).isEqualTo(5L); + assertThat(scope.scope(user(5L, 4), null)).isEqualTo(5L); + assertThat(scope.scope(user(null, 1), 9L)).isEqualTo(9L); + assertThat(scope.scope(user(null, 1), null)).isNull(); + } + + @Test + void requireCompanyForCreate_staffOwn_superRequestedOr400() { + assertThat(scope.requireCompanyForCreate(user(5L, 4), 9L)).isEqualTo(5L); + assertThat(scope.requireCompanyForCreate(user(null, 1), 9L)).isEqualTo(9L); + assertThatThrownBy(() -> scope.requireCompanyForCreate(user(null, 1), null)) + .isInstanceOf(ResponseStatusException.class) + .satisfies(ex -> { + ResponseStatusException e = (ResponseStatusException) ex; + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(e.getBody().getProperties()).containsEntry("message", "Choose a company."); + }); + } + + @Test + void requireSuper_forbidsStaff() { + scope.requireSuper(user(null, 1)); + assertStatus(() -> scope.requireSuper(user(5L, 1)), HttpStatus.FORBIDDEN); + assertStatus(() -> scope.requireSuper(user(null, 4)), HttpStatus.FORBIDDEN); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardCompanyTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardCompanyTest.java new file mode 100644 index 0000000..607dc55 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardCompanyTest.java @@ -0,0 +1,50 @@ +package com.solvway.mobile.api.useraccess; + +import com.solvway.core.enums.GeneralEnum.LoginStatus; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.mobile.api.service.AdminAuthenticationService; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AdminSessionGuardCompanyTest { + + private final AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + private final AdminSessionGuard guard = new AdminSessionGuard(auth); + + private static User user(Long companyId, String status, Long roleId) { + User u = new User(); + u.setEnabled(true); + u.setLogin(LoginStatus.Y); + u.setCompanyId(companyId); + u.setCompanyStatus(status); + Role r = new Role("R"); + r.setId(roleId); + u.setRoles(java.util.List.of(r)); + return u; + } + + @Test + void inactiveCompany_endsStaffSession() { + when(auth.loadUserByToken("tok")).thenReturn(user(5L, "I", 4L)); + assertThatThrownBy(() -> guard.check("tok", false)).isInstanceOf(ResponseStatusException.class) + .satisfies(ex -> { + assertThat(((ResponseStatusException) ex).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(((ResponseStatusException) ex).getReason()).isEqualTo("Invalid Token"); // same as a dead session + }); + } + + @Test + void activeCompany_andSuperAdmin_pass() { + when(auth.loadUserByToken("tok")).thenReturn(user(5L, "A", 4L)); + assertThat(guard.check("tok", false)).isNotNull(); + when(auth.loadUserByToken("sup")).thenReturn(user(null, null, 1L)); + assertThat(guard.check("sup", false)).isNotNull(); + } +} -- 2.54.1 From de007b53283e5a908e701ede0e368deddf0b6342 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 19:43:56 +0800 Subject: [PATCH 09/24] docs(openspec): tick company-scoping task 3.1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-company-scoping/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/add-company-scoping/tasks.md b/openspec/changes/add-company-scoping/tasks.md index 732991e..c8bd5e2 100644 --- a/openspec/changes/add-company-scoping/tasks.md +++ b/openspec/changes/add-company-scoping/tasks.md @@ -44,7 +44,7 @@ Design: `design.md`. All tasks run serially, ordered so that sign-in keeps worki ## 3. mobile-api -- [ ] 3.1 Sign-in, company scope and Companies API (decisions 1, 3, 4 and 5). +- [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`; -- 2.54.1 From 5526294e691f456755837dff4b6a2f81a0564183 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 19:48:30 +0800 Subject: [PATCH 10/24] feat(portal): company sign-in, session company and Companies screen Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../forgot-password/route.company.test.ts | 15 ++ .../app/api/auth/forgot-password/route.ts | 8 +- .../app/api/auth/login/route.company.test.ts | 24 ++ .../app/api/auth/login/route.ts | 5 +- .../api/auth/session/route.company.test.ts | 21 ++ .../app/api/auth/session/route.ts | 7 +- .../app/api/companies/[id]/code/route.test.ts | 32 +++ .../app/api/companies/[id]/code/route.ts | 19 ++ .../app/api/companies/route.test.ts | 46 ++++ .../app/api/companies/route.ts | 27 +++ .../app/companies/page.fixes.test.tsx | 38 ++++ .../app/companies/page.test.tsx | 96 ++++++++ solvway-admin-portal/app/companies/page.tsx | 213 ++++++++++++++++++ .../components/app/Header.company.test.tsx | 25 ++ .../app/components/app/Header.tsx | 3 +- .../app/forgot-password/page.company.test.tsx | 37 +++ .../app/forgot-password/page.tsx | 8 +- .../app/lib/AdminAuthContext.company.test.tsx | 34 +++ .../app/lib/AdminAuthContext.tsx | 24 +- .../app/lib/i18n/defaultMessages.ts | 17 ++ .../app/lib/services/adminCompanies.ts | 10 + solvway-admin-portal/app/lib/types.ts | 17 ++ .../app/lib/useAclSidebar.company.test.tsx | 27 +++ solvway-admin-portal/app/lib/useAclSidebar.ts | 11 +- .../app/login/page.company.test.tsx | 38 ++++ solvway-admin-portal/app/login/page.tsx | 16 ++ 26 files changed, 807 insertions(+), 11 deletions(-) create mode 100644 solvway-admin-portal/app/api/auth/forgot-password/route.company.test.ts create mode 100644 solvway-admin-portal/app/api/auth/login/route.company.test.ts create mode 100644 solvway-admin-portal/app/api/auth/session/route.company.test.ts create mode 100644 solvway-admin-portal/app/api/companies/[id]/code/route.test.ts create mode 100644 solvway-admin-portal/app/api/companies/[id]/code/route.ts create mode 100644 solvway-admin-portal/app/api/companies/route.test.ts create mode 100644 solvway-admin-portal/app/api/companies/route.ts create mode 100644 solvway-admin-portal/app/companies/page.fixes.test.tsx create mode 100644 solvway-admin-portal/app/companies/page.test.tsx create mode 100644 solvway-admin-portal/app/companies/page.tsx create mode 100644 solvway-admin-portal/app/components/app/Header.company.test.tsx create mode 100644 solvway-admin-portal/app/forgot-password/page.company.test.tsx create mode 100644 solvway-admin-portal/app/lib/AdminAuthContext.company.test.tsx create mode 100644 solvway-admin-portal/app/lib/services/adminCompanies.ts create mode 100644 solvway-admin-portal/app/lib/useAclSidebar.company.test.tsx create mode 100644 solvway-admin-portal/app/login/page.company.test.tsx diff --git a/solvway-admin-portal/app/api/auth/forgot-password/route.company.test.ts b/solvway-admin-portal/app/api/auth/forgot-password/route.company.test.ts new file mode 100644 index 0000000..58e26ec --- /dev/null +++ b/solvway-admin-portal/app/api/auth/forgot-password/route.company.test.ts @@ -0,0 +1,15 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); + +import { POST } from "./route"; + +beforeEach(() => mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} })); + +describe("POST /api/auth/forgot-password company", () => { + it("forwards a trimmed company", async () => { + await POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify({ company: " ins ", username: "john", email: "j@x.com" }) }) as never); + expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", email: "j@x.com" }); + }); +}); diff --git a/solvway-admin-portal/app/api/auth/forgot-password/route.ts b/solvway-admin-portal/app/api/auth/forgot-password/route.ts index 9964eaa..5436284 100644 --- a/solvway-admin-portal/app/api/auth/forgot-password/route.ts +++ b/solvway-admin-portal/app/api/auth/forgot-password/route.ts @@ -5,11 +5,15 @@ import { callMobileApi } from "@/app/lib/server/mobileApi"; // the answer must not reveal whether the account exists, so upstream errors are never forwarded. // Same-origin and body-size checks are enforced for every /api write by middleware. export async function POST(req: NextRequest) { - const body = (await req.json().catch(() => ({}))) as { username?: unknown; email?: unknown }; + const body = (await req.json().catch(() => ({}))) as { company?: unknown; username?: unknown; email?: unknown }; const username = typeof body.username === "string" ? body.username.trim() : ""; const email = typeof body.email === "string" ? body.email.trim() : ""; + const company = typeof body.company === "string" ? body.company.trim() : ""; if (username && email) { - await callMobileApi("/api/admin/auth/forgot-password", { method: "POST", body: { username, email } }); + await callMobileApi("/api/admin/auth/forgot-password", { + method: "POST", + body: { ...(company && { company }), username, email }, + }); } return NextResponse.json({ ok: true }); } diff --git a/solvway-admin-portal/app/api/auth/login/route.company.test.ts b/solvway-admin-portal/app/api/auth/login/route.company.test.ts new file mode 100644 index 0000000..81d8974 --- /dev/null +++ b/solvway-admin-portal/app/api/auth/login/route.company.test.ts @@ -0,0 +1,24 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), setSession: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ setSession: mocks.setSession })); + +import { POST } from "./route"; + +const req = (body: unknown) => + new Request("http://localhost/api/auth/login", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters[0]; + +beforeEach(() => { + mocks.callMobileApi.mockReset().mockResolvedValue({ + ok: true, + data: { token: "t", name: "N", roles: [], aclMenu: {}, resetPasswordRequired: "false" }, + }); +}); + +describe("POST /api/auth/login company", () => { + it("forwards a trimmed company", async () => { + await POST(req({ company: " ins ", username: "john", password: "pw" })); + expect(mocks.callMobileApi.mock.calls[0][1].body).toEqual({ company: "ins", username: "john", password: "pw" }); + }); +}); diff --git a/solvway-admin-portal/app/api/auth/login/route.ts b/solvway-admin-portal/app/api/auth/login/route.ts index e275364..d89473a 100644 --- a/solvway-admin-portal/app/api/auth/login/route.ts +++ b/solvway-admin-portal/app/api/auth/login/route.ts @@ -14,7 +14,7 @@ import type { AdminLoginResponse } from "@/app/lib/types"; // echoed back here, keeping this handler's response minimal. export async function POST(req: NextRequest) { const body = await req.json().catch(() => ({})); - const { username, password } = body as { username?: string; password?: string }; + const { company, username, password } = body as { company?: string; username?: string; password?: string }; const identifier = (username ?? "").trim(); if (!identifier || !password) { @@ -23,7 +23,8 @@ export async function POST(req: NextRequest) { const result = await callMobileApi("/api/admin/auth/login", { method: "POST", - body: { username: identifier, password }, + // A blank company is a super-admin login: omit the key rather than send "". + body: { ...(company?.trim() && { company: company.trim() }), username: identifier, password }, // Real-client context for the login_audit trail (X-Client-Ip / X-Client-User-Agent). headers: clientContextHeaders(req), }); diff --git a/solvway-admin-portal/app/api/auth/session/route.company.test.ts b/solvway-admin-portal/app/api/auth/session/route.company.test.ts new file mode 100644 index 0000000..a23907f --- /dev/null +++ b/solvway-admin-portal/app/api/auth/session/route.company.test.ts @@ -0,0 +1,21 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: vi.fn().mockResolvedValue("jwt") })); +vi.mock("@/app/lib/server/sessionRefresh", () => ({ maybeRefreshSession: vi.fn() })); + +import { GET } from "./route"; + +beforeEach(() => mocks.callMobileApi.mockReset()); + +describe("GET /api/auth/session company", () => { + it("passes companyId, companyCode and isSuper through", async () => { + mocks.callMobileApi.mockResolvedValue({ + ok: true, + data: { id: 1, username: "john@ins", name: "J", roles: [], aclMenu: {}, companyId: 7, companyCode: "ins", isSuper: false }, + }); + const res = await GET(new Request("http://localhost/api/auth/session") as never); + expect(await res.json()).toMatchObject({ companyId: 7, companyCode: "ins", isSuper: false }); + }); +}); diff --git a/solvway-admin-portal/app/api/auth/session/route.ts b/solvway-admin-portal/app/api/auth/session/route.ts index dc1c70f..1a94bd9 100644 --- a/solvway-admin-portal/app/api/auth/session/route.ts +++ b/solvway-admin-portal/app/api/auth/session/route.ts @@ -25,6 +25,9 @@ export async function GET(req: NextRequest) { const result = await callMobileApi("/api/admin/me", { token }); if (!result.ok) return errorResponse(result); - const { id, username, name, roles, aclMenu, branch } = result.data; - return NextResponse.json({ id, username, name, roles, aclMenu, branch: branch ?? null }); + const { id, username, name, roles, aclMenu, branch, companyId, companyCode, isSuper } = result.data; + return NextResponse.json({ + id, username, name, roles, aclMenu, branch: branch ?? null, + companyId, companyCode, isSuper, + }); } diff --git a/solvway-admin-portal/app/api/companies/[id]/code/route.test.ts b/solvway-admin-portal/app/api/companies/[id]/code/route.test.ts new file mode 100644 index 0000000..3501216 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/[id]/code/route.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { POST } from "./route"; + +const call = (body: unknown) => + POST(new Request("http://localhost/x", { method: "POST", body: JSON.stringify(body) }) as never, { params: Promise.resolve({ id: "7" }) }); + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset().mockResolvedValue("jwt"); +}); + +describe("POST /api/companies/[id]/code", () => { + it("returns 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await call({ code: "new" })).status).toBe(401); + }); + + it("forwards the code to /api/admin/companies/{id}/code", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 7, code: "new" } }); + await call({ code: "new" }); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies/7/code", { + method: "POST", + body: { code: "new" }, + token: "jwt", + }); + }); +}); diff --git a/solvway-admin-portal/app/api/companies/[id]/code/route.ts b/solvway-admin-portal/app/api/companies/[id]/code/route.ts new file mode 100644 index 0000000..5f34bf2 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/[id]/code/route.ts @@ -0,0 +1,19 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; +import type { AdminCompany } from "@/app/lib/types"; + +export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { + const token = await getToken(); + if (!token) return unauthorized(); + const { id } = await params; + const { code } = (await req.json().catch(() => ({}))) as { code?: string }; + const result = await callMobileApi(`/api/admin/companies/${encodeURIComponent(id)}/code`, { + method: "POST", + body: { code }, + token, + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/companies/route.test.ts b/solvway-admin-portal/app/api/companies/route.test.ts new file mode 100644 index 0000000..9734a71 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/route.test.ts @@ -0,0 +1,46 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET, POST } from "./route"; + +const post = (body: unknown) => + new Request("http://localhost/api/companies", { method: "POST", body: JSON.stringify(body) }) as unknown as Parameters[0]; + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset().mockResolvedValue("jwt"); +}); + +describe("/api/companies", () => { + it("GET returns 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + expect((await GET()).status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("GET forwards to /api/admin/companies", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] }); + await GET(); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", { token: "jwt" }); + }); + + it("POST forwards id, name, code and status", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1 } }); + await POST(post({ id: 1, name: "Ins", code: "ins", status: "A", extra: "x" })); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/companies", { + method: "POST", + body: { id: 1, name: "Ins", code: "ins", status: "A" }, + token: "jwt", + }); + }); + + it("POST relays a 409 from the API", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "Code already used" }); + const res = await POST(post({ name: "Ins", code: "ins", status: "A" })); + expect(res.status).toBe(409); + expect((await res.json()).error).toBe("Code already used"); + }); +}); diff --git a/solvway-admin-portal/app/api/companies/route.ts b/solvway-admin-portal/app/api/companies/route.ts new file mode 100644 index 0000000..3d242e4 --- /dev/null +++ b/solvway-admin-portal/app/api/companies/route.ts @@ -0,0 +1,27 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; +import type { AdminCompany } from "@/app/lib/types"; + +// Super admin only; the mobile-api answers 403 for anyone else, and validation (400) and duplicate codes (409) too. +export async function GET() { + const token = await getToken(); + if (!token) return unauthorized(); + const result = await callMobileApi("/api/admin/companies", { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} + +export async function POST(req: NextRequest) { + const token = await getToken(); + if (!token) return unauthorized(); + const { id, name, code, status } = (await req.json().catch(() => ({}))) as Partial; + const result = await callMobileApi("/api/admin/companies", { + method: "POST", + body: { id, name, code, status }, + token, + }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/companies/page.fixes.test.tsx b/solvway-admin-portal/app/companies/page.fixes.test.tsx new file mode 100644 index 0000000..554e350 --- /dev/null +++ b/solvway-admin-portal/app/companies/page.fixes.test.tsx @@ -0,0 +1,38 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() })); +vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ + ApiError: (await importOriginal()).ApiError, + apiGet: mocks.apiGet, + apiPost: mocks.apiPost, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); + +import CompaniesPage from "./page"; + +beforeEach(() => { + mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]); + mocks.apiPost.mockReset(); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true }); +}); + +describe("CompaniesPage fixes", () => { + it("does not post a code change when the new code equals the current code", async () => { + render(); + await userEvent.click(await screen.findByRole("button", { name: "Change code" })); + const input = screen.getByLabelText("New code"); + await userEvent.clear(input); + await userEvent.type(input, " INS "); + await userEvent.click(screen.getByRole("button", { name: "Confirm" })); + expect(mocks.apiPost).not.toHaveBeenCalled(); + expect(screen.getByRole("alert")).toBeInTheDocument(); + }); + + it("shows the API error text of a failed load directly", async () => { + mocks.apiGet.mockRejectedValue(new Error("Forbidden for you")); + render(); + expect(await screen.findByText("Forbidden for you")).toBeInTheDocument(); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.test.tsx b/solvway-admin-portal/app/companies/page.test.tsx new file mode 100644 index 0000000..be61ac8 --- /dev/null +++ b/solvway-admin-portal/app/companies/page.test.tsx @@ -0,0 +1,96 @@ +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() })); +vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ + ApiError: (await importOriginal()).ApiError, + apiGet: mocks.apiGet, + apiPost: mocks.apiPost, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); + +import CompaniesPage from "./page"; +import { ApiError } from "@/app/lib/clientApi"; + +const ROWS = [ + { id: 1, name: "Insight", code: "ins", status: "A" }, + { id: 2, name: "Clever", code: "cv", status: "I" }, +]; + +beforeEach(() => { + mocks.apiGet.mockReset().mockResolvedValue(ROWS); + mocks.apiPost.mockReset(); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true }); +}); + +describe("CompaniesPage", () => { + it("lists name, code and status", async () => { + render(); + const row = (await screen.findByText("Insight")).closest("tr")!; + expect(within(row).getByText("ins")).toBeInTheDocument(); + expect(within(row).getByText("Active")).toBeInTheDocument(); + expect(within(screen.getByText("Clever").closest("tr")!).getByText("Inactive")).toBeInTheDocument(); + expect(mocks.apiGet).toHaveBeenCalledWith("/api/companies"); + }); + + it("creates a company with name, code and status", async () => { + mocks.apiPost.mockResolvedValue({ id: 3 }); + render(); + await userEvent.click(await screen.findByRole("button", { name: /add company/i })); + await userEvent.type(screen.getByLabelText("Name"), " Acme "); + await userEvent.type(screen.getByLabelText("Code"), "acme"); + await userEvent.click(screen.getByRole("button", { name: /save/i })); + await waitFor(() => + expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { name: "Acme", code: "acme", status: "A" }), + ); + }); + + it("edits name and status only, with no code field", async () => { + mocks.apiPost.mockResolvedValue({ id: 1 }); + render(); + const row = (await screen.findByText("Insight")).closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: "Edit" })); + expect(screen.queryByLabelText("Code")).toBeNull(); + const name = screen.getByLabelText("Name"); + await userEvent.clear(name); + await userEvent.type(name, "Insight Ltd"); + await userEvent.click(screen.getByRole("button", { name: /save/i })); + await waitFor(() => + expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies", { id: 1, name: "Insight Ltd", status: "A" }), + ); + }); + + it("shows an API 409 message on the form", async () => { + mocks.apiPost.mockRejectedValue(new ApiError("Code already used", 409)); + render(); + await userEvent.click(await screen.findByRole("button", { name: /add company/i })); + await userEvent.type(screen.getByLabelText("Name"), "Acme"); + await userEvent.type(screen.getByLabelText("Code"), "ins"); + await userEvent.click(screen.getByRole("button", { name: /save/i })); + expect(await screen.findByText("Code already used")).toBeInTheDocument(); + }); + + it("warns before a code change, then posts the new code", async () => { + mocks.apiPost.mockResolvedValue({ id: 1, code: "new" }); + render(); + const row = (await screen.findByText("Insight")).closest("tr")!; + await userEvent.click(within(row).getByRole("button", { name: /change code/i })); + expect( + screen.getByText("Changing the code changes every staff login name of this company and signs them out."), + ).toBeInTheDocument(); + expect(mocks.apiPost).not.toHaveBeenCalled(); + const code = screen.getByLabelText("New code"); + await userEvent.clear(code); + await userEvent.type(code, "new"); + await userEvent.click(screen.getByRole("button", { name: /confirm/i })); + await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies/1/code", { code: "new" })); + }); + + it("is refused for non-super users", () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, isSuper: false }); + render(); + expect(screen.getByTestId("not-authorized")).toBeInTheDocument(); + expect(mocks.apiGet).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/companies/page.tsx b/solvway-admin-portal/app/companies/page.tsx new file mode 100644 index 0000000..451c8bf --- /dev/null +++ b/solvway-admin-portal/app/companies/page.tsx @@ -0,0 +1,213 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react"; +import { Plus } from "lucide-react"; +import type { ColumnDef } from "@tanstack/react-table"; +import { Button } from "@/app/components/ui/button"; +import { Input } from "@/app/components/ui/input"; +import { Label } from "@/app/components/ui/label"; +import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; +import { DataTable } from "@/app/components/ui/data-table"; +import { PageHeader } from "@/app/components/ui/page-header"; +import { EmptyState, ErrorState } from "@/app/components/ui/states"; +import { Badge } from "@/app/components/ui/badge"; +import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize"; +import { useAdminAuth } from "@/app/lib/AdminAuthContext"; +import { NotAuthorized } from "@/app/lib/RequireModule"; +import { changeAdminCompanyCode, listAdminCompanies, saveAdminCompany } from "@/app/lib/services/adminCompanies"; +import type { AdminCompany } from "@/app/lib/types"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +type Mode = "form" | "code"; +type DialogState = { mode: Mode; company: AdminCompany }; + +const NEW_COMPANY: AdminCompany = { name: "", code: "", status: "A" }; + +// ponytail: the API message is shown as returned (not translated); add codes to the API if that matters. +function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClose: () => void; onSaved: () => void }) { + const t = useT(); + const { mode, company } = state; + const [form, setForm] = useState(company); + const [newCode, setNewCode] = useState(company.code); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + + async function handleSubmit(event: FormEvent) { + event.preventDefault(); + if (mode === "form" && !form.name.trim()) return setError(t("CompNameRequired")); + if ((mode === "code" ? newCode : form.code).trim() === "" && (mode === "code" || !form.id)) { + return setError(t("CompCodeRequired")); + } + if (mode === "code" && newCode.trim().toLowerCase() === company.code.toLowerCase()) { + return setError(t("CompCodeUnchanged")); + } + setError(null); + setSaving(true); + try { + if (mode === "code") await changeAdminCompanyCode(company.id!, newCode.trim()); + else if (form.id) await saveAdminCompany({ id: form.id, name: form.name.trim(), status: form.status }); + else await saveAdminCompany({ name: form.name.trim(), code: form.code.trim(), status: form.status }); + onSaved(); + onClose(); + } catch (err) { + setError(err instanceof Error && err.message ? err.message : t("CompSaveFailed")); + } finally { + setSaving(false); + } + } + + return ( + !open && onClose()}> + + + {mode === "code" ? t("CompChangeCode") : form.id ? t("CompEdit") : t("CompAdd")} + + {error && ( +
+ {error} +
+ )} +
+ {mode === "code" ? ( + <> +

{t("CompChangeCodeWarning")}

+
+ + setNewCode(e.target.value)} disabled={saving} /> +
+ + ) : ( + <> +
+ + setForm((f) => ({ ...f, name: e.target.value }))} disabled={saving} /> +
+ {!form.id && ( +
+ + setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} /> +
+ )} +
+ + +
+ + )} + + + +
+
+
+ ); +} + +function CompaniesPageContent() { + const t = useT(); + const [companies, setCompanies] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [reloadKey, setReloadKey] = useState(0); + const [dialog, setDialog] = useState(null); + const [page, setPage] = useState(1); + const { tableRef, pageSize } = useFitPageSize(); + const size = pageSize ?? MIN_PAGE_SIZE; + + const refetch = useCallback(() => setReloadKey((k) => k + 1), []); + + useEffect(() => { + let cancelled = false; + // eslint-disable-next-line react-hooks/set-state-in-effect -- resets ahead of the reloadKey-triggered fetch below. + setLoading(true); + setError(null); + listAdminCompanies() + .then((result) => !cancelled && setCompanies(result)) + .catch((err: unknown) => !cancelled && setError(err instanceof Error && err.message ? err.message : t("CompLoadFailed"))) + .finally(() => !cancelled && setLoading(false)); + return () => { + cancelled = true; + }; + }, [reloadKey, t]); + + const columns = useMemo[]>( + () => [ + { accessorKey: "name", header: t("Name") }, + { accessorKey: "code", header: t("Code") }, + { + accessorKey: "status", + header: t("Status"), + cell: ({ row }) => ( + + {row.original.status === "A" ? t("CompActive") : t("CompInactive")} + + ), + }, + { + id: "actions", + header: t("CatActions"), + cell: ({ row }) => ( +
+ + +
+ ), + }, + ], + [t], + ); + + return ( + <> + setDialog({ mode: "form", company: NEW_COMPANY })}> +