Esempio n. 1
0
 public function store()
 {
     try {
         $createOrder = Input::json()->all();
         $addOrder = new Order();
         $addOrder->status = 1;
         $addOrder->save();
         $addOrderId = $addOrder->id;
         $numberOfItems = 0;
         foreach ($createOrder['items'] as $OrderItem) {
             $newOrderItem = new Order_Item();
             $newOrderItem->order_id = $addOrderId;
             $newOrderItem->item_id = $OrderItem['item_id'];
             $newOrderItem->order_qty = $OrderItem['order_qty'];
             $newOrderItem->save();
             $numberOfItems = $numberOfItems + 1;
         }
         $addOrder->items = $createOrder['items'];
         $addOrder->open = 'yes';
         $vendorId = $createOrder['vendor_id'];
         $addOrder->vendor_id = $vendorId;
         $vendorName = Vendor::find($vendorId);
         $addOrder->vendor_name = $vendorName->name;
         $addOrder->item_count = $numberOfItems;
         $this->addOrderToEmail($addOrder);
         return $addOrder->toJson();
     } catch (Exception $e) {
         return '{"error":{"text":' . $e->getMessage() . '}}';
     }
 }
Esempio n. 2
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionIndex()
 {
     $model = new Order();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (empty(Yii::app()->user->id)) {
         throw new CHttpException(400, '您目前还没有登录请登录!');
         exit;
     }
     $email = Member::model()->findByAttributes(array('id' => Yii::app()->user->id));
     if (empty($email->email)) {
         throw new CHttpException(400, '您的个人资料里邮箱没有填写!');
         exit;
     }
     if ($email->email_validate == 0) {
         throw new CHttpException(400, '您的个人资料里邮箱没有验证!');
         //header("Location: ../member/update/".Yii::app()->user->id.".html");
     }
     if (isset($_POST['Order'])) {
         $model->attributes = $_POST['Order'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function actionEditCustomer($id)
 {
     $data = CJSON::decode(file_get_contents('php://input'));
     $customer = Customer::model()->findByPk($id);
     if (!$customer) {
         $response = array('success' => false, 'message' => 'Couldn\'t find customer with id = ' . $id);
         $this->renderJSON($response);
     }
     $orders = array();
     if (isset($data['orders'])) {
         $orders = $data['orders'];
         unset($data['orders']);
     }
     $customer->attributes = $data;
     $customer->save();
     if (count($orders)) {
         $ordersArray = array();
         foreach ($orders as $order) {
             $order = array('customer_id' => $id, 'posted_at' => $order['postedAt'], 'amount' => $order['amount'], 'paid_at' => $order['paidAt']);
             $orderModel = new Order();
             $orderModel->attributes = $order;
             $orderModel->save();
         }
     }
     $response = array('success' => true);
     $this->renderJSON($response);
 }
 /**
  * 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->aOrder !== null) {
             if ($this->aOrder->isModified() || $this->aOrder->isNew()) {
                 $affectedRows += $this->aOrder->save($con);
             }
             $this->setOrder($this->aOrder);
         }
         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;
 }
Esempio n. 5
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate($id)
 {
     if (!empty($id) && !Yii::app()->user->isGuest) {
         $customer_email = Yii::app()->user->name;
         $customerModel = Customer::model()->findByAttributes(array('customer_email' => $customer_email));
         $productId = $id;
         $productModel = Product::model()->findByPk($productId);
         $model = new Order();
         $model->order_product_id = $productModel->product_id;
         $model->order_customer_id = $customerModel->customer_id;
         $model->order_amount = $productModel->product_price + $productModel->product_shipping_price;
         if ($model->save()) {
             $attribuits = Order::model()->findByPk($model->order_id);
             $str = "Product Name:{$productModel->product_name}\r\n" . "Order Id:{$attribuits->order_id}\r\n" . "Order Product Id:{$attribuits->order_product_id}\r\n" . "Order Customer Id:{$attribuits->order_customer_id}\r\n" . "Total Amount With Shipping Charges:{$attribuits->order_amount}\r\n";
             $message = new YiiMailMessage();
             $message->subject = "Your order details";
             $message->setBody($str);
             $message->addTo(Yii::app()->user->name);
             $message->from = $customerModel->customer_email;
             Yii::app()->mail->send($message);
             $this->redirect(array('view', 'id' => $model->order_id));
         } else {
             echo "booking failed";
         }
     }
 }
Esempio n. 6
0
    public function testCreateOrderFromCart()
    {
        $cart_srl = 774;

		try
		{
			$cart = new Cart($cart_srl);
			$order = new Order($cart);
			$order->save();
			$order->saveCartProducts($cart);
		}
		catch(Exception $e)
		{
			$this->fail($e->getMessage());
		}


        $order_repository = new OrderRepository();
        $order = $order_repository->getOrderBySrl($order->order_srl);

        $this->assertEquals(count($cart->getProducts()), count($order->getProducts()));
        $this->assertEquals($cart->getShippingMethodName(), $order->shipping_method);
        $this->assertEquals($cart->getShippingCost(), $order->shipping_cost);
        $this->assertEquals($cart->getPaymentMethodName(), $order->payment_method);
        $this->assertEquals($cart->getTotal(), $order->total);
    }
 /**
  * Displays a particular model.
  * @param integer $id the ID of the model to be displayed
  */
 public function actionAdditem($item_id)
 {
     $user_id = Yii::app()->user->id;
     // find the users cart
     $user = User::model()->find(array('condition' => 'id=:user_id', 'params' => array(':user_id' => $user_id)));
     // find the users cart
     $cart = Cart::model()->find(array('condition' => 'cart_owner=:cart_owner', 'params' => array(':cart_owner' => $user_id)));
     // find the item being reffered to by item_id
     $item = Item::model()->find(array('condition' => 'id=:item_id', 'params' => array(':item_id' => $item_id)));
     if (is_null($cart)) {
         // if the cart is not found. create a cart for the user.
         $cart = new Cart();
         $cart->cart_owner = $user->id;
         $cart->save();
     }
     // check if the same order was already made & increment else, create new
     $order = Order::model()->find(array('condition' => 'item_id=:item_id AND cart_id=:cart_id AND order_by=:order_by', 'params' => array(':item_id' => $item_id, ':cart_id' => $cart->id, ':order_by' => $user->id)));
     if (is_null($order)) {
         $order = new Order();
         $order->create_time = time();
         $order->quantity = 1;
         $order->item_id = $item->id;
         $order->cart_id = $cart->id;
         $order->order_by = $user->id;
     } else {
         $order->quantity = 1 + $order->quantity;
         $order->update_time = time();
     }
     $order->save();
     // find all orders by this user.
     $orders = Order::model()->findAll('cart_id=:cart_id AND order_by=:order_by', array(':cart_id' => $cart->id, ':order_by' => $user->id));
     $return = array('success' => true, 'data' => $orders);
     echo CJavaScript::jsonEncode($return);
     Yii::app()->end();
 }
Esempio n. 8
0
 public function run()
 {
     $faker = Faker::create();
     $parking_lot = ParkingLot::all()->random();
     $car = Car::all()->random();
     $order = new Order();
     $order->parking_lot_id = $parking_lot->id;
     $order->car_id = $car->id;
     $order->stripe_customer_id = $faker->swiftBicNumber;
     $order->save();
     $parking_lot = ParkingLot::all()->random();
     $car = Car::all()->random();
     $order2 = new Order();
     $order2->parking_lot_id = $parking_lot->id;
     $order2->car_id = $car->id;
     $order2->stripe_customer_id = $faker->swiftBicNumber;
     $order2->save();
     $parking_lot = ParkingLot::all()->random();
     $car = Car::all()->random();
     $order3 = new Order();
     $order3->parking_lot_id = $parking_lot->id;
     $order3->car_id = $car->id;
     $order3->stripe_customer_id = $faker->swiftBicNumber;
     $order3->save();
 }
Esempio n. 9
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Order();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Order'])) {
         $model->attributes = $_POST['Order'];
         $model->id = F::get_order_id();
         $model->user_id = Yii::app()->user->id ? Yii::app()->user->id : '0';
         if ($model->save()) {
             $cart = Yii::app()->cart;
             $mycart = $cart->contents();
             foreach ($mycart as $mc) {
                 $OrderItem = new OrderItem();
                 $OrderItem->order_id = $model->order_id;
                 $OrderItem->item_id = $mc['id'];
                 $OrderItem->title = $mc['title'];
                 $OrderItem->pic_url = serialize($mc['pic_url']);
                 $OrderItem->sn = $mc['sn'];
                 $OrderItem->num = $mc['qty'];
                 $OrderItem->save();
             }
             $cart->destroy();
             $this->redirect(array('success'));
         }
     }
     //        $this->render('create', array(
     //            'model' => $model,
     //        ));
 }
Esempio n. 10
0
 public function actionOrder()
 {
     $categories = Category::getCategoriesList();
     if (!$categories) {
         $categories = array();
     }
     $name = '';
     $phone = '';
     $comment = '';
     $userName = '';
     $sessionProducts = Cart::getSessionProducts();
     if ($sessionProducts) {
         $productsIdsArray = array_keys($sessionProducts);
         $products = Product::getProductsByIds($productsIdsArray);
         $totalPrice = Cart::getTotalPrice($products);
         $totalProductCount = Cart::countProductsInCart();
     }
     if (isset($_POST['submit'])) {
         $name = FunctionLibrary::clearStr($_POST['name']);
         $phone = FunctionLibrary::clearStr($_POST['phone']);
         $comment = nl2br(FunctionLibrary::clearStr($_POST['comment']));
         $errors = array();
         if (!User::checkName($name)) {
             $errors[] = 'Имя не может быть пустым.';
         }
         if (!User::checkPhone($phone)) {
             $errors[] = 'Невалидный номер телефона.';
         }
         if (!User::checkName($comment)) {
             $errors[] = 'Комментарий не может быть пустым.';
         }
         if (empty($errors)) {
             if (User::isUser()) {
                 $email = User::isLogged();
                 $user = User::getUserByEmail($email);
                 $userId = htmlentities($user['id']);
             } else {
                 $userId = false;
             }
             $result = Order::save($name, $phone, $comment, $userId, $sessionProducts);
             if ($result) {
                 $_SESSION['message'] = 'Заказ оформлен!';
                 Cart::annul();
                 FunctionLibrary::redirectTo('/cart');
             }
         }
     } else {
         if (!$sessionProducts) {
             FunctionLibrary::redirectTo('/');
         }
         if (User::isUser()) {
             $email = User::isLogged();
             $user = User::getUserByEmail($email);
             $userName = htmlentities($user['name']);
         }
     }
     require_once ROOT . '/views/cart/order.php';
     return true;
 }
Esempio n. 11
0
 public function create($data, $save = true)
 {
     $order = new Order($this, $data);
     if ($save) {
         $order->save();
     }
     return $order;
 }
Esempio n. 12
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     $order = new Order();
     $order->pet_id = Input::get('pid');
     $order->user_id = Input::get('uid');
     $order->save();
     return Input::get('pet_id');
 }
 public function postAdd()
 {
     if (Input::get('item_val') == null or Input::get('item_val') == '') {
         return Redirect::back()->with(['message' => 'true', 'title' => 'Hata!', 'text' => 'Tanımsız hata ile karşılaşıldı.', 'type' => 'error']);
     }
     $order = new Order();
     $order->status = 1;
     $order->user = Auth::user()->id;
     $order->name = Input::get('name');
     $order->phone = Input::get('phone');
     $order->address = Input::get('address');
     $order->years = date('Y');
     $order->months = date('Y-m');
     $order->months_one = date('m');
     $order->days = date('Y-m-d');
     $order->days_one = date('d');
     $order->times = date('H:i:s');
     $order->save();
     if ($order->save()) {
         $items = Input::get('item_val');
         foreach ($items as $key => $item) {
             if (!OrderToProduct::where('order_id', $order->id)->where('product_id', $key)->get()) {
                 $result = false;
             } else {
                 $ord = new OrderToProduct();
                 $ord->order_id = $order->id;
                 $ord->product_id = $key;
                 $ord->number = $item;
                 $ord->save();
                 if ($ord->save()) {
                     $result = true;
                 } else {
                     $result = false;
                 }
             }
         }
         if ($result) {
             return Redirect::to('order')->with(['message' => 'true', 'title' => 'Tebrikler!', 'text' => 'Sipariş başarıyla oluşturuldu.', 'type' => 'success']);
         } else {
             return Redirect::back()->with(['message' => 'true', 'title' => 'Hata!', 'text' => 'Sipariş oluşturulamadı.', 'type' => 'error']);
         }
     } else {
         return Redirect::back()->with(['message' => 'true', 'title' => 'Hata!', 'text' => 'Sipariş oluşturulamadı.', 'type' => 'error']);
     }
 }
