Reports.php 24 KB

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