import { SAFE_BINARY_HEADERS, safeContentType } from "@/app/lib/server/binaryProxy"; 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 { forwardedClientIpHeaders } from "@/app/lib/server/clientContext"; // GET/POST -> mobile-api /api/admin/fulfilment/ (add-manual-fulfilment-console). // Only the admin fulfilment routes are forwarded; anything else is 404 so this catch-all // can never reach another admin API. // GET allow-list: batch reads (batches/ and batches//failures). // POST allow-list: batches, batches/tracking, export, print. type Ctx = { params: Promise<{ path: string[] }> }; function jsonError(message: string, status: number) { return NextResponse.json({ error: message }, { status }); } export async function GET(_req: NextRequest, ctx: Ctx) { const token = await getToken(); if (!token) return unauthorized(); const sub = (await ctx.params).path.map(encodeURIComponent).join("/"); // Allow only batch reads: batches/ and batches//failures if (/^batches\/\d+(\/failures)?$/.test(sub)) { const result = await callMobileApi(`/api/admin/fulfilment/${sub}`, { token }); if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } return jsonError("Not found", 404); } export async function POST(req: NextRequest, ctx: Ctx) { const token = await getToken(); if (!token) return unauthorized(); const sub = (await ctx.params).path.map(encodeURIComponent).join("/"); // POST allow-list: batches, batches/tracking, export, print if (["batches", "batches/tracking", "export"].includes(sub)) { const body = await req.json().catch(() => undefined); if (body === undefined) return badRequest("Invalid request body"); const result = await callMobileApi(`/api/admin/fulfilment/${sub}`, { method: "POST", body, token }); if (!result.ok) return errorResponse(result); return NextResponse.json(result.data); } if (sub === "print") { // Binary route: raw fetch like the invoice route. 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); const body = await req.json().catch(() => undefined); if (body === undefined) return badRequest("Invalid request body"); const forwardedIp = await forwardedClientIpHeaders(); const url = `${base}/api/admin/fulfilment/print`; let res: Response; try { res = await fetch(url, { method: "POST", headers: { "api-key": key, ...forwardedIp, Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: JSON.stringify(body), cache: "no-store", signal: AbortSignal.timeout(30_000), }); } catch { return jsonError("Couldn't reach the print service", 502); } // 401 -> let client re-auth if (res.status === 401) return unauthorized(); // 5xx -> 502 if (res.status >= 500) return jsonError("The print service failed.", 502); // Other 4xx -> same status with error from upstream body if (res.status >= 400) { const raw = await res.text(); let err: string; try { const obj = JSON.parse(raw); // inventory's refusals arrive as problem+json, so the reason is usually in "detail" err = obj?.error ?? obj?.message ?? obj?.detail ?? "Couldn't print the delivery orders."; } catch { err = "Couldn't print the delivery orders."; } return jsonError(err, res.status); } // Success: stream bytes back const arrayBuffer = await res.arrayBuffer(); const headers = new Headers({ "Content-Type": safeContentType(res.headers.get("content-type") ?? "application/pdf", ["application/pdf"]), "Cache-Control": "no-store", ...SAFE_BINARY_HEADERS, }); const skipped = res.headers.get("x-skipped-drafts"); if (skipped) headers.set("x-skipped-drafts", skipped); return new NextResponse(arrayBuffer, { status: 200, headers }); } // Anything else -> 404 return jsonError("Not found", 404); }