Esempio n. 14
0
 public static function submitOrder($product, $member)
 {
     $order = new Order();
     $order->product()->associate($product);
     $order->order_date = date('Y-m-d');
     $order->customer_name = $member->name;
     $order->customer_number = $member->membership_no;
     $order->save();
 }
Esempio n. 15
0
 public static function createOrder($email, $name, $invitees)
 {
     $userId = UserPeer::getUserIdForOrder($email);
     $order = new Order();
     $order->setName($name);
     $order->setTimeOpen(time());
     $order->setUserId($userId);
     return $order->save();
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     //
     $order = new Order();
     $order->cliente = 'Stefano';
     $order->indirizzo = 'via Verdi, 15';
     $order->totale = '15';
     $order->save();
 }
Esempio n. 17
0
 /**
  * postCheckOut
  */
 public function postCheckOut()
 {
     $customer = Input::get('customer');
     $customer = Customer::find($customer);
     $customer_address = CustomerReceivedAddress::where('customer_id', $customer->id)->where('default', 1)->first();
     //订单编号
     $orderno = OrderGeneration::where('customer_no', $customer->customer_no)->where('used', 0)->first();
     if (!$orderno) {
         foreach (range(1001, 9998) as $index) {
             if ($index == 1111 || $index == 2222 || $index == 3333 || $index == 4444 || $index == 5555 || $index == 6666 || $index == 7777 || $index == 8888) {
                 continue;
             }
             OrderGeneration::create(['customer_no' => $customer->customer_no, 'order_no' => $index, 'used' => 0]);
         }
         $order_no = $index;
         $no = $order_no . $customer->customer_no;
     } else {
         $order_no = $orderno->order_no;
         $no = $order_no . $customer->customer_no;
     }
     $order = new Order();
     $order->no = $no;
     $order->customer_id = $customer->id;
     $order->customer_address_id = $customer_address->id;
     $order->payment_method_id = 1;
     $order->shipping_method_id = 1;
     $order->order_status = 'order_price_confirmed';
     $order->item_fee = 0.0;
     $order->shipping_fee = 0;
     $order->amount_fee = 0.0;
     $order->point_fee = 0;
     $order->credit_fee = 0;
     $order->pay_fee = 0.0;
     $order->caution_money = 0;
     $order->save();
     $ordergeneration = OrderGeneration::where('order_no', $order_no)->where('customer_no', $customer->customer_no)->first();
     $ordergeneration->used = 1;
     $ordergeneration->save();
     //orderdetail
     $carts = Cart::where('customer_id', $customer->id)->get();
     $sum = 0;
     foreach ($carts as $cart) {
         $total = 0;
         if ($cart->confirm_price == 0.0) {
             $cart->confirm_price = $cart->item->price_market;
         }
         OrderDetail::create(['order_id' => $order->id, 'item_id' => $cart->item_id, 'craft_description' => $cart->craft_description, 'quantity' => $cart->quantity, 'confirm_price' => $cart->confirm_price, 'confirm_quantity' => 0, 'delivery_quantity' => 0]);
         $total = $cart->confirm_price * $cart->quantity;
         $sum += $total;
     }
     $order = Order::find($order->id);
     $order->item_fee = $sum;
     $order->save();
     //查看订单详细页面
     return Redirect::to('admin/orders');
 }
