Dashboard.php 33 KB

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