Reports.php 34 KB

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