where('business_id', auth()->user()->business_id) ->whereIn('type', ['debit', 'credit']); $total_cash_in = (clone $query) ->where('type', 'credit') ->sum('amount'); $total_cash_out = (clone $query) ->where('type', 'debit') ->sum('amount'); $total_running_cash = $total_cash_in - $total_cash_out; // Date Filter $duration = $request->custom_days ?: 'today'; [$filter_from_date, $filter_to_date] = $this->applyDateRange($duration, $request->from_date, $request->to_date); $this->applyDateFilter($query, $duration, 'date', $request->from_date, $request->to_date); // Search filter if ($request->filled('search')) { $query->where(function ($query) use ($request) { $query->where('date', 'like', '%' . $request->search . '%') ->orWhere('invoice_no', 'like', '%' . $request->search . '%') ->orWhere('platform', 'like', '%' . $request->search . '%') ->orWhere('amount', 'like', '%' . $request->search . '%') ->orWhere('transaction_type', 'like', '%' . $request->search . '%') ->orWhereHas('paymentType', function ($q) use ($request) { $q->where('name', 'like', '%' . $request->search . '%'); }); }); } // Platform filter if ($request->filled('platform')) { $query->where('platform', $request->platform); } // Paginate data $perPage = $request->input('per_page', 20); $cash_flows = $query->paginate($perPage)->appends($request->query()); $firstDate = $cash_flows->first()?->date; if ($firstDate) { $opening_balance = (clone $query) ->whereDate('date', '<', $firstDate) ->selectRaw("SUM(CASE WHEN type='credit' THEN amount ELSE 0 END) - SUM(CASE WHEN type='debit' THEN amount ELSE 0 END) as balance") ->value('balance') ?? 0; } else { $opening_balance = 0; } if ($request->ajax()) { return response()->json([ 'data' => view('business::cash-flow.datas', compact('cash_flows', 'total_cash_in', 'total_cash_out', 'opening_balance', 'total_running_cash', 'filter_from_date', 'filter_to_date', 'duration'))->render() ]); } return view('business::cash-flow.index', compact('cash_flows', 'total_cash_in', 'total_cash_out', 'opening_balance', 'total_running_cash', 'filter_from_date', 'filter_to_date', 'duration')); } public function exportExcel() { return Excel::download(new ExportCashFlowReport, 'cash-flow.xlsx'); } public function exportCsv() { return Excel::download(new ExportCashFlowReport, 'cash-flow.csv'); } public function exportPdf() { $cash_flows = Transaction::with([ 'paymentType:id,name', 'sale:id,party_id', 'sale.party:id,name', 'saleReturn:id,sale_id', 'purchase:id,party_id', 'purchase.party:id,name', 'purchaseReturn:id,purchase_id', 'dueCollect:id,party_id', 'dueCollect.party:id,name', ]) ->where('business_id', auth()->user()->business_id) ->whereIn('type', ['debit', 'credit']) ->latest() ->get(); $opening_balance = 0; return PdfService::render('business::cash-flow.pdf', compact('cash_flows', 'opening_balance'),'cash-flow-report.pdf'); } }