Dashboard.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use Carbon\Carbon;
  5. use Illuminate\Support\Facades\Log;
  6. class Dashboard extends Component
  7. {
  8. // Existing properties
  9. public $totMembers = 0;
  10. public $totSuppliers = 0;
  11. public $totTodayIn = 0;
  12. public $totTodayOut = 0;
  13. public $dayName;
  14. public $in;
  15. public $out;
  16. public $members;
  17. // New properties for the enhanced dashboard
  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 $toReceive = 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 = []; // Array to store saved notes
  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->toReceive = \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. 'to_receive' => $this->toReceive,
  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', 2 => 'mar', 3 => 'mer', 4 => 'gio',
  271. 5 => 'ven', 6 => 'sab', 7 => 'dom'
  272. ];
  273. $todayName = $dayNames[$today];
  274. Log::info('Searching courses for today', [
  275. 'today_number' => $today,
  276. 'today_name' => $todayName
  277. ]);
  278. // Try with status = 0 first (inactive), then status = 1 (active) as fallback
  279. $activeCourses = \App\Models\MemberCourse::with(['course.level', 'course.frequency', 'member'])
  280. ->whereIn('status', [0, 1]) // Include both statuses
  281. ->whereRaw('JSON_EXTRACT(`when`, "$[*].day") LIKE ?', ['%"' . $todayName . '"%'])
  282. ->get();
  283. // Fallback: if JSON_EXTRACT doesn't work, get all and filter in PHP
  284. if ($activeCourses->isEmpty()) {
  285. Log::warning('JSON_EXTRACT query returned empty, trying PHP filtering');
  286. $allCourses = \App\Models\MemberCourse::with(['course.level', 'course.frequency', 'member'])
  287. ->whereIn('status', [0, 1])
  288. ->whereNotNull('when')
  289. ->get();
  290. $activeCourses = $allCourses->filter(function($memberCourse) use ($todayName) {
  291. try {
  292. $whenData = json_decode($memberCourse->when, true);
  293. if (is_array($whenData)) {
  294. foreach($whenData as $schedule) {
  295. if (isset($schedule['day']) && is_array($schedule['day']) && in_array($todayName, $schedule['day'])) {
  296. return true;
  297. }
  298. }
  299. }
  300. } catch (\Exception $e) {
  301. Log::debug('Error parsing when data', [
  302. 'member_course_id' => $memberCourse->id,
  303. 'when' => $memberCourse->when,
  304. 'error' => $e->getMessage()
  305. ]);
  306. }
  307. return false;
  308. });
  309. Log::info('PHP filtering results', [
  310. 'total_courses_checked' => $allCourses->count(),
  311. 'matching_courses' => $activeCourses->count()
  312. ]);
  313. }
  314. Log::info('Raw query for courses', [
  315. 'today_name' => $todayName,
  316. 'query_like' => '%"' . $todayName . '"%',
  317. 'total_member_courses' => \App\Models\MemberCourse::count()
  318. ]);
  319. // Debug: let's also try a direct query to see what we get
  320. $allMemberCourses = \App\Models\MemberCourse::with(['course.level', 'course.frequency'])
  321. ->limit(10)
  322. ->get();
  323. Log::info('Sample member courses from database', [
  324. 'sample_courses' => $allMemberCourses->map(function($mc) {
  325. return [
  326. 'id' => $mc->id,
  327. 'course_id' => $mc->course_id,
  328. 'course_name' => $mc->course->name ?? 'No name',
  329. 'level_name' => is_object($mc->course->level) ? $mc->course->level->name : 'No level',
  330. 'frequency_name' => is_object($mc->course->frequency) ? $mc->course->frequency->name : 'No frequency',
  331. 'status' => $mc->status,
  332. 'when' => $mc->when
  333. ];
  334. })->toArray()
  335. ]);
  336. Log::info('Active courses found', [
  337. 'count' => $activeCourses->count(),
  338. 'courses_ids' => $activeCourses->pluck('id')->toArray()
  339. ]);
  340. $this->courses = $activeCourses->map(function($memberCourse) use ($todayName) {
  341. $whenData = json_decode($memberCourse->when, true);
  342. Log::debug('Processing course when data', [
  343. 'member_course_id' => $memberCourse->id,
  344. 'when_data' => $whenData,
  345. 'looking_for_day' => $todayName
  346. ]);
  347. $todaySchedule = null;
  348. if (is_array($whenData)) {
  349. foreach($whenData as $schedule) {
  350. if (isset($schedule['day']) && is_array($schedule['day']) && in_array($todayName, $schedule['day'])) {
  351. $todaySchedule = $schedule;
  352. Log::debug('Found matching schedule', [
  353. 'schedule' => $schedule,
  354. 'member_course_id' => $memberCourse->id
  355. ]);
  356. break;
  357. }
  358. }
  359. }
  360. if ($todaySchedule) {
  361. $days = implode('-', array_map('ucfirst', $todaySchedule['day']));
  362. // Get course details
  363. $course = $memberCourse->course;
  364. $courseName = $course->name ?? 'Corso Sconosciuto';
  365. $levelName = is_object($course->level) ? $course->level->name : '';
  366. $frequencyName = is_object($course->frequency) ? $course->frequency->name : '';
  367. $typeName = $course->getFormattedTypeField() ?? '';
  368. // Build full course name similar to getCoursesForSelect
  369. $courseNameParts = [$courseName];
  370. if ($levelName) $courseNameParts[] = $levelName;
  371. if ($typeName) $courseNameParts[] = $typeName;
  372. if ($frequencyName) $courseNameParts[] = $frequencyName;
  373. $fullCourseName = implode(' - ', $courseNameParts);
  374. return [
  375. 'time' => $todaySchedule['from'] . ' - ' . $todaySchedule['to'],
  376. 'course_name' => $courseName,
  377. 'full_name' => $fullCourseName,
  378. 'level_name' => $levelName,
  379. 'type_name' => $typeName,
  380. 'frequency_name' => $frequencyName,
  381. 'days' => $days,
  382. 'type' => $course->type ?? 'Standard',
  383. 'from_time' => $todaySchedule['from'], // Add for sorting
  384. 'member_course_id' => $memberCourse->id
  385. ];
  386. } else {
  387. Log::debug('No matching schedule found for today', [
  388. 'member_course_id' => $memberCourse->id,
  389. 'when_data' => $whenData
  390. ]);
  391. }
  392. return null;
  393. })->filter()->values();
  394. // Sort by start time (from_time)
  395. $sortedCourses = $this->courses->sortBy('from_time')->values();
  396. // Log the sorted order before removing fields
  397. Log::info('Courses sorted by time', [
  398. 'sorted_courses' => $sortedCourses->map(function($course) {
  399. return [
  400. 'time' => $course['time'],
  401. 'from_time' => $course['from_time'],
  402. 'course_name' => $course['course_name'],
  403. 'member_course_id' => $course['member_course_id']
  404. ];
  405. })->toArray()
  406. ]);
  407. // Limit to 5 courses
  408. $this->courses = $sortedCourses->take(5);
  409. // Remove from_time field from final output and convert to array
  410. $this->courses = $this->courses->map(function($course) {
  411. unset($course['from_time'], $course['member_course_id']);
  412. return $course;
  413. })->toArray();
  414. $endTime = microtime(true);
  415. Log::info('Courses data loaded successfully', [
  416. 'final_courses_count' => count($this->courses),
  417. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2),
  418. 'final_courses_display' => $this->courses
  419. ]);
  420. } catch (\Exception $e) {
  421. Log::error('Error loading courses data', [
  422. 'error' => $e->getMessage(),
  423. 'file' => $e->getFile(),
  424. 'line' => $e->getLine()
  425. ]);
  426. $this->courses = [];
  427. }
  428. }
  429. private function loadCoursesParticipation()
  430. {
  431. Log::info('Loading courses participation');
  432. $startTime = microtime(true);
  433. try {
  434. // Conta le partecipazioni per corso (include tutti gli status)
  435. $courseStats = \App\Models\MemberCourse::with(['course.level', 'course.frequency'])
  436. ->whereIn('status', [0, 1]) // Include both statuses
  437. ->selectRaw('course_id, COUNT(*) as participants')
  438. ->groupBy('course_id')
  439. ->orderBy('participants', 'desc')
  440. ->limit(4)
  441. ->get();
  442. Log::info('Course participation stats', [
  443. 'courses_found' => $courseStats->count(),
  444. 'stats' => $courseStats->map(function($stat) {
  445. $course = $stat->course;
  446. $levelName = is_object($course->level) ? $course->level->name : '';
  447. $frequencyName = is_object($course->frequency) ? $course->frequency->name : '';
  448. return [
  449. 'course_id' => $stat->course_id,
  450. 'course_name' => $course->name ?? 'Unknown',
  451. 'level_name' => $levelName,
  452. 'frequency_name' => $frequencyName,
  453. 'participants' => $stat->participants
  454. ];
  455. })->toArray()
  456. ]);
  457. $totalParticipants = $courseStats->sum('participants');
  458. $this->coursesParticipation = $courseStats->map(function($stat) use ($totalParticipants) {
  459. $percentage = $totalParticipants > 0 ? ($stat->participants / $totalParticipants) * 100 : 0;
  460. $course = $stat->course;
  461. $courseName = $course->name ?? 'Corso Sconosciuto';
  462. $levelName = is_object($course->level) ? $course->level->name : '';
  463. $frequencyName = is_object($course->frequency) ? $course->frequency->name : '';
  464. $typeName = $course->getFormattedTypeField() ?? '';
  465. // Build display name with level and frequency
  466. $displayNameParts = [$courseName];
  467. if ($levelName) $displayNameParts[] = $levelName;
  468. if ($typeName) $displayNameParts[] = $typeName;
  469. if ($frequencyName) $displayNameParts[] = $frequencyName;
  470. $displayName = implode(' - ', $displayNameParts);
  471. // Assegna colori basati sul nome del corso
  472. $color = $this->getCourseColor($courseName);
  473. return [
  474. 'course_name' => $displayName,
  475. 'base_course_name' => $courseName,
  476. 'level_name' => $levelName,
  477. 'type_name' => $typeName,
  478. 'frequency_name' => $frequencyName,
  479. 'participants' => $stat->participants,
  480. 'percentage' => round($percentage, 1),
  481. 'color' => $color
  482. ];
  483. })->toArray();
  484. $endTime = microtime(true);
  485. Log::info('Courses participation loaded successfully', [
  486. 'total_participants' => $totalParticipants,
  487. 'participation_data' => $this->coursesParticipation,
  488. 'execution_time_ms' => round(($endTime - $startTime) * 1000, 2)
  489. ]);
  490. } catch (\Exception $e) {
  491. Log::error('Error loading courses participation', [
  492. 'error' => $e->getMessage(),
  493. 'file' => $e->getFile(),
  494. 'line' => $e->getLine()
  495. ]);
  496. $this->coursesParticipation = [];
  497. }
  498. }
  499. private function getCourseColor($courseName)
  500. {
  501. // Array of different colors for courses
  502. $colors = [
  503. 'padel', // #FFD700 - Gold
  504. 'tennis', // #8B4CF7 - Purple
  505. 'pallavolo', // #FF6B35 - Orange
  506. 'yoga', // #339E8E - Teal
  507. 'blue', // #0618BE - Blue
  508. 'pink', // #E91E63 - Pink
  509. 'green', // #4CAF50 - Green
  510. 'red', // #F44336 - Red
  511. 'indigo', // #3F51B5 - Indigo
  512. 'amber', // #FF9800 - Amber
  513. 'cyan', // #00BCD4 - Cyan
  514. 'lime' // #CDDC39 - Lime
  515. ];
  516. // Use course_id or course name hash to consistently assign colors
  517. // This ensures the same course always gets the same color
  518. $hash = crc32($courseName);
  519. $colorIndex = abs($hash) % count($colors);
  520. $assignedColor = $colors[$colorIndex];
  521. Log::debug('Course color assigned', [
  522. 'course_name' => $courseName,
  523. 'hash' => $hash,
  524. 'color_index' => $colorIndex,
  525. 'assigned_color' => $assignedColor
  526. ]);
  527. return $assignedColor;
  528. }
  529. private function loadSavedNotes()
  530. {
  531. Log::info('Loading saved notes');
  532. try {
  533. // Load saved notes from session or database
  534. $this->savedNotes = session()->get('dashboard_notes', []);
  535. Log::info('Saved notes loaded', [
  536. 'notes_count' => count($this->savedNotes)
  537. ]);
  538. } catch (\Exception $e) {
  539. Log::error('Error loading saved notes', [
  540. 'error' => $e->getMessage()
  541. ]);
  542. $this->savedNotes = [];
  543. }
  544. }
  545. private function saveSavedNotes()
  546. {
  547. try {
  548. // Save notes to session (you can change this to save to database)
  549. session()->put('dashboard_notes', $this->savedNotes);
  550. Log::info('Notes saved to session', [
  551. 'notes_count' => count($this->savedNotes)
  552. ]);
  553. } catch (\Exception $e) {
  554. Log::error('Error saving notes', [
  555. 'error' => $e->getMessage()
  556. ]);
  557. }
  558. }
  559. public function saveNote()
  560. {
  561. Log::info('Save note called', ['note_text' => $this->notes]);
  562. try {
  563. if (trim($this->notes) !== '') {
  564. $newNote = [
  565. 'id' => uniqid(),
  566. 'text' => trim($this->notes),
  567. 'created_at' => now()->format('d/m/Y H:i'),
  568. 'completed' => false
  569. ];
  570. // Add note to the beginning of the array
  571. array_unshift($this->savedNotes, $newNote);
  572. // Save to session/database
  573. $this->saveSavedNotes();
  574. // Clear the input
  575. $this->notes = '';
  576. // Emit event for success message
  577. $this->dispatchBrowserEvent('note-saved');
  578. Log::info('Note saved successfully', [
  579. 'note_id' => $newNote['id'],
  580. 'total_notes' => count($this->savedNotes)
  581. ]);
  582. } else {
  583. Log::warning('Attempted to save empty note');
  584. }
  585. } catch (\Exception $e) {
  586. Log::error('Error saving note', [
  587. 'error' => $e->getMessage(),
  588. 'file' => $e->getFile(),
  589. 'line' => $e->getLine()
  590. ]);
  591. }
  592. }
  593. public function completeNote($noteId)
  594. {
  595. Log::info('Complete note called', ['note_id' => $noteId]);
  596. try {
  597. $initialCount = count($this->savedNotes);
  598. // Find and remove the note from savedNotes
  599. $this->savedNotes = array_filter($this->savedNotes, function($note) use ($noteId) {
  600. return $note['id'] !== $noteId;
  601. });
  602. // Reindex the array
  603. $this->savedNotes = array_values($this->savedNotes);
  604. $finalCount = count($this->savedNotes);
  605. if ($initialCount > $finalCount) {
  606. // Save to session/database
  607. $this->saveSavedNotes();
  608. // Emit event for success message
  609. $this->dispatchBrowserEvent('note-completed');
  610. Log::info('Note completed successfully', [
  611. 'note_id' => $noteId,
  612. 'remaining_notes' => $finalCount
  613. ]);
  614. } else {
  615. Log::warning('Note not found for completion', ['note_id' => $noteId]);
  616. }
  617. } catch (\Exception $e) {
  618. Log::error('Error completing note', [
  619. 'note_id' => $noteId,
  620. 'error' => $e->getMessage(),
  621. 'file' => $e->getFile(),
  622. 'line' => $e->getLine()
  623. ]);
  624. }
  625. }
  626. // Existing methods with logging
  627. public function addMember()
  628. {
  629. Log::info('Redirecting to add member');
  630. return redirect()->to('/members?new=1');
  631. }
  632. public function addSupplier()
  633. {
  634. Log::info('Redirecting to add supplier');
  635. return redirect()->to('/suppliers?new=1');
  636. }
  637. public function addIn()
  638. {
  639. Log::info('Redirecting to add income record');
  640. return redirect()->to('/in?new=1');
  641. }
  642. public function addOut()
  643. {
  644. Log::info('Redirecting to add expense record');
  645. return redirect()->to('/out?new=1');
  646. }
  647. // Debug method - remove after testing
  648. public function debugCourses()
  649. {
  650. Log::info('=== DEBUG COURSES CALLED ===');
  651. $today = now()->format('N');
  652. $dayNames = [
  653. 1 => 'lun', 2 => 'mar', 3 => 'mer', 4 => 'gio',
  654. 5 => 'ven', 6 => 'sab', 7 => 'dom'
  655. ];
  656. $todayName = $dayNames[$today];
  657. // Get all member courses
  658. $allCourses = \App\Models\MemberCourse::with('course')->get();
  659. Log::info('All courses debug', [
  660. 'total_courses' => $allCourses->count(),
  661. 'today_name' => $todayName,
  662. 'courses' => $allCourses->map(function($mc) {
  663. return [
  664. 'id' => $mc->id,
  665. 'status' => $mc->status,
  666. 'when' => $mc->when,
  667. 'course_name' => $mc->course->name ?? 'Unknown'
  668. ];
  669. })->toArray()
  670. ]);
  671. $this->dispatchBrowserEvent('debug-completed');
  672. }
  673. // Temporary method to activate courses for testing
  674. public function activateTestCourses()
  675. {
  676. try {
  677. $updated = \App\Models\MemberCourse::whereIn('id', [21, 22, 23, 24])
  678. ->update(['status' => 1]);
  679. Log::info('Activated test courses', ['updated_count' => $updated]);
  680. // Reload the data
  681. $this->loadCoursesData();
  682. $this->loadCoursesParticipation();
  683. $this->dispatchBrowserEvent('courses-activated', [
  684. 'message' => "Attivati $updated corsi per test"
  685. ]);
  686. } catch (\Exception $e) {
  687. Log::error('Error activating courses', ['error' => $e->getMessage()]);
  688. }
  689. }
  690. // Existing methods (keeping original implementation)
  691. private function getLabels()
  692. {
  693. $labels = array();
  694. for($i = 6; $i >= 0; $i--) {
  695. $labels[] = date("d/M", strtotime('-' . $i . ' days'));
  696. }
  697. return $labels;
  698. }
  699. private function getRecordData($type)
  700. {
  701. $data = [];
  702. for($i = 6; $i >= 0; $i--) {
  703. $found = false;
  704. $records = $type == 'IN' ? $this->in : $this->out;
  705. foreach($records as $record) {
  706. if (date("Y-m-d", strtotime($record->date)) == date("Y-m-d", strtotime('-' . $i . ' days'))) {
  707. $data[] = $record->total;
  708. $found = true;
  709. break;
  710. }
  711. }
  712. if (!$found) {
  713. $data[] = 0;
  714. }
  715. }
  716. return $data;
  717. }
  718. private function getMemberData()
  719. {
  720. $data = [];
  721. for($i = 6; $i >= 0; $i--) {
  722. $found = false;
  723. foreach($this->members as $member) {
  724. if (date("Y-m-d", strtotime($member->created_at)) == date("Y-m-d", strtotime('-' . $i . ' days'))) {
  725. $data[] = $member->total;
  726. $found = true;
  727. break;
  728. }
  729. }
  730. if (!$found) {
  731. $data[] = 0;
  732. }
  733. }
  734. return $data;
  735. }
  736. }