Reports.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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', 'type', '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. $type = null;
  260. if (!empty($course->course_type_id)) {
  261. $type = \App\Models\CourseType::find($course->course_type_id);
  262. }
  263. $levelName = is_object($course->level) ? $course->level->name : 'No Level';
  264. $typeName = is_object($type) ? $type->name : 'No Type';
  265. $frequencyName = is_object($course->frequency) ? $course->frequency->name : 'No Frequency';
  266. $year = $course->year ?? '';
  267. return [
  268. 'id' => $course->id,
  269. 'name' => $course->name,
  270. 'full_name' => "{$course->name} - {$levelName} - {$typeName} - {$frequencyName} ({$year})",
  271. 'level_name' => $levelName,
  272. 'type_name' => $typeName,
  273. 'frequency_name' => $frequencyName,
  274. 'year' => $year
  275. ];
  276. })->values()->toArray();
  277. Log::info('Found ' . count($courses) . ' courses for season ' . $this->seasonFilter);
  278. return $courses;
  279. }
  280. public function getMonthlyTotalsForSeason($season)
  281. {
  282. $originalSeason = $this->seasonFilter;
  283. $this->seasonFilter = $season;
  284. $result = $this->getMonthlyTotals();
  285. $this->seasonFilter = $originalSeason;
  286. return $result;
  287. }
  288. public function getTopCausalsByAmountForSeason($season, $limit = 10)
  289. {
  290. $originalSeason = $this->seasonFilter;
  291. $this->seasonFilter = $season;
  292. $result = $this->getTopCausalsByAmount($limit);
  293. $this->seasonFilter = $originalSeason;
  294. return $result;
  295. }
  296. public function getTesseratiDataForSeason($season)
  297. {
  298. $originalSeason = $this->seasonFilter;
  299. $this->seasonFilter = $season;
  300. $result = $this->getTesseratiData();
  301. $this->seasonFilter = $originalSeason;
  302. return $result;
  303. }
  304. public function updatedSelectedCourse()
  305. {
  306. Log::info('updatedSelectedCourse called with: ' . $this->selectedCourse);
  307. if ($this->selectedCourse) {
  308. $this->emit('courseSelected', $this->selectedCourse);
  309. Log::info('Event emitted with course ID: ' . $this->selectedCourse);
  310. }
  311. }
  312. public function getCourseData($courseId)
  313. {
  314. $this->selectedCourse = $courseId;
  315. return $this->getCourseMonthlyEarnings($courseId);
  316. }
  317. public function getCourseMonthlyEarnings($courseId = null)
  318. {
  319. $courseId = $courseId ?? $this->selectedCourse;
  320. Log::info('Getting earnings for course ID: ' . $courseId);
  321. if (!$courseId) {
  322. return [
  323. 'labels' => [],
  324. 'datasets' => [],
  325. 'tableData' => [],
  326. 'isEmpty' => true,
  327. 'message' => 'Seleziona un corso per visualizzare i dati'
  328. ];
  329. }
  330. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  331. $monthNames = [
  332. 9 => 'Set',
  333. 10 => 'Ott',
  334. 11 => 'Nov',
  335. 12 => 'Dic',
  336. 1 => 'Gen',
  337. 2 => 'Feb',
  338. 3 => 'Mar',
  339. 4 => 'Apr',
  340. 5 => 'Mag',
  341. 6 => 'Giu',
  342. 7 => 'Lug',
  343. 8 => 'Ago'
  344. ];
  345. $monthlyData = [];
  346. foreach ($monthOrder as $i) {
  347. $monthlyData[$i] = [
  348. 'earned' => 0,
  349. 'total' => 0,
  350. 'participants' => 0
  351. ];
  352. }
  353. $memberCourses = \App\Models\MemberCourse::where('course_id', $courseId)
  354. ->with('member')
  355. ->get();
  356. if ($memberCourses->isEmpty()) {
  357. return [
  358. 'labels' => [],
  359. 'datasets' => [],
  360. 'tableData' => [],
  361. 'isEmpty' => true,
  362. 'message' => 'Nessun dato disponibile per questo corso nella stagione ' . $this->seasonFilter
  363. ];
  364. }
  365. $hasData = false;
  366. foreach ($memberCourses as $memberCourse) {
  367. $price = (float)($memberCourse->price ?? 0);
  368. if ($memberCourse->months) {
  369. $monthsData = json_decode($memberCourse->months, true);
  370. if (is_array($monthsData)) {
  371. foreach ($monthsData as $monthData) {
  372. $month = $monthData['m'] ?? null;
  373. $status = $monthData['status'] ?? '';
  374. if ($month !== null && isset($monthlyData[$month])) {
  375. $monthlyData[$month]['total'] += $price;
  376. $monthlyData[$month]['participants']++;
  377. $hasData = true;
  378. if ($status === 1) {
  379. $monthlyData[$month]['earned'] += $price;
  380. }
  381. }
  382. }
  383. }
  384. }
  385. }
  386. if (!$hasData) {
  387. return [
  388. 'labels' => [],
  389. 'datasets' => [],
  390. 'tableData' => [],
  391. 'isEmpty' => true,
  392. 'message' => 'Nessun pagamento registrato per questo corso nella stagione ' . $this->seasonFilter
  393. ];
  394. }
  395. $labels = [];
  396. $earnedData = [];
  397. $totalData = [];
  398. $participantData = [];
  399. $tableData = [];
  400. foreach ($monthOrder as $month) {
  401. $earned = round($monthlyData[$month]['earned'], 2);
  402. $total = round($monthlyData[$month]['total'], 2);
  403. $delta = max(0, $total - $earned);
  404. $participants = $monthlyData[$month]['participants'];
  405. $labels[] = $monthNames[$month];
  406. $earnedData[] = $earned;
  407. $totalData[] = $total;
  408. $participantData[] = $participants;
  409. $percentage = $total > 0 ? round(($earned / $total) * 100, 1) : 0;
  410. $tableData[] = [
  411. 'month' => $monthNames[$month],
  412. 'participants' => $participants,
  413. 'earned' => $earned,
  414. 'total' => $total,
  415. 'delta' => $delta,
  416. 'percentage' => $percentage
  417. ];
  418. }
  419. return [
  420. 'labels' => $labels,
  421. 'datasets' => [
  422. [
  423. 'label' => 'Pagamenti Effettuati',
  424. 'backgroundColor' => 'rgba(16, 185, 129, 0.8)',
  425. 'borderColor' => 'rgba(16, 185, 129, 1)',
  426. 'borderWidth' => 0,
  427. 'borderRadius' => 8,
  428. 'borderSkipped' => false,
  429. 'data' => $earnedData,
  430. 'type' => 'bar',
  431. 'order' => 2
  432. ],
  433. [
  434. 'label' => 'Pagamenti Attesi',
  435. 'backgroundColor' => 'transparent',
  436. 'borderColor' => 'rgba(59, 130, 246, 1)',
  437. 'borderWidth' => 3,
  438. 'pointBackgroundColor' => 'rgba(59, 130, 246, 1)',
  439. 'pointBorderColor' => '#ffffff',
  440. 'pointBorderWidth' => 3,
  441. 'pointRadius' => 7,
  442. 'pointHoverRadius' => 9,
  443. 'data' => $totalData,
  444. 'type' => 'line',
  445. 'tension' => 0.3,
  446. 'order' => 1,
  447. 'participantData' => $participantData
  448. ]
  449. ],
  450. 'tableData' => $tableData,
  451. 'isEmpty' => false
  452. ];
  453. }
  454. public static function getMemberCountChartData($endYear = null, $span = 5)
  455. {
  456. if ($endYear === null) {
  457. $endYear = date('Y');
  458. }
  459. $startYear = $endYear - $span + 1;
  460. $memberCards = MemberCard::select('member_id', 'expire_date', 'card_id')
  461. ->with('card:id,name')
  462. ->whereNotNull('expire_date')
  463. ->whereNotNull('member_id')
  464. ->whereNotNull('card_id')
  465. ->where('status', '!=', 'cancelled')
  466. ->whereRaw('YEAR(expire_date) >= ?', [$startYear])
  467. ->whereRaw('YEAR(expire_date) <= ?', [$endYear])
  468. ->get();
  469. $cardTypes = $memberCards->pluck('card.name')->unique()->filter()->sort()->values();
  470. $seasonCounts = [];
  471. $seasonCardCounts = [];
  472. for ($year = $startYear; $year <= $endYear; $year++) {
  473. $seasonPeriod = ($year - 1) . '-' . $year;
  474. $seasonCounts[$seasonPeriod] = [];
  475. $seasonCardCounts[$seasonPeriod] = [];
  476. foreach ($cardTypes as $cardType) {
  477. $seasonCardCounts[$seasonPeriod][$cardType] = [];
  478. }
  479. }
  480. foreach ($memberCards as $card) {
  481. $expireYear = date('Y', strtotime($card->expire_date));
  482. $expireMonth = date('n', strtotime($card->expire_date));
  483. if ($expireMonth >= 9) {
  484. $seasonPeriod = $expireYear . '-' . ($expireYear + 1);
  485. } else {
  486. $seasonPeriod = ($expireYear - 1) . '-' . $expireYear;
  487. }
  488. if (isset($seasonCounts[$seasonPeriod])) {
  489. $seasonCounts[$seasonPeriod][$card->member_id] = true;
  490. $cardTypeName = $card->card->name ?? 'Unknown';
  491. if (isset($seasonCardCounts[$seasonPeriod][$cardTypeName])) {
  492. $seasonCardCounts[$seasonPeriod][$cardTypeName][$card->member_id] = true;
  493. }
  494. }
  495. }
  496. $seasonLabels = [];
  497. $memberCountData = [];
  498. $cardTypeDatasets = [];
  499. $colors = [
  500. 'rgba(255, 99, 132, 0.2)',
  501. 'rgba(54, 162, 235, 0.2)',
  502. 'rgba(255, 205, 86, 0.2)',
  503. 'rgba(75, 192, 192, 0.2)',
  504. 'rgba(153, 102, 255, 0.2)',
  505. 'rgba(255, 159, 64, 0.2)',
  506. 'rgba(199, 199, 199, 0.2)',
  507. 'rgba(83, 102, 255, 0.2)',
  508. ];
  509. $borderColors = [
  510. 'rgba(255, 99, 132, 1)',
  511. 'rgba(54, 162, 235, 1)',
  512. 'rgba(255, 205, 86, 1)',
  513. 'rgba(75, 192, 192, 1)',
  514. 'rgba(153, 102, 255, 1)',
  515. 'rgba(255, 159, 64, 1)',
  516. 'rgba(199, 199, 199, 1)',
  517. 'rgba(83, 102, 255, 1)',
  518. ];
  519. foreach ($cardTypes as $index => $cardType) {
  520. $cardTypeDatasets[$cardType] = [
  521. 'label' => $cardType,
  522. 'data' => [],
  523. 'backgroundColor' => $colors[$index % count($colors)],
  524. 'borderColor' => $borderColors[$index % count($borderColors)],
  525. 'borderWidth' => 2,
  526. 'pointBackgroundColor' => $borderColors[$index % count($borderColors)],
  527. 'pointRadius' => 4,
  528. 'tension' => 0.3,
  529. 'fill' => true
  530. ];
  531. }
  532. foreach ($seasonCounts as $seasonPeriod => $members) {
  533. $seasonLabels[] = $seasonPeriod;
  534. $memberCountData[] = count($members);
  535. foreach ($cardTypes as $cardType) {
  536. $cardTypeCount = isset($seasonCardCounts[$seasonPeriod][$cardType])
  537. ? count($seasonCardCounts[$seasonPeriod][$cardType])
  538. : 0;
  539. $cardTypeDatasets[$cardType]['data'][] = $cardTypeCount;
  540. }
  541. }
  542. $datasets = [
  543. [
  544. 'label' => 'Totale Membri Tesserati',
  545. 'data' => $memberCountData,
  546. 'backgroundColor' => 'rgba(54, 162, 235, 0.2)',
  547. 'borderColor' => 'rgba(54, 162, 235, 1)',
  548. 'borderWidth' => 3,
  549. 'pointBackgroundColor' => 'rgba(54, 162, 235, 1)',
  550. 'pointRadius' => 6,
  551. 'tension' => 0.3,
  552. 'fill' => true,
  553. 'type' => 'line'
  554. ]
  555. ];
  556. foreach ($cardTypeDatasets as $dataset) {
  557. $datasets[] = $dataset;
  558. }
  559. return [
  560. 'labels' => $seasonLabels,
  561. 'datasets' => $datasets
  562. ];
  563. }
  564. }