]> _ Git - pmi.git/commitdiff
wip #5788 @7:00 affichage dynamique des tarifs selon le changement de remise,
authorsoufiane <soufiane@cubedesigners.com>
Thu, 8 Jun 2023 16:48:05 +0000 (18:48 +0200)
committersoufiane <soufiane@cubedesigners.com>
Thu, 8 Jun 2023 16:48:05 +0000 (18:48 +0200)
app/Http/Controllers/AjaxController.php
app/Models/Client.php
app/Models/CommandPanierSchema.php
app/Models/Product.php
resources/js/app.js
resources/js/components/CartItem.vue
resources/views/components/item-cart.blade.php

index fbd857846b864074a5088e4b23b1c33701a7616b..ed7eb055b14c481eaca81bc76981d028d072b7b1 100644 (file)
@@ -683,4 +683,27 @@ class AjaxController extends CubistFrontController
 
         return __('Votre commande a bien été validée !');
     }
+
+    public function getdiscount($request) {
+        /*$id = $request->id;
+
+        $product = Product::find($id);
+        $products = $request->session()->get('cart_items');
+        $discount = Client::discountArray($product->category);
+        $needs_update = true;
+
+        $cartItems_ = '';
+
+        if($products) {
+            $cartItems_ = array_map(function($value) use ($discount) {
+                $value['discount'] = $discount;
+                return $value;
+            }, $products);
+        }
+
+        $request->session()->flash('cart_items', $cartItems_);
+        $request->session()->put('cart_items', $cartItems_);
+
+        return ['needs_update' => $needs_update, 'cart_data' => $cartItems_];*/
+    }
 }
index 272da8879c1828f72d24cd340fcec8d67933b55b..804c10d20f267c37f7d367b9748c02b45941242c 100644 (file)
@@ -105,8 +105,9 @@ class Client extends CubistMagicAbstractModel
         return Auth::guard('web-clients')->user();
     }
 
