]> _ Git - pmi.git/commitdiff
wip #5834 @6:30 gestion des erreurs, envoie d'email
authorsoufiane <soufiane@cubedesigners.com>
Mon, 3 Apr 2023 15:34:36 +0000 (17:34 +0200)
committersoufiane <soufiane@cubedesigners.com>
Mon, 3 Apr 2023 15:34:36 +0000 (17:34 +0200)
app/Http/Controllers/Admin/ProductBaseController.php
app/Models/Product.php
config/app.php

index 306304d5a0548d9ae50a9efa41daf962aca6e9f5..31c547c1bdd0bcba75d5f31d92bed9e37d4467c3 100644 (file)
@@ -2,12 +2,15 @@
 namespace App\Http\Controllers\Admin;
 
 use App\Models\Product;
+use App\Models\Settings;
 use Cubist\Backpack\app\Magic\Controllers\CubistMagicController;
 use Cubist\Excel\ExcelToArray;
-use Cubist\Util\Json;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
-use PhpOffice\PhpSpreadsheet\IOFactory;
-use Illuminate\Support\Arr;
+use Illuminate\Support\Facades\Redirect;
+use League\Csv\Exception;
+use Prologue\Alerts\Facades\Alert;
+use Illuminate\Support\Facades\Mail;
 
 class ProductBaseController extends CubistMagicController {
 
@@ -27,16 +30,23 @@ class ProductBaseController extends CubistMagicController {
         if(!$fsXLSX)
             return false;
 
-        $sheets = array_map(function($n) { return ExcelToArray::excelToArrayRaw($n->getPathname()); }, $fsXLSX);
+        $sheets = array_map(function ($n) {
+                return [$n->getClientOriginalName() => ExcelToArray::excelToArrayRaw($n->getPathname())];
+            }, $fsXLSX);
+
         return $sheets;
     }
 
     public function parseExcelAndStore(Request $request) {
         $data = [];
         $specifications = [];
+        $changes = [];
         $optionId = -1;
         $index = 1;
         $excels = $this->getSheets($request);
+        $errorsMessage = [];
+        $contentMail = [];
+        $messages = "";
 
         $fields = [
             'category',
@@ -48,71 +58,168 @@ class ProductBaseController extends CubistMagicController {
         ];
 
         if($excels) {
-            //$excel = call_user_func_array('array_merge', $excel);
-
-            foreach ($excels as $excel) {
-                foreach ($excel as $sheet => $rows) {
-                    foreach ($rows as $row => $columns) {
-                        if ($row < 8) {
-                            foreach ($fields as $key => $field) {
-                                $c = $key += 2;
-                                $value = $rows[$c][$index];
-
-                                if (in_array($field, ["basic_selling_price", "basic_purschase_price", "conversion"])) {
-                                    $value = floatval($value);
-                                } elseif ($field === "currency") {
-                                    $value = substr($value, 0, 1);
-                                } elseif ($field === "discount") {
-                                    $value = floatval(str_replace("%", "", $value));
-                                }
 
-                                if (in_array($field, ["category", "currency"])) {
-                                    $value = trim($value);
+            $sizeFiles = sizeof($excels);
+            $sizeSheets = sizeof(call_user_func_array('array_merge', $excels));
+
+            // Parse product files
+            foreach ($excels as $key => $excel) {
+                $filename = key($excel);
+                // Parse product sheets
+                foreach ($excel[$filename] as $sheet => $rows) {
+                    try {
+                        $id = $rows[1][1];
+                    } catch(\Exception $e) {
+                        $errorsMessage[] = "L'Identifiant pour la fiche $sheet est manquant.";
+                        $contentMail["details"][$filename][$sheet] = "Identifiant manquant";
+                    }
+                    try {
+                        // Parse rows of sheet
+                        foreach ($rows as $row => $columns) {
+                            if ($row < 8) {
+                                foreach ($fields as $key => $field) {
+                                    // Ignore first and second row (SKU, ID)
+                                    // Begin at third
+                                    $c = $key += 2;
+                                    $value = $rows[$c][$index];
+
+                                    if (in_array($field, ["basic_selling_price", "basic_purschase_price", "conversion"])) {
+                                        $value = floatval($value);
+                                    } elseif ($field === "currency") {
+                                        $value = substr($value, 0, 1);
+                                    } elseif ($field === "discount") {
+                                        $value = floatval(str_replace("%", "", $value));
+                                    }
+
+                                    if (in_array($field, ["category", "currency"])) {
+                                        $value = trim($value);
+                                    }
+                                    $data[$id][$field] = $value;
+                                }
+                            } elseif ($row >= 9) {
+                                if ($columns[0] && $columns[0] !== " ") {
+                                    $optionId++;
+                                    $specifications[$id][$optionId] = [
+                                        "name_fr" => trim($columns[0]),
+                                        "name_en" => trim($columns[1] ?: $columns[0]),
+                                        "name_de" => trim($columns[2] ?: $columns[0])
+                                    ];
                                 }
 
-                                $data[$sheet][$field] = $value;
-                            }
-                        } elseif ($row >= 9) {
-                            if ($columns[0] && $columns[0] !== " ") {
-                                $optionId++;
-                                $specifications[$sheet][$optionId] = [
-                                    "name_fr" => trim($columns[0]),
-                                    "name_en" => trim($columns[1] ?: $columns[0]),
-                                    "name_de" => trim($columns[2] ?: $columns[0])
-                                ];
-                            }
-
-                            if ($specifications) {
-                                $specifications[$sheet][$optionId]["options"][] = [
-                                    "name_fr" => trim($columns[3]),
-                                    "name_en" => trim($columns[4] ?: $columns[3]),
-                                    "name_de" => trim($columns[5] ?: $columns[3]),
-                                    // To display "ref" in front, must to use html_entity_decode()
-                                    "ref" => trim($columns[6]),
-                                    "purchase_price" => floatval($columns[7]),
-                                    "sale_price" => floatval($columns[8])
-                                ];
+                                if ($specifications) {
+                                    $specifications[$id][$optionId]["options"][] = [
+                                        "name_fr" => trim($columns[3]),
+                                        "name_en" => trim($columns[4] ?: $columns[3]),
+                                        "name_de" => trim($columns[5] ?: $columns[3]),
+                                        "ref" => trim($columns[6]),
+                                        "purchase_price" => floatval($columns[7]),
+                                        "sale_price" => floatval($columns[8])
+                                    ];
+                                }
                             }
                         }
+                    } catch(\Exception $e) {
+                        $errorsMessage[] = "La feuille : $sheet, contient des erreurs";
+                        $contentMail["details"][$filename][$sheet] = "Format invalide";
                     }
                     $optionId = -1;
                 }
+
                 foreach ($specifications as $product => $specification) {
                     $data[$product]['json'] = json_encode($specification);
                 }
-                $this->storeOptions($request, $data);
+
+                $product = Product::find($id);
+                if($product) {
+                    $changes = $this->storeAndReturnChanges($data);
+
+                    // Remove empty array from the changes
+                    $changes = array_filter($changes);
+
+                    // Total changes
+                    $sizeChanges = sizeof($changes);
+
+                    $contentMail["details"][$filename][$sheet] = "OK";
+                    if(!$changes) {
+                        $contentMail["details"][$filename][$sheet] .= " (aucune modification)";
+                    }
+                }else {
+                    if($id) {
+                        $errorsMessage[] = "Aucun ID correspond pour le produit: $sheet";
+                        $contentMail["details"][$filename][$sheet] = "Identifiant inconnu";
+                    }
+                }
             }
+        }else{
+            $errorsMessage[] = "Erreur lors du téléchargement du fichier.";
+            $contentMail["details"] = "Fichier incorrect";
         }
 
+        $successMessage = "$sizeFiles fichier(s) chargé(s)</br>";
+        $successMessage .= "$sizeSheets produit(s) chargé(s)</br>";
+
+        if($changes) {
+            $successMessage .= "$sizeChanges produit(s) modifié(s)</br>";
+        }
+
+        $contentMail["resume"] = $successMessage;
+
+        if(!$changes) {
+            $successMessage = "Aucun nouveau changement.";
+        }
+
+        if($errorsMessage) {
+            foreach ($errorsMessage as $message) {
+                $messages .= "<p>$message</p>";
+            }
+            $messages .= "</br>";
+        }
+
+        $messages .= $successMessage;
+
+        $this->sendEmail($contentMail);
+
+        return $this->redirectToProductWithBag($messages);
     }
 
-    protected function storeOptions($request, $datas) {
-        $excel = $this->getSheets($request);
-        foreach ($datas as $SKU => $data) {
-            $product = Product::where('reference', $SKU);
+    protected function storeAndReturnChanges($datas) {
+        $changes = [];
+        foreach ($datas as $id => $data) {
+            $product = Product::find($id);
             if($product)
                 $product->update($data);
+                $product->save();
+                $changes[$id] = $product->wasChanged();
         }
-        return false;
+        return $changes;
+    }
+
+    private function redirectToProductWithBag($message, $type = "success"): RedirectResponse
+    {
+        if($type === "error") {
+            Alert::error($message)->flash();
+        } else {
+            Alert::success($message)->flash();
+        }
+        return Redirect::to($this->crud->getRoute() . 'product');
+    }
+
+    protected function sendEmail($datas) {
+        $contents = $datas['resume']. "\n";
+        $contents .= "Details : \r\n\n";
+        foreach ($datas['details'] as $filename => $values ) {
+            $contents .= $filename."\r\n";
+            foreach ($values as $product => $value) {
+                $contents .= "> $product : $value \r\n";
+            }
+        }
+
+        Mail::raw($contents, function ($message) {
+            $message->from(config('mail.from.address'), config('mail.from.name'));
+            $message->sender(config('mail.from.address'), config('mail.from.name'));
+            $message->to("soufiane@cubedesigners.com");
+            $message->bcc('test+pmi@cubedesigners.com');
+            $message->subject("Mise à jour");
+        });
     }
 }
index 0040a970bed68cd4bbd3bfa04710a05f4ce00d60..3cd479b0df773807c8c7791a7fa78a88ebae1d84 100644 (file)
@@ -19,6 +19,8 @@ class Product extends CubistMagicPageModel
     protected static $_specificationFields = null;
     protected static $_cart_data = null;
 
+    protected $hidden = ['updated_at'];
+
     /**
      * @var array
      */
@@ -310,15 +312,6 @@ class Product extends CubistMagicPageModel
         return $res;
     }
 
-    public function getDocumentOptions() {
-        $files = $this->getMediaInField('specifications_options');
-        $res = [];
-        foreach ($files as $key => $value) {
-            $res[] = $value;
-        }
-        return $res;
-    }
-
     public function hasProductImage()
     {
         return count($this->getMediaInField($this->images)) > 0;
index 894e01db275805525988fec1bd84d30ad511e9e8..e699ea32a57e1b3db3e0d0640b6d51ceae5a2236 100644 (file)
@@ -195,6 +195,7 @@ return [
         Illuminate\Translation\TranslationServiceProvider::class,
         Illuminate\Validation\ValidationServiceProvider::class,
         Illuminate\View\ViewServiceProvider::class,
+        'Prologue\Alerts\AlertsServiceProvider',
 
         /*
          * Package Service Providers...
@@ -222,7 +223,7 @@ return [
     */
 
     'aliases' => [
-
+        'Alert' => 'Prologue\Alerts\Facades\Alert',
         'App' => Illuminate\Support\Facades\App::class,
         'Artisan' => Illuminate\Support\Facades\Artisan::class,
         'Auth' => Illuminate\Support\Facades\Auth::class,