public function postAddtocart() { $product = Product::find(Input::get('id')); $quantity = Input::get('quantity'); Cart::add(array('id' => $product->id, 'name' => $product->title, 'price' => $product->price, 'qty' => $quantity, 'image' => $product->image)); return Redirect::to('store/cart'); }
public function addToCart($deal_id) { $amount = 1; if ($amount <= 0) { throw new BadRequestHttpException('QUALITY_MUST_GREATER_THAN_0'); } $deal = Deal::find($deal_id); if ($deal == null) { throw new NotFoundException('NOT_FOUND'); } if ($deal->stock < $amount) { throw new BadRequestHttpException('OUT_OF_STOCK'); } if ($deal->time_expired < Carbon::now()) { throw new BadRequestHttpException('EXPIRED'); } // --- Check if deal is existed in cart $deal_cart = \Cart::get($deal_id); if ($deal_cart == null) { \Cart::add(['id' => $deal->id, 'name' => $deal->name, 'quantity' => $amount, 'price' => $deal->deal_price, 'attributes' => ['list_price' => $deal->list_price, 'time_expired' => $deal->time_expired, 'thumb' => $deal->getThumb()]]); } else { \Cart::update($deal_id, ['quantity' => $amount]); } return redirect('/gio-hang'); }
public function add(){ if(IS_AJAX ===false) throw new Exception('请求错误'); $result = array(); if(is_null($this->uid)){ $data = array( 'id' => $this->_get('gid','intval'), 'name' =>'', 'num' =>1, 'price' =>0 ); Cart::add($data); $total = count($_SESSION['cart']['goods']); $result = array('status'=>true,'total'=>$total); }else{ $data = array(); $data['goods_id'] = $this->_get('gid','intval'); $data['user_id'] = $this->uid; $data['goods_num'] = 1; $result = $this->checkAdd($data); if($result){ $db = K('cart'); $where = array('user_id'=>$data['user_id']); $total = $db->countCart($where); $result = array('status'=>true,'total'=>$total); } } exit(json_encode($result)); }
public function addRoomDetailsToCart() { $addToCartDetailsOfRoom = Input::all(); Cart::add(array('id' => $addToCartDetailsOfRoom['roomIDBook'], 'name' => $addToCartDetailsOfRoom['branchBook'], 'qty' => 1, 'price' => $addToCartDetailsOfRoom['priceBook'])); //Cart::destroy(); $addedToCart = true; return Response::json($addedToCart); }
public function addData($data, $add, $type) { $delivery = array(); $cart = new Cart(); if ($data->{$type}->currency == 'RUR') { $currency_id = Currency::getIdByIsoCode('RUB'); } else { $currency_id = Currency::getIdByIsoCode($data->cart->currency); } $def_currency = Configuration::get('PS_CURRENCY_DEFAULT'); $this->context->cookie->id_currency = $def_currency != $currency_id ? $currency_id : $def_currency; $this->context->cookie->write(); $this->context->currency = new Currency($this->context->cookie->id_currency); $cart->id_lang = (int) $this->context->cookie->id_lang; $cart->id_currency = (int) $this->context->cookie->id_currency; $cart->id_guest = (int) $this->context->cookie->id_guest; $cart->add(); $this->context->cookie->id_cart = (int) $cart->id; $this->context->cookie->write(); $buyer = isset($data->{$type}->buyer) ? $data->{$type}->buyer : ''; $b = array(); if ($add) { $delivery = isset($data->{$type}->delivery->address) ? $data->{$type}->delivery->address : new stdClass(); $street = isset($delivery->street) ? ' Улица: ' . $delivery->street : 'Самовывоз'; $subway = isset($delivery->subway) ? ' Метро: ' . $delivery->subway : ''; $block = isset($delivery->block) ? ' Корпус/Строение: ' . $delivery->block : ''; $floor = isset($delivery->floor) ? ' Этаж: ' . $delivery->floor : ''; $house = isset($delivery->house) ? ' Дом: ' . $delivery->house : ''; $address1 = $street . $subway . $block . $floor . $house; $customer = new Customer(Configuration::get('YA_POKUPKI_CUSTOMER')); $address = new Address(); $address->firstname = $customer->firstname; $address->lastname = $customer->lastname; $address->phone_mobile = isset($buyer->phone) ? $buyer->phone : 999999; $address->postcode = isset($delivery->postcode) ? $delivery->postcode : 00; $address->address1 = $address1; $address->city = isset($delivery->city) ? $delivery->city : 'Город'; $address->alias = 'pokupki_' . substr(md5(time() . _COOKIE_KEY_), 0, 7); $address->id_customer = $customer->id; $address->id_country = Configuration::get('PS_COUNTRY_DEFAULT'); $address->save(); $cart->id_address_invoice = (int) $address->id; $cart->id_address_delivery = (int) $address->id; $id_address = (int) $address->id; $cart->update(); $cart->id_customer = (int) $customer->id; $this->context->cookie->id_customer = (int) $customer->id; $this->context->cookie->write(); $b = array('address' => $address, 'customer' => $customer); } CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); $a = array('cart' => $cart); $dd = array_merge($a, $b); return $dd; }
public function postAdd() { if (Request::ajax()) { $productId = Input::get('productId'); $product = Product::findOrFail($productId); $name = Input::get('name'); $price = Input::get('price'); $link = 'product/' . $product->link; Cart::add(['id' => $productId, 'name' => $name, 'qty' => 1, 'price' => $price, 'options' => ['link' => $link]]); return Response::json(array('productId' => $productId, 'name' => $name, 'price' => $price, 'link' => $product->link)); } }
/** * @expectedException App\Exceptions\OrderCreationException */ public function testMakeNewOrderNotWorking() { $worker = \App::make('App\\Droit\\Shop\\Order\\Worker\\OrderWorkerInterface'); // Price 2.00 chf \Cart::add(55, 'Uno', 1, '100', array('weight' => 155)); $shipping = factory(App\Droit\Shop\Shipping\Entities\Shipping::class)->make(); $cart = factory(App\Droit\Shop\Cart\Entities\Cart::class)->make(); $user = factory(App\Droit\User\Entities\User::class)->make(); $this->user->shouldReceive('find')->once()->andReturn($user); $this->order->shouldReceive('newOrderNumber')->once()->andReturn('2015-00000003'); $this->order->shouldReceive('create')->once()->andReturn(null); $this->cart->shouldReceive('create')->once()->andReturn($cart); $result = $worker->make($shipping); }
public function requestAction() { global $smarty, $cookie, $cart, $link; parent::requestAction(); if (!Validate::isLoadedObject($cart) && isset($cookie->id_cart)) { $cart = new Cart((int) $cookie->id_cart); } if (Tools::isSubmit('addToCart')) { if (!isset($cart) || !Validate::isLoadedObject($cart)) { $cart = new Cart(); $cart->copyFromPost(); if ($cart->add()) { $cookie->id_cart = $cart->id; } } if (Tools::getRequest('id_product')) { $id_product = Tools::getRequest('id_product'); } if (Tools::getRequest('quantity')) { $quantity = Tools::getRequest('quantity'); } if (Tools::getRequest('id_attributes')) { $attributes = Tools::getRequest('id_attributes'); } $product = new Product(intval($id_product)); if (Validate::isLoadedObject($cart)) { $cart->addProduct($id_product, $quantity, $product->price, $attributes); } Tools::redirect($link->getPage('CartView')); } if (isset($_GET['delete']) and intval($_GET['delete']) > 0) { $cart->deleteProduct(intval($_GET['delete'])); Tools::redirect($link->getPage('CartView')); } if (Tools::isSubmit('cart_update')) { $quantitys = Tools::getRequest('quantity'); if (count($quantitys) > 0) { foreach ($quantitys as $key => $val) { $cart->updateProduct($key, $val['quantity']); } } Tools::redirect($link->getPage('CartView')); } if (isset($cart) && Validate::isLoadedObject($cart)) { $this->cart_info = $cart->getCartInfo(); $this->cart_info["cart_msg"] = $cart->msg; } $smarty->assign(array('cart_products' => $this->cart_info['cart_products'], 'cart_quantity' => $this->cart_info['cart_quantity'], 'cart_msg' => $this->cart_info['cart_msg'], 'cart_discount' => $this->cart_info['cart_discount'], 'cart_shipping' => $this->cart_info['cart_shipping'], 'cart_total' => $this->cart_info['cart_total'], 'enjoy_free_shipping' => (double) Configuration::get('ENJOY_FREE_SHIPPING'))); }
/** * Setup the layout used by the controller. * * @return void */ protected function getItem() { if (Request::ajax()) { $inp = Input::all(); $misc = Misc::where('item_id', '=', $inp['id'])->where('item_talla', '=', $inp['talla'])->where('item_color', '=', $inp['color'])->where('deleted', '=', 0)->first(); $aux = Misc::where('item_id', '=', $inp['id'])->where('deleted', '=', 0)->first(); $img = Images::where('deleted', '!=', 1)->where('misc_id', '=', $aux->id)->first(); $talla = Tallas::find($inp['talla']); $color = Colores::find($inp['color']); Cart::add(array('id' => $inp['id'], 'name' => $inp['name'], 'qty' => 1, 'options' => array('misc' => $misc->id, 'img' => $img->image, 'talla' => $inp['talla'], 'talla_desc' => $talla->talla_desc, 'color' => $inp['color'], 'color_desc' => $color->color_desc), 'price' => $inp['price'])); $rowid = Cart::search(array('id' => $inp['id'], 'options' => array('talla' => $inp['talla'], 'color' => $inp['color']))); $item = Cart::get($rowid[0]); return Response::json(array('rowid' => $rowid[0], 'img' => $img->image, 'id' => $item->id, 'name' => $item->name, 'talla' => $talla->talla_desc, 'color' => $color->color_desc, 'qty' => $item->qty, 'price' => $item->price, 'subtotal' => $item->subtotal, 'cantArt' => Cart::count(), 'total' => Cart::total())); } }
public function addtocart($goods_id) { $msg = array(); if (!$goods_id) { $msg['error'] = '-1'; $msg['msg'] = '加入购物车失败!'; echo json_encode($msg); throw new Exception('exit'); } $goods_id = (int) $goods_id; //模拟下单start $uid = LuS::get('uid'); $data['goods_id'] = $goods_id; $data['goods_num'] = 1; // $data = $goods_id; //购物车已经存在$goods_id商品的数量 $cart_goods_info = Cart::getCartGoodsInfoByGoodsId($uid, $goods_id); //检查库存 $goods_info = AdminGoodsM::getGoodsInfoByGoodsId($goods_id); if ($goods_info['goods_num'] < $data['goods_num'] + $cart_goods_info['goods_num']) { $msg['error'] = '-2'; $msg['msg'] = '库存不足!'; echo json_encode($msg); throw new Exception('exit'); } //添加 $add_rs = Cart::add($uid, $data); if ($add_rs) { //模拟下单end $msg['error'] = '1'; $msg['msg'] = '加入购物车成功!'; $msg['num'] = Cart::getCount($uid); } else { //模拟下单end $msg['error'] = '-1'; $msg['msg'] = '加入购物车失败!'; } echo json_encode($msg); throw new Exception('exit'); }
$total = 0.00; $unit = ''; $callback = function ($quantity, $product) use ($tax, &$total, &$unit) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); $unit = 'Rupees '; }; array_walk($this->products, $callback); return $unit .round($total, 2); } } $my_cart = new Cart; // Add some items to the cart $my_cart->add('butter', 1); $my_cart->add('milk', 3); $my_cart->add('eggs', 6); $my_cart->getArray(); //Array ( [butter] => 1 [milk] => 3 [eggs] => 6 ) // Print the total with a 5% sales tax. print $my_cart->getTotal(0.05) . "\n"; // The result is 54.29 ?> <?php #Example #2 Passing function parameters by reference function add_some_extra(&$string) { $string .= 'and something extra.'. "\n\n"; } $str = "\n\n" . 'This is a string, '; add_some_extra($str);
public function add_to_cart($return = 'return') { if (!\Input::post()) { return false; } // check for a valid CSRF token // if (!\Security::check_token()) // { // \Messages::error('CSRF attack or expired CSRF token.'); // return false; // } $post = \Input::post(); $product_id = $post['product_id']; if (!($product = Model_Product::find_one_by_id($product_id))) { return; } $selected_attributes = array(); $selected_attributes_json = null; if (isset($post['select']) && !empty($post['select'])) { ksort($post['select']); $selected_attributes_json = json_encode($post['select']); } $product_data = Model_Product::product_data($product, $selected_attributes_json, \Input::post('select'), \Input::post('attributeid')); if (!empty($product_data)) { $attr_obj = null; if (!empty($product_data['current_attributes'])) { $attr_obj = $product_data['current_attributes'][0]->product_attribute; } $item = array('title' => $product->title, 'id' => $product->id, 'product_attribute_id' => $attr_obj ? $attr_obj->id : null, 'quantity' => $post['quantity'], 'attributes' => $attr_obj ? $attr_obj->attributes : null, 'product_code' => $product_data['code'], 'unique_id' => uniqid()); if ($product_data['sale']) { $item += array('price' => $product_data['sale'], 'price_type' => 'sale_price'); } else { $item += array('price' => $product_data['retail_price'], 'price_type' => 'retail_price'); } $stock_options = \Config::load('stock-option.db'); if ($stock_options['allow_buy_out_of_stock'] != 1 && $product_data['stock_quantity'] < 1) { \Messages::error('Product is Out of Stock.'); echo \Messages::display(); return; } $uid = \Cart::generateUID($item); if (\Cart::exists($uid)) { $cart_item = \Cart::item($uid); $quantity = $cart_item->get('quantity'); if ($product_data['stock_quantity'] > 0 && $product_data['stock_quantity'] <= $quantity) { \Messages::error($product->title . ' has not enough stock to fulfill your request.'); echo \Messages::display(); return; } } if ($return == 'return') { \Cart::add($item); // Always return cart item id $uid = \Cart::generateUID($item); if (\Cart::exists($uid)) { return $uid; } return false; } else { $uid = \Cart::generateUID($item); if (\Cart::exists($uid)) { echo $uid; } echo ''; exit; } \Messages::success('Product successfully added to cart.'); echo \Messages::display(); } return false; }
private function _getCart($id_customer, $id_address_billing, $id_address_shipping, $productsNode, $currency, $shipping_method) { $cart = new Cart(); $cart->id_customer = $id_customer; $cart->id_address_invoice = $id_address_billing; $cart->id_address_delivery = $id_address_shipping; $cart->id_currency = Currency::getIdByIsoCode((string) $currency == '' ? 'EUR' : (string) $currency); $cart->id_lang = Configuration::get('PS_LANG_DEFAULT'); $cart->recyclable = 0; $cart->secure_key = md5(uniqid(rand(), true)); $actual_configuration = unserialize(Configuration::get('SHOPPING_FLUX_SHIPPING_MATCHING')); $carrier_to_load = isset($actual_configuration[base64_encode(Tools::safeOutput($shipping_method))]) ? (int) $actual_configuration[base64_encode(Tools::safeOutput($shipping_method))] : (int) Configuration::get('SHOPPING_FLUX_CARRIER'); $carrier = Carrier::getCarrierByReference($carrier_to_load); //manage case PS_CARRIER_DEFAULT is deleted $carrier = is_object($carrier) ? $carrier : new Carrier($carrier_to_load); $cart->id_carrier = $carrier->id; $cart->add(); foreach ($productsNode->Product as $product) { $skus = explode('_', $product->SKU); $added = $cart->updateQty((int) $product->Quantity, (int) $skus[0], isset($skus[1]) ? $skus[1] : null); if ($added < 0 || $added === false) { return false; } } $cart->update(); return $cart; }
public function addOrder(ShopgateOrder $order) { $this->log("PS start add_order", ShopgateLogger::LOGTYPE_DEBUG); $shopgateOrder = PSShopgateOrder::instanceByOrderNumber($order->getOrderNumber()); if ($shopgateOrder->id) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DUPLICATE_ORDER, 'external_order_id: ' . $shopgateOrder->id_order, true); } $comments = array(); // generate products array $products = $this->insertOrderItems($order); //Get or create customer $id_customer = Customer::customerExists($order->getMail(), true, false); $customer = new Customer($id_customer ? $id_customer : (int) $order->getExternalCustomerId()); if (!$customer->id) { $customer = $this->createCustomer($customer, $order); } // prepare addresses: company has to be shorten. add mobile phone / telephone $this->prepareAddresses($order); //Get invoice and delivery addresses $invoiceAddress = $this->getPSAddress($customer, $order->getInvoiceAddress()); $deliveryAddress = $order->getInvoiceAddress() == $order->getDeliveryAddress() ? $invoiceAddress : $this->getPSAddress($customer, $order->getDeliveryAddress()); //Creating currency $this->log("PS setting currency", ShopgateLogger::LOGTYPE_DEBUG); $id_currency = $order->getCurrency() ? Currency::getIdByIsoCode($order->getCurrency()) : $this->id_currency; $currency = new Currency($id_currency ? $id_currency : $this->id_currency); //Creating new cart $this->log("PS set cart variables", ShopgateLogger::LOGTYPE_DEBUG); $cart = new Cart(); $cart->id_lang = $this->id_lang; $cart->id_currency = $currency->id; $cart->id_address_delivery = $deliveryAddress->id; $cart->id_address_invoice = $invoiceAddress->id; $cart->id_customer = $customer->id; if (version_compare(_PS_VERSION_, '1.4.1.0', '>=')) { // id_guest is a connection to a ps_guest entry which includes screen width etc. // is_guest field only exists in Prestashop 1.4.1.0 and higher $cart->id_guest = $customer->is_guest; } $cart->recyclable = 0; $cart->gift = 0; $cart->id_carrier = (int) Configuration::get('SHOPGATE_CARRIER_ID'); $cart->secure_key = $customer->secure_key; $this->log("PS try to create cart", ShopgateLogger::LOGTYPE_DEBUG); if (!$cart->add()) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create cart', true); } //Adding items to cart $this->log("PS adding items to cart", ShopgateLogger::LOGTYPE_DEBUG); foreach ($products as $p) { $this->log("PS cart updateQty product id: " . $p['id_product'], ShopgateLogger::LOGTYPE_DEBUG); $this->log("PS cart updateQty product quantity: " . $p['quantity'], ShopgateLogger::LOGTYPE_DEBUG); $this->log("PS cart updateQty product quantity_difference: " . $p['quantity_difference'], ShopgateLogger::LOGTYPE_DEBUG); $this->log("PS cart updateQty product id_product_attribute: " . $p['id_product_attribute'], ShopgateLogger::LOGTYPE_DEBUG); $this->log("PS cart updateQty product delivery address: " . $deliveryAddress->id, ShopgateLogger::LOGTYPE_DEBUG); //TODO deal with customizations $id_customization = false; if ($p['quantity'] - $p['quantity_difference'] > 0) { // only if the result of $p['quantity'] - $p['quantity_difference'] is higher then 0 $cart->updateQty($p['quantity'] - $p['quantity_difference'], $p['id_product'], $p['id_product_attribute'], $id_customization, 'up', $deliveryAddress->id); } if ($p['quantity_difference'] > 0) { $this->log("PS try to add cart message ", ShopgateLogger::LOGTYPE_DEBUG); $message = new Message(); $message->id_cart = $cart->id; $message->private = 1; $message->message = 'Warning, wanted quantity for product "' . $p['name'] . '" was ' . $p['quantity'] . ' unit(s), however, the amount in stock is ' . $p['quantity_in_stock'] . ' unit(s). Only ' . $p['quantity_in_stock'] . ' unit(s) were added to the order'; $message->save(); } } $id_order_state = 0; $shopgate = new Shopgate(); $payment_name = $shopgate->getTranslation('Mobile Payment'); $this->log("PS map payment method", ShopgateLogger::LOGTYPE_DEBUG); if (!$order->getIsShippingBlocked()) { $id_order_state = $this->getOrderStateId('PS_OS_PREPARATION'); switch ($order->getPaymentMethod()) { case 'SHOPGATE': $payment_name = $shopgate->getTranslation('Shopgate'); break; case 'PREPAY': $payment_name = $shopgate->getTranslation('Bankwire'); $id_order_state = $this->getOrderStateId('PS_OS_BANKWIRE'); break; case 'COD': $payment_name = $shopgate->getTranslation('Cash on Delivery'); break; case 'PAYPAL': $payment_name = $shopgate->getTranslation('PayPal'); break; default: break; } } else { $id_order_state = $this->getOrderStateId('PS_OS_SHOPGATE'); switch ($order->getPaymentMethod()) { case 'SHOPGATE': $payment_name = $shopgate->getTranslation('Shopgate'); break; case 'PREPAY': $payment_name = $shopgate->getTranslation('Bankwire'); break; case 'COD': $payment_name = $shopgate->getTranslation('Cash on Delivery'); break; case 'PAYPAL': $id_order_state = $this->getOrderStateId('PS_OS_PAYPAL'); $payment_name = $shopgate->getTranslation('PayPal'); break; default: $id_order_state = $this->getOrderStateId('PS_OS_SHOPGATE'); break; } } $shippingCosts = $order->getAmountShipping() + $order->getAmountShopPayment(); //Creates shopgate order record and save shipping cost for future use $this->log("PS set PSShopgateOrder object variables", ShopgateLogger::LOGTYPE_DEBUG); $shopgateOrder = new PSShopgateOrder(); $shopgateOrder->order_number = $order->getOrderNumber(); $shopgateOrder->shipping_cost = $shippingCosts; $shopgateOrder->shipping_service = Configuration::get('SHOPGATE_SHIPPING_SERVICE'); $shopgateOrder->id_cart = $cart->id; $shopgateOrder->shop_number = $this->config->getShopNumber(); $shopgateOrder->comments = $this->jsonEncode($comments); if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) { $this->log("PS lower 1.4.0.2: ", ShopgateLogger::LOGTYPE_DEBUG); // Fix: sets in database ps_delivery all zones of passed shippingCosts $this->setShippingCosts(0); } $this->log("PS try creating PSShopgateOrder object", ShopgateLogger::LOGTYPE_DEBUG); if (!$shopgateOrder->add()) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create shopgate order', true); } //PS 1.5 compatibility if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) { $this->log("PS 1.5.x.x: set cart context", ShopgateLogger::LOGTYPE_DEBUG); $this->context = Context::getContext(); $this->context->cart = $cart; $this->log("PS 1.5.x.x: \$cart->setDeliveryOption(array(\$cart->id_address_delivery => \$cart->id_carrier.','))\n\n==============", ShopgateLogger::LOGTYPE_DEBUG); $cart->setDeliveryOption(array($cart->id_address_delivery => $cart->id_carrier . ',')); $this->log("PS 1.5.x.x: \$cart->update()", ShopgateLogger::LOGTYPE_DEBUG); $cart->update(); $cart->id_carrier = (int) Configuration::get('SHOPGATE_CARRIER_ID'); } $amountPaid = $order->getAmountComplete(); if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) { // substract the shipping costs. $amountPaid -= $shippingCosts; } $this->log("\$shopgate->validateOrder(\$cart->id, \$id_order_state, \$amountPaid, \$payment_name, NULL, array(), NULL, false, \$cart->secure_key", ShopgateLogger::LOGTYPE_DEBUG); $this->log("\$cart->id = " . var_export($cart->id, true) . "\n\$id_order_state = " . var_export($id_order_state, true) . "\n\$amountPaid = " . var_export($amountPaid, true) . "\n\$payment_name = " . var_export($payment_name, true) . "\n\$cart->secure_key" . var_export($cart->secure_key, true) . "\n==============", ShopgateLogger::LOGTYPE_DEBUG); try { $shopgate->validateOrder($cart->id, $id_order_state, $amountPaid, $payment_name, NULL, array(), NULL, false, $cart->secure_key); } catch (Swift_Message_MimeException $ex) { $this->log("\$shopgate->validateOrder(\$cart->id, \$id_order_state, \$amountPaid, \$payment_name, NULL, array(), NULL, false, \$cart->secure_key) FAILED with Swift_Message_MimeException", ShopgateLogger::LOGTYPE_ERROR); // catch Exception if there is a problem with sending mails } if (version_compare(_PS_VERSION_, '1.4.0.2', '<') && (int) $shopgate->currentOrder > 0) { $this->log("PS < 1.4.0.2: update shipping and payment cost", ShopgateLogger::LOGTYPE_DEBUG); // in versions below 1.4.0.2 the shipping and payment costs must be updated after the order $updateShopgateOrder = new Order($shopgate->currentOrder); $updateShopgateOrder->total_paid = $order->getAmountComplete(); $updateShopgateOrder->total_paid_real = $order->getAmountComplete(); $updateShopgateOrder->total_products_wt = $order->getAmountItems(); $updateShopgateOrder->total_shipping = $order->getAmountShipping() + $order->getAmountShopPayment(); $updateShopgateOrder->update(); } if ((int) $shopgate->currentOrder > 0) { $this->log("\$shopgateOrder->update()", ShopgateLogger::LOGTYPE_DEBUG); $shopgateOrder->id_order = $shopgate->currentOrder; $shopgateOrder->update(); return array('external_order_id' => $shopgate->currentOrder, 'external_order_number' => $shopgate->currentOrder); } else { $this->log("\$shopgateOrder->delete()", ShopgateLogger::LOGTYPE_DEBUG); $shopgateOrder->delete(); throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create order', true); } }
/** * Creating of the PrestaShop order * @param $neteven_order * @param $neteven_orders * @return int */ private function createOrder($neteven_order, $neteven_orders) { if (constant('_PS_VERSION_') >= 1.5) { include_once dirname(__FILE__) . '/OrderInvoiceOverride.php'; } // Treatment of customer $id_customer = $this->addCustomerInBDD($neteven_order); if ($this->time_analyse) { $this->current_time_2 = time(); Toolbox::displayDebugMessage(self::getL('Customer') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's'); } // Treatment of addresses of the customer $id_address_billing = $this->addAddresseInBDD($neteven_order->OrderID, $neteven_order->BillingAddress, 'facturation', $id_customer); $id_address_shipping = $this->addAddresseInBDD($neteven_order->OrderID, $neteven_order->ShippingAddress, 'livraison', $id_customer); if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('Address') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } // Get secure key of customer $secure_key_default = md5(uniqid(rand(), true)); if ($secure_key = Db::getInstance()->getValue('SELECT `secure_key` FROM `' . _DB_PREFIX_ . 'customer` WHERE `id_customer` = ' . (int) $id_customer)) { $secure_key_default = $secure_key; } else { Toolbox::addLogLine(self::getL('Problem with a secure key recovery for the customer / NetEven Order Id') . ' ' . $neteven_order->OrderID); } // Treatment of order informations $total_wt = 0; $total_product = 0; $total_product_wt = 0; foreach ($neteven_orders as $neteven_order_temp) { if ($neteven_order_temp->OrderID == $neteven_order->OrderID) { if (in_array($neteven_order_temp->Status, $this->getValue('t_list_order_status'))) { continue; } $total_product += floatval($neteven_order_temp->Price->_) - floatval($neteven_order_temp->VAT->_); $total_product_wt += floatval($neteven_order_temp->Price->_); } } $total_wt = $total_product_wt + $neteven_order->OrderShippingCost->_; $date_now = date('Y-m-d H:i:s'); if ($this->time_analyse) { $this->current_time_2 = time(); Toolbox::displayDebugMessage(self::getL('Order total') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's'); } // Creating and add order in PrestaShop if (!($res = Db::getInstance()->getRow('SELECT * FROM `' . _DB_PREFIX_ . 'orders_gateway` WHERE `id_order_neteven` = ' . (int) $neteven_order->OrderID . ' AND `id_order_detail_neteven` = 0'))) { // Creating cart $cart = new Cart(); $cart->id_address_delivery = (int) $id_address_shipping; $cart->id_address_invoice = (int) $id_address_billing; $cart->id_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT'); $cart->id_customer = (int) $id_customer; $cart->id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $cart->id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT'); $cart->recyclable = 1; $cart->gift = 0; $cart->gift_message = ''; $cart->date_add = $date_now; $cart->secure_key = $secure_key_default; $cart->date_upd = $date_now; if (!$cart->add()) { Toolbox::addLogLine(self::getL('Failed for cart creation / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); } if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('Cart') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } // Creating order $id_order_temp = 0; $order = new Order(); $order->id_carrier = Configuration::get('PS_CARRIER_DEFAULT'); $order->id_lang = Configuration::get('PS_LANG_DEFAULT'); $order->id_customer = $id_customer; $order->id_cart = $cart->id; $order->id_currency = Configuration::get('PS_CURRENCY_DEFAULT'); $order->id_address_delivery = $id_address_shipping; $order->id_address_invoice = $id_address_billing; $order->secure_key = $secure_key_default; $order->payment = $neteven_order->PaymentMethod; $order->conversion_rate = 1; $order->module = 'nqgatewayneteven'; $order->recyclable = 0; $order->gift = 0; $order->gift_message = ''; $order->shipping_number = ''; //generate reference order $nbr_order_neteven = Configuration::get('NUMBER_ORDER_NETEVEN'); if (false === $nbr_order_neteven) { $nbr_order_neteven = 1; } else { $nbr_order_neteven = (int) str_replace('N', '', $nbr_order_neteven); $nbr_order_neteven++; } $next_ref_gen_order_neteven = 'N' . sprintf('%07s', $nbr_order_neteven); Configuration::updateValue('NUMBER_ORDER_NETEVEN', $next_ref_gen_order_neteven); $order->reference = $next_ref_gen_order_neteven; //----- $carrier = new Carrier((int) $order->id_carrier); $carrier_tax_rate = false; if (method_exists($carrier, 'getTaxesRate')) { $carrier_tax_rate = $carrier->getTaxesRate(new Address($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); } $total_shipping_tax_excl = $carrier_tax_rate ? $neteven_order->OrderShippingCost->_ / ($carrier_tax_rate / 100) : $neteven_order->OrderShippingCost->_; $total_wt = $total_product_wt + $neteven_order->OrderShippingCost->_; $total = $total_product + $total_shipping_tax_excl; $order->total_discounts_tax_excl = 0; $order->total_discounts_tax_incl = 0; $order->total_discounts = 0; $order->total_wrapping_tax_excl = 0; $order->total_wrapping_tax_incl = 0; $order->total_wrapping = 0; $order->total_products = (double) number_format($total_product, 2, '.', ''); $order->total_products_wt = (double) number_format($total_product_wt, 2, '.', ''); $order->total_shipping_tax_excl = (double) number_format($total_shipping_tax_excl, 2, '.', ''); $order->total_shipping_tax_incl = (double) number_format($neteven_order->OrderShippingCost->_, 2, '.', ''); $order->total_shipping = (double) number_format($neteven_order->OrderShippingCost->_, 2, '.', ''); $order->total_paid_tax_excl = (double) number_format($total, 2, '.', ''); $order->total_paid_tax_incl = (double) number_format($total_wt, 2, '.', ''); $order->total_paid_real = (double) number_format($total_wt, 2, '.', ''); $order->total_paid = (double) number_format($total_wt, 2, '.', ''); $order->carrier_tax_rate = 0; $order->total_wrapping = 0; $order->invoice_number = 0; $order->delivery_number = 0; $order->invoice_date = $date_now; $order->delivery_date = $date_now; $order->valid = 1; $order->date_add = $date_now; $order->date_upd = $date_now; if (Configuration::get('PS_SHOP_ENABLE')) { $order->id_shop = (int) Configuration::get('PS_SHOP_DEFAULT'); } if (!$order->add()) { Toolbox::addLogLine(self::getL('Failed for order creation / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); } else { $id_order_temp = $order->id; Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'order_carrier` (`id_order`, `id_carrier`, `id_order_invoice`, `weight`, `shipping_cost_tax_excl`, `shipping_cost_tax_incl`, `tracking_number`, `date_add`) VALUES (' . (int) $id_order_temp . ', ' . (int) Configuration::get('PS_CARRIER_DEFAULT') . ', 0, 0, 0, 0, 0,"' . pSQL(date('Y-m-d H:i:s')) . '")'); Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'message` (`id_order`, `message`, `date_add`) VALUES (' . (int) $id_order_temp . ', "Place de marché ' . $neteven_order->MarketPlaceName . '", "' . pSQL(date('Y-m-d H:i:s')) . '")'); Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'message` (`id_order`, `message`, `date_add`) VALUES (' . (int) $id_order_temp . ', "ID order NetEven ' . $neteven_order->MarketPlaceOrderId . '", "' . pSQL(date('Y-m-d H:i:s')) . '")'); if ($this->time_analyse) { $this->current_time_2 = time(); Toolbox::displayDebugMessage(self::getL('Order') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's'); } Toolbox::addLogLine(self::getL('Add order Id') . ' ' . (int) $id_order_temp . ' ' . self::getL('NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); // Update order state in order $order_state = array_merge($this->getValue('order_state_before'), array($this->getValue('id_order_state_neteven')), $this->getValue('order_state_after')); if (is_array($order_state) && count($order_state) > 0) { foreach ($order_state as $id_order_state) { if (class_exists('OrderInvoiceOverride' && method_exists('OrderInvoiceOverride', 'clearCacheTotalPaid'))) { OrderInvoiceOverride::clearCacheTotalPaid(); } $new_history = new OrderHistory(); $new_history->id_order = (int) $id_order_temp; $new_history->changeIdOrderState((int) $id_order_state, $id_order_temp); $new_history->addWithemail(true, array()); Toolbox::addLogLine(self::getL('Save order state Id') . ' ' . (int) $id_order_state . ' ' . self::getL('NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); } } if ($this->time_analyse) { $this->current_time_0 = time(); Toolbox::displayDebugMessage(self::getL('History') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's'); } // Insert order in orders_gateway table if (!Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'orders_gateway` (`id_order_neteven`, `id_order`, `id_order_detail_neteven`, `date_add`, `date_upd`) VALUES (' . (int) $neteven_order->OrderID . ', ' . (int) $id_order_temp . ', 0, "' . pSQL($date_now) . '", "' . pSQL($date_now) . '")')) { Toolbox::addLogLine(self::getL('Failed for save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID); } else { Toolbox::addLogLine(self::getL('Save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID); } } } else { $id_order_temp = $res['id_order']; Toolbox::addLogLine(self::getL('Get already exported order Id') . ' ' . $res['id_order'] . ' ' . self::getL('NetEven Order Id') . ' ' . (int) $neteven_order->OrderID); } return $id_order_temp; }
public function hookheader($params) { //Change context Shop to be default if ($this->isVersionOneDotFive() && Shop::isFeatureActive()) { $oldContextShop = $this->getContextShop(); $this->setContextShop(); } //End of change // Check if the module is configured if (!Configuration::get('EBAY_PAYPAL_EMAIL')) { return false; } // Fix hook update product attribute $this->hookupdateProductAttributeEbay(); // init date to check from if (Configuration::get('EBAY_INSTALL_DATE') < date('Y-m-d', strtotime('-30 days')) . 'T' . date('H:i:s', strtotime('-30 days'))) { //If it is more than 30 days that we installed the module $dateToCheckFrom = Configuration::get('EBAY_ORDER_LAST_UPDATE'); $dateToCheckFromArray = explode('T', $dateToCheckFrom); $dateToCheckFrom = date("Y-m-d", strtotime($dateToCheckFromArray[0] . " -30 day")); $dateToCheckFrom .= 'T' . $dateToCheckFromArray[1]; } else { //If it is less than 30 days that we installed the module $dateToCheckFrom = Configuration::get('EBAY_INSTALL_DATE'); $dateToCheckFromArray = explode('T', $dateToCheckFrom); $dateToCheckFrom = date("Y-m-d", strtotime($dateToCheckFromArray[0] . " -1 day")); $dateToCheckFrom .= 'T' . $dateToCheckFromArray[1]; } if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-30 minutes')) . 'T' . date('H:i:s', strtotime('-30 minutes')) . '.000Z') { $dateNew = date('Y-m-d') . 'T' . date('H:i:s') . '.000Z'; $this->setConfiguration('EBAY_ORDER_LAST_UPDATE', $dateNew); // eBay Request $ebay = new eBayRequest(); $page = 1; $orderList = array(); $orderCount = 0; $orderCountTmp = 100; while ($orderCountTmp == 100 && $page < 10) { $orderListTmp = $ebay->getOrders($dateToCheckFrom, $dateNew, $page); $orderCountTmp = count($orderListTmp); $orderList = array_merge((array) $orderList, (array) $orderListTmp); $orderCount += $orderCountTmp; $page++; } // Lock if ($orderList) { foreach ($orderList as $korder => $order) { if ($order['status'] == 'Complete' && $order['amount'] > 0.1 && isset($order['product_list']) && count($order['product_list'])) { if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) { // Check for empty name $order['firstname'] = trim($order['firstname']); $order['familyname'] = trim($order['familyname']); if (empty($order['familyname'])) { $order['familyname'] = $order['firstname']; } if (empty($order['firstname'])) { $order['firstname'] = $order['familyname']; } if (empty($order['phone']) || !Validate::isPhoneNumber($order['phone'])) { $order['phone'] = '0100000000'; } if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname'])) { // Getting the customer $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'customer` WHERE `active` = 1 AND `email` = \'' . pSQL($order['email']) . '\' AND `deleted` = 0' . (substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0')); // Add customer if he doesn't exist if ($id_customer < 1) { $customer = new Customer(); $customer->id_gender = 0; $customer->id_default_group = 1; $customer->secure_key = md5(uniqid(rand(), true)); $customer->email = $order['email']; $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand())); $customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s')); $customer->newsletter = 0; $customer->lastname = pSQL($order['familyname']); $customer->firstname = pSQL($order['firstname']); $customer->active = 1; $customer->add(); $id_customer = $customer->id; } // Search if address exists $id_address = (int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $id_customer . ' AND `alias` = \'eBay\''); if ($id_address > 0) { $address = new Address((int) $id_address); } else { $address = new Address(); $address->id_customer = (int) $id_customer; } $address->id_country = (int) Country::getByIso($order['country_iso_code']); $address->alias = 'eBay'; $address->lastname = pSQL($order['familyname']); $address->firstname = pSQL($order['firstname']); $address->address1 = pSQL($order['address1']); $address->address2 = pSQL($order['address2']); $address->postcode = pSQL($order['postalcode']); $address->city = pSQL($order['city']); $address->phone = pSQL($order['phone']); $address->active = 1; if ($id_address > 0 && Validate::isLoadedObject($address)) { $address->update(); } else { $address->add(); } $id_address = $address->id; $flag = 1; foreach ($order['product_list'] as $product) { if ((int) $product['id_product'] < 1 || !Db::getInstance()->getValue('SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product['id_product'])) { $flag = 0; } if (isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 && !Db::getInstance()->getValue('SELECT `id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_product_attribute` = ' . (int) $product['id_product_attribute'])) { $flag = 0; } } if ($flag == 1) { //Create a Cart for the order $cartNbProducts = 0; $cartAdd = new Cart(); Context::getContext()->customer = new Customer($id_customer); $cartAdd->id_customer = $id_customer; $cartAdd->id_address_invoice = $id_address; $cartAdd->id_address_delivery = $id_address; $cartAdd->id_carrier = 0; $cartAdd->id_lang = $this->id_lang; $cartAdd->id_currency = Currency::getIdByIsoCode('EUR'); $cartAdd->recyclable = 0; $cartAdd->gift = 0; $cartAdd->add(); $id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); foreach ($order['product_list'] as $product) { $prod = new Product($product['id_product'], false, $id_lang); // Qty of product or attribute if (isset($product['id_product_attribute']) && !empty($product['id_product_attribute'])) { $minimalQty = (int) Attribute::getAttributeMinimalQty($product['id_product_attribute']); } else { $minimalQty = $prod->minimal_quantity; } if ($product['quantity'] >= $minimalQty) { if ($this->isVersionOneDotFive()) { $update = $cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL, false, 'up', 0, new Shop(Configuration::get('PS_SHOP_DEFAULT'))); if ($update === TRUE) { $cartNbProducts++; } } elseif ($cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL)) { $cartNbProducts++; } } else { $templateVars = array('{name_product}' => $prod->name, '{min_qty}' => $minimalQty, '{cart_qty}' => $product['quantity']); Mail::Send((int) Configuration::get('PS_LANG_DEFAULT'), 'alertEbay', Mail::l('Product quantity', $id_lang), $templateVars, strval(Configuration::get('PS_SHOP_EMAIL')), NULL, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/'); } } $cartAdd->update(); // Check number of products in the cart and check if order has already been taken if ($cartNbProducts > 0 && !Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) { // Fix on sending e-mail Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = ' . (int) $id_customer); $customerClear = new Customer(); if (method_exists($customerClear, 'clearCache')) { $customerClear->clearCache(true); } $paiement = new eBayPayment(); // Validate order if ($this->isVersionOneDotFive()) { $customer = new Customer($id_customer); $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency), false, $customer->secure_key, new Shop(Configuration::get('PS_SHOP_DEFAULT'))); } else { $customer = new Customer($id_customer); $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency), false, $customer->secure_key); } $id_order = $paiement->currentOrder; // Fix on date Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', array('date_add' => pSQL($order['date_add'])), 'UPDATE', '`id_order` = ' . (int) $id_order); // Fix on sending e-mail Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = ' . (int) $id_customer); // Update price (because of possibility of price impact) foreach ($order['product_list'] as $product) { $tax_rate = Db::getInstance()->getValue('SELECT `tax_rate` FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', array('product_price' => floatval($product['price'] / (1 + $tax_rate / 100)), 'reduction_percent' => 0), 'UPDATE', '`id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']); } $updateOrder = array('total_paid' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']), 'total_products' => floatval(Db::getInstance()->getValue('SELECT SUM(`product_price`) FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $id_order)), 'total_products_wt' => floatval($order['amount'] - $order['shippingServiceCost']), 'total_shipping' => floatval($order['shippingServiceCost'])); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $updateOrder, 'UPDATE', '`id_order` = ' . (int) $id_order); // Register the ebay order ref Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int) $id_order), 'INSERT'); if (!$this->isVersionOneDotFive()) { //Fix on eBay not updating $params = array(); foreach ($order['product_list'] as $product) { $params['product'] = new Product((int) $product['id_product']); $this->hookaddproduct($params); } } } else { $cartAdd->delete(); $orderList[$korder]['errors'][] = $this->l('Could not add product to cart (maybe your stock quantity is 0)'); } } else { $orderList[$korder]['errors'][] = $this->l('Could not found products in database'); } } else { $orderList[$korder]['errors'][] = $this->l('Invalid e-mail'); } } else { $orderList[$korder]['errors'][] = $this->l('Order already imported'); } } else { $orderList[$korder]['errors'][] = $this->l('Status not complete or amount less than 0.1 or no product matching'); } } file_put_contents(dirname(__FILE__) . '/log/orders.php', "<?php\n\n" . '$dateLastImport = ' . "'" . date('d/m/Y H:i:s') . "';\n\n" . '$orderList = ' . var_export($orderList, true) . ";\n\n"); } } // Set old Context Shop if ($this->isVersionOneDotFive() && Shop::isFeatureActive()) { $this->setContextShop($oldContextShop); } }
public static function modify($uid) { //没有登录 $data['uid'] = $uid; if (!$data['uid']) { return false; } //从购物车取出没有对应用户的商品 $sid_where['sid'] = session_id(); $sid_where['uid'] = '0'; $sid_cart_goods_info = self::_list($sid_where); if (!$sid_cart_goods_info) { return false; } //检查用户是否已经存在商品,如果存在添加数量,并删除该条没有对应用户的数据 foreach ($sid_cart_goods_info as $key => $value) { $goods_id = $value['goods_id']; $rs = Cart::getCartGoodsInfoByGoodsId($uid, $goods_id); if ($rs) { $add_data['goods_id'] = $goods_id; $add_data['goods_num'] = $value['goods_num']; Cart::add($uid, $add_data); //删除没有登录情况下的购物车商品 $del_where['sid'] = session_id(); $del_where['uid'] = '0'; $del_where['goods_id'] = $goods_id; Cart::delete($del_where); } } $data['username'] = LuS::get('username'); $where['sid'] = session_id(); $where['uid'] = '0'; return Cart::update($data, $where); }
protected function restoreOrderToCart(Cart $cart) { if (!$cart || !ValidateCore::isLoadedObject($cart)) { return null; } Db::getInstance()->execute('BEGIN'); $new_cart = null; try { /** @var CartCore $new_cart */ /** @noinspection PhpUndefinedClassInspection */ $new_cart = new Cart(); /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_customer = (int) $cart->id_customer; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_address_delivery = (int) $cart->id_address_delivery; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_address_invoice = (int) $cart->id_address_invoice; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_lang = (int) $cart->id_lang; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_currency = (int) $cart->id_currency; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->id_carrier = (int) $cart->id_carrier; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->recyclable = (int) $cart->recyclable; /** @noinspection PhpUndefinedFieldInspection */ $new_cart->gift = (int) $cart->gift; $new_cart->add(); /** @noinspection PhpUndefinedMethodInspection */ $products = $cart->getProducts(); if ($products) { foreach ($products as $p) { $idProduct = $p['id_product']; $idProductAttribute = $p['id_product_attribute']; $qty = $p['cart_quantity']; /** @noinspection PhpUndefinedClassInspection */ /** @noinspection PhpUndefinedFieldInspection */ $producToAdd = new Product((int) $idProduct, true, (int) $cart->id_lang); /** @noinspection PhpUndefinedFieldInspection */ if (!$producToAdd->id || !$producToAdd->active) { continue; } /* Check the quantity availability */ if ($idProductAttribute > 0 and is_numeric($idProductAttribute)) { /** @noinspection PhpUndefinedClassInspection */ /** @noinspection PhpUndefinedMethodInspection */ /** @noinspection PhpUndefinedFieldInspection */ if (!$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) { /* There is not enough product attribute in stock - set customer qty to current stock on hand */ /** @noinspection PhpUndefinedFunctionInspection */ $qty = getAttributeQty($idProductAttribute); } } elseif (!$producToAdd->checkQty((int) $qty)) { /* There is not enough product in stock - set customer qty to current stock on hand */ /** @noinspection PhpUndefinedMethodInspection */ $qty = $producToAdd->getQuantity($idProduct); } $new_cart->updateQty((int) $qty, (int) $idProduct, (int) $idProductAttribute, NULL, 'up'); unset($p); } } $new_cart->update(); Db::getInstance()->execute('COMMIT'); } catch (Exception $e) { Db::getInstance()->execute('ROLLBACK'); throw $e; } /** @noinspection PhpUndefinedFieldInspection */ $this->context->cookie->id_cart = (int) $new_cart->id; return $new_cart; }
public function cart($goods_id, $goods_num) { if ($goods_id) { $uid = LuS::get('uid'); $data['goods_id'] = $goods_id; $data['goods_num'] = $goods_num; // $data = $goods_id; //添加 $rs_add = Cart::add($uid, $data); var_dump($rs_add); // //查询 // $rs_select = Cart::getCartGoodsInfoByGoodsId( $uid, $goods_id ); // var_dump( $rs_select ); //数量减1 $rs_decr = Cart::decr($uid, $goods_id, 1); var_dump($rs_decr); // //查询 $rs_select = Cart::select($uid); var_dump($rs_select); //数量减1 $rs_incr = Cart::incr($uid, $goods_id, 1); var_dump($rs_incr); // //查询 $rs_select = Cart::select($uid); var_dump($rs_select); } }
/** * Duplicate this Cart in the database * * @return array Duplicated cart, with success bool */ public function duplicate() { if (!Validate::isLoadedObject($this)) { return false; } $cart = new Cart($this->id); $cart->id = null; $cart->id_shop = $this->id_shop; $cart->id_shop_group = $this->id_shop_group; if (!Customer::customerHasAddress((int) $cart->id_customer, (int) $cart->id_address_delivery)) { $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $cart->id_customer); } if (!Customer::customerHasAddress((int) $cart->id_customer, (int) $cart->id_address_invoice)) { $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $cart->id_customer); } if ($cart->id_customer) { $cart->secure_key = Cart::$_customer->secure_key; } $cart->add(); if (!Validate::isLoadedObject($cart)) { return false; } $success = true; $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $this->id); $product_gift = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT cr.`gift_product`, cr.`gift_product_attribute` FROM `' . _DB_PREFIX_ . 'cart_rule` cr LEFT JOIN `' . _DB_PREFIX_ . 'order_cart_rule` ocr ON (ocr.`id_order` = ' . (int) $this->id . ') WHERE ocr.`id_cart_rule` = cr.`id_cart_rule`'); $id_address_delivery = Configuration::get('PS_ALLOW_MULTISHIPPING') ? $cart->id_address_delivery : 0; // Customized products: duplicate customizations before products so that we get new id_customizations $customs = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM ' . _DB_PREFIX_ . 'customization c LEFT JOIN ' . _DB_PREFIX_ . 'customized_data cd ON cd.id_customization = c.id_customization WHERE c.id_cart = ' . (int) $this->id); // Get datas from customization table $customs_by_id = array(); foreach ($customs as $custom) { if (!isset($customs_by_id[$custom['id_customization']])) { $customs_by_id[$custom['id_customization']] = array('id_product_attribute' => $custom['id_product_attribute'], 'id_product' => $custom['id_product'], 'quantity' => $custom['quantity']); } } // Backward compatibility: if true set customizations quantity to 0, they will be updated in Cart::_updateCustomizationQuantity $new_customization_method = (int) Db::getInstance()->getValue(' SELECT COUNT(`id_customization`) FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $this->id . ' AND `id_customization` != 0') > 0; // Insert new customizations $custom_ids = array(); foreach ($customs_by_id as $customization_id => $val) { if ($new_customization_method) { $val['quantity'] = 0; } Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'customization` (id_cart, id_product_attribute, id_product, `id_address_delivery`, quantity, `quantity_refunded`, `quantity_returned`, `in_cart`) VALUES(' . (int) $cart->id . ', ' . (int) $val['id_product_attribute'] . ', ' . (int) $val['id_product'] . ', ' . (int) $id_address_delivery . ', ' . (int) $val['quantity'] . ', 0, 0, 1)'); $custom_ids[$customization_id] = Db::getInstance(_PS_USE_SQL_SLAVE_)->Insert_ID(); } // Insert customized_data if (count($customs)) { $first = true; $sql_custom_data = 'INSERT INTO ' . _DB_PREFIX_ . 'customized_data (`id_customization`, `type`, `index`, `value`, `id_module`, `price`, `weight`) VALUES '; foreach ($customs as $custom) { if (!$first) { $sql_custom_data .= ','; } else { $first = false; } $customized_value = $custom['value']; if ((int) $custom['type'] == 0) { $customized_value = md5(uniqid(rand(), true)); Tools::copy(_PS_UPLOAD_DIR_ . $custom['value'], _PS_UPLOAD_DIR_ . $customized_value); Tools::copy(_PS_UPLOAD_DIR_ . $custom['value'] . '_small', _PS_UPLOAD_DIR_ . $customized_value . '_small'); } $sql_custom_data .= '(' . (int) $custom_ids[$custom['id_customization']] . ', ' . (int) $custom['type'] . ', ' . (int) $custom['index'] . ', \'' . pSQL($customized_value) . '\', ' . (int) $custom['id_module'] . ', ' . (double) $custom['price'] . ', ' . (double) $custom['weight'] . ')'; } Db::getInstance()->execute($sql_custom_data); } foreach ($products as $product) { if ($id_address_delivery) { if (Customer::customerHasAddress((int) $cart->id_customer, $product['id_address_delivery'])) { $id_address_delivery = $product['id_address_delivery']; } } foreach ($product_gift as $gift) { if (isset($gift['gift_product']) && isset($gift['gift_product_attribute']) && (int) $gift['gift_product'] == (int) $product['id_product'] && (int) $gift['gift_product_attribute'] == (int) $product['id_product_attribute']) { $product['quantity'] = (int) $product['quantity'] - 1; } } $id_customization = (int) $product['id_customization']; $success &= $cart->updateQty((int) $product['quantity'], (int) $product['id_product'], (int) $product['id_product_attribute'], isset($custom_ids[$id_customization]) ? (int) $custom_ids[$id_customization] : 0, 'up', (int) $id_address_delivery, new Shop((int) $cart->id_shop), false, false); } return array('cart' => $cart, 'success' => $success); }
public static function getCarriersByCountry($id_country, $id_state, $zipcode, $exiting_cart, $id_customer) { // Create temporary Address $addr_temp = new Address(); $addr_temp->id_customer = $id_customer; $addr_temp->id_country = $id_country; $addr_temp->id_state = $id_state; $addr_temp->postcode = $zipcode; // Populate required attributes // Note: Some carrier needs the whole address // the '.' will do the job $addr_temp->firstname = "."; $addr_temp->lastname = "."; $addr_temp->address1 = "."; $addr_temp->city = "."; $addr_temp->alias = "TEMPORARY_ADDRESS_TO_DELETE"; $addr_temp->save(); $cart = new Cart(); $cart->id_currency = $exiting_cart->id_currency; $cart->id_customer = $exiting_cart->id_customer; $cart->id_lang = $exiting_cart->id_lang; $cart->id_address_delivery = $addr_temp->id; $cart->add(); $products = $exiting_cart->getProducts(); foreach ($products as $key => $product) { $cart->updateQty($product['quantity'], $product['id_product'], $product['id_product_attribute']); } $carriers = $cart->simulateCarriersOutput(null, true); //delete temporary objects $addr_temp->delete(); $cart->delete(); return $carriers; }
private function _getCart($id_customer, $id_address_billing, $id_address_shipping, $productsNode) { $cart = new Cart(); $cart->id_customer = $id_customer; $cart->id_address_invoice = $id_address_billing; $cart->id_address_delivery = $id_address_shipping; $cart->id_currency = Currency::getIdByIsoCode('EUR'); $cart->id_lang = Configuration::get('PS_LANG_DEFAULT'); $cart->recyclable = 0; $cart->secure_key = md5(uniqid(rand(), true)); $cart->id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT'); $cart->add(); foreach ($productsNode->Product as $product) { $skus = explode('_', $product->SKU); if (!$cart->updateQty((int) $product->Quantity, (int) $skus[0], isset($skus[1]) ? $skus[1] : NULL)) { return false; } } $cart->update(); return $cart; }
public function duplicate() { if (!Validate::isLoadedObject($this)) { return false; } $cart = new Cart($this->id); $cart->id = null; $cart->id_shop = $this->id_shop; $cart->id_shop_group = $this->id_shop_group; if (!Customer::customerHasAddress((int) $cart->id_customer, (int) $cart->id_address_delivery)) { $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $cart->id_customer); } if (!Customer::customerHasAddress((int) $cart->id_customer, (int) $cart->id_address_invoice)) { $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $cart->id_customer); } if ($cart->id_customer) { $cart->secure_key = Cart::$_customer->secure_key; } $cart->add(); if (!Validate::isLoadedObject($cart)) { return false; } $success = true; $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $this->id); $product_gift = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT cr.`gift_product`, cr.`gift_product_attribute` FROM `' . _DB_PREFIX_ . 'cart_rule` cr LEFT JOIN `' . _DB_PREFIX_ . 'order_cart_rule` ocr ON (ocr.`id_order` = ' . (int) $this->id . ') WHERE ocr.`id_cart_rule` = cr.`id_cart_rule`'); $id_address_delivery = Configuration::get('PS_ALLOW_MULTISHIPPING') ? $cart->id_address_delivery : 0; foreach ($products as $product) { if ($id_address_delivery) { if (Customer::customerHasAddress((int) $cart->id_customer, $product['id_address_delivery'])) { $id_address_delivery = $product['id_address_delivery']; } } foreach ($product_gift as $gift) { if (isset($gift['gift_product']) && isset($gift['gift_product_attribute']) && (int) $gift['gift_product'] == (int) $product['id_product'] && (int) $gift['gift_product_attribute'] == (int) $product['id_product_attribute']) { $product['quantity'] = (int) $product['quantity'] - 1; } } $success &= $cart->updateQty((int) $product['quantity'], (int) $product['id_product'], (int) $product['id_product_attribute'], null, 'up', (int) $id_address_delivery, new Shop((int) $cart->id_shop), false); } // Customized products $customs = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT * FROM ' . _DB_PREFIX_ . 'customization c LEFT JOIN ' . _DB_PREFIX_ . 'customized_data cd ON cd.id_customization = c.id_customization WHERE c.id_cart = ' . (int) $this->id); // Get datas from customization table $customs_by_id = array(); foreach ($customs as $custom) { if (!isset($customs_by_id[$custom['id_customization']])) { $customs_by_id[$custom['id_customization']] = array('id_product_attribute' => $custom['id_product_attribute'], 'id_product' => $custom['id_product'], 'quantity' => $custom['quantity']); } } // Insert new customizations $custom_ids = array(); foreach ($customs_by_id as $customization_id => $val) { Db::getInstance()->execute(' INSERT INTO `' . _DB_PREFIX_ . 'customization` (id_cart, id_product_attribute, id_product, `id_address_delivery`, quantity, `quantity_refunded`, `quantity_returned`, `in_cart`) VALUES(' . (int) $cart->id . ', ' . (int) $val['id_product_attribute'] . ', ' . (int) $val['id_product'] . ', ' . (int) $id_address_delivery . ', ' . (int) $val['quantity'] . ', 0, 0, 1)'); $custom_ids[$customization_id] = Db::getInstance(_PS_USE_SQL_SLAVE_)->Insert_ID(); } // Insert customized_data if (count($customs)) { $first = true; $sql_custom_data = 'INSERT INTO ' . _DB_PREFIX_ . 'customized_data (`id_customization`, `type`, `index`, `value`) VALUES '; foreach ($customs as $custom) { if (!$first) { $sql_custom_data .= ','; } else { $first = false; } $sql_custom_data .= '(' . (int) $custom_ids[$custom['id_customization']] . ', ' . (int) $custom['type'] . ', ' . (int) $custom['index'] . ', \'' . pSQL($custom['value']) . '\')'; } Db::getInstance()->execute($sql_custom_data); } return array('cart' => $cart, 'success' => $success); }
public function duplicate() { if (!Validate::isLoadedObject($this)) { return false; } $cart = new Cart($this->id); $cart->id = NULL; $cart->add(); if (!Validate::isLoadedObject($cart)) { return false; } $success = true; $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $this->id); foreach ($products as $product) { $success &= $cart->updateQty($product['quantity'], (int) $product['id_product'], (int) $product['id_product_attribute'], NULL, 'up'); } // Customized products $customs = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' SELECT * FROM ' . _DB_PREFIX_ . 'customization c LEFT JOIN ' . _DB_PREFIX_ . 'customized_data cd ON cd.id_customization = c.id_customization WHERE c.id_cart = ' . (int) $this->id); // Group line by id_customization $customsById = array(); foreach ($customs as $custom) { if (!isset($customsById[$custom['id_customization']])) { $customsById[$custom['id_customization']] = array(); } $customsById[$custom['id_customization']][] = $custom; } // Insert new customizations $custom_ids = array(); foreach ($customsById as $customizationId => $val) { Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute(' INSERT INTO ' . _DB_PREFIX_ . 'customization (id_customization, id_cart, id_product_attribute, id_product, quantity) VALUES(\'\', ' . (int) $cart->id . ', ' . (int) $custom['id_product_attribute'] . ', ' . (int) $custom['id_product'] . ', ' . (int) $custom['quantity'] . ')'); $custom_ids[$custom['id_customization']] = Db::getInstance(_PS_USE_SQL_SLAVE_)->Insert_ID(); } // Insert customized_data if (sizeof($customs)) { $first = true; $sql_custom_data = 'INSERT INTO ' . _DB_PREFIX_ . 'customized_data (`id_customization`, `type`, `index`, `value`) VALUES '; foreach ($customs as $custom) { if (!$first) { $sql_custom_data .= ','; } else { $first = false; } $sql_custom_data .= '(' . (int) $custom_ids[$custom['id_customization']] . ', ' . (int) $custom['type'] . ', ' . (int) $custom['index'] . ', \'' . pSQL($custom['value']) . '\')'; } Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql_custom_data); } return array('cart' => $cart, 'success' => $success); }
public function addItem($id) { $item = Item::find($id); Cart::add($id, $item->nombre, 1, $item->precio); return Redirect::to('cart'); }
function joinCart() { $link = IReq::get('link'); $goods_id = intval(IReq::get('goods_id')); $goods_num = IReq::get('goods_num') === null ? 1 : intval(IReq::get('goods_num')); $type = IFilter::act(IReq::get('type')); //加入购物车 $cartObj = new Cart(); $addResult = $cartObj->add($goods_id, $goods_num, $type); if ($link != '') { if ($addResult === false) { $this->cart(false); Util::showMessage($cartObj->getError()); } else { $this->redirect($link); } } else { if ($addResult === false) { $result = array('isError' => true, 'message' => $cartObj->getError()); } else { $result = array('isError' => false, 'message' => '添加成功'); } echo JSON::encode($result); } }
public function duplicate() { if (!Validate::isLoadedObject($this)) { return false; } $cart = new Cart($this->id); $cart->id = null; $cart->id_shop = $this->id_shop; $cart->id_shop_group = $this->id_shop_group; $cart->add(); if (!Validate::isLoadedObject($cart)) { return false; } $success = true; $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $this->id); foreach ($products as $product) { $success &= $cart->updateQty($product['quantity'], (int) $product['id_product'], (int) $product['id_product_attribute'], null, 'up', (int) $product['id_address_delivery'], new Shop($cart->id_shop)); } // Customized products $customs = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT * FROM ' . _DB_PREFIX_ . 'customization c LEFT JOIN ' . _DB_PREFIX_ . 'customized_data cd ON cd.id_customization = c.id_customization WHERE c.id_cart = ' . (int) $this->id); // Get datas from customization table $customs_by_id = array(); foreach ($customs as $custom) { if (!isset($customs_by_id[$custom['id_customization']])) { $customs_by_id[$custom['id_customization']] = array('id_product_attribute' => $custom['id_product_attribute'], 'id_product' => $custom['id_product'], 'quantity' => $custom['quantity']); } } // Insert new customizations $custom_ids = array(); foreach ($customs_by_id as $customization_id => $val) { Db::getInstance()->execute(' INSERT INTO `' . _DB_PREFIX_ . 'customization` (id_cart, id_product_attribute, id_product, `id_address_delivery`, quantity, `quantity_refunded`, `quantity_returned`, `in_cart`) VALUES(' . (int) $cart->id . ', ' . (int) $val['id_product_attribute'] . ', ' . (int) $val['id_product'] . ', ' . (int) $this->id_address_delivery . ', ' . (int) $val['quantity'] . ', 0, 0, 1)'); $custom_ids[$customization_id] = Db::getInstance(_PS_USE_SQL_SLAVE_)->Insert_ID(); } // Insert customized_data if (count($customs)) { $first = true; $sql_custom_data = 'INSERT INTO ' . _DB_PREFIX_ . 'customized_data (`id_customization`, `type`, `index`, `value`) VALUES '; foreach ($customs as $custom) { if (!$first) { $sql_custom_data .= ','; } else { $first = false; } $sql_custom_data .= '(' . (int) $custom_ids[$custom['id_customization']] . ', ' . (int) $custom['type'] . ', ' . (int) $custom['index'] . ', \'' . pSQL($custom['value']) . '\')'; } Db::getInstance()->execute($sql_custom_data); } return array('cart' => $cart, 'success' => $success); }
public function saveItemGaji($id) { // 1. setting validasi $messages = array('required' => 'Inputan <b>Tidak Boleh Kosong</b>!', 'numeric' => 'Inputan <b>Harus Angka</b>!', 'same' => 'Password <b>Tidak Sama</b>!'); $validator = Validator::make(Input::all(), array("nilgj" => "required"), $messages); // 2a. jika semua validasi terpenuhi simpan ke database if ($validator->passes()) { // Cart::add(1, 5, 5, 5); $content = Cart::content(); $idcart = 1; $rowId = ''; foreach ($content as $row) { if ($row->name == Input::get("idgj")) { $idcart = $row->id; $rowId = $row->rowid; break; } else { $idcart = $row->id; $idcart += 1; } } if ($rowId != '') { Cart::update($rowId, array('price' => Input::get("nilgj"))); } else { if (Input::get("idgj")) { $idgj = Input::get("idgj"); $gaji = mg01::find($idgj); $jenis = $gaji['jenis']; Cart::add($idcart, Input::get("idgj"), 1, Input::get("nilgj"), array('jenis_gaji' => $jenis, "idkaryawan" => Input::get("idkaryawan"), "iduser" => 0)); } } // Redirect ke url + menuju div tertentu $url = URL::action("MasterKaryawanController@addGaji", ['id' => $id]) . "#datatable"; return Redirect::to($url); } else { return Redirect::to('master/karyawan/add_gaji/' . $id)->withErrors($validator)->withInput(); } }
public function ajaxProcessAddProductOnOrder() { // Load object $order = new Order((int) Tools::getValue('id_order')); if (!Validate::isLoadedObject($order)) { die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The order object cannot be loaded.')))); } if ($order->hasBeenShipped()) { die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('You cannot add products to delivered orders. ')))); } $product_informations = $_POST['add_product']; if (isset($_POST['add_invoice'])) { $invoice_informations = $_POST['add_invoice']; } else { $invoice_informations = array(); } $product = new Product($product_informations['product_id'], false, $order->id_lang); if (!Validate::isLoadedObject($product)) { die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The product object cannot be loaded.')))); } if (isset($product_informations['product_attribute_id']) && $product_informations['product_attribute_id']) { $combination = new Combination($product_informations['product_attribute_id']); if (!Validate::isLoadedObject($combination)) { die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The combination object cannot be loaded.')))); } } // Total method $total_method = Cart::BOTH_WITHOUT_SHIPPING; // Create new cart $cart = new Cart(); $cart->id_shop_group = $order->id_shop_group; $cart->id_shop = $order->id_shop; $cart->id_customer = $order->id_customer; $cart->id_carrier = $order->id_carrier; $cart->id_address_delivery = $order->id_address_delivery; $cart->id_address_invoice = $order->id_address_invoice; $cart->id_currency = $order->id_currency; $cart->id_lang = $order->id_lang; $cart->secure_key = $order->secure_key; // Save new cart $cart->add(); // Save context (in order to apply cart rule) $this->context->cart = $cart; $this->context->customer = new Customer($order->id_customer); // always add taxes even if there are not displayed to the customer $use_taxes = true; $initial_product_price_tax_incl = Product::getPriceStatic($product->id, $use_taxes, isset($combination) ? $combination->id : null, 2, null, false, true, 1, false, $order->id_customer, $cart->id, $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)}); // Creating specific price if needed if ($product_informations['product_price_tax_incl'] != $initial_product_price_tax_incl) { $specific_price = new SpecificPrice(); $specific_price->id_shop = 0; $specific_price->id_shop_group = 0; $specific_price->id_currency = 0; $specific_price->id_country = 0; $specific_price->id_group = 0; $specific_price->id_customer = $order->id_customer; $specific_price->id_product = $product->id; if (isset($combination)) { $specific_price->id_product_attribute = $combination->id; } else { $specific_price->id_product_attribute = 0; } $specific_price->price = $product_informations['product_price_tax_excl']; $specific_price->from_quantity = 1; $specific_price->reduction = 0; $specific_price->reduction_type = 'amount'; $specific_price->from = '0000-00-00 00:00:00'; $specific_price->to = '0000-00-00 00:00:00'; $specific_price->add(); } // Add product to cart $update_quantity = $cart->updateQty($product_informations['product_quantity'], $product->id, isset($product_informations['product_attribute_id']) ? $product_informations['product_attribute_id'] : null, isset($combination) ? $combination->id : null, 'up', 0, new Shop($cart->id_shop)); if ($update_quantity < 0) { // If product has attribute, minimal quantity is set with minimal quantity of attribute $minimal_quantity = $product_informations['product_attribute_id'] ? Attribute::getAttributeMinimalQty($product_informations['product_attribute_id']) : $product->minimal_quantity; die(Tools::jsonEncode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity)))); } elseif (!$update_quantity) { die(Tools::jsonEncode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false)))); } // If order is valid, we can create a new invoice or edit an existing invoice if ($order->hasInvoice()) { $order_invoice = new OrderInvoice($product_informations['invoice']); // Create new invoice if ($order_invoice->id == 0) { // If we create a new invoice, we calculate shipping cost $total_method = Cart::BOTH; // Create Cart rule in order to make free shipping if (isset($invoice_informations['free_shipping']) && $invoice_informations['free_shipping']) { $cart_rule = new CartRule(); $cart_rule->id_customer = $order->id_customer; $cart_rule->name = array(Configuration::get('PS_LANG_DEFAULT') => $this->l('[Generated] CartRule for Free Shipping')); $cart_rule->date_from = date('Y-m-d H:i:s', time()); $cart_rule->date_to = date('Y-m-d H:i:s', time() + 24 * 3600); $cart_rule->quantity = 1; $cart_rule->quantity_per_user = 1; $cart_rule->minimum_amount_currency = $order->id_currency; $cart_rule->reduction_currency = $order->id_currency; $cart_rule->free_shipping = true; $cart_rule->active = 1; $cart_rule->add(); // Add cart rule to cart and in order $cart->addCartRule($cart_rule->id); $values = array('tax_incl' => $cart_rule->getContextualValue(true), 'tax_excl' => $cart_rule->getContextualValue(false)); $order->addCartRule($cart_rule->id, $cart_rule->name[Configuration::get('PS_LANG_DEFAULT')], $values); } $order_invoice->id_order = $order->id; if ($order_invoice->number) { Configuration::updateValue('PS_INVOICE_START_NUMBER', false, false, null, $order->id_shop); } else { $order_invoice->number = Order::getLastInvoiceNumber() + 1; } $invoice_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)}); $carrier = new Carrier((int) $order->id_carrier); $tax_calculator = $carrier->getTaxCalculator($invoice_address); $order_invoice->total_paid_tax_excl = Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2); $order_invoice->total_paid_tax_incl = Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2); $order_invoice->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order_invoice->total_products_wt = (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS); $order_invoice->total_shipping_tax_excl = (double) $cart->getTotalShippingCost(null, false); $order_invoice->total_shipping_tax_incl = (double) $cart->getTotalShippingCost(); $order_invoice->total_wrapping_tax_excl = abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING)); $order_invoice->total_wrapping_tax_incl = abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING)); $order_invoice->shipping_tax_computation_method = (int) $tax_calculator->computation_method; // Update current order field, only shipping because other field is updated later $order->total_shipping += $order_invoice->total_shipping_tax_incl; $order->total_shipping_tax_excl += $order_invoice->total_shipping_tax_excl; $order->total_shipping_tax_incl += $use_taxes ? $order_invoice->total_shipping_tax_incl : $order_invoice->total_shipping_tax_excl; $order->total_wrapping += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING)); $order->total_wrapping_tax_excl += abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING)); $order->total_wrapping_tax_incl += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING)); $order_invoice->add(); $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl)); $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $order->id_carrier; $order_carrier->id_order_invoice = (int) $order_invoice->id; $order_carrier->weight = (double) $cart->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (double) $order_invoice->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = $use_taxes ? (double) $order_invoice->total_shipping_tax_incl : (double) $order_invoice->total_shipping_tax_excl; $order_carrier->add(); } else { $order_invoice->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2); $order_invoice->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2); $order_invoice->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order_invoice->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS); $order_invoice->update(); } } // Create Order detail information $order_detail = new OrderDetail(); $order_detail->createList($order, $cart, $order->getCurrentOrderState(), $cart->getProducts(), isset($order_invoice) ? $order_invoice->id : 0, $use_taxes, (int) Tools::getValue('add_product_warehouse')); // update totals amount of order $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS); $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2); $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2); $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2); if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) { $order->total_shipping = $order_invoice->total_shipping_tax_incl; $order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl; $order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl; } // discount $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)); $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); // Save changes of order $order->update(); // Update weight SUM $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier()); if (Validate::isLoadedObject($order_carrier)) { $order_carrier->weight = (double) $order->getTotalWeight(); if ($order_carrier->update()) { $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight); } } // Update Tax lines $order_detail->updateTaxAmount($order); // Delete specific price if exists if (isset($specific_price)) { $specific_price->delete(); } $products = $this->getProducts($order); // Get the last product $product = end($products); $resume = OrderSlip::getProductSlipResume((int) $product['id_order_detail']); $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity']; $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl']; $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']); $product['return_history'] = OrderReturn::getProductReturnDetail((int) $product['id_order_detail']); $product['refund_history'] = OrderSlip::getProductSlipDetail((int) $product['id_order_detail']); if ($product['id_warehouse'] != 0) { $warehouse = new Warehouse((int) $product['id_warehouse']); $product['warehouse_name'] = $warehouse->name; } else { $product['warehouse_name'] = '--'; } // Get invoices collection $invoice_collection = $order->getInvoicesCollection(); $invoice_array = array(); foreach ($invoice_collection as $invoice) { $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop); $invoice_array[] = $invoice; } // Assign to smarty informations in order to show the new product line $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))); $this->sendChangedNotification($order); die(Tools::jsonEncode(array('result' => true, 'view' => $this->createTemplate('_product_line.tpl')->fetch(), 'can_edit' => $this->tabAccess['add'], 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'discount_form_html' => $this->createTemplate('_discount_form.tpl')->fetch()))); }
/** * @dataProvider containsData */ public function testTotal($products, $total) { $cart = new \Cart(); $cart->add($products); $this->assertEquals($cart->total(), $total); }