Esempio n. 18
0
 public function postAdd()
 {
     $rules = ['firstname' => 'required|min:2', 'lastname' => 'required|min:2', 'address' => 'required|min:5', 'phone' => 'required|min:7'];
     if (!Auth::check()) {
         array_push($rules, ['email' => 'required|email|unique:users']);
     }
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::to("checkout")->withErrors($validator)->withInput(Input::except(''));
     } else {
         if (Auth::check()) {
             $user = User::find(Auth::user()->id);
         } else {
             $user = new User();
             $user->email = Input::get('email');
             $password = str_random(10);
             $user->password = Hash::make($password);
         }
         $user->firstname = Input::get('firstname');
         $user->lastname = Input::get('lastname');
         $user->address = Input::get('address');
         $user->phone = Input::get('phone');
         if ($user->save()) {
             $role = Role::where('name', '=', 'Customer')->first();
             if (!$user->hasRole("Customer")) {
                 $user->roles()->attach($role->id);
             }
             $order = new Order();
             $order->user_id = $user->id;
             $order->status_id = OrderStatus::where('title', '=', 'Новый')->first()->id;
             $order->comment = 'Телефон: <b>' . $user->phone . '</b><br>Адрес: <b>' . $user->address . '</b><br>Комментарий покупателя: ' . '<i>' . Input::get('comment') . '</i>';
             if ($order->save()) {
                 $cart = Cart::content();
                 foreach ($cart as $product) {
                     $orderDetails = new OrderDetails();
                     $orderDetails->order_id = $order->id;
                     $orderDetails->product_id = $product->id;
                     $orderDetails->quantity = $product->qty;
                     $orderDetails->price = $product->price;
                     $orderDetails->save();
                 }
             }
             if (!Auth::check()) {
                 Mail::send('mail.registration', ['firstname' => $user->firstname, 'login' => $user->email, 'password' => $password, 'setting' => Config::get('setting')], function ($message) {
                     $message->to(Input::get('email'))->subject("Регистрация прошла успешно");
                 });
             }
             $orderId = $order->id;
             Mail::send('mail.order', ['cart' => $cart, 'order' => $order, 'phone' => $user->phone, 'user' => $user->firstname . ' ' . $user->lastname], function ($message) use($orderId) {
                 $message->to(Input::get('email'))->subject("Ваша заявка №{$orderId} принята");
             });
             Cart::destroy();
             return Redirect::to("checkout/thanks/spasibo-vash-zakaz-prinyat")->with('successcart', 'ok', ['cart' => $cart]);
         }
     }
 }
