1. не приходит уведомления администратору при оформлении заказа
2. не подтягиваться геоданные при выборе города для и оформлении заказа клиентом
где в коде может быть ошибка
CartController.php
Код: Выделить всё
<?php
Yii::import('orders.models.*');
Yii::import('store.models.*');
/**
* Cart controller
* Display user cart and create new orders
*/
class CartController extends Controller
{
/**
* @var OrderCreateForm
*/
public $form;
/**
* @var bool
*/
protected $_errors = false;
public $main_render;
/**
* Display list of product added to cart
*/
public function actionIndex()
{
Yii::app()->cart->initErp();
// Recount
if (Yii::app()->request->isPostRequest && Yii::app()->request->getPost('recount') && !empty($_POST['quantities']))
$this->processRecount();
$this->form = new OrderCreateForm;
// Make order
if (Yii::app()->request->isPostRequest && Yii::app()->request->getPost('create')) {
if (isset($_POST['OrderCreateForm'])) {
$this->form->attributes = $_POST['OrderCreateForm'];
if ($this->form->validate()) {
$order = $this->createOrder();
Yii::app()->cart->clear();
$this->addFlashMessage(Yii::t('OrdersModule.core', 'Спасибо. Ваш заказ принят.'));
Yii::app()->request->redirect($this->createUrl('view', array('secret_key' => $order->secret_key)));
}
}
}
$deliveryMethods = StoreDeliveryMethod::model()
->applyTranslateCriteria()
->active()
->orderByName()
->findAll();
$session = new CHttpSession();
$items = Yii::app()->cart->getDataWithModels();
if(Yii::app()->request->isAjaxrequest && Yii::app()->request->getPost('key') == 'main-change') {
if (!empty($items)) {
foreach ($session['cart_data'] as $key => $value) {
if($_POST['uniq_id'] == $value['uniq_id']){
$_SESSION['cart_data'][$key]['size'] = $_POST['product-size'];
$_SESSION['cart_data'][$key]['quantity'] = $_POST['qty'];
$_SESSION['erp_data']['products'][$_POST['product_id']]['amount'] = $_POST['qty'];
}
}
}
}
// $totalPrice = Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice());
$totalPrice = StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice()));
$totalOrderPrice = StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice()));
$symbol = Yii::app()->currency->active->symbol;
if(Yii::app()->request->getPost('key') == 'success-order'){
$this->renderPartial('index', array(
'items' => Yii::app()->cart->getDataWithModels(),
'totalPrice' => $totalPrice,
'deliveryMethods' => $deliveryMethods,
), true, true);
}
if(Yii::app()->request->isAjaxrequest && Yii::app()->request->getPost('key') == 'main-change') {
Yii::app()->clientScript->scriptMap = array(
'jquery.js' => false,
'jquery.ui.js' => false,
'jquery.min.js' => false,
'jquery.yiiactiveform.js' => false,
'jquery.magnific-popup.min.js' => false,
);
echo CJSON::encode(array(
'main' => $this->renderPartial('index', array(
'items' => Yii::app()->cart->getDataWithModels(),
'totalPrice' => $totalPrice,
'deliveryMethods' => $deliveryMethods,
), true, true),
'small' => $this->actionRenderSmallCart(),
'orderPrice' => $totalPrice,
'symbol' => $symbol,
));
} else {
$this->render('index', array(
'items' => Yii::app()->cart->getDataWithModels(),
'totalPrice' => Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice()),
'deliveryMethods' => $deliveryMethods,
'orderPrice' => $totalPrice,
'symbol' => $symbol,
));
}
}
/**
* Find order by secret_key and display.
* @throws CHttpException
*/
public function actionView()
{
$secret_key = Yii::app()->request->getParam('secret_key');
$model = Order::model()->find('secret_key=:secret_key', array(':secret_key' => $secret_key));
if (!$model)
throw new CHttpException(404, Yii::t('OrdersModule.core', 'Ошибка. Заказ не найден.'));
$this->render('view', array(
'model' => $model,
));
}
/**
* Validate POST data and add product to cart
*/
public function actionAdd()
{
$variants = array();
// Load product model
$model = StoreProduct::model()
->active()
->findByPk(Yii::app()->request->getPost('product_id', 0));
// Check product
if (!isset($model))
$this->_addError(Yii::t('OrdersModule.core', 'Ошибка. Продукт не найден'), true);
// Update counter
$model->saveCounters(array('added_to_cart_count' => 1));
// Process variants
if (!empty($_POST['eav'])) {
foreach ($_POST['eav'] as $attribute_id => $variant_id) {
if (!empty($variant_id)) {
// Check if attribute/option exists
if (!$this->_checkVariantExists($_POST['product_id'], $attribute_id, $variant_id))
$this->_addError(Yii::t('OrdersModule.core', 'Ошибка. Вариант продукта не найден.'));
else
array_push($variants, $variant_id);
}
}
}
// Process configurable products
if ($model->use_configurations) {
// Get last configurable item
$configurable_id = Yii::app()->request->getPost('configurable_id', 0);
if (!$configurable_id || !in_array($configurable_id, $model->configurations))
$this->_addError(Yii::t('OrdersModule.core', 'Ошибка. Выберите вариант продукта.'), true);
} else
$configurable_id = 0;
$size = isset($_POST['product-size'])?$_POST['product-size']:'';
Yii::app()->cart->add(array(
'product_id' => $model->id,
'variants' => $variants,
'configurable_id' => $configurable_id,
'quantity' => (int)Yii::app()->request->getPost('quantity', 1),
'price' => $model->price,
'size' => $size,//isset($_POST['product-size'])?$_POST['product-size']:'',
'uniq_id' => $model->id.$size,
));
$this->_finish();
}
/**
* Remove product from cart and redirect
*/
public function actionRemove($index)
{
Yii::app()->cart->remove($index);
Yii::app()->request->redirect($this->createUrl('index'));
}
public function actionItemRemove($index)
{
Yii::app()->cart->removeItem($index);
$totalPrice = StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice()));
$symbol = Yii::app()->currency->active->symbol;
$counter = Yii::app()->cart->countItems();
if (!Yii::app()->request->isAjaxRequest)
Yii::app()->request->redirect($this->createUrl('index'));
else
echo (CJSON::encode(array('price' => $totalPrice, 'symbol' => $symbol, 'count' => $counter)));
print_r(Yii::app()->cart->removeItem($index));
//Yii::app()->request->redirect($this->createUrl('renderSmallCart')); //AjaxSmallCArt
// echo $this->actionRenderSmallCart();
}
/**
* Clear cart
*/
public function actionClear()
{
Yii::app()->cart->clear();
if (!Yii::app()->request->isAjaxRequest)
Yii::app()->request->redirect($this->createUrl('index'));
}
/**
* Render data to display in theme header.
*/
public function actionRenderSmallCart()
{
$session = new CHttpSession();
if(Yii::app()->request->isAjaxRequest){
Yii::app()->clientScript->scriptMap = array(
'jquery.js' => false,
'jquery.ui.js' => false,
'jquery.min.js' => false,
'jquery.yiiactiveform.js' => false,
'jquery.magnific-popup.min.js' => false,
// 'jquery.mCustomScrollbar.concat.min.js' => false,
);
}
if(Yii::app()->request->isAjaxRequest && Yii::app()->request->getPost('key') == 'small-change') {
$items = Yii::app()->cart->getDataWithModels();
if (!empty($items)) {
foreach ($session['cart_data'] as $key => $value) {
if($_POST['uniq_id'] == $value['uniq_id']){
$_SESSION['cart_data'][$key]['size'] = $_POST['s_product-size'];
$_SESSION['cart_data'][$key]['quantity'] = $_POST['s_qty'];
$_SESSION['erp_data']['products'][$_POST['product_id']]['amount'] = $_POST['s_qty'];
}
}
}
$totalPrice = StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice()));
$symbol = Yii::app()->currency->active->symbol;
echo CJSON::encode(array(
'cart' => $this->renderPartial('_small_cart_v2', false, true, true),
'price' => $totalPrice,
'symbol' => $symbol,
));
} else {
return $this->renderPartial('_small_cart_v2', false, true, true); //(_small_cart)
}
}
/**
* Render data to display in theme header.
*/
public function actionRenderAjaxSmallCart()
{
$this->renderPartial('_ajax_small_cart_v2'); //(_small_cart)
}
/**
* Create new order
* @return Order
*/
public function createOrder()
{
if (Yii::app()->cart->countItems() == 0)
return false;
$order = new Order;
// Set main data
$order->user_id = Yii::app()->user->isGuest ? null : Yii::app()->user->id;
$order->user_name = $this->form->name;
$order->user_email = $this->form->email;
$order->user_phone = $this->form->phone;
$order->user_address = $this->form->address;
$order->user_comment = $this->form->comment;
$order->delivery_id = $this->form->delivery_id;
if ($order->validate())
$order->save();
else
throw new CHttpException(503, Yii::t('OrdersModule.core', 'Ошибка создания заказа'));
// Process products
foreach (Yii::app()->cart->getDataWithModels() as $item) {
$ordered_product = new OrderProduct;
$ordered_product->order_id = $order->id;
$ordered_product->product_id = $item['model']->id;
$ordered_product->configurable_id = $item['configurable_id'];
$ordered_product->name = $item['model']->name;
$ordered_product->quantity = $item['quantity'];
$ordered_product->sku = $item['model']->sku;
$ordered_product->price = StoreProduct::calculatePrices($item['model'], $item['variant_models'], $item['configurable_id']);
// Process configurable product
if (isset($item['configurable_model']) && $item['configurable_model'] instanceof StoreProduct) {
$configurable_data = array();
$ordered_product->configurable_name = $item['configurable_model']->name;
// Use configurable product sku
$ordered_product->sku = $item['configurable_model']->sku;
// Save configurable data
$attributeModels = StoreAttribute::model()->findAllByPk($item['model']->configurable_attributes);
foreach ($attributeModels as $attribute) {
$method = 'eav_' . $attribute->name;
$configurable_data[$attribute->title] = $item['configurable_model']->$method;
}
$ordered_product->configurable_data = serialize($configurable_data);
}
// Save selected variants as key/value array
if (!empty($item['variant_models'])) {
$variants = array();
foreach ($item['variant_models'] as $variant)
$variants[$variant->attribute->title] = $variant->option->value;
$ordered_product->variants = serialize($variants);
}
$ordered_product->save();
}
// Reload order data.
$order->refresh();
// All products added. Update delivery price.
$order->updateDeliveryPrice();
// Send email to user.
$this->sendEmail($order);
return $order;
}
/**
* Check if product variantion exists
* @param $product_id
* @param $attribute_id
* @param $variant_id
* @return string
*/
protected function _checkVariantExists($product_id, $attribute_id, $variant_id)
{
return StoreProductVariant::model()->countByAttributes(array(
'id' => $variant_id,
'product_id' => $product_id,
'attribute_id' => $attribute_id
));
}
/**
* Recount product quantity and redirect
*/
public function processRecount()
{
Yii::app()->cart->recount(Yii::app()->request->getPost('quantities'));
if (!Yii::app()->request->isAjaxRequest)
Yii::app()->request->redirect($this->createUrl('index'));
}
/**
* Add message to errors array.
* @param string $message
* @param bool $fatal finish request
*/
protected function _addError($message, $fatal = false)
{
if ($this->_errors === false)
$this->_errors = array();
array_push($this->_errors, $message);
if ($fatal === true)
$this->_finish();
}
/**
* Process result and exit!
*/
protected function _finish()
{
if(Yii::app()->request->isAjaxRequest){
Yii::app()->clientScript->scriptMap = array(
// В карте отключаем загрузку core-скриптов, УЖЕ подключенных до ajax загрузки
'jquery.js' => false,
'jquery.ui.js' => false,
'jquery.min.js' => false,
'jquery.yiiactiveform.js' => false,
'jquery.magnific-popup.min.js' => false,
);
}
$view = $this->renderPartial('_small_cart_v2', false, true, true);
$totalPrice = StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice()));
$symbol = Yii::app()->currency->active->symbol;
echo CJSON::encode(array(
'errors' => $this->_errors,
'message' => Yii::t('OrdersModule.core', 'Продукт успешно добавлен в {cart}', array(
'{cart}' => CHtml::link(Yii::t('OrdersModule', 'корзину'), array('/orders/cart/index'))
)),
'view' => $view,
'price' => $totalPrice,
'symbol' => $symbol,
));
//exit; //tried to fix jquery
}
/**
* Sends email to user after create new order.
*/
private function sendEmail(Order $order)
{
$theme = Yii::t('OrdersModule', 'Ваш заказ #') . $order->id;
$lang = Yii::app()->language;
$emailBodyFile = Yii::getPathOfAlias("application.emails.$lang") . DIRECTORY_SEPARATOR . 'new_order.php';
// If template file does not exists use default russian translation
if (!file_exists($emailBodyFile))
$emailBodyFile = Yii::getPathOfAlias("application.emails.ru") . DIRECTORY_SEPARATOR . 'new_order.php';
$body = $this->renderFile($emailBodyFile, array('order' => $order), true);
/**
* @var EMailer $mailer
*/
$mailer = Yii::app()->mail;
$mailer->From = Yii::app()->params['adminEmail'];
$mailer->FromName = Yii::app()->settings->get('core', 'siteName');
$mailer->Subject = $theme;
$mailer->Body = $body;
$mailer->AddAddress($order->user_email);
$mailer->AddAddress('chmichael89@gmail.com');
$mailer->AddReplyTo(Yii::app()->params['adminEmail']);
$mailer->isHtml(true);
$mailer->Send();
$mailer->ClearAddresses();
}
public function actionItemPlus($index)
{
Yii::app()->cart->itemPlus($index);
$item = Yii::app()->cart->getDataWithModels();
$item = $item[$index];
$price = StoreProduct::calculatePrices($item['model'], $item['variant_models'], $item['configurable_id']);
$return = array(
'itemCount' => $item['quantity'],
'itemPrice' => StoreProduct::formatPrice(Yii::app()->currency->convert($price * $item['quantity'])),
'fullPrice' => StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice())),
'totalSale' => StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalSale())),
'totalPrice'=> StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice() - Yii::app()->cart->getTotalSale())),
'headerCart'=> $this->renderPartial('_small_cart_v2', array(), true, true),
);
echo CJSON::encode($return);
}
public function actionItemMinus($index)
{
Yii::app()->cart->itemMinus($index);
$item = Yii::app()->cart->getDataWithModels();
$item = $item[$index];
$price = StoreProduct::calculatePrices($item['model'], $item['variant_models'], $item['configurable_id']);
$return = array(
'itemCount' => $item['quantity'],
'itemPrice' => StoreProduct::formatPrice(Yii::app()->currency->convert($price * $item['quantity'])),
'fullPrice' => StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice())),
'totalSale' => StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalSale())),
'totalPrice'=> StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice() - Yii::app()->cart->getTotalSale())),
'headerCart'=> $this->renderPartial('_small_cart_v2', array(), true, true),
);
echo CJSON::encode($return);
}
public function actionPromocode($promocode)
{
if(isset($promocode))
{
Yii::app()->cart->initErp();
$data = Yii::app()->cart->setPromoCode($promocode);
}
else
$data = array(
'valid' => 'false',
'message' => 'Не передан промокод.'
);
echo CJSON::encode($data);
}
}
Код: Выделить всё
<?php
Yii::import('orders.models.*');
Yii::import('store.models.*');
Yii::import('application.modules.users.*');
Yii::import('application.modules.orders.forms.UserOrderForm');
Yii::import('ext.cart.ErpCart');
Yii::import('application.modules.api.components.UserAnalytics');
/**
* Cart controller
* Display user cart and create new orders
*/
class OrderController extends Controller
{
/**
* @var OrderCreateForm
*/
public $form;
/**
* @var bool
*/
protected $_errors = false;
/**
* user created from @see actionGuest
*
* $var User|null
*/
private $_guestUser = null;
public function actionThankyou($id)
{
$this->registerCustomScript($id);
$this->render('thankyou', array('id' => $id));
}
public function actionGetPay($id)
{
$this->registerCustomScript($id);
$model = Order::model()->findByPk($id);
$this->render('getPay', array('model' => $model));
}
public function actionSetPay($secret_key)
{
$model = Order::model()->findByAttributes(array('secret_key' => $secret_key));
$model->paid = 1;
$model->save(false);
$this->redirect('/order/thankyou/'.$model->id);
}
/**
* Display list of product added to cart
*/
public function actionIndex()
{
Yii::app()->cart->initErp();
$erpData = Yii::app()->cart->getErp();
$userModel = Yii::app()->user;
$user = User::model()->with('profile', 'address', 'mainDelivery')->findByPk($userModel->id);
$this->form = new UserOrderForm;
$cities = Yii::app()->newPost->city();
$citiesArray = CHtml::listData($cities, 'DescriptionRu', 'DescriptionRu');
if(!empty($user))
{
$this->form->userName = $user->profile->name;
$this->form->userSurname = $user->profile->surname;
$this->form->userPhone = $user->profile->phone;
$this->form->userEmail = $user->username;
$this->form->userDeliveryName = isset($user->mainDelivery->name) ? $user->mainDelivery->name : null;
if (!empty($citiesArray) && !empty($citiesArray[$user->mainDelivery->city])) {
$this->form->userDeliveryCity = isset($user->mainDelivery->city) ? $citiesArray[$user->mainDelivery->city] : null;
}
$this->form->userDeliveryType = isset($user->mainDelivery->type) ? $user->mainDelivery->type : null;
$this->form->userDeliveryAddress = isset($user->mainDelivery->address) ? $user->mainDelivery->address : null;
$this->form->userPayType = null;
$this->form->userComment = null;
$this->form->userPromocode = !empty($promoCode['code'])? $promoCode['code'] : '';
$this->form->deliveryNames = $user->address;
$this->form->mainDelivery = $user->mainDelivery;
}
// Make order
$small_cart = Yii::app()->createController('orders/cart');
if (Yii::app()->request->isPostRequest) {
if (isset($_POST['UserOrderForm'])) {
$this->form->attributes = $_POST['UserOrderForm'];
if ($this->form->validate()) {
$order = $this->createOrder();
Yii::app()->cart->clear();
if ($this->form->userPayType == 23) {
echo CJSON::encode(array('url' => $this->createUrl('/order/getPay/', array('id' => $order->id))));
} else {
echo CJSON::encode($small_cart[0]->actionRenderSmallCart());
}
}
}
} else {
Yii::app()->clientScript->scriptMap = array(
'jquery.js' => false,
'jquery.ui.js' => false,
'jquery.min.js' => false,
'jquery.magnific-popup.min.js' => false,
);
$promoData = Yii::app()->cart->getPromoData(); // PROMODATA
$this->renderPartial('_popupOrder', array('model' => $this->form, 'promoData' => $promoData), false, true);
}
}
public function actionGuest()
{
if (!Yii::app()->cart->getDataWithModels())
$this->redirect('/');
Yii::app()->cart->initErp();
$erpData = Yii::app()->cart->getErp();
$erpProducts = $erpData['products'];
$user = new User();
$this->form = new UserOrderForm;
if(!empty($user))
{
$this->form->userName = null;
$this->form->userSurname = null;
$this->form->userPhone = null;
$this->form->userEmail = null;
$this->form->userDeliveryName = null;
$this->form->userDeliveryCity = null;
$this->form->userDeliveryType = null;
$this->form->userDeliveryAddress = null;
$this->form->userPayType = null;
$this->form->userComment = null;
$this->form->userPromocode = !empty($promoCode['code'])? $promoCode['code'] : '';
$this->form->deliveryNames = null;
$this->form->mainDelivery = null;
}
// Make order
if (Yii::app()->request->isPostRequest) {
if (isset($_POST['UserOrderForm'])) {
$this->form->attributes = $_POST['UserOrderForm'];
// if(isset($_POST['ajax']) && $_POST['ajax']==='user-register-form')
// {
// echo CActiveForm::validate($this->form);
// Yii::app()->end();
// }
if ($this->form->validate())
{
$small_cart = Yii::app()->createController('orders/cart');
$cr = new CDbCriteria();
$cr->condition = 'username=:username';
$cr->params = array(':username' => $this->form->userEmail);
$userModel = User::model()->with('profile')->find($cr);
if (is_null($userModel)) {
$user = $this->createUser();
} else {
$this->_guestUser = $this->updateUser($userModel);
}
$order = $this->createOrder();
Yii::app()->cart->clear();
if($this->form->userPayType == 23)
{
// echo CJSON::encode($this->createUrl('/order/getPay/', array('id' => $order->id)));
echo CJSON::encode(array('url' => $this->createUrl('/order/getPay/', array('id' => $order->id))));
}
echo CJSON::encode($small_cart[0]->actionRenderSmallCart());
} else {
if (Yii::app()->request->isAjaxRequest) {
echo CActiveForm::validate($this->form);
Yii::app()->end();
}
}
} else {
$promoData = Yii::app()->cart->getPromoData(); // PROMODATA
$this->renderPartial('_popupOrder', array('model' => $this->form, 'promoData' => $promoData));
}
}
// $this->render('orderGuest', array('model' => $this->form));
}
public function actionChangeAddress($id = null)
{
if(isset($id))
{
$model = UserAddress::model()->findByPk($id);
$this->renderPartial('_formAddress', array('model' => $model));
}
else
{
$model = new UserAddress();
$this->renderPartial('_formAddressNew', array('model' => $model));
}
}
/**
* Create new order
* @return Order
*/
public function createOrder()
{
if (Yii::app()->cart->countItems() == 0)
return false;
Yii::app()->cart->initErp();
$erpData = Yii::app()->cart->getErp();
$promocode = Yii::app()->cart->getPromoData();
$erpProducts = $erpData['products'];
$order = new Order;
// Set main data
if (isset($_COOKIE['_ga'])) {
$order->ga_assigned_id = UserAnalytics::getAssignedID($_COOKIE['_ga']);
}
$guest_erp_id = !empty($this->_guestUser->erp_id) ? $this->_guestUser->erp_id : null;
$guest_user_id = !empty($this->_guestUser->id) ? $this->_guestUser->id : null;
$order->user_id = Yii::app()->user->isGuest ? $guest_user_id : Yii::app()->user->id;
$order->user_erp_id = Yii::app()->user->isGuest ? $guest_erp_id : User::model()->findByPk(Yii::app()->user->id)->erp_id;
$order->user_name = $this->form->userName;
$order->user_email = $this->form->userEmail;
$order->user_phone = $this->form->userPhone;
if (!empty($this->form->userDeliveryCity)) {
$cities = $this->form->cities();
$city = isset($cities[$this->form->userDeliveryCity]) ? 'г. ' . $cities[$this->form->userDeliveryCity] : '';
$deliveryAddress = (!empty($this->form->userDeliveryAddress)) ? ', ' . $this->form->userDeliveryAddress : '';
$order->user_address = $city . $deliveryAddress;
}
$order->delivery_id = $this->form->userDeliveryType;
$order->pay_id = $this->form->userPayType;
$order->promocode = $promocode['code'];
$order->discount = Yii::app()->cart->getTotalSale();
$order->full_price = bcadd(bcsub(Yii::app()->cart->getTotalPrice(), Yii::app()->cart->getTotalSale()), $order->delivery_price);
if($order->delivery_id == 14)
{
$order->np_city = $this->form->userDeliveryCity;
$order->np_address = preg_replace("/^Отделение([0-9\s\№]*)?:/", "", $this->form->userDeliveryAddress);
preg_match('/^Отделение[0-9\s\№]*/', $this->form->userDeliveryAddress, $matches);
if(!empty($matches[0]))
$order->np_whs = str_replace('Отделение №', '',$matches[0]);
if((int)$order->np_whs === 0)
$order->np_whs = 1;
}
if($order->delivery_id == 15)
{
$order->np_city = $this->form->userDeliveryCity;
$order->np_address = preg_replace("/^Отделение([0-9\s\№]*)?:/", "", $this->form->userDeliveryAddress);
}
if ($order->validate())
$order->save();
else
throw new CHttpException(503, Yii::t('OrdersModule.core', 'Ошибка создания заказа'));
// Process products
foreach (Yii::app()->cart->getDataWithModels() as $item) {
$ordered_product = new OrderProduct;
$ordered_product->order_id = $order->id;
$ordered_product->product_id = $item['model']->id;
$ordered_product->size_id = $item['size'] == 0 ? 8 : $item['size'];
$ordered_product->configurable_id = $item['configurable_id'];
$ordered_product->name = $item['model']->name;
$ordered_product->quantity = $item['quantity'];
$ordered_product->sku = $item['model']->sku;
$rouletteDiscount = Yii::app()->cart->erp->getRouletteDiscount($item['model']->id);
$orderPrice = !empty($erpProducts)?
$erpProducts[$item['model']->id]['price'] :
$item['model']->price;
$ordered_product->price = $orderPrice - $rouletteDiscount;
/*!empty($erpProducts)?
bcsub($erpProducts[$item['model']->id]['price'], $erpProducts[$item['model']->id]['discount']) :
$item['model']->price;*/
// $ordered_product->price = StoreProduct::calculatePrices($item['model'], $item['variant_models'], $item['configurable_id']);
$orderDiscount = !empty($erpProducts)?
$erpProducts[$item['model']->id]['discount'] :
$item['model']->discount;
$ordered_product->discount = $orderDiscount + $rouletteDiscount;
// Process configurable product
if (isset($item['configurable_model']) && $item['configurable_model'] instanceof StoreProduct) {
$configurable_data = array();
$ordered_product->configurable_name = $item['configurable_model']->name;
// Use configurable product sku
$ordered_product->sku = $item['configurable_model']->sku;
// Save configurable data
$attributeModels = StoreAttribute::model()->findAllByPk($item['model']->configurable_attributes);
foreach ($attributeModels as $attribute) {
$method = 'eav_' . $attribute->name;
$configurable_data[$attribute->title] = $item['configurable_model']->$method;
}
$ordered_product->configurable_data = serialize($configurable_data);
}
// Save selected variants as key/value array
if (!empty($item['variant_models'])) {
$variants = array();
foreach ($item['variant_models'] as $variant)
$variants[$variant->attribute->title] = $variant->option->value;
$ordered_product->variants = serialize($variants);
}
$ordered_product->save();
}
// Reload order data.
$order->refresh();
// All products added. Update delivery price.
$order->updateDeliveryPrice();
/* SHOULD BE UNCOMMENTED!!!!!!!!!! FROM THIS!!! */
// Send email to user.
$this->sendEmail($order);
$sendSMS = Yii::app()->sms;
$sendSMS->start($this->form->userPhone,$order->id);
/* SHOULD BE UNCOMMENTED!!!!!!!!!! TO THIS!!! */
return $order;
}
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
'fixedVerifyCode' => '123123'
),
);
}
/**
* @param $user User
* @return User|false
*/
public function updateUser(User $user)
{
if (!$profile = $user->profile) {
$profile = new UserProfile();
$profile->user_id = $user->id;
}
$profile->name = $this->form->userName;
$profile->surname = $this->form->userSurname;
$profile->phone = $this->form->userPhone;
if ($profile->save())
return $user;
return false;
}
public function createUser()
{
$password = '12345';
$user = new User('register');
$profile = new UserProfile();
// $address = new UserAddress();
$user->username = $this->form->userEmail;
$user->email = $this->form->userEmail;
$user->password = $password;
$user->verifyPassword = $password;
$user->verifyCode = '123123';
$profile->name = $this->form->userName;
$profile->surname = $this->form->userSurname;
$profile->phone = $this->form->userPhone;
/*$address->name = 'По умолчанию';
$address->city = $this->form->userDeliveryCity;
$address->type = $this->form->userDeliveryType;
$address->address = $this->form->userDeliveryType;
$address->main = 1;*/
$valid = $user->validate();
$valid = $profile->validate() && $valid;
// $valid = $address->validate() && $valid;
if($valid)
{
$user->save();
$profile->user_id = $user->id;
$profile->save();
// $address->user_id = $user->id;
// $address->save();
// Add user to authenticated group
Yii::app()->authManager->assign('Authenticated', $user->id);
// Authenticate user
$identity = new UserIdentity($user->username, $password);
if($identity->authenticate())
{
Yii::app()->user->login($identity, Yii::app()->user->rememberTime);
}
}
return $user;
}
private function sendEmail(Order $order)
{
$theme = Yii::t('OrdersModule', 'Ваш заказ #') . $order->id;
$lang = Yii::app()->language;
$emailBodyFile = Yii::getPathOfAlias("application.emails.$lang") . DIRECTORY_SEPARATOR . 'new_order.php';
// If template file does not exists use default russian translation
if (!file_exists($emailBodyFile))
$emailBodyFile = Yii::getPathOfAlias("application.emails.ru") . DIRECTORY_SEPARATOR . 'new_order.php';
$body = $this->renderFile($emailBodyFile, array('order' => $order), true);
$mailer = Yii::app()->mail;
$mailer->From = Yii::app()->params['adminEmail'];
$mailer->FromName = Yii::app()->settings->get('core', 'siteName');
$mailer->Subject = $theme;
$mailer->Body = $body;
$mailer->AddAddress($order->user_email);
$mailer->AddReplyTo(Yii::app()->params['adminEmail']);
$mailer->isHtml(true);
$mailer->Send();
$mailer->ClearAddresses();
}
public function actionImport()
{
Yii::import('application.modules.orders.components.OrderImport');
$order = new OrderImport();
echo $order->export();
}
public function actionChangeDefaultDelivery()
{
Yii::import('application.modules.users.models.*');
$deliveryId = Yii::app()->getRequest()->getQuery('deliveryId');
$model = UserAddress::model()->findByPk($deliveryId);
$this->renderPartial('changeDefaultDelivery', array('model' => $model), false, true);
}
public function actionChangeDelivery()
{
// 14 - Новая почта на склад
// 15 - Новая почта курьером
// 16 - Собственный курьер
// 17 - Самовывоз
$deliveryId = (int)Yii::app()->getRequest()->getQuery('deliveryId');
$name = 'UserOrderForm[userDeliveryAddress]';
$pay_name = 'UserOrderForm[userPayType]';
$model = new UserOrderForm();
switch ($deliveryId)
{
case 14:
$wenhouses = UserOrderForm::getAddressLine();
$payTypes = $model->payTypes(array(22,23));
$pay = CHtml::dropDownList($pay_name, 'userPayType', $payTypes,
array(
'empty' => array('default' => 'Выберите способ оплаты'),
'class' => 'js-select tsh-select',
'name' => $pay_name,
)
);
$html = CHtml::dropDownList($name, 'userDeliveryAddress', $wenhouses,
array(
'empty' => array('default' => 'Выберите отделение'),
'class' => 'js-select tsh-select',
'name' => $name,
)
);
break;
case 15:
$payTypes = $model->payTypes(array(18,23));
$pay = CHtml::dropDownList($pay_name, 'userPayType', $payTypes,
array(
'empty' => array('default' => 'Выберите способ оплаты'),
'class' => 'js-select tsh-select',
'name' => $pay_name,
)
);
$html = CHtml::textField(
$name, '', array(
'class' => 'input required_field',
'name' => $name,
'placeholder' => 'Адрес',
)
);
break;
case 16:
$payTypes = $model->payTypes(array(18,23));
$pay = CHtml::dropDownList($pay_name, 'userPayType', $payTypes,
array(
'empty' => array('default' => 'Выберите способ оплаты'),
'class' => 'js-select tsh-select',
'name' => $pay_name,
)
);
$html = CHtml::textField(
$name, '', array(
'class' => 'input required_field',
'name' => $name,
'placeholder' => 'Адрес',
)
);
break;
case 17:
$stores = UserOrderForm::getAddressLine();
$payTypes = $model->payTypes(array(20,23));
$pay = CHtml::dropDownList($pay_name, 'userPayType', $payTypes,
array(
'empty' => array('default' => 'Выберите способ оплаты'),
'class' => 'js-select tsh-select',
'name' => $pay_name,
)
);
$html = CHtml::dropDownList($name, 'userDeliveryAddress', $stores,
array(
'empty' => array('default' => 'Выберите магазин'),
'class' => 'js-select tsh-select',
'name' => $name,
)
);
break;
default:
$payTypes = $model->payTypes();
$pay = CHtml::dropDownList($pay_name, 'userPayType', $payTypes,
array(
'empty' => array('default' => 'Выберите способ оплаты'),
'class' => 'js-select tsh-select',
'name' => $pay_name,
'disabled' => true,
)
);
$html = CHtml::textField(
$name, '', array(
'class' => 'input required_field',
'name' => $name,
'disabled' => true,
'placeholder' => 'Адрес',
)
);
break;
}
$deliveryModel = StoreDeliveryMethod::model()->findByPk($deliveryId);
if($deliveryModel !== null && Yii::app()->cart->getTotalPrice() < $deliveryModel->free_from)
$deliveryPrice = !empty($deliveryModel) ? StoreProduct::formatPrice($deliveryModel->price) : StoreProduct::formatPrice(0);
else
$deliveryPrice = StoreProduct::formatPrice(0);
Yii::app()->cart->initErp();
$price = bcsub(
StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalPrice())),
StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalSale())),
2
);
$fullPrice = bcadd($price, $deliveryPrice, 2);
$script = '<script>
var select = $(".js-select");
select.styler({
onSelectOpened: function() {
$(".js-custom-scrollbar").mCustomScrollbar("update");
},
onSelectClosed: function() {
setTimeout( function() {
$(".js-custom-scrollbar").mCustomScrollbar("update");
}, 10);
}
});
</script>';
$data = array(
'html' => $html.$script,
'deliveryPrice' => $deliveryPrice,
'fullPrice' => $fullPrice,
'totalSale' => StoreProduct::formatPrice(Yii::app()->currency->convert(Yii::app()->cart->getTotalSale())),
'pay' => $pay.$script,
);
echo json_encode($data, true);
}
private function registerCustomScript($id)
{
$result = Order::model()->with('products')->findByPk($id);
$products = array();
foreach($result->products as $product) {
$products[] = array(
'name' => $product->name,
'id' => $product->product_id,
'price' => $product->price,
'brand' => '',
'category' => '',
'variant' => '',
'quantity' => $product->quantity,
'coupon' => ''
);
}
$json_products = json_encode($products, JSON_UNESCAPED_UNICODE);
Yii::app()->clientScript->registerScript('purchaseScript',
"dataLayer. push({
'event': 'transaction',
'ecommerce': {
'purchase': {
'actionField': {
'id': '$result->id',
'affiliation': 'Cart',
'revenue': '$result->total_price',
'tax': '',
'shipping': '$result->delivery_price',
'coupon': ''
},
'products': $json_products
}
}
});",
CClientScript::POS_END
);
}
public function getTypes($cityName = 'default')
{
$model = new UserOrderForm();
// $cities = Yii::app()->newPost->city();
// foreach ($cities as $city){
// if($city['Ref'] == $cityRef) {
// $cityName = $city['DescriptionRu'];
// }
// }
$types_1 = array(14, 15, 17);
$types_2 = array(14, 15, 16, 17);
$cityTypes = array(
'Киев' => $types_1,
'Одесса' => $types_1,
'Днепр' => $types_1,
'Кривой рог' => $types_1,
'Херсон' => $types_1,
'Черкассы' => $types_1,
'Харьков' => $types_2
);
if($cityName != 'default') {
if(array_key_exists($cityName, $cityTypes)){
$allTypes = $model->deliveryTypes($cityTypes[$cityName]);
} else {
$allTypes = $model->deliveryTypes();
}
return $allTypes;
} else {
return array();
}
}
public function actionChangeCity()
{
$cityName = Yii::app()->getRequest()->getQuery('cityName');
$name = 'UserOrderForm[userDeliveryType]';
echo CHtml::dropDownList($name, 'userDeliveryType', $this->getTypes($cityName),
array(
'empty' => array('default' => 'Выберите способ доставки'),
'class' => 'js-select tsh-select',
'name' => $name,
'disabled' => $cityName == 'default'? true:false,
)
);
}
public function setPayType($deliveryTypeId)
{
$model = new UserOrderForm();
switch ($deliveryTypeId) {
case 14:
$payTypes = $model->payTypes(array(22, 23));
break;
case 15:
$payTypes = $model->payTypes(array(18, 23));
break;
case 16:
$payTypes = $model->payTypes(array(18, 23));
break;
case 17:
$payTypes = $model->payTypes(array(20, 23));
break;
}
return $payTypes;
}
}