Explorar el Código

Reclamations import

Alexander Musikhin hace 3 semanas
padre
commit
4b6a7ee5d4

+ 31 - 1
app/Services/ImportBaseService.php

@@ -4,6 +4,7 @@ namespace App\Services;
 
 use App\Models\Import;
 use App\Models\Product;
+use Exception;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Str;
@@ -35,9 +36,13 @@ class ImportBaseService
         $cellIterator->setIterateOnlyExistingCells(FALSE);
         $row_content = [];
         $keys = array_values($this->headers);
+
         $i = 0;
         foreach ($cellIterator as $cell) {
-            $row_content[$keys[$i++]] = $cell->getValue();
+            if (isset($keys[$i])) {
+                $row_content[$keys[$i]] = $cell->getValue();
+            }
+            $i++;
         }
 
         return $row_content;
@@ -68,5 +73,30 @@ class ImportBaseService
         return $model?->id ?? '';
     }
 
+    protected function prepare(): bool
+    {
+        try {
+            $this->import->log('Reading file...');
+            $this->readFile();
+        } catch (Exception $exception){
+            $this->import->log($exception->getMessage(), 'ERROR');
+            $this->import->status = 'ERROR';
+            $this->import->save();
+            return false;
+        }
 
+        try {
+            $this->import->log('Checking headers...');
+            $headers = $this->rowToArray($this->rowIterator->current());
+            if (!$this->checkHeaders(array_values($headers))) {
+                throw new Exception("Invalid headers");
+            }
+        } catch (Exception $exception){
+            $this->import->log($exception->getMessage(), 'ERROR');
+            $this->import->status = 'ERROR';
+            $this->import->save();
+            return false;
+        }
+        return true;
+    }
 }

+ 1 - 21
app/Services/ImportOrdersService.php

