From f97bf48d9380ed5ab8bcefe57d30c33c57117a7e Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 19:17:36 +0800 Subject: [PATCH 01/19] docs: propose add-admin-auth-users-roles (change 2) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-admin-auth-users-roles/.openspec.yaml | 2 + .../add-admin-auth-users-roles/design.md | 81 ++++++++++++ .../add-admin-auth-users-roles/proposal.md | 37 ++++++ .../specs/admin-access/spec.md | 121 ++++++++++++++++++ .../specs/admin-roles/spec.md | 48 +++++++ .../specs/admin-users/spec.md | 69 ++++++++++ .../add-admin-auth-users-roles/tasks.md | 48 +++++++ 7 files changed, 406 insertions(+) create mode 100644 openspec/changes/add-admin-auth-users-roles/.openspec.yaml create mode 100644 openspec/changes/add-admin-auth-users-roles/design.md create mode 100644 openspec/changes/add-admin-auth-users-roles/proposal.md create mode 100644 openspec/changes/add-admin-auth-users-roles/specs/admin-access/spec.md create mode 100644 openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md create mode 100644 openspec/changes/add-admin-auth-users-roles/specs/admin-users/spec.md create mode 100644 openspec/changes/add-admin-auth-users-roles/tasks.md diff --git a/openspec/changes/add-admin-auth-users-roles/.openspec.yaml b/openspec/changes/add-admin-auth-users-roles/.openspec.yaml new file mode 100644 index 0000000..7ed429c --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-26 diff --git a/openspec/changes/add-admin-auth-users-roles/design.md b/openspec/changes/add-admin-auth-users-roles/design.md new file mode 100644 index 0000000..6b686b5 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/design.md @@ -0,0 +1,81 @@ +# Design + +## Context + +- The admin portal in `solvway-admin-portal` is babyboo's full back office. Its kept screens call portal route handlers (`app/api/**`), which call `mobile-api` `/api/admin/**` through `callMobileApi` with the `api-key` header and the JWT as a Bearer token. The session is a sealed cookie (`bb_admin` by default). +- Co-Lite's `mobile-api` has no `/api/admin/**` controllers. `AppAccessAspect` checks the api-key and JWT signature and expiry only, so any valid token (member or admin) passes. +- Babyboo's `mobile-api` already solves this: `AdminAuthController`, `AdminUserController`, `AdminRoleController`, their services, `@AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin checks in its `AppAccessAspect`, with unit tests. Babyboo and Co-Lite share the Solvway base, and Co-Lite's `services-system` and `services-auth` already expose every downstream endpoint those services call except the module-management and group endpoints we drop. +- `services-auth` `POST /auth/authenticate` issues admin (type A) tokens and answers 200 with an empty body on failure. `/auth/findUserByToken/BO/{token}` returns the admin user with roles and ACL menu, and returns nothing for a token stored as logged out by `/auth/logoutToken/{token}` (Redis). +- `services-system` `/user/resetAdminPassword` takes username and email, checks they match an admin, sets a random 8-character password with login status N (change required), and emails it. +- Tastefully's module rows use area `A`; babyboo's portal reads area `BO` with names like `BO_USERS`. + +## Goals / Non-Goals + +**Goals:** +- Port, not rewrite: take babyboo's admin classes and tests, then cut what depends on dropped features. +- Every rule in the specs is pinned by a test before it is implemented (porting rule in `CLAUDE.md`). + +**Non-Goals:** +- Login throttling or lockout, session-policy timeouts, Google sign-in, user groups, module management, audit log, country scope. +- Changing member (customer-portal) auth. + +## Decisions + +### 1. Port babyboo's admin layer into `mobile-api`, trimmed + +Copy `AdminAuthController`, `AdminUserController`, `AdminRoleController`, their services and DTOs, `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard`, and the admin branch of babyboo's `AppAccessAspect` (`isAdminPath`, `isAdminToken`, revocation, session guard, `requireAdminModule`). Remove country scope, audit annotations, login-security and lockout handling, and anything that calls a dropped endpoint. Port the matching babyboo unit tests and adapt them; a dropped feature's tests go with it. + +Alternative: write admin controllers fresh against Tastefully's backoffice controllers. Rejected: the portal already speaks babyboo's contract, and babyboo's version has the guard and tests we need. + +### 2. Admin token check uses `findUserByToken/BO` + +On an `/api/admin/**` path the aspect loads the user with `/auth/findUserByToken/BO/{token}`. No user, or a non-admin user, means 403 for a valid member token and 401 for a revoked token. The same lookup gives the roles for the module check and the enabled and login-status flags for the session guard (deactivated means 401; pending password change allows only first-login and logout, otherwise 403). This is one downstream call per admin request. + +`ponytail:` no cache on this lookup; add a short-TTL cache keyed by token if admin latency matters. + +Alternative: a JWT claim for user type. Rejected: needs a `services-auth` change and still needs the lookup for revocation and deactivation. + +### 3. Wrong password becomes 401 in `mobile-api` + +`AdminAuthController.login` maps an empty token from `/auth/authenticate` to 401. `services-auth` stays as is, so other callers (customer portal) are unaffected. + +### 4. Forgot password reuses `/user/resetAdminPassword` + +New public endpoint `POST /api/admin/auth/forgot-password` (`@AppAuth(skipValidate=true)`) with `{username, email}`. It calls `/user/resetAdminPassword` and always answers 200 with no body detail. The admin-triggered reset (`POST /api/admin/users/{id}/resetPassword`) looks up the user and calls the same endpoint with that user's username and email. The portal gets a `/forgot-password` page (added to `PUBLIC_PATHS`) linked from the login page. + +The emailed password is plain text in the email body. That is Tastefully's existing behaviour, accepted for phase 1 because the user must change it at next login. + +### 5. Company + +`service-system` gets `company (id, name, created_at)` and `user.company_id BIGINT NULL` (nullable because member rows share the table). `services-system` `User` gains `companyId`. `AdminUserService.create` sets `companyId` from the logged-in admin, ignoring any value in the request. The seed sets company 1 on the dev admin. + +### 6. Co-Lite back-office modules + +Area `BO`, babyboo's id scheme: `40000000 BO_ROOT` (type R), `40700000 BO_USERS` (`/users`), `40800000 BO_ROLES` (`/roles`). Tastefully's area-`A` rows stay in the table and never show, because the portal reads area `BO`. The portal's `FIXED_PROTECTED_MODULE_NAMES` and `routeModules` are cut to the names that exist. + +### 7. Roles shown + +The role list hides `ROLE_MEMBER`. The local seed drops Tastefully's business roles (KYC, merchant, staff and the rest) and keeps `ROLE_SUPER_ADMIN` (1), `ROLE_ADMIN` (2) and `ROLE_MEMBER` (3). + +### 8. Portal cut-down + +Delete by directory: every `app/` route, `app/api/` family, `app/components/` folder and test not used by the kept screens (list in proposal). Then remove `package.json` dependencies with no remaining import. Rename the cookie default to `colite_admin` and replace babyboo branding strings. The kept-screen tests and the shell and middleware tests must stay green; i18n keys for removed screens go with them. + +### 9. Smoke check + +`local/smoke.sh` logs in through `POST :8080/api/admin/auth/login` and then calls `GET :8080/api/admin/me` and `GET :8080/api/admin/users`, replacing the gateway login. The service-counter read and the public call stay. + +## Risks / Trade-offs + +- [Anyone who knows a username and its email can reset that password, locking the user out until they read the email] → Accepted for phase 1 (staff-only, small team). The response never reveals a match. Throttling comes back with babyboo's login-security later. +- [The ported aspect is security code copied across codebases] → Each guard rule has a ported or new test, and the reviewer reads the whole aspect diff. +- [Deleting most of the portal breaks shared imports in ways tests miss] → `npm run build` and `npm run lint` must pass, not only `vitest`. +- [Plain-text temporary password in email] → Forced change at next login; revisit with real SMTP in change 5. + +## Migration Plan + +Additive SQL in `sql/` of this change, run against `service-system`: +1. `01-company.sql`: create `company`, add `user.company_id`, insert company 1. +2. `02-bo-modules.sql`: insert the three BO module rows. + +Nothing is deployed, so there is no live data. The same statements are mirrored into `local/seed/`. Rollback: drop the column, the table and the rows (`sql/99-rollback.sql`). diff --git a/openspec/changes/add-admin-auth-users-roles/proposal.md b/openspec/changes/add-admin-auth-users-roles/proposal.md new file mode 100644 index 0000000..91d7d28 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/proposal.md @@ -0,0 +1,37 @@ +# Proposal + +## Why + +Lead capture (change 4) needs staff to log in to the admin portal and needs Sales users to exist. Today the copied admin portal is babyboo's full back office, and `mobile-api` has no `/api/admin/**` endpoints, so nobody can log in. This change gives Co-Lite a working staff login, user management and role permissions: the base every later admin screen builds on. See `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md` (Admin portal, Access, Company id). + +## What Changes + +- **Admin portal cut down** to: login, first-login password change, forgot password, Users (list, create, edit, deactivate, assign roles, reset password), Roles (list, create, edit, edit permissions), the app shell with role-based menus, and the not-authorised page. Every other babyboo screen, API route, component and test is removed, along with dependencies only they used. +- **New forgot-password page** in the portal. It uses Tastefully's existing reset: username plus email, a temporary password is emailed, and the user must change it at next login. +- **`mobile-api` gains `/api/admin/**`**: auth (login, first-login, forgot password, logout, refresh), `me`, users, roles and role permissions. Ported from babyboo's AdminAuth, AdminUser and AdminRole controllers onto Co-Lite's existing `services-auth` and `services-system` endpoints. +- **Admin access enforcement** in `mobile-api`: on `/api/admin/**`, a non-admin token is rejected, a logged-out token is rejected, a pending first-login reset confines the token to the first-login endpoint, and each handler declares the modules it needs (`@AdminModule`), checked against the caller's roles. Super admin passes every module check. +- **Wrong-password login returns 401** at `/api/admin/auth/login` (today `services-auth` answers 200 with an empty body). +- **Company**: a `company` table and a `company_id` column on the admin `user` in `service-system`. New users get the creating admin's company. +- **Back-office modules**: Co-Lite's own BO module rows (root, Users, Roles) in `service-system`.`module`. SQL lives in this change folder and is mirrored in `local/seed/`. + +Not in this change: login lockout, session-policy and login-security screens, the module-management screen, user groups, audit log, Google sign-in (all babyboo features Co-Lite drops in phase 1). + +## Capabilities + +### New Capabilities +- `admin-access`: staff login, first-login password change, forgot password, logout, session, menus, and the rules that guard every `/api/admin/**` endpoint and admin portal page. +- `admin-users`: managing staff users (list, search, create, edit, deactivate, assign roles, reset password) and the company they belong to. +- `admin-roles`: managing roles and the back-office modules each role grants. + +### Modified Capabilities +None. + +## Impact + +- `solvway-admin-portal`: most of the tree is deleted; kept screens are adapted to Co-Lite (cookie name, module names, branding text). +- `solvway-mobile-api`: new admin controllers, services, `@AdminModule`, and admin checks in `AppAccessAspect`. +- `solvway-services-system`: `Company` entity, `User.companyId`, user save sets company. No new endpoints expected (the needed ones exist); any gap found is added in the task that needs it. +- `solvway-services-auth`: unchanged unless the admin token check needs it (see design). +- Database `service-system`: new table `company`, new column `user.company_id`, new `module` and `modules_roles` rows. Additive only. +- `local/seed/`: mirrors the SQL; `03-colite.sql` keeps creating the dev admin. +- `local/smoke.sh`: the admin login call moves to `/api/admin/auth/login` on mobile-api. diff --git a/openspec/changes/add-admin-auth-users-roles/specs/admin-access/spec.md b/openspec/changes/add-admin-auth-users-roles/specs/admin-access/spec.md new file mode 100644 index 0000000..e46c8d3 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/specs/admin-access/spec.md @@ -0,0 +1,121 @@ +# Spec Delta + +## Purpose + +Staff log in to the Co-Lite admin portal, and every admin page and `/api/admin/**` endpoint admits only active staff holding the module it needs. + +## ADDED Requirements + +### Requirement: Staff login + +The system SHALL let an active admin user log in with username and password through the admin portal, and SHALL return the user's name, roles, menu and whether a password change is required. + +#### Scenario: Correct credentials + +- **GIVEN** an active admin user `admin` with password `colite-dev-admin` +- **WHEN** they submit those credentials 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: Wrong password + +- **WHEN** a user submits a wrong password +- **THEN** `/api/admin/auth/login` responds 401 +- **AND** the login page shows an invalid-credentials message without saying whether the username exists + +#### 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: First-login password change + +The system SHALL require a user whose password is temporary (new user or reset) to set a new password before using any other admin page or endpoint. + +#### Scenario: Pending change confines the session + +- **GIVEN** a user logged in with a temporary password +- **WHEN** they open any portal page other than the password-change page +- **THEN** they are sent to the password-change page +- **AND** any `/api/admin/**` call other than first-login and logout responds 403 + +#### Scenario: Password changed + +- **GIVEN** a user on the password-change page +- **WHEN** they submit a new password that meets the password rules +- **THEN** the password is saved, the temporary flag clears, and they can use the portal + +### Requirement: Forgot password + +The system SHALL let a user request a temporary password by entering their username and email on a public forgot-password page. The response SHALL be the same whether or not the username and email match an active admin user. + +#### Scenario: Matching username and email + +- **GIVEN** an active admin user with username `sales1` and email `sales1@example.com` +- **WHEN** someone submits `sales1` and `sales1@example.com` +- **THEN** a temporary password is emailed to `sales1@example.com` +- **AND** the user must change it at next login +- **AND** the page shows "If the details match an account, we have emailed a temporary password." + +#### Scenario: Non-matching details + +- **WHEN** someone submits a username and email that do not match an active admin user +- **THEN** no password changes and no email is sent +- **AND** the page shows the same message as for a match + +### Requirement: Logout + +The system SHALL end the session on logout, and SHALL reject the logged-out token on every later `/api/admin/**` call even before it expires. + +#### Scenario: Token used after logout + +- **GIVEN** a user who logged out +- **WHEN** a request reuses their old token on `/api/admin/me` +- **THEN** it responds 401 + +### Requirement: Admin endpoint guard + +Every `/api/admin/**` endpoint except login and forgot password SHALL require a valid admin token, and SHALL require at least one of the back-office modules the endpoint declares, granted to one of the caller's roles. A user with the super admin role SHALL pass every module check. An endpoint that declares no module SHALL be denied to everyone except super admin. + +#### Scenario: No token + +- **WHEN** `/api/admin/users` is called without a token +- **THEN** it responds 401 + +#### Scenario: Member token on an admin path + +- **WHEN** a valid member token calls `/api/admin/me` +- **THEN** it responds 403 + +#### Scenario: Missing module + +- **GIVEN** an admin user whose roles do not grant `BO_USERS` +- **WHEN** they call `GET /api/admin/users` +- **THEN** it responds 403 + +#### Scenario: Granted module + +- **GIVEN** an admin user whose role grants `BO_USERS` +- **WHEN** they call `GET /api/admin/users` +- **THEN** it responds 200 + +### Requirement: Page guard + +The admin portal SHALL show a not-authorised page when a signed-in user opens a page whose module their roles do not grant, and SHALL send a signed-out visitor to the login page for every page except login and forgot password. + +#### Scenario: Signed-out visitor + +- **WHEN** a signed-out visitor opens `/users` +- **THEN** they are sent to the login page and return to `/users` after logging in + +#### Scenario: Page without the module + +- **GIVEN** a signed-in user without `BO_ROLES` +- **WHEN** they open `/roles` +- **THEN** the not-authorised page is shown and no role data is loaded diff --git a/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md b/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md new file mode 100644 index 0000000..8ac436c --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md @@ -0,0 +1,48 @@ +# Spec Delta + +## Purpose + +Admins with the Roles module define roles and choose which back-office modules each role grants, which controls the menus and endpoints its users reach. + +## ADDED Requirements + +### Requirement: Role list and edit + +The system SHALL let an admin with `BO_ROLES` list, create and rename admin roles. Role names SHALL be unique. The member role SHALL NOT appear in the list. + +#### Scenario: Create role + +- **WHEN** an admin with `BO_ROLES` creates role `ROLE_SALES` +- **THEN** it appears in the role list and can be assigned to users + +#### Scenario: Duplicate name + +- **GIVEN** role `ROLE_SALES` exists +- **WHEN** an admin creates another role named `ROLE_SALES` +- **THEN** the save is refused with a message + +### Requirement: Role permissions + +The system SHALL let an admin with `BO_ROLES` choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The super admin role's grants SHALL NOT be editable. + +#### Scenario: Grant Users module + +- **GIVEN** role `ROLE_SALES` without `BO_USERS` +- **WHEN** an admin grants `BO_USERS` to `ROLE_SALES` and saves +- **THEN** users with `ROLE_SALES` see Users in the sidebar after their next login or session refresh +- **AND** `GET /api/admin/users` responds 200 for them + +#### Scenario: Self lock-out + +- **GIVEN** the admin's only role that grants `BO_ROLES` is the role being edited +- **WHEN** they remove `BO_ROLES` from it and save +- **THEN** the save is refused with a message, so no admin loses access to role management by mistake + +### Requirement: Back-office module set + +The system SHALL hold Co-Lite's back-office modules in the module table, with a root entry and one entry per admin screen. This change SHALL add `BO_USERS` (Users) and `BO_ROLES` (Roles). Later changes add their own modules. + +#### Scenario: Seeded modules + +- **WHEN** the local stack starts from an empty database +- **THEN** the super admin's sidebar shows Users and Roles and no Tastefully back-office entries diff --git a/openspec/changes/add-admin-auth-users-roles/specs/admin-users/spec.md b/openspec/changes/add-admin-auth-users-roles/specs/admin-users/spec.md new file mode 100644 index 0000000..e7556db --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/specs/admin-users/spec.md @@ -0,0 +1,69 @@ +# Spec Delta + +## Purpose + +Admins with the Users module manage staff accounts: who can log in, which roles they hold, and which company they belong to. + +## ADDED Requirements + +### Requirement: User list + +The system SHALL list admin users only (never members), paginated on the server, searchable by name, username or email, filterable by active state, and sortable by column. + +#### Scenario: Search + +- **GIVEN** admin users `sales1` and `sales2` and a member `m100` +- **WHEN** an admin with `BO_USERS` searches for `sales` +- **THEN** the list shows `sales1` and `sales2` and not `m100` + +### Requirement: Create user + +The system SHALL let an admin with `BO_USERS` create an admin user with name, username, email and one or more roles. Username and email SHALL be unique. The new user SHALL receive a temporary password by email and SHALL belong to the creating admin's company. + +#### Scenario: New user + +- **WHEN** an admin creates user `sales1` with email `sales1@example.com` and role Sales +- **THEN** the user is saved as active with a pending password change +- **AND** a temporary password is emailed to `sales1@example.com` +- **AND** the user's company is the creating admin's company + +#### Scenario: Duplicate username + +- **GIVEN** a user `sales1` exists +- **WHEN** an admin creates another user with username `sales1` +- **THEN** the save is refused and the form shows that the username is taken + +### Requirement: Edit and deactivate user + +The system SHALL let an admin with `BO_USERS` change a user's name, email, roles and active state. A deactivated user SHALL NOT be able to log in, and a session they already hold SHALL be refused on its next `/api/admin/**` call. An admin SHALL NOT be able to deactivate their own account. + +#### Scenario: Deactivate + +- **GIVEN** user `sales1` is signed in +- **WHEN** an admin deactivates `sales1` +- **THEN** `sales1`'s next `/api/admin/**` call responds 401 +- **AND** `sales1` can no longer log in + +#### Scenario: Self-deactivation + +- **WHEN** an admin tries to deactivate their own account +- **THEN** the save is refused with a message + +### Requirement: Admin-triggered password reset + +The system SHALL let an admin with `BO_USERS` reset another user's password, which emails the user a temporary password and requires a change at next login. + +#### Scenario: Reset + +- **WHEN** an admin resets `sales1`'s password +- **THEN** `sales1`'s old password stops working +- **AND** a temporary password is emailed to `sales1`'s email address + +### Requirement: Company membership + +Every admin user SHALL belong to exactly one company. The company SHALL be set by the system from the creating admin, never from the request. + +#### Scenario: Company in the request is ignored + +- **WHEN** a create-user request carries a company id different from the admin's own +- **THEN** the new user gets the admin's company diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md new file mode 100644 index 0000000..7b4e0b7 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -0,0 +1,48 @@ +# Tasks + +Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most touch shared security code or build files. + +## 1. Database + +- [ ] 1.1 Write `sql/01-company.sql` (create `company`, add nullable `user.company_id`, insert company 1 'Co-Lite'), `sql/02-bo-modules.sql` (`40000000 BO_ROOT` R, `40700000 BO_USERS` `/users`, `40800000 BO_ROLES` `/roles`, area `BO`) and `sql/99-rollback.sql` in this change folder. Mirror them into `local/seed/` (`03-colite.sql` sets `company_id = 1` on the dev admin; `02-reference.sql` keeps only roles 1, 2, 3 and their `modules_roles` rows). Verify: `docker compose -f local/docker-compose.yml down -v && local/up.sh` exits 0, and a read-only SELECT shows the admin with company 1, the three BO modules and three roles. + - Scope: `openspec/changes/add-admin-auth-users-roles/sql/**`, `local/seed/**` + +## 2. services-system + +- [ ] 2.1 Add `companyId` to `services-system` `User` (column `company_id`) and make `/user/save` keep it. Test first: saving a user with `companyId` 1 and reading it back returns 1; saving an existing user without `companyId` does not clear it. Verify: `mvn -T 1C -pl solvway-services-system -am verify`. + - Scope: `solvway-services-system/src/**` + +## 3. mobile-api admin guard + +- [ ] 3.1 Port `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin branch of babyboo's `AppAccessAspect` (admin-path detection, admin-token check via `/auth/findUserByToken/BO/{token}`, revocation, deactivated and pending-reset handling, `requireAdminModule` with super-admin bypass, fail closed) into Co-Lite's `AppAccessAspect`, without country scope or audit. Port babyboo's tests for these classes and add tests for every `admin-access` "Admin endpoint guard" and "Logout" scenario plus: deactivated token gives 401, pending reset gives 403 except first-login and logout, undeclared handler denied to non-super admin. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. + - Scope: `solvway-mobile-api/src/main/java/**/useraccess/**`, `solvway-mobile-api/src/test/java/**/useraccess/**`, `solvway-mobile-api/src/main/resources/application*.yml` + +## 4. mobile-api admin auth + +- [ ] 4.1 Port babyboo's `AdminAuthController` and `AdminAuthenticationService` (login, first-login, logout, refresh, me) onto Co-Lite endpoints, and add `POST /api/admin/auth/forgot-password` calling `/user/resetAdminPassword`. Login answers 401 for an empty token, a deactivated user or a non-admin account; forgot-password always answers 200. Port babyboo's tests for these classes and add one per `admin-access` login, first-login and forgot-password scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. + - Scope: `solvway-mobile-api/src/**/controller/admin/**`, `solvway-mobile-api/src/**/service/admin/**`, `solvway-mobile-api/src/**/dto/admin/**` (or babyboo's equivalent packages) + +## 5. mobile-api users and roles + +- [ ] 5.1 Port `AdminUserController` and `AdminUserService`: admin-only list with search, filter and sort; create with temporary password, email and company from the logged-in admin; edit; deactivate with self-deactivation refused; admin-triggered reset via `/user/resetAdminPassword`. Tests first for each `admin-users` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. + - Scope: as 4.1 +- [ ] 5.2 Port `AdminRoleController`, `AdminRoleService` and `AdminAclService` (role list hiding `ROLE_MEMBER`, create and rename with unique names, `GET/PUT /roles/{id}/modules` replacing grants, self lock-out refused, super admin grants not editable). Tests first for each `admin-roles` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. + - Scope: as 4.1 + +## 6. Admin portal + +- [ ] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0. + - Scope: `solvway-admin-portal/**` +- [ ] 6.2 Add the `/forgot-password` page (public, linked from login) and its route handler calling `/api/admin/auth/forgot-password`, showing the fixed message for any outcome; make the users form refuse self-deactivation and show duplicate-username and lock-out errors from the API. Tests first (vitest) for each portal-visible scenario in the specs. Verify: `npm run lint && npm run build && npm test` exit 0. + - Scope: `solvway-admin-portal/**` + +## 7. Local stack and end-to-end check + +- [ ] 7.1 Update `local/smoke.sh` to log in via `POST :8080/api/admin/auth/login` and call `/api/admin/me` and `/api/admin/users` (keep the counter read and the public call); add the portal to the README run steps (`npm run dev` with `MOBILE_API_BASE_URL=http://localhost:8080` and the app key). Verify: fresh `local/up.sh` then `local/smoke.sh` prints `smoke: OK`. + - Scope: `local/smoke.sh`, `local/README.md`, `local/.env.example` +- [ ] 7.2 Drive the portal in a browser with Playwright against the local stack: login (correct and wrong password), first-login change for a new user, users list/create/edit/deactivate, roles create and grant `BO_USERS`, not-authorised page for a user without `BO_ROLES`, forgot-password message. Screenshots in the change folder's `verification/`. Only local dev data is created. Verify: each scenario observed as specified. + - Scope: `openspec/changes/add-admin-auth-users-roles/verification/**` + +## Workflow follow-up + +- Code review, PR to `main`, merge, then archive this change. -- 2.54.1 From 42071a850f5b0111677739a51ca5285d58b10e23 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 19:23:16 +0800 Subject: [PATCH 02/19] feat(db): company, user.company_id and Co-Lite back-office modules Change SQL in the OpenSpec change folder, mirrored into local/seed. Local seed keeps only roles 1-3; dev admin no longer needs a first-login change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/02-reference.sql | 6 +++--- local/seed/03-colite.sql | 20 ++++++++++++++----- .../sql/01-company.sql | 17 ++++++++++++++++ .../sql/02-bo-modules.sql | 9 +++++++++ .../sql/99-rollback.sql | 6 ++++++ .../add-admin-auth-users-roles/tasks.md | 2 +- 6 files changed, 51 insertions(+), 9 deletions(-) create mode 100644 openspec/changes/add-admin-auth-users-roles/sql/01-company.sql create mode 100644 openspec/changes/add-admin-auth-users-roles/sql/02-bo-modules.sql create mode 100644 openspec/changes/add-admin-auth-users-roles/sql/99-rollback.sql diff --git a/local/seed/02-reference.sql b/local/seed/02-reference.sql index 07378b5..1c81b24 100644 --- a/local/seed/02-reference.sql +++ b/local/seed/02-reference.sql @@ -163,7 +163,7 @@ UNLOCK TABLES; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'ROLE_SUPER_ADMIN',NULL,1,'ROLE_SUPER_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(2,'ROLE_ADMIN',1,2,'ROLE_SUPER_ADMIN/ROLE_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(3,'ROLE_MEMBER',NULL,1,'ROLE_MEMBER','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(4,'ROLE_HQ',1,3,'ROLE_SUPER_ADMIN/ROLE_ADMIN/ROLE_HQ','admin','2020-01-01 00:00:00','admin','2021-03-18 01:46:43'),(31,'ROLE_KYC',42,3,'ROLE_SUPER_ADMIN/ROLE_TEMP_DELETE/ROLE_KYC','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(32,'ROLE_MERCHANT',NULL,1,'ROLE_MERCHANT','admin','2020-01-01 00:00:00','admin','2023-05-12 02:26:10'),(71,'ROLE_MERCHANT_ADMIN',32,2,'ROLE_MERCHANT/ROLE_MERCHANT_ADMIN','admin','2020-01-01 00:00:00','admin','2023-05-12 02:26:10'),(91,'ROLE_MERCHANT_BASIC',71,3,'ROLE_MERCHANT/ROLE_MERCHANT_ADMIN/ROLE_MERCHANT_BASIC','admin','2021-10-21 11:00:00','admin','2023-05-12 02:26:10'),(99,'ROLE_IT',1,2,'ROLE_SUPER_ADMIN/ROLE_IT','solvwayadm','2022-04-05 12:57:42','solvwayadm','2022-04-05 04:57:41'),(110,'ROLE_TASTEFULLY',1,2,'ROLE_SUPER_ADMIN/ROLE_TASTEFULLY','bryanlee','2023-06-01 17:44:58','bryanlee','2024-08-20 05:40:39'),(111,'ROLE_STAFF',1,2,'ROLE_SUPER_ADMIN/ROLE_STAFF','admin','2024-08-20 11:40:29','admin','2024-08-20 05:31:41'),(112,'ROLE_MERC',1,2,'ROLE_SUPER_ADMIN/ROLE_MERC','admin','2024-08-20 14:25:16','admin','2024-08-20 06:25:15'),(113,'ROLE_REGISTEREXHIBITOR (cancel) ',99,3,'ROLE_SUPER_ADMIN/ROLE_IT/ROLE_REGISTEREXHIBITOR (cancel) ','admin','2024-08-23 16:00:19','admin','2024-08-28 02:26:29'),(114,'ROLE_KAYZ',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_KAYZ','Staff','2024-08-23 16:14:23','Staff1','2024-09-26 08:52:44'),(115,'ROLE_TESTING REGISTER',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_TESTING REGISTER','Staff1','2024-08-28 11:36:14','Staff1','2024-08-28 03:36:14'),(116,'ROLE_GWP',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_GWP','Staff1','2024-09-26 13:38:05','Staff1','2024-09-26 05:38:04'),(117,'ROLE_LUCKYDRAW',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_LUCKYDRAW','Staff1','2024-09-26 15:16:59','Staff1','2024-09-26 07:16:59'),(118,'ROLE_EVENT OPERATION',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_EVENT OPERATION','Staff1','2024-09-26 16:52:09','Staff1','2026-04-29 09:03:25'),(119,'ROLE_TSC MEMBER REDEMPTION',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_TSC MEMBER REDEMPTION','Staff1','2025-06-24 18:45:54','Staff1','2025-06-25 14:35:48'),(120,'ROLE_MAIN_DASHBOARD',1,2,'ROLE_SUPER_ADMIN/ROLE_MAIN_DASHBOARD','bryanlee','2023-06-01 17:44:58','bryanlee','2024-08-20 05:40:39'); +INSERT INTO `role` VALUES (1,'ROLE_SUPER_ADMIN',NULL,1,'ROLE_SUPER_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(2,'ROLE_ADMIN',1,2,'ROLE_SUPER_ADMIN/ROLE_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(3,'ROLE_MEMBER',NULL,1,'ROLE_MEMBER','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -272,7 +272,7 @@ UNLOCK TABLES; LOCK TABLES `user_group_roles` WRITE; /*!40000 ALTER TABLE `user_group_roles` DISABLE KEYS */; -INSERT INTO `user_group_roles` VALUES (4,2),(8,32),(4,110),(9,110),(5,111),(7,111),(6,112),(7,114); +INSERT INTO `user_group_roles` VALUES (4,2); /*!40000 ALTER TABLE `user_group_roles` ENABLE KEYS */; UNLOCK TABLES; @@ -282,7 +282,7 @@ UNLOCK TABLES; LOCK TABLES `modules_roles` WRITE; /*!40000 ALTER TABLE `modules_roles` DISABLE KEYS */; -INSERT INTO `modules_roles` VALUES (12010010,99),(12010010,100),(12010010,101),(12010010,110),(12010100,99),(12010100,100),(12010100,101),(12010100,110),(12010100,111),(12010100,114),(12010100,118),(12010100,119),(12010110,99),(12010110,100),(12010110,101),(12010110,110),(12010110,111),(12010120,99),(12010120,100),(12010120,101),(12010120,110),(12010120,111),(12010400,99),(12010400,100),(12010400,101),(12010500,99),(12010500,100),(12010500,101),(12010500,110),(12010790,110),(12010800,99),(12010800,100),(12010800,101),(12010800,110),(12010900,99),(12010900,100),(12010900,101),(12010900,110),(12011200,99),(12011200,100),(12011200,101),(12011200,110),(12011300,99),(12011300,100),(12011300,101),(12011400,99),(12011400,100),(12011400,101),(12011400,110),(12011901,99),(12011901,100),(12011901,101),(12011901,110),(12020100,99),(12020100,100),(12020100,101),(12020100,110),(12020200,99),(12020200,100),(12020200,101),(12020300,99),(12020300,100),(12020300,101),(12020300,110),(12020400,99),(12020400,100),(12020400,101),(12020400,110),(12020500,99),(12020500,100),(12020500,101),(12020500,110),(12610100,99),(12610100,100),(12610100,101),(12610100,109),(12610100,111),(12610100,113),(12610100,115),(12610200,99),(12610200,100),(12610200,101),(12610200,109),(12610200,111),(12610200,113),(12610200,115),(12610210,99),(12610210,100),(12610210,101),(12610210,109),(12610210,111),(12610210,113),(12610210,115),(12610300,99),(12610300,100),(12610300,101),(12610300,109),(12610300,111),(12610300,113),(12610300,115),(12610400,99),(12610400,100),(12610400,101),(12610400,109),(12610400,111),(12610400,113),(12610400,115),(12610405,109),(12610500,99),(12610500,100),(12610500,101),(12610500,109),(12610500,111),(12610500,113),(12610500,115),(12610540,111),(12610550,111),(12610600,99),(12620100,99),(12620200,99),(12620300,99),(12620400,99),(12630006,99),(12630006,100),(12630006,101),(12700100,111),(12700100,114),(12700100,117),(12700100,118),(12700200,111),(12700200,114),(12700200,117),(12700200,118),(12700300,111),(12700300,114),(12700300,117),(12700300,118),(12700400,111),(12700400,114),(12700400,117),(12700400,118),(12700500,111),(12700500,114),(12700500,117),(12700500,118),(12700505,111),(12700510,111),(12700510,114),(12700510,117),(12700510,118),(12700520,111),(12700520,114),(12700520,117),(12700520,118),(12700530,111),(12700530,114),(12700530,116),(12700530,117),(12700530,118),(12700600,111),(12700600,114),(12700600,118),(12700600,119),(12700700,111),(12700700,114),(12700700,118),(12700700,119),(12700800,111),(12700800,114),(12700800,118),(12700800,119),(13000010,110),(13010200,99),(13010200,100),(13010200,101),(13010200,110),(13010220,110),(13010400,99),(13010400,100),(13010400,101),(13010400,109),(13010400,110),(13010994,110),(13015100,101),(13015100,109),(13015100,110),(13015200,99),(13015200,100),(13015200,101),(13015200,110),(13015360,110),(13015370,110),(14010100,99),(14010100,100),(14010100,101),(14020100,99),(14020100,100),(14020100,101),(14020200,99),(14020200,100),(14020200,101),(14020300,99),(14020300,100),(14020300,101),(14020350,99),(14020350,100),(14020350,101),(14020400,99),(14020400,100),(14020400,101),(14020450,99),(14020450,100),(14020450,101),(14020500,99),(14020500,100),(14020500,101),(14020510,99),(14020510,100),(14020510,101),(14080100,99),(14080100,100),(14080100,101),(14090100,99),(14090100,100),(14090100,101),(14090200,99),(14090200,100),(14090200,101),(15010100,99),(15010100,100),(15010100,109),(15010100,110),(15010200,99),(15010200,100),(15010200,109),(15010200,110),(15010300,99),(15010300,100),(15010300,109),(15010300,110),(15010400,99),(15010400,100),(15010400,110),(15020100,99),(15020100,100),(15020100,101),(15020100,110),(15030100,110),(15030200,110),(15030300,110),(15030400,110),(15031500,110),(15031600,110),(15031700,110),(15031800,110),(15031910,110),(15032100,110),(15032200,110),(15032300,110),(15032400,110),(15041000,111),(15041000,112),(15041000,114),(15042000,111),(15042000,112),(15043000,111),(15043000,112),(15043000,114),(15043000,119),(15600200,99),(15600200,100),(15600200,101),(15600410,99),(15600410,100),(15600410,101),(15600415,99),(15600415,100),(15600415,101),(15600610,99),(15600610,100),(15600610,101),(15600620,99),(15600620,100),(15600620,101),(16010100,101),(16010200,101),(16030100,110),(16030200,110),(16030300,110),(19010100,99),(19010100,100),(19010100,101),(19010100,110),(19010200,99),(19010200,100),(19010200,101),(19010200,110),(19010200,111),(19010310,99),(19010310,100),(19010310,101),(19010310,110),(19010310,111),(19010315,99),(19010315,100),(19010315,101),(19010315,110),(19010315,111),(19010320,99),(19010320,100),(19010320,101),(19010320,110),(19010320,111),(19010321,99),(19010321,100),(19010321,101),(19010321,110),(19010321,111),(19020100,99),(19020100,100),(19020100,101),(19020100,110),(19020100,111),(19020200,99),(19020200,100),(19020200,101),(19020200,110),(19020200,111),(19020300,99),(19020300,100),(19020300,101),(19020300,110),(19020300,111),(19035100,99),(19035100,100),(19035100,101),(19035200,99),(19035200,100),(19035200,101),(19035300,99),(19035300,100),(19035300,101),(19035400,99),(19035400,100),(19035400,101),(19035510,99),(19035510,100),(19035510,101),(19035520,99),(19035520,100),(19035520,101),(19040100,99),(19040100,100),(19040100,101),(19050100,99),(19050100,100),(19050100,101),(19050200,99),(19050200,100),(19050200,101),(19050300,99),(19050300,100),(19050300,101),(19050400,99),(19050400,100),(19050400,101),(19050500,99),(19050500,100),(19050500,101),(19055110,99),(19055110,100),(19055110,101),(19055110,109),(19055210,99),(19055210,100),(19055210,101),(19055210,109),(19055210,110),(19055220,99),(19055220,100),(19055220,101),(19055220,109),(19055220,110),(19055310,99),(19055310,100),(19055310,101),(19055310,109),(19055310,110),(19055320,99),(19055320,100),(19055320,101),(19055320,109),(19055320,110),(19055410,99),(19055410,100),(19055410,101),(19055410,110),(19055420,99),(19055420,100),(19055420,101),(19055420,110),(19055430,99),(19055430,100),(19055430,101),(19055430,109),(19055430,110),(19055440,99),(19055440,100),(19055440,101),(19055440,109),(19055440,110),(19056100,110),(19057100,110),(19058100,110),(19058200,110),(19060100,99),(19060100,100),(19060100,101),(19060100,111),(19060110,99),(19060110,100),(19060110,101),(19060110,111),(19060120,99),(19060120,100),(19060120,101),(19060120,111),(19060200,99),(19060200,100),(19060200,101),(19060200,111),(19060300,99),(19060300,100),(19060300,101),(19070110,99),(19070110,100),(19070110,101),(19070110,109),(19070110,110),(19070120,99),(19070120,100),(19070120,101),(19070120,109),(19070120,110),(19090100,99),(19090100,100),(19090100,101),(19090100,109),(19090100,110),(19090110,99),(19090110,100),(19090110,101),(19090110,109),(19090110,110),(19090120,99),(19090120,100),(19090120,101),(19090120,109),(19090120,110),(19090320,99),(19090320,100),(19090320,101),(19090320,109),(19090320,110),(19090330,99),(19090330,100),(19090330,101),(19090330,109),(19090330,110),(19090720,99),(19090720,100),(19090720,101),(19090720,109),(19090720,110),(19090730,99),(19090730,100),(19090730,101),(19090730,109),(19090730,110),(19090843,110),(19090843,111),(19090851,99),(19090851,100),(19090851,101),(19090851,111),(19090852,31),(19090852,99),(19090852,100),(19090852,101),(19090852,111),(19090871,99),(19090871,100),(19090871,101),(19090872,99),(19090872,100),(19090872,101),(19090873,99),(19090873,100),(19090873,101),(19090874,99),(19090874,100),(19090874,101),(19090875,99),(19090875,100),(19090875,101),(19090881,110),(19090881,111),(19090881,114),(19090881,118),(19090910,99),(19090910,100),(19090910,101),(19091010,99),(19091010,100),(19091010,101),(19091021,99),(19091021,100),(19091021,101),(19091022,99),(19091022,100),(19091022,101),(19091110,109),(19091110,110),(19091110,111),(19091120,109),(19091120,110),(19091120,111),(19091610,111),(19091620,111),(19091630,111),(19091710,111),(19091720,111),(19091730,111),(19999998,99),(19999999,99),(19999999,100),(19999999,101),(20090000,3),(20100100,3),(20100200,3),(20100300,3),(20100400,3),(20200100,3),(20300400,3),(20401100,3),(20401200,3),(20500200,3),(20600000,3),(20610000,3),(20620000,3),(20700100,3),(20700200,3),(20700300,3),(20700600,3),(20800100,3),(20800200,3),(20800300,3),(30700000,91),(36000000,91),(36010000,91),(38000000,91),(38000100,91); +INSERT INTO `modules_roles` VALUES (20090000,3),(20100100,3),(20100200,3),(20100300,3),(20100400,3),(20200100,3),(20300400,3),(20401100,3),(20401200,3),(20500200,3),(20600000,3),(20610000,3),(20620000,3),(20700100,3),(20700200,3),(20700300,3),(20700600,3),(20800100,3),(20800200,3),(20800300,3); /*!40000 ALTER TABLE `modules_roles` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index 57af24a..d25b23e 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -1,17 +1,27 @@ --- Local dev only. One company and one admin login. +-- Local dev only. Applies the change SQL (company, BO modules) and creates one admin login. -- Admin login: admin / colite-dev-admin (dev password, documented in local/README.md). --- The company table and user.company_id for real environments are added by the admin-auth change (change 2). +-- Keep the statements below in step with openspec/changes/*/sql/ (and the archive once archived). USE `service-system`; -CREATE TABLE IF NOT EXISTS `company` ( + +-- add-admin-auth-users-roles/sql/01-company.sql +CREATE TABLE `company` ( `id` bigint NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `company` (`id`, `name`) VALUES (1, 'Co-Lite'); +ALTER TABLE `user` ADD COLUMN `company_id` bigint NULL; +-- add-admin-auth-users-roles/sql/02-bo-modules.sql +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40000000, 'BO_ROOT', 'Back Office', 'BO', 'R', 0, NULL, NULL), + (40700000, 'BO_USERS', 'Users', 'BO', 'M', 40000000, '/users', 'UserCog'), + (40800000, 'BO_ROLES', 'Roles', 'BO', 'M', 40000000, '/roles', 'ShieldCheck'); + +-- Dev admin: super admin, company 1, password already set (login 'Y', no first-login change). INSERT INTO `user` (`id`, `email`, `enabled`, `name`, `password`, `username`, `groupid`, `branchid`, - `login`, `status`, `type`, `create_by`, `create_date`, `done_by`) + `login`, `status`, `type`, `create_by`, `create_date`, `done_by`, `company_id`) VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 0, - 'N', 'Y', 'A', 'seed', NOW(), 'seed'); + 'Y', 'Y', 'A', 'seed', NOW(), 'seed', 1); INSERT INTO `users_roles` (`user_id`, `role_id`) VALUES (1, 1); diff --git a/openspec/changes/add-admin-auth-users-roles/sql/01-company.sql b/openspec/changes/add-admin-auth-users-roles/sql/01-company.sql new file mode 100644 index 0000000..4c0bd00 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/sql/01-company.sql @@ -0,0 +1,17 @@ +-- Co-Lite change 2: company and user.company_id. Target: `service-system`. Additive only. Run once. +USE `service-system`; + +CREATE TABLE `company` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +INSERT INTO `company` (`id`, `name`) VALUES (1, 'Co-Lite'); + +-- Nullable: member rows share the `user` table and have no company. +ALTER TABLE `user` ADD COLUMN `company_id` bigint NULL; + +-- Every existing admin belongs to the one company. +UPDATE `user` SET `company_id` = 1 WHERE `type` = 'A'; diff --git a/openspec/changes/add-admin-auth-users-roles/sql/02-bo-modules.sql b/openspec/changes/add-admin-auth-users-roles/sql/02-bo-modules.sql new file mode 100644 index 0000000..2c0b197 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/sql/02-bo-modules.sql @@ -0,0 +1,9 @@ +-- Co-Lite change 2: back-office modules read by the admin portal (area BO). +-- Target: `service-system`.`module`. Additive only. Run once. +-- ROLE_SUPER_ADMIN (id 1) passes every module check and needs no modules_roles rows. +USE `service-system`; + +INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES + (40000000, 'BO_ROOT', 'Back Office', 'BO', 'R', 0, NULL, NULL), + (40700000, 'BO_USERS', 'Users', 'BO', 'M', 40000000, '/users', 'UserCog'), + (40800000, 'BO_ROLES', 'Roles', 'BO', 'M', 40000000, '/roles', 'ShieldCheck'); diff --git a/openspec/changes/add-admin-auth-users-roles/sql/99-rollback.sql b/openspec/changes/add-admin-auth-users-roles/sql/99-rollback.sql new file mode 100644 index 0000000..81368a2 --- /dev/null +++ b/openspec/changes/add-admin-auth-users-roles/sql/99-rollback.sql @@ -0,0 +1,6 @@ +-- Rollback for 01-company.sql and 02-bo-modules.sql. +USE `service-system`; +DELETE FROM `modules_roles` WHERE `module_id` IN (40000000, 40700000, 40800000); +DELETE FROM `module` WHERE `id` IN (40000000, 40700000, 40800000); +ALTER TABLE `user` DROP COLUMN `company_id`; +DROP TABLE `company`; diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index 7b4e0b7..78caa09 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -4,7 +4,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 1. Database -- [ ] 1.1 Write `sql/01-company.sql` (create `company`, add nullable `user.company_id`, insert company 1 'Co-Lite'), `sql/02-bo-modules.sql` (`40000000 BO_ROOT` R, `40700000 BO_USERS` `/users`, `40800000 BO_ROLES` `/roles`, area `BO`) and `sql/99-rollback.sql` in this change folder. Mirror them into `local/seed/` (`03-colite.sql` sets `company_id = 1` on the dev admin; `02-reference.sql` keeps only roles 1, 2, 3 and their `modules_roles` rows). Verify: `docker compose -f local/docker-compose.yml down -v && local/up.sh` exits 0, and a read-only SELECT shows the admin with company 1, the three BO modules and three roles. +- [x] 1.1 Write `sql/01-company.sql` (create `company`, add nullable `user.company_id`, insert company 1 'Co-Lite'), `sql/02-bo-modules.sql` (`40000000 BO_ROOT` R, `40700000 BO_USERS` `/users`, `40800000 BO_ROLES` `/roles`, area `BO`) and `sql/99-rollback.sql` in this change folder. Mirror them into `local/seed/` (`03-colite.sql` sets `company_id = 1` on the dev admin; `02-reference.sql` keeps only roles 1, 2, 3 and their `modules_roles` rows). Verify: `docker compose -f local/docker-compose.yml down -v && local/up.sh` exits 0, and a read-only SELECT shows the admin with company 1, the three BO modules and three roles. - Scope: `openspec/changes/add-admin-auth-users-roles/sql/**`, `local/seed/**` ## 2. services-system -- 2.54.1 From 72b724f4680f3857e9ad908a817583e2c2b7c3d6 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 19:25:07 +0800 Subject: [PATCH 03/19] feat(system): user companyId, kept on update when the request omits it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-admin-auth-users-roles/tasks.md | 2 +- .../system/controller/UserController.java | 3 ++ .../solvway/services/system/model/User.java | 2 + .../controller/UserControllerCompanyTest.java | 54 +++++++++++++++++++ 4 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerCompanyTest.java diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index 78caa09..0062123 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -9,7 +9,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 2. services-system -- [ ] 2.1 Add `companyId` to `services-system` `User` (column `company_id`) and make `/user/save` keep it. Test first: saving a user with `companyId` 1 and reading it back returns 1; saving an existing user without `companyId` does not clear it. Verify: `mvn -T 1C -pl solvway-services-system -am verify`. +- [x] 2.1 Add `companyId` to `services-system` `User` (column `company_id`) and make `/user/save` keep it. Test first: saving a user with `companyId` 1 and reading it back returns 1; saving an existing user without `companyId` does not clear it. Verify: `mvn -T 1C -pl solvway-services-system -am verify`. - Scope: `solvway-services-system/src/**` ## 3. mobile-api admin guard 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 d848bac..ccc6bb4 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 @@ -302,6 +302,9 @@ public class UserController { if(user.getId()!=null) { User persistedUser = findByIdWithPassword(user.getId()); user.setPassword(persistedUser.getPassword()); + if(user.getCompanyId() == null) { + user.setCompanyId(persistedUser.getCompanyId()); + } } if(user.getLogin() != null) { user.setLogin(user.getLogin()); 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 4d17246..9fc02c2 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 @@ -129,6 +129,8 @@ public class User { private String master; + private Long companyId; + @Transient private List linkedAccounts; diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerCompanyTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerCompanyTest.java new file mode 100644 index 0000000..46e8946 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerCompanyTest.java @@ -0,0 +1,54 @@ +package com.solvway.services.system.controller; + +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.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UserControllerCompanyTest { + + @Mock + private UserService userService; + @InjectMocks + private UserController controller; + + @Test + void newUserKeepsCompanyFromRequest() { + User user = new User(); + user.setCompanyId(1L); + when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); + + User saved = controller.save(user); + + assertThat(saved.getCompanyId()).isEqualTo(1L); + } + + @Test + void updateWithoutCompanyKeepsPersistedCompany() { + User persisted = new User(); + persisted.setId(7L); + persisted.setCompanyId(1L); + when(userService.findById(7L)).thenReturn(Optional.of(persisted)); + when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0)); + + User update = new User(); + update.setId(7L); + controller.save(update); + + ArgumentCaptor saved = ArgumentCaptor.forClass(User.class); + verify(userService).save(saved.capture()); + assertThat(saved.getValue().getCompanyId()).isEqualTo(1L); + } +} -- 2.54.1 From 0a990cbcaf70bd87a87aeed26cdaf12a9f83124c Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 19:44:03 +0800 Subject: [PATCH 04/19] feat(mobile-api): admin guard on /api/admin/** (admin token, session state, module grants) Ported from babyboo: @AdminModule, AdminModuleAccess, AdminSessionGuard and the admin branch of AppAccessAspect. Adds the BO area, and services-auth findUserByToken now returns no user for a logged-out token. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-admin-auth-users-roles/tasks.md | 2 +- .../com/solvway/core/enums/GeneralEnum.java | 2 +- .../CodedResponseStatusException.java | 24 ++ .../service/AdminAuthenticationService.java | 23 ++ .../mobile/api/useraccess/AdminModule.java | 30 ++ .../api/useraccess/AdminModuleAccess.java | 34 ++ .../api/useraccess/AdminSessionGuard.java | 31 ++ .../api/useraccess/AppAccessAspect.java | 110 +++++- .../admin/AdminControllerPointcutTest.java | 30 ++ .../AdminAuthenticationServiceTest.java | 43 +++ .../api/useraccess/AdminModuleAccessTest.java | 60 +++ .../api/useraccess/AdminSessionGuardTest.java | 86 +++++ .../useraccess/AppAccessAspectAdminTest.java | 342 ++++++++++++++++++ .../JwtAuthenticationController.java | 4 + .../FindUserByTokenRevocationTest.java | 35 ++ .../system/constant/SystemConstants.java | 2 +- 16 files changed, 850 insertions(+), 8 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/errorhandler/CodedResponseStatusException.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminControllerPointcutTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminModuleAccessTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java create mode 100644 solvway-services-auth/src/test/java/com/solvway/services/auth/controller/FindUserByTokenRevocationTest.java diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index 0062123..d04e049 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -14,7 +14,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 3. mobile-api admin guard -- [ ] 3.1 Port `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin branch of babyboo's `AppAccessAspect` (admin-path detection, admin-token check via `/auth/findUserByToken/BO/{token}`, revocation, deactivated and pending-reset handling, `requireAdminModule` with super-admin bypass, fail closed) into Co-Lite's `AppAccessAspect`, without country scope or audit. Port babyboo's tests for these classes and add tests for every `admin-access` "Admin endpoint guard" and "Logout" scenario plus: deactivated token gives 401, pending reset gives 403 except first-login and logout, undeclared handler denied to non-super admin. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. +- [x] 3.1 Port `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin branch of babyboo's `AppAccessAspect` (admin-path detection, admin-token check via `/auth/findUserByToken/BO/{token}`, revocation, deactivated and pending-reset handling, `requireAdminModule` with super-admin bypass, fail closed) into Co-Lite's `AppAccessAspect`, without country scope or audit. Port babyboo's tests for these classes and add tests for every `admin-access` "Admin endpoint guard" and "Logout" scenario plus: deactivated token gives 401, pending reset gives 403 except first-login and logout, undeclared handler denied to non-super admin. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: `solvway-mobile-api/src/main/java/**/useraccess/**`, `solvway-mobile-api/src/test/java/**/useraccess/**`, `solvway-mobile-api/src/main/resources/application*.yml` ## 4. mobile-api admin auth diff --git a/solvway-core-libs/src/main/java/com/solvway/core/enums/GeneralEnum.java b/solvway-core-libs/src/main/java/com/solvway/core/enums/GeneralEnum.java index 7d6d24a..2db3ab4 100644 --- a/solvway-core-libs/src/main/java/com/solvway/core/enums/GeneralEnum.java +++ b/solvway-core-libs/src/main/java/com/solvway/core/enums/GeneralEnum.java @@ -8,7 +8,7 @@ public class GeneralEnum { @Getter public enum Area { - A("ADMIN"), M("MEMBER"), P("PUBLIC"), B("STOCKIST"), AP("APPS"); + A("ADMIN"), M("MEMBER"), P("PUBLIC"), B("STOCKIST"), AP("APPS"), BO("BACKOFFICE_PORTAL"); private final String name; Area(String name) { diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/errorhandler/CodedResponseStatusException.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/errorhandler/CodedResponseStatusException.java new file mode 100644 index 0000000..0cfedc5 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/errorhandler/CodedResponseStatusException.java @@ -0,0 +1,24 @@ +package com.solvway.mobile.api.errorhandler; + +import org.springframework.http.HttpStatusCode; +import org.springframework.web.server.ResponseStatusException; + +/** + * A {@link ResponseStatusException} carrying a machine-readable {@code code} on its ProblemDetail + * body, so the admin portal can act on it (e.g. {@code PASSWORD_RESET_REQUIRED} sends the user to + * the password-change page). Ported from babyboo, without the details map. + */ +public class CodedResponseStatusException extends ResponseStatusException { + + private final String code; + + public CodedResponseStatusException(HttpStatusCode status, String reason, String code) { + super(status, reason); + this.code = code; + getBody().setProperty("code", code); + } + + public String getCode() { + return code; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java new file mode 100644 index 0000000..6819ced --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java @@ -0,0 +1,23 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.mobile.api.constant.api.RestApiAuthServiceConstants; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class AdminAuthenticationService { + private final RestTemplateCustomUtil restTemplateUtil; + + /** Admin user for a live token, or null (services-auth returns null for a logged-out token). */ + public User loadUserByToken(String token) { + ResponseEntity ent = restTemplateUtil.getForEntity( + restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_SYSTEM_GET_USER_BYTOKEN), + User.class, "BO", token); + return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java new file mode 100644 index 0000000..5f54f2e --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModule.java @@ -0,0 +1,30 @@ +package com.solvway.mobile.api.useraccess; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Declares which BO module(s) an {@code /api/admin/**} handler needs. {@code AppAccessAspect} + * allows a caller holding any one of them (or super-admin, role id 1). A method-level + * declaration wins over the class-level one; an undeclared handler grants nothing to non-super + * admins. {@link #ANY_ADMIN} means any authenticated admin. + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.TYPE}) +public @interface AdminModule { + + String ANY_ADMIN = "ANY_ADMIN"; + + String[] value(); + + /** + * Lets an admin whose first-login password change is pending ({@code login = N}) through. Only + * for the first-login and logout handlers; every other admin handler answers 403 while pending. + * Read from the method annotation only; ignored on a class. + */ + boolean allowPendingReset() default false; +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java new file mode 100644 index 0000000..33ffb11 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminModuleAccess.java @@ -0,0 +1,34 @@ +package com.solvway.mobile.api.useraccess; + +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.ResponseEntity; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +public final class AdminModuleAccess { + + private static final String MODULES_BY_AREA = "/module/findAllByArea/{area}"; + + private AdminModuleAccess() { + } + + /** True when one of {@code roleIds} is granted any of the named BO modules. */ + public static boolean grantedAny(RestTemplateCustomUtil restTemplateUtil, Set roleIds, String... moduleNames) { + if (moduleNames.length == 0) { + return false; + } + Set wanted = Set.of(moduleNames); + ResponseEntity>> ent = restTemplateUtil.getForEntity( + restTemplateUtil.getURLforApiService(MODULES_BY_AREA), + new ParameterizedTypeReference>>() {}, "BO"); + List> modules = ent.getBody() != null ? ent.getBody() : List.of(); + return modules.stream() + .filter(m -> m.get("name") instanceof String name && wanted.contains(name)) + .anyMatch(m -> m.get("roles") instanceof List roles && roles.stream() + .anyMatch(r -> r instanceof Map rm && rm.get("id") instanceof Number n + && roleIds.contains(n.longValue()))); + } +} 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 new file mode 100644 index 0000000..394f6e5 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AdminSessionGuard.java @@ -0,0 +1,31 @@ +package com.solvway.mobile.api.useraccess; + +import com.solvway.core.enums.GeneralEnum.LoginStatus; +import com.solvway.core.model.User; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.service.AdminAuthenticationService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ResponseStatusException; + +/** Per-request admin session state. Not cached, so logout and deactivation bite on the next call. */ +@Component +@RequiredArgsConstructor +public class AdminSessionGuard { + private final AdminAuthenticationService adminAuthenticationService; + + public User check(String jwt, boolean allowPendingReset) { + User user = adminAuthenticationService.loadUserByToken(jwt); + if (user == null) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token"); + } + if (!user.isEnabled()) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Account disabled"); + } + if (user.getLogin() == LoginStatus.N && !allowPendingReset) { + throw new CodedResponseStatusException(HttpStatus.FORBIDDEN, "Password change required", "PASSWORD_RESET_REQUIRED"); + } + return user; + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java index 68932d3..252e6a2 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java @@ -4,6 +4,8 @@ import com.google.cloud.spring.pubsub.core.PubSubTemplate; import com.solvway.core.annotation.AppAuth; import com.solvway.core.enums.GeneralEnum.CmsPlatform; import com.solvway.core.enums.GeneralEnum.FlagYesNo; +import com.solvway.core.enums.JwtEnum.JwtCustomClaim; +import com.solvway.core.model.Role; import com.solvway.core.model.ResponseTime; import com.solvway.core.model.User; import com.solvway.core.utils.HttpReqRespUtils; @@ -17,13 +19,14 @@ import com.solvway.mobile.api.service.AuthenticationService; import com.solvway.mobile.api.service.MemberService; import com.solvway.mobile.api.service.UserService; import com.solvway.mobile.api.util.HeaderRedactionUtil; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; import jakarta.servlet.http.HttpServletRequest; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; @@ -32,12 +35,18 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.HandlerMapping; + +import java.lang.reflect.Method; import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; @Aspect @Component -@RequiredArgsConstructor @Slf4j public class AppAccessAspect { @@ -49,7 +58,36 @@ public class AppAccessAspect { private final AuthAppKeyConfig authAppKey; private final AuthenticationService authenticationService; private final JwtTokenUtil jwtTokenUtil; - @Around("execution(* com.solvway.mobile.api.controller.*.*(..))") + private final AdminSessionGuard adminSessionGuard; + private final RestTemplateCustomUtil restTemplateUtil; + + @Autowired + public AppAccessAspect(MemberService memberService, UserService userService, PubSubConfig pubSubConfig, + PubSubTemplate pubSubTemplate, PubSubUtil pubSubUtil, AuthAppKeyConfig authAppKey, + AuthenticationService authenticationService, JwtTokenUtil jwtTokenUtil, + AdminSessionGuard adminSessionGuard, RestTemplateCustomUtil restTemplateUtil) { + this.memberService = memberService; + this.userService = userService; + this.pubSubConfig = pubSubConfig; + this.pubSubTemplate = pubSubTemplate; + this.pubSubUtil = pubSubUtil; + this.authAppKey = authAppKey; + this.authenticationService = authenticationService; + this.jwtTokenUtil = jwtTokenUtil; + this.adminSessionGuard = adminSessionGuard; + this.restTemplateUtil = restTemplateUtil; + } + + // ponytail: pre-admin-guard signature kept so the existing non-admin tests compile unchanged; + // admin paths fail closed without the guard. Drop it once those tests take the full constructor. + AppAccessAspect(MemberService memberService, UserService userService, PubSubConfig pubSubConfig, + PubSubTemplate pubSubTemplate, PubSubUtil pubSubUtil, AuthAppKeyConfig authAppKey, + AuthenticationService authenticationService, JwtTokenUtil jwtTokenUtil) { + this(memberService, userService, pubSubConfig, pubSubTemplate, pubSubUtil, authAppKey, + authenticationService, jwtTokenUtil, null, null); + } + + @Around("execution(* com.solvway.mobile.api.controller..*.*(..))") public Object appAccessAuthCheck(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); String methodSig = joinPoint.getSignature().toShortString(); @@ -66,7 +104,8 @@ public class AppAccessAspect { } try { if(!shouldSkipAuth(joinPoint)){ - validateJwt(); + String jwt = validateJwt(); + requireAdminAccess(joinPoint, jwt); requireVerifiedPhoneForCp(joinPoint, apiKey); } return joinPoint.proceed(); @@ -175,7 +214,7 @@ public class AppAccessAspect { }; } - private void validateJwt() { + private String validateJwt() { String jwt = HttpReqRespUtils.getJwtToken(); if (!StringUtils.hasLength(jwt)) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing header 'Authorization'"); @@ -189,6 +228,67 @@ public class AppAccessAspect { if (isTokenExpired) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Expired Token"); } + return jwt; + } + + private static final long SUPER_ADMIN_ROLE_ID = 1L; + private static final long INJECTED_ROLE_ADMIN_ID = 2L; + + /** Admin paths: admin token, live and enabled session, and a granted BO module. Fails closed. */ + private void requireAdminAccess(ProceedingJoinPoint joinPoint, String jwt) { + if (!isAdminPath()) { + return; + } + if (!"A".equals(userTypeClaim(jwt))) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Admin access required"); + } + Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); + AdminModule onMethod = method.getAnnotation(AdminModule.class); + AdminModule declared = onMethod != null ? onMethod : method.getDeclaringClass().getAnnotation(AdminModule.class); + // allowPendingReset is honoured on the method only, so it never opens a whole controller. + User admin = adminSessionGuard.check(jwt, onMethod != null && onMethod.allowPendingReset()); + if (declared != null && Arrays.asList(declared.value()).contains(AdminModule.ANY_ADMIN)) { + return; + } + Set roleIds = admin.getRoles() == null ? Set.of() : admin.getRoles().stream() + .map(Role::getId).filter(Objects::nonNull) + // services-auth findUserByToken adds ROLE_ADMIN to every admin, so it never grants a module. + .filter(id -> id != INJECTED_ROLE_ADMIN_ID) + .collect(Collectors.toSet()); + if (roleIds.contains(SUPER_ADMIN_ROLE_ID)) { + return; + } + boolean granted = false; + if (declared != null) { + try { + granted = AdminModuleAccess.grantedAny(restTemplateUtil, roleIds, declared.value()); + } catch (Exception ex) { + log.error("[AppAccessAspect] admin module lookup failed, failing closed: {}", ex.getClass().getSimpleName()); + } + } + if (!granted) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Admin module access denied"); + } + } + + private String userTypeClaim(String jwt) { + try { + Object type = jwtTokenUtil.getCustomClaimFromToken(jwt, JwtCustomClaim.USERTYPE); + return type == null ? null : type.toString(); + } catch (Exception ex) { + return null; + } + } + + private static boolean isAdminPath() { + if (!(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs)) { + return false; + } + HttpServletRequest request = attrs.getRequest(); + Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); + String path = pattern != null ? pattern.toString() + : (StringUtils.hasLength(request.getServletPath()) ? request.getServletPath() : request.getRequestURI()); + return path != null && path.startsWith("/api/admin/"); } private String maskKey(String key) { diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminControllerPointcutTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminControllerPointcutTest.java new file mode 100644 index 0000000..9e7101e --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminControllerPointcutTest.java @@ -0,0 +1,30 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.mobile.api.useraccess.AppAccessAspect; +import org.aspectj.lang.annotation.Around; +import org.junit.jupiter.api.Test; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; + +import java.lang.reflect.Method; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Controllers in controller subpackages (admin controllers live in controller.admin) must pass the access aspect. */ +class AdminControllerPointcutTest { + + static class ProbeController { + public String handler() { + return "ok"; + } + } + + @Test + void accessAspectCoversControllerSubpackages() throws Exception { + Method advice = AppAccessAspect.class.getMethod("appAccessAuthCheck", org.aspectj.lang.ProceedingJoinPoint.class); + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression(advice.getAnnotation(Around.class).value()); + + Method handler = ProbeController.class.getMethod("handler"); + assertThat(pointcut.matches(handler, ProbeController.class)).isTrue(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceTest.java new file mode 100644 index 0000000..7f79662 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceTest.java @@ -0,0 +1,43 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@SuppressWarnings("unchecked") +class AdminAuthenticationServiceTest { + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService service; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + service = new AdminAuthenticationService(rest); + when(rest.getURLforApiService(any())).thenReturn("http://auth/findUserByToken/{area}/{token}"); + } + + @Test + void liveToken_loadsUserInBoArea() { + User u = new User(); + when(rest.getForEntity(any(String.class), eq(User.class), eq("BO"), eq("tok"))) + .thenReturn(ResponseEntity.ok(u)); + assertThat(service.loadUserByToken("tok")).isSameAs(u); + } + + @Test + void non200_returnsNull() { + when(rest.getForEntity(any(String.class), eq(User.class), eq("BO"), eq("tok"))) + .thenReturn(new ResponseEntity<>(HttpStatus.NO_CONTENT)); + assertThat(service.loadUserByToken("tok")).isNull(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminModuleAccessTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminModuleAccessTest.java new file mode 100644 index 0000000..ab69289 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminModuleAccessTest.java @@ -0,0 +1,60 @@ +package com.solvway.mobile.api.useraccess; + +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.ResponseEntity; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@SuppressWarnings("unchecked") +class AdminModuleAccessTest { + + private RestTemplateCustomUtil rest; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + when(rest.getURLforApiService(any())).thenReturn("http://system/module/findAllByArea/{area}"); + when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO"))) + .thenReturn(ResponseEntity.ok(List.of( + Map.of("name", "BO_LEADS", "roles", List.of(Map.of("id", 5), Map.of("id", 6L))), + Map.of("name", "BO_USERS", "roles", List.of(Map.of("id", 9))), + Map.of("name", "BO_EMPTY")))); + } + + @Test + void roleGrantedModule_isGranted() { + assertThat(AdminModuleAccess.grantedAny(rest, Set.of(6L), "BO_LEADS")).isTrue(); + } + + @Test + void anyOfSeveralModules_isGranted() { + assertThat(AdminModuleAccess.grantedAny(rest, Set.of(9L), "BO_LEADS", "BO_USERS")).isTrue(); + } + + @Test + void roleWithoutGrant_isDenied() { + assertThat(AdminModuleAccess.grantedAny(rest, Set.of(9L), "BO_LEADS")).isFalse(); + } + + @Test + void moduleWithNoRoles_orUnknownModule_isDenied() { + assertThat(AdminModuleAccess.grantedAny(rest, Set.of(5L), "BO_EMPTY")).isFalse(); + assertThat(AdminModuleAccess.grantedAny(rest, Set.of(5L), "NOPE")).isFalse(); + } + + @Test + void noModulesDeclared_isDenied() { + assertThat(AdminModuleAccess.grantedAny(rest, Set.of(5L))).isFalse(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardTest.java new file mode 100644 index 0000000..6517a90 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AdminSessionGuardTest.java @@ -0,0 +1,86 @@ +package com.solvway.mobile.api.useraccess; + +import com.solvway.core.enums.GeneralEnum.LoginStatus; +import com.solvway.core.model.User; +import com.solvway.mobile.api.service.AdminAuthenticationService; +import org.junit.jupiter.api.BeforeEach; +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 AdminSessionGuardTest { + + private AdminAuthenticationService auth; + private AdminSessionGuard guard; + + @BeforeEach + void setUp() { + auth = mock(AdminAuthenticationService.class); + guard = new AdminSessionGuard(auth); + } + + private static User user(boolean enabled, LoginStatus login) { + User u = new User(); + u.setEnabled(enabled); + u.setLogin(login); + return u; + } + + private void assertStatus(boolean allowPending, HttpStatus expected) { + assertThatThrownBy(() -> guard.check("tok", allowPending)) + .isInstanceOf(ResponseStatusException.class) + .satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode()).isEqualTo(expected)); + } + + @Test + void unknownOrRevokedToken_lookupNull_isUnauthorized() { + when(auth.loadUserByToken("tok")).thenReturn(null); + assertStatus(false, HttpStatus.UNAUTHORIZED); + } + + @Test + void deactivatedAdmin_isUnauthorized() { + when(auth.loadUserByToken("tok")).thenReturn(user(false, LoginStatus.Y)); + assertStatus(false, HttpStatus.UNAUTHORIZED); + } + + @Test + void pendingPasswordChange_isForbidden() { + when(auth.loadUserByToken("tok")).thenReturn(user(true, LoginStatus.N)); + assertStatus(false, HttpStatus.FORBIDDEN); + } + + @Test + void pendingPasswordChange_allowedWhenHandlerOptsIn() { + User u = user(true, LoginStatus.N); + when(auth.loadUserByToken("tok")).thenReturn(u); + assertThat(guard.check("tok", true)).isSameAs(u); + } + + @Test + void activeAdmin_returnsUser() { + User u = user(true, LoginStatus.Y); + when(auth.loadUserByToken("tok")).thenReturn(u); + assertThat(guard.check("tok", false)).isSameAs(u); + } + + @Test + void deactivatedAdmin_withPendingReset_stillUnauthorized() { + when(auth.loadUserByToken("tok")).thenReturn(user(false, LoginStatus.N)); + assertStatus(true, HttpStatus.UNAUTHORIZED); + } + + @Test + void pendingPasswordChange_carriesCodeForThePortal() { + when(auth.loadUserByToken("tok")).thenReturn(user(true, LoginStatus.N)); + assertThatThrownBy(() -> guard.check("tok", false)) + .isInstanceOf(org.springframework.web.server.ResponseStatusException.class) + .satisfies(ex -> assertThat(((org.springframework.web.server.ResponseStatusException) ex) + .getBody().getProperties()).containsEntry("code", "PASSWORD_RESET_REQUIRED")); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java new file mode 100644 index 0000000..a6be84b --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAdminTest.java @@ -0,0 +1,342 @@ +package com.solvway.mobile.api.useraccess; + +import com.google.cloud.spring.pubsub.core.PubSubTemplate; +import com.solvway.core.annotation.AppAuth; +import com.solvway.core.enums.JwtEnum.JwtCustomClaim; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.core.utils.JwtTokenUtil; +import com.solvway.core.utils.PubSubUtil; +import com.solvway.mobile.api.config.AuthAppKeyConfig; +import com.solvway.mobile.api.config.PubSubConfig; +import com.solvway.mobile.api.service.AuthenticationService; +import com.solvway.mobile.api.service.MemberService; +import com.solvway.mobile.api.service.UserService; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.reflect.MethodSignature; +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.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.HandlerMapping; + +import java.lang.reflect.Method; +import java.util.List; +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.ArgumentMatchers.eq; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Admin guard on /api/admin/** paths: token type, session state, module authorisation. */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@SuppressWarnings("unchecked") +class AppAccessAspectAdminTest { + + private static final String API_KEY = "valid-api-key"; + private static final String TOK = "admin-tok"; + + @Mock private MemberService memberService; + @Mock private UserService userService; + @Mock private PubSubConfig pubSubConfig; + @Mock private PubSubTemplate pubSubTemplate; + @Mock private PubSubUtil pubSubUtil; + @Mock private AuthenticationService authenticationService; + @Mock private JwtTokenUtil jwtTokenUtil; + @Mock private ProceedingJoinPoint joinPoint; + @Mock private MethodSignature methodSignature; + @Mock private AdminSessionGuard guard; + @Mock private RestTemplateCustomUtil rest; + + private AppAccessAspect aspect; + + @AdminModule("BO_LEADS") + static class Target { + @AppAuth + @AdminModule(AdminModule.ANY_ADMIN) + public void anyAdmin() { + } + + @AppAuth + @AdminModule("BO_USERS") + public void methodWins() { + } + + @AppAuth + public void classLevel() { + } + + @AppAuth + @AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true) + public void firstLogin() { + } + + @AppAuth(skipValidate = true) + public void publicLogin() { + } + } + + @AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true) + static class PendingAtClassLevel { + @AppAuth + public void handler() { + } + } + + static class Undeclared { + @AppAuth + public void handler() { + } + } + + @BeforeEach + void setUp() { + AuthAppKeyConfig cfg = new AuthAppKeyConfig(); + cfg.setList(List.of(API_KEY)); + aspect = new AppAccessAspect(memberService, userService, pubSubConfig, pubSubTemplate, pubSubUtil, cfg, + authenticationService, jwtTokenUtil, guard, rest); + when(rest.getURLforApiService(any())).thenReturn("http://system/module/findAllByArea/{area}"); + when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO"))) + .thenReturn(ResponseEntity.ok(List.of( + Map.of("name", "BO_LEADS", "roles", List.of(Map.of("id", 5))), + Map.of("name", "BO_USERS", "roles", List.of(Map.of("id", 9), Map.of("id", 2)))))); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/admin/things"); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req)); + } + + @AfterEach + void clear() { + RequestContextHolder.resetRequestAttributes(); + } + + private void target(Class type, String name) throws Exception { + Method m = type.getMethod(name); + when(joinPoint.getSignature()).thenReturn(methodSignature); + when(methodSignature.getMethod()).thenReturn(m); + when(methodSignature.getDeclaringType()).thenReturn(type); + when(methodSignature.toShortString()).thenReturn(type.getSimpleName() + "." + name + "()"); + } + + private void http(MockedStatic h, String jwt, String userType) { + h.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(API_KEY); + h.when(HttpReqRespUtils::getJwtToken).thenReturn(jwt); + when(jwtTokenUtil.isTokenExpired(jwt)).thenReturn(false); + when(jwtTokenUtil.getCustomClaimFromToken(jwt, JwtCustomClaim.USERTYPE)).thenReturn(userType); + } + + private static User admin(Long... roleIds) { + User u = new User(); + u.setEnabled(true); + for (Long id : roleIds) { + Role r = new Role(); + r.setId(id); + u.getRoles().add(r); + } + return u; + } + + private void expect(HttpStatus status) throws Throwable { + assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint)) + .isInstanceOf(ResponseStatusException.class) + .satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode()).isEqualTo(status)); + verify(joinPoint, never()).proceed(); + } + + @Test + void noToken_isUnauthorized() throws Throwable { + target(Target.class, "anyAdmin"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, "", "A"); + expect(HttpStatus.UNAUTHORIZED); + } + } + + @Test + void memberToken_isForbidden_adminAccessRequired() throws Throwable { + target(Target.class, "anyAdmin"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, "member-tok", "M"); + assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint)) + .isInstanceOfSatisfying(ResponseStatusException.class, ex -> { + assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(ex.getReason()).isEqualTo("Admin access required"); + }); + verify(guard, never()).check(any(), org.mockito.ArgumentMatchers.anyBoolean()); + } + } + + @Test + void adminClaimWithRevokedOrUnknownToken_isUnauthorized() throws Throwable { + target(Target.class, "anyAdmin"); + when(guard.check(TOK, false)).thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token")); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.UNAUTHORIZED); + } + } + + @Test + void deactivatedAdmin_isUnauthorized() throws Throwable { + target(Target.class, "anyAdmin"); + when(guard.check(TOK, false)).thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Account disabled")); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.UNAUTHORIZED); + } + } + + @Test + void pendingPasswordChange_isForbidden() throws Throwable { + target(Target.class, "anyAdmin"); + when(guard.check(TOK, false)).thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN, "PASSWORD_RESET_REQUIRED")); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } + + @Test + void pendingPasswordChange_handlerThatAllowsItIsPassedTheFlag() throws Throwable { + target(Target.class, "firstLogin"); + when(guard.check(TOK, true)).thenReturn(admin(5L)); + when(joinPoint.proceed()).thenReturn("ok"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok"); + } + } + + @Test + void anyAdmin_passesForNonSuperAdminWithoutModuleLookup() throws Throwable { + target(Target.class, "anyAdmin"); + when(guard.check(TOK, false)).thenReturn(admin(77L)); + when(joinPoint.proceed()).thenReturn("ok"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok"); + verify(rest, never()).getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO")); + } + } + + @Test + void methodModule_winsOverClassModule() throws Throwable { + target(Target.class, "methodWins"); + when(guard.check(TOK, false)).thenReturn(admin(5L)); // role 5 holds BO_LEADS (class), not BO_USERS (method) + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } + + @Test + void classModule_appliesWhenMethodUndeclared_andGrantedRolePasses() throws Throwable { + target(Target.class, "classLevel"); + when(guard.check(TOK, false)).thenReturn(admin(5L)); + when(joinPoint.proceed()).thenReturn("ok"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok"); + } + } + + @Test + void superAdminRole1_bypassesModuleCheck() throws Throwable { + target(Target.class, "methodWins"); + when(guard.check(TOK, false)).thenReturn(admin(1L)); + when(joinPoint.proceed()).thenReturn("ok"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok"); + } + } + + @Test + void undeclaredHandler_isForbiddenForNonSuperAdmin() throws Throwable { + target(Undeclared.class, "handler"); + when(guard.check(TOK, false)).thenReturn(admin(5L)); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } + + @Test + void moduleLookupFailure_failsClosed() throws Throwable { + target(Target.class, "classLevel"); + when(guard.check(TOK, false)).thenReturn(admin(5L)); + when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), eq("BO"))) + .thenThrow(new IllegalStateException("system down")); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } + + @Test + void skipValidateHandler_onAdminPath_isNotGuarded() throws Throwable { + target(Target.class, "publicLogin"); + when(joinPoint.proceed()).thenReturn("ok"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, "", "A"); + assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok"); + verify(guard, never()).check(any(), org.mockito.ArgumentMatchers.anyBoolean()); + } + } + + @Test + void nonAdminPath_isNotAffected() throws Throwable { + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/members"); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req)); + target(Undeclared.class, "handler"); + when(joinPoint.proceed()).thenReturn("ok"); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, "member-tok", "M"); + assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok"); + verify(guard, never()).check(any(), org.mockito.ArgumentMatchers.anyBoolean()); + } + } + + @Test + void allowPendingReset_isIgnoredAtClassLevel() throws Throwable { + target(PendingAtClassLevel.class, "handler"); + when(guard.check(TOK, false)).thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN, "PASSWORD_RESET_REQUIRED")); + when(guard.check(TOK, true)).thenReturn(admin(5L)); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } + + @Test + void injectedRoleAdmin2_doesNotGrantModules() throws Throwable { + // services-auth adds ROLE_ADMIN (id 2) to every admin, so a grant to role 2 must not count. + target(Target.class, "methodWins"); + when(guard.check(TOK, false)).thenReturn(admin(2L, 77L)); + try (MockedStatic h = mockStatic(HttpReqRespUtils.class)) { + http(h, TOK, "A"); + expect(HttpStatus.FORBIDDEN); + } + } +} diff --git a/solvway-services-auth/src/main/java/com/solvway/services/auth/controller/JwtAuthenticationController.java b/solvway-services-auth/src/main/java/com/solvway/services/auth/controller/JwtAuthenticationController.java index 2b2b57b..c29f7e5 100644 --- a/solvway-services-auth/src/main/java/com/solvway/services/auth/controller/JwtAuthenticationController.java +++ b/solvway-services-auth/src/main/java/com/solvway/services/auth/controller/JwtAuthenticationController.java @@ -380,6 +380,10 @@ public class JwtAuthenticationController { @RequestMapping({ "/findUserByToken/{area}/{token}" }) public User findUserByToken(@PathVariable("area") Area area, @PathVariable("token") String token) { + // A logged-out token (see logoutToken) resolves to no user. + if (redisUtil.getValue(token) != null) { + return null; + } String username = jwtTokenUtil.getUsernameFromToken(token); User user = null; diff --git a/solvway-services-auth/src/test/java/com/solvway/services/auth/controller/FindUserByTokenRevocationTest.java b/solvway-services-auth/src/test/java/com/solvway/services/auth/controller/FindUserByTokenRevocationTest.java new file mode 100644 index 0000000..9a27ff3 --- /dev/null +++ b/solvway-services-auth/src/test/java/com/solvway/services/auth/controller/FindUserByTokenRevocationTest.java @@ -0,0 +1,35 @@ +package com.solvway.services.auth.controller; + +import com.solvway.core.enums.GeneralEnum.Area; +import com.solvway.services.auth.service.SystemService; +import com.solvway.services.auth.util.RedisUtil; +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.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FindUserByTokenRevocationTest { + + @Mock + private RedisUtil redisUtil; + @Mock + private SystemService systemService; + @InjectMocks + private JwtAuthenticationController controller; + + @Test + void loggedOutTokenResolvesToNoUser() { + when(redisUtil.getValue("tok")).thenReturn("tok"); + + assertThat(controller.findUserByToken(Area.BO, "tok")).isNull(); + verify(systemService, never()).findUserByUsernameWithPassword(any()); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/constant/SystemConstants.java b/solvway-services-system/src/main/java/com/solvway/services/system/constant/SystemConstants.java index 9a24552..007bcc7 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/constant/SystemConstants.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/constant/SystemConstants.java @@ -7,7 +7,7 @@ public class SystemConstants { @Getter public enum Area { - A("ADMIN"),M("MEMBER"),P("PUBLIC"),B("STOCKIST"), AP("APPS"); + A("ADMIN"),M("MEMBER"),P("PUBLIC"),B("STOCKIST"), AP("APPS"), BO("BACKOFFICE_PORTAL"); private final String name; Area(String name) { this.name=name; -- 2.54.1 From 1bfc1c73c657ccf3dc9ee34354be2053f92c0725 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 19:44:11 +0800 Subject: [PATCH 05/19] docs: record admin guard details found while building task 3.1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-admin-auth-users-roles/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/add-admin-auth-users-roles/design.md b/openspec/changes/add-admin-auth-users-roles/design.md index 6b686b5..f830fe7 100644 --- a/openspec/changes/add-admin-auth-users-roles/design.md +++ b/openspec/changes/add-admin-auth-users-roles/design.md @@ -29,7 +29,7 @@ Alternative: write admin controllers fresh against Tastefully's backoffice contr ### 2. Admin token check uses `findUserByToken/BO` -On an `/api/admin/**` path the aspect loads the user with `/auth/findUserByToken/BO/{token}`. No user, or a non-admin user, means 403 for a valid member token and 401 for a revoked token. The same lookup gives the roles for the module check and the enabled and login-status flags for the session guard (deactivated means 401; pending password change allows only first-login and logout, otherwise 403). This is one downstream call per admin request. +On an `/api/admin/**` path the aspect first reads the token's `USERTYPE` claim: anything but `A` is a 403. It then loads the user with `/auth/findUserByToken/BO/{token}`; no user (unknown or logged out) is a 401. `findUserByToken` did not check the logout list, so this change makes it return no user for a logged-out token, and adds `BO` to the `Area` enums in core-libs and services-system. `findUserByToken` also adds `ROLE_ADMIN` (id 2) to every admin, so the module check ignores role 2. The pending-reset 403 carries `code: PASSWORD_RESET_REQUIRED`, which the portal uses to redirect. The same lookup gives the roles for the module check and the enabled and login-status flags for the session guard (deactivated means 401; pending password change allows only first-login and logout, otherwise 403). This is one downstream call per admin request. `ponytail:` no cache on this lookup; add a short-TTL cache keyed by token if admin latency matters. -- 2.54.1 From 9f22837a0014b60392f8da679cdf0a39efb5b636 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 19:55:58 +0800 Subject: [PATCH 06/19] feat(mobile-api): admin login, first-login, forgot password, logout, refresh and me Wrong, blank or failed logins all answer the same 401. A deactivated admin is refused and the token services-auth issued is revoked. resetAdminPassword now refuses deactivated users and users without an email. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-admin-auth-users-roles/design.md | 2 + .../add-admin-auth-users-roles/tasks.md | 2 +- .../api/RestApiAuthServiceConstants.java | 1 + .../api/RestApiSystemServiceConstants.java | 2 + .../controller/admin/AdminAuthController.java | 131 +++++++++ .../api/dto/admin/AdminFirstLoginRequest.java | 5 + .../dto/admin/AdminForgotPasswordRequest.java | 5 + .../api/dto/admin/AdminLoginResponse.java | 10 + .../mobile/api/dto/admin/AdminMeResponse.java | 10 + .../service/AdminAuthenticationService.java | 28 ++ .../admin/AdminAuthControllerTest.java | 253 ++++++++++++++++++ .../AdminAuthenticationServiceWireTest.java | 67 +++++ .../system/controller/UserController.java | 3 +- .../UserControllerResetAdminPasswordTest.java | 50 ++++ 14 files changed, 567 insertions(+), 2 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminFirstLoginRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminForgotPasswordRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginResponse.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminMeResponse.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceWireTest.java create mode 100644 solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerResetAdminPasswordTest.java diff --git a/openspec/changes/add-admin-auth-users-roles/design.md b/openspec/changes/add-admin-auth-users-roles/design.md index f830fe7..e835415 100644 --- a/openspec/changes/add-admin-auth-users-roles/design.md +++ b/openspec/changes/add-admin-auth-users-roles/design.md @@ -70,6 +70,8 @@ Delete by directory: every `app/` route, `app/api/` family, `app/components/` fo - [Anyone who knows a username and its email can reset that password, locking the user out until they read the email] → Accepted for phase 1 (staff-only, small team). The response never reveals a match. Throttling comes back with babyboo's login-security later. - [The ported aspect is security code copied across codebases] → Each guard rule has a ported or new test, and the reviewer reads the whole aspect diff. - [Deleting most of the portal breaks shared imports in ways tests miss] → `npm run build` and `npm run lint` must pass, not only `vitest`. +- [Forgot-password takes longer when the details match (bcrypt plus an email), so timing can hint at a match] → Accepted for phase 1; the body is identical either way. +- [services-auth issues a token to a deactivated admin] → The admin login checks `enabled` and revokes that token before answering 401; `/user/resetAdminPassword` now refuses deactivated users. - [Plain-text temporary password in email] → Forced change at next login; revisit with real SMTP in change 5. ## Migration Plan diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index d04e049..b8cbc9d 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -19,7 +19,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 4. mobile-api admin auth -- [ ] 4.1 Port babyboo's `AdminAuthController` and `AdminAuthenticationService` (login, first-login, logout, refresh, me) onto Co-Lite endpoints, and add `POST /api/admin/auth/forgot-password` calling `/user/resetAdminPassword`. Login answers 401 for an empty token, a deactivated user or a non-admin account; forgot-password always answers 200. Port babyboo's tests for these classes and add one per `admin-access` login, first-login and forgot-password scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. +- [x] 4.1 Port babyboo's `AdminAuthController` and `AdminAuthenticationService` (login, first-login, logout, refresh, me) onto Co-Lite endpoints, and add `POST /api/admin/auth/forgot-password` calling `/user/resetAdminPassword`. Login answers 401 for an empty token, a deactivated user or a non-admin account; forgot-password always answers 200. Port babyboo's tests for these classes and add one per `admin-access` login, first-login and forgot-password scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: `solvway-mobile-api/src/**/controller/admin/**`, `solvway-mobile-api/src/**/service/admin/**`, `solvway-mobile-api/src/**/dto/admin/**` (or babyboo's equivalent packages) ## 5. mobile-api users and roles diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiAuthServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiAuthServiceConstants.java index 79b6a00..4651ca4 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiAuthServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiAuthServiceConstants.java @@ -7,6 +7,7 @@ public class RestApiAuthServiceConstants { public static final String API_REST_AUTHENTICATION= "/auth/webMemberAuthenticate"; public static final String API_REST_AUTHENTICATION_AUTO_LOGIN_UPDATE= "/auth/memberAutoLoginUpdate"; public static final String API_REST_AUTHENTICATION_FINGER_PRINT_LOGIN= "/auth/fingerPrintLoginWithToken/{token}/{memberCode}"; + public static final String API_REST_ADMIN_AUTHENTICATE = "/auth/authenticate"; public static final String API_REST_REFRESH_TOKEN = "/auth/refreshToken/{token}"; public static final String API_REST_SYSTEM_GET_USER_BYTOKEN = "/auth/findUserByToken/{area}/{token}"; public static final String API_REST_LOGOUT_TOKEN= "/auth/logoutToken/{token}"; 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 ecb8523..efca2a0 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 @@ -11,6 +11,8 @@ public class RestApiSystemServiceConstants { public static final String API_REST_SYSTEM_USER_UPDATE_MEMBER_PASSWORD = "/user/updateMemberPassword"; public static final String API_REST_SYSTEM_USER_GET_ENCRYPTED_STRING="/user/getEncryptedStringForPassword"; public static final String API_REST_SYSTEM_USER_CHECK_ENCRYPTED_STRING_MATCHED="/user/checkEncryptedStringMatched"; + public static final String API_REST_SYSTEM_ADMIN_FIRST_TIME_LOGIN = "/user/firstTimeLogin"; + public static final String API_REST_SYSTEM_ADMIN_RESET_PASSWORD = "/user/resetAdminPassword"; public static final String API_REST_SYSTEM_USER_FIRST_TIME_LOGIN="/user/memberFirstTimeLogin"; public static final String API_REST_SYSTEM_USER_VALIDATE_PASSWORD_RULES="/user/validatePasswordFromRulesForMember"; 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 new file mode 100644 index 0000000..c03f525 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminAuthController.java @@ -0,0 +1,131 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.core.enums.GeneralEnum; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminFirstLoginRequest; +import com.solvway.mobile.api.dto.admin.AdminForgotPasswordRequest; +import com.solvway.mobile.api.dto.admin.AdminLoginResponse; +import com.solvway.mobile.api.dto.admin.AdminMeResponse; +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.AdminModule; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +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 org.springframework.web.client.RestClientException; + +import java.util.Map; + +/** Admin login, first-login, forgot-password, logout, refresh and me. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@Slf4j +@RequiredArgsConstructor +public class AdminAuthController { + private static final Map BAD_LOGIN = + Map.of("result", "false", "message", "Invalid username or password"); + private final AdminAuthenticationService adminAuthenticationService; + private final AuthenticationService authenticationService; + + @AppAuth(skipValidate = true) + @PostMapping("/auth/login") + public ResponseEntity login(@RequestBody AuthRequest request) { + // Blank fields never reach services-auth: it fails differently for known and unknown usernames. + if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN); + } + String token; + User u; + try { + token = adminAuthenticationService.getToken(request); + // services-auth authenticates type A only, so a member account also lands here with no token. + u = StringUtils.hasLength(token) ? adminAuthenticationService.loadUserByToken(token) : null; + if (u != null && !u.isEnabled()) { + // services-auth issues tokens to disabled admins; revoke the one we refuse. + authenticationService.logoutToken(token); + u = null; + } + } catch (RestClientException ex) { + u = null; // any upstream failure is a refused login; never echo why + token = null; + } + if (u == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN); + } + return ResponseEntity.ok(new AdminLoginResponse(token, u.getName(), u.getRoles(), u.getAclMenu(), + GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false")); + } + + @AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true) + @AppAuth + @PostMapping("/auth/first-login") + public ResponseEntity> firstLogin(@RequestBody AdminFirstLoginRequest request) { + User u = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (u == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + // Only a pending-change user may use this: it sets a password with no current password. + if (!GeneralEnum.LoginStatus.N.equals(u.getLogin())) { + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("message", "First sign-in is already complete.")); + } + if (!StringUtils.hasLength(request.newPassword())) { + return ResponseEntity.badRequest().body(Map.of("message", "New password is required.")); + } + if (!adminAuthenticationService.firstTimeLogin(u.getId(), request.newPassword())) { + return ResponseEntity.badRequest().body(Map.of("message", "New password does not meet the password policy.")); + } + return ResponseEntity.ok(Map.of("result", "true")); + } + + /** Always 200 with the same body: the answer must not reveal whether username and email matched. */ + @AppAuth(skipValidate = true) + @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()); + } + } catch (Exception e) { + log.warn("Admin forgot-password failed downstream: {}", e.getClass().getSimpleName()); + } + return ResponseEntity.ok(Map.of("result", "true")); + } + + @AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true) + @AppAuth + @PostMapping("/auth/logout") + public ResponseEntity> logout() { + authenticationService.logoutToken(HttpReqRespUtils.getJwtToken()); + return ResponseEntity.ok(Map.of("result", "true")); + } + + /** Re-issues the caller's token via services-auth; {@code token} is null when upstream declines. */ + @AdminModule(AdminModule.ANY_ADMIN) + @AppAuth + @PostMapping("/auth/refresh") + public ResponseEntity> refresh() { + String newToken = authenticationService.refreshToken(HttpReqRespUtils.getJwtToken()); + return ResponseEntity.ok(newToken == null ? Map.of() : Map.of("token", newToken)); + } + + @AdminModule(AdminModule.ANY_ADMIN) + @AppAuth + @GetMapping("/me") + public ResponseEntity me() { + User u = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (u == null) { + return ResponseEntity.notFound().build(); + } + return ResponseEntity.ok(new AdminMeResponse(u.getName(), u.getRoles(), u.getAclMenu())); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminFirstLoginRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminFirstLoginRequest.java new file mode 100644 index 0000000..d3b736c --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminFirstLoginRequest.java @@ -0,0 +1,5 @@ +package com.solvway.mobile.api.dto.admin; + +/** Body of {@code POST /api/admin/auth/first-login}. */ +public record AdminFirstLoginRequest(String newPassword) { +} 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 new file mode 100644 index 0000000..17274f7 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminForgotPasswordRequest.java @@ -0,0 +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) { +} 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 new file mode 100644 index 0000000..88dc43b --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminLoginResponse.java @@ -0,0 +1,10 @@ +package com.solvway.mobile.api.dto.admin; + +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) { +} 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 new file mode 100644 index 0000000..052b45f --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminMeResponse.java @@ -0,0 +1,10 @@ +package com.solvway.mobile.api.dto.admin; + +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(String name, List roles, Module aclMenu) { +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java index 6819ced..cb1a67e 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAuthenticationService.java @@ -2,12 +2,16 @@ package com.solvway.mobile.api.service; import com.solvway.core.model.User; import com.solvway.mobile.api.constant.api.RestApiAuthServiceConstants; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.model.AuthRequest; import com.solvway.mobile.api.util.RestTemplateCustomUtil; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import java.util.Map; + @Service @RequiredArgsConstructor public class AdminAuthenticationService { @@ -20,4 +24,28 @@ public class AdminAuthenticationService { User.class, "BO", token); return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null; } + + /** Token for a type A (admin) user, or null/empty when services-auth rejects the credentials. */ + public String getToken(AuthRequest authRequest) { + ResponseEntity ent = restTemplateUtil.postForEntity( + restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_ADMIN_AUTHENTICATE), + String.class, authRequest); + return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null; + } + + /** Sets the first-login password via services-system; false when it breaks the admin password rules. */ + public boolean firstTimeLogin(Long userId, String newPassword) { + ResponseEntity ent = restTemplateUtil.postForEntity( + restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_FIRST_TIME_LOGIN), + Boolean.class, Map.of("userId", userId, "newPassword", newPassword, "repeatPassword", newPassword)); + return ent.getStatusCode() == HttpStatus.OK && Boolean.TRUE.equals(ent.getBody()); + } + + /** Emails a temporary password when username and email match an admin; returns rows updated (0 = no match). */ + public int resetAdminPassword(String username, String email) { + ResponseEntity ent = restTemplateUtil.postForEntity( + restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_RESET_PASSWORD), + Integer.class, Map.of("username", username, "email", email)); + return ent.getBody() == null ? 0 : ent.getBody(); + } } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerTest.java new file mode 100644 index 0000000..f268703 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminAuthControllerTest.java @@ -0,0 +1,253 @@ +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.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.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.setup.MockMvcBuilders; + +import java.util.List; + +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.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminAuthControllerTest { + + private static final String LOGIN = "{\"username\":\"admin\",\"password\":\"pw\"}"; + private static final String FORGOT = "{\"username\":\"sales1\",\"email\":\"sales1@example.com\"}"; + private static final String FORGOT_BODY = "{\"result\":\"true\"}"; + + @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 User user(boolean enabled, GeneralEnum.LoginStatus login) { + User u = new User(); + u.setId(9L); + u.setName("Admin User"); + u.setEnabled(enabled); + u.setLogin(login); + u.setRoles(List.of(new Role("ROLE_ADMIN"))); + u.setPassword("$2a$secret"); + return u; + } + + private org.springframework.test.web.servlet.ResultActions login() throws Exception { + return mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON).content(LOGIN)); + } + + @Test + void login_correctCredentials_returnsTokenNameRolesAndResetFlag() throws Exception { + when(auth.getToken(any())).thenReturn("tok"); + when(auth.loadUserByToken("tok")).thenReturn(user(true, GeneralEnum.LoginStatus.N)); + + login().andExpect(status().isOk()) + .andExpect(jsonPath("$.token").value("tok")) + .andExpect(jsonPath("$.name").value("Admin User")) + .andExpect(jsonPath("$.roles[0].name").value("ROLE_ADMIN")) + .andExpect(jsonPath("$.resetPasswordRequired").value("true")) + .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("secret")))); + } + + @Test + void login_wrongPassword_emptyToken_is401FixedMessage() throws Exception { + when(auth.getToken(any())).thenReturn(""); + + login().andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.message").value("Invalid username or password")); + verify(auth, never()).loadUserByToken(anyString()); + } + + @Test + void login_deactivatedUser_is401SameMessage() throws Exception { + when(auth.getToken(any())).thenReturn("tok"); + when(auth.loadUserByToken("tok")).thenReturn(user(false, GeneralEnum.LoginStatus.Y)); + + login().andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.message").value("Invalid username or password")) + .andExpect(jsonPath("$.token").doesNotExist()); + } + + @Test + void login_memberAccount_servicesAuthGivesNoToken_is401() throws Exception { + // /auth/authenticate only authenticates type A users; a member gets a 200 with an empty body (null here). + when(auth.getToken(any())).thenReturn(null); + + login().andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.message").value("Invalid username or password")); + } + + @Test + void firstLogin_success_setsPasswordForCaller() throws Exception { + when(auth.loadUserByToken("tok")).thenReturn(user(true, GeneralEnum.LoginStatus.N)); + when(auth.firstTimeLogin(9L, "New#Pass1")).thenReturn(true); + + mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON) + .content("{\"newPassword\":\"New#Pass1\"}")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"result\":\"true\"}")); + } + + @Test + void firstLogin_ruleFailure_is400WithMessage() throws Exception { + when(auth.loadUserByToken("tok")).thenReturn(user(true, GeneralEnum.LoginStatus.N)); + when(auth.firstTimeLogin(9L, "weak")).thenReturn(false); + + mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON) + .content("{\"newPassword\":\"weak\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("New password does not meet the password policy.")); + } + + @Test + void firstLogin_alreadyCompleted_is403() throws Exception { + when(auth.loadUserByToken("tok")).thenReturn(user(true, GeneralEnum.LoginStatus.Y)); + + mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON) + .content("{\"newPassword\":\"New#Pass1\"}")) + .andExpect(status().isForbidden()); + verify(auth, never()).firstTimeLogin(any(), any()); + } + + private org.springframework.test.web.servlet.ResultActions forgot() throws Exception { + return mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON).content(FORGOT)); + } + + @Test + void forgotPassword_match_is200AndResetCalled() throws Exception { + when(auth.resetAdminPassword("sales1", "sales1@example.com")).thenReturn(1); + + forgot().andExpect(status().isOk()).andExpect(content().json(FORGOT_BODY)); + verify(auth).resetAdminPassword("sales1", "sales1@example.com"); + } + + @Test + void forgotPassword_noMatch_sameBody() throws Exception { + when(auth.resetAdminPassword(anyString(), anyString())).thenReturn(0); + + forgot().andExpect(status().isOk()).andExpect(content().json(FORGOT_BODY)); + } + + @Test + void forgotPassword_downstreamException_sameBody() throws Exception { + when(auth.resetAdminPassword(anyString(), anyString())).thenThrow(new IllegalStateException("npe downstream")); + + forgot().andExpect(status().isOk()).andExpect(content().json(FORGOT_BODY)); + } + + @Test + void logout_callsLogoutToken() throws Exception { + mvc.perform(post("/api/admin/auth/logout")).andExpect(status().isOk()); + verify(authenticationService).logoutToken("tok"); + } + + @Test + void refresh_returnsNewToken() throws Exception { + when(authenticationService.refreshToken("tok")).thenReturn("tok2"); + + mvc.perform(post("/api/admin/auth/refresh")).andExpect(status().isOk()) + .andExpect(jsonPath("$.token").value("tok2")); + } + + @Test + void me_returnsNameRolesAndAclMenu() throws Exception { + User u = user(true, GeneralEnum.LoginStatus.Y); + u.setAclMenu(new com.solvway.core.model.Module()); + when(auth.loadUserByToken("tok")).thenReturn(u); + + mvc.perform(get("/api/admin/me")).andExpect(status().isOk()) + .andExpect(jsonPath("$.name").value("Admin User")) + .andExpect(jsonPath("$.roles[0].name").value("ROLE_ADMIN")) + .andExpect(jsonPath("$.aclMenu").exists()) + .andExpect(jsonPath("$.password").doesNotExist()); + } + + @Test + void login_blankPassword_is401WithoutCallingUpstream() throws Exception { + mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON) + .content("{\"username\":\"admin\",\"password\":\"\"}")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.message").value("Invalid username or password")); + verify(auth, never()).getToken(any()); + } + + @Test + void login_missingUsername_is401WithoutCallingUpstream() throws Exception { + mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON) + .content("{\"password\":\"pw\"}")) + .andExpect(status().isUnauthorized()); + verify(auth, never()).getToken(any()); + } + + @Test + void login_upstreamServerError_is401SameMessage() throws Exception { + when(auth.getToken(any())).thenThrow(new org.springframework.web.client.HttpServerErrorException( + org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR)); + + login().andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.message").value("Invalid username or password")); + } + + @Test + void login_deactivatedUser_tokenIsLoggedOut() throws Exception { + when(auth.getToken(any())).thenReturn("newtok"); + when(auth.loadUserByToken("newtok")).thenReturn(user(false, GeneralEnum.LoginStatus.Y)); + + login().andExpect(status().isUnauthorized()); + verify(authenticationService).logoutToken("newtok"); + } + + @Test + void firstLogin_unknownToken_is401() throws Exception { + when(auth.loadUserByToken("tok")).thenReturn(null); + + mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON) + .content("{\"newPassword\":\"N3w-pass!\"}")) + .andExpect(status().isUnauthorized()); + verify(auth, never()).firstTimeLogin(any(), any()); + } + + @Test + void refresh_upstreamDeclines_returnsEmptyObject() throws Exception { + when(authenticationService.refreshToken("tok")).thenReturn(null); + + mvc.perform(post("/api/admin/auth/refresh")) + .andExpect(status().isOk()) + .andExpect(content().json("{}")); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceWireTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceWireTest.java new file mode 100644 index 0000000..21a1fbc --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAuthenticationServiceWireTest.java @@ -0,0 +1,67 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.mobile.api.model.AuthRequest; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.MediaType; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.http.HttpMethod.POST; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; + +class AdminAuthenticationServiceWireTest { + + private MockRestServiceServer server; + private AdminAuthenticationService service; + + @BeforeEach + void setUp() { + RestTemplate restTemplate = new RestTemplate(); + server = MockRestServiceServer.bindTo(restTemplate).build(); + RestTemplateCustomUtil util = new RestTemplateCustomUtil(restTemplate); + ReflectionTestUtils.setField(util, "apiUrl", "http://gw"); + ReflectionTestUtils.setField(util, "apiKey", "k"); + service = new AdminAuthenticationService(util); + } + + @Test + void getToken_postsToAdminAuthenticate_emptyBodyIsNull() { + server.expect(requestTo("http://gw/auth/authenticate")).andExpect(method(POST)) + .andExpect(content().json("{\"username\":\"admin\",\"password\":\"pw\"}")) + .andRespond(withSuccess("", MediaType.TEXT_PLAIN)); + AuthRequest r = new AuthRequest(); + r.setUsername("admin"); + r.setPassword("pw"); + + assertThat(service.getToken(r)).isNullOrEmpty(); + server.verify(); + } + + @Test + void firstTimeLogin_postsUserIdAndBothPasswordsToAdminEndpoint() { + server.expect(requestTo("http://gw/user/firstTimeLogin")).andExpect(method(POST)) + .andExpect(content().json("{\"userId\":9,\"newPassword\":\"New#Pass1\",\"repeatPassword\":\"New#Pass1\"}")) + .andRespond(withSuccess("true", MediaType.APPLICATION_JSON)); + + assertThat(service.firstTimeLogin(9L, "New#Pass1")).isTrue(); + server.verify(); + } + + @Test + void resetAdminPassword_postsUsernameAndEmail() { + server.expect(requestTo("http://gw/user/resetAdminPassword")).andExpect(method(POST)) + .andExpect(content().json("{\"username\":\"sales1\",\"email\":\"a@b.c\"}")) + .andRespond(withSuccess("1", MediaType.APPLICATION_JSON)); + + assertThat(service.resetAdminPassword("sales1", "a@b.c")).isEqualTo(1); + server.verify(); + } +} 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 ccc6bb4..cd22d66 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 @@ -853,7 +853,8 @@ public class UserController { User user = userService.findByUsername(username); if(user == null)return 0; if(!user.getType().equals(UserType.A)) return 0; - if(!user.getEmail().equalsIgnoreCase(emailAddress)) return 0; + if(!user.isEnabled()) return 0; + if(user.getEmail() == null || !user.getEmail().equalsIgnoreCase(emailAddress)) return 0; String randPassword = validateUtil.getRandomPasswordString(8); String newPassword = bCryptPasswordEncoder.encode(randPassword); diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerResetAdminPasswordTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerResetAdminPasswordTest.java new file mode 100644 index 0000000..e70925f --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerResetAdminPasswordTest.java @@ -0,0 +1,50 @@ +package com.solvway.services.system.controller; + +import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.model.User; +import com.solvway.services.system.service.EmailService; +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 java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class UserControllerResetAdminPasswordTest { + + @Mock + private UserService userService; + @Mock + private EmailService emailService; + @InjectMocks + private UserController controller; + + @Test + void deactivatedAdminIsNotReset() { + User user = new User(); + user.setId(5L); + user.setUsername("sales1"); + user.setEmail("sales1@example.com"); + user.setType(UserType.A); + user.setEnabled(false); + when(userService.findByUsername("sales1")).thenReturn(user); + + int updated = controller.resetAdminPassword(new HashMap<>(Map.of("username", "sales1", "email", "sales1@example.com"))); + + assertThat(updated).isZero(); + verify(userService, never()).resetPassword(anyLong(), anyString(), any()); + verify(emailService, never()).send(any()); + } +} -- 2.54.1 From f5d1b6d032753e3badb54eb1cc069db747eb64f3 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 20:26:33 +0800 Subject: [PATCH 07/19] feat(mobile-api): admin users API (list, create, edit, deactivate, reset password) New users get a temporary password by email and the creating admin's company. Self-deactivation and super-admin changes by non-super admins are refused. services-system: saving a user no longer cascades into role rows. Local seed: dev admin on the GLOBAL branch (id 0 does not exist). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 2 +- .../add-admin-auth-users-roles/tasks.md | 2 +- .../java/com/solvway/core/model/User.java | 1 + .../api/RestApiSystemServiceConstants.java | 7 + .../controller/admin/AdminUserController.java | 63 ++ .../mobile/api/dto/admin/AdminRoleRef.java | 6 + .../api/dto/admin/AdminUserRequest.java | 10 + .../mobile/api/service/AdminUserService.java | 277 +++++++++ .../admin/AdminUserControllerTest.java | 108 ++++ .../api/service/AdminUserServiceTest.java | 563 ++++++++++++++++++ .../solvway/services/system/model/User.java | 2 +- 11 files changed, 1038 insertions(+), 3 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminUserController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRef.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminUserRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminUserControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceTest.java diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index d25b23e..400988b 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -22,6 +22,6 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic -- Dev admin: super admin, company 1, password already set (login 'Y', no first-login change). INSERT INTO `user` (`id`, `email`, `enabled`, `name`, `password`, `username`, `groupid`, `branchid`, `login`, `status`, `type`, `create_by`, `create_date`, `done_by`, `company_id`) -VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 0, +VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 1, 'Y', 'Y', 'A', 'seed', NOW(), 'seed', 1); INSERT INTO `users_roles` (`user_id`, `role_id`) VALUES (1, 1); diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index b8cbc9d..4ac3be7 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -24,7 +24,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 5. mobile-api users and roles -- [ ] 5.1 Port `AdminUserController` and `AdminUserService`: admin-only list with search, filter and sort; create with temporary password, email and company from the logged-in admin; edit; deactivate with self-deactivation refused; admin-triggered reset via `/user/resetAdminPassword`. Tests first for each `admin-users` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. +- [x] 5.1 Port `AdminUserController` and `AdminUserService`: admin-only list with search, filter and sort; create with temporary password, email and company from the logged-in admin; edit; deactivate with self-deactivation refused; admin-triggered reset via `/user/resetAdminPassword`. Tests first for each `admin-users` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: as 4.1 - [ ] 5.2 Port `AdminRoleController`, `AdminRoleService` and `AdminAclService` (role list hiding `ROLE_MEMBER`, create and rename with unique names, `GET/PUT /roles/{id}/modules` replacing grants, self lock-out refused, super admin grants not editable). Tests first for each `admin-roles` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: as 4.1 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 f58257d..4799c87 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 @@ -88,6 +88,7 @@ public class User implements Serializable{ private FlagYesNo fromEmrm = FlagYesNo.N; private String aclHtml; private String uuid; + private Long companyId; public User() { } 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 efca2a0..f01e012 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 @@ -5,6 +5,13 @@ public class RestApiSystemServiceConstants { private RestApiSystemServiceConstants() {} public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}"; + public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}"; + public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}"; + public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}"; + public static final String API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE = "/user/findByPropertyAndPageable"; + public static final String API_REST_SYSTEM_ROLE_FIND_ALL = "/role/findAll"; + public static final String API_REST_SYSTEM_USER_SAVE = "/user/save"; + public static final String API_REST_SYSTEM_USER_UPDATE_USER_PASSWORD = "/user/updateUserPassword"; public static final String API_REST_SYSTEM_USER_FIND_EXIST_BY_USERNAME = "/user/findExistByUsername/{username}"; public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME_WITH_PASSWORD = "/user/findByUsernameWithPassword/{username}"; public static final String API_REST_SYSTEM_USER_UPDATE_MEMBER_PHONE_VERIFIED = "/user/updatePhoneVerified"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminUserController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminUserController.java new file mode 100644 index 0000000..b975191 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminUserController.java @@ -0,0 +1,63 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminUserRequest; +import com.solvway.mobile.api.service.AdminUserService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** Admin user CRUD for the portal. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +@AdminModule("BO_USERS") +public class AdminUserController { + private final AdminUserService adminUserService; + + @AppAuth + @GetMapping("/users") + public ResponseEntity> list( + @RequestParam(required = false) String q, + @RequestParam(required = false) String searchKey, + @RequestParam(required = false) String enabled, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size, + @RequestParam(required = false) String sortBy, + @RequestParam(required = false) String sortDir) { + return ResponseEntity.ok(adminUserService.list(q != null ? q : searchKey, enabled, page, size, sortBy, sortDir)); + } + + @AppAuth + @GetMapping("/users/{id}") + public ResponseEntity> getById(@PathVariable Long id) { + return ResponseEntity.ok(adminUserService.findById(id)); + } + + @AppAuth + @PostMapping("/users") + public ResponseEntity> create(@RequestBody AdminUserRequest request) { + return ResponseEntity.ok(adminUserService.create(request)); + } + + @AppAuth + @PutMapping("/users/{id}") + public ResponseEntity> update(@PathVariable Long id, @RequestBody AdminUserRequest request) { + return ResponseEntity.ok(adminUserService.update(id, request)); + } + + @AppAuth + @PostMapping("/users/{id}/changePassword") + public ResponseEntity> changePassword(@PathVariable Long id, @RequestBody Map body) { + return ResponseEntity.ok(Map.of("updated", adminUserService.changePassword(id, body.get("password")))); + } + + @AppAuth + @PostMapping("/users/{id}/resetPassword") + public ResponseEntity> resetPassword(@PathVariable Long id) { + return ResponseEntity.ok(Map.of("updated", adminUserService.resetPassword(id))); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRef.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRef.java new file mode 100644 index 0000000..0b0ec10 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRef.java @@ -0,0 +1,6 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminRoleRef(Long id, String name) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminUserRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminUserRequest.java new file mode 100644 index 0000000..e7bcfaf --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminUserRequest.java @@ -0,0 +1,10 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +/** Fields an admin may set. Username, type, company and password are deliberately absent: the portal's extra fields are ignored. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminUserRequest(String name, String surname, String username, String email, Boolean enabled, + List roles) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java new file mode 100644 index 0000000..0475865 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java @@ -0,0 +1,277 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminRoleRef; +import com.solvway.mobile.api.dto.admin.AdminUserRequest; +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.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Admin users for the portal. Users travel as maps so fields the core {@link User} lacks (status) survive + * the round trip to services-system, whose /user/save is a full-entity save. + */ +@Service +@RequiredArgsConstructor +public class AdminUserService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final long SUPER_ADMIN_ROLE_ID = 1L; + private static final List SECRETS = List.of("password", "passwordSecondary", "passwordEmrm"); + private static final List SAVE_FIELDS = List.of("id", "name", "surname", "email", "username", "enabled", "status", + "login", "type", "companyId", "emailVerified", "phoneVerified", "fromEmrm", "master", "lastModifiedPwd", + "createBy", "doneBy", "createDate"); + private static final Map>> SORTS = Map.of( + "name", by("name"), "username", by("username"), "email", by("email"), + "enabled", by("enabled"), + "roles", Comparator.comparing(m -> roleNames(m).toLowerCase())); + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + + /** + * ponytail: services-system findByPropertyAndPageable ignores q, enabled and sorts, so this loads all + * admins (staff-sized) and filters, sorts and pages here. Upgrade: extend that downstream query. + * It is not company-scoped: that must be added before multi-company. + */ + public Map list(String q, String enabled, int page, int size, String sortBy, String sortDir) { + Map request = Map.of("property", Map.of("type", "A"), + "pageableRest", Map.of("number", 0, "size", 10000, "sorts", List.of(Map.of("direction", "ASC", "property", "id")))); + ResponseEntity> ent = restTemplateUtil.postForEntity( + url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request); + List> all = ent.getBody() == null ? List.of() : (List>) ent.getBody().get("content"); + resolveRoleRefs(all); + String needle = q == null ? "" : q.trim().toLowerCase(); + Comparator> order = SORTS.getOrDefault(sortBy == null ? "name" : sortBy, SORTS.get("name")); + if ("desc".equalsIgnoreCase(sortDir)) order = order.reversed(); + List> filtered = all.stream() + .filter(m -> needle.isEmpty() || contains(m, "name", needle) || contains(m, "username", needle) || contains(m, "email", needle)) + .filter(m -> !"true".equalsIgnoreCase(enabled) && !"false".equalsIgnoreCase(enabled) + || String.valueOf(m.get("enabled")).equalsIgnoreCase(enabled)) + .sorted(order).toList(); + int s = Math.max(size, 1); + int from = (int) Math.min((long) Math.max(page, 0) * s, filtered.size()); + List> content = filtered.subList(from, Math.min(from + s, filtered.size())).stream() + .map(AdminUserService::clean).toList(); + return Map.of("content", content, "totalElements", (long) filtered.size(), + "totalPages", (filtered.size() + s - 1) / s, "number", Math.max(page, 0), "size", s); + } + + public Map findById(Long id) { + return clean(load(id)); + } + + public Map create(AdminUserRequest r) { + if (!StringUtils.hasText(r.name()) || !StringUtils.hasText(r.username()) || !StringUtils.hasText(r.email()) + || r.roles() == null || r.roles().isEmpty()) { + throw error(HttpStatus.BAD_REQUEST, "Name, username, email and at least one role are required", "REQUIRED_FIELD"); + } + User caller = caller(); + requireSuperToGrant(caller, r.roles()); + if (caller.getBranch() == null || caller.getBranch().getId() == null) { + throw error(HttpStatus.BAD_REQUEST, "Your account has no branch to assign", "BRANCH_REQUIRED"); + } + // ponytail: check-then-save is not atomic; the DB unique key on username is the backstop. + if (get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_USERNAME, r.username()) != null) { + throw error(HttpStatus.CONFLICT, "Username is already taken", "USERNAME_TAKEN"); + } + if (get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL, r.email()) != null) { + throw error(HttpStatus.CONFLICT, "Email is already taken", "EMAIL_TAKEN"); + } + Map user = new HashMap<>(); + user.put("name", r.name()); + user.put("surname", r.surname()); + user.put("username", r.username()); + user.put("email", r.email()); + user.put("roles", roles(r.roles())); + user.put("enabled", true); + user.put("status", "Y"); + user.put("type", "A"); + user.put("login", "N"); + user.put("companyId", caller.getCompanyId()); + user.put("branch", Map.of("id", caller.getBranch().getId())); + user.put("createBy", caller.getUsername()); + user.put("doneBy", caller.getUsername()); + user.put("createDate", System.currentTimeMillis()); + Map saved = save(user); + if (adminAuthenticationService.resetAdminPassword(r.username(), r.email()) == 0) { + throw error(HttpStatus.BAD_GATEWAY, "User created but the temporary password email was not sent; retry the password reset", "TEMP_PASSWORD_NOT_SENT"); + } + return clean(saved); + } + + public Map update(Long id, AdminUserRequest r) { + User caller = caller(); + Map user = loadManaged(id, caller); + requireSuperToGrant(caller, r.roles()); + if (r.enabled() != null && !r.enabled() && caller.getId() != null && caller.getId().equals(id)) { + throw error(HttpStatus.BAD_REQUEST, "You cannot deactivate your own account", "SELF_DEACTIVATION"); + } + if (StringUtils.hasText(r.email()) && get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT, r.email(), id) != null) { + throw error(HttpStatus.CONFLICT, "Email is already taken", "EMAIL_TAKEN"); + } + if (r.roles() != null && r.roles().isEmpty()) { + throw error(HttpStatus.BAD_REQUEST, "At least one role is required", "REQUIRED_FIELD"); + } + if (StringUtils.hasText(r.name())) user.put("name", r.name()); + if (r.surname() != null) user.put("surname", r.surname()); + if (StringUtils.hasText(r.email())) user.put("email", r.email()); + if (r.roles() != null) user.put("roles", roles(r.roles())); + if (r.enabled() != null) { + user.put("enabled", r.enabled()); + user.put("status", r.enabled() ? "Y" : "N"); + } + user.put("doneBy", caller.getUsername()); + return clean(save(user)); + } + + public int resetPassword(Long id) { + Map user = loadManaged(id, caller()); + return adminAuthenticationService.resetAdminPassword((String) user.get("username"), (String) user.get("email")); + } + + public int changePassword(Long id, String password) { + loadManaged(id, caller()); + ResponseEntity ent = restTemplateUtil.postForEntity( + url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_UPDATE_USER_PASSWORD), Integer.class, + Map.of("userId", id, "password", password == null ? "" : password)); + int updated = ent.getBody() == null ? 0 : ent.getBody(); + if (updated == 0) throw error(HttpStatus.BAD_REQUEST, "Password does not meet the password rules", "PASSWORD_RULES"); + return updated; + } + + private Map load(Long id) { + Map user = get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID, id); + if (user == null || !"A".equals(user.get("type"))) throw error(HttpStatus.NOT_FOUND, "User not found", "USER_NOT_FOUND"); + return user; + } + + /** The target admin; a non-super caller may not manage a super admin. */ + private Map loadManaged(Long id, User caller) { + Map user = load(id); + if (!isSuper(caller) && user.get("roles") instanceof List l && l.stream().anyMatch( + x -> x instanceof Map m && m.get("id") instanceof Number n && n.longValue() == SUPER_ADMIN_ROLE_ID)) { + throw superRequired("Only a super admin can manage a super admin"); + } + return user; + } + + private static boolean isSuper(User caller) { + return caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID); + } + + private static void requireSuperToGrant(User caller, List requested) { + if (!isSuper(caller) && requested != null && requested.stream().anyMatch(r -> r.id() != null && r.id() == SUPER_ADMIN_ROLE_ID)) { + throw superRequired("Only a super admin can grant the super admin role"); + } + } + + private static CodedResponseStatusException superRequired(String reason) { + return error(HttpStatus.FORBIDDEN, reason, "SUPER_ADMIN_REQUIRED"); + } + + /** services-system's /user/save merges roles, so an id-only role would blank the stored row: send the stored ones. */ + private List> roles(List refs) { + List> stored = restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_FIND_ALL), MAP_LIST).getBody(); + List> out = new ArrayList<>(); + for (AdminRoleRef ref : refs) { + out.add((stored == null ? List.>of() : stored).stream() + .filter(m -> m.get("id") instanceof Number n && ref.id() != null && n.longValue() == ref.id()) + .findFirst().orElseThrow(() -> error(HttpStatus.BAD_REQUEST, "Unknown role " + ref.id(), "UNKNOWN_ROLE"))); + } + return out; + } + + /** services-system serialises a repeated role as a bare id; swap each for the first full occurrence in the list. */ + private static void resolveRoleRefs(List> users) { + Map byId = new HashMap<>(); + for (Map u : users) { + if (u.get("roles") instanceof List l) { + for (Object r : l) if (r instanceof Map m && m.get("id") instanceof Number n) byId.putIfAbsent(n.longValue(), m); + } + } + for (Map u : users) { + if (u.get("roles") instanceof List l) { + u.put("roles", l.stream().map(r -> r instanceof Number n ? byId.get(n.longValue()) : r).filter(java.util.Objects::nonNull).toList()); + } + } + } + + /** + * services-system /user/save writes the whole entity and cannot bind what findById returns (masked passwords, + * nested role/branch trees, transients), so send only the persistent columns, with roles/branch/group as refs. + */ + private static Map slim(Map user) { + Map out = new HashMap<>(); + for (String k : SAVE_FIELDS) if (user.containsKey(k)) out.put(k, user.get(k)); + for (String k : List.of("branch", "userGroup")) { + if (user.get(k) instanceof Map m && m.get("id") != null) out.put(k, Map.of("id", m.get("id"))); + } + if (user.get("roles") instanceof List l) { + out.put("roles", l.stream().map(r -> (Map) r) + .map(r -> Map.of("id", r.get("id"), "name", String.valueOf(r.get("name")))).toList()); + } + return out; + } + + private Map save(Map user) { + ResponseEntity> ent = restTemplateUtil.postForEntity( + url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_SAVE), MAP, slim(user)); + // services-system swallows save errors and returns the unsaved entity, so a missing id means it failed. + if (ent.getBody() == null || ent.getBody().get("id") == null) { + throw error(HttpStatus.INTERNAL_SERVER_ERROR, "User could not be saved", "SAVE_FAILED"); + } + return ent.getBody(); + } + + private Map get(String api, Object... vars) { + return restTemplateUtil.getForEntity(url(api), MAP, vars).getBody(); + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + return caller; + } + + private static Map clean(Map user) { + Map out = new HashMap<>(user); + SECRETS.forEach(out::remove); + return out; + } + + private static boolean contains(Map m, String key, String needle) { + return m.get(key) != null && m.get(key).toString().toLowerCase().contains(needle); + } + + private static Comparator> by(String key) { + return Comparator.comparing(m -> String.valueOf(m.get(key)).toLowerCase()); + } + + private static String roleNames(Map m) { + Object roles = m.get("roles"); + if (!(roles instanceof List l)) return ""; + return String.join(",", l.stream().map(r -> r instanceof Map rm ? String.valueOf(rm.get("name")) : "").toList()); + } + + private static CodedResponseStatusException error(HttpStatus status, String reason, String code) { + return new CodedResponseStatusException(status, reason, code); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminUserControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminUserControllerTest.java new file mode 100644 index 0000000..976b6c0 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminUserControllerTest.java @@ -0,0 +1,108 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.mobile.api.dto.admin.AdminUserRequest; +import com.solvway.mobile.api.service.AdminUserService; +import com.solvway.mobile.api.useraccess.AdminModule; +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.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +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.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.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminUserControllerTest { + + @Mock private AdminUserService users; + @InjectMocks private AdminUserController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void guardedByBackOfficeUsersModule() { + assertThat(AdminUserController.class.getAnnotation(AdminModule.class).value()).containsExactly("BO_USERS"); + } + + @Test + void list_passesParamsAndReturnsPageShape() throws Exception { + when(users.list("ali", "true", 1, 5, "name", "desc")) + .thenReturn(Map.of("content", List.of(Map.of("id", 1)), "totalElements", 6L)); + mvc.perform(get("/api/admin/users").param("q", "ali").param("enabled", "true").param("page", "1") + .param("size", "5").param("sortBy", "name").param("sortDir", "desc")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content[0].id").value(1)) + .andExpect(jsonPath("$.totalElements").value(6)); + } + + @Test + void list_legacySearchKeyActsAsQ() throws Exception { + when(users.list("bob", null, 0, 20, null, null)).thenReturn(Map.of("content", List.of())); + mvc.perform(get("/api/admin/users").param("searchKey", "bob")).andExpect(status().isOk()); + verify(users).list("bob", null, 0, 20, null, null); + } + + @Test + void getById_returnsUser() throws Exception { + when(users.findById(5L)).thenReturn(Map.of("id", 5, "username", "a")); + mvc.perform(get("/api/admin/users/5")).andExpect(status().isOk()).andExpect(jsonPath("$.username").value("a")); + } + + @Test + void create_ignoresPortalExtrasAndPassesRequest() throws Exception { + when(users.create(any())).thenReturn(Map.of("id", 9)); + mvc.perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"N\",\"username\":\"u\",\"email\":\"e@x.com\",\"password\":\"x\",\"companyId\":99," + + "\"roles\":[{\"id\":4,\"name\":\"R\"}]}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(9)); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminUserRequest.class); + verify(users).create(c.capture()); + assertThat(c.getValue().username()).isEqualTo("u"); + assertThat(c.getValue().roles().get(0).id()).isEqualTo(4L); + } + + @Test + void update_passesIdAndRequest() throws Exception { + when(users.update(any(), any())).thenReturn(Map.of("id", 5)); + mvc.perform(put("/api/admin/users/5").contentType(MediaType.APPLICATION_JSON).content("{\"enabled\":false}")) + .andExpect(status().isOk()); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminUserRequest.class); + verify(users).update(org.mockito.ArgumentMatchers.eq(5L), c.capture()); + assertThat(c.getValue().enabled()).isFalse(); + } + + @Test + void resetPassword_returnsUpdated() throws Exception { + when(users.resetPassword(5L)).thenReturn(1); + mvc.perform(post("/api/admin/users/5/resetPassword")).andExpect(status().isOk()) + .andExpect(jsonPath("$.updated").value(1)); + } + + @Test + void changePassword_returnsUpdated() throws Exception { + when(users.changePassword(5L, "Str0ng#Pass")).thenReturn(1); + mvc.perform(post("/api/admin/users/5/changePassword").contentType(MediaType.APPLICATION_JSON) + .content("{\"password\":\"Str0ng#Pass\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.updated").value(1)); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceTest.java new file mode 100644 index 0000000..a5b0b86 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceTest.java @@ -0,0 +1,563 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.LocationHierarchy; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminRoleRef; +import com.solvway.mobile.api.dto.admin.AdminUserRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +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 AdminUserServiceTest { + + private static final String FIND_BY_ID = "/user/findById/{id}"; + private static final String SAVE = "/user/save"; + private static final String PAGE = "/user/findByPropertyAndPageable"; + private static final String BY_USERNAME = "/user/findByUsername/{username}"; + private static final String BY_EMAIL = "/user/findByEmail/{email}"; + private static final String BY_EMAIL_NOT = "/user/findByEmailAndIdNot/{email}/{id}"; + private static final String UPDATE_PWD = "/user/updateUserPassword"; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminUserService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + service = new AdminUserService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + User caller = new User(); + caller.setId(1L); + caller.setUsername("boss"); + caller.setCompanyId(7L); + LocationHierarchy branch = new LocationHierarchy(); + branch.setId(3L); + caller.setBranch(branch); + when(auth.loadUserByToken("tok")).thenReturn(caller); + when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class))) + .thenReturn(ResponseEntity.ok(List.of(fullRole(1, "ROLE_SUPER_ADMIN"), fullRole(4, "ROLE_SALES"), fullRole(5, "ROLE_OPS")))); + } + + private static Map fullRole(long id, String name) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("level", 2); + m.put("tracekey", "tk" + id); + m.put("createBy", "sys"); + return m; + } + + private void callerIsSuper() { + Role r = new Role(); + r.setId(1L); + when(auth.loadUserByToken("tok")).thenAnswer(i -> { + User u = new User(); + u.setId(1L); + u.setUsername("boss"); + u.setCompanyId(7L); + LocationHierarchy b = new LocationHierarchy(); + b.setId(3L); + u.setBranch(b); + u.setRoles(List.of(r)); + return u; + }); + } + + private Map superAdminRow(long id) { + Map m = row(id, "Root", "root", "r@x.com", true); + m.put("roles", List.of(fullRole(1, "ROLE_SUPER_ADMIN"))); + return m; + } + + @AfterEach + void close() { http.close(); } + + private Map row(long id, String name, String username, String email, boolean enabled, String... roles) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("username", username); + m.put("email", email); + m.put("enabled", enabled); + m.put("type", "A"); + m.put("password", "$2a$secret"); + m.put("passwordSecondary", "$2a$secret2"); + m.put("passwordEmrm", "$2a$secret3"); + List> rs = new ArrayList<>(); + for (String r : roles) rs.add(new HashMap<>(Map.of("id", 10L, "name", r))); + m.put("roles", rs); + return m; + } + + private void stubPage(Map... rows) { + when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(rows)))); + } + + private void stubFind(long id, Map row) { + when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(id))) + .thenReturn(ResponseEntity.ok(row)); + } + + private void stubSave(Map saved) { + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(saved)); + } + + private void stubNoDuplicates() { + when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any())) + .thenReturn(ResponseEntity.ok().build()); + when(auth.resetAdminPassword(anyString(), anyString())).thenReturn(1); + } + + private AdminUserRequest req(String name, String username, String email, List roles) { + return new AdminUserRequest(name, null, username, email, null, roles); + } + + private static final List ROLES = List.of(new AdminRoleRef(4L, "ROLE_SALES")); + + private static void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + // ---- list ---- + + @Test + void list_asksDownstreamForAdminsOnly() { + stubPage(row(1, "A", "a", "a@x.com", true, "R")); + service.list(null, null, 0, 20, null, null); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture()); + Map sent = (Map) body.getValue(); + assertThat((Map) sent.get("property")).containsEntry("type", "A"); + } + + @Test + void list_searchesNameUsernameEmailCaseInsensitive() { + stubPage(row(1, "Alice Tan", "alice", "a@x.com", true, "R"), + row(2, "Bob", "bobby", "b@x.com", true, "R"), + row(3, "Cy", "cy", "CARL@x.com", true, "R")); + assertThat(names(service.list("ALI", null, 0, 20, null, null))).containsExactly("Alice Tan"); + assertThat(names(service.list("bobb", null, 0, 20, null, null))).containsExactly("Bob"); + assertThat(names(service.list("carl", null, 0, 20, null, null))).containsExactly("Cy"); + } + + @Test + void list_filtersByEnabled() { + stubPage(row(1, "On", "on", "o@x.com", true, "R"), row(2, "Off", "off", "f@x.com", false, "R")); + assertThat(names(service.list(null, "false", 0, 20, null, null))).containsExactly("Off"); + assertThat(names(service.list(null, "true", 0, 20, null, null))).containsExactly("On"); + assertThat(names(service.list(null, null, 0, 20, null, null))).hasSize(2); + } + + @Test + void list_sortsAndPagesOnTheServer() { + stubPage(row(1, "Cc", "c", "c@x.com", true, "R"), row(2, "Aa", "a", "a@x.com", true, "R"), + row(3, "Bb", "b", "b@x.com", true, "R")); + Map p0 = service.list(null, null, 0, 2, "name", "asc"); + assertThat(names(p0)).containsExactly("Aa", "Bb"); + assertThat(p0).containsEntry("totalElements", 3L).containsEntry("totalPages", 2) + .containsEntry("number", 0).containsEntry("size", 2); + assertThat(names(service.list(null, null, 1, 2, "name", "asc"))).containsExactly("Cc"); + assertThat(names(service.list(null, null, 0, 3, "username", "desc"))).containsExactly("Cc", "Bb", "Aa"); + } + + @Test + void list_neverReturnsPasswordHashes() { + stubPage(row(1, "A", "a", "a@x.com", true, "R")); + Map first = ((List>) service.list(null, null, 0, 20, null, null).get("content")).get(0); + assertThat(first).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm"); + } + + private List names(Map page) { + return ((List>) page.get("content")).stream().map(m -> (String) m.get("name")).toList(); + } + + // ---- get ---- + + @Test + void findById_returnsAdminWithoutPasswords() { + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + assertThat(service.findById(5L)).containsEntry("username", "a") + .doesNotContainKeys("password", "passwordSecondary", "passwordEmrm"); + } + + @Test + void findById_unknownOrNonAdmin_is404() { + when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(8L))) + .thenReturn(ResponseEntity.ok().build()); + assertCoded(() -> service.findById(8L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + Map member = row(9, "M", "m", "m@x.com", true, "R"); + member.put("type", "M"); + stubFind(9, member); + assertCoded(() -> service.findById(9L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + } + + // ---- create ---- + + @Test + void create_savesActiveAdminWithCallerCompanyThenSendsTemporaryPassword() { + stubNoDuplicates(); + stubSave(row(20, "New", "newbie", "n@x.com", true, "ROLE_SALES")); + AdminUserRequest r = new AdminUserRequest("New", "Guy", "newbie", "n@x.com", false, ROLES); + + Map out = service.create(r); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + Map saved = (Map) body.getValue(); + assertThat(saved).containsEntry("username", "newbie").containsEntry("email", "n@x.com") + .containsEntry("name", "New").containsEntry("enabled", true).containsEntry("status", "Y") + .containsEntry("type", "A").containsEntry("login", "N").containsEntry("companyId", 7L) + .containsEntry("createBy", "boss").containsEntry("doneBy", "boss"); + assertThat(saved).doesNotContainKey("id").doesNotContainKey("password"); + assertThat((Map) saved.get("branch")).containsEntry("id", 3L); + assertThat(((List>) saved.get("roles")).get(0)).containsEntry("id", 4L); + verify(auth).resetAdminPassword("newbie", "n@x.com"); + assertThat(out).containsEntry("id", 20L).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm"); + } + + @Test + void create_duplicateUsername_is409UsernameTaken() { + stubNoDuplicates(); + when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), eq("dup"))) + .thenReturn(ResponseEntity.ok(row(2, "X", "dup", "x@x.com", true, "R"))); + assertCoded(() -> service.create(req("N", "dup", "n@x.com", ROLES)), HttpStatus.CONFLICT, "USERNAME_TAKEN"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + verify(auth, never()).resetAdminPassword(anyString(), anyString()); + } + + @Test + void create_duplicateEmail_is409EmailTaken() { + stubNoDuplicates(); + when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("dup@x.com"))) + .thenReturn(ResponseEntity.ok(row(2, "X", "x", "dup@x.com", true, "R"))); + assertCoded(() -> service.create(req("N", "n", "dup@x.com", ROLES)), HttpStatus.CONFLICT, "EMAIL_TAKEN"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_missingRequiredFields_is400() { + assertCoded(() -> service.create(req("", "u", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(req("N", " ", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(req("N", "u", null, ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(req("N", "u", "e@x.com", List.of())), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(req("N", "u", "e@x.com", null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_callerWithoutBranch_is400BranchRequired() { + stubNoDuplicates(); + User noBranch = new User(); + noBranch.setCompanyId(7L); + when(auth.loadUserByToken("tok")).thenReturn(noBranch); + assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "BRANCH_REQUIRED"); + } + + @Test + void create_tempPasswordNotSent_is502AfterUserCreated() { + stubNoDuplicates(); + stubSave(row(20, "N", "u", "e@x.com", true, "R")); + when(auth.resetAdminPassword("u", "e@x.com")).thenReturn(0); + assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.BAD_GATEWAY, "TEMP_PASSWORD_NOT_SENT"); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_saveReturnsNoId_isServerError() { + stubNoDuplicates(); + stubSave(new HashMap<>()); + assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED"); + verify(auth, never()).resetAdminPassword(anyString(), anyString()); + } + + // ---- update ---- + + @Test + void update_changesOnlyNameEmailRolesEnabled() { + stubNoDuplicates(); + Map stored = row(5, "Old", "keep", "old@x.com", true, "R"); + stored.put("companyId", 7L); + stored.put("login", "Y"); + stubFind(5, stored); + stubSave(row(5, "New", "keep", "new@x.com", true, "ROLE_SALES")); + AdminUserRequest r = new AdminUserRequest("New", null, "hacker", "new@x.com", true, ROLES); + + service.update(5L, r); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + Map saved = (Map) body.getValue(); + assertThat(saved).containsEntry("id", 5L).containsEntry("name", "New").containsEntry("email", "new@x.com") + .containsEntry("username", "keep").containsEntry("type", "A").containsEntry("companyId", 7L) + .containsEntry("login", "Y").containsEntry("enabled", true).containsEntry("status", "Y"); + assertThat(((List>) saved.get("roles")).get(0)).containsEntry("id", 4L); + } + + @Test + void update_deactivate_setsEnabledFalseAndStatusN() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + stubSave(row(5, "A", "a", "a@x.com", false, "R")); + service.update(5L, new AdminUserRequest(null, null, null, null, false, null)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("enabled", false).containsEntry("status", "N"); + } + + @Test + void update_selfDeactivation_is400() { + stubFind(1, row(1, "Boss", "boss", "b@x.com", true, "R")); + assertCoded(() -> service.update(1L, new AdminUserRequest(null, null, null, null, false, null)), + HttpStatus.BAD_REQUEST, "SELF_DEACTIVATION"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void update_emailUsedByAnotherUser_is409() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), eq("taken@x.com"), eq(5L))) + .thenReturn(ResponseEntity.ok(row(2, "X", "x", "taken@x.com", true, "R"))); + assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, "taken@x.com", null, null)), + HttpStatus.CONFLICT, "EMAIL_TAKEN"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void update_unknownUser_is404() { + when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(8L))) + .thenReturn(ResponseEntity.ok().build()); + assertCoded(() -> service.update(8L, req("N", null, "e@x.com", ROLES)), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + } + + @Test + void update_blankEmail_skipsDuplicateCheckAndKeepsStoredEmail() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + stubSave(row(5, "A", "a", "a@x.com", true, "R")); + service.update(5L, new AdminUserRequest(null, null, null, "", null, null)); + verify(rest, never()).getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any()); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("email", "a@x.com"); + } + + @Test + void update_loadsCallerOnce() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + stubSave(row(5, "A", "a", "a@x.com", false, "R")); + service.update(5L, new AdminUserRequest("B", null, null, null, false, null)); + verify(auth, times(1)).loadUserByToken("tok"); + } + + // ---- roles are sent as {id, name} from the stored role ---- + + @Test + void create_sendsStoredRoleIdAndNameOnly() { + stubNoDuplicates(); + stubSave(row(20, "N", "u", "e@x.com", true, "R")); + service.create(req("N", "u", "e@x.com", List.of(new AdminRoleRef(4L, "whatever")))); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat(((List>) ((Map) body.getValue()).get("roles")).get(0)) + .containsOnlyKeys("id", "name").containsEntry("id", 4L).containsEntry("name", "ROLE_SALES"); + } + + @Test + void update_sendsStoredRoleIdAndNameOnly() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + stubSave(row(5, "A", "a", "a@x.com", true, "R")); + service.update(5L, new AdminUserRequest(null, null, null, null, null, ROLES)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat(((List>) ((Map) body.getValue()).get("roles")).get(0)) + .containsOnlyKeys("id", "name").containsEntry("name", "ROLE_SALES"); + } + + @Test + void update_savesOnlyWhitelistedUserFields() { + stubNoDuplicates(); + Map stored = row(5, "A", "a", "a@x.com", true, "R"); + stored.put("status", "Y"); + stored.put("companyId", 7L); + stored.put("emailVerified", "Y"); + stored.put("showPassword", false); + stored.put("linkedAccounts", List.of()); + stored.put("token", "t"); + stored.put("memberCode", "m"); + stored.put("branch", new HashMap<>(Map.of("id", 3L, "code", "G", "children", List.of()))); + stored.put("userGroup", new HashMap<>(Map.of("id", 9L, "name", "grp"))); + stubFind(5, stored); + stubSave(row(5, "A", "a", "a@x.com", true, "R")); + + service.update(5L, new AdminUserRequest(null, null, null, null, null, null)); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + Map saved = (Map) body.getValue(); + assertThat(saved).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm", "showPassword", + "linkedAccounts", "token", "memberCode"); + assertThat(saved).containsEntry("emailVerified", "Y").containsEntry("companyId", 7L); + assertThat((Map) saved.get("branch")).containsOnlyKeys("id"); + assertThat((Map) saved.get("userGroup")).containsOnlyKeys("id"); + } + + @Test + void list_sendsASortSoServicesSystemCanPage() { + stubPage(row(1, "A", "a", "a@x.com", true, "R")); + service.list(null, null, 0, 20, null, null); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture()); + Map pageable = (Map) ((Map) body.getValue()).get("pageableRest"); + assertThat((List>) pageable.get("sorts")).containsExactly(Map.of("direction", "ASC", "property", "id")); + } + + @Test + void unknownRole_is400UnknownRole_onCreateAndUpdate() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + List bad = List.of(new AdminRoleRef(99L, "NOPE")); + assertCoded(() -> service.create(req("N", "u", "e@x.com", bad)), HttpStatus.BAD_REQUEST, "UNKNOWN_ROLE"); + assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, null, null, bad)), + HttpStatus.BAD_REQUEST, "UNKNOWN_ROLE"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + // ---- super admin guard ---- + + private static final List SUPER = List.of(new AdminRoleRef(1L, "ROLE_SUPER_ADMIN")); + + @Test + void nonSuperCaller_cannotGrantSuperAdmin() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + assertCoded(() -> service.create(req("N", "u", "e@x.com", SUPER)), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, null, null, SUPER)), + HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void superCaller_canGrantSuperAdmin() { + stubNoDuplicates(); + callerIsSuper(); + stubSave(row(20, "N", "u", "e@x.com", true, "R")); + service.create(req("N", "u", "e@x.com", SUPER)); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void nonSuperCaller_cannotManageSuperAdminTarget() { + stubNoDuplicates(); + stubFind(6, superAdminRow(6)); + assertCoded(() -> service.update(6L, new AdminUserRequest("X", null, null, null, null, null)), + HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + assertCoded(() -> service.resetPassword(6L), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + assertCoded(() -> service.changePassword(6L, "Str0ng#Pass"), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + verify(rest, never()).postForEntity(eq(UPDATE_PWD), eq(Integer.class), any()); + verify(auth, never()).resetAdminPassword(anyString(), anyString()); + } + + @Test + void superCaller_canManageSuperAdminTarget() { + callerIsSuper(); + stubFind(6, superAdminRow(6)); + when(auth.resetAdminPassword("root", "r@x.com")).thenReturn(1); + assertThat(service.resetPassword(6L)).isEqualTo(1); + } + + // ---- shared roles in list (services-system sends repeats as bare ids) ---- + + private Map userWithRoles(long id, String name, Object... roles) { + Map m = row(id, name, name.toLowerCase(), name + "@x.com", true); + m.put("roles", new ArrayList<>(List.of(roles))); + return m; + } + + @Test + void list_sharedRoleSentAsBareId_sortByRolesDoesNotThrow() { + stubPage(userWithRoles(1, "Aa", fullRole(4, "ROLE_SALES")), userWithRoles(2, "Bb", 4L)); + assertThat(names(service.list(null, null, 0, 20, "roles", "asc"))).containsExactly("Aa", "Bb"); + } + + @Test + void list_bareRoleIdResolvedEvenWhenFullRoleIsOnAnotherPage() { + stubPage(userWithRoles(1, "Aa", fullRole(4, "ROLE_SALES")), userWithRoles(2, "Bb", 4L)); + Map page1 = service.list(null, null, 1, 1, "name", "asc"); + Map u = ((List>) page1.get("content")).get(0); + assertThat(u).containsEntry("name", "Bb"); + assertThat(((List>) u.get("roles")).get(0)).containsEntry("name", "ROLE_SALES").containsEntry("tracekey", "tk4"); + } + + // ---- passwords ---- + + @Test + void resetPassword_usesStoredUsernameAndEmail() { + stubFind(5, row(5, "A", "stored", "stored@x.com", true, "R")); + when(auth.resetAdminPassword("stored", "stored@x.com")).thenReturn(1); + assertThat(service.resetPassword(5L)).isEqualTo(1); + verify(auth).resetAdminPassword("stored", "stored@x.com"); + } + + @Test + void changePassword_rulesRejected_is400() { + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + when(rest.postForEntity(eq(UPDATE_PWD), eq(Integer.class), any())).thenReturn(ResponseEntity.ok(0)); + assertCoded(() -> service.changePassword(5L, "weak"), HttpStatus.BAD_REQUEST, "PASSWORD_RULES"); + } + + @Test + void changePassword_ok_returnsRowsUpdated() { + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + when(rest.postForEntity(eq(UPDATE_PWD), eq(Integer.class), any())).thenReturn(ResponseEntity.ok(1)); + assertThat(service.changePassword(5L, "Str0ng#Pass")).isEqualTo(1); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(UPDATE_PWD), eq(Integer.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("userId", 5L).containsEntry("password", "Str0ng#Pass"); + } +} 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 9fc02c2..9ab4b9a 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 @@ -69,7 +69,7 @@ public class User { @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Long.class) - @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE) + @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "users_roles", joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "role_id")}) -- 2.54.1 From 4d261d20d5a6710e4b6a23f53cf5f3325b5665a0 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 20:26:46 +0800 Subject: [PATCH 08/19] docs: hide ROLE_ADMIN from role management (attached to every admin, grants nothing) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-admin-auth-users-roles/design.md | 2 +- .../add-admin-auth-users-roles/specs/admin-roles/spec.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/openspec/changes/add-admin-auth-users-roles/design.md b/openspec/changes/add-admin-auth-users-roles/design.md index e835415..4299fd6 100644 --- a/openspec/changes/add-admin-auth-users-roles/design.md +++ b/openspec/changes/add-admin-auth-users-roles/design.md @@ -55,7 +55,7 @@ Area `BO`, babyboo's id scheme: `40000000 BO_ROOT` (type R), `40700000 BO_USERS` ### 7. Roles shown -The role list hides `ROLE_MEMBER`. The local seed drops Tastefully's business roles (KYC, merchant, staff and the rest) and keeps `ROLE_SUPER_ADMIN` (1), `ROLE_ADMIN` (2) and `ROLE_MEMBER` (3). +The role list hides `ROLE_MEMBER` and `ROLE_ADMIN` (id 2, attached to every admin by `findUserByToken` and ignored by the module check). The local seed drops Tastefully's business roles (KYC, merchant, staff and the rest) and keeps `ROLE_SUPER_ADMIN` (1), `ROLE_ADMIN` (2) and `ROLE_MEMBER` (3). ### 8. Portal cut-down diff --git a/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md b/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md index 8ac436c..6749135 100644 --- a/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md +++ b/openspec/changes/add-admin-auth-users-roles/specs/admin-roles/spec.md @@ -8,7 +8,7 @@ Admins with the Roles module define roles and choose which back-office modules e ### Requirement: Role list and edit -The system SHALL let an admin with `BO_ROLES` list, create and rename admin roles. Role names SHALL be unique. The member role SHALL NOT appear in the list. +The system SHALL let an admin with `BO_ROLES` list, create and rename admin roles. Role names SHALL be unique. The member role and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules). #### Scenario: Create role @@ -23,7 +23,7 @@ The system SHALL let an admin with `BO_ROLES` list, create and rename admin role ### Requirement: Role permissions -The system SHALL let an admin with `BO_ROLES` choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The super admin role's grants SHALL NOT be editable. +The system SHALL let an admin with `BO_ROLES` choose, for a role, which back-office modules it grants, shown as the module tree. Saving SHALL replace the role's module grants with the chosen set. The grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. #### Scenario: Grant Users module -- 2.54.1 From a8cdf33a24df362cba5e8540c20a7c2f17713b4c Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 20:48:05 +0800 Subject: [PATCH 09/19] feat(mobile-api): admin roles API (list, create, rename, module grants) Member and ROLE_ADMIN roles are hidden; super admin grants are not editable; removing your own last BO_ROLES grant is refused. Renaming keeps child roles intact. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-admin-auth-users-roles/tasks.md | 2 +- .../api/RestApiSystemServiceConstants.java | 4 + .../controller/admin/AdminRoleController.java | 61 +++++ .../api/dto/admin/AdminGrantsRequest.java | 8 + .../api/dto/admin/AdminModuleGrant.java | 4 + .../api/dto/admin/AdminRoleRequest.java | 7 + .../mobile/api/service/AdminAclService.java | 106 ++++++++ .../mobile/api/service/AdminRoleService.java | 161 ++++++++++++ .../admin/AdminRoleControllerTest.java | 137 ++++++++++ .../api/service/AdminAclServiceTest.java | 242 ++++++++++++++++++ .../api/service/AdminRoleServiceTest.java | 233 +++++++++++++++++ 11 files changed, 964 insertions(+), 1 deletion(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGrantsRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminModuleGrant.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRoleControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index 4ac3be7..a929a79 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -26,7 +26,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t - [x] 5.1 Port `AdminUserController` and `AdminUserService`: admin-only list with search, filter and sort; create with temporary password, email and company from the logged-in admin; edit; deactivate with self-deactivation refused; admin-triggered reset via `/user/resetAdminPassword`. Tests first for each `admin-users` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: as 4.1 -- [ ] 5.2 Port `AdminRoleController`, `AdminRoleService` and `AdminAclService` (role list hiding `ROLE_MEMBER`, create and rename with unique names, `GET/PUT /roles/{id}/modules` replacing grants, self lock-out refused, super admin grants not editable). Tests first for each `admin-roles` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. +- [x] 5.2 Port `AdminRoleController`, `AdminRoleService` and `AdminAclService` (role list hiding `ROLE_MEMBER`, create and rename with unique names, `GET/PUT /roles/{id}/modules` replacing grants, self lock-out refused, super admin grants not editable). Tests first for each `admin-roles` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: as 4.1 ## 6. Admin portal 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 f01e012..4ac5e88 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 @@ -10,6 +10,10 @@ public class RestApiSystemServiceConstants { public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}"; public static final String API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE = "/user/findByPropertyAndPageable"; public static final String API_REST_SYSTEM_ROLE_FIND_ALL = "/role/findAll"; + public static final String API_REST_SYSTEM_ROLE_SAVE = "/role/save"; + public static final String API_REST_SYSTEM_MODULE_FIND_ALL_BY_AREA = "/module/findAllByArea/{area}"; + public static final String API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE = "/module/addModuleRole/{moduleId}/{roleId}"; + public static final String API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE = "/module/deleteModuleRole/{moduleId}/{roleId}"; public static final String API_REST_SYSTEM_USER_SAVE = "/user/save"; public static final String API_REST_SYSTEM_USER_UPDATE_USER_PASSWORD = "/user/updateUserPassword"; public static final String API_REST_SYSTEM_USER_FIND_EXIST_BY_USERNAME = "/user/findExistByUsername/{username}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java new file mode 100644 index 0000000..ebe40b5 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminRoleController.java @@ -0,0 +1,61 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminGrantsRequest; +import com.solvway.mobile.api.dto.admin.AdminModuleGrant; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +import com.solvway.mobile.api.service.AdminAclService; +import com.solvway.mobile.api.service.AdminRoleService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +/** Admin roles and their back-office module grants. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +public class AdminRoleController { + private final AdminRoleService adminRoleService; + private final AdminAclService adminAclService; + + @AppAuth + @AdminModule({"BO_ROLES", "BO_USERS"}) + @GetMapping("/roles") + public ResponseEntity>> list() { + return ResponseEntity.ok(adminRoleService.list()); + } + @AppAuth + @AdminModule({"BO_ROLES", "BO_USERS"}) + @GetMapping("/roles/{id}") + public ResponseEntity> getById(@PathVariable Long id) { + return ResponseEntity.ok(adminRoleService.get(id)); + } + @AppAuth + @AdminModule("BO_ROLES") + @PostMapping("/roles") + public ResponseEntity> create(@RequestBody AdminRoleRequest request) { + return ResponseEntity.ok(adminRoleService.create(request)); + } + @AppAuth + @AdminModule("BO_ROLES") + @PutMapping("/roles/{id}") + public ResponseEntity> update(@PathVariable Long id, @RequestBody AdminRoleRequest request) { + return ResponseEntity.ok(adminRoleService.update(id, request)); + } + @AppAuth + @AdminModule("BO_ROLES") + @GetMapping("/roles/{id}/modules") + public ResponseEntity> getModules(@PathVariable Long id) { + return ResponseEntity.ok(adminAclService.getGrantTree(id)); + } + @AppAuth + @AdminModule("BO_ROLES") + @PutMapping("/roles/{id}/modules") + public ResponseEntity> putModules(@PathVariable Long id, @RequestBody AdminGrantsRequest request) { + return ResponseEntity.ok(adminAclService.updateGrants(id, request.moduleIds())); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGrantsRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGrantsRequest.java new file mode 100644 index 0000000..f3c9217 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminGrantsRequest.java @@ -0,0 +1,8 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminGrantsRequest(List moduleIds) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminModuleGrant.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminModuleGrant.java new file mode 100644 index 0000000..fc208fb --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminModuleGrant.java @@ -0,0 +1,4 @@ +package com.solvway.mobile.api.dto.admin; + +/** One BO module row of a role's grant tree; the portal builds the checkbox tree from parentId. */ +public record AdminModuleGrant(Long id, String name, Long parentId, boolean granted) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRequest.java new file mode 100644 index 0000000..4b48a69 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRequest.java @@ -0,0 +1,7 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +/** Create/rename body. The portal may also send level and parent; the parent is always ROLE_SUPER_ADMIN, so they are ignored. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminRoleRequest(String name) {} 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 new file mode 100644 index 0000000..9ff6823 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java @@ -0,0 +1,106 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +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.util.RestTemplateCustomUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Back-office module grants per role. Reads and writes the BO module tree through services-system. */ +@Service +@RequiredArgsConstructor +public class AdminAclService { + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final String AREA = "BO"; + private static final String ROLES_MODULE = "BO_ROLES"; + private static final long SUPER_ADMIN_ROLE_ID = 1L; + private static final long ROLE_ADMIN_ID = 2L; + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + private final AdminRoleService adminRoleService; + + public List getGrantTree(Long roleId) { + requireVisibleRole(roleId); + return modules().stream().filter(AdminAclService::isGrantable).map(m -> new AdminModuleGrant(AdminRoleService.idOf(m), (String) m.get("name"), + AdminRoleService.idOf(m.get("parent")), grantedTo(m, roleId))).toList(); + } + + public List updateGrants(Long roleId, List moduleIds) { + requireVisibleRole(roleId); + if (roleId == SUPER_ADMIN_ROLE_ID || roleId == ROLE_ADMIN_ID) { + throw error(HttpStatus.BAD_REQUEST, "This role's grants cannot be edited", "ROLE_NOT_EDITABLE"); + } + if (moduleIds == null) throw error(HttpStatus.BAD_REQUEST, "moduleIds is required", "REQUIRED_FIELD"); + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + + List> modules = modules(); + Set known = new HashSet<>(); + Set current = new HashSet<>(); + for (Map m : modules) { + if (isGrantable(m)) known.add(AdminRoleService.idOf(m)); + if (isGrantable(m) && grantedTo(m, roleId)) current.add(AdminRoleService.idOf(m)); + } + Set wanted = new HashSet<>(moduleIds); + if (!known.containsAll(wanted)) throw error(HttpStatus.BAD_REQUEST, "Unknown back-office module", "UNKNOWN_MODULE"); + requireNoLockout(caller, roleId, wanted, modules); + + // ponytail: not atomic, adds run before deletes and a failure midway leaves a partial grant; a repeated PUT converges. Upgrade: one services-system endpoint that replaces grants in a transaction. + for (Long id : wanted) if (!current.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE, id, roleId); + for (Long id : current) if (!wanted.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE, id, roleId); + return getGrantTree(roleId); + } + + /** A non-super caller must still reach BO_ROLES through one of their roles (role 2 is on every admin and grants nothing). */ + private static void requireNoLockout(User caller, Long roleId, Set wanted, List> modules) { + if (caller.getRoles() == null || caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID)) return; + Set held = new HashSet<>(); + caller.getRoles().stream().map(r -> r.getId()).filter(i -> i != null && i != ROLE_ADMIN_ID).forEach(held::add); + if (!held.contains(roleId)) return; + Map rolesModule = modules.stream().filter(m -> ROLES_MODULE.equals(m.get("name"))).findFirst().orElse(null); + if (rolesModule == null) return; + boolean stillGranted = held.stream().anyMatch(r -> r.equals(roleId) ? wanted.contains(AdminRoleService.idOf(rolesModule)) : grantedTo(rolesModule, r)); + if (!stillGranted) throw error(HttpStatus.BAD_REQUEST, "This change would remove your own access to role management", "ACL_LOCKOUT"); + } + + /** Hidden roles (ROLE_MEMBER, ROLE_ADMIN) look absent, as in the role list. */ + private void requireVisibleRole(Long roleId) { + if (AdminRoleService.isHidden(adminRoleService.find(roleId))) { + throw error(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND"); + } + } + + /** Only leaf modules (type M) are granted; the type R root is just a container. */ + private static boolean isGrantable(Map module) { + return "M".equals(module.get("type")); + } + + private static boolean grantedTo(Map module, Long roleId) { + return module.get("roles") instanceof List l && l.stream().anyMatch(r -> roleId.equals(AdminRoleService.idOf(r))); + } + + private List> modules() { + List> body = restTemplateUtil.getForEntity( + restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_FIND_ALL_BY_AREA), MAP_LIST, AREA).getBody(); + return body == null ? List.of() : body; + } + + private void call(String api, Long moduleId, Long roleId) { + restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(api), Integer.class, moduleId, roleId); + } + + private static CodedResponseStatusException error(HttpStatus status, String reason, String code) { + return new CodedResponseStatusException(status, reason, code); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java new file mode 100644 index 0000000..b1cd4ba --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java @@ -0,0 +1,161 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +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.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Admin roles for the portal. Roles travel as maps. services-system's /role/save swallows errors and recomputes + * level and tracekey from the parent, and /role/findById throws on a missing id, so this reads with findAll and + * verifies a rename by re-reading. + */ +@Service +@RequiredArgsConstructor +public class AdminRoleService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final long SUPER_ADMIN_ROLE_ID = 1L; + private static final List HIDDEN = List.of("ROLE_MEMBER", "ROLE_ADMIN"); + private static final List PROTECTED = List.of("ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_MEMBER"); + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + + public List> list() { + return all().stream().filter(r -> !isHidden(r)).map(AdminRoleService::clean).toList(); + } + + public Map get(Long id) { + Map role = find(id); + if (isHidden(role)) throw notFound(); + return clean(role); + } + + /** Any stored role, hidden ones included; 404 when absent. */ + public Map find(Long id) { + return all().stream().filter(r -> id != null && id.equals(idOf(r))).findFirst().orElseThrow(AdminRoleService::notFound); + } + + public Map create(AdminRoleRequest r) { + String name = requireName(r); + User caller = caller(); + requireFree(name, null); + Map role = new HashMap<>(); + role.put("name", name); + role.put("parent", Map.of("id", SUPER_ADMIN_ROLE_ID)); + role.put("children", List.of()); + role.put("createBy", caller.getUsername()); + role.put("doneBy", caller.getUsername()); + role.put("createDate", System.currentTimeMillis()); + return clean(save(role)); + } + + public Map update(Long id, AdminRoleRequest r) { + User caller = caller(); + Map stored = find(id); + if (isProtected(stored)) throw error(HttpStatus.BAD_REQUEST, "This role cannot be edited", "ROLE_NOT_EDITABLE"); + String name = requireName(r); + requireFree(name, id); + // Send every persisted field back: /role/save recomputes level and tracekey from the parent, and a merge + // without the children would orphan them. + Map role = new HashMap<>(); + for (String k : List.of("id", "level", "tracekey", "createBy", "createDate")) role.put(k, stored.get(k)); + role.put("id", id); + role.put("name", name); + Long parent = idOf(stored.get("parent")); + if (parent != null) role.put("parent", Map.of("id", parent)); + // children go back exactly as stored: services-system re-saves each one from this payload, and a changed list would null their parentid + role.put("children", stored.get("children") instanceof List l ? l : List.of()); + role.put("doneBy", caller.getUsername()); + save(role); + // ponytail: ignore-case match, so a case-only rename failure goes unnoticed; /role/save gives no error signal. + Map reread = find(id); + if (!name.equalsIgnoreCase(String.valueOf(reread.get("name")))) { + throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Role could not be saved", "SAVE_FAILED"); + } + return clean(reread); + } + + public static boolean isProtected(Map role) { + return PROTECTED.contains(role.get("name")); + } + + static Long idOf(Object ref) { + if (ref instanceof Number n) return n.longValue(); + if (ref instanceof Map m && m.get("id") instanceof Number n) return n.longValue(); + return null; + } + + static boolean isHidden(Map role) { + return HIDDEN.contains(role.get("name")); + } + + private String requireName(AdminRoleRequest r) { + if (r == null || !StringUtils.hasText(r.name())) throw error(HttpStatus.BAD_REQUEST, "Role name is required", "REQUIRED_FIELD"); + return r.name().trim(); + } + + /** ponytail: check-then-save is not atomic; the DB unique key on name is the backstop. */ + private void requireFree(String name, Long ownId) { + if (all().stream().anyMatch(x -> name.equalsIgnoreCase(String.valueOf(x.get("name"))) && !(ownId != null && ownId.equals(idOf(x))))) { + throw error(HttpStatus.CONFLICT, "Role name is already taken", "ROLE_NAME_TAKEN"); + } + } + + private List> all() { + List> body = restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_FIND_ALL), MAP_LIST).getBody(); + return body == null ? List.of() : body; + } + + private Map save(Map role) { + ResponseEntity> ent = restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_SAVE), MAP, role); + // services-system swallows save errors and returns the unsaved entity, so a missing id means it failed. + if (ent.getBody() == null || ent.getBody().get("id") == null) { + throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Role could not be saved", "SAVE_FAILED"); + } + return ent.getBody(); + } + + private static Map clean(Map role) { + Map out = new LinkedHashMap<>(); + out.put("id", idOf(role.get("id"))); + out.put("name", role.get("name")); + out.put("level", role.get("level")); + Long parent = idOf(role.get("parent")); + out.put("parent", parent == null ? null : Map.of("id", parent)); + return out; + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + return caller; + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } + + private static CodedResponseStatusException notFound() { + return error(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND"); + } + + private static CodedResponseStatusException error(HttpStatus status, String reason, String code) { + return new CodedResponseStatusException(status, reason, code); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRoleControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRoleControllerTest.java new file mode 100644 index 0000000..b701687 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminRoleControllerTest.java @@ -0,0 +1,137 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminGrantsRequest; +import com.solvway.mobile.api.dto.admin.AdminModuleGrant; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.service.AdminAclService; +import com.solvway.mobile.api.service.AdminRoleService; +import com.solvway.mobile.api.useraccess.AdminModule; +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.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.Arrays; +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.ArgumentMatchers.eq; +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.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminRoleControllerTest { + + @Mock private AdminRoleService roles; + @Mock private AdminAclService acl; + @InjectMocks private AdminRoleController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void everyHandlerIsAuthenticatedAndGuardedByTheRightModule() { + for (Method m : AdminRoleController.class.getDeclaredMethods()) { + if (m.getDeclaringClass() != AdminRoleController.class || m.isSynthetic()) continue; + assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName() + " @AppAuth").isTrue(); + List modules = Arrays.asList(m.getAnnotation(AdminModule.class).value()); + if (m.getName().equals("list") || m.getName().equals("getById")) { + assertThat(modules).as(m.getName()).containsExactlyInAnyOrder("BO_ROLES", "BO_USERS"); + } else { + assertThat(modules).as(m.getName()).containsExactly("BO_ROLES"); + } + } + } + + @Test + void list_returnsRoles() throws Exception { + when(roles.list()).thenReturn(List.of(Map.of("id", 4, "name", "ROLE_SALES"))); + mvc.perform(get("/api/admin/roles")).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].name").value("ROLE_SALES")); + } + + @Test + void getById_returnsRole() throws Exception { + when(roles.get(4L)).thenReturn(Map.of("id", 4, "name", "ROLE_SALES")); + mvc.perform(get("/api/admin/roles/4")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(4)); + } + + @Test + void getById_unknownRoleAnswers404() throws Exception { + when(roles.get(99L)).thenThrow(new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND")); + mvc.perform(get("/api/admin/roles/99")).andExpect(status().isNotFound()); + } + + @Test + void create_ignoresPortalExtrasAndPassesName() throws Exception { + when(roles.create(any())).thenReturn(Map.of("id", 9, "name", "ROLE_SALES")); + mvc.perform(post("/api/admin/roles").contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"ROLE_SALES\",\"parent\":{\"id\":1},\"level\":2}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(9)); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminRoleRequest.class); + verify(roles).create(c.capture()); + assertThat(c.getValue().name()).isEqualTo("ROLE_SALES"); + } + + @Test + void create_duplicateAnswers409() throws Exception { + when(roles.create(any())).thenThrow(new CodedResponseStatusException(HttpStatus.CONFLICT, "Role name is already taken", "ROLE_NAME_TAKEN")); + mvc.perform(post("/api/admin/roles").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"ROLE_SALES\"}")) + .andExpect(status().isConflict()); + } + + @Test + void update_passesIdAndName() throws Exception { + when(roles.update(eq(4L), any())).thenReturn(Map.of("id", 4, "name", "ROLE_OPS")); + mvc.perform(put("/api/admin/roles/4").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"ROLE_OPS\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.name").value("ROLE_OPS")); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminRoleRequest.class); + verify(roles).update(eq(4L), c.capture()); + assertThat(c.getValue().name()).isEqualTo("ROLE_OPS"); + } + + @Test + void getModules_returnsGrantTree() throws Exception { + when(acl.getGrantTree(4L)).thenReturn(List.of(new AdminModuleGrant(40700000L, "BO_USERS", 40000000L, true))); + mvc.perform(get("/api/admin/roles/4/modules")).andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value(40700000)) + .andExpect(jsonPath("$[0].parentId").value(40000000)) + .andExpect(jsonPath("$[0].granted").value(true)); + } + + @Test + void putModules_passesModuleIdsAndReturnsTree() throws Exception { + when(acl.updateGrants(eq(4L), any())).thenReturn(List.of(new AdminModuleGrant(40700000L, "BO_USERS", null, true))); + mvc.perform(put("/api/admin/roles/4/modules").contentType(MediaType.APPLICATION_JSON) + .content("{\"moduleIds\":[40700000,40800000]}")) + .andExpect(status().isOk()).andExpect(jsonPath("$[0].granted").value(true)); + verify(acl).updateGrants(4L, List.of(40700000L, 40800000L)); + } + + @Test + void putModules_lockoutAnswers400() throws Exception { + when(acl.updateGrants(eq(4L), any())).thenThrow(new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "lockout", "ACL_LOCKOUT")); + mvc.perform(put("/api/admin/roles/4/modules").contentType(MediaType.APPLICATION_JSON).content("{\"moduleIds\":[]}")) + .andExpect(status().isBadRequest()); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java new file mode 100644 index 0000000..ddca84a --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java @@ -0,0 +1,242 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminModuleGrant; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +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.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminAclServiceTest { + + private static final String MODULES = "/module/findAllByArea/{area}"; + private static final String ADD = "/module/addModuleRole/{moduleId}/{roleId}"; + private static final String DEL = "/module/deleteModuleRole/{moduleId}/{roleId}"; + private static final long ROOT = 40000000L, USERS = 40700000L, ROLES = 40800000L; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminRoleService roles; + private AdminAclService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + roles = mock(AdminRoleService.class); + service = new AdminAclService(rest, auth, roles); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + when(roles.find(1L)).thenReturn(Map.of("id", 1L, "name", "ROLE_SUPER_ADMIN")); + when(roles.find(2L)).thenReturn(Map.of("id", 2L, "name", "ROLE_ADMIN")); + when(roles.find(4L)).thenReturn(Map.of("id", 4L, "name", "ROLE_SALES")); + when(roles.find(5L)).thenReturn(Map.of("id", 5L, "name", "ROLE_OPS")); + when(roles.find(99L)).thenThrow(new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND")); + // BO_USERS held by 1 and 4; BO_ROLES held by 1 and 5. Root's role list comes first, so later modules see bare parent ids. + stubModules( + module(ROOT, "BO_ROOT", null, 1), + module(USERS, "BO_USERS", ROOT, 1, 4), + module(ROLES, "BO_ROLES", Map.of("id", ROOT, "name", "BO_ROOT"), 1, 5)); + caller(5); + } + + @AfterEach + void close() { http.close(); } + + private static Map module(long id, String name, Object parent, long... roleIds) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("parent", parent); + m.put("type", parent == null ? "R" : "M"); + List rs = new ArrayList<>(); + for (long r : roleIds) rs.add(Map.of("id", r, "name", "R" + r)); + m.put("roles", rs); + return m; + } + + private void stubModules(Map... modules) { + when(rest.getForEntity(eq(MODULES), any(ParameterizedTypeReference.class), eq("BO"))).thenReturn(ResponseEntity.ok(List.of(modules))); + } + + private void caller(long... roleIds) { + User u = new User(); + u.setId(50L); + List rs = new ArrayList<>(); + for (long id : roleIds) { + Role r = new Role(); + r.setId(id); + rs.add(r); + } + u.setRoles(rs); + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + private void verifyNothingChanged() { + verify(rest, never()).getForEntity(eq(ADD), eq(Integer.class), any(), any()); + verify(rest, never()).getForEntity(eq(DEL), eq(Integer.class), any(), any()); + } + + @Test + void grantTree_listsBoModulesWithGrantedFlagAndParentIds() { + List tree = service.getGrantTree(4L); + // the type R root is not grantable, so it is not listed + assertThat(tree).containsExactly( + new AdminModuleGrant(USERS, "BO_USERS", ROOT, true), // parent came as a bare id + new AdminModuleGrant(ROLES, "BO_ROLES", ROOT, false)); // parent came as an object + } + + @Test + void grantTree_unknownRoleIs404() { + assertCoded(() -> service.getGrantTree(99L), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + } + + @Test + void grantTree_ofAHiddenRoleIs404() { + when(roles.find(3L)).thenReturn(Map.of("id", 3L, "name", "ROLE_MEMBER")); + assertCoded(() -> service.getGrantTree(2L), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + assertCoded(() -> service.getGrantTree(3L), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + } + + @Test + void update_rootModuleIsRefused() { + assertCoded(() -> service.updateGrants(4L, List.of(ROOT)), HttpStatus.BAD_REQUEST, "UNKNOWN_MODULE"); + verifyNothingChanged(); + } + + @Test + void update_addsOnlyMissingGrants() { + // 4 holds BO_USERS; wanting BO_USERS + BO_ROLES must add BO_ROLES only + service.updateGrants(4L, List.of(USERS, ROLES)); + verify(rest).getForEntity(eq(ADD), eq(Integer.class), eq(ROLES), eq(4L)); + verify(rest, never()).getForEntity(eq(ADD), eq(Integer.class), eq(USERS), any()); + verify(rest, never()).getForEntity(eq(DEL), eq(Integer.class), any(), any()); + } + + @Test + void update_removesOnlyDroppedGrants() { + service.updateGrants(4L, List.of()); + verify(rest).getForEntity(eq(DEL), eq(Integer.class), eq(USERS), eq(4L)); + verify(rest, never()).getForEntity(eq(ADD), eq(Integer.class), any(), any()); + } + + @Test + void update_sameSetChangesNothing() { + service.updateGrants(4L, List.of(USERS)); + verifyNothingChanged(); + } + + @Test + void update_returnsTheTreeAfterTheChange() { + assertThat(service.updateGrants(4L, List.of(USERS))).hasSize(2); + } + + @Test + void update_nonBoModuleIsRefused() { + assertCoded(() -> service.updateGrants(4L, List.of(USERS, 7000L)), HttpStatus.BAD_REQUEST, "UNKNOWN_MODULE"); + verifyNothingChanged(); + } + + @Test + void update_missingModuleIdsIsRefused() { + assertCoded(() -> service.updateGrants(4L, null), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + verifyNothingChanged(); + } + + @Test + void update_superAdminGrantsAreNotEditable() { + assertCoded(() -> service.updateGrants(1L, List.of(USERS)), HttpStatus.BAD_REQUEST, "ROLE_NOT_EDITABLE"); + verifyNothingChanged(); + } + + @Test + void update_hiddenRoleIs404() { + assertCoded(() -> service.updateGrants(2L, List.of(USERS)), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + verifyNothingChanged(); + } + + @Test + void update_unknownRoleIs404() { + assertCoded(() -> service.updateGrants(99L, List.of()), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + verifyNothingChanged(); + } + + @Test + void update_removingBoRolesFromTheCallersOnlyGrantingRoleIsALockout() { + caller(5, 2); // role 2 is attached to every admin and does not count + assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.BAD_REQUEST, "ACL_LOCKOUT"); + verifyNothingChanged(); + } + + @Test + void update_removingBoRolesIsFineWhenAnotherCallerRoleStillGrantsIt() { + stubModules( + module(ROOT, "BO_ROOT", null, 1), + module(USERS, "BO_USERS", ROOT, 1, 4), + module(ROLES, "BO_ROLES", ROOT, 1, 5, 6)); + caller(5, 6, 2); + service.updateGrants(5L, List.of()); + verify(rest).getForEntity(eq(DEL), eq(Integer.class), eq(ROLES), eq(5L)); + } + + @Test + void update_keepingBoRolesOnTheCallersRoleIsFine() { + service.updateGrants(5L, List.of(ROLES, USERS)); + verify(rest).getForEntity(eq(ADD), eq(Integer.class), eq(USERS), eq(5L)); + verify(rest, never()).getForEntity(eq(DEL), eq(Integer.class), any(), any()); + } + + @Test + void update_editingAnotherRoleNeverLocksOut() { + service.updateGrants(4L, List.of(ROLES)); + verify(rest).getForEntity(eq(ADD), eq(Integer.class), eq(ROLES), eq(4L)); + } + + @Test + void update_superAdminCallerIsNotSubjectToLockout() { + caller(1); + service.updateGrants(5L, List.of()); + verify(rest).getForEntity(eq(DEL), eq(Integer.class), eq(ROLES), eq(5L)); + } + + @Test + void update_unresolvedCallerIsUnauthorized() { + when(auth.loadUserByToken("tok")).thenReturn(null); + assertCoded(() -> service.updateGrants(4L, List.of()), HttpStatus.UNAUTHORIZED, "UNAUTHORIZED"); + verifyNothingChanged(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java new file mode 100644 index 0000000..5d37194 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java @@ -0,0 +1,233 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +import com.solvway.mobile.api.errorhandler.CodedResponseStatusException; +import com.solvway.mobile.api.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.HashMap; +import java.util.List; +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.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminRoleServiceTest { + + private static final String FIND_ALL = "/role/findAll"; + private static final String SAVE = "/role/save"; + + private RestTemplateCustomUtil rest; + private AdminRoleService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + AdminAuthenticationService auth = mock(AdminAuthenticationService.class); + service = new AdminRoleService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + User caller = new User(); + caller.setUsername("boss"); + when(auth.loadUserByToken("tok")).thenReturn(caller); + stubRoles(stored()); + } + + @AfterEach + void close() { http.close(); } + + private static Map role(long id, String name, Object parent, int level, String tracekey) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("level", level); + m.put("tracekey", tracekey); + m.put("parent", parent); + m.put("children", List.of()); + m.put("createBy", "sys"); + m.put("createDate", 1700000000000L); + return m; + } + + private static List> stored() { + Map sales = role(4, "ROLE_SALES", Map.of("id", 1, "name", "ROLE_SUPER_ADMIN", "level", 1, "tracekey", "ROLE_SUPER_ADMIN"), + 2, "ROLE_SUPER_ADMIN/ROLE_SALES"); + sales.put("children", List.of(Map.of("id", 9L, "name", "ROLE_SALES_JR", "createBy", "sys", "createDate", 1L, "parent", 4L))); + return List.of( + role(1, "ROLE_SUPER_ADMIN", null, 1, "ROLE_SUPER_ADMIN"), + role(2, "ROLE_ADMIN", Map.of("id", 1), 2, "ROLE_SUPER_ADMIN/ROLE_ADMIN"), + role(3, "ROLE_MEMBER", null, 1, "ROLE_MEMBER"), + sales); + } + + private void stubRoles(List> first, List>... later) { + var stub = when(rest.getForEntity(eq(FIND_ALL), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(first)); + for (var l : later) stub = stub.thenReturn(ResponseEntity.ok(l)); + } + + private void stubSave(Map saved) { + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(saved)); + } + + private Map savedBody() { + ArgumentCaptor c = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), c.capture()); + return (Map) c.getValue(); + } + + private static void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + @Test + void list_hidesMemberAndAdminRoles() { + assertThat(service.list()).extracting(m -> m.get("name")).containsExactly("ROLE_SUPER_ADMIN", "ROLE_SALES"); + } + + @Test + void list_returnsOnlyPortalFields() { + Map sales = service.list().get(1); + assertThat(sales).containsOnlyKeys("id", "name", "level", "parent"); + assertThat(sales.get("parent")).isEqualTo(Map.of("id", 1L)); + } + + @Test + void get_returnsVisibleRole() { + assertThat(service.get(4L).get("name")).isEqualTo("ROLE_SALES"); + } + + @ParameterizedTest + @ValueSource(longs = {2, 3, 99}) + void get_hiddenOrUnknownRoleIs404(long id) { + assertCoded(() -> service.get(id), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + } + + @Test + void create_savesUnderSuperAdminWithActor() { + Map created = role(10, "ROLE_OPS", Map.of("id", 1), 2, "ROLE_SUPER_ADMIN/ROLE_OPS"); + stubSave(created); + List> after = new java.util.ArrayList<>(stored()); + after.add(created); + stubRoles(stored(), after); + + Map out = service.create(new AdminRoleRequest(" ROLE_OPS ")); + + Map body = savedBody(); + assertThat(body.get("name")).isEqualTo("ROLE_OPS"); + assertThat(body.get("parent")).isEqualTo(Map.of("id", 1L)); + assertThat(body.get("children")).isEqualTo(List.of()); + assertThat(body.get("createBy")).isEqualTo("boss"); + assertThat(body.get("doneBy")).isEqualTo("boss"); + assertThat(body.get("createDate")).isInstanceOf(Long.class); + assertThat(body).doesNotContainKey("id"); + assertThat(out.get("id")).isEqualTo(10L); + assertThat(out.get("name")).isEqualTo("ROLE_OPS"); + } + + @Test + void create_nameIsRequired() { + assertCoded(() -> service.create(new AdminRoleRequest(" ")), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(new AdminRoleRequest(null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @ParameterizedTest + @ValueSource(strings = {"ROLE_SALES", "role_sales", "ROLE_ADMIN", "ROLE_MEMBER"}) + void create_duplicateNameIsRefusedCaseInsensitively(String name) { + assertCoded(() -> service.create(new AdminRoleRequest(name)), HttpStatus.CONFLICT, "ROLE_NAME_TAKEN"); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_failedSaveIsReported() { + // services-system swallows save errors and returns the unsaved entity (no id) + stubSave(new HashMap<>(Map.of("name", "ROLE_OPS"))); + assertCoded(() -> service.create(new AdminRoleRequest("ROLE_OPS")), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED"); + } + + @Test + void rename_keepsStoredLevelParentTracekeyChildrenAndCreateFields() { + Map renamed = role(4, "ROLE_REVENUE", Map.of("id", 1), 2, "ROLE_SUPER_ADMIN/ROLE_REVENUE"); + stubSave(renamed); + List> after = List.of(stored().get(0), renamed); + stubRoles(stored(), after); + + Map out = service.update(4L, new AdminRoleRequest("ROLE_REVENUE")); + + Map body = savedBody(); + assertThat(body.get("id")).isEqualTo(4L); + assertThat(body.get("name")).isEqualTo("ROLE_REVENUE"); + assertThat(body.get("level")).isEqualTo(2); + assertThat(body.get("tracekey")).isEqualTo("ROLE_SUPER_ADMIN/ROLE_SALES"); + assertThat(body.get("parent")).isEqualTo(Map.of("id", 1L)); + // full nested objects pass through: services-system parseChild re-saves each child from them + assertThat(body.get("children")).isEqualTo(stored().get(3).get("children")); + assertThat(body.get("createBy")).isEqualTo("sys"); + assertThat(body.get("createDate")).isEqualTo(1700000000000L); + assertThat(body.get("doneBy")).isEqualTo("boss"); + assertThat(out.get("name")).isEqualTo("ROLE_REVENUE"); + } + + @Test + void rename_toItsOwnNameIsAllowed() { + stubSave(stored().get(3)); + assertThat(service.update(4L, new AdminRoleRequest("role_sales")).get("id")).isEqualTo(4L); + } + + @Test + void rename_toAnotherRolesNameIsRefused() { + assertCoded(() -> service.update(4L, new AdminRoleRequest("role_admin")), HttpStatus.CONFLICT, "ROLE_NAME_TAKEN"); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @ParameterizedTest + @ValueSource(longs = {1, 2, 3}) + void rename_builtInRolesAreNotEditable(long id) { + assertCoded(() -> service.update(id, new AdminRoleRequest("ROLE_X")), HttpStatus.BAD_REQUEST, "ROLE_NOT_EDITABLE"); + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + @Test + void rename_unknownRoleIs404() { + assertCoded(() -> service.update(99L, new AdminRoleRequest("ROLE_X")), HttpStatus.NOT_FOUND, "ROLE_NOT_FOUND"); + } + + @Test + void rename_silentlyFailedSaveIsReported() { + // /role/save swallows errors; the reread still shows the old name + stubSave(stored().get(3)); + assertCoded(() -> service.update(4L, new AdminRoleRequest("ROLE_REVENUE")), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED"); + } + + @Test + void isProtected_matchesBuiltInRoleNames() { + assertThat(AdminRoleService.isProtected(stored().get(0))).isTrue(); + assertThat(AdminRoleService.isProtected(stored().get(1))).isTrue(); + assertThat(AdminRoleService.isProtected(stored().get(2))).isTrue(); + assertThat(AdminRoleService.isProtected(stored().get(3))).isFalse(); + } +} -- 2.54.1 From 1071ddaa2ab63d807f0137206b2fdf3780220970 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 21:24:30 +0800 Subject: [PATCH 10/19] feat(admin-portal): cut babyboo portal down to Co-Lite login, users and roles Removes every other screen, API route, component, test and the dependencies only they used. Cookie colite_admin, Co-Lite branding, BO_USERS/BO_ROLES modules only. The user form no longer loads branches, events or country scope. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../add-admin-auth-users-roles/tasks.md | 2 +- .../skills/run-solvway-admin-portal/SKILL.md | 2 +- solvway-admin-portal/.env.example | 4 +- solvway-admin-portal/Dockerfile | 1 - solvway-admin-portal/README.md | 214 +- .../[memberCode]/deactivate/route.test.ts | 60 - .../[prefix]/[memberCode]/deactivate/route.ts | 26 - .../[memberCode]/reactivate/route.test.ts | 59 - .../[prefix]/[memberCode]/reactivate/route.ts | 25 - .../company-accounts/[prefix]/route.test.ts | 63 - .../admin/company-accounts/[prefix]/route.ts | 22 - .../api/admin/company-accounts/route.test.ts | 138 - .../app/api/admin/company-accounts/route.ts | 55 - .../api/admin/dashboard/event/route.test.ts | 48 - .../app/api/admin/dashboard/event/route.ts | 11 - .../api/admin/dashboard/route.country.test.ts | 21 - .../app/api/admin/dashboard/route.test.ts | 48 - .../app/api/admin/dashboard/route.ts | 5 - .../admin/event-summary/[eventId]/route.ts | 13 - .../api/admin/event-summary/events/route.ts | 7 - .../app/api/admin/event-summary/route.test.ts | 77 - .../api/admin/kyc/[uuid]/action/route.test.ts | 122 - .../app/api/admin/kyc/[uuid]/action/route.ts | 49 - .../kyc/[uuid]/doc/[docType]/route.test.ts | 120 - .../admin/kyc/[uuid]/doc/[docType]/route.ts | 74 - .../app/api/admin/kyc/[uuid]/route.test.ts | 44 - .../app/api/admin/kyc/[uuid]/route.ts | 21 - .../app/api/admin/kyc/counts/route.test.ts | 33 - .../app/api/admin/kyc/counts/route.ts | 16 - .../app/api/admin/kyc/export/route.test.ts | 38 - .../app/api/admin/kyc/export/route.ts | 30 - .../app/api/admin/kyc/route.test.ts | 55 - .../app/api/admin/kyc/route.ts | 32 - .../app/api/admin/kyc/submit/route.test.ts | 64 - .../app/api/admin/kyc/submit/route.ts | 48 - .../app/api/admin/kyc/upload/route.test.ts | 44 - .../app/api/admin/kyc/upload/route.ts | 38 - .../admin/member-corrections/route.test.ts | 51 - .../app/api/admin/member-corrections/route.ts | 33 - .../[messageUuid]/images/[index]/route.ts | 58 - .../member-messages/[uuid]/messages/route.ts | 18 - .../member-messages/[uuid]/read/route.ts | 10 - .../api/admin/member-messages/[uuid]/route.ts | 10 - .../[broadcastUuid]/recipients/route.ts | 10 - .../broadcasts/[broadcastUuid]/route.ts | 10 - .../broadcasts/preview/route.ts | 5 - .../admin/member-messages/broadcasts/route.ts | 9 - .../api/admin/member-messages/by-key/route.ts | 5 - .../api/admin/member-messages/images/route.ts | 69 - .../app/api/admin/member-messages/route.ts | 5 - .../member-messages/routes.broadcasts.test.ts | 106 - .../member-messages/routes.hardening.test.ts | 109 - .../api/admin/member-messages/routes.test.ts | 184 - .../api/admin/member-messages/start/route.ts | 5 - .../member-messages/unread-count/route.ts | 5 - .../[memberCode]/change-history/route.test.ts | 59 - .../[memberCode]/change-history/route.ts | 20 - .../[memberCode]/change-sponsor/route.test.ts | 72 - .../[memberCode]/change-sponsor/route.ts | 29 - .../[memberCode]/correct-rank/route.test.ts | 77 - .../[memberCode]/correct-rank/route.ts | 32 - .../edit-initialize/route.test.ts | 35 - .../[memberCode]/edit-initialize/route.ts | 20 - .../[memberCode]/placement-history/route.ts | 20 - .../admin/members/[memberCode]/route.test.ts | 90 - .../api/admin/members/[memberCode]/route.ts | 36 - .../[memberCode]/status-history/route.test.ts | 35 - .../[memberCode]/status-history/route.ts | 20 - .../app/api/admin/members/route.test.ts | 112 - .../app/api/admin/members/route.ts | 63 - .../admin/network/[memberCode]/route.test.ts | 50 - .../api/admin/network/[memberCode]/route.ts | 27 - .../network/[memberCode]/upline/route.ts | 17 - .../api/admin/reports/rewards/route.test.ts | 60 - .../app/api/admin/reports/rewards/route.ts | 5 - .../reports/sales-items/route.country.test.ts | 21 - .../admin/reports/sales-items/route.test.ts | 36 - .../api/admin/reports/sales-items/route.ts | 6 - .../admin/reports/sales/route.country.test.ts | 21 - .../app/api/admin/reports/sales/route.test.ts | 48 - .../app/api/admin/reports/sales/route.ts | 5 - .../app/api/admin/topup/list/route.test.ts | 57 - .../app/api/admin/topup/list/route.ts | 30 - .../api/admin/topup/list/route.view.test.ts | 45 - .../app/api/admin/topup/removedRoutes.test.ts | 10 - .../app/api/admin/topup/reverse/route.test.ts | 47 - .../app/api/admin/topup/reverse/route.ts | 35 - .../[memberCode]/balances/route.test.ts | 48 - .../wallet/[memberCode]/balances/route.ts | 20 - .../wallet/[memberCode]/ledger/route.test.ts | 59 - .../admin/wallet/[memberCode]/ledger/route.ts | 32 - .../app/api/admin/wallet/adjust/route.test.ts | 77 - .../app/api/admin/wallet/adjust/route.ts | 21 - .../app/api/admin/wallet/ledger/route.test.ts | 116 - .../app/api/admin/wallet/ledger/route.ts | 42 - .../admin/withdrawal/approve/route.test.ts | 47 - .../app/api/admin/withdrawal/approve/route.ts | 32 - .../api/admin/withdrawal/config/route.test.ts | 99 - .../app/api/admin/withdrawal/config/route.ts | 37 - .../api/admin/withdrawal/list/route.test.ts | 101 - .../app/api/admin/withdrawal/list/route.ts | 30 - .../api/admin/withdrawal/reject/route.test.ts | 47 - .../app/api/admin/withdrawal/reject/route.ts | 35 - .../app/api/audit-log/[id]/route.test.ts | 86 - .../app/api/audit-log/[id]/route.ts | 28 - .../app/api/audit-log/route.test.ts | 94 - .../app/api/audit-log/route.ts | 31 - .../app/api/auth/login/route.test.ts | 2 +- .../app/api/auth/login/route.ts | 2 +- .../auth/session/route.countryScope.test.ts | 29 - .../app/api/auth/session/route.ts | 6 +- .../api/banner-settings/[zone]/route.test.ts | 82 - .../app/api/banner-settings/[zone]/route.ts | 39 - .../app/api/banners/[id]/route.test.ts | 176 - .../app/api/banners/[id]/route.ts | 42 - .../app/api/banners/image/route.test.ts | 79 - .../app/api/banners/image/route.ts | 33 - .../app/api/banners/route.test.ts | 178 - solvway-admin-portal/app/api/banners/route.ts | 50 - .../app/api/bulletins/[id]/route.test.ts | 54 - .../app/api/bulletins/[id]/route.ts | 36 - .../app/api/bulletins/image/route.test.ts | 78 - .../app/api/bulletins/image/route.ts | 31 - .../app/api/bulletins/route.test.ts | 64 - .../app/api/bulletins/route.ts | 47 - .../app/api/catalog/[list]/[id]/route.test.ts | 137 - .../app/api/catalog/[list]/[id]/route.ts | 50 - .../api/catalog/[list]/image/route.test.ts | 78 - .../app/api/catalog/[list]/image/route.ts | 30 - .../app/api/catalog/[list]/route.test.ts | 119 - .../app/api/catalog/[list]/route.ts | 45 - .../app/api/collections/[id]/delete/route.ts | 20 - .../app/api/collections/[id]/route.ts | 17 - .../app/api/collections/image/route.ts | 22 - .../app/api/collections/preview/route.ts | 18 - .../app/api/collections/route.ts | 27 - .../app/api/collections/routes.test.ts | 93 - .../app/api/counter/gift-card/sale/route.ts | 24 - .../api/counter/payment-methods/route.test.ts | 62 - .../app/api/counter/payment-methods/route.ts | 20 - .../app/api/counter/products/route.test.ts | 59 - .../app/api/counter/products/route.ts | 18 - .../app/api/counter/quote/route.test.ts | 50 - .../app/api/counter/quote/route.ts | 22 - .../app/api/counter/sale/route.test.ts | 101 - .../app/api/counter/sale/route.ts | 63 - .../counter/split/cancel/[uuid]/route.test.ts | 51 - .../api/counter/split/cancel/[uuid]/route.ts | 29 - .../app/api/counter/split/sale/route.test.ts | 141 - .../app/api/counter/split/sale/route.ts | 58 - .../counter/split/status/[uuid]/route.test.ts | 51 - .../api/counter/split/status/[uuid]/route.ts | 29 - .../counter/wallet/[memberCode]/route.test.ts | 53 - .../api/counter/wallet/[memberCode]/route.ts | 30 - .../api/counter/wallet/preview/route.test.ts | 103 - .../app/api/counter/wallet/preview/route.ts | 26 - .../app/api/counter/wallet/sale/route.test.ts | 132 - .../app/api/counter/wallet/sale/route.ts | 47 - .../app/api/countries/route.test.ts | 42 - .../app/api/countries/route.ts | 15 - .../[countryCode]/[type]/route.test.ts | 48 - .../history/[countryCode]/[type]/route.ts | 20 - .../app/api/currency/route.test.ts | 152 - .../app/api/currency/route.ts | 56 - .../[uuid]/mark-delivered/route.test.ts | 47 - .../[uuid]/mark-delivered/route.ts | 21 - .../[uuid]/mark-shipped/route.test.ts | 66 - .../[uuid]/mark-shipped/route.ts | 25 - .../[uuid]/qianyi/retry/route.ts | 22 - .../[uuid]/qianyi/route.test.ts | 59 - .../delivery-orders/[uuid]/qianyi/route.ts | 18 - .../api/delivery-orders/[uuid]/route.test.ts | 40 - .../app/api/delivery-orders/[uuid]/route.ts | 17 - .../counter/[uuid]/route.test.ts | 50 - .../delivery-orders/counter/[uuid]/route.ts | 21 - .../api/delivery-orders/counter/route.test.ts | 47 - .../app/api/delivery-orders/counter/route.ts | 36 - .../[uuid]/mark-collected/route.test.ts | 46 - .../pickup/[uuid]/mark-collected/route.ts | 23 - .../pickup/[uuid]/mark-ready/route.test.ts | 46 - .../pickup/[uuid]/mark-ready/route.ts | 23 - .../pickup/[uuid]/route.test.ts | 40 - .../delivery-orders/pickup/[uuid]/route.ts | 20 - .../api/delivery-orders/pickup/route.test.ts | 47 - .../app/api/delivery-orders/pickup/route.ts | 38 - .../app/api/delivery-orders/route.test.ts | 82 - .../app/api/delivery-orders/route.ts | 40 - .../to-issue/[orderUuid]/issue/route.test.ts | 62 - .../to-issue/[orderUuid]/issue/route.ts | 21 - .../to-issue/[orderUuid]/plan/route.test.ts | 33 - .../to-issue/[orderUuid]/plan/route.ts | 20 - .../delivery-orders/to-issue/route.test.ts | 60 - .../app/api/delivery-orders/to-issue/route.ts | 22 - .../api/email-logs/[id]/resend/route.test.ts | 57 - .../app/api/email-logs/[id]/resend/route.ts | 24 - .../app/api/email-logs/[id]/route.test.ts | 63 - .../app/api/email-logs/[id]/route.ts | 20 - .../app/api/email-logs/route.test.ts | 40 - .../app/api/email-logs/route.ts | 34 - .../api/email-templates/[id]/route.test.ts | 76 - .../app/api/email-templates/[id]/route.ts | 28 - .../api/email-templates/[id]/status/route.ts | 27 - .../api/email-templates/attachments/route.ts | 32 - .../email-templates/by-name/[name]/route.ts | 23 - .../api/email-templates/preview/route.test.ts | 67 - .../app/api/email-templates/preview/route.ts | 30 - .../app/api/email-templates/route.test.ts | 130 - .../app/api/email-templates/route.ts | 62 - .../[id]/close-out/[action]/route.test.ts | 57 - .../events/[id]/close-out/[action]/route.ts | 37 - .../api/events/[id]/close-out/route.test.ts | 39 - .../app/api/events/[id]/close-out/route.ts | 19 - .../app/api/events/[id]/route.test.ts | 100 - .../app/api/events/[id]/route.ts | 38 - .../api/events/pickup-outlets/route.test.ts | 40 - .../app/api/events/pickup-outlets/route.ts | 16 - .../app/api/events/route.test.ts | 98 - solvway-admin-portal/app/api/events/route.ts | 33 - .../app/api/forms/[id]/delete/route.ts | 20 - .../app/api/forms/[id]/route.ts | 17 - .../app/api/forms/[id]/submissions/route.ts | 29 - solvway-admin-portal/app/api/forms/route.ts | 26 - .../app/api/forms/routes.test.ts | 98 - .../forms/submissions/[sid]/delete/route.ts | 20 - .../app/api/forms/submissions/[sid]/route.ts | 17 - .../app/api/fulfilment-events/note/route.ts | 23 - .../app/api/fulfilment-events/route.test.ts | 60 - .../app/api/fulfilment-events/route.ts | 27 - .../app/api/fulfilment-health/route.test.ts | 29 - .../app/api/fulfilment-health/route.ts | 17 - .../api/fulfilment/[...path]/route.test.ts | 123 - .../app/api/fulfilment/[...path]/route.ts | 107 - .../app/api/geo-locations/route.test.ts | 73 - .../app/api/geo-locations/route.ts | 30 - .../api/gift-cards/[uuid]/deactivate/route.ts | 23 - .../app/api/gift-cards/[uuid]/extend/route.ts | 23 - .../gift-cards/[uuid]/resend-email/route.ts | 23 - .../app/api/gift-cards/[uuid]/route.ts | 16 - .../app/api/gift-cards/amounts/[id]/route.ts | 22 - .../app/api/gift-cards/amounts/route.ts | 26 - .../app/api/gift-cards/issue/route.ts | 24 - .../app/api/gift-cards/route.ts | 26 - .../app/api/gift-cards/routes.test.ts | 90 - .../app/api/health/route.test.ts | 11 - solvway-admin-portal/app/api/health/route.ts | 9 - .../app/api/listSort.sorting.test.ts | 47 - .../app/api/locales/[id]/route.test.ts | 71 - .../app/api/locales/[id]/route.ts | 31 - .../app/api/locales/route.test.ts | 103 - solvway-admin-portal/app/api/locales/route.ts | 40 - .../app/api/locations/[id]/route.test.ts | 65 - .../app/api/locations/[id]/route.ts | 33 - .../locations/invoice-header/route.test.ts | 78 - .../app/api/locations/invoice-header/route.ts | 30 - .../app/api/locations/route.test.ts | 73 - .../app/api/locations/route.ts | 36 - .../api/login-security/audit/route.test.ts | 60 - .../app/api/login-security/audit/route.ts | 32 - .../locked/[username]/unlock/route.test.ts | 82 - .../locked/[username]/unlock/route.ts | 21 - .../api/login-security/locked/route.test.ts | 44 - .../app/api/login-security/locked/route.ts | 14 - .../lockout-config/route.test.ts | 70 - .../login-security/lockout-config/route.ts | 40 - .../session-policy/route.members.test.ts | 46 - .../session-policy/route.rangeCode.test.ts | 24 - .../session-policy/route.test.ts | 63 - .../login-security/session-policy/route.ts | 50 - .../app/api/menus/[handle]/route.ts | 44 - .../app/api/menus/routes.test.ts | 71 - .../app/api/messages/[id]/route.test.ts | 118 - .../app/api/messages/[id]/route.ts | 42 - .../app/api/messages/export/route.test.ts | 69 - .../app/api/messages/export/route.ts | 26 - .../app/api/messages/import/route.test.ts | 64 - .../app/api/messages/import/route.ts | 27 - .../app/api/messages/route.test.ts | 140 - .../app/api/messages/route.ts | 60 - .../app/api/modules/[id]/route.test.ts | 107 - .../app/api/modules/[id]/route.ts | 44 - .../app/api/modules/route.test.ts | 105 - solvway-admin-portal/app/api/modules/route.ts | 40 - .../api/notifications/[id]/read/route.test.ts | 41 - .../app/api/notifications/[id]/read/route.ts | 24 - .../api/notifications/read-all/route.test.ts | 31 - .../app/api/notifications/read-all/route.ts | 19 - .../app/api/notifications/route.test.ts | 114 - .../app/api/notifications/route.ts | 55 - .../notifications/unread-count/route.test.ts | 31 - .../api/notifications/unread-count/route.ts | 16 - .../app/api/online-payments/[id]/route.ts | 23 - .../app/api/online-payments/route.ts | 35 - .../app/api/online-payments/routes.test.ts | 46 - .../app/api/online-users/route.test.ts | 53 - .../app/api/online-users/route.ts | 23 - .../api/online-users/sign-out/route.test.ts | 67 - .../app/api/online-users/sign-out/route.ts | 31 - .../app/api/pages/[id]/delete/route.ts | 20 - .../app/api/pages/[id]/route.ts | 17 - .../app/api/pages/image/route.ts | 22 - solvway-admin-portal/app/api/pages/route.ts | 27 - .../app/api/pages/routes.test.ts | 88 - .../app/api/payment-methods/[id]/route.ts | 27 - .../app/api/payment-methods/route.ts | 34 - .../app/api/pos/events/route.ts | 18 - .../app/api/pos/gift-card/amounts/route.ts | 22 - .../app/api/pos/gift-card/check/route.ts | 24 - .../app/api/pos/gift-card/routes.test.ts | 59 - .../app/api/pos/gift-card/sale/route.ts | 24 - .../app/api/pos/payment-methods/route.test.ts | 62 - .../app/api/pos/payment-methods/route.ts | 19 - .../app/api/pos/pickup-outlets/route.test.ts | 40 - .../app/api/pos/pickup-outlets/route.ts | 16 - .../app/api/pos/products/route.test.ts | 39 - .../app/api/pos/products/route.ts | 23 - .../app/api/pos/quote/route.test.ts | 50 - .../app/api/pos/quote/route.ts | 21 - .../app/api/pos/sale/route.test.ts | 93 - .../app/api/pos/sale/route.ts | 64 - .../api/pos/split/cancel/[uuid]/route.test.ts | 42 - .../app/api/pos/split/cancel/[uuid]/route.ts | 29 - .../app/api/pos/split/sale/route.test.ts | 109 - .../app/api/pos/split/sale/route.ts | 51 - .../api/pos/split/status/[uuid]/route.test.ts | 42 - .../app/api/pos/split/status/[uuid]/route.ts | 30 - .../api/pos/wallet/[memberCode]/route.test.ts | 81 - .../app/api/pos/wallet/[memberCode]/route.ts | 31 - .../app/api/pos/wallet/preview/route.test.ts | 122 - .../app/api/pos/wallet/preview/route.ts | 28 - .../app/api/pos/wallet/sale/route.test.ts | 171 - .../app/api/pos/wallet/sale/route.ts | 53 - .../[refno]/images/[index]/route.ts | 57 - .../product-reviews/[refno]/reply/route.ts | 17 - .../app/api/product-reviews/[refno]/route.ts | 14 - .../product-reviews/[refno]/status/route.ts | 22 - .../app/api/product-reviews/route.ts | 24 - .../app/api/product-reviews/routes.test.ts | 54 - .../app/api/products/[id]/route.test.ts | 123 - .../app/api/products/[id]/route.ts | 36 - .../app/api/products/filters.ts | 14 - .../app/api/products/image/route.test.ts | 78 - .../app/api/products/image/route.ts | 31 - .../app/api/products/import/commit/route.ts | 21 - .../api/products/import/export/route.test.ts | 54 - .../app/api/products/import/export/route.ts | 20 - .../app/api/products/import/route.test.ts | 68 - .../app/api/products/import/validate/route.ts | 21 - .../app/api/products/options/route.test.ts | 62 - .../app/api/products/options/route.ts | 20 - .../api/products/qianyi-skus/route.test.ts | 58 - .../app/api/products/qianyi-skus/route.ts | 22 - .../app/api/products/route.test.ts | 167 - .../app/api/products/route.ts | 53 - .../sku-variation-options/route.test.ts | 23 - .../products/sku-variation-options/route.ts | 21 - .../sku-variations-by-code/route.test.ts | 35 - .../products/sku-variations-by-code/route.ts | 21 - .../app/api/products/skus/[id]/route.test.ts | 37 - .../app/api/products/skus/[id]/route.ts | 17 - .../app/api/products/skus/route.test.ts | 55 - .../app/api/products/skus/route.ts | 31 - .../app/api/products/tags/route.test.ts | 48 - .../app/api/products/tags/route.ts | 16 - .../campaigns/[uuid]/duplicate/route.ts | 26 - .../api/promotions/campaigns/[uuid]/route.ts | 40 - .../campaigns/[uuid]/routes.replaced.test.ts | 40 - .../campaigns/[uuid]/status/route.ts | 34 - .../campaigns/[uuid]/voucher-batches/route.ts | 22 - .../[uuid]/vouchers/generate/route.ts | 33 - .../campaigns/[uuid]/vouchers/route.ts | 82 - .../app/api/promotions/campaigns/route.ts | 40 - .../app/api/promotions/paging.ts | 46 - .../app/api/promotions/redemptions/route.ts | 31 - .../app/api/promotions/routes.test.ts | 305 -- .../app/api/promotions/voucherRoutes.test.ts | 153 - .../[voucherUuid]/resend-email/route.ts | 23 - .../vouchers/[voucherUuid]/revoke/route.ts | 23 - .../api/reference/[table]/[id]/route.test.ts | 71 - .../app/api/reference/[table]/[id]/route.ts | 34 - .../app/api/reference/[table]/route.test.ts | 128 - .../app/api/reference/[table]/route.ts | 47 - .../app/api/reference/bank/[id]/route.test.ts | 52 - .../app/api/reference/bank/[id]/route.ts | 28 - .../reference/bank/countries/route.test.ts | 34 - .../app/api/reference/bank/countries/route.ts | 16 - .../app/api/reference/bank/route.test.ts | 112 - .../app/api/reference/bank/route.ts | 44 - .../api/refunds/[uuid]/approve/route.test.ts | 80 - .../app/api/refunds/[uuid]/approve/route.ts | 26 - .../[uuid]/photos/[index]/route.test.ts | 63 - .../refunds/[uuid]/photos/[index]/route.ts | 57 - .../api/refunds/[uuid]/reject/route.test.ts | 75 - .../app/api/refunds/[uuid]/reject/route.ts | 26 - .../refunds/[uuid]/retry-email/route.test.ts | 80 - .../api/refunds/[uuid]/retry-email/route.ts | 23 - .../app/api/refunds/[uuid]/route.test.ts | 43 - .../app/api/refunds/[uuid]/route.ts | 21 - .../cancelShipment/[doUuid]/route.test.ts | 107 - .../refunds/cancelShipment/[doUuid]/route.ts | 52 - .../eligibility/[orderUuid]/route.test.ts | 30 - .../refunds/eligibility/[orderUuid]/route.ts | 20 - .../app/api/refunds/raise/route.test.ts | 56 - .../app/api/refunds/raise/route.ts | 28 - .../app/api/refunds/route.test.ts | 85 - solvway-admin-portal/app/api/refunds/route.ts | 35 - .../app/api/remainingSort.sorting.test.ts | 47 - .../app/api/shipping/[...path]/route.test.ts | 76 - .../app/api/shipping/[...path]/route.ts | 47 - .../stock-counts/[id]/[action]/route.test.ts | 68 - .../api/stock-counts/[id]/[action]/route.ts | 35 - .../app/api/stock-counts/[id]/route.test.ts | 40 - .../app/api/stock-counts/[id]/route.ts | 19 - .../app/api/stock-counts/route.test.ts | 60 - .../app/api/stock-counts/route.ts | 45 - .../app/api/stock/adjustment/route.test.ts | 70 - .../app/api/stock/adjustment/route.ts | 23 - .../app/api/stock/in/route.test.ts | 59 - .../app/api/stock/in/route.ts | 23 - .../app/api/stock/movements/route.test.ts | 92 - .../app/api/stock/movements/route.ts | 35 - .../app/api/stock/on-hand/route.test.ts | 105 - .../app/api/stock/on-hand/route.ts | 33 - .../[productId]/route.test.ts | 53 - .../product-variations/[productId]/route.ts | 25 - .../app/api/stock/sku-catalog/route.test.ts | 53 - .../app/api/stock/sku-catalog/route.ts | 21 - .../app/api/stock/transfer/route.test.ts | 77 - .../app/api/stock/transfer/route.ts | 23 - .../app/api/warehouses/[id]/route.test.ts | 56 - .../app/api/warehouses/[id]/route.ts | 25 - .../api/warehouses/branch-store/route.test.ts | 49 - .../app/api/warehouses/branch-store/route.ts | 19 - .../app/api/warehouses/route.test.ts | 88 - .../app/api/warehouses/route.ts | 34 - .../[uuid]/approve/route.test.ts | 80 - .../warranty-claims/[uuid]/approve/route.ts | 26 - .../[uuid]/photos/[index]/route.test.ts | 63 - .../[uuid]/photos/[index]/route.ts | 57 - .../[uuid]/reject/route.test.ts | 75 - .../warranty-claims/[uuid]/reject/route.ts | 26 - .../api/warranty-claims/[uuid]/route.test.ts | 43 - .../app/api/warranty-claims/[uuid]/route.ts | 21 - .../app/api/warranty-claims/route.test.ts | 64 - .../app/api/warranty-claims/route.ts | 34 - .../web-orders/[uuid]/invoice/route.test.ts | 99 - .../api/web-orders/[uuid]/invoice/route.ts | 68 - .../app/api/web-orders/[uuid]/route.test.ts | 40 - .../app/api/web-orders/[uuid]/route.ts | 21 - .../[uuid]/void-pending/route.test.ts | 59 - .../web-orders/[uuid]/void-pending/route.ts | 20 - .../app/api/web-orders/route.test.ts | 58 - .../app/api/web-orders/route.ts | 41 - .../app/audit-log/page.test.tsx | 394 -- solvway-admin-portal/app/audit-log/page.tsx | 397 -- .../app/banners/BannerFormDialog.tsx | 502 --- .../app/banners/page.sorting.test.tsx | 91 - .../app/banners/page.test.tsx | 364 -- solvway-admin-portal/app/banners/page.tsx | 396 -- .../app/bulletins/BulletinDrawer.tsx | 88 - .../bulletins/page.area-sort.sorting.test.tsx | 45 - .../app/bulletins/page.sorting.test.tsx | 56 - .../app/bulletins/page.test.tsx | 495 --- solvway-admin-portal/app/bulletins/page.tsx | 694 ---- .../app/catalog-setup/page.copy.test.tsx | 56 - .../app/catalog-setup/page.sorting.test.tsx | 93 - .../app/catalog-setup/page.test.tsx | 593 --- .../app/catalog-setup/page.tsx | 494 --- .../app/collections/[id]/page.tsx | 22 - .../app/collections/new/page.tsx | 20 - .../app/collections/page.sorting.test.tsx | 102 - .../app/collections/page.test.tsx | 98 - solvway-admin-portal/app/collections/page.tsx | 148 - .../app/components/app/AppShell.tsx | 2 +- .../app/components/app/Breadcrumbs.test.tsx | 17 +- .../components/app/CommandPalette.test.tsx | 225 - .../app/components/app/CommandPalette.tsx | 141 - .../app/components/app/Header.test.tsx | 10 +- .../app/components/app/Header.tsx | 6 - .../app/components/app/LocaleSwitcher.tsx | 2 +- .../app/MemberMessagesBadge.test.tsx | 56 - .../components/app/MemberMessagesBadge.tsx | 55 - .../app/NotificationsBell.messages.test.tsx | 68 - .../components/app/NotificationsBell.test.tsx | 193 - .../app/components/app/NotificationsBell.tsx | 234 -- .../app/components/app/SectionTabs.test.tsx | 62 - .../app/components/app/SectionTabs.tsx | 70 - .../app/components/app/Sidebar.test.tsx | 113 +- .../app/components/app/Sidebar.tsx | 11 +- .../app/components/app/icon-map.ts | 9 +- .../components/catalog-setup/BarcodeList.tsx | 117 - .../components/catalog-setup/FieldError.tsx | 16 - .../catalog-setup/SkuDrawer.test.tsx | 112 - .../components/catalog-setup/SkuDrawer.tsx | 144 - .../catalog-setup/SkuEditor.barcodes.test.tsx | 109 - .../catalog-setup/SkuEditor.supplier.test.tsx | 46 - .../catalog-setup/SkuEditor.test.tsx | 284 -- .../components/catalog-setup/SkuEditor.tsx | 422 -- .../catalog-setup/SkuList.export.test.tsx | 68 - .../components/catalog-setup/SkuList.test.tsx | 229 -- .../app/components/catalog-setup/SkuList.tsx | 187 - .../catalog-setup/SkuPicker.test.tsx | 72 - .../components/catalog-setup/SkuPicker.tsx | 115 - .../catalog-setup/SkuVariationPicker.test.tsx | 39 - .../catalog-setup/SkuVariationPicker.tsx | 119 - .../catalog-setup/SupplierSelect.test.tsx | 63 - .../catalog-setup/SupplierSelect.tsx | 67 - .../collections/CollectionForm.test.tsx | 279 -- .../components/collections/CollectionForm.tsx | 587 --- .../dashboard/EventDashboard.alerts.test.tsx | 145 - .../EventDashboard.drilldown.test.tsx | 112 - .../dashboard/EventDashboard.test.tsx | 303 -- .../components/dashboard/EventDashboard.tsx | 506 --- .../app/components/dashboard/action-strip.tsx | 44 - .../components/dashboard/chart-card.test.tsx | 15 - .../app/components/dashboard/chart-card.tsx | 65 - .../components/dashboard/drill-link.test.tsx | 89 - .../app/components/dashboard/drill-link.tsx | 37 - .../app/components/dashboard/hero-band.tsx | 143 - .../components/dashboard/kpi-tile.test.tsx | 30 - .../app/components/dashboard/kpi-tile.tsx | 165 - .../dashboard/page.curve.guard.test.ts | 20 - .../components/events/EventCharts.test.tsx | 15 - .../app/components/events/EventCharts.tsx | 215 - .../events/EventCloseOutDialog.test.tsx | 161 - .../components/events/EventCloseOutDialog.tsx | 145 - .../components/events/EventPicker.test.tsx | 34 - .../app/components/events/EventPicker.tsx | 56 - .../components/events/RunProgress.test.tsx | 56 - .../app/components/events/RunProgress.tsx | 33 - .../app/components/forms/FormEditor.test.tsx | 202 - .../app/components/forms/FormEditor.tsx | 269 -- .../forms/SubmissionsView.sorting.test.tsx | 60 - .../components/forms/SubmissionsView.test.tsx | 198 - .../app/components/forms/SubmissionsView.tsx | 237 -- .../fulfilment/FulfilmentTimeline.test.tsx | 138 - .../fulfilment/FulfilmentTimeline.tsx | 156 - .../app/components/genealogy/org-chart.css | 113 - .../components/genealogy/org-chart.test.tsx | 426 -- .../app/components/genealogy/org-chart.tsx | 436 -- .../components/genealogy/tree-view.test.tsx | 98 - .../app/components/genealogy/tree-view.tsx | 180 - .../inventory/AdjustmentForm.test.tsx | 578 --- .../components/inventory/AdjustmentForm.tsx | 602 --- .../inventory/MovementHistoryReport.test.tsx | 593 --- .../inventory/MovementHistoryReport.tsx | 374 -- .../StockCountDetail.sorting.test.tsx | 87 - .../inventory/StockCountDetail.test.tsx | 501 --- .../components/inventory/StockCountDetail.tsx | 296 -- .../inventory/StockCountsTab.sorting.test.tsx | 98 - .../inventory/StockCountsTab.test.tsx | 118 - .../components/inventory/StockCountsTab.tsx | 170 - .../components/inventory/StockInForm.test.tsx | 620 --- .../app/components/inventory/StockInForm.tsx | 628 --- .../inventory/StockOnHandReport.test.tsx | 438 -- .../inventory/StockOnHandReport.tsx | 252 -- .../inventory/TransferForm.test.tsx | 819 ---- .../app/components/inventory/TransferForm.tsx | 796 ---- .../inventory/insufficientStock.test.ts | 81 - .../components/inventory/insufficientStock.ts | 39 - .../app/components/kyc/KycDocViewer.tsx | 48 - .../app/components/kyc/KycDrawer.tsx | 53 - .../components/kyc/KycReviewDrawer.test.tsx | 201 - .../app/components/kyc/KycReviewDrawer.tsx | 294 -- .../app/components/kyc/KycStatusBadge.tsx | 22 - .../components/kyc/KycSubmitDrawer.test.tsx | 89 - .../app/components/kyc/KycSubmitDrawer.tsx | 288 -- .../locations/AddLocationDialog.test.tsx | 59 - .../locations/AddLocationDialog.tsx | 117 - .../locations/LocationDetailTabs.test.tsx | 67 - .../locations/LocationDetailTabs.tsx | 75 - .../locations/LocationTree.test.tsx | 47 - .../app/components/locations/LocationTree.tsx | 153 - .../locations/MoveLocationDialog.test.tsx | 57 - .../locations/MoveLocationDialog.tsx | 112 - .../locations/StatusToggleDialog.test.tsx | 45 - .../locations/StatusToggleDialog.tsx | 80 - .../locations/tabs/AddressKycTab.test.tsx | 34 - .../locations/tabs/AddressKycTab.tsx | 105 - .../locations/tabs/GeneralTab.test.tsx | 75 - .../components/locations/tabs/GeneralTab.tsx | 88 - .../locations/tabs/GeoAddressTab.test.tsx | 89 - .../locations/tabs/GeoAddressTab.tsx | 121 - .../locations/tabs/InvoicingTab.test.tsx | 187 - .../locations/tabs/InvoicingTab.tsx | 189 - .../locations/tabs/PickupOutletTab.test.tsx | 64 - .../locations/tabs/PickupOutletTab.tsx | 72 - .../locations/tabs/WarehouseTab.test.tsx | 129 - .../locations/tabs/WarehouseTab.tsx | 133 - .../components/members/MemberCell.test.tsx | 46 - .../app/components/members/MemberCell.tsx | 35 - .../members/MemberSearchCombobox.test.tsx | 335 -- .../members/MemberSearchCombobox.tsx | 303 -- .../app/components/menus/MenuEditor.test.tsx | 129 - .../app/components/menus/MenuEditor.tsx | 205 - .../ImageAttachments.hardening.test.tsx | 52 - .../messages/ImageAttachments.test.tsx | 78 - .../components/messages/ImageAttachments.tsx | 116 - .../messages/MemberSearch.hardening.test.tsx | 65 - .../components/messages/MemberSearch.test.tsx | 36 - .../app/components/messages/MemberSearch.tsx | 68 - .../MessageThreadDrawer.hardening.test.tsx | 51 - .../MessageThreadDrawer.scroll.test.tsx | 79 - .../messages/MessageThreadDrawer.test.tsx | 138 - .../messages/MessageThreadDrawer.tsx | 215 - .../NewMessageDialog.hardening.test.tsx | 55 - .../messages/NewMessageDialog.test.tsx | 79 - .../components/messages/NewMessageDialog.tsx | 86 - .../app/components/pages/BlockFields.tsx | 311 -- .../pages/PageEditor.blocks.test.tsx | 234 -- .../pages/PageEditor.forms.test.tsx | 88 - .../pages/PageEditor.review.test.tsx | 145 - .../app/components/pages/PageEditor.test.tsx | 309 -- .../app/components/pages/PageEditor.tsx | 322 -- .../product-page/BundleSection.test.tsx | 230 -- .../components/product-page/BundleSection.tsx | 271 -- .../product-page/CodeMatchNotice.tsx | 61 - .../components/product-page/GroupSection.tsx | 43 - .../product-page/LinkedSku.test.tsx | 269 -- .../product-page/LinkedSkuBanner.tsx | 30 - .../product-page/OptionChips.test.tsx | 38 - .../components/product-page/OptionChips.tsx | 86 - .../product-page/PriceList.test.tsx | 395 -- .../app/components/product-page/PriceList.tsx | 390 -- .../product-page/ProductSetupPage.test.tsx | 541 --- .../product-page/ProductSetupPage.tsx | 497 --- .../app/components/product-page/SetupStep.tsx | 117 - .../components/product-page/SideColumn.tsx | 130 - .../product-page/TypeChooser.test.tsx | 34 - .../components/product-page/TypeChooser.tsx | 52 - .../product-page/VariantsSection.test.tsx | 560 --- .../product-page/VariantsSection.tsx | 520 --- .../product-page/priceTypeLabel.test.ts | 11 - .../products/ProductSearchCombobox.test.tsx | 155 - .../products/ProductSearchCombobox.tsx | 153 - .../products/QianyiSkuPicker.test.tsx | 122 - .../components/products/QianyiSkuPicker.tsx | 179 - .../products/RichTextEditor.test.tsx | 284 -- .../components/products/RichTextEditor.tsx | 329 -- .../app/components/products/TagInput.test.tsx | 98 - .../app/components/products/TagInput.tsx | 84 - .../panels/ContentImagesPanel.test.tsx | 225 - .../products/panels/ContentImagesPanel.tsx | 230 -- .../panels/GroupPanel.picker.test.tsx | 51 - .../products/panels/GroupPanel.test.tsx | 186 - .../components/products/panels/GroupPanel.tsx | 144 - .../panels/OrganizationPanel.test.tsx | 110 - .../products/panels/OrganizationPanel.tsx | 140 - .../panels/ProductDetailsPanel.test.tsx | 70 - .../products/panels/ProductDetailsPanel.tsx | 110 - .../app/components/products/panels/types.ts | 6 - .../refunds/CancelShipmentAction.test.tsx | 185 - .../refunds/CancelShipmentAction.tsx | 213 - .../app/components/refunds/PayoutFields.tsx | 87 - .../shipping/CalculatorTab.test.tsx | 53 - .../app/components/shipping/CalculatorTab.tsx | 122 - .../shipping/CouriersTab.sorting.test.tsx | 77 - .../components/shipping/CouriersTab.test.tsx | 53 - .../app/components/shipping/CouriersTab.tsx | 136 - .../shipping/RateCardEditor.test.tsx | 338 -- .../components/shipping/RateCardEditor.tsx | 305 -- .../shipping/RateCardsTab.sorting.test.tsx | 84 - .../components/shipping/RateCardsTab.test.tsx | 86 - .../app/components/shipping/RateCardsTab.tsx | 141 - .../app/components/shipping/RegionPicker.tsx | 65 - .../shipping/ZoneRatesTable.test.tsx | 97 - .../components/shipping/ZoneRatesTable.tsx | 180 - .../shipping/ZonesTab.sorting.test.tsx | 80 - .../app/components/shipping/ZonesTab.test.tsx | 51 - .../app/components/shipping/ZonesTab.tsx | 128 - .../app/components/ui/breakable-code.test.tsx | 30 - .../app/components/ui/breakable-code.tsx | 26 - .../app/components/ui/calendar.test.tsx | 23 - .../app/components/ui/calendar.tsx | 21 - .../app/components/ui/chart-skeleton.tsx | 37 - .../app/components/ui/chart.tsx | 372 -- .../app/components/ui/command.test.tsx | 53 - .../app/components/ui/command.tsx | 189 - .../app/components/ui/confirm-dialog.test.tsx | 36 - .../app/components/ui/confirm-dialog.tsx | 57 - .../ui/country-code-picker.test.tsx | 48 - .../app/components/ui/country-code-picker.tsx | 78 - .../app/components/ui/date-picker.test.tsx | 122 - .../app/components/ui/date-picker.tsx | 138 - .../components/ui/date-range-picker.test.tsx | 182 - .../app/components/ui/date-range-picker.tsx | 95 - .../components/ui/date-time-picker.test.tsx | 113 - .../app/components/ui/date-time-picker.tsx | 111 - .../app/components/ui/detail-field.test.tsx | 28 - .../app/components/ui/detail-field.tsx | 14 - .../app/components/ui/markdown.tsx | 25 - .../app/components/ui/radio-group.test.tsx | 21 - .../app/components/ui/radio-group.tsx | 42 - .../app/components/ui/segmented.test.tsx | 25 - .../app/components/ui/segmented.tsx | 61 - .../app/components/ui/separator.tsx | 28 - .../app/components/ui/tabs.tsx | 89 - .../app/components/ui/textarea.test.tsx | 26 - .../app/components/ui/textarea.tsx | 23 - .../users/UserForm.countryScope.test.tsx | 206 - .../components/users/UserForm.event.test.tsx | 144 - .../app/components/users/UserForm.test.tsx | 34 +- .../app/components/users/UserForm.tsx | 222 +- .../warehouses/WarehouseFormDialog.test.tsx | 337 -- .../warehouses/WarehouseFormDialog.tsx | 255 -- .../warehouses/WarehouseTree.test.tsx | 45 - .../components/warehouses/WarehouseTree.tsx | 99 - .../warehouses/warehouseLabels.test.ts | 13 - .../components/warehouses/warehouseLabels.ts | 41 - .../app/currency/page.sorting.test.tsx | 42 - .../app/currency/page.test.tsx | 371 -- solvway-admin-portal/app/currency/page.tsx | 325 -- .../app/design-tokens.test.ts | 4 +- .../EmailTemplateEditor.test.tsx | 185 - .../email-templates/EmailTemplateEditor.tsx | 424 -- .../TemplatePreviewPane.test.tsx | 33 - .../email-templates/TemplatePreviewPane.tsx | 23 - .../app/email-templates/[name]/page.test.tsx | 67 - .../app/email-templates/[name]/page.tsx | 113 - .../email-templates/logs/[id]/page.test.tsx | 219 - .../app/email-templates/logs/[id]/page.tsx | 217 - .../app/email-templates/new/page.tsx | 31 - .../page.remaining-sort.sorting.test.tsx | 83 - .../app/email-templates/page.sorting.test.tsx | 44 - .../app/email-templates/page.test.tsx | 431 -- .../app/email-templates/page.tsx | 491 --- .../app/events/page.export.test.tsx | 87 - .../app/events/page.sorting.test.tsx | 107 - solvway-admin-portal/app/events/page.test.tsx | 698 ---- solvway-admin-portal/app/events/page.tsx | 700 ---- .../app/events/summary/page.test.tsx | 436 -- .../app/events/summary/page.tsx | 395 -- solvway-admin-portal/app/forms/[id]/page.tsx | 22 - .../app/forms/[id]/submissions/page.tsx | 16 - solvway-admin-portal/app/forms/new/page.tsx | 20 - .../app/forms/page.sorting.test.tsx | 93 - solvway-admin-portal/app/forms/page.test.tsx | 61 - solvway-admin-portal/app/forms/page.tsx | 137 - .../gift-cards/AmountsPanel.sorting.test.tsx | 87 - .../app/gift-cards/AmountsPanel.tsx | 140 - .../app/gift-cards/CardsPanel.export.test.tsx | 89 - .../app/gift-cards/CardsPanel.tsx | 171 - .../app/gift-cards/GiftCardDrawer.tsx | 199 - .../IssueGiftCardsDialog.country.test.tsx | 70 - .../app/gift-cards/IssueGiftCardsDialog.tsx | 206 - .../app/gift-cards/giftCardLabels.test.ts | 22 - .../app/gift-cards/giftCardLabels.ts | 44 - .../app/gift-cards/page.test.tsx | 319 -- solvway-admin-portal/app/gift-cards/page.tsx | 56 - solvway-admin-portal/app/globals.css | 66 +- solvway-admin-portal/app/globals.test.ts | 20 - .../delivery-orders/BulkIssueDialog.test.tsx | 143 - .../delivery-orders/BulkIssueDialog.tsx | 154 - .../DeliveryDetailBody.sorting.test.tsx | 83 - .../DeliveryDetailBody.test.tsx | 190 - .../delivery-orders/DeliveryDetailBody.tsx | 422 -- .../delivery-orders/DoDetailDrawer.test.tsx | 197 - .../delivery-orders/DoDetailDrawer.tsx | 80 - .../delivery-orders/DoStepper.test.tsx | 52 - .../inventory/delivery-orders/DoStepper.tsx | 33 - .../FulfilmentHealthStrip.test.tsx | 78 - .../delivery-orders/FulfilmentHealthStrip.tsx | 159 - .../delivery-orders/IssueDrawer.test.tsx | 178 - .../inventory/delivery-orders/IssueDrawer.tsx | 222 - .../PickupDetailBody.sorting.test.tsx | 76 - .../delivery-orders/PickupDetailBody.test.tsx | 257 -- .../delivery-orders/PickupDetailBody.tsx | 273 -- .../delivery-orders/SelectionBar.tsx | 23 - .../delivery-orders/ToIssueTab.bulk.test.tsx | 139 - .../delivery-orders/ToIssueTab.test.tsx | 216 - .../inventory/delivery-orders/ToIssueTab.tsx | 410 -- .../[uuid]/QianyiPushPanel.test.tsx | 89 - .../[uuid]/QianyiPushPanel.tsx | 125 - .../delivery-orders/[uuid]/page.test.tsx | 389 -- .../inventory/delivery-orders/[uuid]/page.tsx | 36 - .../counter/[uuid]/page.sorting.test.tsx | 74 - .../counter/[uuid]/page.test.tsx | 134 - .../delivery-orders/counter/[uuid]/page.tsx | 192 - .../delivery-orders/counterChannel.test.ts | 22 - .../delivery-orders/counterChannel.ts | 10 - .../delivery-orders/deliveryStatus.test.ts | 76 - .../delivery-orders/deliveryStatus.ts | 82 - .../delivery-orders/fulfilment.test.tsx | 435 -- .../fulfilment/BatchProgressDialog.test.tsx | 74 - .../fulfilment/BatchProgressDialog.tsx | 100 - .../fulfilment/ImportTrackingDialog.test.tsx | 149 - .../fulfilment/ImportTrackingDialog.tsx | 142 - .../inventory/delivery-orders/lineNames.ts | 18 - .../delivery-orders/page.export.test.tsx | 253 -- .../inventory/delivery-orders/page.test.tsx | 1383 ------- .../app/inventory/delivery-orders/page.tsx | 1281 ------ .../delivery-orders/pick-list/page.test.tsx | 111 - .../delivery-orders/pick-list/page.tsx | 102 - .../pickup/[uuid]/page.test.tsx | 134 - .../delivery-orders/pickup/[uuid]/page.tsx | 94 - .../app/inventory/page.test.tsx | 285 -- solvway-admin-portal/app/inventory/page.tsx | 192 - .../app/inventory/stock-counts/[id]/page.tsx | 15 - solvway-admin-portal/app/layout.tsx | 11 +- .../AdminAuthContext.countryScope.test.tsx | 39 - .../lib/AdminAuthContext.refundsOff.test.tsx | 144 - .../app/lib/AdminAuthContext.tsx | 19 +- .../app/lib/RequireModule.test.tsx | 39 +- .../app/lib/RequireModule.tsx | 3 +- solvway-admin-portal/app/lib/aclSidebar.ts | 8 +- .../app/lib/auditAction.test.ts | 28 - solvway-admin-portal/app/lib/auditAction.ts | 27 - .../app/lib/catalogI18n.test.ts | 68 - .../app/lib/catalogImport.test.ts | 687 ---- solvway-admin-portal/app/lib/catalogImport.ts | 524 --- .../app/lib/catalogSetup.barcodes.test.ts | 155 - .../app/lib/catalogSetup.optionChips.test.ts | 81 - .../app/lib/catalogSetup.options.test.ts | 323 -- .../app/lib/catalogSetup.supplier.test.ts | 21 - .../app/lib/catalogSetup.test.ts | 743 ---- solvway-admin-portal/app/lib/catalogSetup.ts | 936 ----- .../app/lib/catalogSetup.variantLabel.test.ts | 38 - .../app/lib/catalogTables.supplier.test.ts | 19 - .../app/lib/catalogTables.test.ts | 67 - solvway-admin-portal/app/lib/catalogTables.ts | 99 - .../app/lib/catalogueExport.test.ts | 114 - solvway-admin-portal/app/lib/cmsForms.test.ts | 78 - solvway-admin-portal/app/lib/cmsForms.ts | 158 - solvway-admin-portal/app/lib/cmsPages.test.ts | 77 - solvway-admin-portal/app/lib/cmsPages.ts | 159 - .../app/lib/codeOrNameSearch.test.ts | 26 - .../app/lib/codeOrNameSearch.ts | 6 - .../app/lib/collections.test.ts | 182 - solvway-admin-portal/app/lib/collections.ts | 223 - .../app/lib/correctionReason.test.ts | 23 - .../app/lib/correctionReason.ts | 16 - .../app/lib/countryCallingCodes.test.ts | 43 - .../app/lib/countryCallingCodes.ts | 298 -- .../app/lib/date-input.test.ts | 24 - solvway-admin-portal/app/lib/date-input.ts | 24 - solvway-admin-portal/app/lib/downloadDoPdf.ts | 19 - .../app/lib/eventState.test.ts | 40 - solvway-admin-portal/app/lib/eventState.ts | 57 - solvway-admin-portal/app/lib/eventTenders.ts | 20 - .../app/lib/exportAll.test.ts | 196 - solvway-admin-portal/app/lib/exportAll.ts | 32 - solvway-admin-portal/app/lib/features.ts | 2 - solvway-admin-portal/app/lib/fileToBase64.ts | 9 - .../app/lib/filterOptions.test.ts | 39 - solvway-admin-portal/app/lib/format.test.ts | 98 - solvway-admin-portal/app/lib/format.ts | 62 - .../lib/fulfilment/trackingWorkbook.test.ts | 122 - .../app/lib/fulfilment/trackingWorkbook.ts | 105 - solvway-admin-portal/app/lib/geoLevels.ts | 34 - .../app/lib/hooks/useSellableCountry.ts | 28 - .../app/lib/hooks/useSplitPoll.test.ts | 97 - .../app/lib/hooks/useSplitPoll.ts | 122 - .../app/lib/hooks/useTabParam.ts | 22 - .../app/lib/hooks/useVisiblePolling.ts | 25 - .../app/lib/i18n/MessagesProvider.test.tsx | 2 +- .../i18n/defaultMessages.countryScope.test.ts | 15 - .../defaultMessages.posMemberCountry.test.ts | 10 - .../app/lib/i18n/defaultMessages.test.ts | 209 +- .../app/lib/i18n/defaultMessages.ts | 3632 +--------------- .../errorReasonInterpolation.sweep.test.ts | 7 +- solvway-admin-portal/app/lib/i18n/t.test.ts | 6 +- .../app/lib/images/shrinkImage.test.ts | 122 - .../app/lib/images/shrinkImage.ts | 59 - .../app/lib/inventory/quantityInput.test.ts | 21 - .../app/lib/inventory/quantityInput.ts | 11 - .../app/lib/inventory/stockInWorkbook.test.ts | 283 -- .../app/lib/inventory/stockInWorkbook.ts | 199 - .../lib/inventory/transferWorkbook.test.ts | 171 - .../app/lib/inventory/transferWorkbook.ts | 147 - .../app/lib/inventory/workbookRows.test.ts | 71 - .../app/lib/inventory/workbookRows.ts | 45 - .../app/lib/inventoryModules.ts | 13 - .../app/lib/kyc/kycExport.test.ts | 168 - solvway-admin-portal/app/lib/kyc/kycExport.ts | 83 - .../app/lib/kyc/resizeImage.test.ts | 71 - .../app/lib/kyc/resizeImage.ts | 45 - solvway-admin-portal/app/lib/lineName.ts | 5 - .../app/lib/loginEvents.i18n.test.ts | 19 - .../app/lib/loginEvents.test.ts | 16 - solvway-admin-portal/app/lib/loginEvents.ts | 10 - .../app/lib/malaysiaPeriod.test.ts | 62 - .../app/lib/malaysiaPeriod.ts | 48 - .../app/lib/memberLabels.test.ts | 32 - solvway-admin-portal/app/lib/memberLabels.ts | 85 - solvway-admin-portal/app/lib/menus.test.ts | 47 - solvway-admin-portal/app/lib/menus.ts | 44 - .../app/lib/messageContent.test.ts | 96 - .../app/lib/messageContent.ts | 54 - .../app/lib/messageImportPreview.test.ts | 25 - .../app/lib/messageImportPreview.ts | 32 - .../app/lib/messagePlaceholders.test.ts | 13 - .../app/lib/messagePlaceholders.ts | 12 - .../app/lib/messages/broadcastTarget.test.ts | 23 - .../app/lib/messages/broadcastTarget.ts | 34 - .../app/lib/noListApplyButtons.test.ts | 2 +- .../lib/onlinePayments/onlinePayments.test.ts | 94 - .../onlinePayments/onlinePaymentsExport.ts | 69 - .../app/lib/paymentTypes.test.ts | 24 - solvway-admin-portal/app/lib/paymentTypes.ts | 37 - .../app/lib/posEventsI18n.test.ts | 56 - .../app/lib/productPage.test.ts | 810 ---- solvway-admin-portal/app/lib/productPage.ts | 481 --- .../app/lib/productPickerLabel.ts | 10 - .../app/lib/promotionStatus.ts | 12 - .../app/lib/protectedModules.test.ts | 28 +- .../app/lib/protectedModules.ts | 30 +- .../app/lib/referenceTables.test.ts | 90 - .../app/lib/referenceTables.ts | 104 - .../app/lib/routeModules.test.ts | 274 +- solvway-admin-portal/app/lib/routeModules.ts | 290 +- .../app/lib/salesI18n.test.ts | 143 - .../app/lib/sameOrigin.test.ts | 2 +- solvway-admin-portal/app/lib/sameOrigin.ts | 2 +- .../security/binaryProxyHeaders.sweep.test.ts | 37 - .../security/noHtmlInjection.sweep.test.ts | 19 +- .../app/lib/server/apiRoute.test.ts | 2 +- .../app/lib/server/binaryProxy.ts | 12 - .../lib/server/directFetchTraversal.test.ts | 41 - .../app/lib/server/forwardGet.ts | 32 - .../app/lib/server/memberPortalUrl.test.ts | 57 - .../app/lib/server/memberPortalUrl.ts | 19 - .../app/lib/server/messagesProxy.ts | 78 - .../app/lib/server/mobileApi.test.ts | 4 +- .../app/lib/server/publicError.test.ts | 2 +- .../app/lib/server/session.hostPrefix.test.ts | 18 +- .../app/lib/server/session.seal.test.ts | 10 +- .../app/lib/server/session.test.ts | 4 +- .../app/lib/server/upstreamQuery.test.ts | 113 - .../app/lib/server/upstreamQuery.ts | 63 - .../app/lib/services/adminBank.ts | 24 - .../app/lib/services/adminCatalog.ts | 42 - .../lib/services/adminCatalogSetup.test.ts | 68 - .../app/lib/services/adminCatalogSetup.ts | 51 - .../app/lib/services/adminCollections.ts | 35 - .../lib/services/adminCompanyAccount.test.ts | 105 - .../app/lib/services/adminCompanyAccount.ts | 45 - .../app/lib/services/adminCounter.ts | 92 - .../adminCounterDeliveryOrders.test.ts | 43 - .../services/adminCounterDeliveryOrders.ts | 48 - .../services/adminDashboard.actions.test.ts | 74 - .../services/adminDashboard.country.test.ts | 19 - .../app/lib/services/adminDashboard.test.ts | 184 - .../app/lib/services/adminDashboard.ts | 230 -- .../lib/services/adminDeliveryOrders.test.ts | 132 - .../app/lib/services/adminDeliveryOrders.ts | 147 - .../lib/services/adminEventSummary.test.ts | 24 - .../app/lib/services/adminEventSummary.ts | 23 - .../app/lib/services/adminEvents.test.ts | 72 - .../app/lib/services/adminEvents.ts | 36 - .../app/lib/services/adminForms.ts | 43 - .../app/lib/services/adminFulfilment.test.ts | 69 - .../app/lib/services/adminFulfilment.ts | 83 - .../app/lib/services/adminFulfilmentEvents.ts | 14 - .../app/lib/services/adminFulfilmentHealth.ts | 9 - .../app/lib/services/adminGiftCards.ts | 69 - .../app/lib/services/adminKyc.test.ts | 128 - .../app/lib/services/adminKyc.ts | 85 - .../app/lib/services/adminLocations.test.ts | 34 - .../app/lib/services/adminLocations.ts | 21 - .../app/lib/services/adminMenus.ts | 12 - .../services/adminMessages.broadcasts.test.ts | 61 - .../app/lib/services/adminMessages.test.ts | 130 - .../app/lib/services/adminMessages.ts | 164 - .../app/lib/services/adminModules.ts | 33 - .../app/lib/services/adminOnlinePayments.ts | 53 - .../app/lib/services/adminPages.ts | 30 - .../app/lib/services/adminPaymentMethods.ts | 26 - .../adminPickupDeliveryOrders.test.ts | 71 - .../lib/services/adminPickupDeliveryOrders.ts | 69 - .../lib/services/adminPos.products.test.ts | 20 - .../app/lib/services/adminPos.ts | 96 - .../app/lib/services/adminProduct.test.ts | 102 - .../app/lib/services/adminProduct.ts | 96 - .../app/lib/services/adminProductReviews.ts | 34 - .../app/lib/services/adminPromotions.test.ts | 71 - .../app/lib/services/adminPromotions.ts | 114 - .../app/lib/services/adminQianyiOrders.ts | 19 - .../app/lib/services/adminReference.ts | 30 - .../app/lib/services/adminRefunds.test.ts | 97 - .../app/lib/services/adminRefunds.ts | 93 - .../app/lib/services/adminShipping.test.ts | 36 - .../app/lib/services/adminShipping.ts | 58 - .../app/lib/services/adminStock.test.ts | 26 - .../app/lib/services/adminStock.ts | 101 - .../app/lib/services/adminStockCounts.test.ts | 51 - .../app/lib/services/adminStockCounts.ts | 40 - .../app/lib/services/adminTopups.test.ts | 30 - .../app/lib/services/adminTopups.ts | 48 - .../app/lib/services/adminWarehouses.test.ts | 54 - .../app/lib/services/adminWarehouses.ts | 61 - .../app/lib/services/adminWarranty.test.ts | 76 - .../app/lib/services/adminWarranty.ts | 52 - .../app/lib/services/adminWebOrders.test.ts | 188 - .../app/lib/services/adminWebOrders.ts | 224 - .../adminWebOrdersStalePending.test.ts | 31 - .../app/lib/services/adminWithdrawals.test.ts | 140 - .../app/lib/services/adminWithdrawals.ts | 57 - solvway-admin-portal/app/lib/services/api.ts | 31 - .../app/lib/services/auditLog.test.ts | 78 - .../app/lib/services/auditLog.ts | 82 - .../app/lib/services/banners.test.ts | 13 - .../app/lib/services/banners.ts | 73 - .../app/lib/services/bulletins.test.ts | 129 - .../app/lib/services/bulletins.ts | 94 - .../app/lib/services/currency.test.ts | 83 - .../app/lib/services/currency.ts | 78 - .../lib/services/dashboardLabels.i18n.test.ts | 50 - .../app/lib/services/emailTemplates.test.ts | 174 - .../app/lib/services/emailTemplates.ts | 180 - .../app/lib/services/listSort.sorting.test.ts | 44 - .../app/lib/services/locales.test.ts | 42 - .../app/lib/services/locales.ts | 25 - .../app/lib/services/loginSecurity.test.ts | 170 - .../app/lib/services/loginSecurity.ts | 123 - .../app/lib/services/members.test.ts | 176 - .../app/lib/services/members.ts | 192 - .../lib/services/messageAreas.i18n.test.ts | 22 - .../app/lib/services/messages.test.ts | 191 - .../app/lib/services/messages.ts | 115 - .../app/lib/services/network.test.ts | 73 - .../app/lib/services/network.ts | 50 - .../app/lib/services/notifications.test.ts | 106 - .../app/lib/services/notifications.ts | 73 - .../app/lib/services/onlineUsers.ts | 58 - .../app/lib/services/period.ts | 19 - .../app/lib/services/posGiftCards.test.ts | 29 - .../app/lib/services/posGiftCards.ts | 25 - .../services/remainingSort.sorting.test.ts | 44 - .../lib/services/retiredStockistArea.test.ts | 17 - .../app/lib/services/sellableCountries.ts | 7 - .../app/lib/services/types.ts | 6 - .../app/lib/services/wallet.test.ts | 118 - .../app/lib/services/wallet.ts | 110 - .../app/lib/sessionCookieName.ts | 4 +- .../app/lib/sessionPolicyRules.ts | 24 - .../app/lib/shipping/rateCardWorkbook.test.ts | 106 - .../app/lib/shipping/rateCardWorkbook.ts | 152 - .../app/lib/shipping/rateRows.test.ts | 137 - .../app/lib/shipping/rateRows.ts | 96 - .../app/lib/sidebarLayout.test.ts | 234 -- solvway-admin-portal/app/lib/sidebarLayout.ts | 47 - solvway-admin-portal/app/lib/siteLink.ts | 9 - .../app/lib/stockCountStatus.ts | 17 - .../app/lib/stockI18n.test.ts | 84 - solvway-admin-portal/app/lib/storefront.tsx | 19 - solvway-admin-portal/app/lib/types.ts | 2485 +---------- .../app/lib/use-pos-client-key.test.ts | 77 - .../app/lib/use-pos-client-key.ts | 54 - .../app/lib/useAclSidebar.test.tsx | 13 - solvway-admin-portal/app/lib/useAclSidebar.ts | 5 +- .../app/lib/useListingExport.tsx | 52 - .../app/lib/useScanKeyCapture.ts | 30 - .../app/lib/walletAmounts.test.ts | 138 - solvway-admin-portal/app/lib/walletAmounts.ts | 136 - solvway-admin-portal/app/lib/walletLabels.ts | 12 - .../app/lib/walletRequestStatus.test.ts | 17 - .../app/lib/walletRequestStatus.ts | 20 - .../app/lib/walletTrxnType.test.ts | 145 - .../app/lib/walletTrxnType.ts | 135 - solvway-admin-portal/app/lib/xlsx.test.ts | 159 - solvway-admin-portal/app/lib/xlsx.ts | 87 - .../app/listing-page-size.test.ts | 2 +- .../app/locales/page.sorting.test.tsx | 90 - .../app/locales/page.test.tsx | 298 -- solvway-admin-portal/app/locales/page.tsx | 362 -- .../app/locations/page.test.tsx | 187 - solvway-admin-portal/app/locations/page.tsx | 219 - .../page.sessionPolicy.test.tsx | 114 - .../app/login-security/page.sorting.test.tsx | 57 - .../app/login-security/page.test.tsx | 305 -- .../app/login-security/page.tsx | 516 --- solvway-admin-portal/app/login/page.test.tsx | 2 +- solvway-admin-portal/app/login/page.tsx | 12 +- .../broadcast/page.hardening.test.tsx | 53 - .../member-messages/broadcast/page.test.tsx | 145 - .../app/member-messages/broadcast/page.tsx | 228 -- .../[broadcastUuid]/page.sorting.test.tsx | 54 - .../broadcasts/[broadcastUuid]/page.test.tsx | 123 - .../broadcasts/[broadcastUuid]/page.tsx | 165 - .../member-messages/page.broadcasts.test.tsx | 163 - .../member-messages/page.deeplink.test.tsx | 62 - .../member-messages/page.hardening.test.tsx | 87 - .../app/member-messages/page.member.test.tsx | 71 - .../app/member-messages/page.open.test.tsx | 35 - .../app/member-messages/page.test.tsx | 262 -- .../app/member-messages/page.tsx | 385 -- .../[memberCode]/ChangeHistory.test.tsx | 347 -- .../members/[memberCode]/ChangeHistory.tsx | 247 -- .../members/[memberCode]/edit/page.test.tsx | 167 - .../app/members/[memberCode]/edit/page.tsx | 480 --- .../[memberCode]/page.sorting.test.tsx | 215 - .../app/members/[memberCode]/page.test.tsx | 405 -- .../app/members/[memberCode]/page.tsx | 549 --- .../members/knowYourCustomer/page.test.tsx | 220 - .../app/members/knowYourCustomer/page.tsx | 321 -- .../app/members/page.phone-sort.test.tsx | 33 - .../app/members/page.test.tsx | 427 -- solvway-admin-portal/app/members/page.tsx | 344 -- .../app/members/register/page.test.tsx | 129 - .../app/members/register/page.tsx | 182 - solvway-admin-portal/app/menus/page.test.tsx | 77 - solvway-admin-portal/app/menus/page.tsx | 49 - .../messages/ImportMessagesDialog.test.tsx | 128 - .../app/messages/ImportMessagesDialog.tsx | 214 - .../app/messages/MessageEditSheet.test.tsx | 181 - .../app/messages/MessageEditSheet.tsx | 208 - .../app/messages/page.sorting.test.tsx | 41 - .../app/messages/page.test.tsx | 559 --- solvway-admin-portal/app/messages/page.tsx | 302 -- .../app/modules/filterModuleNodes.test.ts | 39 - .../app/modules/filterModuleNodes.ts | 19 - .../app/modules/page.test.tsx | 714 ---- solvway-admin-portal/app/modules/page.tsx | 730 ---- .../app/network/NetworkTabs.test.tsx | 41 - .../app/network/NetworkTabs.tsx | 58 - .../network/PlacementHistory.sorting.test.tsx | 211 - .../company-accounts/page.sorting.test.tsx | 81 - .../network/company-accounts/page.test.tsx | 225 - .../app/network/company-accounts/page.tsx | 609 --- .../app/network/page.test.tsx | 460 --- solvway-admin-portal/app/network/page.tsx | 395 -- .../app/notifications/page.test.tsx | 198 - .../app/notifications/page.tsx | 404 -- .../app/online-payments/page.test.tsx | 339 -- .../app/online-payments/page.tsx | 371 -- .../app/online-users/page.test.tsx | 197 - .../app/online-users/page.tsx | 318 -- .../refunds/RefundDrawer.giftCard.test.tsx | 183 - .../refunds/RefundDrawer.photos.test.tsx | 88 - .../app/orders/refunds/RefundDrawer.test.tsx | 191 - .../app/orders/refunds/RefundDrawer.tsx | 330 -- .../app/orders/refunds/page.test.tsx | 247 -- .../app/orders/refunds/page.tsx | 192 - .../app/orders/refunds/refundLabels.ts | 70 - .../app/orders/refunds/refundSource.test.tsx | 122 - .../WarrantyClaimDrawer.review.test.tsx | 66 - .../WarrantyClaimDrawer.test.tsx | 172 - .../warranty-claims/WarrantyClaimDrawer.tsx | 233 -- .../warranty-claims/page.export.test.tsx | 100 - .../warranty-claims/page.sorting.test.tsx | 56 - .../app/orders/warranty-claims/page.test.tsx | 120 - .../app/orders/warranty-claims/page.tsx | 210 - .../orders/warranty-claims/warrantyLabels.ts | 13 - .../web/[uuid]/OrderParcels.sorting.test.tsx | 73 - .../orders/web/[uuid]/OrderParcels.test.tsx | 57 - .../app/orders/web/[uuid]/OrderParcels.tsx | 90 - .../web/[uuid]/RaiseRefundAction.test.tsx | 240 -- .../orders/web/[uuid]/RaiseRefundAction.tsx | 261 -- .../orders/web/[uuid]/page.sorting.test.tsx | 108 - .../app/orders/web/[uuid]/page.test.tsx | 247 -- .../app/orders/web/[uuid]/page.tsx | 299 -- .../orders/web/[uuid]/voidPending.test.tsx | 144 - .../app/orders/web/eventSellerFilter.test.tsx | 90 - .../app/orders/web/page.export.test.tsx | 115 - .../app/orders/web/page.test.tsx | 453 -- solvway-admin-portal/app/orders/web/page.tsx | 337 -- .../app/orders/web/staleFilter.test.tsx | 90 - .../app/page.actions.test.tsx | 145 - .../app/page.country.test.tsx | 81 - .../app/page.dateAxis.guard.test.ts | 23 - .../app/page.drilldown.test.tsx | 207 - .../app/page.emptyMonth.test.tsx | 129 - solvway-admin-portal/app/page.test.tsx | 559 +-- solvway-admin-portal/app/page.tsx | 638 +-- solvway-admin-portal/app/pages/[id]/page.tsx | 22 - solvway-admin-portal/app/pages/new/page.tsx | 20 - .../app/pages/page.sorting.test.tsx | 84 - solvway-admin-portal/app/pages/page.test.tsx | 112 - solvway-admin-portal/app/pages/page.tsx | 142 - .../app/payment-methods/page.sorting.test.tsx | 102 - .../app/payment-methods/page.test.tsx | 109 - .../app/payment-methods/page.tsx | 329 -- .../_components/GiftCardCodesField.test.tsx | 94 - .../pos/_components/GiftCardCodesField.tsx | 120 - .../_components/SellGiftCardDialog.test.tsx | 189 - .../pos/_components/SellGiftCardDialog.tsx | 289 -- .../pos/_components/SplitTenderPanel.test.tsx | 666 --- .../app/pos/_components/SplitTenderPanel.tsx | 519 --- .../pos/_components/WalletAmountLeg.test.tsx | 167 - .../app/pos/_components/WalletAmountLeg.tsx | 105 - .../app/pos/_components/WalletLegs.tsx | 42 - .../app/pos/components/CartPanel.test.tsx | 116 - .../app/pos/components/CartPanel.tsx | 106 - .../app/pos/components/CustomerCard.test.tsx | 63 - .../app/pos/components/CustomerCard.tsx | 69 - .../pos/components/CustomerDialog.test.tsx | 102 - .../app/pos/components/CustomerDialog.tsx | 142 - .../pos/components/FulfilmentPicker.test.tsx | 122 - .../app/pos/components/FulfilmentPicker.tsx | 140 - .../app/pos/components/PaymentDialog.test.tsx | 144 - .../app/pos/components/PaymentDialog.tsx | 204 - .../app/pos/components/PosPromoPanel.test.tsx | 223 - .../app/pos/components/PosPromoPanel.tsx | 232 -- .../pos/components/ProductGrid.scan.test.tsx | 342 -- .../app/pos/components/ProductGrid.test.tsx | 220 - .../app/pos/components/ProductGrid.tsx | 314 -- .../components/ProductGrid.variants.test.tsx | 225 - .../app/pos/components/ReceiptBuyer.test.tsx | 81 - .../app/pos/components/ReceiptBuyer.tsx | 40 - .../app/pos/components/ReceiptDialog.test.tsx | 53 - .../app/pos/components/ReceiptDialog.tsx | 57 - .../app/pos/components/StepBar.test.tsx | 41 - .../app/pos/components/StepBar.tsx | 52 - .../app/pos/counter/page.test.tsx | 1180 ------ solvway-admin-portal/app/pos/counter/page.tsx | 1321 ------ .../app/pos/currency.test.tsx | 67 - solvway-admin-portal/app/pos/currency.tsx | 39 - .../app/pos/fulfilment.test.ts | 363 -- solvway-admin-portal/app/pos/fulfilment.ts | 235 -- solvway-admin-portal/app/pos/page.test.tsx | 871 ---- solvway-admin-portal/app/pos/page.tsx | 1392 ------- solvway-admin-portal/app/pos/shared.ts | 14 - .../app/pos/usePosQuote.test.tsx | 276 -- solvway-admin-portal/app/pos/usePosQuote.ts | 88 - .../app/product-reviews/ReviewDrawer.test.tsx | 107 - .../app/product-reviews/ReviewDrawer.tsx | 131 - .../ReviewDrawerRegisteredName.test.tsx | 45 - .../app/product-reviews/page.test.tsx | 207 - .../app/product-reviews/page.tsx | 142 - .../app/products/[id]/page.test.tsx | 18 - .../app/products/[id]/page.tsx | 17 - .../app/products/import/page.test.tsx | 175 - .../app/products/import/page.tsx | 239 -- .../products/import/pageCatalogue.test.tsx | 99 - .../app/products/new/page.test.tsx | 31 - .../app/products/new/page.tsx | 18 - .../app/products/page.export.test.tsx | 78 - .../app/products/page.tabs.test.tsx | 37 - .../app/products/page.test.tsx | 375 -- solvway-admin-portal/app/products/page.tsx | 287 -- .../promotions/CampaignForm.country.test.tsx | 102 - .../app/promotions/CampaignForm.test.tsx | 1211 ------ .../app/promotions/CampaignForm.tsx | 748 ---- .../promotions/CampaignsPanel.export.test.tsx | 101 - .../app/promotions/CampaignsPanel.test.tsx | 380 -- .../app/promotions/CampaignsPanel.tsx | 390 -- .../app/promotions/ProductPicker.tsx | 143 - .../promotions/ProductSelectDialog.test.tsx | 91 - .../app/promotions/ProductSelectDialog.tsx | 124 - .../app/promotions/RedemptionsPanel.test.tsx | 336 -- .../app/promotions/RedemptionsPanel.tsx | 237 -- .../promotions/VouchersPanel.codes.test.tsx | 381 -- .../app/promotions/VouchersPanel.test.tsx | 458 --- .../app/promotions/VouchersPanel.tsx | 582 --- .../app/promotions/campaignChecks.test.ts | 322 -- .../app/promotions/campaignChecks.ts | 205 - .../app/promotions/campaignSummary.test.ts | 150 - .../app/promotions/campaignSummary.ts | 188 - .../app/promotions/fixedPrice.test.tsx | 140 - .../app/promotions/page.tab.test.tsx | 46 - .../app/promotions/page.test.tsx | 59 - solvway-admin-portal/app/promotions/page.tsx | 35 - .../app/rank-referral/page.export.test.tsx | 97 - .../app/rank-referral/page.test.tsx | 465 --- .../app/rank-referral/page.tsx | 676 --- .../app/reference/BankPanel.sorting.test.tsx | 75 - .../app/reference/BankPanel.test.tsx | 296 -- .../app/reference/BankPanel.tsx | 411 -- .../app/reference/page.sorting.test.tsx | 108 - .../app/reference/page.test.tsx | 484 --- solvway-admin-portal/app/reference/page.tsx | 424 -- .../app/reports/page.country.test.tsx | 63 - .../app/reports/page.countryPaging.test.tsx | 75 - .../app/reports/page.items.test.tsx | 221 - .../app/reports/page.itemsCountry.test.tsx | 70 - .../app/reports/page.test.tsx | 486 --- solvway-admin-portal/app/reports/page.tsx | 579 --- .../app/roles/[id]/access/page.test.tsx | 12 +- .../app/roles/page.sorting.test.tsx | 2 +- .../app/shipping/page.test.tsx | 33 - solvway-admin-portal/app/shipping/page.tsx | 42 - .../app/users/[id]/page.test.tsx | 6 - .../app/users/new/page.test.tsx | 8 - .../app/wallet/WalletAdjustDialog.test.tsx | 252 -- .../app/wallet/WalletAdjustDialog.tsx | 179 - .../app/wallet/WalletTabs.test.tsx | 78 - .../app/wallet/WalletTabs.tsx | 57 - .../app/wallet/[memberCode]/page.test.tsx | 156 - .../app/wallet/[memberCode]/page.tsx | 204 - .../app/wallet/page.export.test.tsx | 93 - solvway-admin-portal/app/wallet/page.test.tsx | 411 -- solvway-admin-portal/app/wallet/page.tsx | 322 -- .../app/wallet/topups/page.reverse.test.tsx | 168 - .../app/wallet/topups/page.test.tsx | 236 -- .../app/wallet/topups/page.tsx | 311 -- .../wallet/withdrawal-settings/page.test.tsx | 138 - .../app/wallet/withdrawal-settings/page.tsx | 355 -- .../wallet/withdrawals/page.export.test.tsx | 99 - .../app/wallet/withdrawals/page.test.tsx | 400 -- .../app/wallet/withdrawals/page.tsx | 405 -- .../app/warehouses/page.test.tsx | 35 - solvway-admin-portal/app/warehouses/page.tsx | 99 - .../docs/design/DASHBOARD-STANDARD.md | 448 -- solvway-admin-portal/middleware.csp.test.ts | 4 +- .../middleware.hostPrefix.test.ts | 6 +- solvway-admin-portal/middleware.seal.test.ts | 2 +- .../middleware.timeouts.test.ts | 2 +- solvway-admin-portal/package-lock.json | 3637 +---------------- solvway-admin-portal/package.json | 26 +- .../public/brand/babyboo-logo-stacked.webp | Bin 25982 -> 0 bytes .../scripts/check-contrast.py | 86 - solvway-admin-portal/test/pickDate.ts | 32 - solvway-admin-portal/test/pickTime.ts | 20 - solvway-admin-portal/test/readXlsx.ts | 10 - solvway-admin-portal/vendor/xlsx-0.20.3.tgz | Bin 2409319 -> 0 bytes 1304 files changed, 216 insertions(+), 162492 deletions(-) delete mode 100644 solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/company-accounts/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/company-accounts/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/dashboard/event/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/dashboard/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/dashboard/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/event-summary/events/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/event-summary/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/counts/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/export/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/export/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/submit/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/kyc/upload/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-corrections/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-corrections/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/images/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/start/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/member-messages/unread-count/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/change-history/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/change-history/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/change-sponsor/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/change-sponsor/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/correct-rank/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/correct-rank/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/edit-initialize/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/edit-initialize/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/placement-history/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/status-history/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/[memberCode]/status-history/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/members/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/network/[memberCode]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/network/[memberCode]/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/network/[memberCode]/upline/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/reports/rewards/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/reports/rewards/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/reports/sales-items/route.country.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/reports/sales-items/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/reports/sales-items/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/reports/sales/route.country.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/reports/sales/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/reports/sales/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/topup/list/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/topup/list/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/topup/list/route.view.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/topup/removedRoutes.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/topup/reverse/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/topup/reverse/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/wallet/[memberCode]/balances/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/wallet/[memberCode]/balances/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/wallet/[memberCode]/ledger/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/wallet/[memberCode]/ledger/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/wallet/adjust/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/wallet/adjust/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/wallet/ledger/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/wallet/ledger/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/withdrawal/approve/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/withdrawal/approve/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/withdrawal/config/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/withdrawal/config/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/withdrawal/list/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/withdrawal/list/route.ts delete mode 100644 solvway-admin-portal/app/api/admin/withdrawal/reject/route.test.ts delete mode 100644 solvway-admin-portal/app/api/admin/withdrawal/reject/route.ts delete mode 100644 solvway-admin-portal/app/api/audit-log/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/audit-log/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/audit-log/route.test.ts delete mode 100644 solvway-admin-portal/app/api/audit-log/route.ts delete mode 100644 solvway-admin-portal/app/api/auth/session/route.countryScope.test.ts delete mode 100644 solvway-admin-portal/app/api/banner-settings/[zone]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/banner-settings/[zone]/route.ts delete mode 100644 solvway-admin-portal/app/api/banners/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/banners/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/banners/image/route.test.ts delete mode 100644 solvway-admin-portal/app/api/banners/image/route.ts delete mode 100644 solvway-admin-portal/app/api/banners/route.test.ts delete mode 100644 solvway-admin-portal/app/api/banners/route.ts delete mode 100644 solvway-admin-portal/app/api/bulletins/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/bulletins/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/bulletins/image/route.test.ts delete mode 100644 solvway-admin-portal/app/api/bulletins/image/route.ts delete mode 100644 solvway-admin-portal/app/api/bulletins/route.test.ts delete mode 100644 solvway-admin-portal/app/api/bulletins/route.ts delete mode 100644 solvway-admin-portal/app/api/catalog/[list]/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/catalog/[list]/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/catalog/[list]/image/route.test.ts delete mode 100644 solvway-admin-portal/app/api/catalog/[list]/image/route.ts delete mode 100644 solvway-admin-portal/app/api/catalog/[list]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/catalog/[list]/route.ts delete mode 100644 solvway-admin-portal/app/api/collections/[id]/delete/route.ts delete mode 100644 solvway-admin-portal/app/api/collections/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/collections/image/route.ts delete mode 100644 solvway-admin-portal/app/api/collections/preview/route.ts delete mode 100644 solvway-admin-portal/app/api/collections/route.ts delete mode 100644 solvway-admin-portal/app/api/collections/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/gift-card/sale/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/payment-methods/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/payment-methods/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/products/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/products/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/quote/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/quote/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/sale/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/sale/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/split/cancel/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/split/cancel/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/split/sale/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/split/sale/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/split/status/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/split/status/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/wallet/[memberCode]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/wallet/[memberCode]/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/wallet/preview/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/wallet/preview/route.ts delete mode 100644 solvway-admin-portal/app/api/counter/wallet/sale/route.test.ts delete mode 100644 solvway-admin-portal/app/api/counter/wallet/sale/route.ts delete mode 100644 solvway-admin-portal/app/api/countries/route.test.ts delete mode 100644 solvway-admin-portal/app/api/countries/route.ts delete mode 100644 solvway-admin-portal/app/api/currency/history/[countryCode]/[type]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/currency/history/[countryCode]/[type]/route.ts delete mode 100644 solvway-admin-portal/app/api/currency/route.test.ts delete mode 100644 solvway-admin-portal/app/api/currency/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/mark-delivered/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/mark-delivered/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/mark-shipped/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/mark-shipped/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/qianyi/retry/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/qianyi/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/qianyi/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/counter/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/counter/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/counter/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/counter/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/pickup/[uuid]/mark-collected/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/pickup/[uuid]/mark-collected/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/pickup/[uuid]/mark-ready/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/pickup/[uuid]/mark-ready/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/pickup/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/pickup/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/pickup/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/pickup/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/to-issue/[orderUuid]/issue/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/to-issue/[orderUuid]/issue/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/to-issue/[orderUuid]/plan/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/to-issue/[orderUuid]/plan/route.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/to-issue/route.test.ts delete mode 100644 solvway-admin-portal/app/api/delivery-orders/to-issue/route.ts delete mode 100644 solvway-admin-portal/app/api/email-logs/[id]/resend/route.test.ts delete mode 100644 solvway-admin-portal/app/api/email-logs/[id]/resend/route.ts delete mode 100644 solvway-admin-portal/app/api/email-logs/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/email-logs/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/email-logs/route.test.ts delete mode 100644 solvway-admin-portal/app/api/email-logs/route.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/[id]/status/route.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/attachments/route.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/by-name/[name]/route.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/preview/route.test.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/preview/route.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/route.test.ts delete mode 100644 solvway-admin-portal/app/api/email-templates/route.ts delete mode 100644 solvway-admin-portal/app/api/events/[id]/close-out/[action]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/events/[id]/close-out/[action]/route.ts delete mode 100644 solvway-admin-portal/app/api/events/[id]/close-out/route.test.ts delete mode 100644 solvway-admin-portal/app/api/events/[id]/close-out/route.ts delete mode 100644 solvway-admin-portal/app/api/events/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/events/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/events/pickup-outlets/route.test.ts delete mode 100644 solvway-admin-portal/app/api/events/pickup-outlets/route.ts delete mode 100644 solvway-admin-portal/app/api/events/route.test.ts delete mode 100644 solvway-admin-portal/app/api/events/route.ts delete mode 100644 solvway-admin-portal/app/api/forms/[id]/delete/route.ts delete mode 100644 solvway-admin-portal/app/api/forms/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/forms/[id]/submissions/route.ts delete mode 100644 solvway-admin-portal/app/api/forms/route.ts delete mode 100644 solvway-admin-portal/app/api/forms/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/forms/submissions/[sid]/delete/route.ts delete mode 100644 solvway-admin-portal/app/api/forms/submissions/[sid]/route.ts delete mode 100644 solvway-admin-portal/app/api/fulfilment-events/note/route.ts delete mode 100644 solvway-admin-portal/app/api/fulfilment-events/route.test.ts delete mode 100644 solvway-admin-portal/app/api/fulfilment-events/route.ts delete mode 100644 solvway-admin-portal/app/api/fulfilment-health/route.test.ts delete mode 100644 solvway-admin-portal/app/api/fulfilment-health/route.ts delete mode 100644 solvway-admin-portal/app/api/fulfilment/[...path]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/fulfilment/[...path]/route.ts delete mode 100644 solvway-admin-portal/app/api/geo-locations/route.test.ts delete mode 100644 solvway-admin-portal/app/api/geo-locations/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/[uuid]/deactivate/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/[uuid]/extend/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/[uuid]/resend-email/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/amounts/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/amounts/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/issue/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/route.ts delete mode 100644 solvway-admin-portal/app/api/gift-cards/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/health/route.test.ts delete mode 100644 solvway-admin-portal/app/api/health/route.ts delete mode 100644 solvway-admin-portal/app/api/listSort.sorting.test.ts delete mode 100644 solvway-admin-portal/app/api/locales/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/locales/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/locales/route.test.ts delete mode 100644 solvway-admin-portal/app/api/locales/route.ts delete mode 100644 solvway-admin-portal/app/api/locations/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/locations/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/locations/invoice-header/route.test.ts delete mode 100644 solvway-admin-portal/app/api/locations/invoice-header/route.ts delete mode 100644 solvway-admin-portal/app/api/locations/route.test.ts delete mode 100644 solvway-admin-portal/app/api/locations/route.ts delete mode 100644 solvway-admin-portal/app/api/login-security/audit/route.test.ts delete mode 100644 solvway-admin-portal/app/api/login-security/audit/route.ts delete mode 100644 solvway-admin-portal/app/api/login-security/locked/[username]/unlock/route.test.ts delete mode 100644 solvway-admin-portal/app/api/login-security/locked/[username]/unlock/route.ts delete mode 100644 solvway-admin-portal/app/api/login-security/locked/route.test.ts delete mode 100644 solvway-admin-portal/app/api/login-security/locked/route.ts delete mode 100644 solvway-admin-portal/app/api/login-security/lockout-config/route.test.ts delete mode 100644 solvway-admin-portal/app/api/login-security/lockout-config/route.ts delete mode 100644 solvway-admin-portal/app/api/login-security/session-policy/route.members.test.ts delete mode 100644 solvway-admin-portal/app/api/login-security/session-policy/route.rangeCode.test.ts delete mode 100644 solvway-admin-portal/app/api/login-security/session-policy/route.test.ts delete mode 100644 solvway-admin-portal/app/api/login-security/session-policy/route.ts delete mode 100644 solvway-admin-portal/app/api/menus/[handle]/route.ts delete mode 100644 solvway-admin-portal/app/api/menus/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/messages/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/messages/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/messages/export/route.test.ts delete mode 100644 solvway-admin-portal/app/api/messages/export/route.ts delete mode 100644 solvway-admin-portal/app/api/messages/import/route.test.ts delete mode 100644 solvway-admin-portal/app/api/messages/import/route.ts delete mode 100644 solvway-admin-portal/app/api/messages/route.test.ts delete mode 100644 solvway-admin-portal/app/api/messages/route.ts delete mode 100644 solvway-admin-portal/app/api/modules/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/modules/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/modules/route.test.ts delete mode 100644 solvway-admin-portal/app/api/modules/route.ts delete mode 100644 solvway-admin-portal/app/api/notifications/[id]/read/route.test.ts delete mode 100644 solvway-admin-portal/app/api/notifications/[id]/read/route.ts delete mode 100644 solvway-admin-portal/app/api/notifications/read-all/route.test.ts delete mode 100644 solvway-admin-portal/app/api/notifications/read-all/route.ts delete mode 100644 solvway-admin-portal/app/api/notifications/route.test.ts delete mode 100644 solvway-admin-portal/app/api/notifications/route.ts delete mode 100644 solvway-admin-portal/app/api/notifications/unread-count/route.test.ts delete mode 100644 solvway-admin-portal/app/api/notifications/unread-count/route.ts delete mode 100644 solvway-admin-portal/app/api/online-payments/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/online-payments/route.ts delete mode 100644 solvway-admin-portal/app/api/online-payments/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/online-users/route.test.ts delete mode 100644 solvway-admin-portal/app/api/online-users/route.ts delete mode 100644 solvway-admin-portal/app/api/online-users/sign-out/route.test.ts delete mode 100644 solvway-admin-portal/app/api/online-users/sign-out/route.ts delete mode 100644 solvway-admin-portal/app/api/pages/[id]/delete/route.ts delete mode 100644 solvway-admin-portal/app/api/pages/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/pages/image/route.ts delete mode 100644 solvway-admin-portal/app/api/pages/route.ts delete mode 100644 solvway-admin-portal/app/api/pages/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/payment-methods/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/payment-methods/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/events/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/gift-card/amounts/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/gift-card/check/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/gift-card/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/gift-card/sale/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/payment-methods/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/payment-methods/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/pickup-outlets/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/pickup-outlets/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/products/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/products/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/quote/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/quote/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/sale/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/sale/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/split/cancel/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/split/cancel/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/split/sale/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/split/sale/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/split/status/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/split/status/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/wallet/[memberCode]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/wallet/[memberCode]/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/wallet/preview/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/wallet/preview/route.ts delete mode 100644 solvway-admin-portal/app/api/pos/wallet/sale/route.test.ts delete mode 100644 solvway-admin-portal/app/api/pos/wallet/sale/route.ts delete mode 100644 solvway-admin-portal/app/api/product-reviews/[refno]/images/[index]/route.ts delete mode 100644 solvway-admin-portal/app/api/product-reviews/[refno]/reply/route.ts delete mode 100644 solvway-admin-portal/app/api/product-reviews/[refno]/route.ts delete mode 100644 solvway-admin-portal/app/api/product-reviews/[refno]/status/route.ts delete mode 100644 solvway-admin-portal/app/api/product-reviews/route.ts delete mode 100644 solvway-admin-portal/app/api/product-reviews/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/products/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/products/filters.ts delete mode 100644 solvway-admin-portal/app/api/products/image/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/image/route.ts delete mode 100644 solvway-admin-portal/app/api/products/import/commit/route.ts delete mode 100644 solvway-admin-portal/app/api/products/import/export/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/import/export/route.ts delete mode 100644 solvway-admin-portal/app/api/products/import/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/import/validate/route.ts delete mode 100644 solvway-admin-portal/app/api/products/options/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/options/route.ts delete mode 100644 solvway-admin-portal/app/api/products/qianyi-skus/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/qianyi-skus/route.ts delete mode 100644 solvway-admin-portal/app/api/products/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/route.ts delete mode 100644 solvway-admin-portal/app/api/products/sku-variation-options/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/sku-variation-options/route.ts delete mode 100644 solvway-admin-portal/app/api/products/sku-variations-by-code/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/sku-variations-by-code/route.ts delete mode 100644 solvway-admin-portal/app/api/products/skus/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/skus/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/products/skus/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/skus/route.ts delete mode 100644 solvway-admin-portal/app/api/products/tags/route.test.ts delete mode 100644 solvway-admin-portal/app/api/products/tags/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/campaigns/[uuid]/duplicate/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/campaigns/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/campaigns/[uuid]/routes.replaced.test.ts delete mode 100644 solvway-admin-portal/app/api/promotions/campaigns/[uuid]/status/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/campaigns/[uuid]/voucher-batches/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/campaigns/[uuid]/vouchers/generate/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/campaigns/[uuid]/vouchers/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/campaigns/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/paging.ts delete mode 100644 solvway-admin-portal/app/api/promotions/redemptions/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/routes.test.ts delete mode 100644 solvway-admin-portal/app/api/promotions/voucherRoutes.test.ts delete mode 100644 solvway-admin-portal/app/api/promotions/vouchers/[voucherUuid]/resend-email/route.ts delete mode 100644 solvway-admin-portal/app/api/promotions/vouchers/[voucherUuid]/revoke/route.ts delete mode 100644 solvway-admin-portal/app/api/reference/[table]/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/reference/[table]/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/reference/[table]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/reference/[table]/route.ts delete mode 100644 solvway-admin-portal/app/api/reference/bank/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/reference/bank/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/reference/bank/countries/route.test.ts delete mode 100644 solvway-admin-portal/app/api/reference/bank/countries/route.ts delete mode 100644 solvway-admin-portal/app/api/reference/bank/route.test.ts delete mode 100644 solvway-admin-portal/app/api/reference/bank/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/approve/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/approve/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/photos/[index]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/photos/[index]/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/reject/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/reject/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/retry-email/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/retry-email/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/cancelShipment/[doUuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/cancelShipment/[doUuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/eligibility/[orderUuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/eligibility/[orderUuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/raise/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/raise/route.ts delete mode 100644 solvway-admin-portal/app/api/refunds/route.test.ts delete mode 100644 solvway-admin-portal/app/api/refunds/route.ts delete mode 100644 solvway-admin-portal/app/api/remainingSort.sorting.test.ts delete mode 100644 solvway-admin-portal/app/api/shipping/[...path]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/shipping/[...path]/route.ts delete mode 100644 solvway-admin-portal/app/api/stock-counts/[id]/[action]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock-counts/[id]/[action]/route.ts delete mode 100644 solvway-admin-portal/app/api/stock-counts/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock-counts/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/stock-counts/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock-counts/route.ts delete mode 100644 solvway-admin-portal/app/api/stock/adjustment/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock/adjustment/route.ts delete mode 100644 solvway-admin-portal/app/api/stock/in/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock/in/route.ts delete mode 100644 solvway-admin-portal/app/api/stock/movements/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock/movements/route.ts delete mode 100644 solvway-admin-portal/app/api/stock/on-hand/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock/on-hand/route.ts delete mode 100644 solvway-admin-portal/app/api/stock/product-variations/[productId]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock/product-variations/[productId]/route.ts delete mode 100644 solvway-admin-portal/app/api/stock/sku-catalog/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock/sku-catalog/route.ts delete mode 100644 solvway-admin-portal/app/api/stock/transfer/route.test.ts delete mode 100644 solvway-admin-portal/app/api/stock/transfer/route.ts delete mode 100644 solvway-admin-portal/app/api/warehouses/[id]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/warehouses/[id]/route.ts delete mode 100644 solvway-admin-portal/app/api/warehouses/branch-store/route.test.ts delete mode 100644 solvway-admin-portal/app/api/warehouses/branch-store/route.ts delete mode 100644 solvway-admin-portal/app/api/warehouses/route.test.ts delete mode 100644 solvway-admin-portal/app/api/warehouses/route.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/[uuid]/approve/route.test.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/[uuid]/approve/route.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/[uuid]/photos/[index]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/[uuid]/photos/[index]/route.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/[uuid]/reject/route.test.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/[uuid]/reject/route.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/route.test.ts delete mode 100644 solvway-admin-portal/app/api/warranty-claims/route.ts delete mode 100644 solvway-admin-portal/app/api/web-orders/[uuid]/invoice/route.test.ts delete mode 100644 solvway-admin-portal/app/api/web-orders/[uuid]/invoice/route.ts delete mode 100644 solvway-admin-portal/app/api/web-orders/[uuid]/route.test.ts delete mode 100644 solvway-admin-portal/app/api/web-orders/[uuid]/route.ts delete mode 100644 solvway-admin-portal/app/api/web-orders/[uuid]/void-pending/route.test.ts delete mode 100644 solvway-admin-portal/app/api/web-orders/[uuid]/void-pending/route.ts delete mode 100644 solvway-admin-portal/app/api/web-orders/route.test.ts delete mode 100644 solvway-admin-portal/app/api/web-orders/route.ts delete mode 100644 solvway-admin-portal/app/audit-log/page.test.tsx delete mode 100644 solvway-admin-portal/app/audit-log/page.tsx delete mode 100644 solvway-admin-portal/app/banners/BannerFormDialog.tsx delete mode 100644 solvway-admin-portal/app/banners/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/banners/page.test.tsx delete mode 100644 solvway-admin-portal/app/banners/page.tsx delete mode 100644 solvway-admin-portal/app/bulletins/BulletinDrawer.tsx delete mode 100644 solvway-admin-portal/app/bulletins/page.area-sort.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/bulletins/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/bulletins/page.test.tsx delete mode 100644 solvway-admin-portal/app/bulletins/page.tsx delete mode 100644 solvway-admin-portal/app/catalog-setup/page.copy.test.tsx delete mode 100644 solvway-admin-portal/app/catalog-setup/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/catalog-setup/page.test.tsx delete mode 100644 solvway-admin-portal/app/catalog-setup/page.tsx delete mode 100644 solvway-admin-portal/app/collections/[id]/page.tsx delete mode 100644 solvway-admin-portal/app/collections/new/page.tsx delete mode 100644 solvway-admin-portal/app/collections/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/collections/page.test.tsx delete mode 100644 solvway-admin-portal/app/collections/page.tsx delete mode 100644 solvway-admin-portal/app/components/app/CommandPalette.test.tsx delete mode 100644 solvway-admin-portal/app/components/app/CommandPalette.tsx delete mode 100644 solvway-admin-portal/app/components/app/MemberMessagesBadge.test.tsx delete mode 100644 solvway-admin-portal/app/components/app/MemberMessagesBadge.tsx delete mode 100644 solvway-admin-portal/app/components/app/NotificationsBell.messages.test.tsx delete mode 100644 solvway-admin-portal/app/components/app/NotificationsBell.test.tsx delete mode 100644 solvway-admin-portal/app/components/app/NotificationsBell.tsx delete mode 100644 solvway-admin-portal/app/components/app/SectionTabs.test.tsx delete mode 100644 solvway-admin-portal/app/components/app/SectionTabs.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/BarcodeList.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/FieldError.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuDrawer.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuEditor.barcodes.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuEditor.supplier.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuEditor.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuEditor.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuList.export.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuList.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuList.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuPicker.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuPicker.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuVariationPicker.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SkuVariationPicker.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SupplierSelect.test.tsx delete mode 100644 solvway-admin-portal/app/components/catalog-setup/SupplierSelect.tsx delete mode 100644 solvway-admin-portal/app/components/collections/CollectionForm.test.tsx delete mode 100644 solvway-admin-portal/app/components/collections/CollectionForm.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/EventDashboard.alerts.test.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/EventDashboard.drilldown.test.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/EventDashboard.test.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/EventDashboard.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/action-strip.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/chart-card.test.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/chart-card.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/drill-link.test.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/drill-link.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/hero-band.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/kpi-tile.test.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/kpi-tile.tsx delete mode 100644 solvway-admin-portal/app/components/dashboard/page.curve.guard.test.ts delete mode 100644 solvway-admin-portal/app/components/events/EventCharts.test.tsx delete mode 100644 solvway-admin-portal/app/components/events/EventCharts.tsx delete mode 100644 solvway-admin-portal/app/components/events/EventCloseOutDialog.test.tsx delete mode 100644 solvway-admin-portal/app/components/events/EventCloseOutDialog.tsx delete mode 100644 solvway-admin-portal/app/components/events/EventPicker.test.tsx delete mode 100644 solvway-admin-portal/app/components/events/EventPicker.tsx delete mode 100644 solvway-admin-portal/app/components/events/RunProgress.test.tsx delete mode 100644 solvway-admin-portal/app/components/events/RunProgress.tsx delete mode 100644 solvway-admin-portal/app/components/forms/FormEditor.test.tsx delete mode 100644 solvway-admin-portal/app/components/forms/FormEditor.tsx delete mode 100644 solvway-admin-portal/app/components/forms/SubmissionsView.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/components/forms/SubmissionsView.test.tsx delete mode 100644 solvway-admin-portal/app/components/forms/SubmissionsView.tsx delete mode 100644 solvway-admin-portal/app/components/fulfilment/FulfilmentTimeline.test.tsx delete mode 100644 solvway-admin-portal/app/components/fulfilment/FulfilmentTimeline.tsx delete mode 100644 solvway-admin-portal/app/components/genealogy/org-chart.css delete mode 100644 solvway-admin-portal/app/components/genealogy/org-chart.test.tsx delete mode 100644 solvway-admin-portal/app/components/genealogy/org-chart.tsx delete mode 100644 solvway-admin-portal/app/components/genealogy/tree-view.test.tsx delete mode 100644 solvway-admin-portal/app/components/genealogy/tree-view.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/AdjustmentForm.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/AdjustmentForm.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/MovementHistoryReport.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/MovementHistoryReport.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockCountDetail.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockCountDetail.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockCountDetail.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockCountsTab.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockCountsTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockCountsTab.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockInForm.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockInForm.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockOnHandReport.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/StockOnHandReport.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/TransferForm.test.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/TransferForm.tsx delete mode 100644 solvway-admin-portal/app/components/inventory/insufficientStock.test.ts delete mode 100644 solvway-admin-portal/app/components/inventory/insufficientStock.ts delete mode 100644 solvway-admin-portal/app/components/kyc/KycDocViewer.tsx delete mode 100644 solvway-admin-portal/app/components/kyc/KycDrawer.tsx delete mode 100644 solvway-admin-portal/app/components/kyc/KycReviewDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/components/kyc/KycReviewDrawer.tsx delete mode 100644 solvway-admin-portal/app/components/kyc/KycStatusBadge.tsx delete mode 100644 solvway-admin-portal/app/components/kyc/KycSubmitDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/components/kyc/KycSubmitDrawer.tsx delete mode 100644 solvway-admin-portal/app/components/locations/AddLocationDialog.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/AddLocationDialog.tsx delete mode 100644 solvway-admin-portal/app/components/locations/LocationDetailTabs.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/LocationDetailTabs.tsx delete mode 100644 solvway-admin-portal/app/components/locations/LocationTree.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/LocationTree.tsx delete mode 100644 solvway-admin-portal/app/components/locations/MoveLocationDialog.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/MoveLocationDialog.tsx delete mode 100644 solvway-admin-portal/app/components/locations/StatusToggleDialog.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/StatusToggleDialog.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/AddressKycTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/AddressKycTab.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/GeneralTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/GeneralTab.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/GeoAddressTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/GeoAddressTab.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/InvoicingTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/InvoicingTab.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/PickupOutletTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/PickupOutletTab.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/WarehouseTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/locations/tabs/WarehouseTab.tsx delete mode 100644 solvway-admin-portal/app/components/members/MemberCell.test.tsx delete mode 100644 solvway-admin-portal/app/components/members/MemberCell.tsx delete mode 100644 solvway-admin-portal/app/components/members/MemberSearchCombobox.test.tsx delete mode 100644 solvway-admin-portal/app/components/members/MemberSearchCombobox.tsx delete mode 100644 solvway-admin-portal/app/components/menus/MenuEditor.test.tsx delete mode 100644 solvway-admin-portal/app/components/menus/MenuEditor.tsx delete mode 100644 solvway-admin-portal/app/components/messages/ImageAttachments.hardening.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/ImageAttachments.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/ImageAttachments.tsx delete mode 100644 solvway-admin-portal/app/components/messages/MemberSearch.hardening.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/MemberSearch.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/MemberSearch.tsx delete mode 100644 solvway-admin-portal/app/components/messages/MessageThreadDrawer.hardening.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/MessageThreadDrawer.scroll.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/MessageThreadDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/MessageThreadDrawer.tsx delete mode 100644 solvway-admin-portal/app/components/messages/NewMessageDialog.hardening.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/NewMessageDialog.test.tsx delete mode 100644 solvway-admin-portal/app/components/messages/NewMessageDialog.tsx delete mode 100644 solvway-admin-portal/app/components/pages/BlockFields.tsx delete mode 100644 solvway-admin-portal/app/components/pages/PageEditor.blocks.test.tsx delete mode 100644 solvway-admin-portal/app/components/pages/PageEditor.forms.test.tsx delete mode 100644 solvway-admin-portal/app/components/pages/PageEditor.review.test.tsx delete mode 100644 solvway-admin-portal/app/components/pages/PageEditor.test.tsx delete mode 100644 solvway-admin-portal/app/components/pages/PageEditor.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/BundleSection.test.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/BundleSection.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/CodeMatchNotice.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/GroupSection.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/LinkedSku.test.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/LinkedSkuBanner.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/OptionChips.test.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/OptionChips.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/PriceList.test.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/PriceList.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/ProductSetupPage.test.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/ProductSetupPage.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/SetupStep.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/SideColumn.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/TypeChooser.test.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/TypeChooser.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/VariantsSection.test.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/VariantsSection.tsx delete mode 100644 solvway-admin-portal/app/components/product-page/priceTypeLabel.test.ts delete mode 100644 solvway-admin-portal/app/components/products/ProductSearchCombobox.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/ProductSearchCombobox.tsx delete mode 100644 solvway-admin-portal/app/components/products/QianyiSkuPicker.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/QianyiSkuPicker.tsx delete mode 100644 solvway-admin-portal/app/components/products/RichTextEditor.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/RichTextEditor.tsx delete mode 100644 solvway-admin-portal/app/components/products/TagInput.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/TagInput.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/ContentImagesPanel.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/ContentImagesPanel.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/GroupPanel.picker.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/GroupPanel.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/GroupPanel.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/OrganizationPanel.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/OrganizationPanel.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/ProductDetailsPanel.test.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/ProductDetailsPanel.tsx delete mode 100644 solvway-admin-portal/app/components/products/panels/types.ts delete mode 100644 solvway-admin-portal/app/components/refunds/CancelShipmentAction.test.tsx delete mode 100644 solvway-admin-portal/app/components/refunds/CancelShipmentAction.tsx delete mode 100644 solvway-admin-portal/app/components/refunds/PayoutFields.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/CalculatorTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/CalculatorTab.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/CouriersTab.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/CouriersTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/CouriersTab.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/RateCardEditor.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/RateCardEditor.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/RateCardsTab.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/RateCardsTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/RateCardsTab.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/RegionPicker.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/ZoneRatesTable.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/ZoneRatesTable.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/ZonesTab.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/ZonesTab.test.tsx delete mode 100644 solvway-admin-portal/app/components/shipping/ZonesTab.tsx delete mode 100644 solvway-admin-portal/app/components/ui/breakable-code.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/breakable-code.tsx delete mode 100644 solvway-admin-portal/app/components/ui/calendar.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/calendar.tsx delete mode 100644 solvway-admin-portal/app/components/ui/chart-skeleton.tsx delete mode 100644 solvway-admin-portal/app/components/ui/chart.tsx delete mode 100644 solvway-admin-portal/app/components/ui/command.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/command.tsx delete mode 100644 solvway-admin-portal/app/components/ui/confirm-dialog.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/confirm-dialog.tsx delete mode 100644 solvway-admin-portal/app/components/ui/country-code-picker.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/country-code-picker.tsx delete mode 100644 solvway-admin-portal/app/components/ui/date-picker.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/date-picker.tsx delete mode 100644 solvway-admin-portal/app/components/ui/date-range-picker.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/date-range-picker.tsx delete mode 100644 solvway-admin-portal/app/components/ui/date-time-picker.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/date-time-picker.tsx delete mode 100644 solvway-admin-portal/app/components/ui/detail-field.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/detail-field.tsx delete mode 100644 solvway-admin-portal/app/components/ui/markdown.tsx delete mode 100644 solvway-admin-portal/app/components/ui/radio-group.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/radio-group.tsx delete mode 100644 solvway-admin-portal/app/components/ui/segmented.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/segmented.tsx delete mode 100644 solvway-admin-portal/app/components/ui/separator.tsx delete mode 100644 solvway-admin-portal/app/components/ui/tabs.tsx delete mode 100644 solvway-admin-portal/app/components/ui/textarea.test.tsx delete mode 100644 solvway-admin-portal/app/components/ui/textarea.tsx delete mode 100644 solvway-admin-portal/app/components/users/UserForm.countryScope.test.tsx delete mode 100644 solvway-admin-portal/app/components/users/UserForm.event.test.tsx delete mode 100644 solvway-admin-portal/app/components/warehouses/WarehouseFormDialog.test.tsx delete mode 100644 solvway-admin-portal/app/components/warehouses/WarehouseFormDialog.tsx delete mode 100644 solvway-admin-portal/app/components/warehouses/WarehouseTree.test.tsx delete mode 100644 solvway-admin-portal/app/components/warehouses/WarehouseTree.tsx delete mode 100644 solvway-admin-portal/app/components/warehouses/warehouseLabels.test.ts delete mode 100644 solvway-admin-portal/app/components/warehouses/warehouseLabels.ts delete mode 100644 solvway-admin-portal/app/currency/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/currency/page.test.tsx delete mode 100644 solvway-admin-portal/app/currency/page.tsx delete mode 100644 solvway-admin-portal/app/email-templates/EmailTemplateEditor.test.tsx delete mode 100644 solvway-admin-portal/app/email-templates/EmailTemplateEditor.tsx delete mode 100644 solvway-admin-portal/app/email-templates/TemplatePreviewPane.test.tsx delete mode 100644 solvway-admin-portal/app/email-templates/TemplatePreviewPane.tsx delete mode 100644 solvway-admin-portal/app/email-templates/[name]/page.test.tsx delete mode 100644 solvway-admin-portal/app/email-templates/[name]/page.tsx delete mode 100644 solvway-admin-portal/app/email-templates/logs/[id]/page.test.tsx delete mode 100644 solvway-admin-portal/app/email-templates/logs/[id]/page.tsx delete mode 100644 solvway-admin-portal/app/email-templates/new/page.tsx delete mode 100644 solvway-admin-portal/app/email-templates/page.remaining-sort.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/email-templates/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/email-templates/page.test.tsx delete mode 100644 solvway-admin-portal/app/email-templates/page.tsx delete mode 100644 solvway-admin-portal/app/events/page.export.test.tsx delete mode 100644 solvway-admin-portal/app/events/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/events/page.test.tsx delete mode 100644 solvway-admin-portal/app/events/page.tsx delete mode 100644 solvway-admin-portal/app/events/summary/page.test.tsx delete mode 100644 solvway-admin-portal/app/events/summary/page.tsx delete mode 100644 solvway-admin-portal/app/forms/[id]/page.tsx delete mode 100644 solvway-admin-portal/app/forms/[id]/submissions/page.tsx delete mode 100644 solvway-admin-portal/app/forms/new/page.tsx delete mode 100644 solvway-admin-portal/app/forms/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/forms/page.test.tsx delete mode 100644 solvway-admin-portal/app/forms/page.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/AmountsPanel.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/AmountsPanel.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/CardsPanel.export.test.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/CardsPanel.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/GiftCardDrawer.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/IssueGiftCardsDialog.country.test.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/IssueGiftCardsDialog.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/giftCardLabels.test.ts delete mode 100644 solvway-admin-portal/app/gift-cards/giftCardLabels.ts delete mode 100644 solvway-admin-portal/app/gift-cards/page.test.tsx delete mode 100644 solvway-admin-portal/app/gift-cards/page.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/BulkIssueDialog.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/BulkIssueDialog.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/DeliveryDetailBody.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/DeliveryDetailBody.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/DeliveryDetailBody.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/DoDetailDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/DoDetailDrawer.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/DoStepper.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/DoStepper.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/FulfilmentHealthStrip.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/FulfilmentHealthStrip.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/IssueDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/IssueDrawer.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/PickupDetailBody.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/PickupDetailBody.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/PickupDetailBody.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/SelectionBar.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/ToIssueTab.bulk.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/ToIssueTab.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/ToIssueTab.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/[uuid]/QianyiPushPanel.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/[uuid]/QianyiPushPanel.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/[uuid]/page.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/[uuid]/page.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/counter/[uuid]/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/counter/[uuid]/page.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/counter/[uuid]/page.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/counterChannel.test.ts delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/counterChannel.ts delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/deliveryStatus.test.ts delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/deliveryStatus.ts delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/fulfilment.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/fulfilment/BatchProgressDialog.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/fulfilment/BatchProgressDialog.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/fulfilment/ImportTrackingDialog.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/fulfilment/ImportTrackingDialog.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/lineNames.ts delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/page.export.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/page.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/page.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/pick-list/page.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/pick-list/page.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/pickup/[uuid]/page.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/delivery-orders/pickup/[uuid]/page.tsx delete mode 100644 solvway-admin-portal/app/inventory/page.test.tsx delete mode 100644 solvway-admin-portal/app/inventory/page.tsx delete mode 100644 solvway-admin-portal/app/inventory/stock-counts/[id]/page.tsx delete mode 100644 solvway-admin-portal/app/lib/AdminAuthContext.countryScope.test.tsx delete mode 100644 solvway-admin-portal/app/lib/AdminAuthContext.refundsOff.test.tsx delete mode 100644 solvway-admin-portal/app/lib/auditAction.test.ts delete mode 100644 solvway-admin-portal/app/lib/auditAction.ts delete mode 100644 solvway-admin-portal/app/lib/catalogI18n.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogImport.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogImport.ts delete mode 100644 solvway-admin-portal/app/lib/catalogSetup.barcodes.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogSetup.optionChips.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogSetup.options.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogSetup.supplier.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogSetup.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogSetup.ts delete mode 100644 solvway-admin-portal/app/lib/catalogSetup.variantLabel.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogTables.supplier.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogTables.test.ts delete mode 100644 solvway-admin-portal/app/lib/catalogTables.ts delete mode 100644 solvway-admin-portal/app/lib/catalogueExport.test.ts delete mode 100644 solvway-admin-portal/app/lib/cmsForms.test.ts delete mode 100644 solvway-admin-portal/app/lib/cmsForms.ts delete mode 100644 solvway-admin-portal/app/lib/cmsPages.test.ts delete mode 100644 solvway-admin-portal/app/lib/cmsPages.ts delete mode 100644 solvway-admin-portal/app/lib/codeOrNameSearch.test.ts delete mode 100644 solvway-admin-portal/app/lib/codeOrNameSearch.ts delete mode 100644 solvway-admin-portal/app/lib/collections.test.ts delete mode 100644 solvway-admin-portal/app/lib/collections.ts delete mode 100644 solvway-admin-portal/app/lib/correctionReason.test.ts delete mode 100644 solvway-admin-portal/app/lib/correctionReason.ts delete mode 100644 solvway-admin-portal/app/lib/countryCallingCodes.test.ts delete mode 100644 solvway-admin-portal/app/lib/countryCallingCodes.ts delete mode 100644 solvway-admin-portal/app/lib/date-input.test.ts delete mode 100644 solvway-admin-portal/app/lib/date-input.ts delete mode 100644 solvway-admin-portal/app/lib/downloadDoPdf.ts delete mode 100644 solvway-admin-portal/app/lib/eventState.test.ts delete mode 100644 solvway-admin-portal/app/lib/eventState.ts delete mode 100644 solvway-admin-portal/app/lib/eventTenders.ts delete mode 100644 solvway-admin-portal/app/lib/exportAll.test.ts delete mode 100644 solvway-admin-portal/app/lib/exportAll.ts delete mode 100644 solvway-admin-portal/app/lib/features.ts delete mode 100644 solvway-admin-portal/app/lib/fileToBase64.ts delete mode 100644 solvway-admin-portal/app/lib/filterOptions.test.ts delete mode 100644 solvway-admin-portal/app/lib/format.test.ts delete mode 100644 solvway-admin-portal/app/lib/format.ts delete mode 100644 solvway-admin-portal/app/lib/fulfilment/trackingWorkbook.test.ts delete mode 100644 solvway-admin-portal/app/lib/fulfilment/trackingWorkbook.ts delete mode 100644 solvway-admin-portal/app/lib/geoLevels.ts delete mode 100644 solvway-admin-portal/app/lib/hooks/useSellableCountry.ts delete mode 100644 solvway-admin-portal/app/lib/hooks/useSplitPoll.test.ts delete mode 100644 solvway-admin-portal/app/lib/hooks/useSplitPoll.ts delete mode 100644 solvway-admin-portal/app/lib/hooks/useTabParam.ts delete mode 100644 solvway-admin-portal/app/lib/hooks/useVisiblePolling.ts delete mode 100644 solvway-admin-portal/app/lib/i18n/defaultMessages.countryScope.test.ts delete mode 100644 solvway-admin-portal/app/lib/i18n/defaultMessages.posMemberCountry.test.ts delete mode 100644 solvway-admin-portal/app/lib/images/shrinkImage.test.ts delete mode 100644 solvway-admin-portal/app/lib/images/shrinkImage.ts delete mode 100644 solvway-admin-portal/app/lib/inventory/quantityInput.test.ts delete mode 100644 solvway-admin-portal/app/lib/inventory/quantityInput.ts delete mode 100644 solvway-admin-portal/app/lib/inventory/stockInWorkbook.test.ts delete mode 100644 solvway-admin-portal/app/lib/inventory/stockInWorkbook.ts delete mode 100644 solvway-admin-portal/app/lib/inventory/transferWorkbook.test.ts delete mode 100644 solvway-admin-portal/app/lib/inventory/transferWorkbook.ts delete mode 100644 solvway-admin-portal/app/lib/inventory/workbookRows.test.ts delete mode 100644 solvway-admin-portal/app/lib/inventory/workbookRows.ts delete mode 100644 solvway-admin-portal/app/lib/inventoryModules.ts delete mode 100644 solvway-admin-portal/app/lib/kyc/kycExport.test.ts delete mode 100644 solvway-admin-portal/app/lib/kyc/kycExport.ts delete mode 100644 solvway-admin-portal/app/lib/kyc/resizeImage.test.ts delete mode 100644 solvway-admin-portal/app/lib/kyc/resizeImage.ts delete mode 100644 solvway-admin-portal/app/lib/lineName.ts delete mode 100644 solvway-admin-portal/app/lib/loginEvents.i18n.test.ts delete mode 100644 solvway-admin-portal/app/lib/loginEvents.test.ts delete mode 100644 solvway-admin-portal/app/lib/loginEvents.ts delete mode 100644 solvway-admin-portal/app/lib/malaysiaPeriod.test.ts delete mode 100644 solvway-admin-portal/app/lib/malaysiaPeriod.ts delete mode 100644 solvway-admin-portal/app/lib/memberLabels.test.ts delete mode 100644 solvway-admin-portal/app/lib/memberLabels.ts delete mode 100644 solvway-admin-portal/app/lib/menus.test.ts delete mode 100644 solvway-admin-portal/app/lib/menus.ts delete mode 100644 solvway-admin-portal/app/lib/messageContent.test.ts delete mode 100644 solvway-admin-portal/app/lib/messageContent.ts delete mode 100644 solvway-admin-portal/app/lib/messageImportPreview.test.ts delete mode 100644 solvway-admin-portal/app/lib/messageImportPreview.ts delete mode 100644 solvway-admin-portal/app/lib/messagePlaceholders.test.ts delete mode 100644 solvway-admin-portal/app/lib/messagePlaceholders.ts delete mode 100644 solvway-admin-portal/app/lib/messages/broadcastTarget.test.ts delete mode 100644 solvway-admin-portal/app/lib/messages/broadcastTarget.ts delete mode 100644 solvway-admin-portal/app/lib/onlinePayments/onlinePayments.test.ts delete mode 100644 solvway-admin-portal/app/lib/onlinePayments/onlinePaymentsExport.ts delete mode 100644 solvway-admin-portal/app/lib/paymentTypes.test.ts delete mode 100644 solvway-admin-portal/app/lib/paymentTypes.ts delete mode 100644 solvway-admin-portal/app/lib/posEventsI18n.test.ts delete mode 100644 solvway-admin-portal/app/lib/productPage.test.ts delete mode 100644 solvway-admin-portal/app/lib/productPage.ts delete mode 100644 solvway-admin-portal/app/lib/productPickerLabel.ts delete mode 100644 solvway-admin-portal/app/lib/promotionStatus.ts delete mode 100644 solvway-admin-portal/app/lib/referenceTables.test.ts delete mode 100644 solvway-admin-portal/app/lib/referenceTables.ts delete mode 100644 solvway-admin-portal/app/lib/salesI18n.test.ts delete mode 100644 solvway-admin-portal/app/lib/security/binaryProxyHeaders.sweep.test.ts delete mode 100644 solvway-admin-portal/app/lib/server/binaryProxy.ts delete mode 100644 solvway-admin-portal/app/lib/server/directFetchTraversal.test.ts delete mode 100644 solvway-admin-portal/app/lib/server/forwardGet.ts delete mode 100644 solvway-admin-portal/app/lib/server/memberPortalUrl.test.ts delete mode 100644 solvway-admin-portal/app/lib/server/memberPortalUrl.ts delete mode 100644 solvway-admin-portal/app/lib/server/messagesProxy.ts delete mode 100644 solvway-admin-portal/app/lib/server/upstreamQuery.test.ts delete mode 100644 solvway-admin-portal/app/lib/server/upstreamQuery.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminBank.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCatalog.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCatalogSetup.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCatalogSetup.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCollections.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCompanyAccount.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCompanyAccount.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCounter.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCounterDeliveryOrders.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminCounterDeliveryOrders.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminDashboard.actions.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminDashboard.country.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminDashboard.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminDashboard.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminDeliveryOrders.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminDeliveryOrders.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminEventSummary.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminEventSummary.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminEvents.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminEvents.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminForms.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminFulfilment.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminFulfilment.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminFulfilmentEvents.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminFulfilmentHealth.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminGiftCards.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminKyc.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminKyc.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminLocations.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminLocations.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminMenus.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminMessages.broadcasts.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminMessages.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminMessages.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminModules.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminOnlinePayments.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminPages.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminPaymentMethods.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminPickupDeliveryOrders.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminPickupDeliveryOrders.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminPos.products.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminPos.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminProduct.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminProduct.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminProductReviews.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminPromotions.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminPromotions.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminQianyiOrders.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminReference.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminRefunds.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminRefunds.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminShipping.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminShipping.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminStock.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminStock.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminStockCounts.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminStockCounts.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminTopups.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminTopups.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWarehouses.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWarehouses.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWarranty.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWarranty.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWebOrders.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWebOrders.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWebOrdersStalePending.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWithdrawals.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/adminWithdrawals.ts delete mode 100644 solvway-admin-portal/app/lib/services/api.ts delete mode 100644 solvway-admin-portal/app/lib/services/auditLog.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/auditLog.ts delete mode 100644 solvway-admin-portal/app/lib/services/banners.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/banners.ts delete mode 100644 solvway-admin-portal/app/lib/services/bulletins.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/bulletins.ts delete mode 100644 solvway-admin-portal/app/lib/services/currency.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/currency.ts delete mode 100644 solvway-admin-portal/app/lib/services/dashboardLabels.i18n.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/emailTemplates.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/emailTemplates.ts delete mode 100644 solvway-admin-portal/app/lib/services/listSort.sorting.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/locales.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/locales.ts delete mode 100644 solvway-admin-portal/app/lib/services/loginSecurity.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/loginSecurity.ts delete mode 100644 solvway-admin-portal/app/lib/services/members.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/members.ts delete mode 100644 solvway-admin-portal/app/lib/services/messageAreas.i18n.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/messages.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/messages.ts delete mode 100644 solvway-admin-portal/app/lib/services/network.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/network.ts delete mode 100644 solvway-admin-portal/app/lib/services/notifications.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/notifications.ts delete mode 100644 solvway-admin-portal/app/lib/services/onlineUsers.ts delete mode 100644 solvway-admin-portal/app/lib/services/period.ts delete mode 100644 solvway-admin-portal/app/lib/services/posGiftCards.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/posGiftCards.ts delete mode 100644 solvway-admin-portal/app/lib/services/remainingSort.sorting.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/retiredStockistArea.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/sellableCountries.ts delete mode 100644 solvway-admin-portal/app/lib/services/types.ts delete mode 100644 solvway-admin-portal/app/lib/services/wallet.test.ts delete mode 100644 solvway-admin-portal/app/lib/services/wallet.ts delete mode 100644 solvway-admin-portal/app/lib/sessionPolicyRules.ts delete mode 100644 solvway-admin-portal/app/lib/shipping/rateCardWorkbook.test.ts delete mode 100644 solvway-admin-portal/app/lib/shipping/rateCardWorkbook.ts delete mode 100644 solvway-admin-portal/app/lib/shipping/rateRows.test.ts delete mode 100644 solvway-admin-portal/app/lib/shipping/rateRows.ts delete mode 100644 solvway-admin-portal/app/lib/sidebarLayout.test.ts delete mode 100644 solvway-admin-portal/app/lib/sidebarLayout.ts delete mode 100644 solvway-admin-portal/app/lib/siteLink.ts delete mode 100644 solvway-admin-portal/app/lib/stockCountStatus.ts delete mode 100644 solvway-admin-portal/app/lib/stockI18n.test.ts delete mode 100644 solvway-admin-portal/app/lib/storefront.tsx delete mode 100644 solvway-admin-portal/app/lib/use-pos-client-key.test.ts delete mode 100644 solvway-admin-portal/app/lib/use-pos-client-key.ts delete mode 100644 solvway-admin-portal/app/lib/useListingExport.tsx delete mode 100644 solvway-admin-portal/app/lib/useScanKeyCapture.ts delete mode 100644 solvway-admin-portal/app/lib/walletAmounts.test.ts delete mode 100644 solvway-admin-portal/app/lib/walletAmounts.ts delete mode 100644 solvway-admin-portal/app/lib/walletLabels.ts delete mode 100644 solvway-admin-portal/app/lib/walletRequestStatus.test.ts delete mode 100644 solvway-admin-portal/app/lib/walletRequestStatus.ts delete mode 100644 solvway-admin-portal/app/lib/walletTrxnType.test.ts delete mode 100644 solvway-admin-portal/app/lib/walletTrxnType.ts delete mode 100644 solvway-admin-portal/app/lib/xlsx.test.ts delete mode 100644 solvway-admin-portal/app/lib/xlsx.ts delete mode 100644 solvway-admin-portal/app/locales/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/locales/page.test.tsx delete mode 100644 solvway-admin-portal/app/locales/page.tsx delete mode 100644 solvway-admin-portal/app/locations/page.test.tsx delete mode 100644 solvway-admin-portal/app/locations/page.tsx delete mode 100644 solvway-admin-portal/app/login-security/page.sessionPolicy.test.tsx delete mode 100644 solvway-admin-portal/app/login-security/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/login-security/page.test.tsx delete mode 100644 solvway-admin-portal/app/login-security/page.tsx delete mode 100644 solvway-admin-portal/app/member-messages/broadcast/page.hardening.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/broadcast/page.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/broadcast/page.tsx delete mode 100644 solvway-admin-portal/app/member-messages/broadcasts/[broadcastUuid]/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/broadcasts/[broadcastUuid]/page.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/broadcasts/[broadcastUuid]/page.tsx delete mode 100644 solvway-admin-portal/app/member-messages/page.broadcasts.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/page.deeplink.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/page.hardening.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/page.member.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/page.open.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/page.test.tsx delete mode 100644 solvway-admin-portal/app/member-messages/page.tsx delete mode 100644 solvway-admin-portal/app/members/[memberCode]/ChangeHistory.test.tsx delete mode 100644 solvway-admin-portal/app/members/[memberCode]/ChangeHistory.tsx delete mode 100644 solvway-admin-portal/app/members/[memberCode]/edit/page.test.tsx delete mode 100644 solvway-admin-portal/app/members/[memberCode]/edit/page.tsx delete mode 100644 solvway-admin-portal/app/members/[memberCode]/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/members/[memberCode]/page.test.tsx delete mode 100644 solvway-admin-portal/app/members/[memberCode]/page.tsx delete mode 100644 solvway-admin-portal/app/members/knowYourCustomer/page.test.tsx delete mode 100644 solvway-admin-portal/app/members/knowYourCustomer/page.tsx delete mode 100644 solvway-admin-portal/app/members/page.phone-sort.test.tsx delete mode 100644 solvway-admin-portal/app/members/page.test.tsx delete mode 100644 solvway-admin-portal/app/members/page.tsx delete mode 100644 solvway-admin-portal/app/members/register/page.test.tsx delete mode 100644 solvway-admin-portal/app/members/register/page.tsx delete mode 100644 solvway-admin-portal/app/menus/page.test.tsx delete mode 100644 solvway-admin-portal/app/menus/page.tsx delete mode 100644 solvway-admin-portal/app/messages/ImportMessagesDialog.test.tsx delete mode 100644 solvway-admin-portal/app/messages/ImportMessagesDialog.tsx delete mode 100644 solvway-admin-portal/app/messages/MessageEditSheet.test.tsx delete mode 100644 solvway-admin-portal/app/messages/MessageEditSheet.tsx delete mode 100644 solvway-admin-portal/app/messages/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/messages/page.test.tsx delete mode 100644 solvway-admin-portal/app/messages/page.tsx delete mode 100644 solvway-admin-portal/app/modules/filterModuleNodes.test.ts delete mode 100644 solvway-admin-portal/app/modules/filterModuleNodes.ts delete mode 100644 solvway-admin-portal/app/modules/page.test.tsx delete mode 100644 solvway-admin-portal/app/modules/page.tsx delete mode 100644 solvway-admin-portal/app/network/NetworkTabs.test.tsx delete mode 100644 solvway-admin-portal/app/network/NetworkTabs.tsx delete mode 100644 solvway-admin-portal/app/network/PlacementHistory.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/network/company-accounts/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/network/company-accounts/page.test.tsx delete mode 100644 solvway-admin-portal/app/network/company-accounts/page.tsx delete mode 100644 solvway-admin-portal/app/network/page.test.tsx delete mode 100644 solvway-admin-portal/app/network/page.tsx delete mode 100644 solvway-admin-portal/app/notifications/page.test.tsx delete mode 100644 solvway-admin-portal/app/notifications/page.tsx delete mode 100644 solvway-admin-portal/app/online-payments/page.test.tsx delete mode 100644 solvway-admin-portal/app/online-payments/page.tsx delete mode 100644 solvway-admin-portal/app/online-users/page.test.tsx delete mode 100644 solvway-admin-portal/app/online-users/page.tsx delete mode 100644 solvway-admin-portal/app/orders/refunds/RefundDrawer.giftCard.test.tsx delete mode 100644 solvway-admin-portal/app/orders/refunds/RefundDrawer.photos.test.tsx delete mode 100644 solvway-admin-portal/app/orders/refunds/RefundDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/orders/refunds/RefundDrawer.tsx delete mode 100644 solvway-admin-portal/app/orders/refunds/page.test.tsx delete mode 100644 solvway-admin-portal/app/orders/refunds/page.tsx delete mode 100644 solvway-admin-portal/app/orders/refunds/refundLabels.ts delete mode 100644 solvway-admin-portal/app/orders/refunds/refundSource.test.tsx delete mode 100644 solvway-admin-portal/app/orders/warranty-claims/WarrantyClaimDrawer.review.test.tsx delete mode 100644 solvway-admin-portal/app/orders/warranty-claims/WarrantyClaimDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/orders/warranty-claims/WarrantyClaimDrawer.tsx delete mode 100644 solvway-admin-portal/app/orders/warranty-claims/page.export.test.tsx delete mode 100644 solvway-admin-portal/app/orders/warranty-claims/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/orders/warranty-claims/page.test.tsx delete mode 100644 solvway-admin-portal/app/orders/warranty-claims/page.tsx delete mode 100644 solvway-admin-portal/app/orders/warranty-claims/warrantyLabels.ts delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/OrderParcels.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/OrderParcels.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/OrderParcels.tsx delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/RaiseRefundAction.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/RaiseRefundAction.tsx delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/page.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/page.tsx delete mode 100644 solvway-admin-portal/app/orders/web/[uuid]/voidPending.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/eventSellerFilter.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/page.export.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/page.test.tsx delete mode 100644 solvway-admin-portal/app/orders/web/page.tsx delete mode 100644 solvway-admin-portal/app/orders/web/staleFilter.test.tsx delete mode 100644 solvway-admin-portal/app/page.actions.test.tsx delete mode 100644 solvway-admin-portal/app/page.country.test.tsx delete mode 100644 solvway-admin-portal/app/page.dateAxis.guard.test.ts delete mode 100644 solvway-admin-portal/app/page.drilldown.test.tsx delete mode 100644 solvway-admin-portal/app/page.emptyMonth.test.tsx delete mode 100644 solvway-admin-portal/app/pages/[id]/page.tsx delete mode 100644 solvway-admin-portal/app/pages/new/page.tsx delete mode 100644 solvway-admin-portal/app/pages/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/pages/page.test.tsx delete mode 100644 solvway-admin-portal/app/pages/page.tsx delete mode 100644 solvway-admin-portal/app/payment-methods/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/payment-methods/page.test.tsx delete mode 100644 solvway-admin-portal/app/payment-methods/page.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/GiftCardCodesField.test.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/GiftCardCodesField.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/SellGiftCardDialog.test.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/SellGiftCardDialog.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/SplitTenderPanel.test.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/SplitTenderPanel.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/WalletAmountLeg.test.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/WalletAmountLeg.tsx delete mode 100644 solvway-admin-portal/app/pos/_components/WalletLegs.tsx delete mode 100644 solvway-admin-portal/app/pos/components/CartPanel.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/CartPanel.tsx delete mode 100644 solvway-admin-portal/app/pos/components/CustomerCard.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/CustomerCard.tsx delete mode 100644 solvway-admin-portal/app/pos/components/CustomerDialog.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/CustomerDialog.tsx delete mode 100644 solvway-admin-portal/app/pos/components/FulfilmentPicker.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/FulfilmentPicker.tsx delete mode 100644 solvway-admin-portal/app/pos/components/PaymentDialog.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/PaymentDialog.tsx delete mode 100644 solvway-admin-portal/app/pos/components/PosPromoPanel.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/PosPromoPanel.tsx delete mode 100644 solvway-admin-portal/app/pos/components/ProductGrid.scan.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/ProductGrid.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/ProductGrid.tsx delete mode 100644 solvway-admin-portal/app/pos/components/ProductGrid.variants.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/ReceiptBuyer.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/ReceiptBuyer.tsx delete mode 100644 solvway-admin-portal/app/pos/components/ReceiptDialog.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/ReceiptDialog.tsx delete mode 100644 solvway-admin-portal/app/pos/components/StepBar.test.tsx delete mode 100644 solvway-admin-portal/app/pos/components/StepBar.tsx delete mode 100644 solvway-admin-portal/app/pos/counter/page.test.tsx delete mode 100644 solvway-admin-portal/app/pos/counter/page.tsx delete mode 100644 solvway-admin-portal/app/pos/currency.test.tsx delete mode 100644 solvway-admin-portal/app/pos/currency.tsx delete mode 100644 solvway-admin-portal/app/pos/fulfilment.test.ts delete mode 100644 solvway-admin-portal/app/pos/fulfilment.ts delete mode 100644 solvway-admin-portal/app/pos/page.test.tsx delete mode 100644 solvway-admin-portal/app/pos/page.tsx delete mode 100644 solvway-admin-portal/app/pos/shared.ts delete mode 100644 solvway-admin-portal/app/pos/usePosQuote.test.tsx delete mode 100644 solvway-admin-portal/app/pos/usePosQuote.ts delete mode 100644 solvway-admin-portal/app/product-reviews/ReviewDrawer.test.tsx delete mode 100644 solvway-admin-portal/app/product-reviews/ReviewDrawer.tsx delete mode 100644 solvway-admin-portal/app/product-reviews/ReviewDrawerRegisteredName.test.tsx delete mode 100644 solvway-admin-portal/app/product-reviews/page.test.tsx delete mode 100644 solvway-admin-portal/app/product-reviews/page.tsx delete mode 100644 solvway-admin-portal/app/products/[id]/page.test.tsx delete mode 100644 solvway-admin-portal/app/products/[id]/page.tsx delete mode 100644 solvway-admin-portal/app/products/import/page.test.tsx delete mode 100644 solvway-admin-portal/app/products/import/page.tsx delete mode 100644 solvway-admin-portal/app/products/import/pageCatalogue.test.tsx delete mode 100644 solvway-admin-portal/app/products/new/page.test.tsx delete mode 100644 solvway-admin-portal/app/products/new/page.tsx delete mode 100644 solvway-admin-portal/app/products/page.export.test.tsx delete mode 100644 solvway-admin-portal/app/products/page.tabs.test.tsx delete mode 100644 solvway-admin-portal/app/products/page.test.tsx delete mode 100644 solvway-admin-portal/app/products/page.tsx delete mode 100644 solvway-admin-portal/app/promotions/CampaignForm.country.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/CampaignForm.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/CampaignForm.tsx delete mode 100644 solvway-admin-portal/app/promotions/CampaignsPanel.export.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/CampaignsPanel.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/CampaignsPanel.tsx delete mode 100644 solvway-admin-portal/app/promotions/ProductPicker.tsx delete mode 100644 solvway-admin-portal/app/promotions/ProductSelectDialog.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/ProductSelectDialog.tsx delete mode 100644 solvway-admin-portal/app/promotions/RedemptionsPanel.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/RedemptionsPanel.tsx delete mode 100644 solvway-admin-portal/app/promotions/VouchersPanel.codes.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/VouchersPanel.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/VouchersPanel.tsx delete mode 100644 solvway-admin-portal/app/promotions/campaignChecks.test.ts delete mode 100644 solvway-admin-portal/app/promotions/campaignChecks.ts delete mode 100644 solvway-admin-portal/app/promotions/campaignSummary.test.ts delete mode 100644 solvway-admin-portal/app/promotions/campaignSummary.ts delete mode 100644 solvway-admin-portal/app/promotions/fixedPrice.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/page.tab.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/page.test.tsx delete mode 100644 solvway-admin-portal/app/promotions/page.tsx delete mode 100644 solvway-admin-portal/app/rank-referral/page.export.test.tsx delete mode 100644 solvway-admin-portal/app/rank-referral/page.test.tsx delete mode 100644 solvway-admin-portal/app/rank-referral/page.tsx delete mode 100644 solvway-admin-portal/app/reference/BankPanel.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/reference/BankPanel.test.tsx delete mode 100644 solvway-admin-portal/app/reference/BankPanel.tsx delete mode 100644 solvway-admin-portal/app/reference/page.sorting.test.tsx delete mode 100644 solvway-admin-portal/app/reference/page.test.tsx delete mode 100644 solvway-admin-portal/app/reference/page.tsx delete mode 100644 solvway-admin-portal/app/reports/page.country.test.tsx delete mode 100644 solvway-admin-portal/app/reports/page.countryPaging.test.tsx delete mode 100644 solvway-admin-portal/app/reports/page.items.test.tsx delete mode 100644 solvway-admin-portal/app/reports/page.itemsCountry.test.tsx delete mode 100644 solvway-admin-portal/app/reports/page.test.tsx delete mode 100644 solvway-admin-portal/app/reports/page.tsx delete mode 100644 solvway-admin-portal/app/shipping/page.test.tsx delete mode 100644 solvway-admin-portal/app/shipping/page.tsx delete mode 100644 solvway-admin-portal/app/wallet/WalletAdjustDialog.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/WalletAdjustDialog.tsx delete mode 100644 solvway-admin-portal/app/wallet/WalletTabs.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/WalletTabs.tsx delete mode 100644 solvway-admin-portal/app/wallet/[memberCode]/page.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/[memberCode]/page.tsx delete mode 100644 solvway-admin-portal/app/wallet/page.export.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/page.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/page.tsx delete mode 100644 solvway-admin-portal/app/wallet/topups/page.reverse.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/topups/page.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/topups/page.tsx delete mode 100644 solvway-admin-portal/app/wallet/withdrawal-settings/page.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/withdrawal-settings/page.tsx delete mode 100644 solvway-admin-portal/app/wallet/withdrawals/page.export.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/withdrawals/page.test.tsx delete mode 100644 solvway-admin-portal/app/wallet/withdrawals/page.tsx delete mode 100644 solvway-admin-portal/app/warehouses/page.test.tsx delete mode 100644 solvway-admin-portal/app/warehouses/page.tsx delete mode 100644 solvway-admin-portal/docs/design/DASHBOARD-STANDARD.md delete mode 100644 solvway-admin-portal/public/brand/babyboo-logo-stacked.webp delete mode 100644 solvway-admin-portal/scripts/check-contrast.py delete mode 100644 solvway-admin-portal/test/pickDate.ts delete mode 100644 solvway-admin-portal/test/pickTime.ts delete mode 100644 solvway-admin-portal/test/readXlsx.ts delete mode 100644 solvway-admin-portal/vendor/xlsx-0.20.3.tgz diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index a929a79..0697f4b 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -31,7 +31,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 6. Admin portal -- [ ] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0. +- [x] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0. - Scope: `solvway-admin-portal/**` - [ ] 6.2 Add the `/forgot-password` page (public, linked from login) and its route handler calling `/api/admin/auth/forgot-password`, showing the fixed message for any outcome; make the users form refuse self-deactivation and show duplicate-username and lock-out errors from the API. Tests first (vitest) for each portal-visible scenario in the specs. Verify: `npm run lint && npm run build && npm test` exit 0. - Scope: `solvway-admin-portal/**` diff --git a/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md b/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md index 1f1e5a0..5485b6d 100644 --- a/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md +++ b/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md @@ -1,6 +1,6 @@ --- name: run-solvway-admin-portal -description: Build, run, and drive solvway-admin-portal (babyboo Back Office). Use when asked to start the app, run its dev server or tests, or take a screenshot of / interact with the running UI. +description: Build, run, and drive solvway-admin-portal (Co-Lite Back Office). Use when asked to start the app, run its dev server or tests, or take a screenshot of / interact with the running UI. --- All paths below are relative to `solvway-admin-portal/`. diff --git a/solvway-admin-portal/.env.example b/solvway-admin-portal/.env.example index 9041ce4..2cd469a 100644 --- a/solvway-admin-portal/.env.example +++ b/solvway-admin-portal/.env.example @@ -1,5 +1,5 @@ # ── Mobile API (BFF target) ─────────────────────────────────────────── -# Base URL of babyboo's solvway-mobile-api, no trailing slash. +# Base URL of solvway-mobile-api, no trailing slash. # Supplied per environment; there is no sensible default. MOBILE_API_BASE_URL= @@ -10,4 +10,4 @@ MOBILE_API_KEY= # ── Session ─────────────────────────────────────────────────────────── # Name of the httpOnly cookie that stores the admin JWT. -SESSION_COOKIE_NAME=bb_admin +SESSION_COOKIE_NAME=colite_admin diff --git a/solvway-admin-portal/Dockerfile b/solvway-admin-portal/Dockerfile index d5ecf6d..b17ac1f 100644 --- a/solvway-admin-portal/Dockerfile +++ b/solvway-admin-portal/Dockerfile @@ -5,7 +5,6 @@ FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ -COPY vendor/ ./vendor/ RUN npm ci # A High or Critical advisory in a runtime dependency fails the image (F45). Dev tooling is not shipped, # so it is excluded. Moderate advisories do not block; review them with a full `npm audit`. diff --git a/solvway-admin-portal/README.md b/solvway-admin-portal/README.md index ec781e0..9eeb3f1 100644 --- a/solvway-admin-portal/README.md +++ b/solvway-admin-portal/README.md @@ -1,206 +1,26 @@ -# Back-Office Template — babyboo.my +# Co-Lite Admin Portal -> **Migration in progress.** This module is being converted from a Vite SPA to a Next.js App -> Router project (see `openspec/changes/add-admin-portal-auth`). `app/` currently holds only a -> placeholder shell; the real pages, components and services below still live under `src/` — -> specifically `src/legacy-pages/` (renamed from `src/pages/` because Next.js reserves that name -> for its own Pages Router) — pending a later change that ports them into `app/*/page.tsx` with -> `react-router` calls rewired to `next/navigation`. Everything in this README describing routes, -> the mock-data architecture and theming still describes that `src/` tree. +Next.js 16 admin portal for Co-Lite. Screens call the JSON admin APIs (`/api/admin/**`) in `mobile-api` through server-side route handlers. -A reusable admin/back-office front end for MLM (multi-level marketing) clients. It ships -against mock data behind an API-shaped service layer, so a client project can swap in a real -backend without touching any page or component code. +## Run -**Currently skinned for babyboo.my** — baby & maternity retail, competing with Medela, Momcozy, -Kinderkraft and Hamilton. The audience is sleep-deprived, time-poor, highly selective parents, so -decisions are ranked clarity → speed → trust. The look is deliberately warm and soft-edged rather -than clinical: cream page, warm neutrals, brand brown `#6E3E17` with a gold `#F2BC57` accent, and a -1rem radius so nothing has a sharp corner. - -## Stack - -- [Next.js 16](https://nextjs.org/) (App Router, `output: "standalone"`) — build tool and server -- [React 19](https://react.dev/) + TypeScript (strict mode) -- [Tailwind CSS 3](https://tailwindcss.com/) via PostCSS + `tailwind.config.ts` — matches - `solvway-customer-portal`'s wiring -- [Sass](https://sass-lang.com/) — token maps and mixins in `src/styles/` (pending port into - `app/globals.css`, which currently carries a plain-CSS transliteration of the same tokens) -- [shadcn/ui](https://ui.shadcn.com/) — owned component source, themed with CSS variables -- [Recharts](https://recharts.org/) via shadcn's `chart` wrapper — dashboard charts -- [TanStack Table](https://tanstack.com/table) — data tables -- [lucide-react](https://lucide.dev/) — icons -- [react-router-dom v7](https://reactrouter.com/) — still a dependency for the not-yet-ported - `src/legacy-pages/` tree; removed once that tree is rewired to `next/navigation` -- [Vitest](https://vitest.dev/) + [React Testing Library](https://testing-library.com/react) — tests - -## Getting Started +Needs Node 24 (see `.nvmrc`). ```bash -npm install -npm run dev # next dev --port 3001 -npm test # run the full test suite (Vitest, run once) -npm run test:watch # run tests in watch mode -npm run build # next build (type-checks + production build) -npm start # next start --port 3001, after a build - -python3 scripts/check-contrast.py # verify token contrast in both themes +cp .env.example .env.local # then fill in the values below +npm ci +npm run dev # http://localhost:3001 ``` -### Auth +| Variable | Purpose | +| --- | --- | +| `MOBILE_API_BASE_URL` | Base URL of `mobile-api` | +| `MOBILE_API_KEY` | API key sent to `mobile-api` | +| `SESSION_SECRET` | Secret used to seal the session cookie | +| `SESSION_COOKIE_NAME` | Session cookie base name (default `colite_admin`) | -Login is no longer mocked. `/login` posts to the same-origin `/api/auth/login` route handler, -which proxies `solvway-mobile-api` (`app/lib/server/mobileApi.ts`) and sets an httpOnly session -cookie server-side. Signing in requires: - -- `MOBILE_API_BASE_URL` and `MOBILE_API_KEY` set (see `.env.example`), pointing at a reachable - `solvway-mobile-api` instance. -- A real `UserType.A` account in that instance's services-system. - -Without a configured Mobile API, `/login` still renders, but submitting the form reports "Mobile -API is not configured" — there is no local/offline demo login anymore. - -Visiting any other route while unauthenticated redirects back to `/login`; logging out clears the -session and returns you there as well. - -## Screen Inventory - -| Route | Page | Notes | -|---|---|---| -| `/login` | Login | Email/password with a password-reveal toggle; inline error on invalid credentials | -| `/` | Dashboard | Live KPI tiles (members, settled revenue/orders, rewards; Malaysia-time month), 12-month revenue and member-growth charts, revenue by channel, rank/status mix, rewards by type, top-earner leaderboard | -| `/members` | Members | Sortable, faceted, URL-synced member table with column visibility and CSV export | -| `/members/:id` | Member Detail | Identity header, performance strip, tabs for Sales · Commissions · Downline | -| `/reports` | Reports | Live Sales (settled orders) and Rewards tabs, Malaysia-time period presets + date range, paged, period totals, full-result-set CSV export | -| `/network` | Network | Genealogy as an indented tree or a top-down chart, with search that expands ancestors and highlights matches | - -Navigation is a **collapsible sidebar with up to three levels**: it collapses to an icon rail on -desktop (persisted per browser) and becomes an overlay drawer below `lg`. Every leaf resolves to a -real view — `Members → By rank → Diamond` applies `?rank=Diamond`, the Reports children select -`?tab=` — so none of them are decorative. - -[`src/components/app/nav-config.ts`](src/components/app/nav-config.ts) is the **contract a backend -menu endpoint would return**: plain `label` / `to` / `children` / `isDefault` data, with the icon as -the only client-side concern. `nav-config.test.ts` encodes the invariants such an endpoint must -satisfy (leaf-xor-group, depth cap, real routes, unique targets, one default per group), so a -backend implementation can be validated against the same rules the UI relies on. - -## Design Standard - -**[`docs/design/DASHBOARD-STANDARD.md`](docs/design/DASHBOARD-STANDARD.md) is authoritative.** It -defines the tokens, layout grid, KPI and chart specs, required data states, accessibility floor -(WCAG 2.1 AA) and the anti-patterns. Read it before adding a screen. Where it and a component -disagree, the component is wrong. - -## Mock-Data Architecture - -Everything under `src/services/*` is written to look and behave like a real API client: every -function is `async`, returns plain data (no framework types leak out), and pagination, filtering -and **sorting** happen the same way a backend would do them. The Dashboard and Reports are live -(`app/lib/services/adminDashboard.ts` -> BFF -> mobile-api aggregate reads); `src/services/api.ts` holds shared helpers (pagination, sorting, an -artificial network delay). - -**Pages only call functions from the other -`src/services/*` modules. This is the intended swap point: to connect a real backend, replace the -bodies of these service functions with `fetch` calls that return the same shapes (see -`src/types/index.ts`), and no page or component needs to change. - -``` -src/ - components/ - app/ # two-level sidebar + nav config - ui/ # shadcn primitives + DataTable, states, chart skeletons - dashboard/ # KPI tile, chart card (chart + its accessible table) - genealogy/ # tree view and org chart - styles/ - _variables.scss # $palettes (light + dark), breakpoints, layout, z-index - _mixins.scss # respond-to, focus-ring, tap-target, brand gradient - index.scss # emits the token blocks from the maps + base layer - tailwind.css # Tailwind entry + @theme (kept as CSS on purpose) - lib/ - theme.tsx # light/dark provider, persists to localStorage - utils.ts # cn() - services/ - api.ts # shared mock helpers (pagination, sorting, delay) - period.ts # month labels - auth.ts # login/logout/session — swap point - members.ts # list/detail/facets/stats — swap point - network.ts # genealogy tree — swap point -``` - -## Theming - -Colour lives in Sass maps in [`src/styles/_variables.scss`](src/styles/_variables.scss), emitted as -CSS custom properties by `index.scss` and exposed to Tailwind via `@theme inline` in `tailwind.css`. -**No component contains a colour literal.** - -The babyboo palette is brand brown `#6E3E17` with a gold `#F2BC57` accent on a cream page, plus warm -neutrals and a warm-espresso dark mode (not slate). - -**One thing to know about the gold:** `#F2BC57` is 1.73:1 against white, so it can only ever be a -*filled surface* carrying `--accent-foreground` text — never text, a thin indicator, or a chart -series, all of which would be invisible in light mode. Anything in the accent family that must carry -meaning uses `--accent-strong` (`#9A6212`, 5.08:1). That is why the accent is absent from the chart -ramp. - -Both themes live in the same map, so a token cannot be added to light and forgotten in dark. - -To re-skin for a client: - -1. Edit `$palettes` in `src/styles/_variables.scss` — primary, accent, chart ramp, radius. -2. Swap the font `` (was `index.html`, now belongs in `app/layout.tsx` — see the Migration - note above) and the `--font-*` tokens (now in `app/globals.css`, ported from - `src/styles/tailwind.css`). -3. Replace the wordmark in `src/components/app/app-sidebar.tsx`. -4. Run `python3 scripts/check-contrast.py`. - -### Fonts - -Headings are **Google Sans**, body and numerals are **Inter** — two families, no monospace. Numerals -use Inter's own tabular figures (`.tabular`), so columns still align while avoiding the technical -register of monospace digits, and it saves a font request. - -Fonts were linked from `index.html`'s `` tags before the Next.js conversion; the placeholder -`app/layout.tsx` does not yet re-add them (Task 6 restores the font ``s or switches to -`next/font`). If Google Sans must be self-hosted (offline builds, or a licensed -variant), `src/styles/index.scss` has a commented `@font-face` block — drop the `woff2` files into -`public/fonts/` and uncomment; the heading stack already requests the family first. DM Sans is the -fallback if it fails to load. - -Light is the default; dark is opt-in via the header toggle and persisted per browser. Note that -`--border` (dividers, decorative) and `--input` (form-control boundaries, must clear 3:1) are -deliberately different values — see the standard's §2. - -`scripts/check-contrast.py` verifies all of the above (both themes, exits non-zero on regression). -Run it after any palette edit. - -## Testing - -143 tests across 29 files (`npx vitest run`), covering the ported Next.js app under `app/`. Server-only -modules (`app/lib/server/mobileApi.ts`, the `/api/auth/*` route handlers) run under jsdom because -`vitest.config.ts` aliases `server-only` to `test/stub-empty.ts`. Client components mock -`apiGet`/`apiPost` (`app/lib/clientApi.ts`) rather than hitting a network, so UI tests don't depend -on `solvway-mobile-api` being reachable. - -Charts are asserted through the accessible data table that every chart is required to ship -(standard §6) rather than by measuring SVG — so no chart library gets stubbed, and the assertions -check real figures. - -`vitest.setup.ts` (repo root) stubs `matchMedia`, `ResizeObserver`, and the Pointer Events APIs -that Radix needs and jsdom lacks. - -## Known Issues - -- The production bundle is a single ~958 kB (288 kB gzip) chunk. That is down from 2.62 MB - (797 kB gzip) under antd, but a client project with stricter budgets should still code-split - with dynamic `import()`. -- **`sass-embedded` is pinned to 1.77.8 via an `overrides` entry in `package.json`, and removing it - will hang the build on macOS 13.** Vite auto-installs `sass-embedded` as an optional peer; from - roughly 1.83 its bundled Dart VM requires macOS 14+ and aborts with - `VM initialization failed`. Because that happens during the compiler handshake, the build hangs - rather than failing, which makes it look like an infinite loop. On macOS 14+ the pin is harmless - and can be dropped. -- In-browser visual verification across all breakpoints has not been automated. The contrast - floor is checked by script; layout at 375/768/1024/1440px still needs a human or a - browser-driver pass. +## Scripts +- `npm run build` / `npm start` production build and server (port 3001) +- `npm run lint` +- `npm test` diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts deleted file mode 100644 index 6217054..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq() { - return new Request("http://localhost/api/admin/company-accounts/MY/MYHQ00002/deactivate", { - method: "POST", - }) as unknown as Parameters[0]; -} -function ctx(prefix: string, memberCode: string) { - return { params: Promise.resolve({ prefix, memberCode }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts/[prefix]/[memberCode]/deactivate", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards to POST /api/admin/company-accounts/{prefix}/{memberCode}/deactivate", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { prefix: "MY", memberCode: "MYHQ00002", active: "N" } }); - - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/company-accounts/MY/MYHQ00002/deactivate", - { method: "POST", token: "jwt-abc" }, - ); - expect(res.status).toBe(200); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "not found", status: 404 }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(404); - }); - - // deactivate returns an empty 200 downstream (void controller). NextResponse.json(undefined) - // would 500 — the route must return a safe ok body. (Caught in live Part D verification.) - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts deleted file mode 100644 index 85c2c61..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts +++ /dev/null @@ -1,26 +0,0 @@ -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"; - -// POST -> /api/admin/company-accounts/{prefix}/{memberCode}/deactivate -// (add-admin-company-account-crud, Part C). Drops the account from the weighted split; the -// member, its network_tree row and any existing downline are left untouched — there is no hard -// delete. A mutation, so always POST, never a GET. - -export async function POST( - _req: NextRequest, - ctx: { params: Promise<{ prefix: string; memberCode: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix, memberCode } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}/${encodeURIComponent(memberCode)}/deactivate`, - { method: "POST", token }, - ); - if (!result.ok) return errorResponse(result); - // deactivate returns an empty 200 downstream (void); avoid NextResponse.json(undefined) (500). - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts deleted file mode 100644 index 519230d..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq() { - return new Request("http://localhost/api/admin/company-accounts/MY/MYHQ00002/reactivate", { - method: "POST", - }) as unknown as Parameters[0]; -} -function ctx(prefix: string, memberCode: string) { - return { params: Promise.resolve({ prefix, memberCode }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts/[prefix]/[memberCode]/reactivate", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards to POST /api/admin/company-accounts/{prefix}/{memberCode}/reactivate", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { prefix: "MY", memberCode: "MYHQ00002", active: "Y" } }); - - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/company-accounts/MY/MYHQ00002/reactivate", - { method: "POST", token: "jwt-abc" }, - ); - expect(res.status).toBe(200); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "not found", status: 404 }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(404); - }); - - // reactivate returns an empty 200 downstream (void controller); the route must not 500 on it. - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts deleted file mode 100644 index 38b6198..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts +++ /dev/null @@ -1,25 +0,0 @@ -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"; - -// POST -> /api/admin/company-accounts/{prefix}/{memberCode}/reactivate -// (add-admin-company-account-crud, Part C). Restores the account to the weighted split. A -// mutation, so always POST, never a GET. - -export async function POST( - _req: NextRequest, - ctx: { params: Promise<{ prefix: string; memberCode: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix, memberCode } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}/${encodeURIComponent(memberCode)}/reactivate`, - { method: "POST", token }, - ); - if (!result.ok) return errorResponse(result); - // reactivate returns an empty 200 downstream (void); avoid NextResponse.json(undefined) (500). - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts deleted file mode 100644 index 54eeab8..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq() { - return new Request("http://localhost/api/admin/company-accounts/MY") as unknown as Parameters< - typeof GET - >[0]; -} -function ctx(prefix: string) { - return { params: Promise.resolve({ prefix }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/company-accounts/[prefix]", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq(), ctx("MY")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT to GET /api/admin/company-accounts/{prefix} and returns the rows", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const rows = [ - { - prefix: "MY", - memberCode: "MYHQ00002", - name: "HQ Two", - weight: 50, - active: "Y", - configVersion: 3, - directDownline: 2, - allocatedCount: 10, - }, - ]; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: rows }); - - const res = await GET(getReq(), ctx("MY")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts/MY", { - token: "jwt-abc", - }); - expect(res.status).toBe(200); - expect(await res.json()).toEqual(rows); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "boom", status: 400 }); - const res = await GET(getReq(), ctx("MY")); - expect(res.status).toBe(400); - expect((await res.json()).error).toBe("boom"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts deleted file mode 100644 index dbe6507..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 { CompanyAccountRow } from "@/app/lib/types"; - -// GET -> /api/admin/company-accounts/{prefix} (add-admin-company-account-crud, Part C): the -// company accounts configured for one registration country. Read-only — no side effect on GET -// (Next.js prefetch-safe). - -export async function GET(_req: NextRequest, ctx: { params: Promise<{ prefix: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts deleted file mode 100644 index e1d0fc0..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -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, PUT } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/company-accounts", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -function putReq(body: unknown) { - return new Request("http://localhost/api/admin/company-accounts", { - method: "PUT", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("requires prefix, memberCode, name and a weight", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const body of [ - { memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }, - { prefix: "MY", name: "HQ Two", weight: 50 }, - { prefix: "MY", memberCode: "MYHQ00002", weight: 50 }, - { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two" }, - {}, - ]) { - const res = await POST(postReq(body)); - expect(res.status).toBe(400); - } - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects an email without a password (and vice versa) without forwarding", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const base = { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }; - const res1 = await POST(postReq({ ...base, email: "hq2@babyboo.my" })); - expect(res1.status).toBe(400); - const res2 = await POST(postReq({ ...base, password: "Qweqwe123" })); - expect(res2.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT and full body to POST /api/admin/company-accounts", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const body = { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }; - mocks.callMobileApi.mockResolvedValue({ - ok: true, - data: { memberId: "1", loginRequested: false, credentialCreated: false }, - }); - - const res = await POST(postReq(body)); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts", { - method: "POST", - body, - token: "jwt-abc", - }); - expect(res.status).toBe(200); - expect((await res.json()).loginRequested).toBe(false); - }); - - it("forwards a duplicate-code 4xx as-is with the downstream message", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ - ok: false, - error: "member_code already in use", - status: 409, - }); - - const res = await POST( - postReq({ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }), - ); - - expect(res.status).toBe(409); - expect((await res.json()).error).toBe("member_code already in use"); - }); -}); - -describe("PUT /api/admin/company-accounts", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await PUT(putReq({ prefix: "MY", memberCode: "MYHQ00002", weight: 75 })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("requires prefix and memberCode to locate the row", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const body of [{ memberCode: "MYHQ00002", weight: 75 }, { prefix: "MY", weight: 75 }, {}]) { - const res = await PUT(putReq(body)); - expect(res.status).toBe(400); - } - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT and full body to PUT /api/admin/company-accounts", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const body = { prefix: "MY", memberCode: "MYHQ00002", weight: 75, active: "Y" }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ...body, name: "HQ Two", configVersion: 4 } }); - - const res = await PUT(putReq(body)); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts", { - method: "PUT", - body, - token: "jwt-abc", - }); - expect(res.status).toBe(200); - }); - - // update returns an empty 200 downstream (void controller). NextResponse.json(undefined) would - // 500 — the route must return a safe ok body. (Caught in live Part D verification.) - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await PUT(putReq({ prefix: "MY", memberCode: "MYHQ00002", weight: 5 })); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/route.ts deleted file mode 100644 index 5a1b547..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/route.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { CompanyAccountCreatePayload, CompanyAccountUpdatePayload } from "@/app/lib/types"; - -// POST/PUT -> /api/admin/company-accounts (add-admin-company-account-crud, Part C). Both are -// mutations and never go out on GET (Next.js prefetch rule). Create writes the member + tree -// placement + allocation config (+ optional login) as one action; edit changes weight/active/ -// name only — memberCode/prefix locate the row and are never themselves edited. - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const body = await req.json().catch(() => ({})); - const { prefix, memberCode, name, weight, email, password } = body as Partial; - if (!prefix || !memberCode || !name || typeof weight !== "number") { - return badRequest("prefix, memberCode, name and weight are required."); - } - // The optional login travels as a pair (the anchor pattern) — one without the other is a - // malformed request, never forwarded upstream. - if (Boolean(email) !== Boolean(password)) { - return badRequest("email and password must be supplied together, or neither."); - } - - const result = await callMobileApi("/api/admin/company-accounts", { - method: "POST", - body, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} - -export async function PUT(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const body = await req.json().catch(() => ({})); - const { prefix, memberCode } = body as Partial; - if (!prefix || !memberCode) { - return badRequest("prefix and memberCode are required to locate the account."); - } - - const result = await callMobileApi("/api/admin/company-accounts", { - method: "PUT", - body, - token, - }); - if (!result.ok) return errorResponse(result); - // update returns an empty 200 downstream (void); NextResponse.json(undefined) would 500, so - // fall back to a small ok body. - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts b/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts deleted file mode 100644 index 4a5f1c7..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(search = "") { - return new Request(`http://localhost/api/admin/dashboard/event${search}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/dashboard/event", () => { - it("forwards only the event id and the admin JWT (never an operator)", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { pendingOrders: 1 } }); - const res = await GET(getReq("?eventId=7&operator=Ben")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ pendingOrders: 1 }); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/event?eventId=7", { token: "jwt-abc" }); - }); - - it("is 401 without a session and never calls mobile-api", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq("?eventId=7")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("is 400 for a missing or non-numeric event id", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - expect((await GET(getReq())).status).toBe(400); - expect((await GET(getReq("?eventId=7;drop"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes a downstream 403 through", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_DASHBOARD_EVENT module is required." }); - const res = await GET(getReq("?eventId=7")); - expect(res.status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/event/route.ts b/solvway-admin-portal/app/api/admin/dashboard/event/route.ts deleted file mode 100644 index a78d5ff..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/event/route.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; -import { badRequest } from "@/app/lib/server/apiRoute"; - -// GET -> mobile-api GET /api/admin/dashboard/event (BO_DASHBOARD_EVENT, gated upstream). Read-only, prefetch-safe. -// Only the event id is forwarded: mobile-api resolves the operator from the session, never from the client. -export function GET(req: NextRequest) { - const eventId = new URL(req.url).searchParams.get("eventId") ?? ""; - if (!/^\d+$/.test(eventId)) return badRequest("Invalid eventId parameter."); - return forwardAdminGet(req, "/api/admin/dashboard/event", ["eventId"]); -} diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts b/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts deleted file mode 100644 index f80779d..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }); - mocks.getToken.mockReset().mockResolvedValue("jwt-abc"); -}); - -describe("GET /api/admin/dashboard country", () => { - it("forwards country to mobile-api", async () => { - await GET(new Request("http://localhost/api/admin/dashboard?country=SG&evil=1") as unknown as Parameters[0]); - const url = mocks.callMobileApi.mock.calls[0][0] as string; - expect(new URL(url, "http://x").searchParams.get("country")).toBe("SG"); - expect(url).not.toContain("evil"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.test.ts b/solvway-admin-portal/app/api/admin/dashboard/route.test.ts deleted file mode 100644 index 9028c2f..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(search = "") { - return new Request(`http://localhost/api/admin/dashboard${search}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/dashboard", () => { - it("forwards only the documented params and the admin JWT", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } }); - const res = await GET(getReq("?from=2026-09-01&to=2026-09-29&evil=1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: 1 }); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard?from=2026-09-01&to=2026-09-29", { token: "jwt-abc" }); - }); - - it("is 401 without a session and never calls mobile-api", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("is 400 for a malformed date", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await GET(getReq("?from=yesterday")); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream refusal through", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "forbidden", status: 403 }); - const res = await GET(getReq()); - expect(res.status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.ts b/solvway-admin-portal/app/api/admin/dashboard/route.ts deleted file mode 100644 index e6f4edf..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; - -// GET -> mobile-api GET /api/admin/dashboard (BO_DASHBOARD). Read-only; module-gated upstream. -export const GET = (req: NextRequest) => forwardAdminGet(req, "/api/admin/dashboard", ["from", "to", "country"]); diff --git a/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts b/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts deleted file mode 100644 index c0a732a..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; -import { badRequest } from "@/app/lib/server/apiRoute"; - -// GET -> mobile-api GET /api/admin/event-summary/{eventId}?from=&to= (BO_EVENT_SUMMARY, gated upstream). Read-only. -// date is the older one-day form, still forwarded; forwardAdminGet validates from/to, date is checked here. -export async function GET(req: NextRequest, { params }: { params: Promise<{ eventId: string }> }) { - const { eventId } = await params; - if (!/^\d+$/.test(eventId)) return badRequest("Invalid eventId parameter."); - const date = new URL(req.url).searchParams.get("date"); - if (date && !/^\d{4}-\d{2}-\d{2}$/.test(date)) return badRequest("Invalid date parameter."); - return forwardAdminGet(req, `/api/admin/event-summary/${encodeURIComponent(eventId)}`, ["date", "from", "to"]); -} diff --git a/solvway-admin-portal/app/api/admin/event-summary/events/route.ts b/solvway-admin-portal/app/api/admin/event-summary/events/route.ts deleted file mode 100644 index 57ac2d6..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/events/route.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; - -// GET -> mobile-api GET /api/admin/event-summary/events (BO_EVENT_SUMMARY, gated upstream). Read-only, prefetch-safe. -export function GET(req: NextRequest) { - return forwardAdminGet(req, "/api/admin/event-summary/events", []); -} diff --git a/solvway-admin-portal/app/api/admin/event-summary/route.test.ts b/solvway-admin-portal/app/api/admin/event-summary/route.test.ts deleted file mode 100644 index 07f6218..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/route.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -// add-event-summary: the two Event Summary BFF routes are read-only pass-throughs to mobile-api. -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 as getEvents } from "./events/route"; -import { GET as getSummary } from "./[eventId]/route"; - -const req = (path: string) => new Request(`http://localhost${path}`) as unknown as Parameters[0]; -const ctx = (eventId: string) => ({ params: Promise.resolve({ eventId }) }); - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset().mockResolvedValue("jwt-abc"); -}); - -describe("GET /api/admin/event-summary/events", () => { - it("forwards to mobile-api with the admin JWT", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: [{ id: "5" }] }); - const res = await getEvents(req("/api/admin/event-summary/events")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual([{ id: "5" }]); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/events", { token: "jwt-abc" }); - }); - - it("is 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await getEvents(req("/api/admin/event-summary/events"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); - -describe("GET /api/admin/event-summary/[eventId]", () => { - it("forwards the event id and the day", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { orders: 3 } }); - const res = await getSummary(req("/api/admin/event-summary/5?date=2026-10-06&x=1"), ctx("5")); - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?date=2026-10-06", { token: "jwt-abc" }); - }); - - it("forwards without a day when none is given", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5", { token: "jwt-abc" }); - }); - - it("is 400 for a non-numeric id or a malformed day, without calling mobile-api", async () => { - expect((await getSummary(req("/api/admin/event-summary/5;x"), ctx("5;x"))).status).toBe(400); - expect((await getSummary(req("/api/admin/event-summary/5?date=06-10-2026"), ctx("5"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards a Date From / Date To range", async () => { // BABYBOO-39 - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5?from=2026-10-14&to=2026-10-16&x=1"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?from=2026-10-14&to=2026-10-16", { token: "jwt-abc" }); - }); - - it("forwards from, to and the older date together", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5?to=2026-10-16&date=2026-10-14&from=2026-10-14"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?date=2026-10-14&from=2026-10-14&to=2026-10-16", { token: "jwt-abc" }); - }); - - it("is 400 for a malformed from or to, without calling mobile-api", async () => { - expect((await getSummary(req("/api/admin/event-summary/5?from=14-10-2026"), ctx("5"))).status).toBe(400); - expect((await getSummary(req("/api/admin/event-summary/5?from=2026-10-14&to=2026-10"), ctx("5"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes a downstream 403 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_EVENT_SUMMARY module is required." }); - expect((await getSummary(req("/api/admin/event-summary/5"), ctx("5"))).status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts deleted file mode 100644 index e42f954..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -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 ctx = () => ({ params: Promise.resolve({ uuid: "12345" }) }); - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/12345/action", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/[uuid]/action", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ action: "approve", remarks: "" }), ctx()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a non-numeric uuid (path traversal) with 400 before calling upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "approve", remarks: "" }), { params: Promise.resolve({ uuid: "../../member/x" }) }); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects action=delete with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "delete", remarks: "test" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects action=pending with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "pending", remarks: "test" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects reject action with blank remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "reject", remarks: "" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects reject action with whitespace-only remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "reject", remarks: " " }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects revoke action with blank remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "revoke", remarks: "" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("accepts approve with empty remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "A" } }); - - const res = await POST(postReq({ action: "approve", remarks: "" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/approve", { - method: "POST", - body: { action: "approve", remarks: "" }, - token: "jwt-abc", - }); - }); - - it("accepts reject with non-blank remarks (≤500 chars)", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "R" } }); - - const res = await POST(postReq({ action: "reject", remarks: "Document expired on 2025-01-01" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/reject", { - method: "POST", - body: { action: "reject", remarks: "Document expired on 2025-01-01" }, - token: "jwt-abc", - }); - }); - - it("accepts revoke with remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "V" } }); - - const res = await POST(postReq({ action: "revoke", remarks: "Admin correction" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/revoke", { - method: "POST", - body: { action: "revoke", remarks: "Admin correction" }, - token: "jwt-abc", - }); - }); - - it("rejects remarks > 500 chars", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const longRemarks = "x".repeat(501); - const res = await POST(postReq({ action: "reject", remarks: longRemarks }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts deleted file mode 100644 index 8769a47..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { AdminKycRow } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/{uuid}/action { action, remarks } (BO_KYC gated upstream; a mutation, -// never a GET). action ∈ { approve, reject, revoke }. reject/revoke require non-blank remarks ≤ 500 chars. - -const ALLOWED_ACTIONS = new Set(["approve", "reject", "revoke"]); - -export async function POST(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { uuid } = await ctx.params; - // uuid is a Snowflake id carried as a string; anything else never reaches the upstream path. - if (!/^\d+$/.test(uuid)) return badRequest("Parameter \"uuid\" is invalid"); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { action, remarks } = (body ?? {}) as { action?: unknown; remarks?: unknown }; - - if (typeof action !== "string" || !ALLOWED_ACTIONS.has(action)) { - return badRequest("Parameter \"action\" must be one of: approve, reject, revoke"); - } - - const remarksStr = typeof remarks === "string" ? remarks : ""; - - // reject/revoke require non-blank remarks, max 500 chars. - if ((action === "reject" || action === "revoke") && !remarksStr.trim()) { - return badRequest("Remarks are required for this action"); - } - if (remarksStr.length > 500) { - return badRequest("Remarks must not exceed 500 characters"); - } - - const result = await callMobileApi(`/api/admin/kyc/${encodeURIComponent(uuid)}/${action}`, { - method: "POST", - body: { action, remarks: remarksStr }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts deleted file mode 100644 index 99972bf..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ getToken: vi.fn() })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function req(url = "http://localhost/api/admin/kyc/12345/doc/ID_FRONT") { - const u = new URL(url); - return { nextUrl: u } as unknown as Parameters[0]; -} -const ctx = (uuid = "12345", docType = "ID_FRONT") => ({ params: Promise.resolve({ uuid, docType }) }); - -const originalFetch = global.fetch; - -beforeEach(() => { - mocks.getToken.mockReset(); - process.env.MOBILE_API_BASE_URL = "http://gateway"; - process.env.MOBILE_API_KEY = "secret-key"; -}); -afterEach(() => { - global.fetch = originalFetch; -}); - -describe("GET /api/admin/kyc/[uuid]/doc/[docType]", () => { - it("returns 401 without a session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx()); - expect(res.status).toBe(401); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("rejects docType=PASSPORT with 400 and never calls upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "PASSPORT")); - - expect(res.status).toBe(400); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("rejects docType=DRIVING_LICENSE with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "DRIVING_LICENSE")); - - expect(res.status).toBe(400); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("returns upstream bytes with no-store for allowed docTypes", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const imgBytes = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0]); // JPEG marker - const upstream = new Response(imgBytes, { - status: 200, - headers: { "content-type": "image/jpeg" }, - }); - const fetchSpy = vi.fn().mockResolvedValue(upstream); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "ID_FRONT")); - - expect(res.status).toBe(200); - expect(res.headers.get("Cache-Control")).toBe("no-store"); - expect(res.headers.get("content-type")).toBe("image/jpeg"); - const body = new Uint8Array(await res.arrayBuffer()); - expect(Array.from(body)).toEqual([0xFF, 0xD8, 0xFF, 0xE0]); - }); - - it("returns upstream bytes for SELFIE", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const pngBytes = new Uint8Array([0x89, 0x50, 0x4E, 0x47]); - const upstream = new Response(pngBytes, { - status: 200, - headers: { "content-type": "image/png" }, - }); - const fetchSpy = vi.fn().mockResolvedValue(upstream); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("67890", "SELFIE")); - - expect(res.status).toBe(200); - const body = new Uint8Array(await res.arrayBuffer()); - expect(Array.from(body)).toEqual([0x89, 0x50, 0x4E, 0x47]); - }); - - // F20: the proxy is served from the admin origin with the admin's cookie; a stored non-image type must never render - it("never passes a non-image upstream type through, and forbids sniffing", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const type of ["text/html", "image/svg+xml", "application/xhtml+xml", "text/html; charset=utf-8"]) { - global.fetch = vi.fn().mockResolvedValue( - new Response("", { status: 200, headers: { "content-type": type } }), - ) as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "SELFIE")); - - expect(res.headers.get("content-type")).toBe("application/octet-stream"); - expect(res.headers.get("x-content-type-options")).toBe("nosniff"); - } - }); - - it("keeps an image type and forbids sniffing", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - global.fetch = vi.fn().mockResolvedValue( - new Response(new Uint8Array([1]), { status: 200, headers: { "content-type": "Image/PNG; foo=bar" } }), - ) as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "ID_BACK")); - - expect(res.headers.get("content-type")).toBe("image/png"); - expect(res.headers.get("x-content-type-options")).toBe("nosniff"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts deleted file mode 100644 index 67324f7..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { SAFE_BINARY_HEADERS, safeContentType } from "@/app/lib/server/binaryProxy"; -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { unauthorized } from "@/app/lib/server/apiRoute"; -import { isTraversalPath } from "@/app/lib/server/upstreamPathGuard"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// GET -> mobile-api GET /api/admin/kyc/{uuid}/doc/{docType} — streams KYC document image bytes. -// A binary proxy: callMobileApi normalizes JSON, so this route does a raw fetch and passes the -// image bytes + Content-Type through. Authorization is the BO_KYC module grant, enforced -// server-side by mobile-api. Read-only — no side effect on GET (Next.js prefetch-safe). -// Allowed docTypes: ID_FRONT, ID_BACK, SELFIE. - -const TIMEOUT_MS = 30_000; - -const ALLOWED_DOC_TYPES = new Set(["ID_FRONT", "ID_BACK", "SELFIE"]); - -function jsonError(message: string, status: number) { - return NextResponse.json({ error: message }, { status }); -} - -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string; docType: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { docType, uuid } = await ctx.params; - - // Only allow known doc types — never call upstream with an arbitrary path segment. - if (!/^\d+$/.test(uuid)) return jsonError("Invalid uuid", 400); - if (!ALLOWED_DOC_TYPES.has(docType)) { - return jsonError(`Unsupported doc type: ${encodeURIComponent(docType)}`, 400); - } - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return jsonError("Mobile API is not configured", 500); - - // Fetched directly, so callMobileApi's dot-segment guard is applied here too. - const path = `/api/admin/kyc/${encodeURIComponent(uuid)}/doc/${encodeURIComponent(docType)}`; - if (isTraversalPath(path)) return jsonError("Invalid uuid", 400); - const forwardedIp = await forwardedClientIpHeaders(); - const url = `${base}${path}`; - - let res: Response; - try { - res = await fetch(url, { - method: "GET", - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return jsonError("Couldn't reach the KYC service", 502); - } - - if (!res.ok) { - if (res.status === 401) return unauthorized(); - if (res.status === 404) return jsonError("Document not found.", 404); - if (res.status === 403) return jsonError("Not authorized.", 403); - if (res.status >= 500) return jsonError("The KYC service failed.", 502); - return jsonError("Couldn't download the document.", 400); - } - - const body = await res.arrayBuffer(); - const headers = new Headers({ - // KYC documents are JPEG or PNG only (mobile-api KycUploadRules); F20: nothing else renders on this origin - "Content-Type": safeContentType(res.headers.get("content-type"), ["image/jpeg", "image/png"]), - "Cache-Control": "no-store", - ...SAFE_BINARY_HEADERS, - }); - const disposition = res.headers.get("content-disposition"); - if (disposition) headers.set("Content-Disposition", disposition); - return new NextResponse(body, { status: 200, headers }); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts deleted file mode 100644 index 4b68b17..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/12345") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/[uuid]", () => { - it("rejects a non-numeric uuid with 400 before calling upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await GET(getReq(), { params: Promise.resolve({ uuid: "abc" }) }); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq(), { params: Promise.resolve({ uuid: "12345" }) }); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards uuid to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ - ok: true, - data: { record: {}, docTypes: [], member: {}, history: [], warnings: [] }, - }); - - await GET(getReq(), { params: Promise.resolve({ uuid: "12345" }) }); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345", { token: "jwt-abc" }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts deleted file mode 100644 index 3ec4a60..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute"; -import type { AdminKycDetail } from "@/app/lib/types"; - -// GET -> /api/admin/kyc/{uuid} (read-only; BO_KYC gated upstream). - -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { uuid } = await ctx.params; - // uuid is a Snowflake id carried as a string; anything else never reaches the upstream path. - if (!/^\d+$/.test(uuid)) return badRequest("Parameter \"uuid\" is invalid"); - const result = await callMobileApi(`/api/admin/kyc/${encodeURIComponent(uuid)}`, { - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts deleted file mode 100644 index 3e4f78f..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/counts") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/counts", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - }); - - it("forwards to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { P: 1, A: 2, R: 0, V: 0, ALL: 3 } }); - - const res = await GET(getReq()); - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/counts", { token: "jwt-abc" }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/counts/route.ts b/solvway-admin-portal/app/api/admin/kyc/counts/route.ts deleted file mode 100644 index 3b7e1f7..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/counts/route.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 { AdminKycCounts } from "@/app/lib/types"; - -// GET -> /api/admin/kyc/counts (read-only; BO_KYC gated upstream). - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const result = await callMobileApi("/api/admin/kyc/counts", { token }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts deleted file mode 100644 index 08d66ce..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/export") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/export", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - }); - - it("forwards query params (minus page/size) to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] }); - - await GET(getReq("http://localhost/api/admin/kyc/export?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=10")); - - // page/size should be absent from the export call - const [path] = mocks.callMobileApi.mock.calls[0]; - expect(path).toContain("status=P"); - expect(path).toContain("q=ahmad"); - expect(path).not.toContain("page="); - expect(path).not.toContain("size="); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/export/route.ts b/solvway-admin-portal/app/api/admin/kyc/export/route.ts deleted file mode 100644 index 77b89c0..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/export/route.ts +++ /dev/null @@ -1,30 +0,0 @@ -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 { TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; - -// GET -> /api/admin/kyc/export?status=&q=&from=&to=&channel= (same filters as list but no page/size; read-only; BO_KYC gated upstream). - -const QUERY = { - status: TEXT, - q: TEXT, - from: TEXT, - to: TEXT, - channel: TEXT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - // Export does NOT carry page/size, so they are not in its allow-list. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/kyc/export${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/route.test.ts deleted file mode 100644 index 531b063..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/route.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards query params to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0, page: 0, size: 10 } }); - - await GET(getReq("http://localhost/api/admin/kyc?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=20")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/kyc?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=20", - { token: "jwt-abc" }, - ); - }); - - it("omits absent query params", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0, page: 0, size: 10 } }); - - await GET(getReq()); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc", { token: "jwt-abc" }); - }); - - it("returns 200 on success", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const payload = { content: [], totalElements: 0, page: 0, size: 10 }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: payload }); - - const res = await GET(getReq()); - expect(res.status).toBe(200); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/route.ts b/solvway-admin-portal/app/api/admin/kyc/route.ts deleted file mode 100644 index 9fe50da..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/route.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; -import type { AdminKycPage } from "@/app/lib/types"; - -// GET -> /api/admin/kyc?status=&q=&from=&to=&channel=&page=&size= (read-only; BO_KYC gated upstream). - -const QUERY = { - status: TEXT, - q: TEXT, - from: TEXT, - to: TEXT, - channel: TEXT, - ...paging(500), - ...SORT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/kyc${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts deleted file mode 100644 index d35a14a..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/submit", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/submit", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST( - postReq({ - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }), - ); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the submit body to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "999", status: "P" } }); - - const res = await POST( - postReq({ - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }), - ); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/submit", { - method: "POST", - body: { - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }, - token: "jwt-abc", - }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/submit/route.ts b/solvway-admin-portal/app/api/admin/kyc/submit/route.ts deleted file mode 100644 index 0b242bd..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/submit/route.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { AdminKycRow } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/submit { memberCode, submitName, identityType, identityNo, docs } -// (BO_KYC gated upstream; a mutation, never a GET). - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { memberCode, submitName, identityType, identityNo, docs } = (body ?? {}) as { - memberCode?: unknown; - submitName?: unknown; - identityType?: unknown; - identityNo?: unknown; - docs?: unknown; - }; - - if (typeof memberCode !== "string" || !memberCode) { - return badRequest("Parameter \"memberCode\" is required"); - } - if (typeof submitName !== "string" || !submitName) { - return badRequest("Parameter \"submitName\" is required"); - } - if (typeof identityType !== "string" || !identityType) { - return badRequest("Parameter \"identityType\" is required"); - } - if (typeof identityNo !== "string" || !identityNo) { - return badRequest("Parameter \"identityNo\" is required"); - } - - const result = await callMobileApi("/api/admin/kyc/submit", { - method: "POST", - body: { memberCode, submitName, identityType, identityNo, docs }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts deleted file mode 100644 index b638417..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/upload", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/upload", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "data" })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the upload body to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { reference: "ref-123" } }); - - const res = await POST( - postReq({ memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "base64data" }), - ); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/upload", { - method: "POST", - body: { memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "base64data" }, - token: "jwt-abc", - }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/upload/route.ts b/solvway-admin-portal/app/api/admin/kyc/upload/route.ts deleted file mode 100644 index aa362db..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/upload/route.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { KycUploadResult } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/upload { memberCode, docType, fileType, base } (BO_KYC gated upstream; -// a mutation, never a GET). - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { memberCode, docType, fileType, base } = (body ?? {}) as { - memberCode?: unknown; - docType?: unknown; - fileType?: unknown; - base?: unknown; - }; - - if (typeof memberCode !== "string" || !memberCode) { - return badRequest("Parameter \"memberCode\" is required"); - } - - const result = await callMobileApi("/api/admin/kyc/upload", { - method: "POST", - body: { memberCode, docType, fileType, base }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts b/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts deleted file mode 100644 index aea8e9e..0000000 --- a/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(qs: string) { - return new Request(`http://localhost/api/admin/member-corrections${qs}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/member-corrections", () => { - it("forwards the query string with the admin JWT and returns the page", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const page = { content: [], totalElements: 0 }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: page }); - - const res = await GET(getReq("?type=RANK&memberCode=MY1&page=1&size=20")); - - expect(res.status).toBe(200); - expect(await res.json()).toEqual(page); - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/member-corrections?type=RANK&memberCode=MY1&page=1&size=20", - { token: "jwt-abc" }, - ); - }); - - it("forwards no query string when there is none", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } }); - - await GET(getReq("")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/member-corrections", { token: "jwt-abc" }); - }); - - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - - const res = await GET(getReq("")); - - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/member-corrections/route.ts b/solvway-admin-portal/app/api/admin/member-corrections/route.ts deleted file mode 100644 index 955d6b7..0000000 --- a/solvway-admin-portal/app/api/admin/member-corrections/route.ts +++ /dev/null @@ -1,33 +0,0 @@ -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 { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; -import type { AdminMemberCorrectionPage } from "@/app/lib/types"; - -// GET -> /api/admin/member-corrections (BABYBOO-43): admin rank and referral corrections, newest -// first. Forwards the query string (type, memberCode, from, to, page, size) with the bb_admin JWT. Read-only — -// no side effect on GET (Next.js prefetch-safe). BO_RANK_REFERRAL is enforced upstream. - -const QUERY = { - type: TEXT, - memberCode: TEXT, - from: TEXT, - to: TEXT, - ...paging(500), - ...SORT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/member-corrections${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts deleted file mode 100644 index f1ce24c..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { unauthorized } from "@/app/lib/server/apiRoute"; -import { expiredSignal, isId } from "@/app/lib/server/messagesProxy"; -import { isTraversalPath } from "@/app/lib/server/upstreamPathGuard"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// GET -> mobile-api GET /api/admin/member-messages/{uuid}/messages/{messageUuid}/images/{index}: streams a -// private message image. Raw fetch (callMobileApi normalises JSON). Side-effect free, so prefetch-safe. -const TIMEOUT_MS = 120_000; // covers the piped body too, so a slow link can finish a 5 MB image -const IMAGE_TYPES = new Set(["image/jpeg", "image/png"]); -const err = (message: string, status: number) => NextResponse.json({ error: message }, { status }); - -export async function GET( - _req: NextRequest, - ctx: { params: Promise<{ uuid: string; messageUuid: string; index: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - const { uuid, messageUuid, index } = await ctx.params; - if (!isId(uuid) || !isId(messageUuid) || !/^\d{1,2}$/.test(index)) return err("Invalid image reference", 400); - // Fetched directly, so callMobileApi's dot-segment guard is applied here too. - const path = `/api/admin/member-messages/${encodeURIComponent(uuid)}/messages/${encodeURIComponent(messageUuid)}/images/${encodeURIComponent(index)}`; - if (isTraversalPath(path)) return err("Invalid image reference", 400); - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return err("Mobile API is not configured", 500); - - const forwardedIp = await forwardedClientIpHeaders(); - - let res: Response; - try { - res = await fetch(`${base}${path}`, { - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return err("Couldn't reach the messaging service", 502); - } - if (!res.ok) { - if (expiredSignal(res.status, await res.text().catch(() => ""))) return unauthorized(); - if (res.status === 404) return err("Image not found.", 404); - if (res.status === 403) return err("Not authorized.", 403); - return err("Couldn't load the image.", res.status >= 500 ? 502 : 400); - } - // Served from the origin that holds the admin session: never pass an upstream type through unchecked. - const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase(); - return new NextResponse(res.body, { - status: 200, - headers: { - "Content-Type": IMAGE_TYPES.has(type) ? type : "application/octet-stream", - "Cache-Control": "private, no-store", - "X-Content-Type-Options": "nosniff", - }, - }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts deleted file mode 100644 index af48bf8..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -type Ctx = { params: Promise<{ uuid: string }> }; - -// GET -> /api/admin/member-messages/{uuid}/messages?before=&size= POST -> same path { body, imageRefs }. -export async function GET(req: NextRequest, ctx: Ctx) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/messages`, "GET", { query: ["before", "size"] }); -} - -export async function POST(req: NextRequest, ctx: Ctx) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/messages`, "POST", { body: true }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts deleted file mode 100644 index 3ed8a98..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// POST -> mobile-api POST /api/admin/member-messages/{uuid}/read (a mutation, never a GET). -export async function POST(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/read`, "POST"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts deleted file mode 100644 index 265e8e2..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/{uuid}. -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}`, "GET"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts deleted file mode 100644 index bfbdc56..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts/{broadcastUuid}/recipients?unreadOnly=&page=&size=. -export async function GET(req: NextRequest, ctx: { params: Promise<{ broadcastUuid: string }> }) { - const { broadcastUuid } = await ctx.params; - if (!isId(broadcastUuid)) return badRequest('Parameter "broadcastUuid" is invalid'); - return relay(req, `/broadcasts/${encodeURIComponent(broadcastUuid)}/recipients`, "GET", { query: ["unreadOnly", "page", "size", "sortBy", "sortDir"] }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts deleted file mode 100644 index f4e5302..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts/{broadcastUuid}. -export async function GET(req: NextRequest, ctx: { params: Promise<{ broadcastUuid: string }> }) { - const { broadcastUuid } = await ctx.params; - if (!isId(broadcastUuid)) return badRequest('Parameter "broadcastUuid" is invalid'); - return relay(req, `/broadcasts/${encodeURIComponent(broadcastUuid)}`, "GET"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts deleted file mode 100644 index cb162c6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// POST -> mobile-api POST /api/admin/member-messages/broadcasts/preview { target }. -export const POST = (req: NextRequest) => relay(req, "/broadcasts/preview", "POST", { body: true }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts deleted file mode 100644 index b2c5fc6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts (q, sortBy, sortDir, page, size): one summary row per broadcast. -export const GET = (req: NextRequest) => - relay(req, "/broadcasts", "GET", { query: ["q", "sortBy", "sortDir", "page", "size"] }); - -// POST -> mobile-api POST /api/admin/member-messages/broadcasts { target, subject, body, imageRefs }. -export const POST = (req: NextRequest) => relay(req, "/broadcasts", "POST", { body: true }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts b/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts deleted file mode 100644 index bf17bc6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/by-key (query forwarded: member). -export const GET = (req: NextRequest) => relay(req, "/by-key", "GET", { query: ["member"] }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/images/route.ts b/solvway-admin-portal/app/api/admin/member-messages/images/route.ts deleted file mode 100644 index 78db3b4..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/images/route.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, unauthorized } from "@/app/lib/server/apiRoute"; -import { codeOf, codeResponse, expiredSignal } from "@/app/lib/server/messagesProxy"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// POST multipart { file } -> mobile-api POST /api/admin/member-messages/images -> { ref }. TWO-STEP upload: -// the ref is committed by mobile-api when the message is sent (abandoned uploads are reaped, intended). -const ALLOWED = new Set(["image/jpeg", "image/png"]); -const MAX_BYTES = 5 * 1024 * 1024; -const TIMEOUT_MS = 30_000; - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - // Refuse an oversized declared body before buffering it (formData() reads everything into memory). - if (Number(req.headers?.get("content-length") ?? 0) > MAX_BYTES + 64 * 1024) { - return badRequest("Image must be 5 MB or smaller", { code: "MESSAGE_INVALID" }); - } - - let file: unknown; - try { - file = (await req.formData()).get("file"); - } catch { - return badRequest("Invalid request body"); - } - if (!(file instanceof File)) return badRequest('Parameter "file" is required'); - if (!ALLOWED.has(file.type)) return badRequest("Only JPEG or PNG images are allowed", { code: "MESSAGE_INVALID" }); - if (file.size > MAX_BYTES) return badRequest("Image must be 5 MB or smaller", { code: "MESSAGE_INVALID" }); - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return NextResponse.json({ error: "Mobile API is not configured" }, { status: 500 }); - - const forwardedIp = await forwardedClientIpHeaders(); - - const form = new FormData(); - form.set("file", file, file.name); - let res: Response; - try { - res = await fetch(`${base}/api/admin/member-messages/images`, { - method: "POST", - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, // no Content-Type: fetch sets the boundary - body: form, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return NextResponse.json({ error: "Couldn't reach the messaging service" }, { status: 502 }); - } - const text = await res.text(); - let data: Record = {}; - try { - data = text ? JSON.parse(text) : {}; - } catch { - /* non-JSON upstream body: fall through to the generic message */ - } - if (!res.ok) { - if (expiredSignal(res.status, text)) return unauthorized(); - const code = codeOf(text); // matches the code field or a reason text that carries it - if (code) return codeResponse(code); - const message = (data.detail as string) || (data.message as string) || (data.error as string) || "Upload failed"; - const status = res.status >= 400 && res.status < 500 ? res.status : 502; - return NextResponse.json({ error: message }, { status }); - } - // A 200 without a ref would let the UI send a message pointing at nothing. - if (typeof data.ref !== "string") return NextResponse.json({ error: "Upload failed" }, { status: 502 }); - return NextResponse.json({ ref: data.ref }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/route.ts b/solvway-admin-portal/app/api/admin/member-messages/route.ts deleted file mode 100644 index 77ae2d5..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages (query forwarded: types, unreadOnly, q, page, size). -export const GET = (req: NextRequest) => relay(req, "", "GET", { query: ["types", "unreadOnly", "q", "page", "size", "sortBy", "sortDir"] }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts b/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts deleted file mode 100644 index a5406d1..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import type { NextRequest } from "next/server"; - -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 as listBroadcasts } from "./broadcasts/route"; -import { GET as summary } from "./broadcasts/[broadcastUuid]/route"; -import { GET as recipients } from "./broadcasts/[broadcastUuid]/recipients/route"; - -// BABYBOO-56 broadcast read count: read-only BFF relays. -const B = "http://localhost/api/admin/member-messages"; -const req = (url: string) => new Request(url, { method: "GET" }) as unknown as NextRequest; -const ctx = (broadcastUuid: string) => ({ params: Promise.resolve({ broadcastUuid }) }); -const lastCall = () => { - const [url, opts] = mocks.callMobileApi.mock.calls.at(-1)!; - const [path, qs = ""] = String(url).split("?"); - return { path, sp: new URLSearchParams(qs), opts }; -}; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { fine: 1 } }); - mocks.getToken.mockReset().mockResolvedValue("jwt"); - process.env.MOBILE_API_BASE_URL = "http://up"; - process.env.MOBILE_API_KEY = "k"; -}); - -describe("GET broadcasts summaries relay", () => { - it("forwards q, page and size to mobile-api with the session token", async () => { - const res = await listBroadcasts(req(`${B}/broadcasts?q=raya&page=1&size=20`)); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, sp, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts"); - expect([sp.get("q"), sp.get("page"), sp.get("size")]).toEqual(["raya", "1", "20"]); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await listBroadcasts(req(`${B}/broadcasts?page=0&size=20`))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Something odd", status: 500 }); - expect((await listBroadcasts(req(`${B}/broadcasts?page=0&size=20`))).status).toBeGreaterThanOrEqual(400); - }); -}); - -describe("GET broadcast recipients relay", () => { - it("forwards the uuid, unreadOnly, page and size", async () => { - const res = await recipients(req(`${B}/broadcasts/b1/recipients?unreadOnly=true&page=2&size=20`), ctx("b1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, sp, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts/b1/recipients"); - expect([sp.get("unreadOnly"), sp.get("page"), sp.get("size")]).toEqual(["true", "2", "20"]); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await recipients(req(`${B}/broadcasts/b1/recipients`), ctx("b1"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a path-like broadcast id before any upstream call", async () => { - const res = await recipients(req(`${B}/broadcasts/x/recipients`), ctx("../admin")); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream 404 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Broadcast not found", status: 404 }); - expect((await recipients(req(`${B}/broadcasts/b1/recipients`), ctx("b1"))).status).toBe(404); - }); -}); - -describe("GET single broadcast summary relay", () => { - it("forwards the uuid to mobile-api with the session token", async () => { - const res = await summary(req(`${B}/broadcasts/b1`), ctx("b1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts/b1"); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await summary(req(`${B}/broadcasts/b1`), ctx("b1"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a path-like broadcast id with 400 before any upstream call", async () => { - expect((await summary(req(`${B}/broadcasts/x`), ctx("../admin"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream 404 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Broadcast not found", status: 404 }); - expect((await summary(req(`${B}/broadcasts/b1`), ctx("b1"))).status).toBe(404); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts b/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts deleted file mode 100644 index 8c2e4cd..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import type { NextRequest } from "next/server"; - -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 as list } from "./route"; -import { GET as byKey } from "./by-key/route"; -import { GET as messages } from "./[uuid]/messages/route"; -import { POST as upload } from "./images/route"; -import { GET as image } from "./[uuid]/messages/[messageUuid]/images/[index]/route"; - -const B = "http://localhost/api/admin/member-messages"; -const get = (url: string) => new Request(url) as unknown as NextRequest; -const img = (messageUuid = "m1") => ({ params: Promise.resolve({ uuid: "c1", messageUuid, index: "0" }) }); -const formReq = (fd: FormData, headers: Record = {}) => - ({ headers: new Headers(headers), formData: async () => fd }) as unknown as NextRequest; -const pngForm = () => { - const fd = new FormData(); - fd.append("file", new File(["abc"], "a.png", { type: "image/png" })); - return fd; -}; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }); - mocks.getToken.mockReset().mockResolvedValue("jwt"); - process.env.MOBILE_API_BASE_URL = "http://up"; - process.env.MOBILE_API_KEY = "k"; -}); -afterEach(() => vi.unstubAllGlobals()); - -describe("query whitelist", () => { - it("forwards only the documented query keys", async () => { - await list(get(`${B}?types=S&q=x&page=1&size=20&unreadOnly=true&reader=M:MY3&adminUsername=eve`)); - await byKey(get(`${B}/by-key?member=MY5&reader=M:MY3`)); - await messages(get(`${B}/c1/messages?before=m9&size=30&reader=M:MY3`), { params: Promise.resolve({ uuid: "c1" }) }); - const urls = mocks.callMobileApi.mock.calls.map((c) => c[0] as string); - expect(urls[0]).toBe("/api/admin/member-messages?types=S&unreadOnly=true&q=x&page=1&size=20"); - expect(urls[1]).toBe("/api/admin/member-messages/by-key?member=MY5"); - expect(urls[2]).toBe("/api/admin/member-messages/c1/messages?before=m9&size=30"); - }); - - it("passes a module-denied 403 through for the blocked state", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_MEMBER_MESSAGES module is required." }); - const res = await list(get(B)); - expect(res.status).toBe(403); - }); -}); - -describe("upload", () => { - it("refuses a declared body far over 5 MB before reading it", async () => { - const formData = vi.fn(); - const fetchMock = vi.fn(); - vi.stubGlobal("fetch", fetchMock); - const res = await upload({ headers: new Headers({ "content-length": String(7 * 1024 * 1024) }), formData } as unknown as NextRequest); - expect(res.status).toBe(400); - expect(formData).not.toHaveBeenCalled(); - expect(fetchMock).not.toHaveBeenCalled(); - }); - - it("forwards the file under the `file` field", async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ref: "messages/admin/1.png" }), { status: 200 })); - vi.stubGlobal("fetch", fetchMock); - const res = await upload(formReq(pngForm())); - expect(await res.json()).toEqual({ ref: "messages/admin/1.png" }); - expect((fetchMock.mock.calls[0][1].body as FormData).get("file")).toBeInstanceOf(File); - }); - - it("answers 502 when a 200 reply has no ref", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("", { status: 200 }))); - expect((await upload(formReq(pngForm()))).status).toBe(502); - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", { status: 200 }))); - expect((await upload(formReq(pngForm()))).status).toBe(502); - }); - - it("maps mobile-api's expired-token 500 to 401", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("JWT expired token", { status: 500 }))); - expect((await upload(formReq(pngForm()))).status).toBe(401); - }); -}); - -describe("image stream", () => { - it("never serves a non-image type as-is and sets nosniff", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("" } }); - fireEvent.click(screen.getByRole("button", { name: "Show editor" })); - const last = onChange.mock.calls.at(-1)?.[0] as string; - expect(last).toContain("

Pasted

"); - expect(last).not.toContain("script"); - }); - - it("passes HTML typed in Show HTML to the form before switching back", async () => { - const { onChange } = await mount("

x

"); - fireEvent.click(screen.getByRole("button", { name: "Show HTML" })); - fireEvent.change(screen.getByLabelText("HTML source"), { target: { value: "

Pasted

" } }); - expect(onChange).toHaveBeenLastCalledWith("

Pasted

"); - }); - - it("refuses a non-https YouTube link", async () => { - const { onChange } = await mount("

x

"); - const prompt = vi.spyOn(window, "prompt").mockReturnValueOnce("http://www.youtube.com/watch?v=dQw4w9WgXcQ"); - fireEvent.click(screen.getByRole("button", { name: "YouTube video" })); - expect(onChange).not.toHaveBeenCalled(); - prompt.mockRestore(); - }); - - it("emits an empty string when the text is cleared", async () => { - const { container, onChange } = await mount("

x

"); - act(() => { editorOf(container).commands.clearContent(true); }); - expect(onChange).toHaveBeenLastCalledWith(""); - }); - - it("keeps an image-only document", async () => { - const { container, onChange } = await mount("

x

"); - act(() => { editorOf(container).commands.setContent('', { emitUpdate: true }); }); - expect(onChange.mock.calls.at(-1)?.[0]).toContain(' { - const { container } = await mount("## Head\n\n- one"); - expect(container.querySelector(".ProseMirror h2")?.textContent).toBe("Head"); - expect(container.querySelector(".ProseMirror li")?.textContent).toBe("one"); - }); - - it("loads a value that arrives after mount", async () => { - const onChange = vi.fn(); - const { container, rerender } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - rerender(); - await waitFor(() => expect(container.querySelector(".ProseMirror")?.textContent).toBe("Loaded")); - expect(onChange).not.toHaveBeenCalled(); - }); - - it("disables editing when disabled", async () => { - const { container } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - expect(container.querySelector(".ProseMirror")?.getAttribute("contenteditable")).toBe("false"); - expect(screen.getByRole("button", { name: "Bold" })).toBeDisabled(); - }); - it("uploads a picked image and inserts it", async () => { - const onChange = vi.fn(); - const onUploadImage = vi.fn().mockResolvedValue("https://s3.test/bucket/product/1.png"); - const { container } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - const file = new File(["png"], "a.png", { type: "image/png" }); - fireEvent.change(screen.getByLabelText("Upload image"), { target: { files: [file] } }); - await waitFor(() => expect(onChange.mock.calls.at(-1)?.[0]).toContain('src="https://s3.test/bucket/product/1.png"')); - expect(onUploadImage).toHaveBeenCalledWith(file); - }); - - it("shows an upload error and inserts nothing when the upload fails", async () => { - const onChange = vi.fn(); - const onUploadImage = vi.fn().mockRejectedValue(new Error("Upload failed")); - const { container } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - fireEvent.change(screen.getByLabelText("Upload image"), { target: { files: [new File(["x"], "a.png", { type: "image/png" })] } }); - expect(await screen.findByText("Upload failed")).toBeInTheDocument(); - expect(onChange).not.toHaveBeenCalled(); - }); - - it("flags an off-site image and leaves trusted ones alone", async () => { - render( -

'} - onChange={vi.fn()} - onUploadImage={vi.fn()} - trustedImageHosts={["s3.test"]} - />, - ); - expect(await screen.findByText(/cdn\.shopify\.com\/a\.png/)).toBeInTheDocument(); - expect(screen.queryByText(/s3\.test\/bucket\/b\.png/)).not.toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Re-upload to Babyboo" })).toBeInTheDocument(); - }); - - it("re-uploads an off-site image and swaps its src", async () => { - const onChange = vi.fn(); - const onUploadImage = vi.fn().mockResolvedValue("https://s3.test/bucket/product/9.png"); - // jsdom's Response cannot wrap a Blob, so stub only what the editor reads. - const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({ - ok: true, - blob: async () => new Blob(["png"], { type: "image/png" }), - } as Response); - render( -

'} onChange={onChange} - onUploadImage={onUploadImage} trustedImageHosts={["s3.test"]} />, - ); - fireEvent.click(await screen.findByRole("button", { name: "Re-upload to Babyboo" })); - await waitFor(() => expect(onChange.mock.calls.at(-1)?.[0]).toContain('src="https://s3.test/bucket/product/9.png"')); - expect(onChange.mock.calls.at(-1)?.[0]).not.toContain("cdn.shopify.com"); - expect((onUploadImage.mock.calls[0][0] as File).type).toBe("image/png"); - await waitFor(() => expect(screen.queryByRole("button", { name: "Re-upload to Babyboo" })).not.toBeInTheDocument()); - fetchMock.mockRestore(); - }); - - it("shows the manual fallback when the fetch fails", async () => { - const onChange = vi.fn(); - const fetchMock = vi.spyOn(globalThis, "fetch").mockRejectedValue(new TypeError("Failed to fetch")); - render( -

'} onChange={onChange} - onUploadImage={vi.fn()} trustedImageHosts={["s3.test"]} />, - ); - fireEvent.click(await screen.findByRole("button", { name: "Re-upload to Babyboo" })); - expect(await screen.findByText(/Couldn't copy this image/)).toBeInTheDocument(); - expect(onChange).not.toHaveBeenCalled(); - fetchMock.mockRestore(); - }); - - it("hides the image button when no upload function is given", async () => { - await mount("

x

"); - expect(screen.queryByLabelText("Upload image")).not.toBeInTheDocument(); - }); - - it("places Image between Link and YouTube when uploads are enabled", async () => { - const { container } = render(); - await waitFor(() => expect(container.querySelector(".ProseMirror")).not.toBeNull()); - const names = screen.getAllByRole("button").map((b) => b.getAttribute("aria-label")); - expect(names.slice(names.indexOf("Link"), names.indexOf("Link") + 3)).toEqual(["Link", "Image", "YouTube video"]); - }); - it("inserts a picked emoji at the cursor", async () => { - const { container, onChange } = await mount("

Hi

"); - act(() => { editorOf(container).commands.focus("end"); }); - fireEvent.click(screen.getByRole("button", { name: "Emoji" })); - fireEvent.click(await screen.findByText("pick-bottle")); - expect(onChange).toHaveBeenLastCalledWith("

Hi🍼

"); - }); - it("shows a size counter near the limit", async () => { - await mount(`

${"a".repeat(58000)}

`); - expect(screen.getByText(/KB of 64 KB/)).toBeInTheDocument(); - }); - - it("shows no counter for a normal description", async () => { - await mount("

short

"); - expect(screen.queryByText(/KB of 64 KB/)).not.toBeInTheDocument(); - }); - - it("gives every toolbar control a hover title equal to its label", async () => { - render(); - await waitFor(() => expect(document.querySelector(".ProseMirror")).not.toBeNull()); - expect(screen.getByRole("button", { name: "Bold" })).toHaveAttribute("title", "Bold"); - expect(screen.getByLabelText("Text style")).toHaveAttribute("title", "Text style"); - expect(screen.getByLabelText("Text colour")).toHaveAttribute("title", "Text colour"); - const controls = Array.from(screen.getByRole("toolbar").querySelectorAll("button, select, input:not([hidden])")) as HTMLElement[]; - expect(controls.length).toBeGreaterThan(15); - for (const el of controls) { - expect(el, el.outerHTML.slice(0, 80)).toHaveAttribute("title", el.getAttribute("aria-label")!); - } - }); - - it("titles the image button and the Show HTML toggle", async () => { - render(); - await waitFor(() => expect(document.querySelector(".ProseMirror")).not.toBeNull()); - expect(screen.getByRole("button", { name: "Image" })).toHaveAttribute("title", "Image"); - expect(screen.getByRole("button", { name: "Emoji" })).toHaveAttribute("title", "Emoji"); - const toggle = screen.getByRole("button", { name: "Show HTML" }); - expect(toggle).toHaveAttribute("title", "Show HTML"); - }); -}); diff --git a/solvway-admin-portal/app/components/products/RichTextEditor.tsx b/solvway-admin-portal/app/components/products/RichTextEditor.tsx deleted file mode 100644 index 4d609d7..0000000 --- a/solvway-admin-portal/app/components/products/RichTextEditor.tsx +++ /dev/null @@ -1,329 +0,0 @@ -"use client" - -import { useEffect, useRef, useState, type ChangeEvent, type ReactNode } from "react" -import { renderToStaticMarkup } from "react-dom/server" -import { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react" -import StarterKit from "@tiptap/starter-kit" -import TextAlign from "@tiptap/extension-text-align" -import { Color, TextStyle } from "@tiptap/extension-text-style" -import Image from "@tiptap/extension-image" -import Youtube from "@tiptap/extension-youtube" -import { TableKit } from "@tiptap/extension-table" -import { - AlignCenter, AlignLeft, AlignRight, Bold, Code, Eraser, ImagePlus, Italic, Link as LinkIcon, List, ListOrdered, - Minus, Quote, Smile, SquarePlay, Strikethrough, Table as TableIcon, Underline, -} from "lucide-react" - -import { EmojiPicker } from "frimousse" - -import { Button } from "@/app/components/ui/button" -import { Markdown } from "@/app/components/ui/markdown" -import { Popover, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover" -import { Textarea } from "@/app/components/ui/textarea" -import { useT } from "@/app/lib/i18n/MessagesProvider" - -export interface RichTextEditorProps { - id?: string - /** Marks the editing area aria-invalid, for a save error shown beside it. */ - invalid?: boolean - value: string - onChange: (html: string) => void - disabled?: boolean - onUploadImage?: (file: File) => Promise - trustedImageHosts?: string[] -} - -const SAFE_LINK = /^(https?:|mailto:)/i - -/** Stored value → editor HTML. Legacy Markdown descriptions are rendered once and saved back as HTML. */ -export function toEditorHtml(value: string): string { - if (!value.trim()) return "" - if (/^\s*{value}) -} - -function htmlOf(editor: Editor): string { - return editor.isEmpty ? "" : editor.getHTML() -} - -/** - * Shopify-style visual editor for the product Long Description (add-rich-text-long-description). - * Emits HTML; the storefront sanitises it on render. Tiptap's schema drops anything the toolbar - * cannot produce, including pasted scripts. - */ -export function RichTextEditor({ id, invalid, value, onChange, disabled, onUploadImage, trustedImageHosts = [] }: RichTextEditorProps) { - const t = useT() - const [source, setSource] = useState(null) - const [emojiOpen, setEmojiOpen] = useState(false) - const emitted = useRef(value) - // Current editor HTML, for the off-site image notice. - const [html, setHtml] = useState(() => toEditorHtml(value)) - - const editor = useEditor({ - immediatelyRender: false, - editable: !disabled, - content: toEditorHtml(value), - extensions: [ - StarterKit.configure({ - heading: { levels: [2, 3, 4] }, - // No auto-appended empty paragraph after a trailing heading/table: it would be stored. - trailingNode: false, - link: { openOnClick: false, protocols: ["http", "https", "mailto"], isAllowedUri: (url) => SAFE_LINK.test(url) }, - }), - TextStyle, - Color, - TextAlign.configure({ types: ["heading", "paragraph"], alignments: ["left", "center", "right"] }), - // Inline, as in Shopify: a pasted

stays one paragraph instead of gaining an empty one. - Image.configure({ inline: true }), - Youtube.configure({ nocookie: true }), - TableKit, - ], - editorProps: { attributes: { ...(id ? { id } : {}), ...(invalid ? { "aria-invalid": "true" } : {}), class: "min-h-[160px] px-3 py-2 text-sm outline-none" } }, - onUpdate: ({ editor }) => { - const html = htmlOf(editor) - emitted.current = html - setHtml(html) - onChange(html) - }, - }) - - useEffect(() => { - if (editor && value !== emitted.current) { - emitted.current = value - editor.commands.setContent(toEditorHtml(value), { emitUpdate: false }) - setHtml(toEditorHtml(value)) - } - }, [editor, value]) - - useEffect(() => { - editor?.setEditable(!disabled, false) - }, [editor, disabled]) - - const state = useEditorState({ - editor, - selector: ({ editor }) => ({ - level: editor?.isActive("heading") ? String(editor.getAttributes("heading").level) : "0", - color: (editor?.getAttributes("textStyle").color as string | undefined) ?? "#000000", - active: Object.fromEntries( - ["bold", "italic", "underline", "strike", "bulletList", "orderedList", "blockquote", "link"].map((n) => [n, editor?.isActive(n) ?? false]), - ) as Record, - }), - }) - - function run(fn: (e: Editor) => void) { - if (editor) fn(editor) - } - - const fileInput = useRef(null) - const [uploaded, setUploaded] = useState([]) - const [imageError, setImageError] = useState(null) - const [busy, setBusy] = useState(false) - - const trusted = new Set([...trustedImageHosts, ...uploaded]) - const offsiteSrcs = Array.from( - new Set(Array.from(new DOMParser().parseFromString(html, "text/html").images, (img) => img.getAttribute("src") ?? "")), - ).filter((src) => { - try { return !trusted.has(new URL(src).host) } catch { return true } - }) - - // ponytail: images removed from the text stay in the public bucket (orphans); diff old/new srcs on save and delete them if storage growth matters. - async function upload(file: File): Promise { - const url = await onUploadImage!(file) - setUploaded((hosts) => [...hosts, new URL(url).host]) - return url - } - - function openImagePicker() { - fileInput.current?.click() - } - - async function pickImage(event: ChangeEvent) { - const file = event.target.files?.[0] - event.target.value = "" - if (!file || !editor) return - setImageError(null) - setBusy(true) - try { - const src = await upload(file) - editor.chain().focus().setImage({ src }).run() - } catch (err) { - setImageError(err instanceof Error ? err.message : "CatUploadImageFailed") - } finally { - setBusy(false) - } - } - - function addLink() { - const url = window.prompt(t("RtePromptLink")) - if (!url) return - if (!SAFE_LINK.test(url)) return - run((e) => e.chain().focus().extendMarkRange("link").setLink({ href: url }).run()) - } - - async function reupload(src: string) { - if (!editor) return - setImageError(null) - setBusy(true) - try { - let blob: Blob - try { - const res = await fetch(src) - if (!res.ok) throw new Error(String(res.status)) - blob = await res.blob() - if (!blob.type.startsWith("image/")) throw new Error("not an image") - } catch { - setImageError("RteCopyFailed") - return - } - const name = new URL(src).pathname.split("/").pop() || "image" - const next = await upload(new File([blob], name, { type: blob.type })) - const { tr } = editor.state - editor.state.doc.descendants((node, pos) => { - if (node.type.name === "image" && node.attrs.src === src) tr.setNodeMarkup(pos, undefined, { ...node.attrs, src: next }) - }) - editor.view.dispatch(tr) - } catch (err) { - setImageError(err instanceof Error ? err.message : "CatUploadImageFailed") - } finally { - setBusy(false) - } - } - - function addYoutube() { - const src = window.prompt(t("RtePromptYoutube")) - // https only: the storefront drops any other embed. - if (src && /^https:\/\//i.test(src)) run((e) => e.chain().focus().setYoutubeVideo({ src }).run()) - } - - function toggleSource() { - if (!editor) return - if (source === null) { - setSource(htmlOf(editor)) - return - } - editor.commands.setContent(source, { emitUpdate: true }) - setSource(null) - } - - const off = disabled || !editor || source !== null || busy - const btn = (label: string, icon: ReactNode, onClick: () => void, active?: boolean) => ( - - ) - - return ( -
-
- - {btn(t("RteBold"), , () => run((e) => e.chain().focus().toggleBold().run()), state?.active.bold)} - {btn(t("RteItalic"), , () => run((e) => e.chain().focus().toggleItalic().run()), state?.active.italic)} - {btn(t("RteUnderline"), , () => run((e) => e.chain().focus().toggleUnderline().run()), state?.active.underline)} - {btn(t("RteStrikethrough"), , () => run((e) => e.chain().focus().toggleStrike().run()), state?.active.strike)} - { - const color = (ev.target as HTMLInputElement).value - run((e) => e.chain().focus().setColor(color).run()) - }} - onChange={() => {}} /> - {btn(t("RteAlignLeft"), , () => run((e) => e.chain().focus().setTextAlign("left").run()))} - {btn(t("RteAlignCentre"), , () => run((e) => e.chain().focus().setTextAlign("center").run()))} - {btn(t("RteAlignRight"), , () => run((e) => e.chain().focus().setTextAlign("right").run()))} - {btn(t("RteBulletList"), , () => run((e) => e.chain().focus().toggleBulletList().run()), state?.active.bulletList)} - {btn(t("RteNumberedList"), , () => run((e) => e.chain().focus().toggleOrderedList().run()), state?.active.orderedList)} - {btn(t("RteQuote"), , () => run((e) => e.chain().focus().toggleBlockquote().run()), state?.active.blockquote)} - {btn(t("RteDivider"), , () => run((e) => e.chain().focus().setHorizontalRule().run()))} - {btn(t("RteLink"), , addLink, state?.active.link)} - {onUploadImage ? ( - <> - - - - ) : null} - {btn(t("RteYoutube"), , addYoutube)} - {btn(t("RteTable"), , () => run((e) => e.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()))} - - - - - - { - run((e) => e.chain().focus().insertContent(emoji).run()) - setEmojiOpen(false) - }} - > - - - {t("Loading")} - {t("RteEmojiEmpty")} - - - - - - {btn(t("RteClearFormatting"), , () => run((e) => e.chain().focus().unsetAllMarks().clearNodes().run()))} - -
- - {source !== null ? ( -