AssociadoImportService.php 3.0 KB

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