@@ -58,29 +58,9 @@ class ImportOrdersService extends ImportBaseService
 
     public function handle(): bool
     {
-        try {
-            $this->import->log('Reading file...');
-            $this->readFile();
-        } catch (Exception $exception){
-            $this->import->log($exception->getMessage(), 'ERROR');
-            $this->import->status = 'ERROR';
-            $this->import->save();
+        if(!$this->prepare()) {
             return false;
         }
-
-        try {
-            $this->import->log('Checking headers...');
-            $headers = $this->rowToArray($this->rowIterator->current());
-            if (!$this->checkHeaders(array_values($headers))) {
-                throw new Exception("Invalid headers");
-            }
-        } catch (Exception $exception){
-            $this->import->log($exception->getMessage(), 'ERROR');
-            $this->import->status = 'ERROR';
-            $this->import->save();
-            return false;
-        }
-        $this->rowIterator->next();
         $strNumber = 0;
         $result = [
             'productsCreated' => 0,

+ 156 - 0
app/Services/ImportReclamationsService.php

@@ -2,13 +2,169 @@
 
 namespace App\Services;
 
+use App\Helpers\DateHelper;
 use App\Models\Import;
+use App\Models\Order;
+use App\Models\Product;
+use App\Models\ProductSKU;
+use App\Models\Reclamation;
+use Illuminate\Support\Str;
 
 class ImportReclamationsService extends ImportBaseService
 {
 
+    const HEADERS = [
+        'Округ'                         => 'districts.name',
+        'Район'                         => 'areas.name',
+        'Адрес'                         => 'orders.object_address',
+        'Артикул'                       => 'products.article',
+        'Тип'                           => 'products.nomenclature_number',
+        'RFID'                          => 'products_sku.rfid',
+        'Гарантии'                      => 'reclamations.guarantee',
+        'Что сделано'                   => 'reclamations.whats_done',
+        'Дата создания'                 => 'reclamations.create_date',
+        'Дата начала работ'             => 'reclamations.start_work_date',
+        'Дата завершения работ'         => 'reclamations.finish_date',
+        'Год поставки МАФ'              => 'orders.year',
+        'Причина'                       => 'reclamations.reason',
+        'Статус'                        => 'reclamation_statuses.name',
+        'Комментарий'                   => 'reclamations.comment',
+    ];
+
+
+    public function __construct(Import $import)
+    {
+        parent::__construct($import);
+        $this->headers = self::HEADERS;
+    }
+
     public function handle()
     {
+        if(!$this->prepare()) {
+            return false;
+        }
+        $strNumber = 0;
+        $result = [
+            'reclamationsCreated' => 0,
+            'mafAttached' => 0,
+        ];
+
+
+        foreach ($this->rowIterator as $row) {
+            $r = $this->rowToArray($row);
+            $strNumber++;
+            if(1 === $strNumber) {
+                echo $this->import->log('Skip headers Row: ' . $strNumber);
+                continue;
+            }
+
+            echo $this->import->log("Row $strNumber: " . $r['orders.object_address']);
+            $year = (int) $r['orders.year'];
+
+            // округ
+            if(!($districtId = $this->findId('districts.shortname', $r['districts.name'] ?? ''))) {
+                continue;
+            }
+
+            // район
+            if(!($areaId = $this->findId('areas.name', $r['areas.name']))) {
+                continue;
+            }
+
+            // manager
+            $userId = config('app.default_maf_order_user_id');
+
+            // status
+            if(!($statusId = $this->findId('reclamation_statuses.name', $r['reclamation_statuses.name']))) {
+                continue;
+            }
+
+            // order
+            $order = Order::query()
+                ->where('year', $year)
+                ->where('object_address', $r['orders.object_address'])
+                ->first();
+            if(!$order) {
+                echo $this->import->log('Order NOT FOUND: ' . $r['orders.object_address'], 'WARNING');
+                continue;
+            } else {
+                echo $this->import->log('Found order: ' . $order->object_address);
+            }
+
+            // product
+            $product = Product::query()
+                ->where('year', $year)
+                ->where('nomenclature_number', $r['products.nomenclature_number'])
+                ->first();
+            if(!$product) {
+                echo $this->import->log('Product not found: ' . $r['products.nomenclature_number'], 'WARNING');
+                continue;
+            }
+
+            $rfid = Str::replace(' ', '', $r['products_sku.rfid']);
+
+            // check maf with this nomenclature number in order
+            $productSKU = ProductSKU::query()
+                ->where('year', $year)
+                ->where('product_id', $product->id)
+                ->where('order_id', $order->id)
+                ->where('rfid', $rfid)
+                ->first();
+            if(!$productSKU) {
+                echo $this->import->log('SKU not found: ' . $r['products.nomenclature_number'], 'WARNING');
+                continue;
+            }
+
+            $createDate = ($r['reclamations.create_date']) ? DateHelper::excelDateToISODate($r['reclamations.create_date']) : null;
+            $finishDate = ($r['reclamations.finish_date']) ? DateHelper::excelDateToISODate($r['reclamations.finish_date']) : null;
+            $startWorkDate = ($r['reclamations.start_work_date']) ? DateHelper::excelDateToISODate($r['reclamations.start_work_date']) : null;
+
+            // reclamation
+            $reclamation = Reclamation::query()
+                ->where('order_id', $order->id)
+                ->where('status_id', $statusId)
+                ->where('create_date', $createDate)
+                ->where('finish_date', $finishDate)
+                ->where('start_work_date', $startWorkDate)
+                ->where('reason', $r['reclamations.reason'])
+                ->where('whats_done', $r['reclamations.whats_done'])
+                ->where('guarantee', $r['reclamations.guarantee'])
+                ->first();
+
+            if(!$reclamation) {
+                $reclamation = Reclamation::query()
+                    ->create([
+                        'order_id' => $order->id,
+                        'user_id' => $userId,
+                        'status_id' => $statusId,
+                        'create_date' => $createDate,
+                        'finish_date' => $finishDate,
+                        'reason' => $r['reclamations.reason'],
+                        'guarantee' => $r['reclamations.guarantee'],
+                        'whats_done' => $r['reclamations.whats_done'],
+                        'start_work_date' => $startWorkDate,
+                        'comment' => $r['reclamations.comment'],
+                    ]);
+                echo $this->import->log('Reclamation created: ' . $r['orders.object_address']);
+                $result['reclamationsCreated']++;
+            } else {
+                echo $this->import->log('Reclamation found: ' . $r['orders.object_address']);
+            }
+
+            if(!$reclamation->skus->contains($productSKU)) {
+                $reclamation->skus()->syncWithoutDetaching($productSKU->id);
+                echo $this->import->log('Attached MAF to reclamation, maf_id: ' . $productSKU->id);
+                $result['mafAttached']++;
+            } else {
+                echo $this->import->log('MAF already attached!');
+            }
+        }
+
+        echo $this->import->log(print_r($result, true));
+        $this->import->status = 'DONE';
+        $this->import->save();
+
+        return true;
 
     }