Reports.php 22 KB

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