|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Modules\Finance\Http\Controllers; |
| 4 | + |
| 5 | +use App\Http\Controllers\Controller; |
| 6 | +use App\Modules\Finance\Models\Bill; |
| 7 | +use App\Modules\Finance\Models\Invoice; |
| 8 | +use Carbon\Carbon; |
| 9 | +use Illuminate\Http\Request; |
| 10 | +use Illuminate\Support\Facades\DB; |
| 11 | +use Inertia\Inertia; |
| 12 | +use Inertia\Response; |
| 13 | + |
| 14 | +class FinanceReportController extends Controller |
| 15 | +{ |
| 16 | + // GET /finance/reports/profit-loss |
| 17 | + public function profitLoss(Request $request): Response |
| 18 | + { |
| 19 | + $this->authorize('viewAny', Invoice::class); |
| 20 | + |
| 21 | + $tenantId = app('tenant')->id; |
| 22 | + $dateFrom = $request->get('date_from', now()->startOfYear()->toDateString()); |
| 23 | + $dateTo = $request->get('date_to', now()->toDateString()); |
| 24 | + |
| 25 | + // Revenue: sum payments for paid invoices |
| 26 | + $revenueRows = DB::table('invoices') |
| 27 | + ->join('payments', 'payments.invoice_id', '=', 'invoices.id') |
| 28 | + ->where('invoices.tenant_id', $tenantId) |
| 29 | + ->where('invoices.status', 'paid') |
| 30 | + ->whereNull('invoices.deleted_at') |
| 31 | + ->whereBetween('payments.payment_date', [$dateFrom, $dateTo]) |
| 32 | + ->select( |
| 33 | + DB::raw('YEAR(payments.payment_date) as year'), |
| 34 | + DB::raw('MONTH(payments.payment_date) as month'), |
| 35 | + DB::raw('SUM(payments.amount) as revenue') |
| 36 | + ) |
| 37 | + ->groupBy('year', 'month') |
| 38 | + ->orderBy('year') |
| 39 | + ->orderBy('month') |
| 40 | + ->get(); |
| 41 | + |
| 42 | + // Expenses: sum bill payments for paid bills |
| 43 | + $expenseRows = DB::table('bills') |
| 44 | + ->join('bill_payments', 'bill_payments.bill_id', '=', 'bills.id') |
| 45 | + ->where('bills.tenant_id', $tenantId) |
| 46 | + ->where('bills.status', 'paid') |
| 47 | + ->whereNull('bills.deleted_at') |
| 48 | + ->whereBetween('bill_payments.payment_date', [$dateFrom, $dateTo]) |
| 49 | + ->select( |
| 50 | + DB::raw('YEAR(bill_payments.payment_date) as year'), |
| 51 | + DB::raw('MONTH(bill_payments.payment_date) as month'), |
| 52 | + DB::raw('SUM(bill_payments.amount) as expenses') |
| 53 | + ) |
| 54 | + ->groupBy('year', 'month') |
| 55 | + ->orderBy('year') |
| 56 | + ->orderBy('month') |
| 57 | + ->get() |
| 58 | + ->keyBy(fn ($r) => $r->year . '-' . $r->month); |
| 59 | + |
| 60 | + $totalRevenue = (float) $revenueRows->sum('revenue'); |
| 61 | + $totalExpenses = (float) $expenseRows->sum('expenses'); |
| 62 | + $netProfit = $totalRevenue - $totalExpenses; |
| 63 | + |
| 64 | + $breakdown = $revenueRows->map(function ($row) use ($expenseRows) { |
| 65 | + $key = $row->year . '-' . $row->month; |
| 66 | + $expenses = (float) ($expenseRows->get($key)?->expenses ?? 0); |
| 67 | + $revenue = (float) $row->revenue; |
| 68 | + $net = $revenue - $expenses; |
| 69 | + $margin = $revenue > 0 ? round($net / $revenue * 100, 2) : 0; |
| 70 | + return [ |
| 71 | + 'year' => $row->year, |
| 72 | + 'month' => $row->month, |
| 73 | + 'label' => Carbon::createFromDate($row->year, $row->month, 1)->format('M Y'), |
| 74 | + 'revenue' => $revenue, |
| 75 | + 'expenses' => $expenses, |
| 76 | + 'net' => $net, |
| 77 | + 'margin' => $margin, |
| 78 | + ]; |
| 79 | + })->values(); |
| 80 | + |
| 81 | + return Inertia::render('Finance/Reports/ProfitLossSummary', [ |
| 82 | + 'date_from' => $dateFrom, |
| 83 | + 'date_to' => $dateTo, |
| 84 | + 'total_revenue' => $totalRevenue, |
| 85 | + 'total_expenses' => $totalExpenses, |
| 86 | + 'net_profit' => $netProfit, |
| 87 | + 'breakdown' => $breakdown, |
| 88 | + ]); |
| 89 | + } |
| 90 | + |
| 91 | + // GET /finance/reports/aged-receivables |
| 92 | + public function agedReceivables(Request $request): Response |
| 93 | + { |
| 94 | + $this->authorize('viewAny', Invoice::class); |
| 95 | + |
| 96 | + $tenantId = app('tenant')->id; |
| 97 | + $asOf = $request->get('as_of', now()->toDateString()); |
| 98 | + $asOfDate = Carbon::parse($asOf); |
| 99 | + |
| 100 | + $invoices = Invoice::with(['contact', 'items', 'payments']) |
| 101 | + ->where('tenant_id', $tenantId) |
| 102 | + ->whereNotIn('status', ['draft', 'paid', 'cancelled']) |
| 103 | + ->get() |
| 104 | + ->map(function ($inv) use ($asOfDate) { |
| 105 | + $daysOverdue = 0; |
| 106 | + $bucket = 'current'; |
| 107 | + if ($inv->due_date) { |
| 108 | + $diff = $asOfDate->diffInDays($inv->due_date, false); |
| 109 | + $daysOverdue = (int) max(0, $diff * -1); |
| 110 | + $bucket = match (true) { |
| 111 | + $daysOverdue === 0 => 'current', |
| 112 | + $daysOverdue <= 30 => '1-30', |
| 113 | + $daysOverdue <= 60 => '31-60', |
| 114 | + $daysOverdue <= 90 => '61-90', |
| 115 | + default => '91+', |
| 116 | + }; |
| 117 | + } |
| 118 | + return [ |
| 119 | + 'id' => $inv->id, |
| 120 | + 'number' => $inv->number, |
| 121 | + 'customer' => $inv->contact?->name ?? '—', |
| 122 | + 'due_date' => $inv->due_date?->toDateString(), |
| 123 | + 'amount' => (float) $inv->total, |
| 124 | + 'amount_due' => (float) $inv->amount_due, |
| 125 | + 'days_overdue' => $daysOverdue, |
| 126 | + 'bucket' => $bucket, |
| 127 | + ]; |
| 128 | + }); |
| 129 | + |
| 130 | + $bucketKeys = ['current', '1-30', '31-60', '61-90', '91+']; |
| 131 | + $totals = collect($bucketKeys)->mapWithKeys(fn ($k) => [ |
| 132 | + $k => (float) $invoices->where('bucket', $k)->sum('amount_due'), |
| 133 | + ])->all(); |
| 134 | + |
| 135 | + return Inertia::render('Finance/Reports/AgedReceivablesSummary', [ |
| 136 | + 'rows' => $invoices->values(), |
| 137 | + 'totals' => $totals, |
| 138 | + 'grand_total' => (float) $invoices->sum('amount_due'), |
| 139 | + 'as_of' => $asOf, |
| 140 | + ]); |
| 141 | + } |
| 142 | + |
| 143 | + // GET /finance/reports/aged-payables |
| 144 | + public function agedPayables(Request $request): Response |
| 145 | + { |
| 146 | + $this->authorize('viewAny', Bill::class); |
| 147 | + |
| 148 | + $tenantId = app('tenant')->id; |
| 149 | + $asOf = $request->get('as_of', now()->toDateString()); |
| 150 | + $asOfDate = Carbon::parse($asOf); |
| 151 | + |
| 152 | + $bills = Bill::with(['contact', 'items', 'payments']) |
| 153 | + ->where('tenant_id', $tenantId) |
| 154 | + ->whereNotIn('status', ['draft', 'paid', 'cancelled']) |
| 155 | + ->get() |
| 156 | + ->map(function ($bill) use ($asOfDate) { |
| 157 | + $daysOverdue = 0; |
| 158 | + $bucket = 'current'; |
| 159 | + if ($bill->due_date) { |
| 160 | + $diff = $asOfDate->diffInDays($bill->due_date, false); |
| 161 | + $daysOverdue = (int) max(0, $diff * -1); |
| 162 | + $bucket = match (true) { |
| 163 | + $daysOverdue === 0 => 'current', |
| 164 | + $daysOverdue <= 30 => '1-30', |
| 165 | + $daysOverdue <= 60 => '31-60', |
| 166 | + $daysOverdue <= 90 => '61-90', |
| 167 | + default => '91+', |
| 168 | + }; |
| 169 | + } |
| 170 | + return [ |
| 171 | + 'id' => $bill->id, |
| 172 | + 'number' => $bill->number, |
| 173 | + 'supplier' => $bill->contact?->name ?? '—', |
| 174 | + 'due_date' => $bill->due_date?->toDateString(), |
| 175 | + 'amount' => (float) $bill->total, |
| 176 | + 'amount_due' => (float) $bill->amount_due, |
| 177 | + 'days_overdue' => $daysOverdue, |
| 178 | + 'bucket' => $bucket, |
| 179 | + ]; |
| 180 | + }); |
| 181 | + |
| 182 | + $bucketKeys = ['current', '1-30', '31-60', '61-90', '91+']; |
| 183 | + $totals = collect($bucketKeys)->mapWithKeys(fn ($k) => [ |
| 184 | + $k => (float) $bills->where('bucket', $k)->sum('amount_due'), |
| 185 | + ])->all(); |
| 186 | + |
| 187 | + return Inertia::render('Finance/Reports/AgedPayablesSummary', [ |
| 188 | + 'rows' => $bills->values(), |
| 189 | + 'totals' => $totals, |
| 190 | + 'grand_total' => (float) $bills->sum('amount_due'), |
| 191 | + 'as_of' => $asOf, |
| 192 | + ]); |
| 193 | + } |
| 194 | + |
| 195 | + // GET /finance/reports/invoice-summary |
| 196 | + public function invoiceSummary(Request $request): Response |
| 197 | + { |
| 198 | + $this->authorize('viewAny', Invoice::class); |
| 199 | + |
| 200 | + $tenantId = app('tenant')->id; |
| 201 | + $dateFrom = $request->get('date_from', now()->startOfMonth()->toDateString()); |
| 202 | + $dateTo = $request->get('date_to', now()->toDateString()); |
| 203 | + |
| 204 | + $invoices = Invoice::with(['contact', 'items', 'payments']) |
| 205 | + ->where('tenant_id', $tenantId) |
| 206 | + ->whereBetween('issue_date', [$dateFrom, $dateTo]) |
| 207 | + ->get(); |
| 208 | + |
| 209 | + $statuses = ['draft', 'sent', 'partial', 'paid', 'cancelled']; |
| 210 | + |
| 211 | + $summary = collect($statuses)->mapWithKeys(function ($status) use ($invoices) { |
| 212 | + $group = $invoices->where('status', $status); |
| 213 | + return [$status => [ |
| 214 | + 'count' => $group->count(), |
| 215 | + 'amount' => (float) $group->sum(fn ($i) => $i->total), |
| 216 | + ]]; |
| 217 | + })->all(); |
| 218 | + |
| 219 | + // Overdue: sent/partial with due_date in the past |
| 220 | + $overdueInvoices = $invoices->filter(fn ($i) => |
| 221 | + in_array($i->status, ['sent', 'partial']) && |
| 222 | + $i->due_date !== null && |
| 223 | + $i->due_date->isPast() |
| 224 | + ); |
| 225 | + |
| 226 | + $summary['overdue'] = [ |
| 227 | + 'count' => $overdueInvoices->count(), |
| 228 | + 'amount' => (float) $overdueInvoices->sum(fn ($i) => $i->amount_due), |
| 229 | + ]; |
| 230 | + |
| 231 | + $table = $invoices->map(fn ($inv) => [ |
| 232 | + 'id' => $inv->id, |
| 233 | + 'number' => $inv->number, |
| 234 | + 'customer' => $inv->contact?->name ?? '—', |
| 235 | + 'issue_date'=> $inv->issue_date?->toDateString(), |
| 236 | + 'due_date' => $inv->due_date?->toDateString(), |
| 237 | + 'status' => $inv->status, |
| 238 | + 'total' => (float) $inv->total, |
| 239 | + 'amount_due'=> (float) $inv->amount_due, |
| 240 | + ])->values(); |
| 241 | + |
| 242 | + return Inertia::render('Finance/Reports/InvoiceSummary', [ |
| 243 | + 'date_from' => $dateFrom, |
| 244 | + 'date_to' => $dateTo, |
| 245 | + 'summary' => $summary, |
| 246 | + 'total_count' => $invoices->count(), |
| 247 | + 'total_amount'=> (float) $invoices->sum(fn ($i) => $i->total), |
| 248 | + 'invoices' => $table, |
| 249 | + ]); |
| 250 | + } |
| 251 | + |
| 252 | + // GET /finance/reports/expense-summary |
| 253 | + public function expenseSummary(Request $request): Response |
| 254 | + { |
| 255 | + $this->authorize('viewAny', Bill::class); |
| 256 | + |
| 257 | + $tenantId = app('tenant')->id; |
| 258 | + $dateFrom = $request->get('date_from', now()->startOfMonth()->toDateString()); |
| 259 | + $dateTo = $request->get('date_to', now()->toDateString()); |
| 260 | + |
| 261 | + $bills = Bill::with(['contact', 'items', 'payments']) |
| 262 | + ->where('tenant_id', $tenantId) |
| 263 | + ->whereBetween('issue_date', [$dateFrom, $dateTo]) |
| 264 | + ->get(); |
| 265 | + |
| 266 | + $statuses = ['draft', 'received', 'partial', 'paid', 'cancelled']; |
| 267 | + |
| 268 | + $summary = collect($statuses)->mapWithKeys(function ($status) use ($bills) { |
| 269 | + $group = $bills->where('status', $status); |
| 270 | + return [$status => [ |
| 271 | + 'count' => $group->count(), |
| 272 | + 'amount' => (float) $group->sum(fn ($b) => $b->total), |
| 273 | + ]]; |
| 274 | + })->all(); |
| 275 | + |
| 276 | + $overdueBills = $bills->filter(fn ($b) => |
| 277 | + in_array($b->status, ['received', 'partial']) && |
| 278 | + $b->due_date !== null && |
| 279 | + $b->due_date->isPast() |
| 280 | + ); |
| 281 | + |
| 282 | + $summary['overdue'] = [ |
| 283 | + 'count' => $overdueBills->count(), |
| 284 | + 'amount' => (float) $overdueBills->sum(fn ($b) => $b->amount_due), |
| 285 | + ]; |
| 286 | + |
| 287 | + $table = $bills->map(fn ($bill) => [ |
| 288 | + 'id' => $bill->id, |
| 289 | + 'number' => $bill->number, |
| 290 | + 'supplier' => $bill->contact?->name ?? '—', |
| 291 | + 'issue_date'=> $bill->issue_date?->toDateString(), |
| 292 | + 'due_date' => $bill->due_date?->toDateString(), |
| 293 | + 'status' => $bill->status, |
| 294 | + 'total' => (float) $bill->total, |
| 295 | + 'amount_due'=> (float) $bill->amount_due, |
| 296 | + ])->values(); |
| 297 | + |
| 298 | + return Inertia::render('Finance/Reports/ExpenseSummary', [ |
| 299 | + 'date_from' => $dateFrom, |
| 300 | + 'date_to' => $dateTo, |
| 301 | + 'summary' => $summary, |
| 302 | + 'total_count' => $bills->count(), |
| 303 | + 'total_amount'=> (float) $bills->sum(fn ($b) => $b->total), |
| 304 | + 'bills' => $table, |
| 305 | + ]); |
| 306 | + } |
| 307 | +} |
0 commit comments