ParceirosImportService.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\PartnerAgreementStatusEnum;
  4. use App\Imports\ParceirosImport;
  5. use App\Models\Category;
  6. use App\Models\PartnerAgreement;
  7. use App\Traits\ImportsPartners;
  8. use Illuminate\Http\UploadedFile;
  9. use Maatwebsite\Excel\Facades\Excel;
  10. class ParceirosImportService
  11. {
  12. use ImportsPartners;
  13. public function syncFromExcel(UploadedFile $file): array
  14. {
  15. $import = new ParceirosImport();
  16. Excel::import($import, $file);
  17. $rows = $import->rows ?? collect();
  18. $created = 0;
  19. $updated = 0;
  20. $importedPartnerIds = [];
  21. $processedCategoryIds = [];
  22. $currentCategoryId = null;
  23. foreach ($rows as $row) {
  24. $col0 = $this->cell($row[0] ?? '');
  25. $col1 = $this->cell($row[1] ?? '');
  26. $col2 = $this->cell($row[2] ?? '');
  27. if ($col0 === '' && $col1 === '' && $col2 === '') {
  28. continue;
  29. }
  30. $upper0 = mb_strtoupper($col0);
  31. if (str_contains($upper0, 'LISTA DE PARCEIROS')) {
  32. continue;
  33. }
  34. if ($upper0 === 'EMPRESA') {
  35. if ($col1 === '') {
  36. continue;
  37. }
  38. $category = $this->findOrCreateCategory($col1);
  39. $currentCategoryId = $category->id;
  40. $processedCategoryIds[$currentCategoryId] = true;
  41. continue;
  42. }
  43. if ($currentCategoryId === null || $col0 === '') {
  44. continue;
  45. }
  46. [$partner, $isNew] = $this->upsertPartner($col0, [
  47. 'description' => $col1 ?: null,
  48. 'phone' => $col2 ?: null,
  49. 'category_id' => $currentCategoryId,
  50. ]);
  51. $importedPartnerIds[] = $partner->id;
  52. $isNew ? $created++ : $updated++;
  53. }
  54. $inactivated = 0;
  55. if (!empty($processedCategoryIds) && !empty($importedPartnerIds)) {
  56. $inactivated = PartnerAgreement::whereIn('category_id', array_keys($processedCategoryIds))
  57. ->where('status', PartnerAgreementStatusEnum::ACTIVE)
  58. ->whereNotIn('id', $importedPartnerIds)
  59. ->update(['status' => PartnerAgreementStatusEnum::INACTIVE]);
  60. }
  61. return [
  62. 'created' => $created,
  63. 'updated' => $updated,
  64. 'inactivated' => $inactivated,
  65. ];
  66. }
  67. private function findOrCreateCategory(string $rawName): Category
  68. {
  69. $name = mb_convert_case(mb_strtolower($rawName), MB_CASE_TITLE, 'UTF-8');
  70. $category = Category::whereRaw(
  71. 'LOWER(TRIM(name)) = LOWER(TRIM(?)) AND type = ?',
  72. [$name, 'partner']
  73. )->first();
  74. return $category ?? Category::create([
  75. 'name' => $name,
  76. 'type' => 'partner',
  77. 'active' => true,
  78. ]);
  79. }
  80. }