public function api_add($item_id, $count = 1, $options = '') { $item = Catalog::item($item_id); if (!$item) { return ['result' => 'error', 'code' => self::ERROR_ITEM_NOT_FOUND, 'error' => 'Item no found']; } if (!$this->order->id) { if (!$this->order->model->save()) { return ['result' => 'error', 'code' => self::ERROR_CREATE_ORDER, 'error' => 'Cannot create order. ' . $this->order->formatErrors()]; } Yii::$app->session->set(Order::SESSION_KEY, $this->order->model->access_token); } $good = Good::findOne(['order_id' => $this->order->id, 'item_id' => $item->primaryKey, 'options' => $options]); if ($good) { $good->count += $count; } else { $good = new Good(['order_id' => $this->order->id, 'item_id' => $item->primaryKey, 'count' => (int) $count, 'options' => $options, 'price' => $item->getPrice()]); } if ($good->save()) { $i = $item->getAttributes(); $i['title'] = $item->title; $i['price'] = $item->getPrice(); $response = ['result' => 'success', 'order' => $this->order, 'good' => $good, 'item' => $i]; return $response; } else { return ['result' => 'error', 'code' => self::ERROR_CREATE_GOOD, 'error' => $good->formatErrors()]; } }
public function api_add($item_id, $count = 1, $options = '', $increaseOnDuplicate = true) { $item = Item::findOne($item_id); if (!$item) { return ['result' => 'error', 'code' => self::ERROR_ITEM_NOT_FOUND, 'error' => 'Item no found']; } if (!$this->order->id) { if (!$this->order->model->save()) { return ['result' => 'error', 'code' => self::ERROR_CREATE_ORDER, 'error' => 'Cannot create order. ' . $this->order->formatErrors()]; } Yii::$app->session->set(Order::SESSION_KEY, $this->order->model->access_token); } $good = Good::findOne(['order_id' => $this->order->id, 'item_id' => $item->primaryKey, 'options' => $options]); if ($good && !$increaseOnDuplicate) { return ['result' => 'error', 'code' => self::ERROR_GOOD_DUPLICATE, 'error' => 'Dublicate good in order.']; } if ($good) { $good->count += $count; } else { $good = new Good(['order_id' => $this->order->id, 'item_id' => $item->primaryKey, 'count' => (int) $count, 'options' => $options, 'discount' => $item->discount, 'price' => $item->price]); } if ($good->save()) { $response = ['result' => 'success', 'order_id' => $this->order->id, 'good_id' => $good->primaryKey, 'item_id' => $item->primaryKey, 'options' => $good->options, 'discount' => $good->discount]; if ($response['discount']) { $response['price'] = round($good->price * (1 - $good->discount / 100)); $response['old_price'] = $good->price; } else { $response['price'] = $good->price; } return $response; } else { return ['result' => 'error', 'code' => self::ERROR_CREATE_GOOD, 'error' => $good->formatErrors()]; } }