ParceirosImportService.php 3.0 KB

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