Пример #1
0
 protected function _deleteProduct($orderDetail, $quantity)
 {
     $price = $orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01);
     if ($orderDetail->reduction_percent != 0.0) {
         $reduction_amount = $price * $orderDetail->reduction_percent / 100;
     } elseif ($orderDetail->reduction_amount != '0.000000') {
         $reduction_amount = Tools::ps_round($orderDetail->reduction_amount, 2);
     }
     if (isset($reduction_amount) && $reduction_amount) {
         $price = Tools::ps_round($price - $reduction_amount, 2);
     }
     $productPriceWithoutTax = number_format($price / (1 + $orderDetail->tax_rate * 0.01), 2, '.', '');
     $price += Tools::ps_round($orderDetail->ecotax * (1 + $orderDetail->ecotax_tax_rate / 100), 2);
     $productPrice = number_format($quantity * $price, 2, '.', '');
     /* Update cart */
     $cart = new Cart($this->id_cart);
     $cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down');
     // customization are deleted in deleteCustomization
     $cart->update();
     /* Update order */
     $shippingDiff = $this->total_shipping - $cart->getOrderShippingCost();
     $this->total_products -= $productPriceWithoutTax;
     // After upgrading from old version
     // total_products_wt is null
     // removing a product made order total negative
     // and don't recalculating totals (on getTotalProductsWithTaxes)
     if ($this->total_products_wt != 0) {
         $this->total_products_wt -= $productPrice;
     }
     $this->total_shipping = $cart->getOrderShippingCost();
     /* It's temporary fix for 1.3 version... */
     if ($orderDetail->product_quantity_discount != '0.000000') {
         $this->total_paid -= $productPrice + $shippingDiff;
     } else {
         $this->total_paid = $cart->getOrderTotal();
     }
     $this->total_paid_real -= $productPrice + $shippingDiff;
     /* Prevent from floating precision issues (total_products has only 2 decimals) */
     if ($this->total_products < 0) {
         $this->total_products = 0;
     }
     if ($this->total_paid < 0) {
         $this->total_paid = 0;
     }
     if ($this->total_paid_real < 0) {
         $this->total_paid_real = 0;
     }
     /* Prevent from floating precision issues */
     $this->total_paid = number_format($this->total_paid, 2, '.', '');
     $this->total_paid_real = number_format($this->total_paid_real, 2, '.', '');
     $this->total_products = number_format($this->total_products, 2, '.', '');
     $this->total_products_wt = number_format($this->total_products_wt, 2, '.', '');
     /* Update order detail */
     $orderDetail->product_quantity -= (int) $quantity;
     if (!$orderDetail->product_quantity) {
         if (!$orderDetail->delete()) {
             return false;
         }
         if (count($this->getProductsDetail()) == 0) {
             $history = new OrderHistory();
             $history->id_order = (int) $this->id;
             $history->changeIdOrderState(Configuration::get('PS_OS_CANCELED'), (int) $this->id);
             if (!$history->addWithemail()) {
                 return false;
             }
         }
         return $this->update();
     }
     return $orderDetail->update() && $this->update();
 }
