Beispiel #1
0
 public function createProduct($data)
 {
     $orderProduct = new OrderProduct();
     $createTime = date('Y-m-d H:i:s');
     $orderProduct->orderId = $data['orderId'];
     $orderProduct->startDate = $data['startDate'];
     $orderProduct->endDate = $data['endDate'];
     $orderProduct->totalTimes = $data['totalTimes'];
     $orderProduct->usedTimes = $data['use'];
     $orderProduct->createTime = $createTime;
     if ($orderProduct->save()) {
         return array('code' => 200, 'mes' => 'success');
     } else {
         return array('code' => 500, 'mes' => 'create fail');
     }
 }
Beispiel #2
0
 public function createOrder()
 {
     $time = date('Y-m-d H:i:s', time());
     $transaction = $this->db->beginTransaction();
     try {
         $criteria = new CDbCriteria();
         $criteria->addCondition('dpid=:dpid and site_id=:siteId and is_temp=:isTemp');
         $criteria->params = array(':dpid' => $this->siteNo->dpid, ':siteId' => $this->siteNo->site_id, ':isTemp' => $this->siteNo->is_temp);
         $criteria->order = 'lid desc';
         $order = Order::model()->find($criteria);
         if (!$order) {
             $order = new Order();
             $data = array('lid' => $this->getMaxOrderId(), 'dpid' => $this->companyId, 'site_id' => $this->siteId, 'create_at' => date('Y-m-d H:i:s', time()), 'is_temp' => $this->siteNo->is_temp, 'number' => $this->siteNo->number, 'update_at' => date('Y-m-d H:i:s', time()), 'remark' => yii::t('app', '无'), 'taste_memo' => "");
             $order->attributes = $data;
             $order->save();
         }
         $setId = 0;
         if ($this->product['type']) {
             $setId = $this->product['lid'];
             $orderProduct = OrderProduct::model()->find('order_id=:orderId and dpid=:dpid and set_id=:setId and product_order_status=0', array(':orderId' => $order->lid, 'dpid' => $this->companyId, ':setId' => $setId));
         } else {
             $orderProduct = OrderProduct::model()->find('order_id=:orderId and dpid=:dpid and product_id=:productId and product_order_status=0', array(':orderId' => $order->lid, 'dpid' => $this->companyId, ':productId' => $this->product['lid']));
         }
         if ($orderProduct) {
             $orderProduct->price = $this->getProductPrice($this->companyId, $this->product['lid'], $this->product['type']);
             $orderProduct->delete_flag = 0;
             $orderProduct->update_at = date('Y-m-d H:i:s', time());
             $orderProduct->update();
         } else {
             $orderProduct = new OrderProduct();
             $orderProductData = array('lid' => $this->getMaxOrderProductId(), 'dpid' => $this->companyId, 'create_at' => date('Y-m-d H:i:s', time()), 'order_id' => $order->lid, 'set_id' => $setId, 'product_id' => $this->product['lid'], 'price' => $this->getProductPrice($this->companyId, $this->product['lid'], $this->product['type']), 'update_at' => date('Y-m-d H:i:s', time()), 'amount' => 1, 'taste_memo' => "");
             $orderProduct->attributes = $orderProductData;
             $orderProduct->save();
         }
         $transaction->commit();
         //提交事务会真正的执行数据库操作
         return true;
     } catch (Exception $e) {
         $transaction->rollback();
         //如果操作失败, 数据回滚
         return false;
     }
 }
Beispiel #3
0
 /**
  * 保存订单商品信息
  * @param $oid
  * @param $cartinfo
  * @return bool
  * @throws Exception
  */
 protected function saveOrderProduct($userId, $order_id, $cartInfo)
 {
     $list = $cartInfo['list'];
     foreach ($list as $row) {
         if ($row['type'] == 1) {
             $pInfo = Tab::model()->findByPk($row['product_id']);
             if (empty($pInfo)) {
                 throw new Exception("谱子不存在!", 500);
             }
         } elseif ($row['type'] == 2) {
             $pInfo = Zine::model()->findByPk($row['product_id']);
             if (empty($pInfo)) {
                 throw new Exception("杂志商品不存在!", 500);
             }
         } else {
             $pInfo = Product::model()->findByPk($row['product_id']);
             if (empty($pInfo)) {
                 throw new Exception("订单商品不存在!", 500);
             }
         }
         if ($row['sell_price'] != $pInfo['sell_price']) {
             throw new exception('价格错误,请重试');
         }
         $m = new OrderProduct();
         $m->order_id = $order_id;
         $m->user_id = $userId;
         $m->product_id = $row['product_id'];
         $m->type = $row['type'];
         $m->product_sn = empty($row['type']) ? $pInfo['product_sn'] : '';
         $m->product_name = empty($row['type']) ? $pInfo['product_name'] : ($row['type'] == 1 ? $pInfo['tabname'] : $pInfo['name']);
         $m->size_id = $row['size_id'];
         $m->brand_id = $row['type'] == 0 ? $pInfo['brand_id'] : 0;
         $m->sell_price = $row['sell_price'];
         $m->quantity = $row['quantity'];
         //$m->shipping_id 	= 0;
         //$m->shipping_code 	= '';
         //$m->shipping_time 	= 0;
         $opid = $m->save();
         if (empty($opid)) {
             throw new Exception("订单商品生成失败!", 1);
         }
         $this->updateProductStock($pInfo, $row);
         //更新商品的库存
     }
     return true;
 }
