Reports.php 35 KB

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