Пример #2
0
 public function addOrder(ShopgateOrder $order)
 {
     $this->log("PS start add_order", ShopgateLogger::LOGTYPE_DEBUG);
     $shopgateOrder = PSShopgateOrder::instanceByOrderNumber($order->getOrderNumber());
     if ($shopgateOrder->id) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DUPLICATE_ORDER, 'external_order_id: ' . $shopgateOrder->id_order, true);
     }
     $comments = array();
     // generate products array
     $products = $this->insertOrderItems($order);
     //Get or create customer
     $id_customer = Customer::customerExists($order->getMail(), true, false);
     $customer = new Customer($id_customer ? $id_customer : (int) $order->getExternalCustomerId());
     if (!$customer->id) {
         $customer = $this->createCustomer($customer, $order);
     }
     // prepare addresses: company has to be shorten. add mobile phone / telephone
     $this->prepareAddresses($order);
     //Get invoice and delivery addresses
     $invoiceAddress = $this->getPSAddress($customer, $order->getInvoiceAddress());
     $deliveryAddress = $order->getInvoiceAddress() == $order->getDeliveryAddress() ? $invoiceAddress : $this->getPSAddress($customer, $order->getDeliveryAddress());
     //Creating currency
     $this->log("PS setting currency", ShopgateLogger::LOGTYPE_DEBUG);
     $id_currency = $order->getCurrency() ? Currency::getIdByIsoCode($order->getCurrency()) : $this->id_currency;
     $currency = new Currency($id_currency ? $id_currency : $this->id_currency);
     //Creating new cart
     $this->log("PS set cart variables", ShopgateLogger::LOGTYPE_DEBUG);
     $cart = new Cart();
     $cart->id_lang = $this->id_lang;
     $cart->id_currency = $currency->id;
     $cart->id_address_delivery = $deliveryAddress->id;
     $cart->id_address_invoice = $invoiceAddress->id;
     $cart->id_customer = $customer->id;
     if (version_compare(_PS_VERSION_, '1.4.1.0', '>=')) {
         // id_guest is a connection to a ps_guest entry which includes screen width etc.
         // is_guest field only exists in Prestashop 1.4.1.0 and higher
         $cart->id_guest = $customer->is_guest;
     }
     $cart->recyclable = 0;
     $cart->gift = 0;
     $cart->id_carrier = (int) Configuration::get('SHOPGATE_CARRIER_ID');
     $cart->secure_key = $customer->secure_key;
     $this->log("PS try to create cart", ShopgateLogger::LOGTYPE_DEBUG);
     if (!$cart->add()) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create cart', true);
     }
     //Adding items to cart
     $this->log("PS adding items to cart", ShopgateLogger::LOGTYPE_DEBUG);
     foreach ($products as $p) {
         $this->log("PS cart updateQty product id: " . $p['id_product'], ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("PS cart updateQty product quantity: " . $p['quantity'], ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("PS cart updateQty product quantity_difference: " . $p['quantity_difference'], ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("PS cart updateQty product id_product_attribute: " . $p['id_product_attribute'], ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("PS cart updateQty product delivery address: " . $deliveryAddress->id, ShopgateLogger::LOGTYPE_DEBUG);
         //TODO deal with customizations
         $id_customization = false;
         if ($p['quantity'] - $p['quantity_difference'] > 0) {
             // only if the result of $p['quantity'] - $p['quantity_difference'] is higher then 0
             $cart->updateQty($p['quantity'] - $p['quantity_difference'], $p['id_product'], $p['id_product_attribute'], $id_customization, 'up', $deliveryAddress->id);
         }
         if ($p['quantity_difference'] > 0) {
             $this->log("PS try to add cart message ", ShopgateLogger::LOGTYPE_DEBUG);
             $message = new Message();
             $message->id_cart = $cart->id;
             $message->private = 1;
             $message->message = 'Warning, wanted quantity for product "' . $p['name'] . '" was ' . $p['quantity'] . ' unit(s), however, the amount in stock is ' . $p['quantity_in_stock'] . ' unit(s). Only ' . $p['quantity_in_stock'] . ' unit(s) were added to the order';
             $message->save();
         }
     }
     $id_order_state = 0;
     $shopgate = new Shopgate();
     $payment_name = $shopgate->getTranslation('Mobile Payment');
     $this->log("PS map payment method", ShopgateLogger::LOGTYPE_DEBUG);
     if (!$order->getIsShippingBlocked()) {
         $id_order_state = $this->getOrderStateId('PS_OS_PREPARATION');
         switch ($order->getPaymentMethod()) {
             case 'SHOPGATE':
                 $payment_name = $shopgate->getTranslation('Shopgate');
                 break;
             case 'PREPAY':
                 $payment_name = $shopgate->getTranslation('Bankwire');
                 $id_order_state = $this->getOrderStateId('PS_OS_BANKWIRE');
                 break;
             case 'COD':
                 $payment_name = $shopgate->getTranslation('Cash on Delivery');
                 break;
             case 'PAYPAL':
                 $payment_name = $shopgate->getTranslation('PayPal');
                 break;
             default:
                 break;
         }
     } else {
         $id_order_state = $this->getOrderStateId('PS_OS_SHOPGATE');
         switch ($order->getPaymentMethod()) {
             case 'SHOPGATE':
                 $payment_name = $shopgate->getTranslation('Shopgate');
                 break;
             case 'PREPAY':
                 $payment_name = $shopgate->getTranslation('Bankwire');
                 break;
             case 'COD':
                 $payment_name = $shopgate->getTranslation('Cash on Delivery');
                 break;
             case 'PAYPAL':
                 $id_order_state = $this->getOrderStateId('PS_OS_PAYPAL');
                 $payment_name = $shopgate->getTranslation('PayPal');
                 break;
             default:
                 $id_order_state = $this->getOrderStateId('PS_OS_SHOPGATE');
                 break;
         }
     }
     $shippingCosts = $order->getAmountShipping() + $order->getAmountShopPayment();
     //Creates shopgate order record and save shipping cost for future use
     $this->log("PS set PSShopgateOrder object variables", ShopgateLogger::LOGTYPE_DEBUG);
     $shopgateOrder = new PSShopgateOrder();
     $shopgateOrder->order_number = $order->getOrderNumber();
     $shopgateOrder->shipping_cost = $shippingCosts;
     $shopgateOrder->shipping_service = Configuration::get('SHOPGATE_SHIPPING_SERVICE');
     $shopgateOrder->id_cart = $cart->id;
     $shopgateOrder->shop_number = $this->config->getShopNumber();
     $shopgateOrder->comments = $this->jsonEncode($comments);
     if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) {
         $this->log("PS lower 1.4.0.2: ", ShopgateLogger::LOGTYPE_DEBUG);
         // Fix: sets in database ps_delivery all zones of passed shippingCosts
         $this->setShippingCosts(0);
     }
     $this->log("PS try creating PSShopgateOrder object", ShopgateLogger::LOGTYPE_DEBUG);
     if (!$shopgateOrder->add()) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create shopgate order', true);
     }
     //PS 1.5 compatibility
     if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
         $this->log("PS 1.5.x.x: set cart context", ShopgateLogger::LOGTYPE_DEBUG);
         $this->context = Context::getContext();
         $this->context->cart = $cart;
         $this->log("PS 1.5.x.x: \$cart->setDeliveryOption(array(\$cart->id_address_delivery => \$cart->id_carrier.','))\n\n==============", ShopgateLogger::LOGTYPE_DEBUG);
         $cart->setDeliveryOption(array($cart->id_address_delivery => $cart->id_carrier . ','));
         $this->log("PS 1.5.x.x: \$cart->update()", ShopgateLogger::LOGTYPE_DEBUG);
         $cart->update();
         $cart->id_carrier = (int) Configuration::get('SHOPGATE_CARRIER_ID');
     }
     $amountPaid = $order->getAmountComplete();
     if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) {
         // substract the shipping costs.
         $amountPaid -= $shippingCosts;
     }
     $this->log("\$shopgate->validateOrder(\$cart->id, \$id_order_state, \$amountPaid, \$payment_name, NULL, array(), NULL, false, \$cart->secure_key", ShopgateLogger::LOGTYPE_DEBUG);
     $this->log("\$cart->id = " . var_export($cart->id, true) . "\n\$id_order_state = " . var_export($id_order_state, true) . "\n\$amountPaid = " . var_export($amountPaid, true) . "\n\$payment_name = " . var_export($payment_name, true) . "\n\$cart->secure_key" . var_export($cart->secure_key, true) . "\n==============", ShopgateLogger::LOGTYPE_DEBUG);
     try {
         $shopgate->validateOrder($cart->id, $id_order_state, $amountPaid, $payment_name, NULL, array(), NULL, false, $cart->secure_key);
     } catch (Swift_Message_MimeException $ex) {
         $this->log("\$shopgate->validateOrder(\$cart->id, \$id_order_state, \$amountPaid, \$payment_name, NULL, array(), NULL, false, \$cart->secure_key) FAILED with Swift_Message_MimeException", ShopgateLogger::LOGTYPE_ERROR);
         // catch Exception if there is a problem with sending mails
     }
     if (version_compare(_PS_VERSION_, '1.4.0.2', '<') && (int) $shopgate->currentOrder > 0) {
         $this->log("PS < 1.4.0.2: update shipping and payment cost", ShopgateLogger::LOGTYPE_DEBUG);
         // in versions below 1.4.0.2 the shipping and payment costs must be updated after the order
         $updateShopgateOrder = new Order($shopgate->currentOrder);
         $updateShopgateOrder->total_paid = $order->getAmountComplete();
         $updateShopgateOrder->total_paid_real = $order->getAmountComplete();
         $updateShopgateOrder->total_products_wt = $order->getAmountItems();
         $updateShopgateOrder->total_shipping = $order->getAmountShipping() + $order->getAmountShopPayment();
         $updateShopgateOrder->update();
     }
     if ((int) $shopgate->currentOrder > 0) {
         $this->log("\$shopgateOrder->update()", ShopgateLogger::LOGTYPE_DEBUG);
         $shopgateOrder->id_order = $shopgate->currentOrder;
         $shopgateOrder->update();
         return array('external_order_id' => $shopgate->currentOrder, 'external_order_number' => $shopgate->currentOrder);
     } else {
         $this->log("\$shopgateOrder->delete()", ShopgateLogger::LOGTYPE_DEBUG);
         $shopgateOrder->delete();
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create order', true);
     }
 }
 private function _getCart($id_customer, $id_address_billing, $id_address_shipping, $productsNode)
 {
     $cart = new Cart();
     $cart->id_customer = $id_customer;
     $cart->id_address_invoice = $id_address_billing;
     $cart->id_address_delivery = $id_address_shipping;
     $cart->id_currency = Currency::getIdByIsoCode('EUR');
     $cart->id_lang = Configuration::get('PS_LANG_DEFAULT');
     $cart->recyclable = 0;
     $cart->secure_key = md5(uniqid(rand(), true));
     $cart->id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT');
     $cart->add();
     foreach ($productsNode->Product as $product) {
         $skus = explode('_', $product->SKU);
         if (!$cart->updateQty((int) $product->Quantity, (int) $skus[0], isset($skus[1]) ? $skus[1] : NULL)) {
             return false;
         }
     }
     $cart->update();
     return $cart;
 }
Пример #4
0
 protected function _deleteProduct($orderDetail, $quantity)
 {
     $product_price_tax_excl = $orderDetail->unit_price_tax_excl * $quantity;
     $product_price_tax_incl = $orderDetail->unit_price_tax_incl * $quantity;
     /* Update cart */
     $cart = new Cart($this->id_cart);
     $cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down');
     // customization are deleted in deleteCustomization
     $cart->update();
     /* Update order */
     $shipping_diff_tax_incl = $this->total_shipping_tax_incl - $cart->getPackageShippingCost($this->id_carrier, true, null, $this->getCartProducts());
     $shipping_diff_tax_excl = $this->total_shipping_tax_excl - $cart->getPackageShippingCost($this->id_carrier, false, null, $this->getCartProducts());
     $this->total_shipping -= $shipping_diff_tax_incl;
     $this->total_shipping_tax_excl -= $shipping_diff_tax_excl;
     $this->total_shipping_tax_incl -= $shipping_diff_tax_incl;
     $this->total_products -= $product_price_tax_excl;
     $this->total_products_wt -= $product_price_tax_incl;
     $this->total_paid -= $product_price_tax_incl + $shipping_diff_tax_incl;
     $this->total_paid_tax_incl -= $product_price_tax_incl + $shipping_diff_tax_incl;
     $this->total_paid_tax_excl -= $product_price_tax_excl + $shipping_diff_tax_excl;
     $this->total_paid_real -= $product_price_tax_incl + $shipping_diff_tax_incl;
     $fields = array('total_shipping', 'total_shipping_tax_excl', 'total_shipping_tax_incl', 'total_products', 'total_products_wt', 'total_paid', 'total_paid_tax_incl', 'total_paid_tax_excl', 'total_paid_real');
     /* Prevent from floating precision issues (total_products has only 2 decimals) */
     foreach ($fields as $field) {
         if ($this->{$field} < 0) {
             $this->{$field} = 0;
         }
     }
     /* Prevent from floating precision issues */
     foreach ($fields as $field) {
         $this->{$field} = number_format($this->{$field}, 2, '.', '');
     }
     /* Update order detail */
     $orderDetail->product_quantity -= (int) $quantity;
     if ($orderDetail->product_quantity == 0) {
         if (!$orderDetail->delete()) {
             return false;
         }
         if (count($this->getProductsDetail()) == 0) {
             $history = new OrderHistory();
             $history->id_order = (int) $this->id;
             $history->changeIdOrderState(Configuration::get('PS_OS_CANCELED'), $this);
             if (!$history->addWithemail()) {
                 return false;
             }
         }
         return $this->update();
     } else {
         $orderDetail->total_price_tax_incl -= $product_price_tax_incl;
         $orderDetail->total_price_tax_excl -= $product_price_tax_excl;
         $orderDetail->total_shipping_price_tax_incl -= $shipping_diff_tax_incl;
         $orderDetail->total_shipping_price_tax_excl -= $shipping_diff_tax_excl;
     }
     return $orderDetail->update() && $this->update();
 }
