Reports.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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 ($now->month >= 9) {
  37. return $currentYear . '-' . ($currentYear + 1);
  38. } else {
  39. return ($currentYear - 1) . '-' . $currentYear;
  40. }
  41. }
  42. /**
  43. * Get available seasons for dropdown
  44. */
  45. public function getAvailableSeasons()
  46. {
  47. $seasons = [];
  48. $currentYear = Carbon::now()->year;
  49. $startYear = 2023;
  50. $endYear = Carbon::now()->month >= 9 ? $currentYear + 1 : $currentYear;
  51. for ($year = $startYear; $year < $endYear; $year++) {
  52. $seasons[] = $year . '-' . ($year + 1);
  53. }
  54. return array_reverse($seasons);
  55. }
  56. /**
  57. * Parse season string to get start and end years
  58. */
  59. private function parseSeason($season)
  60. {
  61. $parts = explode('-', $season);
  62. return [
  63. 'start_year' => (int)$parts[0],
  64. 'end_year' => (int)$parts[1]
  65. ];
  66. }
  67. /**
  68. * Get date range for a season (September 1st to August 31st)
  69. */
  70. private function getSeasonDateRange($season)
  71. {
  72. $years = $this->parseSeason($season);
  73. return [
  74. 'start' => Carbon::create($years['start_year'], 9, 1), // September 1st
  75. 'end' => Carbon::create($years['end_year'], 8, 31) // August 31st
  76. ];
  77. }
  78. public function setSelectedCourse($courseId)
  79. {
  80. $this->selectedCourse = $courseId;
  81. Log::info('Selected course set to: ' . $courseId);
  82. return $this->getCourseMonthlyEarnings();
  83. }
  84. public function getTesseratiData()
  85. {
  86. $endYear = $this->parseSeason($this->seasonFilter)['end_year'];
  87. return self::getMemberCountChartData($endYear);
  88. }
  89. public function change($type)
  90. {
  91. $this->type = $type;
  92. }
  93. public function updateCharts()
  94. {
  95. $this->courses = $this->getCoursesForSelect();
  96. $this->emit('chartsUpdated');
  97. $this->dispatchBrowserEvent('chartsUpdated');
  98. }
  99. public function updateCourseChart()
  100. {
  101. $this->emit('chartsUpdated');
  102. $this->dispatchBrowserEvent('chartsUpdated');
  103. }
  104. public function updatedSeasonFilter()
  105. {
  106. $this->courses = $this->getCoursesForSelect();
  107. $this->emit('chartsUpdated');
  108. $this->dispatchBrowserEvent('chartsUpdated');
  109. }
  110. public function setSeasonFilter($season)
  111. {
  112. $this->seasonFilter = $season;
  113. }
  114. public function getMonthlyTotals()
  115. {
  116. Log::info('=== getMonthlyTotals called ===');
  117. Log::info('Current seasonFilter: ' . $this->seasonFilter);
  118. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  119. Log::info('Date range start: ' . $dateRange['start']);
  120. Log::info('Date range end: ' . $dateRange['end']);
  121. // September to August order
  122. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  123. $monthNames = ['Set', 'Ott', 'Nov', 'Dic', 'Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago'];
  124. $incomeData = array_fill(0, 12, 0);
  125. $expenseData = array_fill(0, 12, 0);
  126. // Get income records within season date range
  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. // Get expense records within season date range
  135. $expenseRecords = DB::table('records')
  136. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  137. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  138. ->where('records.type', 'OUT')
  139. ->select(DB::raw('MONTH(records.date) as month_num'), DB::raw('SUM(records_rows.amount) as total'))
  140. ->groupBy('month_num')
  141. ->get();
  142. // Map income data to correct position in season array
  143. foreach ($incomeRecords as $record) {
  144. $monthIndex = array_search($record->month_num, $monthOrder);
  145. if ($monthIndex !== false) {
  146. $incomeData[$monthIndex] = $record->total;
  147. }
  148. }
  149. // Map expense data to correct position in season array
  150. foreach ($expenseRecords as $record) {
  151. $monthIndex = array_search($record->month_num, $monthOrder);
  152. if ($monthIndex !== false) {
  153. $expenseData[$monthIndex] = $record->total;
  154. }
  155. }
  156. Log::info('Income data: ' . json_encode($incomeData));
  157. Log::info('Expense data: ' . json_encode($expenseData));
  158. return [
  159. 'labels' => $monthNames,
  160. 'datasets' => [
  161. [
  162. 'label' => 'Entrate',
  163. 'data' => $incomeData,
  164. 'backgroundColor' => 'rgba(54, 162, 235, 0.5)'
  165. ],
  166. [
  167. 'label' => 'Uscite',
  168. 'data' => $expenseData,
  169. 'backgroundColor' => 'rgba(255, 99, 132, 0.5)'
  170. ],
  171. ]
  172. ];
  173. }
  174. public function getYearlySummary()
  175. {
  176. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  177. $totalIncome = DB::table('records')
  178. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  179. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  180. ->where('records.type', 'IN')
  181. ->sum('records_rows.amount');
  182. $totalExpenses = DB::table('records')
  183. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  184. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  185. ->where('records.type', 'OUT')
  186. ->sum('records_rows.amount');
  187. $delta = $totalIncome - $totalExpenses;
  188. return [
  189. 'totalIncome' => $totalIncome,
  190. 'totalExpenses' => $totalExpenses,
  191. 'delta' => $delta
  192. ];
  193. }
  194. public function getTopCausalsByAmount($limit = 10)
  195. {
  196. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  197. $query = DB::table('records_rows')
  198. ->join('records', 'records_rows.record_id', '=', 'records.id')
  199. ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
  200. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']]);
  201. $query->where('records.type', 'IN');
  202. Log::info('Query: ' . $query->toSql());
  203. $causals = $query->select(
  204. 'causals.id',
  205. 'causals.name',
  206. 'causals.parent_id',
  207. DB::raw('SUM(records_rows.amount) as total_amount')
  208. )
  209. ->groupBy('causals.id', 'causals.name', 'causals.parent_id')
  210. ->orderBy('total_amount', 'desc')
  211. ->limit($limit)
  212. ->get();
  213. Log::info('Causals: ' . json_encode($causals));
  214. $inData = [];
  215. foreach ($causals as $causal) {
  216. $tempCausal = new \App\Models\Causal();
  217. $tempCausal->id = $causal->id;
  218. $tempCausal->name = $causal->name;
  219. $tempCausal->parent_id = $causal->parent_id;
  220. $treeName = $tempCausal->getTree();
  221. $displayName = strlen($treeName) > 30 ? substr($treeName, 0, 27) . '...' : $treeName;
  222. $inData[] = [
  223. 'label' => $displayName,
  224. 'value' => $causal->total_amount,
  225. 'fullName' => $treeName
  226. ];
  227. }
  228. usort($inData, function ($a, $b) {
  229. return $b['value'] <=> $a['value'];
  230. });
  231. $inData = array_slice($inData, 0, $limit);
  232. return [
  233. 'inLabels' => array_column($inData, 'label'),
  234. 'inData' => $inData,
  235. 'datasets' => [
  236. [
  237. 'label' => 'Entrate per Causale',
  238. 'data' => array_column($inData, 'value'),
  239. ]
  240. ]
  241. ];
  242. }
  243. public function getCoursesForSelect()
  244. {
  245. $seasonYears = $this->parseSeason($this->seasonFilter);
  246. Log::info('Getting courses for season: ' . $this->seasonFilter);
  247. Log::info('Season years: ' . json_encode($seasonYears));
  248. $courses = Course::with(['level', 'type', 'frequency'])
  249. ->where('active', true)
  250. ->where(function ($query) use ($seasonYears) {
  251. // Match courses that belong to the exact season
  252. $query->where('year', $this->seasonFilter)
  253. ->orWhere('year', 'like', '%' . $seasonYears['start_year'] . '-' . $seasonYears['end_year'] . '%')
  254. ->orWhere('year', 'like', '%' . $seasonYears['start_year'] . '%')
  255. ->orWhere('year', 'like', '%' . $seasonYears['end_year'] . '%');
  256. })
  257. ->orderBy('name')
  258. ->get()
  259. ->filter(function ($course) use ($seasonYears) {
  260. // Additional filtering to ensure course belongs to the season
  261. $courseYear = $course->year;
  262. // Check if course year matches the season format (e.g., "2024-2025")
  263. if ($courseYear === $this->seasonFilter) {
  264. return true;
  265. }
  266. // Check if course year contains the season years
  267. if (
  268. str_contains($courseYear, $seasonYears['start_year']) &&
  269. str_contains($courseYear, $seasonYears['end_year'])
  270. ) {
  271. return true;
  272. }
  273. // Check if course year is exactly one of the season years
  274. if ($courseYear == $seasonYears['start_year'] || $courseYear == $seasonYears['end_year']) {
  275. return true;
  276. }
  277. return false;
  278. })
  279. ->map(function ($course) {
  280. $type = null;
  281. if (!empty($course->course_type_id)) {
  282. $type = \App\Models\CourseType::find($course->course_type_id);
  283. }
  284. $levelName = is_object($course->level) ? $course->level->name : 'No Level';
  285. $typeName = is_object($type) ? $type->name : 'No Type';
  286. $frequencyName = is_object($course->frequency) ? $course->frequency->name : 'No Frequency';
  287. $year = $course->year ?? '';
  288. return [
  289. 'id' => $course->id,
  290. 'name' => $course->name,
  291. 'full_name' => "{$course->name} - {$levelName} - {$typeName} - {$frequencyName} ({$year})",
  292. 'level_name' => $levelName,
  293. 'type_name' => $typeName,
  294. 'frequency_name' => $frequencyName,
  295. 'year' => $year
  296. ];
  297. })->values()->toArray();
  298. Log::info('Found ' . count($courses) . ' courses for season ' . $this->seasonFilter);
  299. return $courses;
  300. }
  301. public function getMonthlyTotalsForSeason($season)
  302. {
  303. $originalSeason = $this->seasonFilter;
  304. $this->seasonFilter = $season;
  305. $result = $this->getMonthlyTotals();
  306. $this->seasonFilter = $originalSeason;
  307. return $result;
  308. }
  309. /**
  310. * Get top causals for a specific season
  311. */
  312. public function getTopCausalsByAmountForSeason($season, $limit = 10)
  313. {
  314. $originalSeason = $this->seasonFilter;
  315. $this->seasonFilter = $season;
  316. $result = $this->getTopCausalsByAmount($limit);
  317. $this->seasonFilter = $originalSeason;
  318. return $result;
  319. }
  320. /**
  321. * Get tesserati data for a specific season
  322. */
  323. public function getTesseratiDataForSeason($season)
  324. {
  325. $originalSeason = $this->seasonFilter;
  326. $this->seasonFilter = $season;
  327. $result = $this->getTesseratiData();
  328. $this->seasonFilter = $originalSeason;
  329. return $result;
  330. }
  331. public function updatedSelectedCourse()
  332. {
  333. Log::info('updatedSelectedCourse called with: ' . $this->selectedCourse);
  334. if ($this->selectedCourse) {
  335. $this->emit('courseSelected', $this->selectedCourse);
  336. Log::info('Event emitted with course ID: ' . $this->selectedCourse);
  337. }
  338. }
  339. public function getCourseData($courseId)
  340. {
  341. $this->selectedCourse = $courseId;
  342. return $this->getCourseMonthlyEarnings($courseId);
  343. }
  344. public function getCourseMonthlyEarnings($courseId = null)
  345. {
  346. $courseId = $courseId ?? $this->selectedCourse;
  347. Log::info('Getting earnings for course ID: ' . $courseId);
  348. if (!$courseId) {
  349. return [
  350. 'labels' => [],
  351. 'datasets' => [],
  352. 'tableData' => [],
  353. 'isEmpty' => true,
  354. 'message' => 'Seleziona un corso per visualizzare i dati'
  355. ];
  356. }
  357. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  358. $monthNames = [
  359. 9 => 'Set',
  360. 10 => 'Ott',
  361. 11 => 'Nov',
  362. 12 => 'Dic',
  363. 1 => 'Gen',
  364. 2 => 'Feb',
  365. 3 => 'Mar',
  366. 4 => 'Apr',
  367. 5 => 'Mag',
  368. 6 => 'Giu',
  369. 7 => 'Lug',
  370. 8 => 'Ago'
  371. ];
  372. $monthlyData = [];
  373. foreach ($monthOrder as $i) {
  374. $monthlyData[$i] = [
  375. 'earned' => 0,
  376. 'total' => 0,
  377. 'participants' => 0
  378. ];
  379. }
  380. $memberCourses = \App\Models\MemberCourse::where('course_id', $courseId)
  381. ->with('member')
  382. ->get();
  383. // Check if there are any member courses
  384. if ($memberCourses->isEmpty()) {
  385. return [
  386. 'labels' => [],
  387. 'datasets' => [],
  388. 'tableData' => [],
  389. 'isEmpty' => true,
  390. 'message' => 'Nessun dato disponibile per questo corso nella stagione ' . $this->seasonFilter
  391. ];
  392. }
  393. $hasData = false;
  394. foreach ($memberCourses as $memberCourse) {
  395. $price = (float)($memberCourse->price ?? 0);
  396. if ($memberCourse->months) {
  397. $monthsData = json_decode($memberCourse->months, true);
  398. if (is_array($monthsData)) {
  399. foreach ($monthsData as $monthData) {
  400. $month = $monthData['m'] ?? null;
  401. $status = $monthData['status'] ?? '';
  402. if ($month !== null && isset($monthlyData[$month])) {
  403. $monthlyData[$month]['total'] += $price;
  404. $monthlyData[$month]['participants']++;
  405. $hasData = true;
  406. if ($status === 1) {
  407. $monthlyData[$month]['earned'] += $price;
  408. }
  409. }
  410. }
  411. }
  412. }
  413. }
  414. // Check if we actually have any data
  415. if (!$hasData) {
  416. return [
  417. 'labels' => [],
  418. 'datasets' => [],
  419. 'tableData' => [],
  420. 'isEmpty' => true,
  421. 'message' => 'Nessun pagamento registrato per questo corso nella stagione ' . $this->seasonFilter
  422. ];
  423. }
  424. $labels = [];
  425. $earnedData = [];
  426. $totalData = [];
  427. $participantData = [];
  428. $tableData = [];
  429. foreach ($monthOrder as $month) {
  430. $earned = round($monthlyData[$month]['earned'], 2);
  431. $total = round($monthlyData[$month]['total'], 2);
  432. $delta = $total - $earned;
  433. $participants = $monthlyData[$month]['participants'];
  434. $labels[] = $monthNames[$month];
  435. $earnedData[] = $earned;
  436. $totalData[] = $total;
  437. $participantData[] = $participants;
  438. $tableData[] = [
  439. 'month' => $monthNames[$month],
  440. 'participants' => $participants,
  441. 'earned' => $earned,
  442. 'total' => $total,
  443. 'delta' => $delta,
  444. 'percentage' => $total > 0 ? round(($earned / $total) * 100, 1) : 0
  445. ];
  446. }
  447. return [
  448. 'labels' => $labels,
  449. 'datasets' => [
  450. [
  451. 'label' => 'Pagamenti Effettuati',
  452. 'backgroundColor' => 'rgba(16, 185, 129, 0.8)',
  453. 'borderColor' => 'rgba(16, 185, 129, 1)',
  454. 'borderWidth' => 0,
  455. 'borderRadius' => 8,
  456. 'borderSkipped' => false,
  457. 'data' => $earnedData,
  458. 'type' => 'bar',
  459. 'order' => 2
  460. ],
  461. [
  462. 'label' => 'Pagamenti Attesi',
  463. 'backgroundColor' => 'transparent',
  464. 'borderColor' => 'rgba(59, 130, 246, 1)',
  465. 'borderWidth' => 3,
  466. 'pointBackgroundColor' => 'rgba(59, 130, 246, 1)',
  467. 'pointBorderColor' => '#ffffff',
  468. 'pointBorderWidth' => 3,
  469. 'pointRadius' => 7,
  470. 'pointHoverRadius' => 9,
  471. 'data' => $totalData,
  472. 'type' => 'line',
  473. 'tension' => 0.3,
  474. 'order' => 1,
  475. 'participantData' => $participantData
  476. ]
  477. ],
  478. 'tableData' => $tableData,
  479. 'isEmpty' => false
  480. ];
  481. }
  482. public static function getMemberCountChartData($endYear = null, $span = 5)
  483. {
  484. if ($endYear === null) {
  485. $endYear = date('Y');
  486. }
  487. $startYear = $endYear - $span + 1;
  488. $memberCards = MemberCard::select('member_id', 'expire_date')
  489. ->whereNotNull('expire_date')
  490. ->whereNotNull('member_id')
  491. ->where('status', '!=', 'cancelled')
  492. ->whereRaw('YEAR(expire_date) >= ?', [$startYear])
  493. ->whereRaw('YEAR(expire_date) <= ?', [$endYear])
  494. ->get();
  495. $seasonCounts = [];
  496. for ($year = $startYear; $year <= $endYear; $year++) {
  497. $seasonPeriod = ($year - 1) . '-' . $year;
  498. $seasonCounts[$seasonPeriod] = [];
  499. }
  500. foreach ($memberCards as $card) {
  501. $expireYear = date('Y', strtotime($card->expire_date));
  502. $expireMonth = date('n', strtotime($card->expire_date));
  503. if ($expireMonth >= 9) {
  504. $seasonPeriod = $expireYear . '-' . ($expireYear + 1);
  505. } else {
  506. $seasonPeriod = ($expireYear - 1) . '-' . $expireYear;
  507. }
  508. if (isset($seasonCounts[$seasonPeriod])) {
  509. $seasonCounts[$seasonPeriod][$card->member_id] = true;
  510. }
  511. }
  512. $seasonLabels = [];
  513. $memberCountData = [];
  514. foreach ($seasonCounts as $seasonPeriod => $members) {
  515. $seasonLabels[] = $seasonPeriod;
  516. $memberCountData[] = count($members);
  517. }
  518. return [
  519. 'labels' => $seasonLabels,
  520. 'datasets' => [
  521. [
  522. 'label' => 'Membri Tesserati',
  523. 'data' => $memberCountData,
  524. 'backgroundColor' => 'rgba(54, 162, 235, 0.2)',
  525. 'borderColor' => 'rgba(54, 162, 235, 1)',
  526. 'borderWidth' => 2,
  527. 'pointBackgroundColor' => 'rgba(54, 162, 235, 1)',
  528. 'pointRadius' => 4,
  529. 'tension' => 0.3,
  530. 'fill' => true
  531. ]
  532. ]
  533. ];
  534. }
  535. }