Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
108 lines
4.2 KiB
TypeScript
108 lines
4.2 KiB
TypeScript
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/<path> (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/<digits> and batches/<digits>/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/<digits> and batches/<digits>/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);
|
|
}
|