Reports.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Illuminate\Support\Facades\Auth;
  5. use Carbon\Carbon;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. use App\Models\Course;
  9. use App\Models\MemberCard;
  10. class Reports extends Component
  11. {
  12. public $type = 'anagrafica';
  13. public $seasonFilter;
  14. public $courses = [];
  15. public $selectedCourse = null;
  16. public function mount()
  17. {
  18. if (Auth::user()->level != env('LEVEL_ADMIN', 0))
  19. return redirect()->to('/reports');
  20. if (isset($_GET["type"]))
  21. $this->type = $_GET["type"];
  22. $this->seasonFilter = $this->getCurrentSeason();
  23. $this->courses = $this->getCoursesForSelect();
  24. }
  25. public function render()
  26. {
  27. return view('livewire.reports');
  28. }
  29. /**
  30. * Get current season in format "2024-2025"
  31. */
  32. private function getCurrentSeason()
  33. {
  34. $now = Carbon::now();
  35. $currentYear = $now->year;
  36. // If we're in September-December, season is current year to next year
  37. // If we're in January-August, season is previous year to current year
  38. if ($now->month >= 9) {
  39. return $currentYear . '-' . ($currentYear + 1);
  40. } else {
  41. return ($currentYear - 1) . '-' . $currentYear;
  42. }
  43. }
  44. /**
  45. * Get available seasons for dropdown
  46. */
  47. public function getAvailableSeasons()
  48. {
  49. $seasons = [];
  50. $currentYear = Carbon::now()->year;
  51. $startYear = 2020; // Adjust based on your data
  52. // If current month is September or later, include next season
  53. $endYear = Carbon::now()->month >= 9 ? $currentYear + 1 : $currentYear;
  54. for ($year = $startYear; $year <= $endYear; $year++) {
  55. $seasons[] = $year . '-' . ($year + 1);
  56. }
  57. return array_reverse($seasons); // Most recent first
  58. }
  59. /**
  60. * Parse season string to get start and end years
  61. */
  62. private function parseSeason($season)
  63. {
  64. $parts = explode('-', $season);
  65. return [
  66. 'start_year' => (int)$parts[0],
  67. 'end_year' => (int)$parts[1]
  68. ];
  69. }
  70. /**
  71. * Get date range for a season (September 1st to August 31st)
  72. */
  73. private function getSeasonDateRange($season)
  74. {
  75. $years = $this->parseSeason($season);
  76. return [
  77. 'start' => Carbon::create($years['start_year'], 9, 1), // September 1st
  78. 'end' => Carbon::create($years['end_year'], 8, 31) // August 31st
  79. ];
  80. }
  81. public function setSelectedCourse($courseId)
  82. {
  83. $this->selectedCourse = $courseId;
  84. Log::info('Selected course set to: ' . $courseId);
  85. return $this->getCourseMonthlyEarnings();
  86. }
  87. public function getTesseratiData()
  88. {
  89. $endYear = $this->parseSeason($this->seasonFilter)['end_year'];
  90. return self::getMemberCountChartData($endYear);
  91. }
  92. public function change($type)
  93. {
  94. $this->type = $type;
  95. }
  96. public function updateCharts()
  97. {
  98. $this->courses = $this->getCoursesForSelect();
  99. $this->emit('chartsUpdated');
  100. $this->dispatchBrowserEvent('chartsUpdated');
  101. }
  102. public function updateCourseChart()
  103. {
  104. $this->emit('chartsUpdated');
  105. $this->dispatchBrowserEvent('chartsUpdated');
  106. }
  107. public function updatedSeasonFilter()
  108. {
  109. $this->courses = $this->getCoursesForSelect();
  110. $this->emit('chartsUpdated');
  111. $this->dispatchBrowserEvent('chartsUpdated');
  112. }
  113. public function setSeasonFilter($season)
  114. {
  115. $this->seasonFilter = $season;
  116. }
  117. public function getMonthlyTotals()
  118. {
  119. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  120. Log::info('Getting monthly totals for season: ' . $this->seasonFilter);
  121. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  122. $monthNames = ['Set', 'Ott', 'Nov', 'Dic', 'Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago'];
  123. $incomeData = array_fill(0, 12, 0);
  124. $expenseData = array_fill(0, 12, 0);
  125. Log::info('Date range: ' . $dateRange['start'] . ' to ' . $dateRange['end']);
  126. // Get income records with detailed logging
  127. $incomeRecords = DB::table('records')
  128. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  129. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  130. ->where('records.type', 'IN')
  131. ->select(DB::raw('MONTH(records.date) as month_num'), DB::raw('SUM(records_rows.amount) as total'))
  132. ->groupBy('month_num')
  133. ->get();
  134. Log::info('Income records found: ' . $incomeRecords->count());
  135. foreach ($incomeRecords as $record) {
  136. Log::info("Income - Month: {$record->month_num}, Total: {$record->total}");
  137. }
  138. // Get expense records with detailed logging
  139. $expenseRecords = DB::table('records')
  140. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  141. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  142. ->where('records.type', 'OUT')
  143. ->select(DB::raw('MONTH(records.date) as month_num'), DB::raw('SUM(records_rows.amount) as total'))
  144. ->groupBy('month_num')
  145. ->get();
  146. Log::info('Expense records found: ' . $expenseRecords->count());
  147. foreach ($expenseRecords as $record) {
  148. Log::info("Expense - Month: {$record->month_num}, Total: {$record->total}");
  149. }
  150. // Process income records
  151. foreach ($incomeRecords as $record) {
  152. $monthIndex = array_search($record->month_num, $monthOrder);
  153. if ($monthIndex !== false) {
  154. $incomeData[$monthIndex] = $record->total;
  155. // Special logging for May (month 5)
  156. if ($record->month_num == 5) {
  157. Log::info("MAY INCOME DETECTED:");
  158. Log::info("- Month number: {$record->month_num}");
  159. Log::info("- Total amount: {$record->total}");
  160. Log::info("- Array index: {$monthIndex}");
  161. Log::info("- Month name: Mag");
  162. // Get detailed May records for debugging
  163. $mayIncomeDetails = DB::table('records')
  164. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  165. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  166. ->where('records.type', 'IN')
  167. ->whereRaw('MONTH(records.date) = 5')
  168. ->select('records.date', 'records_rows.amount')
  169. ->get();
  170. Log::info("May income detail records count: " . $mayIncomeDetails->count());
  171. foreach ($mayIncomeDetails as $detail) {
  172. Log::info("May record - Date: {$detail->date}, Amount: {$detail->amount}");
  173. }
  174. }
  175. }
  176. }
  177. // Process expense records
  178. foreach ($expenseRecords as $record) {
  179. $monthIndex = array_search($record->month_num, $monthOrder);
  180. if ($monthIndex !== false) {
  181. $expenseData[$monthIndex] = $record->total;
  182. // Special logging for May (month 5)
  183. if ($record->month_num == 5) {
  184. Log::info("MAY EXPENSE DETECTED:");
  185. Log::info("- Month number: {$record->month_num}");
  186. Log::info("- Total amount: {$record->total}");
  187. Log::info("- Array index: {$monthIndex}");
  188. Log::info("- Month name: Mag");
  189. // Get detailed May records for debugging
  190. $mayExpenseDetails = DB::table('records')
  191. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  192. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  193. ->where('records.type', 'OUT')
  194. ->whereRaw('MONTH(records.date) = 5')
  195. ->select('records.date', 'records_rows.amount')
  196. ->get();
  197. Log::info("May expense detail records count: " . $mayExpenseDetails->count());
  198. foreach ($mayExpenseDetails as $detail) {
  199. Log::info("May record - Date: {$detail->date}, Amount: {$detail->amount}");
  200. }
  201. }
  202. }
  203. }
  204. // Log final arrays
  205. Log::info('Final income data array: ' . json_encode($incomeData));
  206. Log::info('Final expense data array: ' . json_encode($expenseData));
  207. // Specifically log May position (index 8 in our academic year order)
  208. Log::info("May position in chart:");
  209. Log::info("- Income for May (index 8): " . $incomeData[8]);
  210. Log::info("- Expense for May (index 8): " . $expenseData[8]);
  211. return [
  212. 'labels' => $monthNames,
  213. 'datasets' => [
  214. [
  215. 'label' => 'Entrate',
  216. 'data' => $incomeData,
  217. 'backgroundColor' => 'rgba(54, 162, 235, 0.5)'
  218. ],
  219. [
  220. 'label' => 'Uscite',
  221. 'data' => $expenseData,
  222. 'backgroundColor' => 'rgba(255, 99, 132, 0.5)'
  223. ],
  224. ]
  225. ];
  226. }
  227. public function getYearlySummary()
  228. {
  229. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  230. $totalIncome = DB::table('records')
  231. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  232. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  233. ->where('records.type', 'IN')
  234. ->sum('records_rows.amount');
  235. $totalExpenses = DB::table('records')
  236. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  237. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  238. ->where('records.type', 'OUT')
  239. ->sum('records_rows.amount');
  240. $delta = $totalIncome - $totalExpenses;
  241. return [
  242. 'totalIncome' => $totalIncome,
  243. 'totalExpenses' => $totalExpenses,
  244. 'delta' => $delta
  245. ];
  246. }
  247. public function getTopCausalsByAmount($limit = 10)
  248. {
  249. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  250. $query = DB::table('records_rows')
  251. ->join('records', 'records_rows.record_id', '=', 'records.id')
  252. ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
  253. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']]);
  254. $query->where('records.type', 'IN');
  255. Log::info('Query: ' . $query->toSql());
  256. $causals = $query->select(
  257. 'causals.id',
  258. 'causals.name',
  259. 'causals.parent_id',
  260. DB::raw('SUM(records_rows.amount) as total_amount')
  261. )
  262. ->groupBy('causals.id', 'causals.name', 'causals.parent_id')
  263. ->orderBy('total_amount', 'desc')
  264. ->limit($limit)
  265. ->get();
  266. Log::info('Causals: ' . json_encode(value: $causals));
  267. $inData = [];
  268. foreach ($causals as $causal) {
  269. $tempCausal = new \App\Models\Causal();
  270. $tempCausal->id = $causal->id;
  271. $tempCausal->name = $causal->name;
  272. $tempCausal->parent_id = $causal->parent_id;
  273. $treeName = $tempCausal->getTree();
  274. $displayName = strlen($treeName) > 30 ? substr($treeName, 0, 27) . '...' : $treeName;
  275. $inData[] = [
  276. 'label' => $displayName,
  277. 'value' => $causal->total_amount,
  278. 'fullName' => $treeName
  279. ];
  280. }
  281. usort($inData, function ($a, $b) {
  282. return $b['value'] <=> $a['value'];
  283. });
  284. $inData = array_slice($inData, 0, $limit);
  285. return [
  286. 'inLabels' => array_column($inData, 'label'),
  287. 'inData' => $inData,
  288. 'datasets' => [
  289. [
  290. 'label' => 'Entrate per Causale',
  291. 'data' => array_column($inData, 'value'),
  292. ]
  293. ]
  294. ];
  295. }
  296. public function getCoursesForSelect()
  297. {
  298. $seasonYears = $this->parseSeason($this->seasonFilter);
  299. $courses = Course::with(['level', 'type', 'frequency'])
  300. ->where('active', true)
  301. ->where(function($query) use ($seasonYears) {
  302. $query->where('year', 'like', '%' . $seasonYears['start_year'] . '%')
  303. ->orWhere('year', 'like', '%' . $seasonYears['end_year'] . '%')
  304. ->orWhere('year', 'like', '%' . $this->seasonFilter . '%');
  305. })
  306. ->orderBy('name')
  307. ->get()
  308. ->map(function ($course) {
  309. $type = null;
  310. if (!empty($course->course_type_id)) {
  311. $type = \App\Models\CourseType::find($course->course_type_id);
  312. if ($type) {
  313. $typeName = $type->name;
  314. }
  315. }
  316. $levelName = is_object($course->level) ? $course->level->name : 'No Level';
  317. $typeName = is_object($type) ? $type->name : 'No Type';
  318. $frequencyName = is_object($course->frequency) ? $course->frequency->name : 'No Frequency';
  319. $year = $course->year ?? '';
  320. return [
  321. 'id' => $course->id,
  322. 'name' => $course->name,
  323. 'full_name' => "{$course->name} - {$levelName} - {$typeName} - {$frequencyName} ({$year})",
  324. 'level_name' => $levelName,
  325. 'type_name' => $typeName,
  326. 'frequency_name' => $frequencyName,
  327. 'year' => $year
  328. ];
  329. })->toArray();
  330. return $courses;
  331. }
  332. public function getCourseMonthlyEarnings()
  333. {
  334. $courseId = $this->selectedCourse;
  335. Log::info('Getting earnings for course ID: ' . $courseId);
  336. // September to August order for academic year
  337. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  338. $monthNames = [
  339. 9 => 'Set', 10 => 'Ott', 11 => 'Nov', 12 => 'Dic',
  340. 1 => 'Gen', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr',
  341. 5 => 'Mag', 6 => 'Giu', 7 => 'Lug', 8 => 'Ago'
  342. ];
  343. if (empty($courseId)) {
  344. return [
  345. 'labels' => array_values($monthNames),
  346. 'datasets' => [
  347. [
  348. 'label' => 'Pagamenti Effettuati',
  349. 'backgroundColor' => 'rgba(0, 184, 148, 1)',
  350. 'data' => array_fill(0, 12, 0),
  351. 'type' => 'bar',
  352. 'order' => 3
  353. ],
  354. [
  355. 'label' => 'Pagamenti Attesi',
  356. 'backgroundColor' => 'transparent',
  357. 'borderColor' => 'rgba(48, 51, 107, 1)',
  358. 'borderWidth' => 3,
  359. 'pointBackgroundColor' => 'rgba(48, 51, 107, 1)',
  360. 'pointRadius' => 5,
  361. 'data' => array_fill(0, 12, 0),
  362. 'type' => 'line',
  363. 'tension' => 0.2,
  364. 'order' => 2
  365. ]
  366. ]
  367. ];
  368. }
  369. $monthlyData = [];
  370. foreach ($monthOrder as $i) {
  371. $monthlyData[$i] = [
  372. 'earned' => 0,
  373. 'total' => 0,
  374. 'participants' => 0
  375. ];
  376. }
  377. $memberCourses = \App\Models\MemberCourse::where('course_id', $courseId)
  378. ->with('member')
  379. ->get();
  380. foreach ($memberCourses as $memberCourse) {
  381. $price = (float)($memberCourse->price ?? 0);
  382. if ($memberCourse->months) {
  383. $monthsData = json_decode($memberCourse->months, true);
  384. if (is_array($monthsData)) {
  385. foreach ($monthsData as $monthData) {
  386. $month = $monthData['m'] ?? null;
  387. $status = $monthData['status'] ?? '';
  388. if ($month !== null && isset($monthlyData[$month])) {
  389. $monthlyData[$month]['total'] += $price;
  390. if ($status === 1) {
  391. $monthlyData[$month]['earned'] += $price;
  392. }
  393. $monthlyData[$month]['participants']++;
  394. }
  395. }
  396. }
  397. }
  398. }
  399. $labels = [];
  400. $earnedData = [];
  401. $totalData = [];
  402. $participantData = [];
  403. $missingData = [];
  404. foreach ($monthOrder as $month) {
  405. $labels[] = $monthNames[$month];
  406. $earnedData[] = round($monthlyData[$month]['earned'], 2);
  407. $totalData[] = round($monthlyData[$month]['total'], 2);
  408. $participantData[] = $monthlyData[$month]['participants'];
  409. $missingData[] = round($monthlyData[$month]['total'] - $monthlyData[$month]['earned'], 2);
  410. }
  411. return [
  412. 'labels' => $labels,
  413. 'datasets' => [
  414. [
  415. 'label' => 'Pagamenti Effettuati',
  416. 'backgroundColor' => 'rgba(0, 184, 148, 1)',
  417. 'data' => $earnedData,
  418. 'type' => 'bar',
  419. 'order' => 3
  420. ],
  421. [
  422. 'label' => 'Pagamenti Attesi',
  423. 'backgroundColor' => 'transparent',
  424. 'borderColor' => 'rgba(48, 51, 107, 1)',
  425. 'borderWidth' => 3,
  426. 'pointBackgroundColor' => 'rgba(48, 51, 107, 1)',
  427. 'pointRadius' => 5,
  428. 'data' => $totalData,
  429. 'type' => 'line',
  430. 'tension' => 0.2,
  431. 'order' => 2,
  432. 'participants' => $participantData,
  433. 'missing' => $missingData
  434. ]
  435. ]
  436. ];
  437. }
  438. public static function getMemberCountChartData($endYear = null, $span = 5)
  439. {
  440. if ($endYear === null) {
  441. $endYear = date('Y');
  442. }
  443. $startYear = $endYear - $span + 1;
  444. $memberCards = MemberCard::select('member_id', 'expire_date')
  445. ->whereNotNull('expire_date')
  446. ->whereNotNull('member_id')
  447. ->where('status', '!=', 'cancelled')
  448. ->whereRaw('YEAR(expire_date) >= ?', [$startYear])
  449. ->whereRaw('YEAR(expire_date) <= ?', [$endYear])
  450. ->get();
  451. $seasonCounts = [];
  452. for ($year = $startYear; $year <= $endYear; $year++) {
  453. $seasonPeriod = ($year - 1) . '-' . $year;
  454. $seasonCounts[$seasonPeriod] = [];
  455. }
  456. foreach ($memberCards as $card) {
  457. $expireYear = date('Y', strtotime($card->expire_date));
  458. $expireMonth = date('n', strtotime($card->expire_date));
  459. // Determine which season this belongs to
  460. if ($expireMonth >= 9) {
  461. // September-December: belongs to season starting that year
  462. $seasonPeriod = $expireYear . '-' . ($expireYear + 1);
  463. } else {
  464. // January-August: belongs to season starting previous year
  465. $seasonPeriod = ($expireYear - 1) . '-' . $expireYear;
  466. }
  467. if (isset($seasonCounts[$seasonPeriod])) {
  468. $seasonCounts[$seasonPeriod][$card->member_id] = true;
  469. }
  470. }
  471. $seasonLabels = [];
  472. $memberCountData = [];
  473. foreach ($seasonCounts as $seasonPeriod => $members) {
  474. $seasonLabels[] = $seasonPeriod;
  475. $memberCountData[] = count($members);
  476. }
  477. return [
  478. 'labels' => $seasonLabels,
  479. 'datasets' => [
  480. [
  481. 'label' => 'Membri Tesserati',
  482. 'data' => $memberCountData,
  483. 'backgroundColor' => 'rgba(54, 162, 235, 0.2)',
  484. 'borderColor' => 'rgba(54, 162, 235, 1)',
  485. 'borderWidth' => 2,
  486. 'pointBackgroundColor' => 'rgba(54, 162, 235, 1)',
  487. 'pointRadius' => 4,
  488. 'tension' => 0.3,
  489. 'fill' => true
  490. ]
  491. ]
  492. ];
  493. }
  494. }