Exemplo n.º 1
0
 /**
  * 添加商品到购物车
  * @param $request
  */
 public function addToCart($userId, $request)
 {
     if (empty($request) || empty($request)) {
         throw new exception('传输数据错误,请重试');
     }
     if ($request['type'] == 'product') {
         $pInfo = Product::model()->findByPk($request['id']);
         //商品详情
     } elseif ($request['type'] == 'tab') {
         $pInfo = Tab::model()->findByPk($request['id']);
     } elseif ($request['type'] == 'zine') {
         $pInfo = Zine::model()->findByPk($request['id']);
     }
     //校验数量和所选尺寸等信息
     //查找购物车里面的商品
     $map = array();
     $map['user_id'] = $userId;
     $map['product_id'] = $request['id'];
     $map['size_id'] = $request['size'];
     $map['type'] = $this->product_type[$request['type']];
     $cartInfo = Cart::model()->findByAttributes($map);
     $this->addToCartBeforeCheck($request, $pInfo, $cartInfo);
     $time = time();
     if (empty($cartInfo)) {
         $cartInfo = new Cart();
         $cartInfo->user_id = $userId;
         $cartInfo->product_id = $request['id'];
         $cartInfo->type = $this->product_type[$request['type']];
         $cartInfo->size_id = $request['size'];
         $cartInfo->shop_price = $pInfo['sell_price'];
         $cartInfo->sell_price = $pInfo['sell_price'];
         $cartInfo->quantity = $request['num'];
         $cartInfo->add_time = $time;
         $cartInfo->update_time = $time;
         $cartInfo->is_pay = isset($request['buynow']) && !empty($request['buynow']) ? 1 : 0;
         $flag = $cartInfo->save();
     } else {
         //若立即购买的P在购物车中已经存在
         $cartInfo->shop_price = $pInfo['sell_price'];
         $cartInfo->sell_price = $pInfo['sell_price'];
         $cartInfo->quantity += $request['num'];
         $cartInfo->is_pay = isset($request['buynow']) && !empty($request['buynow']) ? 1 : 0;
         $cartInfo->update_time = $time;
         $flag = $cartInfo->save();
     }
     if (empty($flag)) {
         throw new exception('添加购物车失败,请重试!');
     }
     return true;
 }
Exemplo n.º 2
0
 /**
  * Update context after customer login
  * @param Customer $customer Created customer
  */
 public function updateCustomer(Customer $customer)
 {
     $this->customer = $customer;
     $this->cookie->id_customer = (int) $customer->id;
     $this->cookie->customer_lastname = $customer->lastname;
     $this->cookie->customer_firstname = $customer->firstname;
     $this->cookie->passwd = $customer->passwd;
     $this->cookie->logged = 1;
     $customer->logged = 1;
     $this->cookie->email = $customer->email;
     $this->cookie->is_guest = $customer->isGuest();
     $this->cart->secure_key = $customer->secure_key;
     if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->cookie->id_cart) || Cart::getNbProducts($this->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->customer->id))) {
         $this->cart = new Cart($id_cart);
     } else {
         $id_carrier = (int) $this->cart->id_carrier;
         $this->cart->id_carrier = 0;
         $this->cart->setDeliveryOption(null);
         $this->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id);
         $this->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id);
     }
     $this->cart->id_customer = (int) $customer->id;
     if (isset($id_carrier) && $id_carrier) {
         $delivery_option = [$this->cart->id_address_delivery => $id_carrier . ','];
         $this->cart->setDeliveryOption($delivery_option);
     }
     $this->cart->save();
     $this->cookie->id_cart = (int) $this->cart->id;
     $this->cookie->write();
     $this->cart->autosetProductAddress();
 }
Exemplo n.º 3
0
 /**
  * trigger login after
  * @param $logged_info
  */
 function triggerLoginAfter($logged_info)
 {
     $cartRepo = new CartRepository();
     if ($this->cartBeforeLogin instanceof Cart) {
         if ($memberCart = $cartRepo->getCart($this->module_info->module_srl, NULL, $logged_info->member_srl, session_id()))
         {
             if ($memberCart->cart_srl != $this->cartBeforeLogin->cart_srl) {
                 $memberCart->merge($this->cartBeforeLogin);
             }
             Context::set('cart', $memberCart);
         } else {
             $this->cartBeforeLogin->member_srl = $logged_info->member_srl;
             $this->cartBeforeLogin->save();
         }
     }
 }
 public function setPhpCookieData()
 {
     if (!isset($_COOKIE['id_guest'])) {
         if (!isset($this->context->cookie->id_guest)) {
             Guest::setNewGuest($this->context->cookie);
         }
         setcookie('id_guest', $this->context->cookie->id_guest, time() + 86400, "/");
     } else {
         $this->context->cookie->id_guest = $_COOKIE['id_guest'];
         setcookie('id_guest', $this->context->cookie->id_guest, time() + 86400, "/");
     }
     $guest = new Guest($this->context->cookie->id_guest);
     if (!isset($_COOKIE['id_cart']) && !isset($this->context->cart->id)) {
         $cart = new Cart();
         $cart->recyclable = 0;
         $cart->gift = 0;
         $cart->id_shop = (int) $this->context->shop->id;
         $cart->id_lang = ($id_lang = (int) Tools::getValue('id_lang')) ? $id_lang : Configuration::get('PS_LANG_DEFAULT');
         $cart->id_currency = ($id_currency = (int) Tools::getValue('id_currency')) ? $id_currency : Configuration::get('PS_CURRENCY_DEFAULT');
         $cart->id_address_delivery = 0;
         $cart->id_address_invoice = 0;
         $cart->id_currency = Configuration::get('PS_CURRENCY_DEFAULT');
         $cart->id_guest = (int) $this->context->cookie->id_guest;
         $cart->setNoMultishipping();
         $cart->save();
         $this->context->cart = $cart;
         $this->context->cookie->id_cart = $cart->id;
         setcookie('id_cart', $cart->id, time() + 86400, "/");
     } else {
         $cart = new Cart((int) $_COOKIE['id_cart']);
         $this->context->cart = $cart;
         $this->context->cookie->id_cart = $cart->id;
         setcookie('id_cart', $cart->id, time() + 86400, "/");
     }
     $customer = new Customer();
     $customer->id_gender = 0;
     $customer->id_default_group = 1;
     $customer->outstanding_allow_amount = 0;
     $customer->show_public_prices = 0;
     $customer->max_payment_days = 0;
     $customer->active = 1;
     $customer->is_guest = 0;
     $customer->deleted = 0;
     $customer->logged = 0;
     $customer->id_guest = $this->context->cookie->id_guest;
     $this->context->customer = $customer;
 }
Exemplo n.º 5
0
 public function add()
 {
     $validator = Validator::make(Input::all(), Cart::$rules);
     if ($validator->passes() == true) {
         $key = 'kiobostha?kiobos';
         $price = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode(Input::get('price')), MCRYPT_MODE_ECB));
         $cart = new Cart();
         $cart->invoice = uniqid(rand());
         $cart->user_id = Auth::user()->id;
         $cart->product_id = Input::get('id');
         $cart->quantity = Input::get('quantity');
         $cart->price = Input::get('quantity') * $price;
         $cart->catagory_id = Input::get('catagory');
         if ($cart->save()) {
             return Redirect::back()->with('event', '<p class="alert alert-success"><span class="glyphicon glyphicon-ok"></span> Successfully added to cart</p>');
         }
         return Redirect::back()->with('event', '<p class="alert alert-danger"><span class="glyphicon glyphicon-remove"></span> Error occured. Please try after again.</p>');
     }
     return Redirect::back()->withErrors($validator)->withInput();
 }
Exemplo n.º 6
0
	/**
	 * Test that an empty cart has 0 products
	 */
	public function testEmptyCart()
	{
		$cart = new Cart();
		$cart->module_srl = 123;
		$cart->save();

		$this->assertEquals(0, count($cart->getProducts()));
	}
