Reports.php 36 KB

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