ImportsPartners.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace App\Traits;
  3. use App\Enums\PartnerAgreementStatusEnum;
  4. use App\Enums\UserStatusEnum;
  5. use App\Enums\UserTypeEnum;
  6. use App\Models\PartnerAgreement;
  7. use App\Models\User;
  8. use Illuminate\Support\Facades\Hash;
  9. use Illuminate\Support\Str;
  10. trait ImportsPartners
  11. {
  12. private function upsertPartner(string $companyName, array $data, string $type = 'partner'): array
  13. {
  14. $partner = PartnerAgreement::withTrashed()
  15. ->whereRaw('LOWER(TRIM(company_name)) = LOWER(TRIM(?))', [$companyName])
  16. ->first();
  17. if ($partner) {
  18. $wasModified = false;
  19. if ($partner->trashed()) {
  20. $partner->restore();
  21. $partner->services()->onlyTrashed()->restore();
  22. $partner->user?->update(['status' => UserStatusEnum::ACTIVE]);
  23. $wasModified = true;
  24. }
  25. $partner->fill(array_merge($data, [
  26. 'type' => $type,
  27. 'status' => PartnerAgreementStatusEnum::ACTIVE,
  28. ]));
  29. if ($partner->isDirty()) {
  30. $partner->save();
  31. $wasModified = true;
  32. }
  33. return [$partner, false, $wasModified];
  34. }
  35. $user = $this->findOrCreateUser($companyName);
  36. $partner = PartnerAgreement::create(array_merge($data, [
  37. 'company_name' => $companyName,
  38. 'user_id' => $user->id,
  39. 'type' => $type,
  40. 'status' => PartnerAgreementStatusEnum::ACTIVE,
  41. ]));
  42. return [$partner, true, true];
  43. }
  44. private function findOrCreateUser(string $companyName): User
  45. {
  46. $slug = Str::slug($companyName);
  47. $email = "{$slug}@serprati.com";
  48. $counter = 2;
  49. while (User::where('email', $email)->exists()) {
  50. $email = "{$slug}{$counter}@serprati.com";
  51. $counter++;
  52. }
  53. return User::create([
  54. 'name' => $companyName,
  55. 'email' => $email,
  56. 'password' => Hash::make('Serprati2026'),
  57. 'type' => UserTypeEnum::PARCEIRO,
  58. 'status' => UserStatusEnum::ACTIVE,
  59. ]);
  60. }
  61. private function parsePrice(?string $value): ?float
  62. {
  63. if (empty($value)) {
  64. return null;
  65. }
  66. $cleaned = preg_replace('/[^\d,]/', '', (string) $value);
  67. $cleaned = str_replace(',', '.', $cleaned);
  68. return is_numeric($cleaned) ? (float) $cleaned : null;
  69. }
  70. private function cell(mixed $value): string
  71. {
  72. return trim(preg_replace('/\s+/', ' ', (string) ($value ?? '')));
  73. }
  74. private function firstLine(mixed $value): string
  75. {
  76. return trim(explode("\n", (string) ($value ?? ''))[0]);
  77. }
  78. }