| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?php
- namespace App\Services;
- use App\Enums\PartnerAgreementStatusEnum;
- use App\Imports\ParceirosImport;
- use App\Models\Category;
- use App\Models\PartnerAgreement;
- use App\Traits\ImportsPartners;
- use Illuminate\Http\UploadedFile;
- use Maatwebsite\Excel\Facades\Excel;
- class ParceirosImportService
- {
- use ImportsPartners;
- public function syncFromExcel(UploadedFile $file): array
- {
- $import = new ParceirosImport();
- Excel::import($import, $file);
- $rows = $import->rows ?? collect();
- $created = 0;
- $updated = 0;
- $importedPartnerIds = [];
- $processedCategoryIds = [];
- $currentCategoryId = null;
- foreach ($rows as $row) {
- $col0 = $this->cell($row[0] ?? '');
- $col1 = $this->cell($row[1] ?? '');
- $col2 = $this->cell($row[2] ?? '');
- if ($col0 === '' && $col1 === '' && $col2 === '') {
- continue;
- }
- $upper0 = mb_strtoupper($col0);
- if (str_contains($upper0, 'LISTA DE PARCEIROS')) {
- continue;
- }
- if ($upper0 === 'EMPRESA') {
- if ($col1 === '') {
- continue;
- }
- $category = $this->findOrCreateCategory($col1);
- $currentCategoryId = $category->id;
- $processedCategoryIds[$currentCategoryId] = true;
- continue;
- }
- if ($currentCategoryId === null || $col0 === '') {
- continue;
- }
- [$partner, $isNew] = $this->upsertPartner($col0, [
- 'description' => $col1 ?: null,
- 'phone' => $col2 ?: null,
- 'category_id' => $currentCategoryId,
- ]);
- $importedPartnerIds[] = $partner->id;
- $isNew ? $created++ : $updated++;
- }
- $inactivated = 0;
- if (!empty($processedCategoryIds) && !empty($importedPartnerIds)) {
- $inactivated = PartnerAgreement::whereIn('category_id', array_keys($processedCategoryIds))
- ->where('status', PartnerAgreementStatusEnum::ACTIVE)
- ->whereNotIn('id', $importedPartnerIds)
- ->update(['status' => PartnerAgreementStatusEnum::INACTIVE]);
- }
- return [
- 'created' => $created,
- 'updated' => $updated,
- 'inactivated' => $inactivated,
- ];
- }
- private function findOrCreateCategory(string $rawName): Category
- {
- $name = mb_convert_case(mb_strtolower($rawName), MB_CASE_TITLE, 'UTF-8');
- $category = Category::whereRaw(
- 'LOWER(TRIM(name)) = LOWER(TRIM(?)) AND type = ?',
- [$name, 'partner']
- )->first();
- return $category ?? Category::create([
- 'name' => $name,
- 'type' => 'partner',
- 'active' => true,
- ]);
- }
- }
|