Dashboard.php.bak 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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. $this->received = \App\Models\Record::where('type', 'IN')
  178. ->whereRaw('DATE_FORMAT(date, "%Y-%m") = ?', [$currentMonth])
  179. ->where(function ($query) {
  180. $query->where('deleted', false)->orWhere('deleted', null);
  181. })
  182. ->sum('amount') ?? 0;
  183. $this->paid = \App\Models\Record::where('type', 'OUT')
  184. ->whereRaw('DATE_FORMAT(date, "%Y-%m") = ?', [$currentMonth])
  185. ->where('data_pagamento', '<=', $currentDate)
  186. ->where(function ($query) {
  187. $query->where('deleted', false)->orWhere('deleted', null);
  188. })
  189. ->sum('amount') ?? 0;
  190. $this->toPay = \App\Models\Record::where('type', 'OUT')
  191. ->whereRaw('DATE_FORMAT(date, "%Y-%m") = ?', [$currentMonth])
  192. ->where(function ($query) use($currentDate) {
  193. $query->where('data_pagamento', '>', $currentDate)
  194. ->orWhereNull('data_pagamento');
  195. })
  196. ->where(function ($query) {
  197. $query->where('deleted', false)->orWhere('deleted', null);
  198. })
  199. ->sum('amount') ?? 0;
  200. $endTime = microtime(true);
  201. Log::info('Financial stats loaded successfully', [
  202. 'received' => $this->received,
  203. 'paid' => $this->paid,
  204. 'to_pay' => $this->toPay,
  205. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  206. ]);
  207. } catch (\Exception $e) {
  208. Log::error('Error loading financial stats', [
  209. 'error' => $e->getMessage(),
  210. 'file' => $e->getFile(),
  211. 'line' => $e->getLine()
  212. ]);
  213. }
  214. }
  215. private function loadRecentData()
  216. {
  217. Log::info('Loading recent data');
  218. $startTime = microtime(true);
  219. try {
  220. // Load recent users
  221. $recentMembers = \App\Models\Member::where('is_archived', 0)
  222. ->orWhere('is_archived', NULL)
  223. ->orderBy('created_at', 'desc')
  224. ->limit(5)
  225. ->get();
  226. $this->recentUsers = $recentMembers->map(function ($member) {
  227. return [
  228. 'surname' => strtoupper($member->last_name),
  229. 'name' => strtoupper($member->first_name),
  230. 'phone' => $member->phone ?? '',
  231. 'email' => $member->email ?? ''
  232. ];
  233. })->toArray();
  234. Log::info('Recent users loaded', ['count' => count($this->recentUsers)]);
  235. // Load recent transactions
  236. $recentRecords = \App\Models\Record::where('date', '>=', now()->subDays(30))
  237. ->with(['member', 'supplier'])
  238. ->orderBy('date', 'desc')
  239. ->orderBy('created_at', 'desc')
  240. ->limit(10)
  241. ->get();
  242. $this->recentTransactions = $recentRecords->map(function ($record) {
  243. if ($record->type == 'IN') {
  244. $name = $record->member ?
  245. strtoupper($record->member->last_name) . ' ' . strtoupper($record->member->first_name) :
  246. 'MEMBRO SCONOSCIUTO';
  247. } else {
  248. $name = $record->supplier ?
  249. strtoupper($record->supplier->name) :
  250. 'FORNITORE SCONOSCIUTO';
  251. }
  252. $totalAmount = 0;
  253. foreach ($record->rows as $row) {
  254. $totalAmount += $row->amount;
  255. }
  256. return [
  257. 'name' => $name,
  258. 'amount' => $totalAmount,
  259. 'type' => $record->type == 'IN' ? 'ENTRATA' : 'USCITA'
  260. ];
  261. })->toArray();
  262. Log::info('Recent transactions loaded', ['count' => count($this->recentTransactions)]);
  263. $this->loadCoursesData();
  264. $this->loadCoursesParticipation();
  265. $endTime = microtime(true);
  266. Log::info('Recent data loaded successfully', [
  267. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  268. ]);
  269. } catch (\Exception $e) {
  270. Log::error('Error loading recent data', [
  271. 'error' => $e->getMessage(),
  272. 'file' => $e->getFile(),
  273. 'line' => $e->getLine()
  274. ]);
  275. }
  276. }
  277. private function loadCoursesData()
  278. {
  279. Log::info('Loading courses data');
  280. $startTime = microtime(true);
  281. try {
  282. $today = now()->format('N');
  283. $dayNames = [
  284. 1 => 'lun',
  285. 2 => 'mar',
  286. 3 => 'mer',
  287. 4 => 'gio',
  288. 5 => 'ven',
  289. 6 => 'sab',
  290. 7 => 'dom'
  291. ];
  292. $todayName = $dayNames[$today];
  293. Log::info('Searching courses for today', [
  294. 'today_number' => $today,
  295. 'today_name' => $todayName
  296. ]);
  297. $memberCourses = \App\Models\MemberCourse::with(['course.level', 'course.frequency', 'member'])
  298. ->whereIn('status', [0, 1])
  299. ->whereHas('course', function ($query) {
  300. $query->whereNotNull('when');
  301. })
  302. ->get();
  303. Log::info('Total member courses found', [
  304. 'count' => $memberCourses->count()
  305. ]);
  306. $activeCourses = $memberCourses->filter(function ($memberCourse) use ($todayName) {
  307. try {
  308. $whenData = json_decode($memberCourse->course->when, true);
  309. if (!is_array($whenData)) {
  310. return false;
  311. }
  312. foreach ($whenData as $schedule) {
  313. if (
  314. isset($schedule['day']) &&
  315. is_array($schedule['day']) &&
  316. in_array($todayName, $schedule['day'])
  317. ) {
  318. return true;
  319. }
  320. }
  321. } catch (\Exception $e) {
  322. Log::debug('Error parsing course schedule', [
  323. 'member_course_id' => $memberCourse->id,
  324. 'course_id' => $memberCourse->course->id,
  325. 'when' => $memberCourse->course->when,
  326. 'error' => $e->getMessage()
  327. ]);
  328. }
  329. return false;
  330. });
  331. Log::info('Active courses found for today', [
  332. 'count' => $activeCourses->count(),
  333. 'course_ids' => $activeCourses->pluck('course.id')->toArray()
  334. ]);
  335. $this->courses = $activeCourses->map(function ($memberCourse) use ($todayName) {
  336. $whenData = json_decode($memberCourse->course->when, true);
  337. Log::debug('Processing course schedule', [
  338. 'member_course_id' => $memberCourse->id,
  339. 'course_id' => $memberCourse->course->id,
  340. 'course_name' => $memberCourse->course->name,
  341. 'when_data' => $whenData,
  342. 'looking_for_day' => $todayName
  343. ]);
  344. $todaySchedule = null;
  345. if (is_array($whenData)) {
  346. foreach ($whenData as $schedule) {
  347. if (
  348. isset($schedule['day']) &&
  349. is_array($schedule['day']) &&
  350. in_array($todayName, $schedule['day'])
  351. ) {
  352. $todaySchedule = $schedule;
  353. Log::debug('Found matching schedule', [
  354. 'schedule' => $schedule,
  355. 'course_id' => $memberCourse->course->id
  356. ]);
  357. break;
  358. }
  359. }
  360. }
  361. if (!$todaySchedule) {
  362. Log::debug('No matching schedule found for today', [
  363. 'course_id' => $memberCourse->course->id,
  364. 'when_data' => $whenData
  365. ]);
  366. return null;
  367. }
  368. $days = implode('-', array_map('ucfirst', $todaySchedule['day']));
  369. $course = $memberCourse->course;
  370. $courseName = $course->name ?? 'Corso Sconosciuto';
  371. $levelName = $course->level?->name ?? '';
  372. $frequencyName = $course->frequency?->name ?? '';
  373. $typeName = $course->getFormattedTypeField() ?? '';
  374. $courseNameParts = [$courseName];
  375. if ($levelName) $courseNameParts[] = $levelName;
  376. if ($typeName) $courseNameParts[] = $typeName;
  377. if ($frequencyName) $courseNameParts[] = $frequencyName;
  378. $fullCourseName = implode(' - ', $courseNameParts);
  379. return [
  380. 'time' => $todaySchedule['from'] . ' - ' . $todaySchedule['to'],
  381. 'course_name' => $courseName,
  382. 'full_name' => $fullCourseName,
  383. 'level_name' => $levelName,
  384. 'type_name' => $typeName,
  385. 'frequency_name' => $frequencyName,
  386. 'days' => $days,
  387. 'type' => $course->type ?? 'Standard',
  388. 'from_time' => $todaySchedule['from'],
  389. 'course_id' => $course->id,
  390. 'member_course_id' => $memberCourse->id
  391. ];
  392. })->filter()->values();
  393. $sortedCourses = $this->courses->sortBy('from_time')->take(5);
  394. Log::info('Courses sorted by time', [
  395. 'sorted_courses' => $sortedCourses->map(function ($course) {
  396. return [
  397. 'time' => $course['time'],
  398. 'from_time' => $course['from_time'],
  399. 'course_name' => $course['course_name'],
  400. 'course_id' => $course['course_id']
  401. ];
  402. })->toArray()
  403. ]);
  404. $this->courses = $sortedCourses->map(function ($course) {
  405. unset($course['from_time'], $course['member_course_id'], $course['course_id']);
  406. return $course;
  407. })->toArray();
  408. $endTime = microtime(true);
  409. Log::info('Courses data loaded successfully', [
  410. 'final_courses_count' => count($this->courses),
  411. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2),
  412. 'final_courses_display' => $this->courses
  413. ]);
  414. } catch (\Exception $e) {
  415. Log::error('Error loading courses data', [
  416. 'error' => $e->getMessage(),
  417. 'file' => $e->getFile(),
  418. 'line' => $e->getLine()
  419. ]);
  420. $this->courses = [];
  421. }
  422. }
  423. private function loadCoursesParticipation()
  424. {
  425. Log::info('Loading courses participation');
  426. $startTime = microtime(true);
  427. try {
  428. // Conta le partecipazioni per corso (include tutti gli status)
  429. $courseStats = \App\Models\MemberCourse::with(['course.level', 'course.frequency'])
  430. ->whereIn('status', [0, 1]) // Include both statuses
  431. ->selectRaw('course_id, COUNT(*) as participants')
  432. ->groupBy('course_id')
  433. ->orderBy('participants', 'desc')
  434. ->limit(4)
  435. ->get();
  436. Log::info('Course participation stats', [
  437. 'courses_found' => $courseStats->count(),
  438. 'stats' => $courseStats->map(function ($stat) {
  439. $course = $stat->course;
  440. $levelName = is_object($course->level) ? $course->level->name : '';
  441. $frequencyName = is_object($course->frequency) ? $course->frequency->name : '';
  442. return [
  443. 'course_id' => $stat->course_id,
  444. 'course_name' => $course->name ?? 'Unknown',
  445. 'level_name' => $levelName,
  446. 'frequency_name' => $frequencyName,
  447. 'participants' => $stat->participants
  448. ];
  449. })->toArray()
  450. ]);
  451. $totalParticipants = $courseStats->sum('participants');
  452. $this->coursesParticipation = $courseStats->map(function ($stat) use ($totalParticipants) {
  453. $percentage = $totalParticipants > 0 ? ($stat->participants / $totalParticipants) * 100 : 0;
  454. $course = $stat->course;
  455. $courseName = $course->name ?? 'Corso Sconosciuto';
  456. $levelName = is_object($course->level) ? $course->level->name : '';
  457. $frequencyName = is_object($course->frequency) ? $course->frequency->name : '';
  458. $typeName = $course->getFormattedTypeField() ?? '';
  459. // Build display name with level and frequency
  460. $displayNameParts = [$courseName];
  461. if ($levelName) $displayNameParts[] = $levelName;
  462. if ($typeName) $displayNameParts[] = $typeName;
  463. if ($frequencyName) $displayNameParts[] = $frequencyName;
  464. $displayName = implode(' - ', $displayNameParts);
  465. // Assegna colori basati sul nome del corso
  466. $color = $this->getCourseColor($courseName);
  467. return [
  468. 'course_name' => $displayName,
  469. 'base_course_name' => $courseName,
  470. 'level_name' => $levelName,
  471. 'type_name' => $typeName,
  472. 'frequency_name' => $frequencyName,
  473. 'participants' => $stat->participants,
  474. 'percentage' => round($percentage, 1),
  475. 'color' => $color
  476. ];
  477. })->toArray();
  478. $endTime = microtime(true);
  479. Log::info('Courses participation loaded successfully', [
  480. 'total_participants' => $totalParticipants,
  481. 'participation_data' => $this->coursesParticipation,
  482. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  483. ]);
  484. } catch (\Exception $e) {
  485. Log::error('Error loading courses participation', [
  486. 'error' => $e->getMessage(),
  487. 'file' => $e->getFile(),
  488. 'line' => $e->getLine()
  489. ]);
  490. $this->coursesParticipation = [];
  491. }
  492. }
  493. private function getCourseColor($courseName)
  494. {
  495. $colors = [
  496. 'padel',
  497. 'tennis',
  498. 'pallavolo',
  499. 'yoga',
  500. 'blue',
  501. 'pink',
  502. 'green',
  503. 'red',
  504. 'indigo',
  505. 'amber',
  506. 'cyan',
  507. 'lime'
  508. ];
  509. $hash = crc32($courseName);
  510. $colorIndex = abs($hash) % count($colors);
  511. $assignedColor = $colors[$colorIndex];
  512. Log::debug('Course color assigned', [
  513. 'course_name' => $courseName,
  514. 'hash' => $hash,
  515. 'color_index' => $colorIndex,
  516. 'assigned_color' => $assignedColor
  517. ]);
  518. return $assignedColor;
  519. }
  520. private function loadSavedNotes()
  521. {
  522. Log::info('Loading saved notes');
  523. try {
  524. $this->savedNotes = session()->get('dashboard_notes', []);
  525. Log::info('Saved notes loaded', [
  526. 'notes_count' => count($this->savedNotes)
  527. ]);
  528. } catch (\Exception $e) {
  529. Log::error('Error loading saved notes', [
  530. 'error' => $e->getMessage()
  531. ]);
  532. $this->savedNotes = [];
  533. }
  534. }
  535. private function saveSavedNotes()
  536. {
  537. try {
  538. session()->put('dashboard_notes', $this->savedNotes);
  539. Log::info('Notes saved to session', [
  540. 'notes_count' => count($this->savedNotes)
  541. ]);
  542. } catch (\Exception $e) {
  543. Log::error('Error saving notes', [
  544. 'error' => $e->getMessage()
  545. ]);
  546. }
  547. }
  548. public function saveNote()
  549. {
  550. Log::info('Save note called', ['note_text' => $this->notes]);
  551. try {
  552. if (trim($this->notes) !== '') {
  553. $newNote = [
  554. 'id' => uniqid(),
  555. 'text' => trim($this->notes),
  556. 'created_at' => now()->timezone('Europe/Rome')->format('d/m/Y H:i'),
  557. 'completed' => false
  558. ];
  559. array_unshift($this->savedNotes, $newNote);
  560. $this->saveSavedNotes();
  561. $this->notes = '';
  562. $this->dispatchBrowserEvent('note-saved');
  563. Log::info('Note saved successfully', [
  564. 'note_id' => $newNote['id'],
  565. 'total_notes' => count($this->savedNotes)
  566. ]);
  567. } else {
  568. Log::warning('Attempted to save empty note');
  569. }
  570. } catch (\Exception $e) {
  571. Log::error('Error saving note', [
  572. 'error' => $e->getMessage(),
  573. 'file' => $e->getFile(),
  574. 'line' => $e->getLine()
  575. ]);
  576. }
  577. }
  578. public function completeNote($noteId)
  579. {
  580. Log::info('Complete note called', ['note_id' => $noteId]);
  581. try {
  582. $initialCount = count($this->savedNotes);
  583. $this->savedNotes = array_filter($this->savedNotes, function ($note) use ($noteId) {
  584. return $note['id'] !== $noteId;
  585. });
  586. $this->savedNotes = array_values($this->savedNotes);
  587. $finalCount = count($this->savedNotes);
  588. if ($initialCount > $finalCount) {
  589. $this->saveSavedNotes();
  590. $this->dispatchBrowserEvent('note-completed');
  591. Log::info('Note completed successfully', [
  592. 'note_id' => $noteId,
  593. 'remaining_notes' => $finalCount
  594. ]);
  595. } else {
  596. Log::warning('Note not found for completion', ['note_id' => $noteId]);
  597. }
  598. } catch (\Exception $e) {
  599. Log::error('Error completing note', [
  600. 'note_id' => $noteId,
  601. 'error' => $e->getMessage(),
  602. 'file' => $e->getFile(),
  603. 'line' => $e->getLine()
  604. ]);
  605. }
  606. }
  607. public function addMember()
  608. {
  609. Log::info('Redirecting to add member');
  610. return redirect()->to('/members?new=1');
  611. }
  612. public function addSupplier()
  613. {
  614. Log::info('Redirecting to add supplier');
  615. return redirect()->to('/suppliers?new=1');
  616. }
  617. public function addIn()
  618. {
  619. Log::info('Redirecting to add income record');
  620. return redirect()->to('/in?new=1');
  621. }
  622. public function addOut()
  623. {
  624. Log::info('Redirecting to add expense record');
  625. return redirect()->to('/out?new=1');
  626. }
  627. public function debugCourses()
  628. {
  629. Log::info('=== DEBUG COURSES CALLED ===');
  630. $today = now()->format('N');
  631. $dayNames = [
  632. 1 => 'lun',
  633. 2 => 'mar',
  634. 3 => 'mer',
  635. 4 => 'gio',
  636. 5 => 'ven',
  637. 6 => 'sab',
  638. 7 => 'dom'
  639. ];
  640. $todayName = $dayNames[$today];
  641. // Get all member courses
  642. $allCourses = \App\Models\MemberCourse::with('course')->get();
  643. Log::info('All courses debug', [
  644. 'total_courses' => $allCourses->count(),
  645. 'today_name' => $todayName,
  646. 'courses' => $allCourses->map(function ($mc) {
  647. return [
  648. 'id' => $mc->id,
  649. 'status' => $mc->status,
  650. 'when' => $mc->when,
  651. 'course_name' => $mc->course->name ?? 'Unknown'
  652. ];
  653. })->toArray()
  654. ]);
  655. $this->dispatchBrowserEvent('debug-completed');
  656. }
  657. public function activateTestCourses()
  658. {
  659. try {
  660. $updated = \App\Models\MemberCourse::whereIn('id', [21, 22, 23, 24])
  661. ->update(['status' => 1]);
  662. Log::info('Activated test courses', ['updated_count' => $updated]);
  663. $this->loadCoursesData();
  664. $this->loadCoursesParticipation();
  665. $this->dispatchBrowserEvent('courses-activated', [
  666. 'message' => "Attivati $updated corsi per test"
  667. ]);
  668. } catch (\Exception $e) {
  669. Log::error('Error activating courses', ['error' => $e->getMessage()]);
  670. }
  671. }
  672. private function getLabels()
  673. {
  674. $labels = array();
  675. for ($i = 6; $i >= 0; $i--) {
  676. $labels[] = date("d/M", strtotime('-' . $i . ' days'));
  677. }
  678. return $labels;
  679. }
  680. private function getRecordData($type)
  681. {
  682. $data = [];
  683. for ($i = 6; $i >= 0; $i--) {
  684. $found = false;
  685. $records = $type == 'IN' ? $this->in : $this->out;
  686. foreach ($records as $record) {
  687. if (date("Y-m-d", strtotime($record->date)) == date("Y-m-d", strtotime('-' . $i . ' days'))) {
  688. $data[] = $record->total;
  689. $found = true;
  690. break;
  691. }
  692. }
  693. if (!$found) {
  694. $data[] = 0;
  695. }
  696. }
  697. return $data;
  698. }
  699. private function getMemberData()
  700. {
  701. $data = [];
  702. for ($i = 6; $i >= 0; $i--) {
  703. $found = false;
  704. foreach ($this->members as $member) {
  705. if (date("Y-m-d", strtotime($member->created_at)) == date("Y-m-d", strtotime('-' . $i . ' days'))) {
  706. $data[] = $member->total;
  707. $found = true;
  708. break;
  709. }
  710. }
  711. if (!$found) {
  712. $data[] = 0;
  713. }
  714. }
  715. return $data;
  716. }
  717. }