Преглед изворни кода

Export to Wrod, check goods and remember when reload page (can select goods on many pages and export it)

Alexander Musikhin пре 2 година
родитељ
комит
25aa739ac6

+ 1 - 0
.gitignore

@@ -5,6 +5,7 @@
 /public/storage
 /storage/*.key
 /vendor
+~$*
 .env
 .env.backup
 .env.production

+ 4 - 63
README.md

@@ -1,66 +1,7 @@
-<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
+## Custom products catalog for stroyprofit.com
 
-<p align="center">
-<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
-<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
-<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
-<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
-</p>
+Installation:
+ - git clone...
+ - setup .env file: database and IMAGES_PATH - path to images of stroyprofit
 
-## About Laravel
 
-Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
-
-- [Simple, fast routing engine](https://laravel.com/docs/routing).
-- [Powerful dependency injection container](https://laravel.com/docs/container).
-- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
-- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
-- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
-- [Robust background job processing](https://laravel.com/docs/queues).
-- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
-
-Laravel is accessible, powerful, and provides tools required for large, robust applications.
-
-## Learning Laravel
-
-Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
-
-You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
-
-If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 2000 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
-
-## Laravel Sponsors
-
-We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
-
-### Premium Partners
-
-- **[Vehikl](https://vehikl.com/)**
-- **[Tighten Co.](https://tighten.co)**
-- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
-- **[64 Robots](https://64robots.com)**
-- **[Cubet Techno Labs](https://cubettech.com)**
-- **[Cyber-Duck](https://cyber-duck.co.uk)**
-- **[Many](https://www.many.co.uk)**
-- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
-- **[DevSquad](https://devsquad.com)**
-- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
-- **[OP.GG](https://op.gg)**
-- **[WebReinvent](https://webreinvent.com/?utm_source=laravel&utm_medium=github&utm_campaign=patreon-sponsors)**
-- **[Lendio](https://lendio.com)**
-
-## Contributing
-
-Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
-
-## Code of Conduct
-
-In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
-
-## Security Vulnerabilities
-
-If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
-
-## License
-
-The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

+ 65 - 0
app/Http/Controllers/ExportController.php

@@ -0,0 +1,65 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Models\Product;
+use Illuminate\Http\Request;
+
+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();
+
+        $my_template = new \PhpOffice\PhpWord\TemplateProcessor(storage_path('template_maf.docx'));
+
+        $vars_for_template = [];
+        $i = 1;
+        foreach ($products as $product){
+            $vars_for_template = array_merge($vars_for_template, [
+                'series#' . $i        => $product->series,
+                'num#' . $i           => $i,
+                'name#' . $i          => $product->name,
+                'price#' . $i         => number_format($product->price, 0, '', ' '),
+                'image#' . $i         => $product->image_path,
+                'description#' . $i   => str_replace("\n", '</w:t><w:br/><w:t xml:space="preserve">', $product->characteristics . "\r\n" . $product->tech_description),
+            ]);
+            $i++;
+        }
+
+//        dd($vars_for_template);
+        $my_template->cloneBlock('product_block', count($products), true, true, $vars_for_template);
+
+        foreach ($vars_for_template as $k => $v){
+            if(str_starts_with($k, 'image')){
+                $my_template->setImageValue($k, ['path' => public_path() . '/' . env('IMAGES_PATH') . '/' . $v,
+                        'width' => 270, 'height' => 180
+                ]);
+            } else {
+                $my_template->setValue($k, $v);
+            }
+
+            if(str_starts_with($k, 'series')) {
+//                $my_template->cloneRow($k, 5);
+            }
+
+
+        }
+
+
+//        dd($vars_for_template);
+
+
+
+        $file = 'Наш_Двор_' . date('YmdHis') . '.docx';
+        header("Content-Description: File Transfer");
+        header('Content-Disposition: attachment; filename="' . $file . '"');
+        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
+        header('Content-Transfer-Encoding: binary');
+        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+        header('Expires: 0');
+        ob_clean();
+        $my_template->saveAs("php://output");
+        exit();
+    }
+}

+ 8 - 0
app/Http/Controllers/ProductController.php

@@ -41,6 +41,8 @@ class ProductController extends Controller
             $query->where('price', '<=', $data['s_price_max']);
         }
 
+        $query->orderBy('series');
+
         $data['products'] = $query->paginate($data['perpage'] ?? 20)->withQueryString();
 
         // get all series for select field
@@ -149,4 +151,10 @@ class ProductController extends Controller
         return redirect()->route('view_product', $id);
     }
 
+    public function select_export(Request $request){
+        $data['ids'] = json_decode($request->ids, true);
+        $data['products'] = Product::query()->whereIn('id', $data['ids'])->get();
+        return view('products.select_export', $data);
+    }
+
 }

+ 70 - 3
resources/views/products/index.blade.php

@@ -6,6 +6,9 @@
             <div class="col-5">
                 <div class="">Всего найдено: {{ $products->total() }}</div>
                 {{ $products->links() }}
+                Выбрано: <span id="count_selected">0</span>
+                <button class="btn btn-sm btn-primary mx-3" onclick="select_export()">Экспорт</button>
+                <button class="btn btn-sm btn-primary" onclick="reset_selected()">Сбросить выбор</button>
             </div>
             <div class="col-7">
                 <form class="" action="" method="get">
@@ -63,9 +66,8 @@
                     <thead>
                     <tr class="align-middle">
                         <th class="text-center">Артикул, Серия<br>
-                            <label><input type="checkbox" onchange="toggle(this)">&nbsp;Все</label>
+                            <label><input type="checkbox" class="check_all" onchange="toggle(this)">&nbsp;Все</label>
                         </th>
-
                         <th>Группа <br> Наименование <br> Наименование под образец формы</th>
                         <th>Цена</th>
                         <th>Характеристики</th>
@@ -79,7 +81,7 @@
                         <tr class="align-middle prod-tr">
                             <td class="text-center">
                                 <label>
-                                    <input type="checkbox" class="form-check-inline me-0 prd-chk" name="ids" value="{{ $product->id }}"><br>
+                                    <input type="checkbox" onchange="select_product({{ $product->id }}, this)" class="form-check-inline me-0 prd-chk" name="ids" value="{{ $product->id }}"><br>
                                     {{ $product->article }}<br>
                                     {{ $product->series }}
                                 </label>
@@ -116,15 +118,80 @@
         </div>
     </div>
 
+    <form action="{{ route('select_export') }}" method="post" class="visually-hidden" id="select_export">
+        @csrf
+        <textarea name="ids" id="ids"></textarea>
+
+    </form>
 
     <script>
         function toggle(source) {
             let checkboxes = document.querySelectorAll('.prd-chk');
             for(let i =0; i < checkboxes.length; i++){
                 checkboxes[i].checked = source.checked;
+                select_product(checkboxes[i].value, source);
+            }
+            calc_selected();
+        }
+
+        function select_product(id, status){
+            let selected_products = JSON.parse(localStorage.getItem('selected_products'));
+            if(!selected_products) selected_products = [];
+
+            console.log(status.checked);
+
+            if(status.checked){
+                // console.log('select '+id);
+                if(!selected_products.includes(id)){
+                    selected_products.push(id);
+                }
+
+            } else {
+                // console.log('deselect '+id);
+                const index = selected_products.indexOf(id);
+                if(index > -1){
+                    selected_products.splice(index, 1);
+                }
+            }
+
+            localStorage.setItem('selected_products', JSON.stringify(selected_products));
+            calc_selected();
+        }
+
+        function calc_selected(){
+            let selected_products = JSON.parse(localStorage.getItem('selected_products'));
+            if(!selected_products) selected_products = [];
+            document.getElementById('count_selected').innerText = selected_products.length;
+
+            let checkboxes = document.querySelectorAll('.prd-chk');
+            for(let i =0; i < checkboxes.length; i++){
+
+                if(selected_products.includes(checkboxes[i].value)){
+                    checkboxes[i].checked = true;
+                }
+            }
+        }
+
+        function reset_selected(){
+            localStorage.setItem('selected_products', JSON.stringify([]));
+            let checkboxes = document.querySelectorAll('.prd-chk');
+            for(let i =0; i < checkboxes.length; i++) {
+                checkboxes[i].checked = false;
             }
+            document.querySelector('.check_all').checked = false;
+
+            calc_selected();
         }
 
+        function select_export(){
+            let selected_products = localStorage.getItem('selected_products')
+            //document.location = '{{ route('select_export') }}?ids='+selected_products;
+            document.getElementById('ids').value = selected_products;
+            document.getElementById('select_export').submit();
+        }
+
+        calc_selected();
+
 
 
 

+ 26 - 0
resources/views/products/select_export.blade.php

@@ -0,0 +1,26 @@
+@extends('layouts.app')
+
+
+@section('content')
+    <div class="container-fluid">
+        <div class="row">
+            <div class="col-12 text-center my-5">
+                Выбранные артикулы:
+                @foreach($products as $product)
+                    {{ $product->article }}
+                @endforeach
+            </div>
+            <div class="col-12 text-center">
+                <form method="post" action="{{ route('export_docx') }}">
+                    @csrf
+                    <input type="hidden" name="ids" value="{{ json_encode($ids) }}">
+                    <button type="submit" class="btn btn-primary">Экспорт в .docx</button>
+                </form>
+
+            </div>
+        </div>
+    </div>
+
+
+@endsection
+

+ 2 - 1
routes/web.php

@@ -22,5 +22,6 @@ Route::post('/upload_xls', [ProductController::class, 'upload_xls'])->name('uplo
 Route::post('/upload_image', [ProductController::class, 'upload_image'])->name('upload_image');
 Route::post('/save_product', [ProductController::class, 'save_product'])->name('save_product');
 Route::post('/update_image/{id}', [ProductController::class, 'update_image'])->name('update_image');
-
+Route::post('/select_export', [ProductController::class, 'select_export'])->name('select_export');
+Route::post('/export_docx', [\App\Http\Controllers\ExportController::class, 'export_docx'])->name('export_docx');
 

BIN
storage/template_maf.docx


+ 1 - 2
todo.txt

@@ -5,11 +5,10 @@
 + при редатировании товара можно загружать изображения
 + если несколько изображений найдено по артикулу - можно выбрать одно
 
++ выбор товаров с запоминаннием при переходах между страницами
 
 
 
-
-todo выбор товаров с запоминаннием при переходах между страницами
 todo формирование документа ворд из выбранных товаров
 todo Авторизация в системе без разделения ролей на базе «манагера»