Beispiel #4
0
      */
     if (\Actionpay\CPA::getLastPartnerName()) {
         // Имя партнёра и идентификатор трафика, хранящиеся в cookie клиента
         $order->partner_name = \Actionpay\CPA::getLastPartnerName();
         $order->partner_traffic_id = \Actionpay\CPA::getLastTrafficIdentifer();
         // Генерируем уникальный ID для отслеживания заказа патрнером.
         // Очень важно, чтобы этот ID генерировался случайным образом!
         $order->partner_order_id = $order->id . '_' . sprintf('%06x', rand(0, pow(2, 24) - 1));
         $order->save();
     }
     foreach ($basket as $productId => $count) {
         $orderProduct = new OrderProduct();
         $orderProduct->order_id = $order->id;
         $orderProduct->product_id = $productId;
         $orderProduct->count = $count;
         $orderProduct->save();
     }
     // редирект на страницу "спасибо"
     $app->redirect('/thankyou?order=' . $order->id);
     // очистка корзины
     $app->session('basket', array());
     $app->session('basketTotalItems', 0);
     $app->session('basketTotalPrice', 0);
     return '';
 }
 $basket = $app->session('basket');
 if (!empty($basket)) {
     $products = Product::getAll(array('id' => array_keys($basket)), array('name' => true));
 } else {
     $products = array();
 }
 public function checkout_step3()
 {
     // Processing Cart
     $cart_id = $this->cart_id;
     if (!$cart_id) {
         $cart_id = Input::get('cart_id');
     }
     $address_id = Input::get('address_id');
     $payment_id = Input::get('payment_id');
     $cart_products = DB::table('cart_products')->where('cart_id', $cart_id)->leftJoin('products', 'cart_products.product_id', '=', 'products.id')->leftJoin('users', 'cart_products.added_by', '=', 'users.id')->select('products.*', 'cart_products.quantity as cart_quantity', 'users.first_name as added_by')->orderBy('store_id')->get();
     $cart_users = DB::table('cart_users')->leftJoin('users', 'cart_users.user_id', '=', 'users.id')->select('users.*')->get();
     $response_array['cart'] = Cart::find($cart_id)->toArray();
     $response_array['cart']['total_amount'] = 0;
     $response_array['cart']['total_quantity'] = 0;
     $response_array['cart']['users'] = array();
     $response_array['cart']['stores'] = array();
     $store_id = 0;
     if ($cart_products) {
         $response_array['cart']['is_minimum_reached'] = 1;
         foreach ($cart_products as $cart_product) {
             if ($store_id != $cart_product->store_id) {
                 $store_id = $cart_product->store_id;
                 // Retriving Store
                 $store = Store::find($store_id)->toArray();
                 // Retriving Delivery Slot
                 $time = date("Y-m-d H:i:s");
                 $slot = Slot::where('store_id', $store_id)->where('start_time', '>', $time)->where('is_available', 1)->orderBy('start_time')->first();
                 if ($slot) {
                     $next_slot_start = date("D, jS M, H a", strtotime($slot->start_time));
                     $next_slot_end = date("h a", strtotime($slot->end_time));
                     $next_slot = $next_slot_start . " - " . $next_slot_end;
                 } else {
                     $next_slot = "No Slots available";
                 }
                 $store['slot'] = $next_slot;
                 $store['count'] = 1;
                 $store['sub_total'] = 0;
                 $response_array['cart']['stores'][$store_id] = $store;
                 $response_array['cart']['stores'][$store_id]['products'] = array();
             } else {
                 $response_array['cart']['stores'][$store_id]['count'] += 1;
             }
             $product = json_decode(json_encode($cart_product), true);
             $product['sub_total'] = $product['cart_quantity'] * $product['price'];
             $response_array['cart']['stores'][$store_id]['sub_total'] += $product['sub_total'];
             $response_array['cart']['total_amount'] += $product['sub_total'];
             $response_array['cart']['total_quantity']++;
             array_push($response_array['cart']['stores'][$store_id]['products'], $product);
         }
     }
     if ($cart_users) {
         foreach ($cart_users as $cart_user) {
             $product = json_decode(json_encode($cart_user), true);
             array_push($response_array['cart']['users'], $cart_user);
         }
     }
     foreach ($response_array['cart']['stores'] as $st) {
         if ($st['sub_total'] < $st['minimum_order_amount']) {
             $response_array['cart']['is_minimum_reached'] = 0;
         }
     }
     if (isset($response_array['cart']['is_minimum_reached']) && $response_array['cart']['is_minimum_reached'] == 1) {
         $order = new Order();
         $order->user_id = $this->user_id;
         $order->date = date("Y-m-d H:i:s");
         $order->total_products = $response_array['cart']['total_quantity'];
         $order->total_amount = $response_array['cart']['total_amount'];
         $order->payment_id = $payment_id;
         $order->address_id = $address_id;
         $payment = Payment::find($payment_id);
         $order->payment_customer_id = $payment->customer_id;
         $address = UserAddress::find($address_id);
         $order->address = $address->address . " " . $address->zipcode;
         $order->status = "Initiated";
         $order->save();
         foreach ($cart_products as $cart_product) {
             $order_product = new OrderProduct();
             $order_product->order_id = $order->id;
             $product = Product::find($cart_product->id);
             $product->total_sale += $cart_product->cart_quantity;
             $product->save();
             $order_product->price = $cart_product->price;
             $order_product->quantity = $cart_product->cart_quantity;
             $order_product->fulfilment_status = "Pending";
             $order_product->type = "Product";
             $order_product->parent_id = 0;
             $order_product->product_name = $product->name;
             $order_product->product_image_url = $product->image_url;
             $order_product->product_quantity = $product->quantity;
             $order_product->product_unit = $product->unit;
             $order_product->store_id = $product->store_id;
             $order_product->save();
         }
         // removing products from cart
         CartProduct::where('cart_id', $cart_id)->delete();
         // Order Placement Mail
         $user = User::find($this->user_id);
         Mail::send('emails.order_success', array('user' => $user, 'order' => $order), function ($message) use($user) {
             $message->to($user->email, $user->first_name)->subject('Thanks for placing the order!');
         });
         // Order Placement Mail to Admin
         $admin_email = Config::get('app.admin_email');
         Mail::send('emails.admin_order_success', array('user' => $user, 'order' => $order), function ($message) use($admin_email) {
             $message->to($admin_email, "Admin")->subject('New Order!');
         });
     } else {
         $message = "Minimum order amount not reached";
         if (Request::format() == 'html') {
             return View::make('checkout_step3')->with('store', $this->store)->with('departments', $this->departments)->with('zipcode', $this->zipcode)->with('city', $this->city)->with('stores1', $this->stores)->with('message', $message);
         } else {
             $response_array = array('success' => false, 'error_code' => 411, 'error' => $message);
             $response_code = 200;
             $response = Response::json($response_array, $response_code);
             return $response;
         }
     }
     if (Request::format() == 'html') {
         return View::make('checkout_step3')->with('store', $this->store)->with('departments', $this->departments)->with('zipcode', $this->zipcode)->with('city', $this->city)->with('stores1', $this->stores)->with('message', 'Thanks for placing your Order!!');
     } else {
         $response_array = array('success' => true);
         $response_code = 200;
         $response = Response::json($response_array, $response_code);
         return $response;
     }
 }
 public function actionEditProduct()
 {
     $id = Yii::app()->request->getParam('id', 0);
     $setid = Yii::app()->request->getParam('setid', 0);
     $orderId = Yii::app()->request->getParam('orderId');
     $typeId = Yii::app()->request->getParam('typeId');
     $companyId = Yii::app()->request->getParam('companyId');
     //$orderProduct=null;
     //$models=null;
     //$modelsp=null;
     //if($setid=='0000000000')
     //{
     $orderProduct = OrderProduct::model()->with(array('product', 'productSet'))->find('t.lid=:id and t.dpid=:dpid', array(':id' => $id, ':dpid' => $companyId));
     //}
     if (Yii::app()->request->isPostRequest) {
         Until::validOperate($companyId, $this);
         $isset = Yii::app()->request->getPost('isset', 0);
         //$setid = Yii::app()->request->getParam('setid',0);
         $selsetlist = Yii::app()->request->getPost('selsetlist', 0);
         //var_dump($orderProduct);exit;
         $orderProduct->attributes = Yii::app()->request->getPost('OrderProduct');
         //var_dump(Yii::app()->request->getPost('OrderProduct'));exit;
         //var_dump($selsetlist,$isset);exit;
         $db = Yii::app()->db;
         $transaction = $db->beginTransaction();
         try {
             if ($isset == 0) {
                 $orderProduct->save();
             } else {
                 if (strlen($selsetlist) > 10) {
                     $productIdlist = explode(',', $selsetlist);
                     //$setid=Yii::app()->request->getPost('OrderProduct');
                     //var_dump($setid['set_id']);exit;
                     $db->createCommand('delete from nb_order_product where set_id=:setid and dpid=:dpid')->execute(array(':setid' => $orderProduct->set_id, ':dpid' => $companyId));
                     foreach ($productIdlist as $productId) {
                         //var_dump($productId);exit;
                         $sorderProduct = new OrderProduct();
                         $sorderProduct->dpid = $companyId;
                         $sorderProduct->delete_flag = '0';
                         $sorderProduct->product_order_status = '0';
                         $sorderProduct->set_id = $orderProduct->set_id;
                         $sorderProduct->order_id = $orderProduct->order_id;
                         $sorderProduct->create_at = date('Y-m-d H:i:s', time());
                         $productUnit = explode('|', $productId);
                         $sorderProduct->product_id = $productUnit[0];
                         $sorderProduct->amount = $productUnit[1];
                         $sorderProduct->price = $productUnit[2];
                         $sorderProduct->is_giving = '0';
                         $sorderProduct->zhiamount = 0;
                         $se = new Sequence("order_product");
                         $sorderProduct->lid = $se->nextval();
                         //var_dump($sorderProduct);exit;
                         $sorderProduct->save();
                     }
                 }
             }
             $transaction->commit();
             Yii::app()->user->setFlash('success', yii::t('app', '修改成功'));
             //echo '333';exit;
             $this->redirect(array('defaultOrder/order', 'companyId' => $this->companyId, 'orderId' => $orderProduct->order_id, 'typeId' => $typeId));
         } catch (Exception $e) {
             $transaction->rollback();
             //如果操作失败, 数据回滚
             //var_dump($e);
             //echo json_encode(array('status'=>0,'message'=>'换台失败'));
             Yii::app()->user->setFlash('success', yii::t('app', '添加失败'));
             return false;
         }
     }
     $this->renderPartial('editproduct', array('orderid' => $orderId, 'orderProduct' => $orderProduct, 'typeId' => $typeId));
 }
 /**
  * Create new order
  * @return Order
  */
 public function createOrder()
 {
     if (Yii::app()->cart->countItems() == 0) {
         return false;
     }
     Yii::import('mod.cart.models.Order');
     Yii::import('mod.cart.models.OrderProduct');
     $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;
     $order->payment_id = $this->form->payment_id;
     if ($order->validate()) {
         if ($order->save()) {
         }
     } else {
         throw new CHttpException(503, Yii::t('CartModule.default', 'ERROR_CREATE_ORDER'));
     }
     // 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->currency_id = $item['model']->currency_id;
         $ordered_product->supplier_id = $item['model']->supplier_id;
         $ordered_product->name = $item['model']->name;
         $ordered_product->quantity = $item['quantity'];
         $ordered_product->sku = $item['model']->sku;
         $ordered_product->date_create = $order->date_create;
         // if($item['currency_id']){
         //     $currency = ShopCurrency::model()->findByPk($item['currency_id']);
         //$ordered_product->price = ShopProduct::calculatePrices($item['model'], $item['variant_models'], $item['configurable_id']) * $currency->rate;
         // }else{
         $ordered_product->price = ShopProduct::calculatePrices($item['model'], $item['variant_models'], $item['configurable_id']);
         // }
         // Process configurable product
         if (isset($item['configurable_model']) && $item['configurable_model'] instanceof ShopProduct) {
             $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 = ShopAttribute::model()->cache($this->cacheTime)->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();
     //@todo panix text email tpl
     // All products added. Update delivery price.
     $order->updateDeliveryPrice();
     // Send email to user.
     $this->sendClientEmail($order);
     // Send email to admin.
     $this->sendAdminEmail($order);
     if (Yii::app()->hasModule('sms')) {
         /* $this->widget('mod.sms.widgets.SMSWidget', array(
                'key' => 'ADMIN_ORDER_BEFORE',
                'model' => $order
            ));*/
         $this->widget('mod.sms.widgets.SMSWidget', array('key' => 'CLIENT_ORDER_BEFORE', 'model' => $order));
     }
     return $order;
 }
Beispiel #8
0
 public function actionDoOrder()
 {
     if (Yii::app()->user->isGuest || empty($_POST)) {
         throw new CHttpException(404, 'Страница не найдена');
     }
     $product_ids = Yii::app()->request->getPost('id');
     if (empty($product_ids) || !is_array($product_ids)) {
         throw new CHttpException(404, 'Не выбраны товары для заказа');
     }
     $model_order = new Order();
     if (count($product_ids)) {
         $model_order->order_status_id = Order::STATUS_CREATED;
         $model_order->user_id = Yii::app()->user->id;
         $model_order->ip = $_SERVER['REMOTE_ADDR'];
         $model_order->comment = $_POST['comment'];
         $model_order->date = date('Y-m-d H:i:s', time());
         $model_order->save();
         $order_id = $model_order->order_id;
     }
     $products = array();
     foreach ($product_ids as $pid) {
         if (!isset($_POST["quantity{$pid}"]) || !$_POST["quantity{$pid}"]) {
             continue;
         }
         $model_order_product = new OrderProduct();
         $model_order_product->product_id = $pid;
         $model_order_product->order_id = $order_id;
         $model_order_product->quantity = $_POST["quantity{$pid}"];
         $products[$pid] = $_POST["quantity{$pid}"];
         $model_order_product->save();
     }
     //Отпраляем письмо с заказом
     $message = new YiiMailMessage();
     $message->view = 'orderinfo';
     $message->setSubject("Создан новый заказ на сайте kto-tut.ru");
     $message->setBody(array('products' => $products, 'comment' => $_POST['comment'], 'for_admin' => true), 'text/html');
     $message->addTo(Yii::app()->params['adminEmail']);
     $message->from = Yii::app()->params['adminEmail'];
     Yii::app()->mail->send($message);
     $message = new YiiMailMessage();
     $message->view = 'orderinfo';
     $message->setSubject('Ваш заказ на сайте kto-tut.ru успешно сформирован!');
     $message->setBody(array('products' => $products, 'comment' => $_POST['comment'], 'for_admin' => false), 'text/html');
     $message->addTo(Yii::app()->user->me->email);
     $message->from = Yii::app()->params['adminEmail'];
     Yii::app()->mail->send($message);
     $this->redirect('success');
 }
 public function update_order_product()
 {
     $id = Input::get('id');
     $order_product = OrderProduct::find($id);
     if ($order_product) {
         $order_id = $order_product->order_id;
         $store_id = $order_product->store_id;
         if (Input::has('quantity') && !Input::has('product_name')) {
             $order_product->quantity = Input::get('quantity');
         }
         if (Input::has('price') && !Input::has('product_name')) {
             $order_product->price = Input::get('price');
         }
         if (Input::has('status') && !Input::has('product_name')) {
             $order_product->fulfilment_status = Input::get('status');
         }
         if (Input::has('product_name')) {
             $order_product->fulfilment_status = 'Replacement';
             $order_product->save();
             $order_product = new OrderProduct();
             $order_product->order_id = $order_id;
             $order_product->price = Input::get('price');
             $order_product->quantity = Input::get('quantity');
             $order_product->fulfilment_status = 'Fullfilled';
             $order_product->type = 'Replacement';
             $order_product->parent_id = $id;
             $order_product->product_name = Input::get('product_name');
             $image = Input::file('product_image_url');
             $validator = Validator::make(array('ima' => $image), array('ima' => 'required|mimes:jpeg,bmp,png'));
             if ($validator->fails()) {
                 $error_messages = $validator->messages();
                 $response_array = array('success' => false, 'error' => 'Invalid Input', 'error_code' => 401);
                 $response_code = 200;
                 $message = "Invalid Input File";
                 $type = "failed";
                 return Redirect::to('/admin/order/' . $order_id . '/details')->with('type', $type)->with('message', $message);
             } else {
                 if (Input::hasFile('product_image_url')) {
                     $order_product->product_image_url = upload_image(Input::file('product_image_url'));
                 }
                 $order_product->product_quantity = Input::get('product_quantity');
                 $order_product->product_unit = Input::get('product_unit');
                 $order_product->store_id = $store_id;
             }
             $order_product->save();
         }
         // update order data
         $products = OrderProduct::where('order_id', $order_id)->where('fulfilment_status', 'Fullfilled')->get();
         $total_products = 0;
         $total_amount = 0.0;
         foreach ($products as $product) {
             $total_products++;
             $total_amount = $total_amount + $product->quantity * $product->price;
             echo $total_amount;
         }
         $order = Order::find($order_id);
         $order->total_products = $total_products;
         $order->total_amount = $total_amount;
         $order->save();
         return Redirect::to('/admin/order/' . $order_id . '/details');
     }
 }
Beispiel #10
0
 /**
  * Add product to existing order
  *
  * @param StoreProduct $product
  * @param integer $quantity
  * @param float $price
  */
 public function addProduct($product, $quantity, $price)
 {
     if (!$this->isNewRecord) {
         $ordered_product = new OrderProduct();
         $ordered_product->order_id = $this->id;
         $ordered_product->product_id = $product->id;
         $ordered_product->name = $product->name;
         $ordered_product->quantity = $quantity;
         $ordered_product->sku = $product->sku;
         $ordered_product->price = $price;
         $ordered_product->save();
         // Raise event
         $event = new CModelEvent($this, array('product_model' => $product, 'ordered_product' => $ordered_product, 'quantity' => $quantity));
         $this->onProductAdded($event);
     }
 }
 public function actionPayment($id)
 {
     $cart = $this->getCart();
     $add = CheckoutAddress::model()->findByPk($id);
     $link;
     $onlinePaymentMethodName;
     $extrapObj = array();
     $orderArray = array();
     $classArray = array();
     if (!empty($add) && !empty($cart['items'])) {
         if (isset($_POST['Payment']['payment_method'])) {
             $pay_method = $_POST['Payment']['payment_method'];
             $cart['payment'] = $pay_method == 4 ? 2 : $pay_method;
             $paymentType = is_numeric($pay_method) ? 'others' : 'online';
             $order = new Order();
             $order->order_status_id = 1;
             $order->total = $this->getCartTotal();
             $order->ip = Yii::app()->request->userHostAddress;
             $order->user_agent = Yii::app()->request->userAgent;
             $order->firstname = $add->firstname;
             $order->lastname = $add->lastname;
             $order->email = $add->email;
             $order->telephone = $add->telephone;
             $order->payment_firstname = $add->firstname;
             $order->payment_lastname = $add->lastname;
             $order->payment_company = '';
             $order->payment_tax_id = 0;
             $order->payment_address_1 = $add->address_1;
             $order->payment_address_2 = $add->address_2;
             $order->payment_city = $add->city;
             $order->payment_postcode = $add->postal_code;
             $order->payment_country_id = $add->country_id;
             $order->payment_zone_id = $add->zone_id;
             $order->payment_method = $cart['payment'];
             $order->payment_code = uniqid() . rand(1, 9);
             $order->shipping_firstname = $add->firstname;
             $order->shipping_lastname = $add->lastname;
             $order->shipping_company = '';
             $order->shipping_address_1 = $add->address_1;
             $order->shipping_address_2 = $add->address_2;
             $order->shipping_city = $add->city;
             $order->shipping_postcode = $add->postal_code;
             $order->shipping_country_id = $add->country_id;
             $order->shipping_zone_id = $add->zone_id;
             $order->shipping_method = 2;
             if ($add->zone_id == 2412) {
                 $order->shipping_method = 1;
             }
             $storeid = UtilityHelper::yiiparam('storeID');
             $store = Store::model()->findByPk($storeid);
             $order->store_id = $storeid;
             $order->store_name = $store->name;
             $order->store_url = $store->url;
             $order->payment_country = Country::model()->findByPk($order->payment_country_id)->name;
             $order->payment_zone = Zone::model()->findByPk($order->payment_zone_id)->name;
             $order->shipping_country = $order->payment_country;
             $order->shipping_zone = $order->payment_zone;
             if ($order->save()) {
                 foreach ($cart['items'] as $product) {
                     $orderproduct = new OrderProduct();
                     $orderproduct->order_id = $order->id;
                     $orderproduct->product_id = $product['product_id'];
                     $orderproduct->name = $product['name'];
                     $orderproduct->model = $product['model'];
                     $orderproduct->quantity = $product['quantity'];
                     $orderproduct->price = $product['price'];
                     $orderproduct->total = $product['total'];
                     $orderproduct->tax = 0;
                     if ($orderproduct->save()) {
                         if (!empty($product['option'])) {
                             foreach ($product['option'] as $orderoption) {
                                 $orderoption->order_id = $order->id;
                                 $orderoption->order_product_id = $orderproduct->id;
                                 $orderoption->save();
                             }
                         }
                     } else {
                         Yii::log("CartPaymentOrderProductErrors: " . CVarDumper::dumpAsString($orderproduct->getErrors()), CLogger::LEVEL_ERROR, "cart.actions.payment");
                     }
                 }
                 //Yii::app()->user->setState('user_cart', NULL);
                 $extrap = array();
                 //
                 switch ($paymentType) {
                     case 'others':
                         // Will need to loop through the ids for non online payment to do this properly
                         if ($pay_method == 1) {
                             $link = '_cash';
                             $extrap = array('orderID' => $order->id, 'total' => $order->total);
                             UtilityHelper::changeOrderStatus($order->id);
                         } else {
                             if ($pay_method == 3) {
                                 $link = '_bank';
                                 $extrap = array('orderID' => $order->id, 'total' => $order->total);
                             }
                         }
                         break;
                     case 'online':
                         $subClasses = new PaymentGatewayHelper();
                         $subClassesArray = $subClasses->getSubClasses();
                         foreach ($subClassesArray as $class => $payOption) {
                             ${$class} = new $class();
                             $onlinePaymentMethodName = ${$class}->getPaymentName();
                             if ($pay_method == $onlinePaymentMethodName) {
                                 $link = ${$class}->getViewLink();
                                 ${$class}->setOrderObj($order);
                                 $extrapObj = ${$class}->getOrderObj();
                                 foreach ($extrapObj as $field => $value) {
                                     $orderArray[$field] = $value;
                                 }
                                 $link = ${$class}->getViewLink();
                                 $extrap = array('orderID' => $orderArray['id'], 'total' => $orderArray['total']);
                                 ${$class}->regPaymentTransaction($order);
                                 $classArray['pay_method'] = $pay_method;
                             } else {
                                 continue;
                             }
                         }
                         break;
                     default:
                         break;
                 }
                 if (Yii::app()->getRequest()->getIsAjaxRequest()) {
                     $this->renderPartial($link, array_merge(array('ref' => $order->payment_code), $extrap, $classArray), false, true);
                     Yii::app()->end();
                 }
                 $this->render($link, array_merge(array('ref' => $order->payment_code), $extrap, $classArray));
                 Yii::app()->end();
             } else {
                 Yii::log("CartPaymentErrors: " . CVarDumper::dumpAsString($order->getErrors()), CLogger::LEVEL_ERROR, "cart.actions.payment");
             }
         }
         if (Yii::app()->getRequest()->getIsAjaxRequest()) {
             $this->renderPartial('_payment', array('app' => $add), false, true);
             Yii::app()->end();
         }
         $this->render('payment', array('app' => $add));
         Yii::app()->end();
     }
     $this->redirect(array('cart'));
 }
 /**
  * 生成订单
  * $products = array(array(2,1,18),array(3,1,29)) ==>array(product_id,product_num,price)
  */
 public function actionCreateOrder()
 {
     $siteNo = SiteNo::model()->find('company_id=:companyId and code=:code and delete_flag=0', array(':companyId' => $this->companyId, ':code' => $this->seatNum));
     if (!$siteNo) {
         echo 0;
         exit;
     }
     if (Yii::app()->request->isPostRequest) {
         $now = time();
         $site_no_id = $siteNo->id;
         $waiter_id = $siteNo->waiter_id;
         $number = $siteNo->number;
         $products = Yii::app()->request->getPost('products');
         $transaction = Yii::app()->db->beginTransaction();
         try {
             $order = Order::model()->with('siteNo')->find('t.company_id=:companyId and siteNo.code=:code and delete_flag=0', array(':companyId' => $this->companyId, ':code' => $this->seatNum));
             if (!$order) {
                 $order = new Order();
                 $orderData = array('company_id' => $this->companyId, 'site_no_id' => $site_no_id, 'waiter_id' => $waiter_id, 'number' => $number, 'create_time' => $now);
                 $order->attributes = $orderData;
                 $order->save();
             }
             $orderId = $order->order_id;
             foreach ($products as $product) {
                 $orderProduct = new OrderProduct();
                 $productData = array('order_id' => $orderId, 'product_id' => $product[0], 'price' => $product[2], 'amount' => $product[1]);
                 $orderProduct->attributes = $productData;
                 $orderProduct->save();
             }
             $transaction->commit();
             $res = Helper::printCartGoods($this->companyId, $this->seatNum);
             //setcookie('orderId',$orderId);
         } catch (Exception $e) {
             $transaction->rollback();
             //回滚函数
         }
     }
     $this->redirect(array('/waiter/product/cartList', 'cid' => $this->companyId, 'code' => $this->seatNum));
 }
 private static function set_order_products($order_id, $products)
 {
     foreach ($products as $product) {
         $product = json_decode($product);
         $order_product = new OrderProduct(array('order_id' => $order_id, 'product_id' => $product->id, 'product_info' => json_encode($product)));
         $order_product->save();
     }
 }
Beispiel #14
0
 function updateAction()
 {
     if (isset($_POST['ajax'])) {
         if (isset($_POST['attachOrder']) && $this->access->actionAccess('attachOrder')) {
             $orderID = AF::get($_POST, 'order_id');
             $campID = AF::get($_POST, 'camp_id', 0);
             if (!$orderID) {
                 Message::echoJsonError(__('order_attach_no_fields'));
             }
             $order = new Order();
             $order->fillFromDbPk($orderID);
             $o = clone $order;
             $r = Orders::createAttachedOrder($order, $campID, true);
             unset($order);
             unset($o);
             if ($r) {
                 Message::echoJsonSuccess(array('message' => __('order_attach_success'), 'order_id' => $r));
             } else {
                 Message::echoJsonError(__('order_attach_error'));
             }
         }
     }
     /*
     if(isset($_POST['ajax']))
     {
         if( isset($_POST['add_rocket']) && $this->access->actionAccess('rocket') )
         {
     
             $orderID = AF::get($_POST, 'order_id');
             $rocket = AF::get($_POST, 'rocket', 0);
     
             if(!$orderID)
                 Message::echoJsonError(__('order_rocket_no_fields'));
     
             $newRocket = ($rocket) ? 0 : 1;
             $orderModel = new Order();
             $orderModel->order_id = $orderID;
             $orderModel->rocket = $newRocket;
             $orderModel->setIsNewRecord(false);
     
             if($orderModel->save(false))
                 Message::echoJsonSuccess(__('order_rocket_action_'.$newRocket));
             else
                 Message::echoJsonError(__('order_rocket_not_action_'.$newRocket));
         }
     
         if(isset($_POST['update_expiry_date']) && $this->access->actionAccess('update'))
         {
             $expiryMonth = AF::get($_POST,'expiry_month');
             $expiryYear = AF::get($_POST,'expiry_year');
             $orderID = AF::get($_POST,'order_id');
     
             if(!$orderID)
                 Message::echoJsonError(__('order_incorrect_order_id'));
     
             if(!$expiryMonth || (int)$expiryMonth > 12 || !$expiryYear || (int) $expiryYear < date('Y'))
                 Message::echoJsonError(__('order_incorrect_expiry_date'));
     
             $pacnetModel = new OrderPn();
             $pacnetModel->order_id = $orderID;
             $pacnetModel->expiry_date = OrderPn::convertExpiryDateFormat($expiryMonth, $expiryYear);
             $pacnetModel->setIsNewRecord(false);
     
             if($pacnetModel->save(false))
             {
                 OrderLog::createLog($this->user->user_id, $orderID, 16, $pacnetModel->expiry_date);
                 Message::echoJsonSuccess(__('order_updeted_expiry_date'));
             }
             else
                 Message::echoJsonError(__('order_not_updeted_expiry_date'));
         }
     
         if(isset($_POST['update_cc_cvv']) && $this->access->actionAccess('update'))
         {
     
             $ccCvv = AF::get($_POST,'cc_cvv');
             $orderID = AF::get($_POST,'order_id');
     
             if(!$orderID)
                 Message::echoJsonError(__('order_incorrect_order_id'));
     
             if(!$ccCvv || strlen($ccCvv) > 4 || strlen($ccCvv) < 3)
                 Message::echoJsonError(__('order_incorrect_cc_cvv'));
     
             $pacnetModel = new OrderPn();
             $pacnetModel->fillFromDbPk($orderID);
             $arrayNote1 = unserialize(NoteBase64::decode($pacnetModel->note1));
             $arrayNote1['ccc'] = $ccCvv;
             $pacnetModel->note1 = NoteBase64::encode(serialize($arrayNote1));
             $pacnetModel->IsNewRecord = false;
             if($pacnetModel->save(false))
             {
                 OrderLog::createLog($this->user->user_id, $orderID, 17, '***');
                 Message::echoJsonSuccess(__('order_updeted_cc_cvv'));
             }
             else
                 Message::echoJsonSuccess(__('order_not_updeted_cc_cvv'));
     
     
     
         }
     }
     */
     //$model = new Order();
     $id = AF::get($this->params, 'id', FALSE);
     if (!$id) {
         throw new AFHttpException(0, 'no_id');
     }
     if (isset($_POST['set_void']) && $this->access->actionAccess('order_refund')) {
         $orderLogsModel = new OrderLog();
         $orderLogsModel->user_id = $this->user->user_id;
         $orderLogsModel->action = 3;
         if (!$orderLogsModel->canVoid()) {
             $this->redirect();
         }
         $orderModel = new Order();
         $orderModel->fillFromDbPk($id);
         if ($orderModel->status == 'void') {
             $this->redirect();
         }
         $orderModel->status = 'void';
         $orderModel->amount_refunded = '(`amount_product`+`amount_shipping`):sql';
         $orderModel->model_uset_id = $this->user->user_id;
         // remove recurring by all product
         /*
         if($orderModel->recurring == '0' || $orderModel->recurring == -1)
             $saveModel->recurring = 'NULL:sql';
         */
         if ($orderModel->save(false)) {
             //$saveModel->
             $jobModel = new Job();
             $jobModel->order_id = $orderModel->order_id;
             $jobModel->job_type = 'refund';
             $jobModel->addNew();
             //Set void events
             Event::setEvents($orderModel->order_id, 6);
             OrderLog::createLog($this->user->user_id, $id, 3);
         }
     }
     if (isset($_POST['set_shipping_address'])) {
         $orderModel = new Order();
         $orderModel->fillFromDbPk($id);
         $orderModel->address_id = $_POST['shipping_address'];
         $orderModel->save();
     }
     if (isset($_POST['set_billing_address'])) {
         $orderModel = new Order();
         $orderModel->fillFromDbPk($id);
         $orderModel->address_id = $_POST['billing_address'];
         $orderModel->save();
     }
     if (isset($_POST['cancel_retries']) && $this->access->actionAccess('update')) {
         $orderModel = Order::model()->findByPk($id);
         if ($orderModel->cancelRetries($this->user->user_id)) {
             // save success
         } else {
             // failed, now what?
         }
         $this->redirect();
     }
     if (isset($_POST['order_form_cancel_retry_set_recurring_next']) && $this->access->actionAccess('update')) {
         $productID = (int) AF::get($_POST, 'product_id');
         $recurringNext = AF::get($_POST, 'recurring_next');
         $parentOrder = Order::model()->findByPk($id);
         // have to use a different method of Order class population to not overwrite $parentOrder
         $childOrder = new Order();
         $childID = $parentOrder->hasDeclinedRebilled();
         if (!$childID) {
             return false;
         }
         $childOrder->fillFromDbPk($childID);
         if ($childOrder->cancelRetries($this->user->user_id)) {
             // set rebill date
             $orderProduct = new OrderProduct();
             $orderProduct->fillFromDbPks(array('order_id' => $id, 'product_id' => $productID));
             $orderProduct->addFlags('recurring');
             $orderProduct->recurring_next = $recurringNext;
             if ($orderProduct->save()) {
                 OrderLog::createLog($this->user->user_id, $id, 12, $recurringNext);
                 $this->redirect();
             } else {
                 return false;
             }
         } else {
             // failed, now what?
             return false;
         }
     }
     if (isset($_POST['discount_next_retries']) && $this->access->actionAccess('update')) {
         $discount = (int) AF::get($_POST, 'count_discount_next_retries');
         //$productID = (int) AF::get($_POST, 'product_id');
         if ($discount <= 0 || $discount > 100) {
             $this->redirect();
         }
         /*
         $orderModel=new Order();
         $orderModel->fillFromDbPk($id);
         */
         $orderModel = Order::model()->with('campaign')->findByPk($id);
         if ($orderModel) {
             $orderModel->amount_product = $orderModel->amount_product - $orderModel->amount_product * $discount / 100;
             $orderModel->model_uset_id = $this->user->user_id;
             if ($orderModel->save(false)) {
                 OrderLog::createLog($this->user->user_id, $id, 24, 'Discount ' . $discount . '%. New price ' . Currency::getSingPrice($orderModel->amount_product, $orderModel->campaign->currency_id));
             }
         }
         $this->redirect();
         /*
         $orderProduct=new OrderProduct();
         $orderProduct->order_id=$id;
         $orderProduct->product_id=$productID;
         //$orderProduct->fillFromDbPks(array('order_id'=>$id, 'product_id'=>$productID));
         
         $orderProduct->discount_next=$discount;
         if($orderProduct->tempUpdate())
         {
             OrderLog::createLog($this->user->user_id, $id, 24, 'Discount '.$discount.'%. New price '.$saveModel->amount_product);
         }
         */
         /*
         $orderModel = new Order();
         $orderModel->fillFromDbPk($id);
         $saveModel = new Order();
         $saveModel->order_id = $id;
         $saveModel->amount_product = $orderModel->amount_product - ($orderModel->amount_product*$discount/100);
         $saveModel->model_uset_id = $this->user->user_id;
         $saveModel->IsNewRecord = false;
         if($saveModel->save(false))
         {
             OrderLog::createLog($this->user->user_id, $id, 24, 'Discount '.$discount.'%. New price '.$saveModel->amount_product);
         }
         $this->redirect();
         */
     }
     if (isset($_POST['set_returned']) && $this->access->actionAccess('update')) {
         $reason = AF::get($_POST, 'returned_reason');
         if ($this->access->actionAccess('order_refund') && $reason) {
             $orderTempModel = new Order();
             $orderTempModel->fillFromDbPk($id);
             $saveModel = new Order();
             $saveModel->order_id = $id;
             $saveModel->returned = $reason;
             $saveModel->status = 'returned';
             $saveModel->model_uset_id = $this->user->user_id;
             $saveModel->IsNewRecord = false;
             $saveModel->save(false);
             // disable recurring to order products
             $orderProducts = OrderProducts::getProductsByOrderID($saveModel->order_id);
             foreach ($orderProducts as $orderProduct) {
                 $orderProduct->removeFlags('recurring');
                 $orderProduct->tempUpdate();
             }
             Event::setEvents($saveModel->order_id, 7);
             OrderLog::createLog($this->user->user_id, $id, 10, $reason);
         }
         $this->redirect();
     }
     if (isset($_POST['set_flags']) && $this->access->actionAccess('update')) {
         $flags = AF::get($_POST, 'flags', false);
         if (!$flags) {
             $flags = array();
         }
         $orderModel = new Order();
         $orderModel->fillFromDbPk($id);
         $orderModel->removeFlags(array('fraud', 'chargeback'));
         $orderModel->addFlags($flags);
         $orderModel->save(false);
         $customerModel = new Customer();
         $customerModel->fillFromDbPk($orderModel->customer_id);
         $customerModel->removeFlags('blacklisted');
         $customerModel->addFlags($flags);
         $customerModel->save(false);
         // Blacklisting must cancel all recurring
         if ($customerModel->isFlag('blacklisted') || $orderModel->isFlag('chargeback')) {
             Client::chargeBack($orderModel->customer_id);
         }
         OrderLog::createLog($this->user->user_id, $id, 11, implode(',', $flags));
         $this->redirect();
     }
     if (isset($_POST['set_recurring']) && $this->access->actionAccess('update')) {
         $productID = (int) AF::get($_POST, 'product_id');
         $isSet = (int) AF::get($_POST, 'is_set', 0);
         $orderProduct = OrderProduct::model()->find('order_id = :order_id AND product_id = :product_id', array(':order_id' => $id, ':product_id' => $productID));
         if ($isSet) {
             $orderProduct->addFlags('recurring');
             if (!$orderProduct->recurring_next) {
                 $updateDate = true;
             } else {
                 $date = new DateTime($orderProduct->recurring_next);
                 $updateDate = $date->getTimestamp() < time() ? true : false;
             }
             if ($updateDate) {
                 OrderProduct::updateRecurringNext($orderProduct->order_product_id);
             }
         } else {
             $orderProduct->removeFlags('recurring');
         }
         if ($orderProduct->save()) {
             OrderLog::createLog($this->user->user_id, $id, 4, $isSet ? 'yes' : 'no');
         }
         $this->redirect();
     }
     if (isset($_POST['stop_next_recurring']) && $this->access->actionAccess('update')) {
         $stopNextRecurring = AF::get($_POST, 'stop_next_recurring');
         $op_id = AF::get($_POST, 'order_product_id');
         $orderProduct = OrderProduct::model()->findByPk($op_id);
         if ($orderProduct->isFlag('recurring')) {
             if ($stopNextRecurring === '0' || $stopNextRecurring === '-1') {
                 if ($stopNextRecurring === '-1') {
                     $orderProduct->addFlags('stop_next_recurring');
                 } else {
                     $orderProduct->removeFlags('stop_next_recurring');
                 }
                 $orderProduct->save();
                 $notes = $stopNextRecurring === '0' ? 'no' : 'yes';
                 OrderLog::createLog($this->user->user_id, $id, 7, $notes);
             }
         }
         $this->redirect();
     }
     if (isset($_POST['cc_number']) && $this->access->actionAccess('update')) {
         $pacnetModel = new OrderPn();
         //$pacnetModel->fillFromDbPk($id);
         $pacnetModel->order_id = $id;
         $ccNumber = trim(AF::get($_POST, 'cc_number'));
         if ($ccNumber) {
             $pacnetModel->card_number = OrderPn::convertCreditCardNumberFormat($ccNumber);
             $arrayNote1 = unserialize(NoteBase64::decode($pacnetModel->note1));
             $arrayNote1['ccn'] = $ccNumber;
             $pacnetModel->note1 = NoteBase64::encode(serialize($arrayNote1));
             $pacnetModel->IsNewRecord = false;
             $pacnetModel->save(false);
             OrderLog::createLog($this->user->user_id, $id, 14, '**** **** **** ' . $pacnetModel->cc_number_last_four);
         }
         $this->redirect();
     }
     if (isset($_POST['set_recurring_next']) && $this->access->actionAccess('update')) {
         $productID = (int) AF::get($_POST, 'product_id');
         $recurringNext = AF::get($_POST, 'recurring_next');
         $orderProduct = new OrderProduct();
         $orderProduct->order_id = $id;
         $orderProduct->product_id = $productID;
         //$orderProduct->fillFromDbPks(array('order_id'=>$id, 'product_id'=>$productID));
         $orderProduct->recurring_next = $recurringNext;
         if ($orderProduct->tempUpdate()) {
             OrderLog::createLog($this->user->user_id, $id, 12, $recurringNext);
         }
         $this->redirect();
         /*
         $saveModel = new Order();
         $saveModel->order_id = $id;
         $saveModel->recurring_next = AF::get($_POST, 'recurring_next');
         
         if($saveModel->recurring_next)
         {
             $saveModel->model_uset_id = $this->user->user_id;
             $saveModel->IsNewRecord = false;
             $saveModel->save(false);
             OrderLog::createLog($this->user->user_id, $id, 12, $saveModel->recurring_next);
         }
         $this->redirect();
         */
     }
     $model = Order::model()->with('customer', 'campaign', 'affiliate', 'click', 'payment', 'gateway')->restrictions(array('campaign_id', 'aff_id'))->findByPk($id);
     if (!$model) {
         throw new AFHttpException(0, 'incorrect_id');
     }
     if (isset($_POST['amount_refunded']) && $this->access->actionAccess('update')) {
         $amount_refunded = AF::get($_POST, 'amount_refunded', 0);
         $model->refunded($amount_refunded);
         if (!$model->errors) {
             $jobModel = new Job();
             $jobModel->order_id = $model->order_id;
             $jobModel->job_type = 'refund';
             $jobModel->addNew();
             OrderLog::createLog($this->user->user_id, $id, 13, $amount_refunded);
         }
     }
     if (isset($_POST['set_discount_next']) && $this->access->actionAccess('update')) {
         $discount = (int) AF::get($_POST, 'discount_next');
         $productID = (int) AF::get($_POST, 'product_id');
         if ($discount <= 0 || $discount > 100) {
             $this->redirect();
         }
         $orderProduct = new OrderProduct();
         $orderProduct->order_id = $id;
         $orderProduct->product_id = $productID;
         $orderProduct->discount_next = $discount;
         if ($orderProduct->tempUpdate()) {
             OrderLog::createLog($this->user->user_id, $id, 6, $discount);
         }
         $this->redirect();
     }
     /*
     $infoPayment = array(
         'payment_type' => Payments::typeName($model->payment_type),
         'payment_method' => Payments::methodName($model->payment_type,$model->payment_method),
         //'payment_status' => $model->payment_status,
     );
     $addInfoPayment = array();
     if($model->payment_type == 'gc')
     {
         $addInfoPayment = array(
             'bank_code' => $model->bank_code,
             'issuer_id' => $model->issuer_id,
             'bank_name' => $model->bank_name,
             'bank_city' => $model->bank_city,
             'branch_code' => $model->branch_code,
             'checkdigit' => $model->checkdigit,
             'account_number' => $model->account_number,
             'account_holder' => $model->account_holder,
         );
     }
     		elseif($model->payment_type == 'pn')
     {
         $addInfoPayment = array(
             'cc_number' => '<span id="update_order_cc_number">'.$model->card_number.'</span> <a id="a_cc_update" href="javascript:AF.Orders.editCcNumber()"><i class="icon-edit"></i></a>',
             'ccv' => '<span id="update_order_cc_cvv">***</span> <a id="a_cvv_update" href="javascript:AF.Orders.editCcCvv()"><i class="icon-edit"></i></a>',
             'expiry_date' => '<span id="update_order_expiry_date">'.$model->expiry_date_formatted.'</span> <a id="a_expiry_date_update" href="javascript:AF.Orders.editExpiryDate()"><i class="icon-edit"></i></a>',
         );
     }
     $infoPayment = array_merge($infoPayment, $addInfoPayment);
     */
     /*
     $productModel = new Product();
     $productModel->fillFromDbPk($model->product_id);
     
     $recurringTotal = 0;
     
     if( $productModel->product_next_id && ($model->recurring === '0' || $model->recurring === '-1') )
     {
         $nextProductModel = new Product();
         $nextProductModel->fillFromDbPk($productModel->product_next_id);
         $shippingModel = new Shipping();
         $shippingModel->fillFromDbPk($model->shipping_id);
         $recurringTotal = ($nextProductModel->product_price + $shippingModel->amount_subscription);
         $recurringTotal =  number_format( ($recurringTotal - ($recurringTotal*$model->discount_next/100) ), 2);
     }
     
     $recurringTotal = Currency::getSingPrice($recurringTotal, $model->currency_id);
     */
     /*
     $nextProductModel = new Product();
     $nextProductModel->fillFromDbPk($productModel->product_next_id);
     */
     /*
     $msql=SafeMySQL::getInstance();
     $sql="SELECT c.*, a.*
             FROM `orders` as o
             JOIN `customers` as c USING (`customer_id`)
             JOIN `addresses` as a USING (`address_id`)
             WHERE o.`order_id`=?i";
     $allFields=$msql->getRow($sql, $model->order_id);
     fb($allFields);
     */
     $customerAddresses = Address::model()->getExistingAddresses($model->customer_id);
     $orderProducts = $model->getOrderProducts();
     $orderLogsModel = new OrderLog();
     $orderLogsModel->user_id = $this->user->user_id;
     $orderLogsModel->action = 3;
     $canVoid = $orderLogsModel->canVoid();
     $pagination = new Pagination(array('action' => $this->action, 'controller' => $this->controller, 'params' => $this->params));
     //$orderModels = AFActiveDataProvider::models('OrderLog', $this->params, $pagination);
     $orderModels = new OrderLogs('OrderLog');
     $dataProvider = $orderModels->getByOrderID($id);
     $maxAmountChargeback = 0;
     foreach ($dataProvider as $item) {
         if (in_array($item->action, array(29, 30)) && $item->amount) {
             $maxAmountChargeback += $item->amount;
         }
     }
     // we need to do some formatting here
     $paymentCRM = $model->payment->crmFormat();
     // grab attachment campaign info
     $attached = $model->getAttachedOrders();
     $model->user_id_updated = $this->user->user_id;
     $model->updated = 'NOW():sql';
     $modelAttempt = new Attempt();
     $modelAttempt->getLastOrderAttempt($model->order_id, Attempt::DEBIT_TYPE);
     //order children
     $orderChildren = Orders::getChildren($model->order_id);
     $this->addToPageTitle('Update Orders');
     Assets::js('jquery.form');
     Assets::css('jquery-ui');
     Assets::js('//code.jquery.com/ui/1.10.3/jquery-ui.js');
     Assets::js('dateRange/jquery.daterange');
     $this->render('update', array('model' => $model, 'paymentModel' => $paymentCRM, 'orderProducts' => $orderProducts, 'canVoid' => $canVoid, 'dataProvider' => $dataProvider, 'customerAddresses' => $customerAddresses, 'attached' => $attached, 'maxAmountChargeback' => $maxAmountChargeback, 'modelAttempt' => $modelAttempt, 'orderChildren' => $orderChildren));
 }
Beispiel #15
0
 /**
  * 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;
 }
 /**
  * Performs the work of inserting or updating the row in the database.
  *
  * If the object is new, it inserts it; otherwise an update is performed.
  * All related objects are also updated in this method.
  *
  * @param      ConnectionInterface $con
  * @return int             The number of rows affected by this insert/update and any referring fk objects' save() operations.
  * @throws PropelException
  * @see save()
  */
 protected function doSave(ConnectionInterface $con)
 {
     $affectedRows = 0;
     // initialize var to track total num of affected rows
     if (!$this->alreadyInSave) {
         $this->alreadyInSave = true;
         // We call the save method on the following object(s) if they
         // were passed to this object by their corresponding set
         // method.  This object relates to these object(s) by a
         // foreign key reference.
         if ($this->aOrderProduct !== null) {
             if ($this->aOrderProduct->isModified() || $this->aOrderProduct->isNew()) {
                 $affectedRows += $this->aOrderProduct->save($con);
             }
             $this->setOrderProduct($this->aOrderProduct);
         }
         if ($this->isNew() || $this->isModified()) {
             // persist changes
             if ($this->isNew()) {
                 $this->doInsert($con);
             } else {
                 $this->doUpdate($con);
             }
             $affectedRows += 1;
             $this->resetModified();
         }
         $this->alreadyInSave = false;
     }
     return $affectedRows;
 }