import { NextRequest, NextResponse } from "next/server"; import { connectDb } from "@/lib/server/db"; import { StockMovement } from "@/lib/server/models/StockMovement"; import { authorize, branchParam, MANAGERS } from "@/lib/server/auth"; import { scopedPopulate } from "@/lib/server/tenantGuard"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; // GET /api/stock/movements?branchId=&limit= — recent ledger entries, newest first. export async function GET(req: NextRequest) { await connectDb(); const gate = authorize(req, MANAGERS); if (!gate.ok) return gate.response; const auth = gate.auth; const scope = branchParam(auth, req.nextUrl.searchParams.get("branchId")); if (!scope.ok) return scope.response; const limit = Math.min(Number(req.nextUrl.searchParams.get("limit")) || 50, 200); const filter: Record = { businessId: auth.businessId }; if (scope.branchId) filter.branchId = scope.branchId; const movements = await StockMovement.find(filter) .sort({ createdAt: -1 }) .limit(limit) .populate(scopedPopulate("branchId", "branchName", auth.businessId)) .populate(scopedPopulate("productId", "label unit", auth.businessId)) .populate(scopedPopulate("recordedBy", "name", auth.businessId)) .lean(); return NextResponse.json({ movements }); }