middleware('check.permission:stock-reports.read')->only(['index']); } public function index(Request $request) { $businessId = auth()->user()->business_id; $productsQuery = Product::with(['stocks' => function ($q) { $q->select('id', 'product_id', 'productStock', 'productPurchasePrice', 'productSalePrice'); }]) ->where('business_id', $businessId) ->where('product_type', '!=', 'combo'); if ($request->search) { $productsQuery->where(function ($q) use ($request) { $q->where('productName', 'like', '%' . $request->search . '%') ->orWhereHas('stocks', function ($stock) use ($request) { $stock->where('productSalePrice', 'like', '%' . $request->search . '%') ->orWhere('productPurchasePrice', 'like', '%' . $request->search . '%'); }); }); } $stock_reports = $productsQuery ->latest() ->paginate($request->per_page ?? 20) ->appends($request->query()); $total_qty = $stock_reports->getCollection()->sum(function ($product) { return $product->stocks->sum('productStock'); }); $total_stock_value = $stock_reports->getCollection()->sum(function ($product) { return $product->stocks->sum(function ($stock) { return $stock->productStock * $stock->productPurchasePrice; }); }); if ($request->ajax()) { return response()->json([ 'data' => view('business::reports.stocks.datas', compact('stock_reports'))->render(), 'total_stock_value' => currency_format($total_stock_value, currency: business_currency()), 'total_qty' => $total_qty ]); } return view('business::reports.stocks.stock-reports', compact('stock_reports', 'total_stock_value', 'total_qty')); } public function exportExcel() { return Excel::download(new ExportCurrentStockReport, 'current-stock-report.xlsx'); } public function exportCsv() { return Excel::download(new ExportCurrentStockReport, 'current-stock-report.csv'); } public function exportPdf(Request $request) { $productsQuery = Product::with(['stocks' => function ($q) { $q->select('id', 'product_id', 'productStock', 'productPurchasePrice', 'productSalePrice'); }]) ->where('business_id', auth()->user()->business_id) ->where('product_type', '!=', 'combo'); if ($request->search) { $productsQuery->where(function ($q) use ($request) { $q->where('productName', 'like', '%' . $request->search . '%') ->orWhereHas('stocks', function ($stock) use ($request) { $stock->where('productSalePrice', 'like', '%' . $request->search . '%') ->orWhere('productPurchasePrice', 'like', '%' . $request->search . '%'); }); }); } $stock_reports = $productsQuery ->latest() ->limit($request->per_page ?? 20) ->get(); return PdfService::render('business::reports.stocks.pdf', compact('stock_reports'), 'stock-report.pdf'); } }