Reports.php 26 KB

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