Esempio n. 19
0
 public function actionOkpay()
 {
     $model = new OkPayForm();
     if (isset($_POST['ok_txn_status']) && $_POST['ok_txn_status'] == 'completed') {
         $request = 'ok_verify=true';
         $get = $_POST;
         foreach ($_POST as $key => $value) {
             $value = urlencode(stripslashes($value));
             $request .= "&{$key}={$value}";
         }
         $result = file_get_contents('https://www.okpay.com/ipn-verify.html?' . $request);
         if ($result == 'VERIFIED') {
             $json = json_encode($get);
             $order = new Order();
             $order->date = date('Y-m-d H:i:s');
             $order->json = $json;
             $order->save();
         } elseif ($result == 'INVALID') {
             echo 'invalid';
         } elseif ($result == 'TEST') {
             $json = json_encode($get);
             $order = new Order();
             $order->date = date('Y-m-d');
             $order->json = $json;
             $order->save();
         } else {
             header("HTTP/1.0 404 Not Found");
             Yii::app()->end;
         }
     }
     echo '0<br>';
     if (isset($_POST['OkPayForm'])) {
         $model->attributes = $_POST['OkPayForm'];
         echo '1<br>';
         if ($model->validate()) {
             echo '2<br>';
             $balance = Yii::app()->OkPay->getBalance();
             var_dump($balance);
             echo '<br>';
             echo '<br>';
             var_dump(Yii::app()->OkPay->account_check($model->purse));
             if (Yii::app()->OkPay->account_check($model->purse) && $balance[$model->currency] >= $model->sum) {
                 if (Yii::app()->OkPay->transfer($model->purse, $model->sum, $model->currency, null, true)) {
                     Yii::app()->user->setFlash('okpay-status', 'Confirmed');
                 } else {
                     Yii::app()->user->setFlash('okpay-status', 'Error');
                 }
             } else {
                 Yii::app()->user->setFlash('okpay-status', 'Error');
             }
         }
         //$this->refresh();
     }
     $this->render('okpay', array('purse' => 'OK856052983', 'model' => $model));
 }
 public function processPayment()
 {
     $v = Validator::make(["amount" => Input::get("amount"), "email" => Input::get("email")], ["amount" => "required|integer", "email" => "required|email"]);
     if ($v->passes()) {
         $billing = new Billing();
         $billing->name = Input::get("name");
         $billing->address = Input::get("address");
         $billing->city = Input::get("city");
         $billing->state = Input::get("state");
         $billing->zip = Input::get("zip");
         $billing->email = Input::get("email");
         $billing->phone = Input::get("phone");
         $billing->save();
         $order = new Order();
         $order->amount = Input::get("amount");
         $order->billing_id = $billing->id;
         $order->save();
         $bitcoinRedirectURL = URL::to("/");
         if (Input::get('type') == "bitpay") {
             try {
                 $bitpayResponse = $this->bitpayRequestCurl($order->id, $order->amount, $billing);
             } catch (\Exception $e) {
                 Session::flash("error_msg", $e->getMessage());
                 return Redirect::back();
             }
             //Set order status to pending since user didnt paid yet and serialize the response maybe useful later
             $order->type = "bitpay";
             $order->status = "Pending";
             $order->response = serialize($bitpayResponse);
             $bitcoinRedirectURL = $bitpayResponse->url;
         }
         if (Input::get('type') == "coinbase") {
             try {
                 $coinbaseResponse = $this->coinbaseRequestCurl($order->id, $order->amount);
             } catch (\Exception $e) {
                 Session::flash("error_msg", $e->getMessage());
                 return Redirect::back();
             }
             $order->type = "coinbase";
             $order->status = "Pending";
             $order->response = serialize($coinbaseResponse);
             $bitcoinRedirectURL = "https://www.coinbase.com/checkouts/" . $coinbaseResponse->button->code;
         }
         return Redirect::to($bitcoinRedirectURL);
     } else {
         $response = "";
         $messages = $v->messages()->all();
         foreach ($messages as $message) {
             $response .= "<li style='margin-left:10px;'>{$message}</li>";
         }
         Session::flash("error_msg", $response);
         return Redirect::back()->withInput();
     }
 }