Пример #5
0
 public function hookheader($params)
 {
     //Change context Shop to be default
     if ($this->isVersionOneDotFive() && Shop::isFeatureActive()) {
         $oldContextShop = $this->getContextShop();
         $this->setContextShop();
     }
     //End of change
     // Check if the module is configured
     if (!Configuration::get('EBAY_PAYPAL_EMAIL')) {
         return false;
     }
     // Fix hook update product attribute
     $this->hookupdateProductAttributeEbay();
     // init date to check from
     if (Configuration::get('EBAY_INSTALL_DATE') < date('Y-m-d', strtotime('-30 days')) . 'T' . date('H:i:s', strtotime('-30 days'))) {
         //If it is more than 30 days that we installed the module
         $dateToCheckFrom = Configuration::get('EBAY_ORDER_LAST_UPDATE');
         $dateToCheckFromArray = explode('T', $dateToCheckFrom);
         $dateToCheckFrom = date("Y-m-d", strtotime($dateToCheckFromArray[0] . " -30 day"));
         $dateToCheckFrom .= 'T' . $dateToCheckFromArray[1];
     } else {
         //If it is less than 30 days that we installed the module
         $dateToCheckFrom = Configuration::get('EBAY_INSTALL_DATE');
         $dateToCheckFromArray = explode('T', $dateToCheckFrom);
         $dateToCheckFrom = date("Y-m-d", strtotime($dateToCheckFromArray[0] . " -1 day"));
         $dateToCheckFrom .= 'T' . $dateToCheckFromArray[1];
     }
     if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-30 minutes')) . 'T' . date('H:i:s', strtotime('-30 minutes')) . '.000Z') {
         $dateNew = date('Y-m-d') . 'T' . date('H:i:s') . '.000Z';
         $this->setConfiguration('EBAY_ORDER_LAST_UPDATE', $dateNew);
         // eBay Request
         $ebay = new eBayRequest();
         $page = 1;
         $orderList = array();
         $orderCount = 0;
         $orderCountTmp = 100;
         while ($orderCountTmp == 100 && $page < 10) {
             $orderListTmp = $ebay->getOrders($dateToCheckFrom, $dateNew, $page);
             $orderCountTmp = count($orderListTmp);
             $orderList = array_merge((array) $orderList, (array) $orderListTmp);
             $orderCount += $orderCountTmp;
             $page++;
         }
         // Lock
         if ($orderList) {
             foreach ($orderList as $korder => $order) {
                 if ($order['status'] == 'Complete' && $order['amount'] > 0.1 && isset($order['product_list']) && count($order['product_list'])) {
                     if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) {
                         // Check for empty name
                         $order['firstname'] = trim($order['firstname']);
                         $order['familyname'] = trim($order['familyname']);
                         if (empty($order['familyname'])) {
                             $order['familyname'] = $order['firstname'];
                         }
                         if (empty($order['firstname'])) {
                             $order['firstname'] = $order['familyname'];
                         }
                         if (empty($order['phone']) || !Validate::isPhoneNumber($order['phone'])) {
                             $order['phone'] = '0100000000';
                         }
                         if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname'])) {
                             // Getting the customer
                             $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'customer` WHERE `active` = 1 AND `email` = \'' . pSQL($order['email']) . '\' AND `deleted` = 0' . (substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
                             // Add customer if he doesn't exist
                             if ($id_customer < 1) {
                                 $customer = new Customer();
                                 $customer->id_gender = 0;
                                 $customer->id_default_group = 1;
                                 $customer->secure_key = md5(uniqid(rand(), true));
                                 $customer->email = $order['email'];
                                 $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand()));
                                 $customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s'));
                                 $customer->newsletter = 0;
                                 $customer->lastname = pSQL($order['familyname']);
                                 $customer->firstname = pSQL($order['firstname']);
                                 $customer->active = 1;
                                 $customer->add();
                                 $id_customer = $customer->id;
                             }
                             // Search if address exists
                             $id_address = (int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $id_customer . ' AND `alias` = \'eBay\'');
                             if ($id_address > 0) {
                                 $address = new Address((int) $id_address);
                             } else {
                                 $address = new Address();
                                 $address->id_customer = (int) $id_customer;
                             }
                             $address->id_country = (int) Country::getByIso($order['country_iso_code']);
                             $address->alias = 'eBay';
                             $address->lastname = pSQL($order['familyname']);
                             $address->firstname = pSQL($order['firstname']);
                             $address->address1 = pSQL($order['address1']);
                             $address->address2 = pSQL($order['address2']);
                             $address->postcode = pSQL($order['postalcode']);
                             $address->city = pSQL($order['city']);
                             $address->phone = pSQL($order['phone']);
                             $address->active = 1;
                             if ($id_address > 0 && Validate::isLoadedObject($address)) {
                                 $address->update();
                             } else {
                                 $address->add();
                             }
                             $id_address = $address->id;
                             $flag = 1;
                             foreach ($order['product_list'] as $product) {
                                 if ((int) $product['id_product'] < 1 || !Db::getInstance()->getValue('SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product['id_product'])) {
                                     $flag = 0;
                                 }
                                 if (isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 && !Db::getInstance()->getValue('SELECT `id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_product_attribute` = ' . (int) $product['id_product_attribute'])) {
                                     $flag = 0;
                                 }
                             }
                             if ($flag == 1) {
                                 //Create a Cart for the order
                                 $cartNbProducts = 0;
                                 $cartAdd = new Cart();
                                 Context::getContext()->customer = new Customer($id_customer);
                                 $cartAdd->id_customer = $id_customer;
                                 $cartAdd->id_address_invoice = $id_address;
                                 $cartAdd->id_address_delivery = $id_address;
                                 $cartAdd->id_carrier = 0;
                                 $cartAdd->id_lang = $this->id_lang;
                                 $cartAdd->id_currency = Currency::getIdByIsoCode('EUR');
                                 $cartAdd->recyclable = 0;
                                 $cartAdd->gift = 0;
                                 $cartAdd->add();
                                 $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                                 foreach ($order['product_list'] as $product) {
                                     $prod = new Product($product['id_product'], false, $id_lang);
                                     // Qty of product or attribute
                                     if (isset($product['id_product_attribute']) && !empty($product['id_product_attribute'])) {
                                         $minimalQty = (int) Attribute::getAttributeMinimalQty($product['id_product_attribute']);
                                     } else {
                                         $minimalQty = $prod->minimal_quantity;
                                     }
                                     if ($product['quantity'] >= $minimalQty) {
                                         if ($this->isVersionOneDotFive()) {
                                             $update = $cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL, false, 'up', 0, new Shop(Configuration::get('PS_SHOP_DEFAULT')));
                                             if ($update === TRUE) {
                                                 $cartNbProducts++;
                                             }
                                         } elseif ($cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL)) {
                                             $cartNbProducts++;
                                         }
                                     } else {
                                         $templateVars = array('{name_product}' => $prod->name, '{min_qty}' => $minimalQty, '{cart_qty}' => $product['quantity']);
                                         Mail::Send((int) Configuration::get('PS_LANG_DEFAULT'), 'alertEbay', Mail::l('Product quantity', $id_lang), $templateVars, strval(Configuration::get('PS_SHOP_EMAIL')), NULL, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/');
                                     }
                                 }
                                 $cartAdd->update();
                                 // Check number of products in the cart and check if order has already been taken
                                 if ($cartNbProducts > 0 && !Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) {
                                     // Fix on sending e-mail
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                                     $customerClear = new Customer();
                                     if (method_exists($customerClear, 'clearCache')) {
                                         $customerClear->clearCache(true);
                                     }
                                     $paiement = new eBayPayment();
                                     // Validate order
                                     if ($this->isVersionOneDotFive()) {
                                         $customer = new Customer($id_customer);
                                         $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency), false, $customer->secure_key, new Shop(Configuration::get('PS_SHOP_DEFAULT')));
                                     } else {
                                         $customer = new Customer($id_customer);
                                         $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency), false, $customer->secure_key);
                                     }
                                     $id_order = $paiement->currentOrder;
                                     // Fix on date
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', array('date_add' => pSQL($order['date_add'])), 'UPDATE', '`id_order` = ' . (int) $id_order);
                                     // Fix on sending e-mail
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                                     // Update price (because of possibility of price impact)
                                     foreach ($order['product_list'] as $product) {
                                         $tax_rate = Db::getInstance()->getValue('SELECT `tax_rate` FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']);
                                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', array('product_price' => floatval($product['price'] / (1 + $tax_rate / 100)), 'reduction_percent' => 0), 'UPDATE', '`id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']);
                                     }
                                     $updateOrder = array('total_paid' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']), 'total_products' => floatval(Db::getInstance()->getValue('SELECT SUM(`product_price`) FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $id_order)), 'total_products_wt' => floatval($order['amount'] - $order['shippingServiceCost']), 'total_shipping' => floatval($order['shippingServiceCost']));
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $updateOrder, 'UPDATE', '`id_order` = ' . (int) $id_order);
                                     // Register the ebay order ref
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int) $id_order), 'INSERT');
                                     if (!$this->isVersionOneDotFive()) {
                                         //Fix on eBay not updating
                                         $params = array();
                                         foreach ($order['product_list'] as $product) {
                                             $params['product'] = new Product((int) $product['id_product']);
                                             $this->hookaddproduct($params);
                                         }
                                     }
                                 } else {
                                     $cartAdd->delete();
                                     $orderList[$korder]['errors'][] = $this->l('Could not add product to cart (maybe your stock quantity is 0)');
                                 }
                             } else {
                                 $orderList[$korder]['errors'][] = $this->l('Could not found products in database');
                             }
                         } else {
                             $orderList[$korder]['errors'][] = $this->l('Invalid e-mail');
                         }
                     } else {
                         $orderList[$korder]['errors'][] = $this->l('Order already imported');
                     }
                 } else {
                     $orderList[$korder]['errors'][] = $this->l('Status not complete or amount less than 0.1 or no product matching');
                 }
             }
             file_put_contents(dirname(__FILE__) . '/log/orders.php', "<?php\n\n" . '$dateLastImport = ' . "'" . date('d/m/Y H:i:s') . "';\n\n" . '$orderList = ' . var_export($orderList, true) . ";\n\n");
         }
     }
     // Set old Context Shop
     if ($this->isVersionOneDotFive() && Shop::isFeatureActive()) {
         $this->setContextShop($oldContextShop);
     }
 }
        if ($id_hotel) {
            $obj_booking_dtl = new HotelBookingDetail();
            $hotel_room_data = $obj_booking_dtl->DataForFrontSearch($date_from, $date_to, $id_hotel, $id_product, 1);
            if ($hotel_room_data) {
                $total_available_rooms = $hotel_room_data['stats']['num_avail'];
            }
        }
    }
    $obj_htl_cart_booking_data = new HotelCartBookingData();
    $result = $obj_htl_cart_booking_data->deleteCartBookingDataOnRemoveFromBlockCart($id_cart, $id_product);
    if ($result) {
        die(Tools::jsonEncode(array('status' => 'success', 'avail_rooms' => $total_available_rooms)));
    } else {
        die(Tools::jsonEncode(array('status' => 'failed')));
    }
}
if (isset($delete_room_form_cart) && $delete_room_form_cart) {
    $num_rooms_to_decr_from_cart = Tools::getValue('num_rooms');
    $obj_htl_cart_booking_data = new HotelCartBookingData();
    $delete_room_from_cart_booking_data = $obj_htl_cart_booking_data->deleteCartDataByIdProductIdCart($id_cart, $id_product, $date_from, $date_to);
    if ($delete_room_from_cart_booking_data) {
        $cart_obj = new Cart($id_cart);
        $update_cart_product = $cart_obj->updateQty($num_rooms_to_decr_from_cart, $id_product, null, false, $operator = 'down', 0, null, true);
        if ($update_cart_product) {
            die(Tools::jsonEncode(array('status' => 'success', 'msg' => 'successfully cart product updated.')));
        } else {
            die(Tools::jsonEncode(array('status' => 'failed', 'msg' => 'error while updating cart product.')));
        }
    }
    die(Tools::jsonEncode(array('status' => 'failed', 'msg' => 'error while deleting room from cart booking table.')));
}
Пример #7
0
 public static function getCarriersByCountry($id_country, $id_state, $zipcode, $exiting_cart, $id_customer)
 {
     // Create temporary Address
     $addr_temp = new Address();
     $addr_temp->id_customer = $id_customer;
     $addr_temp->id_country = $id_country;
     $addr_temp->id_state = $id_state;
     $addr_temp->postcode = $zipcode;
     // Populate required attributes
     // Note: Some carrier needs the whole address
     // the '.' will do the job
     $addr_temp->firstname = ".";
     $addr_temp->lastname = ".";
     $addr_temp->address1 = ".";
     $addr_temp->city = ".";
     $addr_temp->alias = "TEMPORARY_ADDRESS_TO_DELETE";
     $addr_temp->save();
     $cart = new Cart();
     $cart->id_currency = $exiting_cart->id_currency;
     $cart->id_customer = $exiting_cart->id_customer;
     $cart->id_lang = $exiting_cart->id_lang;
     $cart->id_address_delivery = $addr_temp->id;
     $cart->add();
     $products = $exiting_cart->getProducts();
     foreach ($products as $key => $product) {
         $cart->updateQty($product['quantity'], $product['id_product'], $product['id_product_attribute']);
     }
     $carriers = $cart->simulateCarriersOutput(null, true);
     //delete temporary objects
     $addr_temp->delete();
     $cart->delete();
     return $carriers;
 }
Пример #8
0
 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);
     }
 }
Пример #9
0
    public function validation()
    {
        if (!$this->active || !Configuration::get('GOINTERPAY_STORE') || !Configuration::get('GOINTERPAY_SECRET')) {
            return false;
        }
        if (!isset($_GET['orderId'])) {
            return false;
        }
        include_once _PS_MODULE_DIR_ . 'gointerpay/Rest.php';
        $rest = new Rest(Configuration::get('GOINTERPAY_STORE'), Configuration::get('GOINTERPAY_SECRET'));
        $result = $rest->orderDetail(Tools::safeOutput(Tools::getValue('orderId')));
        $cart = new Cart((int) $result['cartId']);
        $original_total = Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
        /* Check the currency code */
        $id_currency_new = (int) Currency::getIdByIsoCode($result['foreignCurrencyCode']);
        if ($id_currency_new) {
            $cart->id_currency = (int) $id_currency_new;
            $cart->save();
        } else {
            die('Sorry, we were not able to accept orders in the following currency: ' . Tools::safeOutput($result['foreignCurrencyCode']));
        }
        $name = explode(" ", $result['delivery_address']['name']);
        $lastname = " - ";
        if (isset($name[1])) {
            $lastname = $name[1];
        }
        /* Update the delivery and billing address */
        $delivery_address = new Address((int) $cart->id_address_delivery);
        $delivery_address->firstname = $name[0];
        $delivery_address->lastname = $lastname;
        $delivery_address->company = $result['delivery_address']['company'];
        $delivery_address->phone = $result['delivery_address']['phone'];
        $delivery_address->phone_mobile = $result['delivery_address']['altPhone'];
        $delivery_address->id_country = (int) Country::getByIso($result['delivery_address']['countryCode']);
        $delivery_address->id_state = (int) State::getIdByIso($result['delivery_address']['state'], (int) $delivery_address->id_country);
        $delivery_address->address1 = $result['delivery_address']['address1'];
        $delivery_address->address2 = $result['delivery_address']['address2'];
        $delivery_address->city = $result['delivery_address']['city'];
        $delivery_address->postcode = $result['delivery_address']['zip'];
        $delivery_address->save();
        /* If no billing address specified, use the delivery address */
        if ($result['invoice_address']['address1'] != '' || $result['invoice_address']['city'] != '') {
            $invoice_name = explode(" ", $result['invoice_address']['name']);
            $invoice_lastname = " - ";
            if (isset($invoice_name[1])) {
                $invoice_lastname = $invoice_name[1];
            }
            $invoice_address = new Address((int) $cart->id_address_invoice);
            $invoice_address->firstname = $invoice_name[0];
            $invoice_address->lastname = $invoice_lastname;
            $invoice_address->company = $result['invoice_address']['company'];
            $invoice_address->phone = $result['invoice_address']['phone'];
            $invoice_address->phone_mobile = $result['invoice_address']['altPhone'];
            $invoice_address->id_country = (int) Country::getByIso($result['invoice_address']['countryCode']);
            $invoice_address->id_state = (int) State::getIdByIso($result['invoice_address']['state'], (int) $invoice_address->id_country);
            $invoice_address->address1 = $result['invoice_address']['address1'];
            $invoice_address->address2 = $result['invoice_address']['address2'];
            $invoice_address->city = $result['invoice_address']['city'];
            $invoice_address->postcode = $result['invoice_address']['zip'];
            if ($cart->id_address_delivery == $cart->id_address_invoice) {
                $invoice_address->add();
                $cart->id_address_invoice = (int) $invoice_address->id;
                $cart->save();
            } else {
                $invoice_address->save();
            }
        }
        /* Store the Order ID and Shipping cost */
        Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'gointerpay_order_id` (`id_cart`, `orderId`, `shipping`, `shipping_orig`, `taxes`, `total`, `products`, `status`)
		VALUES (\'' . (int) $cart->id . '\', \'' . pSQL(Tools::getValue('orderId')) . '\', \'' . (double) $result['shippingTotal'] . '\', \'' . (double) $result['shippingTotalForeign'] . '\', \'' . (double) $result['quotedDutyTaxes'] . '\', \'' . (double) $result['grandTotal'] . '\', \'' . (double) $result['itemsTotal'] . '\', \'Init\')');
        /* Add the duties and taxes */
        Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'specific_price` WHERE id_customer = ' . (int) $cart->id_customer . ' AND id_product = ' . (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES'));
        $specific_price = new SpecificPrice();
        $specific_price->id_product = (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES');
        $specific_price->id_shop = 0;
        $specific_price->id_country = 0;
        $specific_price->id_group = 0;
        $specific_price->id_cart = (int) $cart->id;
        $specific_price->id_product_attribute = 0;
        $specific_price->id_currency = $cart->id_currency;
        $specific_price->id_customer = $cart->id_customer;
        $specific_price->price = (double) $result['quotedDutyTaxesForeign'];
        $specific_price->from_quantity = 1;
        $specific_price->reduction = 0;
        $specific_price->reduction_type = 'percentage';
        $specific_price->from = date('Y-m-d H:i:s');
        $specific_price->to = strftime('%Y-%m-%d %H:%M:%S', time() + 10);
        $specific_price->add();
        if (Validate::isLoadedObject($specific_price)) {
            $cart->updateQty(1, (int) Configuration::get('GOINTERPAY_ID_TAXES_TDUTIES'));
        }
        $result['status'] = 'Pending';
        $total = Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
        $message = '
		Total paid on Interpay: ' . (double) $result['grandTotalForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Duties and taxes on Interpay: ' . (double) $result['quotedDutyTaxesForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Shipping on Interpay: ' . (double) $result['shippingTotalForeign'] . ' ' . (string) $result['foreignCurrencyCode'] . '
		Currency: ' . $result['foreignCurrencyCode'];
        if ($result['status'] == 'Pending') {
            $this->context->cart->id = (int) $result['cartId'];
            Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'gointerpay_order_id` SET `status` = \'Pending\' WHERE `id_cart` = ' . (int) $cart->id);
            $order_status = Configuration::get('GOINTERPAY_PAYMENT_PENDING');
            $price_difference = abs($original_total - ((double) $result['grandTotalForeign'] - (double) $result['quotedDutyTaxesForeign'] - (double) $result['shippingTotalForeign'])) * 100 / $original_total;
            if ($price_difference > 1) {
                /* Uncomment this line if you would like to decline orders with a too high price difference */
                // $order_status = Configuration::get('PS_OS_ERROR');
                /*$message .= '
                		
                		Warning: The difference between the price paid and the price to pay was higher than 1% ('.number_format($price_difference, 2, '.', '').'%)
                		However, the payment was processed by Interpay, you should get in touch with the customer and Interpay to resolve that matter.';*/
            }
            $this->validateOrder((int) $cart->id, (int) $order_status, $total, $this->displayName, $message, array(), NULL, false, $cart->secure_key);
            Tools::redirectLink(__PS_BASE_URI__ . 'history.php');
        } else {
            die('Order was not found or cannot be validated at this time, please contact us.');
        }
    }
 /**
  * Add Products to cart
  * @param Cart $cart Cart object
  */
 private function addProductsToCart($cart, $codeCountry)
 {
     $products = $this->datas->orderLineItems;
     $country = $this->getCountry($codeCountry);
     $address = Address::initialize();
     $address->id_country = $country->id;
     if ($products && count($products)) {
         foreach ($products as $p) {
             if (PowaTagAPI::apiLog()) {
                 PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::IN_PROGRESS, 'Product : ' . $p->product->code);
             }
             $product = PowaTagProductHelper::getProductByCode($p->product->code, $this->context->language->id);
             if (!Validate::isLoadedObject($product)) {
                 $this->addError(sprintf($this->module->l('This product does not exists : %s'), $p->product->code), PowaTagErrorType::$SKU_NOT_FOUND);
                 if (PowaTagAPI::apiLog()) {
                     PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : ' . $this->error['message']);
                 }
                 return false;
             }
             $variants = $p->product->productVariants;
             $product_rate = 1 + $product->getTaxesRate($address) / 100;
             foreach ($variants as $variant) {
                 $variantCurrency = $this->getCurrencyByIsoCode($variant->finalPrice->currency);
                 if (!PowaTagValidate::currencyEnable($variantCurrency)) {
                     $this->addError(sprintf($this->module->l('Currency not found : %s'), $variant->code), PowaTagErrorType::$CURRENCY_NOT_SUPPORTED);
                     if (PowaTagAPI::apiLog()) {
                         PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : ' . $this->error['message']);
                     }
                     return false;
                 }
                 $variantAmount = $variant->finalPrice->amount;
                 $id_product_attribute = false;
                 $combination = false;
                 if ($id_product_attribute = PowaTagProductAttributeHelper::getCombinationByCode($product->id, $variant->code)) {
                     $combination = new Combination($id_product_attribute);
                     $priceAttribute = $product->getPrice($this->display_taxes, $id_product_attribute);
                     $qtyInStock = PowaTagProductQuantityHelper::getProductQuantity($product, $id_product_attribute);
                 } else {
                     if ($product) {
                         $priceAttribute = $product->getPrice($this->display_taxes);
                         $qtyInStock = PowaTagProductQuantityHelper::getProductQuantity($product);
                     } else {
                         $this->addError(sprintf($this->module->l('This variant does not exist : %s'), $variant->code), PowaTagErrorType::$SKU_NOT_FOUND);
                         if (PowaTagAPI::apiLog()) {
                             PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : ' . $this->error['message']);
                         }
                         return false;
                     }
                 }
                 if ($qtyInStock == 0) {
                     $this->addError(sprintf($this->module->l('No Stock Available')), PowaTagErrorType::$SKU_OUT_OF_STOCK);
                     if (PowaTagAPI::apiLog()) {
                         PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : ' . $this->error['message']);
                     }
                     return false;
                 }
                 if ($qtyInStock < $p->quantity) {
                     $this->addError(sprintf($this->module->l('Quantity > Stock Count')), PowaTagErrorType::$INSUFFICIENT_STOCK);
                     if (PowaTagAPI::apiLog()) {
                         PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : ' . $this->error['message']);
                     }
                     return false;
                 }
                 if ($p->quantity < $product->minimal_quantity || $combination && $combination->minimal_quantity > $p->quantity) {
                     $this->addError(sprintf($this->module->l('Quantity < minimal quantity for product')), PowaTagErrorType::$OTHER_STOCK_ERROR);
                     if (PowaTagAPI::apiLog()) {
                         PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::ERROR, 'Product : ' . $this->error['message']);
                     }
                     return false;
                 }
                 $cart->updateQty($p->quantity, $product->id, $id_product_attribute);
                 if (PowaTagAPI::apiLog()) {
                     PowaTagLogs::initAPILog('Add product to cart', PowaTagLogs::SUCCESS, 'Cart ID : ' . $cart->id . ' - Product ID : ' . $product->id);
                 }
                 break;
             }
         }
     } else {
         $this->addError($this->module->l('No product found in request'), PowaTagErrorType::$SKU_NOT_FOUND);
         return false;
     }
     // add vouchers
     if (isset($this->datas->vouchers)) {
         $this->context->cart = $cart;
         $vouchers = $this->datas->vouchers;
         if ($vouchers && count($vouchers)) {
             foreach ($vouchers as $voucher) {
                 $ci = CartRule::getIdByCode($voucher);
                 if (!$ci) {
                     continue;
                 }
                 $cr = new CartRule($ci);
                 if (!$cr) {
                     continue;
                 }
                 if ($error = $cr->checkValidity($this->context, false, true)) {
                     continue;
                 }
                 $this->context->cart->addCartRule($cr->id);
                 if (PowaTagAPI::apiLog()) {
                     PowaTagLogs::initAPILog('Added voucher', PowaTagLogs::SUCCESS, 'Cart ID : ' . $cart->id . ' - Voucher : ' . $voucher);
                 }
             }
         }
     }
     return true;
 }
