ParceirosImportService.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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] = $this->upsertPartner($col0, [
  46. 'description' => $col1 ?: null,
  47. 'phone' => $col2 ?: null,
  48. 'category_id' => $currentCategoryId,
  49. ]);
  50. $importedPartnerIds[] = $partner->id;
  51. $isNew ? $created++ : $updated++;
  52. }
  53. $inactivated = 0;
  54. if (!empty($processedCategoryIds) && !empty($importedPartnerIds)) {
  55. $inactivated = PartnerAgreement::whereIn('category_id', array_keys($processedCategoryIds))
  56. ->where('status', PartnerAgreementStatusEnum::ACTIVE)
  57. ->whereNotIn('id', $importedPartnerIds)
  58. ->update(['status' => PartnerAgreementStatusEnum::INACTIVE]);
  59. }
  60. return [
  61. 'created' => $created,
  62. 'updated' => $updated,
  63. 'inactivated' => $inactivated,
  64. ];
  65. }
  66. private function findOrCreateCategory(string $rawName): Category
  67. {
  68. $name = mb_convert_case(mb_strtolower($rawName), MB_CASE_TITLE, 'UTF-8');
  69. $category = Category::whereRaw(
  70. 'LOWER(TRIM(name)) = LOWER(TRIM(?)) AND type = ?',
  71. [$name, 'partner']
  72. )->first();
  73. return $category ?? Category::create([
  74. 'name' => $name,
  75. 'type' => 'partner',
  76. 'active' => true,
  77. ]);
  78. }
  79. }