public function displayMain() { global $smarty, $link, $cookie; $errors = false; if (!$cookie->logged || !User::checkPassword($cookie->id_user, $cookie->passwd)) { Tools::redirect($link->getPage('userView')); } $referer = Tools::Q('referer') ? $link->getPage(Tools::Q('referer')) : $link->getPage('MyAddressesView'); if ($id_address = Tools::Q('id')) { $address = new Address((int) $id_address); if (Tools::isSubmit('saveAddress')) { $address->copyFromPost(); if ($address->update()) { Tools::redirect($referer); } else { $errors = $address->_errors; } } $smarty->assign('address', $address); } elseif (Tools::isSubmit('saveAddress')) { $address = new Address(); $address->copyFromPost(); $address->id_user = $cookie->id_user; if ($address->add()) { Tools::redirect($referer); } else { $errors = $address->_errors; } } $countrys = Country::loadData(1, 1000, 'position', 'asc', array('active' => true)); $smarty->assign(array('referer' => Tools::Q('referer'), 'countrys' => $countrys, 'errors' => $errors)); return $smarty->fetch('address.tpl'); }
public function init() { parent::init(); if (Tools::isSubmit('storedelivery') && (int) Tools::getValue('storedelivery') != 0) { //Save cookie only if previous id_adress wasn't a store $cookie = new Cookie('storedelivery'); $cookie->__set('id_address_delivery', $this->context->cart->id_address_delivery); $store = new Store(Tools::getValue('storedelivery')); //Test if store address exist in address table Tools::strlen($store->name) > 32 ? $storeName = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($storeName = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); $sql = 'SELECT id_address FROM ' . _DB_PREFIX_ . 'address WHERE alias=\'' . addslashes($storeName) . '\' AND address1=\'' . addslashes($store->address1) . '\' AND address2=\'' . addslashes($store->address2) . '\' AND postcode=\'' . $store->postcode . '\' AND city=\'' . addslashes($store->city) . '\' AND id_country=\'' . addslashes($store->id_country) . '\' AND active=1 AND deleted=0'; $id_address = Db::getInstance()->getValue($sql); //Create store adress if not exist for this user if (empty($id_address)) { $country = new Country($store->id_country, $this->context->language->id); $address = new Address(); $address->id_country = $store->id_country; $address->id_state = $store->id_state; $address->country = $country->name; Tools::strlen($store->name) > 32 ? $address->alias = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($address->alias = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); Tools::strlen($store->name) > 32 ? $address->lastname = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($address->lastname = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); $address->firstname = " "; $address->address1 = $store->address1; $address->address2 = $store->address2; $address->postcode = $store->postcode; $address->city = $store->city; $address->phone = $store->phone; $address->deleted = 0; //create an address non deleted to register them in order $address->add(); $id_address = $address->id; } //Update cart info $cart = $this->context->cart; $cart->id_address_delivery = $id_address; $cart->update(); //Change address of all product in cart else we are redirect on step Carrier because of function autostep or OrderController Db::getInstance()->update('cart_product', array('id_address_delivery' => (int) $id_address), $where = 'id_cart = ' . $this->context->cart->id); //Change post carrier option else bad default carrier is saved by fonction processCarrier of ParentOrderController $array = array_values(Tools::getValue('delivery_option')); $_POST['delivery_option'] = array($id_address => $array[0]); } else { $cookie = new Cookie('storedelivery'); $id_address_delivery = $cookie->__get('id_address_delivery'); if ($id_address_delivery != false && $this->context->cart->id_address_delivery != $id_address_delivery && Tools::isSubmit('storedelivery')) { $this->context->cart->id_address_delivery = $cookie->__get('id_address_delivery'); $this->context->cart->update(); //Change address of all product in cart else we are redirect on step Carrier because of function autostep or OrderController Db::getInstance()->update('cart_product', array('id_address_delivery' => (int) $cookie->__get('id_address_delivery')), $where = 'id_cart = ' . $this->context->cart->id); //Change post carrier option else bad default carrier is saved by fonction processCarrier of ParentOrderController $array = array_values(Tools::getValue('delivery_option')); $_POST['delivery_option'] = array($cookie->__get('id_address_delivery') => $array[0]); $cookie->__unset('id_address_delivery'); } } }
public function init() { parent::init(); if (Tools::isSubmit('storedelivery') && (int) Tools::getValue('storedelivery') != 0) { $cookie = new Cookie('storedelivery'); $cookie->__set('id_address_delivery', $this->context->cart->id_address_delivery); $store = new Store(Tools::getValue('storedelivery')); Tools::strlen($store->name) > 32 ? $storeName = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($storeName = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); $sql = 'SELECT id_address FROM ' . _DB_PREFIX_ . 'address WHERE alias=\'' . addslashes($storeName) . '\' AND address1=\'' . addslashes($store->address1) . '\' AND address2=\'' . addslashes($store->address2) . '\' AND postcode=\'' . $store->postcode . '\' AND city=\'' . addslashes($store->city) . '\' AND id_country=\'' . addslashes($store->id_country) . '\' AND active=1 AND deleted=0'; $id_address = Db::getInstance()->getValue($sql); if (empty($id_address)) { $country = new Country($store->id_country, $this->context->language->id); $address = new Address(); $address->id_country = $store->id_country; $address->id_state = $store->id_state; $address->country = $country->name; Tools::strlen($store->name) > 32 ? $address->alias = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($address->alias = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); Tools::strlen($store->name) > 32 ? $address->lastname = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($address->lastname = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); $address->firstname = " "; $address->address1 = $store->address1; $address->address2 = $store->address2; $address->postcode = $store->postcode; $address->city = $store->city; $address->phone = $store->phone; $address->deleted = 0; $address->add(); $id_address = $address->id; } $cart = $this->context->cart; $cart->id_address_delivery = $id_address; $cart->update(); Db::getInstance()->update('cart_product', array('id_address_delivery' => (int) $id_address), $where = 'id_cart = ' . $this->context->cart->id); $array = array_values(Tools::getValue('delivery_option')); $_POST['delivery_option'] = array($id_address => $array[0]); } else { $cookie = new Cookie('storedelivery'); $id_address_delivery = $cookie->__get('id_address_delivery'); if ($id_address_delivery != false && $this->context->cart->id_address_delivery != $id_address_delivery && Tools::isSubmit('storedelivery')) { $this->context->cart->id_address_delivery = $cookie->__get('id_address_delivery'); $this->context->cart->update(); Db::getInstance()->update('cart_product', array('id_address_delivery' => (int) $cookie->__get('id_address_delivery')), $where = 'id_cart = ' . $this->context->cart->id); $array = array_values(Tools::getValue('delivery_option')); $_POST['delivery_option'] = array($cookie->__get('id_address_delivery') => $array[0]); $cookie->__unset('id_address_delivery'); } } }
public function displayMain() { global $smarty, $link; $errors = array(); if (Tools::isSubmit('CreateUser')) { if (!Validate::isEmail(Tools::getRequest('email')) || User::userExists(Tools::getRequest('email'))) { $errors[] = 'The email is invalid or an account is already registered with this e-mail!'; } elseif (empty($_POST['passwd'])) { $errors[] = 'The password is empty!'; } else { $user = new User(); $user->copyFromPost(); $user->active = 1; if ($user->add()) { $address = new Address(); $address->copyFromPost(); $address->id_user = $user->id; $address->is_default = 1; if ($address->add()) { $user->logined(array('id_address' => $address->id)); if (Tools::getRequest("step") == 2) { Tools::redirect($link->getPage('CheckoutView')); } else { Tools::redirect($link->getPage('MyaccountView')); } return; } else { $errors = $address->_errors; } } else { $errors = $user->_errors; } } } $countrys = Country::loadData(1, 500, null, null, array('active' => 1)); $smarty->assign(array('id_default_country' => Configuration::get('TM_DEFAULT_COUNTRY_ID'), 'countrys' => $countrys, 'step' => Tools::getRequest("step"), 'errors' => $errors)); return $smarty->fetch('join.tpl'); }
function getShippingAddressID($id_country, $id_state) { if (!$id_state) { $id_state = 0; } $sql = 'SELECT id_address FROM `' . _DB_PREFIX_ . 'address` WHERE alias=\'agileexpress\' AND id_customer=0 AND id_manufacturer=0 AND id_supplier=0 AND id_country=' . $id_country . ' AND id_state=' . $id_state; $result = Db::getInstance()->getRow($sql); $id_address = 0; $id_address = isset($result['id_address']) ? intval($result['id_address']) : 0; if ($id_address <= 0) { $address = new Address(); $address->id = 0; $address->alias = 'agileexpress'; $address->id_customer = 0; $address->id_manufacturer = 0; $address->id_supplier = 0; $address->id_country = $id_country; $address->id_state = $id_state; $address->lastname = 'Temporary'; $address->firstname = 'Address'; $address->address1 = 'For shipping fee and tax calculation only'; $address->address2 = 'It will be replaced with real address'; $address->city = ' after payment'; $address->postcode = 'postcode'; $address->add(); $id_address = $address->id; } return $id_address; }
public function hookAjaxOpc() { $cookie = new Cookie('storedelivery'); $cookie->__set('id_address_delivery', $this->context->cart->id_address_delivery); $cookie->__set('opc', true); if (Tools::isSubmit('storedelivery') && (int) Tools::getValue('storedelivery') != 0) { $store = new Store(Tools::getValue('storedelivery')); //Test if store address exist in address table Tools::strlen($store->name) > 32 ? $storeName = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($storeName = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); $sql = 'SELECT id_address FROM ' . _DB_PREFIX_ . 'address WHERE alias=\'' . addslashes($storeName) . '\' AND address1=\'' . addslashes($store->address1) . '\' AND address2=\'' . addslashes($store->address2) . '\' AND postcode=\'' . $store->postcode . '\' AND city=\'' . addslashes($store->city) . '\' AND id_country=\'' . addslashes($store->id_country) . '\' AND active=1 AND deleted=0'; $id_address = Db::getInstance()->getValue($sql); //Create store adress if not exist for this user if (empty($id_address)) { $country = new Country($store->id_country, $this->context->language->id); $address = new Address(); $address->id_country = $store->id_country; $address->id_state = $store->id_state; $address->country = $country->name; Tools::strlen($store->name) > 32 ? $address->alias = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($address->alias = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); Tools::strlen($store->name) > 32 ? $address->lastname = Tools::substr(preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name), 0, 29) . '...' : ($address->lastname = preg_replace("/[^a-zA-Zěščřžýáíéèêàô ]+/", '', $store->name)); $address->firstname = $this->l('Store of'); $address->address1 = $store->address1; $address->address2 = $store->address2; $address->postcode = $store->postcode; $address->city = $store->city; $address->phone = $store->phone; $address->deleted = 0; //create an address non deleted to register them in order $address->add(); $id_address = $address->id; } $cookie->__set('id_address_delivery', $id_address); } die(Tools::jsonEncode(array('result' => "ok"))); }
public function ajaxProcessSaveOrder() { $products = Tools::getValue('products'); $delivery_date = Tools::getValue('delivery_date'); $delivery_time_from = Tools::getValue('delivery_time_from'); $delivery_time_to = Tools::getValue('delivery_time_to'); $id_employee = Tools::getValue('employees'); if (!empty($id_employee) && is_array($id_employee)) { $id_employee = $id_employee[0]; } $other = Tools::getValue('other'); if (empty($products)) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Products to be select', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Non e\' stato selezionato nessun prodotto. Prego selezionarle almeno uno.'))); } $id_customer = (int) Tools::getValue('id_customer'); if ($id_customer < 1) { $customer = new Customer(); $customer->firstname = Tools::getValue('firstname'); $customer->lastname = Tools::getValue('lastname'); $customer->email = Tools::getValue('email'); $customer->phone = Tools::getValue('phone'); $customer->id_gender = Tools::getValue('id_gender'); $customer->id_shop = (int) Context::getContext()->shop->id; $customer->passwd = strtoupper(Tools::passwdGen(10)); $customer->newsletter = 1; if ($customer->validateFields(false, true) !== true) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Fields of customer not valid', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione del cliente. Prego riprovare.'))); } $result = $customer->add(); if (!$result) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Address of customer is to be added', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione del cliente. Prego riprovare.'))); } $stores = Db::getInstance()->executeS(' SELECT st.id_country,st.id_state,st.city FROM ' . _DB_PREFIX_ . 'store_shop ss LEFT JOIN `' . _DB_PREFIX_ . 'store` st ON (ss.`id_store` = st.`id_store`) WHERE ss.`id_shop` = ' . (int) Context::getContext()->shop->id); $address = new Address(); $address->id_customer = $customer->id; $address->alias = 'indirizzo'; $address->firstname = $customer->firstname; $address->lastname = $customer->lastname; $address->address1 = '-'; $address->postcode = '00000'; $address->phone = $customer->phone; $address->phone_mobile = $customer->phone; $address->id_country = $stores[0]['id_country']; $address->id_state = $stores[0]['id_state']; $address->city = $stores[0]['city']; if ($address->validateFields(false, true) !== true) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Fields of address of customer not valid', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione del cliente. Prego riprovare.'))); } $address->add(); $customer->id_address_delivery = $address->id; $customer->id_address_invoice = $address->id; if (!$result) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Customer is to be added', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione del cliente. Prego riprovare.'))); } $id_customer = $customer->id; } else { $customer = new Customer($id_customer); $customer->firstname = Tools::getValue('firstname'); $customer->lastname = Tools::getValue('lastname'); $customer->email = Tools::getValue('email'); $customer->phone = Tools::getValue('phone'); $customer->id_gender = Tools::getValue('id_gender'); $customer->id_shop = (int) Context::getContext()->shop->id; $customer->update(); $addresses = $customer->getAddresses((int) Context::getContext()->language->id); if (empty($addresses)) { $customer->id_address_delivery = $customer->id_address_invoice = 0; } else { $customer->id_address_delivery = $addresses[0]['id_address']; $customer->id_address_invoice = $addresses[0]['id_address']; $address = new Address($addresses[0]['id_address'], (int) Context::getContext()->language->id); $address->firstname = $customer->firstname; $address->lastname = $customer->lastname; $address->phone = $customer->phone; $address->phone_mobile = $customer->phone; $address->update(); } } $id_order = (int) Tools::getValue('id_order'); $feature_duration = Configuration::get('APH_FEATURE_DURATION'); $services_duration = json_decode(Configuration::get('APH_SERVICES_DURATION'), true); $reservation_offline_status = Configuration::get('APH_RESERVATION_OFFLINE_STATUS'); // always add taxes even if there are not displayed to the customer $use_taxes = true; // Total method $total_method = Cart::BOTH_WITHOUT_SHIPPING; //TODO ajaxProcessAddProductOnOrder() in AdminOrdersController if ($id_order < 1) { do { $reference = Order::generateReference(); } while (Order::getByReference($reference)->count()); $order = new Order(); $order->id_customer = (int) $customer->id; $order->secure_key = $customer->secure_key; $order->id_address_invoice = $customer->id_address_delivery; $order->id_address_delivery = $customer->id_address_invoice; $order->id_currency = (int) Context::getContext()->currency->id; $order->id_lang = (int) Context::getContext()->language->id; $order->reference = $reference; $order->id_shop = (int) Context::getContext()->shop->id; $order->id_shop_group = (int) Context::getContext()->shop->id_shop_group; $order->id_cart = 0; $order->id_carrier = 0; $order->payment = 'Pagamento alla consegna'; $order->module = 'cashondelivery'; $order->total_paid = 0; $order->total_paid_real = 0; $order->total_products = 0; $order->total_products_wt = 0; $order->conversion_rate = 1; $order->delivery_number = 1; $order->delivery_date = $delivery_date . ' ' . $delivery_time_from; $order->current_state = $reservation_offline_status; if ($order->validateFields(false, true) !== true) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Fields of order not valid', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione dell\'appuntamento. Prego riprovare.'))); } $result = $order->add(); if (!$result) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Order is about to be added', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante la creazione dell\'appuntamento. Prego riprovare.'))); } // 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); // calculate prices of products $products_detail = array(); foreach ($products as &$product_id) { $product = new Product($product_id, false, $order->id_lang, $order->id_shop); $products_detail[$product_id] = array(); $products_detail[$product_id]['id'] = $products_detail[$product_id]['id_product'] = $product_id; $products_detail[$product_id]['name'] = $product->name; $products_detail[$product_id]['ean13'] = $product->ean13; $products_detail[$product_id]['upc'] = $product->upc; $products_detail[$product_id]['reference'] = $product->reference; $products_detail[$product_id]['cart_quantity'] = 1; $products_detail[$product_id]['id_product_attribute'] = 0; $products_detail[$product_id]['id_shop'] = $order->id_shop; $products_detail[$product_id]['id_supplier'] = 0; $products_detail[$product_id]['weight'] = $product->weight; $products_detail[$product_id]['height'] = $product->height; $products_detail[$product_id]['depth'] = $product->depth; $products_detail[$product_id]['ecotax'] = $product->ecotax; $products_detail[$product_id]['price_without_reduction'] = Product::getPriceStatic((int) $product_id, true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context); $products_detail[$product_id]['price_with_reduction'] = Product::getPriceStatic((int) $product_id, true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context); $products_detail[$product_id]['price'] = $products_detail[$product_id]['price_with_reduction_without_tax'] = Product::getPriceStatic((int) $product_id, false, $products_detail[$product_id]['id_product_attribute'], 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context); switch (Configuration::get('PS_ROUND_TYPE')) { case Order::ROUND_TOTAL: $products_detail[$product_id]['total'] = $products_detail[$product_id]['price_with_reduction_without_tax'] * (int) $products_detail[$product_id]['cart_quantity']; $products_detail[$product_id]['total_wt'] = $products_detail[$product_id]['price_with_reduction'] * (int) $products_detail[$product_id]['cart_quantity']; break; case Order::ROUND_LINE: $products_detail[$product_id]['total'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction_without_tax'] * (int) $products_detail[$product_id]['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_); $products_detail[$product_id]['total_wt'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction'] * (int) $products_detail[$product_id]['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_); break; case Order::ROUND_ITEM: default: $products_detail[$product_id]['total'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction_without_tax'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $products_detail[$product_id]['cart_quantity']; $products_detail[$product_id]['total_wt'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $products_detail[$product_id]['cart_quantity']; break; } $products_detail[$product_id]['price_wt'] = $products_detail[$product_id]['price_with_reduction']; $products_detail[$product_id]['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction']; $products_detail[$product_id]['wholesale_price'] = $product->wholesale_price; $products_detail[$product_id]['additional_shipping_cost'] = $product->additional_shipping_cost; // Add product to cart $update_quantity = $cart->updateQty($products_detail[$product_id]['cart_quantity'], $product->id, $products_detail[$product_id]['id_product_attribute'], null, 'up', 0, new Shop($cart->id_shop)); $order_detail = new AphOrderDetail(); $order_detail->createList($order, $cart, $order->current_state, array($products_detail[$product_id]), 0, $use_taxes, 0); // 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); // 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->id_cart = $cart->id; $order->update(); // Update Tax lines $order_detail->updateTaxAmount($order); // duration event $features = $product->getFeatures(); foreach ($features as &$feature) { if ($feature_duration == $feature['id_feature']) { $products_detail[$product_id]['duration'] = (int) $services_duration[$feature['id_feature_value']]; } } $order_detail->id_employee = $id_employee; $order_detail->delivery_date = $delivery_date; $order_detail->delivery_time_from = $delivery_time_from; if (!empty($products_detail[$product_id]['duration'])) { $time = new DateTime($delivery_date . ' ' . $delivery_time_from); $time->add(new DateInterval('PT' . $products_detail[$product_id]['duration'] . 'M')); $time_to = $time->format('H:i'); if ($time_to > $delivery_time_to) { $delivery_time_to = $time_to; } } $order_detail->delivery_time_to = $delivery_time_to; $order_detail->note = $other; $order_detail->update(); } } else { $order = new Order($id_order); $order->id_customer = (int) $customer->id; $order->secure_key = $customer->secure_key; $order->id_address_invoice = $customer->id_address_delivery; $order->id_address_delivery = $customer->id_address_invoice; $order->id_currency = (int) Context::getContext()->currency->id; $order->id_lang = (int) Context::getContext()->language->id; $order->total_paid = 0; $order->total_paid_real = 0; $order->total_products = 0; $order->total_products_wt = 0; $order->conversion_rate = 1; $order->delivery_number = 1; $order->delivery_date = $delivery_date . ' ' . $delivery_time_from; if ($order->validateFields(false, true) !== true) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Fields of order not valid', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante l\'aggiornamento dell\'appuntamento. Prego riprovare.'))); } $result = $order->update(); if (!$result) { PrestaShopLogger::addLog('AphCalendar::saveOrder - Order is about to be added', 1, null, 'AphCalendar', 0, true); die(Tools::jsonEncode(array('result' => false, 'error' => 'Si e\' verificato un problema durante l\'aggiornamento dell\'appuntamento. Prego riprovare.'))); } // Create new cart $cart = new Cart($order->id_cart); // Save context (in order to apply cart rule) $this->context->cart = $cart; $this->context->customer = new Customer($order->id_customer); $id_order_detail = Tools::getValue('id_order_detail'); $order_detail = new AphOrderDetail($id_order_detail); if (empty($products_detail[$order_detail->product_id])) { $order_detail->delete(); } // calculate prices of products $products_detail = array(); $is_to_update = false; foreach ($products as &$product_id) { $is_to_update = $product_id == $order_detail->product_id; $product = new Product($product_id, false, $order->id_lang, $order->id_shop); $products_detail[$product_id] = array(); $products_detail[$product_id]['id'] = $products_detail[$product_id]['id_product'] = $product_id; $products_detail[$product_id]['name'] = $product->name; $products_detail[$product_id]['ean13'] = $product->ean13; $products_detail[$product_id]['upc'] = $product->upc; $products_detail[$product_id]['reference'] = $product->reference; $products_detail[$product_id]['cart_quantity'] = 1; $products_detail[$product_id]['id_product_attribute'] = 0; $products_detail[$product_id]['id_shop'] = $order->id_shop; $products_detail[$product_id]['id_supplier'] = 0; $products_detail[$product_id]['weight'] = $product->weight; $products_detail[$product_id]['height'] = $product->height; $products_detail[$product_id]['depth'] = $product->depth; $products_detail[$product_id]['ecotax'] = $product->ecotax; $products_detail[$product_id]['price_without_reduction'] = Product::getPriceStatic((int) $product_id, true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context); $products_detail[$product_id]['price_with_reduction'] = Product::getPriceStatic((int) $product_id, true, isset($row['id_product_attribute']) ? (int) $row['id_product_attribute'] : null, 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context); $products_detail[$product_id]['price'] = $products_detail[$product_id]['price_with_reduction_without_tax'] = Product::getPriceStatic((int) $product_id, false, $products_detail[$product_id]['id_product_attribute'], 6, null, false, true, $products_detail[$product_id]['cart_quantity'], false, $order->id_customer, (int) $cart->id, $order->id_address_invoice, $specific_price_output, true, true, $this->context); switch (Configuration::get('PS_ROUND_TYPE')) { case Order::ROUND_TOTAL: $products_detail[$product_id]['total'] = $products_detail[$product_id]['price_with_reduction_without_tax'] * (int) $products_detail[$product_id]['cart_quantity']; $products_detail[$product_id]['total_wt'] = $products_detail[$product_id]['price_with_reduction'] * (int) $products_detail[$product_id]['cart_quantity']; break; case Order::ROUND_LINE: $products_detail[$product_id]['total'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction_without_tax'] * (int) $products_detail[$product_id]['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_); $products_detail[$product_id]['total_wt'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction'] * (int) $products_detail[$product_id]['cart_quantity'], _PS_PRICE_COMPUTE_PRECISION_); break; case Order::ROUND_ITEM: default: $products_detail[$product_id]['total'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction_without_tax'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $products_detail[$product_id]['cart_quantity']; $products_detail[$product_id]['total_wt'] = Tools::ps_round($products_detail[$product_id]['price_with_reduction'], _PS_PRICE_COMPUTE_PRECISION_) * (int) $products_detail[$product_id]['cart_quantity']; break; } $products_detail[$product_id]['price_wt'] = $products_detail[$product_id]['price_with_reduction']; $products_detail[$product_id]['reduction_applies'] = $specific_price_output && (double) $specific_price_output['reduction']; $products_detail[$product_id]['wholesale_price'] = $product->wholesale_price; $products_detail[$product_id]['additional_shipping_cost'] = $product->additional_shipping_cost; // Add product to cart $update_quantity = $cart->updateQty($products_detail[$product_id]['cart_quantity'], $product->id, $products_detail[$product_id]['id_product_attribute'], null, 'up', 0, new Shop($cart->id_shop)); $order_detail = new AphOrderDetail(); $order_detail->createList($order, $cart, $order->current_state, array($products_detail[$product_id]), 0, $use_taxes, 0); // 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); // 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->id_cart = $cart->id; $order->update(); // Update Tax lines $order_detail->updateTaxAmount($order); // duration event $features = $product->getFeatures(); foreach ($features as &$feature) { if ($feature_duration == $feature['id_feature']) { $products_detail[$product_id]['duration'] = (int) $services_duration[$feature['id_feature_value']]; } } $order_detail->id_employee = $id_employee; $order_detail->delivery_date = $delivery_date; $order_detail->delivery_time_from = $delivery_time_from; if (!empty($products_detail[$product_id]['duration'])) { $time = new DateTime($delivery_date . ' ' . $delivery_time_from); $time->add(new DateInterval('PT' . $products_detail[$product_id]['duration'] . 'M')); $time_to = $time->format('H:i'); if ($time_to > $delivery_time_to) { $delivery_time_to = $time_to; } } $order_detail->delivery_time_to = $delivery_time_to; $order_detail->note = $other; if ($is_to_update) { $order_detail->update(); } else { $order_detail->add(); } } } $send_memo = (bool) Tools::getValue('send_memo'); if (!empty($send_memo)) { $shop = new AphStore($products_detail[$product_id]['id_shop']); $topic = 'Promemoria appuntamento'; $data = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{product_name}' => $products_detail[$product_id]['name'], '{delivery_date}' => $order_detail->delivery_date, '{delivery_time_from}' => $order_detail->delivery_time_from, '{shop_name}' => $shop->name, '{shop_address}' => $shop->shop_address1 . (!empty($shop->shop_address2) ? ' ' . $shop->shop_address2 : ''), '{shop_city}' => $shop->shop_city, '{shop_link_rewrite}' => $shop->shop_link_rewrite, '{shop_phone}' => $shop->phone); if (Validate::isLoadedObject($order)) { !Mail::Send((int) $order->id_lang, 'order_memo', $topic, $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, false, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } } die(Tools::jsonEncode(array('result' => true))); }
/** * Create virtual address to associate id_zone for a country selection * * @param $id_country * @param $zipcode * @return bool */ private function addAddress($id_country, $zipcode) { $customer = new Customer((int) Configuration::get(CarrierCompare::VIRTUAL_CUSTOMER)); $address = new Address(); $address->id_country = $id_country; $address->alias = 'Shipping Estimation'; $address->lastname = $customer->lastname; $address->firstname = $customer->firstname; $address->address1 = 'test'; $address->city = 'test'; $address->postcode = $zipcode; $address->id_customer = $customer->id; if ($address->add()) { Configuration::updateValue(CarrierCompare::VIRTUAL_ADDRESS, $address->id); return true; } return false; }
protected function getPSAddress(Customer $customer, ShopgateAddress $shopgateAddress) { // Get country $id_country = Country::getByIso($shopgateAddress->getCountry()); if (!$id_country) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_UNKNOWN_COUNTRY_CODE, 'Invalid country code:' . $id_country, true); } // Get state $id_state = 0; if ($shopgateAddress->getState()) { $id_state = (int) Db::getInstance()->getValue('SELECT `id_state` FROM `' . _DB_PREFIX_ . 'state` WHERE `id_country` = ' . $id_country . ' AND `iso_code` = \'' . pSQL(Tools::substr($shopgateAddress->getState(), 3, 2)) . '\''); } // Create alias $alias = Tools::substr('Shopgate_' . $customer->id . '_' . sha1($customer->id . '-' . $shopgateAddress->getFirstName() . '-' . $shopgateAddress->getLastName() . '-' . $shopgateAddress->getCompany() . '-' . $shopgateAddress->getStreet1() . '-' . $shopgateAddress->getStreet2() . '-' . $shopgateAddress->getZipcode() . '-' . $shopgateAddress->getCity()), 0, 32); // Try getting address id by alias $id_address = Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `alias` = \'' . pSQL($alias) . '\' AND `id_customer`=' . $customer->id); // Get or create address $address = new Address($id_address ? $id_address : null); if (!$address->id) { $address->id_customer = $customer->id; $address->id_country = $id_country; $address->id_state = $id_state; $address->country = Country::getNameById($this->id_lang, $address->id_country); $address->alias = $alias; $address->company = $shopgateAddress->getCompany(); $address->lastname = $shopgateAddress->getLastName(); $address->firstname = $shopgateAddress->getFirstName(); $address->address1 = $shopgateAddress->getStreet1(); $address->address2 = $shopgateAddress->getStreet2(); $address->postcode = $shopgateAddress->getZipcode(); $address->city = $shopgateAddress->getCity(); $address->phone = $shopgateAddress->getPhone(); $address->phone_mobile = $shopgateAddress->getMobile(); if (!$address->add()) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create address', true); } } return $address; }
function submitAccount() { global $cookie, $errors, $smarty; $email = Tools::getValue('email'); if (empty($email) or !Validate::isEmail($email)) { $errors[] = Tools::displayError('e-mail not valid'); } elseif (!Validate::isPasswd(Tools::getValue('passwd'))) { $errors[] = Tools::displayError('invalid password'); } elseif (Customer::customerExists($email)) { $errors[] = Tools::displayError('someone has already registered with this e-mail address'); } elseif (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) and !(Tools::getValue('months') == '' and Tools::getValue('days') == '' and Tools::getValue('years') == '')) { $errors[] = Tools::displayError('invalid birthday'); } else { $customer = new Customer(); if (Tools::isSubmit('newsletter')) { $customer->ip_registration_newsletter = pSQL(Tools::getRemoteAddr()); $customer->newsletter_date_add = pSQL(date('Y-m-d h:i:s')); } $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days']; /* Customer and address, same fields, caching data */ $errors = $customer->validateControler(); $address = new Address(); $address->id_customer = 1; $errors = array_unique(array_merge($errors, $address->validateControler())); if (!sizeof($errors)) { $customer->active = 1; if (!$customer->add()) { $errors[] = Tools::displayError('an error occurred while creating your account'); } else { $address->id_customer = (int) $customer->id; if (!$address->add()) { $errors[] = Tools::displayError('an error occurred while creating your address'); } else { if (Mail::Send((int) $cookie->id_lang, 'account', Mail::l('Welcome!', (int) $cookie->id_lang), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd')), $customer->email, $customer->firstname . ' ' . $customer->lastname)) { $smarty->assign('confirmation', 1); } $cookie->id_customer = (int) $customer->id; $cookie->customer_lastname = $customer->lastname; $cookie->customer_firstname = $customer->firstname; $cookie->passwd = $customer->passwd; $cookie->logged = 1; $cookie->email = $customer->email; Module::hookExec('createAccount', array('_POST' => $_POST, 'newCustomer' => $customer)); // Next ! $payerID = strval(Tools::getValue('payerID')); displayProcess($payerID); } } } } }
/** * make new address of PILIBABA WAREHOUSE assign to customer * * @param Order , * * @return id, The address id which inserted into database; **/ protected function newAddress($order) { $pilibbabAddress = PilipayWarehouseAddress::getWarehouseAddressBy(Tools::getValue(self::PILIPAY_WAREHOUSES, Configuration::get(self::PILIPAY_WAREHOUSES))); $AddressObject = new Address(); $AddressObject->id_customer = $order->id_customer; $AddressObject->firstname = pSQL($pilibbabAddress['firstName']); $AddressObject->lastname = pSQL($pilibbabAddress['lastName']); $AddressObject->address1 = pSQL($pilibbabAddress['address']); $AddressObject->city = pSQL($pilibbabAddress['city']); $AddressObject->id_country = pSQL(PilipayWarehouseAddress::getCountryId()); $AddressObject->id_state = pSQL(PilipayWarehouseAddress::getStateId()); $AddressObject->phone = pSQL($pilibbabAddress['tel']); $AddressObject->postcode = pSQL($pilibbabAddress['zipcode']); $AddressObject->alias = 'pilibaba'; $AddressObject->add(); return $AddressObject->id; }
private function saveAddress($cart_id_address, $id_country, $id_state, $postcode, $city, $firstname, $lastname, $address1) { $dummy = "dummyvalue"; if ($cart_id_address > 0) { // update existing one $tmp_addr = new Address($cart_id_address); $tmp_addr->deleted = 0; } else { // create a new address $tmp_addr = new Address(); $tmp_addr->alias = "My Address"; $tmp_addr->lastname = $dummy; $tmp_addr->firstname = $dummy; $tmp_addr->address1 = $dummy; $tmp_addr->postcode = $postcode; $tmp_addr->city = $dummy; } if (trim($postcode) != "") { $tmp_addr->postcode = $postcode; } if (trim($city) != "") { $tmp_addr->city = $city; } if (trim($firstname) != "") { $tmp_addr->firstname = $firstname; } if (trim($lastname) != "") { $tmp_addr->lastname = $lastname; } if (trim($address1) != "") { $tmp_addr->address1 = $address1; } if (trim($id_country) == "") { $id_country = (int) Configuration::get('PS_COUNTRY_DEFAULT'); } if (trim($id_country) != "") { $tmp_addr->id_country = $id_country; if (trim($id_state) != "") { $tmp_addr->id_state = $id_state; } else { $tmp_addr->id_state = 0; } if (Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(dirname(__FILE__) . '/../../modules/vatnumber/vatnumber.php') && !VatNumber::isApplicable($id_country)) { $tmp_addr->vat_number = ""; } if ($cart_id_address > 0) { $tmp_addr->update(); } else { $tmp_addr->add(); } return $tmp_addr->id; } else { return 0; } }
private function saveAddress($cart_id_address, $id_country, $id_state, $postcode, $city, $firstname, $lastname, $address1) { $dummy = "dummyvalue"; if ($cart_id_address > 0) { // update existing one /* @var $tmp_addr AddressCore */ $tmp_addr = new Address($cart_id_address); $tmp_addr->deleted = 0; } else { // create a new address $tmp_addr = new Address(); $tmp_addr->alias = "My Address"; $tmp_addr->lastname = $dummy; $tmp_addr->firstname = $dummy; $tmp_addr->address1 = $dummy; $tmp_addr->postcode = $postcode; $tmp_addr->city = $dummy; } if (trim($postcode) != "") { $tmp_addr->postcode = $postcode; } // For carrier module which depend on city field if (trim($city) != "") { $tmp_addr->city = $city; } if (trim($firstname) != "") { $tmp_addr->firstname = $firstname; } if (trim($lastname) != "") { $tmp_addr->lastname = $lastname; } if (trim($address1) != "") { $tmp_addr->address1 = $address1; } // kvoli virtual produktom, ked online country bola skryta a teda id_country bolo prazdne if (trim($id_country) == "") { $id_country = (int) Configuration::get('PS_COUNTRY_DEFAULT'); } if (trim($id_country) != "") { $tmp_addr->id_country = $id_country; if (trim($id_state) != "") { $tmp_addr->id_state = $id_state; } else { $tmp_addr->id_state = 0; } // Reset VAT number when address is non-EU (otherwise, taxes won't be added when VAT address changes to non-VAT!) if (Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(dirname(__FILE__) . '/../../modules/vatnumber/vatnumber.php') && !VatNumber::isApplicable($id_country)) { $tmp_addr->vat_number = ""; } if ($cart_id_address > 0) { $tmp_addr->update(); } else { $tmp_addr->add(); // $opckt_helper->addAddressIdAndCartId($tmp_addr->id, $this->context->cookie->id_cart); } return $tmp_addr->id; } else { return 0; } }
public function update_cart_by_junglee_xml($order_id, $orderdetail) { $prefix = _DB_PREFIX_; $tablename = $prefix . 'orders'; $total_amount = 0; $total_principal = 0; $shipping_amount = 0; $total_promo = 0; $ClientRequestId = 0; $AmazonOrderID = (string) $orderdetail->OrderReport->AmazonOrderID; foreach ($orderdetail->OrderReport->Item as $item) { $SKU = (string) $item->SKU; $Title = (string) $item->Title; $Quantity = (int) $item->Quantity; $Principal_Promotions = 0; $Shipping_Promotions = 0; foreach ($item->ItemPrice->Component as $amount_type) { $item_charge_type = (string) $amount_type->Type; if ($item_charge_type == 'Principal') { $Principal = abs((double) $amount_type->Amount); } if ($item_charge_type == 'Shipping') { $Shipping = abs((double) $amount_type->Amount); } if ($item_charge_type == 'Tax') { $Tax = abs((double) $amount_type->Amount); } if ($item_charge_type == 'ShippingTax') { $ShippingTax = abs((double) $amount_type->Amount); } } if (!empty($item->Promotion)) { foreach ($item->Promotion as $promotions) { foreach ($promotions->Component as $promotion_amount_type) { $promotion_type = (string) $promotion_amount_type->Type; if ($promotion_type == 'Shipping') { $Shipping_Promotions += abs((double) $promotion_amount_type->Amount); } if ($promotion_type == 'Principal') { $Principal_Promotions += abs((double) $promotion_amount_type->Amount); } } } } $total_principal += $Principal; $total_amount += $Principal - $Principal_Promotions + ($Shipping - $Shipping_Promotions); $shipping_amount += $Shipping + $Shipping_Promotions; $total_promo += $Principal_Promotions + $Shipping_Promotions; foreach ($item->CustomizationInfo as $info) { $info_type = (string) $info->Type; if ($info_type == 'url') { $info_array = explode(',', $info->Data); $customerId_array = explode('=', $info_array[0]); $ClientRequestId = $customerId_array[1]; } } } $ShippingServiceLevel = (string) $orderdetail->OrderReport->FulfillmentData->FulfillmentServiceLevel; $sql = 'UPDATE `' . $prefix . 'pwa_orders` set `shipping_service` = "' . $ShippingServiceLevel . '" , `order_type` = "junglee" where `prestashop_order_id` = "' . $order_id . '" '; Db::getInstance()->Execute($sql); $cust_name = (string) $orderdetail->OrderReport->BillingData->BuyerName; $name_arr = explode(' ', $cust_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 = $cust_name; $lastname = ' '; } $email = (string) $orderdetail->OrderReport->BillingData->BuyerEmailAddress; $sql = 'SELECT * from `' . $prefix . 'customer` where email = "' . $email . '" '; $results = Db::getInstance()->ExecuteS($sql); if (empty($results)) { $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) $orderdetail->OrderReport->FulfillmentData->Address->CountryCode); if ($id_country == 0 || $id_country == '') { $id_country = 110; } $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) $orderdetail->OrderReport->FulfillmentData->Address->AddressFieldOne; $address->address2 = (string) $orderdetail->OrderReport->FulfillmentData->Address->AddressFieldTwo; $address->postcode = (string) $orderdetail->OrderReport->FulfillmentData->Address->PostalCode; $address->phone_mobile = (string) $orderdetail->OrderReport->FulfillmentData->Address->PhoneNumber; $address->city = (string) $orderdetail->OrderReport->FulfillmentData->Address->City . ' ' . (string) $orderdetail->OrderReport->FulfillmentData->Address->StateOrRegion; $address->active = 1; $address->add(); $address_id = $address->id; $id_order_state = 2; $reference = Order::generateReference(); $order = new Order(); $order->id = $order_id; $order->id_customer = (int) $customer_id; $order->id_address_invoice = (int) $address_id; $carrier = null; $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 = 'SELECT id_currency from `' . $prefix . 'currency` where `active` = 1 and `deleted` = 0 and `iso_code` = "INR" limit 0,1'; $result = Db::getInstance()->ExecuteS($sql); $currency_id = $result[0]['id_currency']; $sql = 'UPDATE `' . $tablename . '` set `id_customer` = ' . (int) $customer_id . ', `id_carrier` = ' . $id_carrier . ', `id_address_invoice` = ' . (int) $address_id . ', `id_address_delivery` = ' . (int) $address_id . ', `id_currency` = ' . $currency_id . ', `reference` = "' . $reference . '", `secure_key` = "' . md5(uniqid()) . '", `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 . ', `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').', Db::getInstance()->Execute($sql); $i = 0; foreach ($orderdetail->OrderReport->Item as $item) { $id_product = (string) $item->SKU; $product = new Product((int) $product_id); $SKU = $product->reference; $AmazonOrderItemCode = (string) $item->AmazonOrderItemCode; $Title = (string) $item->Title; $Quantity = (int) $item->Quantity; foreach ($item->ItemPrice->Component as $amount_type) { $item_charge_type = (string) $amount_type->Type; if ($item_charge_type == 'Principal') { $Amount = (double) $amount_type->Amount; } } $Amount = $Amount / $Quantity; $Amount = round($Amount, 3); $acknowledge_arr['items'][$i]['AmazonOrderItemCode'] = $AmazonOrderItemCode; $acknowledge_arr['items'][$i]['product_id'] = $id_product; $i++; $sql = 'INSERT into `' . $prefix . 'order_detail` set `id_order` = ' . $order_id . ', `product_id` = ' . $id_product . ', `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` = ' . $Amount * $Quantity . ', `unit_price_tax_incl` = ' . $Amount . ', `unit_price_tax_excl` = ' . $Amount . ', `original_product_price` = ' . $Amount . ' '; Db::getInstance()->Execute($sql); $sql = 'UPDATE `' . $prefix . 'stock_available` set `quantity` = `quantity` - ' . $Quantity . ' where `id_product` = ' . $id_product . ' and `id_product_attribute` = 0 '; Db::getInstance()->Execute($sql); /*$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` = ' . $id_product . ' '; Db::getInstance()->Execute($sql); } // 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(); } // Acknowledge the order in seller central using MWS FEED API $acknowledge_arr['MerchantOrderID'] = (int) $order->id; $obj = new Pwapresta(); $obj->pwa_acknowledge_feed($acknowledge_arr); $history = new OrderHistory(); $history->id_order = $order->id; $history->changeIdOrderState((int) $id_order_state, $order->id, true); $history->addWithemail(true, array()); }
public function isSameAddress($idAddress, $idCart, $idCustomer) { $sql = Db::getInstance()->getRow('SELECT * FROM ' . _DB_PREFIX_ . 'country WHERE iso_code = "BE"'); $isoBel = $sql['id_country']; $sql = Db::getInstance()->getRow('SELECT * FROM ' . _DB_PREFIX_ . 'country WHERE iso_code = "FR"'); $isoFr = $sql['id_country']; $return = Db::getInstance()->GetRow('SELECT * FROM ' . _DB_PREFIX_ . 'socolissimo_delivery_info WHERE id_cart =\'' . intval($idCart) . '\' AND id_customer =\'' . intval($idCustomer) . '\''); $psAddress = new Address(intval($idAddress)); $newAddress = new Address(); // in 1.7.0 country is mandatory if ($return['cecountry'] == "FR") { $isoCode = $isoFr; $nameCountry = "france"; } if ($return['cecountry'] == "BE") { $nameCountry = "belgique"; $isoCode = $isoBel; } if ($this->upper($psAddress->lastname) != $this->upper($return['prname']) || $this->upper($psAddress->firstname) != $this->upper($return['prfirstname']) || $this->upper($psAddress->address1) != $this->upper($return['pradress3']) || $this->upper($psAddress->address2) != $this->upper($return['pradress2']) || $this->upper($psAddress->postcode) != $this->upper($return['przipcode']) || $this->upper($psAddress->city) != $this->upper($return['prtown']) || str_replace(array(' ', '.', '-', ',', ';', '+', '/', '\\', '+', '(', ')'), '', $psAddress->phone_mobile) != $return['cephonenumber']) { $newAddress->id_customer = intval($idCustomer); $newAddress->lastname = substr($return['prname'], 0, 32); $newAddress->firstname = substr($return['prfirstname'], 0, 32); $newAddress->postcode = $return['przipcode']; $newAddress->city = $return['prtown']; $newAddress->id_country = $isoCode; $newAddress->alias = 'So Colissimo - ' . date('d-m-Y'); if (!in_array($return['delivery_mode'], array('DOM', 'RDV'))) { $newAddress->active = 1; $newAddress->deleted = 1; $newAddress->address1 = $return['pradress1']; $newAddress->add(); } else { $newAddress->address1 = $return['pradress3']; isset($return['pradress2']) ? $newAddress->address2 = $return['pradress2'] : ($newAddress->address2 = ''); isset($return['pradress1']) ? $newAddress->other .= $return['pradress1'] : ($newAddress->other = ''); isset($return['pradress4']) ? $newAddress->other .= ' | ' . $return['pradress4'] : ($newAddress->other = ''); $newAddress->postcode = $return['przipcode']; $newAddress->city = $return['prtown']; $newAddress->id_country = $isoCode; $newAddress->alias = 'So Colissimo - ' . date('d-m-Y'); $newAddress->add(); } return intval($newAddress->id); } else { return intval($psAddress->id); } }
public function validation() { if (!$this->active || !Configuration::get('GOINTERPAY_STORE') || !Configuration::get('GOINTERPAY_SECRET')) { return false; } if (!isset($_GET['orderId'])) { return false; } include_once _PS_MODULE_DIR_ . 'gointerpay/Rest.php'; $rest = new Rest(Configuration::get('GOINTERPAY_STORE'), Configuration::get('GOINTERPAY_SECRET')); $result = $rest->orderDetail(Tools::safeOutput(Tools::getValue('orderId'))); $cart = new Cart((int) $result['cartId']); $original_total = Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2); /* Check the currency code */ $id_currency_new = (int) Currency::getIdByIsoCode($result['foreignCurrencyCode']); if ($id_currency_new) { $cart->id_currency = (int) $id_currency_new; $cart->save(); } else { die('Sorry, we were not able to accept orders in the following currency: ' . Tools::safeOutput($result['foreignCurrencyCode'])); } $name = explode(" ", $result['delivery_address']['name']); $lastname = " - "; if (isset($name[1])) { $lastname = $name[1]; } /* Update the delivery and billing address */ $delivery_address = new Address((int) $cart->id_address_delivery); $delivery_address->firstname = $name[0]; $delivery_address->lastname = $lastname; $delivery_address->company = $result['delivery_address']['company']; $delivery_address->phone = $result['delivery_address']['phone']; $delivery_address->phone_mobile = $result['delivery_address']['altPhone']; $delivery_address->id_country = (int) Country::getByIso($result['delivery_address']['countryCode']); $delivery_address->id_state = (int) State::getIdByIso($result['delivery_address']['state'], (int) $delivery_address->id_country); $delivery_address->address1 = $result['delivery_address']['address1']; $delivery_address->address2 = $result['delivery_address']['address2']; $delivery_address->city = $result['delivery_address']['city']; $delivery_address->postcode = $result['delivery_address']['zip']; $delivery_address->save(); /* If no billing address specified, use the delivery address */ if ($result['invoice_address']['address1'] != '' || $result['invoice_address']['city'] != '') { $invoice_name = explode(" ", $result['invoice_address']['name']); $invoice_lastname = " - "; if (isset($invoice_name[1])) { $invoice_lastname = $invoice_name[1]; } $invoice_address = new Address((int) $cart->id_address_invoice); $invoice_address->firstname = $invoice_name[0]; $invoice_address->lastname = $invoice_lastname; $invoice_address->company = $result['invoice_address']['company']; $invoice_address->phone = $result['invoice_address']['phone']; $invoice_address->phone_mobile = $result['invoice_address']['altPhone']; $invoice_address->id_country = (int) Country::getByIso($result['invoice_address']['countryCode']); $invoice_address->id_state = (int) State::getIdByIso($result['invoice_address']['state'], (int) $invoice_address->id_country); $invoice_address->address1 = $result['invoice_address']['address1']; $invoice_address->address2 = $result['invoice_address']['address2']; $invoice_address->city = $result['invoice_address']['city']; $invoice_address->postcode = $result['invoice_address']['zip']; if ($cart->id_address_delivery == $cart->id_address_invoice) { $invoice_address->add(); $cart->id_address_invoice = (int) $invoice_address->id; $cart->save(); } else { $invoice_address->save(); } } /* Store the Order ID and Shipping cost */ Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'gointerpay_order_id` (`id_cart`, `orderId`, `shipping`, `shipping_orig`, `taxes`, `total`, `products`, `status`) VALUES (\'' . (int) $cart->id . '\', \'' . pSQL(Tools::getValue('orderId')) . '\', \'' . (double) $result['shippingTotal'] . '\', \'' . (double) $result['shippingTotalForeign'] . '\', \'' . (double) $result['quotedDutyTaxes'] . '\', \'' . (double) $result['grandTotal'] . '\', \'' . (double) $result['itemsTotal'] . '\', \'Init\')'); /* Add the duties and taxes */ Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'specific_price` WHERE id_customer = ' . (int) $cart->id_customer . ' AND id_product = ' . (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES')); $specific_price = new SpecificPrice(); $specific_price->id_product = (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES'); $specific_price->id_shop = 0; $specific_price->id_country = 0; $specific_price->id_group = 0; $specific_price->id_cart = (int) $cart->id; $specific_price->id_product_attribute = 0; $specific_price->id_currency = $cart->id_currency; $specific_price->id_customer = $cart->id_customer; $specific_price->price = (double) $result['quotedDutyTaxesForeign']; $specific_price->from_quantity = 1; $specific_price->reduction = 0; $specific_price->reduction_type = 'percentage'; $specific_price->from = date('Y-m-d H:i:s'); $specific_price->to = strftime('%Y-%m-%d %H:%M:%S', time() + 10); $specific_price->add(); if (Validate::isLoadedObject($specific_price)) { $cart->updateQty(1, (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES')); } $result['status'] = 'Pending'; $total = Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2); $message = ' Total paid on Interpay: ' . (double) $result['grandTotalForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . ' Duties and taxes on Interpay: ' . (double) $result['quotedDutyTaxesForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . ' Shipping on Interpay: ' . (double) $result['shippingTotalForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . ' Currency: ' . $result['foreignCurrencyCode']; if ($result['status'] == 'Pending') { $this->context->cart->id = (int) $result['cartId']; Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'gointerpay_order_id` SET `status` = \'Pending\' WHERE `id_cart` = ' . (int) $cart->id); $order_status = Configuration::get('GOINTERPAY_PAYMENT_PENDING'); $price_difference = abs($original_total - ((double) $result['grandTotalForeign'] - (double) $result['quotedDutyTaxesForeign'] - (double) $result['shippingTotalForeign'])) * 100 / $original_total; if ($price_difference > 1) { /* Uncomment this line if you would like to decline orders with a too high price difference */ // $order_status = Configuration::get('PS_OS_ERROR'); /*$message .= ' Warning: The difference between the price paid and the price to pay was higher than 1% ('.number_format($price_difference, 2, '.', '').'%) However, the payment was processed by Interpay, you should get in touch with the customer and Interpay to resolve that matter.';*/ } $this->validateOrder((int) $cart->id, (int) $order_status, $total, $this->displayName, $message, array(), NULL, false, $cart->secure_key); Tools::redirectLink(__PS_BASE_URI__ . 'history.php'); } else { die('Order was not found or cannot be validated at this time, please contact us.'); } }
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('-45 minutes')) . 'T' . date('H:i:s', strtotime('-45 minutes')) . '.000Z') { $ebay = new eBayRequest(); $orderList = $ebay->getOrders(Configuration::get('EBAY_ORDER_LAST_UPDATE'), $dateNew); if ($orderList) { foreach ($orderList as $order) { if ($order['status'] == 'Complete') { $result = Db::getInstance()->getRow('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')); $id_customer = isset($result['id_customer']) ? $result['id_customer'] : 0; // 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; } $address = new Address(); $address->id_customer = (int) $id_customer; $address->id_country = (int) Country::getByIso($order['country_iso_code']); $address->alias = 'eBay ' . date('Y-m-d H:i:s'); $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; $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']) && !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) { $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->add(); foreach ($order['product_list'] as $product) { $cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) ? $product['id_product_attribute'] : NULL); } $cartAdd->update(); // 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), _PS_OS_PAYMENT_, floatval($cartAdd->getOrderTotal(true, 3)), 'Paypal eBay', NULL, array(), intval($cartAdd->id_currency)); $id_order = $paiement->currentOrder; // 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']); } } } } } Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', $dateNew); } }
} $new_address = new Address(); $new_address->alias = 'SHIP2MYID-' . Tools::passwdGen(6); $new_address->lastname = $lastname; $new_address->firstname = $firstname; $new_address->address1 = 'waiting...'; $new_address->postcode = $postcode; $new_address->city = $city; $new_address->phone = $telephone_no; $new_address->id_country = $id_country; $new_address->id_state = $id_state; $new_address->id_customer = (int) $current_cart->id_customer; $new_address->id_manufacturer = 0; $new_address->id_supplier = 0; $new_address->id_warehouse = 0; if (!$new_address->add()) { die('<script language="javascript" type="text/javascript">top.location.href = "' . $context->link->getPageLink('order') . '?step=1" ;</script>'); } /* * Save shipto data in shipto cart object. */ $shipto_cart = ShiptomyidCart::getByIdCart($current_cart->id); if (!$shipto_cart) { $shipto_cart = new ShiptomyidCart(); $shipto_cart->id_cart = $current_cart->id; } $shipto_cart->receiver_email = $email; $shipto_cart->receiver_lastname = $lastname; $shipto_cart->receiver_firstname = $firstname; $shipto_cart->receiver_city = $city; $shipto_cart->receiver_postcode = $postcode;
function cronOrdersSync() { $orders = $this->client->getOrders(array(7)); foreach ($orders as $order) { $channelOrderId = $order->getId(); $billingAddress = $order->getBillingAddress(); $shippingAddress = $order->getShippingAddress(); if (empty($billingAddress)) { continue; } $id_customer = $this->createPrestashopCustomer($billingAddress, $order->getEmail()); $lines = $order->getLines(); $AddressObject = new Address(); $AddressObject->id_customer = $id_customer; $AddressObject->firstname = $billingAddress->getfirstName(); $AddressObject->lastname = $billingAddress->getlastName(); $AddressObject->address1 = " " . $billingAddress->getHouseNr(); $AddressObject->address1 .= " " . $billingAddress->getHouseNrAddition(); $AddressObject->address1 .= " " . $billingAddress->getStreetName(); $AddressObject->address1 .= " " . $billingAddress->getZipCode(); $AddressObject->address1 .= " " . $billingAddress->getCity(); $AddressObject->city = $billingAddress->getCity(); $AddressObject->id_customer = $id_customer; $AddressObject->id_country = Country::getByIso($billingAddress->getCountryIso()); $AddressObject->alias = $billingAddress->getcompanyName() != "" ? "Company" : "Home"; $AddressObject->add(); $CarrierObject = new Carrier(); $CarrierObject->delay[1] = "2-4"; $CarrierObject->active = 1; $CarrierObject->name = "ChannelEngine Order"; $CarrierObject->add(); $id_carrier = $CarrierObject->id; $currency_object = new Currency(); $default_currency_object = $currency_object->getDefaultCurrency(); $id_currency = $default_currency_object->id; $id_address = $AddressObject->id; // Create Cart Object $cart = new Cart(); $cart->id_customer = (int) $id_customer; $cart->id_address_delivery = $id_address; $cart->id_address_invoice = $id_address; $cart->id_lang = 1; $cart->id_currency = (int) $id_address; $cart->id_carrier = $id_carrier; $cart->recyclable = 0; $cart->id_shop_group = 1; $cart->gift = 0; $cart->add(); if (!empty($lines)) { foreach ($lines as $item) { $quantity = $item->getQuantity(); if (strpos($item->getmerchantProductNo(), '-') !== false) { $getMerchantProductNo = explode("-", $item->getMerchantProductNo()); $cart->updateQty($quantity, $getMerchantProductNo[0], $getMerchantProductNo[1]); } else { $cart->updateQty($quantity, $item->getmerchantProductNo()); } } } $cart->update(); $order_object = new Order(); $order_object->id_address_delivery = $id_address; $order_object->id_address_invoice = $id_address; $order_object->id_cart = $cart->id; $order_object->id_currency = $id_currency; $order_object->id_customer = $id_customer; $order_object->id_carrier = $id_carrier; $order_object->payment = "ChannelEngine Order"; $order_object->module = "1"; $order_object->valid = 1; $order_object->total_paid_tax_excl = $order->getTotalInclVat(); $order_object->total_discounts_tax_incl = 0; $order_object->total_paid = $order->getTotalInclVat(); $order_object->total_paid_real = $order->getTotalInclVat(); $order_object->total_products = $order->getSubTotalInclVat() - $order->getSubTotalVat(); $order_object->total_products_wt = $order->getSubTotalInclVat(); $order_object->total_paid_tax_incl = $order->getSubTotalInclVat(); $order_object->conversion_rate = 1; $order_object->id_shop = 1; $order_object->id_lang = 1; $order_object->id_shop_group = 1; $order_object->secure_key = md5(uniqid(rand(), true)); $order_id = $order_object->add(); // Insert new Order detail list using cart for the current order $order_detail = new OrderDetail(); $orderClass = new Order(); $order_detail->createList($order_object, $cart, 1, $cart->getProducts(), 1); $order_detail_list[] = $order_detail; // Adding an entry in order_carrier table if (!is_null($CarrierObject)) { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order_object->id; $order_carrier->id_carrier = (int) $id_carrier; $order_carrier->weight = (double) $order_object->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (double) $order_object->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = (double) $order_object->total_shipping_tax_incl; $order_carrier->add(); } foreach ($lines as $item) { $getMerchantProductNo = explode("-", $item->getMerchantProductNo()); $query = "UPDATE `" . _DB_PREFIX_ . "order_detail` SET id_channelengine_product='" . $item->getId() . "'" . "WHERE product_id ='" . $getMerchantProductNo[0] . "' AND product_attribute_id = '" . $getMerchantProductNo[1] . "' AND id_order = ' " . $order_object->id . "' "; Db::getInstance()->Execute($query); } Db::getInstance()->update('orders', array('id_channelengine_order' => $channelOrderId), 'id_order = ' . $order_object->id); } }
public function isSameAddress($idAddress, $idCart, $idCustomer) { $return = Db::getInstance()->getRow('SELECT * FROM ' . _DB_PREFIX_ . 'socolissimo_delivery_info WHERE id_cart =\'' . (int) $idCart . '\' AND id_customer =\'' . (int) $idCustomer . '\''); $psAddress = new Address((int) $idAddress); $newAddress = new Address(); if ($this->upper($psAddress->lastname) != $this->upper($return['prname']) || $this->upper($psAddress->firstname) != $this->upper($return['prfirstname']) || $this->upper($psAddress->address1) != $this->upper($return['pradress3']) || $this->upper($psAddress->address2) != $this->upper($return['pradress2']) || $this->upper($psAddress->postcode) != $this->upper($return['przipcode']) || $this->upper($psAddress->city) != $this->upper($return['prtown']) || str_replace(array(' ', '.', '-', ',', ';', '+', '/', '\\', '+', '(', ')'), '', $psAddress->phone_mobile) != $return['cephonenumber']) { $newAddress->id_customer = (int) $idCustomer; $newAddress->lastname = substr($return['prname'], 0, 32); $newAddress->firstname = substr($return['prfirstname'], 0, 32); $newAddress->postcode = $return['przipcode']; $newAddress->city = $return['prtown']; $newAddress->id_country = Country::getIdByName(null, 'france'); $newAddress->alias = 'So Colissimo - ' . date('d-m-Y'); if (!in_array($return['delivery_mode'], array('DOM', 'RDV'))) { $newAddress->active = 1; $newAddress->deleted = 1; $newAddress->address1 = $return['pradress1']; $newAddress->add(); } else { $newAddress->address1 = $return['pradress3']; isset($return['pradress2']) ? $newAddress->address2 = $return['pradress2'] : ($newAddress->address2 = ''); isset($return['pradress1']) ? $newAddress->other .= $return['pradress1'] : ($newAddress->other = ''); isset($return['pradress4']) ? $newAddress->other .= ' | ' . $return['pradress4'] : ($newAddress->other = ''); $newAddress->postcode = $return['przipcode']; $newAddress->city = $return['prtown']; $newAddress->id_country = Country::getIdByName(null, 'france'); $newAddress->alias = 'So Colissimo - ' . date('d-m-Y'); $newAddress->add(); } return (int) $newAddress->id; } else { return (int) $psAddress->id; } }
private function _getAddress($addressNode, $id_customer, $type) { //alias is limited $type = Tools::substr($type, 0, 32); $id_address = (int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $id_customer . ' AND `alias` = \'' . pSQL($type) . '\''); if ($id_address) { $address = new Address((int) $id_address); } else { $address = new Address(); } $customer = new Customer((int) $id_customer); $street1 = ''; $street2 = ''; $line2 = false; $streets = Explode(' ', (string) $addressNode->Street); foreach ($streets as $street) { if (Tools::strlen($street1) + Tools::strlen($street) + 1 < 32 && !$line2) { $street1 .= $street . ' '; } else { $line2 = true; $street2 .= $street . ' '; } } $lastname = (string) $addressNode->LastName; $firstname = (string) $addressNode->FirstName; $address->id_customer = (int) $id_customer; $address->id_country = (int) Country::getByIso(trim($addressNode->Country)); $address->alias = pSQL($type); $address->lastname = !empty($lastname) ? pSQL($lastname) : $customer->lastname; $address->firstname = !empty($firstname) ? pSQL($firstname) : $customer->firstname; $address->address1 = pSQL($street1); $address->address2 = pSQL($street2); $address->company = pSQL($addressNode->Company); $address->postcode = pSQL($addressNode->PostalCode); $address->city = pSQL($addressNode->Town); $address->phone = Tools::substr(pSQL($addressNode->Phone), 0, 16); $address->phone_mobile = Tools::substr(pSQL($addressNode->PhoneMobile), 0, 16); if ($id_address) { $address->update(); } else { $address->add(); } return $address->id; }
/** * Add addresses * @param $order_id * @param $order_infos * @param $type * @param $id_customer * @return mixed */ private function addAddresseInBDD($order_id, $neteven_address, $type, $id_customer) { $id_country = $this->getValue('id_country_default'); if (!($id_country = Country::getIdByName(2, $neteven_address->Country))) { Toolbox::addLogLine(self::getL('Problem with id_country on address') . ' ' . $type . ' ' . self::getL('NetEven Order Id') . ' ' . $order_id); } $country = Db::getInstance()->getRow(' SELECT c.`id_country` FROM `' . _DB_PREFIX_ . 'country` c INNER JOIN `' . _DB_PREFIX_ . 'country_lang` cl ON (c.`id_country` = cl.`id_country`) WHERE LOWER(c.`iso_code`) = "' . pSQL(strtolower($neteven_address->Country)) . '" OR LOWER(cl.`name`) = "' . pSQL(strtolower($neteven_address->Country)) . '" GROUP BY c.`id_country` '); if (!empty($country['id_country'])) { $id_country = $country['id_country']; } if ($id_address = Toolbox::existAddress($neteven_address, $id_country, $id_customer)) { Toolbox::addLogLine(self::getL('Get existing address for NetEven Order Id') . ' ' . $order_id); } else { Toolbox::addLogLine(self::getL('Creation of address of NetEven order Id') . ' ' . $order_id); $date_now = date('Y-m-d H:i:s'); $new_address = new Address(); $new_address->alias = 'Address'; $new_address->lastname = !empty($neteven_address->LastName) ? substr(Toolbox::stringFilter($neteven_address->LastName), 0, 32) : ' '; $new_address->firstname = !empty($neteven_address->FirstName) ? substr(Toolbox::stringFilter($neteven_address->FirstName), 0, 32) : ' '; $new_address->address1 = !empty($neteven_address->Address1) ? Toolbox::stringWithNumericFilter($neteven_address->Address1) : ' '; $new_address->address2 = Toolbox::stringWithNumericFilter($neteven_address->Address2); $new_address->postcode = Toolbox::numericFilter($neteven_address->PostalCode); $new_address->city = !empty($neteven_address->CityName) ? Toolbox::stringFilter($neteven_address->CityName) : ' '; $new_address->phone = substr(Toolbox::numericFilter($neteven_address->Phone), 0, 16); $new_address->phone_mobile = substr(Toolbox::numericFilter($neteven_address->Mobile), 0, 16); $new_address->id_country = $id_country; $new_address->id_customer = $id_customer; $new_address->date_add = $date_now; $new_address->date_upd = $date_now; if (!empty($neteven_address->Company)) { $new_address->company = $neteven_address->Company; } if (!$new_address->add()) { Toolbox::addLogLine(self::getL('Failed for creation of address of NetEven order Id') . ' ' . $order_id); } else { $id_address = $new_address->id; } } return $id_address; }
} // Create address if (is_array($address) && isset($address['id_address'])) { $address = new Address($address['id_address']); } if ((!$address || !$address->id) && $customer->id) { $address = new Address(); $address->id_country = Country::getByIso($ppec->result['COUNTRYCODE']); $address->alias = 'Paypal_Address'; $address->lastname = $customer->lastname; $address->firstname = $customer->firstname; $address->address1 = $ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET']; $address->city = $ppec->result['PAYMENTREQUEST_0_SHIPTOCITY']; $address->postcode = $ppec->result['SHIPTOZIP']; $address->id_customer = $customer->id; $address->add(); } if ($customer->id && !$address->id) { $ppec->logs[] = $ppec->l('Cannot create Address'); } // Create Order if ($address->id && $customer->id) { $ppec->getContext()->cart->id_customer = $customer->id; $ppec->getContext()->cart->id_guest = $ppec->getContext()->cookie->id_guest; if (!$ppec->getContext()->cart->update()) { $ppec->logs[] = $ppec->l('Cannot update existing cart'); } else { $ppec->redirectToCheckout($customer, $ppec->type != 'payment_cart'); } } }
public function preProcess() { parent::preProcess(); if (self::$cookie->isLogged() and !Tools::isSubmit('ajax')) { Tools::redirect('my-account.php'); } if (Tools::getValue('create_account')) { $create_account = 1; self::$smarty->assign('email_create', 1); } if (Tools::isSubmit('SubmitCreate')) { if (!Validate::isEmail($email = Tools::getValue('email_create')) or empty($email)) { $this->errors[] = Tools::displayError('Invalid e-mail address'); } elseif (Customer::customerExists($email)) { $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.'); $_POST['email'] = $_POST['email_create']; unset($_POST['email_create']); } else { $create_account = 1; self::$smarty->assign('email_create', Tools::safeOutput($email)); $_POST['email'] = $email; } } if (Tools::isSubmit('submitAccount') or Tools::isSubmit('submitGuestAccount')) { $create_account = 1; if (Tools::isSubmit('submitAccount')) { self::$smarty->assign('email_create', 1); } /* New Guest customer */ if (!Tools::getValue('is_new_customer', 1) and !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) { $this->errors[] = Tools::displayError('You cannot create a guest account.'); } if (!Tools::getValue('is_new_customer', 1)) { $_POST['passwd'] = md5(time() . _COOKIE_KEY_); } if (isset($_POST['guest_email']) and $_POST['guest_email']) { $_POST['email'] = $_POST['guest_email']; } /* Preparing customer */ $customer = new Customer(); $lastnameAddress = $_POST['lastname']; $firstnameAddress = $_POST['firstname']; $_POST['lastname'] = $_POST['customer_lastname']; $_POST['firstname'] = $_POST['customer_firstname']; if (!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) { $this->errors[] = Tools::displayError('You must register at least one phone number'); } if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) and !(Tools::getValue('months') == '' and Tools::getValue('days') == '' and Tools::getValue('years') == '')) { $this->errors[] = Tools::displayError('Invalid date of birth'); } $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days']; $this->errors = array_unique(array_merge($this->errors, $customer->validateControler())); /* Preparing address */ $address = new Address(); $_POST['lastname'] = $lastnameAddress; $_POST['firstname'] = $firstnameAddress; $address->id_customer = 1; $this->errors = array_unique(array_merge($this->errors, $address->validateControler())); /* US customer: normalize the address */ if ($address->id_country == Country::getByIso('US')) { include_once _PS_TAASC_PATH_ . 'AddressStandardizationSolution.php'; $normalize = new AddressStandardizationSolution(); $address->address1 = $normalize->AddressLineStandardization($address->address1); $address->address2 = $normalize->AddressLineStandardization($address->address2); } $zip_code_format = Country::getZipCodeFormat((int) Tools::getValue('id_country')); if (Country::getNeedZipCode((int) Tools::getValue('id_country'))) { if ($postcode = Tools::getValue('postcode') and $zip_code_format) { $zip_regexp = '/^' . $zip_code_format . '$/ui'; $zip_regexp = str_replace(' ', '( |)', $zip_regexp); $zip_regexp = str_replace('-', '(-|)', $zip_regexp); $zip_regexp = str_replace('N', '[0-9]', $zip_regexp); $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp); $zip_regexp = str_replace('C', Country::getIsoById((int) Tools::getValue('id_country')), $zip_regexp); if (!preg_match($zip_regexp, $postcode)) { $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', Country::getIsoById((int) Tools::getValue('id_country')), str_replace('N', '0', str_replace('L', 'A', $zip_code_format))); } } elseif ($zip_code_format) { $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is required.'); } elseif ($postcode and !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) { $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.'); } } if (Country::isNeedDniByCountryId($address->id_country) and (!Tools::getValue('dni') or !Validate::isDniLite(Tools::getValue('dni')))) { $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.'); } elseif (!Country::isNeedDniByCountryId($address->id_country)) { $address->dni = NULL; } if (!sizeof($this->errors)) { if (Customer::customerExists(Tools::getValue('email'))) { $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.'); } if (Tools::isSubmit('newsletter')) { $customer->ip_registration_newsletter = pSQL(Tools::getRemoteAddr()); $customer->newsletter_date_add = pSQL(date('Y-m-d H:i:s')); } if (!sizeof($this->errors)) { if (!($country = new Country($address->id_country, Configuration::get('PS_LANG_DEFAULT'))) or !Validate::isLoadedObject($country)) { die(Tools::displayError()); } if ((int) $country->contains_states and !(int) $address->id_state) { $this->errors[] = Tools::displayError('This country requires a state selection.'); } else { $customer->active = 1; /* New Guest customer */ if (Tools::isSubmit('is_new_customer')) { $customer->is_guest = !Tools::getValue('is_new_customer', 1); } else { $customer->is_guest = 0; } if (!$customer->add()) { $this->errors[] = Tools::displayError('An error occurred while creating your account.'); } else { $address->id_customer = (int) $customer->id; if (!$address->add()) { $this->errors[] = Tools::displayError('An error occurred while creating your address.'); } else { if (!$customer->is_guest) { if (!Mail::Send((int) self::$cookie->id_lang, 'account', Mail::l('Welcome!'), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd')), $customer->email, $customer->firstname . ' ' . $customer->lastname)) { $this->errors[] = Tools::displayError('Cannot send email'); } } self::$smarty->assign('confirmation', 1); self::$cookie->id_customer = (int) $customer->id; self::$cookie->customer_lastname = $customer->lastname; self::$cookie->customer_firstname = $customer->firstname; self::$cookie->passwd = $customer->passwd; self::$cookie->logged = 1; self::$cookie->email = $customer->email; self::$cookie->is_guest = !Tools::getValue('is_new_customer', 1); /* Update cart address */ self::$cart->secure_key = $customer->secure_key; self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id); self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id); self::$cart->update(); Module::hookExec('createAccount', array('_POST' => $_POST, 'newCustomer' => $customer)); if (Tools::isSubmit('ajax')) { $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => true, 'id_customer' => (int) self::$cookie->id_customer, 'id_address_delivery' => self::$cart->id_address_delivery, 'id_address_invoice' => self::$cart->id_address_invoice, 'token' => Tools::getToken(false)); die(Tools::jsonEncode($return)); } if ($back = Tools::getValue('back')) { Tools::redirect($back); } Tools::redirect('my-account.php'); } } } } } if (sizeof($this->errors)) { if (!Tools::getValue('is_new_customer')) { unset($_POST['passwd']); } if (Tools::isSubmit('ajax')) { $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => false, 'id_customer' => 0); die(Tools::jsonEncode($return)); } } } if (Tools::isSubmit('SubmitLogin')) { Module::hookExec('beforeAuthentication'); $passwd = trim(Tools::getValue('passwd')); $email = trim(Tools::getValue('email')); if (empty($email)) { $this->errors[] = Tools::displayError('E-mail address required'); } elseif (!Validate::isEmail($email)) { $this->errors[] = Tools::displayError('Invalid e-mail address'); } elseif (empty($passwd)) { $this->errors[] = Tools::displayError('Password is required'); } elseif (Tools::strlen($passwd) > 32) { $this->errors[] = Tools::displayError('Password is too long'); } elseif (!Validate::isPasswd($passwd)) { $this->errors[] = Tools::displayError('Invalid password'); } else { $customer = new Customer(); $authentication = $customer->getByEmail(trim($email), trim($passwd)); if (!$authentication or !$customer->id) { /* Handle brute force attacks */ sleep(1); $this->errors[] = Tools::displayError('Authentication failed'); } else { self::$cookie->id_compare = isset(self::$cookie->id_compare) ? self::$cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id); self::$cookie->id_customer = (int) $customer->id; self::$cookie->customer_lastname = $customer->lastname; self::$cookie->customer_firstname = $customer->firstname; self::$cookie->id_default_group = $customer->id_default_group; self::$cookie->logged = 1; self::$cookie->is_guest = $customer->isGuest(); self::$cookie->passwd = $customer->passwd; self::$cookie->email = $customer->email; if (Configuration::get('PS_CART_FOLLOWING') and (empty(self::$cookie->id_cart) or Cart::getNbProducts(self::$cookie->id_cart) == 0)) { self::$cookie->id_cart = (int) Cart::lastNoneOrderedCart((int) $customer->id); } /* Update cart address */ self::$cart->id_carrier = 0; self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id); self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id); // If a logged guest logs in as a customer, the cart secure key was already set and needs to be updated self::$cart->secure_key = $customer->secure_key; self::$cart->update(); Module::hookExec('authentication'); if (!Tools::isSubmit('ajax')) { if ($back = Tools::getValue('back')) { Tools::redirect($back); } Tools::redirect('my-account.php'); } } } if (Tools::isSubmit('ajax')) { $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false)); die(Tools::jsonEncode($return)); } } if (isset($create_account)) { /* Select the most appropriate country */ if (isset($_POST['id_country']) and is_numeric($_POST['id_country'])) { $selectedCountry = (int) $_POST['id_country']; } /* FIXME : language iso and country iso are not similar, * maybe an associative table with country an language can resolve it, * But for now it's a bug ! * @see : bug #6968 * @link:http://www.prestashop.com/bug_tracker/view/6968/ elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $array = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']); if (Validate::isLanguageIsoCode($array[0])) { $selectedCountry = Country::getByIso($array[0]); if (!$selectedCountry) $selectedCountry = (int)(Configuration::get('PS_COUNTRY_DEFAULT')); } }*/ if (!isset($selectedCountry)) { $selectedCountry = (int) Configuration::get('PS_COUNTRY_DEFAULT'); } if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) { $countries = Carrier::getDeliveredCountries((int) self::$cookie->id_lang, true, true); } else { $countries = Country::getCountries((int) self::$cookie->id_lang, true); } self::$smarty->assign(array('countries' => $countries, 'sl_country' => isset($selectedCountry) ? $selectedCountry : 0, 'vat_management' => Configuration::get('VATNUMBER_MANAGEMENT'))); /* Call a hook to display more information on form */ self::$smarty->assign(array('HOOK_CREATE_ACCOUNT_FORM' => Module::hookExec('createAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Module::hookExec('createAccountTop'))); } /* Generate years, months and days */ if (isset($_POST['years']) and is_numeric($_POST['years'])) { $selectedYears = (int) $_POST['years']; } $years = Tools::dateYears(); if (isset($_POST['months']) and is_numeric($_POST['months'])) { $selectedMonths = (int) $_POST['months']; } $months = Tools::dateMonths(); if (isset($_POST['days']) and is_numeric($_POST['days'])) { $selectedDays = (int) $_POST['days']; } $days = Tools::dateDays(); self::$smarty->assign(array('years' => $years, 'sl_year' => isset($selectedYears) ? $selectedYears : 0, 'months' => $months, 'sl_month' => isset($selectedMonths) ? $selectedMonths : 0, 'days' => $days, 'sl_day' => isset($selectedDays) ? $selectedDays : 0)); self::$smarty->assign('newsletter', (int) Module::getInstanceByName('blocknewsletter')->active); }
protected function importAddresses() { $this->truncateTables(array('address')); $handle = $this->openCsvFile('address.csv'); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, ';'); $current_line++) { $res = false; $fields = $this->filterFields('Address', $this->address_fields, $line); if (!isset($fields['id'])) { $address = new Address((int) $line[0]); $address->id = $line[0]; } else { $address = new Address((int) $fields['id']); } foreach ($fields as $key => $field) { $address->{$key} = $field; } $address->force_id = true; if (!$res) { $res = $address->add(); } } $this->closeCsvFile($handle); return true; }
public function update_cart_by_junglee_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; foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) { $product_id = (string) $item->SKU; $product = new Product((int) $product_id); $SKU = $product->reference; $Title = (string) $item->Title; $Amount = (double) $item->Price->Amount; $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_principal += $principal; $total_amount += $principal - $principal_promo + ($Shipping - $shipping_promo); $shipping_amount += $Shipping; $total_promo += $principal_promo + $shipping_promo + $other_promo; } $ShippingServiceLevel = (string) $xml->ProcessedOrder->ShippingServiceLevel; $sql = 'UPDATE `' . $prefix . 'pwa_orders` set `shipping_service` = "' . $ShippingServiceLevel . '" , `order_type` = "junglee" where `prestashop_order_id` = "' . $order_id . '" '; Db::getInstance()->Execute($sql); $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; //$id_order_state = Configuration::get('PS_OS_PREPARATION'); $id_order_state = 99; $reference = Order::generateReference(); $order = new Order(); $order->id = $order_id; $order->id_customer = (int) $customer_id; $order->id_address_invoice = (int) $address_id; $carrier = null; $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 = 'SELECT id_currency from `' . $prefix . 'currency` where `active` = 1 and `deleted` = 0 and `iso_code` = "INR" limit 0,1'; $result = Db::getInstance()->ExecuteS($sql); $currency_id = $result[0]['id_currency']; $sql = 'UPDATE `' . $tablename . '` set `id_customer` = ' . (int) $customer_id . ', `id_carrier` = ' . $id_carrier . ', `id_address_invoice` = ' . (int) $address_id . ', `id_address_delivery` = ' . (int) $address_id . ', `id_currency` = ' . $currency_id . ', `reference` = "' . $reference . '", `secure_key` = "' . md5(uniqid()) . '", `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 . ', `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').', /*`total_wrapping_tax_incl` = '.$WrappingAmount.', `total_wrapping_tax_excl` = '.$WrappingAmount.', `total_wrapping` = '.$WrappingAmount.',*/ Db::getInstance()->Execute($sql); $acknowledge_arr = array(); $i = 0; foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) { $product_id = (string) $item->SKU; $product = new Product((int) $product_id); $SKU = $product->reference; $AmazonOrderItemCode = (string) $item->AmazonOrderItemCode; $Title = (string) $item->Title; $Amount = (double) $item->Price->Amount; $acknowledge_arr['items'][$i]['AmazonOrderItemCode'] = $AmazonOrderItemCode; $acknowledge_arr['items'][$i]['product_id'] = $product_id; $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_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` = ' . $Amount * $Quantity . ', `unit_price_tax_incl` = ' . $Amount . ', `unit_price_tax_excl` = ' . $Amount . ', `original_product_price` = ' . $Amount . ' '; Db::getInstance()->Execute($sql); $sql = 'UPDATE `' . $prefix . 'stock_available` set `quantity` = `quantity` - ' . $Quantity . ' where `id_product` = ' . $product_id . ' and `id_product_attribute` = 0 '; 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(); } // 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()); $acknowledge_arr['MerchantOrderID'] = (int) $order->id; }
public function isSameAddress($id_address, $id_cart, $id_customer) { $return = Db::getInstance()->getRow('SELECT * FROM ' . _DB_PREFIX_ . 'socolissimo_delivery_info WHERE id_cart =\'' . (int) $id_cart . '\' AND id_customer =\'' . (int) $id_customer . '\''); if (!$return) { return $id_address; } $ps_address = new Address((int) $id_address); $new_address = new Address(); $sql = Db::getInstance()->getRow('SELECT c.id_country, cl.name FROM ' . _DB_PREFIX_ . 'country c LEFT JOIN ' . _DB_PREFIX_ . 'country_lang cl ON cl.id_lang = ' . (int) $this->context->language->id . ' AND cl.id_country = c.id_country WHERE iso_code = "' . pSQL($return['cecountry']) . '"'); $iso_code = $sql['id_country']; if ($this->upper($ps_address->lastname) != $this->upper($return['prname']) || $ps_address->id_country != $iso_code || $this->upper($ps_address->firstname) != $this->upper($return['prfirstname']) || $this->upper($ps_address->address1) != $this->upper($return['pradress3']) || $this->upper($ps_address->address2) != $this->upper($return['pradress2']) || $this->upper($ps_address->postcode) != $this->upper($return['przipcode']) || $this->upper($ps_address->city) != $this->upper($return['prtown']) || str_replace(array(' ', '.', '-', ',', ';', '+', '/', '\\', '+', '(', ')'), '', $ps_address->phone_mobile) != $return['cephonenumber']) { $new_address->id_customer = (int) $id_customer; $new_address->lastname = preg_replace('/\\d/', '', Tools::substr($return['prname'], 0, 32)); $new_address->firstname = preg_replace('/\\d/', '', Tools::substr($return['prfirstname'], 0, 32)); $new_address->postcode = $return['przipcode']; $new_address->city = $return['prtown']; $new_address->id_country = $iso_code; $new_address->alias = 'So Colissimo - ' . date('d-m-Y'); $new_address->phone_mobile = $return['cephonenumber']; if (!in_array($return['delivery_mode'], array('DOM', 'RDV'))) { $new_address->active = 1; $new_address->deleted = 1; $new_address->address1 = $return['pradress1']; $new_address->address2 = $return['pradress2']; $new_address->add(); } else { $new_address->address1 = $return['pradress3']; isset($return['pradress2']) ? $new_address->address2 = $return['pradress2'] : ($new_address->address2 = ''); isset($return['pradress1']) ? $new_address->other .= $return['pradress1'] : ($new_address->other = ''); isset($return['pradress4']) ? $new_address->other .= ' | ' . $return['pradress4'] : ($new_address->other = ''); $new_address->postcode = $return['przipcode']; $new_address->city = $return['prtown']; $new_address->id_country = $iso_code; $new_address->alias = 'So Colissimo - ' . date('d-m-Y'); $new_address->add(); } return (int) $new_address->id; } return (int) $ps_address->id; }
$address = new Address(); $address->id_customer = 1; $errors = array_unique(array_merge($errors, $address->validateControler())); if (!sizeof($errors)) { if (!($country = new Country($address->id_country)) or !Validate::isLoadedObject($country)) { die(Tools::displayError()); } if (intval($country->contains_states) and !intval($address->id_state)) { $errors[] = Tools::displayError('this country require a state selection'); } else { $customer->active = 1; if (!$customer->add()) { $errors[] = Tools::displayError('an error occurred while creating your account'); } else { $address->id_customer = intval($customer->id); if (!$address->add()) { $errors[] = Tools::displayError('an error occurred while creating your address'); } else { if (!Mail::Send(intval($cookie->id_lang), 'account', 'Welcome!', array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd')), $customer->email, $customer->firstname . ' ' . $customer->lastname)) { $errors[] = Tools::displayError('cannot send email'); } $smarty->assign('confirmation', 1); $cookie->id_customer = intval($customer->id); $cookie->customer_lastname = $customer->lastname; $cookie->customer_firstname = $customer->firstname; $cookie->passwd = $customer->passwd; $cookie->logged = 1; $cookie->email = $customer->email; Module::hookExec('createAccount', array('_POST' => $_POST, 'newCustomer' => $customer)); if ($back) { Tools::redirect($back);
/** * Manage address */ public function processAddress() { $customer = new Customer(); if (!Tools::getValue('email')) { return true; } if (!$customer->getByEmail(Tools::getValue('email'))) { $_POST['passwd'] = md5(time() . _COOKIE_KEY_); $this->errors += $customer->validateController(); $customer->active = 1; if (empty($this->errors) && !$customer->add()) { $this->errors[] = Tools::displayError('An error occurred while creating your account.'); } } $addresses = $customer->getAddresses($this->context->language->id); $id_address = null; foreach ($addresses as $address) { if ($address['firstname'] != $_POST['firstname']) { continue; } if ($address['lastname'] != $_POST['lastname']) { continue; } if (isset($_POST['city'])) { if ($address['city'] != $_POST['city']) { continue; } } if ($address['phone'] != $_POST['phone']) { continue; } $id_address = $address['id_address']; break; } if (!$id_address) { $address = new Address(); $address->id_customer = $customer->id; $_POST['id_country'] = 177; $_POST['alias'] = 'Address ' + count($addresses) + 1; $_POST['address1'] = 'some address'; $_POST['city'] = 'some city'; $this->errors += $address->validateController(); if (empty($this->errors) && !$address->add()) { $this->errors[] = Tools::displayError('An error occurred while creating your account.'); } else { $id_address = $address->id; $data = array(); $data['email'] = $customer->email; $data['firstname'] = $customer->firstname; $data['lastname'] = $customer->lastname; $data['ip_registration_newsletter'] = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : $_SERVER['REMOTE_ADDR']; $data['newsletter_date_add'] = date("d.m.y"); $data['phone'] = $address->phone; function charset($str) { if (!$str) { exit; } $charset = mb_detect_encoding($str, "auto"); if ($charset != "UTF-8") { $str = iconv($charset, 'utf-8', $str); } return $str; } //ключ доступа к API (из Личного Кабинета) $api_key = "58priw95sdjt7umw17ixbnkkkudtoq5u7nmfcacy"; // Список контактов $list = "4734062"; //dev-etagerca $POST = array('api_key' => $api_key, 'field_names[0]' => 'email', 'field_names[1]' => 'Name', 'field_names[2]' => 'email_request_ip', 'field_names[3]' => 'email_add_time', 'field_names[4]' => 'phone', 'field_names[5]' => 'email_list_ids'); for ($i = 0; $i < 1; $i++) { $POST['data[' . $i . '][0]'] = $data['email']; $POST['data[' . $i . '][1]'] = charset($data['firstname']) . ' ' . charset($data['lastname']); $POST['data[' . $i . '][2]'] = $data['ip_registration_newsletter']; $POST['data[' . $i . '][3]'] = $data['newsletter_date_add']; $POST['data[' . $i . '][4]'] = $data['phone']; $POST['data[' . $i . '][5]'] = $list; } $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $POST); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_URL, 'http://api.unisender.com/ru/api/importContacts?format=json'); $result = curl_exec($ch); // if ($result) { // // Раскодируем ответ API-сервера // $jsonObj = json_decode($result); // // if(null===$jsonObj) { // // Ошибка в полученном ответе // echo "Invalid JSON"; // // } // elseif(!empty($jsonObj->error)) { // // Ошибка импорта // echo("An error occured: " . $jsonObj->error . "(code: " . $jsonObj->code . ")"); // // } else { // // Новые подписчики успешно добавлены // echo("Success! Added " . $jsonObj->result->new_emails . " new e-mail addresses"); // // } // } else { // // Ошибка соединения с API-сервером // echo("API access error"); // } } } $this->context->cookie->id_customer = $customer->id; $this->context->cart->id_customer = $customer->id; $this->context->cart->id_address_delivery = $id_address; $this->context->cart->id_address_invoice = $id_address; /* if (!Tools::getValue('multi-shipping')) $this->context->cart->setNoMultishipping(); $same = Tools::isSubmit('same'); if(!Tools::getValue('id_address_invoice', false) && !$same) $same = true; if (!Customer::customerHasAddress($this->context->customer->id, (int)Tools::getValue('id_address_delivery')) || (!$same && Tools::getValue('id_address_delivery') != Tools::getValue('id_address_invoice') && !Customer::customerHasAddress($this->context->customer->id, (int)Tools::getValue('id_address_invoice')))) $this->errors[] = Tools::displayError('Invalid address', !Tools::getValue('ajax')); else { $this->context->cart->id_address_delivery = (int)Tools::getValue('id_address_delivery'); $this->context->cart->id_address_invoice = $same ? $this->context->cart->id_address_delivery : (int)Tools::getValue('id_address_invoice'); CartRule::autoRemoveFromCart($this->context); CartRule::autoAddToCart($this->context); if (!$this->context->cart->update()) $this->errors[] = Tools::displayError('An error occurred while updating your cart.', !Tools::getValue('ajax')); if (!$this->context->cart->isMultiAddressDelivery()) $this->context->cart->setNoMultishipping(); // If there is only one delivery address, set each delivery address lines with the main delivery address if (Tools::isSubmit('message')) $this->_updateMessage(Tools::getValue('message')); // Add checking for all addresses $address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers(); if (count($address_without_carriers) && !$this->context->cart->isVirtualCart()) { if (count($address_without_carriers) > 1) $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.', !Tools::getValue('ajax'))); elseif ($this->context->cart->isMultiAddressDelivery()) $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.', !Tools::getValue('ajax'))); else $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to the address you selected.', !Tools::getValue('ajax'))); } } */ if ($this->errors) { if (Tools::getValue('ajax')) { die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } $this->step = 1; } if ($this->ajax) { die(true); } }