Пример #11
0
 public function hookbackOfficeTop($params)
 {
     // Check if the module is configured
     if (!Configuration::get('EBAY_PAYPAL_EMAIL')) {
         return false;
     }
     // If no update yet
     if (!Configuration::get('EBAY_ORDER_LAST_UPDATE')) {
         Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', date('Y-m-d') . 'T' . date('H:i:s') . '.000Z');
     }
     // init Var
     $dateNew = date('Y-m-d') . 'T' . date('H:i:s') . '.000Z';
     if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-30 minutes')) . 'T' . date('H:i:s', strtotime('-30 minutes')) . '.000Z') {
         // Lock
         Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', $dateNew);
         // eBay Request
         $ebay = new eBayRequest();
         $page = 1;
         $orderList = array();
         $orderCount = 0;
         $orderCountTmp = 100;
         while ($orderCountTmp == 100 && $page < 10) {
             $orderListTmp = $ebay->getOrders(date('Y-m-d', strtotime('-30 days')) . 'T' . date('H:i:s', strtotime('-30 days')) . '.000Z', $dateNew, $page);
             $orderCountTmp = count($orderListTmp);
             $orderList = array_merge((array) $orderList, (array) $orderListTmp);
             $orderCount += $orderCountTmp;
             $page++;
         }
         if ($orderList) {
             foreach ($orderList as $korder => $order) {
                 if ($order['status'] == 'Complete' && $order['amount'] > 0.1 && isset($order['product_list']) && count($order['product_list'])) {
                     if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) {
                         $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'customer` WHERE `active` = 1 AND `email` = \'' . pSQL($order['email']) . '\' AND `deleted` = 0' . (substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
                         // Check for empty name
                         $order['firstname'] = trim($order['firstname']);
                         $order['familyname'] = trim($order['familyname']);
                         if (empty($order['familyname'])) {
                             $order['familyname'] = $order['firstname'];
                         }
                         if (empty($order['firstname'])) {
                             $order['firstname'] = $order['familyname'];
                         }
                         if (empty($order['phone']) || !Validate::isPhoneNumber($order['phone'])) {
                             $order['phone'] = '0100000000';
                         }
                         if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname'])) {
                             // Add customer if he doesn't exist
                             if ($id_customer < 1) {
                                 $customer = new Customer();
                                 $customer->id_gender = 9;
                                 $customer->id_default_group = 1;
                                 $customer->secure_key = md5(uniqid(rand(), true));
                                 $customer->email = $order['email'];
                                 $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand()));
                                 $customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s'));
                                 $customer->newsletter = 0;
                                 $customer->lastname = pSQL($order['familyname']);
                                 $customer->firstname = pSQL($order['firstname']);
                                 $customer->active = 1;
                                 $customer->add();
                                 $id_customer = $customer->id;
                             }
                             // Search if address exists
                             $id_address = (int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $id_customer . ' AND `alias` = \'eBay\'');
                             if ($id_address > 0) {
                                 $address = new Address((int) $id_address);
                             } else {
                                 $address = new Address();
                                 $address->id_customer = (int) $id_customer;
                             }
                             $address->id_country = (int) Country::getByIso($order['country_iso_code']);
                             $address->alias = 'eBay';
                             $address->lastname = pSQL($order['familyname']);
                             $address->firstname = pSQL($order['firstname']);
                             $address->address1 = pSQL($order['address1']);
                             $address->address2 = pSQL($order['address2']);
                             $address->postcode = pSQL($order['postalcode']);
                             $address->city = pSQL($order['city']);
                             $address->phone = pSQL($order['phone']);
                             $address->active = 1;
                             if ($id_address > 0 && Validate::isLoadedObject($address)) {
                                 $address->update();
                             } else {
                                 $address->add();
                             }
                             $id_address = $address->id;
                             $flag = 1;
                             foreach ($order['product_list'] as $product) {
                                 if ((int) $product['id_product'] < 1 || !Db::getInstance()->getValue('SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product['id_product'])) {
                                     $flag = 0;
                                 }
                                 if (isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 && !Db::getInstance()->getValue('SELECT `id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_product_attribute` = ' . (int) $product['id_product_attribute'])) {
                                     $flag = 0;
                                 }
                             }
                             if ($flag == 1) {
                                 $cartNbProducts = 0;
                                 $cartAdd = new Cart();
                                 $cartAdd->id_customer = $id_customer;
                                 $cartAdd->id_address_invoice = $id_address;
                                 $cartAdd->id_address_delivery = $id_address;
                                 $cartAdd->id_carrier = 1;
                                 $cartAdd->id_lang = $this->id_lang;
                                 $cartAdd->id_currency = Currency::getIdByIsoCode('EUR');
                                 $cartAdd->recyclable = 0;
                                 $cartAdd->gift = 0;
                                 $cartAdd->add();
                                 foreach ($order['product_list'] as $product) {
                                     if ($cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL)) {
                                         $cartNbProducts++;
                                     }
                                 }
                                 $cartAdd->update();
                                 // Check number of products in the cart
                                 if ($cartNbProducts > 0) {
                                     // Fix on sending e-mail
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                                     $customerClear = new Customer();
                                     if (method_exists($customerClear, 'clearCache')) {
                                         $customerClear->clearCache(true);
                                     }
                                     // Validate order
                                     $paiement = new eBayPayment();
                                     $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency));
                                     $id_order = $paiement->currentOrder;
                                     // Fix on date
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', array('date_add' => pSQL($order['date_add'])), 'UPDATE', '`id_order` = ' . (int) $id_order);
                                     // Fix on sending e-mail
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                                     // Update price (because of possibility of price impact)
                                     $updateOrder = array('total_paid' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']), 'total_products' => floatval($order['amount']), 'total_products_wt' => floatval($order['amount']), 'total_shipping' => floatval($order['shippingServiceCost']));
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $updateOrder, 'UPDATE', '`id_order` = ' . (int) $id_order);
                                     foreach ($order['product_list'] as $product) {
                                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', array('product_price' => floatval($product['price']), 'tax_rate' => 0, 'reduction_percent' => 0), 'UPDATE', '`id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']);
                                     }
                                     // Register the ebay order ref
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int) $id_order), 'INSERT');
                                 } else {
                                     $cartAdd->delete();
                                     $orderList[$korder]['errors'][] = $this->l('Could not add product to cart (maybe your stock quantity is 0)');
                                 }
                             } else {
                                 $orderList[$korder]['errors'][] = $this->l('Could not found products in database');
                             }
                         } else {
                             $orderList[$korder]['errors'][] = $this->l('Invalid e-mail');
                         }
                     } else {
                         $orderList[$korder]['errors'][] = $this->l('Order already imported');
                     }
                 } else {
                     $orderList[$korder]['errors'][] = $this->l('Status not complete or amount less than 0.1 or no product matching');
                 }
             }
             file_put_contents(dirname(__FILE__) . '/log/orders.php', "<?php\n\n" . '$dateLastImport = ' . "'" . date('d/m/Y H:i:s') . "';\n\n" . '$orderList = ' . var_export($orderList, true) . ";\n\n");
         }
     }
 }
Пример #12
0
 private function _deleteProduct($orderDetail, $quantity)
 {
     $price = $orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01);
     if ($orderDetail->reduction_percent != 0.0) {
         $reduction_amount = $price * $orderDetail->reduction_percent / 100;
     } elseif ($orderDetail->reduction_amount != '0.000000') {
         $reduction_amount = Tools::ps_round($orderDetail->reduction_amount * (1 + $orderDetail->tax_rate * 0.01), 2);
     }
     if (isset($reduction_amount) and $reduction_amount) {
         $price = Tools::ps_round($price - $reduction_amount, 2);
     }
     $unitPrice = number_format($price, 2, '.', '');
     $productPrice = number_format($quantity * $price, 2, '.', '');
     $productPriceWithoutTax = number_format($productPrice / (1 + $orderDetail->tax_rate * 0.01), 2, '.', '');
     /* Update cart */
     $cart = new Cart($this->id_cart);
     $cart->updateQty($quantity, $orderDetail->product_id, $orderDetail->product_attribute_id, false, 'down');
     // customization are deleted in deleteCustomization
     $cart->update();
     /* Update order */
     $shippingDiff = $this->total_shipping - $cart->getOrderShippingCost();
     $this->total_products -= $productPriceWithoutTax;
     $this->total_products_wt -= $productPrice;
     $this->total_shipping = $cart->getOrderShippingCost();
     /* It's temporary fix for 1.3 version... waiting historization system on 1.4 version  */
     if ($orderDetail->product_quantity_discount != '0.000000') {
         $this->total_paid -= $productPrice + $shippingDiff;
     } else {
         $this->total_paid = $cart->getOrderTotal();
     }
     $this->total_paid_real -= $productPrice + $shippingDiff;
     /* Prevent from floating precision issues (total_products has only 2 decimals) */
     if ($this->total_products < 0) {
         $this->total_products = 0;
     }
     /* Prevent from floating precision issues */
     $this->total_paid = number_format($this->total_paid, 2, '.', '');
     $this->total_paid_real = number_format($this->total_paid_real, 2, '.', '');
     $this->total_products = number_format($this->total_products, 2, '.', '');
     $this->total_products_wt = number_format($this->total_products_wt, 2, '.', '');
     /* Update order detail */
     $orderDetail->product_quantity -= intval($quantity);
     if (!$orderDetail->product_quantity) {
         if (!$orderDetail->delete()) {
             return false;
         }
         if (count($this->getProductsDetail()) == 0) {
             global $cookie;
             $history = new OrderHistory();
             $history->id_order = intval($this->id);
             $history->changeIdOrderState(_PS_OS_CANCELED_, intval($this->id));
             if (!$history->addWithemail()) {
                 return false;
             }
         }
         return $this->update();
     }
     return $orderDetail->update() and $this->update();
 }
 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);
     }
 }
Пример #14
0
 private function _getCart($id_customer, $id_address_billing, $id_address_shipping, $productsNode, $currency, $shipping_method)
 {
     $cart = new Cart();
     $cart->id_customer = $id_customer;
     $cart->id_address_invoice = $id_address_billing;
     $cart->id_address_delivery = $id_address_shipping;
     $cart->id_currency = Currency::getIdByIsoCode((string) $currency == '' ? 'EUR' : (string) $currency);
     $cart->id_lang = Configuration::get('PS_LANG_DEFAULT');
     $cart->recyclable = 0;
     $cart->secure_key = md5(uniqid(rand(), true));
     $actual_configuration = unserialize(Configuration::get('SHOPPING_FLUX_SHIPPING_MATCHING'));
     $carrier_to_load = isset($actual_configuration[base64_encode(Tools::safeOutput($shipping_method))]) ? (int) $actual_configuration[base64_encode(Tools::safeOutput($shipping_method))] : (int) Configuration::get('SHOPPING_FLUX_CARRIER');
     $carrier = Carrier::getCarrierByReference($carrier_to_load);
     //manage case PS_CARRIER_DEFAULT is deleted
     $carrier = is_object($carrier) ? $carrier : new Carrier($carrier_to_load);
     $cart->id_carrier = $carrier->id;
     $cart->add();
     foreach ($productsNode->Product as $product) {
         $skus = explode('_', $product->SKU);
         $added = $cart->updateQty((int) $product->Quantity, (int) $skus[0], isset($skus[1]) ? $skus[1] : null);
         if ($added < 0 || $added === false) {
             return false;
         }
     }
     $cart->update();
     return $cart;
 }
 protected function restoreOrderToCart(Cart $cart)
 {
     if (!$cart || !ValidateCore::isLoadedObject($cart)) {
         return null;
     }
     Db::getInstance()->execute('BEGIN');
     $new_cart = null;
     try {
         /** @var CartCore $new_cart */
         /** @noinspection PhpUndefinedClassInspection */
         $new_cart = new Cart();
         /** @noinspection PhpUndefinedFieldInspection */
         $new_cart->id_customer = (int) $cart->id_customer;
         /** @noinspection PhpUndefinedFieldInspection */
         $new_cart->id_address_delivery = (int) $cart->id_address_delivery;
         /** @noinspection PhpUndefinedFieldInspection */
         $new_cart->id_address_invoice = (int) $cart->id_address_invoice;
         /** @noinspection PhpUndefinedFieldInspection */
         $new_cart->id_lang = (int) $cart->id_lang;
         /** @noinspection PhpUndefinedFieldInspection */
         $new_cart->id_currency = (int) $cart->id_currency;
         /** @noinspection PhpUndefinedFieldInspection */
         $new_cart->id_carrier = (int) $cart->id_carrier;
         /** @noinspection PhpUndefinedFieldInspection */
         $new_cart->recyclable = (int) $cart->recyclable;
         /** @noinspection PhpUndefinedFieldInspection */
         $new_cart->gift = (int) $cart->gift;
         $new_cart->add();
         /** @noinspection PhpUndefinedMethodInspection */
         $products = $cart->getProducts();
         if ($products) {
             foreach ($products as $p) {
                 $idProduct = $p['id_product'];
                 $idProductAttribute = $p['id_product_attribute'];
                 $qty = $p['cart_quantity'];
                 /** @noinspection PhpUndefinedClassInspection */
                 /** @noinspection PhpUndefinedFieldInspection */
                 $producToAdd = new Product((int) $idProduct, true, (int) $cart->id_lang);
                 /** @noinspection PhpUndefinedFieldInspection */
                 if (!$producToAdd->id || !$producToAdd->active) {
                     continue;
                 }
                 /* Check the quantity availability  */
                 if ($idProductAttribute > 0 and is_numeric($idProductAttribute)) {
                     /** @noinspection PhpUndefinedClassInspection */
                     /** @noinspection PhpUndefinedMethodInspection */
                     /** @noinspection PhpUndefinedFieldInspection */
                     if (!$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) {
                         /* There is not enough product attribute in stock - set customer qty to current stock on hand */
                         /** @noinspection PhpUndefinedFunctionInspection */
                         $qty = getAttributeQty($idProductAttribute);
                     }
                 } elseif (!$producToAdd->checkQty((int) $qty)) {
                     /* There is not enough product in stock - set customer qty to current stock on hand */
                     /** @noinspection PhpUndefinedMethodInspection */
                     $qty = $producToAdd->getQuantity($idProduct);
                 }
                 $new_cart->updateQty((int) $qty, (int) $idProduct, (int) $idProductAttribute, NULL, 'up');
                 unset($p);
             }
         }
         $new_cart->update();
         Db::getInstance()->execute('COMMIT');
     } catch (Exception $e) {
         Db::getInstance()->execute('ROLLBACK');
         throw $e;
     }
     /** @noinspection PhpUndefinedFieldInspection */
     $this->context->cookie->id_cart = (int) $new_cart->id;
     return $new_cart;
 }
Пример #16
0
 public function ajaxProcessAddProductOnOrder()
 {
     // Load object
     $order = new Order((int) Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The order object cannot be loaded.'))));
     }
     if ($order->hasBeenShipped()) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('You cannot add products to delivered orders. '))));
     }
     $product_informations = $_POST['add_product'];
     if (isset($_POST['add_invoice'])) {
         $invoice_informations = $_POST['add_invoice'];
     } else {
         $invoice_informations = array();
     }
     $product = new Product($product_informations['product_id'], false, $order->id_lang);
     if (!Validate::isLoadedObject($product)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The product object cannot be loaded.'))));
     }
     if (isset($product_informations['product_attribute_id']) && $product_informations['product_attribute_id']) {
         $combination = new Combination($product_informations['product_attribute_id']);
         if (!Validate::isLoadedObject($combination)) {
             die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The combination object cannot be loaded.'))));
         }
     }
     // Total method
     $total_method = Cart::BOTH_WITHOUT_SHIPPING;
     // Create new cart
     $cart = new Cart();
     $cart->id_shop_group = $order->id_shop_group;
     $cart->id_shop = $order->id_shop;
     $cart->id_customer = $order->id_customer;
     $cart->id_carrier = $order->id_carrier;
     $cart->id_address_delivery = $order->id_address_delivery;
     $cart->id_address_invoice = $order->id_address_invoice;
     $cart->id_currency = $order->id_currency;
     $cart->id_lang = $order->id_lang;
     $cart->secure_key = $order->secure_key;
     // Save new cart
     $cart->add();
     // Save context (in order to apply cart rule)
     $this->context->cart = $cart;
     $this->context->customer = new Customer($order->id_customer);
     // always add taxes even if there are not displayed to the customer
     $use_taxes = true;
     $initial_product_price_tax_incl = Product::getPriceStatic($product->id, $use_taxes, isset($combination) ? $combination->id : null, 2, null, false, true, 1, false, $order->id_customer, $cart->id, $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
     // Creating specific price if needed
     if ($product_informations['product_price_tax_incl'] != $initial_product_price_tax_incl) {
         $specific_price = new SpecificPrice();
         $specific_price->id_shop = 0;
         $specific_price->id_shop_group = 0;
         $specific_price->id_currency = 0;
         $specific_price->id_country = 0;
         $specific_price->id_group = 0;
         $specific_price->id_customer = $order->id_customer;
         $specific_price->id_product = $product->id;
         if (isset($combination)) {
             $specific_price->id_product_attribute = $combination->id;
         } else {
             $specific_price->id_product_attribute = 0;
         }
         $specific_price->price = $product_informations['product_price_tax_excl'];
         $specific_price->from_quantity = 1;
         $specific_price->reduction = 0;
         $specific_price->reduction_type = 'amount';
         $specific_price->from = '0000-00-00 00:00:00';
         $specific_price->to = '0000-00-00 00:00:00';
         $specific_price->add();
     }
     // Add product to cart
     $update_quantity = $cart->updateQty($product_informations['product_quantity'], $product->id, isset($product_informations['product_attribute_id']) ? $product_informations['product_attribute_id'] : null, isset($combination) ? $combination->id : null, 'up', 0, new Shop($cart->id_shop));
     if ($update_quantity < 0) {
         // If product has attribute, minimal quantity is set with minimal quantity of attribute
         $minimal_quantity = $product_informations['product_attribute_id'] ? Attribute::getAttributeMinimalQty($product_informations['product_attribute_id']) : $product->minimal_quantity;
         die(Tools::jsonEncode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity))));
     } elseif (!$update_quantity) {
         die(Tools::jsonEncode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false))));
     }
     // If order is valid, we can create a new invoice or edit an existing invoice
     if ($order->hasInvoice()) {
         $order_invoice = new OrderInvoice($product_informations['invoice']);
         // Create new invoice
         if ($order_invoice->id == 0) {
             // If we create a new invoice, we calculate shipping cost
             $total_method = Cart::BOTH;
             // Create Cart rule in order to make free shipping
             if (isset($invoice_informations['free_shipping']) && $invoice_informations['free_shipping']) {
                 $cart_rule = new CartRule();
                 $cart_rule->id_customer = $order->id_customer;
                 $cart_rule->name = array(Configuration::get('PS_LANG_DEFAULT') => $this->l('[Generated] CartRule for Free Shipping'));
                 $cart_rule->date_from = date('Y-m-d H:i:s', time());
                 $cart_rule->date_to = date('Y-m-d H:i:s', time() + 24 * 3600);
                 $cart_rule->quantity = 1;
                 $cart_rule->quantity_per_user = 1;
                 $cart_rule->minimum_amount_currency = $order->id_currency;
                 $cart_rule->reduction_currency = $order->id_currency;
                 $cart_rule->free_shipping = true;
                 $cart_rule->active = 1;
                 $cart_rule->add();
                 // Add cart rule to cart and in order
                 $cart->addCartRule($cart_rule->id);
                 $values = array('tax_incl' => $cart_rule->getContextualValue(true), 'tax_excl' => $cart_rule->getContextualValue(false));
                 $order->addCartRule($cart_rule->id, $cart_rule->name[Configuration::get('PS_LANG_DEFAULT')], $values);
             }
             $order_invoice->id_order = $order->id;
             if ($order_invoice->number) {
                 Configuration::updateValue('PS_INVOICE_START_NUMBER', false, false, null, $order->id_shop);
             } else {
                 $order_invoice->number = Order::getLastInvoiceNumber() + 1;
             }
             $invoice_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
             $carrier = new Carrier((int) $order->id_carrier);
             $tax_calculator = $carrier->getTaxCalculator($invoice_address);
             $order_invoice->total_paid_tax_excl = Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl = Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt = (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->total_shipping_tax_excl = (double) $cart->getTotalShippingCost(null, false);
             $order_invoice->total_shipping_tax_incl = (double) $cart->getTotalShippingCost();
             $order_invoice->total_wrapping_tax_excl = abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order_invoice->total_wrapping_tax_incl = abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->shipping_tax_computation_method = (int) $tax_calculator->computation_method;
             // Update current order field, only shipping because other field is updated later
             $order->total_shipping += $order_invoice->total_shipping_tax_incl;
             $order->total_shipping_tax_excl += $order_invoice->total_shipping_tax_excl;
             $order->total_shipping_tax_incl += $use_taxes ? $order_invoice->total_shipping_tax_incl : $order_invoice->total_shipping_tax_excl;
             $order->total_wrapping += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_excl += abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_incl += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->add();
             $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl));
             $order_carrier = new OrderCarrier();
             $order_carrier->id_order = (int) $order->id;
             $order_carrier->id_carrier = (int) $order->id_carrier;
             $order_carrier->id_order_invoice = (int) $order_invoice->id;
             $order_carrier->weight = (double) $cart->getTotalWeight();
             $order_carrier->shipping_cost_tax_excl = (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->shipping_cost_tax_incl = $use_taxes ? (double) $order_invoice->total_shipping_tax_incl : (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->add();
         } else {
             $order_invoice->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->update();
         }
     }
     // Create Order detail information
     $order_detail = new OrderDetail();
     $order_detail->createList($order, $cart, $order->getCurrentOrderState(), $cart->getProducts(), isset($order_invoice) ? $order_invoice->id : 0, $use_taxes, (int) Tools::getValue('add_product_warehouse'));
     // update totals amount of order
     $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
     $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
     $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2);
     $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
     $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
     if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) {
         $order->total_shipping = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl;
     }
     // discount
     $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     // Save changes of order
     $order->update();
     // Update weight SUM
     $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
     if (Validate::isLoadedObject($order_carrier)) {
         $order_carrier->weight = (double) $order->getTotalWeight();
         if ($order_carrier->update()) {
             $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
         }
     }
     // Update Tax lines
     $order_detail->updateTaxAmount($order);
     // Delete specific price if exists
     if (isset($specific_price)) {
         $specific_price->delete();
     }
     $products = $this->getProducts($order);
     // Get the last product
     $product = end($products);
     $resume = OrderSlip::getProductSlipResume((int) $product['id_order_detail']);
     $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
     $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
     $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']);
     $product['return_history'] = OrderReturn::getProductReturnDetail((int) $product['id_order_detail']);
     $product['refund_history'] = OrderSlip::getProductSlipDetail((int) $product['id_order_detail']);
     if ($product['id_warehouse'] != 0) {
         $warehouse = new Warehouse((int) $product['id_warehouse']);
         $product['warehouse_name'] = $warehouse->name;
     } else {
         $product['warehouse_name'] = '--';
     }
     // Get invoices collection
     $invoice_collection = $order->getInvoicesCollection();
     $invoice_array = array();
     foreach ($invoice_collection as $invoice) {
         $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop);
         $invoice_array[] = $invoice;
     }
     // Assign to smarty informations in order to show the new product line
     $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')));
     $this->sendChangedNotification($order);
     die(Tools::jsonEncode(array('result' => true, 'view' => $this->createTemplate('_product_line.tpl')->fetch(), 'can_edit' => $this->tabAccess['add'], 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'discount_form_html' => $this->createTemplate('_discount_form.tpl')->fetch())));
 }
    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)));
    }