chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
e396568cc3
commit
5ee51d1913
2918 files changed
+302373
-3
No files matched your search
@@ -5,6 +5,7 @@
|
|||||||
# Local env and secrets
|
# Local env and secrets
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
|
!.env.example
|
||||||
*.key
|
*.key
|
||||||
*service-account*.json
|
*service-account*.json
|
||||||
|
|
||||||
@@ -14,3 +15,6 @@
|
|||||||
|
|
||||||
# Playwright
|
# Playwright
|
||||||
.playwright-mcp/
|
.playwright-mcp/
|
||||||
|
|
||||||
|
# Build output
|
||||||
|
target/
|
||||||
@@ -4,9 +4,9 @@ Run serially: every group touches build files or shared config.
|
|||||||
|
|
||||||
## 1. Copy modules into the repo
|
## 1. Copy modules into the repo
|
||||||
|
|
||||||
- [ ] 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.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.
|
||||||
- [ ] 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.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.
|
||||||
- [ ] 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.
|
- [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
|
## 2. Single build
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -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?
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
24
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"semi": false,
|
||||||
|
"singleQuote": true,
|
||||||
|
"arrowParens": "avoid",
|
||||||
|
"printWidth": 100,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
@@ -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"]
|
||||||
@@ -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.
|
||||||
|
|
||||||
+60
@@ -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 });
|
||||||
|
});
|
||||||
|
});
|
||||||
+26
@@ -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 });
|
||||||
|
}
|
||||||
+59
@@ -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 });
|
||||||
|
});
|
||||||
|
});
|
||||||
+25
@@ -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);
|
||||||
|
}
|
||||||
+58
@@ -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");
|
||||||
|
}
|
||||||
+10
@@ -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"] });
|
||||||
|
}
|
||||||
+10
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
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/sales-items${search}`) as unknown as Parameters<typeof GET>[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /api/admin/reports/sales-items", () => {
|
||||||
|
it("forwards sortBy and sortDir with the other documented params, dropping unknown ones", async () => {
|
||||||
|
const res = await GET(getReq("?page=1&size=10&from=2026-09-01&to=2026-09-29&supplierId=3&sortBy=qty&sortDir=desc&evil=1"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const url = new URL(`http://x${mocks.callMobileApi.mock.calls[0][0]}`);
|
||||||
|
expect(url.pathname).toBe("/api/admin/reports/sales-items");
|
||||||
|
expect(Object.fromEntries(url.searchParams)).toEqual({
|
||||||
|
page: "1", size: "10", from: "2026-09-01", to: "2026-09-29", supplierId: "3", sortBy: "qty", sortDir: "desc",
|
||||||
|
});
|
||||||
|
expect(mocks.callMobileApi.mock.calls[0][1]).toEqual({ token: "jwt-abc" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends no sort params when none given", async () => {
|
||||||
|
await GET(getReq("?page=0&size=10"));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/reports/sales-items?page=0&size=10", { token: "jwt-abc" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import type { NextRequest } from "next/server";
|
||||||
|
import { forwardAdminGet } from "@/app/lib/server/forwardGet";
|
||||||
|
|
||||||
|
// GET -> mobile-api GET /api/admin/reports/sales-items (BO_REPORTS; add-sku-supplier). Read-only; module-gated upstream.
|
||||||
|
export const GET = (req: NextRequest) =>
|
||||||
|
forwardAdminGet(req, "/api/admin/reports/sales-items", ["page", "size", "from", "to", "supplierId", "country", "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 country", () => {
|
||||||
|
it("forwards country to mobile-api", async () => {
|
||||||
|
await GET(new Request("http://localhost/api/admin/reports/sales?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/reports/sales${search}`) as unknown as Parameters<typeof GET>[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /api/admin/reports/sales", () => {
|
||||||
|
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&page=1&size=10&evil=1"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({ ok: 1 });
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/reports/sales?page=1&size=10&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/reports/sales (BO_REPORTS). Read-only; module-gated upstream.
|
||||||
|
export const GET = (req: NextRequest) => forwardAdminGet(req, "/api/admin/reports/sales", ["page", "size", "from", "to", "sortBy", "sortDir", "country"]);
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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/topup/list${search}`) as unknown as Parameters<typeof GET>[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /api/admin/topup/list", () => {
|
||||||
|
it("forwards page/size params and the admin JWT", 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("?page=1&size=10"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||||
|
"/api/admin/topup/list?page=1&size=10",
|
||||||
|
{ 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("propagates an upstream refusal (no BO_WALLET) as a 403 error response", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "The Wallet module (BO_WALLET) is required.", status: 403 });
|
||||||
|
const res = await GET(getReq());
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(res.headers.get("content-type")).toContain("application/json");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// portal-query-allowlist (F38)
|
||||||
|
describe("GET /api/admin/topup/list query allow-list", () => {
|
||||||
|
it("cannot inject through page and clamps size", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
|
||||||
|
await GET(getReq("?page=0%26view%3Dcompleted&size=9999"));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/topup/list?size=500", { token: "jwt-abc" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 { paging, SORT, upstreamQuery, type QueryRule } from "@/app/lib/server/upstreamQuery";
|
||||||
|
import type { AdminTopupPage } from "@/app/lib/types";
|
||||||
|
|
||||||
|
// GET -> /api/admin/topup/list?page=&size= (read-only; BO_WALLET gated upstream).
|
||||||
|
|
||||||
|
const QUERY: Record<string, QueryRule> = {
|
||||||
|
...paging(500),
|
||||||
|
view: { type: "enum", values: ["completed"] },
|
||||||
|
...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.
|
||||||
|
// add-topup-reversal: view=completed is the only other view; anything else reads the pending queue.
|
||||||
|
// Absent page/size take mobile-api's defaults (0, 10).
|
||||||
|
const qs = upstreamQuery(new URL(req.url).searchParams, QUERY);
|
||||||
|
const result = await callMobileApi<AdminTopupPage>(
|
||||||
|
`/api/admin/topup/list${qs}`,
|
||||||
|
{ token },
|
||||||
|
);
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
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 getReq = (qs: string) =>
|
||||||
|
new Request(`http://localhost/api/admin/topup/list${qs}`) as unknown as Parameters<typeof GET>[0];
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
|
||||||
|
});
|
||||||
|
|
||||||
|
// add-topup-reversal: the Completed view is the same read with view=completed.
|
||||||
|
describe("GET /api/admin/topup/list view", () => {
|
||||||
|
it("passes view=completed through to mobile-api", async () => {
|
||||||
|
await GET(getReq("?page=1&size=10&view=completed"));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/topup/list?page=1&size=10&view=completed", { token: "jwt-abc" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the pending read unchanged without a view", async () => {
|
||||||
|
await GET(getReq("?page=0&size=10"));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/topup/list?page=0&size=10", { token: "jwt-abc" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops an unknown view", async () => {
|
||||||
|
await GET(getReq("?page=0&size=10&view=all"));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/topup/list?page=0&size=10", { token: "jwt-abc" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// BABYBOO-54 B2: regression guard — the Completed view forwards sortBy/sortDir too.
|
||||||
|
describe("GET /api/admin/topup/list completed sort", () => {
|
||||||
|
it("forwards view=completed with sortBy and sortDir", async () => {
|
||||||
|
await GET(getReq("?page=0&size=10&view=completed&sortBy=refNo&sortDir=desc"));
|
||||||
|
const [url] = mocks.callMobileApi.mock.calls.at(-1)!;
|
||||||
|
const sp = new URLSearchParams(String(url).split("?")[1]);
|
||||||
|
expect([sp.get("view"), sp.get("sortBy"), sp.get("sortDir")]).toEqual(["completed", "refNo", "desc"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { existsSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
|
||||||
|
// add-online-topup-ipay88: the member pays online, so mobile-api no longer approves or rejects a top-up.
|
||||||
|
describe("removed admin top-up routes", () => {
|
||||||
|
it.each(["approve", "reject"])("has no %s route handler", name => {
|
||||||
|
expect(existsSync(join(__dirname, name, "route.ts"))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
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/topup/reverse", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
}) as unknown as Parameters<typeof POST>[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("POST /api/admin/topup/reverse", () => {
|
||||||
|
it("requires a numeric uuid and a reason", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
expect((await POST(postReq({ uuid: "555" }))).status).toBe(400);
|
||||||
|
expect((await POST(postReq({ uuid: "x", reason: "r" }))).status).toBe(400);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards uuid + trimmed reason as a POST to mobile-api with the admin JWT", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "555", status: "R" } });
|
||||||
|
const res = await POST(postReq({ uuid: "555", reason: " Chargeback " }));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/topup/reverse", {
|
||||||
|
method: "POST",
|
||||||
|
body: { uuid: "555", reason: "Chargeback" },
|
||||||
|
token: "jwt-abc",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 401 without a session", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue(null);
|
||||||
|
const res = await POST(postReq({ uuid: "555", reason: "r" }));
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
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 { AdminTopupRow } from "@/app/lib/types";
|
||||||
|
|
||||||
|
// POST -> /api/admin/topup/reverse { uuid, reason } (BO_WALLET 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 { uuid, reason } = (body ?? {}) as { uuid?: unknown; reason?: unknown };
|
||||||
|
// uuid is a Snowflake id carried as a string (it exceeds JS's safe-integer range).
|
||||||
|
if (typeof uuid !== "string" || !/^\d+$/.test(uuid)) {
|
||||||
|
return badRequest("Parameter \"uuid\" is required");
|
||||||
|
}
|
||||||
|
if (typeof reason !== "string" || !reason.trim()) {
|
||||||
|
return badRequest("A reversal reason is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await callMobileApi<AdminTopupRow>("/api/admin/topup/reverse", {
|
||||||
|
method: "POST",
|
||||||
|
body: { uuid, reason: reason.trim() },
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -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() {
|
||||||
|
return new Request(
|
||||||
|
"http://localhost/api/admin/wallet/BB0100/balances",
|
||||||
|
) as unknown as Parameters<typeof GET>[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /api/admin/wallet/[memberCode]/balances", () => {
|
||||||
|
it("forwards the member code and admin JWT", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
data: [{ walletTypeCode: "PRODUCT", balance: 0, enabled: "Y" }],
|
||||||
|
});
|
||||||
|
const res = await GET(getReq(), { params: Promise.resolve({ memberCode: "BB0100" }) });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/wallet/BB0100/balances", {
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("propagates an upstream refusal (no BO_WALLET) as a 403 error response", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "The Wallet module (BO_WALLET) is required.", status: 403 });
|
||||||
|
const res = await GET(getReq(), { params: Promise.resolve({ memberCode: "BB0100" }) });
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(res.headers.get("content-type")).toContain("application/json");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 { AdminWalletBalance } from "@/app/lib/types";
|
||||||
|
|
||||||
|
// GET -> /api/admin/wallet/{memberCode}/balances (read-only; BO_WALLET gated upstream).
|
||||||
|
|
||||||
|
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<AdminWalletBalance[]>(
|
||||||
|
`/api/admin/wallet/${encodeURIComponent(memberCode)}/balances`,
|
||||||
|
{ token },
|
||||||
|
);
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -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(search = "") {
|
||||||
|
return new Request(
|
||||||
|
`http://localhost/api/admin/wallet/BB0100/ledger${search}`,
|
||||||
|
) as unknown as Parameters<typeof GET>[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /api/admin/wallet/[memberCode]/ledger", () => {
|
||||||
|
it("forwards the member code, page params and admin JWT", 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("?page=1&size=10"), { params: Promise.resolve({ memberCode: "BB0100" }) });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||||
|
"/api/admin/wallet/BB0100/ledger?page=1&size=10",
|
||||||
|
{ 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();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("propagates an upstream refusal (no BO_WALLET) as a 403 error response", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "The Wallet module (BO_WALLET) is required.", status: 403 });
|
||||||
|
const res = await GET(getReq(), { params: Promise.resolve({ memberCode: "BB0100" }) });
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(res.headers.get("content-type")).toContain("application/json");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// portal-query-allowlist (F38)
|
||||||
|
describe("GET /api/admin/wallet/{memberCode}/ledger query allow-list", () => {
|
||||||
|
it("encodes the member code and forwards only paging/sort", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
|
||||||
|
await GET(getReq("?page=0&size=10&walletType=X&sortDir=up"), { params: Promise.resolve({ memberCode: "BB01/../x?y" }) });
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/wallet/BB01%2F..%2Fx%3Fy/ledger?page=0&size=10", { token: "jwt-abc" });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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, upstreamQuery } from "@/app/lib/server/upstreamQuery";
|
||||||
|
import type { AdminWalletLedgerPage } from "@/app/lib/types";
|
||||||
|
|
||||||
|
// GET -> /api/admin/wallet/{memberCode}/ledger?page=&size=&sortBy=&sortDir= (read-only; BO_WALLET gated upstream).
|
||||||
|
|
||||||
|
const QUERY = {
|
||||||
|
...paging(500),
|
||||||
|
...SORT,
|
||||||
|
};
|
||||||
|
|
||||||
|
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): only the params mobile-api accepts, validated and encoded.
|
||||||
|
// The member code is a path segment, so it is encoded too.
|
||||||
|
const qs = upstreamQuery(new URL(req.url).searchParams, QUERY);
|
||||||
|
const result = await callMobileApi<AdminWalletLedgerPage>(
|
||||||
|
`/api/admin/wallet/${encodeURIComponent(memberCode)}/ledger${qs}`,
|
||||||
|
{ 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 * as route from "./route";
|
||||||
|
|
||||||
|
const { POST } = route;
|
||||||
|
type Req = Parameters<typeof POST>[0];
|
||||||
|
|
||||||
|
const body = {
|
||||||
|
memberCode: "MY10001",
|
||||||
|
walletCode: "PRODUCT",
|
||||||
|
direction: "IN",
|
||||||
|
amount: 25.5,
|
||||||
|
reason: "Goodwill",
|
||||||
|
refNo: "ref-1",
|
||||||
|
};
|
||||||
|
const req = (b: unknown = body) =>
|
||||||
|
new Request("http://localhost/api/admin/wallet/adjust", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(b),
|
||||||
|
}) as unknown as Req;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("POST /api/admin/wallet/adjust (BABYBOO-54)", () => {
|
||||||
|
it("returns 401 without a session and never calls mobile-api", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue(null);
|
||||||
|
const res = await POST(req());
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards the body and admin JWT to mobile-api by POST and returns the 200 body", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
const ok = { refNo: "ref-1", trxnType: "AJI", amount: 25.5, balance: 125.5 };
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: ok });
|
||||||
|
const res = await POST(req());
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual(ok);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/wallet/adjust", {
|
||||||
|
method: "POST",
|
||||||
|
body,
|
||||||
|
token: "jwt-abc",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes a 409 INSUFFICIENT_BALANCE through with its code", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({
|
||||||
|
ok: false,
|
||||||
|
status: 409,
|
||||||
|
error: "Insufficient balance",
|
||||||
|
code: "INSUFFICIENT_BALANCE",
|
||||||
|
});
|
||||||
|
const res = await POST(req());
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
expect((await res.json()).code).toBe("INSUFFICIENT_BALANCE");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("passes a 400 validation refusal through", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "reason is required" });
|
||||||
|
const res = await POST(req());
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect((await res.json()).error).toBe("reason is required");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("has no GET export (prefetch-safe)", () => {
|
||||||
|
expect((route as Record<string, unknown>).GET).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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 { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||||
|
|
||||||
|
// POST -> /api/admin/wallet/adjust. Mutation: POST only, never GET (Link prefetch is a GET).
|
||||||
|
// BO_WALLET_ADJUST is enforced upstream in mobile-api; doneBy comes from the session there.
|
||||||
|
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 result = await callMobileApi("/api/admin/wallet/adjust", { method: "POST", body, token });
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
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/wallet/ledger${search}`,
|
||||||
|
) as unknown as Parameters<typeof GET>[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyPage = { content: [], number: 0, size: 10, totalElements: 0, totalPages: 0 };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mocks.callMobileApi.mockReset();
|
||||||
|
mocks.getToken.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("GET /api/admin/wallet/ledger", () => {
|
||||||
|
it("forwards the query params and admin JWT", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: emptyPage });
|
||||||
|
const res = await GET(
|
||||||
|
getReq("?page=1&size=10&type=TPU&from=2026-08-01&to=2026-08-31&memberCode=MY10001"),
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||||
|
"/api/admin/wallet/ledger?page=1&size=10&type=TPU&from=2026-08-01&to=2026-08-31&memberCode=MY10001",
|
||||||
|
{ token: "jwt-abc" },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards refNo (BABYBOO-54)", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: emptyPage });
|
||||||
|
await GET(getReq("?page=0&size=10&refNo=3299434405991206912"));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||||
|
"/api/admin/wallet/ledger?page=0&size=10&refNo=3299434405991206912",
|
||||||
|
{ token: "jwt-abc" },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards walletType", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: emptyPage });
|
||||||
|
await GET(getReq("?page=0&size=10&walletType=ACORN"));
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||||
|
"/api/admin/wallet/ledger?page=0&size=10&walletType=ACORN",
|
||||||
|
{ token: "jwt-abc" },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards the Gift card walletType (add-gift-card-wallet)", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: emptyPage });
|
||||||
|
const res = await GET(getReq("?page=0&size=10&walletType=GIFT"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
||||||
|
"/api/admin/wallet/ledger?page=0&size=10&walletType=GIFT",
|
||||||
|
{ token: "jwt-abc" },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards only the documented params (unknown params are dropped)", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({ ok: true, data: emptyPage });
|
||||||
|
const res = await GET(getReq("?page=0&size=10&ownerUuid=424242&evil=1"));
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/wallet/ledger?page=0&size=10", {
|
||||||
|
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("propagates an upstream refusal (no BO_WALLET) as a 403 error response", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
mocks.callMobileApi.mockResolvedValue({
|
||||||
|
ok: false,
|
||||||
|
error: "The Wallet module (BO_WALLET) is required.",
|
||||||
|
status: 403,
|
||||||
|
});
|
||||||
|
const res = await GET(getReq());
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(res.headers.get("content-type")).toContain("application/json");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects an unknown walletType as 400 without calling upstream", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
const res = await GET(getReq("?walletType=GOLD"));
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a non-numeric page param as 400 without calling upstream", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
const res = await GET(getReq("?page=abc"));
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a negative size param as 400 without calling upstream", async () => {
|
||||||
|
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||||
|
const res = await GET(getReq("?size=-5"));
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
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 { AdminWalletLedgerListPage } from "@/app/lib/types";
|
||||||
|
|
||||||
|
// GET -> /api/admin/wallet/ledger?page=&size=&type=&types=&from=&to=&memberCode=&refNo=&sortBy=&sortDir=
|
||||||
|
// Read-only, BO_WALLET-gated upstream in mobile-api. Only the documented params are forwarded
|
||||||
|
// (an ownerUuid is never accepted from the client — a memberCode filter resolves to it
|
||||||
|
// server-side). `types` is a comma-separated WalletTrxnType set for a category filter (in + out)
|
||||||
|
// and supersedes the single-value `type` upstream. Paging params are validated here so a malformed
|
||||||
|
// page/size fails as a 400, not as a confusing upstream error.
|
||||||
|
|
||||||
|
const FORWARDED_PARAMS = new Set(["page", "size", "type", "types", "from", "to", "memberCode", "walletType", "refNo", "sortBy", "sortDir"]);
|
||||||
|
const NUMERIC_PARAMS = new Set(["page", "size"]);
|
||||||
|
const WALLET_TYPES = new Set(["PRODUCT", "ACORN", "APPLE", "GIFT"]);
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const token = await getToken();
|
||||||
|
if (!token) return unauthorized();
|
||||||
|
|
||||||
|
const search = new URL(req.url).searchParams;
|
||||||
|
const forwarded = new URLSearchParams();
|
||||||
|
for (const key of FORWARDED_PARAMS) {
|
||||||
|
const value = search.get(key);
|
||||||
|
if (value === null) continue;
|
||||||
|
if (NUMERIC_PARAMS.has(key) && !/^\d+$/.test(value)) {
|
||||||
|
return badRequest(`Invalid ${key} parameter.`);
|
||||||
|
}
|
||||||
|
if (key === "walletType" && !WALLET_TYPES.has(value)) {
|
||||||
|
return badRequest(`Invalid ${key} parameter.`);
|
||||||
|
}
|
||||||
|
forwarded.set(key, value);
|
||||||
|
}
|
||||||
|
const qs = forwarded.toString();
|
||||||
|
const result = await callMobileApi<AdminWalletLedgerListPage>(
|
||||||
|
`/api/admin/wallet/ledger${qs ? `?${qs}` : ""}`,
|
||||||
|
{ token },
|
||||||
|
);
|
||||||
|
if (!result.ok) return errorResponse(result);
|
||||||
|
return NextResponse.json(result.data);
|
||||||
|
}
|
||||||
Loaded 100 of 2918 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user