diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index a929a79..0697f4b 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -31,7 +31,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 6. Admin portal -- [ ] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0. +- [x] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0. - Scope: `solvway-admin-portal/**` - [ ] 6.2 Add the `/forgot-password` page (public, linked from login) and its route handler calling `/api/admin/auth/forgot-password`, showing the fixed message for any outcome; make the users form refuse self-deactivation and show duplicate-username and lock-out errors from the API. Tests first (vitest) for each portal-visible scenario in the specs. Verify: `npm run lint && npm run build && npm test` exit 0. - Scope: `solvway-admin-portal/**` diff --git a/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md b/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md index 1f1e5a0..5485b6d 100644 --- a/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md +++ b/solvway-admin-portal/.claude/skills/run-solvway-admin-portal/SKILL.md @@ -1,6 +1,6 @@ --- name: run-solvway-admin-portal -description: Build, run, and drive solvway-admin-portal (babyboo Back Office). Use when asked to start the app, run its dev server or tests, or take a screenshot of / interact with the running UI. +description: Build, run, and drive solvway-admin-portal (Co-Lite Back Office). Use when asked to start the app, run its dev server or tests, or take a screenshot of / interact with the running UI. --- All paths below are relative to `solvway-admin-portal/`. diff --git a/solvway-admin-portal/.env.example b/solvway-admin-portal/.env.example index 9041ce4..2cd469a 100644 --- a/solvway-admin-portal/.env.example +++ b/solvway-admin-portal/.env.example @@ -1,5 +1,5 @@ # ── Mobile API (BFF target) ─────────────────────────────────────────── -# Base URL of babyboo's solvway-mobile-api, no trailing slash. +# Base URL of solvway-mobile-api, no trailing slash. # Supplied per environment; there is no sensible default. MOBILE_API_BASE_URL= @@ -10,4 +10,4 @@ MOBILE_API_KEY= # ── Session ─────────────────────────────────────────────────────────── # Name of the httpOnly cookie that stores the admin JWT. -SESSION_COOKIE_NAME=bb_admin +SESSION_COOKIE_NAME=colite_admin diff --git a/solvway-admin-portal/Dockerfile b/solvway-admin-portal/Dockerfile index d5ecf6d..b17ac1f 100644 --- a/solvway-admin-portal/Dockerfile +++ b/solvway-admin-portal/Dockerfile @@ -5,7 +5,6 @@ FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ -COPY vendor/ ./vendor/ RUN npm ci # A High or Critical advisory in a runtime dependency fails the image (F45). Dev tooling is not shipped, # so it is excluded. Moderate advisories do not block; review them with a full `npm audit`. diff --git a/solvway-admin-portal/README.md b/solvway-admin-portal/README.md index ec781e0..9eeb3f1 100644 --- a/solvway-admin-portal/README.md +++ b/solvway-admin-portal/README.md @@ -1,206 +1,26 @@ -# Back-Office Template — babyboo.my +# Co-Lite Admin Portal -> **Migration in progress.** This module is being converted from a Vite SPA to a Next.js App -> Router project (see `openspec/changes/add-admin-portal-auth`). `app/` currently holds only a -> placeholder shell; the real pages, components and services below still live under `src/` — -> specifically `src/legacy-pages/` (renamed from `src/pages/` because Next.js reserves that name -> for its own Pages Router) — pending a later change that ports them into `app/*/page.tsx` with -> `react-router` calls rewired to `next/navigation`. Everything in this README describing routes, -> the mock-data architecture and theming still describes that `src/` tree. +Next.js 16 admin portal for Co-Lite. Screens call the JSON admin APIs (`/api/admin/**`) in `mobile-api` through server-side route handlers. -A reusable admin/back-office front end for MLM (multi-level marketing) clients. It ships -against mock data behind an API-shaped service layer, so a client project can swap in a real -backend without touching any page or component code. +## Run -**Currently skinned for babyboo.my** — baby & maternity retail, competing with Medela, Momcozy, -Kinderkraft and Hamilton. The audience is sleep-deprived, time-poor, highly selective parents, so -decisions are ranked clarity → speed → trust. The look is deliberately warm and soft-edged rather -than clinical: cream page, warm neutrals, brand brown `#6E3E17` with a gold `#F2BC57` accent, and a -1rem radius so nothing has a sharp corner. - -## Stack - -- [Next.js 16](https://nextjs.org/) (App Router, `output: "standalone"`) — build tool and server -- [React 19](https://react.dev/) + TypeScript (strict mode) -- [Tailwind CSS 3](https://tailwindcss.com/) via PostCSS + `tailwind.config.ts` — matches - `solvway-customer-portal`'s wiring -- [Sass](https://sass-lang.com/) — token maps and mixins in `src/styles/` (pending port into - `app/globals.css`, which currently carries a plain-CSS transliteration of the same tokens) -- [shadcn/ui](https://ui.shadcn.com/) — owned component source, themed with CSS variables -- [Recharts](https://recharts.org/) via shadcn's `chart` wrapper — dashboard charts -- [TanStack Table](https://tanstack.com/table) — data tables -- [lucide-react](https://lucide.dev/) — icons -- [react-router-dom v7](https://reactrouter.com/) — still a dependency for the not-yet-ported - `src/legacy-pages/` tree; removed once that tree is rewired to `next/navigation` -- [Vitest](https://vitest.dev/) + [React Testing Library](https://testing-library.com/react) — tests - -## Getting Started +Needs Node 24 (see `.nvmrc`). ```bash -npm install -npm run dev # next dev --port 3001 -npm test # run the full test suite (Vitest, run once) -npm run test:watch # run tests in watch mode -npm run build # next build (type-checks + production build) -npm start # next start --port 3001, after a build - -python3 scripts/check-contrast.py # verify token contrast in both themes +cp .env.example .env.local # then fill in the values below +npm ci +npm run dev # http://localhost:3001 ``` -### Auth +| Variable | Purpose | +| --- | --- | +| `MOBILE_API_BASE_URL` | Base URL of `mobile-api` | +| `MOBILE_API_KEY` | API key sent to `mobile-api` | +| `SESSION_SECRET` | Secret used to seal the session cookie | +| `SESSION_COOKIE_NAME` | Session cookie base name (default `colite_admin`) | -Login is no longer mocked. `/login` posts to the same-origin `/api/auth/login` route handler, -which proxies `solvway-mobile-api` (`app/lib/server/mobileApi.ts`) and sets an httpOnly session -cookie server-side. Signing in requires: - -- `MOBILE_API_BASE_URL` and `MOBILE_API_KEY` set (see `.env.example`), pointing at a reachable - `solvway-mobile-api` instance. -- A real `UserType.A` account in that instance's services-system. - -Without a configured Mobile API, `/login` still renders, but submitting the form reports "Mobile -API is not configured" — there is no local/offline demo login anymore. - -Visiting any other route while unauthenticated redirects back to `/login`; logging out clears the -session and returns you there as well. - -## Screen Inventory - -| Route | Page | Notes | -|---|---|---| -| `/login` | Login | Email/password with a password-reveal toggle; inline error on invalid credentials | -| `/` | Dashboard | Live KPI tiles (members, settled revenue/orders, rewards; Malaysia-time month), 12-month revenue and member-growth charts, revenue by channel, rank/status mix, rewards by type, top-earner leaderboard | -| `/members` | Members | Sortable, faceted, URL-synced member table with column visibility and CSV export | -| `/members/:id` | Member Detail | Identity header, performance strip, tabs for Sales · Commissions · Downline | -| `/reports` | Reports | Live Sales (settled orders) and Rewards tabs, Malaysia-time period presets + date range, paged, period totals, full-result-set CSV export | -| `/network` | Network | Genealogy as an indented tree or a top-down chart, with search that expands ancestors and highlights matches | - -Navigation is a **collapsible sidebar with up to three levels**: it collapses to an icon rail on -desktop (persisted per browser) and becomes an overlay drawer below `lg`. Every leaf resolves to a -real view — `Members → By rank → Diamond` applies `?rank=Diamond`, the Reports children select -`?tab=` — so none of them are decorative. - -[`src/components/app/nav-config.ts`](src/components/app/nav-config.ts) is the **contract a backend -menu endpoint would return**: plain `label` / `to` / `children` / `isDefault` data, with the icon as -the only client-side concern. `nav-config.test.ts` encodes the invariants such an endpoint must -satisfy (leaf-xor-group, depth cap, real routes, unique targets, one default per group), so a -backend implementation can be validated against the same rules the UI relies on. - -## Design Standard - -**[`docs/design/DASHBOARD-STANDARD.md`](docs/design/DASHBOARD-STANDARD.md) is authoritative.** It -defines the tokens, layout grid, KPI and chart specs, required data states, accessibility floor -(WCAG 2.1 AA) and the anti-patterns. Read it before adding a screen. Where it and a component -disagree, the component is wrong. - -## Mock-Data Architecture - -Everything under `src/services/*` is written to look and behave like a real API client: every -function is `async`, returns plain data (no framework types leak out), and pagination, filtering -and **sorting** happen the same way a backend would do them. The Dashboard and Reports are live -(`app/lib/services/adminDashboard.ts` -> BFF -> mobile-api aggregate reads); `src/services/api.ts` holds shared helpers (pagination, sorting, an -artificial network delay). - -**Pages only call functions from the other -`src/services/*` modules. This is the intended swap point: to connect a real backend, replace the -bodies of these service functions with `fetch` calls that return the same shapes (see -`src/types/index.ts`), and no page or component needs to change. - -``` -src/ - components/ - app/ # two-level sidebar + nav config - ui/ # shadcn primitives + DataTable, states, chart skeletons - dashboard/ # KPI tile, chart card (chart + its accessible table) - genealogy/ # tree view and org chart - styles/ - _variables.scss # $palettes (light + dark), breakpoints, layout, z-index - _mixins.scss # respond-to, focus-ring, tap-target, brand gradient - index.scss # emits the token blocks from the maps + base layer - tailwind.css # Tailwind entry + @theme (kept as CSS on purpose) - lib/ - theme.tsx # light/dark provider, persists to localStorage - utils.ts # cn() - services/ - api.ts # shared mock helpers (pagination, sorting, delay) - period.ts # month labels - auth.ts # login/logout/session — swap point - members.ts # list/detail/facets/stats — swap point - network.ts # genealogy tree — swap point -``` - -## Theming - -Colour lives in Sass maps in [`src/styles/_variables.scss`](src/styles/_variables.scss), emitted as -CSS custom properties by `index.scss` and exposed to Tailwind via `@theme inline` in `tailwind.css`. -**No component contains a colour literal.** - -The babyboo palette is brand brown `#6E3E17` with a gold `#F2BC57` accent on a cream page, plus warm -neutrals and a warm-espresso dark mode (not slate). - -**One thing to know about the gold:** `#F2BC57` is 1.73:1 against white, so it can only ever be a -*filled surface* carrying `--accent-foreground` text — never text, a thin indicator, or a chart -series, all of which would be invisible in light mode. Anything in the accent family that must carry -meaning uses `--accent-strong` (`#9A6212`, 5.08:1). That is why the accent is absent from the chart -ramp. - -Both themes live in the same map, so a token cannot be added to light and forgotten in dark. - -To re-skin for a client: - -1. Edit `$palettes` in `src/styles/_variables.scss` — primary, accent, chart ramp, radius. -2. Swap the font `` (was `index.html`, now belongs in `app/layout.tsx` — see the Migration - note above) and the `--font-*` tokens (now in `app/globals.css`, ported from - `src/styles/tailwind.css`). -3. Replace the wordmark in `src/components/app/app-sidebar.tsx`. -4. Run `python3 scripts/check-contrast.py`. - -### Fonts - -Headings are **Google Sans**, body and numerals are **Inter** — two families, no monospace. Numerals -use Inter's own tabular figures (`.tabular`), so columns still align while avoiding the technical -register of monospace digits, and it saves a font request. - -Fonts were linked from `index.html`'s `` tags before the Next.js conversion; the placeholder -`app/layout.tsx` does not yet re-add them (Task 6 restores the font ``s or switches to -`next/font`). If Google Sans must be self-hosted (offline builds, or a licensed -variant), `src/styles/index.scss` has a commented `@font-face` block — drop the `woff2` files into -`public/fonts/` and uncomment; the heading stack already requests the family first. DM Sans is the -fallback if it fails to load. - -Light is the default; dark is opt-in via the header toggle and persisted per browser. Note that -`--border` (dividers, decorative) and `--input` (form-control boundaries, must clear 3:1) are -deliberately different values — see the standard's §2. - -`scripts/check-contrast.py` verifies all of the above (both themes, exits non-zero on regression). -Run it after any palette edit. - -## Testing - -143 tests across 29 files (`npx vitest run`), covering the ported Next.js app under `app/`. Server-only -modules (`app/lib/server/mobileApi.ts`, the `/api/auth/*` route handlers) run under jsdom because -`vitest.config.ts` aliases `server-only` to `test/stub-empty.ts`. Client components mock -`apiGet`/`apiPost` (`app/lib/clientApi.ts`) rather than hitting a network, so UI tests don't depend -on `solvway-mobile-api` being reachable. - -Charts are asserted through the accessible data table that every chart is required to ship -(standard §6) rather than by measuring SVG — so no chart library gets stubbed, and the assertions -check real figures. - -`vitest.setup.ts` (repo root) stubs `matchMedia`, `ResizeObserver`, and the Pointer Events APIs -that Radix needs and jsdom lacks. - -## Known Issues - -- The production bundle is a single ~958 kB (288 kB gzip) chunk. That is down from 2.62 MB - (797 kB gzip) under antd, but a client project with stricter budgets should still code-split - with dynamic `import()`. -- **`sass-embedded` is pinned to 1.77.8 via an `overrides` entry in `package.json`, and removing it - will hang the build on macOS 13.** Vite auto-installs `sass-embedded` as an optional peer; from - roughly 1.83 its bundled Dart VM requires macOS 14+ and aborts with - `VM initialization failed`. Because that happens during the compiler handshake, the build hangs - rather than failing, which makes it look like an infinite loop. On macOS 14+ the pin is harmless - and can be dropped. -- In-browser visual verification across all breakpoints has not been automated. The contrast - floor is checked by script; layout at 375/768/1024/1440px still needs a human or a - browser-driver pass. +## Scripts +- `npm run build` / `npm start` production build and server (port 3001) +- `npm run lint` +- `npm test` diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts deleted file mode 100644 index 6217054..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq() { - return new Request("http://localhost/api/admin/company-accounts/MY/MYHQ00002/deactivate", { - method: "POST", - }) as unknown as Parameters[0]; -} -function ctx(prefix: string, memberCode: string) { - return { params: Promise.resolve({ prefix, memberCode }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts/[prefix]/[memberCode]/deactivate", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards to POST /api/admin/company-accounts/{prefix}/{memberCode}/deactivate", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { prefix: "MY", memberCode: "MYHQ00002", active: "N" } }); - - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/company-accounts/MY/MYHQ00002/deactivate", - { method: "POST", token: "jwt-abc" }, - ); - expect(res.status).toBe(200); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "not found", status: 404 }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(404); - }); - - // deactivate returns an empty 200 downstream (void controller). NextResponse.json(undefined) - // would 500 — the route must return a safe ok body. (Caught in live Part D verification.) - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts deleted file mode 100644 index 85c2c61..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/deactivate/route.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; - -// POST -> /api/admin/company-accounts/{prefix}/{memberCode}/deactivate -// (add-admin-company-account-crud, Part C). Drops the account from the weighted split; the -// member, its network_tree row and any existing downline are left untouched — there is no hard -// delete. A mutation, so always POST, never a GET. - -export async function POST( - _req: NextRequest, - ctx: { params: Promise<{ prefix: string; memberCode: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix, memberCode } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}/${encodeURIComponent(memberCode)}/deactivate`, - { method: "POST", token }, - ); - if (!result.ok) return errorResponse(result); - // deactivate returns an empty 200 downstream (void); avoid NextResponse.json(undefined) (500). - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts deleted file mode 100644 index 519230d..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq() { - return new Request("http://localhost/api/admin/company-accounts/MY/MYHQ00002/reactivate", { - method: "POST", - }) as unknown as Parameters[0]; -} -function ctx(prefix: string, memberCode: string) { - return { params: Promise.resolve({ prefix, memberCode }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts/[prefix]/[memberCode]/reactivate", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards to POST /api/admin/company-accounts/{prefix}/{memberCode}/reactivate", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { prefix: "MY", memberCode: "MYHQ00002", active: "Y" } }); - - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/company-accounts/MY/MYHQ00002/reactivate", - { method: "POST", token: "jwt-abc" }, - ); - expect(res.status).toBe(200); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "not found", status: 404 }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(404); - }); - - // reactivate returns an empty 200 downstream (void controller); the route must not 500 on it. - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await POST(postReq(), ctx("MY", "MYHQ00002")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts deleted file mode 100644 index 38b6198..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/[memberCode]/reactivate/route.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; - -// POST -> /api/admin/company-accounts/{prefix}/{memberCode}/reactivate -// (add-admin-company-account-crud, Part C). Restores the account to the weighted split. A -// mutation, so always POST, never a GET. - -export async function POST( - _req: NextRequest, - ctx: { params: Promise<{ prefix: string; memberCode: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix, memberCode } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}/${encodeURIComponent(memberCode)}/reactivate`, - { method: "POST", token }, - ); - if (!result.ok) return errorResponse(result); - // reactivate returns an empty 200 downstream (void); avoid NextResponse.json(undefined) (500). - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts deleted file mode 100644 index 54eeab8..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq() { - return new Request("http://localhost/api/admin/company-accounts/MY") as unknown as Parameters< - typeof GET - >[0]; -} -function ctx(prefix: string) { - return { params: Promise.resolve({ prefix }) }; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/company-accounts/[prefix]", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq(), ctx("MY")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT to GET /api/admin/company-accounts/{prefix} and returns the rows", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const rows = [ - { - prefix: "MY", - memberCode: "MYHQ00002", - name: "HQ Two", - weight: 50, - active: "Y", - configVersion: 3, - directDownline: 2, - allocatedCount: 10, - }, - ]; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: rows }); - - const res = await GET(getReq(), ctx("MY")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts/MY", { - token: "jwt-abc", - }); - expect(res.status).toBe(200); - expect(await res.json()).toEqual(rows); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "boom", status: 400 }); - const res = await GET(getReq(), ctx("MY")); - expect(res.status).toBe(400); - expect((await res.json()).error).toBe("boom"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts deleted file mode 100644 index dbe6507..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/[prefix]/route.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { CompanyAccountRow } from "@/app/lib/types"; - -// GET -> /api/admin/company-accounts/{prefix} (add-admin-company-account-crud, Part C): the -// company accounts configured for one registration country. Read-only — no side effect on GET -// (Next.js prefetch-safe). - -export async function GET(_req: NextRequest, ctx: { params: Promise<{ prefix: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { prefix } = await ctx.params; - const result = await callMobileApi( - `/api/admin/company-accounts/${encodeURIComponent(prefix)}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts b/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts deleted file mode 100644 index e1d0fc0..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/route.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST, PUT } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/company-accounts", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -function putReq(body: unknown) { - return new Request("http://localhost/api/admin/company-accounts", { - method: "PUT", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/company-accounts", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("requires prefix, memberCode, name and a weight", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const body of [ - { memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }, - { prefix: "MY", name: "HQ Two", weight: 50 }, - { prefix: "MY", memberCode: "MYHQ00002", weight: 50 }, - { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two" }, - {}, - ]) { - const res = await POST(postReq(body)); - expect(res.status).toBe(400); - } - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects an email without a password (and vice versa) without forwarding", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const base = { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }; - const res1 = await POST(postReq({ ...base, email: "hq2@babyboo.my" })); - expect(res1.status).toBe(400); - const res2 = await POST(postReq({ ...base, password: "Qweqwe123" })); - expect(res2.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT and full body to POST /api/admin/company-accounts", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const body = { prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }; - mocks.callMobileApi.mockResolvedValue({ - ok: true, - data: { memberId: "1", loginRequested: false, credentialCreated: false }, - }); - - const res = await POST(postReq(body)); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts", { - method: "POST", - body, - token: "jwt-abc", - }); - expect(res.status).toBe(200); - expect((await res.json()).loginRequested).toBe(false); - }); - - it("forwards a duplicate-code 4xx as-is with the downstream message", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ - ok: false, - error: "member_code already in use", - status: 409, - }); - - const res = await POST( - postReq({ prefix: "MY", memberCode: "MYHQ00002", name: "HQ Two", weight: 50 }), - ); - - expect(res.status).toBe(409); - expect((await res.json()).error).toBe("member_code already in use"); - }); -}); - -describe("PUT /api/admin/company-accounts", () => { - it("returns 401 when there is no session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await PUT(putReq({ prefix: "MY", memberCode: "MYHQ00002", weight: 75 })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("requires prefix and memberCode to locate the row", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const body of [{ memberCode: "MYHQ00002", weight: 75 }, { prefix: "MY", weight: 75 }, {}]) { - const res = await PUT(putReq(body)); - expect(res.status).toBe(400); - } - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the admin JWT and full body to PUT /api/admin/company-accounts", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const body = { prefix: "MY", memberCode: "MYHQ00002", weight: 75, active: "Y" }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ...body, name: "HQ Two", configVersion: 4 } }); - - const res = await PUT(putReq(body)); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/company-accounts", { - method: "PUT", - body, - token: "jwt-abc", - }); - expect(res.status).toBe(200); - }); - - // update returns an empty 200 downstream (void controller). NextResponse.json(undefined) would - // 500 — the route must return a safe ok body. (Caught in live Part D verification.) - it("returns 200 ok when the downstream body is empty", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true }); - const res = await PUT(putReq({ prefix: "MY", memberCode: "MYHQ00002", weight: 5 })); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: true }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/company-accounts/route.ts b/solvway-admin-portal/app/api/admin/company-accounts/route.ts deleted file mode 100644 index 5a1b547..0000000 --- a/solvway-admin-portal/app/api/admin/company-accounts/route.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { CompanyAccountCreatePayload, CompanyAccountUpdatePayload } from "@/app/lib/types"; - -// POST/PUT -> /api/admin/company-accounts (add-admin-company-account-crud, Part C). Both are -// mutations and never go out on GET (Next.js prefetch rule). Create writes the member + tree -// placement + allocation config (+ optional login) as one action; edit changes weight/active/ -// name only — memberCode/prefix locate the row and are never themselves edited. - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const body = await req.json().catch(() => ({})); - const { prefix, memberCode, name, weight, email, password } = body as Partial; - if (!prefix || !memberCode || !name || typeof weight !== "number") { - return badRequest("prefix, memberCode, name and weight are required."); - } - // The optional login travels as a pair (the anchor pattern) — one without the other is a - // malformed request, never forwarded upstream. - if (Boolean(email) !== Boolean(password)) { - return badRequest("email and password must be supplied together, or neither."); - } - - const result = await callMobileApi("/api/admin/company-accounts", { - method: "POST", - body, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} - -export async function PUT(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const body = await req.json().catch(() => ({})); - const { prefix, memberCode } = body as Partial; - if (!prefix || !memberCode) { - return badRequest("prefix and memberCode are required to locate the account."); - } - - const result = await callMobileApi("/api/admin/company-accounts", { - method: "PUT", - body, - token, - }); - if (!result.ok) return errorResponse(result); - // update returns an empty 200 downstream (void); NextResponse.json(undefined) would 500, so - // fall back to a small ok body. - return NextResponse.json(result.data ?? { ok: true }); -} diff --git a/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts b/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts deleted file mode 100644 index 4a5f1c7..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/event/route.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(search = "") { - return new Request(`http://localhost/api/admin/dashboard/event${search}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/dashboard/event", () => { - it("forwards only the event id and the admin JWT (never an operator)", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { pendingOrders: 1 } }); - const res = await GET(getReq("?eventId=7&operator=Ben")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ pendingOrders: 1 }); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard/event?eventId=7", { token: "jwt-abc" }); - }); - - it("is 401 without a session and never calls mobile-api", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq("?eventId=7")); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("is 400 for a missing or non-numeric event id", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - expect((await GET(getReq())).status).toBe(400); - expect((await GET(getReq("?eventId=7;drop"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes a downstream 403 through", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_DASHBOARD_EVENT module is required." }); - const res = await GET(getReq("?eventId=7")); - expect(res.status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/event/route.ts b/solvway-admin-portal/app/api/admin/dashboard/event/route.ts deleted file mode 100644 index a78d5ff..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/event/route.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; -import { badRequest } from "@/app/lib/server/apiRoute"; - -// GET -> mobile-api GET /api/admin/dashboard/event (BO_DASHBOARD_EVENT, gated upstream). Read-only, prefetch-safe. -// Only the event id is forwarded: mobile-api resolves the operator from the session, never from the client. -export function GET(req: NextRequest) { - const eventId = new URL(req.url).searchParams.get("eventId") ?? ""; - if (!/^\d+$/.test(eventId)) return badRequest("Invalid eventId parameter."); - return forwardAdminGet(req, "/api/admin/dashboard/event", ["eventId"]); -} diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts b/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts deleted file mode 100644 index f80779d..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.country.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }); - mocks.getToken.mockReset().mockResolvedValue("jwt-abc"); -}); - -describe("GET /api/admin/dashboard country", () => { - it("forwards country to mobile-api", async () => { - await GET(new Request("http://localhost/api/admin/dashboard?country=SG&evil=1") as unknown as Parameters[0]); - const url = mocks.callMobileApi.mock.calls[0][0] as string; - expect(new URL(url, "http://x").searchParams.get("country")).toBe("SG"); - expect(url).not.toContain("evil"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.test.ts b/solvway-admin-portal/app/api/admin/dashboard/route.test.ts deleted file mode 100644 index 9028c2f..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(search = "") { - return new Request(`http://localhost/api/admin/dashboard${search}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/dashboard", () => { - it("forwards only the documented params and the admin JWT", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } }); - const res = await GET(getReq("?from=2026-09-01&to=2026-09-29&evil=1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ ok: 1 }); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/dashboard?from=2026-09-01&to=2026-09-29", { token: "jwt-abc" }); - }); - - it("is 401 without a session and never calls mobile-api", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("is 400 for a malformed date", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await GET(getReq("?from=yesterday")); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream refusal through", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "forbidden", status: 403 }); - const res = await GET(getReq()); - expect(res.status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/dashboard/route.ts b/solvway-admin-portal/app/api/admin/dashboard/route.ts deleted file mode 100644 index e6f4edf..0000000 --- a/solvway-admin-portal/app/api/admin/dashboard/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; - -// GET -> mobile-api GET /api/admin/dashboard (BO_DASHBOARD). Read-only; module-gated upstream. -export const GET = (req: NextRequest) => forwardAdminGet(req, "/api/admin/dashboard", ["from", "to", "country"]); diff --git a/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts b/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts deleted file mode 100644 index c0a732a..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/[eventId]/route.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; -import { badRequest } from "@/app/lib/server/apiRoute"; - -// GET -> mobile-api GET /api/admin/event-summary/{eventId}?from=&to= (BO_EVENT_SUMMARY, gated upstream). Read-only. -// date is the older one-day form, still forwarded; forwardAdminGet validates from/to, date is checked here. -export async function GET(req: NextRequest, { params }: { params: Promise<{ eventId: string }> }) { - const { eventId } = await params; - if (!/^\d+$/.test(eventId)) return badRequest("Invalid eventId parameter."); - const date = new URL(req.url).searchParams.get("date"); - if (date && !/^\d{4}-\d{2}-\d{2}$/.test(date)) return badRequest("Invalid date parameter."); - return forwardAdminGet(req, `/api/admin/event-summary/${encodeURIComponent(eventId)}`, ["date", "from", "to"]); -} diff --git a/solvway-admin-portal/app/api/admin/event-summary/events/route.ts b/solvway-admin-portal/app/api/admin/event-summary/events/route.ts deleted file mode 100644 index 57ac2d6..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/events/route.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { NextRequest } from "next/server"; -import { forwardAdminGet } from "@/app/lib/server/forwardGet"; - -// GET -> mobile-api GET /api/admin/event-summary/events (BO_EVENT_SUMMARY, gated upstream). Read-only, prefetch-safe. -export function GET(req: NextRequest) { - return forwardAdminGet(req, "/api/admin/event-summary/events", []); -} diff --git a/solvway-admin-portal/app/api/admin/event-summary/route.test.ts b/solvway-admin-portal/app/api/admin/event-summary/route.test.ts deleted file mode 100644 index 07f6218..0000000 --- a/solvway-admin-portal/app/api/admin/event-summary/route.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -// add-event-summary: the two Event Summary BFF routes are read-only pass-throughs to mobile-api. -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET as getEvents } from "./events/route"; -import { GET as getSummary } from "./[eventId]/route"; - -const req = (path: string) => new Request(`http://localhost${path}`) as unknown as Parameters[0]; -const ctx = (eventId: string) => ({ params: Promise.resolve({ eventId }) }); - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset().mockResolvedValue("jwt-abc"); -}); - -describe("GET /api/admin/event-summary/events", () => { - it("forwards to mobile-api with the admin JWT", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: [{ id: "5" }] }); - const res = await getEvents(req("/api/admin/event-summary/events")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual([{ id: "5" }]); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/events", { token: "jwt-abc" }); - }); - - it("is 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await getEvents(req("/api/admin/event-summary/events"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); - -describe("GET /api/admin/event-summary/[eventId]", () => { - it("forwards the event id and the day", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { orders: 3 } }); - const res = await getSummary(req("/api/admin/event-summary/5?date=2026-10-06&x=1"), ctx("5")); - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?date=2026-10-06", { token: "jwt-abc" }); - }); - - it("forwards without a day when none is given", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5", { token: "jwt-abc" }); - }); - - it("is 400 for a non-numeric id or a malformed day, without calling mobile-api", async () => { - expect((await getSummary(req("/api/admin/event-summary/5;x"), ctx("5;x"))).status).toBe(400); - expect((await getSummary(req("/api/admin/event-summary/5?date=06-10-2026"), ctx("5"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards a Date From / Date To range", async () => { // BABYBOO-39 - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5?from=2026-10-14&to=2026-10-16&x=1"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?from=2026-10-14&to=2026-10-16", { token: "jwt-abc" }); - }); - - it("forwards from, to and the older date together", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: true, data: {} }); - await getSummary(req("/api/admin/event-summary/5?to=2026-10-16&date=2026-10-14&from=2026-10-14"), ctx("5")); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-summary/5?date=2026-10-14&from=2026-10-14&to=2026-10-16", { token: "jwt-abc" }); - }); - - it("is 400 for a malformed from or to, without calling mobile-api", async () => { - expect((await getSummary(req("/api/admin/event-summary/5?from=14-10-2026"), ctx("5"))).status).toBe(400); - expect((await getSummary(req("/api/admin/event-summary/5?from=2026-10-14&to=2026-10"), ctx("5"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes a downstream 403 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_EVENT_SUMMARY module is required." }); - expect((await getSummary(req("/api/admin/event-summary/5"), ctx("5"))).status).toBe(403); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts deleted file mode 100644 index e42f954..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -const ctx = () => ({ params: Promise.resolve({ uuid: "12345" }) }); - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/12345/action", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/[uuid]/action", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ action: "approve", remarks: "" }), ctx()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a non-numeric uuid (path traversal) with 400 before calling upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "approve", remarks: "" }), { params: Promise.resolve({ uuid: "../../member/x" }) }); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects action=delete with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "delete", remarks: "test" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects action=pending with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "pending", remarks: "test" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects reject action with blank remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "reject", remarks: "" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects reject action with whitespace-only remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "reject", remarks: " " }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects revoke action with blank remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await POST(postReq({ action: "revoke", remarks: "" }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("accepts approve with empty remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "A" } }); - - const res = await POST(postReq({ action: "approve", remarks: "" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/approve", { - method: "POST", - body: { action: "approve", remarks: "" }, - token: "jwt-abc", - }); - }); - - it("accepts reject with non-blank remarks (≤500 chars)", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "R" } }); - - const res = await POST(postReq({ action: "reject", remarks: "Document expired on 2025-01-01" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/reject", { - method: "POST", - body: { action: "reject", remarks: "Document expired on 2025-01-01" }, - token: "jwt-abc", - }); - }); - - it("accepts revoke with remarks", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "12345", status: "V" } }); - - const res = await POST(postReq({ action: "revoke", remarks: "Admin correction" }), ctx()); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345/revoke", { - method: "POST", - body: { action: "revoke", remarks: "Admin correction" }, - token: "jwt-abc", - }); - }); - - it("rejects remarks > 500 chars", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const longRemarks = "x".repeat(501); - const res = await POST(postReq({ action: "reject", remarks: longRemarks }), ctx()); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts deleted file mode 100644 index 8769a47..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/action/route.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { AdminKycRow } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/{uuid}/action { action, remarks } (BO_KYC gated upstream; a mutation, -// never a GET). action ∈ { approve, reject, revoke }. reject/revoke require non-blank remarks ≤ 500 chars. - -const ALLOWED_ACTIONS = new Set(["approve", "reject", "revoke"]); - -export async function POST(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { uuid } = await ctx.params; - // uuid is a Snowflake id carried as a string; anything else never reaches the upstream path. - if (!/^\d+$/.test(uuid)) return badRequest("Parameter \"uuid\" is invalid"); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { action, remarks } = (body ?? {}) as { action?: unknown; remarks?: unknown }; - - if (typeof action !== "string" || !ALLOWED_ACTIONS.has(action)) { - return badRequest("Parameter \"action\" must be one of: approve, reject, revoke"); - } - - const remarksStr = typeof remarks === "string" ? remarks : ""; - - // reject/revoke require non-blank remarks, max 500 chars. - if ((action === "reject" || action === "revoke") && !remarksStr.trim()) { - return badRequest("Remarks are required for this action"); - } - if (remarksStr.length > 500) { - return badRequest("Remarks must not exceed 500 characters"); - } - - const result = await callMobileApi(`/api/admin/kyc/${encodeURIComponent(uuid)}/${action}`, { - method: "POST", - body: { action, remarks: remarksStr }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts deleted file mode 100644 index 99972bf..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ getToken: vi.fn() })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function req(url = "http://localhost/api/admin/kyc/12345/doc/ID_FRONT") { - const u = new URL(url); - return { nextUrl: u } as unknown as Parameters[0]; -} -const ctx = (uuid = "12345", docType = "ID_FRONT") => ({ params: Promise.resolve({ uuid, docType }) }); - -const originalFetch = global.fetch; - -beforeEach(() => { - mocks.getToken.mockReset(); - process.env.MOBILE_API_BASE_URL = "http://gateway"; - process.env.MOBILE_API_KEY = "secret-key"; -}); -afterEach(() => { - global.fetch = originalFetch; -}); - -describe("GET /api/admin/kyc/[uuid]/doc/[docType]", () => { - it("returns 401 without a session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx()); - expect(res.status).toBe(401); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("rejects docType=PASSPORT with 400 and never calls upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "PASSPORT")); - - expect(res.status).toBe(400); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("rejects docType=DRIVING_LICENSE with 400", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const fetchSpy = vi.fn(); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "DRIVING_LICENSE")); - - expect(res.status).toBe(400); - expect(fetchSpy).not.toHaveBeenCalled(); - }); - - it("returns upstream bytes with no-store for allowed docTypes", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const imgBytes = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0]); // JPEG marker - const upstream = new Response(imgBytes, { - status: 200, - headers: { "content-type": "image/jpeg" }, - }); - const fetchSpy = vi.fn().mockResolvedValue(upstream); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "ID_FRONT")); - - expect(res.status).toBe(200); - expect(res.headers.get("Cache-Control")).toBe("no-store"); - expect(res.headers.get("content-type")).toBe("image/jpeg"); - const body = new Uint8Array(await res.arrayBuffer()); - expect(Array.from(body)).toEqual([0xFF, 0xD8, 0xFF, 0xE0]); - }); - - it("returns upstream bytes for SELFIE", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const pngBytes = new Uint8Array([0x89, 0x50, 0x4E, 0x47]); - const upstream = new Response(pngBytes, { - status: 200, - headers: { "content-type": "image/png" }, - }); - const fetchSpy = vi.fn().mockResolvedValue(upstream); - global.fetch = fetchSpy as unknown as typeof fetch; - - const res = await GET(req(), ctx("67890", "SELFIE")); - - expect(res.status).toBe(200); - const body = new Uint8Array(await res.arrayBuffer()); - expect(Array.from(body)).toEqual([0x89, 0x50, 0x4E, 0x47]); - }); - - // F20: the proxy is served from the admin origin with the admin's cookie; a stored non-image type must never render - it("never passes a non-image upstream type through, and forbids sniffing", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - for (const type of ["text/html", "image/svg+xml", "application/xhtml+xml", "text/html; charset=utf-8"]) { - global.fetch = vi.fn().mockResolvedValue( - new Response("", { status: 200, headers: { "content-type": type } }), - ) as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "SELFIE")); - - expect(res.headers.get("content-type")).toBe("application/octet-stream"); - expect(res.headers.get("x-content-type-options")).toBe("nosniff"); - } - }); - - it("keeps an image type and forbids sniffing", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - global.fetch = vi.fn().mockResolvedValue( - new Response(new Uint8Array([1]), { status: 200, headers: { "content-type": "Image/PNG; foo=bar" } }), - ) as unknown as typeof fetch; - - const res = await GET(req(), ctx("12345", "ID_BACK")); - - expect(res.headers.get("content-type")).toBe("image/png"); - expect(res.headers.get("x-content-type-options")).toBe("nosniff"); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts deleted file mode 100644 index 67324f7..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/doc/[docType]/route.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { SAFE_BINARY_HEADERS, safeContentType } from "@/app/lib/server/binaryProxy"; -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { unauthorized } from "@/app/lib/server/apiRoute"; -import { isTraversalPath } from "@/app/lib/server/upstreamPathGuard"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// GET -> mobile-api GET /api/admin/kyc/{uuid}/doc/{docType} — streams KYC document image bytes. -// A binary proxy: callMobileApi normalizes JSON, so this route does a raw fetch and passes the -// image bytes + Content-Type through. Authorization is the BO_KYC module grant, enforced -// server-side by mobile-api. Read-only — no side effect on GET (Next.js prefetch-safe). -// Allowed docTypes: ID_FRONT, ID_BACK, SELFIE. - -const TIMEOUT_MS = 30_000; - -const ALLOWED_DOC_TYPES = new Set(["ID_FRONT", "ID_BACK", "SELFIE"]); - -function jsonError(message: string, status: number) { - return NextResponse.json({ error: message }, { status }); -} - -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string; docType: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { docType, uuid } = await ctx.params; - - // Only allow known doc types — never call upstream with an arbitrary path segment. - if (!/^\d+$/.test(uuid)) return jsonError("Invalid uuid", 400); - if (!ALLOWED_DOC_TYPES.has(docType)) { - return jsonError(`Unsupported doc type: ${encodeURIComponent(docType)}`, 400); - } - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return jsonError("Mobile API is not configured", 500); - - // Fetched directly, so callMobileApi's dot-segment guard is applied here too. - const path = `/api/admin/kyc/${encodeURIComponent(uuid)}/doc/${encodeURIComponent(docType)}`; - if (isTraversalPath(path)) return jsonError("Invalid uuid", 400); - const forwardedIp = await forwardedClientIpHeaders(); - const url = `${base}${path}`; - - let res: Response; - try { - res = await fetch(url, { - method: "GET", - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return jsonError("Couldn't reach the KYC service", 502); - } - - if (!res.ok) { - if (res.status === 401) return unauthorized(); - if (res.status === 404) return jsonError("Document not found.", 404); - if (res.status === 403) return jsonError("Not authorized.", 403); - if (res.status >= 500) return jsonError("The KYC service failed.", 502); - return jsonError("Couldn't download the document.", 400); - } - - const body = await res.arrayBuffer(); - const headers = new Headers({ - // KYC documents are JPEG or PNG only (mobile-api KycUploadRules); F20: nothing else renders on this origin - "Content-Type": safeContentType(res.headers.get("content-type"), ["image/jpeg", "image/png"]), - "Cache-Control": "no-store", - ...SAFE_BINARY_HEADERS, - }); - const disposition = res.headers.get("content-disposition"); - if (disposition) headers.set("Content-Disposition", disposition); - return new NextResponse(body, { status: 200, headers }); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts deleted file mode 100644 index 4b68b17..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/12345") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/[uuid]", () => { - it("rejects a non-numeric uuid with 400 before calling upstream", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const res = await GET(getReq(), { params: Promise.resolve({ uuid: "abc" }) }); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq(), { params: Promise.resolve({ uuid: "12345" }) }); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards uuid to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ - ok: true, - data: { record: {}, docTypes: [], member: {}, history: [], warnings: [] }, - }); - - await GET(getReq(), { params: Promise.resolve({ uuid: "12345" }) }); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/12345", { token: "jwt-abc" }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts b/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts deleted file mode 100644 index 3ec4a60..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/[uuid]/route.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute"; -import type { AdminKycDetail } from "@/app/lib/types"; - -// GET -> /api/admin/kyc/{uuid} (read-only; BO_KYC gated upstream). - -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const token = await getToken(); - if (!token) return unauthorized(); - - const { uuid } = await ctx.params; - // uuid is a Snowflake id carried as a string; anything else never reaches the upstream path. - if (!/^\d+$/.test(uuid)) return badRequest("Parameter \"uuid\" is invalid"); - const result = await callMobileApi(`/api/admin/kyc/${encodeURIComponent(uuid)}`, { - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts deleted file mode 100644 index 3e4f78f..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/counts/route.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/counts") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/counts", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - }); - - it("forwards to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { P: 1, A: 2, R: 0, V: 0, ALL: 3 } }); - - const res = await GET(getReq()); - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/counts", { token: "jwt-abc" }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/counts/route.ts b/solvway-admin-portal/app/api/admin/kyc/counts/route.ts deleted file mode 100644 index 3b7e1f7..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/counts/route.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { AdminKycCounts } from "@/app/lib/types"; - -// GET -> /api/admin/kyc/counts (read-only; BO_KYC gated upstream). - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - const result = await callMobileApi("/api/admin/kyc/counts", { token }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts deleted file mode 100644 index 08d66ce..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/export/route.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc/export") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc/export", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - }); - - it("forwards query params (minus page/size) to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: [] }); - - await GET(getReq("http://localhost/api/admin/kyc/export?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=10")); - - // page/size should be absent from the export call - const [path] = mocks.callMobileApi.mock.calls[0]; - expect(path).toContain("status=P"); - expect(path).toContain("q=ahmad"); - expect(path).not.toContain("page="); - expect(path).not.toContain("size="); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/export/route.ts b/solvway-admin-portal/app/api/admin/kyc/export/route.ts deleted file mode 100644 index 77b89c0..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/export/route.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import { TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; - -// GET -> /api/admin/kyc/export?status=&q=&from=&to=&channel= (same filters as list but no page/size; read-only; BO_KYC gated upstream). - -const QUERY = { - status: TEXT, - q: TEXT, - from: TEXT, - to: TEXT, - channel: TEXT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - // Export does NOT carry page/size, so they are not in its allow-list. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/kyc/export${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/route.test.ts deleted file mode 100644 index 531b063..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/route.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(url = "http://localhost/api/admin/kyc") { - return new Request(url) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/kyc", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await GET(getReq()); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards query params to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0, page: 0, size: 10 } }); - - await GET(getReq("http://localhost/api/admin/kyc?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=20")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/kyc?status=P&q=ahmad&from=2025-01-01&to=2025-12-31&channel=MEMBER&page=0&size=20", - { token: "jwt-abc" }, - ); - }); - - it("omits absent query params", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0, page: 0, size: 10 } }); - - await GET(getReq()); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc", { token: "jwt-abc" }); - }); - - it("returns 200 on success", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const payload = { content: [], totalElements: 0, page: 0, size: 10 }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: payload }); - - const res = await GET(getReq()); - expect(res.status).toBe(200); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/route.ts b/solvway-admin-portal/app/api/admin/kyc/route.ts deleted file mode 100644 index 9fe50da..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/route.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; -import type { AdminKycPage } from "@/app/lib/types"; - -// GET -> /api/admin/kyc?status=&q=&from=&to=&channel=&page=&size= (read-only; BO_KYC gated upstream). - -const QUERY = { - status: TEXT, - q: TEXT, - from: TEXT, - to: TEXT, - channel: TEXT, - ...paging(500), - ...SORT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/kyc${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts deleted file mode 100644 index d35a14a..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/submit/route.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/submit", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/submit", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST( - postReq({ - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }), - ); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the submit body to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { uuid: "999", status: "P" } }); - - const res = await POST( - postReq({ - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }), - ); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/submit", { - method: "POST", - body: { - memberCode: "BB0100", - submitName: "Ahmad", - identityType: "MYKAD", - identityNo: "880101-01-1234", - docs: { ID_FRONT: "kyc/BB0100/a.jpg", ID_BACK: "kyc/BB0100/b.jpg", SELFIE: "kyc/BB0100/c.jpg" }, - }, - token: "jwt-abc", - }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/submit/route.ts b/solvway-admin-portal/app/api/admin/kyc/submit/route.ts deleted file mode 100644 index 0b242bd..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/submit/route.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { AdminKycRow } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/submit { memberCode, submitName, identityType, identityNo, docs } -// (BO_KYC gated upstream; a mutation, never a GET). - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { memberCode, submitName, identityType, identityNo, docs } = (body ?? {}) as { - memberCode?: unknown; - submitName?: unknown; - identityType?: unknown; - identityNo?: unknown; - docs?: unknown; - }; - - if (typeof memberCode !== "string" || !memberCode) { - return badRequest("Parameter \"memberCode\" is required"); - } - if (typeof submitName !== "string" || !submitName) { - return badRequest("Parameter \"submitName\" is required"); - } - if (typeof identityType !== "string" || !identityType) { - return badRequest("Parameter \"identityType\" is required"); - } - if (typeof identityNo !== "string" || !identityNo) { - return badRequest("Parameter \"identityNo\" is required"); - } - - const result = await callMobileApi("/api/admin/kyc/submit", { - method: "POST", - body: { memberCode, submitName, identityType, identityNo, docs }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts b/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts deleted file mode 100644 index b638417..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/upload/route.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { POST } from "./route"; - -function postReq(body: unknown) { - return new Request("http://localhost/api/admin/kyc/upload", { - method: "POST", - body: JSON.stringify(body), - }) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("POST /api/admin/kyc/upload", () => { - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - const res = await POST(postReq({ memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "data" })); - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("forwards the upload body to mobile-api", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { reference: "ref-123" } }); - - const res = await POST( - postReq({ memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "base64data" }), - ); - - expect(res.status).toBe(200); - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/kyc/upload", { - method: "POST", - body: { memberCode: "BB0100", docType: "ID_FRONT", fileType: "jpg", base: "base64data" }, - token: "jwt-abc", - }); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/kyc/upload/route.ts b/solvway-admin-portal/app/api/admin/kyc/upload/route.ts deleted file mode 100644 index aa362db..0000000 --- a/solvway-admin-portal/app/api/admin/kyc/upload/route.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import type { KycUploadResult } from "@/app/lib/types"; - -// POST -> /api/admin/kyc/upload { memberCode, docType, fileType, base } (BO_KYC gated upstream; -// a mutation, never a GET). - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - let body: unknown; - try { - body = await req.json(); - } catch { - return badRequest("Invalid request body"); - } - const { memberCode, docType, fileType, base } = (body ?? {}) as { - memberCode?: unknown; - docType?: unknown; - fileType?: unknown; - base?: unknown; - }; - - if (typeof memberCode !== "string" || !memberCode) { - return badRequest("Parameter \"memberCode\" is required"); - } - - const result = await callMobileApi("/api/admin/kyc/upload", { - method: "POST", - body: { memberCode, docType, fileType, base }, - token, - }); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts b/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts deleted file mode 100644 index aea8e9e..0000000 --- a/solvway-admin-portal/app/api/admin/member-corrections/route.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET } from "./route"; - -function getReq(qs: string) { - return new Request(`http://localhost/api/admin/member-corrections${qs}`) as unknown as Parameters[0]; -} - -beforeEach(() => { - mocks.callMobileApi.mockReset(); - mocks.getToken.mockReset(); -}); - -describe("GET /api/admin/member-corrections", () => { - it("forwards the query string with the admin JWT and returns the page", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - const page = { content: [], totalElements: 0 }; - mocks.callMobileApi.mockResolvedValue({ ok: true, data: page }); - - const res = await GET(getReq("?type=RANK&memberCode=MY1&page=1&size=20")); - - expect(res.status).toBe(200); - expect(await res.json()).toEqual(page); - expect(mocks.callMobileApi).toHaveBeenCalledWith( - "/api/admin/member-corrections?type=RANK&memberCode=MY1&page=1&size=20", - { token: "jwt-abc" }, - ); - }); - - it("forwards no query string when there is none", async () => { - mocks.getToken.mockResolvedValue("jwt-abc"); - mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [], totalElements: 0 } }); - - await GET(getReq("")); - - expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/member-corrections", { token: "jwt-abc" }); - }); - - it("returns 401 without a session", async () => { - mocks.getToken.mockResolvedValue(null); - - const res = await GET(getReq("")); - - expect(res.status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/member-corrections/route.ts b/solvway-admin-portal/app/api/admin/member-corrections/route.ts deleted file mode 100644 index 955d6b7..0000000 --- a/solvway-admin-portal/app/api/admin/member-corrections/route.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { callMobileApi } from "@/app/lib/server/mobileApi"; -import { getToken } from "@/app/lib/server/session"; -import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; -import { paging, SORT, TEXT, upstreamQuery } from "@/app/lib/server/upstreamQuery"; -import type { AdminMemberCorrectionPage } from "@/app/lib/types"; - -// GET -> /api/admin/member-corrections (BABYBOO-43): admin rank and referral corrections, newest -// first. Forwards the query string (type, memberCode, from, to, page, size) with the bb_admin JWT. Read-only — -// no side effect on GET (Next.js prefetch-safe). BO_RANK_REFERRAL is enforced upstream. - -const QUERY = { - type: TEXT, - memberCode: TEXT, - from: TEXT, - to: TEXT, - ...paging(500), - ...SORT, -}; - -export async function GET(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - - // portal-query-allowlist (F38): only the params mobile-api accepts, validated and encoded. - const qs = upstreamQuery(new URL(req.url).searchParams, QUERY); - const result = await callMobileApi( - `/api/admin/member-corrections${qs}`, - { token }, - ); - if (!result.ok) return errorResponse(result); - return NextResponse.json(result.data); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts deleted file mode 100644 index f1ce24c..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/[messageUuid]/images/[index]/route.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { unauthorized } from "@/app/lib/server/apiRoute"; -import { expiredSignal, isId } from "@/app/lib/server/messagesProxy"; -import { isTraversalPath } from "@/app/lib/server/upstreamPathGuard"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// GET -> mobile-api GET /api/admin/member-messages/{uuid}/messages/{messageUuid}/images/{index}: streams a -// private message image. Raw fetch (callMobileApi normalises JSON). Side-effect free, so prefetch-safe. -const TIMEOUT_MS = 120_000; // covers the piped body too, so a slow link can finish a 5 MB image -const IMAGE_TYPES = new Set(["image/jpeg", "image/png"]); -const err = (message: string, status: number) => NextResponse.json({ error: message }, { status }); - -export async function GET( - _req: NextRequest, - ctx: { params: Promise<{ uuid: string; messageUuid: string; index: string }> }, -) { - const token = await getToken(); - if (!token) return unauthorized(); - const { uuid, messageUuid, index } = await ctx.params; - if (!isId(uuid) || !isId(messageUuid) || !/^\d{1,2}$/.test(index)) return err("Invalid image reference", 400); - // Fetched directly, so callMobileApi's dot-segment guard is applied here too. - const path = `/api/admin/member-messages/${encodeURIComponent(uuid)}/messages/${encodeURIComponent(messageUuid)}/images/${encodeURIComponent(index)}`; - if (isTraversalPath(path)) return err("Invalid image reference", 400); - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return err("Mobile API is not configured", 500); - - const forwardedIp = await forwardedClientIpHeaders(); - - let res: Response; - try { - res = await fetch(`${base}${path}`, { - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return err("Couldn't reach the messaging service", 502); - } - if (!res.ok) { - if (expiredSignal(res.status, await res.text().catch(() => ""))) return unauthorized(); - if (res.status === 404) return err("Image not found.", 404); - if (res.status === 403) return err("Not authorized.", 403); - return err("Couldn't load the image.", res.status >= 500 ? 502 : 400); - } - // Served from the origin that holds the admin session: never pass an upstream type through unchecked. - const type = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase(); - return new NextResponse(res.body, { - status: 200, - headers: { - "Content-Type": IMAGE_TYPES.has(type) ? type : "application/octet-stream", - "Cache-Control": "private, no-store", - "X-Content-Type-Options": "nosniff", - }, - }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts deleted file mode 100644 index af48bf8..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/messages/route.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -type Ctx = { params: Promise<{ uuid: string }> }; - -// GET -> /api/admin/member-messages/{uuid}/messages?before=&size= POST -> same path { body, imageRefs }. -export async function GET(req: NextRequest, ctx: Ctx) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/messages`, "GET", { query: ["before", "size"] }); -} - -export async function POST(req: NextRequest, ctx: Ctx) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/messages`, "POST", { body: true }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts deleted file mode 100644 index 3ed8a98..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/read/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// POST -> mobile-api POST /api/admin/member-messages/{uuid}/read (a mutation, never a GET). -export async function POST(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}/read`, "POST"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts deleted file mode 100644 index 265e8e2..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/[uuid]/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/{uuid}. -export async function GET(req: NextRequest, ctx: { params: Promise<{ uuid: string }> }) { - const { uuid } = await ctx.params; - if (!isId(uuid)) return badRequest('Parameter "uuid" is invalid'); - return relay(req, `/${encodeURIComponent(uuid)}`, "GET"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts deleted file mode 100644 index bfbdc56..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/recipients/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts/{broadcastUuid}/recipients?unreadOnly=&page=&size=. -export async function GET(req: NextRequest, ctx: { params: Promise<{ broadcastUuid: string }> }) { - const { broadcastUuid } = await ctx.params; - if (!isId(broadcastUuid)) return badRequest('Parameter "broadcastUuid" is invalid'); - return relay(req, `/broadcasts/${encodeURIComponent(broadcastUuid)}/recipients`, "GET", { query: ["unreadOnly", "page", "size", "sortBy", "sortDir"] }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts deleted file mode 100644 index f4e5302..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/[broadcastUuid]/route.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { NextRequest } from "next/server"; -import { badRequest } from "@/app/lib/server/apiRoute"; -import { isId, relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts/{broadcastUuid}. -export async function GET(req: NextRequest, ctx: { params: Promise<{ broadcastUuid: string }> }) { - const { broadcastUuid } = await ctx.params; - if (!isId(broadcastUuid)) return badRequest('Parameter "broadcastUuid" is invalid'); - return relay(req, `/broadcasts/${encodeURIComponent(broadcastUuid)}`, "GET"); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts deleted file mode 100644 index cb162c6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/preview/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// POST -> mobile-api POST /api/admin/member-messages/broadcasts/preview { target }. -export const POST = (req: NextRequest) => relay(req, "/broadcasts/preview", "POST", { body: true }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts b/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts deleted file mode 100644 index b2c5fc6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/broadcasts/route.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/broadcasts (q, sortBy, sortDir, page, size): one summary row per broadcast. -export const GET = (req: NextRequest) => - relay(req, "/broadcasts", "GET", { query: ["q", "sortBy", "sortDir", "page", "size"] }); - -// POST -> mobile-api POST /api/admin/member-messages/broadcasts { target, subject, body, imageRefs }. -export const POST = (req: NextRequest) => relay(req, "/broadcasts", "POST", { body: true }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts b/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts deleted file mode 100644 index bf17bc6..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/by-key/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages/by-key (query forwarded: member). -export const GET = (req: NextRequest) => relay(req, "/by-key", "GET", { query: ["member"] }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/images/route.ts b/solvway-admin-portal/app/api/admin/member-messages/images/route.ts deleted file mode 100644 index 78db3b4..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/images/route.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { NextResponse, type NextRequest } from "next/server"; -import { getToken } from "@/app/lib/server/session"; -import { badRequest, unauthorized } from "@/app/lib/server/apiRoute"; -import { codeOf, codeResponse, expiredSignal } from "@/app/lib/server/messagesProxy"; -import { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; - -// POST multipart { file } -> mobile-api POST /api/admin/member-messages/images -> { ref }. TWO-STEP upload: -// the ref is committed by mobile-api when the message is sent (abandoned uploads are reaped, intended). -const ALLOWED = new Set(["image/jpeg", "image/png"]); -const MAX_BYTES = 5 * 1024 * 1024; -const TIMEOUT_MS = 30_000; - -export async function POST(req: NextRequest) { - const token = await getToken(); - if (!token) return unauthorized(); - // Refuse an oversized declared body before buffering it (formData() reads everything into memory). - if (Number(req.headers?.get("content-length") ?? 0) > MAX_BYTES + 64 * 1024) { - return badRequest("Image must be 5 MB or smaller", { code: "MESSAGE_INVALID" }); - } - - let file: unknown; - try { - file = (await req.formData()).get("file"); - } catch { - return badRequest("Invalid request body"); - } - if (!(file instanceof File)) return badRequest('Parameter "file" is required'); - if (!ALLOWED.has(file.type)) return badRequest("Only JPEG or PNG images are allowed", { code: "MESSAGE_INVALID" }); - if (file.size > MAX_BYTES) return badRequest("Image must be 5 MB or smaller", { code: "MESSAGE_INVALID" }); - - const base = process.env.MOBILE_API_BASE_URL; - const key = process.env.MOBILE_API_KEY; - if (!base || !key) return NextResponse.json({ error: "Mobile API is not configured" }, { status: 500 }); - - const forwardedIp = await forwardedClientIpHeaders(); - - const form = new FormData(); - form.set("file", file, file.name); - let res: Response; - try { - res = await fetch(`${base}/api/admin/member-messages/images`, { - method: "POST", - headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}` }, // no Content-Type: fetch sets the boundary - body: form, - cache: "no-store", - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - } catch { - return NextResponse.json({ error: "Couldn't reach the messaging service" }, { status: 502 }); - } - const text = await res.text(); - let data: Record = {}; - try { - data = text ? JSON.parse(text) : {}; - } catch { - /* non-JSON upstream body: fall through to the generic message */ - } - if (!res.ok) { - if (expiredSignal(res.status, text)) return unauthorized(); - const code = codeOf(text); // matches the code field or a reason text that carries it - if (code) return codeResponse(code); - const message = (data.detail as string) || (data.message as string) || (data.error as string) || "Upload failed"; - const status = res.status >= 400 && res.status < 500 ? res.status : 502; - return NextResponse.json({ error: message }, { status }); - } - // A 200 without a ref would let the UI send a message pointing at nothing. - if (typeof data.ref !== "string") return NextResponse.json({ error: "Upload failed" }, { status: 502 }); - return NextResponse.json({ ref: data.ref }); -} diff --git a/solvway-admin-portal/app/api/admin/member-messages/route.ts b/solvway-admin-portal/app/api/admin/member-messages/route.ts deleted file mode 100644 index 77ae2d5..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/route.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { NextRequest } from "next/server"; -import { relay } from "@/app/lib/server/messagesProxy"; - -// GET -> mobile-api GET /api/admin/member-messages (query forwarded: types, unreadOnly, q, page, size). -export const GET = (req: NextRequest) => relay(req, "", "GET", { query: ["types", "unreadOnly", "q", "page", "size", "sortBy", "sortDir"] }); diff --git a/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts b/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts deleted file mode 100644 index a5406d1..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/routes.broadcasts.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import type { NextRequest } from "next/server"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET as listBroadcasts } from "./broadcasts/route"; -import { GET as summary } from "./broadcasts/[broadcastUuid]/route"; -import { GET as recipients } from "./broadcasts/[broadcastUuid]/recipients/route"; - -// BABYBOO-56 broadcast read count: read-only BFF relays. -const B = "http://localhost/api/admin/member-messages"; -const req = (url: string) => new Request(url, { method: "GET" }) as unknown as NextRequest; -const ctx = (broadcastUuid: string) => ({ params: Promise.resolve({ broadcastUuid }) }); -const lastCall = () => { - const [url, opts] = mocks.callMobileApi.mock.calls.at(-1)!; - const [path, qs = ""] = String(url).split("?"); - return { path, sp: new URLSearchParams(qs), opts }; -}; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { fine: 1 } }); - mocks.getToken.mockReset().mockResolvedValue("jwt"); - process.env.MOBILE_API_BASE_URL = "http://up"; - process.env.MOBILE_API_KEY = "k"; -}); - -describe("GET broadcasts summaries relay", () => { - it("forwards q, page and size to mobile-api with the session token", async () => { - const res = await listBroadcasts(req(`${B}/broadcasts?q=raya&page=1&size=20`)); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, sp, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts"); - expect([sp.get("q"), sp.get("page"), sp.get("size")]).toEqual(["raya", "1", "20"]); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await listBroadcasts(req(`${B}/broadcasts?page=0&size=20`))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("maps an upstream failure to an error response", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Something odd", status: 500 }); - expect((await listBroadcasts(req(`${B}/broadcasts?page=0&size=20`))).status).toBeGreaterThanOrEqual(400); - }); -}); - -describe("GET broadcast recipients relay", () => { - it("forwards the uuid, unreadOnly, page and size", async () => { - const res = await recipients(req(`${B}/broadcasts/b1/recipients?unreadOnly=true&page=2&size=20`), ctx("b1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, sp, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts/b1/recipients"); - expect([sp.get("unreadOnly"), sp.get("page"), sp.get("size")]).toEqual(["true", "2", "20"]); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await recipients(req(`${B}/broadcasts/b1/recipients`), ctx("b1"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a path-like broadcast id before any upstream call", async () => { - const res = await recipients(req(`${B}/broadcasts/x/recipients`), ctx("../admin")); - expect(res.status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream 404 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Broadcast not found", status: 404 }); - expect((await recipients(req(`${B}/broadcasts/b1/recipients`), ctx("b1"))).status).toBe(404); - }); -}); - -describe("GET single broadcast summary relay", () => { - it("forwards the uuid to mobile-api with the session token", async () => { - const res = await summary(req(`${B}/broadcasts/b1`), ctx("b1")); - expect(res.status).toBe(200); - expect(await res.json()).toEqual({ fine: 1 }); - const { path, opts } = lastCall(); - expect(path).toBe("/api/admin/member-messages/broadcasts/b1"); - expect(opts).toEqual(expect.objectContaining({ method: "GET", token: "jwt" })); - }); - - it("returns 401 with no session and never calls upstream", async () => { - mocks.getToken.mockResolvedValue(null); - expect((await summary(req(`${B}/broadcasts/b1`), ctx("b1"))).status).toBe(401); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("rejects a path-like broadcast id with 400 before any upstream call", async () => { - expect((await summary(req(`${B}/broadcasts/x`), ctx("../admin"))).status).toBe(400); - expect(mocks.callMobileApi).not.toHaveBeenCalled(); - }); - - it("passes an upstream 404 through", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Broadcast not found", status: 404 }); - expect((await summary(req(`${B}/broadcasts/b1`), ctx("b1"))).status).toBe(404); - }); -}); diff --git a/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts b/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts deleted file mode 100644 index 8c2e4cd..0000000 --- a/solvway-admin-portal/app/api/admin/member-messages/routes.hardening.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import type { NextRequest } from "next/server"; - -const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); -vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); -vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); - -import { GET as list } from "./route"; -import { GET as byKey } from "./by-key/route"; -import { GET as messages } from "./[uuid]/messages/route"; -import { POST as upload } from "./images/route"; -import { GET as image } from "./[uuid]/messages/[messageUuid]/images/[index]/route"; - -const B = "http://localhost/api/admin/member-messages"; -const get = (url: string) => new Request(url) as unknown as NextRequest; -const img = (messageUuid = "m1") => ({ params: Promise.resolve({ uuid: "c1", messageUuid, index: "0" }) }); -const formReq = (fd: FormData, headers: Record = {}) => - ({ headers: new Headers(headers), formData: async () => fd }) as unknown as NextRequest; -const pngForm = () => { - const fd = new FormData(); - fd.append("file", new File(["abc"], "a.png", { type: "image/png" })); - return fd; -}; - -beforeEach(() => { - mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: {} }); - mocks.getToken.mockReset().mockResolvedValue("jwt"); - process.env.MOBILE_API_BASE_URL = "http://up"; - process.env.MOBILE_API_KEY = "k"; -}); -afterEach(() => vi.unstubAllGlobals()); - -describe("query whitelist", () => { - it("forwards only the documented query keys", async () => { - await list(get(`${B}?types=S&q=x&page=1&size=20&unreadOnly=true&reader=M:MY3&adminUsername=eve`)); - await byKey(get(`${B}/by-key?member=MY5&reader=M:MY3`)); - await messages(get(`${B}/c1/messages?before=m9&size=30&reader=M:MY3`), { params: Promise.resolve({ uuid: "c1" }) }); - const urls = mocks.callMobileApi.mock.calls.map((c) => c[0] as string); - expect(urls[0]).toBe("/api/admin/member-messages?types=S&unreadOnly=true&q=x&page=1&size=20"); - expect(urls[1]).toBe("/api/admin/member-messages/by-key?member=MY5"); - expect(urls[2]).toBe("/api/admin/member-messages/c1/messages?before=m9&size=30"); - }); - - it("passes a module-denied 403 through for the blocked state", async () => { - mocks.callMobileApi.mockResolvedValue({ ok: false, status: 403, error: "The BO_MEMBER_MESSAGES module is required." }); - const res = await list(get(B)); - expect(res.status).toBe(403); - }); -}); - -describe("upload", () => { - it("refuses a declared body far over 5 MB before reading it", async () => { - const formData = vi.fn(); - const fetchMock = vi.fn(); - vi.stubGlobal("fetch", fetchMock); - const res = await upload({ headers: new Headers({ "content-length": String(7 * 1024 * 1024) }), formData } as unknown as NextRequest); - expect(res.status).toBe(400); - expect(formData).not.toHaveBeenCalled(); - expect(fetchMock).not.toHaveBeenCalled(); - }); - - it("forwards the file under the `file` field", async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ref: "messages/admin/1.png" }), { status: 200 })); - vi.stubGlobal("fetch", fetchMock); - const res = await upload(formReq(pngForm())); - expect(await res.json()).toEqual({ ref: "messages/admin/1.png" }); - expect((fetchMock.mock.calls[0][1].body as FormData).get("file")).toBeInstanceOf(File); - }); - - it("answers 502 when a 200 reply has no ref", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("", { status: 200 }))); - expect((await upload(formReq(pngForm()))).status).toBe(502); - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", { status: 200 }))); - expect((await upload(formReq(pngForm()))).status).toBe(502); - }); - - it("maps mobile-api's expired-token 500 to 401", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("JWT expired token", { status: 500 }))); - expect((await upload(formReq(pngForm()))).status).toBe(401); - }); -}); - -describe("image stream", () => { - it("never serves a non-image type as-is and sets nosniff", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("" } }); - fireEvent.click(screen.getByRole("button", { name: "Show editor" })); - const last = onChange.mock.calls.at(-1)?.[0] as string; - expect(last).toContain("

Pasted

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

x

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

Pasted

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

Pasted

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

x

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

x

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

x

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

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

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

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

x

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

Hi

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

Hi🍼

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

${"a".repeat(58000)}

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

short

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

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