Reports.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. $inData[] = [
  206. 'label' => $displayName,
  207. 'value' => $causal->total_amount,
  208. 'fullName' => $treeName
  209. ];
  210. }
  211. usort($inData, function ($a, $b) {
  212. return $b['value'] <=> $a['value'];
  213. });
  214. $inData = array_slice($inData, 0, $limit);
  215. return [
  216. 'inLabels' => array_column($inData, 'label'),
  217. 'inData' => $inData,
  218. 'datasets' => [
  219. [
  220. 'label' => 'Entrate per Causale',
  221. 'data' => array_column($inData, 'value'),
  222. ]
  223. ]
  224. ];
  225. }
  226. public function getCoursesForSelect()
  227. {
  228. $seasonYears = $this->parseSeason($this->seasonFilter);
  229. Log::info('Getting courses for season: ' . $this->seasonFilter);
  230. Log::info('Season years: ' . json_encode($seasonYears));
  231. $courses = Course::with(['level', 'type', 'frequency'])
  232. ->where('active', true)
  233. ->where(function ($query) use ($seasonYears) {
  234. $query->where('year', $this->seasonFilter)
  235. ->orWhere('year', 'like', '%' . $seasonYears['start_year'] . '-' . $seasonYears['end_year'] . '%')
  236. ->orWhere('year', 'like', '%' . $seasonYears['start_year'] . '%')
  237. ->orWhere('year', 'like', '%' . $seasonYears['end_year'] . '%');
  238. })
  239. ->orderBy('name')
  240. ->get()
  241. ->filter(function ($course) use ($seasonYears) {
  242. $courseYear = $course->year;
  243. if ($courseYear === $this->seasonFilter) {
  244. return true;
  245. }
  246. if (
  247. str_contains($courseYear, $seasonYears['start_year']) &&
  248. str_contains($courseYear, $seasonYears['end_year'])
  249. ) {
  250. return true;
  251. }
  252. if ($courseYear == $seasonYears['start_year'] || $courseYear == $seasonYears['end_year']) {
  253. return true;
  254. }
  255. return false;
  256. })
  257. ->map(function ($course) {
  258. $type = null;
  259. if (!empty($course->course_type_id)) {
  260. $type = \App\Models\CourseType::find($course->course_type_id);
  261. }
  262. $levelName = is_object($course->level) ? $course->level->name : 'No Level';
  263. $typeName = is_object($type) ? $type->name : 'No Type';
  264. $frequencyName = is_object($course->frequency) ? $course->frequency->name : 'No Frequency';
  265. $year = $course->year ?? '';
  266. return [
  267. 'id' => $course->id,
  268. 'name' => $course->name,
  269. 'full_name' => "{$course->name} - {$levelName} - {$typeName} - {$frequencyName} ({$year})",
  270. 'level_name' => $levelName,
  271. 'type_name' => $typeName,
  272. 'frequency_name' => $frequencyName,
  273. 'year' => $year
  274. ];
  275. })->values()->toArray();
  276. Log::info('Found ' . count($courses) . ' courses for season ' . $this->seasonFilter);
  277. return $courses;
  278. }
  279. public function getMonthlyTotalsForSeason($season)
  280. {
  281. $originalSeason = $this->seasonFilter;
  282. $this->seasonFilter = $season;
  283. $result = $this->getMonthlyTotals();
  284. $this->seasonFilter = $originalSeason;
  285. return $result;
  286. }
  287. public function getTopCausalsByAmountForSeason($season, $limit = 10)
  288. {
  289. $originalSeason = $this->seasonFilter;
  290. $this->seasonFilter = $season;
  291. $result = $this->getTopCausalsByAmount($limit);
  292. $this->seasonFilter = $originalSeason;
  293. return $result;
  294. }
  295. public function getTesseratiDataForSeason($season)
  296. {
  297. $originalSeason = $this->seasonFilter;
  298. $this->seasonFilter = $season;
  299. $result = $this->getTesseratiData();
  300. $this->seasonFilter = $originalSeason;
  301. return $result;
  302. }
  303. public function updatedSelectedCourse()
  304. {
  305. Log::info('updatedSelectedCourse called with: ' . $this->selectedCourse);
  306. if ($this->selectedCourse) {
  307. $this->emit('courseSelected', $this->selectedCourse);
  308. Log::info('Event emitted with course ID: ' . $this->selectedCourse);
  309. }
  310. }
  311. public function getCourseData($courseId)
  312. {
  313. $this->selectedCourse = $courseId;
  314. return $this->getCourseMonthlyEarnings($courseId);
  315. }
  316. public function getCourseMonthlyEarnings($courseId = null)
  317. {
  318. $courseId = $courseId ?? $this->selectedCourse;
  319. Log::info('Getting earnings for course ID: ' . $courseId);
  320. if (!$courseId) {
  321. return [
  322. 'labels' => [],
  323. 'datasets' => [],
  324. 'tableData' => [],
  325. 'isEmpty' => true,
  326. 'message' => 'Seleziona un corso per visualizzare i dati'
  327. ];
  328. }
  329. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  330. $monthNames = [
  331. 9 => 'Set',
  332. 10 => 'Ott',
  333. 11 => 'Nov',
  334. 12 => 'Dic',
  335. 1 => 'Gen',
  336. 2 => 'Feb',
  337. 3 => 'Mar',
  338. 4 => 'Apr',
  339. 5 => 'Mag',
  340. 6 => 'Giu',
  341. 7 => 'Lug',
  342. 8 => 'Ago'
  343. ];
  344. $monthlyData = [];
  345. foreach ($monthOrder as $i) {
  346. $monthlyData[$i] = [
  347. 'earned' => 0,
  348. 'total' => 0,
  349. 'participants' => 0
  350. ];
  351. }
  352. $memberCourses = \App\Models\MemberCourse::where('course_id', $courseId)
  353. ->with('member')
  354. ->get();
  355. if ($memberCourses->isEmpty()) {
  356. return [
  357. 'labels' => [],
  358. 'datasets' => [],
  359. 'tableData' => [],
  360. 'isEmpty' => true,
  361. 'message' => 'Nessun dato disponibile per questo corso nella stagione ' . $this->seasonFilter
  362. ];
  363. }
  364. $hasData = false;
  365. foreach ($memberCourses as $memberCourse) {
  366. $price = (float)($memberCourse->price ?? 0);
  367. if ($memberCourse->months) {
  368. $monthsData = json_decode($memberCourse->months, true);
  369. if (is_array($monthsData)) {
  370. foreach ($monthsData as $monthData) {
  371. $month = $monthData['m'] ?? null;
  372. $status = $monthData['status'] ?? '';
  373. if ($month !== null && isset($monthlyData[$month])) {
  374. $monthlyData[$month]['total'] += $price;
  375. $monthlyData[$month]['participants']++;
  376. $hasData = true;
  377. if ($status === 1) {
  378. $monthlyData[$month]['earned'] += $price;
  379. }
  380. }
  381. }
  382. }
  383. }
  384. }
  385. if (!$hasData) {
  386. return [
  387. 'labels' => [],
  388. 'datasets' => [],
  389. 'tableData' => [],
  390. 'isEmpty' => true,
  391. 'message' => 'Nessun pagamento registrato per questo corso nella stagione ' . $this->seasonFilter
  392. ];
  393. }
  394. $labels = [];
  395. $earnedData = [];
  396. $totalData = [];
  397. $participantData = [];
  398. $tableData = [];
  399. foreach ($monthOrder as $month) {
  400. $earned = round($monthlyData[$month]['earned'], 2);
  401. $total = round($monthlyData[$month]['total'], 2);
  402. $delta = $total - $earned;
  403. $participants = $monthlyData[$month]['participants'];
  404. $labels[] = $monthNames[$month];
  405. $earnedData[] = $earned;
  406. $totalData[] = $total;
  407. $participantData[] = $participants;
  408. $tableData[] = [
  409. 'month' => $monthNames[$month],
  410. 'participants' => $participants,
  411. 'earned' => $earned,
  412. 'total' => $total,
  413. 'delta' => $delta,
  414. 'percentage' => $total > 0 ? round(($earned / $total) * 100, 1) : 0
  415. ];
  416. }
  417. return [
  418. 'labels' => $labels,
  419. 'datasets' => [
  420. [
  421. 'label' => 'Pagamenti Effettuati',
  422. 'backgroundColor' => 'rgba(16, 185, 129, 0.8)',
  423. 'borderColor' => 'rgba(16, 185, 129, 1)',
  424. 'borderWidth' => 0,
  425. 'borderRadius' => 8,
  426. 'borderSkipped' => false,
  427. 'data' => $earnedData,
  428. 'type' => 'bar',
  429. 'order' => 2
  430. ],
  431. [
  432. 'label' => 'Pagamenti Attesi',
  433. 'backgroundColor' => 'transparent',
  434. 'borderColor' => 'rgba(59, 130, 246, 1)',
  435. 'borderWidth' => 3,
  436. 'pointBackgroundColor' => 'rgba(59, 130, 246, 1)',
  437. 'pointBorderColor' => '#ffffff',
  438. 'pointBorderWidth' => 3,
  439. 'pointRadius' => 7,
  440. 'pointHoverRadius' => 9,
  441. 'data' => $totalData,
  442. 'type' => 'line',
  443. 'tension' => 0.3,
  444. 'order' => 1,
  445. 'participantData' => $participantData
  446. ]
  447. ],
  448. 'tableData' => $tableData,
  449. 'isEmpty' => false
  450. ];
  451. }
  452. public static function getMemberCountChartData($endYear = null, $span = 5)
  453. {
  454. if ($endYear === null) {
  455. $endYear = date('Y');
  456. }
  457. $startYear = $endYear - $span + 1;
  458. $memberCards = MemberCard::select('member_id', 'expire_date')
  459. ->whereNotNull('expire_date')
  460. ->whereNotNull('member_id')
  461. ->where('status', '!=', 'cancelled')
  462. ->whereRaw('YEAR(expire_date) >= ?', [$startYear])
  463. ->whereRaw('YEAR(expire_date) <= ?', [$endYear])
  464. ->get();
  465. $seasonCounts = [];
  466. for ($year = $startYear; $year <= $endYear; $year++) {
  467. $seasonPeriod = ($year - 1) . '-' . $year;
  468. $seasonCounts[$seasonPeriod] = [];
  469. }
  470. foreach ($memberCards as $card) {
  471. $expireYear = date('Y', strtotime($card->expire_date));
  472. $expireMonth = date('n', strtotime($card->expire_date));
  473. if ($expireMonth >= 9) {
  474. $seasonPeriod = $expireYear . '-' . ($expireYear + 1);
  475. } else {
  476. $seasonPeriod = ($expireYear - 1) . '-' . $expireYear;
  477. }
  478. if (isset($seasonCounts[$seasonPeriod])) {
  479. $seasonCounts[$seasonPeriod][$card->member_id] = true;
  480. }
  481. }
  482. $seasonLabels = [];
  483. $memberCountData = [];
  484. foreach ($seasonCounts as $seasonPeriod => $members) {
  485. $seasonLabels[] = $seasonPeriod;
  486. $memberCountData[] = count($members);
  487. }
  488. return [
  489. 'labels' => $seasonLabels,
  490. 'datasets' => [
  491. [
  492. 'label' => 'Membri Tesserati',
  493. 'data' => $memberCountData,
  494. 'backgroundColor' => 'rgba(54, 162, 235, 0.2)',
  495. 'borderColor' => 'rgba(54, 162, 235, 1)',
  496. 'borderWidth' => 2,
  497. 'pointBackgroundColor' => 'rgba(54, 162, 235, 1)',
  498. 'pointRadius' => 4,
  499. 'tension' => 0.3,
  500. 'fill' => true
  501. ]
  502. ]
  503. ];
  504. }
  505. }