Reports.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  117. // September to August order
  118. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  119. $monthNames = ['Set', 'Ott', 'Nov', 'Dic', 'Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago'];
  120. $incomeData = array_fill(0, 12, 0);
  121. $expenseData = array_fill(0, 12, 0);
  122. // Get income records within season date range
  123. $incomeRecords = DB::table('records')
  124. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  125. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  126. ->where('records.type', 'IN')
  127. ->select(DB::raw('MONTH(records.date) as month_num'), DB::raw('SUM(records_rows.amount) as total'))
  128. ->groupBy('month_num')
  129. ->get();
  130. // Get expense records within season date range
  131. $expenseRecords = DB::table('records')
  132. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  133. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  134. ->where('records.type', 'OUT')
  135. ->select(DB::raw('MONTH(records.date) as month_num'), DB::raw('SUM(records_rows.amount) as total'))
  136. ->groupBy('month_num')
  137. ->get();
  138. // Map income data to correct position in season array
  139. foreach ($incomeRecords as $record) {
  140. $monthIndex = array_search($record->month_num, $monthOrder);
  141. if ($monthIndex !== false) {
  142. $incomeData[$monthIndex] = $record->total;
  143. }
  144. }
  145. // Map expense data to correct position in season array
  146. foreach ($expenseRecords as $record) {
  147. $monthIndex = array_search($record->month_num, $monthOrder);
  148. if ($monthIndex !== false) {
  149. $expenseData[$monthIndex] = $record->total;
  150. }
  151. }
  152. return [
  153. 'labels' => $monthNames,
  154. 'datasets' => [
  155. [
  156. 'label' => 'Entrate',
  157. 'data' => $incomeData,
  158. 'backgroundColor' => 'rgba(54, 162, 235, 0.5)'
  159. ],
  160. [
  161. 'label' => 'Uscite',
  162. 'data' => $expenseData,
  163. 'backgroundColor' => 'rgba(255, 99, 132, 0.5)'
  164. ],
  165. ]
  166. ];
  167. }
  168. public function getYearlySummary()
  169. {
  170. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  171. $totalIncome = DB::table('records')
  172. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  173. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  174. ->where('records.type', 'IN')
  175. ->sum('records_rows.amount');
  176. $totalExpenses = DB::table('records')
  177. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  178. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  179. ->where('records.type', 'OUT')
  180. ->sum('records_rows.amount');
  181. $delta = $totalIncome - $totalExpenses;
  182. return [
  183. 'totalIncome' => $totalIncome,
  184. 'totalExpenses' => $totalExpenses,
  185. 'delta' => $delta
  186. ];
  187. }
  188. public function getTopCausalsByAmount($limit = 10)
  189. {
  190. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  191. $query = DB::table('records_rows')
  192. ->join('records', 'records_rows.record_id', '=', 'records.id')
  193. ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
  194. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']]);
  195. $query->where('records.type', 'IN');
  196. Log::info('Query: ' . $query->toSql());
  197. $causals = $query->select(
  198. 'causals.id',
  199. 'causals.name',
  200. 'causals.parent_id',
  201. DB::raw('SUM(records_rows.amount) as total_amount')
  202. )
  203. ->groupBy('causals.id', 'causals.name', 'causals.parent_id')
  204. ->orderBy('total_amount', 'desc')
  205. ->limit($limit)
  206. ->get();
  207. Log::info('Causals: ' . json_encode($causals));
  208. $inData = [];
  209. foreach ($causals as $causal) {
  210. $tempCausal = new \App\Models\Causal();
  211. $tempCausal->id = $causal->id;
  212. $tempCausal->name = $causal->name;
  213. $tempCausal->parent_id = $causal->parent_id;
  214. $treeName = $tempCausal->getTree();
  215. $displayName = strlen($treeName) > 30 ? substr($treeName, 0, 27) . '...' : $treeName;
  216. $inData[] = [
  217. 'label' => $displayName,
  218. 'value' => $causal->total_amount,
  219. 'fullName' => $treeName
  220. ];
  221. }
  222. usort($inData, function ($a, $b) {
  223. return $b['value'] <=> $a['value'];
  224. });
  225. $inData = array_slice($inData, 0, $limit);
  226. return [
  227. 'inLabels' => array_column($inData, 'label'),
  228. 'inData' => $inData,
  229. 'datasets' => [
  230. [
  231. 'label' => 'Entrate per Causale',
  232. 'data' => array_column($inData, 'value'),
  233. ]
  234. ]
  235. ];
  236. }
  237. public function getCoursesForSelect()
  238. {
  239. $seasonYears = $this->parseSeason($this->seasonFilter);
  240. Log::info('Getting courses for season: ' . $this->seasonFilter);
  241. Log::info('Season years: ' . json_encode($seasonYears));
  242. $courses = Course::with(['level', 'type', 'frequency'])
  243. ->where('active', true)
  244. ->where(function($query) use ($seasonYears) {
  245. // Match courses that contain either year of the season
  246. $query->where('year', 'like', '%' . $seasonYears['start_year'] . '%')
  247. ->orWhere('year', 'like', '%' . $seasonYears['end_year'] . '%')
  248. ->orWhere('year', 'like', '%' . $this->seasonFilter . '%');
  249. })
  250. ->orderBy('name')
  251. ->get()
  252. ->map(function ($course) {
  253. $type = null;
  254. if (!empty($course->course_type_id)) {
  255. $type = \App\Models\CourseType::find($course->course_type_id);
  256. }
  257. $levelName = is_object($course->level) ? $course->level->name : 'No Level';
  258. $typeName = is_object($type) ? $type->name : 'No Type';
  259. $frequencyName = is_object($course->frequency) ? $course->frequency->name : 'No Frequency';
  260. $year = $course->year ?? '';
  261. return [
  262. 'id' => $course->id,
  263. 'name' => $course->name,
  264. 'full_name' => "{$course->name} - {$levelName} - {$typeName} - {$frequencyName} ({$year})",
  265. 'level_name' => $levelName,
  266. 'type_name' => $typeName,
  267. 'frequency_name' => $frequencyName,
  268. 'year' => $year
  269. ];
  270. })->toArray();
  271. Log::info('Found ' . count($courses) . ' courses for season ' . $this->seasonFilter);
  272. return $courses;
  273. }
  274. public function updatedSelectedCourse()
  275. {
  276. Log::info('updatedSelectedCourse called with: ' . $this->selectedCourse);
  277. if ($this->selectedCourse) {
  278. $this->emit('courseSelected', $this->selectedCourse);
  279. Log::info('Event emitted with course ID: ' . $this->selectedCourse);
  280. }
  281. }
  282. public function getCourseData($courseId)
  283. {
  284. $this->selectedCourse = $courseId;
  285. return $this->getCourseMonthlyEarnings($courseId);
  286. }
  287. public function getCourseMonthlyEarnings($courseId = null)
  288. {
  289. $courseId = $courseId ?? $this->selectedCourse;
  290. Log::info('Getting earnings for course ID: ' . $courseId);
  291. if (!$courseId) {
  292. return [
  293. 'labels' => [],
  294. 'datasets' => []
  295. ];
  296. }
  297. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  298. $monthNames = [
  299. 9 => 'Set', 10 => 'Ott', 11 => 'Nov', 12 => 'Dic',
  300. 1 => 'Gen', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr',
  301. 5 => 'Mag', 6 => 'Giu', 7 => 'Lug', 8 => 'Ago'
  302. ];
  303. $monthlyData = [];
  304. foreach ($monthOrder as $i) {
  305. $monthlyData[$i] = [
  306. 'earned' => 0,
  307. 'total' => 0,
  308. 'participants' => 0
  309. ];
  310. }
  311. $memberCourses = \App\Models\MemberCourse::where('course_id', $courseId)
  312. ->with('member')
  313. ->get();
  314. foreach ($memberCourses as $memberCourse) {
  315. $price = (float)($memberCourse->price ?? 0);
  316. if ($memberCourse->months) {
  317. $monthsData = json_decode($memberCourse->months, true);
  318. if (is_array($monthsData)) {
  319. foreach ($monthsData as $monthData) {
  320. $month = $monthData['m'] ?? null;
  321. $status = $monthData['status'] ?? '';
  322. if ($month !== null && isset($monthlyData[$month])) {
  323. $monthlyData[$month]['total'] += $price;
  324. if ($status === 1) {
  325. $monthlyData[$month]['earned'] += $price;
  326. }
  327. $monthlyData[$month]['participants']++;
  328. }
  329. }
  330. }
  331. }
  332. }
  333. $labels = [];
  334. $earnedData = [];
  335. $totalData = [];
  336. $participantData = [];
  337. $missingData = [];
  338. foreach ($monthOrder as $month) {
  339. $labels[] = $monthNames[$month];
  340. $earnedData[] = round($monthlyData[$month]['earned'], 2);
  341. $totalData[] = round($monthlyData[$month]['total'], 2);
  342. $participantData[] = $monthlyData[$month]['participants'];
  343. $missingData[] = round($monthlyData[$month]['total'] - $monthlyData[$month]['earned'], 2);
  344. }
  345. return [
  346. 'labels' => $labels,
  347. 'datasets' => [
  348. [
  349. 'label' => 'Pagamenti Effettuati',
  350. 'backgroundColor' => 'rgba(0, 184, 148, 1)',
  351. 'data' => $earnedData,
  352. 'type' => 'bar',
  353. 'order' => 3
  354. ],
  355. [
  356. 'label' => 'Pagamenti Attesi',
  357. 'backgroundColor' => 'transparent',
  358. 'borderColor' => 'rgba(48, 51, 107, 1)',
  359. 'borderWidth' => 3,
  360. 'pointBackgroundColor' => 'rgba(48, 51, 107, 1)',
  361. 'pointRadius' => 5,
  362. 'data' => $totalData,
  363. 'type' => 'line',
  364. 'tension' => 0.2,
  365. 'order' => 2,
  366. 'participants' => $participantData,
  367. 'missing' => $missingData
  368. ]
  369. ]
  370. ];
  371. }
  372. public static function getMemberCountChartData($endYear = null, $span = 5)
  373. {
  374. if ($endYear === null) {
  375. $endYear = date('Y');
  376. }
  377. $startYear = $endYear - $span + 1;
  378. $memberCards = MemberCard::select('member_id', 'expire_date')
  379. ->whereNotNull('expire_date')
  380. ->whereNotNull('member_id')
  381. ->where('status', '!=', 'cancelled')
  382. ->whereRaw('YEAR(expire_date) >= ?', [$startYear])
  383. ->whereRaw('YEAR(expire_date) <= ?', [$endYear])
  384. ->get();
  385. $seasonCounts = [];
  386. for ($year = $startYear; $year <= $endYear; $year++) {
  387. $seasonPeriod = ($year - 1) . '-' . $year;
  388. $seasonCounts[$seasonPeriod] = [];
  389. }
  390. foreach ($memberCards as $card) {
  391. $expireYear = date('Y', strtotime($card->expire_date));
  392. $expireMonth = date('n', strtotime($card->expire_date));
  393. // Determine which season this belongs to
  394. if ($expireMonth >= 9) {
  395. // September-December: belongs to season starting that year
  396. $seasonPeriod = $expireYear . '-' . ($expireYear + 1);
  397. } else {
  398. // January-August: belongs to season starting previous year
  399. $seasonPeriod = ($expireYear - 1) . '-' . $expireYear;
  400. }
  401. if (isset($seasonCounts[$seasonPeriod])) {
  402. $seasonCounts[$seasonPeriod][$card->member_id] = true;
  403. }
  404. }
  405. $seasonLabels = [];
  406. $memberCountData = [];
  407. foreach ($seasonCounts as $seasonPeriod => $members) {
  408. $seasonLabels[] = $seasonPeriod;
  409. $memberCountData[] = count($members);
  410. }
  411. return [
  412. 'labels' => $seasonLabels,
  413. 'datasets' => [
  414. [
  415. 'label' => 'Membri Tesserati',
  416. 'data' => $memberCountData,
  417. 'backgroundColor' => 'rgba(54, 162, 235, 0.2)',
  418. 'borderColor' => 'rgba(54, 162, 235, 1)',
  419. 'borderWidth' => 2,
  420. 'pointBackgroundColor' => 'rgba(54, 162, 235, 1)',
  421. 'pointRadius' => 4,
  422. 'tension' => 0.3,
  423. 'fill' => true
  424. ]
  425. ]
  426. ];
  427. }
  428. }