Esempio n. 21
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Order();
     if (isset($_POST['Order'])) {
         $model->attributes = $_POST['Order'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Esempio n. 22
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     $user = User::find(Auth::user()->id);
     $order = new Order();
     $order->user()->associate($user);
     $order->status = 'unconfirmed';
     if (Auth::user()->role == "cashier") {
         $order->mode = "in-store";
     }
     $order->save();
     return Redirect::to('/pizza/create')->with('order', $order->order_id);
 }
Esempio n. 23
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Order();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     //        print_r($_POST);
     //        exit;
     if (!$_POST['delivery_address']) {
         echo '<script>alert("您还没有添加收货地址!")</script>';
         echo '<script type="text/javascript">history.go(-1)</script>';
         die;
     } else {
         if (isset($_POST)) {
             $model->attributes = $_POST;
             $model->order_id = F::get_order_id();
             $model->user_id = Yii::app()->user->id ? Yii::app()->user->id : '0';
             $model->create_time = time();
             $cri = new CDbCriteria(array('condition' => 'contact_id =' . $_POST['delivery_address'] . ' AND user_id = ' . Yii::app()->user->id));
             $address = AddressResult::model()->find($cri);
             $model->receiver_name = $address->contact_name;
             $model->receiver_country = $address->country;
             $model->receiver_state = $address->state;
             $model->receiver_city = $address->city;
             $model->receiver_district = $address->district;
             $model->receiver_address = $address->address;
             $model->receiver_zip = $address->zipcode;
             $model->receiver_mobile = $address->mobile_phone;
             $model->receiver_phone = $address->phone;
             if ($model->save()) {
                 $cart = Yii::app()->cart;
                 $mycart = $cart->contents();
                 foreach ($mycart as $mc) {
                     $OrderItem = new OrderItem();
                     $OrderItem->order_id = $model->order_id;
                     $OrderItem->item_id = $mc['id'];
                     $OrderItem->title = $mc['title'];
                     $OrderItem->pic_url = serialize($mc['pic_url']);
                     $OrderItem->sn = $mc['sn'];
                     $OrderItem->num = $mc['qty'];
                     $OrderItem->price = $mc['price'];
                     $OrderItem->amount = $mc['subtotal'];
                     $OrderItem->save();
                 }
                 $cart->destroy();
                 $this->redirect(array('success'));
             }
         }
     }
     //        $this->render('create', array(
     //            'model' => $model,
     //        ));
 }
Esempio n. 24
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Order();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Order'])) {
         $model->attributes = $_POST['Order'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->idorder));
         }
     }
     $this->render('create', array('model' => $model));
 }
Esempio n. 25
0
 private function createOrderAndSaveIt()
 {
     $this->deleteCityOrder();
     $order = new Order();
     $order->userId = Yii::app()->user->id;
     $order->name = $this->name;
     if (!$order->save()) {
         $errMsg = "Could not save named order to database" . PHP_EOL . CVarDumper::dumpAsString($order->getErrors());
         $this->logAndThrowException($errMsg, 'TripStorage.createOrderAndSaveIt');
         return $order;
     }
     return $order;
 }
Esempio n. 26
0
 public function actionCreate($user_id)
 {
     $model = new Order();
     $model->user_id = $user_id;
     $item = new Item();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model)
     if (isset($_POST['Order']) && isset($_POST['Sku'])) {
         $transaction = $model->dbConnection->beginTransaction();
         try {
             $model->attributes = $_POST['Order'];
             $model->order_id = F::get_order_id();
             $model->create_time = time();
             if ($model->save()) {
                 foreach ($_POST['Sku']['item_id'] as $key => $itemId) {
                     $items = Item::model()->findByPk($itemId);
                     $sku = Sku::model()->findByPk($_POST['Sku']['sku_id'][$key]);
                     if ($sku->stock < $_POST['Item-number'][$key]) {
                         throw new CException('Stock is not enough' . json_encode($sku->getErrors()), 0);
                     }
                     $orderItem = new OrderItem();
                     $orderItem->item_id = $itemId;
                     $orderItem->title = $items->title;
                     $orderItem->desc = $items->desc;
                     $orderItem->pic = $items->getMainPic();
                     $orderItem->props_name = $sku->props_name;
                     $orderItem->price = $sku->price;
                     $orderItem->quantity = $_POST['Item-number'][$key];
                     //need to update
                     $sku->stock -= $_POST['Item-number'][$key];
                     if (!$sku->save()) {
                         throw new Exception('Cut down stock fail');
                     }
                     $orderItem->total_price = $orderItem->price * $orderItem->quantity;
                     $orderItem->order_id = $model->order_id;
                     //                        var_dump($orderItem->save());die;
                     if (!$orderItem->save()) {
                         throw new Exception('save order item fail');
                     }
                 }
             } else {
                 throw new Exception('save order fail');
             }
             $transaction->commit();
             $this->redirect(array('view', 'id' => $model->order_id));
         } catch (Exception $e) {
             $transaction->rollBack();
         }
     }
     $this->render('create', array('model' => $model, 'Item' => $item));
 }
 /**
  * MAKE AN ORDER: ORDER , DETAILED ORDER
  */
 public function actionMakeOrder($ridString)
 {
     $uid = Yii::app()->user->id;
     $curUser = User::Model()->findByPk($uid);
     $userType = $curUser->type;
     $ridStrArray = explode(".", $ridString);
     $count = count($ridStrArray);
     $ridArray = array();
     $resArray = array();
     $productArray = array();
     $total = 0;
     for ($i = 0; $i < $count; $i++) {
         $ridArray[] = (int) $ridStrArray[$i];
         $resArray[] = Res::Model()->findByPk($ridArray[$i]);
         $productArray[] = Product::Model()->findByPk($resArray[$i]->pid);
         $total = $total + $productArray[$i]->price * $resArray[$i]->amount;
         //update the status of cart
         $resArray[$i]->status = 2;
         $resArray[$i]->save();
         // update the amount in the product
         $productArray[$i]->amount = $productArray[$i]->amount - $resArray[$i]->amount;
         $productArray[$i]->save();
     }
     switch ($userType) {
         case 1:
             $total = $total * 0.9;
             break;
         case 2:
             $total = $total * 0.85;
             break;
         case 3:
             $total = $total * 0.75;
             break;
         default:
             # code...
             break;
     }
     $order = new Order();
     $order->total = $total;
     $order->save();
     $oid = $order->oid;
     for ($i = 0; $i < $count; $i++) {
         $dorder = new Dorder();
         $dorder->oid = $oid;
         $dorder->pid = $productArray[$i]->pid;
         $dorder->amount = $resArray[$i]->amount;
         $dorder->save();
     }
 }
