with(['warehouse', 'material']) ->when($request->warehouse_id, fn($q, $v) => $q->where('warehouse_id', $v)) ->when($request->material_id, fn($q, $v) => $q->where('material_id', $v)) ->when($request->low_stock, fn($q) => $q->whereRaw('quantity <= (SELECT min_stock FROM materials WHERE materials.id = inventories.material_id AND min_stock IS NOT NULL)')); return $this->paginate($query->paginate($request->input('per_page', 20))); } /** * 导出库存台账 * GET /inventory/stock/export */ public function export(Request $request): JsonResponse { $rows = Inventory::with(['warehouse', 'material']) ->when($request->warehouse_id, fn($q, $v) => $q->where('warehouse_id', $v)) ->get() ->map(fn($inv) => [ 'warehouse' => $inv->warehouse?->name, 'material_code' => $inv->material?->code, 'material_name' => $inv->material?->name, 'unit' => $inv->material?->unit, 'quantity' => $inv->quantity, 'batch_no' => $inv->batch_no, 'expire_date' => $inv->expire_date?->toDateString(), 'safety_stock' => $inv->material?->min_stock, 'updated_at' => $inv->updated_at?->toDateTimeString(), ]); return $this->success(['rows' => $rows, 'total' => $rows->count()]); } }