Reports.php.bak 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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, 3);
  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 getYearlySummary()
  179. {
  180. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  181. $totalIncome = DB::table('records')
  182. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  183. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  184. ->where('records.type', 'IN')
  185. ->sum('records_rows.amount');
  186. $totalExpenses = DB::table('records')
  187. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  188. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']])
  189. ->where('records.type', 'OUT')
  190. ->sum('records_rows.amount');
  191. $delta = $totalIncome - $totalExpenses;
  192. return [
  193. 'totalIncome' => $totalIncome,
  194. 'totalExpenses' => $totalExpenses,
  195. 'delta' => $delta
  196. ];
  197. }
  198. public function getTopCausalsByAmount($limit = 10)
  199. {
  200. $dateRange = $this->getSeasonDateRange($this->seasonFilter);
  201. $query = DB::table('records_rows')
  202. ->join('records', 'records_rows.record_id', '=', 'records.id')
  203. ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
  204. ->whereBetween('records.date', [$dateRange['start'], $dateRange['end']]);
  205. $query->where('records.type', 'IN');
  206. Log::info('Query: ' . $query->toSql());
  207. $causals = $query->select(
  208. 'causals.id',
  209. 'causals.name',
  210. 'causals.parent_id',
  211. DB::raw('SUM(records_rows.amount) as total_amount')
  212. )
  213. ->where(function ($query) {
  214. $query->where('causals.no_reports', '=', '0')
  215. ->orWhereNull('causals.no_reports');
  216. })
  217. ->groupBy('causals.id', 'causals.name', 'causals.parent_id')
  218. ->orderBy('total_amount', 'desc')
  219. ->limit($limit)
  220. ->get();
  221. Log::info('Causals: ' . json_encode($causals));
  222. $inData = [];
  223. foreach ($causals as $causal) {
  224. $tempCausal = new \App\Models\Causal();
  225. $tempCausal->id = $causal->id;
  226. $tempCausal->name = $causal->name;
  227. $tempCausal->parent_id = $causal->parent_id;
  228. $treeName = $tempCausal->getTree();
  229. //$displayName = strlen($treeName) > 30 ? substr($treeName, 0, 27) . '...' : $treeName;
  230. $displayName = $treeName;
  231. $inData[] = [
  232. 'label' => $displayName,
  233. 'value' => $causal->total_amount,
  234. 'fullName' => $treeName
  235. ];
  236. }
  237. usort($inData, function ($a, $b) {
  238. return $b['value'] <=> $a['value'];
  239. });
  240. $inData = array_slice($inData, 0, $limit);
  241. return [
  242. 'inLabels' => array_column($inData, 'label'),
  243. 'inData' => $inData,
  244. 'datasets' => [
  245. [
  246. 'label' => 'Entrate per Causale',
  247. 'data' => array_column($inData, 'value'),
  248. ]
  249. ]
  250. ];
  251. }
  252. public function getCoursesForSelect()
  253. {
  254. $seasonYears = $this->parseSeason($this->seasonFilter);
  255. Log::info('Getting courses for season: ' . $this->seasonFilter);
  256. Log::info('Season years: ' . json_encode($seasonYears));
  257. $courses = Course::with(['level', 'frequency'])
  258. ->where('active', true)
  259. ->where(function ($query) use ($seasonYears) {
  260. $query->where('year', $this->seasonFilter)
  261. ->orWhere('year', 'like', '%' . $seasonYears['start_year'] . '-' . $seasonYears['end_year'] . '%')
  262. ->orWhere('year', 'like', '%' . $seasonYears['start_year'] . '%')
  263. ->orWhere('year', 'like', '%' . $seasonYears['end_year'] . '%');
  264. })
  265. ->orderBy('name')
  266. ->get()
  267. ->filter(function ($course) use ($seasonYears) {
  268. $courseYear = $course->year;
  269. if ($courseYear === $this->seasonFilter) {
  270. return true;
  271. }
  272. if (
  273. str_contains($courseYear, $seasonYears['start_year']) &&
  274. str_contains($courseYear, $seasonYears['end_year'])
  275. ) {
  276. return true;
  277. }
  278. if ($courseYear == $seasonYears['start_year'] || $courseYear == $seasonYears['end_year']) {
  279. return true;
  280. }
  281. return false;
  282. })
  283. ->map(function ($course) {
  284. Log::info('Processing course: ' . $course->name . ' (ID: ' . $course->id . ')' . $course);
  285. $levelName = is_object($course->level) ? $course->level->name : 'No Level';
  286. $typeName = $course->getFormattedTypeField();
  287. $frequencyName = is_object($course->frequency) ? $course->frequency->name : 'No Frequency';
  288. $year = $course->year ?? '';
  289. return [
  290. 'id' => $course->id,
  291. 'name' => $course->name,
  292. 'full_name' => "{$course->name} - {$levelName} - {$typeName} - {$frequencyName} ({$year})",
  293. 'level_name' => $levelName,
  294. 'type_name' => $typeName,
  295. 'frequency_name' => $frequencyName,
  296. 'year' => $year
  297. ];
  298. })->values()->toArray();
  299. Log::info('Found ' . count($courses) . ' courses for season ' . $this->seasonFilter);
  300. return $courses;
  301. }
  302. public function getMonthlyTotalsForSeason($season)
  303. {
  304. $originalSeason = $this->seasonFilter;
  305. $this->seasonFilter = $season;
  306. $result = $this->getMonthlyTotals();
  307. $this->seasonFilter = $originalSeason;
  308. return $result;
  309. }
  310. public function getTopCausalsByAmountForSeason($season, $limit = 10)
  311. {
  312. $originalSeason = $this->seasonFilter;
  313. $this->seasonFilter = $season;
  314. $result = $this->getTopCausalsByAmount($limit);
  315. $this->seasonFilter = $originalSeason;
  316. return $result;
  317. }
  318. public function getTesseratiDataForSeason($season)
  319. {
  320. $originalSeason = $this->seasonFilter;
  321. $this->seasonFilter = $season;
  322. $result = $this->getTesseratiData();
  323. $this->seasonFilter = $originalSeason;
  324. return $result;
  325. }
  326. public function updatedSelectedCourse()
  327. {
  328. Log::info('updatedSelectedCourse called with: ' . $this->selectedCourse);
  329. if ($this->selectedCourse) {
  330. $this->emit('courseSelected', $this->selectedCourse);
  331. Log::info('Event emitted with course ID: ' . $this->selectedCourse);
  332. }
  333. }
  334. public function getCourseData($courseId)
  335. {
  336. $this->selectedCourse = $courseId;
  337. return $this->getCourseMonthlyEarnings($courseId);
  338. }
  339. public function getCourseMonthlyEarnings($courseId = null)
  340. {
  341. $courseId = $courseId ?? $this->selectedCourse;
  342. Log::info('Getting earnings for course ID: ' . $courseId);
  343. if (!$courseId) {
  344. return [
  345. 'labels' => [],
  346. 'datasets' => [],
  347. 'tableData' => [],
  348. 'isEmpty' => true,
  349. 'message' => 'Seleziona un corso per visualizzare i dati'
  350. ];
  351. }
  352. $monthOrder = [9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8];
  353. $monthNames = [
  354. 9 => 'Set',
  355. 10 => 'Ott',
  356. 11 => 'Nov',
  357. 12 => 'Dic',
  358. 1 => 'Gen',
  359. 2 => 'Feb',
  360. 3 => 'Mar',
  361. 4 => 'Apr',
  362. 5 => 'Mag',
  363. 6 => 'Giu',
  364. 7 => 'Lug',
  365. 8 => 'Ago'
  366. ];
  367. $monthNamesExtended = [
  368. 0 => 'Settembre',
  369. 1 => 'Ottobre',
  370. 2 => 'Novembre',
  371. 3 => 'Dicembre',
  372. 4 => 'Gennaio',
  373. 5 => 'Febbraio',
  374. 6 => 'Marzo',
  375. 7 => 'Aprile',
  376. 8 => 'Maggio',
  377. 9 => 'Giugno',
  378. 10 => 'Luglio',
  379. 11 => 'Agosto'
  380. ];
  381. $monthlyData = [];
  382. foreach ($monthOrder as $i) {
  383. $monthlyData[$i] = [
  384. 'earned' => 0,
  385. 'total' => 0,
  386. 'suspended' => 0,
  387. 'participants' => 0
  388. ];
  389. }
  390. $rates = \App\Models\Rate::whereHas('member_course', function ($query) use ($courseId) {
  391. $query->where('course_id', $courseId);
  392. })->with('member_course')->get();
  393. if ($rates->isEmpty()) {
  394. return [
  395. 'labels' => [],
  396. 'datasets' => [],
  397. 'tableData' => [],
  398. 'isEmpty' => true,
  399. 'message' => 'Nessun dato disponibile per questo corso nella stagione ' . $this->seasonFilter
  400. ];
  401. }
  402. $hasData = false;
  403. foreach ($rates as $rate) {
  404. $totalPrice = (float)($rate->price ?? 0);
  405. if ($rate->months) {
  406. $monthsData = json_decode($rate->months, true);
  407. if (is_array($monthsData) && count($monthsData) > 0) {
  408. $pricePerMonth = $totalPrice / count($monthsData);
  409. foreach ($monthsData as $month) {
  410. $monthNumber = (int)$month;
  411. if (isset($monthlyData[$monthNumber])) {
  412. $monthlyData[$monthNumber]['total'] += $pricePerMonth;
  413. $monthlyData[$monthNumber]['participants']++;
  414. $hasData = true;
  415. // if (!is_null($rate->record_id) && $rate->record_id !== '') {
  416. // $monthlyData[$monthNumber]['earned'] += $pricePerMonth;
  417. // }
  418. // pagamenti effettuati
  419. if (!is_null($rate->record_id) && $rate->record_id !== '' && $rate->status == 1) {
  420. $monthlyData[$monthNumber]['participants']--;
  421. $monthlyData[$monthNumber]['earned'] += $pricePerMonth;
  422. }
  423. // pagamenti sospesi
  424. if ($rate->status == 2) {
  425. $monthlyData[$monthNumber]['participants']--;
  426. $monthlyData[$monthNumber]['total'] -= $pricePerMonth;
  427. $monthlyData[$monthNumber]['suspended']++;
  428. }
  429. }
  430. }
  431. }
  432. }
  433. }
  434. if (!$hasData) {
  435. return [
  436. 'labels' => [],
  437. 'datasets' => [],
  438. 'tableData' => [],
  439. 'isEmpty' => true,
  440. 'message' => 'Nessun pagamento registrato per questo corso nella stagione ' . $this->seasonFilter
  441. ];
  442. }
  443. $labels = [];
  444. $earnedData = [];
  445. $totalData = [];
  446. $participantData = [];
  447. $tableData = [];
  448. foreach ($monthOrder as $month) {
  449. $earned = round($monthlyData[$month]['earned'], 2);
  450. $total = round($monthlyData[$month]['total'], 2);
  451. $delta = max(0, $total - $earned);
  452. $participants = $monthlyData[$month]['participants'];
  453. $suspended = $monthlyData[$month]['suspended'];
  454. $labels[] = $monthNames[$month];
  455. $earnedData[] = $earned;
  456. $totalData[] = $total;
  457. $participantData[] = $participants;
  458. $suspendedData[] = $suspended;
  459. $percentage = $total > 0 ? round(($earned / $total) * 100, 1) : 0;
  460. $tableData[] = [
  461. 'month' => $monthNames[$month],
  462. 'participants' => $participants,
  463. 'suspended' => $suspended,
  464. 'earned' => $earned,
  465. 'total' => $total,
  466. 'delta' => $delta,
  467. 'percentage' => $percentage
  468. ];
  469. }
  470. $daIncassareData = array_map(function($tot, $inc) {
  471. return $tot - $inc;
  472. }, $totalData, $earnedData);
  473. return [
  474. 'labels' => $labels,
  475. 'datasets' => [
  476. [
  477. 'label' => 'TOT. INCASSATO',
  478. 'data' => $earnedData,
  479. 'participantData' => $participantData,
  480. 'suspendedData' => $suspendedData,
  481. 'monthNamesExtended' => $monthNamesExtended,
  482. ],
  483. [
  484. 'label' => 'TOT. DA INCASSARE',
  485. 'data' => $daIncassareData,
  486. 'participantData' => $participantData,
  487. 'suspendedData' => $suspendedData,
  488. 'monthNamesExtended' => $monthNamesExtended,
  489. ]
  490. ],
  491. 'tableData' => $tableData,
  492. 'isEmpty' => false
  493. ];
  494. }
  495. public static function getMemberCountChartData($endYear = null, $span = 5)
  496. {
  497. if ($endYear === null) {
  498. $endYear = date('Y');
  499. }
  500. $startYear = $endYear - $span + 1;
  501. $memberCards = MemberCard::select('member_id', 'expire_date', 'card_id')
  502. ->with('card:id,name')
  503. ->whereNotNull('expire_date')
  504. ->whereNotNull('member_id')
  505. ->whereNotNull('card_id')
  506. ->where('status', '!=', 'cancelled')
  507. ->whereRaw('YEAR(expire_date) >= ?', [$startYear])
  508. ->whereRaw('YEAR(expire_date) <= ?', [$endYear])
  509. ->get();
  510. $cardTypes = $memberCards->pluck('card.name')->unique()->filter()->sort()->values();
  511. $seasonCounts = [];
  512. $seasonCardCounts = [];
  513. for ($year = $startYear; $year <= $endYear; $year++) {
  514. $seasonPeriod = ($year - 1) . '-' . $year;
  515. $seasonCounts[$seasonPeriod] = [];
  516. $seasonCardCounts[$seasonPeriod] = [];
  517. foreach ($cardTypes as $cardType) {
  518. $seasonCardCounts[$seasonPeriod][$cardType] = [];
  519. }
  520. }
  521. foreach ($memberCards as $card) {
  522. $expireYear = date('Y', strtotime($card->expire_date));
  523. $expireMonth = date('n', strtotime($card->expire_date));
  524. if ($expireMonth >= 9) {
  525. $seasonPeriod = $expireYear . '-' . ($expireYear + 1);
  526. } else {
  527. $seasonPeriod = ($expireYear - 1) . '-' . $expireYear;
  528. }
  529. if (isset($seasonCounts[$seasonPeriod])) {
  530. $seasonCounts[$seasonPeriod][$card->member_id] = true;
  531. $cardTypeName = $card->card->name ?? 'Unknown';
  532. if (isset($seasonCardCounts[$seasonPeriod][$cardTypeName])) {
  533. $seasonCardCounts[$seasonPeriod][$cardTypeName][$card->member_id] = true;
  534. }
  535. }
  536. }
  537. $seasonLabels = [];
  538. $memberCountData = [];
  539. $cardTypeDatasets = [];
  540. $colors = [
  541. 'rgba(255, 99, 132, 0.2)',
  542. 'rgba(54, 162, 235, 0.2)',
  543. 'rgba(255, 205, 86, 0.2)',
  544. 'rgba(75, 192, 192, 0.2)',
  545. 'rgba(153, 102, 255, 0.2)',
  546. 'rgba(255, 159, 64, 0.2)',
  547. 'rgba(199, 199, 199, 0.2)',
  548. 'rgba(83, 102, 255, 0.2)',
  549. ];
  550. $borderColors = [
  551. 'rgba(255, 99, 132, 1)',
  552. 'rgba(54, 162, 235, 1)',
  553. 'rgba(255, 205, 86, 1)',
  554. 'rgba(75, 192, 192, 1)',
  555. 'rgba(153, 102, 255, 1)',
  556. 'rgba(255, 159, 64, 1)',
  557. 'rgba(199, 199, 199, 1)',
  558. 'rgba(83, 102, 255, 1)',
  559. ];
  560. foreach ($cardTypes as $index => $cardType) {
  561. $cardTypeDatasets[$cardType] = [
  562. 'label' => $cardType,
  563. 'data' => [],
  564. 'backgroundColor' => $colors[$index % count($colors)],
  565. 'borderColor' => $borderColors[$index % count($borderColors)],
  566. 'borderWidth' => 2,
  567. 'pointBackgroundColor' => $borderColors[$index % count($borderColors)],
  568. 'pointRadius' => 4,
  569. 'tension' => 0.3,
  570. 'fill' => true
  571. ];
  572. }
  573. foreach ($seasonCounts as $seasonPeriod => $members) {
  574. $seasonLabels[] = $seasonPeriod;
  575. $memberCountData[] = count($members);
  576. foreach ($cardTypes as $cardType) {
  577. $cardTypeCount = isset($seasonCardCounts[$seasonPeriod][$cardType])
  578. ? count($seasonCardCounts[$seasonPeriod][$cardType])
  579. : 0;
  580. $cardTypeDatasets[$cardType]['data'][] = $cardTypeCount;
  581. }
  582. }
  583. $datasets = [
  584. [
  585. 'label' => 'Totale Membri Tesserati',
  586. 'data' => $memberCountData,
  587. 'backgroundColor' => 'rgba(54, 162, 235, 0.2)',
  588. 'borderColor' => 'rgba(54, 162, 235, 1)',
  589. 'borderWidth' => 3,
  590. 'pointBackgroundColor' => 'rgba(54, 162, 235, 1)',
  591. 'pointRadius' => 6,
  592. 'tension' => 0.3,
  593. 'fill' => true,
  594. 'type' => 'line'
  595. ]
  596. ];
  597. foreach ($cardTypeDatasets as $dataset) {
  598. $datasets[] = $dataset;
  599. }
  600. return [
  601. 'labels' => $seasonLabels,
  602. 'datasets' => $datasets
  603. ];
  604. }
  605. }