浏览代码

move vars generation to jobs

Alexander Musikhin 2 年之前
父节点
当前提交
79063e4dab

+ 3 - 50
app/Http/Controllers/ExportController.php

@@ -13,62 +13,15 @@ class ExportController extends Controller
 {
     public function export_docx(Request $request){
         $ids = json_decode($request->ids,true);
-        $products = Product::query()->whereIn('id', $ids)->orderBy('series', 'asc')->get();
-
-        $vars_for_template = [];
-        $i = 1;
-        foreach ($products as $product){
-            switch ($request->descr) {
-                case 1:
-                    $descr = $product->characteristics . "\r\n" . $product->tech_description_short;
-                    break;
-                case 2:
-                    $descr = $product->characteristics . "\r\n" . $product->tech_description;
-                    break;
-                case 3:
-                    $descr = $product->tech_description_short;
-                    break;
-                case 4:
-                    $descr = $product->tech_description;
-                    break;
-                case 5:
-                default:
-                    $descr = $product->characteristics;
-                    break;
-            }
-
-            $vars_for_template = array_merge($vars_for_template, [
-                'series#' . $i        => $product->series,
-                'product_group#' .$i  => $product->product_group,
-                'num#' . $i           => $i,
-                'name#' . $i          => $product->name,
-                'name_for_form#' . $i          => $product->name_for_form,
-                'price#' . $i         => number_format($product->price, 2, '.', ' '),
-                'image#' . $i         => $product->image_path,
-                'description#' . $i   => str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $descr),
-
-            ]);
-
-            if($i < $products->count()) {
-                $vars_for_template['page_br#' . $i] = '<w:p><w:r><w:br w:type="page"/></w:r></w:p>';
-            } else {
-                $vars_for_template['page_br#' . $i] = '';
-            }
-            $i++;
-
-        }
-        //dd($vars_for_template);
-        // prepared vars - run job
-
 
         $filename = 'Наш_Двор_' . date('YmdHis') . '.docx';
+        $connection = (count($ids) > 200) ? 'database' : 'sync';
 
-        $connection = ($products->count() > 200) ? 'database' : 'sync';
         if(isset($request->separate_docs) && ($request->separate_docs == 'yes')){
-            GenerateSeparateDocxJob::dispatch($vars_for_template, $products->count(), $filename, $request->template)->onConnection($connection);
+            GenerateSeparateDocxJob::dispatch($ids, $request->descr, $filename, $request->template)->onConnection($connection);
             $filename = Str::replace('.docx', '.zip', $filename);
         } else {
-            GenerateDocxJob::dispatch($vars_for_template, count($products), $filename, $request->template)->onConnection($connection);
+            GenerateDocxJob::dispatch($ids, $request->descr, $filename, $request->template)->onConnection($connection);
         }
 
         Log::notice('Created export job. Execution time: ' . microtime(true) - LARAVEL_START);

+ 55 - 9
app/Jobs/GenerateDocxJob.php

@@ -2,6 +2,7 @@
 
 namespace App\Jobs;
 
+use App\Models\Product;
 use Illuminate\Bus\Queueable;
 use Illuminate\Contracts\Queue\ShouldBeUnique;
 use Illuminate\Contracts\Queue\ShouldQueue;
@@ -15,8 +16,8 @@ class GenerateDocxJob implements ShouldQueue
 {
     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
-    protected $vars;
-    protected $prod_count;
+    protected $ids;
+    protected $descr;
     protected $filename;
     protected $template;
     /**
@@ -24,10 +25,10 @@ class GenerateDocxJob implements ShouldQueue
      *
      * @return void
      */
-    public function __construct($vars, $count_products, $filename, $template)
+    public function __construct($ids, $descr, $filename, $template)
     {
-        $this->vars =$vars;
-        $this->prod_count = $count_products;
+        $this->ids =$ids;
+        $this->descr = $descr;
         $this->filename = $filename;
         $this->template = $template;
     }
@@ -39,14 +40,59 @@ class GenerateDocxJob implements ShouldQueue
      */
     public function handle()
     {
+        $products = Product::query()->whereIn('id', $this->ids)->orderBy('series', 'asc')->get();
         $tmpfile = public_path('exported/docx/' . $this->filename . '.txt');
+
+        $vars_for_template = [];
+        $i = 1;
+        foreach ($products as $product){
+            switch ($this->descr) {
+                case 1:
+                    $descr = $product->characteristics . "\r\n" . $product->tech_description_short;
+                    break;
+                case 2:
+                    $descr = $product->characteristics . "\r\n" . $product->tech_description;
+                    break;
+                case 3:
+                    $descr = $product->tech_description_short;
+                    break;
+                case 4:
+                    $descr = $product->tech_description;
+                    break;
+                case 5:
+                default:
+                    $descr = $product->characteristics;
+                    break;
+            }
+
+            $vars_for_template = array_merge($vars_for_template, [
+                'series#' . $i        => $product->series,
+                'product_group#' .$i  => $product->product_group,
+                'num#' . $i           => $i,
+                'name#' . $i          => $product->name,
+                'name_for_form#' . $i          => $product->name_for_form,
+                'price#' . $i         => number_format($product->price, 2, '.', ' '),
+                'image#' . $i         => $product->image_path,
+                'description#' . $i   => str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $descr),
+            ]);
+
+            // remove last page break
+            if($i < $products->count()) {
+                $vars_for_template['page_br#' . $i] = '<w:p><w:r><w:br w:type="page"/></w:r></w:p>';
+            } else {
+                $vars_for_template['page_br#' . $i] = '';
+            }
+            $i++;
+        }
+
+
         $my_template = new TemplateProcessor(storage_path('templates/' . $this->template));
-        $my_template->cloneBlock('product_block', $this->prod_count, true, true, $this->vars);
+        $my_template->cloneBlock('product_block', $products->count(), true, true, $vars_for_template);
 
         $i = 0;
-        $total = count($this->vars);
+        $total = count($vars_for_template);
 
-        foreach ($this->vars as $k => $v){
+        foreach ($vars_for_template as $k => $v){
             $file = public_path() . '/' . env('IMAGES_PATH') . '/' . $v;
             if(str_starts_with($k, 'image') && file_exists($file) && $v !== ''){
                 $my_template->setImageValue($k, ['path' => $file, 'width' => 270, 'height' => 180]);
@@ -56,7 +102,7 @@ class GenerateDocxJob implements ShouldQueue
 
             if(($i++ % 50) == 0) {
                 $f = fopen($tmpfile, 'w+');
-                $percent = round($i / ($total / 100), 0);
+                $percent = round(($i - 2) / ($total / 100), 0);
                 fwrite($f, $percent);
                 fclose($f);
             }

+ 58 - 21
app/Jobs/GenerateSeparateDocxJob.php

@@ -2,6 +2,7 @@
 
 namespace App\Jobs;
 
+use App\Models\Product;
 use Illuminate\Bus\Queueable;
 use Illuminate\Contracts\Queue\ShouldBeUnique;
 use Illuminate\Contracts\Queue\ShouldQueue;
@@ -16,8 +17,8 @@ class GenerateSeparateDocxJob implements ShouldQueue
 {
     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
-    protected $vars;
-    protected $products_count;
+    protected $ids;
+    protected $descr;
     protected $filename;
     protected $template;
 
@@ -26,10 +27,10 @@ class GenerateSeparateDocxJob implements ShouldQueue
      *
      * @return void
      */
-    public function __construct($vars, $products_count, $filename, $template)
+    public function __construct($ids, $descr, $filename, $template)
     {
-        $this->vars = $vars;
-        $this->products_count = $products_count;
+        $this->ids = $ids;
+        $this->descr = $descr;
         $this->filename = $filename;
         $this->template = $template;
     }
@@ -42,18 +43,46 @@ class GenerateSeparateDocxJob implements ShouldQueue
     public function handle()
     {
         $tmpfile = public_path('exported/docx/' . Str::replace('.docx', '.zip', $this->filename) . '.txt');
-
+        $products = Product::query()->whereIn('id', $this->ids)->orderBy('series', 'asc')->get();
+        $i = 1;
         $file_for_arch = [];
-        for ($i = 0; $i < $this->products_count; $i++) {
-            $my_template = new TemplateProcessor(storage_path('templates/' . $this->template));
-            $tmp_vars = [];
-            foreach ($this->vars as $k => $v) {
-                if (Str::endsWith($k, '#' . $i + 1)) {
-                    $tmp_vars[Str::replace('#' . $i + 1, '#1', $k)] = $v;
-                }
+
+        foreach ($products as $product){
+            switch ($this->descr) {
+                case 1:
+                    $descr = $product->characteristics . "\r\n" . $product->tech_description_short;
+                    break;
+                case 2:
+                    $descr = $product->characteristics . "\r\n" . $product->tech_description;
+                    break;
+                case 3:
+                    $descr = $product->tech_description_short;
+                    break;
+                case 4:
+                    $descr = $product->tech_description;
+                    break;
+                case 5:
+                default:
+                    $descr = $product->characteristics;
+                    break;
             }
-            $my_template->cloneBlock('product_block', 1, true, true, $tmp_vars);
-            foreach ($tmp_vars as $k => $v) {
+
+            $vars_for_template = [
+                'series#1'              => $product->series,
+                'article#1'             => $product->article,
+                'product_group#1'       => $product->product_group,
+                'num#1'                 => 1, // $i,
+                'name#1'                => $product->name,
+                'name_for_form#1'       => $product->name_for_form,
+                'price#1'               => number_format($product->price, 2, '.', ' '),
+                'image#1'               => $product->image_path,
+                'description#1'         => str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $descr),
+                'page_br#1' => ''
+            ];
+            $article = '';
+            $my_template = new TemplateProcessor(storage_path('templates/' . $this->template));
+            $my_template->cloneBlock('product_block', 1, true, true, $vars_for_template);
+            foreach ($vars_for_template as $k => $v) {
                 $file = public_path() . '/' . env('IMAGES_PATH') . '/' . $v;
                 if (str_starts_with($k, 'image') && file_exists($file) && $v !== '') {
                     $my_template->setImageValue($k, ['path' => $file, 'width' => 270, 'height' => 180]);
@@ -61,23 +90,31 @@ class GenerateSeparateDocxJob implements ShouldQueue
                     $my_template->setValue($k, 1);
                 } elseif (Str::startsWith($k, 'page_br')) {
                     $my_template->setValue($k, '');
+                } elseif(Str::startsWith($k, 'article')){
+                    $article = $v;
                 } else {
                     $my_template->setValue($k, $v);
                 }
             }
 
+            $filename = Str::replace('Наш_Двор_', 'Наш_Двор_' . $article . '_', $this->filename);
+            $filename = Str::replace('.docx', '_' . str_pad($i + 1, 4, 0, STR_PAD_LEFT) . '.docx', $filename);
+
+            $my_template->saveAs(public_path('exported/docx/') . $filename);
+            $file_for_arch[] = $filename;
+
             if (($i % 10) == 0) {
                 $f = fopen($tmpfile, 'w+');
-                $percent = round(($i - 2) / ($this->products_count / 100), 0);
+                $percent = round(($i - 2) / (count($this->ids) / 100), 0);
                 fwrite($f, $percent);
                 fclose($f);
             }
-
-            $filename = Str::replace('.docx', '_' . str_pad($i + 1, 4, 0, STR_PAD_LEFT) . '.docx', $this->filename);
-            $my_template->saveAs(public_path('exported/docx/') . $filename);
-            $file_for_arch[] = $filename;
+            $i++;
         }
 
+
+
+        // creating zip file
         $zip_file = public_path('exported/docx/') . Str::replace('.docx', '.zip', $this->filename);
         $zip = new \ZipArchive();
         $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
@@ -91,6 +128,6 @@ class GenerateSeparateDocxJob implements ShouldQueue
         }
         unlink($tmpfile);
 
-        Log::notice('Generation finished: ' . $i . ' / ' . $this->products_count . '  Execution time: ' . microtime(true) - LARAVEL_START);
+        Log::notice('Generation finished: ' . $i . ' / ' . count($this->ids) . '  Execution time: ' . microtime(true) - LARAVEL_START);
     }
 }

+ 4 - 4
resources/views/products/index.blade.php

@@ -3,7 +3,7 @@
 @section('content')
     <div class="container-fluid">
         <div class="row align-items-center">
-            <div class="col-xl-5 col-md-12">
+            <div class="col-xl-3 col-md-12">
                 <div class="mb-1">Всего найдено: {{ $products->total() }}</div>
                 Выбрано: <span id="count_selected">0</span>
                 <button class="btn btn-sm btn-primary mx-2 disabled" id="export-button" onclick="select_export()">Экспорт</button>
@@ -12,7 +12,7 @@
                         aria-expanded="false" aria-controls="searchForm"
                 >Фильтр</button>
             </div>
-            <div class="col-xl-7 col-md-12 collapse d-md-block" id="searchForm">
+            <div class="col-xl-9 col-md-12 collapse d-md-block" id="searchForm">
                 <form class="" action="" method="get">
                     <div class="row my-2 justify-content-center">
                         <div class="col-6 col-sm-6 col-md-auto">
@@ -54,8 +54,8 @@
                                 </option>
                             </select>
                         </div>
-                        <div class="col-12 col-md-auto  mt-md-0 text-center">
-                            <button id="sb" class="btn btn-sm btn-primary mt-4" type="submit">Поиск</button>
+                        <div class="col-12 col-md-auto  mt-md-1 text-center">
+                            <button id="sb" class="btn btn-sm btn-primary mt-4" type="submit">Применить</button>
                             <a href="{{ route('index') }}" class="btn btn-sm btn-light mt-4 ms-1">Сброс</a>
                         </div>
                     </div>

+ 4 - 1
resources/views/products/wait.blade.php

@@ -28,7 +28,10 @@
         </script>
     @else
         <script>
-            document.getElementById('link').click();
+            setTimeout(function () {
+                document.getElementById('link').click();
+            }, 1000);
+
             setTimeout(function () {
                 window.location = '/';
             }, 3000);