Dashboard.php 29 KB

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