public function actionRemove($id) { if (Yii::$app->request->post()) { $cart = new \common\models\Cart(); $cart->remove($id); $this->redirect(array('cart')); } }
public function save() { //Yii::getLogger()->log('start save photobook:'.$this->id, YII_DEBUG); $cart = Cart::findOne(['id' => $this->id]); if (empty($cart)) { $cart = new Cart(); $cart->user_id = $this->user_id; $cart->title = $this->title; $cart->price = $this->price; $cart->quantity = $this->quantity; $cart->sub_total = $this->sub_total; $cart->product_type = $this->product_type; if (empty($this->product_info)) { $this->product_info = []; } $cart->product_info = json_encode($this->product_info); Yii::getLogger()->log('save:', YII_DEBUG); if ($cart->save()) { $this->id = $cart->id; return $cart; } else { Yii::getLogger()->log('save error', YII_DEBUG); } } else { $cart->user_id = $this->user_id; $cart->title = $this->title; $cart->price = $this->price; $cart->quantity = $this->quantity; $cart->sub_total = $this->sub_total; $cart->product_type = $this->product_type; if (empty($this->product_info)) { $this->product_info = []; } $cart->product_info = json_encode($this->product_info); Yii::getLogger()->log('update:', YII_DEBUG); if ($cart->update()) { return $cart; } else { Yii::getLogger()->log('update error:' . print_r($cart, true), YII_DEBUG); } } return null; }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Cart::find(); $query->orderBy(['created_at' => SORT_DESC]); $dataProvider = new ActiveDataProvider(['query' => $query]); if ($this->load($params) && !$this->validate()) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'user_id' => $this->user_id, 'product_id' => $this->product_id, 'number' => $this->number, 'market_price' => $this->market_price, 'price' => $this->price, 'type' => $this->type, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]); $query->andFilterWhere(['like', 'session_id', $this->session_id])->andFilterWhere(['like', 'sku', $this->sku])->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'thumb', $this->thumb]); return $dataProvider; }
/** * This method is called after the user is successfully logged in. * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event. * If you override this method, make sure you call the parent implementation * so that the event is triggered. * @param IdentityInterface $identity the user identity information * @param boolean $cookieBased whether the login is cookie-based * @param integer $duration number of seconds that the user can remain in logged-in status. * If 0, it means login till the user closes the browser or the session is manually destroyed. */ protected function afterLogin($identity, $cookieBased, $duration) { $carts = Cart::find()->where(['session_id' => $this->oldSessionId])->all(); foreach ($carts as $cart) { $exist = Cart::find()->where(['user_id' => $identity->id, 'product_id' => $cart->product_id])->one(); if ($exist) { Cart::updateAllCounters(['number' => $cart->number], ['user_id' => $identity->id]); Cart::deleteAll(['session_id' => $this->oldSessionId, 'product_id' => $cart->product_id]); } else { Cart::updateAll(['session_id' => Yii::$app->session->id, 'user_id' => $identity->id], ['session_id' => $this->oldSessionId, 'product_id' => $cart->product_id]); } } Cart::updateAll(['session_id' => Yii::$app->session->id], ['user_id' => $identity->id]); //Cart::updateAll(['session_id' => Yii::$app->session->id, 'user_id' => $identity->id], ['session_id' => $this->oldSessionId]); return parent::afterLogin($identity, $cookieBased, $duration); }
public function actionCheckout() { $user_id = 0; if (Yii::$app->user->isGuest) { return $this->redirect('/login'); } if (!Yii::$app->user->isGuest) { $user_id = Yii::$app->user->identity->id; } $cart_json = []; if (isset($_COOKIE["cart_{$user_id}"])) { $cart_json = Json::decode($_COOKIE["cart_{$user_id}"]); } elseif (isset($_COOKIE["cart_0"])) { $cart_json = Json::decode($_COOKIE["cart_0"]); } else { return $this->redirect('/shop'); Yii::$app->end(); } $ar_product_id = array_keys($cart_json); $cart_items = Product::find()->where(['in', 'id', $cart_json])->all(); if (isset($_POST) && !empty($_POST['place_order'])) { $grand_total = 0.0; $grand_total_purchase_price = 0.0; foreach ($cart_items as $ci) { $unit_price = floatval($ci->selling_price); $qty = intval($cart_json[$ci->id]['qty']); $row_total = $unit_price * $qty; $grand_total += $row_total; $unit_purchase_price = floatval($ci->purchase_price); $row_total_purchase_price = $unit_purchase_price * $qty; $grand_total_purchase_price += $row_total_purchase_price; } $order = new Order(); $order->bill_number = Custom::getUniqueId(0, 6); $order->member_id = $user_id; $order->total_amount = $grand_total; $order->total_payable = $grand_total; $order->payment_method = $_POST['payment_method']; $order->beforeSave(true); if ($order->validate() && $order->insert()) { $product = ''; foreach ($cart_items as $ci) { $unit_price = floatval($ci->selling_price); $qty = intval($cart_json[$ci->id]['qty']); $row_total = $unit_price * $qty; $product .= "{$ci->id},"; $cart = new Cart(); $cart->order_id = $order->id; $cart->product_id = $ci->id; $cart->unit_selling_price = $ci->selling_price; $cart->quantity_sold = $qty; $cart->subtotal_payable = $row_total; $cart->subtotal_paid = $row_total; $cart->beforeSave(true); $cart->insert(); } } $sale_amount = $grand_total - $grand_total_purchase_price; $app_root = \Yii::getAlias('@approot'); include "{$app_root}/affiliate/controller/record-sale.php"; $cookies = Yii::$app->response->cookies; if (isset($_COOKIE['cart_' . $user_id])) { $cookies->remove('cart_' . $user_id); unset($cookies['cart_' . $user_id]); } if (isset($_COOKIE['cart_0'])) { $cookies->remove('cart_0'); unset($cookies['cart_0']); } return $this->redirect(['/member/order', 'id' => $order->id]); } return $this->render('checkout', ['cart_items' => $cart_items, 'cookie_data' => $cart_json]); }
<div class="row"> <?php echo $this->render('/menu/_sidebar', ['modelGoodsCategories' => $modelGoodsCategories, 'modelBrends' => $modelBrends, 'modelBanner' => $modelBanner, 'PRICE_1' => $PRICE_1, 'PRICE_2' => $PRICE_2]); ?> <div class="col-sm-9 padding-right target-goods"> <div class="features_items" id="start_animation"><!--features_items--> <h2 class="title text-center">Товары</h2> <?php if ($modelNewGoods) { ?> <?php foreach ($modelNewGoods as $good) { ?> <?php $inCart = Cart::_isItemAlreadyInCart($good->id); ?> <div class="col-sm-4"> <div class="product-image-wrapper"> <div class="single-products img-<?php echo $good->id; ?> "> <div class="productinfo text-center"> <a href="/shop/detail?item=<?php echo $good->id; ?> "><img src="<?php echo $Module::getGoodImage($good->image);
/** * Finds the Cart model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Cart the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Cart::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
public function actionCartFormSubmit() { if (Yii::$app->request->isPost) { $model_form = new Order(); $model_form->load(Yii::$app->request->post()); $model_form->scenario = 'submit'; $model_form->payment_type = Yii::$app->request->post('payment') ? Yii::$app->request->post('payment') : 0; //$model_form->validate(); //vd( $model_form->getErrors()); $model_form->status = 1; } if ($model_form->load(Yii::$app->request->post()) && $model_form->validate()) { $model_form->save(); Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; Yii::$app->session->setFlash('success', 'Благодарим за покупку'); //Todo сохранить заказы !!! $iP = Yii::$app->session->id; $model = Cart::getAllByIp($iP); if ($model) { //vd($model_form->created_at); $listItemsInOrder = OrderItems::Add($model, $model_form->id, $model_form->created_at); //vd($listItemsInOrder); } //Todo отправка email !!! // Todo отправка ел почты //$model_Email = Email::find()->where(['id' => 1])->one(); // $currEmail = $model_Email->email; //vd($model->email); Yii::$app->mailer->compose(['html' => '@common/mail/order'], ['order_id' => $model_form->id, 'listItemsInOrder' => $listItemsInOrder])->setFrom('*****@*****.**')->setTo('*****@*****.**')->setSubject('нОвый заказ')->send(); //Todo Очистить корзину Cart::DeleteAllByIp($iP); $this->redirect('/site/index'); } else { // либо страница отображается первый раз, либо есть ошибка в данных $data = $this->getCommonDate(); $model_form = new Order(); $iP = Yii::$app->session->id; $model = Cart::getAllByIp($iP); } return $this->render('cart', ['data' => $data, 'model' => $model, 'model_form' => $model_form]); }
/** * @return \yii\db\ActiveQuery */ public function getCarts() { return $this->hasMany(Cart::className(), ['member_id' => 'member_id']); }
public function actionCheckout2() { $this->layout = 'layouts'; if (Yii::$app->user->isGuest) { $this->redirect(Url::toRoute(['photobooks/not-found'])); return; } $ref = Yii::$app->request->get('ref'); $id = Yii::$app->request->get('id'); $user_id = Yii::$app->user->identity->getId(); $user = User::findOne(['id' => Yii::$app->user->identity->getId()]); $course = CurrencyConvertor::getCurse($user->default_currency); $cart_rows = CartForm::getUserCart($user_id, true, $course); if (count($cart_rows) == 0) { Yii::$app->getSession()->setFlash('error', Yii::t('app', 'Корзина пуста. Вы не можите создать счет.')); $this->redirect(Url::toRoute(['photobooks/index'])); } $total = 0; //Считаем сумму foreach ($cart_rows as $key => $cart_row) { $total += $cart_row['sub_total']; } $invoice = new InvoiceForm(); $invoice->user_id = $user_id; $invoice->data = ['rows' => $cart_rows]; $invoice->currency = $user->default_currency; $invoice->payment_type = Invoice::TYPE_LIQPAY; $invoice->delivery_address = $user->delivery_address; $invoice->total = $total; $invoice->status = Invoice::STATUS_NEW; if (!$invoice->save()) { Yii::$app->getSession()->setFlash('error', Yii::t('app', 'Ну удалось записать в базу данных.')); $this->redirect(Url::toRoute(['photobooks/index'])); return; } //Имеем $invoice->id //Нужно его привязать к фотокнигам foreach ($cart_rows as $key => $cart_row) { $total += $cart_row['sub_total']; if ($cart_row['product_type'] == Cart::PRODUCT_PHOTOBOOK && !empty($cart_row['product_info']) && !empty($cart_row['product_info']['Photobook'])) { $pb_id = $cart_row['product_info']['Photobook']['id']; $photobook = new PhotobookForm(); if ($photobook->loadById($pb_id)) { $photobook->invoice_id = $invoice->id; $photobook->save(); } } } //Чистим корзину Cart::deleteAll(['user_id' => $user_id]); //Отправляем пользователя на счет $this->redirect(Url::toRoute(['photobooks/invoice', 'id' => $invoice->id])); //return $this->render('checkout', [ 'user_id'=>$user_id, 'cart_rows'=>$cart_rows, 'course'=>$course, 'default_currency'=>$user->default_currency]); }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use common\models\Cart; $cart = new Cart(); if ($_POST) { $cart->update($_POST); Yii::$app->controller->refresh(); } ?> <div class="container"> <div class="row" id="starts"> <div class="col-md-12 col-sm-12 col-xs-12 site-content"> <div class="col-md-12 col-sm-12 col-xs-12" style="border-bottom: solid 1px #FF9999; padding-bottom: 20px; margin-bottom: 30px;"> <?php echo Html::a('< Lanjutkan Belanja', ['site/product']); ?> </div> <div class="form"> <div class="row"> <?php $form = ActiveForm::begin(['id' => 'cart-form', 'options' => ['class' => 'form-horizontal']]); ?> <div class="col-md-8 col-sm-8 col-xs-12" style="padding: 0px 50px 0px;"> <table cellpadding="6" cellspacing="5" style="width:100%"> <tr> <th></th> <th></th> <th>Jumlah & Waktu Pengiriman</th> <th style="text-align:right">Sub-Total</th>
public function actionDeleteCartRow() { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; if (Yii::$app->user->isGuest) { return ['error' => ['msg' => Yii::t('app', 'Доступ закрыт')]]; } $cart_id = Yii::$app->request->get('id', 0); if ($cart_id <= 0) { return ['error' => ['msg' => Yii::t('app', 'Не верный id')]]; } $carForm = new CartForm(); if (!$carForm->loadById($cart_id)) { return ['error' => ['msg' => Yii::t('app', 'Запись не найдена')]]; } if (Yii::$app->user->identity->role != User::ROLE_ADMIN) { if ($carForm->user_id != Yii::$app->user->identity->getId()) { return ['error' => ['msg' => Yii::t('app', 'Ошибка прав доступа')]]; } } if ($carForm->product_type == Cart::PRODUCT_PHOTOBOOK && !empty($carForm->product_info) && !empty($carForm->product_info['Photobook'])) { $pb_id = $carForm->product_info['Photobook']['id']; $photobook = new PhotobookForm(); if ($photobook->loadById($pb_id)) { $photobook->setStatus(Photobook::STATUS_NEW); } } if (!Cart::deleteAll(['id' => $cart_id])) { return ['error' => ['msg' => Yii::t('app', 'Не удалось удалить строку')]]; } return ['response' => ['status' => true]]; }
public function actionAjaxAdd() { Yii::$app->response->format = Response::FORMAT_JSON; $productId = Yii::$app->request->post('productId'); $number = Yii::$app->request->post('number'); if ($productId && $number) { // 如果购物车已有,则更新,否则在购物车中增加 if ($cart = Cart::find()->where(['and', 'product_id=' . $productId, ['or', 'session_id="' . Yii::$app->session->id . '"', 'user_id=' . Yii::$app->user->isGuest ? 0 : Yii::$app->user->id]])->one()) { $product = Product::findOne($productId); if ($cart->number + $number <= $product->stock) { $cart->updateAllCounters(['number' => $number], ['and', 'product_id=' . $productId, ['or', 'session_id="' . Yii::$app->session->id . '"', 'user_id=' . Yii::$app->user->isGuest ? 0 : Yii::$app->user->id]]); return ['status' => 1, 'productId' => $productId, 'number' => $number]; } else { return ['status' => -2, 'productId' => $productId, 'number' => $number]; } } elseif ($model = Product::findOne($productId)) { if ($model->stock >= $number) { $cart = new Cart(); $cart->session_id = Yii::$app->session->id; $cart->user_id = Yii::$app->user->isGuest ? 0 : Yii::$app->user->id; $cart->product_id = $productId; $cart->number = $number; $cart->sku = $model->sku; $cart->name = $model->name; $cart->market_price = $model->market_price; $cart->price = $model->price; $cart->thumb = $model->thumb; $cart->type = $model->type; $cart->save(); return ['status' => 1, 'productId' => $productId, 'number' => $number]; } else { return ['status' => -2, 'productId' => $productId, 'number' => $number]; } } } return ['status' => -1, 'productId' => $productId, 'number' => $number]; }
/** * @return \yii\db\ActiveQuery */ public function getCarts() { return $this->hasMany(Cart::className(), ['product_id' => 'id']); }
public function actionGetGoodsByPriceRange() { $cur = Yii::$app->request->post('valute'); $data = Yii::$app->request->post('data'); $dataFrom = $data['0']; $dataTo = $data['1']; //vd($dataFrom.'|' . $dataTo); // $modelGoods = Goods::getGoodsByPriceRange($dataFrom ,$dataTo,$cur); $query = Goods::find()->where(['>', 'price', $dataFrom])->AndWhere(['<', 'price', $dataTo])->AndWhere(['status' => Goods::STATUS_ACTIVE]); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count(), 'defaultPageSize' => 2]); $modelsGoods = $query->offset($pages->offset)->limit(3)->all(); Yii::$app->response->format = Response::FORMAT_JSON; $iP = Yii::$app->session->id; $quantityInCart = Cart::getQountAllByIp($iP); $data = $this->getCommonDate(); $modelBest = Goods::getBest(3); return $this->renderAjax('products-ajax', ['modelsGoods' => $modelsGoods, 'pages' => $pages, 'modelBest' => $modelBest ? $modelBest : false]); }