/**
     * Creating order details of order
     * @param $neteven_order
     * @param $id_order
     * @return mixed
     */
    private function createOrderDetails($neteven_order, $id_order)
    {
        global $cookie;
        $date_now = date('Y-m-d H:i:s');
        if (in_array($neteven_order->Status, $this->getValue('t_list_order_status'))) {
            return;
        }
        // If order detail doesn't exist
        if (!($res = Db::getInstance()->getRow('SELECT * FROM `' . _DB_PREFIX_ . 'orders_gateway` WHERE `id_order_neteven` = ' . (int) $neteven_order->OrderID . ' AND `id_order_detail_neteven` = ' . (int) $neteven_order->OrderLineID))) {
            // If product exist
            $ref_temp = $neteven_order->SKU;
            $type_temp = substr($ref_temp, 0, 1);
            $id_p_temp = str_replace($type_temp, '', $ref_temp);
            $where_req = '';
            if ($type_temp == 'D') {
                $where_req = 'pa.`id_product_attribute` = ' . (int) $id_p_temp;
            }
            if ($type_temp == 'P') {
                $where_req = 'p.`id_product` = ' . (int) $id_p_temp;
            }
            if (self::$type_sku == 'reference') {
                $where_req = ' (p.`reference` = "' . pSQL($ref_temp) . '" OR pa.`reference` = "' . pSQL($ref_temp) . '") ';
            }
            if (empty($where_req)) {
                return;
            }
            $res_product = Db::getInstance()->getRow('
					SELECT pl.`name` as name_product, p.`id_product`, pa.`id_product_attribute`, p.`reference` as product_reference, pa.`reference` as product_attribute_reference, p.`weight` as weight, GROUP_CONCAT(CONCAT(agl.`name`," : ",al.`name`) SEPARATOR ", ") as attribute_name
					FROM `' . _DB_PREFIX_ . 'product` p
					INNER JOIN `' . _DB_PREFIX_ . 'product_lang` pl ON(p.`id_product` = pl.`id_product` AND pl.`id_lang` = ' . (int) $this->getValue('id_lang') . ')
					LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (pa.`id_product` = p.`id_product`)
					LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON (pac.`id_product_attribute`=pa.`id_product_attribute`)
					LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON (a.`id_attribute`=pac.`id_attribute`)
					LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON (al.`id_attribute`=a.`id_attribute` AND al.`id_lang`=' . (int) $this->getValue('id_lang') . ')
					LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON (agl.`id_attribute_group`=a.`id_attribute_group` AND agl.`id_lang`=' . (int) $this->getValue('id_lang') . ')
					WHERE p.`active` = 1 AND ' . $where_req . '
					GROUP BY pa.`id_product_attribute`, p.`id_product`
				');
            if ($res_product) {
                // Get order detail informations
                $product_reference = $res_product['product_reference'];
                $id_product_attribute = 0;
                $name = $res_product['name_product'];
                $control_attribute_product = false;
                if (!empty($res_product['id_product_attribute'])) {
                    $product_reference = $res_product['product_attribute_reference'];
                    $id_product_attribute = $res_product['id_product_attribute'];
                    if (!empty($res_product['attribute_name'])) {
                        $name .= ' - ' . $res_product['attribute_name'];
                    }
                    $control_attribute_product = true;
                }
                // Add product in cart
                $order = new Order($id_order);
                if (!Db::getInstance()->getRow('SELECT `id_cart` FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $order->id_cart . ' AND `id_product` = ' . (int) $res_product['id_product'] . ' AND `id_product_attribute` = ' . (int) $id_product_attribute)) {
                    Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'cart_product` (`id_cart`, `id_product`, `id_product_attribute`, `quantity`, `date_add`) VALUES (' . (int) $order->id_cart . ', ' . (int) $res_product['id_product'] . ', ' . (int) $id_product_attribute . ', ' . (int) $neteven_order->Quantity . ', "' . pSQL($date_now) . '")');
                }
                if ($this->time_analyse) {
                    $this->current_time_0 = time();
                    Toolbox::displayDebugMessage(self::getL('Order information') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's');
                }
                // Add order detail
                $tax = new Tax(Configuration::get('PS_TAX'), $cookie->id_lang);
                $price_product = ($neteven_order->Price->_ - floatval($neteven_order->VAT->_)) / $neteven_order->Quantity;
                $order_detail = new OrderDetail();
                $order_detail->id_order = $id_order;
                $order_detail->product_id = $res_product['id_product'];
                $order_detail->product_attribute_id = $id_product_attribute;
                $order_detail->product_name = $name;
                $order_detail->product_quantity = $neteven_order->Quantity;
                $order_detail->product_quantity_in_stock = $neteven_order->Quantity;
                $order_detail->product_quantity_refunded = 0;
                $order_detail->product_quantity_return = 0;
                $order_detail->product_quantity_reinjected = 0;
                $order_detail->product_price = number_format((double) $price_product, 4, '.', '');
                $order_detail->total_price_tax_excl = number_format((double) $price_product, 4, '.', '');
                $order_detail->unit_price_tax_incl = number_format((double) $price_product, 4, '.', '');
                $order_detail->unit_price_tax_excl = $tax->rate ? number_format((double) $price_product / ((double) $tax->rate / 100), 4, '.', '') : $price_product;
                $order_detail->reduction_percent = 0;
                $order_detail->reduction_amount = 0;
                $order_detail->group_reduction = 0;
                $order_detail->product_quantity_discount = 0;
                $order_detail->product_ean13 = NULL;
                $order_detail->product_upc = NULL;
                $order_detail->product_reference = $product_reference;
                $order_detail->product_supplier_reference = NULL;
                $order_detail->product_weight = !empty($res_product['weight']) ? (double) $res_product['weight'] : 0;
                $order_detail->tax_name = $tax->name;
                $order_detail->tax_rate = (double) $tax->rate;
                $order_detail->ecotax = 0;
                $order_detail->ecotax_tax_rate = 0;
                $order_detail->discount_quantity_applied = 0;
                $order_detail->download_hash = '';
                $order_detail->download_nb = 0;
                $order_detail->download_deadline = '0000-00-00 00:00:00';
                $order_detail->id_warehouse = 0;
                if (Configuration::get('PS_SHOP_ENABLE')) {
                    $order_detail->id_shop = (int) Configuration::get('PS_SHOP_DEFAULT');
                }
                if (!$order_detail->add()) {
                    Toolbox::addLogLine(self::getL('Failed for creation of order detail / NetEven Order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . $neteven_order->OrderLineID);
                } else {
                    if ($this->time_analyse) {
                        $this->current_time_2 = time();
                        Toolbox::displayDebugMessage(self::getL('Order detail') . ' : ' . ((int) $this->current_time_2 - (int) $this->current_time_0) . 's');
                    }
                    $id_order_detail_temp = $order_detail->id;
                    Toolbox::addLogLine(self::getL('Creation of order detail for NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID);
                    // Update quantity of product
                    if (class_exists('StockAvailable')) {
                        // Update quantity of product
                        if ($control_attribute_product) {
                            StockAvailable::setQuantity($res_product['id_product'], $id_product_attribute, StockAvailable::getQuantityAvailableByProduct($res_product['id_product'], $id_product_attribute) - $neteven_order->Quantity);
                        } else {
                            StockAvailable::setQuantity($res_product['id_product'], 0, StockAvailable::getQuantityAvailableByProduct($res_product['id_product']) - $neteven_order->Quantity);
                        }
                    } else {
                        $t_info_product = array();
                        $t_info_product['id_product'] = $res_product["id_product"];
                        $t_info_product['cart_quantity'] = $neteven_order->Quantity;
                        $t_info_product['id_product_attribute'] = NULL;
                        if ($control_attribute_product) {
                            $t_info_product['id_product_attribute'] = $id_product_attribute;
                        }
                        Product::updateQuantity($t_info_product);
                    }
                    if ($this->time_analyse) {
                        $this->current_time_0 = time();
                        Toolbox::displayDebugMessage(self::getL('Cart product') . ' : ' . ((int) $this->current_time_0 - (int) $this->current_time_2) . 's');
                    }
                    // Insert order in orders_gateway table
                    if (!Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'orders_gateway` (`id_order_neteven`, `id_order`, `id_order_detail_neteven`, `date_add`, `date_upd`) VALUES (' . (int) $neteven_order->OrderID . ', ' . (int) $id_order . ', ' . (int) $neteven_order->OrderLineID . ', "' . pSQL($date_now) . '", "' . pSQL($date_now) . '")')) {
                        Toolbox::addLogLine(self::getL('Failed for save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID);
                    } else {
                        Toolbox::addLogLine(self::getL('Save export NetEven order Id') . ' ' . (int) $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . (int) $neteven_order->OrderLineID);
                    }
                }
            }
        } else {
            Toolbox::addLogLine(self::getL('Failed for creation of order detail of NetEven order Id') . $neteven_order->OrderID . ' ' . self::getL('NetEven order detail id') . ' ' . $neteven_order->OrderLineID . ' ' . self::getL('Product not found SKU') . ' ' . $neteven_order->SKU);
        }
        $order = new Order($id_order);
        $products = $order->getProductsDetail();
        if (count($products) == 0 && $this->getValue('mail_active')) {
            $this->sendDebugMail($this->getValue('mail_list_alert'), self::getL('Order imported is empty'), self::getL('Order Id') . ' ' . (int) $order->id);
        }
    }
示例#2
0
 /**
  * @global object $cookie Employee cookie necessary to keep trace of his/her actions
  */
 public function postProcess()
 {
     global $currentIndex, $cookie;
     /* Update shipping number */
     if (Tools::isSubmit('submitShippingNumber') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) {
         if ($this->tabAccess['edit'] === '1') {
             if (!$order->hasBeenShipped()) {
                 die(Tools::displayError('The shipping number can only be set once the order has been shipped.'));
             }
             $_GET['view' . $this->table] = true;
             $shipping_number = pSQL(Tools::getValue('shipping_number'));
             $order->shipping_number = $shipping_number;
             $order->update();
             if ($shipping_number) {
                 global $_LANGMAIL;
                 $customer = new Customer((int) $order->id_customer);
                 $carrier = new Carrier((int) $order->id_carrier);
                 if (!Validate::isLoadedObject($customer) or !Validate::isLoadedObject($carrier)) {
                     die(Tools::displayError());
                 }
                 $templateVars = array('{order_amount}' => Tools::displayPrice($order->total_paid, $currency, false), '{carrier_name}' => $carrier->name, '{tracking_number}' => $order->shipping_number, '{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => (int) $order->id);
                 if (strpos($order->payment, 'COD') === false) {
                     @Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Your order #' . $order->id . ' with IndusDiva.com has been shipped'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                 } else {
                     @Mail::Send((int) $order->id_lang, 'in_transit_cod', Mail::l('Your order #' . $order->id . ' with IndusDiva.com has been shipped'), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                 }
                 //Send SMS
                 $delivery = new Address((int) $order->id_address_delivery);
                 if (strpos($order->payment, 'COD') === false) {
                     $smsText = 'Dear customer, your order #' . $order->id . ' at IndusDiva.com has been shipped via ' . $carrier->name . '. The airway bill no is ' . $order->shipping_number . '. www.indusdiva.com';
                 } else {
                     $smsText = 'Dear customer, your order #' . $order->id . ' at IndusDiva.com has been shipped. Carrier: ' . $carrier->name . ', AWB No. : ' . $order->shipping_number . ', Amount payable:' . Tools::displayPrice($order->total_paid, $currency, false) . '. www.indusdiva.com';
                 }
                 Tools::sendSMS($delivery->phone_mobile, $smsText);
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
         }
     } elseif (Tools::isSubmit('submitExpectedShippingDate') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) {
         $dateshipping = new DateTime(Tools::getValue('expected_shipping_date'));
         $order->expected_shipping_date = pSQL($dateshipping->format('Y-m-d H:i:s'));
         $order->update();
         $order = new Order($id_order);
     } elseif (Tools::isSubmit('submitCarrier') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) {
         $order->shipping_number = '';
         $order->id_carrier = (int) Tools::getValue('id_carrier');
         $order->update();
         $order = new Order($id_order);
     } elseif (Tools::isSubmit('submitState') and $id_order = (int) Tools::getValue('id_order') and Validate::isLoadedObject($order = new Order($id_order))) {
         if ($this->tabAccess['edit'] === '1') {
             $_GET['view' . $this->table] = true;
             if (!($newOrderStatusId = (int) Tools::getValue('id_order_state'))) {
                 $this->_errors[] = Tools::displayError('Invalid new order status');
             } else {
                 if ($newOrderStatusId == _PS_OS_DELIVERED_ && strpos($order->payment, 'COD')) {
                     $paymentHistory = new OrderPaymentHistory();
                     $paymentHistory->id_order = (int) $id_order;
                     $paymentHistory->id_employee = (int) $cookie->id_employee;
                     $paymentHistory->changeIdOrderPaymentState(_PS_PS_PAYMENT_WITH_CARRIER_, (int) $id_order);
                     $paymentHistory->addState();
                 }
                 $history = new OrderHistory();
                 $history->id_order = (int) $id_order;
                 $history->id_employee = (int) $cookie->id_employee;
                 $history->changeIdOrderState((int) $newOrderStatusId, (int) $id_order);
                 $order = new Order((int) $order->id);
                 $carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang);
                 $templateVars = array();
                 if ($history->id_order_state == _PS_OS_SHIPPING_ and $order->shipping_number) {
                     $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
                 } elseif ($history->id_order_state == _PS_OS_CHEQUE_) {
                     $templateVars = array('{cheque_name}' => Configuration::get('CHEQUE_NAME') ? Configuration::get('CHEQUE_NAME') : '', '{cheque_address_html}' => Configuration::get('CHEQUE_ADDRESS') ? nl2br(Configuration::get('CHEQUE_ADDRESS')) : '');
                 } elseif ($history->id_order_state == _PS_OS_BANKWIRE_) {
                     $templateVars = array('{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER') ? Configuration::get('BANK_WIRE_OWNER') : '', '{bankwire_details}' => Configuration::get('BANK_WIRE_DETAILS') ? nl2br(Configuration::get('BANK_WIRE_DETAILS')) : '', '{bankwire_address}' => Configuration::get('BANK_WIRE_ADDRESS') ? nl2br(Configuration::get('BANK_WIRE_ADDRESS')) : '');
                 }
                 if ($history->id_order_state == _PS_OS_CANCELED_) {
                     $this->cancelOrder($id_order);
                 }
                 if ($history->addWithemail(true, $templateVars)) {
                     Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder' . '&token=' . $this->token);
                 }
                 $this->_errors[] = Tools::displayError('An error occurred while changing the status or was unable to send e-mail to the customer.');
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
         }
     } elseif (isset($_POST['submitMessage'])) {
         $_GET['view' . $this->table] = true;
         if ($this->tabAccess['edit'] === '1') {
             if (!($id_order = (int) Tools::getValue('id_order')) or !($id_customer = (int) Tools::getValue('id_customer'))) {
                 $this->_errors[] = Tools::displayError('An error occurred before sending message');
             } elseif (!Tools::getValue('message')) {
                 $this->_errors[] = Tools::displayError('Message cannot be blank');
             } else {
                 /* Get message rules and and check fields validity */
                 $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
                 foreach ($rules['required'] as $field) {
                     if (($value = Tools::getValue($field)) == false and (string) $value != '0') {
                         if (!Tools::getValue('id_' . $this->table) or $field != 'passwd') {
                             $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required.');
                         }
                     }
                 }
                 foreach ($rules['size'] as $field => $maxLength) {
                     if (Tools::getValue($field) and Tools::strlen(Tools::getValue($field)) > $maxLength) {
                         $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is too long.') . ' (' . $maxLength . ' ' . Tools::displayError('chars max') . ')';
                     }
                 }
                 foreach ($rules['validate'] as $field => $function) {
                     if (Tools::getValue($field)) {
                         if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
                             $this->_errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is invalid.');
                         }
                     }
                 }
                 if (!sizeof($this->_errors)) {
                     $message = new Message();
                     $message->id_employee = (int) $cookie->id_employee;
                     $message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8');
                     $message->id_order = $id_order;
                     $message->private = Tools::getValue('visibility');
                     if (!$message->add()) {
                         $this->_errors[] = Tools::displayError('An error occurred while sending message.');
                     } elseif ($message->private) {
                         Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token);
                     } elseif (Validate::isLoadedObject($customer = new Customer($id_customer))) {
                         $order = new Order((int) $message->id_order);
                         if (Validate::isLoadedObject($order)) {
                             $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message));
                             if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order'), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                                 Tools::redirectAdmin($currentIndex . '&id_order=' . $id_order . '&vieworder&conf=11' . '&token=' . $this->token);
                             }
                         }
                     }
                     $this->_errors[] = Tools::displayError('An error occurred while sending e-mail to customer.');
                 }
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
         }
     } elseif (Tools::isSubmit('cancelProduct') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) {
         if ($this->tabAccess['delete'] === '1') {
             $productList = Tools::getValue('id_order_detail');
             $customizationList = Tools::getValue('id_customization');
             $qtyList = Tools::getValue('cancelQuantity');
             $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
             $full_product_list = $productList;
             $full_quantity_list = $qtyList;
             if ($customizationList) {
                 foreach ($customizationList as $key => $id_order_detail) {
                     $full_product_list[$id_order_detail] = $id_order_detail;
                     $full_quantity_list[$id_order_detail] = $customizationQtyList[$key];
                 }
             }
             if ($productList or $customizationList) {
                 if ($productList) {
                     $id_cart = Cart::getCartIdByOrderId($order->id);
                     $customization_quantities = Customization::countQuantityByCart($id_cart);
                     foreach ($productList as $key => $id_order_detail) {
                         $qtyCancelProduct = abs($qtyList[$key]);
                         if (!$qtyCancelProduct) {
                             $this->_errors[] = Tools::displayError('No quantity selected for product.');
                         }
                         // check actionable quantity
                         $order_detail = new OrderDetail($id_order_detail);
                         $customization_quantity = 0;
                         if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) {
                             $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id];
                         }
                         if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) {
                             $this->_errors[] = Tools::displayError('Invalid quantity selected for product.');
                         }
                     }
                 }
                 if ($customizationList) {
                     $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
                     foreach ($customizationList as $id_customization => $id_order_detail) {
                         $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                         $customization_quantity = $customization_quantities[$id_customization];
                         if (!$qtyCancelProduct) {
                             $this->_errors[] = Tools::displayError('No quantity selected for product.');
                         }
                         if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) {
                             $this->_errors[] = Tools::displayError('Invalid quantity selected for product.');
                         }
                     }
                 }
                 if (!sizeof($this->_errors) and $productList) {
                     foreach ($productList as $key => $id_order_detail) {
                         $qtyCancelProduct = abs($qtyList[$key]);
                         $orderDetail = new OrderDetail((int) $id_order_detail);
                         // Reinject product
                         if (!$order->hasBeenDelivered() or $order->hasBeenDelivered() and Tools::isSubmit('reinjectQuantities')) {
                             $reinjectableQuantity = (int) $orderDetail->product_quantity - (int) $orderDetail->product_quantity_reinjected;
                             $quantityToReinject = $qtyCancelProduct > $reinjectableQuantity ? $reinjectableQuantity : $qtyCancelProduct;
                             if (!Product::reinjectQuantities($orderDetail, $quantityToReinject)) {
                                 $this->_errors[] = Tools::displayError('Cannot re-stock product') . ' <span class="bold">' . $orderDetail->product_name . '</span>';
                             } else {
                                 $updProductAttributeID = !empty($orderDetail->product_attribute_id) ? (int) $orderDetail->product_attribute_id : NULL;
                                 $newProductQty = Product::getQuantity((int) $orderDetail->product_id, $updProductAttributeID);
                                 $product = get_object_vars(new Product((int) $orderDetail->product_id, false, (int) $cookie->id_lang));
                                 if (!empty($orderDetail->product_attribute_id)) {
                                     $updProduct['quantity_attribute'] = (int) $newProductQty;
                                     $product['quantity_attribute'] = $updProduct['quantity_attribute'];
                                 } else {
                                     $updProduct['stock_quantity'] = (int) $newProductQty;
                                     $product['stock_quantity'] = $updProduct['stock_quantity'];
                                 }
                                 Hook::updateQuantity($product, $order);
                             }
                         }
                         // Delete product
                         if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct)) {
                             $this->_errors[] = Tools::displayError('An error occurred during deletion of the product.') . ' <span class="bold">' . $orderDetail->product_name . '</span>';
                         }
                         Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail));
                     }
                 }
                 if (!sizeof($this->_errors) and $customizationList) {
                     foreach ($customizationList as $id_customization => $id_order_detail) {
                         $orderDetail = new OrderDetail((int) $id_order_detail);
                         $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                         if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail)) {
                             $this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.') . ' ' . $id_customization;
                         }
                     }
                 }
                 // E-mail params
                 if ((isset($_POST['generateCreditSlip']) or isset($_POST['generateDiscount'])) and !sizeof($this->_errors)) {
                     $customer = new Customer((int) $order->id_customer);
                     $params['{lastname}'] = $customer->lastname;
                     $params['{firstname}'] = $customer->firstname;
                     $params['{id_order}'] = $order->id;
                 }
                 // Generate credit slip
                 if (isset($_POST['generateCreditSlip']) and !sizeof($this->_errors)) {
                     if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, isset($_POST['shippingBack']))) {
                         $this->_errors[] = Tools::displayError('Cannot generate credit slip');
                     } else {
                         Module::hookExec('orderSlip', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list));
                         @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                     }
                 }
                 // Generate voucher
                 if (isset($_POST['generateDiscount']) and !sizeof($this->_errors)) {
                     if (!($voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Credit Slip concerning the order #'), isset($_POST['shippingBack'])))) {
                         $this->_errors[] = Tools::displayError('Cannot generate voucher');
                     } else {
                         $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
                         $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
                         $params['{voucher_num}'] = $voucher->name;
                         @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order'), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                     }
                 }
             } else {
                 $this->_errors[] = Tools::displayError('No product or quantity selected.');
             }
             // Redirect if no errors
             if (!sizeof($this->_errors)) {
                 Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token);
             }
         } else {
             $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
         }
     } elseif (Tools::isSubmit('updateOrder') and Validate::isLoadedObject($order = new Order((int) Tools::getValue('id_order')))) {
         $cart = Cart::getCartByOrderId($order->id);
         $update = false;
         if ($discountValue = Tools::getValue('addDiscount')) {
             $discountVoucher = new Discount();
             $discountVoucher->name = 'ADMIND-' . $order->id . date('mdHis');
             $discountVoucher->id_discount_type = 2;
             $discountVoucher->id_customer = $order->id_customer;
             $discountVoucher->cumulable = 1;
             $discountVoucher->cumulable_reduction = 1;
             $discountVoucher->date_from = $order->date_add;
             $discountVoucher->date_to = date('Y-m-d', time() + 86400);
             $discountVoucher->quantity = 1;
             $discountVoucher->quantity_per_user = 1;
             $discountVoucher->value = (double) $discountValue;
             $discountVoucher->minimal = 0;
             $discountVoucher->id_currency = 4;
             $discountVoucher->behavior_not_exhausted = 1;
             $discountVoucher->add(true);
             $cart->addDiscount($discountVoucher->id);
             $order->addDiscount($discountVoucher->id, $discountVoucher->name, $discountVoucher->value);
             $cart->update();
             $update = true;
         }
         //waive shipping, create a free shipping voucher, apply, reload the order object
         if (Tools::getValue('waiveShipping')) {
             $freeShipVoucher = new Discount();
             $freeShipVoucher->name = 'ADMINFS-' . $order->id . date('mdHis');
             $freeShipVoucher->id_discount_type = 3;
             $freeShipVoucher->id_customer = $order->id_customer;
             $freeShipVoucher->cumulable = 1;
             $freeShipVoucher->cumulable_reduction = 1;
             $freeShipVoucher->date_from = $order->date_add;
             $freeShipVoucher->date_to = date('Y-m-d', time() + 86400);
             $freeShipVoucher->quantity = 0;
             $freeShipVoucher->quantity_per_user = 1;
             $freeShipVoucher->value = 0;
             $freeShipVoucher->add(true);
             $cart->addDiscount($freeShipVoucher->id);
             $order->addDiscount($freeShipVoucher->id, $freeShipVoucher->name, $freeShipVoucher->value);
             $cart->update();
             $update = true;
         }
         $id_product = false;
         if ($id_product = Tools::getValue('addProductID')) {
             $product = new Product((int) $id_product, true, (int) $cookie->id_lang);
             if ($product->quantity > 0 && $product->available_for_order) {
                 $cart->updateQty(1, $id_product);
             }
             $orderDetail = null;
             $db = Db::getInstance();
             $res = $db->getRow('select id_order_detail from ps_order_detail where id_order = ' . $order->id . ' and product_id = ' . $id_product);
             $vat_address = new Address((int) $order->id_address_delivery);
             $customer = new Customer((int) $order->id_customer);
             $unitPrice = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             if ($res) {
                 $orderDetail = new OrderDetail($res['id_order_detail']);
                 $orderDetail->product_quantity = $orderDetail->product_quantity + 1;
             } else {
                 $productName = $product->name;
                 $orderDetail = new OrderDetail();
                 $orderDetail->product_quantity = 1;
                 $orderDetail->id_order = $order->id;
                 $orderDetail->product_id = $id_product;
                 $orderDetail->product_name = $productName;
                 $orderDetail->product_ean13 = $product->ean13;
                 $price = Product::getPriceStatic($id_product, false, NULL, 6, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                 $price_wt = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                 $tax_rate = Tax::getProductTaxRate((int) $id_product, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                 $specificPrice = 0;
                 $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $id_product, Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, $orderDetail->product_quantity);
                 $orderDetail->product_price = (double) Product::getPriceStatic((int) $id_product, false, NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE);
                 $orderDetail->product_quantity_discount = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
                 $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0);
                 $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0);
                 $orderDetail->tax_rate = $tax_rate;
                 $orderDetail->tax_name = 'default_tax';
                 $orderDetail->group_reduction = 0;
                 $orderDetail->product_quantity_in_stock = (int) Product::getQuantity((int) $id_product, NULL);
                 $orderDetail->product_quantity_refunded = 0;
                 $orderDetail->product_quantity_reinjected = 0;
                 $orderDetail->ecotax = 0;
                 $orderDetail->ecotax_tax_rate = 0;
                 $orderDetail->discount_quantity_applied = 0;
                 $orderDetail->add(true, true);
             }
             $price = Product::getPriceStatic($id_product, false, NULL, 6, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $price_wt = Product::getPriceStatic((int) $id_product, true, NULL, 2, NULL, false, true, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $tax_rate = Tax::getProductTaxRate((int) $id_product, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $id_product, Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, $orderDetail->product_quantity);
             $orderDetail->product_price = (double) Product::getPriceStatic((int) $id_product, false, NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $orderDetail->product_quantity, false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE);
             $orderDetail->product_quantity_discount = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
             $orderDetail->reduction_percent = (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0);
             $orderDetail->reduction_amount = (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0);
             $orderDetail->update();
             $product->addStockMvt(-1, _STOCK_MOVEMENT_ORDER_REASON_, NULL, $order->id, (int) $cookie->id_employee);
             $update = true;
         }
         if ($update) {
             //Recalculate product prices with and without tax from order detail
             $detailIds = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
                     SELECT id_order_detail
                     FROM `' . _DB_PREFIX_ . 'order_detail` od
                     WHERE od.`id_order` = ' . (int) $order->id);
             $totalProducts = 0.0;
             $totalProductsWT = 0.0;
             foreach ($detailIds as $id) {
                 $reduction_amount = 0.0;
                 $orderDetail = new OrderDetail($id['id_order_detail']);
                 $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.0) {
                     $reduction_amount = Tools::ps_round($orderDetail->reduction_amount, 2);
                 }
                 if (isset($reduction_amount) and $reduction_amount) {
                     $price = Tools::ps_round($price - $reduction_amount, 2);
                 }
                 $productPriceWithoutTax = $price / (1 + $orderDetail->tax_rate * 0.01);
                 //Update order
                 $totalProducts += $orderDetail->product_quantity * $productPriceWithoutTax;
                 $totalProductsWT += $orderDetail->product_quantity * $price;
             }
             $order->total_products = Tools::ps_round($totalProducts, 2);
             $order->total_products_wt = Tools::ps_round($totalProductsWT, 2);
             $order->total_shipping = $cart->getOrderShippingCost();
             //$order->total_products = $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order->total_discounts = abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
             $order->total_paid = $order->total_products_wt + $order->total_shipping - $order->total_discounts + $order->total_cod;
             $order->total_paid_real = $order->total_products_wt + $order->total_shipping - $order->total_discounts + $order->total_cod;
             //$order->total_products_wt = (float)($cart->getOrderTotal(true, Cart::ONLY_PRODUCTS));
             $order->update();
         }
         // Redirect if no errors
         if (!sizeof($this->_errors)) {
             Tools::redirectAdmin($currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token);
         }
     } elseif (isset($_GET['messageReaded'])) {
         Message::markAsReaded((int) $_GET['messageReaded'], (int) $cookie->id_employee);
     }
     parent::postProcess();
 }