public function delete() { if (parent::delete()) { $cart = new Cart($this->id_cart); $cart->status = Cart::IS_CLOSE; return $cart->update(); } return false; }
public function postDelete() { if (Request::ajax()) { $productId = Input::get('productId'); $rows = Cart::search(array('id' => $productId)); $rowId = $rows[0]; Cart::update($rowId, 0); $total = Cart::total(); return Response::json(array('productId' => $productId, 'quantity' => $quantity, 'total' => $total)); } }
/** * 更新购物车 */ public function update() { //不是ajax提交返回 $sid = $_POST['sid']; if (!IS_AJAX) { return; } //购物车更新 Cart::update($_POST); //获得所有商品数据 $total = Cart::getAllData(); $total['xiaoji'] = $total['goods'][$sid]['total']; $this->ajax($total); }
public function displayMain() { global $smarty, $cookie, $link; $cart = new Cart((int) $cookie->id_cart); if (isset($_POST['msg']) && pSQL($_POST['msg'], true) != $cart->msg) { $cart->msg = substr(pSQL($_POST['msg'], true), 0, 500); $cart->update(); } if (!$cookie->logged || !User::checkPassword($cookie->id_user, $cookie->passwd)) { Tools::redirect($link->getPage('LoginView', false, array('step' => 2))); } else { $this->LoginedAction(); } $smarty->assign(array('id_default_carrier' => Configuration::get('TM_DEFAULT_CARRIER_ID'))); return $smarty->fetch('checkout.tpl'); }
public function displayMain() { global $cookie, $link; if (!isset($cookie->id_cart) || !$cookie->logged) { Tools::redirect($link->getPage('UserView')); } if (!Tools::getRequest('id_module') || !Tools::getRequest('id_address')) { Tools::redirect($link->getPage('CheckoutView')); } $cart = new Cart((int) $cookie->id_cart); $cart->id_address = (int) Tools::getRequest('id_address'); $cart->id_carrier = (int) Tools::getRequest('id_carrier'); $cart->update(); $payment = Module::hook((int) Tools::getRequest('id_module')); if (!$payment->active) { Tools::redirect($link->getPage('CheckoutView')); } return $payment->execPayment($cart); }
public function logined($vals = array()) { global $cookie; $cookie->logged = 1; $cookie->id_user = $this->id; $cookie->email = $this->email; $cookie->passwd = $this->passwd; $cookie->first_name = $this->first_name; $cookie->last_name = $this->last_name; if (count($vals) > 0) { foreach ($vals as $key => $val) { $cookie->{$key} = $val; } } if (isset($cookie->id_cart)) { $cart = new Cart((int) $cookie->id_cart); $cart->id_user = $this->id; if (isset($vals['id_address'])) { $cart->id_address = (int) $vals['id_address']; } $cart->update(); } $cookie->write(); }
function add($item_id, $item_table, $qty = false, $table = false) { global $CFG; $table = $table ? $table : 'cart'; $item = DB::getRecord($item_table, $item_id, false, true); $item_name = $item['name']; if (!($item_id > 0) && !$item) { $errors[$item_id] = $CFG->cart_item_error; Errors::merge($errors); return false; } if (empty($item_table)) { $errors[$item_id] = $CFG->cart_table_error; Errors::merge($errors); return false; } if (!($qty > 0)) { $errors[$item_id] = $CFG->cart_qty_error; Errors::merge($errors); return false; } if ($c_item = Cart::getItem($item_id, $item_table, $table)) { return Cart::update($item_id, $item_table, $c_item['qty'] + $qty, $table); } if (User::isLoggedIn()) { $id = DB::insert($table, array('item_id' => $item_id, 'item_table' => $item_table, 'qty' => $qty, 'user_id' => User::$info['id'])); $messages[$item_name] = str_ireplace('[qty]', $qty, $CFG->cart_add_message); Messages::merge($messages); return $id; } else { $_SESSION['cart'][$item_table . '_' . $item_id] = array('item_id' => $item_id, 'item_table' => $item_table, 'qty' => $qty); $messages[$item_name] = str_ireplace('[qty]', $qty, $CFG->cart_add_message); Messages::merge($messages); return true; } }
public function minusCart($deal_id) { $cart = \Cart::get($deal_id); $newQuantity = --$cart->quantity; if ($newQuantity <= 0) { \Cart::remove($deal_id); } else { \Cart::update($deal_id, ['quantity' => $newQuantity]); } return redirect('/gio-hang'); }
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 postCart() { if (Request::ajax()) { if (isset($_POST['buypid'])) { $optionprice = $name = DB::table('products_options')->where('product_id', $_POST['buypid'])->where("option_value", $_POST['buyoption'])->pluck('price'); return $optionprice; exit; } if (isset($_POST['pid'])) { $item = Product::find($_POST['pid']); Cart::update($_POST['rowid'], array('qty' => $_POST['qty'])); $content = Cart::content(); $total = Cart::total(); $itemHtml = ""; /*$itemHtml .="<div class='beta-select'><i class='fa fa-shopping-cart'></i><span id='cart-count'> Cart (".Cart::count().")</span> <i class='fa fa-chevron-down'></i></div> <div class='beta-dropdown cart-body'>";*/ if ($content) { foreach ($content as $itemRow) { $product = Product::find($itemRow->id); if ($itemRow->options->has('buying') && $itemRow->options->buying != "") { $itemRow->price = DB::table('products_options')->where("product_option_value_id", $itemRow->optionid)->pluck('price'); } if (public_path()) { $source_folder = public_path() . '/uploads/images/'; $destination_folder = public_path() . '/uploads/images/'; } else { $source_folder = '/home/medicalng/public_html/uploads/images/'; $destination_folder = '/home/medicalng/public_html/uploads/images/'; } $image_info = pathinfo($source_folder . $product->image); $image_extension = strtolower($image_info["extension"]); //image extension $image_name_only = strtolower($image_info["filename"]); //file name only, no extension $imgName = $image_name_only . "-50x50" . "." . $image_extension; $itemHtml .= "<div class='cart-item'>\n <!--<a class='cart-item-edit' pid='" . $itemRow->rowid . "' href=\"javascript:void(0);\"><i class='fa fa-pencil'></i></a>-->\n <a class='cart-item-delete' pid='" . $itemRow->rowid . "' href=\"javascript:void(0);\"><i class='fa fa-times'></i></a>\n <div class='media'>\n <a class='pull-left' href=\"javascript:void(0);\"><img src='" . url() . "/uploads/images/thumbs/{$imgName}' alt=''></a>\n <div class='media-body'>\n <span class='cart-item-title'>" . $itemRow->name . "</span>\n "; $itemHtml .= "<span class='cart-item-options'>"; if ($itemRow->options) { foreach ($itemRow->options as $key => $value) { if ($value != "") { $itemHtml .= $value . "&mdash"; } } } $itemHtml .= "</span>"; $itemHtml .= "\n <span class='cart-item-amount'>{$itemRow->qty}*<span>₦" . number_format($itemRow->price, 2, '.', ',') . "</span>\n </div>\n </div>\n </div>\n\n "; } $itemHtml .= "<div class='cart-caption'>\n <div class='cart-total text-right'>Subtotal: <span class='cart-total-value'>₦" . number_format($total, 2, ".", ",") . "</span></div>\n <div class='clearfix'></div>\n\n <div class='center'>\n <div class='space10'> </div>\n <a href='" . url() . "/cart' class='beta-btn primary text-center'>Checkout <i class='fa fa-chevron-right'></i></a>\n </div></div>"; } else { $itemHtml .= "Cart is empty"; } /*$itemHtml .= "</div>";*/ echo $itemHtml; } if (isset($_POST['delid'])) { //$item = Product::find($_POST['delid']); Cart::remove($_POST['rowid']); //(array('id' => $item->id, 'name' => $item->title, 'qty' => 1, 'price' => $item->price)); $content = Cart::content(); Session::put("cartItems", $content); $total = Cart::total(); $itemHtml = ""; /*$itemHtml .="<div class='beta-select'><i class='fa fa-shopping-cart'></i><span id='cart-count'> Cart (".Cart::count().")</span> <i class='fa fa-chevron-down'></i></div> <div class='beta-dropdown cart-body'>";*/ if ($content) { foreach ($content as $itemRow) { $product = Product::find($itemRow->id); if ($itemRow->options->has('buying') && $itemRow->options->buying != "") { $itemRow->price = DB::table('products_options')->where("product_option_value_id", $itemRow->optionid)->pluck('price'); } if (public_path()) { $source_folder = public_path() . '/uploads/images/'; $destination_folder = public_path() . '/uploads/images/'; } else { $source_folder = '/home/medicalng/public_html/uploads/images/'; $destination_folder = '/home/medicalng/public_html/uploads/images/'; } $image_info = pathinfo($source_folder . $product->image); $image_extension = strtolower($image_info["extension"]); //image extension $image_name_only = strtolower($image_info["filename"]); //file name only, no extension $imgName = $image_name_only . "-50x50" . "." . $image_extension; $itemHtml .= "<div class='cart-item'>\n <!--<a class='cart-item-edit' pid='" . $itemRow->rowid . "' href=\"javascript:void(0);\"><i class='fa fa-pencil'></i></a>-->\n <a class='cart-item-delete' pid='" . $itemRow->rowid . "' href=\"javascript:void(0);\"><i class='fa fa-times'></i></a>\n <div class='media'>\n <a class='pull-left' href=\"javascript:void(0);\"><img src='" . url() . "/uploads/images/thumbs/{$imgName}' alt=''></a>\n <div class='media-body'>\n <span class='cart-item-title'>" . $itemRow->name . "</span>\n "; $itemHtml .= "<span class='cart-item-options'>"; $thml = ""; if ($itemRow->options) { foreach ($itemRow->options as $key => $value) { if ($value != "") { $thml .= " —" . $value; } } $thml = preg_replace("/^ —/", "", $thml); } $itemHtml .= $thml . "</span>"; $itemHtml .= "\n <span class='cart-item-amount'>{$itemRow->qty}*<span>₦" . number_format($itemRow->price, 2, '.', ',') . "</span>\n </div>\n </div>\n </div>\n\n "; } $itemHtml .= "<div class='cart-caption'>\n <div class='cart-total text-right'>Subtotal: <span class='cart-total-value'>₦" . number_format($total, 2, ".", ",") . "</span></div>\n <div class='clearfix'></div>\n\n <div class='center'>\n <div class='space10'> </div>\n <a href='" . url() . "/cart' class='beta-btn primary text-center'>Checkout <i class='fa fa-chevron-right'></i></a>\n </div></div>"; } else { $itemHtml .= "Cart is empty"; } /*$itemHtml .="</div>";*/ echo $itemHtml; } //return ($itemHtml); //exit; } }
private function _deleteProduct($orderDetail, $quantity) { $price = $orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01); if ($orderDetail->reduction_percent != 0.0) { $reduction_amount = $price * $orderDetail->reduction_percent / 100; } elseif ($orderDetail->reduction_amount != '0.000000') { $reduction_amount = Tools::ps_round($orderDetail->reduction_amount * (1 + $orderDetail->tax_rate * 0.01), 2); } if (isset($reduction_amount) and $reduction_amount) { $price = Tools::ps_round($price - $reduction_amount, 2); } $unitPrice = number_format($price, 2, '.', ''); $productPrice = number_format($quantity * $price, 2, '.', ''); $productPriceWithoutTax = number_format($productPrice / (1 + $orderDetail->tax_rate * 0.01), 2, '.', ''); /* Update cart */ $cart = new Cart($this->id_cart); $cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down'); // customization are deleted in deleteCustomization $cart->update(); /* Update order */ $shippingDiff = $this->total_shipping - $cart->getOrderShippingCost(); $this->total_products -= $productPriceWithoutTax; $this->total_products_wt -= $productPrice; $this->total_shipping = $cart->getOrderShippingCost(); /* It's temporary fix for 1.3 version... waiting historization system on 1.4 version */ if ($orderDetail->product_quantity_discount != '0.000000') { $this->total_paid -= $productPrice + $shippingDiff; } else { $this->total_paid = $cart->getOrderTotal(); } $this->total_paid_real -= $productPrice + $shippingDiff; /* Prevent from floating precision issues (total_products has only 2 decimals) */ if ($this->total_products < 0) { $this->total_products = 0; } /* Prevent from floating precision issues */ $this->total_paid = number_format($this->total_paid, 2, '.', ''); $this->total_paid_real = number_format($this->total_paid_real, 2, '.', ''); $this->total_products = number_format($this->total_products, 2, '.', ''); $this->total_products_wt = number_format($this->total_products_wt, 2, '.', ''); /* Update order detail */ $orderDetail->product_quantity -= intval($quantity); if (!$orderDetail->product_quantity) { if (!$orderDetail->delete()) { return false; } if (count($this->getProductsDetail()) == 0) { global $cookie; $history = new OrderHistory(); $history->id_order = intval($this->id); $history->changeIdOrderState(_PS_OS_CANCELED_, intval($this->id)); if (!$history->addWithemail()) { return false; } } return $this->update(); } return $orderDetail->update() and $this->update(); }
protected function _deleteProduct($orderDetail, $quantity) { $price = $orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01); if ($orderDetail->reduction_percent != 0.0) { $reduction_amount = $price * $orderDetail->reduction_percent / 100; } elseif ($orderDetail->reduction_amount != '0.000000') { $reduction_amount = Tools::ps_round($orderDetail->reduction_amount, 2); } if (isset($reduction_amount) && $reduction_amount) { $price = Tools::ps_round($price - $reduction_amount, 2); } $productPriceWithoutTax = number_format($price / (1 + $orderDetail->tax_rate * 0.01), 2, '.', ''); $price += Tools::ps_round($orderDetail->ecotax * (1 + $orderDetail->ecotax_tax_rate / 100), 2); $productPrice = number_format($quantity * $price, 2, '.', ''); /* Update cart */ $cart = new Cart($this->id_cart); $cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down'); // customization are deleted in deleteCustomization $cart->update(); /* Update order */ $shippingDiff = $this->total_shipping - $cart->getOrderShippingCost(); $this->total_products -= $productPriceWithoutTax; // After upgrading from old version // total_products_wt is null // removing a product made order total negative // and don't recalculating totals (on getTotalProductsWithTaxes) if ($this->total_products_wt != 0) { $this->total_products_wt -= $productPrice; } $this->total_shipping = $cart->getOrderShippingCost(); /* It's temporary fix for 1.3 version... */ if ($orderDetail->product_quantity_discount != '0.000000') { $this->total_paid -= $productPrice + $shippingDiff; } else { $this->total_paid = $cart->getOrderTotal(); } $this->total_paid_real -= $productPrice + $shippingDiff; /* Prevent from floating precision issues (total_products has only 2 decimals) */ if ($this->total_products < 0) { $this->total_products = 0; } if ($this->total_paid < 0) { $this->total_paid = 0; } if ($this->total_paid_real < 0) { $this->total_paid_real = 0; } /* Prevent from floating precision issues */ $this->total_paid = number_format($this->total_paid, 2, '.', ''); $this->total_paid_real = number_format($this->total_paid_real, 2, '.', ''); $this->total_products = number_format($this->total_products, 2, '.', ''); $this->total_products_wt = number_format($this->total_products_wt, 2, '.', ''); /* Update order detail */ $orderDetail->product_quantity -= (int) $quantity; if (!$orderDetail->product_quantity) { if (!$orderDetail->delete()) { return false; } if (count($this->getProductsDetail()) == 0) { $history = new OrderHistory(); $history->id_order = (int) $this->id; $history->changeIdOrderState(Configuration::get('PS_OS_CANCELED'), (int) $this->id); if (!$history->addWithemail()) { return false; } } return $this->update(); } return $orderDetail->update() && $this->update(); }
$paypal = new Paypal(); $cart = new Cart((int) $cookie->id_cart); $address = new Address((int) $cart->id_address_delivery); $country = new Country((int) $address->id_country); $state = NULL; if ($address->id_state) { $state = new State((int) $address->id_state); } $customer = new Customer((int) $cart->id_customer); $business = Configuration::get('PAYPAL_BUSINESS'); $header = Configuration::get('PAYPAL_HEADER'); $currency_order = new Currency((int) $cart->id_currency); $currency_module = $paypal->getCurrency((int) $cart->id_currency); if (empty($business) or !Validate::isEmail($business)) { die($paypal->getL('Paypal error: (invalid or undefined business account email)')); } if (!Validate::isLoadedObject($address) or !Validate::isLoadedObject($customer) or !Validate::isLoadedObject($currency_module)) { die($paypal->getL('Paypal error: (invalid address or customer)')); } // check currency of payment if ($currency_order->id != $currency_module->id) { $cookie->id_currency = $currency_module->id; $cart->id_currency = $currency_module->id; $cart->update(); } $smarty->assign(array('redirect_text' => $paypal->getL('Please wait, redirecting to Paypal... Thanks.'), 'cancel_text' => $paypal->getL('Cancel'), 'cart_text' => $paypal->getL('My cart'), 'return_text' => $paypal->getL('Return to shop'), 'paypal_url' => $paypal->getPaypalStandardUrl(), 'address' => $address, 'country' => $country, 'state' => $state, 'amount' => (double) $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), 'customer' => $customer, 'total' => (double) $cart->getOrderTotal(true, Cart::BOTH), 'shipping' => Tools::ps_round((double) $cart->getOrderShippingCost() + (double) $cart->getOrderTotal(true, Cart::ONLY_WRAPPING), 2), 'discount' => $cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS), 'business' => $business, 'currency_module' => $currency_module, 'cart_id' => (int) $cart->id . '_' . pSQL($cart->secure_key), 'products' => $cart->getProducts(), 'paypal_id' => (int) $paypal->id, 'header' => $header, 'url' => Tools::getShopDomain(true, true) . __PS_BASE_URI__)); if (is_file(_PS_THEME_DIR_ . 'modules/paypal/standard/redirect.tpl')) { $smarty->display(_PS_THEME_DIR_ . 'modules/' . $paypal->name . '/standard/redirect.tpl'); } else { $smarty->display(_PS_MODULE_DIR_ . $paypal->name . '/standard/redirect.tpl'); }
public function displayMain() { global $cookie; /* when user add or change address,from addressView or joinView */ if (isset($_GET['ajaxStates']) and isset($_GET['id_country'])) { $states = Db::getInstance()->getAll(' SELECT s.id_state, s.name FROM ' . DB_PREFIX . 'state s LEFT JOIN ' . DB_PREFIX . 'country c ON (s.`id_country` = c.`id_country`) WHERE s.id_country = ' . (int) Tools::G('id_country') . ' AND s.active = 1 AND c.`need_state` = 1 ORDER BY s.`name` ASC'); if (is_array($states) and !empty($states)) { $list = ''; if (Tools::G('no_empty') != true) { $list = '<option value="0">-----------</option>' . "\n"; } foreach ($states as $state) { $list .= '<option value="' . (int) $state['id_state'] . '"' . (Tools::G('id_state') == $state['id_state'] ? ' selected="selected"' : '') . '>' . $state['name'] . '</option>' . "\n"; } } else { $list = 'false'; } die($list); } //end get states /* from cartView get total */ if (isset($_GET['getTotal']) and isset($_GET['id_cart']) and isset($_GET['id_carrier'])) { $carrier = new Carrier((int) $_GET['id_carrier']); $cart = new Cart((int) $_GET['id_cart']); $shipping = $carrier->shipping; $p_total = $cart->getProductTotal(); $total = $shipping + $p_total - $cart->discount; $arr = array('name' => $carrier->name, 'shipping' => Tools::displayPrice($shipping), 'total' => Tools::displayPrice($total)); echo json_encode($arr); exit; } //end use gettotal /* start use promo code,from CartView */ if (isset($_GET['validatedPromocode']) && isset($_GET['code'])) { if (!isset($cookie->id_cart)) { $arr = array('status' => "NO", 'msg' => "cart is not init!"); echo json_encode($arr); exit; } $row = Db::getInstance()->getRow('SELECT * FROM ' . _DB_PREFIX_ . 'coupon WHERE code="' . pSQL($_GET['code']) . '" AND active=1'); if ($row) { if ($row['id_user'] == 0 || $row['id_user'] == @$cookie->id_user) { $cart = new Cart($cookie->id_cart); $total = $cart->getProductTotal(); $quantity = $cart->getProductQantity(); $discount = 0; if ($total > $row['total_over'] || $row['quantity_over'] > 0 && $quantity > $row['quantity_over']) { if ($row['off'] > 0) { $discount = (double) $total * $row['off'] / 100; } else { $discount = (double) $row['amount']; } $cart->discount = $discount; if ($cart->update()) { $arr = array('status' => "YES", 'discount' => "-" . Tools::displayPrice($discount), 'total' => Tools::displayPrice($cart->getOrderTotal())); echo json_encode($arr); exit; } } } } $arr = array('status' => "NO", 'msg' => "the code don't found!"); echo json_encode($arr); exit; } //end use promo code /** * 购物车 */ if (Tools::G('c') == 'Cart') { global $cart; switch (Tools::G('m')) { case 'removeItem': if ($cart->deleteProduct(Tools::G('id'))) { $cart_info = $cart->getCartInfo(); $result = array('status' => 'yes', 'cart_total' => Tools::displayPrice($cart_info['cart_total']), 'cart_quantity' => $cart_info['cart_quantity']); die(json_encode($result)); } die(json_encode(array("status" => "no"))); break; case 'plusItem': if ($row = $cart->plusProduct(Tools::G('id'))) { $cart_info = $cart->getCartInfo(); $result = array('status' => 'yes', 'cart_total' => Tools::displayPrice($cart_info['cart_total']), 'cart_quantity' => $cart_info['cart_quantity'], 'item' => array('quantity' => $row['quantity'], 'total' => Tools::displayPrice($row['total']))); die(json_encode($result)); } die(json_encode(array("status" => "no"))); break; case 'minusItem': if ($row = $cart->minusProduct(Tools::G('id'))) { $cart_info = $cart->getCartInfo(); $result = array('status' => 'yes', 'cart_total' => Tools::displayPrice($cart_info['cart_total']), 'cart_quantity' => $cart_info['cart_quantity'], 'item' => array('quantity' => $row['quantity'], 'total' => Tools::displayPrice($row['total']))); die(json_encode($result)); } die(json_encode(array("status" => "no"))); break; case 'deleteMultiItem': if ($cart->deleteMultiProduct(explode(',', Tools::G('id')))) { $cart_info = $cart->getCartInfo(); $result = array('status' => 'yes', 'cart_total' => Tools::displayPrice($cart_info['cart_total']), 'cart_quantity' => $cart_info['cart_quantity']); die(json_encode($result)); } die(json_encode(array("status" => "no"))); break; default: break; } } /** * 商品收藏 */ if (Tools::G('c') == 'Wish') { if (!isset($cookie->id_user)) { die(json_encode(array("status" => "no", "msg" => "d'not login!"))); } $user = new User((int) $cookie->id_user); if (!Validate::isLoadedObject($user)) { die(json_encode(array("status" => "no", "msg" => "user load fail!"))); } switch (Tools::G('m')) { case 'addItem': if ($status = $user->addToWish(Tools::G('id'))) { if ($status === 1) { $result = array("m" => "add", 'status' => 'yes'); } else { if ($status === -1) { $result = array("m" => "delete", 'status' => 'yes'); } } die(json_encode($result)); } die(json_encode(array("status" => "no"))); break; default: break; } } /* start use add wish,from ProductView or CategoryView */ if (isset($_GET['action']) && $_GET['action'] == 'add_wish' && isset($_GET['id_product'])) { if ($action = Wish::userAddWishProduct($_GET['id_product'])) { $wishs = Wish::getWishSumByUser(); $count_html = ""; if ($wishs['count'] > 0) { $count_html = "<i>{$wishs['count']}</i>"; } $arr = array('action' => $action, 'count' => $count_html, 'status' => "YES"); echo json_encode($arr); } else { $arr = array('status' => "NO"); echo json_encode($arr); } exit; } //end use add wish /** * 邮箱是否已被注册 */ if (Tools::P('existsEmail')) { $valid = true; if (User::userExists(Tools::P('existsEmail'))) { $valid = false; } echo json_encode(array('valid' => $valid)); } }
protected function _changeCartGoodsNum($uid, $goods_id, $old_goods_num, $goods_num, $indecr = '+') { if ($indecr === '-') { $data['goods_num'] = $old_goods_num - $goods_num; } elseif ($indecr === '+') { $data['goods_num'] = $old_goods_num + $goods_num; } //获取商品数量,购物车的商品数量是否超出库存 $goods_info = AdminGoodsM::getGoodsInfoByGoodsId($goods_id); if ($goods_info['goods_num'] < $data['goods_num']) { $data['goods_num'] = $goods_info['goods_num']; } $where['goods_id'] = $goods_id; //是否登录的条件 $_where = self::_where($uid); $new_where = array_merge($where, $_where); return Cart::update($data, $new_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 editcartnum() { $cart_ids = $_POST['goods_number']; $uid = LuS::get('uid'); if ($cart_ids) { //处理数据 $cart_id = 0; foreach ($cart_ids as $key => $value) { $cart_id = $key; $goods_num = $value; //检查库存 $goods_id = Cart::getGoodsIdByCartId($cart_id); if ($goods_id) { //获取库存 $goods_info = AdminGoodsM::getGoodsInfoByGoodsId($goods_id); if ($goods_info['goods_num'] >= $goods_num) { $data['goods_num'] = $goods_num; $where['cart_id'] = $cart_id; Cart::update($data, $where); } else { $data['goods_num'] = $goods_info['goods_num']; $where['cart_id'] = $cart_id; Cart::update($data, $where); } } } $return = array(); //取出新数据 $cart_goods_list = Cart::select($uid); $data = Cart::getOrderTotal($cart_goods_list); $total = $data['total']; $all_num = $data['num']; $shipping_fee = Cart::getOrderShippingFee($total); $money_paid = $total + $shipping_fee; foreach ($cart_goods_list as $k => $v) { if ($v['cart_id'] == $cart_id) { $return[] = array($v['cart_id'], $v['goods_num'], $v['goods_price'], $total, $money_paid, $shipping_fee, $all_num); break; } } echo json_encode($return); } throw new Exception('exit'); }
public function hookbackOfficeTop($params) { // Check if the module is configured if (!Configuration::get('EBAY_PAYPAL_EMAIL')) { return false; } // If no update yet if (!Configuration::get('EBAY_ORDER_LAST_UPDATE')) { Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', date('Y-m-d') . 'T' . date('H:i:s') . '.000Z'); } // init Var $dateNew = date('Y-m-d') . 'T' . date('H:i:s') . '.000Z'; if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-30 minutes')) . 'T' . date('H:i:s', strtotime('-30 minutes')) . '.000Z') { // Lock Configuration::updateValue('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(date('Y-m-d', strtotime('-30 days')) . 'T' . date('H:i:s', strtotime('-30 days')) . '.000Z', $dateNew, $page); $orderCountTmp = count($orderListTmp); $orderList = array_merge((array) $orderList, (array) $orderListTmp); $orderCount += $orderCountTmp; $page++; } 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']) . '\'')) { $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')); // 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'])) { // Add customer if he doesn't exist if ($id_customer < 1) { $customer = new Customer(); $customer->id_gender = 9; $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) { $cartNbProducts = 0; $cartAdd = new Cart(); $cartAdd->id_customer = $id_customer; $cartAdd->id_address_invoice = $id_address; $cartAdd->id_address_delivery = $id_address; $cartAdd->id_carrier = 1; $cartAdd->id_lang = $this->id_lang; $cartAdd->id_currency = Currency::getIdByIsoCode('EUR'); $cartAdd->recyclable = 0; $cartAdd->gift = 0; $cartAdd->add(); foreach ($order['product_list'] as $product) { if ($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++; } } $cartAdd->update(); // Check number of products in the cart if ($cartNbProducts > 0) { // 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); } // Validate order $paiement = new eBayPayment(); $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)); $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) $updateOrder = array('total_paid' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']), 'total_products' => floatval($order['amount']), 'total_products_wt' => floatval($order['amount']), 'total_shipping' => floatval($order['shippingServiceCost'])); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $updateOrder, 'UPDATE', '`id_order` = ' . (int) $id_order); foreach ($order['product_list'] as $product) { Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', array('product_price' => floatval($product['price']), 'tax_rate' => 0, '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']); } // 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'); } 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"); } } }
function ajax_del_cart() { import('ORG.Util.Cart'); $id = intval($_REQUEST['id']); $cart = new Cart(); $arr = array('rowid' => md5($id), 'qty' => 0); $cart->update($arr); }
static function _initPaymentDetails() { // Uses the active currency $cart_amount = Cart::get_price(); // The Payment ID must be known and up to date when the cart is // parsed in order to consider payment dependent Coupons if (isset($_POST['paymentId'])) { $_SESSION['shop']['paymentId'] = intval($_POST['paymentId']); } // Determine any valid value for it if ($cart_amount && empty($_SESSION['shop']['paymentId'])) { $arrPaymentId = Payment::getCountriesRelatedPaymentIdArray($_SESSION['shop']['countryId'], Currency::getCurrencyArray()); $_SESSION['shop']['paymentId'] = current($arrPaymentId); } if (empty($_SESSION['shop']['paymentId'])) { $_SESSION['shop']['paymentId'] = null; } // hide currency navbar self::$show_currency_navbar = false; if (isset($_POST['customer_note'])) { $_SESSION['shop']['note'] = trim(strip_tags(contrexx_input2raw($_POST['customer_note']))); } if (isset($_POST['agb'])) { $_SESSION['shop']['agb'] = \Html::ATTRIBUTE_CHECKED; } if (isset($_POST['cancellation_terms'])) { $_SESSION['shop']['cancellation_terms'] = \Html::ATTRIBUTE_CHECKED; } // if shipperId is not set, there is no use in trying to determine a shipment_price if (isset($_SESSION['shop']['shipperId'])) { $shipmentPrice = self::_calculateShipmentPrice($_SESSION['shop']['shipperId'], Cart::get_price(), Cart::get_weight()); // anything wrong with this kind of shipping? if ($shipmentPrice == -1) { unset($_SESSION['shop']['shipperId']); $_SESSION['shop']['shipment_price'] = '0.00'; } else { $_SESSION['shop']['shipment_price'] = $shipmentPrice; } } else { $_SESSION['shop']['shipment_price'] = '0.00'; } $_SESSION['shop']['payment_price'] = self::_calculatePaymentPrice($_SESSION['shop']['paymentId'], $cart_amount); Cart::update(self::$objCustomer); self::update_session(); }
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_' . Tools::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; $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 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); } }
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; }
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; }
protected function _deleteProduct($orderDetail, $quantity) { $product_price_tax_excl = $orderDetail->unit_price_tax_excl * $quantity; $product_price_tax_incl = $orderDetail->unit_price_tax_incl * $quantity; /* Update cart */ $cart = new Cart($this->id_cart); $cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down'); // customization are deleted in deleteCustomization $cart->update(); /* Update order */ $shipping_diff_tax_incl = $this->total_shipping_tax_incl - $cart->getPackageShippingCost($this->id_carrier, true, null, $this->getCartProducts()); $shipping_diff_tax_excl = $this->total_shipping_tax_excl - $cart->getPackageShippingCost($this->id_carrier, false, null, $this->getCartProducts()); $this->total_shipping -= $shipping_diff_tax_incl; $this->total_shipping_tax_excl -= $shipping_diff_tax_excl; $this->total_shipping_tax_incl -= $shipping_diff_tax_incl; $this->total_products -= $product_price_tax_excl; $this->total_products_wt -= $product_price_tax_incl; $this->total_paid -= $product_price_tax_incl + $shipping_diff_tax_incl; $this->total_paid_tax_incl -= $product_price_tax_incl + $shipping_diff_tax_incl; $this->total_paid_tax_excl -= $product_price_tax_excl + $shipping_diff_tax_excl; $this->total_paid_real -= $product_price_tax_incl + $shipping_diff_tax_incl; $fields = array('total_shipping', 'total_shipping_tax_excl', 'total_shipping_tax_incl', 'total_products', 'total_products_wt', 'total_paid', 'total_paid_tax_incl', 'total_paid_tax_excl', 'total_paid_real'); /* Prevent from floating precision issues (total_products has only 2 decimals) */ foreach ($fields as $field) { if ($this->{$field} < 0) { $this->{$field} = 0; } } /* Prevent from floating precision issues */ foreach ($fields as $field) { $this->{$field} = number_format($this->{$field}, 2, '.', ''); } /* Update order detail */ $orderDetail->product_quantity -= (int) $quantity; if ($orderDetail->product_quantity == 0) { if (!$orderDetail->delete()) { return false; } if (count($this->getProductsDetail()) == 0) { $history = new OrderHistory(); $history->id_order = (int) $this->id; $history->changeIdOrderState(Configuration::get('PS_OS_CANCELED'), $this); if (!$history->addWithemail()) { return false; } } return $this->update(); } else { $orderDetail->total_price_tax_incl -= $product_price_tax_incl; $orderDetail->total_price_tax_excl -= $product_price_tax_excl; $orderDetail->total_shipping_price_tax_incl -= $shipping_diff_tax_incl; $orderDetail->total_shipping_price_tax_excl -= $shipping_diff_tax_excl; } return $orderDetail->update() && $this->update(); }
if (!isset($return['ERRORCODE']) or $return['ERRORCODE'] == NULL or in_array($return['ERRORCODE'], $nonBlockingError)) { if ($return['SIGNATURE'] === socolissimo::make_key($return['CENAME'], (double) $return['DYPREPARATIONTIME'], $return['DYFORWARDINGCHARGES'], $return['TRCLIENTNUMBER'], $return['ORDERID'])) { global $cookie; if (isset($cookie) or is_object($cookie)) { if (saveOrderShippingDetails((int) $cookie->id_cart, (int) $return['TRCLIENTNUMBER'], $return)) { global $cookie; $cart = new Cart((int) $cookie->id_cart); $TRPARAMPLUS = explode('|', Tools::getValue('TRPARAMPLUS')); $cart->id_carrier = $TRPARAMPLUS[0]; $cart->gift = (int) $TRPARAMPLUS[1]; if ((int) $cart->gift) { if (Validate::isMessage($TRPARAMPLUS[2])) { $cart->gift_message = strip_tags($TRPARAMPLUS[2]); } } if (!$cart->update()) { Tools::redirect(); } else { Tools::redirect('order.php?step=3&cgv=1'); } } else { echo '<div class="alert error"><img src="' . _PS_IMG_ . 'admin/forbbiden.gif" alt="nok" /> ' . $so->displaySoError('999') . ' <p><br/><a href="' . Tools::getProtocol(true) . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__ . 'order.php" class="button_small" title="Retour">« Retour</a></p></div>'; } } else { echo '<div class="alert error"><img src="' . _PS_IMG_ . 'admin/forbbiden.gif" alt="nok" /> ' . $so->displaySoError('999') . ' <p><br/><a href="' . Tools::getProtocol(true) . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__ . 'order.php" class="button_small" title="Retour">« Retour</a></p></div>'; } } else { echo '<div class="alert error"><img src="' . _PS_IMG_ . 'admin/forbbiden.gif" alt="nok" /> ' . $so->displaySoError('998') . ' <p><br/><a href="' . Tools::getProtocol(true) . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__ . 'order.php" class="button_small" title="Retour">« Retour</a></p></div>';
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); } }
public function resetCartPrices() { $cart = \Cart::content(); foreach ($cart as $item) { $product = $this->product->find($item->id); if ($product) { \Cart::update($item->rowid, array('price' => $product->price_cents)); } } }
public function update_cart_by_site_xml($order_id, $data) { $xml = simplexml_load_string($data); $prefix = _DB_PREFIX_; $tablename = $prefix . 'orders'; $total_amount = 0; $total_principal = 0; $shipping_amount = 0; $total_promo = 0; $ClientRequestId = 0; $WrappingAmount = 0; $gift = 0; $gift_message = ' '; foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) { $SKU = (string) $item->SKU; if ($SKU == 'wrapping_fee') { $WrappingAmount = (double) $item->Price->Amount; $gift = 1; $gift_message = (string) $item->Description; } $Title = (string) $item->Title; $Amount = (double) $item->Price->Amount; $ClientRequestId = (int) $item->ClientRequestId; $other_promo = 0; foreach ($item->ItemCharges->Component as $amount_type) { $item_charge_type = (string) $amount_type->Type; if ($item_charge_type == 'Principal') { $principal = (string) $amount_type->Charge->Amount; } if ($item_charge_type == 'Shipping') { $Shipping = (string) $amount_type->Charge->Amount; } if ($item_charge_type == 'PrincipalPromo') { $principal_promo = (string) $amount_type->Charge->Amount; } if ($item_charge_type == 'ShippingPromo') { $shipping_promo = (string) $amount_type->Charge->Amount; } if ($item_charge_type == 'OtherPromo') { $other_promo = (string) $amount_type->Charge->Amount; } } $CurrencyCode = (string) $item->Price->CurrencyCode; $Quantity = (int) $item->Quantity; /* * Total Item Charge = (Principal - PrincipalPromo) + (Shipping - ShippingPromo) + Tax + ShippingTax */ $total_principal += $principal; $total_amount += $principal - $principal_promo + ($Shipping - $shipping_promo); $shipping_amount += $Shipping; $total_promo += $principal_promo + $shipping_promo + $other_promo; } $total_principal = $total_principal - $WrappingAmount; $ShippingServiceLevel = (string) $xml->ProcessedOrder->ShippingServiceLevel; $sql = 'UPDATE `' . $prefix . 'pwa_orders` set `shipping_service` = "' . $ShippingServiceLevel . '" , `order_type` = "site" where `prestashop_order_id` = "' . $order_id . '" '; Db::getInstance()->Execute($sql); $id_cart = $ClientRequestId; $this->context = Context::getContext(); $this->context->cart = new Cart($id_cart); if ((int) $this->context->cart->id_customer == 0) { $email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress; $sql = 'SELECT * from `' . $prefix . 'customer` where email = "' . $email . '" '; $results = Db::getInstance()->ExecuteS($sql); if (empty($results)) { $name = (string) $xml->ProcessedOrder->BuyerInfo->BuyerName; $name_arr = explode(' ', $name); if (count($name_arr) > 1) { $firstname = ''; for ($i = 0; $i <= count($name_arr) - 2; $i++) { $firstname = $firstname . ' ' . $name_arr[$i]; } $lastname = $name_arr[count($name_arr) - 1]; } else { $firstname = $name; $lastname = '.'; } $password = Tools::passwdGen(); $customer = new Customer(); $customer->firstname = trim($firstname); $customer->lastname = $lastname; $customer->email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress; $customer->passwd = md5($password); $customer->active = 1; if (Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) { $customer->is_guest = 1; } else { $customer->is_guest = 0; } $customer->add(); $customer_id = $customer->id; if (Configuration::get('PS_CUSTOMER_CREATION_EMAIL') && !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) { Mail::Send($this->context->language->id, 'account', Mail::l('Welcome!'), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => $password), $customer->email, $customer->firstname . ' ' . $customer->lastname); } } else { $customer_id = $results[0]['id_customer']; } $id_country = Country::getByIso((string) $xml->ProcessedOrder->ShippingAddress->CountryCode); if ($id_country == 0 || $id_country == '') { $id_country = 110; } $name = (string) $xml->ProcessedOrder->ShippingAddress->Name; $name_arr = explode(' ', $name); if (count($name_arr) > 1) { $firstname = ''; for ($i = 0; $i <= count($name_arr) - 2; $i++) { $firstname = $firstname . ' ' . $name_arr[$i]; } $lastname = $name_arr[count($name_arr) - 1]; } else { $firstname = $name; $lastname = '.'; } $address = new Address(); $address->id_country = $id_country; $address->id_state = 0; $address->id_customer = $customer_id; $address->alias = 'My Address'; $address->firstname = trim($firstname); $address->lastname = $lastname; $address->address1 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldOne; $address->address2 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldTwo; $address->postcode = (string) $xml->ProcessedOrder->ShippingAddress->PostalCode; $address->city = (string) $xml->ProcessedOrder->ShippingAddress->City . ' ' . (string) $xml->ProcessedOrder->ShippingAddress->State; $address->active = 1; $address->add(); $address_id = $address->id; $cart = new Cart($id_cart); $cart->id_customer = $customer_id; $cart->id_address_delivery = $address_id; $cart->id_address_invoice = $address_id; $cart->update(); } $this->context->cart = new Cart($id_cart); $this->context->customer = new Customer($this->context->cart->id_customer); $id_order_state = 99; // The tax cart is loaded before the customer so re-cache the tax calculation method //$this->context->cart->setTaxCalculationMethod(); $this->context->language = new Language($this->context->cart->id_lang); $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop); $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency; $this->context->currency = new Currency($id_currency, null, $this->context->shop->id); $reference = Order::generateReference(); $cart_rules = $this->context->cart->getCartRules(); $order = new Order(); $order->id = $order_id; $order->id_customer = (int) $this->context->cart->id_customer; $order->id_address_invoice = (int) $this->context->cart->id_address_invoice; $order->id_shop = (int) $this->context->shop->id; $order->id_shop_group = (int) $this->context->shop->id_shop_group; $carrier = null; if ((int) $this->context->cart->id_carrier) { $carrier = 'yes'; $id_carrier = (int) $this->context->cart->id_carrier; } else { $sql = 'SELECT id_carrier from `' . $prefix . 'carrier` where `active` = 1 and `deleted` = 0 limit 0,1'; $result = Db::getInstance()->ExecuteS($sql); $id_carrier = $result[0]['id_carrier']; } $sql = 'UPDATE `' . $tablename . '` set `id_customer` = ' . (int) $this->context->cart->id_customer . ', `id_carrier` = ' . $id_carrier . ', `id_address_invoice` = ' . (int) $this->context->cart->id_address_invoice . ', `id_address_delivery` = ' . (int) $this->context->cart->id_address_delivery . ', `id_currency` = ' . $this->context->currency->id . ', `id_lang` = ' . (int) $this->context->cart->id_lang . ', `id_cart` = ' . (int) $this->context->cart->id . ', `reference` = "' . $reference . '", `id_shop` = ' . (int) $this->context->shop->id . ', `id_shop_group` = ' . (int) $this->context->shop->id_shop_group . ', `secure_key` = "' . $this->context->cart->secure_key . '", `conversion_rate` = ' . $this->context->currency->conversion_rate . ', `total_paid` = ' . $total_amount . ', `total_paid_tax_incl` = ' . $total_amount . ', `total_paid_tax_excl` = ' . $total_amount . ', `total_paid_real` = 0, `total_shipping` = ' . $shipping_amount . ', `total_shipping_tax_incl` = ' . $shipping_amount . ', `total_shipping_tax_excl` = ' . $shipping_amount . ', `total_discounts` = ' . (double) $total_promo . ', `total_discounts_tax_incl` = ' . (double) $total_promo . ', `total_discounts_tax_excl` = ' . (double) $total_promo . ', `total_products` = ' . $total_principal . ', `total_products_wt` = ' . $total_principal . ', `total_wrapping_tax_incl` = ' . $WrappingAmount . ', `total_wrapping_tax_excl` = ' . $WrappingAmount . ', `total_wrapping` = ' . $WrappingAmount . ', `gift` = ' . $gift . ', `gift_message` = "' . $gift_message . '", `invoice_date` = "0000-00-00 00:00:00", `delivery_date` = "0000-00-00 00:00:00" where `id_order` = ' . $order_id . ' '; //`round_mode` = '.Configuration::get('PS_PRICE_ROUND_MODE').', //`carrier_tax_rate` = '.$carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})).' , Db::getInstance()->Execute($sql); $acknowledge_arr = array(); $i = 0; foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) { $SKU = (string) $item->SKU; if ($SKU == 'wrapping_fee') { //Nothing } else { $AmazonOrderItemCode = (string) $item->AmazonOrderItemCode; $Title = (string) $item->Title; $Amount = (double) $item->Price->Amount; $product_id = (int) $item->ItemCustomData->Item_product_id; $product_attribute_id = (int) $item->ItemCustomData->Item_attr_product_id; $Item_price_excl_tax = $item->ItemCustomData->Item_price_excl_tax; $A_Name = ''; foreach ($item->ItemCustomData->Item_attribute as $attribute) { if ($A_Name == '') { $A_Name = $attribute->Attribute_name . ' : ' . $attribute->Attribute_val; } else { $A_Name = $A_Name . ', ' . $attribute->Attribute_name . ' : ' . $attribute->Attribute_val; } } $acknowledge_arr['items'][$i]['AmazonOrderItemCode'] = $AmazonOrderItemCode; $acknowledge_arr['items'][$i]['product_id'] = $product_id; $Title = $Title . ' - ' . $A_Name; $CurrencyCode = (string) $item->Price->CurrencyCode; $Quantity = (int) $item->Quantity; $other_promo = 0; foreach ($item->ItemCharges->Component as $amount_type) { $item_charge_type = (string) $amount_type->Type; if ($item_charge_type == 'Principal') { $principal = (string) $amount_type->Charge->Amount; } if ($item_charge_type == 'Shipping') { $Shipping = (string) $amount_type->Charge->Amount; } if ($item_charge_type == 'PrincipalPromo') { $principal_promo = (string) $amount_type->Charge->Amount; } if ($item_charge_type == 'ShippingPromo') { $shipping_promo = (string) $amount_type->Charge->Amount; } if ($item_charge_type == 'OtherPromo') { $other_promo = (string) $amount_type->Charge->Amount; } } $sql = 'INSERT into `' . $prefix . 'order_detail` set `id_order` = ' . $order_id . ', `product_id` = ' . $product_id . ', `product_attribute_id` = ' . $product_attribute_id . ', `product_name` = "' . $Title . '", `product_quantity` = ' . $Quantity . ', `product_quantity_in_stock` = ' . $Quantity . ', `product_price` = ' . $Amount . ', `product_reference` = "' . $SKU . '", `total_price_tax_incl` = ' . $Amount * $Quantity . ', `total_price_tax_excl` = ' . $Item_price_excl_tax * $Quantity . ', `unit_price_tax_incl` = ' . $Amount . ', `unit_price_tax_excl` = ' . $Item_price_excl_tax . ', `original_product_price` = ' . $Amount . ' '; Db::getInstance()->Execute($sql); if (Pack::isPack($product_id)) { $product = new Product((int) $product_id); if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2) { $products_pack = Pack::getItems($product_id, (int) Configuration::get('PS_LANG_DEFAULT')); foreach ($products_pack as $product_pack) { $sql = 'UPDATE `' . $prefix . 'stock_available` set `quantity` = `quantity` - ' . $product_pack->pack_quantity * $Quantity . ' where `id_product` = ' . $product_pack->id . ' and `id_product_attribute` = 0 '; Db::getInstance()->Execute($sql); $sql = 'UPDATE `' . $prefix . 'stock_available` set `quantity` = `quantity` - ' . $product_pack->pack_quantity * $Quantity . ' where `id_product` = ' . $product_pack->id . ' and `id_product_attribute` = ' . $product_pack->id_pack_product_attribute . ' '; Db::getInstance()->Execute($sql); } } if ($product->pack_stock_type == 0 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 0 || Configuration::get('PS_PACK_STOCK_TYPE') == 2)) { $sql = 'UPDATE `' . $prefix . 'stock_available` set `quantity` = `quantity` - ' . $Quantity . ' where `id_product` = ' . $product_id . ' and `id_product_attribute` = 0 '; Db::getInstance()->Execute($sql); if ($product_attribute_id > 0) { $sql = 'UPDATE `' . $prefix . 'stock_available` set `quantity` = `quantity` - ' . $Quantity . ' where `id_product` = ' . $product_id . ' and `id_product_attribute` = ' . $product_attribute_id . ' '; Db::getInstance()->Execute($sql); } $date = date('Y-m-d'); $sql = 'UPDATE `' . $prefix . 'product_sale` set `quantity` = `quantity` + ' . $Quantity . ', `sale_nbr` = `sale_nbr` + ' . $Quantity . ', `date_upd` = ' . $date . ' where `id_product` = ' . $product_id . ' '; Db::getInstance()->Execute($sql); } } else { $sql = 'UPDATE `' . $prefix . 'stock_available` set `quantity` = `quantity` - ' . $Quantity . ' where `id_product` = ' . $product_id . ' and `id_product_attribute` = 0 '; Db::getInstance()->Execute($sql); if ($product_attribute_id > 0) { $sql = 'UPDATE `' . $prefix . 'stock_available` set `quantity` = `quantity` - ' . $Quantity . ' where `id_product` = ' . $product_id . ' and `id_product_attribute` = ' . $product_attribute_id . ' '; Db::getInstance()->Execute($sql); } $date = date('Y-m-d'); $sql = 'UPDATE `' . $prefix . 'product_sale` set `quantity` = `quantity` + ' . $Quantity . ', `sale_nbr` = `sale_nbr` + ' . $Quantity . ', `date_upd` = ' . $date . ' where `id_product` = ' . $product_id . ' '; Db::getInstance()->Execute($sql); } } $i++; } // Adding an entry in order_carrier table if (!is_null($carrier)) { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $id_carrier; $order_carrier->weight = '0'; $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount; $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount; $order_carrier->add(); } else { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $id_carrier; $order_carrier->weight = '0'; $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount; $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount; $order_carrier->add(); } foreach ($cart_rules as $cart_rule) { $values['tax_incl'] = $cart_rule['value_real']; $values['tax_excl'] = $cart_rule['value_tax_exc']; $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping); } // Set the order status $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState((int) $id_order_state, $order->id, true); $history->addWithemail(true, array(), $this->context); if ($total_amount == 0) { $date = date('Y-m-d H:i:s'); $sql = 'INSERT into `' . $prefix . 'order_payment` set order_reference = "' . $reference . '", `id_currency` = "' . $this->context->currency->id . '", `amount` = "0.0", `payment_method` = "Pay With Amazon", `conversion_rate` = "' . $this->context->currency->conversion_rate . '", `date_add` = "' . $date . '" '; Db::getInstance()->Execute($sql); } $acknowledge_arr['MerchantOrderID'] = (int) $order->id; }
public static function editarProducto($input) { $respuesta = array(); $reglas = array('id' => array('integer')); $validator = Validator::make($input, $reglas); if ($validator->fails()) { $respuesta['mensaje'] = $validator; $respuesta['error'] = true; } else { if (is_null(Session::get('carrito'))) { Carrito::agregar($input); } if (isset($input['cantidad']) && $input['cantidad'] != "") { $cantidad = $input['cantidad']; } else { $cantidad = 1; } $producto = Producto::find($input['producto_id']); $carrito = Carrito::find(Session::get('carrito')); $datos[$producto->id] = array('cantidad' => $cantidad, 'precio' => $producto->precio(2), 'fecha_carga' => date("Y-m-d H:i:s"), 'estado' => 'A'); $carrito->productos()->sync($datos, false); Cart::update($input['rowId'], $cantidad); $respuesta['mensaje'] = 'Producto carrito modificado.'; $respuesta['error'] = false; $respuesta['data'] = $carrito; } return $respuesta; }