Reports.php 28 KB

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