Reports.php 38 KB

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