Reports.php 25 KB

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