Esempio n. 28
0
 public function actionCreate()
 {
     $model = new Order();
     if (isset($_POST['Order'])) {
         $model->setAttributes($_POST['Order']);
         if ($model->save()) {
             if (Yii::app()->getRequest()->getIsAjaxRequest()) {
                 Yii::app()->end();
             } else {
                 $this->redirect(array('admin'));
             }
         }
     }
     $this->render('create', array('model' => $model));
 }
Esempio n. 29
0
 /**
  * 添加订单
  * 请求类型:POST
  */
 public function addOrder()
 {
     $user = Auth::user();
     $rules = array('shop_id' => 'required | integer | exists:shop,id', 'front_user_id' => 'required | integer | exists:front_user,front_uid', 'total' => 'required | integer | between:1,20', 'order_menus' => 'required | max:255', 'total_pay' => 'required | numeric', 'dispatch' => 'numeric', 'beta' => 'max:255', 'receive_address' => 'required | max:255');
     $record = array('shop_id' => Input::get('shop_id'), 'front_user_id' => $user->front_uid, 'ordertime' => time(), 'total' => Input::get('total'), 'order_menus' => Input::get('order_menus'), 'total_pay' => Input::get('total_pay'), 'dispatch' => Input::get('dispatch') == NULL ? 0 : Input::get('dispatch'), 'beta' => Input::get('beta'), 'receive_address' => Input::get('receive_address'));
     $v = Validator::make($record, $rules);
     if ($v->fails()) {
         $message = $v->messages();
         return json_encode(array('success' => false, 'state' => 400, 'errMsg' => $message->toArray(), 'no' => 1));
     }
     $order = new Order($record);
     if ($order->save()) {
         return json_encode(array('success' => true, 'state' => 200, 'errMsg' => 'finished', 'no' => 0));
     }
 }
Esempio n. 30
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');
 }