Dashboard.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Carbon\Carbon;
  5. use DateTimeZone;
  6. use Illuminate\Support\Facades\Log;
  7. class Dashboard extends Component
  8. {
  9. // Existing properties
  10. public $totMembers = 0;
  11. public $totSuppliers = 0;
  12. public $totTodayIn = 0;
  13. public $totTodayOut = 0;
  14. public $dayName;
  15. public $in;
  16. public $out;
  17. public $members;
  18. public $activeUsers = 0;
  19. public $registeredUsers = 0;
  20. public $expiredCertificates = 0;
  21. public $suspendedSubscriptions = 0;
  22. public $activeUsersChange = 0;
  23. public $registeredUsersChange = 0;
  24. public $expiredCertificatesChange = 0;
  25. public $suspendedSubscriptionsChange = 0;
  26. public $received = 0;
  27. public $toPay = 0;
  28. public $paid = 0;
  29. public $courses = [];
  30. public $active_member_courses = [];
  31. public $active_member_courses_count = 0;
  32. public $active_courses = 0;
  33. public $active_subscriptions = 0;
  34. public $fields = [];
  35. public $recentUsers = [];
  36. public $recentTransactions = [];
  37. public $coursesParticipation = [];
  38. public $notes = '';
  39. public $savedNotes = [];
  40. public array $membersDatas = [];
  41. public array $recordDatas = [];
  42. public array $labels = [];
  43. public array $monthlyLabels = [];
  44. public array $monthlyIncomeData = [];
  45. public array $monthlyExpenseData = [];
  46. public function render()
  47. {
  48. Log::info('Dashboard render method called');
  49. return view('livewire.dashboard');
  50. }
  51. public function mount()
  52. {
  53. Log::info('Dashboard mount started');
  54. $startTime = microtime(true);
  55. $this->dayName = Carbon::now()->locale('it_IT')->dayName;
  56. Log::info('Day name set', ['day' => $this->dayName]);
  57. $this->loadBasicStats();
  58. $this->loadUserStats();
  59. $this->loadFinancialStats();
  60. $this->loadRecentData();
  61. $this->loadSavedNotes();
  62. $endTime = microtime(true);
  63. $executionTime = round(($endTime - $startTime) * 1000, 2);
  64. Log::info('Dashboard mount completed', [
  65. 'execution_time_ms' => $executionTime,
  66. 'active_users' => $this->activeUsers,
  67. 'courses_count' => count($this->courses),
  68. 'participation_count' => count($this->coursesParticipation)
  69. ]);
  70. }
  71. private function loadBasicStats()
  72. {
  73. Log::info('Loading basic stats');
  74. $startTime = microtime(true);
  75. try {
  76. $this->totMembers = \App\Models\Member::count();
  77. $this->totSuppliers = \App\Models\Supplier::count();
  78. Log::info('Basic counts loaded', [
  79. 'total_members' => $this->totMembers,
  80. 'total_suppliers' => $this->totSuppliers
  81. ]);
  82. // Calculate today's income and expenses
  83. $this->totTodayIn = 0;
  84. $todayRecordsIn = \App\Models\Record::where('type', 'IN')
  85. ->where('date', date("Y-m-d"))
  86. ->get();
  87. foreach ($todayRecordsIn as $record) {
  88. foreach ($record->rows as $row) {
  89. $this->totTodayIn += $row->amount;
  90. }
  91. }
  92. $this->totTodayOut = 0;
  93. $todayRecordsOut = \App\Models\Record::where('type', 'OUT')
  94. ->where('date', date("Y-m-d"))
  95. ->get();
  96. foreach ($todayRecordsOut as $record) {
  97. foreach ($record->rows as $row) {
  98. $this->totTodayOut += $row->amount;
  99. }
  100. }
  101. $endTime = microtime(true);
  102. Log::info('Basic stats loaded successfully', [
  103. 'today_income' => $this->totTodayIn,
  104. 'today_expenses' => $this->totTodayOut,
  105. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  106. ]);
  107. } catch (\Exception $e) {
  108. Log::error('Error loading basic stats', [
  109. 'error' => $e->getMessage(),
  110. 'file' => $e->getFile(),
  111. 'line' => $e->getLine()
  112. ]);
  113. }
  114. }
  115. private function loadUserStats()
  116. {
  117. Log::info('Loading user stats');
  118. $startTime = microtime(true);
  119. try {
  120. $this->activeUsers = \App\Models\Member::where('is_archived', 0)->orWhere('is_archived', NULL)->count();
  121. $this->registeredUsers = \App\Models\Member::where('current_status', 2)->count();
  122. $this->suspendedSubscriptions = \App\Models\Member::where('current_status', 1)->count();
  123. Log::info('User counts loaded', [
  124. 'active_users' => $this->activeUsers,
  125. 'registered_users' => $this->registeredUsers,
  126. 'suspended_subscriptions' => $this->suspendedSubscriptions
  127. ]);
  128. $this->expiredCertificates = \App\Models\Member::whereHas('certificates', function ($query) {
  129. $query->where('expire_date', '<', now());
  130. })->whereDoesntHave('certificates', function ($query) {
  131. $query->where('expire_date', '>=', now());
  132. })->count();
  133. Log::info('Expired certificates count', ['expired_certificates' => $this->expiredCertificates]);
  134. // Calculate changes from last month
  135. $lastMonth = now()->subMonth();
  136. $endOfLastMonth = $lastMonth->copy()->endOfMonth();
  137. $lastMonthActiveUsers = \App\Models\Member::where('is_archived', false)
  138. ->where('created_at', '<=', $endOfLastMonth)
  139. ->count();
  140. $lastMonthRegisteredUsers = \App\Models\Member::where('current_status', 2)
  141. ->where('updated_at', '<=', $endOfLastMonth)
  142. ->count();
  143. $lastMonthSuspendedSubscriptions = \App\Models\Member::where('current_status', 1)
  144. ->where('updated_at', '<=', $endOfLastMonth)
  145. ->count();
  146. $lastMonthExpiredCertificates = \App\Models\Member::whereHas('certificates', function ($query) use ($endOfLastMonth) {
  147. $query->where('expire_date', '<', $endOfLastMonth);
  148. })->whereDoesntHave('certificates', function ($query) use ($endOfLastMonth) {
  149. $query->where('expire_date', '>=', $endOfLastMonth);
  150. })->count();
  151. $this->activeUsersChange = $this->activeUsers - $lastMonthActiveUsers;
  152. $this->registeredUsersChange = $this->registeredUsers - $lastMonthRegisteredUsers;
  153. $this->expiredCertificatesChange = $this->expiredCertificates - $lastMonthExpiredCertificates;
  154. $this->suspendedSubscriptionsChange = $this->suspendedSubscriptions - $lastMonthSuspendedSubscriptions;
  155. $endTime = microtime(true);
  156. Log::info('User stats loaded successfully', [
  157. 'changes' => [
  158. 'active_users' => $this->activeUsersChange,
  159. 'registered_users' => $this->registeredUsersChange,
  160. 'expired_certificates' => $this->expiredCertificatesChange,
  161. 'suspended_subscriptions' => $this->suspendedSubscriptionsChange
  162. ],
  163. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  164. ]);
  165. } catch (\Exception $e) {
  166. Log::error('Error loading user stats', [
  167. 'error' => $e->getMessage(),
  168. 'file' => $e->getFile(),
  169. 'line' => $e->getLine()
  170. ]);
  171. }
  172. }
  173. private function loadFinancialStats()
  174. {
  175. Log::info('Loading financial stats');
  176. $startTime = microtime(true);
  177. try {
  178. $currentMonth = now()->format('Y-m');
  179. $currentDate = now()->format('Y-m-d');
  180. Log::info('Calculating financial stats for month', ['month' => $currentMonth]);
  181. // excluded members
  182. $excluded_members = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  183. // excluded payment method
  184. $excluded_payment_methods = \App\Models\PaymentMethod::where('money', true)->pluck('id')->toArray();
  185. // excluded causals
  186. $excluded_causals = \App\Models\Causal::orWhereIn('name', [
  187. 'Corrispettivo fiscale giornaliero',
  188. 'CFG',
  189. ])->orWhere('hidden', 1)->orWhere('enabled', 0)->pluck('id')->toArray();
  190. // Incassato
  191. $this->received = 0;
  192. $records_in = \App\Models\Record::with('rows')->where('type', 'IN')
  193. ->whereRaw('DATE_FORMAT(date, "%Y-%m") = ?', [$currentMonth])
  194. ->where(function ($query) {
  195. $query->where('deleted', false)->orWhere('deleted', null);
  196. })->get();
  197. foreach ($records_in as $record) {
  198. if (in_array($record->payment_method_id, $excluded_payment_methods)) {
  199. continue;
  200. }
  201. if (in_array($record->member_id, $excluded_members)) {
  202. continue;
  203. }
  204. foreach ($record->rows as $row) {
  205. if ($row->causal_id) {
  206. $causal = \App\Models\Causal::find($row->causal_id);
  207. if (!$causal || (isset($causal->hidden) && $causal->hidden)) {
  208. continue;
  209. }
  210. if (in_array($row->causal_id, $excluded_causals)) {
  211. continue;
  212. }
  213. $this->received += $row->amount;
  214. if ($row->vat_id > 0) {
  215. $this->received += getVatValue($row->amount, $row->vat_id);
  216. }
  217. }
  218. }
  219. }
  220. // END - Incassato
  221. // Pagato
  222. $this->paid = 0;
  223. $records_out = \App\Models\Record::with('rows')->where('type', 'OUT')
  224. ->whereRaw('DATE_FORMAT(data_pagamento, "%Y-%m") = ?', [$currentMonth])
  225. ->where(function ($query) {
  226. $query->where('deleted', false)->orWhere('deleted', null);
  227. })->get();
  228. foreach ($records_out as $record) {
  229. if (in_array($record->payment_method_id, $excluded_payment_methods)) {
  230. continue;
  231. }
  232. if (in_array($record->member_id, $excluded_members)) {
  233. continue;
  234. }
  235. foreach ($record->rows as $row) {
  236. if ($row->causal_id) {
  237. $causal = \App\Models\Causal::find($row->causal_id);
  238. if (!$causal || (isset($causal->hidden) && $causal->hidden)) {
  239. continue;
  240. }
  241. if (in_array($row->causal_id, $excluded_causals)) {
  242. continue;
  243. }
  244. $this->paid += $row->amount;
  245. if ($row->vat_id > 0) {
  246. $this->paid += getVatValue($row->amount, $row->vat_id);
  247. }
  248. }
  249. }
  250. }
  251. // END - Pagato
  252. // Da pagare
  253. $this->toPay = 0;
  254. $records_toPay = \App\Models\Record::with('rows')->where('type', 'OUT')
  255. ->where(function ($query) use ($currentDate) {
  256. $query->where('data_pagamento', '>', $currentDate)
  257. ->orWhereNull('data_pagamento');
  258. })
  259. ->where(function ($query) {
  260. $query->where('deleted', false)->orWhere('deleted', null);
  261. })->get();
  262. foreach ($records_toPay as $record) {
  263. if (in_array($record->payment_method_id, $excluded_payment_methods)) {
  264. continue;
  265. }
  266. if (in_array($record->member_id, $excluded_members)) {
  267. continue;
  268. }
  269. foreach ($record->rows as $row) {
  270. if ($row->causal_id) {
  271. $causal = \App\Models\Causal::find($row->causal_id);
  272. if (!$causal || (isset($causal->hidden) && $causal->hidden)) {
  273. continue;
  274. }
  275. if (in_array($row->causal_id, $excluded_causals)) {
  276. continue;
  277. }
  278. $this->toPay += $row->amount;
  279. if ($row->vat_id > 0) {
  280. $this->toPay += getVatValue($row->amount, $row->vat_id);
  281. }
  282. }
  283. }
  284. }
  285. // END - Da pagare
  286. $endTime = microtime(true);
  287. Log::info('Financial stats loaded successfully', [
  288. 'received' => $this->received,
  289. 'paid' => $this->paid,
  290. 'to_pay' => $this->toPay,
  291. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  292. ]);
  293. } catch (\Exception $e) {
  294. Log::error('Error loading financial stats', [
  295. 'error' => $e->getMessage(),
  296. 'file' => $e->getFile(),
  297. 'line' => $e->getLine()
  298. ]);
  299. }
  300. }
  301. private function loadRecentData()
  302. {
  303. Log::info('Loading recent data');
  304. $startTime = microtime(true);
  305. try {
  306. // Load recent users
  307. $recentMembers = \App\Models\Member::where('is_archived', 0)
  308. ->orWhere('is_archived', NULL)
  309. ->orderBy('created_at', 'desc')
  310. ->limit(5)
  311. ->get();
  312. $this->recentUsers = $recentMembers->map(function ($member) {
  313. return [
  314. 'surname' => strtoupper($member->last_name),
  315. 'name' => strtoupper($member->first_name),
  316. 'phone' => $member->phone ?? '',
  317. 'email' => $member->email ?? ''
  318. ];
  319. })->toArray();
  320. Log::info('Recent users loaded', ['count' => count($this->recentUsers)]);
  321. // Load recent transactions
  322. $recentRecords = \App\Models\Record::where('date', '>=', now()->subDays(30))
  323. ->with(['member', 'supplier'])
  324. ->orderBy('date', 'desc')
  325. ->orderBy('created_at', 'desc')
  326. ->limit(10)
  327. ->get();
  328. $this->recentTransactions = $recentRecords->map(function ($record) {
  329. if ($record->type == 'IN') {
  330. $name = $record->member ?
  331. strtoupper($record->member->last_name) . ' ' . strtoupper($record->member->first_name) :
  332. 'MEMBRO SCONOSCIUTO';
  333. } else {
  334. $name = $record->supplier ?
  335. strtoupper($record->supplier->name) :
  336. 'FORNITORE SCONOSCIUTO';
  337. }
  338. $totalAmount = 0;
  339. foreach ($record->rows as $row) {
  340. $totalAmount += $row->amount;
  341. }
  342. return [
  343. 'name' => $name,
  344. 'amount' => $totalAmount,
  345. 'type' => $record->type == 'IN' ? 'ENTRATA' : 'USCITA'
  346. ];
  347. })->toArray();
  348. Log::info('Recent transactions loaded', ['count' => count($this->recentTransactions)]);
  349. $this->loadCoursesData();
  350. $this->loadCoursesParticipation();
  351. $endTime = microtime(true);
  352. Log::info('Recent data loaded successfully', [
  353. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  354. ]);
  355. } catch (\Exception $e) {
  356. Log::error('Error loading recent data', [
  357. 'error' => $e->getMessage(),
  358. 'file' => $e->getFile(),
  359. 'line' => $e->getLine()
  360. ]);
  361. }
  362. }
  363. private function loadCoursesData()
  364. {
  365. Log::info('Loading courses data');
  366. $startTime = microtime(true);
  367. try {
  368. $today = now()->format('N');
  369. $dayNames = [
  370. 1 => 'lun',
  371. 2 => 'mar',
  372. 3 => 'mer',
  373. 4 => 'gio',
  374. 5 => 'ven',
  375. 6 => 'sab',
  376. 7 => 'dom'
  377. ];
  378. $todayName = $dayNames[$today];
  379. Log::info('Searching courses for today', [
  380. 'today_number' => $today,
  381. 'today_name' => $todayName
  382. ]);
  383. // $memberCourses = \App\Models\MemberCourse::with(['course.level', 'course.frequency', 'member'])
  384. // ->whereIn('status', [0, 1])
  385. // ->whereHas('course', function ($query) {
  386. // $query->whereNotNull('when');
  387. // })
  388. // ->get();
  389. // Log::info('Total member courses found', [
  390. // 'count' => $memberCourses->count()
  391. // ]);
  392. // $activeCourses = $memberCourses->filter(function ($memberCourse) use ($todayName) {
  393. // try {
  394. // $whenData = json_decode($memberCourse->course->when, true);
  395. // if (!is_array($whenData)) {
  396. // return false;
  397. // }
  398. // foreach ($whenData as $schedule) {
  399. // if (
  400. // isset($schedule['day']) &&
  401. // is_array($schedule['day']) &&
  402. // in_array($todayName, $schedule['day'])
  403. // ) {
  404. // return true;
  405. // }
  406. // }
  407. // } catch (\Exception $e) {
  408. // Log::debug('Error parsing course schedule', [
  409. // 'member_course_id' => $memberCourse->id,
  410. // 'course_id' => $memberCourse->course->id,
  411. // 'when' => $memberCourse->course->when,
  412. // 'error' => $e->getMessage()
  413. // ]);
  414. // }
  415. // return false;
  416. // });
  417. // Log::info('Active courses found for today', [
  418. // 'count' => $activeCourses->count(),
  419. // 'course_ids' => $activeCourses->pluck('course.id')->toArray()
  420. // ]);
  421. // $this->courses = $activeCourses->map(function ($memberCourse) use ($todayName) {
  422. // $whenData = json_decode($memberCourse->course->when, true);
  423. // Log::debug('Processing course schedule', [
  424. // 'member_course_id' => $memberCourse->id,
  425. // 'course_id' => $memberCourse->course->id,
  426. // 'course_name' => $memberCourse->course->name,
  427. // 'when_data' => $whenData,
  428. // 'looking_for_day' => $todayName
  429. // ]);
  430. // $todaySchedule = null;
  431. // if (is_array($whenData)) {
  432. // foreach ($whenData as $schedule) {
  433. // if (
  434. // isset($schedule['day']) &&
  435. // is_array($schedule['day']) &&
  436. // in_array($todayName, $schedule['day'])
  437. // ) {
  438. // $todaySchedule = $schedule;
  439. // Log::debug('Found matching schedule', [
  440. // 'schedule' => $schedule,
  441. // 'course_id' => $memberCourse->course->id
  442. // ]);
  443. // break;
  444. // }
  445. // }
  446. // }
  447. // if (!$todaySchedule) {
  448. // Log::debug('No matching schedule found for today', [
  449. // 'course_id' => $memberCourse->course->id,
  450. // 'when_data' => $whenData
  451. // ]);
  452. // return null;
  453. // }
  454. // $days = implode('-', array_map('ucfirst', $todaySchedule['day']));
  455. // $course = $memberCourse->course;
  456. // $courseName = $course->name ?? 'Corso Sconosciuto';
  457. // $levelName = $course->level?->name ?? '';
  458. // $frequencyName = $course->frequency?->name ?? '';
  459. // $typeName = $course->getFormattedTypeField() ?? '';
  460. // $fullCourseName = $course->getDetailsName();
  461. // return [
  462. // 'time' => $todaySchedule['from'] . ' - ' . $todaySchedule['to'],
  463. // 'course_name' => $courseName,
  464. // 'full_name' => $fullCourseName,
  465. // 'level_name' => $levelName,
  466. // 'type_name' => $typeName,
  467. // 'frequency_name' => $frequencyName,
  468. // 'days' => $days,
  469. // 'type' => $course->type ?? 'Standard',
  470. // 'from_time' => $todaySchedule['from'],
  471. // 'course_id' => $course->id,
  472. // 'member_course_id' => $memberCourse->id
  473. // ];
  474. // })->filter()->unique('course_id')->values();
  475. // $sortedCourses = $this->courses->sortBy('from_time')->take(5)->values();
  476. // Log::info('Courses sorted by time', [
  477. // 'sorted_courses' => $sortedCourses->map(function ($course) {
  478. // return [
  479. // 'time' => $course['time'],
  480. // 'from_time' => $course['from_time'],
  481. // 'course_name' => $course['course_name'],
  482. // 'course_id' => $course['course_id']
  483. // ];
  484. // })->toArray()
  485. // ]);
  486. // $this->courses = $sortedCourses->map(function ($course) {
  487. // unset($course['from_time'], $course['member_course_id'], $course['course_id']);
  488. // return $course;
  489. // })->toArray();
  490. $now = date('Y-m-d');
  491. $day = substr(Carbon::now()->locale('it_IT')->dayName, 0, 3);
  492. $this->courses = \App\Models\Course::where('enabled', true)->where('date_from', '<=', $now)->where('date_to', '>=', $now)->whereJsonContains('when', ['day' => $day])->get()->map(function ($t) use ($day) {
  493. $when = json_decode($t->when, true);
  494. $time = '';
  495. foreach ($when as $w) {
  496. if (in_array($day, $w['day'])) {
  497. $time = $w['from'] . ' - ' . $w['to'];
  498. }
  499. }
  500. return [
  501. 'full_name' => $t->getDetailsName(),
  502. 'course_name' => ($t->discipline?->name ? $t->discipline->name . " - " : "") . $t->name,
  503. 'time' => $time,
  504. ];
  505. })->sortBy([['time', 'asc'], ['course_name', 'asc']], SORT_NATURAL)->toArray();
  506. $this->courses = array_values($this->courses);
  507. $member_courses = \App\Models\MemberCourse::where('date_from', '<=', $now)->where('date_to', '>=', $now)->get();
  508. foreach ($member_courses as $member_course) {
  509. if (!isset($this->active_member_courses[$member_course->course_id])) {
  510. $this->active_member_courses[$member_course->course_id] = ['name' => $member_course->course->getDetailsName(), 'count' => 0];
  511. }
  512. $this->active_member_courses[$member_course->course_id]['count']++;
  513. $this->active_member_courses_count++;
  514. }
  515. usort($this->active_member_courses, function ($a, $b) {
  516. if ($a['count'] == $b['count']) {
  517. return strcmp($a['name'], $b['name']);
  518. }
  519. return $a['count'] < $b['count'];
  520. });
  521. $this->active_courses = \App\Models\Course::where('enabled', true)->where('date_from', '<=', $now)->where('date_to', '>=', $now)->count();
  522. $this->active_subscriptions = \App\Models\MemberSubscription::where('date_from', '<=', $now)->where('date_to', '>=', $now)->count();
  523. $endTime = microtime(true);
  524. Log::info('Courses data loaded successfully', [
  525. 'final_courses_count' => count($this->courses),
  526. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2),
  527. 'final_courses_display' => $this->courses
  528. ]);
  529. } catch (\Exception $e) {
  530. Log::error('Error loading courses data', [
  531. 'error' => $e->getMessage(),
  532. 'file' => $e->getFile(),
  533. 'line' => $e->getLine()
  534. ]);
  535. $this->courses = [];
  536. $this->active_member_courses = [];
  537. $this->active_member_courses_count = 0;
  538. $this->active_courses = 0;
  539. $this->active_subscriptions = 0;
  540. }
  541. }
  542. private function loadCoursesParticipation()
  543. {
  544. Log::info('Loading courses participation');
  545. $startTime = microtime(true);
  546. try {
  547. // Conta le partecipazioni per corso (include tutti gli status)
  548. $courseStats = \App\Models\MemberCourse::with(['course.level', 'course.frequency'])
  549. ->whereIn('status', [0, 1]) // Include both statuses
  550. ->selectRaw('course_id, COUNT(*) as participants')
  551. ->groupBy('course_id')
  552. ->orderBy('participants', 'desc')
  553. ->limit(4)
  554. ->get();
  555. Log::info('Course participation stats', [
  556. 'courses_found' => $courseStats->count(),
  557. 'stats' => $courseStats->map(function ($stat) {
  558. $course = $stat->course;
  559. $levelName = is_object($course->level) ? $course->level->name : '';
  560. $frequencyName = is_object($course->frequency) ? $course->frequency->name : '';
  561. return [
  562. 'course_id' => $stat->course_id,
  563. 'course_name' => $course->name ?? 'Unknown',
  564. 'level_name' => $levelName,
  565. 'frequency_name' => $frequencyName,
  566. 'participants' => $stat->participants
  567. ];
  568. })->toArray()
  569. ]);
  570. $totalParticipants = $courseStats->sum('participants');
  571. $this->coursesParticipation = $courseStats->map(function ($stat) use ($totalParticipants) {
  572. $percentage = $totalParticipants > 0 ? ($stat->participants / $totalParticipants) * 100 : 0;
  573. $course = $stat->course;
  574. $courseName = $course->name ?? 'Corso Sconosciuto';
  575. $levelName = is_object($course->level) ? $course->level->name : '';
  576. $frequencyName = is_object($course->frequency) ? $course->frequency->name : '';
  577. $typeName = $course->getFormattedTypeField() ?? '';
  578. $displayName = $course->getDetailsName();
  579. // Assegna colori basati sul nome del corso
  580. $color = $this->getCourseColor($courseName);
  581. return [
  582. 'course_name' => $displayName,
  583. 'base_course_name' => $courseName,
  584. 'level_name' => $levelName,
  585. 'type_name' => $typeName,
  586. 'frequency_name' => $frequencyName,
  587. 'participants' => $stat->participants,
  588. 'percentage' => round($percentage, 1),
  589. 'color' => $color
  590. ];
  591. })->toArray();
  592. $endTime = microtime(true);
  593. Log::info('Courses participation loaded successfully', [
  594. 'total_participants' => $totalParticipants,
  595. 'participation_data' => $this->coursesParticipation,
  596. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  597. ]);
  598. } catch (\Exception $e) {
  599. Log::error('Error loading courses participation', [
  600. 'error' => $e->getMessage(),
  601. 'file' => $e->getFile(),
  602. 'line' => $e->getLine()
  603. ]);
  604. $this->coursesParticipation = [];
  605. }
  606. }
  607. private function getCourseColor($courseName)
  608. {
  609. $colors = [
  610. 'padel',
  611. 'tennis',
  612. 'pallavolo',
  613. 'yoga',
  614. 'blue',
  615. 'pink',
  616. 'green',
  617. 'red',
  618. 'indigo',
  619. 'amber',
  620. 'cyan',
  621. 'lime'
  622. ];
  623. $hash = crc32($courseName);
  624. $colorIndex = abs($hash) % count($colors);
  625. $assignedColor = $colors[$colorIndex];
  626. Log::debug('Course color assigned', [
  627. 'course_name' => $courseName,
  628. 'hash' => $hash,
  629. 'color_index' => $colorIndex,
  630. 'assigned_color' => $assignedColor
  631. ]);
  632. return $assignedColor;
  633. }
  634. private function loadSavedNotes()
  635. {
  636. Log::info('Loading saved notes');
  637. try {
  638. $this->savedNotes = session()->get('dashboard_notes', []);
  639. Log::info('Saved notes loaded', [
  640. 'notes_count' => count($this->savedNotes)
  641. ]);
  642. } catch (\Exception $e) {
  643. Log::error('Error loading saved notes', [
  644. 'error' => $e->getMessage()
  645. ]);
  646. $this->savedNotes = [];
  647. }
  648. }
  649. private function saveSavedNotes()
  650. {
  651. try {
  652. session()->put('dashboard_notes', $this->savedNotes);
  653. Log::info('Notes saved to session', [
  654. 'notes_count' => count($this->savedNotes)
  655. ]);
  656. } catch (\Exception $e) {
  657. Log::error('Error saving notes', [
  658. 'error' => $e->getMessage()
  659. ]);
  660. }
  661. }
  662. public function saveNote()
  663. {
  664. Log::info('Save note called', ['note_text' => $this->notes]);
  665. try {
  666. if (trim($this->notes) !== '') {
  667. $newNote = [
  668. 'id' => uniqid(),
  669. 'text' => trim($this->notes),
  670. 'created_at' => now()->timezone('Europe/Rome')->format('d/m/Y H:i'),
  671. 'completed' => false
  672. ];
  673. array_unshift($this->savedNotes, $newNote);
  674. $this->saveSavedNotes();
  675. $this->notes = '';
  676. $this->dispatchBrowserEvent('note-saved');
  677. Log::info('Note saved successfully', [
  678. 'note_id' => $newNote['id'],
  679. 'total_notes' => count($this->savedNotes)
  680. ]);
  681. } else {
  682. Log::warning('Attempted to save empty note');
  683. }
  684. } catch (\Exception $e) {
  685. Log::error('Error saving note', [
  686. 'error' => $e->getMessage(),
  687. 'file' => $e->getFile(),
  688. 'line' => $e->getLine()
  689. ]);
  690. }
  691. }
  692. public function completeNote($noteId)
  693. {
  694. Log::info('Complete note called', ['note_id' => $noteId]);
  695. try {
  696. $initialCount = count($this->savedNotes);
  697. $this->savedNotes = array_filter($this->savedNotes, function ($note) use ($noteId) {
  698. return $note['id'] !== $noteId;
  699. });
  700. $this->savedNotes = array_values($this->savedNotes);
  701. $finalCount = count($this->savedNotes);
  702. if ($initialCount > $finalCount) {
  703. $this->saveSavedNotes();
  704. $this->dispatchBrowserEvent('note-completed');
  705. Log::info('Note completed successfully', [
  706. 'note_id' => $noteId,
  707. 'remaining_notes' => $finalCount
  708. ]);
  709. } else {
  710. Log::warning('Note not found for completion', ['note_id' => $noteId]);
  711. }
  712. } catch (\Exception $e) {
  713. Log::error('Error completing note', [
  714. 'note_id' => $noteId,
  715. 'error' => $e->getMessage(),
  716. 'file' => $e->getFile(),
  717. 'line' => $e->getLine()
  718. ]);
  719. }
  720. }
  721. public function addMember()
  722. {
  723. Log::info('Redirecting to add member');
  724. return redirect()->to('/members?new=1');
  725. }
  726. public function addSupplier()
  727. {
  728. Log::info('Redirecting to add supplier');
  729. return redirect()->to('/suppliers?new=1');
  730. }
  731. public function addIn()
  732. {
  733. Log::info('Redirecting to add income record');
  734. return redirect()->to('/in?new=1');
  735. }
  736. public function addOut()
  737. {
  738. Log::info('Redirecting to add expense record');
  739. return redirect()->to('/out?new=1');
  740. }
  741. public function debugCourses()
  742. {
  743. Log::info('=== DEBUG COURSES CALLED ===');
  744. $today = now()->format('N');
  745. $dayNames = [
  746. 1 => 'lun',
  747. 2 => 'mar',
  748. 3 => 'mer',
  749. 4 => 'gio',
  750. 5 => 'ven',
  751. 6 => 'sab',
  752. 7 => 'dom'
  753. ];
  754. $todayName = $dayNames[$today];
  755. // Get all member courses
  756. $allCourses = \App\Models\MemberCourse::with('course')->get();
  757. Log::info('All courses debug', [
  758. 'total_courses' => $allCourses->count(),
  759. 'today_name' => $todayName,
  760. 'courses' => $allCourses->map(function ($mc) {
  761. return [
  762. 'id' => $mc->id,
  763. 'status' => $mc->status,
  764. 'when' => $mc->when,
  765. 'course_name' => $mc->course->name ?? 'Unknown'
  766. ];
  767. })->toArray()
  768. ]);
  769. $this->dispatchBrowserEvent('debug-completed');
  770. }
  771. public function activateTestCourses()
  772. {
  773. try {
  774. $updated = \App\Models\MemberCourse::whereIn('id', [21, 22, 23, 24])
  775. ->update(['status' => 1]);
  776. Log::info('Activated test courses', ['updated_count' => $updated]);
  777. $this->loadCoursesData();
  778. $this->loadCoursesParticipation();
  779. $this->dispatchBrowserEvent('courses-activated', [
  780. 'message' => "Attivati $updated corsi per test"
  781. ]);
  782. } catch (\Exception $e) {
  783. Log::error('Error activating courses', ['error' => $e->getMessage()]);
  784. }
  785. }
  786. private function getLabels()
  787. {
  788. $labels = array();
  789. for ($i = 6; $i >= 0; $i--) {
  790. $labels[] = date("d/M", strtotime('-' . $i . ' days'));
  791. }
  792. return $labels;
  793. }
  794. private function getRecordData($type)
  795. {
  796. $data = [];
  797. for ($i = 6; $i >= 0; $i--) {
  798. $found = false;
  799. $records = $type == 'IN' ? $this->in : $this->out;
  800. foreach ($records as $record) {
  801. if (date("Y-m-d", strtotime($record->date)) == date("Y-m-d", strtotime('-' . $i . ' days'))) {
  802. $data[] = $record->total;
  803. $found = true;
  804. break;
  805. }
  806. }
  807. if (!$found) {
  808. $data[] = 0;
  809. }
  810. }
  811. return $data;
  812. }
  813. private function getMemberData()
  814. {
  815. $data = [];
  816. for ($i = 6; $i >= 0; $i--) {
  817. $found = false;
  818. foreach ($this->members as $member) {
  819. if (date("Y-m-d", strtotime($member->created_at)) == date("Y-m-d", strtotime('-' . $i . ' days'))) {
  820. $data[] = $member->total;
  821. $found = true;
  822. break;
  823. }
  824. }
  825. if (!$found) {
  826. $data[] = 0;
  827. }
  828. }
  829. return $data;
  830. }
  831. }