From cfa0845a923ab6e28aac395c2ff37f8d9250b80e Mon Sep 17 00:00:00 2001 From: soufiane Date: Mon, 3 Apr 2023 17:34:36 +0200 Subject: [PATCH] wip #5834 @6:30 gestion des erreurs, envoie d'email --- .../Admin/ProductBaseController.php | 209 +++++++++++++----- app/Models/Product.php | 11 +- config/app.php | 3 +- 3 files changed, 162 insertions(+), 61 deletions(-) diff --git a/app/Http/Controllers/Admin/ProductBaseController.php b/app/Http/Controllers/Admin/ProductBaseController.php index 306304d..31c547c 100644 --- a/app/Http/Controllers/Admin/ProductBaseController.php +++ b/app/Http/Controllers/Admin/ProductBaseController.php @@ -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)
"; + $successMessage .= "$sizeSheets produit(s) chargé(s)
"; + + if($changes) { + $successMessage .= "$sizeChanges produit(s) modifié(s)
"; + } + + $contentMail["resume"] = $successMessage; + + if(!$changes) { + $successMessage = "Aucun nouveau changement."; + } + + if($errorsMessage) { + foreach ($errorsMessage as $message) { + $messages .= "

$message

"; + } + $messages .= "
"; + } + + $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"); + }); } } diff --git a/app/Models/Product.php b/app/Models/Product.php index 0040a97..3cd479b 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -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; diff --git a/config/app.php b/config/app.php index 894e01d..e699ea3 100644 --- a/config/app.php +++ b/config/app.php @@ -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, -- 2.39.5