Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
69e2b4eb7b | ||
|
|
4c48ebea2e | ||
|
|
816c8bcb5e | ||
|
|
92c8ad3b25 | ||
|
|
ca98d4dc22 | ||
|
|
49966586ca | ||
|
|
ad4713094a | ||
|
|
b2e0a17790 | ||
|
|
da813874ec | ||
|
|
1071ddaa2a | ||
|
|
a8cdf33a24 | ||
|
|
4d261d20d5 | ||
|
|
f5d1b6d032 | ||
|
|
9f22837a00 | ||
|
|
1bfc1c73c6 | ||
|
|
0a990cbcaf | ||
|
|
72b724f468 | ||
|
|
42071a850f | ||
|
|
f97bf48d93 | ||
|
|
c31b6630eb | ||
|
|
6b2fcf5780 | ||
|
|
1c77d9b63f |
No files matched your search
@@ -25,7 +25,7 @@ Then check it:
|
|||||||
local/smoke.sh
|
local/smoke.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
It prints `smoke: OK` when admin login, a service-counter read and a public mobile-api call all succeed.
|
It prints `smoke: OK` when admin login, `/api/admin/me`, the users list, a service-counter read and a public mobile-api call all succeed.
|
||||||
|
|
||||||
| What | Where |
|
| What | Where |
|
||||||
|---|---|
|
|---|---|
|
||||||
@@ -34,6 +34,23 @@ It prints `smoke: OK` when admin login, a service-counter read and a public mobi
|
|||||||
| MySQL | localhost:3307, user `root`, password `colite-dev` |
|
| MySQL | localhost:3307, user `root`, password `colite-dev` |
|
||||||
| Admin login | `admin` / `colite-dev-admin` |
|
| Admin login | `admin` / `colite-dev-admin` |
|
||||||
|
|
||||||
|
## Admin portal
|
||||||
|
|
||||||
|
The portal runs outside Docker with `npm run dev` and talks to `mobile-api` on port 8080. With the stack up:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd solvway-admin-portal
|
||||||
|
cat > .env.local <<'EOF'
|
||||||
|
MOBILE_API_BASE_URL=http://localhost:8080
|
||||||
|
MOBILE_API_KEY=colite-local-app-key
|
||||||
|
SESSION_SECRET=colite-local-session-secret-0123456789abcdef
|
||||||
|
EOF
|
||||||
|
npm ci
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Open http://localhost:3001 and log in as `admin` / `colite-dev-admin`. `.env.local` is git-ignored. The portal declares Node 24; Node 22 also runs it.
|
||||||
|
|
||||||
## Reset
|
## Reset
|
||||||
|
|
||||||
Deletes the database volume; the next start reseeds from `local/seed/`:
|
Deletes the database volume; the next start reseeds from `local/seed/`:
|
||||||
|
|||||||
@@ -163,7 +163,7 @@ UNLOCK TABLES;
|
|||||||
|
|
||||||
LOCK TABLES `role` WRITE;
|
LOCK TABLES `role` WRITE;
|
||||||
/*!40000 ALTER TABLE `role` DISABLE KEYS */;
|
/*!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 */;
|
/*!40000 ALTER TABLE `role` ENABLE KEYS */;
|
||||||
UNLOCK TABLES;
|
UNLOCK TABLES;
|
||||||
|
|
||||||
@@ -272,7 +272,7 @@ UNLOCK TABLES;
|
|||||||
|
|
||||||
LOCK TABLES `user_group_roles` WRITE;
|
LOCK TABLES `user_group_roles` WRITE;
|
||||||
/*!40000 ALTER TABLE `user_group_roles` DISABLE KEYS */;
|
/*!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 */;
|
/*!40000 ALTER TABLE `user_group_roles` ENABLE KEYS */;
|
||||||
UNLOCK TABLES;
|
UNLOCK TABLES;
|
||||||
|
|
||||||
@@ -282,7 +282,7 @@ UNLOCK TABLES;
|
|||||||
|
|
||||||
LOCK TABLES `modules_roles` WRITE;
|
LOCK TABLES `modules_roles` WRITE;
|
||||||
/*!40000 ALTER TABLE `modules_roles` DISABLE KEYS */;
|
/*!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),(19Line truncated
|
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 */;
|
/*!40000 ALTER TABLE `modules_roles` ENABLE KEYS */;
|
||||||
UNLOCK TABLES;
|
UNLOCK TABLES;
|
||||||
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
|
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
|
||||||
|
|||||||
@@ -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).
|
-- 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`;
|
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,
|
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||||
`name` varchar(255) NOT NULL,
|
`name` varchar(255) NOT NULL,
|
||||||
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (`id`)
|
PRIMARY KEY (`id`)
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
INSERT INTO `company` (`id`, `name`) VALUES (1, 'Co-Lite');
|
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`,
|
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,
|
VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 1,
|
||||||
'N', 'Y', 'A', 'seed', NOW(), 'seed');
|
'Y', 'Y', 'A', 'seed', NOW(), 'seed', 1);
|
||||||
INSERT INTO `users_roles` (`user_id`, `role_id`) VALUES (1, 1);
|
INSERT INTO `users_roles` (`user_id`, `role_id`) VALUES (1, 1);
|
||||||
@@ -8,19 +8,27 @@ APP_KEY=colite-local-app-key
|
|||||||
|
|
||||||
fail() { echo "FAIL: $1"; exit 1; }
|
fail() { echo "FAIL: $1"; exit 1; }
|
||||||
|
|
||||||
# 1. Admin login: gateway -> service-auth -> service-system -> MySQL
|
# 1. Admin login: mobile-api -> service-auth -> service-system -> MySQL
|
||||||
token=$(curl -sf -X POST "$GW/auth/authenticate" -H "api-key: $GW_KEY" -H 'Content-Type: application/json' \
|
token=$(curl -sf -X POST "$MOBILE/api/admin/auth/login" -H "api-key: $APP_KEY" -H 'Content-Type: application/json' \
|
||||||
-d '{"username":"admin","password":"colite-dev-admin"}') || fail "POST $GW/auth/authenticate"
|
-d '{"username":"admin","password":"colite-dev-admin"}' \
|
||||||
[ -n "$token" ] || fail "POST $GW/auth/authenticate returned no token"
|
| sed -n 's/.*"token":"\([^"]*\)".*/\1/p') || fail "POST $MOBILE/api/admin/auth/login"
|
||||||
echo "auth/authenticate: 200"
|
[ -n "$token" ] || fail "POST $MOBILE/api/admin/auth/login returned no token"
|
||||||
|
echo "api/admin/auth/login: 200"
|
||||||
|
|
||||||
# 2. gateway -> service-counter -> MySQL
|
# 2. Admin guard and session lookup, then the users list (service-system)
|
||||||
|
for path in /api/admin/me /api/admin/users; do
|
||||||
|
code=$(curl -s -o /dev/null -w '%{http_code}' "$MOBILE$path" -H "api-key: $APP_KEY" -H "Authorization: Bearer $token")
|
||||||
|
[ "$code" = 200 ] || fail "GET $MOBILE$path returned $code"
|
||||||
|
echo "${path#/}: $code"
|
||||||
|
done
|
||||||
|
|
||||||
|
# 3. gateway -> service-counter -> MySQL
|
||||||
code=$(curl -s -o /dev/null -w '%{http_code}' "$GW/counter/event/findCurrentEvent" \
|
code=$(curl -s -o /dev/null -w '%{http_code}' "$GW/counter/event/findCurrentEvent" \
|
||||||
-H "api-key: $GW_KEY" -H "Authorization: Bearer $token")
|
-H "api-key: $GW_KEY" -H "Authorization: Bearer $token")
|
||||||
[ "$code" = 200 ] || fail "GET $GW/counter/event/findCurrentEvent returned $code"
|
[ "$code" = 200 ] || fail "GET $GW/counter/event/findCurrentEvent returned $code"
|
||||||
echo "counter/event/findCurrentEvent: $code"
|
echo "counter/event/findCurrentEvent: $code"
|
||||||
|
|
||||||
# 3. mobile-api -> gateway -> service-system -> MySQL
|
# 4. mobile-api -> gateway -> service-system -> MySQL, no login
|
||||||
code=$(curl -s -o /dev/null -w '%{http_code}' "$MOBILE/api/public/messages/en_US" -H "api-key: $APP_KEY")
|
code=$(curl -s -o /dev/null -w '%{http_code}' "$MOBILE/api/public/messages/en_US" -H "api-key: $APP_KEY")
|
||||||
[ "$code" = 200 ] || fail "GET $MOBILE/api/public/messages/en_US returned $code"
|
[ "$code" = 200 ] || fail "GET $MOBILE/api/public/messages/en_US returned $code"
|
||||||
echo "api/public/messages/en_US: $code"
|
echo "api/public/messages/en_US: $code"
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# 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 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.
|
||||||
|
|
||||||
|
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, create_date)` 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` 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
|
||||||
|
|
||||||
|
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`.
|
||||||
|
- [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.
|
||||||
|
- [A non-super admin with `BO_USERS` or `BO_ROLES` could use one module to gain the other] → A non-super admin cannot change their own roles or the grants of a role they hold, and nobody can assign `ROLE_ADMIN` or `ROLE_MEMBER`. They can still give a colleague any visible role; a subset rule (assign only what you hold) is deferred.
|
||||||
|
- [The gateway token bypass for `/user/resetAdminPassword` returns the updated-row count (1 or 0) to anyone with a gateway api-key allowed on `/user/`] → Gateway keys stay internal (mobile-api only); the public endpoint in mobile-api always answers the same.
|
||||||
|
- [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`).
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -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 and `ROLE_ADMIN` SHALL NOT appear in the list (`ROLE_ADMIN` is attached to every admin automatically and grants no modules).
|
||||||
|
|
||||||
|
#### Scenario: Create role
|
||||||
|
|
||||||
|
- **WHEN** an admin with `BO_ROLES` creates role `ROLE_SALES`
|
||||||
|
- **THEN** it appears in the role list and can be assigned to users
|
||||||
|
|
||||||
|
#### 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 grants of the super admin role and of `ROLE_ADMIN` SHALL NOT be editable. An admin who is not super admin SHALL NOT change the grants of a role they hold.
|
||||||
|
|
||||||
|
#### 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: Own role
|
||||||
|
|
||||||
|
- **GIVEN** an admin who is not super admin and holds `ROLE_SALES`
|
||||||
|
- **WHEN** they change the module grants of `ROLE_SALES` and save
|
||||||
|
- **THEN** the save is refused with a message, so no admin can widen their own access or lock themselves out of role management
|
||||||
|
|
||||||
|
### 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
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# 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. An admin who is not super admin SHALL NOT change the roles on their own account. No admin SHALL assign `ROLE_ADMIN` or `ROLE_MEMBER` when creating or editing a user.
|
||||||
|
|
||||||
|
#### 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
|
||||||
|
|
||||||
|
#### Scenario: Own roles
|
||||||
|
|
||||||
|
- **GIVEN** an admin who is not super admin and holds `ROLE_SALES`
|
||||||
|
- **WHEN** they save their own account with a different set of roles
|
||||||
|
- **THEN** the save is refused with a message and their roles are unchanged
|
||||||
|
|
||||||
|
#### Scenario: Hidden roles
|
||||||
|
|
||||||
|
- **WHEN** an admin creates or edits a user with `ROLE_ADMIN` or `ROLE_MEMBER` in the roles
|
||||||
|
- **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. The system SHALL NOT let an admin set another user's password to a value the admin chooses.
|
||||||
|
|
||||||
|
#### 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
|
||||||
|
|
||||||
|
#### Scenario: No direct password set
|
||||||
|
|
||||||
|
- **WHEN** an admin calls `POST /api/admin/users/{id}/changePassword`
|
||||||
|
- **THEN** the endpoint does not exist and no password changes
|
||||||
|
|
||||||
|
### 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
|
||||||
@@ -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';
|
||||||
@@ -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');
|
||||||
@@ -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`;
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Tasks
|
||||||
|
|
||||||
|
Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most touch shared security code or build files.
|
||||||
|
|
||||||
|
## 1. Database
|
||||||
|
|
||||||
|
- [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
|
||||||
|
|
||||||
|
- [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
|
||||||
|
|
||||||
|
- [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
|
||||||
|
|
||||||
|
- [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
|
||||||
|
|
||||||
|
- [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
|
||||||
|
- [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
|
||||||
|
|
||||||
|
- [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/**`
|
||||||
|
- [x] 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
|
||||||
|
|
||||||
|
- [x] 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`
|
||||||
|
- [x] 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/**`
|
||||||
|
|
||||||
|
## 8. Review follow-up: close self-escalation
|
||||||
|
|
||||||
|
- [x] 8.1 In `mobile-api`: delete `POST /api/admin/users/{id}/changePassword` and `AdminUserService.changePassword`; in `AdminUserService` refuse (403, `OWN_ROLES`) a non-super caller whose update changes the role set on their own account, and refuse (400, `UNKNOWN_ROLE`) `ROLE_ADMIN` or `ROLE_MEMBER` on create and update; in `AdminAclService.updateGrants` refuse (403, `OWN_ROLE`) a non-super caller editing a role they hold, and delete `requireNoLockout`, which that rule makes unreachable. Tests first for each new scenario. Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify` exits 0.
|
||||||
|
- Scope: `solvway-mobile-api/src/**/admin/**`, `solvway-mobile-api/src/**/service/Admin*`
|
||||||
|
- [x] 8.2 In the portal: delete the change-password route, `ChangePasswordDialog`, `changeAdminUserPassword` and the button on the edit-user page; the emailed reset stays. Verify: `npm run lint && npx tsc --noEmit && npx vitest run` exit 0.
|
||||||
|
- Scope: `solvway-admin-portal/**`
|
||||||
|
|
||||||
|
## Workflow follow-up
|
||||||
|
|
||||||
|
- Code review, PR to `main`, merge, then archive this change.
|
||||||
|
After Width: | Height: | Size: 105 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 33 KiB |
@@ -0,0 +1,2 @@
|
|||||||
|
schema: spec-driven
|
||||||
|
created: 2026-11-26
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# local-dev-stack Specification
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
Lets a developer build, start, seed and check the whole Co-Lite backend on their own machine, with no shared environment.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
### Requirement: Single build for all backend modules
|
||||||
|
|
||||||
|
The repository SHALL build and test every kept backend module with one Maven command run from the repository root.
|
||||||
|
|
||||||
|
#### Scenario: Root build succeeds
|
||||||
|
|
||||||
|
- **GIVEN** a fresh clone with JDK 21 and Maven installed
|
||||||
|
- **WHEN** the developer runs `mvn -T 1C verify` at the repository root
|
||||||
|
- **THEN** every kept module compiles and its tests pass
|
||||||
|
|
||||||
|
### Requirement: Isolated core library version
|
||||||
|
|
||||||
|
The Co-Lite core library MUST be published under a version distinct from every other Solvway project on the same machine.
|
||||||
|
|
||||||
|
#### Scenario: Local install does not overwrite other projects
|
||||||
|
|
||||||
|
- **GIVEN** Tastefully's `tastefully-v1` core library is in the local Maven repository
|
||||||
|
- **WHEN** the developer installs Co-Lite's core library
|
||||||
|
- **THEN** it is stored as version `colite-v1`
|
||||||
|
- **AND** the `tastefully-v1` artifact is unchanged
|
||||||
|
|
||||||
|
### Requirement: One command starts the local stack
|
||||||
|
|
||||||
|
The repository SHALL start MySQL, Redis, the Pub/Sub emulator and every kept backend service locally with one documented command.
|
||||||
|
|
||||||
|
#### Scenario: Stack starts healthy
|
||||||
|
|
||||||
|
- **WHEN** the developer runs the documented start command
|
||||||
|
- **THEN** every service container reaches a running, healthy state
|
||||||
|
- **AND** no service logs a startup failure about a missing topic, subscription, schema or dropped service
|
||||||
|
|
||||||
|
### Requirement: Local database is seeded on first start
|
||||||
|
|
||||||
|
The local stack SHALL create the kept service schemas, their reference data, one company and one admin user on first start of an empty database.
|
||||||
|
|
||||||
|
#### Scenario: Empty database is seeded
|
||||||
|
|
||||||
|
- **GIVEN** the local MySQL volume is empty
|
||||||
|
- **WHEN** the stack starts
|
||||||
|
- **THEN** the schemas `service-system`, `service-counter`, `service-member`, `service-log` and `service-email` exist with their tables
|
||||||
|
- **AND** one company and one admin user exist
|
||||||
|
|
||||||
|
#### Scenario: Seed contains no customer data
|
||||||
|
|
||||||
|
- **WHEN** the seed files are committed
|
||||||
|
- **THEN** they contain table definitions and reference rows only, with no Tastefully member, attendance, order or user rows
|
||||||
|
|
||||||
|
### Requirement: Local stack can be reset
|
||||||
|
|
||||||
|
The repository SHALL provide a documented command that deletes local data and reseeds from scratch.
|
||||||
|
|
||||||
|
#### Scenario: Reset restores the seeded state
|
||||||
|
|
||||||
|
- **GIVEN** the developer has changed data in the local database
|
||||||
|
- **WHEN** they run the documented reset command and start the stack again
|
||||||
|
- **THEN** the database holds only the seeded data
|
||||||
|
|
||||||
|
### Requirement: End-to-end smoke check
|
||||||
|
|
||||||
|
The repository SHALL include a smoke check that logs in as the seeded admin through the gateway, reads from services-counter through the gateway, and calls a public mobile-api endpoint, confirming each succeeds against MySQL.
|
||||||
|
|
||||||
|
#### Scenario: Smoke check passes on a healthy stack
|
||||||
|
|
||||||
|
- **GIVEN** the stack is running and seeded
|
||||||
|
- **WHEN** the developer runs the smoke check
|
||||||
|
- **THEN** it exits with status 0 and prints HTTP status 200 for each call
|
||||||
|
|
||||||
|
#### Scenario: Smoke check fails loudly
|
||||||
|
|
||||||
|
- **GIVEN** services-counter is stopped
|
||||||
|
- **WHEN** the developer runs the smoke check
|
||||||
|
- **THEN** it exits with a non-zero status and names the failing call
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: run-solvway-admin-portal
|
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/`.
|
All paths below are relative to `solvway-admin-portal/`.
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# ── Mobile API (BFF target) ───────────────────────────────────────────
|
# ── 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.
|
# Supplied per environment; there is no sensible default.
|
||||||
MOBILE_API_BASE_URL=
|
MOBILE_API_BASE_URL=
|
||||||
|
|
||||||
@@ -10,4 +10,4 @@ MOBILE_API_KEY=
|
|||||||
|
|
||||||
# ── Session ───────────────────────────────────────────────────────────
|
# ── Session ───────────────────────────────────────────────────────────
|
||||||
# Name of the httpOnly cookie that stores the admin JWT.
|
# Name of the httpOnly cookie that stores the admin JWT.
|
||||||
SESSION_COOKIE_NAME=bb_admin
|
SESSION_COOKIE_NAME=colite_admin
|
||||||
@@ -5,7 +5,6 @@ FROM base AS deps
|
|||||||
RUN apk add --no-cache libc6-compat
|
RUN apk add --no-cache libc6-compat
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
COPY vendor/ ./vendor/
|
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
# A High or Critical advisory in a runtime dependency fails the image (F45). Dev tooling is not shipped,
|
# 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`.
|
# so it is excluded. Moderate advisories do not block; review them with a full `npm audit`.
|
||||||
|
|||||||
@@ -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
|
Next.js 16 admin portal for Co-Lite. Screens call the JSON admin APIs (`/api/admin/**`) in `mobile-api` through server-side route handlers.
|
||||||
> 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.
|
|
||||||
|
|
||||||
A reusable admin/back-office front end for MLM (multi-level marketing) clients. It ships
|
## Run
|
||||||
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.
|
|
||||||
|
|
||||||
**Currently skinned for babyboo.my** — baby & maternity retail, competing with Medela, Momcozy,
|
Needs Node 24 (see `.nvmrc`).
|
||||||
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
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
cp .env.example .env.local # then fill in the values below
|
||||||
npm run dev # next dev --port 3001
|
npm ci
|
||||||
npm test # run the full test suite (Vitest, run once)
|
npm run dev # http://localhost:3001
|
||||||
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
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 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,
|
## Scripts
|
||||||
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 `<link>` (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 `<link>` tags before the Next.js conversion; the placeholder
|
|
||||||
`app/layout.tsx` does not yet re-add them (Task 6 restores the font `<link>`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.
|
|
||||||
|
|
||||||
|
- `npm run build` / `npm start` production build and server (port 3001)
|
||||||
|
- `npm run lint`
|
||||||
|
- `npm test`
|
||||||
@@ -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<typeof POST>[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 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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 });
|
|
||||||
}
|
|
||||||
@@ -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<typeof POST>[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 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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 });
|
|
||||||
}
|
|
||||||
@@ -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");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<CompanyAccountRow[]>(
|
|
||||||
`/api/admin/company-accounts/${encodeURIComponent(prefix)}`,
|
|
||||||
{ token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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<typeof POST>[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
function putReq(body: unknown) {
|
|
||||||
return new Request("http://localhost/api/admin/company-accounts", {
|
|
||||||
method: "PUT",
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
}) as unknown as Parameters<typeof PUT>[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 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<CompanyAccountCreatePayload>;
|
|
||||||
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<CompanyAccountUpdatePayload>;
|
|
||||||
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 });
|
|
||||||
}
|
|
||||||
@@ -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<typeof GET>[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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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"]);
|
|
||||||
}
|
|
||||||
@@ -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<typeof GET>[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");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<typeof GET>[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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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"]);
|
|
||||||
@@ -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"]);
|
|
||||||
}
|
|
||||||
@@ -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", []);
|
|
||||||
}
|
|
||||||
@@ -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<typeof getEvents>[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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<typeof POST>[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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<AdminKycRow>(`/api/admin/kyc/${encodeURIComponent(uuid)}/${action}`, {
|
|
||||||
method: "POST",
|
|
||||||
body: { action, remarks: remarksStr },
|
|
||||||
token,
|
|
||||||
});
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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<typeof GET>[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("<script>alert(1)</script>", { 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");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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 });
|
|
||||||
}
|
|
||||||
@@ -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<typeof GET>[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" });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<AdminKycDetail>(`/api/admin/kyc/${encodeURIComponent(uuid)}`, {
|
|
||||||
token,
|
|
||||||
});
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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<typeof GET>[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" });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<AdminKycCounts>("/api/admin/kyc/counts", { token });
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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<typeof GET>[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=");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<unknown[]>(
|
|
||||||
`/api/admin/kyc/export${qs}`,
|
|
||||||
{ token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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<typeof GET>[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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<AdminKycPage>(
|
|
||||||
`/api/admin/kyc${qs}`,
|
|
||||||
{ token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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<typeof POST>[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",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<AdminKycRow>("/api/admin/kyc/submit", {
|
|
||||||
method: "POST",
|
|
||||||
body: { memberCode, submitName, identityType, identityNo, docs },
|
|
||||||
token,
|
|
||||||
});
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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<typeof POST>[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",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<KycUploadResult>("/api/admin/kyc/upload", {
|
|
||||||
method: "POST",
|
|
||||||
body: { memberCode, docType, fileType, base },
|
|
||||||
token,
|
|
||||||
});
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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<typeof GET>[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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<AdminMemberCorrectionPage>(
|
|
||||||
`/api/admin/member-corrections${qs}`,
|
|
||||||
{ token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -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",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -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 });
|
|
||||||
}
|
|
||||||
@@ -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");
|
|
||||||
}
|
|
||||||
@@ -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");
|
|
||||||
}
|
|
||||||
@@ -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"] });
|
|
||||||
}
|
|
||||||
@@ -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");
|
|
||||||
}
|
|
||||||
@@ -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 });
|
|
||||||
@@ -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 });
|
|
||||||
@@ -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"] });
|
|
||||||
@@ -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<string, unknown> = {};
|
|
||||||
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 });
|
|
||||||
}
|
|
||||||
@@ -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"] });
|
|
||||||
@@ -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);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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<string, string> = {}) =>
|
|
||||||
({ 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("<html/>", { 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("<script>", { status: 200, headers: { "content-type": "text/html" } })));
|
|
||||||
const res = await image(get(`${B}/c1/messages/m1/images/0`), img());
|
|
||||||
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 pipes the body", async () => {
|
|
||||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("png", { status: 200, headers: { "content-type": "image/png" } })));
|
|
||||||
const res = await image(get(`${B}/c1/messages/m1/images/0`), img());
|
|
||||||
expect(res.headers.get("content-type")).toBe("image/png");
|
|
||||||
expect(await res.text()).toBe("png");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("refuses a malformed message id without calling upstream", async () => {
|
|
||||||
const fetchMock = vi.fn();
|
|
||||||
vi.stubGlobal("fetch", fetchMock);
|
|
||||||
expect((await image(get(B), img("../x"))).status).toBe(400);
|
|
||||||
expect(fetchMock).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("maps mobile-api's expired-token 500 to 401", async () => {
|
|
||||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("invalid token", { status: 500 })));
|
|
||||||
expect((await image(get(B), img())).status).toBe(401);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,184 +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 unread } from "./unread-count/route";
|
|
||||||
import { GET as byKey } from "./by-key/route";
|
|
||||||
import { POST as start } from "./start/route";
|
|
||||||
import { POST as preview } from "./broadcasts/preview/route";
|
|
||||||
import { GET as broadcastList, POST as broadcast } from "./broadcasts/route";
|
|
||||||
import { GET as thread } from "./[uuid]/route";
|
|
||||||
import { GET as messages, POST as reply } from "./[uuid]/messages/route";
|
|
||||||
import { POST as read } from "./[uuid]/read/route";
|
|
||||||
import { GET as image } from "./[uuid]/messages/[messageUuid]/images/[index]/route";
|
|
||||||
import { POST as upload } from "./images/route";
|
|
||||||
|
|
||||||
const B = "http://localhost/api/admin/member-messages";
|
|
||||||
const req = (url: string, body?: unknown, method = body === undefined ? "GET" : "POST") =>
|
|
||||||
new Request(url, { method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }) as unknown as NextRequest;
|
|
||||||
const c1 = { params: Promise.resolve({ uuid: "c1" }) };
|
|
||||||
|
|
||||||
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";
|
|
||||||
});
|
|
||||||
afterEach(() => vi.unstubAllGlobals());
|
|
||||||
|
|
||||||
const reply_ = { body: "hi", imageRefs: ["messages/admin/a.png"] };
|
|
||||||
const cases: [string, () => Promise<Response>, string, "GET" | "POST", unknown?][] = [
|
|
||||||
["list", () => list(req(`${B}?types=S&page=0&size=20`)), "/api/admin/member-messages?types=S&page=0&size=20", "GET"],
|
|
||||||
["unread-count", () => unread(req(`${B}/unread-count`)), "/api/admin/member-messages/unread-count", "GET"],
|
|
||||||
["by-key", () => byKey(req(`${B}/by-key?member=MY5`)), "/api/admin/member-messages/by-key?member=MY5", "GET"],
|
|
||||||
["thread", () => thread(req(`${B}/c1`), c1), "/api/admin/member-messages/c1", "GET"],
|
|
||||||
["messages GET", () => messages(req(`${B}/c1/messages?before=m9&size=30`), c1), "/api/admin/member-messages/c1/messages?before=m9&size=30", "GET"],
|
|
||||||
["reply", () => reply(req(`${B}/c1/messages`, reply_), c1), "/api/admin/member-messages/c1/messages", "POST", reply_],
|
|
||||||
["read", () => read(req(`${B}/c1/read`, undefined, "POST"), c1), "/api/admin/member-messages/c1/read", "POST"],
|
|
||||||
["start", () => start(req(`${B}/start`, { memberCode: "MY5", body: "yo", imageRefs: [] })), "/api/admin/member-messages/start", "POST", { memberCode: "MY5", body: "yo", imageRefs: [] }],
|
|
||||||
["preview", () => preview(req(`${B}/broadcasts/preview`, { target: { kind: "ALL" } })), "/api/admin/member-messages/broadcasts/preview", "POST", { target: { kind: "ALL" } }],
|
|
||||||
["broadcast", () => broadcast(req(`${B}/broadcasts`, { target: { kind: "ALL" }, subject: "s", body: "b", imageRefs: [] })), "/api/admin/member-messages/broadcasts", "POST", { target: { kind: "ALL" }, subject: "s", body: "b", imageRefs: [] }],
|
|
||||||
];
|
|
||||||
|
|
||||||
describe("admin messages BFF relays", () => {
|
|
||||||
it.each(cases)("%s forwards to mobile-api and returns its data", async (_n, call, path, method, body) => {
|
|
||||||
const res = await call();
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(await res.json()).toEqual({ fine: 1 });
|
|
||||||
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
|
||||||
path,
|
|
||||||
expect.objectContaining({ method, token: "jwt", ...(body === undefined ? {} : { body }) }),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(cases)("%s returns 401 with no session and never calls upstream", async (_n, call) => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
expect((await call()).status).toBe(401);
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
// mobile-api has no `code` field: the reason text is the whole error, so the relay derives the code.
|
|
||||||
it.each([
|
|
||||||
["EMPTY_TARGET", 400, 500],
|
|
||||||
["NOT_IN_NETWORK", 403, 500],
|
|
||||||
["MESSAGE_INVALID", 400, 500],
|
|
||||||
["MESSAGE_IMAGE_NOT_OWNED", 400, 500],
|
|
||||||
["MESSAGE_COMMIT_FAILED", 502, 500],
|
|
||||||
["MESSAGE_UPLOAD_FAILED", 502, 400],
|
|
||||||
])("derives code %s from the upstream reason text and answers %i", async (code, status, upstreamStatus) => {
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: `${code}: details`, status: upstreamStatus });
|
|
||||||
const res = await broadcast(req(`${B}/broadcasts`, { target: { kind: "LIST", codes: [] } }));
|
|
||||||
expect(res.status).toBe(status);
|
|
||||||
expect(await res.json()).toEqual({ error: code, code });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps 401 as 401, passes 404 through and adds no code to an unknown failure", async () => {
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Session expired", status: 401 });
|
|
||||||
expect((await thread(req(`${B}/c1`), c1)).status).toBe(401);
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Conversation not found", status: 404 });
|
|
||||||
const nf = await thread(req(`${B}/c1`), c1);
|
|
||||||
expect(nf.status).toBe(404);
|
|
||||||
expect(await nf.json()).toEqual({ error: "Conversation not found" });
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Something odd", status: 500 });
|
|
||||||
expect((await (await thread(req(`${B}/c1`), c1)).json()).code).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects a path-like conversation id before any upstream call", async () => {
|
|
||||||
const res = await thread(req(`${B}/x`), { params: Promise.resolve({ uuid: "../admin" }) });
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects a non-JSON body on POST", async () => {
|
|
||||||
const bad = new Request(`${B}/start`, { method: "POST", body: "{nope" }) as unknown as NextRequest;
|
|
||||||
expect((await start(bad)).status).toBe(400);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("GET image stream", () => {
|
|
||||||
const ctx = (index: string) => ({ params: Promise.resolve({ uuid: "c1", messageUuid: "m1", index }) });
|
|
||||||
|
|
||||||
it("streams the bytes with no-store and the upstream content type", async () => {
|
|
||||||
const f = vi.fn().mockResolvedValue(new Response(new Uint8Array([1, 2, 3]), { status: 200, headers: { "content-type": "image/png" } }));
|
|
||||||
vi.stubGlobal("fetch", f);
|
|
||||||
const res = await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"));
|
|
||||||
expect(f.mock.calls[0][0]).toBe("http://up/api/admin/member-messages/c1/messages/m1/images/0");
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(res.headers.get("content-type")).toBe("image/png");
|
|
||||||
expect(res.headers.get("cache-control")).toBe("private, no-store");
|
|
||||||
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3]));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("maps upstream 404 to 404 and rejects a bad index", async () => {
|
|
||||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("", { status: 404 })));
|
|
||||||
expect((await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"))).status).toBe(404);
|
|
||||||
expect((await image(req(`${B}/c1/messages/m1/images/x`), ctx("x"))).status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 with no session", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
expect((await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"))).status).toBe(401);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("POST images (multipart pass-through)", () => {
|
|
||||||
const withFile = (file: File | null) =>
|
|
||||||
({ formData: async () => ({ get: () => file }) }) as unknown as NextRequest;
|
|
||||||
|
|
||||||
it("forwards a valid png and returns the ref", async () => {
|
|
||||||
const f = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ref: "messages/admin/a.png" }), { status: 200 }));
|
|
||||||
vi.stubGlobal("fetch", f);
|
|
||||||
const res = await upload(withFile(new File(["x"], "a.png", { type: "image/png" })));
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(await res.json()).toEqual({ ref: "messages/admin/a.png" });
|
|
||||||
expect(f.mock.calls[0][0]).toBe("http://up/api/admin/member-messages/images");
|
|
||||||
expect(f.mock.calls[0][1].headers.Authorization).toBe("Bearer jwt");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects a non-image type, an oversize file and a missing file without calling upstream", async () => {
|
|
||||||
const f = vi.fn();
|
|
||||||
vi.stubGlobal("fetch", f);
|
|
||||||
expect((await upload(withFile(new File(["x"], "a.gif", { type: "image/gif" })))).status).toBe(400);
|
|
||||||
expect((await upload(withFile(new File([new Uint8Array(5 * 1024 * 1024 + 1)], "a.png", { type: "image/png" })))).status).toBe(400);
|
|
||||||
expect((await upload(withFile(null))).status).toBe(400);
|
|
||||||
expect(f).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("derives the code from an upstream reason text (no code field upstream)", async () => {
|
|
||||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({ message: "MESSAGE_UPLOAD_FAILED" }), { status: 500 })));
|
|
||||||
const res = await upload(withFile(new File(["x"], "a.png", { type: "image/png" })));
|
|
||||||
expect(res.status).toBe(502);
|
|
||||||
expect(await res.json()).toEqual({ error: "MESSAGE_UPLOAD_FAILED", code: "MESSAGE_UPLOAD_FAILED" });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 with no session", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
expect((await upload(withFile(null))).status).toBe(401);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// BABYBOO-54 B2: the list relay forwards sortBy/sortDir (param order not asserted).
|
|
||||||
describe("member-messages list sort forwarding", () => {
|
|
||||||
it("forwards sortBy and sortDir", async () => {
|
|
||||||
await list(req(`${B}?sortBy=time&sortDir=desc&page=0&size=20`));
|
|
||||||
const [url] = mocks.callMobileApi.mock.calls.at(-1)!;
|
|
||||||
const sp = new URLSearchParams(String(url).split("?")[1]);
|
|
||||||
expect(String(url).startsWith("/api/admin/member-messages?")).toBe(true);
|
|
||||||
expect([sp.get("sortBy"), sp.get("sortDir"), sp.get("page"), sp.get("size")]).toEqual(["time", "desc", "0", "20"]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// BABYBOO-54 2.4: broadcasts relay forwards sortBy/sortDir.
|
|
||||||
describe("member-messages broadcasts sort forwarding", () => {
|
|
||||||
it("forwards sortBy and sortDir", async () => {
|
|
||||||
await broadcastList(req(`${B}/broadcasts?sortBy=read&sortDir=desc&page=0&size=20`));
|
|
||||||
const [url] = mocks.callMobileApi.mock.calls.at(-1)!;
|
|
||||||
const sp = new URLSearchParams(String(url).split("?")[1]);
|
|
||||||
expect(String(url).startsWith("/api/admin/member-messages/broadcasts?")).toBe(true);
|
|
||||||
expect([sp.get("sortBy"), sp.get("sortDir")]).toEqual(["read", "desc"]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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/start { memberCode, body, imageRefs }.
|
|
||||||
export const POST = (req: NextRequest) => relay(req, "/start", "POST", { body: true });
|
|
||||||
@@ -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/unread-count.
|
|
||||||
export const GET = (req: NextRequest) => relay(req, "/unread-count", "GET");
|
|
||||||
@@ -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 { GET } from "./route";
|
|
||||||
|
|
||||||
function getReq() {
|
|
||||||
return new Request("http://localhost/api/admin/members/BB0100/change-history") as unknown as Parameters<typeof GET>[0];
|
|
||||||
}
|
|
||||||
const ctx = { params: Promise.resolve({ memberCode: "BB0100" }) };
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mocks.callMobileApi.mockReset();
|
|
||||||
mocks.getToken.mockReset();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("GET /api/admin/members/[memberCode]/change-history", () => {
|
|
||||||
it("forwards the member code and admin JWT and passes the upstream JSON through", async () => {
|
|
||||||
const data = [
|
|
||||||
{
|
|
||||||
at: "2026-10-29T14:31:58+08:00",
|
|
||||||
by: "SYS",
|
|
||||||
changes: [{ field: "memberRank", oldValue: "SQUIRREL", newValue: "GIRAFFE" }],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data });
|
|
||||||
const res = await GET(getReq(), ctx);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(await res.json()).toEqual(data);
|
|
||||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/change-history", {
|
|
||||||
token: "jwt-abc",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 without a session", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
const res = await GET(getReq(), ctx);
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("passes an upstream 404 on instead of masking it", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 404, error: "Member not found" });
|
|
||||||
const res = await GET(getReq(), ctx);
|
|
||||||
expect(res.status).toBe(404);
|
|
||||||
expect(await res.json()).toMatchObject({ error: "Member not found" });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 when the upstream session has expired", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 401, expired: true, error: "expired" });
|
|
||||||
const res = await GET(getReq(), ctx);
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,20 +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 { AdminMemberChangeEntry } from "@/app/lib/types";
|
|
||||||
|
|
||||||
// GET -> /api/admin/members/{memberCode}/change-history (read-only).
|
|
||||||
|
|
||||||
export async function GET(_req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
|
|
||||||
const token = await getToken();
|
|
||||||
if (!token) return unauthorized();
|
|
||||||
|
|
||||||
const { memberCode } = await ctx.params;
|
|
||||||
const result = await callMobileApi<AdminMemberChangeEntry[]>(
|
|
||||||
`/api/admin/members/${encodeURIComponent(memberCode)}/change-history`,
|
|
||||||
{ token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -1,72 +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/members/BB0100/change-sponsor", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
}) as unknown as Parameters<typeof POST>[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
const ctx = { params: Promise.resolve({ memberCode: "BB0100" }) };
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mocks.callMobileApi.mockReset();
|
|
||||||
mocks.getToken.mockReset();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("POST /api/admin/members/[memberCode]/change-sponsor", () => {
|
|
||||||
it("forwards the new sponsor and trimmed reason with the admin JWT", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { success: true } });
|
|
||||||
|
|
||||||
const res = await POST(postReq({ newSponsorCode: "BB0001", reason: " Wrong referral code " }), ctx);
|
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/change-sponsor", {
|
|
||||||
method: "POST",
|
|
||||||
body: { newSponsorCode: "BB0001", reason: "Wrong referral code" },
|
|
||||||
token: "jwt-abc",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects a missing sponsor or a blank or over-long reason with 400 and forwards nothing", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
|
|
||||||
expect((await POST(postReq({ reason: "x" }), ctx)).status).toBe(400);
|
|
||||||
|
|
||||||
const blank = await POST(postReq({ newSponsorCode: "BB0001", reason: "" }), ctx);
|
|
||||||
expect(blank.status).toBe(400);
|
|
||||||
expect(await blank.json()).toEqual({ error: "A reason is required." });
|
|
||||||
|
|
||||||
const long = await POST(postReq({ newSponsorCode: "BB0001", reason: "x".repeat(256) }), ctx);
|
|
||||||
expect(long.status).toBe(400);
|
|
||||||
expect(await long.json()).toEqual({ error: "The reason must be 255 characters or fewer." });
|
|
||||||
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("passes an upstream refusal through", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The Rank & referral module (BO_RANK_REFERRAL) is required." });
|
|
||||||
|
|
||||||
const res = await POST(postReq({ newSponsorCode: "BB0001", reason: "x" }), ctx);
|
|
||||||
|
|
||||||
expect(res.status).toBe(403);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 without a session", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
|
|
||||||
const res = await POST(postReq({ newSponsorCode: "BB0001", reason: "x" }), ctx);
|
|
||||||
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,29 +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 { checkCorrectionReason } from "@/app/lib/correctionReason";
|
|
||||||
|
|
||||||
// POST -> /api/admin/members/{memberCode}/change-sponsor (referral / placement correction).
|
|
||||||
// Mutation lives on POST only. The actor is derived from the bb_admin JWT server-side and a reason
|
|
||||||
// is required (BABYBOO-43). A cycle-creating move is rejected upstream with 400, and a caller
|
|
||||||
// without BO_RANK_REFERRAL with 403; both pass through.
|
|
||||||
|
|
||||||
export async function POST(req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
|
|
||||||
const token = await getToken();
|
|
||||||
if (!token) return unauthorized();
|
|
||||||
|
|
||||||
const { memberCode } = await ctx.params;
|
|
||||||
const body = (await req.json().catch(() => ({}))) as { newSponsorCode?: string; reason?: unknown };
|
|
||||||
if (!body.newSponsorCode?.trim()) {
|
|
||||||
return NextResponse.json({ error: "A new sponsor code is required." }, { status: 400 });
|
|
||||||
}
|
|
||||||
const reason = checkCorrectionReason(body.reason);
|
|
||||||
if (!reason.ok) return NextResponse.json({ error: reason.error }, { status: 400 });
|
|
||||||
const result = await callMobileApi<{ success: boolean }>(
|
|
||||||
`/api/admin/members/${encodeURIComponent(memberCode)}/change-sponsor`,
|
|
||||||
{ method: "POST", body: { newSponsorCode: body.newSponsorCode, reason: reason.reason }, token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -1,77 +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/members/BB0100/correct-rank", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
}) as unknown as Parameters<typeof POST>[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
const ctx = { params: Promise.resolve({ memberCode: "BB0100" }) };
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mocks.callMobileApi.mockReset();
|
|
||||||
mocks.getToken.mockReset();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("POST /api/admin/members/[memberCode]/correct-rank", () => {
|
|
||||||
it("validates and forwards the rank and trimmed reason with the admin JWT", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { success: true } });
|
|
||||||
|
|
||||||
const res = await POST(postReq({ newRank: "squirrel", reason: " Set wrongly by admin " }), ctx);
|
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/correct-rank", {
|
|
||||||
method: "POST",
|
|
||||||
body: { newRank: "SQUIRREL", reason: "Set wrongly by admin" },
|
|
||||||
token: "jwt-abc",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects a missing or unknown rank with 400 and forwards nothing", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
|
|
||||||
expect((await POST(postReq({ reason: "x" }), ctx)).status).toBe(400);
|
|
||||||
expect((await POST(postReq({ newRank: "GOD", reason: "x" }), ctx)).status).toBe(400);
|
|
||||||
// remove-legacy-member-ranks: the old MLM ranks no longer exist.
|
|
||||||
for (const legacy of ["S1", "S2", "S3", "EM", "BP"]) {
|
|
||||||
expect((await POST(postReq({ newRank: legacy, reason: "x" }), ctx)).status).toBe(400);
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects a blank or over-long reason with 400 and forwards nothing", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
|
|
||||||
const blank = await POST(postReq({ newRank: "SQUIRREL", reason: " " }), ctx);
|
|
||||||
expect(blank.status).toBe(400);
|
|
||||||
expect(await blank.json()).toEqual({ error: "A reason is required." });
|
|
||||||
|
|
||||||
const missing = await POST(postReq({ newRank: "SQUIRREL" }), ctx);
|
|
||||||
expect(missing.status).toBe(400);
|
|
||||||
|
|
||||||
const long = await POST(postReq({ newRank: "SQUIRREL", reason: "x".repeat(256) }), ctx);
|
|
||||||
expect(long.status).toBe(400);
|
|
||||||
expect(await long.json()).toEqual({ error: "The reason must be 255 characters or fewer." });
|
|
||||||
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 without a session", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
|
|
||||||
const res = await POST(postReq({ newRank: "SQUIRREL", reason: "x" }), ctx);
|
|
||||||
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -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 { checkCorrectionReason } from "@/app/lib/correctionReason";
|
|
||||||
|
|
||||||
// POST -> /api/admin/members/{memberCode}/correct-rank (rank correction, I4; BABYBOO-43).
|
|
||||||
// Mutation lives on POST only. The actor is derived from the bb_admin JWT server-side
|
|
||||||
// (mobile-api); the rank is validated against the shared enum upstream and a reason is required.
|
|
||||||
// A caller without the BO_RANK_REFERRAL module is refused upstream with 403 and that passes through.
|
|
||||||
|
|
||||||
const KNOWN_RANKS = ["NA", "M", "OTTER", "SQUIRREL", "GIRAFFE"];
|
|
||||||
|
|
||||||
export async function POST(req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
|
|
||||||
const token = await getToken();
|
|
||||||
if (!token) return unauthorized();
|
|
||||||
|
|
||||||
const { memberCode } = await ctx.params;
|
|
||||||
const body = (await req.json().catch(() => ({}))) as { newRank?: string; reason?: unknown };
|
|
||||||
const newRank = body.newRank?.trim().toUpperCase();
|
|
||||||
if (!newRank || !KNOWN_RANKS.includes(newRank)) {
|
|
||||||
return NextResponse.json({ error: "A valid rank is required." }, { status: 400 });
|
|
||||||
}
|
|
||||||
const reason = checkCorrectionReason(body.reason);
|
|
||||||
if (!reason.ok) return NextResponse.json({ error: reason.error }, { status: 400 });
|
|
||||||
const result = await callMobileApi<{ success: boolean }>(
|
|
||||||
`/api/admin/members/${encodeURIComponent(memberCode)}/correct-rank`,
|
|
||||||
{ method: "POST", body: { newRank, reason: reason.reason }, token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -1,35 +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/members/BB0100/edit-initialize") as unknown as Parameters<typeof GET>[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mocks.callMobileApi.mockReset();
|
|
||||||
mocks.getToken.mockReset();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("GET /api/admin/members/[memberCode]/edit-initialize", () => {
|
|
||||||
it("forwards the member code and admin JWT", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { nationalities: [], banks: [] } });
|
|
||||||
const res = await GET(getReq(), { params: Promise.resolve({ memberCode: "BB0100" }) });
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/edit-initialize", {
|
|
||||||
token: "jwt-abc",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 without a session", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
const res = await GET(getReq(), { params: Promise.resolve({ memberCode: "BB0100" }) });
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,20 +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 { AdminEditInitialize } from "@/app/lib/types";
|
|
||||||
|
|
||||||
// GET -> /api/admin/members/{memberCode}/edit-initialize (geo cascade + nationality/bank options).
|
|
||||||
|
|
||||||
export async function GET(_req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
|
|
||||||
const token = await getToken();
|
|
||||||
if (!token) return unauthorized();
|
|
||||||
|
|
||||||
const { memberCode } = await ctx.params;
|
|
||||||
const result = await callMobileApi<AdminEditInitialize>(
|
|
||||||
`/api/admin/members/${encodeURIComponent(memberCode)}/edit-initialize`,
|
|
||||||
{ token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -1,20 +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 { AdminSponsorHistoryPage } from "@/app/lib/types";
|
|
||||||
|
|
||||||
// GET -> /api/admin/members/{memberCode}/placement-history (read-only).
|
|
||||||
|
|
||||||
export async function GET(_req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
|
|
||||||
const token = await getToken();
|
|
||||||
if (!token) return unauthorized();
|
|
||||||
|
|
||||||
const { memberCode } = await ctx.params;
|
|
||||||
const result = await callMobileApi<AdminSponsorHistoryPage>(
|
|
||||||
`/api/admin/members/${encodeURIComponent(memberCode)}/placement-history`,
|
|
||||||
{ token },
|
|
||||||
);
|
|
||||||
if (!result.ok) return errorResponse(result);
|
|
||||||
return NextResponse.json(result.data);
|
|
||||||
}
|
|
||||||
@@ -1,90 +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, PUT } from "./route";
|
|
||||||
|
|
||||||
function getReq(memberCode: string) {
|
|
||||||
const req = new Request(`http://localhost/api/admin/members/${memberCode}`) as unknown as Parameters<typeof GET>[0];
|
|
||||||
const ctx = { params: Promise.resolve({ memberCode }) };
|
|
||||||
return { req, ctx };
|
|
||||||
}
|
|
||||||
|
|
||||||
function putReq(memberCode: string, body: unknown) {
|
|
||||||
const req = new Request(`http://localhost/api/admin/members/${memberCode}`, {
|
|
||||||
method: "PUT",
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
}) as unknown as Parameters<typeof PUT>[0];
|
|
||||||
const ctx = { params: Promise.resolve({ memberCode }) };
|
|
||||||
return { req, ctx };
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mocks.callMobileApi.mockReset();
|
|
||||||
mocks.getToken.mockReset();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("GET /api/admin/members/[memberCode]", () => {
|
|
||||||
it("forwards the member code and admin JWT to GET /api/admin/members/{memberCode}", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { memberCode: "BB0100" } });
|
|
||||||
const { req, ctx } = getReq("BB0100");
|
|
||||||
const res = await GET(req, ctx);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100", { token: "jwt-abc" });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 without a session", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
const { req, ctx } = getReq("BB0100");
|
|
||||||
const res = await GET(req, ctx);
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("passes through a genuine upstream 404 so the page shows its not-found state", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Member not found", status: 404 });
|
|
||||||
const { req, ctx } = getReq("NOPE");
|
|
||||||
const res = await GET(req, ctx);
|
|
||||||
expect(res.status).toBe(404);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("PUT /api/admin/members/[memberCode]", () => {
|
|
||||||
it("forwards the edit body and admin JWT to PUT /api/admin/members/{memberCode}", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { success: true } });
|
|
||||||
const body = { name: "AINA TAN", email: "aina@example.com" };
|
|
||||||
const { req, ctx } = putReq("BB0100", body);
|
|
||||||
const res = await PUT(req, ctx);
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100", {
|
|
||||||
method: "PUT",
|
|
||||||
body,
|
|
||||||
token: "jwt-abc",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("passes through a 400 validation error from upstream", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
|
||||||
mocks.callMobileApi.mockResolvedValue({
|
|
||||||
ok: false,
|
|
||||||
error: "Age should be greater than 18 years.",
|
|
||||||
status: 400,
|
|
||||||
});
|
|
||||||
const { req, ctx } = putReq("BB0100", { name: "AINA TAN" });
|
|
||||||
const res = await PUT(req, ctx);
|
|
||||||
expect(res.status).toBe(400);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 without a session", async () => {
|
|
||||||
mocks.getToken.mockResolvedValue(null);
|
|
||||||
const { req, ctx } = putReq("BB0100", {});
|
|
||||||
const res = await PUT(req, ctx);
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||