Advertisement
Guest User

AdminControllers

a guest
Sep 7th, 2016
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 61.42 KB | None | 0 0
  1. <?php
  2.  
  3. class AdminOrdersController extends AdminOrdersControllerCore
  4. {
  5.     /*
  6.     * module: customerportfolio
  7.     * date: 2016-09-06 11:13:35
  8.     * version: 1.5
  9.     */
  10.     public function __construct()
  11.     {
  12.         $this->bootstrap = true;
  13.         $this->table = 'order';
  14.         $this->className = 'Order';
  15.         $this->lang = false;
  16.         $this->addRowAction('view');
  17.         $this->explicitSelect = true;
  18.         $this->deleted = false;
  19.         $this->context = Context::getContext();
  20.         $this->_select = '
  21.         a.id_currency,
  22.         a.id_order AS id_pdf,
  23.         CONCAT(LEFT(c.`firstname`, 1), \'. \', c.`lastname`) AS `customer`,
  24.         osl.`name` AS `osname`,
  25.         os.`color`,
  26.         IF((SELECT COUNT(so.id_order) FROM `'._DB_PREFIX_.'orders` so WHERE so.id_customer = a.id_customer) > 1, 0, 1) as new';
  27.         $this->_join = '
  28.         LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = a.`id_customer`)
  29.         LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = a.`current_state`)
  30.         LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)$this->context->language->id.')';
  31.         if ($this->context->cookie->profile == Configuration::get('CUSTOMER_PORTFOLIO_PROFIL'))
  32.         {
  33.             $this->_join = $this->_join.'
  34.             LEFT JOIN `'._DB_PREFIX_.'portfolio_customer_employee` pce ON (pce.`id_customer` = a.`id_customer`)';
  35.             $this->_where = ' AND pce.`id_employee` = '.$this->context->cookie->id_employee.' ';
  36.         }
  37.         $this->_orderBy = 'id_order';
  38.         $this->_orderWay = 'DESC';
  39.         $statuses_array = array();
  40.         $statuses = OrderState::getOrderStates((int)$this->context->language->id);
  41.         foreach ($statuses as $status)
  42.             $statuses_array[$status['id_order_state']] = $status['name'];
  43.         $this->fields_list = array(
  44.         'id_order' => array(
  45.             'title' => $this->l('ID'),
  46.             'align' => 'center',
  47.             'width' => 25
  48.         ),
  49.         'reference' => array(
  50.             'title' => $this->l('Reference'),
  51.             'align' => 'center',
  52.             'width' => 65
  53.         ),
  54.         'new' => array(
  55.             'title' => $this->l('New'),
  56.             'width' => 25,
  57.             'align' => 'center',
  58.             'type' => 'bool',
  59.             'tmpTableFilter' => true,
  60.             'icon' => array(
  61.                 0 => 'blank.gif',
  62.                 1 => array(
  63.                     'src' => 'note.png',
  64.                     'alt' => $this->l('First customer order'),
  65.                 )
  66.             ),
  67.             'orderby' => false
  68.         ),
  69.         'customer' => array(
  70.             'title' => $this->l('Customer'),
  71.             'havingFilter' => true,
  72.         ),
  73.         'total_paid_tax_incl' => array(
  74.             'title' => $this->l('Total'),
  75.             'width' => 70,
  76.             'align' => 'right',
  77.             'prefix' => '<b>',
  78.             'suffix' => '</b>',
  79.             'type' => 'price',
  80.             'currency' => true
  81.         ),
  82.         'payment' => array(
  83.             'title' => $this->l('Payment'),
  84.             'width' => 100
  85.         ),
  86.         'osname' => array(
  87.             'title' => $this->l('Status'),
  88.             'color' => 'color',
  89.             'width' => 280,
  90.             'type' => 'select',
  91.             'list' => $statuses_array,
  92.             'filter_key' => 'os!id_order_state',
  93.             'filter_type' => 'int'
  94.         ),
  95.         'date_add' => array(
  96.             'title' => $this->l('Date'),
  97.             'width' => 130,
  98.             'align' => 'right',
  99.             'type' => 'datetime',
  100.             'filter_key' => 'a!date_add'
  101.         ),
  102.         'id_pdf' => array(
  103.             'title' => $this->l('PDF'),
  104.             'width' => 35,
  105.             'align' => 'center',
  106.             'callback' => 'printPDFIcons',
  107.             'orderby' => false,
  108.             'search' => false,
  109.             'remove_onclick' => true)
  110.         );
  111.         $this->shopLinkType = 'shop';
  112.         $this->shopShareDatas = Shop::SHARE_ORDER;
  113.         if (Tools::isSubmit('id_order'))
  114.         {
  115.             $order = new Order((int)Tools::getValue('id_order'));
  116.             if (!Validate::isLoadedObject($order))
  117.                 throw new PrestaShopException('Cannot load Order object');
  118.             $this->context->cart = new Cart($order->id_cart);
  119.             $this->context->customer = new Customer($order->id_customer);
  120.         }
  121.         AdminController::__construct();
  122.     }
  123.     /*
  124.     * module: customerportfolio
  125.     * date: 2016-09-06 11:13:35
  126.     * version: 1.5
  127.     */
  128.     public function renderView()
  129.     {
  130.         $order = new Order(Tools::getValue('id_order'));
  131.         if (!Validate::isLoadedObject($order))
  132.             throw new PrestaShopException('object can\'t be loaded');
  133.         if ($this->context->cookie->profile == Configuration::get('CUSTOMER_PORTFOLIO_PROFIL') && !empty($order->id_customer))
  134.         {
  135.             $check_access = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'portfolio_customer_employee`
  136.                                                         WHERE id_customer = '.$order->id_customer.' AND `id_employee` = '.$this->context->cookie->id_employee.';');
  137.             if (empty($check_access))
  138.             {
  139.                 $this->errors[] = $this->l('Access denied.');
  140.                 return;
  141.             }
  142.         }
  143.         $customer = new Customer($order->id_customer);
  144.         $carrier = new Carrier($order->id_carrier);
  145.         $products = $this->getProducts($order);
  146.         $currency = new Currency((int)$order->id_currency);
  147.         $carrier_module_call = null;
  148.         if ($carrier->is_module)
  149.         {
  150.             $module = Module::getInstanceByName($carrier->external_module_name);
  151.             if (method_exists($module, 'displayInfoByCart'))
  152.                 $carrier_module_call = call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
  153.         }
  154.         $addressInvoice = new Address($order->id_address_invoice, $this->context->language->id);
  155.         if (Validate::isLoadedObject($addressInvoice) && $addressInvoice->id_state)
  156.             $invoiceState = new State((int)$addressInvoice->id_state);
  157.         if ($order->id_address_invoice == $order->id_address_delivery)
  158.         {
  159.             $addressDelivery = $addressInvoice;
  160.             if (isset($invoiceState))
  161.                 $deliveryState = $invoiceState;
  162.         }
  163.         else
  164.         {
  165.             $addressDelivery = new Address($order->id_address_delivery, $this->context->language->id);
  166.             if (Validate::isLoadedObject($addressDelivery) && $addressDelivery->id_state)
  167.                 $deliveryState = new State((int)$addressDelivery->id_state);
  168.         }
  169.         $this->toolbar_title = sprintf($this->l('Order #%1$d (%2$s) - %3$s %4$s'), $order->id, $order->reference, $customer->firstname, $customer->lastname);
  170.         $warehouse_list = null;
  171.         $order_details = $order->getOrderDetailList();
  172.         foreach ($order_details as $order_detail)
  173.         {
  174.             $product = new Product($order_detail['product_id']);
  175.             if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management)
  176.             {
  177.                 $warehouses = Warehouse::getWarehousesByProductId($order_detail['product_id'], $order_detail['product_attribute_id']);
  178.                 foreach ($warehouses as $warehouse)
  179.                     if (!isset($warehouse_list[$warehouse['id_warehouse']]))
  180.                         $warehouse_list[$warehouse['id_warehouse']] = $warehouse;
  181.             }
  182.         }
  183.         $payment_methods = array();
  184.         foreach (PaymentModule::getInstalledPaymentModules() as $payment)
  185.         {
  186.             $module = Module::getInstanceByName($payment['name']);
  187.             if (Validate::isLoadedObject($module))
  188.                 $payment_methods[] = $module->displayName;
  189.         }
  190.         $display_out_of_stock_warning = false;
  191.         $current_order_state = $order->getCurrentOrderState();
  192.         if ($current_order_state->delivery != 1 && $current_order_state->shipped != 1)
  193.             $display_out_of_stock_warning = true;
  194.         foreach ($products as &$product)
  195.         {
  196.             $product['current_stock'] = StockAvailable::getQuantityAvailableByProduct($product['product_id'], $product['product_attribute_id'], $product['id_shop']);
  197.             $resume = OrderSlip::getProductSlipResume($product['id_order_detail']);
  198.             $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
  199.             $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
  200.             $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl'], $currency);
  201.             $product['refund_history'] = OrderSlip::getProductSlipDetail($product['id_order_detail']);
  202.             $product['return_history'] = OrderReturn::getProductReturnDetail($product['id_order_detail']);
  203.             if ($product['current_stock'] == 0 && $display_out_of_stock_warning)
  204.                 $this->displayWarning($this->l('This product is out of stock: ').' '.$product['product_name']);
  205.         }
  206.         if ($this->context->cookie->profile == Configuration::get('CUSTOMER_PORTFOLIO_PROFIL'))
  207.         {
  208.             $previous = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders o, '._DB_PREFIX_.'portfolio_customer_employee pce WHERE pce.id_customer=o.id_customer AND pce.id_employee='.$this->context->cookie->id_employee.' AND o.id_order < '.(int)$order->id.' ORDER BY o.id_order DESC');
  209.             $next = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders o, '._DB_PREFIX_.'portfolio_customer_employee pce WHERE pce.id_customer=o.id_customer AND pce.id_employee='.$this->context->cookie->id_employee.' AND o.id_order > '.(int)$order->id.' ORDER BY o.id_order ASC');
  210.         }
  211.         else
  212.         {
  213.             $previous = $order->getPreviousOrderId();
  214.             $next = $order->getNextOrderId();
  215.         }
  216.         $this->tpl_view_vars = array(
  217.             'order' => $order,
  218.             'cart' => new Cart($order->id_cart),
  219.             'customer' => $customer,
  220.             'customer_addresses' => $customer->getAddresses($this->context->language->id),
  221.             'addresses' => array(
  222.                 'delivery' => $addressDelivery,
  223.                 'deliveryState' => isset($deliveryState) ? $deliveryState : null,
  224.                 'invoice' => $addressInvoice,
  225.                 'invoiceState' => isset($invoiceState) ? $invoiceState : null
  226.             ),
  227.             'customerStats' => $customer->getStats(),
  228.             'products' => $products,
  229.             'discounts' => $order->getCartRules(),
  230.             'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), // Get the sum of total_paid_tax_incl of the order with similar reference
  231.             'total_paid' => $order->getTotalPaid(),
  232.             'returns' => OrderReturn::getOrdersReturn($order->id_customer, $order->id),
  233.             'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, 0),
  234.             'orderMessages' => OrderMessage::getOrderMessages($order->id_lang),
  235.             'messages' => Message::getMessagesByOrderId($order->id, true),
  236.             'carrier' => new Carrier($order->id_carrier),
  237.             'history' => $order->getHistory($this->context->language->id),
  238.             'states' => OrderState::getOrderStates($this->context->language->id),
  239.             'warehouse_list' => $warehouse_list,
  240.             'sources' => ConnectionsSource::getOrderSources($order->id),
  241.             'currentState' => $order->getCurrentOrderState(),
  242.             'currency' => new Currency($order->id_currency),
  243.             'currencies' => Currency::getCurrencies(),
  244.             'previousOrder' => $previous,
  245.             'nextOrder' => $next,
  246.             'current_index' => self::$currentIndex,
  247.             'carrierModuleCall' => $carrier_module_call,
  248.             'iso_code_lang' => $this->context->language->iso_code,
  249.             'id_lang' => $this->context->language->id,
  250.             'can_edit' => ($this->tabAccess['edit'] == 1),
  251.             'current_id_lang' => $this->context->language->id,
  252.             'invoices_collection' => $order->getInvoicesCollection(),
  253.             'not_paid_invoices_collection' => $order->getNotPaidInvoicesCollection(),
  254.             'payment_methods' => $payment_methods,
  255.             'invoice_management_active' => Configuration::get('PS_INVOICE')
  256.         );
  257.         return AdminController::renderView();
  258.     }
  259.    
  260.     /*
  261.     * module: customerportfolio
  262.     * date: 2016-09-06 11:13:35
  263.     * version: 1.5
  264.     */
  265.     public function ajaxProcessSearchCustomers()
  266.     {
  267.         if ($this->context->cookie->profile == Configuration::get('CUSTOMER_PORTFOLIO_PROFIL'))
  268.         {
  269.             $sql = 'SELECT c.*
  270.                     FROM `'._DB_PREFIX_.'customer` c, `'._DB_PREFIX_.'portfolio_customer_employee` pce
  271.                     WHERE pce.`id_customer`=c.`id_customer` AND pce.`id_employee`='.$this->context->cookie->id_employee.' AND
  272.                             (c.`email` LIKE \'%'.pSQL(Tools::getValue('customer_search')).'%\'
  273.                             OR c.`id_customer` LIKE \'%'.pSQL(Tools::getValue('customer_search')).'%\'
  274.                             OR c.`lastname` LIKE \'%'.pSQL(Tools::getValue('customer_search')).'%\'
  275.                             OR c.`firstname` LIKE \'%'.pSQL(Tools::getValue('customer_search')).'%\'
  276.                         )'.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER);
  277.             $customers = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
  278.         }
  279.         else
  280.             $customers = Customer::searchByName(pSQL(Tools::getValue('customer_search')));
  281.         if ($customers)
  282.             $to_return = array('customers' => $customers, 'found' => true);
  283.         else
  284.             $to_return = array('found' => false);
  285.         $this->content = Tools::jsonEncode($to_return);
  286.     }
  287.         if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
  288.             $order = new Order(Tools::getValue('id_order'));
  289.             if (!Validate::isLoadedObject($order)) {
  290.                 throw new PrestaShopException('Can\'t load Order object');
  291.             }
  292.         }
  293.        
  294.         if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
  295.             if ($this->tabAccess['edit'] === '1') {
  296.                 $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
  297.                 if (!Validate::isLoadedObject($order_carrier)) {
  298.                     $this->errors[] = Tools::displayError('Order carrier ID is invalid');
  299.                 } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
  300.                     $this->errors[] = Tools::displayError('Tracking number is incorrect');
  301.                 } else {
  302.                     $order->shipping_number = Tools::getValue('tracking_number');
  303.                     $order->update();
  304.                     $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
  305.                     if ($order_carrier->update()) {
  306.                         $customer = new Customer((int) $order->id_customer);
  307.                         $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
  308.                         if (!Validate::isLoadedObject($customer)) {
  309.                             throw new PrestaShopException('Can\'t load Customer object');
  310.                         }
  311.                        
  312.                         if (!Validate::isLoadedObject($carrier)) {
  313.                             throw new PrestaShopException('Can\'t load Carrier object');
  314.                         }
  315.                        
  316.                         $templateVars = array(
  317.                             '{followup}' => str_replace('@', $order->shipping_number, $carrier->url),
  318.                             '{firstname}' => $customer->firstname,
  319.                             '{lastname}' => $customer->lastname,
  320.                             '{id_order}' => $order->id
  321.                         );
  322.                         if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, TRUE)) {
  323.                             Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order));
  324.                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
  325.                         } else {
  326.                             $this->errors[] = Tools::displayError('An error occurred while sending e-mail to the customer.');
  327.                         }    
  328.                     } else {
  329.                         $this->errors[] = Tools::displayError('Order carrier can\'t be updated');
  330.                     }
  331.                 }
  332.             } else {
  333.                 $this->errors[] = Tools::displayError('You do not have permission to edit here.');
  334.             }    
  335.         } elseif (Tools::isSubmit('submitState') && isset($order)) {
  336.            
  337.             if ($this->tabAccess['edit'] === '1') {
  338.                 $order_state = new OrderState(Tools::getValue('id_order_state'));
  339.                 if (!Validate::isLoadedObject($order_state)) {
  340.                     $this->errors[] = Tools::displayError('Invalid new order status');
  341.                 } else {
  342.                     $current_order_state = $order->getCurrentOrderState();
  343.                     if ($current_order_state->id != $order_state->id) {
  344.                         $history = new OrderHistory();
  345.                         $history->id_order = $order->id;
  346.                         $history->id_employee = (int) $this->context->employee->id;
  347.                         $history->changeIdOrderState($order_state->id, $order->id);
  348.                         $carrier = new Carrier($order->id_carrier, $order->id_lang);
  349.                         $templateVars = array();
  350.                         if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') && $order->shipping_number) {
  351.                             $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
  352.                         } elseif ($history->id_order_state == Configuration::get('PS_OS_CHEQUE')) {
  353.                             $templateVars = array(
  354.                                 '{cheque_name}' => (Configuration::get('CHEQUE_NAME') ? Configuration::get('CHEQUE_NAME') : ''),
  355.                                 '{cheque_address_html}' => (Configuration::get('CHEQUE_ADDRESS') ? nl2br(Configuration::get('CHEQUE_ADDRESS')) : '')
  356.                             );
  357.                         } elseif ($history->id_order_state == Configuration::get('PS_OS_BANKWIRE')) {
  358.                             $templateVars = array(
  359.                                 '{bankwire_owner}' => (Configuration::get('BANK_WIRE_OWNER') ? Configuration::get('BANK_WIRE_OWNER') : ''),
  360.                                 '{bankwire_details}' => (Configuration::get('BANK_WIRE_DETAILS') ? nl2br(Configuration::get('BANK_WIRE_DETAILS')) : ''),
  361.                                 '{bankwire_address}' => (Configuration::get('BANK_WIRE_ADDRESS') ? nl2br(Configuration::get('BANK_WIRE_ADDRESS')) : '')
  362.                             );
  363.                         }
  364.                         if ($history->addWithemail(TRUE, $templateVars)) {
  365.                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&token=' . $this->token);
  366.                         }
  367.                        
  368.                         $this->errors[] = Tools::displayError('An error occurred while changing the status or was unable to send e-mail to the customer.');
  369.                     } else {
  370.                         $this->errors[] = Tools::displayError('This order is already assigned this status');
  371.                     }    
  372.                 }
  373.             } else {
  374.                 $this->errors[] = Tools::displayError('You do not have permission to edit here.');
  375.             }    
  376.         } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
  377.            
  378.             if ($this->tabAccess['edit'] === '1') {
  379.                 $customer = new Customer(Tools::getValue('id_customer'));
  380.                 if (!Validate::isLoadedObject($customer)) {
  381.                     $this->errors[] = Tools::displayError('Customer is invalid');
  382.                 } elseif (!Tools::getValue('message')) {
  383.                     $this->errors[] = Tools::displayError('Message cannot be blank');
  384.                 } else {
  385.                    
  386.                     $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
  387.                     foreach ($rules['required'] as $field) {
  388.                         if (($value = Tools::getValue($field)) == FALSE && (string) $value != '0') {
  389.                             if (!Tools::getValue('id_' . $this->table) || $field != 'passwd') {
  390.                                 $this->errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is required.');
  391.                             }
  392.                         }
  393.                     }
  394.                    
  395.                     foreach ($rules['size'] as $field => $maxLength) {
  396.                         if (Tools::getValue($field) && Tools::strlen(Tools::getValue($field)) > $maxLength) {
  397.                             $this->errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is too long.') . ' (' . $maxLength . ' ' . Tools::displayError('chars max') . ')';
  398.                         }
  399.                     }
  400.                    
  401.                     foreach ($rules['validate'] as $field => $function) {
  402.                         if (Tools::getValue($field)) {
  403.                             if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
  404.                                 $this->errors[] = Tools::displayError('field') . ' <b>' . $field . '</b> ' . Tools::displayError('is invalid.');
  405.                             }
  406.                         }
  407.                     }
  408.                     if (!count($this->errors)) {
  409.                         $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
  410.                         if (!$id_customer_thread) {
  411.                             $customer_thread = new CustomerThread();
  412.                             $customer_thread->id_contact = 0;
  413.                             $customer_thread->id_customer = (int) $order->id_customer;
  414.                             $customer_thread->id_shop = (int) $this->context->shop->id;
  415.                             $customer_thread->id_order = (int) $order->id;
  416.                             $customer_thread->id_lang = (int) $this->context->language->id;
  417.                             $customer_thread->email = $customer->email;
  418.                             $customer_thread->status = 'open';
  419.                             $customer_thread->token = Tools::passwdGen(12);
  420.                             $customer_thread->add();
  421.                         } else {
  422.                             $customer_thread = new CustomerThread((int) $id_customer_thread);
  423.                         }    
  424.                         $customer_message = new CustomerMessage();
  425.                         $customer_message->id_customer_thread = $customer_thread->id;
  426.                         $customer_message->id_employee = (int) $this->context->employee->id;
  427.                         $customer_message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8');
  428.                         $customer_message->private = Tools::getValue('visibility');
  429.                         if (!$customer_message->add()) {
  430.                             $this->errors[] = Tools::displayError('An error occurred while saving message');
  431.                         } elseif ($customer_message->private) {
  432.                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&conf=11&token=' . $this->token);
  433.                         } else {
  434.                             $message = $customer_message->message;
  435.                             if (Configuration::get('PS_MAIL_TYPE') != Mail::TYPE_TEXT) {
  436.                                 $message = Tools::nl2br($customer_message->message);
  437.                             }
  438.                             $varsTpl = array(
  439.                                 '{lastname}' => $customer->lastname,
  440.                                 '{firstname}' => $customer->firstname,
  441.                                 '{id_order}' => $order->id,
  442.                                 '{message}' => $message
  443.                             );
  444.                            
  445.                             if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order', (int) $order->id_lang), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, TRUE)) {
  446.                                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=11' . '&token=' . $this->token);
  447.                             }
  448.                         }
  449.                        
  450.                         $this->errors[] = Tools::displayError('An error occurred while sending e-mail to the customer.');
  451.                     }
  452.                 }
  453.             } else {
  454.                 $this->errors[] = Tools::displayError('You do not have permission to delete here.');
  455.             }
  456.         } elseif (Tools::isSubmit('partialRefund') && isset($order)) {
  457.            
  458.             if ($this->tabAccess['edit'] == '1') {
  459.                 if (is_array($_POST['partialRefundProduct'])) {
  460.                     $amount = 0;
  461.                     $order_detail_list = array();
  462.                     foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) {
  463.                         if (isset($amount_detail) && !empty($amount_detail)) {
  464.                             $amount += $amount_detail;
  465.                             $order_detail_list[$id_order_detail]['quantity'] = (int) $_POST['partialRefundProductQuantity'][$id_order_detail];
  466.                             $order_detail_list[$id_order_detail]['amount'] = (float) $amount_detail;
  467.                         }
  468.                     }
  469.                    
  470.                     $shipping_cost_amount = (float) Tools::getValue('partialRefundShippingCost');
  471.                     if ($shipping_cost_amount > 0) {
  472.                         $amount += $shipping_cost_amount;
  473.                     }
  474.                     if ($amount > 0) {
  475.                         if (!OrderSlip::createPartialOrderSlip($order, $amount, $shipping_cost_amount, $order_detail_list)) {
  476.                             $this->errors[] = Tools::displayError('Cannot generate partial credit slip');
  477.                         }    
  478.                     } else {
  479.                         $this->errors[] = Tools::displayError('You have to write an amount if you want to do a partial credit slip');
  480.                     }
  481.                     if (!count($this->errors)) {
  482.                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token);
  483.                     }    
  484.                 } else {
  485.                     $this->errors[] = Tools::displayError('Partial refund data is incorrect');
  486.                 }    
  487.             } else {
  488.                 $this->errors[] = Tools::displayError('You do not have permission to delete here.');
  489.             }    
  490.         } elseif (Tools::isSubmit('cancelProduct') && isset($order)) {
  491.            
  492.             if ($this->tabAccess['delete'] === '1') {
  493.                 if (!Tools::isSubmit('id_order_detail')) {
  494.                     $this->errors[] = Tools::displayError('You must select a product');
  495.                 } elseif (!Tools::isSubmit('cancelQuantity')) {
  496.                     $this->errors[] = Tools::displayError('You must enter a quantity');
  497.                 } else {
  498.                     $productList = Tools::getValue('id_order_detail');
  499.                     $customizationList = Tools::getValue('id_customization');
  500.                     $qtyList = Tools::getValue('cancelQuantity');
  501.                     $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
  502.                     $full_product_list = $productList;
  503.                     $full_quantity_list = $qtyList;
  504.                     if ($customizationList) {
  505.                         foreach ($customizationList as $key => $id_order_detail) {
  506.                             $full_product_list[$id_order_detail] = $id_order_detail;
  507.                             $full_quantity_list[$id_order_detail] += $customizationQtyList[$key];
  508.                         }
  509.                     }    
  510.                     if ($productList || $customizationList) {
  511.                         if ($productList) {
  512.                             $id_cart = Cart::getCartIdByOrderId($order->id);
  513.                             $customization_quantities = Customization::countQuantityByCart($id_cart);
  514.                             foreach ($productList as $key => $id_order_detail) {
  515.                                 $qtyCancelProduct = abs($qtyList[$key]);
  516.                                 if (!$qtyCancelProduct) {
  517.                                     $this->errors[] = Tools::displayError('No quantity selected for product.');
  518.                                 }
  519.                                
  520.                                 $order_detail = new OrderDetail($id_order_detail);
  521.                                 $customization_quantity = 0;
  522.                                 if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) {
  523.                                     $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id];
  524.                                 }
  525.                                
  526.                                 if (($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return) < $qtyCancelProduct) {
  527.                                     $this->errors[] = Tools::displayError('Invalid quantity selected for product.');
  528.                                 }    
  529.                             }
  530.                         }
  531.                        
  532.                         if ($customizationList) {
  533.                             $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
  534.                             foreach ($customizationList as $id_customization => $id_order_detail) {
  535.                                 $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
  536.                                 $customization_quantity = $customization_quantities[$id_customization];
  537.                                 if (!$qtyCancelProduct) {
  538.                                     $this->errors[] = Tools::displayError('No quantity selected for product.');
  539.                                 }
  540.                                
  541.                                 if ($qtyCancelProduct > ($customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned']))) {
  542.                                     $this->errors[] = Tools::displayError('Invalid quantity selected for product.');
  543.                                 }    
  544.                             }
  545.                         }
  546.                         if (!count($this->errors) && $productList) {
  547.                             foreach ($productList as $key => $id_order_detail) {
  548.                                 $qty_cancel_product = abs($qtyList[$key]);
  549.                                 $order_detail = new OrderDetail((int) ($id_order_detail));
  550.                                 if (!$order->hasBeenDelivered() || ($order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities'))) {
  551.                                     $reinjectable_quantity = (int) $order_detail->product_quantity - (int) $order_detail->product_quantity_reinjected;
  552.                                     $quantity_to_reinject = $qty_cancel_product > $reinjectable_quantity ? $reinjectable_quantity : $qty_cancel_product;
  553.                                     $product_to_inject = new Product($order_detail->product_id, FALSE, $this->context->language->id, $order->id_shop);
  554.                                     $product = new Product($order_detail->product_id);
  555.                                     if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')
  556.                                             && $product->advanced_stock_management
  557.                                             && $order_detail->id_warehouse != 0) {
  558.                                         $manager = StockManagerFactory::getManager();
  559.                                         $movements = StockMvt::getNegativeStockMvts(
  560.                                                         $order_detail->id_order, $order_detail->product_id, $order_detail->product_attribute_id, $quantity_to_reinject
  561.                                         );
  562.                                         foreach ($movements as $movement) {
  563.                                             $manager->addProduct(
  564.                                                     $order_detail->product_id, $order_detail->product_attribute_id, new Warehouse($movement['id_warehouse']), $movement['physical_quantity'], NULL, $movement['price_te'], TRUE
  565.                                             );
  566.                                         }
  567.                                        
  568.                                         StockAvailable::synchronize($order_detail->product_id);
  569.                                     } else if ($order_detail->id_warehouse == 0) {
  570.                                         StockAvailable::updateQuantity(
  571.                                                 $order_detail->product_id, $order_detail->product_attribute_id, $quantity_to_reinject, $order->id_shop
  572.                                         );
  573.                                     } else {
  574.                                         $this->errors[] = Tools::displayError('Cannot re-stock product');
  575.                                     }    
  576.                                 }
  577.                                 $order_detail = new OrderDetail((int) $id_order_detail);
  578.                                 if (!$order->deleteProduct($order, $order_detail, $qtyCancelProduct)) {
  579.                                     $this->errors[] = Tools::displayError('An error occurred during deletion of the product.') . ' <span class="bold">' . $order_detail->product_name . '</span>';
  580.                                 }
  581.                                
  582.                                 Hook::exec('actionProductCancel', array('order' => $order, 'id_order_detail' => $id_order_detail));
  583.                             }
  584.                         }
  585.                        
  586.                         if (!count($this->errors) && $customizationList) {
  587.                             foreach ($customizationList as $id_customization => $id_order_detail) {
  588.                                 $order_detail = new OrderDetail((int) ($id_order_detail));
  589.                                 $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
  590.                                 if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $order_detail)) {
  591.                                     $this->errors[] = Tools::displayError('An error occurred during deletion of product customization.') . ' ' . $id_customization;
  592.                                 }    
  593.                             }
  594.                         }
  595.                         if ((Tools::isSubmit('generateCreditSlip') || Tools::isSubmit('generateDiscount')) && !count($this->errors)) {
  596.                             $customer = new Customer((int) ($order->id_customer));
  597.                             $params['{lastname}'] = $customer->lastname;
  598.                             $params['{firstname}'] = $customer->firstname;
  599.                             $params['{id_order}'] = $order->id;
  600.                         }
  601.                         if (Tools::isSubmit('generateCreditSlip') && !count($this->errors)) {
  602.                             if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, Tools::isSubmit('shippingBack'))) {
  603.                                 $this->errors[] = Tools::displayError('Cannot generate credit slip');
  604.                             } else {
  605.                                 Hook::exec('actionOrderSlipAdd', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list));
  606.                                 @Mail::Send(
  607.                                                 (int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, TRUE
  608.                                 );
  609.                             }
  610.                         }
  611.                         if (Tools::isSubmit('generateDiscount') && !count($this->errors)) {
  612.                             if (TRUE || !$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Credit Slip for order #'), Tools::isSubmit('shippingBack'))) {
  613.                                 $this->errors[] = Tools::displayError('Cannot generate voucher');
  614.                             } else {
  615.                                 $currency = $this->context->currency;
  616.                                 $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, FALSE);
  617.                                 $params['{voucher_num}'] = $voucher->name;
  618.                                 @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order', (int) $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, TRUE);
  619.                             }
  620.                         }
  621.                     } else {
  622.                         $this->errors[] = Tools::displayError('No product or quantity selected.');
  623.                     }    
  624.                     if (!count($this->errors)) {
  625.                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=24&token=' . $this->token);
  626.                     }    
  627.                 }
  628.             } else {
  629.                 $this->errors[] = Tools::displayError('You do not have permission to delete here.');
  630.             }    
  631.         } elseif (Tools::isSubmit('messageReaded')) {
  632.             Message::markAsReaded(Tools::getValue('messageReaded'), $this->context->employee->id);
  633.         } elseif (Tools::isSubmit('submitAddPayment') && isset($order)) {
  634.             if ($this->tabAccess['edit'] === '1') {
  635.                 $amount = str_replace(',', '.', Tools::getValue('payment_amount'));
  636.                 $currency = new Currency(Tools::getValue('payment_currency'));
  637.                 $order_has_invoice = $order->hasInvoice();
  638.                 if ($order_has_invoice) {
  639.                     $order_invoice = new OrderInvoice(Tools::getValue('payment_invoice'));
  640.                 } else {
  641.                     $order_invoice = NULL;
  642.                 }
  643.                
  644.                 if (!Validate::isLoadedObject($order)) {
  645.                     $this->errors[] = Tools::displayError('Order can\'t be found');
  646.                 } elseif (!Validate::isPrice($amount)) {
  647.                     $this->errors[] = Tools::displayError('Amount is invalid');
  648.                 } elseif (!Validate::isString(Tools::getValue('payment_method'))) {
  649.                     $this->errors[] = Tools::displayError('Payment method is invalid');
  650.                 } elseif (!Validate::isString(Tools::getValue('payment_transaction_id'))) {
  651.                     $this->errors[] = Tools::displayError('Transaction ID is invalid');
  652.                 } elseif (!Validate::isLoadedObject($currency)) {
  653.                     $this->errors[] = Tools::displayError('Currency is invalid');
  654.                 } elseif ($order_has_invoice && !Validate::isLoadedObject($order_invoice)) {
  655.                     $this->errors[] = Tools::displayError('Invoice is invalid');
  656.                 } elseif (!Validate::isDate(Tools::getValue('payment_date'))) {
  657.                     $this->errors[] = Tools::displayError('Date is invalid');
  658.                 } else {
  659.                     if (!$order->addOrderPayment($amount, Tools::getValue('payment_method'), Tools::getValue('payment_transaction_id'), $currency, Tools::getValue('payment_date'), $order_invoice)) {
  660.                         $this->errors[] = Tools::displayError('An error occurred on adding order payment');
  661.                     } else {
  662.                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
  663.                     }
  664.                 }
  665.             } else {
  666.                 $this->errors[] = Tools::displayError('You do not have permission to edit here.');
  667.             }    
  668.         } elseif (Tools::isSubmit('submitEditNote')) {
  669.             $note = Tools::getValue('note');
  670.             $order_invoice = new OrderInvoice((int) Tools::getValue('id_order_invoice'));
  671.             if (Validate::isLoadedObject($order_invoice) && Validate::isCleanHtml($note)) {
  672.                 if ($this->tabAccess['edit'] === '1') {
  673.                     $order_invoice->note = $note;
  674.                     if ($order_invoice->save()) {
  675.                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order_invoice->id_order . '&vieworder&conf=4&token=' . $this->token);
  676.                     } else {
  677.                         $this->errors[] = Tools::displayError('Unable to save invoice note.');
  678.                     }    
  679.                 } else {
  680.                     $this->errors[] = Tools::displayError('You do not have permission to edit here.');
  681.                 }    
  682.             } else {
  683.                 $this->errors[] = Tools::displayError('Unable to load invoice for edit note.');
  684.             }    
  685.         } elseif (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) &&
  686.                 ($module_name = Tools::getValue('payment_module_name')) &&
  687.                 ($id_order_state = Tools::getValue('id_order_state'))) {
  688.             if ($this->tabAccess['edit'] === '1') {
  689.                 $payment_module = Module::getInstanceByName($module_name);
  690.                 $cart = new Cart((int) $id_cart);
  691.                 $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(TRUE, Cart::BOTH), $payment_module->displayName, sprintf($this->l('Manual order - ID Employee :%d'), (int) Context::getContext()->cookie->id_employee), array(), NULL, FALSE, $cart->secure_key);
  692.                
  693.                 require_once(_PS_MODULE_DIR_ . "belvg_preorderproducts/belvg_preorderproducts.php");
  694.                 $products = $cart->getProducts();
  695.                 $preorder_fl = FALSE;
  696.                 foreach ($products as $product) {
  697.                     if ($preorder_id = ProductPreorder::checkActiveStatic($product['id_product'], $product['id_product_attribute'])) {
  698.                         $preorder_init_product_obj = $product;
  699.                         $preorder_fl = TRUE;
  700.                         break;
  701.                     }
  702.                 }
  703.                 if ($preorder_fl) {
  704.                     $objOrder = new Order($payment_module->currentOrder);
  705.                     Belvg_PreOrderProducts::checkPreorder($objOrder);
  706.                 }
  707.                
  708.                 if ($payment_module->currentOrder) {
  709.                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
  710.                 }    
  711.             } else {
  712.                 $this->errors[] = Tools::displayError('You do not have permission to add here.');
  713.             }    
  714.         } elseif ((Tools::isSubmit('submitAddressShipping') || Tools::isSubmit('submitAddressInvoice')) && isset($order)) {
  715.             if ($this->tabAccess['edit'] === '1') {
  716.                 $address = new Address(Tools::getValue('id_address'));
  717.                 if (Validate::isLoadedObject($address)) {
  718.                     if (Tools::isSubmit('submitAddressShipping')) {
  719.                         $order->id_address_delivery = $address->id;
  720.                     } elseif (Tools::isSubmit('submitAddressInvoice')) {
  721.                         $order->id_address_invoice = $address->id;
  722.                     }
  723.                    
  724.                     $order->update();
  725.                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
  726.                 } else {
  727.                     $this->errors[] = Tools::displayErrror('This address can\'t be loaded');
  728.                 }    
  729.             } else {
  730.                 $this->errors[] = Tools::displayError('You do not have permission to edit here.');
  731.             }
  732.         } elseif (Tools::isSubmit('submitChangeCurrency') && isset($order)) {
  733.             if ($this->tabAccess['edit'] === '1') {
  734.                 if (Tools::getValue('new_currency') != $order->id_currency && !$order->valid) {
  735.                     $old_currency = new Currency($order->id_currency);
  736.                     $currency = new Currency(Tools::getValue('new_currency'));
  737.                     if (!Validate::isLoadedObject($currency)) {
  738.                         throw new PrestaShopException('Can\'t load Currency object');
  739.                     }
  740.                     foreach ($order->getOrderDetailList() as $row) {
  741.                         $order_detail = new OrderDetail($row['id_order_detail']);
  742.                         $order_detail->product_price = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
  743.                         $order_detail->reduction_amount = Tools::convertPriceFull($order_detail->reduction_amount, $old_currency, $currency);
  744.                         $order_detail->unit_price_tax_incl = Tools::convertPriceFull($order_detail->unit_price_tax_incl, $old_currency, $currency);
  745.                         $order_detail->unit_price_tax_excl = Tools::convertPriceFull($order_detail->unit_price_tax_excl, $old_currency, $currency);
  746.                         $order_detail->total_price_tax_incl = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
  747.                         $order_detail->total_price_tax_excl = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
  748.                         $order_detail->group_reduction = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
  749.                         $order_detail->product_quantity_discount = Tools::convertPriceFull($order_detail->product_price, $old_currency, $currency);
  750.                         $order_detail->update();
  751.                     }
  752.                     $id_order_carrier = Db::getInstance()->getValue('
  753.                         SELECT `id_order_carrier`
  754.                         FROM `' . _DB_PREFIX_ . 'order_carrier`
  755.                         WHERE `id_order` = ' . (int) $order->id);
  756.                     $order_carrier = new OrderCarrier($id_order_carrier);
  757.                     $order_carrier->shipping_cost_tax_excl = (float) Tools::convertPriceFull($order_carrier->shipping_cost_tax_excl, $old_currency, $currency);
  758.                     $order_carrier->shipping_cost_tax_incl = (float) Tools::convertPriceFull($order_carrier->shipping_cost_tax_incl, $old_currency, $currency);
  759.                     $order_carrier->update();
  760.                     $order->total_discounts = Tools::convertPriceFull($order->total_discounts, $old_currency, $currency);
  761.                     $order->total_discounts_tax_incl = Tools::convertPriceFull($order->total_discounts_tax_incl, $old_currency, $currency);
  762.                     $order->total_discounts_tax_excl = Tools::convertPriceFull($order->total_discounts_tax_excl, $old_currency, $currency);
  763.                     $order->total_paid = Tools::convertPriceFull($order->total_paid, $old_currency, $currency);
  764.                     $order->total_paid_tax_incl = Tools::convertPriceFull($order->total_paid_tax_incl, $old_currency, $currency);
  765.                     $order->total_paid_tax_excl = Tools::convertPriceFull($order->total_discounts_tax_excl, $old_currency, $currency);
  766.                     $order->total_paid_real = Tools::convertPriceFull($order->total_paid_real, $old_currency, $currency);
  767.                     $order->total_products = Tools::convertPriceFull($order->total_products, $old_currency, $currency);
  768.                     $order->total_products_wt = Tools::convertPriceFull($order->total_products_wt, $old_currency, $currency);
  769.                     $order->total_shipping = Tools::convertPriceFull($order->total_shipping, $old_currency, $currency);
  770.                     $order->total_shipping_tax_incl = Tools::convertPriceFull($order->total_shipping_tax_incl, $old_currency, $currency);
  771.                     $order->total_shipping_tax_excl = Tools::convertPriceFull($order->total_shipping_tax_excl, $old_currency, $currency);
  772.                     $order->total_wrapping = Tools::convertPriceFull($order->total_wrapping, $old_currency, $currency);
  773.                     $order->total_wrapping_tax_incl = Tools::convertPriceFull($order->total_wrapping_tax_incl, $old_currency, $currency);
  774.                     $order->total_wrapping_tax_excl = Tools::convertPriceFull($order->total_wrapping_tax_excl, $old_currency, $currency);
  775.                     $order->id_currency = $currency->id;
  776.                     $order->update();
  777.                 } else {
  778.                     $this->errors[] = Tools::displayError('You cannot change the currency');
  779.                 }    
  780.             } else {
  781.                 $this->errors[] = Tools::displayError('You do not have permission to edit here.');
  782.             }    
  783.         } elseif (Tools::isSubmit('submitGenerateInvoice') && isset($order)) {
  784.             if ($order->hasInvoice()) {
  785.                 $this->errors[] = Tools::displayError('This order already has an invoice');
  786.             } else {
  787.                 $order->setInvoice();
  788.                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
  789.             }
  790.         } elseif (Tools::isSubmit('submitDeleteVoucher') && isset($order)) {
  791.             if ($this->tabAccess['edit'] === '1') {
  792.                 $order_cart_rule = new OrderCartRule(Tools::getValue('id_order_cart_rule'));
  793.                 if (Validate::isLoadedObject($order_cart_rule) && $order_cart_rule->id_order == $order->id) {
  794.                     if ($order_cart_rule->id_order_invoice) {
  795.                         $order_invoice = new OrderInvoice($order_cart_rule->id_order_invoice);
  796.                         if (!Validate::isLoadedObject($order_invoice)) {
  797.                             throw new PrestaShopException('Can\'t load Order Invoice object');
  798.                         }
  799.                         $order_invoice->total_discount_tax_excl -= $order_cart_rule->value_tax_excl;
  800.                         $order_invoice->total_discount_tax_incl -= $order_cart_rule->value;
  801.                         $order_invoice->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
  802.                         $order_invoice->total_paid_tax_incl += $order_cart_rule->value;
  803.                         $order_invoice->update();
  804.                     }
  805.                     $order->total_discounts -= $order_cart_rule->value;
  806.                     $order->total_discounts_tax_incl -= $order_cart_rule->value;
  807.                     $order->total_discounts_tax_excl -= $order_cart_rule->value_tax_excl;
  808.                     $order->total_paid += $order_cart_rule->value;
  809.                     $order->total_paid_tax_incl += $order_cart_rule->value;
  810.                     $order->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
  811.                     $order_cart_rule->delete();
  812.                     $order->update();
  813.                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
  814.                 } else {
  815.                     $this->errors[] = Tools::displayError('Cannot edit this Order Cart Rule');
  816.                 }    
  817.             } else {
  818.                 $this->errors[] = Tools::displayError('You do not have permission to edit here.');
  819.             }    
  820.         } elseif (Tools::getValue('submitNewVoucher') && isset($order)) {
  821.             if ($this->tabAccess['edit'] === '1') {
  822.                 if (!Tools::getValue('discount_name')) {
  823.                     $this->errors[] = Tools::displayError('You must specify a name in order to create a new discount');
  824.                 } else {
  825.                     if ($order->hasInvoice()) {
  826.                         if (!Tools::isSubmit('discount_all_invoices')) {
  827.                             $order_invoice = new OrderInvoice(Tools::getValue('discount_invoice'));
  828.                             if (!Validate::isLoadedObject($order_invoice)) {
  829.                                 throw new PrestaShopException('Can\'t load Order Invoice object');
  830.                             }    
  831.                         }
  832.                     }
  833.                     $cart_rules = array();
  834.                     switch (Tools::getValue('discount_type')) {
  835.                         case 1:
  836.                             if (Tools::getValue('discount_value') < 100) {
  837.                                 if (isset($order_invoice)) {
  838.                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * Tools::getValue('discount_value') / 100, 2);
  839.                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * Tools::getValue('discount_value') / 100, 2);
  840.                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
  841.                                 } elseif ($order->hasInvoice()) {
  842.                                     $order_invoices_collection = $order->getInvoicesCollection();
  843.                                     foreach ($order_invoices_collection as $order_invoice) {
  844.                                         $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * Tools::getValue('discount_value') / 100, 2);
  845.                                         $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * Tools::getValue('discount_value') / 100, 2);
  846.                                         $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
  847.                                     }
  848.                                 } else {
  849.                                     $cart_rules[0]['value_tax_incl'] = Tools::ps_round($order->total_paid_tax_incl * Tools::getValue('discount_value') / 100, 2);
  850.                                     $cart_rules[0]['value_tax_excl'] = Tools::ps_round($order->total_paid_tax_excl * Tools::getValue('discount_value') / 100, 2);
  851.                                 }
  852.                             } else {
  853.                                 $this->errors[] = Tools::displayError('Discount value is invalid');
  854.                             }
  855.                             break;
  856.                         case 2:
  857.                             if (isset($order_invoice)) {
  858.                                 if (Tools::getValue('discount_value') > $order_invoice->total_paid_tax_incl) {
  859.                                     $this->errors[] = Tools::displayError('Discount value is greater than the order invoice total');
  860.                                 } else {
  861.                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round(Tools::getValue('discount_value'), 2);
  862.                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round(Tools::getValue('discount_value') / (1 + ($order->getTaxesAverageUsed() / 100)), 2);
  863.                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
  864.                                 }
  865.                             } elseif ($order->hasInvoice()) {
  866.                                 $order_invoices_collection = $order->getInvoicesCollection();
  867.                                 foreach ($order_invoices_collection as $order_invoice) {
  868.                                     if (Tools::getValue('discount_value') > $order_invoice->total_paid_tax_incl) {
  869.                                         $this->errors[] = Tools::displayError('Discount value is greater than the order invoice total (Invoice:') . $order_invoice->getInvoiceNumberFormatted(Context::getContext()->language->id) . ')';
  870.                                     } else {
  871.                                         $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round(Tools::getValue('discount_value'), 2);
  872.                                         $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round(Tools::getValue('discount_value') / (1 + ($order->getTaxesAverageUsed() / 100)), 2);
  873.                                         $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
  874.                                     }
  875.                                 }
  876.                             } else {
  877.                                 if (Tools::getValue('discount_value') > $order->total_paid_tax_incl) {
  878.                                     $this->errors[] = Tools::displayError('Discount value is greater than the order total');
  879.                                 } else {
  880.                                     $cart_rules[0]['value_tax_incl'] = Tools::ps_round(Tools::getValue('discount_value'), 2);
  881.                                     $cart_rules[0]['value_tax_excl'] = Tools::ps_round(Tools::getValue('discount_value') / (1 + ($order->getTaxesAverageUsed() / 100)), 2);
  882.                                 }
  883.                             }
  884.                             break;
  885.                         case 3:
  886.                             if (isset($order_invoice)) {
  887.                                 if ($order_invoice->total_shipping_tax_incl > 0) {
  888.                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
  889.                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
  890.                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
  891.                                 }
  892.                             } elseif ($order->hasInvoice()) {
  893.                                 $order_invoices_collection = $order->getInvoicesCollection();
  894.                                 foreach ($order_invoices_collection as $order_invoice) {
  895.                                     if ($order_invoice->total_shipping_tax_incl <= 0) {
  896.                                         continue;
  897.                                     }
  898.                                    
  899.                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
  900.                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
  901.                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
  902.                                 }
  903.                             } else {
  904.                                 $cart_rules[0]['value_tax_incl'] = $order->total_shipping_tax_incl;
  905.                                 $cart_rules[0]['value_tax_excl'] = $order->total_shipping_tax_excl;
  906.                             }
  907.                             break;
  908.                            
  909.                         default:
  910.                             $this->errors[] = Tools::displayError('Discount type is invalid');
  911.                             break;
  912.                     }
  913.                     $res = TRUE;
  914.                     foreach ($cart_rules as &$cart_rule) {
  915.                         $cartRuleObj = new CartRule();
  916.                         $cartRuleObj->date_from = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($order->date_add)));
  917.                         $cartRuleObj->date_to = date('Y-m-d H:i:s', strtotime('+1 hour'));
  918.                         $cartRuleObj->name[Configuration::get('PS_LANG_DEFAULT')] = Tools::getValue('discount_name');
  919.                         $cartRuleObj->quantity = 0;
  920.                         $cartRuleObj->quantity_per_user = 1;
  921.                         if (Tools::getValue('discount_type') == 1) {
  922.                             $cartRuleObj->reduction_percent = Tools::getValue('discount_value');
  923.                         } elseif (Tools::getValue('discount_type') == 2) {
  924.                             $cartRuleObj->reduction_amount = $cart_rule['value_tax_excl'];
  925.                         } elseif (Tools::getValue('discount_type') == 3) {
  926.                             $cartRuleObj->free_shipping = 1;
  927.                         }
  928.                        
  929.                         $cartRuleObj->active = 0;
  930.                         if ($res = $cartRuleObj->add()) {
  931.                             $cart_rule['id'] = $cartRuleObj->id;
  932.                         } else {
  933.                             break;
  934.                         }
  935.                     }
  936.                     if ($res) {
  937.                         foreach ($cart_rules as $id_order_invoice => $cart_rule) {
  938.                             $order_cart_rule = new OrderCartRule();
  939.                             $order_cart_rule->id_order = $order->id;
  940.                             $order_cart_rule->id_cart_rule = $cart_rule['id'];
  941.                             $order_cart_rule->id_order_invoice = $id_order_invoice;
  942.                             $order_cart_rule->name = Tools::getValue('discount_name');
  943.                             $order_cart_rule->value = $cart_rule['value_tax_incl'];
  944.                             $order_cart_rule->value_tax_excl = $cart_rule['value_tax_excl'];
  945.                             $res &= $order_cart_rule->add();
  946.                             $order->total_discounts += $order_cart_rule->value;
  947.                             $order->total_discounts_tax_incl += $order_cart_rule->value;
  948.                             $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
  949.                             $order->total_paid -= $order_cart_rule->value;
  950.                             $order->total_paid_tax_incl -= $order_cart_rule->value;
  951.                             $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
  952.                         }
  953.                         $res &= $order->update();
  954.                     }
  955.                     if ($res) {
  956.                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
  957.                     } else {
  958.                         $this->errors[] = Tools::displayError('An error occurred on OrderCartRule creation');
  959.                     }    
  960.                 }
  961.             } else {
  962.                 $this->errors[] = Tools::displayError('You do not have permission to edit here.');
  963.             }
  964.         }
  965.         parent::postProcess();
  966.     }
  967. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement