chore: repo foundation and local stack (change 1) #1

Merged
ngqile merged 16 commits from add-repo-foundation-local-stack into main 2026-11-26 11:10:43 +00:00
2944 changed files with 309202 additions and 1 deletions

No files matched your search

+4
View File
@@ -5,6 +5,7 @@
# Local env and secrets
.env
.env.*
!.env.example
*.key
*service-account*.json
@@ -14,3 +15,6 @@
# Playwright
.playwright-mcp/
# Build output
target/
+3 -1
View File
@@ -9,7 +9,7 @@ Co-Lite: event CRM for a single company (multi-company SaaS later), cloned from
## Status
Pre-design. No code has been ported yet. Repo layout, module list and the porting approach are decided in the first brainstorm, then recorded as an OpenSpec change.
Phase 1 design: `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md`. Change 1 (`add-repo-foundation-local-stack`) ports the kept Tastefully modules and portals and adds the local stack; see `local/README.md` to run it.
## Fixed Decisions
@@ -17,3 +17,5 @@ Pre-design. No code has been ported yet. Repo layout, module list and the portin
- Admin screens call JSON admin APIs (`/api/admin/**`) in `mobile-api`.
- New tables carry a company id so a later multi-company move is a migration, not a rebuild.
- When porting a module, list the old screen's business rules first and turn them into tests before building the new screen.
- Exception to the SQL-placement rule: runnable local seed files live in `local/seed/` (loaded by docker-compose on an empty volume). Schema and DDL changes for real environments still go in the OpenSpec change folder.
- Never copy Tastefully customer data (members, users, attendance, orders) into this repo or a local database. Seeds use schema-only and reference-table dumps.
@@ -0,0 +1,183 @@
# Co-Lite Phase 1 — Foundation and Lead Tracking
Date: 2026-11-26
Status: Draft for approval
## Intent
Co-Lite is an event CRM for one company, cloned from Tastefully (Solvway platform). Go-live is 15 January 2027, seven weeks from this design, with two developers.
Success on go-live day is one thing: **staff can track leads at an event.** A salesperson keys a lead into the admin portal during an event. The system tells them whether the person is new or already known. Sales can then work through their leads after the event. Everything else on the feature list waits for later phases.
Nothing is deployed yet. Phase 1 is built to run end to end on a developer machine first, then deployed to the team's own Kubernetes cluster before go-live.
## Goals
- One repository that holds the Co-Lite backend modules, the admin portal and the customer portal, and runs locally with one command.
- Admin portal (Next.js, modelled on babyboo's `solvway-admin-portal`) with staff login, users and roles, events, leads and event leads.
- Lead capture with New/Existing detection, a salesperson assigned per lead per event, and follow-up tracking.
- New tables carry a company id.
- Key-in form and Event Leads Listing usable on a phone or iPad at the event.
- Deployed to the team's Kubernetes cluster by go-live.
## Non-goals (phase 1)
- WhatsApp inbox. It becomes its own service in a later phase. Start Meta business verification now; it needs no code.
- Vouchers, partners and partner vouchers, pop-up and featured ads, product flyers, Spin & Win, Blindbox, achievement board, notifications.
- Member-app changes. The customer portal is copied in but not stripped or re-skinned in phase 1.
- Visitor self-registration as a lead, and linking leads to members.
- Merging duplicate leads.
- Per-salesperson visibility. All staff see all leads.
- Importing existing leads. The user confirmed none exist; every lead on 15 January starts as NEW.
- Audit log of lead changes (my call: rows keep updated_by / updated_at; babyboo's audit pipeline is ported later).
## Anti-goals
- A lead captured twice as two records because staff typed the same phone in another format.
- A New/Existing flag that changes after capture. It records what was true at that event.
- Porting Tastefully screens that do not serve lead tracking "while we're at it".
- Deploying or extending the Tastefully Thymeleaf backoffice.
## Constraints
- Java 21, Spring Boot 3.2, Maven multi-module, MySQL (one schema per service), Redis, Google Pub/Sub. These are inherited from Tastefully.
- Schemas are managed by hand-written DDL (no `ddl-auto`, no Flyway). DDL lives in the OpenSpec change folder.
- `mobile-api` has no tables. It calls services through `solvway-api-gateway`. Every admin screen needs an `/api/admin/**` endpoint in `mobile-api` plus the service endpoints behind it.
- Admin portal stack follows babyboo: Next.js 16, React 19, TanStack Table, Vitest.
- Treat any reachable database as production: read-only.
- Production runs on the team's own Kubernetes cluster. Google Pub/Sub stays (reached from the cluster with a service-account key; emulator locally). My call: replacing Pub/Sub touches about 12 modules and does not fit phase 1.
- Staff key leads in on phones and iPads, so the screens they use at the event must work at those sizes.
## Approaches considered
| | Approach | Trade-off |
|---|---|---|
| **A (chosen)** | One repo with a trimmed copy of Tastefully. Leads live in `services-counter`, next to `Event` and `EventAttendance`. | Cheapest. No new service. Event and lead data share one schema, so listings are plain joins, and the Event Leads Listing can follow the attendance listing pattern. Cost: `services-counter` stays a broad service of about 50 tables. |
| B | Same repo, leads in a new `services-lead`. | Cleaner boundary, but about 2 extra days of setup (Dockerfile, gateway route, local profile, schema), plus a batched cross-service call for event names. Too costly against seven weeks. |
| C | Collapse services into one application. | A rewrite. Does not fit the timeline. |
The user picked A.
## Decisions
### Repository layout
One git repository (`co-lite`), matching Tastefully and babyboo:
```
co-lite/
solvway-core-libs/
solvway-core-session/
solvway-api-gateway/
solvway-mobile-api/
solvway-services-auth/
solvway-services-system/ admin users, roles, modules/menus
solvway-services-counter/ events, attendance, leads, event leads
solvway-services-member/
solvway-services-log/
solvway-services-email/ password reset and notices
solvway-admin-portal/ from babyboo, cut down
solvway-customer-portal/ from Tastefully, untouched in phase 1
local/ docker-compose and seed data
docs/ openspec/
```
**Dropped:** bonus, stockist, inventory, payment, payment-gateway, job-bonus, job-flush-pending-sales, job-parse-tree, member-portal, stockist-portal, services-css, services-drive, services-report, services-staff, api-mobile-gateway, backoffice.
The backoffice is read in place at `~/Projects/tastefully` for business rules. It is not copied.
**Porting rule:** remove whole modules only. Inside a kept module, remove code only where it will not compile or start without a dropped module. That includes gateway routes and Pub/Sub subscriptions that point at dropped services. No other trimming in phase 1.
### Local environment
- `local/docker-compose.yml` runs MySQL, Redis and the Pub/Sub emulator.
- Each kept Java module gets a `local` Spring profile pointing at them.
- The Next.js apps run with `npm run dev` against the local gateway.
- Every kept module and both Next.js apps get a Dockerfile (most exist already) so the same images run locally and on Kubernetes.
- One documented command brings the stack up. A seed script creates the schemas and the minimum reference data: one company, an admin user, roles and menus.
### Deployment
The last phase 1 change deploys to the team's Kubernetes cluster: images, manifests, secrets (DB, Redis, Pub/Sub key, SMTP), ingress with TLS and a domain, and real SMTP for password reset. Only after the local stack works end to end. Cluster specifics (registry, ingress controller, MySQL hosting) are gathered when that change is written.
### Who is a salesperson
A salesperson is an admin-portal user (`services-system` User) with a Sales role. They key leads in themselves, so they need a login anyway. This is why `services-staff` is dropped.
### Admin portal
Start from babyboo's `solvway-admin-portal`: shell, auth, role-based menus and table components. Remove every babyboo screen not listed here.
The event-floor screens (Event Leads Listing, key-in form, event lead edit, lead detail) are responsive down to phone width: the listing collapses to cards, the key-in form is a single column with large touch targets and the right keyboard for phone and email fields. Back-office screens (users, roles, events, interests) stay desktop-first.
Phase 1 screens:
1. Login, first-login password change, forgot/reset password.
2. Users: list, create, edit, deactivate, assign roles.
3. Roles: list, create, edit permissions.
4. Events: list, create, edit. Keep only the fields Co-Lite needs from Tastefully's event model.
5. Lead Listing.
6. Event Leads Listing, with the key-in form.
7. Lead detail: the lead's fields plus their event history.
8. Interests: manage the product/service list used to tag leads.
`mobile-api` gains the matching `/api/admin/**` controllers. Adapt them from babyboo's AdminAuth, AdminUser and AdminRole controllers onto Tastefully's `services-system`. AdminEvent is built new against Tastefully's event model, because babyboo's version does not match it.
### Lead data model (in `services-counter`)
**lead** (one row per person)
- id, uuid, company_id
- name, mobile_e164 (nullable), email_normalised (nullable), company_name, job_title, notes
- created_by, created_at, updated_by, updated_at
- At least one of mobile or email is required.
- Indexed, not unique: (company_id, mobile_e164) and (company_id, email_normalised). My call: a shared office or family phone must not block capturing a real person.
**event_lead** (one row per lead per event)
- id, uuid, company_id, event_uuid, lead_uuid
- salesperson_user_id (nullable)
- lead_type: NEW or EXISTING, set at capture and never recalculated
- temperature: HOT, WARM or COLD
- status: OPEN, CONTACTED, QUALIFIED, WON or LOST
- next_follow_up_date, notes
- captured_by, captured_at, updated_by, updated_at
- Unique (event_uuid, lead_uuid).
**interest** (admin-managed list): id, company_id, name, active, sort_order.
**event_lead_interest**: event_lead_id, interest_id.
### Capture and matching rules
1. Staff enter mobile and/or email. The mobile is normalised to E.164, defaulting to the Malaysian country code (+60) when no country code is given. The email is trimmed and lowercased.
2. The system looks for leads matching either value within the company.
- **No match:** a new lead is created, and the event lead is marked NEW.
- **One or more matches:** staff pick the matching person, or choose "different person", which creates a new lead (NEW) carrying the same value.
- **Picked a match:** The event lead is marked EXISTING. If staff entered details the lead did not have, they fill the blanks; existing values are not overwritten.
- Mobile and email matching different leads is the same case: all candidates are shown and staff pick one. No automatic merge.
3. A lead already captured at this event cannot be captured again. The form opens the existing event lead instead.
4. A lead is EXISTING if it existed before this capture, at any event or entered any other way.
### Listings
- **Lead Listing:** all leads. Search by name, mobile or email. Each row shows the number of events, the last event and the latest salesperson. Paginated server-side. CSV export.
- **Event Leads Listing:** one event's leads. Columns: name, mobile, email, NEW/EXISTING, salesperson, temperature, status, interests, next follow-up. Filters: salesperson, temperature, status, interest, NEW/EXISTING. Paginated server-side. CSV export.
- Event lead edits: salesperson, temperature, status, interests, next follow-up and notes.
- Lead edits (lead detail page, edit permission): name, mobile, email, company, job title, notes. Same normalisation as capture. If the new mobile or email belongs to another lead, the other lead is shown as a warning; the save is allowed and nothing is merged (my call).
### Access
- All staff with lead access see all leads.
- Permissions follow babyboo's per-screen module access (`@AdminModule` plus module-to-role mapping), since the portal comes from babyboo. Separate modules for view leads, edit leads, export leads, manage interests, manage events, manage users/roles (my call).
- Export is a separate permission because it moves customer data out of the system.
### Company id
New tables (lead, event_lead, interest, event_lead_interest) carry `company_id NOT NULL`. Tastefully's admin `user` has no company field, so phase 1 adds a `company_id` column to it (my call; the only change to an existing table) and a small `company` table in `services-system`. The seed creates one company and assigns every user to it. Lead APIs take the company id from the logged-in user, never from the request.
## Left to the builder
- Which Tastefully event fields to keep in the Co-Lite event form, read from `solvway-backoffice` event templates.
- Exact permission names, following existing ROLE_* naming.
- Table component reuse and page layout, following babyboo.
- The phone normalisation library. Check whether one is already present before adding one.
- Whether to keep babyboo's login-lockout and session-policy screens; they depend on endpoints Tastefully's `services-system` lacks. Default: drop.
- The OpenSpec change split. Suggested: (1) repo setup and local stack, (2) admin auth, users and roles, (3) events, (4) leads and event leads, (5) Kubernetes deployment.
+20
View File
@@ -0,0 +1,20 @@
# Local docker-compose stack only. Dev values, never used anywhere else.
# up.sh copies this to local/.env (git-ignored) on first run.
MYSQLHOST=mysql
MYSQLPORT=3306
MYSQLUSER=root
MYSQLPWD=colite-dev
REDISHOST=redis
GCP_PROJECT=co-lite-local
GCP_CREDENTIAL_FILE=
APIGATEWAYURL=http://api-gateway
AES_SECRET_KEY=colite-local-aes-key
# Auth service signs and mobile-api verifies, so both must hold the same value (32+ chars).
JWT_TOKEN=colite-local-jwt-secret-0123456789abcdef
JWT_SECRET=colite-local-jwt-secret-0123456789abcdef
USER_AUTH_API_SECRET=colite-local-user-auth-secret
# mobile-api -> gateway key; must match a key in local/appkeys.json.
APIKEY=colite-local-gateway-key-000000000000
# Inbound keys clients send to mobile-api: "<key>:<PLATFORM>" (APP or CP).
AUTH_API_KEYS=colite-local-app-key:APP,colite-local-cp-key:CP
JAVA_OPTS=-Xmx384m
+66
View File
@@ -0,0 +1,66 @@
# Co-Lite local stack
Runs the whole Co-Lite backend on your machine: MySQL, Redis, the Pub/Sub emulator and the eight Java services, with the same service names as Kubernetes. Everything here is dev-only.
## Prerequisites
- JDK 21 and Maven 3.9+
- Docker with Compose v2
- Access to the base image registry: `docker login gitea.containerverse.dev`
- About 6 GB of free RAM
## Start
From the repository root:
```sh
local/up.sh
```
This copies `local/.env.example` to `local/.env` (git-ignored) if it is missing, builds every module with `mvn -T 1C -DskipTests package`, and starts the stack. The services take about a minute to boot after MySQL finishes seeding.
Then check it:
```sh
local/smoke.sh
```
It prints `smoke: OK` when admin login, a service-counter read and a public mobile-api call all succeed.
| What | Where |
|---|---|
| mobile-api | http://localhost:8080 (header `api-key: colite-local-app-key`) |
| api-gateway | http://localhost:8081 (header `api-key: colite-local-gateway-key-000000000000`) |
| MySQL | localhost:3307, user `root`, password `colite-dev` |
| Admin login | `admin` / `colite-dev-admin` |
## Reset
Deletes the database volume; the next start reseeds from `local/seed/`:
```sh
docker compose -f local/docker-compose.yml down -v
local/up.sh
```
## Seed data
`local/seed/` is loaded only when the MySQL volume is empty, in file-name order:
- `00-schemas.sql`: creates the five service schemas.
- `01-schema.sql`: table structure from a Tastefully schema-only dump.
- `02-reference.sql`: allow-listed reference rows (roles, modules, lookups, messages).
- `03-colite.sql`: the Co-Lite company and the dev admin login.
Never put Tastefully customer data (members, users, attendance, orders) in these files.
## Rebuild one service after a change
```sh
mvn -T 1C -B -q -DskipTests -pl solvway-services-counter -am package
docker compose -f local/docker-compose.yml up -d --build service-counter
```
`-am` builds the core library alongside the module; a module cannot be built alone because the `colite-v1` core library is not installed in `~/.m2` by default.
Services reach each other by container name (`service-system`, `api-gateway` and so on), so a service run from an IDE outside Docker cannot join the stack. Run it inside the stack and attach a debugger instead: add `-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005` to `JAVA_OPTS` for that service and publish port 5005.
+10
View File
@@ -0,0 +1,10 @@
[
{
"key": "colite-local-gateway-key-000000000000",
"name": "Local mobile-api",
"desc": "Local docker-compose only",
"type": "BO",
"allowList": ["/"],
"ipList": ["0.0.0.0/0"]
}
]
+116
View File
@@ -0,0 +1,116 @@
# Local dev stack. Service names match the Kubernetes service names.
name: co-lite
services:
mysql:
image: mysql:8.0
# Match the Tastefully server: dumped functions are not declared DETERMINISTIC, and some tables exceed strict row-size limits.
command: --log-bin-trust-function-creators=1 --innodb-strict-mode=OFF
environment:
MYSQL_ROOT_PASSWORD: ${MYSQLPWD}
ports: ["3307:3306"]
volumes:
- mysql-data:/var/lib/mysql
- ./seed:/docker-entrypoint-initdb.d:ro
healthcheck:
# TCP, not the socket: the init-time server has networking off, so this only passes after seeding.
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-p${MYSQLPWD}"]
interval: 5s
retries: 60
redis:
image: redis:7
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
retries: 20
pubsub:
image: gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators
command: gcloud beta emulators pubsub start --host-port=0.0.0.0:8085 --project=co-lite-local
healthcheck:
test: ["CMD", "curl", "-sf", "http://localhost:8085"]
interval: 5s
retries: 30
pubsub-init:
image: curlimages/curl:8.11.1
entrypoint: ["sh", "/pubsub/init.sh"]
volumes:
- ./pubsub:/pubsub:ro
depends_on:
pubsub: {condition: service_healthy}
api-gateway:
build:
context: ../solvway-api-gateway
args: {BUILD_PROFILE: local}
env_file: .env
depends_on:
mysql: {condition: service_healthy}
redis: {condition: service_healthy}
pubsub-init: {condition: service_completed_successfully}
ports: ["8081:80"]
volumes:
- ./appkeys.json:/deployments/appkeys/appkeys.json:ro
mobile-api:
build:
context: ../solvway-mobile-api
args: {BUILD_PROFILE: local}
env_file: .env
depends_on:
mysql: {condition: service_healthy}
redis: {condition: service_healthy}
pubsub-init: {condition: service_completed_successfully}
ports: ["8080:80"]
service-auth:
build:
context: ../solvway-services-auth
args: {BUILD_PROFILE: local}
env_file: .env
depends_on:
mysql: {condition: service_healthy}
redis: {condition: service_healthy}
pubsub-init: {condition: service_completed_successfully}
service-system:
build:
context: ../solvway-services-system
args: {BUILD_PROFILE: local}
env_file: .env
depends_on:
mysql: {condition: service_healthy}
redis: {condition: service_healthy}
pubsub-init: {condition: service_completed_successfully}
service-counter:
build:
context: ../solvway-services-counter
args: {BUILD_PROFILE: local}
env_file: .env
depends_on:
mysql: {condition: service_healthy}
redis: {condition: service_healthy}
pubsub-init: {condition: service_completed_successfully}
service-member:
build:
context: ../solvway-services-member
args: {BUILD_PROFILE: local}
env_file: .env
depends_on:
mysql: {condition: service_healthy}
redis: {condition: service_healthy}
pubsub-init: {condition: service_completed_successfully}
service-log:
build:
context: ../solvway-services-log
args: {BUILD_PROFILE: local}
env_file: .env
depends_on:
mysql: {condition: service_healthy}
redis: {condition: service_healthy}
pubsub-init: {condition: service_completed_successfully}
service-email:
build:
context: ../solvway-services-email
args: {BUILD_PROFILE: local}
env_file: .env
depends_on:
mysql: {condition: service_healthy}
redis: {condition: service_healthy}
pubsub-init: {condition: service_completed_successfully}
volumes:
mysql-data:
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Creates every topic and subscription in topics.txt on the Pub/Sub emulator. Idempotent.
set -eu
base="http://pubsub:8085/v1/projects/co-lite-local"
grep -v '^#' /pubsub/topics.txt | while read -r topic sub; do
[ -z "$topic" ] && continue
code=$(curl -s -o /dev/null -w '%{http_code}' -X PUT "$base/topics/$topic")
case $code in 200|409) ;; *) echo "topic $topic failed: HTTP $code"; exit 1;; esac
if [ -n "${sub:-}" ]; then
code=$(curl -s -o /dev/null -w '%{http_code}' -X PUT -H 'Content-Type: application/json' \
-d "{\"topic\":\"projects/co-lite-local/topics/$topic\"}" "$base/subscriptions/$sub")
case $code in 200|409) ;; *) echo "subscription $sub failed: HTTP $code"; exit 1;; esac
fi
done
echo "pubsub-init: done"
+42
View File
@@ -0,0 +1,42 @@
# topic [subscription] - one per line; created in the Pub/Sub emulator before services start
activate-member-topic activate-member-subscription
backoffice-topic backoffice-subscription
batch-transfer-member-topic batch-transfer-member-subscription
camunda-new-registration-topic camunda-new-registration-subscription
create-merchant-sales-topic create-merchant-sales-subscription
create-stockist-branch-topic create-stockist-branch-subscription
email-save-request-topic email-save-request-subscription
email-topic email-subscription
error-log-topic error-log-subscription
event-attendance-topic event-attendance-subscription
exist-member-jumio-success-topic exist-member-jumio-success-subscription
extend-member-expiry-topic extend-member-expiry-subscription
generate-credit-note-doc-topic generate-credit-note-doc-subscription
generate-order-doc-topic generate-order-doc-subscription
indo-member-jumio-success-topic indo-member-jumio-success-subscription
indo-member-remain-my-topic indo-member-remain-my-subscription
kyc-jumio-topic kyc-jumio-subscription
member-topic member-subscription
new-member-add-user-topic new-member-add-user-subscription
new-member-topic new-member-subscription
new-preferred-customer-add-user-topic new-preferred-customer-add-user-subscription
new-reg-order-topic new-reg-order-subscription
new-stockist-add-user-topic new-stockist-add-user-subscription
order-paid-topic order-paid-subscription
response-time-log-topic response-time-log-subscription
sms-topic sms-subscription
transfer-member-migrate-sales-topic transfer-member-migrate-sales-subscription
update-branch-warehouse-topic update-branch-warehouse-subscription
update-promotion-code-topic update-promotion-code-subscription
update-sync-topic update-sync-member-subscription
update-sync-topic update-sync-system-subscription
voucher-update-invoice-topic voucher-update-invoice-topic
create-branch-warehouse-topic
inventory-remark-update-topic
save-consignment-trxn-topic
save-sales-submission-trxn-topic
tastefully-rewards-topic
transfer-member-wallet-topic
update-stockist-branch-topic
update-stockist-sales-inventory-topic
wallet-update-invoice-topic
+6
View File
@@ -0,0 +1,6 @@
-- Local dev only. Creates the empty service schemas; 01-schema.sql (Tastefully dump) fills them.
CREATE DATABASE IF NOT EXISTS `service-system` CHARACTER SET utf8mb4;
CREATE DATABASE IF NOT EXISTS `service-counter` CHARACTER SET utf8mb4;
CREATE DATABASE IF NOT EXISTS `service-member` CHARACTER SET utf8mb4;
CREATE DATABASE IF NOT EXISTS `service-log` CHARACTER SET utf8mb4;
CREATE DATABASE IF NOT EXISTS `service-email` CHARACTER SET utf8mb4;
File diff suppressed because it is too large. Load diff
+298
View File
@@ -0,0 +1,298 @@
-- Local dev only. Tastefully reference rows for service-system (allow-listed tables).
-- supported_user_agent rows omitted (captured traffic, not setup data).
USE `service-system`;
-- MySQL dump 10.13 Distrib 8.0.19, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: service-system
-- ------------------------------------------------------
-- Server version 8.4.8
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Dumping data for table `country_nationality`
--
LOCK TABLES `country_nationality` WRITE;
/*!40000 ALTER TABLE `country_nationality` DISABLE KEYS */;
INSERT INTO `country_nationality` VALUES (55,1),(55,2),(55,3),(55,4),(55,5),(55,6),(55,7),(55,8),(55,9),(55,10),(55,11),(55,12),(55,13),(55,14),(55,15),(55,16),(55,17),(55,18),(55,19),(55,20),(55,21),(55,22),(55,23),(55,24),(55,25),(55,26),(55,27),(55,28),(55,29),(55,30),(55,31),(55,32),(55,33),(55,34),(55,35),(55,36),(55,37),(55,38),(55,39),(55,40),(55,41),(55,42),(55,43),(55,44),(55,45),(55,46),(55,47),(55,48),(55,49),(55,50),(55,51),(55,52),(55,53),(55,54),(55,55),(55,56),(55,57),(55,58),(55,59),(55,60),(55,61),(55,62),(55,63),(55,64),(55,65),(55,66),(55,67),(55,68),(55,69),(55,70),(55,71),(55,72),(55,73),(55,74),(55,75),(55,76),(55,77),(55,78),(55,79),(55,80),(55,81),(55,82),(55,83),(55,84),(55,85),(55,86),(55,87),(55,88),(55,89),(55,90),(55,91),(55,92),(55,93),(55,94),(55,95),(55,96),(55,97),(55,98),(55,99),(55,100),(55,101),(55,102),(55,103),(55,104),(55,105),(55,106),(55,107),(55,108),(55,109),(55,110),(55,111),(55,112),(55,113),(55,114),(55,115),(55,116),(55,117),(55,118),(55,119),(55,120),(55,121),(55,122),(55,123),(55,124),(55,125),(55,126),(55,127),(55,128),(55,129),(55,130),(55,131),(55,132),(55,133),(55,134),(55,135),(55,136),(55,137),(55,138),(55,139),(55,140),(55,141),(55,142),(55,143),(55,144),(55,145),(55,146),(55,147),(55,148),(55,149),(55,150),(55,151),(55,152),(55,153),(55,154),(55,155),(55,156),(55,157),(55,158),(55,159),(55,160),(55,161),(55,162),(55,163),(55,164),(55,165),(55,166),(55,167),(55,168),(55,169),(55,170),(55,171),(55,172),(55,173),(55,174),(55,175),(55,176),(55,177),(55,178),(55,179),(55,180),(55,181),(55,182),(55,183),(55,184),(55,185),(55,186),(55,187),(55,188),(55,189),(55,190),(55,191),(55,192),(55,193),(55,194),(55,195),(55,196),(55,197),(55,198),(55,199),(55,200),(55,201),(55,202),(55,203),(55,204),(55,205),(55,206),(55,207),(55,208),(55,209),(55,210),(55,211),(55,212),(55,213),(55,214),(55,215),(55,216),(55,217),(55,218),(55,219),(55,220),(55,221),(55,222),(55,223),(55,224),(55,225),(55,226),(55,227),(55,228),(55,229),(55,230),(55,231),(55,232),(55,233),(55,234),(55,235),(55,236),(55,237),(55,238),(56,2),(57,6),(58,5),(64,3);
/*!40000 ALTER TABLE `country_nationality` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `marrital_status`
--
LOCK TABLES `marrital_status` WRITE;
/*!40000 ALTER TABLE `marrital_status` DISABLE KEYS */;
INSERT INTO `marrital_status` VALUES (1,'S','Single','SINGLE','N'),(2,'M','Married','MARRIED','Y'),(3,'T2','TEST2','TEST_TAG2','N'),(4,'S1','Divorced','DIVORCED','N'),(5,'5','test 1','testing','N'),(6,'6','test 2','testing 2','N'),(7,'7','test 3','testing 3','N'),(8,'8','test 8','testing 8','N'),(9,'9','test 9','testing 9','N'),(10,'10','test 10','testing 10','N'),(11,'11','test 001','testing 001','N'),(12,'T9','Test Spouse','T9','Y'),(13,'a','a','','Y'),(14,'W01','Widowed','WIDOWED','N'),(15,'L01','Living Apart','LIVINGAPART','N'),(16,'D','Divorced','Divorced','N');
/*!40000 ALTER TABLE `marrital_status` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `module`
--
LOCK TABLES `module` WRITE;
/*!40000 ALTER TABLE `module` DISABLE KEYS */;
INSERT INTO `module` VALUES (10000000,'BackOffice','Back Office','A','R',0,NULL,NULL),(12000000,'MEMBER','Member','A','M',10000000,NULL,'mdi mdi-account'),(12010000,'MemberOperations','Member','A','M',12000000,NULL,NULL),(12010010,'MemberRegistration','Add Member','A','M',12010000,'/admin/members/newMemberPreform',NULL),(12010100,'SearchMEMBER','Search MEMBER','A','M',12010000,'/admin/members',NULL),(12010110,'UpdateMember','Update Member','A','A',12010000,NULL,NULL),(12010120,'ViewMember','View Member','A','A',12010000,NULL,NULL),(12010500,'ChangeBankDetails','Change Bank Details','A','M',12010000,'/admin/members/chgBankDetails',NULL),(12010790,'ResetMemberUsername','Reset Member Username','A','M',12010000,'/admin/members/resetMemberUsername',NULL),(12010800,'ResetMemberPassword','Reset Member Password','A','M',12010000,'/admin/members/resetMemberPassword',NULL),(12010900,'ResetMemberPasswordSecondary','Reset Member Password Secondary','A','M',12010000,'/admin/members/resetMemberPasswordSecondary',NULL),(12011200,'ChangeMemberStatus','Change MEMBER Status','A','M',12010000,'/admin/members/changeMemberStatus',NULL),(12011300,'MemberStatusHistoryListing','MEMBER Membership Status Listing','A','M',12010000,'/admin/members/memberStatusHistoryListing',NULL),(12011400,'ChangeMemberRank','ChangeMemberRank','A','M',12010000,'/admin/members/changeMemberRank',NULL),(12011901,'RemovePendingMember','RemovePendingMember','A','M',12010000,'/admin/members/removePendingMember',NULL),(12020000,'SponsorNetwork','Sponsor Network','A','M',12000000,NULL,NULL),(12020100,'SponsorTree','Sponsor Tree','A','M',12020000,'/admin/members/networkTreeV2',NULL),(12020200,'DownlineListing','Downline Listing','A','M',12020000,'/admin/members/downlineListing',NULL),(12020300,'UplineListing','Upline Listing','A','M',12020000,'/admin/members/uplineListing',NULL),(12020400,'ChangeSponsor','Change Sponsor','A','M',12030000,'/admin/members/changeSponsor',NULL),(12020500,'ChangeSponsorListing','Change Sponsor Listing','A','M',12030000,'/admin/members/changeSponsorListing',NULL),(12030000,'SponsorChange','SponsorChange','A','M',12000000,NULL,NULL),(12600000,'Stockist','Stockist','A','M',10000000,NULL,'icon-people'),(12610000,'StockistTask','StockistTask','A','M',12600000,NULL,NULL),(12610100,'StockistRegistration','StockistRegistration','A','M',12610000,'/admin/stockists/newStockist',NULL),(12610200,'StockistListing','StockistListing','A','M',12610000,'/admin/stockists/stockistListing',NULL),(12610210,'UpdateStockist','Update Stockist','A','A',12610000,NULL,NULL),(12610300,'ActivateOrDeactivate','ActivateOrDeactivate','A','M',12610000,'/admin/stockists/changeStatus',NULL),(12610400,'ResetStockistPassword','ResetStockistPassword','A','M',12610000,'/admin/stockists/resetStockistPassword',NULL),(12610500,'StockistProfile','StockistProfile','A','A',12610000,NULL,NULL),(12610540,'StockistCmsProfileListing','StockistCmsProfileListing','A','M',12610000,'/admin/stockists/stockistCmsProfileListing',NULL),(12610550,'StockistCmsProfile','StockistCmsProfile','A','A',12610000,NULL,NULL),(12610560,'StockistCategoryTag','StockistCategoryTag','A','M',12610000,'/admin/stockists/stockistCategoryTag/listing',NULL),(12610600,'StockistPaymentMethod','StockistPaymentMethod','A','M',12610000,'/admin/paymentMethod/stockistPaymentMethod',NULL),(12620000,'ConsignmentWallet','ConsignmentWallet','A','M',12600000,NULL,NULL),(12620100,'ConsignmentListing','Consignment Listing','A','M',12620000,'/admin/stockists/consignmentListing',NULL),(12620200,'ViewCgnWallet','ViewCgnWallet','A','M',12620000,'/admin/stockists/viewCgnWallet',NULL),(12620300,'ConsignmentTopUp','ConsignmentTopUp','A','M',12620000,'/admin/stockists/consignmentTopUp',NULL),(12620400,'ConsignmentReturn','ConsignmentReturn','A','M',12620000,'/admin/counter/consignmentReturn',NULL),(12630006,'StockistSalesListing','StockistSalesListing','A','M',12600000,'/admin/stockists/stockistSalesListing',NULL),(12630007,'SalesSubmissionListing','SalesSubmissionListing','A','M',12600000,'/admin/stockists/salesSubmissionListing',NULL),(12640000,'StockistStock','StockistStock','A','M',12600000,NULL,NULL),(12640100,'StockistStockStatement','StockistStockStatement','A','M',12640000,'/admin/stockistStock/trxn/list',NULL),(12640200,'StockistStockBalance','StockistStockBalance','A','M',12640000,'/admin/stockistStock/balance/list',NULL),(12640300,'StockistStockBalanceByProduct','StockistStockBalance','A','M',12640000,'/admin/stockistStock/balance/product/list',NULL),(12700000,'Event','Event','A','M',10000000,NULL,'mdi mdi-calendar'),(12700100,'EventListing','EventListing','A','M',12700000,'/admin/event/listing',NULL),(12700200,'AddEvent','AddEvent','A','A',12700000,NULL,NULL),(12700300,'EditEvent','EditEvent','A','A',12700000,NULL,NULL),(12700400,'EventBooth','EventBooth','A','A',12700000,NULL,NULL),(12700500,'EventReceiptListing','EventReceipt','A','M',12700000,'/admin/event/eventReceipt/listing',NULL),(12700505,'EventReceiptBreakdowLine truncated
/*!40000 ALTER TABLE `module` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `country_marrital_status`
--
LOCK TABLES `country_marrital_status` WRITE;
/*!40000 ALTER TABLE `country_marrital_status` DISABLE KEYS */;
INSERT INTO `country_marrital_status` VALUES (17,1),(17,2),(19,1),(19,2),(19,4),(19,14),(19,15),(27,1),(27,2),(27,4),(59,1),(59,2);
/*!40000 ALTER TABLE `country_marrital_status` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `system_property`
--
LOCK TABLES `system_property` WRITE;
/*!40000 ALTER TABLE `system_property` DISABLE KEYS */;
INSERT INTO `system_property` VALUES (2,'ALPHABET_LENGTH_MIN','N','ADMIN_PWD_FORMAT','3'),(3,'ALPHABET_LENGTH_MAX','N','ADMIN_PWD_FORMAT','10'),(5,'NUMERIC_LENGTH_MIN','N','ADMIN_PWD_FORMAT','1'),(6,'NUMERIC_LENGTH_MAX','N','ADMIN_PWD_FORMAT','10'),(8,'UPPERCASE_LENGTH_MIN','Y','ADMIN_PWD_FORMAT','1'),(9,'UPPERCASE_LENGTH_MAX','N','ADMIN_PWD_FORMAT','10'),(11,'LOWERCASE_LENGTH_MIN','Y','ADMIN_PWD_FORMAT','1'),(12,'LOWERCASE_LENGTH_MAX','N','ADMIN_PWD_FORMAT','10'),(14,'SYMBOLIC_LENGTH_MIN','N','ADMIN_PWD_FORMAT','3'),(15,'SYMBOLIC_LENGTH_MAX','N','ADMIN_PWD_FORMAT','10'),(16,'INPUT_LENGTH_MIN','Y','ADMIN_PWD_FORMAT','8'),(17,'INPUT_LENGTH_MAX','N','ADMIN_PWD_FORMAT','15'),(18,'NO_OTHER_LANGUAGE','N','ADMIN_PWD_FORMAT',''),(19,'SPACE_NOT_ALLOWED','N','ADMIN_PWD_FORMAT',''),(20,'ALPHABET_LENGTH_MIN','N','MEMBER_PWD_FORMAT','1'),(21,'ALPHABET_LENGTH_MAX','N','MEMBER_PWD_FORMAT','20'),(22,'NUMERIC_LENGTH_MIN','N','MEMBER_PWD_FORMAT','6'),(23,'NUMERIC_LENGTH_MAX','N','MEMBER_PWD_FORMAT','30'),(24,'UPPERCASE_LENGTH_MIN','N','MEMBER_PWD_FORMAT','1'),(25,'UPPERCASE_LENGTH_MAX','N','MEMBER_PWD_FORMAT','20'),(26,'LOWERCASE_LENGTH_MIN','N','MEMBER_PWD_FORMAT','1'),(27,'LOWERCASE_LENGTH_MAX','N','MEMBER_PWD_FORMAT','20'),(28,'SYMBOLIC_LENGTH_MIN','N','MEMBER_PWD_FORMAT','1'),(29,'SYMBOLIC_LENGTH_MAX','N','MEMBER_PWD_FORMAT','20'),(30,'INPUT_LENGTH_MIN','Y','MEMBER_PWD_FORMAT','6'),(31,'INPUT_LENGTH_MAX','N','MEMBER_PWD_FORMAT','35'),(32,'NO_OTHER_LANGUAGE','N','MEMBER_PWD_FORMAT',''),(33,'SPACE_NOT_ALLOWED','N','MEMBER_PWD_FORMAT',''),(34,'MEMBER_LOGIN_BLOCK_PERIOD','Y','MEMBER_LOGIN_BLOCK','7'),(35,'ADMIN_LOGIN_BLOCK_PERIOD','Y','ADMIN_LOGIN_BLOCK','1'),(36,'MEMBER_LOGIN_BLOCK_TIME_UNIT','Y','MEMBER_LOGIN_BLOCK_TIME_UNIT','M'),(37,'ADMIN_LOGIN_BLOCK_TIME_UNIT','Y','ADMIN_LOGIN_BLOCK_TIME_UNIT','M'),(38,'ADMIN_PASSWORD_AGING','Y','ADMIN_PASSWORD_AGING','300'),(39,'MEMBER_PASSWORD_AGING','Y','MEMBER_PASSWORD_AGING','300'),(40,'ADMIN_PASSWORD_AGING_TIME_UNIT','Y','ADMIN_PASSWORD_AGING_TIME_UNIT','Y'),(41,'MEMBER_PASSWORD_AGING_TIME_UNIT','Y','MEMBER_PASSWORD_AGING_TIME_UNIT','Y'),(42,'ALPHABET_LENGTH_MIN','N','MEMBER_PWD_SECONDARY_FORMAT','3'),(43,'ALPHABET_LENGTH_MAX','N','MEMBER_PWD_SECONDARY_FORMAT','20'),(44,'NUMERIC_LENGTH_MIN','N','MEMBER_PWD_SECONDARY_FORMAT','0'),(45,'NUMERIC_LENGTH_MAX','N','MEMBER_PWD_SECONDARY_FORMAT','30'),(46,'UPPERCASE_LENGTH_MIN','N','MEMBER_PWD_SECONDARY_FORMAT','0'),(47,'UPPERCASE_LENGTH_MAX','N','MEMBER_PWD_SECONDARY_FORMAT','20'),(48,'LOWERCASE_LENGTH_MIN','N','MEMBER_PWD_SECONDARY_FORMAT','0'),(49,'LOWERCASE_LENGTH_MAX','N','MEMBER_PWD_SECONDARY_FORMAT','20'),(50,'SYMBOLIC_LENGTH_MIN','N','MEMBER_PWD_SECONDARY_FORMAT','0'),(51,'SYMBOLIC_LENGTH_MAX','N','MEMBER_PWD_SECONDARY_FORMAT','20'),(52,'INPUT_LENGTH_MIN','Y','MEMBER_PWD_SECONDARY_FORMAT','6'),(53,'INPUT_LENGTH_MAX','Y','MEMBER_PWD_SECONDARY_FORMAT','35'),(54,'NO_OTHER_LANGUAGE','N','MEMBER_PWD_SECONDARY_FORMAT',''),(55,'SPACE_NOT_ALLOWED','N','MEMBER_PWD_SECONDARY_FORMAT',''),(59,'ALPHABET_LENGTH_MIN','N','STOCKIST_PWD_FORMAT','3'),(60,'ALPHABET_LENGTH_MAX','N','STOCKIST_PWD_FORMAT','10'),(61,'NUMERIC_LENGTH_MIN','N','STOCKIST_PWD_FORMAT','1'),(62,'NUMERIC_LENGTH_MAX','N','STOCKIST_PWD_FORMAT','10'),(63,'UPPERCASE_LENGTH_MIN','N','STOCKIST_PWD_FORMAT','1'),(64,'UPPERCASE_LENGTH_MAX','N','STOCKIST_PWD_FORMAT','10'),(65,'LOWERCASE_LENGTH_MIN','N','STOCKIST_PWD_FORMAT','1'),(66,'LOWERCASE_LENGTH_MAX','N','STOCKIST_PWD_FORMAT','10'),(67,'SYMBOLIC_LENGTH_MIN','N','STOCKIST_PWD_FORMAT','3'),(68,'SYMBOLIC_LENGTH_MAX','N','STOCKIST_PWD_FORMAT','10'),(69,'INPUT_LENGTH_MIN','Y','STOCKIST_PWD_FORMAT','3'),(70,'INPUT_LENGTH_MAX','N','STOCKIST_PWD_FORMAT','15'),(71,'NO_OTHER_LANGUAGE','N','STOCKIST_PWD_FORMAT',''),(72,'SPACE_NOT_ALLOWED','N','STOCKIST_PWD_FORMAT',''),(73,'STOCKIST_LOGIN_BLOCK_PERIOD','Y','STOCKIST_LOGIN_BLOCK','1'),(74,'STOCKIST_LOGIN_BLOCK_TIME_UNIT','Y','STOCKIST_LOGIN_BLOCK_TIME_UNIT','M'),(75,'STOCKIST_PASSWORD_AGING','Y','STOCKIST_PASSWORD_AGING','6'),(76,'STOCKIST_PASSWORD_AGING_TIME_UNIT','Y','STOCKIST_PASSWORD_AGING_TIME_UNIT','M'),(80,'APP','Y','MAINTENANCE','false'),(85,'APP_UPDATE_SOON','Y','APP_FORCE_LOGOUT','false'),(86,'APP_UPDATE_TIME','Y','APP_FORCE_LOGOUT','2021-09-03 07:00:00'),(87,'APP_REFRESH_TIME_SECONG','Y','APP_FORCE_LOGOUT','60'),(89,'APP_SUSPEND_USER','Y','APP_FORCE_LOGOUT',''),(113,'EDIT_PROFILE','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2,1.0.16'),(114,'NEW_REGISTRATION','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2'),(115,'MEMBER_LISTING','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2'),(116,'PURCHASE','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2'),(117,'PRV_LISTING','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2'),(118,'PERSONAL_PURCHASE_LISTING','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2'),(119,'PURCHASE_HISTORY','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2'),(120,'BONUS_STATEMENT','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2'),(121,'BONUS_CP58','N','APPS_SIDE_MENU_BLACK_LIST','0.0.1,0.0.2'),(122Line truncated
/*!40000 ALTER TABLE `system_property` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `user_group`
--
LOCK TABLES `user_group` WRITE;
/*!40000 ALTER TABLE `user_group` DISABLE KEYS */;
INSERT INTO `user_group` VALUES (1,'IT Dept','solvwayadm','2022-04-05 12:34:30','solvwayadm','2022-04-05 04:34:29'),(4,'Please Ignore','bryanlee','2023-06-01 17:49:41','bryanlee','2024-08-29 13:47:44'),(5,'Staff','admin','2024-08-20 11:43:31','admin','2024-08-20 03:43:30'),(6,'Merchant','admin','2024-08-20 14:36:21','admin','2024-08-20 06:36:20'),(7,'EVENTSTAFF','admin','2024-08-23 16:02:00','Staff','2024-08-23 08:15:51'),(8,'Exhibitor','Staff2','2024-08-27 19:03:58','Staff2','2024-08-27 11:03:58'),(9,'exhibitor1','Staff2','2024-08-27 20:11:29','Staff2','2024-08-27 12:11:29');
/*!40000 ALTER TABLE `user_group` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `salutation`
--
LOCK TABLES `salutation` WRITE;
/*!40000 ALTER TABLE `salutation` DISABLE KEYS */;
INSERT INTO `salutation` VALUES (1,'MR','Mr.','Mr.'),(2,'Ms.','Ms.','Ms.'),(3,'Dato','Dato','Dato'),(4,'Sir','Sir','Sir'),(5,'Madam','Madam','Madam'),(6,'Mrs.','Mrs.','Mrs.');
/*!40000 ALTER TABLE `salutation` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `reason_code`
--
LOCK TABLES `reason_code` WRITE;
/*!40000 ALTER TABLE `reason_code` DISABLE KEYS */;
INSERT INTO `reason_code` VALUES (2,'01','Assemble','SA','Y'),(4,'02','Stock Count Adjustment','SA','Y'),(9,'03','Stock Export to Oversea','SA','Y'),(10,'04','System Error ','SA','Y'),(11,'05','Transfer the Item Code','SA','Y'),(13,'ST01','Under Ordering','ST','Y'),(14,'ST02','Product Quality Issue','ST','Y'),(15,'ST03','Under-estimating the Demand','ST','Y'),(16,'06','For Internal Request','SA','Y'),(17,'TM001','Opening new landed country','TM','Y'),(18,'TM002','Migration','TM','Y');
/*!40000 ALTER TABLE `reason_code` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `supported_user_agent`
--
LOCK TABLES `supported_user_agent` WRITE;
/*!40000 ALTER TABLE `supported_user_agent` DISABLE KEYS */;
/*!40000 ALTER TABLE `supported_user_agent` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `location_hierarchy`
--
LOCK TABLES `location_hierarchy` WRITE;
/*!40000 ALTER TABLE `location_hierarchy` DISABLE KEYS */;
INSERT INTO `location_hierarchy` VALUES (1,'','GLOBAL','Global','GLOBAL','G','Y',0,0,NULL,NULL,NULL,NULL,'N',0,NULL,'N','N','N','','','','N','N','N','','2023-04-07 05:40:14'),(2,'','MY','Malaysia','GLOBAL/MY','C','Y',1,0,NULL,NULL,'{}',NULL,'N',161,NULL,'N','Y','N','','','MYNRICTAG','N','N','N','','2022-05-16 06:31:49'),(21,'MYR','WM','West Malaysia','GLOBAL/MY/WM','R','Y',2,0,NULL,NULL,NULL,NULL,'N',0,NULL,'N','N','N','','','','N','N','N','','2022-03-23 06:04:45'),(35,NULL,'MYB','Kuala Lumpur','GLOBAL/MY/WM/MYB','B','Y',21,2,'https://storage.googleapis.com/aameba-bucket-public-prd/GS-ae174e31-da79-4447-a2ee-10e31bd4bd2f.png','IN',NULL,'','Y',0,'','N','N','N','','','','N','N','N','','2023-05-30 08:26:34'),(63,NULL,'T2963003','T2963003 Exhibitor','GLOBAL/MY/WM/T2963003','B','Y',21,58,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2024-08-28 08:02:00'),(64,NULL,'T1586517','T1586517 Exhibitor','GLOBAL/MY/WM/T1586517','B','Y',21,60,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2024-08-28 08:29:49'),(65,NULL,'T2137022','T2137022 Exhibitor','GLOBAL/MY/WM/T2137022','B','Y',21,73,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(66,NULL,'T1767952','T1767952 Exhibitor','GLOBAL/MY/WM/T1767952','B','Y',21,75,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(67,NULL,'T1367524','T1367524 Exhibitor','GLOBAL/MY/WM/T1367524','B','Y',21,76,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(68,NULL,'T2998454','T2998454 Exhibitor','GLOBAL/MY/WM/T2998454','B','Y',21,74,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(69,NULL,'T1383203','T1383203 Exhibitor','GLOBAL/MY/WM/T1383203','B','Y',21,84,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(70,NULL,'T1443779','T1443779 Exhibitor','GLOBAL/MY/WM/T1443779','B','Y',21,83,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(71,NULL,'T2112837','T2112837 Exhibitor','GLOBAL/MY/WM/T2112837','B','Y',21,88,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(72,NULL,'T1828528','T1828528 Exhibitor','GLOBAL/MY/WM/T1828528','B','Y',21,82,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(73,NULL,'T2851323','T2851323 Exhibitor','GLOBAL/MY/WM/T2851323','B','Y',21,65,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(74,NULL,'T2421331','T2421331 Exhibitor','GLOBAL/MY/WM/T2421331','B','Y',21,102,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(75,NULL,'T1944647','T1944647 Exhibitor','GLOBAL/MY/WM/T1944647','B','Y',21,66,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(76,NULL,'T1752273','T1752273 Exhibitor','GLOBAL/MY/WM/T1752273','B','Y',21,68,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(77,NULL,'T2982775','T2982775 Exhibitor','GLOBAL/MY/WM/T2982775','B','Y',21,90,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(78,NULL,'T2830264','T2830264 Exhibitor','GLOBAL/MY/WM/T2830264','B','Y',21,89,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(79,NULL,'T1215013','T1215013 Exhibitor','GLOBAL/MY/WM/T1215013','B','Y',21,67,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(80,NULL,'T2253141','T2253141 Exhibitor','GLOBAL/MY/WM/T2253141','B','Y',21,104,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(81,NULL,'T2637889','T2637889 Exhibitor','GLOBAL/MY/WM/T2637889','B','Y',21,106,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(82,NULL,'T2405652','T2405652 Exhibitor','GLOBAL/MY/WM/T2405652','B','Y',21,97,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(83,NULL,'T2790400','T2790400 Exhibitor','GLOBAL/MY/WM/T2790400','B','Y',21,92,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(84,NULL,'T1175149','T1175149 Exhibitor','GLOBAL/MY/WM/T1175149','B','Y',21,96,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(85,NULL,'T2445515','T2445515 Exhibitor','GLOBAL/MY/WM/T2445515','B','Y',21,98,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(86,NULL,'T1483643','T1483643 Exhibitor','GLOBAL/MY/WM/T1483643','B','Y',21,81,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(87,NULL,'T1868392','T1868392 Exhibitor','GLOBAL/MY/WM/T1868392','B','Y',21,105,NULL,'IN',NULL,NULL,'Y',0,NULL,'N','N','N','','','','N','N','Y','','2025-01-15 06:50:13'),(88,NULL,'T2521771','T2521771 Exhibitor','GLOBAL/MY/WM/Line truncated
/*!40000 ALTER TABLE `location_hierarchy` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `country_race`
--
LOCK TABLES `country_race` WRITE;
/*!40000 ALTER TABLE `country_race` DISABLE KEYS */;
INSERT INTO `country_race` VALUES (21,2),(21,3),(21,12),(22,1),(22,2),(22,3),(22,12),(23,1),(23,2),(23,3),(23,12),(28,1),(28,2),(28,3),(28,12),(60,1),(60,2),(60,14),(60,15),(67,2);
/*!40000 ALTER TABLE `country_race` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `country_salutation`
--
LOCK TABLES `country_salutation` WRITE;
/*!40000 ALTER TABLE `country_salutation` DISABLE KEYS */;
INSERT INTO `country_salutation` VALUES (24,1),(24,2),(25,1),(25,2),(26,1),(26,2),(29,1),(29,2),(61,1),(61,2);
/*!40000 ALTER TABLE `country_salutation` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `public_holiday`
--
LOCK TABLES `public_holiday` WRITE;
/*!40000 ALTER TABLE `public_holiday` DISABLE KEYS */;
INSERT INTO `public_holiday` VALUES (1,'MY','2024-07-07','Awal Muharram'),(2,'MY','2024-07-08','Awal Muharram holiday'),(3,'MY','2024-08-31','Merdeka Day'),(4,'MY','2024-09-16','Prophet Muhammad\'s Birthday'),(5,'MY','2024-10-31','Deepavali'),(6,'MY','2024-12-11','Sultan of Selangor\'s Birthday'),(7,'MY','2024-12-25','Christmas Day');
/*!40000 ALTER TABLE `public_holiday` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `generic_hierarchy`
--
LOCK TABLES `generic_hierarchy` WRITE;
/*!40000 ALTER TABLE `generic_hierarchy` DISABLE KEYS */;
INSERT INTO `generic_hierarchy` VALUES (1,2097644833095917395,0,'Help Center','HelpCenter',0,'HC','Y','Y','SYS','2024-12-23 11:38:28','SYS','2024-12-23 11:38:28'),(2,3223357376484659200,2097644833095917395,'Contact Us','ContactUs',0,'HC','Y','N','admin','2026-03-25 11:45:52','admin','2026-03-25 11:45:52');
/*!40000 ALTER TABLE `generic_hierarchy` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `role`
--
LOCK TABLES `role` WRITE;
/*!40000 ALTER TABLE `role` DISABLE KEYS */;
INSERT INTO `role` VALUES (1,'ROLE_SUPER_ADMIN',NULL,1,'ROLE_SUPER_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(2,'ROLE_ADMIN',1,2,'ROLE_SUPER_ADMIN/ROLE_ADMIN','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(3,'ROLE_MEMBER',NULL,1,'ROLE_MEMBER','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(4,'ROLE_HQ',1,3,'ROLE_SUPER_ADMIN/ROLE_ADMIN/ROLE_HQ','admin','2020-01-01 00:00:00','admin','2021-03-18 01:46:43'),(31,'ROLE_KYC',42,3,'ROLE_SUPER_ADMIN/ROLE_TEMP_DELETE/ROLE_KYC','admin','2020-01-01 00:00:00','admin','2021-02-27 12:23:44'),(32,'ROLE_MERCHANT',NULL,1,'ROLE_MERCHANT','admin','2020-01-01 00:00:00','admin','2023-05-12 02:26:10'),(71,'ROLE_MERCHANT_ADMIN',32,2,'ROLE_MERCHANT/ROLE_MERCHANT_ADMIN','admin','2020-01-01 00:00:00','admin','2023-05-12 02:26:10'),(91,'ROLE_MERCHANT_BASIC',71,3,'ROLE_MERCHANT/ROLE_MERCHANT_ADMIN/ROLE_MERCHANT_BASIC','admin','2021-10-21 11:00:00','admin','2023-05-12 02:26:10'),(99,'ROLE_IT',1,2,'ROLE_SUPER_ADMIN/ROLE_IT','solvwayadm','2022-04-05 12:57:42','solvwayadm','2022-04-05 04:57:41'),(110,'ROLE_TASTEFULLY',1,2,'ROLE_SUPER_ADMIN/ROLE_TASTEFULLY','bryanlee','2023-06-01 17:44:58','bryanlee','2024-08-20 05:40:39'),(111,'ROLE_STAFF',1,2,'ROLE_SUPER_ADMIN/ROLE_STAFF','admin','2024-08-20 11:40:29','admin','2024-08-20 05:31:41'),(112,'ROLE_MERC',1,2,'ROLE_SUPER_ADMIN/ROLE_MERC','admin','2024-08-20 14:25:16','admin','2024-08-20 06:25:15'),(113,'ROLE_REGISTEREXHIBITOR (cancel) ',99,3,'ROLE_SUPER_ADMIN/ROLE_IT/ROLE_REGISTEREXHIBITOR (cancel) ','admin','2024-08-23 16:00:19','admin','2024-08-28 02:26:29'),(114,'ROLE_KAYZ',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_KAYZ','Staff','2024-08-23 16:14:23','Staff1','2024-09-26 08:52:44'),(115,'ROLE_TESTING REGISTER',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_TESTING REGISTER','Staff1','2024-08-28 11:36:14','Staff1','2024-08-28 03:36:14'),(116,'ROLE_GWP',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_GWP','Staff1','2024-09-26 13:38:05','Staff1','2024-09-26 05:38:04'),(117,'ROLE_LUCKYDRAW',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_LUCKYDRAW','Staff1','2024-09-26 15:16:59','Staff1','2024-09-26 07:16:59'),(118,'ROLE_EVENT OPERATION',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_EVENT OPERATION','Staff1','2024-09-26 16:52:09','Staff1','2026-04-29 09:03:25'),(119,'ROLE_TSC MEMBER REDEMPTION',111,3,'ROLE_SUPER_ADMIN/ROLE_STAFF/ROLE_TSC MEMBER REDEMPTION','Staff1','2025-06-24 18:45:54','Staff1','2025-06-25 14:35:48'),(120,'ROLE_MAIN_DASHBOARD',1,2,'ROLE_SUPER_ADMIN/ROLE_MAIN_DASHBOARD','bryanlee','2023-06-01 17:44:58','bryanlee','2024-08-20 05:40:39');
/*!40000 ALTER TABLE `role` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `message`
--
LOCK TABLES `message` WRITE;
/*!40000 ALTER TABLE `message` DISABLE KEYS */;
INSERT INTO `message` VALUES (5,'en_US','English','{\"en_US\": \"English\", \"in_ID\": \"Inggris\", \"ms_MY\": \"Bahasa Inggeris\", \"zh_CN\": \"English\", \"zh_TW\": \"English\"}','A'),(7,'zh_CN','Simplified Chinese','{\"en_US\": \"Simplified Chinese\", \"in_ID\": \"Bahasa Cina\", \"ms_MY\": \"Bahasa Cina Dipermudah\", \"zh_CN\": \"中文简体\", \"zh_TW\": \"中文简体\"}','A'),(8,'id','ID','{\"en_US\": \"ID\", \"ms_MY\": \"ID\", \"zh_CN\": \"编号\"}','A'),(9,'MemberGroup','Member Group','{\"en_US\": \"Visitor\", \"ms_MY\": \"Ahli\", \"zh_CN\": \"会员\"}','A'),(10,'MEMBER','Member','{\"en_US\": \"Visitor\", \"in_ID\": \"Member\", \"ms_MY\": \"Member\", \"zh_CN\": \"会员\", \"zh_TW\": \"會員\"}','A'),(11,'MembersListing','Member Listing','{\"en_US\": \"Visitor Listing\", \"in_ID\": \"Daftar Member\", \"ms_MY\": \"Senarai Member\", \"zh_CN\": \"Member 清单\", \"zh_TW\": \"Member 清單\"}','A'),(12,'AddMember','Add Member','{\"en_US\": \"Add Visitor\", \"zh_CN\": \"Add Member\"}','A'),(13,'SystemGroup','System Group','{\"en_US\": \"System Group\", \"in_ID\": \"Grup Sistem\", \"ms_MY\": \"Kumpulan Sistem\", \"zh_CN\": \"系统组别\", \"zh_TW\": \"系統組別\"}','A'),(14,'User','User','{\"en_US\": \"User\", \"in_ID\": \"Pengguna\", \"ms_MY\": \"Pengguna\", \"zh_CN\": \"用户\", \"zh_TW\": \"用戶\"}','A'),(15,'UsersListing','Users Listing','{\"en_US\": \"Users Listing\", \"in_ID\": \"Daftar Pengguna\", \"ms_MY\": \"Senarai Pengguna\", \"zh_CN\": \"用户清单\", \"zh_TW\": \"用戶清單\"}','A'),(16,'AddUser','注册新账号','{\"en_US\": \"Add User\", \"ms_MY\": \"Tambah Pengguna\", \"zh_CN\": \"注册新账号\"}','A'),(17,'Role','Role','{\"en_US\": \"Role\", \"in_ID\": \"Tugas\", \"ms_MY\": \"Peranan\", \"zh_CN\": \"职责\", \"zh_TW\": \"職責\"}','A'),(18,'RolesListing','Roles Listing','{\"en_US\": \"Roles Listing\", \"in_ID\": \"Daftar Tugasan\", \"ms_MY\": \"Senarai Peranan\", \"zh_CN\": \"职责清单\", \"zh_TW\": \"職責清單\"}','A'),(19,'AddRole','Add Role','{\"en_US\": \"Add Roles\", \"in_ID\": \"Add Roles\", \"ms_MY\": \"Tambah Peranan\", \"zh_CN\": \"添加权限\", \"zh_TW\": \"Add Roles\"}','A'),(20,'Country','Country','{\"en_US\": \"Country\", \"in_ID\": \"Negara\", \"ms_MY\": \"Negara\", \"zh_CN\": \"国家\", \"zh_TW\": \"國家\"}','A'),(21,'CountriesListing','Countries Listing','{\"en_US\": \"Countries Listing\", \"ms_MY\": \"Senarai Negara\", \"zh_CN\": \"国家清单\"}','A'),(22,'AddCountry','Add Country','{\"en_US\": \"Add Country\", \"in_ID\": \"Add Country\", \"ms_MY\": \"Tambah Negara\", \"zh_CN\": \"添加国家\", \"zh_TW\": \"Add Country\"}','A'),(23,'Module','Module','{\"en_US\": \"Module\", \"ms_MY\": \"Modul\", \"zh_CN\": \"模块权限\"}','A'),(24,'ModulesListing','Module Listing','{\"en_US\": \"Module Listing\", \"ms_MY\": \"Senarai Modul\", \"zh_CN\": \"模块权限清单\"}','A'),(25,'OnlineUsers','Online Users','{\"en_US\": \"Online Users\", \"ms_MY\": \"Pengguna Dalam Talian\", \"zh_CN\": \"在线用户\", \"Search Merchant\": \"搜索成员\"}','A'),(26,'Username','Username','{\"en_US\": \"Username\"}','A'),(27,'Password','Password','{\"en_US\": \"Password\", \"in_ID\": \"Kata Sandi\", \"ms_MY\": \"Kata Laluan\", \"zh_CN\": \"密码\", \"zh_TW\": \"密碼\"}','A'),(28,'SecurityCode','Security Code','{\"en_US\": \"Security Code\", \"in_ID\": \"Kode Keamanan\", \"ms_MY\": \"Kod Keselamatan\", \"zh_CN\": \"验证码\", \"zh_TW\": \"驗證碼\"}','A'),(29,'SignIn','Sign In','{\"en_US\": \"Sign In\", \"in_ID\": \"Login \", \"ms_MY\": \"Daftar masuk\", \"zh_CN\": \"登入\", \"zh_TW\": \"登入\"}','A'),(30,'ForgotPwd','Forgot your password ?','{\"en_US\": \"Forgot your password ?\", \"in_ID\": \"Lupa Kata Sandi ?\", \"ms_MY\": \"Lupa Kata Laluan\", \"zh_CN\": \"忘记密码?\", \"zh_TW\": \"忘記密碼?\"}','A'),(31,'Backoffice','Back Office','{\"en_US\": \"Back Office \", \"in_ID\": \"Back Office \", \"ms_MY\": \"Back Office\", \"zh_CN\": \"行政后台\", \"zh_TW\": \"行政後台\"}','A'),(32,'Currency','Currency','{\"en_US\": \"Currency\", \"ms_MY\": \"Mata Wang\", \"zh_CN\": \"货币\"}','A'),(33,'AddCurrency','AddCurrency','{\"en_US\": \"Add Currency\", \"in_ID\": \"Add Currency\", \"ms_MY\": \"Tambah Mata Wang\", \"zh_CN\": \"添加货币\", \"zh_TW\": \"Add Currency\"}','A'),(34,'ctryCodeAlreadyExists','ctryCodeAlreadyExists','{\"en_US\": \"This Country Code had existed!\\r\\n\", \"ms_MY\": \"Kod negara ini telah wujud\", \"zh_CN\": \"此国家编号已经存在!\"}','A'),(35,'Address','Address','{\"en_US\": \"Address\", \"in_ID\": \"Alamat\", \"ms_MY\": \"Alamat\", \"zh_CN\": \"地址\", \"zh_TW\": \"地址\"}','A'),(36,'AddAddress','AddAddress','{\"en_US\": \"Add Address\", \"ms_MY\": \"Tambah Alamat\", \"zh_CN\": \"添加地址\"}','A'),(37,'MessageCode','Message Code','{\"en_US\": \"Message Code\", \"ms_MY\": \"Kod Pesanan\", \"zh_CN\": \"消息代码\"}','A'),(38,'AddLocale','Add Locale','{\"en_US\": \"Add Locale\", \"ms_MY\":Line truncated
/*!40000 ALTER TABLE `message` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `config_country`
--
LOCK TABLES `config_country` WRITE;
/*!40000 ALTER TABLE `config_country` DISABLE KEYS */;
INSERT INTO `config_country` VALUES (1,'RM',2),(17,'RM',20),(18,'RR',2),(19,'RM',22),(22,'RR',22),(23,'RR',20),(24,'RS',2),(25,'RS',22),(26,'RS',20),(27,'RM',30),(28,'RR',30),(29,'RS',30),(30,'TS',2),(31,'TS',20),(32,'TS',22),(33,'TS',30),(37,'RP',2),(38,'RP',20),(39,'RP',22),(40,'RP',30),(41,'RSK',2),(42,'RSK',20),(43,'RSK',22),(44,'RSK',30),(55,'RN',2),(56,'RN',20),(57,'RN',22),(58,'RN',30),(59,'RM',58),(60,'RR',58),(61,'RS',58),(62,'TS',58),(63,'RP',58),(64,'RN',58),(65,'RSK',58);
/*!40000 ALTER TABLE `config_country` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `currency`
--
LOCK TABLES `currency` WRITE;
/*!40000 ALTER TABLE `currency` DISABLE KEYS */;
INSERT INTO `currency` VALUES (24,'BN','BND','TRX',0.34722,'2021-01-31 21:04:18','admin','Y','2021-03-31 21:05:16','2023-06-07 11:58:05'),(25,'SG','SGD','TRX',0.34722,'2021-01-31 21:05:20','admin','Y','2021-03-31 21:05:48','2023-06-07 11:58:05'),(26,'HK','HKD','TRX',1.87742,'2021-01-31 21:05:52','admin','Y','2021-03-31 21:06:08','2023-06-07 11:58:05'),(27,'MY','MYR','TRX',1.00000,'2021-01-31 21:06:34','admin','Y','2021-03-31 21:06:44','2023-06-07 11:58:05'),(28,'ID','IDR','TRX',3489.46000,'2021-01-31 21:34:34','admin','Y','2021-03-31 21:35:08','2023-06-07 11:58:05'),(29,'BN','BND','BNS',0.32377,'2021-04-30 00:00:00','admin','Y','2021-04-23 16:50:33','2023-06-07 11:58:05'),(30,'HK','HKD','BNS',1.88402,'2021-04-30 00:00:00','admin','Y','2021-04-23 16:53:13','2023-06-07 11:58:05'),(31,'SG','SGD','BNS',0.32377,'2021-04-30 00:00:00','admin','Y','2021-04-23 16:54:08','2023-06-07 11:58:05'),(32,'MY','MYR','BNS',1.00000,'2021-04-30 00:00:00','admin','Y','2021-04-23 16:54:40','2023-06-07 11:58:05'),(33,'ID','IDR','BNS',3525.85628,'2021-04-30 00:00:00','admin','Y','2021-04-23 16:59:27','2023-06-07 11:58:05'),(34,'BN','BND','BNS',0.32224,'2021-05-31 15:07:00','admin','Y','2021-05-26 15:08:08','2023-06-07 11:58:05'),(35,'HK','HKD','BNS',1.88130,'2021-05-26 15:08:15','admin','Y','2021-05-26 15:08:30','2023-06-07 11:58:05'),(36,'ID','IDR','BNS',3469.54510,'2021-05-31 15:08:00','admin','Y','2021-05-26 15:09:11','2023-06-07 11:58:05'),(37,'MY','MYR','BNS',1.00000,'2021-05-31 15:10:00','admin','Y','2021-05-26 15:10:35','2023-06-07 11:58:05'),(38,'SG','SGD','BNS',0.32224,'2021-05-31 15:10:00','admin','Y','2021-05-26 15:11:01','2023-06-07 11:58:05'),(39,'BN','BND','BNS',0.32248,'2021-06-30 00:55:00','admin','Y','2021-07-01 10:56:54','2023-06-07 11:58:05'),(40,'SG','SGD','BNS',0.32248,'2021-06-30 00:57:00','admin','Y','2021-07-01 10:57:37','2023-06-07 11:58:05'),(41,'HK','HKD','BNS',1.87715,'2021-06-30 00:00:00','admin','Y','2021-07-01 10:58:13','2023-06-07 11:58:05'),(42,'ID','IDR','BNS',3468.78097,'2021-06-30 00:00:00','admin','Y','2021-07-01 10:58:46','2023-06-07 11:58:05'),(43,'MY','MYR','BNS',1.00000,'2021-06-30 00:00:00','admin','Y','2021-07-01 10:59:14','2023-06-07 11:58:05'),(44,'BN','BND','BNS',0.32256,'2021-07-01 00:00:00','admin','Y','2021-08-02 10:25:45','2023-06-07 11:58:05'),(45,'SG','SGD','BNS',0.32256,'2021-07-01 00:00:00','admin','Y','2021-08-02 10:29:08','2023-06-07 11:58:05'),(46,'HK','HKD','BNS',1.85068,'2021-07-01 00:00:00','admin','Y','2021-08-02 10:29:50','2023-06-07 11:58:05'),(47,'ID','IDR','BNS',3455.08391,'2021-07-01 00:00:00','admin','Y','2021-08-02 10:30:47','2023-06-07 11:58:05'),(48,'MY','MYR','BNS',1.00000,'2021-07-01 00:00:00','admin','Y','2021-08-02 10:31:09','2023-06-07 11:58:05'),(49,'BN','BND','BNS',0.32104,'2021-08-01 00:00:00','admin','Y','2021-09-02 11:54:41','2023-06-07 11:58:05'),(50,'SG','SGD','BNS',0.32104,'2021-08-01 00:00:00','admin','Y','2021-09-02 11:56:01','2023-06-07 11:58:05'),(51,'HK','HKD','BNS',1.84310,'2021-08-01 00:00:00','admin','Y','2021-09-02 11:56:57','2023-06-07 11:58:05'),(52,'ID','IDR','BNS',3406.57469,'2021-08-01 00:00:00','admin','Y','2021-09-02 11:57:59','2023-06-07 11:58:05'),(53,'BN','BND','BNS',0.32665,'2021-03-31 00:00:00','admin','Y','2021-09-06 14:52:59','2023-06-07 11:58:05'),(54,'SG','SGD','BNS',0.32665,'2021-03-31 00:00:00','admin','Y','2021-09-06 14:53:45','2023-06-07 11:58:05'),(55,'HK','HKD','BNS',1.88953,'2021-03-31 00:00:00','admin','Y','2021-09-06 14:54:43','2023-06-07 11:58:05'),(56,'MY','MYR','BNS',1.00000,'2021-03-31 00:00:00','admin','Y','2021-09-06 14:55:24','2023-06-07 11:58:05'),(57,'MY','MYR','BNS',1.00000,'2021-08-01 00:00:00','admin','Y','2021-09-09 11:36:24','2023-06-07 11:58:05'),(58,'BN','BND','BNS',0.32351,'2021-09-01 00:00:00','admin','Y','2021-10-01 10:02:18','2023-06-07 11:58:05'),(59,'HK','HKD','BNS',1.86742,'2021-09-01 00:00:00','admin','Y','2021-10-01 10:03:16','2023-06-07 11:58:05'),(60,'ID','IDR','BNS',3421.86736,'2021-09-01 00:00:00','admin','Y','2021-10-01 10:04:02','2023-06-07 11:58:05'),(61,'MY','MYR','BNS',1.00000,'2021-09-01 00:00:00','admin','Y','2021-10-01 10:04:39','2023-06-07 11:58:05'),(62,'SG','SGD','BNS',0.32351,'2021-09-01 00:00:00','admin','Y','2021-10-01 10:05:18','2023-06-07 11:58:05');
/*!40000 ALTER TABLE `currency` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `bank`
--
LOCK TABLES `bank` WRITE;
/*!40000 ALTER TABLE `bank` DISABLE KEYS */;
INSERT INTO `bank` VALUES (1,'BKRM','','','Bank Rakyat Berhad','BRB',2,'Y','BKRM','02-Bank Rakyat Berhad'),(2,'AMB','','','AmBank Berhad','AMB',2,'Y','AMB','08-AmBank Berhad'),(3,'BSN','','','Bank Simpanan Nasional Berhad','BSN',2,'Y','BSN','10-Bank Simpanan Nasional Berhad'),(4,'ALL','','','Alliance Bank Berhad','ABB',2,'Y','ALL','12-Alliance Bank Berhad'),(5,'SCB','','','Standard Chartered Bank Berhad','SCBHMY',2,'Y','SCB','14-Standard Chartered Bank Berhad'),(6,'CITI','','','Citibank','CITIMY',2,'Y','CITI','17-Citibank'),(7,'RHB','','','RHB Bank Berhad','RHBMY',2,'Y','RHB','18-RHB Bank Berhad'),(8,'HSBC','','','HSBC Bank Berhad','HSBCMY',2,'Y','HSBC','22-HSBC Bank Berhad'),(9,'HLBB','','','Hong Leong Bank Berhad','HLBMY',2,'Y','HLBB','24-Hong Leong Bank Berhad/ Hong Leong Finance'),(10,'UOB','','','United Overseas Bank (M) Bhd','UOBMY',2,'Y','UOB','26-United Overseas Bank (M) Bhd'),(11,'MBB','','','Malayan Banking Berhad','MAYBANKMY',2,'Y','MBB','27-Malayan Banking Berhad'),(12,'OCBC','','','OCBC Bank Berhad','OCBCMY',2,'Y','OCBC','29-OCBC Bank Berhad'),(13,'AFFIN','','','Affin Bank Berhad','AFBBMY',2,'Y','AFFIN','32-Affin Bank Berhad'),(14,'PBB','','','Public Bank Berhad','PBBMY',2,'Y','PBB','33-Public Bank Berhad/ Public Finance Berhad'),(15,'CIMB','','','CIMB Bank Berhad','CIMBMY',2,'Y','CIMB','35-CIMB Bank Berhad'),(16,'BMMB','','','Bank Muamalat Malaysia Berhad','BMMB',2,'Y','BMMB','41-Bank Muamalat Malaysia Berhad'),(17,'BIMB','','','Bank Islam Malaysia Berhad','BIMB',2,'Y','BIMB','45-Bank Islam Malaysia Berhad'),(18,'AGRO','','','Agro Bank','AGROMY',2,'Y','AGRO','49-Agro Bank'),(19,'DBS','','DBSSSGSGXXX','DBS Bank','DBSSG',20,'Y','DBS',''),(20,'POSB','','DBSSSGSGXXX','POSB Bank','POSB',20,'Y','POSB',''),(21,'AMBD','','','AUTORITI MONETARI BRUNEI DARUSSALAM','AMBD',30,'N','AMBD',NULL),(22,'BBB','','','BAIDURI BANK BERHAD ','BBB',30,'N','BAID',''),(23,'BIBD','','','BANK ISLAM BRUNEI DARUSSALAM BERHAD ','BIBD',30,'N','BIBD',NULL),(24,'BKCH','','','BANK OF CHINA (HONGKONG) LIMITED BRUNEI BRANCH','BKCH',30,'N','BKCH',NULL),(25,'MBB','','','MALAYAN BANKING BERHAD (MAYBANK)','MBB',30,'N','MBBE',''),(26,'TAIB','','','PERBADANAN TABUNG AMANAH ISLAM BRUNEI','TAIB',30,'N','PTAI',''),(27,'RHBB','','','RHB BANK BERHAD','RHBB',30,'N','RHBB',NULL),(28,'SCB','','','STANDARD CHARTERED BANK BRUNEI','SCB',30,'N','SCBL',''),(29,'UOVB','','','UNITED OVERSEAS BANK LIMITED','UOVB',30,'N','UOVB',NULL),(30,'003','251','SCBLHKHHXXX','STANDARD CHARTERED BANK (HK) LTD','scblbk',22,'N','003',NULL),(128,'004','004','HSBCHKHHXXX','HONGKONG & SHANGHAI BANKING CORP','hsbchk',22,'N','004',NULL),(224,'012','005','BKCHHKHHXXX','BANK OF CHINA (HONG KONG) LIMITED','bkchhk',22,'N','012',NULL),(322,'024','201','HASEHKHHXXX','HANG SENG BANK LTD','hsbhk',22,'N','024',NULL),(418,'015','133','BEASHKHHXXX','THE BANK OF EAST ASIA, LTD','beashk',22,'N','015',NULL),(517,'214','120','ICBKHKHHXXX','ICBC LIMITED','icbkhk',22,'N','214',NULL),(518,'016','185','DHBKHKHHXXX','DBS BANK (HONG KONG) LIMITED','dbshk',22,'N','016',NULL),(619,'035','798','WIHBHKHHXXX','OCBC WING HANG BANK LIMITED','wihbhk',22,'N','035',NULL),(687,'022','896','OCBCHKHHXXX','OVERSEA-CHINESE BANKING CORP LTD','ocbchk',22,'N','022',NULL),(688,'018','694','KWHKHKHHXXX','CHINA CITIC BANK INTERNATIONAL LTD','citic',22,'N','018',NULL),(768,'382','100','COMMHKHHXXX','BANK OF COMMUNICATIONS (HK) LIMITED','commhk',22,'N','382',NULL),(810,'221','671','PCBCHKHHXXX','CHINA CONSTRUCTION BANK CORPORATION','pcbchk',22,'N','221',NULL),(815,'039','744','CIYUHKHHXXX','CHIYU BANKING CORPORATION LTD','ciyuhk',22,'N','039',NULL),(842,'041','276','LCHBHKHHXXX','CHONG HING BANK LTD','lchbhk',22,'N','041',NULL),(896,'040','750','DSBAHKHHXXX','DAH SING BANK LTD','dsbahk',22,'N','040',NULL),(900,'128','841','IBALHKHHXXX','FUBON BANK (HONG KONG) LIMITED','ibalhk',22,'N','128',NULL),(909,'ACEH','','','BPD Aceh','ACEH',58,'Y','',''),(910,'ACEH_UUS','','','BPD Aceh UUS','ACEH_UUS',58,'N','',''),(911,'AGRIS','','','Bank Agris','AGRIS',58,'N','',''),(912,'AGRONIAGA','','','Bank BRI Agroniaga','AGRONIAGA',58,'N','',''),(913,'AMAR','','','Bank Amar Indonesia (formerly Anglomas International Bank)','AMAR',58,'N','',''),(914,'ANZ','','','Bank ANZ Indonesia','ANZ',58,'N','',''),(915,'ARTA_NIAGA_KENCANA','','','Bank Arta Niaga Kencana','ARTA_NIAGA_KENCANA',58,'N','',''),(916,'ARTHA','','','Bank Artha Graha International','ARTHA',58,'N','',''),(917,'ARTOS','','','Bank Artos Indonesia','ARTOS',58,'N','',''),(918,'BALI','','','BPD Bali','BALI',58,'N','',''),(919,'BAML','','','Bank of America Merill-Lynch','BAML',58,'N','',''),(920,'BANGKOK','','','Bangkok Bank','BANGKOK',58,'N','',''),(922,'BCA','','','Bank Central Asia (BCA)','BCA',58,'Y','',''),(923,'BCA_SYR','','','Bank Central Asia (BCA) Syariah','BCA_SYR',58,'Y','',''),(924,'BENGKULU','','','BPD Bengkulu','BENGKULU',58,'Y','',''),(925,'BISNIS_INTERNASIONAL','','','Bank Bisnis Internasional','BISNIS_INTERNASIONAL',58,'Y','',''),(926,'BJB','','','Bank BJB','BJB'Line truncated
/*!40000 ALTER TABLE `bank` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `geo_location_hierarchy`
--
LOCK TABLES `geo_location_hierarchy` WRITE;
/*!40000 ALTER TABLE `geo_location_hierarchy` DISABLE KEYS */;
INSERT INTO `geo_location_hierarchy` VALUES (160,'{\"en_US\": \"Global\", \"zh_CN\": \"全球\"}','160',0,'Y','G',NULL,NULL),(161,'{\"en_US\": \"Malaysia\", \"zh_CN\": \"马来西亚\", \"zh_TW\": \"馬來西亞\"}','160/161',160,'Y','C','T',NULL),(163,'{\"en_US\": \"Johor\"}','160/161/163',161,'Y','S',NULL,NULL),(164,'{\"en_US\": \"Kedah\"}','160/161/164',161,'Y','S',NULL,NULL),(165,'{\"en_US\": \"Kelantan\"}','160/161/165',161,'Y','S',NULL,NULL),(166,'{\"en_US\": \"Wp Kuala Lumpur\"}','160/161/166',161,'Y','S','N',NULL),(167,'{\"en_US\": \"Kajang\", \"zh_CN\": \"加影\"}','160/161/166/167',166,'Y','T',NULL,NULL),(168,'{\"en_US\": \"Seremban\", \"zh_CN\": \"芙蓉\"}','160/161/165/168',165,'Y','T',NULL,NULL),(169,'{\"en_US\": \"Senawang\", \"zh_CN\": \"旺城\"}','160/161/165/168/169',168,'N','P',NULL,NULL),(170,'{\"en_US\": \"Seremban 2\", \"zh_CN\": \"芙蓉 2\"}','160/161/165/168/170',168,'Y','T',NULL,NULL),(186,'{\"en_US\": \"Hong Kong, Sar\", \"zh_CN\": \"香港特别行政区\", \"zh_TW\": \"香港特別行政區\"}','160/186',160,'N','C','T',NULL),(187,'{\"en_US\": \"Singapore\", \"zh_CN\": \"新加坡\", \"zh_TW\": \"新加坡\"}','160/187',160,'Y','C','C',NULL),(188,'{\"en_US\": \"Brunei\", \"in_ID\": \"Brunei\", \"ms_MY\": \"Brunei\", \"zh_CN\": \"汶莱\", \"zh_TW\": \"汶萊\"}','160/188',160,'N','C','T',NULL),(208,'{\"en_US\": \"Jelebu\", \"zh_CN\": \"日叻务\"}','160/161/165/208',165,'N','C','T',NULL),(209,'{\"en_US\": \"Indonesia\", \"zh_CN\": \"印度尼西亚\", \"zh_TW\": \"印度尼西亞\"}','160/209',160,'N','C','SD',NULL),(212,'{\"en_US\": \"Hong Kong\", \"zh_CN\": \"港岛\", \"zh_TW\": \"港島\"}','160/186/212',186,'Y','S',NULL,NULL),(217,'{\"en_US\": \"Labuan\"}','160/161/217',161,'Y','S',NULL,NULL),(219,'{\"en_US\": \"Melaka\"}','160/161/219',161,'Y','S',NULL,NULL),(220,'{\"en_US\": \"Negeri Sembilan\"}','160/161/220',161,'Y','S',NULL,NULL),(221,'{\"en_US\": \"Jurong East\"}','160/187/221',187,'Y','T',NULL,NULL),(222,'{\"en_US\": \"Yishun\"}','160/187/222',187,'Y','T',NULL,NULL),(223,'{\"en_US\": \"Clementi\"}','160/187/223',187,'Y','T',NULL,NULL),(224,'{\"en_US\": \"Pasir Ris\"}','160/187/224',187,'Y','T',NULL,NULL),(225,'{\"en_US\": \"Punggol\"}','160/187/225',187,'Y','T',NULL,NULL),(226,'{\"en_US\": \"Tampines\"}','160/187/226',187,'Y','T',NULL,NULL),(227,'{\"en_US\": \"Rochor\"}','160/187/227',187,'Y','T',NULL,NULL),(228,'{\"en_US\": \"Seletar\"}','160/187/228',187,'Y','T',NULL,NULL),(229,'{\"en_US\": \"Serangoon\"}','160/187/229',187,'Y','T',NULL,NULL),(230,'{\"en_US\": \"Choa Chu Kang\"}','160/187/230',187,'Y','T',NULL,NULL),(231,'{\"en_US\": \"Bukit Batok\"}','160/187/231',187,'Y','T',NULL,NULL),(232,'{\"en_US\": \"Sengkang\"}','160/187/232',187,'Y','T',NULL,NULL),(233,'{\"en_US\": \"Woodlands\"}','160/187/233',187,'Y','T',NULL,NULL),(234,'{\"en_US\": \"Ang Mo Kio\"}','160/187/234',187,'Y','T',NULL,NULL),(235,'{\"en_US\": \"Jurong West\"}','160/187/235',187,'Y','T',NULL,NULL),(236,'{\"en_US\": \"Kampung Glam\"}','160/187/236',187,'Y','T',NULL,NULL),(237,'{\"en_US\": \"Tengah\"}','160/187/237',187,'Y','T',NULL,NULL),(238,'{\"en_US\": \"Paya Lebar\"}','160/187/238',187,'Y','T',NULL,NULL),(239,'{\"en_US\": \"Kranji\"}','160/187/239',187,'Y','T',NULL,NULL),(240,'{\"en_US\": \"Novena\"}','160/187/240',187,'Y','T',NULL,NULL),(241,'{\"en_US\": \"Newton\"}','160/187/241',187,'Y','T',NULL,NULL),(242,'{\"en_US\": \"Simei\"}','160/187/242',187,'Y','T',NULL,NULL),(243,'{\"en_US\": \"Jurong\"}','160/187/243',187,'Y','T',NULL,NULL),(244,'{\"en_US\": \"Kampong Ubi\"}','160/187/244',187,'Y','T',NULL,NULL),(245,'{\"en_US\": \"West Coast\"}','160/187/245',187,'Y','T',NULL,NULL),(246,'{\"en_US\": \"Hougang\"}','160/187/246',187,'Y','T',NULL,NULL),(247,'{\"en_US\": \"Buona Vista\"}','160/187/247',187,'Y','T',NULL,NULL),(248,'{\"en_US\": \"Pahang\"}','160/161/248',161,'Y','S',NULL,NULL),(249,'{\"en_US\": \"Perlis\"}','160/161/249',161,'Y','S',NULL,NULL),(250,'{\"en_US\": \"Pulau Pinang\"}','160/161/250',161,'Y','S',NULL,NULL),(251,'{\"en_US\": \"Perak\"}','160/161/251',161,'Y','S',NULL,NULL),(252,'{\"en_US\": \"Putrajaya\"}','160/161/252',161,'Y','S',NULL,NULL),(253,'{\"en_US\": \"Sabah\"}','160/161/253',161,'Y','S',NULL,NULL),(254,'{\"en_US\": \"Sarawak\"}','160/161/254',161,'Y','S',NULL,NULL),(255,'{\"en_US\": \"Selangor\"}','160/161/255',161,'Y','S',NULL,NULL),(256,'{\"en_US\": \"Terengganu\"}','160/161/256',161,'Y','S',NULL,NULL),(257,'{\"en_US\": \"Kowloon\", \"zh_CN\": \"九龙\", \"zh_TW\": \"九龍\"}','160/186/257',186,'Y','S',NULL,NULL),(258,'{\"en_US\": \"New Territories\", \"zh_CN\": \"新界\", \"zh_TW\": \"新界\"}','160/186/258',186,'Y','S',NULL,NULL),(277,'{\"en_US\": \"Kennedy Town\", \"zh_CN\": \"坚尼地城\", \"zh_TW\": \"堅尼地城\"}','160/186/212/277',212,'Y','T',NULL,NULL),(278,'{\"en_US\": \"Shek Tong Tsui\", \"zh_CN\": \"石塘咀\", \"zh_TW\": \"石塘咀\"}','160/186/212/278',212,'Y','T',NULL,NULL),(279,'{\"en_US\": \"Sai Ying Pun\", \"zh_CN\": \"西营盘\"Line truncated
/*!40000 ALTER TABLE `geo_location_hierarchy` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `race`
--
LOCK TABLES `race` WRITE;
/*!40000 ALTER TABLE `race` DISABLE KEYS */;
INSERT INTO `race` VALUES (1,'C','Chinese','CHINESE'),(2,'M','Malay','MALAY'),(3,'I','Indian','INDIAN'),(4,'Ca','Caucasian','Caucasian'),(5,'Mo','Mongolian','Mongolian'),(6,'ne','Negroid','Negroid'),(7,'am',' American',' American'),(8,'et',' Ethiopian',' Ethiopian'),(9,'aus','Australoid ','Australoid '),(10,'cap','Capoid','Capoid'),(11,'as','Asian','Asian'),(12,'O','Others','Others'),(13,'a','a','aa'),(14,'JV','Javanese','javanese'),(15,'SD','Sundanese','sundanese');
/*!40000 ALTER TABLE `race` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `preferred_language`
--
LOCK TABLES `preferred_language` WRITE;
/*!40000 ALTER TABLE `preferred_language` DISABLE KEYS */;
INSERT INTO `preferred_language` VALUES (1,'en_US','English'),(2,'zh_CN','简体中文'),(3,'es','Spanish'),(4,'hi','HINDI'),(5,'ar','ARABIC'),(6,'pt','PORTUGUESE'),(7,'BN','BENGALI'),(8,'ru','RUSSIAN'),(9,'ja','JAPANESE'),(10,'lah','LAHNDA'),(11,'jv','JAVANESE'),(12,'de','GERMAN'),(13,'ko','Korean'),(14,'zh_TW','中文繁體'),(15,'BM','Bahasa Malaysia');
/*!40000 ALTER TABLE `preferred_language` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `app_version`
--
LOCK TABLES `app_version` WRITE;
/*!40000 ALTER TABLE `app_version` DISABLE KEYS */;
INSERT INTO `app_version` VALUES (1,'ANDROID','1.0.0'),(2,'IOS','1.0.0');
/*!40000 ALTER TABLE `app_version` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `country_preferred_language`
--
LOCK TABLES `country_preferred_language` WRITE;
/*!40000 ALTER TABLE `country_preferred_language` DISABLE KEYS */;
/*!40000 ALTER TABLE `country_preferred_language` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `nationality`
--
LOCK TABLES `nationality` WRITE;
/*!40000 ALTER TABLE `nationality` DISABLE KEYS */;
INSERT INTO `nationality` VALUES (1,'MY','MYS','Malaysia','Malaysia'),(2,'SG','SGP','Singapore','Singapore'),(3,'ID','IDN','Indonesia','Indonesia'),(4,'TH','THA','Thailand','Thailand'),(5,'BN','BRN','Brunei','Brunei'),(6,'HK','HKG','Hong Kong','HongKong'),(7,'MO','MAC','Macau','Macau'),(8,'CN','CHN','China','China'),(9,'AF','AFG','Afghanistan','Afghanistan'),(10,'AL','ALB','Albania','Albania'),(11,'DZ','DZA','Algeria','Algeria'),(12,'AD','AND','Andorra','Andorra'),(13,'AO','AGO','Angola','Angola'),(14,'AE','ARE','United Arab Emirates','UnitedArabEmirates'),(15,'AI','AIA','Anguilla','Anguilla'),(16,'AS','ASM','American Samoa','AmericanSamoa'),(17,'AG','ATG','Antigua and Barbuda','AntiguaAndBarbuda'),(18,'AR','ARG','Argentina','Argentina'),(19,'AM','ARM','Armenia','Armenia'),(20,'AW','ABW','Aruba','Aruba'),(21,'AU','AUS','Australia','Australia'),(22,'AT','AUT','Austria','Austria'),(23,'AZ','AZE','Azerbaijan','Azerbaijan'),(24,'BS','BHS','Bahamas','Bahamas'),(25,'BH','BHR','Bahrain','Bahrain'),(26,'BD','BGD','Bangladesh','Bangladesh'),(27,'BB','BRB','Barbados','Barbados'),(28,'BY','BLR','Belarus','Belarus'),(29,'BE','BEL','Belgium','Belgium'),(30,'BZ','BLZ','Belize','Belize'),(31,'BJ','BEN','Benin','Benin'),(32,'BM','BMU','Bermuda','Bermuda'),(33,'BT','BTN','Bhutan','Bhutan'),(34,'BO','BOL','Bolivia','Bolivia'),(35,'BA','BIH','Bosnia and Herzegovina','BosniaAndHerzegovina'),(36,'BW','BWA','Botswana','Botswana'),(37,'BR','BRA','Brazil','Brazil'),(38,'IO','IOT','British Indian Ocean Territory','BritishIndianOceanTerritory'),(39,'VG','VGB','British Virgin Islands','BritishVirginIslands'),(40,'BG','BGR','Bulgaria','Bulgaria'),(41,'BF','BFA','Burkina Faso','BurkinaFaso'),(42,'BI','BDI','Burundi','Burundi'),(43,'KH','KHM','Cambodia','Cambodia'),(44,'CM','CMR','Cameroon','Cameroon'),(45,'CA','CAN','Canada','Canada'),(46,'CV','CPV','Cabo Verde','CaboVerde'),(47,'KY','CYM','Cayman Islands','CaymanIslands'),(48,'CF','CAF','Central African Republic','CentralAfricanRepublic'),(49,'TD','TCD','Chad','Chad'),(50,'CL','CHL','Chile','Chile'),(51,'CX','CXR','Christmas Island','ChristmasIsland'),(52,'CC','CCK','Cocos Islands','CocosIslands'),(53,'CO','COL','Colombia','Colombia'),(54,'KM','COM','Comoros','Comoros'),(55,'CG','COG','Congo','Congo'),(56,'CR','CRI','Costa Rica','CostaRica'),(57,'HR','HRV','Croatia','Croatia'),(58,'CU','CUB','Cuba','Cuba'),(59,'CW','CUW','Curacao','Curacao'),(60,'CY','CYP','Cyprus','Cyprus'),(61,'CZ','CZE','Czech Republic','CzechRepublic'),(62,'CD','COD','Republic of the Congo','RepublicOfTheCongo'),(63,'DK','DNK','Denmark','Denmark'),(64,'DJ','DJI','Djibouti','Djibouti'),(65,'DM','DMA','Dominica','Dominica'),(66,'DO','DOM','Dominican Republic','DominicanRepublic'),(67,'TL','TLS','East Timor','EastTimor'),(68,'EC','ECU','Ecuador','Ecuador'),(69,'EG','EGY','Egypt','Egypt'),(70,'SV','SLV','El Salvador','ElSalvador'),(71,'GQ','GNQ','Equatorial Guinea','EquatorialGuinea'),(72,'ER','ERI','Eritrea','Eritrea'),(73,'EE','EST','Estonia','Estonia'),(74,'ET','ETH','Ethiopia','Ethiopia'),(75,'FK','FLK','Falkland Islands','FalklandIslands'),(76,'FO','FRO','Faroe Islands','FaroeIslands'),(77,'FJ','FJI','Fiji','Fiji'),(78,'FI','FIN','Finland','Finland'),(79,'FR','FRA','France','France'),(80,'PF','PYF','French Polynesia','FrenchPolynesia'),(81,'GA','GAB','Gabon','Gabon'),(82,'GM','GMB','Gambia','Gambia'),(83,'GE','GEO','Georgia','Georgia'),(84,'DE','DEU','Germany','Germany'),(85,'GH','GHA','Ghana','Ghana'),(86,'GI','GIB','Gibraltar','Gibraltar'),(87,'GR','GRC','Greece','Greece'),(88,'GL','GRL','Greenland','Greenland'),(89,'GD','GRD','Grenada','Grenada'),(90,'GU','GUM','Guam','Guam'),(91,'GT','GTM','Guatemala','Guatemala'),(92,'GG','GGY','Guernsey','Guernsey'),(93,'GN','GIN','Guinea','Guinea'),(94,'GW','GNB','Guinea-Bissau','Guinea-Bissau'),(95,'GY','GUY','Guyana','Guyana'),(96,'HT','HTI','Haiti','Haiti'),(97,'HN','HND','Honduras','Honduras'),(98,'HU','HUN','Hungary','Hungary'),(99,'IS','ISL','Iceland','Iceland'),(100,'IN','IND','India','India'),(101,'IR','IRN','Iran','Iran'),(102,'IQ','IRQ','Iraq','Iraq'),(103,'IE','IRL','Ireland','Ireland'),(104,'IM','IMN','Isle of Man','IsleOfMan'),(105,'IL','ISR','Israel','Israel'),(106,'IT','ITA','Italy','Italy'),(107,'CI','CIV','Ivory Coast','IvoryCoast'),(108,'JM','JAM','Jamaica','Jamaica'),(109,'JP','JPN','Japan','Japan'),(110,'JE','JEY','Jersey','Jersey'),(111,'JO','JOR','Jordan','Jordan'),(112,'KZ','KAZ','Kazakhstan','Kazakhstan'),(113,'KE','KEN','Kenya','Kenya'),(114,'KI','KIR','Kiribati','Kiribati'),(115,'XK','XKX','Kosovo','Kosovo'),(116,'KW','KWT','Kuwait','Kuwait'),(117,'KG','KGZ','Kyrgyzstan','Kyrgyzstan'),(118,'LA','LAO','Laos','Laos'),(119,'LV','LVA','Latvia','Latvia'),(120,'LB','LBN','Lebanon','Lebanon'),(121,'LS','LSO','Lesotho','Lesotho'),(122,'LR','LBR','Liberia','Liberia'),(123,'LY','LBY','Libya','Libya'),(124,'LI','LIE','Liechtenstein','Liechtenstein'),(125,'LT','LTU','Lithuania','Lithuania'),(126,'LU','LUX','Luxembourg','Luxembourg'),(127,'MK','MKD','MacedoniLine truncated
/*!40000 ALTER TABLE `nationality` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `user_group_roles`
--
LOCK TABLES `user_group_roles` WRITE;
/*!40000 ALTER TABLE `user_group_roles` DISABLE KEYS */;
INSERT INTO `user_group_roles` VALUES (4,2),(8,32),(4,110),(9,110),(5,111),(7,111),(6,112),(7,114);
/*!40000 ALTER TABLE `user_group_roles` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping data for table `modules_roles`
--
LOCK TABLES `modules_roles` WRITE;
/*!40000 ALTER TABLE `modules_roles` DISABLE KEYS */;
INSERT INTO `modules_roles` VALUES (12010010,99),(12010010,100),(12010010,101),(12010010,110),(12010100,99),(12010100,100),(12010100,101),(12010100,110),(12010100,111),(12010100,114),(12010100,118),(12010100,119),(12010110,99),(12010110,100),(12010110,101),(12010110,110),(12010110,111),(12010120,99),(12010120,100),(12010120,101),(12010120,110),(12010120,111),(12010400,99),(12010400,100),(12010400,101),(12010500,99),(12010500,100),(12010500,101),(12010500,110),(12010790,110),(12010800,99),(12010800,100),(12010800,101),(12010800,110),(12010900,99),(12010900,100),(12010900,101),(12010900,110),(12011200,99),(12011200,100),(12011200,101),(12011200,110),(12011300,99),(12011300,100),(12011300,101),(12011400,99),(12011400,100),(12011400,101),(12011400,110),(12011901,99),(12011901,100),(12011901,101),(12011901,110),(12020100,99),(12020100,100),(12020100,101),(12020100,110),(12020200,99),(12020200,100),(12020200,101),(12020300,99),(12020300,100),(12020300,101),(12020300,110),(12020400,99),(12020400,100),(12020400,101),(12020400,110),(12020500,99),(12020500,100),(12020500,101),(12020500,110),(12610100,99),(12610100,100),(12610100,101),(12610100,109),(12610100,111),(12610100,113),(12610100,115),(12610200,99),(12610200,100),(12610200,101),(12610200,109),(12610200,111),(12610200,113),(12610200,115),(12610210,99),(12610210,100),(12610210,101),(12610210,109),(12610210,111),(12610210,113),(12610210,115),(12610300,99),(12610300,100),(12610300,101),(12610300,109),(12610300,111),(12610300,113),(12610300,115),(12610400,99),(12610400,100),(12610400,101),(12610400,109),(12610400,111),(12610400,113),(12610400,115),(12610405,109),(12610500,99),(12610500,100),(12610500,101),(12610500,109),(12610500,111),(12610500,113),(12610500,115),(12610540,111),(12610550,111),(12610600,99),(12620100,99),(12620200,99),(12620300,99),(12620400,99),(12630006,99),(12630006,100),(12630006,101),(12700100,111),(12700100,114),(12700100,117),(12700100,118),(12700200,111),(12700200,114),(12700200,117),(12700200,118),(12700300,111),(12700300,114),(12700300,117),(12700300,118),(12700400,111),(12700400,114),(12700400,117),(12700400,118),(12700500,111),(12700500,114),(12700500,117),(12700500,118),(12700505,111),(12700510,111),(12700510,114),(12700510,117),(12700510,118),(12700520,111),(12700520,114),(12700520,117),(12700520,118),(12700530,111),(12700530,114),(12700530,116),(12700530,117),(12700530,118),(12700600,111),(12700600,114),(12700600,118),(12700600,119),(12700700,111),(12700700,114),(12700700,118),(12700700,119),(12700800,111),(12700800,114),(12700800,118),(12700800,119),(13000010,110),(13010200,99),(13010200,100),(13010200,101),(13010200,110),(13010220,110),(13010400,99),(13010400,100),(13010400,101),(13010400,109),(13010400,110),(13010994,110),(13015100,101),(13015100,109),(13015100,110),(13015200,99),(13015200,100),(13015200,101),(13015200,110),(13015360,110),(13015370,110),(14010100,99),(14010100,100),(14010100,101),(14020100,99),(14020100,100),(14020100,101),(14020200,99),(14020200,100),(14020200,101),(14020300,99),(14020300,100),(14020300,101),(14020350,99),(14020350,100),(14020350,101),(14020400,99),(14020400,100),(14020400,101),(14020450,99),(14020450,100),(14020450,101),(14020500,99),(14020500,100),(14020500,101),(14020510,99),(14020510,100),(14020510,101),(14080100,99),(14080100,100),(14080100,101),(14090100,99),(14090100,100),(14090100,101),(14090200,99),(14090200,100),(14090200,101),(15010100,99),(15010100,100),(15010100,109),(15010100,110),(15010200,99),(15010200,100),(15010200,109),(15010200,110),(15010300,99),(15010300,100),(15010300,109),(15010300,110),(15010400,99),(15010400,100),(15010400,110),(15020100,99),(15020100,100),(15020100,101),(15020100,110),(15030100,110),(15030200,110),(15030300,110),(15030400,110),(15031500,110),(15031600,110),(15031700,110),(15031800,110),(15031910,110),(15032100,110),(15032200,110),(15032300,110),(15032400,110),(15041000,111),(15041000,112),(15041000,114),(15042000,111),(15042000,112),(15043000,111),(15043000,112),(15043000,114),(15043000,119),(15600200,99),(15600200,100),(15600200,101),(15600410,99),(15600410,100),(15600410,101),(15600415,99),(15600415,100),(15600415,101),(15600610,99),(15600610,100),(15600610,101),(15600620,99),(15600620,100),(15600620,101),(16010100,101),(16010200,101),(16030100,110),(16030200,110),(16030300,110),(19010100,99),(19010100,100),(19010100,101),(19010100,110),(19010200,99),(19010200,100),(19010200,101),(19010200,110),(19010200,111),(19010310,99),(19010310,100),(19010310,101),(19010310,110),(19010310,111),(19010315,99),(19010315,100),(19010315,101),(19010315,110),(19010315,111),(19010320,99),(19010320,100),(19010320,101),(19010320,110),(19010320,111),(19010321,99),(19010321,100),(19010321,101),(19010321,110),(19010321,111),(19020100,99),(19020100,100),(19020100,101),(19020100,110),(19020100,111),(19020200,99),(19020200,100),(19020200,101),(19020200,110),(19020200,111),(19020300,99),(19020300,100),(19020300,101),(19020300,110),(19020300,111),(19035100,99),(19035100,100),(19Line truncated
/*!40000 ALTER TABLE `modules_roles` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2026-11-26 16:18:05
+17
View File
@@ -0,0 +1,17 @@
-- Local dev only. One company and one admin login.
-- Admin login: admin / colite-dev-admin (dev password, documented in local/README.md).
-- The company table and user.company_id for real environments are added by the admin-auth change (change 2).
USE `service-system`;
CREATE TABLE IF NOT EXISTS `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');
INSERT INTO `user` (`id`, `email`, `enabled`, `name`, `password`, `username`, `groupid`, `branchid`,
`login`, `status`, `type`, `create_by`, `create_date`, `done_by`)
VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 0,
'N', 'Y', 'A', 'seed', NOW(), 'seed');
INSERT INTO `users_roles` (`user_id`, `role_id`) VALUES (1, 1);
Executable
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Smoke check for the local stack: exits non-zero and names the failing call if any step fails.
set -u
GW=http://localhost:8081
MOBILE=http://localhost:8080
GW_KEY=colite-local-gateway-key-000000000000
APP_KEY=colite-local-app-key
fail() { echo "FAIL: $1"; exit 1; }
# 1. Admin login: gateway -> service-auth -> service-system -> MySQL
token=$(curl -sf -X POST "$GW/auth/authenticate" -H "api-key: $GW_KEY" -H 'Content-Type: application/json' \
-d '{"username":"admin","password":"colite-dev-admin"}') || fail "POST $GW/auth/authenticate"
[ -n "$token" ] || fail "POST $GW/auth/authenticate returned no token"
echo "auth/authenticate: 200"
# 2. gateway -> service-counter -> MySQL
code=$(curl -s -o /dev/null -w '%{http_code}' "$GW/counter/event/findCurrentEvent" \
-H "api-key: $GW_KEY" -H "Authorization: Bearer $token")
[ "$code" = 200 ] || fail "GET $GW/counter/event/findCurrentEvent returned $code"
echo "counter/event/findCurrentEvent: $code"
# 3. mobile-api -> gateway -> service-system -> MySQL
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"
echo "api/public/messages/en_US: $code"
echo "smoke: OK"
Executable
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
# Builds every backend module and starts the local stack.
set -eu
cd "$(dirname "$0")"
[ -f .env ] || cp .env.example .env
(cd .. && mvn -T 1C -B -q -DskipTests package)
docker compose up -d --build
docker compose ps
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-26
@@ -0,0 +1,76 @@
# Design
## Context
See proposal.md for the motivation. The phase 1 design is in `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md`.
What Tastefully looks like today (commit `8bd93d15`):
- There is no root pom. Each module is a standalone Spring Boot 3.2.8 app with its own parent and pulls `com.solvway.core:solvway-core-libs:${core-project.version}` (`tastefully-v1`) from `~/.m2`. Babyboo uses `babyboo-v1` at the same coordinates.
- Every service listens on port 80. The gateway resolves services by hostname from `app.services.name.*`: `service-auth`, `service-system`, `service-counter` and so on. These are the k8s service names.
- MySQL holds one schema per service (`service-system`, `service-counter`, `service-member`, `service-log`, `service-email`). Tables are managed by hand-written DDL; there is no `ddl-auto` and no Flyway. No full DDL exists in the repo.
- Config comes from environment variables: `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`, `REDISHOST`, `GCP_PROJECT`, `GCP_CREDENTIAL_FILE`, `APIGATEWAYURL` and `AES_SECRET_KEY`. mobile-api also requires `JWT_SECRET`, `APIKEY` and `AUTH_API_KEYS`.
- Added by this change when literal secrets were removed: `JWT_TOKEN` (required, must equal `JWT_SECRET`), `USER_AUTH_API_SECRET` (required), and optional `SMTP_PASSWORD`, `MAILGUN_API_KEY`, `SENDGRID_API_KEY`, `MAILJET_API_KEY`, `MAILJET_SECRET_KEY`, `JUMIO_TOKEN`, `JUMIO_SECRET`, `XXL_JOB_TOKEN`, `IPGEOLOCATION_API_KEY` and `USERSTACK_API_KEY`. The gateway reads its API keys from a mounted `/deployments/appkeys/appkeys.json`. Change 5 (k8s) must supply all of these.
- The dumped schema loads only with MySQL `log_bin_trust_function_creators=1` and `innodb_strict_mode=OFF`; change 5 must check the production server matches.
- Pub/Sub inbound adapters are declared in each service's `PubSubConfig` (system 7, counter 12, member 12, log 3, email 3). Some serve flows Co-Lite drops (stockist, Jumio, Camunda). They stay, so each subscription must exist in the emulator.
- The Dockerfiles use the base image `gitea.containerverse.dev/solvway/docker-java-21`, `ADD target/*.jar` and `-Dspring.profiles.active=$BUILD_PROFILE`.
## Goals / Non-Goals
**Goals:**
- Bring the stack up from a clean clone with two commands: build, then up.
- Use the same hostnames and ports as k8s, so change 5 reuses the images and env contract unchanged.
**Non-Goals:**
- Any admin API, lead table or portal trimming. Those belong to changes 2–4.
- Removing dead code inside kept modules beyond what stops compilation or startup.
- Running the Next.js apps inside compose. They run with `npm run dev`.
## Decisions
1. **Copy with `git archive` at pinned commits.** Tastefully `8bd93d15` and babyboo `f64d096ea`. Only tracked files come across: no `node_modules`, `target` or stray files.
- Alternative: `cp -r`. Rejected because it drags in untracked junk and possibly local secrets.
2. **Root aggregator pom.** Add a `pom.xml` with `<packaging>pom</packaging>` that lists the kept modules, with `solvway-core-libs` and `solvway-core-session` first. Module poms keep their own Spring Boot parent. The aggregator only orders the reactor, so `mvn -T 1C verify` at the root builds everything.
- Alternative: a shared parent. Rejected because it would rewrite every module pom for no phase-1 gain.
3. **core-libs version `colite-v1`.** Set it in `solvway-core-libs/pom.xml`, and set `core-project.version` in every kept module. The same applies to `solvway-core-session` if it is versioned the same way.
4. **Compose mirrors k8s.** Compose service names equal the k8s names (`service-auth`, `service-system`, `service-counter`, `service-member`, `service-log`, `service-email`, `api-gateway`, `mobile-api`). Each service listens on port 80 inside its container. Only `mobile-api` and `api-gateway` are published to the host, on 8080 and 8081.
- Images are built from the existing Dockerfiles with `BUILD_PROFILE=local`.
5. **`local` Spring profile per module.** Add an `application-local.yml` that sets `spring.cloud.gcp.pubsub.emulator-host: pubsub:8085` and `spring.cloud.gcp.project-id: co-lite-local`. It also disables the credentials-file requirement where the emulator needs that. All other values still come from the env file `local/.env.example`, with dev-only values; a copied `.env` is git-ignored.
6. **Pub/Sub emulator plus an init job.** A one-shot container creates every topic and subscription from `local/pubsub/topics.txt`, one `topic subscription` pair per line, before the services start (`depends_on: condition: service_completed_successfully`). The list is extracted from the kept modules' `PubSubConfig` classes and resolved property values.
7. **Seed from the user's Tastefully dump.** MySQL runs its official image's `/docker-entrypoint-initdb.d`. It runs only on an empty volume, which gives first-start seeding for free.
- Files, in run order:
1. `01-schema.sql`: schema-only dump of the five schemas.
2. `02-reference.sql`: reference-table rows (roles, modules/menus, system_property, location_hierarchy and other lookup tables, chosen per table).
3. `03-colite.sql`: one company and one admin user, with a bcrypt hash of a dev-only password documented in `local/README.md`.
- Reset is `docker compose down -v`.
- **Location:** `local/seed/`. Decided by the user: runnable dev seed files are a documented exception to the SQL-placement rule (see `CLAUDE.md`), because the change folder moves when the change is archived and would break the compose mount.
- **Source:** the user supplies a schema-only dump and a reference-table data dump, not a full dump. Customer data from Tastefully never enters this repo or the local database.
8. **Smoke check is `local/smoke.sh`.** It makes three calls and exits non-zero, naming the failing call, if any of them fails:
1. Admin login: `POST /auth/authenticate` on the gateway (auth → system → MySQL).
2. `GET /counter/event/findCurrentEvent` on the gateway, with the admin token (counter → MySQL).
3. `GET /api/public/messages/en_US` on mobile-api (mobile-api → gateway → system → MySQL).
- The originally planned `GET /api/event/upcomingEvent` returns a hardcoded URL and never reaches a service. mobile-api has no public endpoint backed by counter; its counter calls need a member token. That is why the counter call goes through the gateway directly.
9. **Dropped-service references.** HTTP calls to dropped services are strings; they compile and only fail if called, so they stay. Remove only these:
- gateway routes whose `uri` points at a dropped service (bonus, payment, inventory, stockist, wallet and similar);
- any bean or config that fails at startup without a dropped service.
- Each removal is listed in the task's commit message.
## Risks / Trade-offs
- [The base image `gitea.containerverse.dev/solvway/docker-java-21` needs registry access] → The README documents `docker login gitea.containerverse.dev`. If access is a blocker, use `eclipse-temurin:21-jre` locally only.
- [The dump may contain customer data in tables thought to be reference data] → Reference rows are dumped per table from an allow-list, and the diff is reviewed before commit (spec scenario "Seed contains no customer data").
- [The schema dump drifts from the entity mappings] → The smoke check and service startup catch it, and change 2–4 tests run against the seeded schema.
- [Subscriptions are missed in the emulator] → The services fail at startup. The "stack starts healthy" scenario checks the logs.
- [Six JVMs plus MySQL use about 6 GB of RAM] → Set `JAVA_OPTS=-Xmx384m` per service in compose.
## Migration Plan
None. This is a new repo with nothing deployed. Rollback is reverting the commits.
@@ -0,0 +1,33 @@
# Proposal
## Why
Co-Lite has no code yet. Before any lead-tracking work can start, the repository needs the Tastefully modules Co-Lite keeps, plus the two web apps. It also needs a way to run the whole system on a developer machine, because nothing is deployed yet. This is change 1 of 5 in phase 1 (see `docs/superpowers/specs/2026-11-26-co-lite-foundation-and-leads-design.md`). Go-live is 15 January 2027.
## What Changes
- Copy the kept Tastefully modules into this repo from Tastefully commit `8bd93d15`: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log and services-email.
- Copy `solvway-admin-portal` from babyboo commit `f64d096ea` and `solvway-customer-portal` from Tastefully. Both are unchanged in this change; they are trimmed in later changes.
- Add a root Maven aggregator `pom.xml` so one parallel build covers every kept module.
- Change the core-libs version from `tastefully-v1` to `colite-v1`, so Co-Lite's library cannot overwrite Tastefully's or babyboo's in the shared local Maven repository.
- Remove gateway routes for dropped services, plus any code in kept modules that stops compilation or startup without a dropped module.
- Add `local/`: a docker-compose stack with MySQL, Redis, the Pub/Sub emulator and every kept backend service, plus one documented start command.
- Seed the local MySQL with Tastefully's schemas and reference data, taken from a schema dump the user supplies, plus one company and one admin user.
- Add a smoke check: one existing public mobile-api endpoint that reads from services-counter and MySQL through the gateway.
## Capabilities
### New Capabilities
- `local-dev-stack`: running the full Co-Lite backend on a developer machine: build, start, seed and smoke-check.
### Modified Capabilities
None.
## Impact
- New top-level modules and `local/` directory; no existing code in this repo is touched.
- Shared local Maven repository: adds `com.solvway.core:solvway-core-libs:colite-v1` alongside the existing versions.
- Requires a Tastefully schema dump from the user before the seed task (task group 4) can finish.
- No production systems or databases are touched. The local MySQL is disposable and dev-only.
@@ -0,0 +1,80 @@
# Spec Delta
## Purpose
Lets a developer build, start, seed and check the whole Co-Lite backend on their own machine, with no shared environment.
## ADDED 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
@@ -0,0 +1,37 @@
# Tasks
Run serially: every group touches build files or shared config.
## 1. Copy modules into the repo
- [x] 1.1 Copy the ten kept backend modules (core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email) from Tastefully `8bd93d15`, using `git -C ~/Projects/tastefully archive 8bd93d15 <dirs> | tar -x`. Verify: `ls` shows exactly those ten `solvway-*` dirs, and `find . -name node_modules -o -name target` is empty.
- [x] 1.2 Copy `solvway-admin-portal` from babyboo `f64d096ea` and `solvway-customer-portal` from Tastefully `8bd93d15` the same way. Verify that `npm ci && npm test && npm run build` passes in each app, or record the pre-existing failures with their output.
- [x] 1.3 Scan the copied tree for secrets: `grep -rnEi "(password|secret|apikey|api_key|token|BEGIN .*PRIVATE KEY)\s*[:=]" --include=*.yml --include=*.yaml --include=*.properties --include=*.env* --include=*.json .`. Replace every literal secret with an env placeholder. Verify: re-running the scan shows only placeholders or dev-only values. Commit with the list of replaced keys, never the values.
## 2. Single build
- [x] 2.1 Set the core-libs version to `colite-v1` in `solvway-core-libs/pom.xml` (and core-session if it shares the scheme), and set `core-project.version` to `colite-v1` in every kept module pom. Verify: `grep -rn "tastefully-v1\|babyboo-v1" --include=pom.xml .` is empty.
- [x] 2.2 Add a root `pom.xml` aggregator (groupId `com.solvway`, artifactId `co-lite`, packaging `pom`) listing the ten modules, core-libs and core-session first. Verify: `mvn -T 1C verify` at the root passes, and `ls ~/.m2/repository/com/solvway/core/solvway-core-libs/` still contains `tastefully-v1` with an unchanged timestamp. Do not run `mvn install` against the Tastefully or babyboo repos.
- [x] 2.3 Remove gateway routes to dropped services in `solvway-api-gateway/src/main/resources/application.yml`, and any `app.services.name.*` entries only they use. Verify: the existing gateway tests pass, and `grep -nE "bonus|payment|inventory|stockist|wallet" solvway-api-gateway/src/main/resources/application.yml` is empty.
## 3. Local stack (without seed)
- [x] 3.1 Extract every Pub/Sub topic and subscription name used by the kept modules: read each `PubSubConfig`, `PubSubListener` and publisher call, and resolve property values. Write them to `local/pubsub/topics.txt` as `topic subscription` lines, plus publish-only topics as `topic` lines. Verify: every `@Value("${pubsub...}")` key in the kept modules resolves to a name (none unresolved). Result: 32 unique subscriptions plus 9 publish-only topics. There are fewer than the 37 adapter constructions because Tastefully shares some subscription names across services (e.g. `new-member-add-user-subscription` in system, counter and member). This is kept as-is.
- [x] 3.2 Add `application-local.yml` to each kept Spring module with the emulator host and `co-lite-local` project id. Verify: `mvn -T 1C verify` still passes.
- [x] 3.3 Add `local/docker-compose.yml`: mysql:8, redis:7, the Pub/Sub emulator, a pubsub-init one-shot that reads `topics.txt`, and the eight Java services named as in design decision 4, each with `JAVA_OPTS=-Xmx384m`. Add `local/.env.example` with dev-only values for every env var listed in design Context, and git-ignore `local/.env`. Add `local/up.sh`, which runs `mvn -T 1C -DskipTests package` then `docker compose up -d --build`. Verify: with an empty MySQL (schemas created empty by an init script), `local/up.sh` brings pubsub-init to exit 0, and no service log shows a missing topic or subscription error. Result (2026-11-26): pubsub-init exit 0, 7 of 8 services start on empty schemas, and service-counter stops only on `Table 'service-counter.event' doesn't exist`, which is expected until group 4 seeds the schema. Gateway API keys are mounted from `local/appkeys.json` at `/deployments/appkeys/appkeys.json`, as in k8s.
## 4. Seed (needs the user's Tastefully dump)
- [x] 4.1 Ask the user for the dump, giving them this exact command: `mysqldump --no-data --routines --triggers --skip-add-drop-table --databases service-system service-counter service-member service-log service-email > 01-schema.sql`, plus a data dump of an allow-list of reference tables. Build the allow-list from the services-system entities: role, module, system_property, location_hierarchy and the other lookup tables, each checked for personal data before it is listed. Put the files in `local/seed/`. Verify: grep the files for `INSERT INTO \`(member|user|event_attendance|orders)` and it is empty.
- [x] 4.2 Write `03-colite.sql`: one company row and one admin user with the Administrator role, a bcrypt hash of the documented dev password, and the column set matching the dumped `user` table. Verify: after `docker compose down -v && local/up.sh`, `SELECT count(*) FROM \`service-system\`.user` returns 1. The admin can log in through `POST /auth/...` via the gateway (endpoint confirmed from services-auth) and gets a token. Result: `POST /auth/authenticate` through the gateway (`api-key` header) returns a JWT for `admin` / `colite-dev-admin`. A wrong password returns 200 with an empty body, which is existing Tastefully behaviour. MySQL runs with `--log-bin-trust-function-creators=1 --innodb-strict-mode=OFF` to load the dumped schema, and its healthcheck uses TCP so services wait for seeding to finish.
- [x] 4.3 Write `local/README.md`: prerequisites (JDK 21, Maven, Docker, registry login), build/up, reset (`docker compose -f local/docker-compose.yml down -v`), the dev login, and how to rebuild one service and attach a debugger inside the stack. (This replaces the planned "run one service from an IDE": services address each other by container name, so a service outside Docker cannot join the stack.) Verify: a second developer follows it on a clean clone without help. If no second developer is available, re-run the documented commands verbatim on a fresh clone in a scratch dir.
## 5. Smoke check
- [x] 5.1 Add `local/smoke.sh` (design decision 8). Verify on a healthy stack: exit 0 and prints `200`. Then `docker compose stop service-counter`: exit non-zero, with the failing URL printed.
- [x] 5.2 Integration: from a fresh clone in a scratch directory, run `mvn -T 1C verify`, `local/up.sh` and `local/smoke.sh`. Verify: all three succeed and `docker compose ps` shows every service running. Paste the outputs into the PR description.
## Workflow follow-up
- Code review, then push the branch and confirm the PR target with the user.
- Archive the change after merge.
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Aggregator only: orders the reactor. Each module keeps its own Spring Boot parent. -->
<groupId>com.solvway</groupId>
<artifactId>co-lite</artifactId>
<version>colite-v1</version>
<packaging>pom</packaging>
<modules>
<module>solvway-core-libs</module>
<module>solvway-core-session</module>
<module>solvway-api-gateway</module>
<module>solvway-mobile-api</module>
<module>solvway-services-auth</module>
<module>solvway-services-system</module>
<module>solvway-services-counter</module>
<module>solvway-services-member</module>
<module>solvway-services-log</module>
<module>solvway-services-email</module>
</modules>
</project>
@@ -0,0 +1,105 @@
---
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.
---
All paths below are relative to `solvway-admin-portal/`.
This is a **Next.js 16 App Router** app (React 19, TypeScript). `/login` posts to the same-origin
`/api/auth/login` route handler, which proxies `solvway-mobile-api` (`app/lib/server/mobileApi.ts`)
and sets an httpOnly session cookie server-side. Drive it by starting the dev server, then
driving the browser with `playwright-cli` (see the `playwright-cli` skill for its commands).
## Prerequisites
Needs Node 22+ and npm. No OS packages needed — it's a pure JS toolchain.
A real sign-in also needs, at runtime:
- `MOBILE_API_BASE_URL` and `MOBILE_API_KEY` (see `.env.example`) pointing at a reachable
`solvway-mobile-api` instance.
- A real `UserType.A` account in that instance's services-system.
Without those two env vars, the app still starts and `/login` still renders, but submitting the
form reports **"Mobile API is not configured"** — there is no local/offline demo login. A purely
local run with no env vars can reach `/login` (and any other page reachable without auth) but
cannot complete sign-in.
## Setup
```bash
npm install
```
Run this even if `node_modules/` already exists and looks populated — see Gotchas.
## Run (agent path)
Start the dev server in the background and poll the port instead of sleeping:
```bash
npm run dev & # next dev --port 3001, binds http://localhost:3001/
timeout 30 bash -c 'until curl -sf http://localhost:3001/login >/dev/null; do sleep 1; done'
```
Expect `▲ Next.js 16.x.x` and `Local: http://localhost:3001`.
Drive it with `playwright-cli`:
1. `playwright-cli open http://localhost:3001/`. An unauthenticated request to any non-public
path (`app/lib/routeGuard.ts` `PUBLIC_PATHS`) redirects to `/login` via `middleware.ts`.
2. If redirected to `/login`, signing in requires a **reachable `solvway-mobile-api`** (with
`MOBILE_API_BASE_URL`/`MOBILE_API_KEY` configured for this dev server) **and** a real
`UserType.A` account: fill `input#email` / `input#password` and click the button labelled
"Log in". On success this redirects to `/` (Dashboard). If the Mobile API is not configured,
or the environment has no reachable mobile-api, submitting reports an inline error instead
("Mobile API is not configured", or the upstream's invalid-credentials message) — that is
expected in an isolated dev run, not a bug in this app.
3. `playwright-cli snapshot` to confirm state, `playwright-cli screenshot` to prove render,
`playwright-cli console error` to confirm nothing threw, then `playwright-cli close`.
Without a working sign-in, you can still verify the app shell: `/login`'s own render (form,
validation, password-reveal toggle) and the unauthenticated-redirect behavior on any other route
are both fully exercisable with no backend. Reaching the Dashboard/Members/Reports/Network pages
past login needs the mobile-api + account described above.
**Stop**: kill the PID you started, never a broad pattern:
```bash
kill <pid-from-$!> # or: lsof -ti :3001, check it is next dev, then kill that PID
```
## Run (human path)
```bash
npm run dev # → open http://localhost:3001/ in a browser. Ctrl-C to stop.
```
## Build
```bash
npm run build # next build — type-checks + production build
npm start # next start --port 3001, after a build
```
## Test
```bash
npm test # vitest run
npm run test:watch # vitest, watch mode
npx eslint app # lint
```
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` rather than hitting a network, so
none of this suite depends on a reachable `solvway-mobile-api`.
## Gotchas
- **`node_modules/` existing ≠ complete.** A prior/partial install can leave `node_modules/`
present but missing a dependency, so `npm run dev` fails with a resolution error even though the
directory looked populated. Always `npm install` before trusting an existing `node_modules/`.
- **A local run with no `MOBILE_API_BASE_URL`/`MOBILE_API_KEY` cannot complete sign-in.** This is
expected, not a broken build — the login form surfaces "Mobile API is not configured" instead of
hanging or throwing.
+10
View File
@@ -0,0 +1,10 @@
.git
.gitignore
node_modules
.next
.env*
README.md
*.log
.playwright-mcp
# test/ and *.test.ts(x) are deliberately NOT excluded: the builder stage runs
# `npm run test`, and vitest.config.ts aliases `server-only` to test/stub-empty.ts.
+13
View File
@@ -0,0 +1,13 @@
# ── Mobile API (BFF target) ───────────────────────────────────────────
# Base URL of babyboo's solvway-mobile-api, no trailing slash.
# Supplied per environment; there is no sensible default.
MOBILE_API_BASE_URL=
# The "Mobile APP" api-key required on every mobile-api request.
# SERVER-ONLY — never prefix with NEXT_PUBLIC_, or it ships to every browser.
# Must match an entry in solvway-mobile-api's application.yml `auth.api-key.list`.
MOBILE_API_KEY=
# ── Session ───────────────────────────────────────────────────────────
# Name of the httpOnly cookie that stores the admin JWT.
SESSION_COOKIE_NAME=bb_admin
+53
View File
@@ -0,0 +1,53 @@
# Logs
/logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# Dependencies
node_modules
/.pnp
.pnp.js
# Testing
/coverage
# Next.js build output
/.next/
/out/
# Production build output
/build
dist
dist-ssr
*.local
# Local environment files (never commit secrets)
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Vercel
.vercel
# TypeScript
*.tsbuildinfo
# Superpowers SDD workspace
.superpowers/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+1
View File
@@ -0,0 +1 @@
24
+7
View File
@@ -0,0 +1,7 @@
{
"semi": false,
"singleQuote": true,
"arrowParens": "avoid",
"printWidth": 100,
"trailingComma": "all"
}
+62
View File
@@ -0,0 +1,62 @@
FROM node:24-alpine AS base
# ── Stage 1: install deps ─────────────────────────────────────────────────────
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
COPY vendor/ ./vendor/
RUN npm ci
# A High or Critical advisory in a runtime dependency fails the image (F45). Dev tooling is not shipped,
# so it is excluded. Moderate advisories do not block; review them with a full `npm audit`.
RUN npm audit --omit=dev --audit-level=high
# ── Stage 2: source shared by test and build ─────────────────────────────────
FROM base AS source
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# ── Stage 3a: test ────────────────────────────────────────────────────────────
# Tests run here deliberately: a red suite fails the image build, matching
# solvway-customer-portal. The Maven modules are built with -Dmaven.test.skip=true and
# not covered in CI, so this is the only automated gate this module gets.
# .dockerignore must therefore NOT exclude test/ or *.test.ts(x) — vitest.config.ts
# aliases `server-only` to test/stub-empty.ts.
# BuildKit runs this stage in parallel with builder, and builds only stages the target needs: the
# runner's COPY of .tests-passed is what keeps this suite a gate. Do not remove it.
FROM source AS test
# ci-runs-repo-checks: an ESLint error fails the image like a red test (warnings do not).
RUN npm run lint && npm run test && touch .tests-passed
# ── Stage 3b: build ───────────────────────────────────────────────────────────
FROM source AS builder
# Delete Next's build cache in the same RUN so it never lands in a committed layer. Nothing reads it: the
# build starts from a clean .next (.dockerignore) and the runner copies only standalone/, static/ and public/.
# Left in, Turbopack's churning .sst store made Docker fail to apply the layer (main run 5980:
# "failed to Lchown .../.next/cache/turbopack/...sst: no such file").
RUN npm run build && rm -rf .next/cache
# ── Stage 4: runtime image ────────────────────────────────────────────────────
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
RUN addgroup --system --gid 1001 nodejs \
&& adduser --system --uid 1001 nextjs
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
# Depends on the test stage so a red suite fails the image (see Stage 3a).
COPY --from=test /app/.tests-passed /tmp/.tests-passed
USER nextjs
EXPOSE 3000
# Supply MOBILE_API_BASE_URL, MOBILE_API_KEY and SESSION_COOKIE_NAME at runtime
# via -e flags / k8s env — never bake secrets into the image
CMD ["node", "server.js"]
+206
View File
@@ -0,0 +1,206 @@
# Back-Office Template — babyboo.my
> **Migration in progress.** This module is being converted from a Vite SPA to a Next.js App
> Router project (see `openspec/changes/add-admin-portal-auth`). `app/` currently holds only a
> placeholder shell; the real pages, components and services below still live under `src/` —
> specifically `src/legacy-pages/` (renamed from `src/pages/` because Next.js reserves that name
> for its own Pages Router) — pending a later change that ports them into `app/*/page.tsx` with
> `react-router` calls rewired to `next/navigation`. Everything in this README describing routes,
> the mock-data architecture and theming still describes that `src/` tree.
A reusable admin/back-office front end for MLM (multi-level marketing) clients. It ships
against mock data behind an API-shaped service layer, so a client project can swap in a real
backend without touching any page or component code.
**Currently skinned for babyboo.my** — baby & maternity retail, competing with Medela, Momcozy,
Kinderkraft and Hamilton. The audience is sleep-deprived, time-poor, highly selective parents, so
decisions are ranked clarity → speed → trust. The look is deliberately warm and soft-edged rather
than clinical: cream page, warm neutrals, brand brown `#6E3E17` with a gold `#F2BC57` accent, and a
1rem radius so nothing has a sharp corner.
## Stack
- [Next.js 16](https://nextjs.org/) (App Router, `output: "standalone"`) — build tool and server
- [React 19](https://react.dev/) + TypeScript (strict mode)
- [Tailwind CSS 3](https://tailwindcss.com/) via PostCSS + `tailwind.config.ts` — matches
`solvway-customer-portal`'s wiring
- [Sass](https://sass-lang.com/) — token maps and mixins in `src/styles/` (pending port into
`app/globals.css`, which currently carries a plain-CSS transliteration of the same tokens)
- [shadcn/ui](https://ui.shadcn.com/) — owned component source, themed with CSS variables
- [Recharts](https://recharts.org/) via shadcn's `chart` wrapper — dashboard charts
- [TanStack Table](https://tanstack.com/table) — data tables
- [lucide-react](https://lucide.dev/) — icons
- [react-router-dom v7](https://reactrouter.com/) — still a dependency for the not-yet-ported
`src/legacy-pages/` tree; removed once that tree is rewired to `next/navigation`
- [Vitest](https://vitest.dev/) + [React Testing Library](https://testing-library.com/react) — tests
## Getting Started
```bash
npm install
npm run dev # next dev --port 3001
npm test # run the full test suite (Vitest, run once)
npm run test:watch # run tests in watch mode
npm run build # next build (type-checks + production build)
npm start # next start --port 3001, after a build
python3 scripts/check-contrast.py # verify token contrast in both themes
```
### Auth
Login is no longer mocked. `/login` posts to the same-origin `/api/auth/login` route handler,
which proxies `solvway-mobile-api` (`app/lib/server/mobileApi.ts`) and sets an httpOnly session
cookie server-side. Signing in requires:
- `MOBILE_API_BASE_URL` and `MOBILE_API_KEY` set (see `.env.example`), pointing at a reachable
`solvway-mobile-api` instance.
- A real `UserType.A` account in that instance's services-system.
Without a configured Mobile API, `/login` still renders, but submitting the form reports "Mobile
API is not configured" — there is no local/offline demo login anymore.
Visiting any other route while unauthenticated redirects back to `/login`; logging out clears the
session and returns you there as well.
## Screen Inventory
| Route | Page | Notes |
|---|---|---|
| `/login` | Login | Email/password with a password-reveal toggle; inline error on invalid credentials |
| `/` | Dashboard | Live KPI tiles (members, settled revenue/orders, rewards; Malaysia-time month), 12-month revenue and member-growth charts, revenue by channel, rank/status mix, rewards by type, top-earner leaderboard |
| `/members` | Members | Sortable, faceted, URL-synced member table with column visibility and CSV export |
| `/members/:id` | Member Detail | Identity header, performance strip, tabs for Sales · Commissions · Downline |
| `/reports` | Reports | Live Sales (settled orders) and Rewards tabs, Malaysia-time period presets + date range, paged, period totals, full-result-set CSV export |
| `/network` | Network | Genealogy as an indented tree or a top-down chart, with search that expands ancestors and highlights matches |
Navigation is a **collapsible sidebar with up to three levels**: it collapses to an icon rail on
desktop (persisted per browser) and becomes an overlay drawer below `lg`. Every leaf resolves to a
real view — `Members → By rank → Diamond` applies `?rank=Diamond`, the Reports children select
`?tab=` — so none of them are decorative.
[`src/components/app/nav-config.ts`](src/components/app/nav-config.ts) is the **contract a backend
menu endpoint would return**: plain `label` / `to` / `children` / `isDefault` data, with the icon as
the only client-side concern. `nav-config.test.ts` encodes the invariants such an endpoint must
satisfy (leaf-xor-group, depth cap, real routes, unique targets, one default per group), so a
backend implementation can be validated against the same rules the UI relies on.
## Design Standard
**[`docs/design/DASHBOARD-STANDARD.md`](docs/design/DASHBOARD-STANDARD.md) is authoritative.** It
defines the tokens, layout grid, KPI and chart specs, required data states, accessibility floor
(WCAG 2.1 AA) and the anti-patterns. Read it before adding a screen. Where it and a component
disagree, the component is wrong.
## Mock-Data Architecture
Everything under `src/services/*` is written to look and behave like a real API client: every
function is `async`, returns plain data (no framework types leak out), and pagination, filtering
and **sorting** happen the same way a backend would do them. The Dashboard and Reports are live
(`app/lib/services/adminDashboard.ts` -> BFF -> mobile-api aggregate reads); `src/services/api.ts` holds shared helpers (pagination, sorting, an
artificial network delay).
**Pages only call functions from the other
`src/services/*` modules. This is the intended swap point: to connect a real backend, replace the
bodies of these service functions with `fetch` calls that return the same shapes (see
`src/types/index.ts`), and no page or component needs to change.
```
src/
components/
app/ # two-level sidebar + nav config
ui/ # shadcn primitives + DataTable, states, chart skeletons
dashboard/ # KPI tile, chart card (chart + its accessible table)
genealogy/ # tree view and org chart
styles/
_variables.scss # $palettes (light + dark), breakpoints, layout, z-index
_mixins.scss # respond-to, focus-ring, tap-target, brand gradient
index.scss # emits the token blocks from the maps + base layer
tailwind.css # Tailwind entry + @theme (kept as CSS on purpose)
lib/
theme.tsx # light/dark provider, persists to localStorage
utils.ts # cn()
services/
api.ts # shared mock helpers (pagination, sorting, delay)
period.ts # month labels
auth.ts # login/logout/session — swap point
members.ts # list/detail/facets/stats — swap point
network.ts # genealogy tree — swap point
```
## Theming
Colour lives in Sass maps in [`src/styles/_variables.scss`](src/styles/_variables.scss), emitted as
CSS custom properties by `index.scss` and exposed to Tailwind via `@theme inline` in `tailwind.css`.
**No component contains a colour literal.**
The babyboo palette is brand brown `#6E3E17` with a gold `#F2BC57` accent on a cream page, plus warm
neutrals and a warm-espresso dark mode (not slate).
**One thing to know about the gold:** `#F2BC57` is 1.73:1 against white, so it can only ever be a
*filled surface* carrying `--accent-foreground` text — never text, a thin indicator, or a chart
series, all of which would be invisible in light mode. Anything in the accent family that must carry
meaning uses `--accent-strong` (`#9A6212`, 5.08:1). That is why the accent is absent from the chart
ramp.
Both themes live in the same map, so a token cannot be added to light and forgotten in dark.
To re-skin for a client:
1. Edit `$palettes` in `src/styles/_variables.scss` — primary, accent, chart ramp, radius.
2. Swap the font `<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.
@@ -0,0 +1,60 @@
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 });
});
});
@@ -0,0 +1,26 @@
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 });
}
@@ -0,0 +1,59 @@
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 });
});
});
@@ -0,0 +1,25 @@
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 });
}
@@ -0,0 +1,63 @@
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");
});
});
@@ -0,0 +1,22 @@
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);
}
@@ -0,0 +1,138 @@
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 });
});
});
@@ -0,0 +1,55 @@
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 });
}
@@ -0,0 +1,48 @@
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);
});
});
@@ -0,0 +1,11 @@
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"]);
}
@@ -0,0 +1,21 @@
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");
});
});
@@ -0,0 +1,48 @@
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);
});
});
@@ -0,0 +1,5 @@
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"]);
@@ -0,0 +1,13 @@
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"]);
}
@@ -0,0 +1,7 @@
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", []);
}
@@ -0,0 +1,77 @@
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);
});
});
@@ -0,0 +1,122 @@
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();
});
});
@@ -0,0 +1,49 @@
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);
}
@@ -0,0 +1,120 @@
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");
});
});
@@ -0,0 +1,74 @@
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 });
}
@@ -0,0 +1,44 @@
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" });
});
});
@@ -0,0 +1,21 @@
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);
}
@@ -0,0 +1,33 @@
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" });
});
});
@@ -0,0 +1,16 @@
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);
}
@@ -0,0 +1,38 @@
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=");
});
});
@@ -0,0 +1,30 @@
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);
}
@@ -0,0 +1,55 @@
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);
});
});
@@ -0,0 +1,32 @@
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);
}
@@ -0,0 +1,64 @@
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",
});
});
});
@@ -0,0 +1,48 @@
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);
}
@@ -0,0 +1,44 @@
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",
});
});
});
@@ -0,0 +1,38 @@
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);
}
@@ -0,0 +1,51 @@
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();
});
});
@@ -0,0 +1,33 @@
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);
}
@@ -0,0 +1,58 @@
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",
},
});
}
@@ -0,0 +1,18 @@
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 });
}
@@ -0,0 +1,10 @@
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");
}
@@ -0,0 +1,10 @@
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");
}
@@ -0,0 +1,10 @@
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"] });
}
@@ -0,0 +1,10 @@
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");
}
@@ -0,0 +1,5 @@
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 });
@@ -0,0 +1,9 @@
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 });
@@ -0,0 +1,5 @@
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"] });
@@ -0,0 +1,69 @@
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 });
}
@@ -0,0 +1,5 @@
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"] });
@@ -0,0 +1,106 @@
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);
});
});
@@ -0,0 +1,109 @@
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);
});
});
@@ -0,0 +1,184 @@
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"]);
});
});
@@ -0,0 +1,5 @@
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 });
@@ -0,0 +1,5 @@
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");
@@ -0,0 +1,59 @@
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);
});
});
@@ -0,0 +1,20 @@
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);
}
@@ -0,0 +1,72 @@
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();
});
});
@@ -0,0 +1,29 @@
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);
}
@@ -0,0 +1,77 @@
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();
});
});
@@ -0,0 +1,32 @@
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);
}
@@ -0,0 +1,35 @@
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();
});
});
@@ -0,0 +1,20 @@
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);
}
@@ -0,0 +1,20 @@
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);
}
@@ -0,0 +1,90 @@
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();
});
});
@@ -0,0 +1,36 @@
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 { AdminMember, AdminMemberUpdatePayload } from "@/app/lib/types";
// GET -> /api/admin/members/{memberCode} (detail, side-effect-free).
// PUT -> /api/admin/members/{memberCode} (profile edit). Mutations live on PUT
// only; the actor is derived from the bb_admin JWT server-side (mobile-api),
// never from the request body. Genuine upstream 4xx (400 validation, 404
// missing) passes through.
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<AdminMember>(`/api/admin/members/${encodeURIComponent(memberCode)}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function PUT(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 Partial<AdminMemberUpdatePayload>;
const result = await callMobileApi<{ success: boolean }>(`/api/admin/members/${encodeURIComponent(memberCode)}`, {
method: "PUT",
body,
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,35 @@
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/status-history") as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/members/[memberCode]/status-history", () => {
it("forwards the member code and admin JWT", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
const res = await GET(getReq(), { params: Promise.resolve({ memberCode: "BB0100" }) });
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/status-history", {
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();
});
});
@@ -0,0 +1,20 @@
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 { AdminStatusHistoryPage } from "@/app/lib/types";
// GET -> /api/admin/members/{memberCode}/status-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<AdminStatusHistoryPage>(
`/api/admin/members/${encodeURIComponent(memberCode)}/status-history`,
{ token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,112 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, POST } from "./route";
function getReq(qs = "") {
return new Request(`http://localhost/api/admin/members${qs}`) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/members", () => {
it("forwards the admin JWT and query string to GET /api/admin/members", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({
ok: true,
data: { content: [], number: 0, size: 10, totalElements: 0, totalPages: 0 },
});
const res = await GET(getReq("?status=Y&page=1&size=10&name=AINA"));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members?status=Y&page=1&size=10&name=AINA", {
token: "jwt-abc",
});
});
it("forwards with no query string when there are no filters", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
await GET(getReq());
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members", { 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();
});
it("passes through a genuine upstream 4xx status (e.g. 400 validation)", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "bad filter", status: 400 });
const res = await GET(getReq("?status=Z"));
expect(res.status).toBe(400);
});
});
// babyboo-42: admin "Register member".
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/members", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
const registration = {
name: "Jane",
nickname: "Janey",
email: "jane@example.com",
dob: "2000-01-01",
phoneNoPrefix: "60",
phoneNo: "123456789",
referralCode: "MY9999999",
};
describe("POST /api/admin/members", () => {
it("forwards only the registration fields with the admin JWT", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { memberCode: "MY1234567", emailSent: true } });
const res = await POST(postReq({ ...registration, password: "x", doneBy: "someone-else" }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ memberCode: "MY1234567", emailSent: true });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members", {
method: "POST",
body: registration,
token: "jwt-abc",
});
});
it("passes an upstream 400 or 403 through", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "This phone no already registered. ", status: 400 });
expect((await POST(postReq(registration))).status).toBe(400);
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Forbidden", status: 403 });
expect((await POST(postReq(registration))).status).toBe(403);
});
it("returns 401 without a session and forwards nothing", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await POST(postReq(registration))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
// portal-query-allowlist (F38)
describe("GET /api/admin/members query allow-list", () => {
it("drops a param mobile-api does not accept and an injected page", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
await GET(getReq("?name=AINA&page=1%26status%3DN&actor=root"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members?name=AINA", { token: "jwt-abc" });
});
});
@@ -0,0 +1,63 @@
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 { AdminMemberPage } from "@/app/lib/types";
// GET -> /api/admin/members*. Forwards the bb_admin JWT from the session cookie
// and the full query string (filters + paging) to mobile-api. Read-only — no
// side effect on GET (Next.js prefetch-safe).
const QUERY = {
memberCode: TEXT,
name: TEXT,
email: TEXT,
phoneNo: TEXT,
status: TEXT,
joinDateFrom: TEXT,
joinDateTo: TEXT,
gender: TEXT,
bank: TEXT,
sponsorId: TEXT,
q: TEXT,
rank: TEXT,
nickname: TEXT,
sponsor: TEXT,
referrer: 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<AdminMemberPage>(`/api/admin/members${qs}`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
// POST -> admin "Register member" (babyboo-42). Only the registration fields are forwarded, as
// strings — never an actor or a password; the actor comes from the JWT upstream (mobile-api), and a
// caller without BO_MEMBERS is refused there with 403, which passes through.
const REGISTRATION_FIELDS = ["name", "nickname", "email", "dob", "phoneNoPrefix", "phoneNo", "referralCode"] as const;
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const raw = (await req.json().catch(() => ({}))) as Record<string, unknown>;
const body = Object.fromEntries(
REGISTRATION_FIELDS.map(key => [key, typeof raw[key] === "string" ? raw[key] : ""]),
);
const result = await callMobileApi<{ memberCode: string; emailSent: boolean }>("/api/admin/members", {
method: "POST",
body,
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,50 @@
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";
const get = (qs: string, memberCode = "BB0100") =>
GET(new Request(`http://localhost/api/admin/network/x${qs}`) as unknown as Parameters<typeof GET>[0], {
params: Promise.resolve({ memberCode }),
});
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { mbid: "BB0100" } });
});
// portal-query-allowlist (F38)
describe("GET /api/admin/network/{memberCode}", () => {
it("defaults level to 99 (the whole tree)", async () => {
await get("");
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/network/BB0100?level=99", { token: "jwt-abc" });
});
it("forwards a valid level", async () => {
await get("?level=3");
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/network/BB0100?level=3", { token: "jwt-abc" });
});
it("cannot inject through level, and clamps it to 99", async () => {
await get("?level=1%26memberCode%3DX");
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/network/BB0100?level=99", { token: "jwt-abc" });
await get("?level=5000");
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/network/BB0100?level=99", { token: "jwt-abc" });
});
it("encodes the member code path segment", async () => {
await get("", "BB01/../x?y=1");
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/network/BB01%2F..%2Fx%3Fy%3D1?level=99", { token: "jwt-abc" });
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await get("")).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,27 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { upstreamQuery } from "@/app/lib/server/upstreamQuery";
import type { AdminTreeNode } from "@/app/lib/types";
// GET -> /api/admin/network/{memberCode} (tree from the chosen root, read-only).
const QUERY = {
level: { type: "int", min: 1, max: 99 },
} as const;
export async function GET(req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { memberCode } = await ctx.params;
// portal-query-allowlist (F38): level is an int in [1, 99] (99, the whole tree, when absent or invalid, as the
// portal's own caller sends); the member code is a path segment, so it is encoded.
const qs = upstreamQuery(new URL(req.url).searchParams, QUERY) || "?level=99";
const result = await callMobileApi<AdminTreeNode>(`/api/admin/network/${encodeURIComponent(memberCode)}${qs}`, {
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,17 @@
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 { AdminTreeNode } from "@/app/lib/types";
// GET -> /api/admin/network/{memberCode}/upline (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<AdminTreeNode[]>(`/api/admin/network/${encodeURIComponent(memberCode)}/upline`, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -0,0 +1,60 @@
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/reports/rewards${search}`) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/reports/rewards", () => {
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("?rewardCode=SELF_ACORN&page=0&size=10&evil=1"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: 1 });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/reports/rewards?page=0&size=10&rewardCode=SELF_ACORN", { 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);
});
});
// BABYBOO-54 B2: the Rewards tab sorts server-side; sortBy/sortDir must reach mobile-api.
describe("GET /api/admin/reports/rewards sort forwarding", () => {
it("forwards sortBy and sortDir", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} });
await GET(getReq("?page=0&size=10&sortBy=amount&sortDir=desc&evil=1"));
const [url] = mocks.callMobileApi.mock.calls.at(-1)!;
const sp = new URLSearchParams(String(url).split("?")[1]);
expect([sp.get("sortBy"), sp.get("sortDir"), sp.get("page"), sp.get("evil")]).toEqual(["amount", "desc", "0", null]);
});
});
@@ -0,0 +1,5 @@
import type { NextRequest } from "next/server";
import { forwardAdminGet } from "@/app/lib/server/forwardGet";
// GET -> mobile-api GET /api/admin/reports/rewards (BO_REPORTS). Read-only; module-gated upstream.
export const GET = (req: NextRequest) => forwardAdminGet(req, "/api/admin/reports/rewards", ["page", "size", "from", "to", "rewardCode", "sortBy", "sortDir"]);
@@ -0,0 +1,21 @@
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/reports/sales-items country", () => {
it("forwards country to mobile-api", async () => {
await GET(new Request("http://localhost/api/admin/reports/sales-items?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");
});
});
Loaded 100 of 2944 files, more files were not shown because too many files have changed in this diff. Show more