-    public static function discountArray($categoryProduct) {
-        $categoryClient = self::getClientConnected()->discount ?? 'A';
+    public static function discountArray($categoryProduct, $categoryClient = false) {
+        if(!$categoryClient)
+            $categoryClient = self::getClientConnected()->discount ?? 'A';
         //dd(self::getClientConnected());
         $category_array = [
             'A' => 0,
index ad83292cf2683ebe7e3f3baa482bc17a349c2c07..a127cc7da8bf70a5836ec746697b8205bb4a3dda 100644 (file)
@@ -33,30 +33,45 @@ class CommandPanierSchema extends CubistMagicAbstractModel
 
     protected function getAllByUserId() {
         $userID = Client::getClientConnected()->id;
-        return self::all()->where('user_id', $userID)->toArray();
-    }
+        $items = self::all()->where('user_id', $userID)->toArray();
+        $allProducts = array_map(function($n){ return json_decode($n['products'], true); }, $items);
 
-    public static function fillData($currentCartRef, $data, $haveStatus = true) {
-        /**
-         *
-         */
-        $options = Product::getOptionsByProductsId($data['products']);
+        $categories = Product::getCategoriesByProductsId($allProducts);
+        $options = Product::getOptionsByProductsId($allProducts);
+        $categoryClient = Client::getClientConnected()->discount ?? 'A';
 
+        foreach ($allProducts as $key => $products){
+            $data['products'] = $products;
+            $currentCartRef = Panier::getRefs($data['products']);
+            $data = self::test($currentCartRef,$options,$categories,$categoryClient,$data);
+            dd($data);
+            $items[$key]['products'] = json_encode($data['products']);
+        }
+
+        return $items;
+    }
+
+    protected static function test($currentCartRef,$options,$categories,$categoryClient,$data = []){
         $opt = [];
         $total = [];
-
         foreach ($currentCartRef as $keyRefs => $refs) {
             foreach (explode("/", $refs) as $key => $ref) {
                 $key -= 1;
                 if ($key > -1) {
-                    $opt_ = array_filter($options[$keyRefs][$key]["options"], function ($n) use ($ref) {
+                    $optByProductId = array_column($options, $data['products'][$keyRefs]['id'])[0][0];
+                    $optByProductId = json_decode($optByProductId, true);
+                    $opt_ = array_filter($optByProductId[$keyRefs]["options"], function ($n) use ($ref) {
                         return $n["ref"] === $ref;
                     });
                     $opt_ = array_values($opt_);
-                    $opt[$refs][] = $opt_[0]["sale_price"];
+                    $opt[$refs][] = $opt_[0]["sale_price"] ?? 0;
                 }
             }
 
+            $cat = array_column($categories, $data['products'][$keyRefs]['id'])['category'] ?? 'A';
+            $discount = Client::discountArray($cat,$categoryClient);
+            $data['products'][$keyRefs]['discount'] = $discount;
+
             $quantity = intval($data['products'][$keyRefs]["quantity"]);
             $basicSellingPrice = $data['products'][$keyRefs]["basic_selling_price"];
 
@@ -68,7 +83,7 @@ class CommandPanierSchema extends CubistMagicAbstractModel
             $discount = floatval($data['products'][$keyRefs]["discount"]) ?? 0;
             $price = floatval($basicPriceByProductId + $totalOptionsPrice);
             $price = ($price - (($price * $discount) / 100));
-            $total[] = floatval($price * $quantity);
+            $total[] = str_replace(',','.',$price * $quantity);
             $data['products'][$keyRefs]["price"] = $price;
         }
 
@@ -80,10 +95,25 @@ class CommandPanierSchema extends CubistMagicAbstractModel
         $ht += ($ht > 1000) ? 20 : 0;
         $tva = $ht * 0.2;
         $ttc = $ht + $tva;
-        $data['total'] = !$checkUnavailableEcommerceProduct ? $ttc : null;
+        $data['total'] = !$checkUnavailableEcommerceProduct ? number_format($ttc,2) : null;
+
+        return $data;
+    }
+
+    public static function fillData($currentCartRef, $data, $haveStatus = true) {
+        /**
+         *
+         */
+        $categories = Product::getCategoriesByProductsId($data['products']);
+        $options = Product::getOptionsByProductsId($data['products']);
+        $categoryClient = Client::getClientConnected()->discount ?? 'A';
+
+        $data = self::test($currentCartRef, $options,$categories,$categoryClient,$data);
 
         //
-        $data['addresses'] = json_encode($data['addresses']);
+        if(isset($data['addresses']))
+            $data['addresses'] = json_encode($data['addresses']);
+
         $data['products'] = json_encode($data['products']);
 
         if($haveStatus)
index d3cac4956083ed96280acf1f11cd016628edccbd..e15fd0991ecf9fea6ad02a5e2e657690cb4d2c0c 100644 (file)
@@ -11,6 +11,7 @@ use Illuminate\Support\Facades\App;
 use Illuminate\Support\Str;
 use Spatie\Image\Manipulations;
 use Spatie\MediaLibrary\Models\Media;
+use Illuminate\Support\Arr;
 
 class Product extends CubistMagicPageModel
 {
@@ -501,23 +502,53 @@ class Product extends CubistMagicPageModel
         return self::$_cart_data;
     }
 
-    public function getOptions() {
-        return json_decode($this['json'], true);
-    }
-
     public static function getOptionsByProductsId($products) {
-        $options = Product::whereIn('id', array_column($products, 'id'))
-            ->select('id','json')
-            ->get()
-            ->groupBy('id')
-            ->map(function ($group) {
-                return $group->pluck('json')->toArray();
-            })
-            ->toArray();
-
-        return array_map(function($n) use($options) {
+        $options = collect($products)->map(function ($product) {
+            return collect($product)->map(function ($pro) {
+                return Product::where('id', $pro['id'])
+                    ->select('id', 'json')
+                    ->get()
+                    ->groupBy('id')
+                    ->map(function ($group) {
+                        return $group->pluck('json')->toArray();
+                    })
+                    ->toArray();
+            });
+        })->toArray();
+
+        $_arr = call_user_func_array('array_merge',$options);
+
+        return $_arr;
+
+        /*return array_map(function($n) {
+                $key = array_keys($n)[0];
+                return json_decode($n[$key][0], true);
+            }, $_arr
+        );*/
+
+        /*return array_map(function($n) use($options) {
             return json_decode($options[$n['id']][0],true);
             }, $products
+        );*/
+    }
+
+    public static function getCategoriesByProductsId($products) {
+        $cat = collect($products)->map(function ($product) {
+            return collect($product)->map(function ($pro) {
+                return Product::where('id', $pro['id'])
+                    ->select('id', 'category')
+                    ->get()
+                    ->groupBy('id')
+                    ->toArray();
+            });
+        })->toArray();
+
+        $_arr = call_user_func_array('array_merge',$cat);
+
+        return array_map(function($n) {
+                $key = array_keys($n)[0];
+                return $n[$key][0];
+            }, $_arr
         );
     }
 
index ad873287404c566d9e55dfa2e0291c03e40815c0..82f99a5639416967163faa8754b04781c3755622 100644 (file)
@@ -91,9 +91,18 @@ const app = new Vue({
         this.items = JSON.parse(this.$el.dataset.cartItems);
         this.tab = window.location.hash.replace('#','') || 'infos'
         this.getUser()
+
+        eventBus.$on('send-id', data => {
+            this.getDiscount(data)
+        })
+    },
+
+    created() {
+
     },
 
     mounted() {
+
         eventBus.$on('add-item', data => {
             data.action = 'add';
             data.ref = data.ref !== "" ? data.ref : this.ref;
@@ -497,8 +506,8 @@ const app = new Vue({
 
             axios.post('/ajax/storecart', data)
                 .then(function (response) {
-                    root.validateAction = true
-                    root.confirmMessageCart = response.data;
+                    //root.validateAction = true
+                    //root.confirmMessageCart = response.data;
                 })
                 .catch(function (error) {
                     console.log(error)
@@ -567,6 +576,20 @@ const app = new Vue({
                 })
                 .catch(function (error) {
                 })
+        },
+        getDiscount(id) {
+            let root = this
+
+            axios.post('/ajax/getdiscount', id)
+                .then(function (response) {
+                    if (response.data.needs_update) {
+                        root.items = response.data.cart_data;
+                    }
+                    console.log(root.items)
+                })
+                .catch(function (error) {
+                    }
+                )
         }
     },
     /**
index ec5b50b21408803f125b7ae1b45da19b66dcfc70..131d257b4099bd92cd9e716002c8429651ea8863 100644 (file)
             },
         },
 
+        mounted() {
+            console.log(this.item)
+            eventBus.$emit('send-id', {
+                id: this.item.id
+            });
+        },
+
         watch: {
             'item.quantity': function (newValue, oldValue) {
                 if (!this.sendevents) {
@@ -61,8 +68,9 @@
                     ref: this.item.ref,
                     price: this.price,
                     quantity: newValue,
-                });
-            }
+                }
+                );
+            },
         },
 
         computed: {
index a2910aa2fe1f772a7f75c6fd74473bbae8fc1d3a..804d786121f1318f78823c9ab2aa4868a4f60891 100644 (file)
@@ -30,7 +30,7 @@
                         <div>
                             <p class="no-m">{{ $product['ref'] }}</p>
                             <p class="no-m text-navy">{{ $product['name'] }}</p>
-                            @isset($product['discount'])
+                            @if(isset($product['discount']) && $product['discount'] !== 0)
                                 @if(floatval($product['basic_selling_price']))
                                     <p class="no-m">{{ __('Prix catalogue') }} : <span class="text-navy line-through">{{
                                         $product['basic_selling_price'] }} € HT</span>
@@ -47,7 +47,7 @@
                                         </p>
                                     @endif
                                 @endisset
-                            @endisset
+                            @endif
                             <p class="no-m">{{ __('Quantité') }} : <span class="text-navy">{{$product['quantity']}}</span></p>
                         </div>
                         <div class="product-price">