AssociadoImportService.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\UserStatusEnum;
  4. use App\Enums\UserTypeEnum;
  5. use App\Imports\AssociadoImport;
  6. use App\Models\User;
  7. use Carbon\Carbon;
  8. use Illuminate\Support\Facades\Hash;
  9. use Illuminate\Support\Str;
  10. use Maatwebsite\Excel\Facades\Excel;
  11. class AssociadoImportService
  12. {
  13. public function syncFromExcel(string $filePath): array
  14. {
  15. $import = new AssociadoImport();
  16. Excel::import($import, $filePath);
  17. $rows = $import->rows ?? collect();
  18. $today = Carbon::today()->toDateString();
  19. $existing = User::where('type', UserTypeEnum::ASSOCIADO)
  20. ->whereNotNull('registration')
  21. ->get()
  22. ->keyBy('registration');
  23. $importedRegistrations = [];
  24. $seenRegistrations = [];
  25. $created = 0;
  26. $updated = 0;
  27. foreach ($rows as $row) {
  28. $registration = $row['registration'];
  29. $name = $row['name'];
  30. if (isset($seenRegistrations[$registration])) {
  31. continue;
  32. }
  33. $seenRegistrations[$registration] = true;
  34. $importedRegistrations[] = $registration;
  35. if ($existing->has($registration)) {
  36. $user = $existing->get($registration);
  37. $changed = false;
  38. if ($user->name !== $name) {
  39. $user->name = $name;
  40. $changed = true;
  41. }
  42. if ($user->status !== UserStatusEnum::ACTIVE) {
  43. $user->status = UserStatusEnum::ACTIVE;
  44. $user->excluded_at = null;
  45. $changed = true;
  46. }
  47. if ($changed) {
  48. $user->save();
  49. $updated++;
  50. }
  51. } else {
  52. $firstName = $this->extractFirstName($name);
  53. $email = "{$firstName}_{$registration}@serprati.com";
  54. $password = "{$firstName}2026";
  55. User::create([
  56. 'name' => $name,
  57. 'email' => $email,
  58. 'password' => Hash::make($password),
  59. 'type' => UserTypeEnum::ASSOCIADO,
  60. 'status' => UserStatusEnum::ACTIVE,
  61. 'registration' => $registration,
  62. 'admission_date' => $today,
  63. ]);
  64. $created++;
  65. }
  66. }
  67. $inactivated = User::where('type', UserTypeEnum::ASSOCIADO)
  68. ->where('status', UserStatusEnum::ACTIVE)
  69. ->whereNotNull('registration')
  70. ->whereNotIn('registration', $importedRegistrations)
  71. ->update([
  72. 'status' => UserStatusEnum::INACTIVE,
  73. 'excluded_at' => now(),
  74. ]);
  75. return [
  76. 'created' => $created,
  77. 'updated' => $updated,
  78. 'inactivated' => $inactivated,
  79. ];
  80. }
  81. private function extractFirstName(string $fullName): string
  82. {
  83. $firstName = explode(' ', trim($fullName))[0];
  84. return strtolower(Str::ascii($firstName));
  85. }
  86. }