feat(admin-portal): cut babyboo portal down to Co-Lite login, users and roles

Removes every other screen, API route, component, test and the dependencies only
they used. Cookie colite_admin, Co-Lite branding, BO_USERS/BO_ROLES modules only.
The user form no longer loads branches, events or country scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-26 21:24:30 +08:00
1 parent a8cdf33a24
commit 1071ddaa2a
1304 files changed
+216 -162492

No files matched your search

@@ -31,7 +31,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t
## 6. Admin portal
- [ ] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0.
- [x] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0.
- Scope: `solvway-admin-portal/**`
- [ ] 6.2 Add the `/forgot-password` page (public, linked from login) and its route handler calling `/api/admin/auth/forgot-password`, showing the fixed message for any outcome; make the users form refuse self-deactivation and show duplicate-username and lock-out errors from the API. Tests first (vitest) for each portal-visible scenario in the specs. Verify: `npm run lint && npm run build && npm test` exit 0.
- Scope: `solvway-admin-portal/**`
@@ -1,6 +1,6 @@
---
name: run-solvway-admin-portal
description: Build, run, and drive solvway-admin-portal (babyboo Back Office). Use when asked to start the app, run its dev server or tests, or take a screenshot of / interact with the running UI.
description: Build, run, and drive solvway-admin-portal (Co-Lite Back Office). Use when asked to start the app, run its dev server or tests, or take a screenshot of / interact with the running UI.
---
All paths below are relative to `solvway-admin-portal/`.
+2 -2
View File
@@ -1,5 +1,5 @@
# ── Mobile API (BFF target) ───────────────────────────────────────────
# Base URL of babyboo's solvway-mobile-api, no trailing slash.
# Base URL of solvway-mobile-api, no trailing slash.
# Supplied per environment; there is no sensible default.
MOBILE_API_BASE_URL=
@@ -10,4 +10,4 @@ MOBILE_API_KEY=
# ── Session ───────────────────────────────────────────────────────────
# Name of the httpOnly cookie that stores the admin JWT.
SESSION_COOKIE_NAME=bb_admin
SESSION_COOKIE_NAME=colite_admin
-1
View File
@@ -5,7 +5,6 @@ FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
COPY vendor/ ./vendor/
RUN npm ci
# A High or Critical advisory in a runtime dependency fails the image (F45). Dev tooling is not shipped,
# so it is excluded. Moderate advisories do not block; review them with a full `npm audit`.
+17 -197
View File
@@ -1,206 +1,26 @@
# Back-Office Template — babyboo.my
# Co-Lite Admin Portal
> **Migration in progress.** This module is being converted from a Vite SPA to a Next.js App
> Router project (see `openspec/changes/add-admin-portal-auth`). `app/` currently holds only a
> placeholder shell; the real pages, components and services below still live under `src/` —
> specifically `src/legacy-pages/` (renamed from `src/pages/` because Next.js reserves that name
> for its own Pages Router) — pending a later change that ports them into `app/*/page.tsx` with
> `react-router` calls rewired to `next/navigation`. Everything in this README describing routes,
> the mock-data architecture and theming still describes that `src/` tree.
Next.js 16 admin portal for Co-Lite. Screens call the JSON admin APIs (`/api/admin/**`) in `mobile-api` through server-side route handlers.
A reusable admin/back-office front end for MLM (multi-level marketing) clients. It ships
against mock data behind an API-shaped service layer, so a client project can swap in a real
backend without touching any page or component code.
## Run
**Currently skinned for babyboo.my** — baby & maternity retail, competing with Medela, Momcozy,
Kinderkraft and Hamilton. The audience is sleep-deprived, time-poor, highly selective parents, so
decisions are ranked clarity → speed → trust. The look is deliberately warm and soft-edged rather
than clinical: cream page, warm neutrals, brand brown `#6E3E17` with a gold `#F2BC57` accent, and a
1rem radius so nothing has a sharp corner.
## Stack
- [Next.js 16](https://nextjs.org/) (App Router, `output: "standalone"`) — build tool and server
- [React 19](https://react.dev/) + TypeScript (strict mode)
- [Tailwind CSS 3](https://tailwindcss.com/) via PostCSS + `tailwind.config.ts` — matches
`solvway-customer-portal`'s wiring
- [Sass](https://sass-lang.com/) — token maps and mixins in `src/styles/` (pending port into
`app/globals.css`, which currently carries a plain-CSS transliteration of the same tokens)
- [shadcn/ui](https://ui.shadcn.com/) — owned component source, themed with CSS variables
- [Recharts](https://recharts.org/) via shadcn's `chart` wrapper — dashboard charts
- [TanStack Table](https://tanstack.com/table) — data tables
- [lucide-react](https://lucide.dev/) — icons
- [react-router-dom v7](https://reactrouter.com/) — still a dependency for the not-yet-ported
`src/legacy-pages/` tree; removed once that tree is rewired to `next/navigation`
- [Vitest](https://vitest.dev/) + [React Testing Library](https://testing-library.com/react) — tests
## Getting Started
Needs Node 24 (see `.nvmrc`).
```bash
npm install
npm run dev # next dev --port 3001
npm test # run the full test suite (Vitest, run once)
npm run test:watch # run tests in watch mode
npm run build # next build (type-checks + production build)
npm start # next start --port 3001, after a build
python3 scripts/check-contrast.py # verify token contrast in both themes
cp .env.example .env.local # then fill in the values below
npm ci
npm run dev # http://localhost:3001
```
### Auth
| Variable | Purpose |
| --- | --- |
| `MOBILE_API_BASE_URL` | Base URL of `mobile-api` |
| `MOBILE_API_KEY` | API key sent to `mobile-api` |
| `SESSION_SECRET` | Secret used to seal the session cookie |
| `SESSION_COOKIE_NAME` | Session cookie base name (default `colite_admin`) |
Login is no longer mocked. `/login` posts to the same-origin `/api/auth/login` route handler,
which proxies `solvway-mobile-api` (`app/lib/server/mobileApi.ts`) and sets an httpOnly session
cookie server-side. Signing in requires:
- `MOBILE_API_BASE_URL` and `MOBILE_API_KEY` set (see `.env.example`), pointing at a reachable
`solvway-mobile-api` instance.
- A real `UserType.A` account in that instance's services-system.
Without a configured Mobile API, `/login` still renders, but submitting the form reports "Mobile
API is not configured" — there is no local/offline demo login anymore.
Visiting any other route while unauthenticated redirects back to `/login`; logging out clears the
session and returns you there as well.
## Screen Inventory
| Route | Page | Notes |
|---|---|---|
| `/login` | Login | Email/password with a password-reveal toggle; inline error on invalid credentials |
| `/` | Dashboard | Live KPI tiles (members, settled revenue/orders, rewards; Malaysia-time month), 12-month revenue and member-growth charts, revenue by channel, rank/status mix, rewards by type, top-earner leaderboard |
| `/members` | Members | Sortable, faceted, URL-synced member table with column visibility and CSV export |
| `/members/:id` | Member Detail | Identity header, performance strip, tabs for Sales · Commissions · Downline |
| `/reports` | Reports | Live Sales (settled orders) and Rewards tabs, Malaysia-time period presets + date range, paged, period totals, full-result-set CSV export |
| `/network` | Network | Genealogy as an indented tree or a top-down chart, with search that expands ancestors and highlights matches |
Navigation is a **collapsible sidebar with up to three levels**: it collapses to an icon rail on
desktop (persisted per browser) and becomes an overlay drawer below `lg`. Every leaf resolves to a
real view — `Members → By rank → Diamond` applies `?rank=Diamond`, the Reports children select
`?tab=` — so none of them are decorative.
[`src/components/app/nav-config.ts`](src/components/app/nav-config.ts) is the **contract a backend
menu endpoint would return**: plain `label` / `to` / `children` / `isDefault` data, with the icon as
the only client-side concern. `nav-config.test.ts` encodes the invariants such an endpoint must
satisfy (leaf-xor-group, depth cap, real routes, unique targets, one default per group), so a
backend implementation can be validated against the same rules the UI relies on.
## Design Standard
**[`docs/design/DASHBOARD-STANDARD.md`](docs/design/DASHBOARD-STANDARD.md) is authoritative.** It
defines the tokens, layout grid, KPI and chart specs, required data states, accessibility floor
(WCAG 2.1 AA) and the anti-patterns. Read it before adding a screen. Where it and a component
disagree, the component is wrong.
## Mock-Data Architecture
Everything under `src/services/*` is written to look and behave like a real API client: every
function is `async`, returns plain data (no framework types leak out), and pagination, filtering
and **sorting** happen the same way a backend would do them. The Dashboard and Reports are live
(`app/lib/services/adminDashboard.ts` -> BFF -> mobile-api aggregate reads); `src/services/api.ts` holds shared helpers (pagination, sorting, an
artificial network delay).
**Pages only call functions from the other
`src/services/*` modules. This is the intended swap point: to connect a real backend, replace the
bodies of these service functions with `fetch` calls that return the same shapes (see
`src/types/index.ts`), and no page or component needs to change.
```
src/
components/
app/ # two-level sidebar + nav config
ui/ # shadcn primitives + DataTable, states, chart skeletons
dashboard/ # KPI tile, chart card (chart + its accessible table)
genealogy/ # tree view and org chart
styles/
_variables.scss # $palettes (light + dark), breakpoints, layout, z-index
_mixins.scss # respond-to, focus-ring, tap-target, brand gradient
index.scss # emits the token blocks from the maps + base layer
tailwind.css # Tailwind entry + @theme (kept as CSS on purpose)
lib/
theme.tsx # light/dark provider, persists to localStorage
utils.ts # cn()
services/
api.ts # shared mock helpers (pagination, sorting, delay)
period.ts # month labels
auth.ts # login/logout/session — swap point
members.ts # list/detail/facets/stats — swap point
network.ts # genealogy tree — swap point
```
## Theming
Colour lives in Sass maps in [`src/styles/_variables.scss`](src/styles/_variables.scss), emitted as
CSS custom properties by `index.scss` and exposed to Tailwind via `@theme inline` in `tailwind.css`.
**No component contains a colour literal.**
The babyboo palette is brand brown `#6E3E17` with a gold `#F2BC57` accent on a cream page, plus warm
neutrals and a warm-espresso dark mode (not slate).
**One thing to know about the gold:** `#F2BC57` is 1.73:1 against white, so it can only ever be a
*filled surface* carrying `--accent-foreground` text — never text, a thin indicator, or a chart
series, all of which would be invisible in light mode. Anything in the accent family that must carry
meaning uses `--accent-strong` (`#9A6212`, 5.08:1). That is why the accent is absent from the chart
ramp.
Both themes live in the same map, so a token cannot be added to light and forgotten in dark.
To re-skin for a client:
1. Edit `$palettes` in `src/styles/_variables.scss` — primary, accent, chart ramp, radius.
2. Swap the font `<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.
## Scripts
- `npm run build` / `npm start` production build and server (port 3001)
- `npm run lint`
- `npm test`
@@ -1,60 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function postReq() {
return new Request("http://localhost/api/admin/company-accounts/MY/MYHQ00002/deactivate", {
method: "POST",
}) as unknown as Parameters<typeof POST>[0];
}
function ctx(prefix: string, memberCode: string) {
return { params: Promise.resolve({ prefix, memberCode }) };
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/company-accounts/[prefix]/[memberCode]/deactivate", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq(), ctx("MY", "MYHQ00002"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards to POST /api/admin/company-accounts/{prefix}/{memberCode}/deactivate", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { prefix: "MY", memberCode: "MYHQ00002", active: "N" } });
const res = await POST(postReq(), ctx("MY", "MYHQ00002"));
expect(mocks.callMobileApi).toHaveBeenCalledWith(
"/api/admin/company-accounts/MY/MYHQ00002/deactivate",
{ method: "POST", token: "jwt-abc" },
);
expect(res.status).toBe(200);
});
it("maps an upstream failure to an error response", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "not found", status: 404 });
const res = await POST(postReq(), ctx("MY", "MYHQ00002"));
expect(res.status).toBe(404);
});
// deactivate returns an empty 200 downstream (void controller). NextResponse.json(undefined)
// would 500 — the route must return a safe ok body. (Caught in live Part D verification.)
it("returns 200 ok when the downstream body is empty", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true });
const res = await POST(postReq(), ctx("MY", "MYHQ00002"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true });
});
});
@@ -1,26 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// POST -> /api/admin/company-accounts/{prefix}/{memberCode}/deactivate
// (add-admin-company-account-crud, Part C). Drops the account from the weighted split; the
// member, its network_tree row and any existing downline are left untouched — there is no hard
// delete. A mutation, so always POST, never a GET.
export async function POST(
_req: NextRequest,
ctx: { params: Promise<{ prefix: string; memberCode: string }> },
) {
const token = await getToken();
if (!token) return unauthorized();
const { prefix, memberCode } = await ctx.params;
const result = await callMobileApi(
`/api/admin/company-accounts/${encodeURIComponent(prefix)}/${encodeURIComponent(memberCode)}/deactivate`,
{ method: "POST", token },
);
if (!result.ok) return errorResponse(result);
// deactivate returns an empty 200 downstream (void); avoid NextResponse.json(undefined) (500).
return NextResponse.json(result.data ?? { ok: true });
}
@@ -1,59 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function postReq() {
return new Request("http://localhost/api/admin/company-accounts/MY/MYHQ00002/reactivate", {
method: "POST",
}) as unknown as Parameters<typeof POST>[0];
}
function ctx(prefix: string, memberCode: string) {
return { params: Promise.resolve({ prefix, memberCode }) };
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/company-accounts/[prefix]/[memberCode]/reactivate", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq(), ctx("MY", "MYHQ00002"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards to POST /api/admin/company-accounts/{prefix}/{memberCode}/reactivate", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { prefix: "MY", memberCode: "MYHQ00002", active: "Y" } });
const res = await POST(postReq(), ctx("MY", "MYHQ00002"));
expect(mocks.callMobileApi).toHaveBeenCalledWith(
"/api/admin/company-accounts/MY/MYHQ00002/reactivate",
{ method: "POST", token: "jwt-abc" },
);
expect(res.status).toBe(200);
});
it("maps an upstream failure to an error response", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "not found", status: 404 });
const res = await POST(postReq(), ctx("MY", "MYHQ00002"));
expect(res.status).toBe(404);
});
// reactivate returns an empty 200 downstream (void controller); the route must not 500 on it.
it("returns 200 ok when the downstream body is empty", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true });
const res = await POST(postReq(), ctx("MY", "MYHQ00002"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true });
});
});
@@ -1,25 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// POST -> /api/admin/company-accounts/{prefix}/{memberCode}/reactivate
// (add-admin-company-account-crud, Part C). Restores the account to the weighted split. A
// mutation, so always POST, never a GET.
export async function POST(
_req: NextRequest,
ctx: { params: Promise<{ prefix: string; memberCode: string }> },
) {
const token = await getToken();
if (!token) return unauthorized();
const { prefix, memberCode } = await ctx.params;
const result = await callMobileApi(
`/api/admin/company-accounts/${encodeURIComponent(prefix)}/${encodeURIComponent(memberCode)}/reactivate`,
{ method: "POST", token },
);
if (!result.ok) return errorResponse(result);
// reactivate returns an empty 200 downstream (void); avoid NextResponse.json(undefined) (500).
return NextResponse.json(result.data ?? { ok: true });
}
@@ -1,63 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq() {
return new Request("http://localhost/api/admin/company-accounts/MY") as unknown as Parameters<
typeof GET
>[0];
}
function ctx(prefix: string) {
return { params: Promise.resolve({ prefix }) };
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/company-accounts/[prefix]", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq(), ctx("MY"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the admin JWT to GET /api/admin/company-accounts/{prefix} and returns the rows", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const rows = [
{
prefix: "MY",
memberCode: "MYHQ00002",
name: "HQ Two",
weight: 50,
active: "Y",
configVersion: 3,
directDownline: 2,
allocatedCount: 10,
},
];
mocks.callMobileApi.mockResolvedValue({ ok: true, data: rows });
const res = await GET(getReq(), ctx("MY"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts/MY", {
token: "jwt-abc",
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual(rows);
});
it("maps an upstream failure to an error response", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "boom", status: 400 });
const res = await GET(getReq(), ctx("MY"));
expect(res.status).toBe(400);
expect((await res.json()).error).toBe("boom");
});
});
@@ -1,22 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { CompanyAccountRow } from "@/app/lib/types";
// GET -> /api/admin/company-accounts/{prefix} (add-admin-company-account-crud, Part C): the
// company accounts configured for one registration country. Read-only — no side effect on GET
// (Next.js prefetch-safe).
export async function GET(_req: NextRequest, ctx: { params: Promise<{ prefix: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { prefix } = await ctx.params;
const result = await callMobileApi<CompanyAccountRow[]>(
`/api/admin/company-accounts/${encodeURIComponent(prefix)}`,
{ token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,138 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST, PUT } from "./route";
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/company-accounts", {
method: "POST",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
function putReq(body: unknown) {
return new Request("http://localhost/api/admin/company-accounts", {
method: "PUT",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof PUT>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/company-accounts", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq({ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("requires prefix, memberCode, name and a weight", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
for (const body of [
{ memberCode: "MYHQ00002", name: "HQ Two", weight: 50 },
{ prefix: "MY", name: "HQ Two", weight: 50 },
{ prefix: "MY", memberCode: "MYHQ00002", weight: 50 },
{ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two" },
{},
]) {
const res = await POST(postReq(body));
expect(res.status).toBe(400);
}
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects an email without a password (and vice versa) without forwarding", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const base = { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 };
const res1 = await POST(postReq({ ...base, email: "hq2@babyboo.my" }));
expect(res1.status).toBe(400);
const res2 = await POST(postReq({ ...base, password: "Qweqwe123" }));
expect(res2.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the admin JWT and full body to POST /api/admin/company-accounts", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const body = { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 };
mocks.callMobileApi.mockResolvedValue({
ok: true,
data: { memberId: "1", loginRequested: false, credentialCreated: false },
});
const res = await POST(postReq(body));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts", {
method: "POST",
body,
token: "jwt-abc",
});
expect(res.status).toBe(200);
expect((await res.json()).loginRequested).toBe(false);
});
it("forwards a duplicate-code 4xx as-is with the downstream message", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({
ok: false,
error: "member_code already in use",
status: 409,
});
const res = await POST(
postReq({ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }),
);
expect(res.status).toBe(409);
expect((await res.json()).error).toBe("member_code already in use");
});
});
describe("PUT /api/admin/company-accounts", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await PUT(putReq({ prefix: "MY", memberCode: "MYHQ00002", weight: 75 }));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("requires prefix and memberCode to locate the row", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
for (const body of [{ memberCode: "MYHQ00002", weight: 75 }, { prefix: "MY", weight: 75 }, {}]) {
const res = await PUT(putReq(body));
expect(res.status).toBe(400);
}
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the admin JWT and full body to PUT /api/admin/company-accounts", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const body = { prefix: "MY", memberCode: "MYHQ00002", weight: 75, active: "Y" };
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ...body, name: "HQ Two", configVersion: 4 } });
const res = await PUT(putReq(body));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts", {
method: "PUT",
body,
token: "jwt-abc",
});
expect(res.status).toBe(200);
});
// update returns an empty 200 downstream (void controller). NextResponse.json(undefined) would
// 500 — the route must return a safe ok body. (Caught in live Part D verification.)
it("returns 200 ok when the downstream body is empty", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true });
const res = await PUT(putReq({ prefix: "MY", memberCode: "MYHQ00002", weight: 5 }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: true });
});
});
@@ -1,55 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { CompanyAccountCreatePayload, CompanyAccountUpdatePayload } from "@/app/lib/types";
// POST/PUT -> /api/admin/company-accounts (add-admin-company-account-crud, Part C). Both are
// mutations and never go out on GET (Next.js prefetch rule). Create writes the member + tree
// placement + allocation config (+ optional login) as one action; edit changes weight/active/
// name only — memberCode/prefix locate the row and are never themselves edited.
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const body = await req.json().catch(() => ({}));
const { prefix, memberCode, name, weight, email, password } = body as Partial<CompanyAccountCreatePayload>;
if (!prefix || !memberCode || !name || typeof weight !== "number") {
return badRequest("prefix, memberCode, name and weight are required.");
}
// The optional login travels as a pair (the anchor pattern) — one without the other is a
// malformed request, never forwarded upstream.
if (Boolean(email) !== Boolean(password)) {
return badRequest("email and password must be supplied together, or neither.");
}
const result = await callMobileApi("/api/admin/company-accounts", {
method: "POST",
body,
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export async function PUT(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const body = await req.json().catch(() => ({}));
const { prefix, memberCode } = body as Partial<CompanyAccountUpdatePayload>;
if (!prefix || !memberCode) {
return badRequest("prefix and memberCode are required to locate the account.");
}
const result = await callMobileApi("/api/admin/company-accounts", {
method: "PUT",
body,
token,
});
if (!result.ok) return errorResponse(result);
// update returns an empty 200 downstream (void); NextResponse.json(undefined) would 500, so
// fall back to a small ok body.
return NextResponse.json(result.data ?? { ok: true });
}
@@ -1,48 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(search = "") {
return new Request(`http://localhost/api/admin/dashboard/event${search}`) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/dashboard/event", () => {
it("forwards only the event id and the admin JWT (never an operator)", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { pendingOrders: 1 } });
const res = await GET(getReq("?eventId=7&operator=Ben"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ pendingOrders: 1 });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/event?eventId=7", { token: "jwt-abc" });
});
it("is 401 without a session and never calls mobile-api", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq("?eventId=7"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("is 400 for a missing or non-numeric event id", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
expect((await GET(getReq())).status).toBe(400);
expect((await GET(getReq("?eventId=7;drop"))).status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes a downstream 403 through", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_DASHBOARD_EVENT module is required." });
const res = await GET(getReq("?eventId=7"));
expect(res.status).toBe(403);
});
});
@@ -1,11 +0,0 @@
import type { NextRequest } from "next/server";
import { forwardAdminGet } from "@/app/lib/server/forwardGet";
import { badRequest } from "@/app/lib/server/apiRoute";
// GET -> mobile-api GET /api/admin/dashboard/event (BO_DASHBOARD_EVENT, gated upstream). Read-only, prefetch-safe.
// Only the event id is forwarded: mobile-api resolves the operator from the session, never from the client.
export function GET(req: NextRequest) {
const eventId = new URL(req.url).searchParams.get("eventId") ?? "";
if (!/^\d+$/.test(eventId)) return badRequest("Invalid eventId parameter.");
return forwardAdminGet(req, "/api/admin/dashboard/event", ["eventId"]);
}
@@ -1,21 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("GET /api/admin/dashboard country", () => {
it("forwards country to mobile-api", async () => {
await GET(new Request("http://localhost/api/admin/dashboard?country=SG&evil=1") as unknown as Parameters<typeof GET>[0]);
const url = mocks.callMobileApi.mock.calls[0][0] as string;
expect(new URL(url, "http://x").searchParams.get("country")).toBe("SG");
expect(url).not.toContain("evil");
});
});
@@ -1,48 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(search = "") {
return new Request(`http://localhost/api/admin/dashboard${search}`) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/dashboard", () => {
it("forwards only the documented params and the admin JWT", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } });
const res = await GET(getReq("?from=2026-09-01&to=2026-09-29&evil=1"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ok: 1 });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard?from=2026-09-01&to=2026-09-29", { token: "jwt-abc" });
});
it("is 401 without a session and never calls mobile-api", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq());
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("is 400 for a malformed date", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await GET(getReq("?from=yesterday"));
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes an upstream refusal through", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "forbidden", status: 403 });
const res = await GET(getReq());
expect(res.status).toBe(403);
});
});
@@ -1,5 +0,0 @@
import type { NextRequest } from "next/server";
import { forwardAdminGet } from "@/app/lib/server/forwardGet";
// GET -> mobile-api GET /api/admin/dashboard (BO_DASHBOARD). Read-only; module-gated upstream.
export const GET = (req: NextRequest) => forwardAdminGet(req, "/api/admin/dashboard", ["from", "to", "country"]);
@@ -1,13 +0,0 @@
import type { NextRequest } from "next/server";
import { forwardAdminGet } from "@/app/lib/server/forwardGet";
import { badRequest } from "@/app/lib/server/apiRoute";
// GET -> mobile-api GET /api/admin/event-summary/{eventId}?from=&to= (BO_EVENT_SUMMARY, gated upstream). Read-only.
// date is the older one-day form, still forwarded; forwardAdminGet validates from/to, date is checked here.
export async function GET(req: NextRequest, { params }: { params: Promise<{ eventId: string }> }) {
const { eventId } = await params;
if (!/^\d+$/.test(eventId)) return badRequest("Invalid eventId parameter.");
const date = new URL(req.url).searchParams.get("date");
if (date && !/^\d{4}-\d{2}-\d{2}$/.test(date)) return badRequest("Invalid date parameter.");
return forwardAdminGet(req, `/api/admin/event-summary/${encodeURIComponent(eventId)}`, ["date", "from", "to"]);
}
@@ -1,7 +0,0 @@
import type { NextRequest } from "next/server";
import { forwardAdminGet } from "@/app/lib/server/forwardGet";
// GET -> mobile-api GET /api/admin/event-summary/events (BO_EVENT_SUMMARY, gated upstream). Read-only, prefetch-safe.
export function GET(req: NextRequest) {
return forwardAdminGet(req, "/api/admin/event-summary/events", []);
}
@@ -1,77 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
// add-event-summary: the two Event Summary BFF routes are read-only pass-throughs to mobile-api.
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET as getEvents } from "./events/route";
import { GET as getSummary } from "./[eventId]/route";
const req = (path: string) => new Request(`http://localhost${path}`) as unknown as Parameters<typeof getEvents>[0];
const ctx = (eventId: string) => ({ params: Promise.resolve({ eventId }) });
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("GET /api/admin/event-summary/events", () => {
it("forwards to mobile-api with the admin JWT", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [{ id: "5" }] });
const res = await getEvents(req("/api/admin/event-summary/events"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual([{ id: "5" }]);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/events", { token: "jwt-abc" });
});
it("is 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await getEvents(req("/api/admin/event-summary/events"))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
describe("GET /api/admin/event-summary/[eventId]", () => {
it("forwards the event id and the day", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { orders: 3 } });
const res = await getSummary(req("/api/admin/event-summary/5?date=2026-10-06&x=1"), ctx("5"));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?date=2026-10-06", { token: "jwt-abc" });
});
it("forwards without a day when none is given", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} });
await getSummary(req("/api/admin/event-summary/5"), ctx("5"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5", { token: "jwt-abc" });
});
it("is 400 for a non-numeric id or a malformed day, without calling mobile-api", async () => {
expect((await getSummary(req("/api/admin/event-summary/5;x"), ctx("5;x"))).status).toBe(400);
expect((await getSummary(req("/api/admin/event-summary/5?date=06-10-2026"), ctx("5"))).status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards a Date From / Date To range", async () => { // BABYBOO-39
mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} });
await getSummary(req("/api/admin/event-summary/5?from=2026-10-14&to=2026-10-16&x=1"), ctx("5"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?from=2026-10-14&to=2026-10-16", { token: "jwt-abc" });
});
it("forwards from, to and the older date together", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} });
await getSummary(req("/api/admin/event-summary/5?to=2026-10-16&date=2026-10-14&from=2026-10-14"), ctx("5"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?date=2026-10-14&from=2026-10-14&to=2026-10-16", { token: "jwt-abc" });
});
it("is 400 for a malformed from or to, without calling mobile-api", async () => {
expect((await getSummary(req("/api/admin/event-summary/5?from=14-10-2026"), ctx("5"))).status).toBe(400);
expect((await getSummary(req("/api/admin/event-summary/5?from=2026-10-14&to=2026-10"), ctx("5"))).status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes a downstream 403 through", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_EVENT_SUMMARY module is required." });
expect((await getSummary(req("/api/admin/event-summary/5"), ctx("5"))).status).toBe(403);
});
});
@@ -1,122 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
const ctx = () => ({ params: Promise.resolve({ uuid: "12345" }) });
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/kyc/12345/action", {
method: "POST",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/kyc/[uuid]/action", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq({ action: "approve", remarks: "" }), ctx());
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects a non-numeric uuid (path traversal) with 400 before calling upstream", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await POST(postReq({ action: "approve", remarks: "" }), { params: Promise.resolve({ uuid: "../../member/x" }) });
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects action=delete with 400", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await POST(postReq({ action: "delete", remarks: "test" }), ctx());
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects action=pending with 400", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await POST(postReq({ action: "pending", remarks: "test" }), ctx());
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects reject action with blank remarks", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await POST(postReq({ action: "reject", remarks: "" }), ctx());
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects reject action with whitespace-only remarks", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await POST(postReq({ action: "reject", remarks: " " }), ctx());
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects revoke action with blank remarks", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await POST(postReq({ action: "revoke", remarks: "" }), ctx());
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("accepts approve with empty remarks", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "A" } });
const res = await POST(postReq({ action: "approve", remarks: "" }), ctx());
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/approve", {
method: "POST",
body: { action: "approve", remarks: "" },
token: "jwt-abc",
});
});
it("accepts reject with non-blank remarks (≤500 chars)", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "R" } });
const res = await POST(postReq({ action: "reject", remarks: "Document expired on 2025-01-01" }), ctx());
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/reject", {
method: "POST",
body: { action: "reject", remarks: "Document expired on 2025-01-01" },
token: "jwt-abc",
});
});
it("accepts revoke with remarks", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "V" } });
const res = await POST(postReq({ action: "revoke", remarks: "Admin correction" }), ctx());
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/revoke", {
method: "POST",
body: { action: "revoke", remarks: "Admin correction" },
token: "jwt-abc",
});
});
it("rejects remarks > 500 chars", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const longRemarks = "x".repeat(501);
const res = await POST(postReq({ action: "reject", remarks: longRemarks }), ctx());
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -1,49 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminKycRow } from "@/app/lib/types";
// POST -> /api/admin/kyc/{uuid}/action { action, remarks } (BO_KYC gated upstream; a mutation,
// never a GET). action ∈ { approve, reject, revoke }. reject/revoke require non-blank remarks ≤ 500 chars.
const ALLOWED_ACTIONS = new Set(["approve", "reject", "revoke"]);
export async function POST(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { uuid } = await ctx.params;
// uuid is a Snowflake id carried as a string; anything else never reaches the upstream path.
if (!/^\d+$/.test(uuid)) return badRequest("Parameter \"uuid\" is invalid");
let body: unknown;
try {
body = await req.json();
} catch {
return badRequest("Invalid request body");
}
const { action, remarks } = (body ?? {}) as { action?: unknown; remarks?: unknown };
if (typeof action !== "string" || !ALLOWED_ACTIONS.has(action)) {
return badRequest("Parameter \"action\" must be one of: approve, reject, revoke");
}
const remarksStr = typeof remarks === "string" ? remarks : "";
// reject/revoke require non-blank remarks, max 500 chars.
if ((action === "reject" || action === "revoke") && !remarksStr.trim()) {
return badRequest("Remarks are required for this action");
}
if (remarksStr.length > 500) {
return badRequest("Remarks must not exceed 500 characters");
}
const result = await callMobileApi<AdminKycRow>(`/api/admin/kyc/${encodeURIComponent(uuid)}/${action}`, {
method: "POST",
body: { action, remarks: remarksStr },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,120 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
const mocks = vi.hoisted(() => ({ getToken: vi.fn() }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function req(url = "http://localhost/api/admin/kyc/12345/doc/ID_FRONT") {
const u = new URL(url);
return { nextUrl: u } as unknown as Parameters<typeof GET>[0];
}
const ctx = (uuid = "12345", docType = "ID_FRONT") => ({ params: Promise.resolve({ uuid, docType }) });
const originalFetch = global.fetch;
beforeEach(() => {
mocks.getToken.mockReset();
process.env.MOBILE_API_BASE_URL = "http://gateway";
process.env.MOBILE_API_KEY = "secret-key";
});
afterEach(() => {
global.fetch = originalFetch;
});
describe("GET /api/admin/kyc/[uuid]/doc/[docType]", () => {
it("returns 401 without a session and never calls upstream", async () => {
mocks.getToken.mockResolvedValue(null);
const fetchSpy = vi.fn();
global.fetch = fetchSpy as unknown as typeof fetch;
const res = await GET(req(), ctx());
expect(res.status).toBe(401);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("rejects docType=PASSPORT with 400 and never calls upstream", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const fetchSpy = vi.fn();
global.fetch = fetchSpy as unknown as typeof fetch;
const res = await GET(req(), ctx("12345", "PASSPORT"));
expect(res.status).toBe(400);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("rejects docType=DRIVING_LICENSE with 400", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const fetchSpy = vi.fn();
global.fetch = fetchSpy as unknown as typeof fetch;
const res = await GET(req(), ctx("12345", "DRIVING_LICENSE"));
expect(res.status).toBe(400);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("returns upstream bytes with no-store for allowed docTypes", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const imgBytes = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0]); // JPEG marker
const upstream = new Response(imgBytes, {
status: 200,
headers: { "content-type": "image/jpeg" },
});
const fetchSpy = vi.fn().mockResolvedValue(upstream);
global.fetch = fetchSpy as unknown as typeof fetch;
const res = await GET(req(), ctx("12345", "ID_FRONT"));
expect(res.status).toBe(200);
expect(res.headers.get("Cache-Control")).toBe("no-store");
expect(res.headers.get("content-type")).toBe("image/jpeg");
const body = new Uint8Array(await res.arrayBuffer());
expect(Array.from(body)).toEqual([0xFF, 0xD8, 0xFF, 0xE0]);
});
it("returns upstream bytes for SELFIE", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const pngBytes = new Uint8Array([0x89, 0x50, 0x4E, 0x47]);
const upstream = new Response(pngBytes, {
status: 200,
headers: { "content-type": "image/png" },
});
const fetchSpy = vi.fn().mockResolvedValue(upstream);
global.fetch = fetchSpy as unknown as typeof fetch;
const res = await GET(req(), ctx("67890", "SELFIE"));
expect(res.status).toBe(200);
const body = new Uint8Array(await res.arrayBuffer());
expect(Array.from(body)).toEqual([0x89, 0x50, 0x4E, 0x47]);
});
// F20: the proxy is served from the admin origin with the admin's cookie; a stored non-image type must never render
it("never passes a non-image upstream type through, and forbids sniffing", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
for (const type of ["text/html", "image/svg+xml", "application/xhtml+xml", "text/html; charset=utf-8"]) {
global.fetch = vi.fn().mockResolvedValue(
new Response("<script>alert(1)</script>", { status: 200, headers: { "content-type": type } }),
) as unknown as typeof fetch;
const res = await GET(req(), ctx("12345", "SELFIE"));
expect(res.headers.get("content-type")).toBe("application/octet-stream");
expect(res.headers.get("x-content-type-options")).toBe("nosniff");
}
});
it("keeps an image type and forbids sniffing", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
global.fetch = vi.fn().mockResolvedValue(
new Response(new Uint8Array([1]), { status: 200, headers: { "content-type": "Image/PNG; foo=bar" } }),
) as unknown as typeof fetch;
const res = await GET(req(), ctx("12345", "ID_BACK"));
expect(res.headers.get("content-type")).toBe("image/png");
expect(res.headers.get("x-content-type-options")).toBe("nosniff");
});
});
@@ -1,74 +0,0 @@
import { SAFE_BINARY_HEADERS, safeContentType } from "@/app/lib/server/binaryProxy";
import { NextResponse, type NextRequest } from "next/server";
import { getToken } from "@/app/lib/server/session";
import { unauthorized } from "@/app/lib/server/apiRoute";
import { isTraversalPath } from "@/app/lib/server/upstreamPathGuard";
import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext";
// GET -> mobile-api GET /api/admin/kyc/{uuid}/doc/{docType} — streams KYC document image bytes.
// A binary proxy: callMobileApi normalizes JSON, so this route does a raw fetch and passes the
// image bytes + Content-Type through. Authorization is the BO_KYC module grant, enforced
// server-side by mobile-api. Read-only — no side effect on GET (Next.js prefetch-safe).
// Allowed docTypes: ID_FRONT, ID_BACK, SELFIE.
const TIMEOUT_MS = 30_000;
const ALLOWED_DOC_TYPES = new Set(["ID_FRONT", "ID_BACK", "SELFIE"]);
function jsonError(message: string, status: number) {
return NextResponse.json({ error: message }, { status });
}
export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string; docType: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { docType, uuid } = await ctx.params;
// Only allow known doc types — never call upstream with an arbitrary path segment.
if (!/^\d+$/.test(uuid)) return jsonError("Invalid uuid", 400);
if (!ALLOWED_DOC_TYPES.has(docType)) {
return jsonError(`Unsupported doc type: ${encodeURIComponent(docType)}`, 400);
}
const base = process.env.MOBILE_API_BASE_URL;
const key = process.env.MOBILE_API_KEY;
if (!base || !key) return jsonError("Mobile API is not configured", 500);
// Fetched directly, so callMobileApi's dot-segment guard is applied here too.
const path = `/api/admin/kyc/${encodeURIComponent(uuid)}/doc/${encodeURIComponent(docType)}`;
if (isTraversalPath(path)) return jsonError("Invalid uuid", 400);
const forwardedIp = await forwardedClientIpHeaders();
const url = `${base}${path}`;
let res: Response;
try {
res = await fetch(url, {
method: "GET",
headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` },
cache: "no-store",
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch {
return jsonError("Couldn't reach the KYC service", 502);
}
if (!res.ok) {
if (res.status === 401) return unauthorized();
if (res.status === 404) return jsonError("Document not found.", 404);
if (res.status === 403) return jsonError("Not authorized.", 403);
if (res.status >= 500) return jsonError("The KYC service failed.", 502);
return jsonError("Couldn't download the document.", 400);
}
const body = await res.arrayBuffer();
const headers = new Headers({
// KYC documents are JPEG or PNG only (mobile-api KycUploadRules); F20: nothing else renders on this origin
"Content-Type": safeContentType(res.headers.get("content-type"), ["image/jpeg", "image/png"]),
"Cache-Control": "no-store",
...SAFE_BINARY_HEADERS,
});
const disposition = res.headers.get("content-disposition");
if (disposition) headers.set("Content-Disposition", disposition);
return new NextResponse(body, { status: 200, headers });
}
@@ -1,44 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(url = "http://localhost/api/admin/kyc/12345") {
return new Request(url) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/kyc/[uuid]", () => {
it("rejects a non-numeric uuid with 400 before calling upstream", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await GET(getReq(), { params: Promise.resolve({ uuid: "abc" }) });
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq(), { params: Promise.resolve({ uuid: "12345" }) });
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards uuid to mobile-api", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({
ok: true,
data: { record: {}, docTypes: [], member: {}, history: [], warnings: [] },
});
await GET(getReq(), { params: Promise.resolve({ uuid: "12345" }) });
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345", { token: "jwt-abc" });
});
});
@@ -1,21 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute";
import type { AdminKycDetail } from "@/app/lib/types";
// GET -> /api/admin/kyc/{uuid} (read-only; BO_KYC gated upstream).
export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { uuid } = await ctx.params;
// uuid is a Snowflake id carried as a string; anything else never reaches the upstream path.
if (!/^\d+$/.test(uuid)) return badRequest("Parameter \"uuid\" is invalid");
const result = await callMobileApi<AdminKycDetail>(`/api/admin/kyc/${encodeURIComponent(uuid)}`, {
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,33 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(url = "http://localhost/api/admin/kyc/counts") {
return new Request(url) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/kyc/counts", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq());
expect(res.status).toBe(401);
});
it("forwards to mobile-api", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { P: 1, A: 2, R: 0, V: 0, ALL: 3 } });
const res = await GET(getReq());
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/counts", { token: "jwt-abc" });
});
});
@@ -1,16 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminKycCounts } from "@/app/lib/types";
// GET -> /api/admin/kyc/counts (read-only; BO_KYC gated upstream).
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<AdminKycCounts>("/api/admin/kyc/counts", { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,38 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(url = "http://localhost/api/admin/kyc/export") {
return new Request(url) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/kyc/export", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq());
expect(res.status).toBe(401);
});
it("forwards query params (minus page/size) to mobile-api", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] });
await GET(getReq("http://localhost/api/admin/kyc/export?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=10"));
// page/size should be absent from the export call
const [path] = mocks.callMobileApi.mock.calls[0];
expect(path).toContain("status=P");
expect(path).toContain("q=ahmad");
expect(path).not.toContain("page=");
expect(path).not.toContain("size=");
});
});
@@ -1,30 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery";
// GET -> /api/admin/kyc/export?status=&q=&from=&to=&channel= (same filters as list but no page/size; read-only; BO_KYC gated upstream).
const QUERY = {
status: TEXT,
q: TEXT,
from: TEXT,
to: TEXT,
channel: TEXT,
};
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
// portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded.
// Export does NOT carry page/size, so they are not in its allow-list.
const qs = upstreamQuery(new URL(req.url).searchParams, QUERY);
const result = await callMobileApi<unknown[]>(
`/api/admin/kyc/export${qs}`,
{ token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,55 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(url = "http://localhost/api/admin/kyc") {
return new Request(url) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/kyc", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq());
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards query params to mobile-api", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0, page: 0, size: 10 } });
await GET(getReq("http://localhost/api/admin/kyc?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=20"));
expect(mocks.callMobileApi).toHaveBeenCalledWith(
"/api/admin/kyc?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=20",
{ token: "jwt-abc" },
);
});
it("omits absent query params", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0, page: 0, size: 10 } });
await GET(getReq());
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc", { token: "jwt-abc" });
});
it("returns 200 on success", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const payload = { content: [], totalElements: 0, page: 0, size: 10 };
mocks.callMobileApi.mockResolvedValue({ ok: true, data: payload });
const res = await GET(getReq());
expect(res.status).toBe(200);
});
});
@@ -1,32 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery";
import type { AdminKycPage } from "@/app/lib/types";
// GET -> /api/admin/kyc?status=&q=&from=&to=&channel=&page=&size= (read-only; BO_KYC gated upstream).
const QUERY = {
status: TEXT,
q: TEXT,
from: TEXT,
to: TEXT,
channel: TEXT,
...paging(500),
...SORT,
};
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
// portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded.
const qs = upstreamQuery(new URL(req.url).searchParams, QUERY);
const result = await callMobileApi<AdminKycPage>(
`/api/admin/kyc${qs}`,
{ token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,64 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/kyc/submit", {
method: "POST",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/kyc/submit", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(
postReq({
memberCode: "BB0100",
submitName: "Ahmad",
identityType: "MYKAD",
identityNo: "880101-01-1234",
docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" },
}),
);
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the submit body to mobile-api", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "999", status: "P" } });
const res = await POST(
postReq({
memberCode: "BB0100",
submitName: "Ahmad",
identityType: "MYKAD",
identityNo: "880101-01-1234",
docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" },
}),
);
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/submit", {
method: "POST",
body: {
memberCode: "BB0100",
submitName: "Ahmad",
identityType: "MYKAD",
identityNo: "880101-01-1234",
docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" },
},
token: "jwt-abc",
});
});
});
@@ -1,48 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminKycRow } from "@/app/lib/types";
// POST -> /api/admin/kyc/submit { memberCode, submitName, identityType, identityNo, docs }
// (BO_KYC gated upstream; a mutation, never a GET).
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
let body: unknown;
try {
body = await req.json();
} catch {
return badRequest("Invalid request body");
}
const { memberCode, submitName, identityType, identityNo, docs } = (body ?? {}) as {
memberCode?: unknown;
submitName?: unknown;
identityType?: unknown;
identityNo?: unknown;
docs?: unknown;
};
if (typeof memberCode !== "string" || !memberCode) {
return badRequest("Parameter \"memberCode\" is required");
}
if (typeof submitName !== "string" || !submitName) {
return badRequest("Parameter \"submitName\" is required");
}
if (typeof identityType !== "string" || !identityType) {
return badRequest("Parameter \"identityType\" is required");
}
if (typeof identityNo !== "string" || !identityNo) {
return badRequest("Parameter \"identityNo\" is required");
}
const result = await callMobileApi<AdminKycRow>("/api/admin/kyc/submit", {
method: "POST",
body: { memberCode, submitName, identityType, identityNo, docs },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,44 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/kyc/upload", {
method: "POST",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/kyc/upload", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq({ memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "data" }));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the upload body to mobile-api", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { reference: "ref-123" } });
const res = await POST(
postReq({ memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "base64data" }),
);
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/upload", {
method: "POST",
body: { memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "base64data" },
token: "jwt-abc",
});
});
});
@@ -1,38 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { KycUploadResult } from "@/app/lib/types";
// POST -> /api/admin/kyc/upload { memberCode, docType, fileType, base } (BO_KYC gated upstream;
// a mutation, never a GET).
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
let body: unknown;
try {
body = await req.json();
} catch {
return badRequest("Invalid request body");
}
const { memberCode, docType, fileType, base } = (body ?? {}) as {
memberCode?: unknown;
docType?: unknown;
fileType?: unknown;
base?: unknown;
};
if (typeof memberCode !== "string" || !memberCode) {
return badRequest("Parameter \"memberCode\" is required");
}
const result = await callMobileApi<KycUploadResult>("/api/admin/kyc/upload", {
method: "POST",
body: { memberCode, docType, fileType, base },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,51 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(qs: string) {
return new Request(`http://localhost/api/admin/member-corrections${qs}`) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/member-corrections", () => {
it("forwards the query string with the admin JWT and returns the page", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const page = { content: [], totalElements: 0 };
mocks.callMobileApi.mockResolvedValue({ ok: true, data: page });
const res = await GET(getReq("?type=RANK&memberCode=MY1&page=1&size=20"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual(page);
expect(mocks.callMobileApi).toHaveBeenCalledWith(
"/api/admin/member-corrections?type=RANK&memberCode=MY1&page=1&size=20",
{ token: "jwt-abc" },
);
});
it("forwards no query string when there is none", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } });
await GET(getReq(""));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/member-corrections", { token: "jwt-abc" });
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq(""));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -1,33 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery";
import type { AdminMemberCorrectionPage } from "@/app/lib/types";
// GET -> /api/admin/member-corrections (BABYBOO-43): admin rank and referral corrections, newest
// first. Forwards the query string (type, memberCode, from, to, page, size) with the bb_admin JWT. Read-only —
// no side effect on GET (Next.js prefetch-safe). BO_RANK_REFERRAL is enforced upstream.
const QUERY = {
type: TEXT,
memberCode: TEXT,
from: TEXT,
to: TEXT,
...paging(500),
...SORT,
};
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
// portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded.
const qs = upstreamQuery(new URL(req.url).searchParams, QUERY);
const result = await callMobileApi<AdminMemberCorrectionPage>(
`/api/admin/member-corrections${qs}`,
{ token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,58 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { getToken } from "@/app/lib/server/session";
import { unauthorized } from "@/app/lib/server/apiRoute";
import { expiredSignal, isId } from "@/app/lib/server/messagesProxy";
import { isTraversalPath } from "@/app/lib/server/upstreamPathGuard";
import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext";
// GET -> mobile-api GET /api/admin/member-messages/{uuid}/messages/{messageUuid}/images/{index}: streams a
// private message image. Raw fetch (callMobileApi normalises JSON). Side-effect free, so prefetch-safe.
const TIMEOUT_MS = 120_000; // covers the piped body too, so a slow link can finish a 5 MB image
const IMAGE_TYPES = new Set(["image/jpeg", "image/png"]);
const err = (message: string, status: number) => NextResponse.json({ error: message }, { status });
export async function GET(
_req: NextRequest,
ctx: { params: Promise<{ uuid: string; messageUuid: string; index: string }> },
) {
const token = await getToken();
if (!token) return unauthorized();
const { uuid, messageUuid, index } = await ctx.params;
if (!isId(uuid) || !isId(messageUuid) || !/^\d{1,2}$/.test(index)) return err("Invalid image reference", 400);
// Fetched directly, so callMobileApi's dot-segment guard is applied here too.
const path = `/api/admin/member-messages/${encodeURIComponent(uuid)}/messages/${encodeURIComponent(messageUuid)}/images/${encodeURIComponent(index)}`;
if (isTraversalPath(path)) return err("Invalid image reference", 400);
const base = process.env.MOBILE_API_BASE_URL;
const key = process.env.MOBILE_API_KEY;
if (!base || !key) return err("Mobile API is not configured", 500);
const forwardedIp = await forwardedClientIpHeaders();
let res: Response;
try {
res = await fetch(`${base}${path}`, {
headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` },
cache: "no-store",
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch {
return err("Couldn't reach the messaging service", 502);
}
if (!res.ok) {
if (expiredSignal(res.status, await res.text().catch(() => ""))) return unauthorized();
if (res.status === 404) return err("Image not found.", 404);
if (res.status === 403) return err("Not authorized.", 403);
return err("Couldn't load the image.", res.status >= 500 ? 502 : 400);
}
// Served from the origin that holds the admin session: never pass an upstream type through unchecked.
const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
return new NextResponse(res.body, {
status: 200,
headers: {
"Content-Type": IMAGE_TYPES.has(type) ? type : "application/octet-stream",
"Cache-Control": "private, no-store",
"X-Content-Type-Options": "nosniff",
},
});
}
@@ -1,18 +0,0 @@
import type { NextRequest } from "next/server";
import { badRequest } from "@/app/lib/server/apiRoute";
import { isId, relay } from "@/app/lib/server/messagesProxy";
type Ctx = { params: Promise<{ uuid: string }> };
// GET -> /api/admin/member-messages/{uuid}/messages?before=&size= POST -> same path { body, imageRefs }.
export async function GET(req: NextRequest, ctx: Ctx) {
const { uuid } = await ctx.params;
if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid');
return relay(req, `/${encodeURIComponent(uuid)}/messages`, "GET", { query: ["before", "size"] });
}
export async function POST(req: NextRequest, ctx: Ctx) {
const { uuid } = await ctx.params;
if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid');
return relay(req, `/${encodeURIComponent(uuid)}/messages`, "POST", { body: true });
}
@@ -1,10 +0,0 @@
import type { NextRequest } from "next/server";
import { badRequest } from "@/app/lib/server/apiRoute";
import { isId, relay } from "@/app/lib/server/messagesProxy";
// POST -> mobile-api POST /api/admin/member-messages/{uuid}/read (a mutation, never a GET).
export async function POST(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) {
const { uuid } = await ctx.params;
if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid');
return relay(req, `/${encodeURIComponent(uuid)}/read`, "POST");
}
@@ -1,10 +0,0 @@
import type { NextRequest } from "next/server";
import { badRequest } from "@/app/lib/server/apiRoute";
import { isId, relay } from "@/app/lib/server/messagesProxy";
// GET -> mobile-api GET /api/admin/member-messages/{uuid}.
export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) {
const { uuid } = await ctx.params;
if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid');
return relay(req, `/${encodeURIComponent(uuid)}`, "GET");
}
@@ -1,10 +0,0 @@
import type { NextRequest } from "next/server";
import { badRequest } from "@/app/lib/server/apiRoute";
import { isId, relay } from "@/app/lib/server/messagesProxy";
// GET -> mobile-api GET /api/admin/member-messages/broadcasts/{broadcastUuid}/recipients?unreadOnly=&page=&size=.
export async function GET(req: NextRequest, ctx: { params: Promise<{ broadcastUuid: string }> }) {
const { broadcastUuid } = await ctx.params;
if (!isId(broadcastUuid)) return badRequest('Parameter "broadcastUuid" is invalid');
return relay(req, `/broadcasts/${encodeURIComponent(broadcastUuid)}/recipients`, "GET", { query: ["unreadOnly", "page", "size", "sortBy", "sortDir"] });
}
@@ -1,10 +0,0 @@
import type { NextRequest } from "next/server";
import { badRequest } from "@/app/lib/server/apiRoute";
import { isId, relay } from "@/app/lib/server/messagesProxy";
// GET -> mobile-api GET /api/admin/member-messages/broadcasts/{broadcastUuid}.
export async function GET(req: NextRequest, ctx: { params: Promise<{ broadcastUuid: string }> }) {
const { broadcastUuid } = await ctx.params;
if (!isId(broadcastUuid)) return badRequest('Parameter "broadcastUuid" is invalid');
return relay(req, `/broadcasts/${encodeURIComponent(broadcastUuid)}`, "GET");
}
@@ -1,5 +0,0 @@
import type { NextRequest } from "next/server";
import { relay } from "@/app/lib/server/messagesProxy";
// POST -> mobile-api POST /api/admin/member-messages/broadcasts/preview { target }.
export const POST = (req: NextRequest) => relay(req, "/broadcasts/preview", "POST", { body: true });
@@ -1,9 +0,0 @@
import type { NextRequest } from "next/server";
import { relay } from "@/app/lib/server/messagesProxy";
// GET -> mobile-api GET /api/admin/member-messages/broadcasts (q, sortBy, sortDir, page, size): one summary row per broadcast.
export const GET = (req: NextRequest) =>
relay(req, "/broadcasts", "GET", { query: ["q", "sortBy", "sortDir", "page", "size"] });
// POST -> mobile-api POST /api/admin/member-messages/broadcasts { target, subject, body, imageRefs }.
export const POST = (req: NextRequest) => relay(req, "/broadcasts", "POST", { body: true });
@@ -1,5 +0,0 @@
import type { NextRequest } from "next/server";
import { relay } from "@/app/lib/server/messagesProxy";
// GET -> mobile-api GET /api/admin/member-messages/by-key (query forwarded: member).
export const GET = (req: NextRequest) => relay(req, "/by-key", "GET", { query: ["member"] });
@@ -1,69 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { getToken } from "@/app/lib/server/session";
import { badRequest, unauthorized } from "@/app/lib/server/apiRoute";
import { codeOf, codeResponse, expiredSignal } from "@/app/lib/server/messagesProxy";
import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext";
// POST multipart { file } -> mobile-api POST /api/admin/member-messages/images -> { ref }. TWO-STEP upload:
// the ref is committed by mobile-api when the message is sent (abandoned uploads are reaped, intended).
const ALLOWED = new Set(["image/jpeg", "image/png"]);
const MAX_BYTES = 5 * 1024 * 1024;
const TIMEOUT_MS = 30_000;
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
// Refuse an oversized declared body before buffering it (formData() reads everything into memory).
if (Number(req.headers?.get("content-length") ?? 0) > MAX_BYTES + 64 * 1024) {
return badRequest("Image must be 5 MB or smaller", { code: "MESSAGE_INVALID" });
}
let file: unknown;
try {
file = (await req.formData()).get("file");
} catch {
return badRequest("Invalid request body");
}
if (!(file instanceof File)) return badRequest('Parameter "file" is required');
if (!ALLOWED.has(file.type)) return badRequest("Only JPEG or PNG images are allowed", { code: "MESSAGE_INVALID" });
if (file.size > MAX_BYTES) return badRequest("Image must be 5 MB or smaller", { code: "MESSAGE_INVALID" });
const base = process.env.MOBILE_API_BASE_URL;
const key = process.env.MOBILE_API_KEY;
if (!base || !key) return NextResponse.json({ error: "Mobile API is not configured" }, { status: 500 });
const forwardedIp = await forwardedClientIpHeaders();
const form = new FormData();
form.set("file", file, file.name);
let res: Response;
try {
res = await fetch(`${base}/api/admin/member-messages/images`, {
method: "POST",
headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, // no Content-Type: fetch sets the boundary
body: form,
cache: "no-store",
signal: AbortSignal.timeout(TIMEOUT_MS),
});
} catch {
return NextResponse.json({ error: "Couldn't reach the messaging service" }, { status: 502 });
}
const text = await res.text();
let data: Record<string, unknown> = {};
try {
data = text ? JSON.parse(text) : {};
} catch {
/* non-JSON upstream body: fall through to the generic message */
}
if (!res.ok) {
if (expiredSignal(res.status, text)) return unauthorized();
const code = codeOf(text); // matches the code field or a reason text that carries it
if (code) return codeResponse(code);
const message = (data.detail as string) || (data.message as string) || (data.error as string) || "Upload failed";
const status = res.status >= 400 && res.status < 500 ? res.status : 502;
return NextResponse.json({ error: message }, { status });
}
// A 200 without a ref would let the UI send a message pointing at nothing.
if (typeof data.ref !== "string") return NextResponse.json({ error: "Upload failed" }, { status: 502 });
return NextResponse.json({ ref: data.ref });
}
@@ -1,5 +0,0 @@
import type { NextRequest } from "next/server";
import { relay } from "@/app/lib/server/messagesProxy";
// GET -> mobile-api GET /api/admin/member-messages (query forwarded: types, unreadOnly, q, page, size).
export const GET = (req: NextRequest) => relay(req, "", "GET", { query: ["types", "unreadOnly", "q", "page", "size", "sortBy", "sortDir"] });
@@ -1,106 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { NextRequest } from "next/server";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET as listBroadcasts } from "./broadcasts/route";
import { GET as summary } from "./broadcasts/[broadcastUuid]/route";
import { GET as recipients } from "./broadcasts/[broadcastUuid]/recipients/route";
// BABYBOO-56 broadcast read count: read-only BFF relays.
const B = "http://localhost/api/admin/member-messages";
const req = (url: string) => new Request(url, { method: "GET" }) as unknown as NextRequest;
const ctx = (broadcastUuid: string) => ({ params: Promise.resolve({ broadcastUuid }) });
const lastCall = () => {
const [url, opts] = mocks.callMobileApi.mock.calls.at(-1)!;
const [path, qs = ""] = String(url).split("?");
return { path, sp: new URLSearchParams(qs), opts };
};
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { fine: 1 } });
mocks.getToken.mockReset().mockResolvedValue("jwt");
process.env.MOBILE_API_BASE_URL = "http://up";
process.env.MOBILE_API_KEY = "k";
});
describe("GET broadcasts summaries relay", () => {
it("forwards q, page and size to mobile-api with the session token", async () => {
const res = await listBroadcasts(req(`${B}/broadcasts?q=raya&page=1&size=20`));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ fine: 1 });
const { path, sp, opts } = lastCall();
expect(path).toBe("/api/admin/member-messages/broadcasts");
expect([sp.get("q"), sp.get("page"), sp.get("size")]).toEqual(["raya", "1", "20"]);
expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" }));
});
it("returns 401 with no session and never calls upstream", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await listBroadcasts(req(`${B}/broadcasts?page=0&size=20`))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("maps an upstream failure to an error response", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Something odd", status: 500 });
expect((await listBroadcasts(req(`${B}/broadcasts?page=0&size=20`))).status).toBeGreaterThanOrEqual(400);
});
});
describe("GET broadcast recipients relay", () => {
it("forwards the uuid, unreadOnly, page and size", async () => {
const res = await recipients(req(`${B}/broadcasts/b1/recipients?unreadOnly=true&page=2&size=20`), ctx("b1"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ fine: 1 });
const { path, sp, opts } = lastCall();
expect(path).toBe("/api/admin/member-messages/broadcasts/b1/recipients");
expect([sp.get("unreadOnly"), sp.get("page"), sp.get("size")]).toEqual(["true", "2", "20"]);
expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" }));
});
it("returns 401 with no session and never calls upstream", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await recipients(req(`${B}/broadcasts/b1/recipients`), ctx("b1"))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects a path-like broadcast id before any upstream call", async () => {
const res = await recipients(req(`${B}/broadcasts/x/recipients`), ctx("../admin"));
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes an upstream 404 through", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Broadcast not found", status: 404 });
expect((await recipients(req(`${B}/broadcasts/b1/recipients`), ctx("b1"))).status).toBe(404);
});
});
describe("GET single broadcast summary relay", () => {
it("forwards the uuid to mobile-api with the session token", async () => {
const res = await summary(req(`${B}/broadcasts/b1`), ctx("b1"));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ fine: 1 });
const { path, opts } = lastCall();
expect(path).toBe("/api/admin/member-messages/broadcasts/b1");
expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" }));
});
it("returns 401 with no session and never calls upstream", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await summary(req(`${B}/broadcasts/b1`), ctx("b1"))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects a path-like broadcast id with 400 before any upstream call", async () => {
expect((await summary(req(`${B}/broadcasts/x`), ctx("../admin"))).status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes an upstream 404 through", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Broadcast not found", status: 404 });
expect((await summary(req(`${B}/broadcasts/b1`), ctx("b1"))).status).toBe(404);
});
});
@@ -1,109 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { NextRequest } from "next/server";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET as list } from "./route";
import { GET as byKey } from "./by-key/route";
import { GET as messages } from "./[uuid]/messages/route";
import { POST as upload } from "./images/route";
import { GET as image } from "./[uuid]/messages/[messageUuid]/images/[index]/route";
const B = "http://localhost/api/admin/member-messages";
const get = (url: string) => new Request(url) as unknown as NextRequest;
const img = (messageUuid = "m1") => ({ params: Promise.resolve({ uuid: "c1", messageUuid, index: "0" }) });
const formReq = (fd: FormData, headers: Record<string, string> = {}) =>
({ headers: new Headers(headers), formData: async () => fd }) as unknown as NextRequest;
const pngForm = () => {
const fd = new FormData();
fd.append("file", new File(["abc"], "a.png", { type: "image/png" }));
return fd;
};
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
mocks.getToken.mockReset().mockResolvedValue("jwt");
process.env.MOBILE_API_BASE_URL = "http://up";
process.env.MOBILE_API_KEY = "k";
});
afterEach(() => vi.unstubAllGlobals());
describe("query whitelist", () => {
it("forwards only the documented query keys", async () => {
await list(get(`${B}?types=S&q=x&page=1&size=20&unreadOnly=true&reader=M:MY3&adminUsername=eve`));
await byKey(get(`${B}/by-key?member=MY5&reader=M:MY3`));
await messages(get(`${B}/c1/messages?before=m9&size=30&reader=M:MY3`), { params: Promise.resolve({ uuid: "c1" }) });
const urls = mocks.callMobileApi.mock.calls.map((c) => c[0] as string);
expect(urls[0]).toBe("/api/admin/member-messages?types=S&unreadOnly=true&q=x&page=1&size=20");
expect(urls[1]).toBe("/api/admin/member-messages/by-key?member=MY5");
expect(urls[2]).toBe("/api/admin/member-messages/c1/messages?before=m9&size=30");
});
it("passes a module-denied 403 through for the blocked state", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_MEMBER_MESSAGES module is required." });
const res = await list(get(B));
expect(res.status).toBe(403);
});
});
describe("upload", () => {
it("refuses a declared body far over 5 MB before reading it", async () => {
const formData = vi.fn();
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const res = await upload({ headers: new Headers({ "content-length": String(7 * 1024 * 1024) }), formData } as unknown as NextRequest);
expect(res.status).toBe(400);
expect(formData).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
it("forwards the file under the `file` field", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ref: "messages/admin/1.png" }), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
const res = await upload(formReq(pngForm()));
expect(await res.json()).toEqual({ ref: "messages/admin/1.png" });
expect((fetchMock.mock.calls[0][1].body as FormData).get("file")).toBeInstanceOf(File);
});
it("answers 502 when a 200 reply has no ref", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("<html/>", { status: 200 })));
expect((await upload(formReq(pngForm()))).status).toBe(502);
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", { status: 200 })));
expect((await upload(formReq(pngForm()))).status).toBe(502);
});
it("maps mobile-api's expired-token 500 to 401", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("JWT expired token", { status: 500 })));
expect((await upload(formReq(pngForm()))).status).toBe(401);
});
});
describe("image stream", () => {
it("never serves a non-image type as-is and sets nosniff", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("<script>", { status: 200, headers: { "content-type": "text/html" } })));
const res = await image(get(`${B}/c1/messages/m1/images/0`), img());
expect(res.headers.get("content-type")).toBe("application/octet-stream");
expect(res.headers.get("x-content-type-options")).toBe("nosniff");
});
it("keeps an image type and pipes the body", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("png", { status: 200, headers: { "content-type": "image/png" } })));
const res = await image(get(`${B}/c1/messages/m1/images/0`), img());
expect(res.headers.get("content-type")).toBe("image/png");
expect(await res.text()).toBe("png");
});
it("refuses a malformed message id without calling upstream", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
expect((await image(get(B), img("../x"))).status).toBe(400);
expect(fetchMock).not.toHaveBeenCalled();
});
it("maps mobile-api's expired-token 500 to 401", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("invalid token", { status: 500 })));
expect((await image(get(B), img())).status).toBe(401);
});
});
@@ -1,184 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { NextRequest } from "next/server";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET as list } from "./route";
import { GET as unread } from "./unread-count/route";
import { GET as byKey } from "./by-key/route";
import { POST as start } from "./start/route";
import { POST as preview } from "./broadcasts/preview/route";
import { GET as broadcastList, POST as broadcast } from "./broadcasts/route";
import { GET as thread } from "./[uuid]/route";
import { GET as messages, POST as reply } from "./[uuid]/messages/route";
import { POST as read } from "./[uuid]/read/route";
import { GET as image } from "./[uuid]/messages/[messageUuid]/images/[index]/route";
import { POST as upload } from "./images/route";
const B = "http://localhost/api/admin/member-messages";
const req = (url: string, body?: unknown, method = body === undefined ? "GET" : "POST") =>
new Request(url, { method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }) as unknown as NextRequest;
const c1 = { params: Promise.resolve({ uuid: "c1" }) };
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { fine: 1 } });
mocks.getToken.mockReset().mockResolvedValue("jwt");
process.env.MOBILE_API_BASE_URL = "http://up";
process.env.MOBILE_API_KEY = "k";
});
afterEach(() => vi.unstubAllGlobals());
const reply_ = { body: "hi", imageRefs: ["messages/admin/a.png"] };
const cases: [string, () => Promise<Response>, string, "GET" | "POST", unknown?][] = [
["list", () => list(req(`${B}?types=S&page=0&size=20`)), "/api/admin/member-messages?types=S&page=0&size=20", "GET"],
["unread-count", () => unread(req(`${B}/unread-count`)), "/api/admin/member-messages/unread-count", "GET"],
["by-key", () => byKey(req(`${B}/by-key?member=MY5`)), "/api/admin/member-messages/by-key?member=MY5", "GET"],
["thread", () => thread(req(`${B}/c1`), c1), "/api/admin/member-messages/c1", "GET"],
["messages GET", () => messages(req(`${B}/c1/messages?before=m9&size=30`), c1), "/api/admin/member-messages/c1/messages?before=m9&size=30", "GET"],
["reply", () => reply(req(`${B}/c1/messages`, reply_), c1), "/api/admin/member-messages/c1/messages", "POST", reply_],
["read", () => read(req(`${B}/c1/read`, undefined, "POST"), c1), "/api/admin/member-messages/c1/read", "POST"],
["start", () => start(req(`${B}/start`, { memberCode: "MY5", body: "yo", imageRefs: [] })), "/api/admin/member-messages/start", "POST", { memberCode: "MY5", body: "yo", imageRefs: [] }],
["preview", () => preview(req(`${B}/broadcasts/preview`, { target: { kind: "ALL" } })), "/api/admin/member-messages/broadcasts/preview", "POST", { target: { kind: "ALL" } }],
["broadcast", () => broadcast(req(`${B}/broadcasts`, { target: { kind: "ALL" }, subject: "s", body: "b", imageRefs: [] })), "/api/admin/member-messages/broadcasts", "POST", { target: { kind: "ALL" }, subject: "s", body: "b", imageRefs: [] }],
];
describe("admin messages BFF relays", () => {
it.each(cases)("%s forwards to mobile-api and returns its data", async (_n, call, path, method, body) => {
const res = await call();
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ fine: 1 });
expect(mocks.callMobileApi).toHaveBeenCalledWith(
path,
expect.objectContaining({ method, token: "jwt", ...(body === undefined ? {} : { body }) }),
);
});
it.each(cases)("%s returns 401 with no session and never calls upstream", async (_n, call) => {
mocks.getToken.mockResolvedValue(null);
expect((await call()).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
// mobile-api has no `code` field: the reason text is the whole error, so the relay derives the code.
it.each([
["EMPTY_TARGET", 400, 500],
["NOT_IN_NETWORK", 403, 500],
["MESSAGE_INVALID", 400, 500],
["MESSAGE_IMAGE_NOT_OWNED", 400, 500],
["MESSAGE_COMMIT_FAILED", 502, 500],
["MESSAGE_UPLOAD_FAILED", 502, 400],
])("derives code %s from the upstream reason text and answers %i", async (code, status, upstreamStatus) => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: `${code}: details`, status: upstreamStatus });
const res = await broadcast(req(`${B}/broadcasts`, { target: { kind: "LIST", codes: [] } }));
expect(res.status).toBe(status);
expect(await res.json()).toEqual({ error: code, code });
});
it("keeps 401 as 401, passes 404 through and adds no code to an unknown failure", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Session expired", status: 401 });
expect((await thread(req(`${B}/c1`), c1)).status).toBe(401);
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Conversation not found", status: 404 });
const nf = await thread(req(`${B}/c1`), c1);
expect(nf.status).toBe(404);
expect(await nf.json()).toEqual({ error: "Conversation not found" });
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Something odd", status: 500 });
expect((await (await thread(req(`${B}/c1`), c1)).json()).code).toBeUndefined();
});
it("rejects a path-like conversation id before any upstream call", async () => {
const res = await thread(req(`${B}/x`), { params: Promise.resolve({ uuid: "../admin" }) });
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects a non-JSON body on POST", async () => {
const bad = new Request(`${B}/start`, { method: "POST", body: "{nope" }) as unknown as NextRequest;
expect((await start(bad)).status).toBe(400);
});
});
describe("GET image stream", () => {
const ctx = (index: string) => ({ params: Promise.resolve({ uuid: "c1", messageUuid: "m1", index }) });
it("streams the bytes with no-store and the upstream content type", async () => {
const f = vi.fn().mockResolvedValue(new Response(new Uint8Array([1, 2, 3]), { status: 200, headers: { "content-type": "image/png" } }));
vi.stubGlobal("fetch", f);
const res = await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"));
expect(f.mock.calls[0][0]).toBe("http://up/api/admin/member-messages/c1/messages/m1/images/0");
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("image/png");
expect(res.headers.get("cache-control")).toBe("private, no-store");
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3]));
});
it("maps upstream 404 to 404 and rejects a bad index", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("", { status: 404 })));
expect((await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"))).status).toBe(404);
expect((await image(req(`${B}/c1/messages/m1/images/x`), ctx("x"))).status).toBe(400);
});
it("returns 401 with no session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"))).status).toBe(401);
});
});
describe("POST images (multipart pass-through)", () => {
const withFile = (file: File | null) =>
({ formData: async () => ({ get: () => file }) }) as unknown as NextRequest;
it("forwards a valid png and returns the ref", async () => {
const f = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ref: "messages/admin/a.png" }), { status: 200 }));
vi.stubGlobal("fetch", f);
const res = await upload(withFile(new File(["x"], "a.png", { type: "image/png" })));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ ref: "messages/admin/a.png" });
expect(f.mock.calls[0][0]).toBe("http://up/api/admin/member-messages/images");
expect(f.mock.calls[0][1].headers.Authorization).toBe("Bearer jwt");
});
it("rejects a non-image type, an oversize file and a missing file without calling upstream", async () => {
const f = vi.fn();
vi.stubGlobal("fetch", f);
expect((await upload(withFile(new File(["x"], "a.gif", { type: "image/gif" })))).status).toBe(400);
expect((await upload(withFile(new File([new Uint8Array(5 * 1024 * 1024 + 1)], "a.png", { type: "image/png" })))).status).toBe(400);
expect((await upload(withFile(null))).status).toBe(400);
expect(f).not.toHaveBeenCalled();
});
it("derives the code from an upstream reason text (no code field upstream)", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({ message: "MESSAGE_UPLOAD_FAILED" }), { status: 500 })));
const res = await upload(withFile(new File(["x"], "a.png", { type: "image/png" })));
expect(res.status).toBe(502);
expect(await res.json()).toEqual({ error: "MESSAGE_UPLOAD_FAILED", code: "MESSAGE_UPLOAD_FAILED" });
});
it("returns 401 with no session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await upload(withFile(null))).status).toBe(401);
});
});
// BABYBOO-54 B2: the list relay forwards sortBy/sortDir (param order not asserted).
describe("member-messages list sort forwarding", () => {
it("forwards sortBy and sortDir", async () => {
await list(req(`${B}?sortBy=time&sortDir=desc&page=0&size=20`));
const [url] = mocks.callMobileApi.mock.calls.at(-1)!;
const sp = new URLSearchParams(String(url).split("?")[1]);
expect(String(url).startsWith("/api/admin/member-messages?")).toBe(true);
expect([sp.get("sortBy"), sp.get("sortDir"), sp.get("page"), sp.get("size")]).toEqual(["time", "desc", "0", "20"]);
});
});
// BABYBOO-54 2.4: broadcasts relay forwards sortBy/sortDir.
describe("member-messages broadcasts sort forwarding", () => {
it("forwards sortBy and sortDir", async () => {
await broadcastList(req(`${B}/broadcasts?sortBy=read&sortDir=desc&page=0&size=20`));
const [url] = mocks.callMobileApi.mock.calls.at(-1)!;
const sp = new URLSearchParams(String(url).split("?")[1]);
expect(String(url).startsWith("/api/admin/member-messages/broadcasts?")).toBe(true);
expect([sp.get("sortBy"), sp.get("sortDir")]).toEqual(["read", "desc"]);
});
});
@@ -1,5 +0,0 @@
import type { NextRequest } from "next/server";
import { relay } from "@/app/lib/server/messagesProxy";
// POST -> mobile-api POST /api/admin/member-messages/start { memberCode, body, imageRefs }.
export const POST = (req: NextRequest) => relay(req, "/start", "POST", { body: true });
@@ -1,5 +0,0 @@
import type { NextRequest } from "next/server";
import { relay } from "@/app/lib/server/messagesProxy";
// GET -> mobile-api GET /api/admin/member-messages/unread-count.
export const GET = (req: NextRequest) => relay(req, "/unread-count", "GET");
@@ -1,59 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq() {
return new Request("http://localhost/api/admin/members/BB0100/change-history") as unknown as Parameters<typeof GET>[0];
}
const ctx = { params: Promise.resolve({ memberCode: "BB0100" }) };
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/members/[memberCode]/change-history", () => {
it("forwards the member code and admin JWT and passes the upstream JSON through", async () => {
const data = [
{
at: "2026-10-29T14:31:58+08:00",
by: "SYS",
changes: [{ field: "memberRank", oldValue: "SQUIRREL", newValue: "GIRAFFE" }],
},
];
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data });
const res = await GET(getReq(), ctx);
expect(res.status).toBe(200);
expect(await res.json()).toEqual(data);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/change-history", {
token: "jwt-abc",
});
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq(), ctx);
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes an upstream 404 on instead of masking it", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 404, error: "Member not found" });
const res = await GET(getReq(), ctx);
expect(res.status).toBe(404);
expect(await res.json()).toMatchObject({ error: "Member not found" });
});
it("returns 401 when the upstream session has expired", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 401, expired: true, error: "expired" });
const res = await GET(getReq(), ctx);
expect(res.status).toBe(401);
});
});
@@ -1,20 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminMemberChangeEntry } from "@/app/lib/types";
// GET -> /api/admin/members/{memberCode}/change-history (read-only).
export async function GET(_req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { memberCode } = await ctx.params;
const result = await callMobileApi<AdminMemberChangeEntry[]>(
`/api/admin/members/${encodeURIComponent(memberCode)}/change-history`,
{ token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,72 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/members/BB0100/change-sponsor", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
const ctx = { params: Promise.resolve({ memberCode: "BB0100" }) };
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/members/[memberCode]/change-sponsor", () => {
it("forwards the new sponsor and trimmed reason with the admin JWT", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { success: true } });
const res = await POST(postReq({ newSponsorCode: "BB0001", reason: " Wrong referral code " }), ctx);
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/change-sponsor", {
method: "POST",
body: { newSponsorCode: "BB0001", reason: "Wrong referral code" },
token: "jwt-abc",
});
});
it("rejects a missing sponsor or a blank or over-long reason with 400 and forwards nothing", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
expect((await POST(postReq({ reason: "x" }), ctx)).status).toBe(400);
const blank = await POST(postReq({ newSponsorCode: "BB0001", reason: "" }), ctx);
expect(blank.status).toBe(400);
expect(await blank.json()).toEqual({ error: "A reason is required." });
const long = await POST(postReq({ newSponsorCode: "BB0001", reason: "x".repeat(256) }), ctx);
expect(long.status).toBe(400);
expect(await long.json()).toEqual({ error: "The reason must be 255 characters or fewer." });
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes an upstream refusal through", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The Rank & referral module (BO_RANK_REFERRAL) is required." });
const res = await POST(postReq({ newSponsorCode: "BB0001", reason: "x" }), ctx);
expect(res.status).toBe(403);
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq({ newSponsorCode: "BB0001", reason: "x" }), ctx);
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -1,29 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { checkCorrectionReason } from "@/app/lib/correctionReason";
// POST -> /api/admin/members/{memberCode}/change-sponsor (referral / placement correction).
// Mutation lives on POST only. The actor is derived from the bb_admin JWT server-side and a reason
// is required (BABYBOO-43). A cycle-creating move is rejected upstream with 400, and a caller
// without BO_RANK_REFERRAL with 403; both pass through.
export async function POST(req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { memberCode } = await ctx.params;
const body = (await req.json().catch(() => ({}))) as { newSponsorCode?: string; reason?: unknown };
if (!body.newSponsorCode?.trim()) {
return NextResponse.json({ error: "A new sponsor code is required." }, { status: 400 });
}
const reason = checkCorrectionReason(body.reason);
if (!reason.ok) return NextResponse.json({ error: reason.error }, { status: 400 });
const result = await callMobileApi<{ success: boolean }>(
`/api/admin/members/${encodeURIComponent(memberCode)}/change-sponsor`,
{ method: "POST", body: { newSponsorCode: body.newSponsorCode, reason: reason.reason }, token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,77 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/members/BB0100/correct-rank", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
const ctx = { params: Promise.resolve({ memberCode: "BB0100" }) };
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/members/[memberCode]/correct-rank", () => {
it("validates and forwards the rank and trimmed reason with the admin JWT", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { success: true } });
const res = await POST(postReq({ newRank: "squirrel", reason: " Set wrongly by admin " }), ctx);
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/correct-rank", {
method: "POST",
body: { newRank: "SQUIRREL", reason: "Set wrongly by admin" },
token: "jwt-abc",
});
});
it("rejects a missing or unknown rank with 400 and forwards nothing", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
expect((await POST(postReq({ reason: "x" }), ctx)).status).toBe(400);
expect((await POST(postReq({ newRank: "GOD", reason: "x" }), ctx)).status).toBe(400);
// remove-legacy-member-ranks: the old MLM ranks no longer exist.
for (const legacy of ["S1", "S2", "S3", "EM", "BP"]) {
expect((await POST(postReq({ newRank: legacy, reason: "x" }), ctx)).status).toBe(400);
}
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("rejects a blank or over-long reason with 400 and forwards nothing", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const blank = await POST(postReq({ newRank: "SQUIRREL", reason: " " }), ctx);
expect(blank.status).toBe(400);
expect(await blank.json()).toEqual({ error: "A reason is required." });
const missing = await POST(postReq({ newRank: "SQUIRREL" }), ctx);
expect(missing.status).toBe(400);
const long = await POST(postReq({ newRank: "SQUIRREL", reason: "x".repeat(256) }), ctx);
expect(long.status).toBe(400);
expect(await long.json()).toEqual({ error: "The reason must be 255 characters or fewer." });
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq({ newRank: "SQUIRREL", reason: "x" }), ctx);
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -1,32 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { checkCorrectionReason } from "@/app/lib/correctionReason";
// POST -> /api/admin/members/{memberCode}/correct-rank (rank correction, I4; BABYBOO-43).
// Mutation lives on POST only. The actor is derived from the bb_admin JWT server-side
// (mobile-api); the rank is validated against the shared enum upstream and a reason is required.
// A caller without the BO_RANK_REFERRAL module is refused upstream with 403 and that passes through.
const KNOWN_RANKS = ["NA", "M", "OTTER", "SQUIRREL", "GIRAFFE"];
export async function POST(req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { memberCode } = await ctx.params;
const body = (await req.json().catch(() => ({}))) as { newRank?: string; reason?: unknown };
const newRank = body.newRank?.trim().toUpperCase();
if (!newRank || !KNOWN_RANKS.includes(newRank)) {
return NextResponse.json({ error: "A valid rank is required." }, { status: 400 });
}
const reason = checkCorrectionReason(body.reason);
if (!reason.ok) return NextResponse.json({ error: reason.error }, { status: 400 });
const result = await callMobileApi<{ success: boolean }>(
`/api/admin/members/${encodeURIComponent(memberCode)}/correct-rank`,
{ method: "POST", body: { newRank, reason: reason.reason }, token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,35 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq() {
return new Request("http://localhost/api/admin/members/BB0100/edit-initialize") as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/members/[memberCode]/edit-initialize", () => {
it("forwards the member code and admin JWT", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { nationalities: [], banks: [] } });
const res = await GET(getReq(), { params: Promise.resolve({ memberCode: "BB0100" }) });
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100/edit-initialize", {
token: "jwt-abc",
});
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(getReq(), { params: Promise.resolve({ memberCode: "BB0100" }) });
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -1,20 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminEditInitialize } from "@/app/lib/types";
// GET -> /api/admin/members/{memberCode}/edit-initialize (geo cascade + nationality/bank options).
export async function GET(_req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { memberCode } = await ctx.params;
const result = await callMobileApi<AdminEditInitialize>(
`/api/admin/members/${encodeURIComponent(memberCode)}/edit-initialize`,
{ token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,20 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminSponsorHistoryPage } from "@/app/lib/types";
// GET -> /api/admin/members/{memberCode}/placement-history (read-only).
export async function GET(_req: NextRequest, ctx: { params: Promise<{ memberCode: string }> }) {
const token = await getToken();
if (!token) return unauthorized();
const { memberCode } = await ctx.params;
const result = await callMobileApi<AdminSponsorHistoryPage>(
`/api/admin/members/${encodeURIComponent(memberCode)}/placement-history`,
{ token },
);
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,90 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, PUT } from "./route";
function getReq(memberCode: string) {
const req = new Request(`http://localhost/api/admin/members/${memberCode}`) as unknown as Parameters<typeof GET>[0];
const ctx = { params: Promise.resolve({ memberCode }) };
return { req, ctx };
}
function putReq(memberCode: string, body: unknown) {
const req = new Request(`http://localhost/api/admin/members/${memberCode}`, {
method: "PUT",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof PUT>[0];
const ctx = { params: Promise.resolve({ memberCode }) };
return { req, ctx };
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/members/[memberCode]", () => {
it("forwards the member code and admin JWT to GET /api/admin/members/{memberCode}", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { memberCode: "BB0100" } });
const { req, ctx } = getReq("BB0100");
const res = await GET(req, ctx);
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100", { token: "jwt-abc" });
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const { req, ctx } = getReq("BB0100");
const res = await GET(req, ctx);
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes through a genuine upstream 404 so the page shows its not-found state", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Member not found", status: 404 });
const { req, ctx } = getReq("NOPE");
const res = await GET(req, ctx);
expect(res.status).toBe(404);
});
});
describe("PUT /api/admin/members/[memberCode]", () => {
it("forwards the edit body and admin JWT to PUT /api/admin/members/{memberCode}", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { success: true } });
const body = { name: "AINA TAN", email: "aina@example.com" };
const { req, ctx } = putReq("BB0100", body);
const res = await PUT(req, ctx);
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/members/BB0100", {
method: "PUT",
body,
token: "jwt-abc",
});
});
it("passes through a 400 validation error from upstream", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({
ok: false,
error: "Age should be greater than 18 years.",
status: 400,
});
const { req, ctx } = putReq("BB0100", { name: "AINA TAN" });
const res = await PUT(req, ctx);
expect(res.status).toBe(400);
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const { req, ctx } = putReq("BB0100", {});
const res = await PUT(req, ctx);
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -1,36 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { 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);
}
@@ -1,35 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq() {
return new Request("http://localhost/api/admin/members/BB0100/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();
});
});
@@ -1,20 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { 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);
}
@@ -1,112 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, 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" });
});
});
@@ -1,63 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery";
import type { 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);
}
@@ -1,50 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
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();
});
});
@@ -1,27 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { 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);
}
@@ -1,17 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { 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);
}
@@ -1,60 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { 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]);
});
});
@@ -1,5 +0,0 @@
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"]);
@@ -1,21 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("GET /api/admin/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");
});
});
@@ -1,36 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(search = "") {
return new Request(`http://localhost/api/admin/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" });
});
});
@@ -1,6 +0,0 @@
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"]);
@@ -1,21 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
beforeEach(() => {
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} });
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("GET /api/admin/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");
});
});
@@ -1,48 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(search = "") {
return new Request(`http://localhost/api/admin/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);
});
});
@@ -1,5 +0,0 @@
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"]);
@@ -1,57 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(search = "") {
return new Request(`http://localhost/api/admin/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" });
});
});
@@ -1,30 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { 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);
}
@@ -1,45 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
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"]);
});
});
@@ -1,10 +0,0 @@
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);
});
});
@@ -1,47 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/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();
});
});
@@ -1,35 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { 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);
}
@@ -1,48 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq() {
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");
});
});
@@ -1,20 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { 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);
}
@@ -1,59 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(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" });
});
});
@@ -1,32 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import { paging, SORT, 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);
}
@@ -1,77 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import * 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();
});
});
@@ -1,21 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { 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);
}
@@ -1,116 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(search = "") {
return new Request(
`http://localhost/api/admin/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();
});
});
@@ -1,42 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { 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);
}
@@ -1,47 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { POST } from "./route";
function postReq(body: unknown) {
return new Request("http://localhost/api/admin/withdrawal/approve", {
method: "POST",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/admin/withdrawal/approve", () => {
it("requires a numeric uuid", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await POST(postReq({ uuid: "not-a-number" }));
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the uuid 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: "C" } });
const res = await POST(postReq({ uuid: "555" }));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/withdrawal/approve", {
method: "POST",
body: { uuid: "555" },
token: "jwt-abc",
});
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(postReq({ uuid: "555" }));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
});
@@ -1,32 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { AdminWithdrawalRow } from "@/app/lib/types";
// POST -> /api/admin/withdrawal/approve { uuid } (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");
}
// uuid is a Snowflake id carried as a string (it exceeds JS's safe-integer range).
const uuid = (body as { uuid?: unknown } | null)?.uuid;
if (typeof uuid !== "string" || !/^\d+$/.test(uuid)) {
return badRequest("Parameter \"uuid\" is required");
}
const result = await callMobileApi<AdminWithdrawalRow>("/api/admin/withdrawal/approve", {
method: "POST",
body: { uuid },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,99 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, PUT } from "./route";
function getReq() {
return new Request("http://localhost/api/admin/withdrawal/config") as unknown as Parameters<typeof GET>[0];
}
function putReq(body: unknown) {
return new Request("http://localhost/api/admin/withdrawal/config", {
method: "PUT",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof PUT>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/withdrawal/config", () => {
it("forwards the admin JWT and returns the config", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const config = {
minAmount: 50,
maxAmount: null,
increment: null,
feePercent: 2,
feeCapAmount: null,
weeklyCutoffDay: 5,
weeklyCutoffTime: "17:00:00",
nextCutoff: "2026-10-02T17:00:00",
doneBy: "admin",
};
mocks.callMobileApi.mockResolvedValue({ ok: true, data: config });
const res = await GET(getReq());
expect(res.status).toBe(200);
expect(await res.json()).toEqual(config);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/withdrawal/config", { 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);
});
});
describe("PUT /api/admin/withdrawal/config", () => {
it("forwards the body and the admin JWT", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const body = {
minAmount: 50,
maxAmount: null,
increment: null,
feePercent: 2,
feeCapAmount: null,
weeklyCutoffDay: null,
weeklyCutoffTime: null,
};
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ...body, nextCutoff: null, doneBy: "admin" } });
const res = await PUT(putReq(body));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/withdrawal/config", {
method: "PUT",
body,
token: "jwt-abc",
});
});
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await PUT(putReq({}));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("propagates a validation refusal (e.g. CONFIG_MAX_BELOW_MIN) as a 400 error response", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "CONFIG_MAX_BELOW_MIN", status: 400 });
const res = await PUT(putReq({ minAmount: 100, maxAmount: 50 }));
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: "CONFIG_MAX_BELOW_MIN" });
});
});
@@ -1,37 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
import type { WithdrawalConfig } from "@/app/lib/types";
// GET/PUT -> /api/admin/withdrawal/config (BABYBOO-13, Task 4). GET is read-only (BO_WALLET
// gated upstream); PUT is a mutation and never goes out on GET. Mirrors the withdrawal/list route.
export async function GET(_req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApi<WithdrawalConfig>("/api/admin/withdrawal/config", { 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();
let body: unknown;
try {
body = await req.json();
} catch {
return badRequest("Invalid request body");
}
const result = await callMobileApi<WithdrawalConfig>("/api/admin/withdrawal/config", {
method: "PUT",
body,
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,101 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
function getReq(search = "") {
return new Request(`http://localhost/api/admin/withdrawal/list${search}`) as unknown as Parameters<typeof GET>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("GET /api/admin/withdrawal/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/withdrawal/list?page=1&size=10",
{ token: "jwt-abc" },
);
});
it("forwards the cycle filter when supplied", 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=0&size=10&cycle=2026-10-02T17%3A00%3A00"));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith(
"/api/admin/withdrawal/list?page=0&size=10&cycle=2026-10-02T17%3A00%3A00",
{ token: "jwt-abc" },
);
});
it("omits the cycle param entirely when not supplied", 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=0&size=10"));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/withdrawal/list?page=0&size=10", {
token: "jwt-abc",
});
});
it("forwards status and member, URL-encoded, when present", 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=0&size=10&status=ALL&member=IRENE%20LIM"));
expect(res.status).toBe(200);
const path = mocks.callMobileApi.mock.calls[0][0] as string;
const q = new URL(path, "http://x").searchParams;
expect(q.get("status")).toBe("ALL");
expect(q.get("member")).toBe("IRENE LIM");
expect(path).toContain("member=IRENE%20LIM");
});
it("omits status and member when absent", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({
ok: true,
data: { content: [], number: 0, size: 10, totalElements: 0, totalPages: 0 },
});
await GET(getReq("?page=0&size=10"));
const path = mocks.callMobileApi.mock.calls[0][0] as string;
expect(path).not.toContain("status=");
expect(path).not.toContain("member=");
});
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");
});
});
Loaded 100 of 1304 files, more files were not shown because too many files have changed in this diff. Show more