Reports.php 27 KB

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