ReportController.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Order;
  5. class ReportController extends Controller
  6. {
  7. public function accounting()
  8. {
  9. $orders = Order::where('status', '>=', 2)->whereHas('goods')->latest()->get(['created_at', 'amount']);
  10. $ordersByDay = $orders->where('created_at', '>=', date('Y-m-01', strtotime('-1 months')))->groupBy(function ($item) {
  11. return $item->created_at->format('Y-m-d');
  12. })->map(function ($row) {
  13. return $row->sum('amount');
  14. })->toArray();
  15. $ordersByMonth = $orders->where('created_at', '>=', date('Y-01-01', strtotime('-1 years')))->groupBy(function ($item) {
  16. return $item->created_at->format('Y-m');
  17. })->map(function ($row) {
  18. return $row->sum('amount');
  19. })->toArray();
  20. $ordersByYear = $orders->groupBy(function ($item) {
  21. return $item->created_at->format('Y');
  22. })->map(function ($row) {
  23. return $row->sum('amount');
  24. })->sort()->toArray();
  25. $currentDays = date('j');
  26. $lastDays = date('t', strtotime('-1 months'));
  27. $data['days'] = range(1, $currentDays > $lastDays ? $currentDays : $lastDays);
  28. $data['years'] = range(1, 12);
  29. for ($i = 1; $i <= $currentDays; $i++) {
  30. $data['currentMonth'][] = $ordersByDay[date(sprintf('Y-m-%02u', $i))] ?? 0;
  31. }
  32. for ($i = 1; $i <= $lastDays; $i++) {
  33. $data['lastMonth'][] = $ordersByDay[date(sprintf('Y-m-%02u', $i), strtotime('-1 months'))] ?? 0;
  34. }
  35. for ($i = 1; $i <= date('m'); $i++) {
  36. $data['currentYear'][] = $ordersByMonth[date(sprintf('Y-%02u', $i))] ?? 0;
  37. }
  38. for ($i = 1; $i <= 12; $i++) {
  39. $data['lastYear'][] = $ordersByMonth[date(sprintf('Y-%02u', $i), strtotime('-1 years'))] ?? 0;
  40. }
  41. ksort($ordersByYear);
  42. $data['ordersByYear'] = $ordersByYear;
  43. return view('admin.report.accounting', compact('data'));
  44. }
  45. }