if ($oldcart->id) {
    $oldcart->id_customer = $customer->id;
    if ($oldcart->id_address_delivery <= 0 or !in_array($txn_type, $recurring_txn_types)) {
        $oldcart->id_address_delivery = $address->id;
        $delivery_option[(int) $oldcart->id_address_delivery] = $oldcart->id_carrier . ",";
        $oldcart->delivery_option = serialize($delivery_option);
    }
    if ($oldcart->id_address_invoice <= 0 or !in_array($txn_type, $recurring_txn_types)) {
        $oldcart->id_address_invoice = $address->id;
    }
    $paid_currency_id = intval(Currency::getIdByIsoCode($_POST['mc_currency']));
    if (isset($paid_currency_id) and $paid_currency_id > 0) {
        $oldcart->id_currency = $paid_currency_id;
    }
    $oldcart->secure_key = $customer->secure_key;
    $oldcart->save();
    Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'cart_product SET id_address_delivery = ' . (int) $oldcart->id_address_delivery . ' WHERE id_cart=' . (int) $oldcart->id);
}
$cookie->id_customer = intval($customer->id);
$cookie->customer_lastname = $customer->lastname;
$cookie->customer_firstname = $customer->firstname;
$cookie->passwd = $customer->passwd;
$cookie->logged = 1;
$cookie->email = $customer->email;
$cookie->id_lang = $oldcart->id_lang;
$cookie->id_cart = $oldcart->id;
if ($result == 'VERIFIED') {
    if (!isset($_POST['mc_gross'])) {
        $errors .= $paypal->getL('mc_gross') . '<br />';
    }
    if (!isset($_POST['payment_status'])) {
Exemplo n.º 8
0
 /**
  * This function will run parse an order that we get from Amazon MWS.
  * It saves orders of the customers to the DB.
  * @param $response ListOrderItemsResponse Contains the orders from Amazon
  * Marketplace WebService
  * @return void
  */
 public function parseListOrders($response)
 {
     $checkDate = date("Y-m-d", strtotime($this->amazon_check_time));
     $listOrdersResult = $response->getListOrdersResult();
     if ($listOrdersResult->isSetOrders()) {
         $orders = $listOrdersResult->getOrders();
         $orderList = $orders->getOrder();
         foreach ($orderList as $order) {
             if ($order->isSetAmazonOrderId()) {
                 $strOrderId = $order->getAmazonOrderId();
                 Yii::log("Found Amazon Order " . $strOrderId, 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                 $objCart = Cart::LoadByIdStr($strOrderId);
                 if (!$objCart instanceof Cart) {
                     //We ignore orders we've already downloaded
                     $objCart = new Cart();
                     $objCart->id_str = $strOrderId;
                     $objCart->origin = 'amazon';
                     //We mark this as just a cart, not an order, because we download the items next
                     $objCart->cart_type = CartType::cart;
                     $objOrderTotal = $order->getOrderTotal();
                     Yii::log("Order total information " . print_r($objOrderTotal, true), 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                     $objCart->total = $objOrderTotal->getAmount();
                     $objCart->currency = $objOrderTotal->getCurrencyCode();
                     $objCart->status = OrderStatus::Requested;
                     $objCart->datetime_cre = $order->getPurchaseDate();
                     $objCart->modified = $order->getLastUpdateDate();
                     if (!$objCart->save()) {
                         Yii::log("Error saving cart " . print_r($objCart->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                     }
                     //Since email from is Anonymous, we probably will have to create a shell record
                     $objCustomer = Customer::LoadByEmail($order->getBuyerEmail());
                     if (!$objCustomer) {
                         $customerName = $this->_getCustomerName($order->getBuyerName());
                         $objCustomer = new Customer();
                         $objCustomer->email = $order->getBuyerEmail();
                         $objCustomer->first_name = $customerName['first_name'];
                         $objCustomer->last_name = $customerName['last_name'];
                         $objCustomer->record_type = Customer::EXTERNAL_SHELL_ACCOUNT;
                         $objCustomer->allow_login = Customer::UNAPPROVED_USER;
                         $objCustomer->save();
                     }
                     $objCart->customer_id = $objCustomer->id;
                     if (!$objCart->save()) {
                         Yii::log("Error saving cart " . print_r($objCart->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                     }
                     if ($order->isSetShippingAddress()) {
                         $shippingAddress = $order->getShippingAddress();
                         $countrycode = Country::IdByCode($shippingAddress->getCountryCode());
                         if ($shippingAddress->isSetStateOrRegion()) {
                             $objState = State::LoadByCode($shippingAddress->getStateOrRegion(), $countrycode);
                         }
                         $customerName = $this->_getCustomerName($shippingAddress->getName());
                         $config = array('address_label' => 'amazon', 'customer_id' => $objCustomer->id, 'first_name' => $customerName['first_name'], 'last_name' => $customerName['last_name'], 'address1' => $shippingAddress->getAddressLine1(), 'address2' => trim($shippingAddress->getAddressLine2() . " " . $shippingAddress->getAddressLine3()), 'city' => $shippingAddress->getCity(), 'state_id' => $objState->id, 'postal' => $shippingAddress->getPostalCode(), 'country_id' => $countrycode, 'phone' => $shippingAddress->getPhone());
                         $objCustAddress = CustomerAddress::findOrCreate($config);
                         $objCustomer->default_billing_id = $objCustAddress->id;
                         $objCustomer->default_shipping_id = $objCustAddress->id;
                         $objCustomer->save();
                         $objCart->shipaddress_id = $objCustAddress->id;
                         $objCart->billaddress_id = $objCustAddress->id;
                         //Amazon doesn't provide billing data, just dupe
                         if (!$objCart->save()) {
                             Yii::log("Error saving cart " . print_r($objCart->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                         }
                         Yii::log("Looking for destination " . $objState->country_code . " " . $objState->code . " " . $shippingAddress->getPostalCode(), 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                         $objDestination = Destination::LoadMatching($objState->country_code, $objState->code, $shippingAddress->getPostalCode());
                         if ($objDestination === null) {
                             Yii::log("Did not find destination, using default in Web Store ", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                             $objDestination = Destination::getAnyAny();
                         }
                         $objCart->tax_code_id = $objDestination->taxcode;
                         $objCart->recalculateAndSave();
                     }
                     if ($order->isSetShipServiceLevel()) {
                         $strShip = $order->getShipServiceLevel();
                         //If we have a shipping object already, update it, otherwise create it
                         if (isset($objCart->shipping)) {
                             $objShipping = $objCart->shipping;
                         } else {
                             //create
                             $objShipping = new CartShipping();
                             if (!$objShipping->save()) {
                                 Yii::log("Error saving shipping info for cart " . print_r($objShipping->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                             }
                         }
                         if ($order->isSetShipmentServiceLevelCategory()) {
                             $strShip = $order->getShipmentServiceLevelCategory();
                         }
                         $objShipping->shipping_module = get_class($this);
                         $objShipping->shipping_data = $strShip;
                         $objShipping->shipping_method = $this->objModule->getConfig('product');
                         $objShipping->shipping_cost = 0;
                         $objShipping->shipping_sell = 0;
                         $objShipping->save();
                         $objCart->shipping_id = $objShipping->id;
                         if (!$objCart->save()) {
                             Yii::log("Error saving cart " . print_r($objCart->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                         }
                     }
                     //Because Amazon comes down with no payment info, just generate one here
                     $objP = new CartPayment();
                     $objP->payment_method = $this->objModule->getConfig('ls_payment_method');
                     $objP->payment_module = get_class($this);
                     $objP->payment_data = 'Amazon';
                     $objP->payment_amount = $objOrderTotal->getAmount();
                     $objP->datetime_posted = $order->getPurchaseDate();
                     if (!$objP->save()) {
                         Yii::log("Error saving payment " . print_r($objP->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                     }
                     $objCart->payment_id = $objP->id;
                     if (!$objCart->save()) {
                         Yii::log("Error saving cart " . print_r($objCart->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                     }
                     TaskQueue::CreateEvent('integration', get_class($this), 'ListOrderDetails', $objCart->id_str . "," . $checkDate);
                 }
             }
         }
     }
 }
Exemplo n.º 9
0
 public function fakeCrowdFundingPurches($id)
 {
     set_time_limit(0);
     $this->login();
     $bottom = Input::get('bottom', '');
     $top = Input::get('top', '');
     $p_id = Input::get('p_id', '');
     try {
         if (!$p_id || !$top || !$bottom) {
             throw new Exception("需要关键数据", 1);
         }
         $funding = CrowdFunding::find($id);
         $funding->load(['eventItem']);
         $product = CrowdFundingProduct::find($p_id);
         $quantity = 1;
         $users = User::where('u_mobile', '>=', $bottom)->where('u_mobile', '<=', $top)->get();
         foreach ($users as $key => $user) {
             $u_id = $user->u_id;
             // sku need to be calulated before cart generated
             $product->loadProduct($quantity);
             // add cart
             $cart = new Cart();
             $cart->p_id = $p_id;
             $cart->p_name = $product->p_title;
             $cart->u_id = $u_id;
             $cart->b_id = $product->b_id;
             $cart->created_at = Tools::getNow();
             $cart->c_quantity = $quantity;
             $cart->c_price = $product->p_price;
             $cart->c_amount = $product->p_price * $quantity;
             $cart->c_discount = 100;
             $cart->c_price_origin = $product->p_price;
             $cart->c_amount_origin = $product->p_price * $quantity;
             $cart->c_status = 2;
             $cart->c_type = 2;
             $re = $cart->save();
             if (!$re) {
                 throw new Exception("提交库存失败", 7006);
             }
             $shipping_address = 'Fake Purches';
             $shipping_name = $user->u_name;
             $shipping_phone = $user->u_mobile;
             $date_obj = new DateTime($funding->eventItem->e_start_at);
             $delivery_time_obj = $date_obj->modify('+' . ($funding->c_time + $funding->c_yield_time) . 'days');
             // add order
             $order_group_no = Order::generateOrderGroupNo($u_id);
             $rnd_str = rand(10, 99);
             $order_no = $order_group_no . $cart->b_id . $rnd_str;
             $order = new Order();
             $order->u_id = $u_id;
             $order->b_id = $cart->b_id;
             $order->o_amount_origin = $cart->c_amount_origin;
             $order->o_amount = $cart->c_amount;
             $order->o_shipping_fee = $funding->c_shipping_fee;
             $order->o_shipping_name = $shipping_name;
             $order->o_shipping_phone = $shipping_phone;
             $order->o_shipping_address = $shipping_address;
             $order->o_delivery_time = $delivery_time_obj->format('Y-m-d H:i:s');
             $order->o_shipping = $funding->c_shipping;
             $order->o_comment = 'Fake Order';
             $order->o_number = $order_no;
             $order->o_group_number = $order_group_no;
             $o_id = $order->addOrder();
             Cart::bindOrder([$order->o_id => [$cart->c_id]]);
             $cart->checkout();
             $order->o_status = 2;
             $order->o_shipping_status = 10;
             $order->paied_at = Tools::getNow();
             $order->save();
         }
     } catch (Exception $e) {
         echo $e->getMessage();
     }
     echo "done";
 }
Exemplo n.º 10
0
 public function getResponse()
 {
     $this->doorGets->checkAjaxMode();
     $response = array('code' => 404, 'data' => array());
     $arrayAction = array('index' => 'Home', 'add' => 'add', 'plus' => 'plus', 'minus' => 'minus', 'remove' => 'remove', 'shippingMethod' => 'shippingMethod');
     $out = '';
     $params = $this->doorGets->Params();
     $modules = $this->doorGets->getAllActiveModules();
     $lgActuel = $this->doorGets->getLangueTradution();
     $lg = 'en';
     if (array_key_exists('lg', $params['GET']) && array_key_exists($params['GET']['lg'], $this->doorGets->allLanguages)) {
         $lg = $this->doorGets->myLanguage = $params['GET']['lg'];
     }
     if (array_key_exists($this->Action, $arrayAction)) {
         switch ($this->Action) {
             case 'index':
                 break;
             case 'add':
                 if (true) {
                     $uri = array_key_exists('uri', $params['GET']) && !empty($params['GET']['uri']) ? $params['GET']['uri'] : '';
                     $quantity = array_key_exists('qty', $params['GET']) && !empty($params['GET']['qty']) ? (int) $params['GET']['qty'] : 1;
                     $id = array_key_exists('id', $params['GET']) && !empty($params['GET']['id']) ? $params['GET']['id'] : '';
                     if (empty($quantity)) {
                         $quantity = 1;
                     }
                     if (!empty($uri) && !empty($id) && array_key_exists($uri, $modules)) {
                         $sqlUri = $this->doorGets->getRealUri($uri);
                         $table = '_m_' . $sqlUri;
                         $tableTraduction = $table . '_traduction';
                         $isContent = $this->doorGets->dbQS($id, $table);
                         if (!empty($isContent)) {
                             $idTraduction = $this->doorGets->getIdContentTraduction($isContent);
                             if (!is_null($idTraduction)) {
                                 $isContentTraduction = $this->doorGets->dbQS($idTraduction, $tableTraduction);
                                 if (!empty($isContentTraduction)) {
                                     $product = array('uri' => $uri, 'id' => $id, 'quantity' => $quantity);
                                     $Cart = new Cart($this->doorGets);
                                     $Cart->addProduct($product);
                                     $Cart->save();
                                     $products = $Cart->getProducts();
                                     $productName = $products[$uri . '-' . $id]['title'];
                                     $response = array('code' => 200, 'data' => array('message' => $productName . ' ' . $this->doorGets->__("est dans votre panier") . '.', 'products' => $Cart->getProducts(), 'count' => $Cart->getCount(), 'totalAmount' => number_format($Cart->getTotalAmount(), 2, ',', ' '), 'totalAmountVat' => number_format($this->vat * $Cart->getTotalAmount() + $Cart->shippingAmount, 2, ',', ' '), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => number_format($Cart->getTotalAmountPromo(), 2, ',', ' '), 'totalAmountPromoVat' => number_format($this->vat * $Cart->getTotalAmountPromo() + $Cart->shippingAmount, 2, ',', ' '), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg, 'uri' => $uri));
                                 }
                             }
                         }
                     }
                 }
                 break;
             case 'minus':
                 if (array_key_exists('uri', $params['GET'])) {
                     $uri = $params['GET']['uri'];
                     $Cart = new Cart($this->doorGets);
                     $newAmount = $Cart->minusProduct($uri);
                     $Cart->save();
                     $response = array('code' => 200, 'data' => array('message' => $this->doorGets->__("Le quantité du produit a été mise à jour") . '.', 'products' => $Cart->getProducts(true), 'count' => $Cart->getCount(), 'totalAmount' => $Cart->getTotalAmount(true), 'totalAmountVat' => $Cart->getTotalAmountVAT(true), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => $Cart->getTotalAmountPromo(true), 'totalAmountPromoVat' => $Cart->getTotalAmountPromoShippingVAT(true), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg, 'newAmount' => $newAmount, 'uri' => $uri));
                 }
                 break;
             case 'plus':
                 if (array_key_exists('uri', $params['GET'])) {
                     $uri = $params['GET']['uri'];
                     $Cart = new Cart($this->doorGets);
                     $newAmount = $Cart->plusProduct($uri);
                     $Cart->save();
                     $response = array('code' => 200, 'data' => array('message' => $this->doorGets->__("Le quantité du produit a été mise à jour") . '.', 'products' => $Cart->getProducts(true), 'count' => $Cart->getCount(), 'totalAmount' => $Cart->getTotalAmount(true), 'totalAmountVat' => $Cart->getTotalAmountVAT(true), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => $Cart->getTotalAmountPromo(true), 'totalAmountPromoVat' => $Cart->getTotalAmountPromoShippingVAT(true), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg, 'newAmount' => $newAmount, 'uri' => $uri));
                 }
                 break;
             case 'remove':
                 if (array_key_exists('uri', $params['GET'])) {
                     $uri = $params['GET']['uri'];
                     $Cart = new Cart($this->doorGets);
                     $Cart->removeProduct($uri);
                     $Cart->save();
                     $response = array('code' => 200, 'data' => array('message' => $this->doorGets->__("Le produit a été supprimé de votre panier") . '.', 'products' => $Cart->getProducts(true), 'count' => $Cart->getCount(), 'totalAmount' => $Cart->getTotalAmount(true), 'totalAmountVat' => $Cart->getTotalAmountVAT(true), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => $Cart->getTotalAmountPromo(true), 'totalAmountPromoVat' => $Cart->getTotalAmountPromoShippingVAT(true), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg, 'uri' => $uri));
                 }
                 break;
             case 'shippingMethod':
                 if (array_key_exists('key', $params['GET'])) {
                     $key = $params['GET']['key'];
                     $Cart = new Cart($this->doorGets);
                     $Cart->setShippingMethod($key);
                     $Cart->save();
                     $response = array('code' => 200, 'data' => array('message' => $this->doorGets->__("Le prix de la livraison est à jour") . '.', 'products' => $Cart->getProducts(true), 'count' => $Cart->getCount(), 'totalAmount' => $Cart->getTotalAmount(true), 'totalAmountVat' => $Cart->getTotalAmountVAT(true), 'subtotalAmountVat' => $Cart->getSubTotalAmountPromoVAT(true), 'totalAmountPromo' => $Cart->getTotalAmountPromo(true), 'totalAmountPromoVat' => $Cart->getTotalAmountPromoShippingVAT(true), 'shippingAmount' => $Cart->getShippingAmount(), 'langue' => $lg));
                 }
                 break;
         }
     }
     return json_encode($response, JSON_FORCE_OBJECT);
 }
Exemplo n.º 11
0
 public function social()
 {
     $social_id = Input::get('id');
     if (Auth::check()) {
         $user_id = Auth::user()->id;
         $user = User::find($user_id);
         $user->social_id = $social_id;
         $user->save();
         $store = StoreLocation::where('zipcode', Auth::user()->zipcode)->first();
         if ($store) {
             $store_id = $store->id;
         } else {
             $store_id = 0;
         }
         $cart = Cart::where('user_id')->orderBy('updated_at', 'desc')->first();
         if ($cart) {
             $cart_id = $cart->id;
         } else {
             $cart = new Cart();
             $cart->cart_url = "";
             $cart->user_id = Auth::user()->id;
             $cart->save();
             $cart_id = $cart->id;
             $cart_user = new CartUser();
             $cart_user->cart_id = $cart_id;
             $cart_user->user_id = Auth::user()->id;
             $cart_user->save();
         }
         Session::put('zipcode', Auth::user()->zipcode);
         Session::put('store_id', $store_id);
         Session::put('cart_id', $cart_id);
         return Redirect::to('/user');
     } else {
         $user = User::where('social_id', $social_id)->first();
         if ($user) {
             $already = 'there';
             Auth::login($user);
         } else {
             $already = '';
             $zipcode = Session::get('zipcode');
             if ($zipcode == null) {
                 return Redirect::to("/")->with('message', 'Please Select the Zipcode and proceed');
             } else {
                 $social_id = Input::get('id');
                 $first_name = Input::get('first_name');
                 $last_name = Input::get('last_name');
                 $email = Input::get('email');
                 $user = User::add($first_name, $last_name, '', $email, '', $zipcode, $social_id, '');
             }
         }
         Auth::login($user);
         $store = StoreLocation::where('zipcode', Auth::user()->zipcode)->first();
         if ($store) {
             $store_id = $store->id;
         } else {
             $store_id = 0;
         }
         $cart = Cart::where('user_id')->orderBy('updated_at', 'desc')->first();
         if ($cart) {
             $cart_id = $cart->id;
         } else {
             $cart = new Cart();
             $cart->cart_url = "";
             $cart->user_id = Auth::user()->id;
             $cart->save();
             $cart_id = $cart->id;
             $cart_user = new CartUser();
             $cart_user->cart_id = $cart_id;
             $cart_user->user_id = Auth::user()->id;
             $cart_user->save();
         }
         // dd(Session::get('zipcode'));
         Session::put('zipcode', Auth::user()->zipcode);
         Session::put('store_id', $store_id);
         Session::put('cart_id', $cart_id);
         if ($already == 'there') {
             return Redirect::to("/store/{$store_id}");
         } else {
             return Redirect::to("/login");
         }
     }
     $response = Response::json($response_array, $response_code);
     return $response;
 }
Exemplo n.º 12
0
 /**
  * The function posts Order.
  * 
  * @access private
  * @param object $Order The Order to save.
  * @param object $Cart The Cart object to clear items.
  * @return string The JSON response.
  */
 private function postOrder(Order $Order, Cart $Cart = null)
 {
     $error = array();
     $Order->setPost($_POST);
     $Custom = $Order->getCustom();
     $Address = $Order->getAddress();
     if ($Order->Type == Order::STANDARD && (!$Address->Name || !$Address->Phone) || $Order->Type == Order::CUSTOM && (!$Custom->Name || !$Custom->Email) || $Order->Type == Order::PRODUCT && (!$Address->Name || !$Address->Phone)) {
         $error[] = 'Заполните все обязательные поля';
     } else {
         if ($Order->Type != Order::CUSTOM && !Error::check($Address->Email, 'email')) {
             $error[] = 'Введите корректный E-mail';
         } else {
             if ($Order->save()) {
                 if (!empty($_FILES['file']['tmp_name'])) {
                     if (File::upload($Order, $_FILES['file'])) {
                         $Order->save();
                     }
                 }
                 if ($Cart) {
                     $Cart->clear();
                     $Cart->save();
                 }
                 $Email = new Email_Order($Order);
                 if (!$Email->send()) {
                     $error[] = 'Ошибка отправки сообщения';
                 }
             } else {
                 $error[] = 'Ошибка записи данных';
             }
         }
     }
     $response = array('result' => count($error) ? 0 : 1);
     $response['posted'] = 1;
     $response['msg'] = implode("\n", $error);
     return $this->outputJSON($response);
 }
Exemplo n.º 13
0
    public function hooknewOrder($params)
    {
        if (!$this->active) {
            return;
        }
        $cart = new Cart($params['cart']->id);
        $order = $params['order'];
        $option = Db::getInstance()->getValue('SELECT `option`
												FROM `' . _DB_PREFIX_ . 'tnt_carrier_option`
												WHERE `id_carrier` = "' . (int) $params['cart']->id_carrier . '"');
        if (isset($option) && strpos($option, 'D') !== false) {
            $dropOff = Db::getInstance()->getRow('SELECT `code`, `name`, `address`, `zipcode`, `city`
												FROM `' . _DB_PREFIX_ . 'tnt_carrier_drop_off`
												WHERE `id_cart` = "' . (int) $params['cart']->id . '"');
            $alias = "tntRelaisColis" . $order->id;
            $id_address = Db::getInstance()->getValue('SELECT id_address FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = "' . (int) $params['cart']->id_customer . '" AND `alias` = "' . $alias . '"');
            if ($id_address > 0) {
                $address_new = new Address($id_address);
            } else {
                $address_old = new Address($cart->id_address_delivery);
                $address_new = new Address();
                $address_new->id_customer = $address_old->id_customer;
                $address_new->id_country = $address_old->id_country;
                $address_new->id_state = $address_old->id_state;
                $address_new->id_manufacturer = $address_old->id_manufacturer;
                $address_new->id_supplier = $address_old->id_supplier;
                $address_new->lastname = $address_old->lastname;
                $address_new->firstname = $address_old->firstname;
                $address_new->phone = $address_old->phone;
                $address_new->phone_mobile = $address_old->phone_mobile;
                $address_new->alias = $alias;
            }
            if (strlen($dropOff['name']) >= 32) {
                $address_new->company = substr($dropOff['name'], 0, 31);
            } else {
                $address_new->company = $dropOff['name'];
            }
            $address_new->address1 = $dropOff['address'];
            $address_new->postcode = $dropOff['zipcode'];
            $address_new->city = $dropOff['city'];
            $address_new->deleted = 1;
            $address_new->save();
            $cart->id_address_delivery = $address_new->id;
            $cart->save();
            $order->id_address_delivery = $address_new->id;
            $order->save();
        }
    }
Exemplo n.º 14
0
 /**
  * 点单
  * 
  */
 public function actionCreateCart()
 {
     $seatNum = $this->seatNum ? $this->seatNum : 0;
     //	$siteNo = SiteNo::model()->find('company_id=:companyId and code=:code and delete_flag=0',array(':companyId'=>$this->companyId,':code'=>$seatNum));
     $productId = Yii::app()->request->getParam('id');
     $now = time();
     $cart = new Cart();
     $cartDate = array('product_id' => $productId, 'company_id' => $this->companyId, 'code' => $seatNum, 'product_num' => 1, 'create_time' => $now);
     $cart->attributes = $cartDate;
     if ($cart->save()) {
         echo 1;
     } else {
         echo 0;
     }
     Yii::app()->end();
 }
Exemplo n.º 15
0
 /**
  * postAddItem
  */
 public function postAddItem()
 {
     $item_id = Input::get('item_id');
     $customer_id = Input::get('customer_id');
     $cart = new Cart();
     $cart->customer_id = $customer_id;
     $cart->item_id = $item_id;
     $cart->quantity = 1;
     $cart->type = 0;
     $cart->craft_description = '';
     $cart->confirm_price = 0.0;
     $cart->save();
     return Response::json(array('msg' => 1));
 }
Exemplo n.º 16
0
 public function getNewCart($module_srl, $member_srl = null, $session_id = null, $items = 0)
 {
     if (!$session_id) {
         $session_id = session_id();
     }
     $cart = new Cart(array('module_srl' => $module_srl, 'member_srl' => $member_srl, 'session_id' => $session_id, 'items' => $items));
     $cart->save();
     return $cart;
 }
 public function user_index()
 {
     $user_id = mysql_real_escape_string(Site::CurrentUser()->id);
     // Code from Cart->create()			// First check CRSF
     if ($this->post) {
         // From the post data, build the cart items
         $raw_items = array();
         if (isset($_POST['items']['signups'])) {
             foreach ($_POST['items']['signups'] as $id => $value) {
                 $id = mysql_real_escape_string($id);
                 $signup = EventSignup::find("event_signups.user_id = '{$user_id}' AND event_signups.id = '{$id}'");
                 if ($signup && !$signup->paid && !$signup->is_soldout()) {
                     $raw_items[$signup->id]['signup'] = $signup;
                 }
             }
         }
         if (isset($_POST['items']['services'])) {
             $service_count = array();
             foreach ($_POST['items']['services'] as $id => $value) {
                 $id = mysql_real_escape_string($id);
                 $service = EventService::find("event_signups.user_id = '{$user_id}' AND event_services.id = '{$id}'");
                 if ($service && !$service->paid && $service->service->available()) {
                     if (isset($service_count[$service->service->id])) {
                         $service_count[$service->service->id]++;
                     } else {
                         $service_count[$service->service->id] = 1;
                     }
                     if ($service->service->available() == -1 || $service_count[$service->service->id] <= $service->service->available()) {
                         if ($service->event_signup->paid || isset($raw_items[$service->event_signup->id]['signup'])) {
                             $raw_items[$service->event_signup->id]['services'][] = $service;
                         }
                     }
                 }
             }
         }
         // Sort properly
         $items = array();
         foreach ($raw_items as $id => $parts) {
             if (isset($parts['signup'])) {
                 $items[] = $parts['signup'];
             }
             if (isset($parts['services'])) {
                 $items = array_merge($items, $parts['services']);
             }
         }
         if (count($items) == 0) {
             Site::Flash("error", "None of the items you selected could be paid for.");
             Redirect("bookings");
         }
         $hash = Cart::hash_items($items);
         $cart = Cart::find("carts.hash = '{$hash}' AND carts.hash IS NOT NULL");
         if (!$cart) {
             $cart = new Cart();
             $cart->user_id = $user_id;
             $cart->hash = $hash;
             if ($cart->save()) {
                 foreach ($items as $item) {
                     $cart->add_item($item);
                 }
             } else {
                 Site::Flash("error", "Unable to create cart.");
                 Redirect("bookings");
             }
         }
         Redirect("bookings/pay/{$cart->id}");
     } elseif ($this->post) {
         global $site;
         $site['flash']['error'] = "Invalid form submission";
     }
     // Fetch all signups in event order and iterate through them
     $items = array();
     $signups = EventSignup::find_all("event_signups.user_id = '{$user_id}' AND events.enddate >= NOW()", "events.startdate DESC");
     foreach ($signups as $signup) {
         if (!$signup->paid) {
             $items[] = $signup;
         } else {
             foreach ($signup->event_services() as $service) {
                 if (!$service->paid) {
                     $items[] = $signup;
                     break;
                 }
             }
         }
     }
     $this->assign("items", $items);
     // Traditional My Bookings Page
     $unpaid = EventSignup::find_all("event_signups.user_id = '{$user_id}' AND event_signups.paid = false", "events.startdate DESC");
     $paid = EventSignup::find_all("event_signups.user_id = '{$user_id}' AND event_signups.paid = true AND voucher = false", "events.startdate DESC");
     $vouchers = EventSignup::find_all("event_signups.user_id = '{$user_id}' AND event_signups.paid = true AND voucher = true", "events.startdate DESC");
     $this->assign("unpaid", $unpaid);
     $this->assign("paid", $paid);
     $this->assign("vouchers", $vouchers);
     $this->title = "My Bookings";
     $this->render("event_signup/user_index.tpl");
 }
Exemplo n.º 18
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Cart();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Cart'])) {
         $model->attributes = $_POST['Cart'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Exemplo n.º 19
0
<?php

global $custAuth, $home_dir;
require_once $home_dir . 'models/cart.m.php';
if (isset($_POST['email'])) {
    $cart_products = null;
    $cart_totals = null;
    if ($custAuth->isAuth()) {
        $cart_products = Cart::loadCart($db, $custAuth->customer->val('customer_id'));
        $cart_totals = Cart::loadCartTotals($db, $custAuth->customer->val('customer_id'));
    }
    if ($custAuth->login($_POST['email'], $_POST['password'])) {
        if (isset($cart_totals) && $cart_totals['p'] > 0) {
            foreach ($cart_products as $product) {
                $cart = new Cart($db);
                $cart->data['cart_product_id'] = $product->ival('product_id');
                $cart->data['cart_customer_id'] = $custAuth->customer->ival('customer_id');
                $cart->save();
            }
        }
        redirect(_g('r', 'front'));
    } else {
        $messages->error(t('Login incorrect!'));
    }
}
$page_title = t('Sign In');
 public function postOrder($id)
 {
     $token = Input::get('token', '');
     $u_id = Input::get('u_id', 0);
     $p_id = Input::get('product', 0);
     $quantity = Input::get('quantity', 0);
     $shipping_name = Input::get('shipping_name', '');
     $shipping_phone = Input::get('shipping_phone', '');
     $shipping_address = Input::get('shipping_address', '');
     $comment = Input::get('comment', '');
     DB::beginTransaction();
     try {
         $funding = CrowdFunding::find($id);
         $funding->load(['eventItem']);
         $date_end = new DateTime($funding->eventItem->e_end_at);
         $date_start = new DateTime($funding->eventItem->e_start_at);
         $now = new DateTime();
         if ($now > $date_end) {
             throw new Exception("抱歉, 众筹已经结束", 2001);
         }
         if ($now < $date_start) {
             throw new Exception("抱歉, 众筹还未开始, 请耐心等待", 2001);
         }
         if ($funding->c_status != 4) {
             throw new Exception("抱歉, 无效的众筹状态", 2001);
         }
         if ($funding->u_id == $u_id) {
             throw new Exception("您不能认筹自己发起的众筹", 2001);
         }
         $validator = Validator::make(['收货人电话' => (string) $shipping_phone, '收货人姓名' => $shipping_name, '收获地址' => $shipping_address, '产品' => $p_id, '数量' => $quantity], ['收货人电话' => 'required|numeric|digits:11', '收货人姓名' => 'required', '收获地址' => 'required', '产品' => 'required|numeric', '数量' => 'required|numeric']);
         if ($validator->fails()) {
             $msg = $validator->messages();
             throw new Exception($msg->first(), 7001);
         }
         $user = User::chkUserByToken($token, $u_id);
         if (!$user->u_mobile && ($id = 30)) {
             throw new Exception("此众筹需要绑定联系电话,请到[我的-编辑资料]里绑定后进行支持", 2001);
         }
         if ($funding->c_local_only) {
             $funding_owner = User::find($funding->u_id);
             if ($funding_owner->u_school_id != $user->u_school_id) {
                 throw new Exception("该众筹仅限于同校参与", 2001);
             }
         }
         $product = CrowdFundingProduct::find($p_id);
         if ($product->p_price == 0) {
             if ($quantity != 1) {
                 throw new Exception("此类众筹只能认筹一份", 1);
             }
             // check if user has bought
             $chk = Cart::where('u_id', '=', $u_id)->where('c_type', '=', 2)->where('p_id', '=', $p_id)->where('c_status', '>', 0)->first();
             if (!empty($chk)) {
                 throw new Exception("此类众筹每人限认筹一次", 7001);
             }
         }
         // sku need to be calulated before cart generated
         $product->loadProduct($quantity);
         // add cart
         $cart = new Cart();
         $cart->p_id = $p_id;
         $cart->p_name = $product->p_title;
         $cart->u_id = $u_id;
         $cart->b_id = $product->b_id;
         $cart->created_at = Tools::getNow();
         $cart->c_quantity = $quantity;
         $cart->c_price = $product->p_price;
         $cart->c_amount = $product->p_price * $quantity;
         $cart->c_discount = 100;
         $cart->c_price_origin = $product->p_price;
         $cart->c_amount_origin = $product->p_price * $quantity;
         $cart->c_status = 2;
         $cart->c_type = 2;
         $re = $cart->save();
         if (!$re) {
             throw new Exception("提交库存失败", 7006);
         }
         if (!$funding->c_shipping) {
             $shipping_address = '';
         }
         $shipping_name = $shipping_name ? $shipping_name : $user->u_name;
         $shipping_phone = $shipping_phone ? $shipping_phone : $user->u_mobile;
         $date_obj = new DateTime($funding->eventItem->e_start_at);
         $delivery_time_obj = $date_obj->modify('+' . ($funding->c_time + $funding->c_yield_time) . 'days');
         // add order
         $order_group_no = Order::generateOrderGroupNo($u_id);
         $rnd_str = rand(10, 99);
         $order_no = $order_group_no . $cart->b_id . $rnd_str;
         $order = new Order();
         $order->u_id = $u_id;
         $order->b_id = $cart->b_id;
         $order->o_amount_origin = $cart->c_amount_origin;
         $order->o_amount = $cart->c_amount;
         $order->o_shipping_fee = $funding->c_shipping_fee;
         $order->o_shipping_name = $shipping_name;
         $order->o_shipping_phone = $shipping_phone;
         $order->o_shipping_address = $shipping_address;
         $order->o_delivery_time = $delivery_time_obj->format('Y-m-d H:i:s');
         $order->o_shipping = $funding->c_shipping;
         $order->o_comment = $comment;
         $order->o_number = $order_no;
         $order->o_group_number = $order_group_no;
         $o_id = $order->addOrder();
         Cart::bindOrder([$order->o_id => [$cart->c_id]]);
         // change order to finish if price = 0
         if ($order->o_amount == 0) {
             $cart->checkout();
             $order->o_status = Order::$STATUS_FINISHED;
             $order->o_shipping_status = Order::$SHIPPING_STATUS_FINISHED;
             $order->paied_at = Tools::getNow();
             $order->save();
         }
         $data = ['order_no' => $order_group_no];
         $re = Tools::reTrue('提交订单成功', $data);
         DB::commit();
     } catch (Exception $e) {
         $re = Tools::reFalse($e->getCode(), '提交订单失败:' . $e->getMessage());
         DB::rollback();
     }
     return Response::json($re);
 }
Exemplo n.º 21
0
 function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special, $dont_touch_amount = false)
 {
     if (!$this->active) {
         return;
     }
     $currency = $this->getCurrency();
     $cart = new Cart(intval($id_cart));
     $cart->id_currency = $currency->id;
     $cart->save();
     parent::validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod, $message, $extraVars, $currency_special, true);
 }
 private function createCartIfNotExists()
 {
     if ($this->getUser()->isAuthenticated()) {
         $promoter = PromoterPeer::getPromoterByUserId($this->getUser()->getId());
         $cart = CartPeer::getCart($promoter->getClientId());
         if (isset($cart)) {
             return $cart;
         }
     }
     $cart = CartPeer::getCartByIdSession(session_id());
     if (!isset($cart)) {
         $cart = new Cart();
         $cart->setIdState(2);
         //$cart->setClientId($promoter->getClientId());
         //$cart->setClosingTime()  //modificar yml
         $cart->setNightAuditId(1);
         $cart->setIdSession(session_id());
         $cart->save();
     }
     return $cart;
 }
Exemplo n.º 23
0
 public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false)
 {
     if (!$this->active) {
         return;
     }
     $this->_validateErrors = array();
     $currency = $this->getCurrency();
     $cart = new Cart(intval($id_cart));
     $cart_currency = $_SESSION['params1']['cart']->id_currency;
     $cart_total = $_SESSION['params1']['cart']->getOrderTotal(true, 3);
     $cart->id_currency = $cart_currency;
     $amountPaid = $cart_total;
     $id_lang = $_SESSION['params1']['cart']->id_lang;
     $subject = 'CCAvenue Payment Status';
     $template = 'payment_success';
     $firstname = $_SESSION['params1']['cookie']->customer_firstname;
     $lastname = $_SESSION['params1']['cookie']->customer_lastname;
     $Order_Id = $id_cart;
     $date_added = $_SESSION['params1']['cookie']->date_add;
     $payment_method = $paymentMethod;
     $total = $cart_total;
     $to = $_SESSION['params1']['cookie']->email;
     $templateVars = array('{firstname}' => $firstname, '{lastname}' => $lastname, '{Order_Id}' => $Order_Id, '{date_added}' => $date_added, '{payment_method}' => $payment_method, '{total}' => $total);
     $ccavenue_payment_success_mail = trim(Configuration::get('CCAVENUE_PAYMENT_SUCCESS_MAIL'));
     //$ccavenue_payment_success_mail = 0;
     $payment_status = '';
     if (isset($extraVars['payment_status'])) {
         $payment_status = $extraVars['payment_status'];
     }
     if ($ccavenue_payment_success_mail && $id_order_state == '2') {
         Mail::Send($id_lang, $template, $subject, $templateVars, $to, NULL, NULL, NULL, NULL, NULL, _PS_MODULE_DIR_ . $this->name . '/mails/');
     }
     $cart->save();
     parent::validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod, $message, $extraVars, $currency_special, true, $secure_key);
 }
Exemplo n.º 24
0
 public function actionAddtocart($id)
 {
     /* gunakan layout store */
     $this->layout = 'store';
     /* panggil model Cart */
     $model = new Cart();
     /* set data ke masing masing field */
     /* product_id */
     $_POST['Cart']['product_id'] = $id;
     /* qty */
     $_POST['Cart']['quantity'] = 1;
     /* cart_code */
     $_POST['Cart']['cart_code'] = Yii::app()->session['cart_code'];
     /* set ke attribut2 */
     $model->attributes = $_POST['Cart'];
     /* update qty-nya jika produk sudah ada di dalam keranjang belanja
      * menjadi +1 */
     if ($this->addQuantity($id, Yii::app()->session['cart_code'], 1)) {
         /* direct ke halaman cart */
         $this->redirect(array('cart/'));
         /* add ke keranjang belanja jika produk belum ada di keranjang */
     } elseif ($model->save()) {
         /* direct ke halaman cart */
         $this->redirect(array('cart/'));
     } else {
         /* produk tidak ada di dalam data product kasih error 404 */
         throw new CHttpException(404, 'The requested id invalid.');
     }
 }
Exemplo n.º 25
0
 public function saveOrders($status, $result)
 {
     $cart = new Cart();
     $user_Id = Yii::app()->user->id;
     if (!empty($user_Id)) {
         $cartData = $this->processCart();
         $cart_items = Yii::app()->session['cartItems'];
         $cart->cart_orderno = uniqid();
         $cart->cart_payment_status = $status;
         $cart->cart_order_status = 0;
         $cart->cart_user_id = $user_Id;
         $cart->cart_paypal_result = json_encode($result);
         $sessCartId = Yii::app()->session['cartId'];
         if (!empty($sessCartId)) {
             $cart->cart_id = Yii::app()->session['cartId'];
             $cart->isNewRecord = false;
         }
         if ($cart->save() && empty($sessCartId)) {
             Yii::app()->session['cartId'] = $cart->cart_id;
             if (!empty($cartData['fabrics'])) {
                 foreach ($cartData['fabrics'] as $key => $arrObj) {
                     $cartItemsModel = new CartItems();
                     $fabId = $arrObj->fab_id;
                     $shirtArr = array();
                     $trouserArr = array();
                     $suitArr = array();
                     $blazerArr = array();
                     if ($arrObj->fab_for == 1) {
                         $shirtArr = array('sleeve' => $cart_items['fabric'][$fabId]['txt_sleeve'], 'collor' => $cart_items['fabric'][$fabId]['txt_collor'], 'cuff' => $cart_items['fabric'][$fabId]['txt_cuff'], 'placket' => $cart_items['fabric'][$fabId]['txt_placket'], 'pocket' => $cart_items['fabric'][$fabId]['txt_pocket'], 'back_shirt' => $cart_items['fabric'][$fabId]['txt_back_shirt'], 'front_shirt' => $cart_items['fabric'][$fabId]['txt_front_shirt'], 'button' => $cart_items['fabric'][$fabId]['txt_button'], 'monogram' => $cart_items['fabric'][$fabId]['txt_monogram'], 'fabid' => $cart_items['fabric'][$fabId]['txt_fabric']);
                     } else {
                         if ($arrObj->fab_for == 2) {
                             $trouserArr = array('belt' => $cart_items['fabric'][$fabId]['txt_belt'], 'pleated' => $cart_items['fabric'][$fabId]['txt_pleated'], 'sidepocket' => $cart_items['fabric'][$fabId]['txt_sidepocket'], 'backpocket' => $cart_items['fabric'][$fabId]['txt_backpocket'], 'bottomstyle' => $cart_items['fabric'][$fabId]['txt_bottomstyle'], 'back_lining' => $cart_items['fabric'][$fabId]['txt_lining'], 'button' => $cart_items['fabric'][$fabId]['txt_button'], 'fabid' => $cart_items['fabric'][$fabId]['txt_fabric']);
                         } else {
                             if ($arrObj->fab_for == 3) {
                                 $blazerArr = array();
                             }
                         }
                     }
                     $customizations = array('product' => $arrObj->fab_for, 'shirt' => $shirtArr, 'trouser' => $trouserArr, 'blazer' => $blazerArr, 'suit' => $suitArr);
                     $customization_json = json_encode($customizations);
                     $cartItemsModel->citm_cart_id = $cart->cart_id;
                     $cartItemsModel->citm_color = $arrObj->fab_color;
                     $cartItemsModel->citm_pattern = $arrObj->fab_pattern;
                     $cartItemsModel->citm_fabric = $arrObj->fab_fabric;
                     $cartItemsModel->citm_customization = $customization_json;
                     //$cartItemsModel->citm_measurement
                     $cartItemsModel->citm_type = 2;
                     $cartItemsModel->citm_price = $arrObj->fab_price;
                     //$cartItemsModel->citm_discount = 0;
                     $cartItemsModel->citm_qty = $cart_items['fabric'][$fabId]['qty'];
                     //$cartItemsModel->citm_rental
                     //$errors = $cartItemsModel->getErrors();
                     //prd($errors);
                     if (!empty($cart_items['fabric'][$fabId]['user_measurement_id'])) {
                         $cartItemsModel->citm_user_measurement_id = $cart_items['fabric'][$fabId]['user_measurement_id'];
                     }
                     $cartItemsModel->isNewRecord = true;
                     $cartItemsModel->save();
                 }
             }
             if (!empty($cartData['items'])) {
                 foreach ($cartData['items'] as $key1 => $arrObj1) {
                     $cartItemsModel = new CartItems();
                     $itemid = $arrObj1->itm_id;
                     $cartItemsModel->citm_cart_id = $cart->cart_id;
                     $cartItemsModel->citm_item_id = $arrObj1->itm_id;
                     $cartItemsModel->citm_type = '0';
                     $cartItemsModel->citm_price = $arrObj1->itm_price;
                     //$cartItemsModel->citm_discount = 0;
                     $cartItemsModel->citm_qty = $cart_items['item'][$itemid]['qty'];
                     //$cartItemsModel->citm_rental
                     //$errors = $cartItemsModel->getErrors();
                     //pr($errors);
                     $cartItemsModel->isNewRecord = true;
                     $cartItemsModel->save();
                 }
             }
         }
     }
 }
	/**
	 * Store an error message in the cart in order to
	 * let the user know there was a problem with his
	 * payment; used for errors that were received by IPN
	 *
	 * @param $cart_srl
	 * @param $transaction_id
	 * @param $error_message
	 */
	protected function markTransactionAsFailedInUserCart($cart_srl, $transaction_id, $error_message)
	{
		$cart = new Cart($cart_srl);
		$cart->setExtra("transaction_id", $transaction_id);
		$cart->setExtra("transaction_message", $error_message);
		$cart->save();
	}
Exemplo n.º 27
0
    public function validation()
    {
        if (!$this->active || !Configuration::get('GOINTERPAY_STORE') || !Configuration::get('GOINTERPAY_SECRET')) {
            return false;
        }
        if (!isset($_GET['orderId'])) {
            return false;
        }
        include_once _PS_MODULE_DIR_ . 'gointerpay/Rest.php';
        $rest = new Rest(Configuration::get('GOINTERPAY_STORE'), Configuration::get('GOINTERPAY_SECRET'));
        $result = $rest->orderDetail(Tools::safeOutput(Tools::getValue('orderId')));
        $cart = new Cart((int) $result['cartId']);
        $original_total = Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
        /* Check the currency code */
        $id_currency_new = (int) Currency::getIdByIsoCode($result['foreignCurrencyCode']);
        if ($id_currency_new) {
            $cart->id_currency = (int) $id_currency_new;
            $cart->save();
        } else {
            die('Sorry, we were not able to accept orders in the following currency: ' . Tools::safeOutput($result['foreignCurrencyCode']));
        }
        $name = explode(" ", $result['delivery_address']['name']);
        $lastname = " - ";
        if (isset($name[1])) {
            $lastname = $name[1];
        }
        /* Update the delivery and billing address */
        $delivery_address = new Address((int) $cart->id_address_delivery);
        $delivery_address->firstname = $name[0];
        $delivery_address->lastname = $lastname;
        $delivery_address->company = $result['delivery_address']['company'];
        $delivery_address->phone = $result['delivery_address']['phone'];
        $delivery_address->phone_mobile = $result['delivery_address']['altPhone'];
        $delivery_address->id_country = (int) Country::getByIso($result['delivery_address']['countryCode']);
        $delivery_address->id_state = (int) State::getIdByIso($result['delivery_address']['state'], (int) $delivery_address->id_country);
        $delivery_address->address1 = $result['delivery_address']['address1'];
        $delivery_address->address2 = $result['delivery_address']['address2'];
        $delivery_address->city = $result['delivery_address']['city'];
        $delivery_address->postcode = $result['delivery_address']['zip'];
        $delivery_address->save();
        /* If no billing address specified, use the delivery address */
        if ($result['invoice_address']['address1'] != '' || $result['invoice_address']['city'] != '') {
            $invoice_name = explode(" ", $result['invoice_address']['name']);
            $invoice_lastname = " - ";
            if (isset($invoice_name[1])) {
                $invoice_lastname = $invoice_name[1];
            }
            $invoice_address = new Address((int) $cart->id_address_invoice);
            $invoice_address->firstname = $invoice_name[0];
            $invoice_address->lastname = $invoice_lastname;
            $invoice_address->company = $result['invoice_address']['company'];
            $invoice_address->phone = $result['invoice_address']['phone'];
            $invoice_address->phone_mobile = $result['invoice_address']['altPhone'];
            $invoice_address->id_country = (int) Country::getByIso($result['invoice_address']['countryCode']);
            $invoice_address->id_state = (int) State::getIdByIso($result['invoice_address']['state'], (int) $invoice_address->id_country);
            $invoice_address->address1 = $result['invoice_address']['address1'];
            $invoice_address->address2 = $result['invoice_address']['address2'];
            $invoice_address->city = $result['invoice_address']['city'];
            $invoice_address->postcode = $result['invoice_address']['zip'];
            if ($cart->id_address_delivery == $cart->id_address_invoice) {
                $invoice_address->add();
                $cart->id_address_invoice = (int) $invoice_address->id;
                $cart->save();
            } else {
                $invoice_address->save();
            }
        }
        /* Store the Order ID and Shipping cost */
        Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'gointerpay_order_id` (`id_cart`, `orderId`, `shipping`, `shipping_orig`, `taxes`, `total`, `products`, `status`)
		VALUES (\'' . (int) $cart->id . '\', \'' . pSQL(Tools::getValue('orderId')) . '\', \'' . (double) $result['shippingTotal'] . '\', \'' . (double) $result['shippingTotalForeign'] . '\', \'' . (double) $result['quotedDutyTaxes'] . '\', \'' . (double) $result['grandTotal'] . '\', \'' . (double) $result['itemsTotal'] . '\', \'Init\')');
        /* Add the duties and taxes */
        Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'specific_price` WHERE id_customer = ' . (int) $cart->id_customer . ' AND id_product = ' . (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES'));
        $specific_price = new SpecificPrice();
        $specific_price->id_product = (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES');
        $specific_price->id_shop = 0;
        $specific_price->id_country = 0;
        $specific_price->id_group = 0;
        $specific_price->id_cart = (int) $cart->id;
        $specific_price->id_product_attribute = 0;
        $specific_price->id_currency = $cart->id_currency;
        $specific_price->id_customer = $cart->id_customer;
        $specific_price->price = (double) $result['quotedDutyTaxesForeign'];
        $specific_price->from_quantity = 1;
        $specific_price->reduction = 0;
        $specific_price->reduction_type = 'percentage';
        $specific_price->from = date('Y-m-d H:i:s');
        $specific_price->to = strftime('%Y-%m-%d %H:%M:%S', time() + 10);
        $specific_price->add();
        if (Validate::isLoadedObject($specific_price)) {
            $cart->updateQty(1, (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES'));
        }
        $result['status'] = 'Pending';
        $total = Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
        $message = '
		Total paid on Interpay: ' . (double) $result['grandTotalForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Duties and taxes on Interpay: ' . (double) $result['quotedDutyTaxesForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Shipping on Interpay: ' . (double) $result['shippingTotalForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Currency: ' . $result['foreignCurrencyCode'];
        if ($result['status'] == 'Pending') {
            $this->context->cart->id = (int) $result['cartId'];
            Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'gointerpay_order_id` SET `status` = \'Pending\' WHERE `id_cart` = ' . (int) $cart->id);
            $order_status = Configuration::get('GOINTERPAY_PAYMENT_PENDING');
            $price_difference = abs($original_total - ((double) $result['grandTotalForeign'] - (double) $result['quotedDutyTaxesForeign'] - (double) $result['shippingTotalForeign'])) * 100 / $original_total;
            if ($price_difference > 1) {
                /* Uncomment this line if you would like to decline orders with a too high price difference */
                // $order_status = Configuration::get('PS_OS_ERROR');
                /*$message .= '
                		
                		Warning: The difference between the price paid and the price to pay was higher than 1% ('.number_format($price_difference, 2, '.', '').'%)
                		However, the payment was processed by Interpay, you should get in touch with the customer and Interpay to resolve that matter.';*/
            }
            $this->validateOrder((int) $cart->id, (int) $order_status, $total, $this->displayName, $message, array(), NULL, false, $cart->secure_key);
            Tools::redirectLink(__PS_BASE_URI__ . 'history.php');
        } else {
            die('Order was not found or cannot be validated at this time, please contact us.');
        }
    }
 private function createCart()
 {
     $firstItem = current($this->datas->orderLineItems);
     $firstVariant = current($firstItem->product->productVariants);
     if (!($currency = $this->getCurrencyByIsoCode($firstVariant->finalPrice->currency))) {
         return false;
     }
     $this->shippingCost = $this->getShippingCost($this->datas->orderLineItems, $currency, (int) $this->address->id_country, false);
     $this->shippingCostWt = $this->getShippingCost($this->datas->orderLineItems, $currency, (int) $this->address->id_country, true);
     $cart = new Cart();
     $cart->id_carrier = (int) Configuration::get('POWATAG_SHIPPING');
     $cart->delivery_option = serialize(array($this->address->id => $cart->id_carrier . ','));
     $cart->id_lang = (int) $this->context->language->id;
     $cart->id_address_delivery = (int) $this->address->id;
     $cart->id_address_invoice = (int) $this->invoice_address->id;
     $cart->id_currency = (int) $currency->id;
     $cart->id_customer = (int) $this->customer->id;
     $cart->secure_key = $this->customer->secure_key;
     if (!$cart->save()) {
         $this->addError($this->module->l('Impossible to save cart'), PowaTagErrorType::$INTERNAL_ERROR);
         if (PowaTagAPI::apiLog()) {
             PowaTagLogs::initAPILog('Create cart', PowaTagLogs::ERROR, $this->error['message']);
         }
         return false;
     }
     if (PowaTagAPI::apiLog()) {
         PowaTagLogs::initAPILog('Create cart', PowaTagLogs::SUCCESS, 'Cart ID : ' . $cart->id);
     }
     $this->cart = $cart;
     if (!$this->addProductsToCart($cart, $this->address->id_country)) {
         return false;
     }
     return $this->cart->id;
 }
Exemplo n.º 29
0
 public static function create_from_signup($signup, $note = "")
 {
     $hash = self::hash_items($signup);
     $cart = Cart::find("carts.hash = '{$hash}' AND carts.hash IS NOT NULL");
     if ($cart) {
         return $cart;
     }
     $cart = new Cart();
     $cart->user_id = $signup->user->id;
     $cart->note = $note;
     $cart->hash = $hash;
     if ($cart->save()) {
         // Add Signup
         $added = false;
         if (!$signup->paid) {
             $cart->add_item($signup);
             $added = true;
         }
         foreach ($signup->event_services() as $service) {
             if (!$service->paid) {
                 $cart->add_item($service);
                 $added = true;
             }
         }
         $cart = Cart::find_by_id($cart->id);
         if ($added) {
             return $cart;
         } else {
             $cart->destroy();
             return false;
         }
     }
     return false;
 }
Exemplo n.º 30
0
function ecommerce_frontend($page)
{
    $ec = new EcommerceController();
    include 'classes/cart.class.php';
    ob_start();
    $page->_executeLayout();
    $output = ob_get_contents();
    ob_end_clean();
    $uri_arr = explode('/', $page->url);
    if (in_array('products', $uri_arr)) {
        $cart = new Cart('shopping_cart');
        // search
        if (in_array('search', $uri_arr)) {
            $keywords = !empty($_GET['keywords']) ? $_GET['keywords'] : '';
            $output = str_replace('<!-- ecommerce -->', $ec->products_search($keywords), $output);
        }
        // cart
        if (in_array('cart', $uri_arr)) {
            // add item to cart
            if (!empty($_POST['variant_id']) && !empty($_POST['quantity'])) {
                $quantity = $cart->getItemQuantity($_POST['variant_id']) + $_POST['quantity'];
                $cart->setItemQuantity($_POST['variant_id'], $quantity);
            }
            //update cart item quantity
            if (!empty($_POST['quantity'])) {
                if (is_array($_POST['quantity'])) {
                    foreach ($_POST['quantity'] as $variant_id => $quantity) {
                        $cart->setItemQuantity($variant_id, $quantity);
                    }
                }
            }
            // remove item from cart
            if (!empty($_POST['remove'])) {
                foreach ($_POST['remove'] as $variant_id) {
                    $cart->setItemQuantity($variant_id, 0);
                }
            }
            if (!empty($_POST['variant_id']) || !empty($_POST['quantity']) || !empty($_POST['remove'])) {
                $cart->save();
            }
            $output = str_replace('<!-- ecommerce -->', $cart->display(), $output);
        }
        // checkout
        if (in_array('checkout', $uri_arr)) {
            if ($cart->hasItems()) {
                $output = str_replace('<!-- ecommerce -->', $ec->checkout(), $output);
            } else {
                $output = str_replace('<!-- ecommerce -->', '<p>You have no items in your cart.</p>', $output);
            }
        }
        //product display
        if (count($uri_arr) == 1) {
            // products main page display
            $output = str_replace('<!-- ecommerce -->', $ec->products_all(), $output);
        } else {
            // display products by type
            if (in_array('types', $uri_arr)) {
                if ($page->slug == 'types') {
                    $output = str_replace('<!-- ecommerce -->', $ec->product_types_nav(), $output);
                } else {
                    $output = str_replace('<!-- ecommerce -->', $ec->products_by_type($page->slug), $output);
                }
            } else {
                if (in_array('vendors', $uri_arr)) {
                    $output = str_replace('<!-- ecommerce -->', $ec->products_by_vendor($page->slug), $output);
                } else {
                    $output = str_replace('<!-- ecommerce -->', $ec->product_show($page->slug), $output);
                }
            }
        }
        //add cart actions
        if ($cart->hasItems()) {
            $cart_actions = '<div id="cart-actions"><ul>';
            if (!in_array('cart', $uri_arr)) {
                $cart_actions .= '<li><a href="/products/cart">View Cart</a></li>';
            }
            if (!in_array('checkout', $uri_arr) && !in_array('cart', $uri_arr)) {
                $cart_actions .= '<li class="last"><a href="https://www.emedamerica.com/products/checkout">Checkout</a></li>';
            }
            $cart_actions .= '</ul></div>';
            $output = str_replace('<!-- ecommerce cart actions -->', $cart_actions, $output);
        }
    }
    // add ecommerce stylesheet to the frontend layout
    $output = str_replace('</head>', '<link rel="stylesheet" href="/public/ecommerce/ecommerce.css" type="text/css" /></head>', $output);
    //add ecommerce js file
    $output = str_replace('</head>', '<script type="text/javascript" charset="utf-8" src="/public/ecommerce/ecommerce.js"></script></head>', $output);
    // add flash to the frontend
    if ($ec->get_flash()) {
        $output = str_replace('<!-- ecommerce flash -->', $ec->get_flash(), $output);
    }
    // write frontend output
    echo $output;
    // clear the flash
    $_SESSION['ecommerce_flash'] = '';
    die;
}