Exemplo n.º 1
0
 public function actionAddProducts()
 {
     if (isset($_POST['product_id'])) {
         $product = Products::findOne(['id' => (int) $_POST['product_id']]);
         // забираем продукт по id
         if (empty($product)) {
             // получили ли мы продукт
             die('error on finding product');
         }
         // $this->redirect('/products/shop'); //error
     }
     if (isset($_POST['quantity']) && $_POST['quantity'] > 0) {
         // проверка
         $quantity = $_POST['quantity'];
     } else {
         die('error with quantity');
     }
     // $this->redirect('/products/shop'); //error
     if (empty(Yii::$app->user->identity->id)) {
         die('error with user');
     }
     // $this->redirect('/products/shop'); //error
     $order = Orders::findOne(['user_id' => Yii::$app->user->identity->id, 'confirm' => 0]);
     //найти не подтвержденный заказ
     if (empty($order)) {
         $order = new Orders();
         $order->user_id = Yii::$app->user->identity->id;
         $order->status = 0;
         $order->confirm = 0;
         $order->price = 0;
         $save = $order->save();
         if ($save === false) {
             die('error on creating order');
         }
         //$this->redirect('/products/shop'); //error
     }
     $orderProducts = $order->getProducts();
     //получить список продуктов этого заказа
     $productIdList = [];
     //заносим в массив id
     foreach ($orderProducts as $orderProduct) {
         $productIdList[] = $orderProduct->id;
     }
     if (in_array($product->id, $productIdList)) {
         //если продукт в массиве то обновляем данные, иначе добавляем
         $add = $order->updateProducts($product->id, $quantity);
     } else {
         $add = $order->addProducts($product->id, $quantity);
     }
     if ($add === false) {
         die('error on adding products to order');
     }
     //$this->redirect('/products/shop'); //error
     $order->price = round($order->calculateGrandTotal());
     //считаем полную стоимость заказа
     if ($order->save()) {
         $this->redirect('cart');
     } else {
         die('error on saving order');
     }
     //$this->redirect('/products/shop'); //error
 }