diff --git a/adm/tabs/AdminOrders.php b/adm/tabs/AdminOrders.php index 9b7559b7..52591086 100755 --- a/adm/tabs/AdminOrders.php +++ b/adm/tabs/AdminOrders.php @@ -27,1683 +27,1694 @@ class AdminOrders extends AdminTab { - public function __construct() - { - global $cookie; + public function __construct() + { + global $cookie; - $this->table = 'order'; - $this->className = 'Order'; - $this->view = true; - $this->colorOnBackground = true; - $this->_select = ' - a.id_order AS id_pdf, - CONCAT(LEFT(c.`firstname`, 1), \'. \', c.`lastname`) AS `customer`, - osl.`name` AS `osname`, - os.`color`, - IF( + $this->table = 'order'; + $this->className = 'Order'; + $this->view = true; + $this->colorOnBackground = true; + $this->_select = ' + a.id_order AS id_pdf, + CONCAT(LEFT(c.`firstname`, 1), \'. \', c.`lastname`) AS `customer`, + osl.`name` AS `osname`, + os.`color`, + IF( (SELECT COUNT(so.id_order) FROM `'._DB_PREFIX_.'orders` so WHERE so.id_customer = a.id_customer) > 1 AND (SELECT so.id_order FROM `'._DB_PREFIX_.'orders` so WHERE so.id_customer = a.id_customer ORDER BY so.date_add ASC LIMIT 1) != a.id_order , 0, 1) as new, - (SELECT COUNT(od.`id_order`) FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order` = a.`id_order` GROUP BY `id_order`) AS product_number, - a.id_order AS `mixed`, - x.`id_country` - '; - - $this->_join = 'LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = a.`id_customer`) - LEFT JOIN `'._DB_PREFIX_.'address` x ON (x.`id_address` = a.`id_address_delivery`) - LEFT JOIN `'._DB_PREFIX_.'order_history` oh ON (oh.`id_order` = a.`id_order`) - LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = oh.`id_order_state`) - LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)($cookie->id_lang).')'; - $this->_where = 'AND oh.`id_order_history` = (SELECT MAX(`id_order_history`) FROM `'._DB_PREFIX_.'order_history` moh WHERE moh.`id_order` = a.`id_order` GROUP BY moh.`id_order`)'; - - $statesArray = array(); - $states = OrderState::getOrderStates((int)($cookie->id_lang)); - - $order_errors = Db::getInstance()->ExecuteS('SELECT id_order FROM ps_orders WHERE id_order NOT IN (select id_order from ps_order_history)'); - if(count($order_errors) > 0) echo '
'; - foreach($order_errors as $error_order) { - echo 'Erreur commande n°'.$error_order['id_order'].'
'; - } - if(count($order_errors) > 0) echo '

'; - - $country_array = array(); - foreach(Country::getCountries((int) $cookie->id_lang, TRUE) as $country) { - $country_array[(int) $country['id_country']] = $country['name']; - } - - foreach ($states AS $state) - $statesArray[$state['id_order_state']] = $state['name']; - $this->fieldsDisplay = array( - 'id_order' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25), - 'new' => array('title' => $this->l('New'), 'width' => 25, 'align' => 'center', 'type' => 'bool', 'filter_key' => 'new', 'tmpTableFilter' => true, 'icon' => array(0 => 'blank.gif', 1 => 'news-new.gif'), 'orderby' => false), - 'customer' => array('title' => $this->l('Customer'), 'widthColumn' => 160, 'width' => 140, 'filter_key' => 'customer', 'tmpTableFilter' => true), - 'total_paid' => array('title' => $this->l('Total'), 'width' => 70, 'align' => 'right', 'prefix' => '', 'suffix' => '', 'price' => true, 'currency' => true), - 'payment' => array('title' => $this->l('Payment'), 'width' => 100), - 'osname' => array('title' => $this->l('Status'), 'widthColumn' => 230, 'type' => 'select', 'select' => $statesArray, 'filter_key' => 'os!id_order_state', 'filter_type' => 'int', 'width' => 200), - 'date_add' => array('title' => $this->l('Date'), 'width' => 35, 'align' => 'right', 'type' => 'datetime', 'filter_key' => 'a!date_add'), - //'mixed' => array('title' => $this->l('Mixed'), 'callback' => 'printMixedSale', 'orderby' => false, 'search' => false), - 'id_pdf' => array('title' => $this->l('PDF'), 'callback' => 'printPDFIcons', 'orderby' => false, 'search' => false), - 'id_country' => array('title' => $this->l('Pays'), 'callback' => 'printCountry', 'orderby' => false, 'type' => 'select', 'select' => $country_array, 'filter_key' => 'x!id_country', 'filter_type' => 'int', 'width' => 35,), - ); - parent::__construct(); - - if(!isset($_POST['submitFilter']) && !isset($_POST['orderFilter_a!date_add'])) { - $_POST['orderFilter_a!date_add'][0] = date('Y-m-d'); - $_POST['orderFilter_a!date_add'][1] = date('Y-m-d'); - $_POST['submitFilter'] = 1; - $_POST['submitFilterorder'] = 1; - } - } - - /** - * @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( - '{followup}' => str_replace('@', $order->shipping_number, $carrier->url), - '{firstname}' => $customer->firstname, - '{lastname}' => $customer->lastname, - '{id_order}' => (int)($order->id) - ); - @Mail::Send((int)($order->id_lang), 'in_transit', Mail::l('Package in transit'), $templateVars, - $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL, NULL, - _PS_MAIL_DIR_, true); - } - } - else - $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); - } - - elseif(Tools::getValue('send_return_instruction') && Tools::getValue('id_order_return')) { - $id_order = (int) Tools::getValue('id_order'); - $id_order_return = (int) Tools::getValue('id_order_return'); - if(Validate::isLoadedObject($order = new Order($id_order))) { - $customer = new Customer($order->id_customer); - $return_link = Db::getInstance()->getRow(' - SELECT `return_number`, `link` - FROM `'._DB_PREFIX_.'order_return_link` - WHERE `id_order_return` = '.(int) $id_order_return.' - '); - $products = Db::getInstance()->ExecuteS(' - SELECT `id_order_detail`, `product_quantity` - FROM `'._DB_PREFIX_.'order_return_detail` - WHERE `id_order_return` = '.(int) $id_order_return.' - '); - $product_list = ''; - Mail::Send( - intval($order->id_lang), - 'order_return_2', - $subject[(int) $order->id_lang], - array( - '{id_order}' => $order->id, - '{return_link}' => $return_link['link'], - '{product_list}' => $product_list, - '{product_list_txt}' => implode("\r\n", $product_list_txt), - ), - $customer->email, - $customer->firstname.' '.$customer->lastname - ); - } - } - elseif(Tools::isSubmit('submitCreateReturn')) { - $id_order = (int) Tools::getValue('id_order'); - if(Validate::isLoadedObject($order = new Order($id_order)) && ($address_delivery = Db::getInstance()->getRow(' - SELECT * - FROM `'._DB_PREFIX_.'address` - WHERE `id_address` = '.(int) $order->id_address_delivery.' - ')) && in_array((int) $address_delivery['id_country'], array(3, 6, 8, 12))) { - $returnable = array(); - foreach(Db::getInstance()->ExecuteS(' - SELECT d.`id_order_detail`, d.`id_order`, d.`product_name`, d.`product_quantity_return`, d.`product_quantity_refunded`, d.`product_quantity`, c.`id_sale`, d.`product_weight` - FROM `'._DB_PREFIX_.'order_detail` d - LEFT JOIN `'._DB_PREFIX_.'product_ps_cache` c - ON d.`product_id` = c.`id_product` - WHERE d.`id_order` = '.(int) $order->id.' - ') as $product) { - $qty = OrderReturn::getOrderDetailReturnQty($product); - if($qty > 0) { - $returnable[$product['id_order_detail']] = array($product['product_name'], $qty, $product['product_weight']); - } - } - } - $error = FALSE; - $total_weight = 0.0; - $return_reasons = array(); - foreach(Tools::getValue('return_product') as $id_order_detail => $qty) { - if(!isset($returnable[(int) $id_order_detail]) || $returnable[(int) $id_order_detail][1] < $qty) { - $error = TRUE; - } else { - for($i = 1; $i <= $qty; $i++) { - if(!($return_reason = Tools::getValue('return_reason_'.$id_order_detail.'_'.$i))) { - $error = true; - $this->_errors[] = Tools::displayError('Order detail #%s empty return reason'); - } elseif(!($return_instruction = Tools::getValue('return_instruction_'.$id_order_detail.'_'.$i))) { - $error = true; - $this->_errors[] = Tools::displayError('Order detail #%s empty return instruction'); - } else { - $return_reasons[] = array($id_order_detail, $i, $return_reason, $return_instruction); - } - } - $total_weight += $qty * $returnable[(int) $id_order_detail][2]; - } - } - if(!$error) { - Db::getInstance()->Execute(' - INSERT INTO `'._DB_PREFIX_.'order_return` - VALUES ( - DEFAULT, - '.(int) $order->id_customer.', - '.(int) $order->id.', - 2, - "'.''/* QUESTION */.'", - NOW(), - NOW() - ) - '); - $id_order_return = Db::getInstance()->Insert_ID(); - foreach($return_reasons as $return_reason) { - Db::getInstance()->Execute(' - INSERT INTO `'._DB_PREFIX_.'order_return_detail_qty` (`id_order_return`, `id_order_detail`, `qty`, `reason`, `instruction`) - VALUES ( - '.(int) $id_order_return.', - '.(int) $return_reason[0].', - '.(int) $return_reason[1].', - '.(int) $return_reason[2].', - '.(int) $return_reason[3].' - ) - '); - } - $product_list = ''; - if($order->id_lang == 3) { - // Spain - if((int) Tools::getValue('return_option') == 2) { - // Free - $pcode = '11'; - $chars = array('I', 'O', 'P', 'S', 'T', ); - $return_link = 'http://devoluciones.puntopack.es/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=ES&Language=es'; - } - // else { - // // Paid - // $pcode = '08'; - // $chars = array('A', 'E', 'K', 'R', 'Z', ); - // $return_link = 'http://devoluciones.puntopack.es/d/F1BEBEBO/?SiteId=F1BEBEBO4&Country=ES&Language=es'; - // } - } else { - if((int) $address_delivery['id_country'] == 3) { - // Belgium - if((int) Tools::getValue('return_option') == 2) { - // Free - $pcode = '36'; - $chars = array('K', 'P', 'T', 'S', 'W', 'Z', ); - $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=BE&Language=fr'; - } - // else { - // // Paid - // $pcode = '24'; - // $chars = array('C', 'J', 'L', 'M', 'N', 'R', ); - // $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO5&Country=BE&Language=fr'; - // } - } elseif((int) $address_delivery['id_country'] == 6) { - // Spain - if((int) Tools::getValue('return_option') == 2) { - // Free - $pcode = '11'; - $chars = array('I', 'O', 'P', 'S', 'T', ); - $return_link = 'http://devoluciones.puntopack.es/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=ES&Language=fr'; - } - // else { - // // Paid - // $pcode = '08'; - // $chars = array('A', 'E', 'K', 'R', 'Z', ); - // $return_link = 'http://devoluciones.puntopack.es/d/F1BEBEBO/?SiteId=F1BEBEBO4&Country=ES&Language=fr'; - // } - } elseif((int) $address_delivery['id_country'] == 8) { - // France - if((int) Tools::getValue('return_option') == 2) { - // Free - $pcode = '05'; - $chars = array('L', 'J', 'R', 'N', 'W', ); - $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=FR&Language=fr'; - } - // else { - // // Paid - // $pcode = '01'; - // $chars = array('B', 'C', 'D', 'G', 'V', ); - // $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO6&Country=FR&Language=fr'; - // } - } - // elseif((int) $address_delivery['id_country'] == 12) { - // // Luxemburg - // if((int) Tools::getValue('return_option') == 2) { - // // Free - // $pcode = '05'; - // $chars = array('L', 'J', 'R', 'N', 'W', ); - // $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=LU&Language=fr'; - // } else { - // // Paid - // $pcode = '01'; - // $chars = array('B', 'C', 'D', 'G', 'V', ); - // $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO6&Country=LU&Language=fr'; - // } - // } - } - Db::getInstance()->Execute('SET AUTOCOMMIT = 0'); - Db::getInstance()->Execute('START TRANSACTION'); - $cpt = Db::getInstance()->ExecuteS(' - SELECT `number` - FROM `'._DB_PREFIX_.'order_return_link_number` - WHERE `carrier` = "mondialrelay" - FOR UPDATE - '); - $cpt = (int) $cpt[0]['number'] + 1; - Db::getInstance()->ExecuteS(' - UPDATE `'._DB_PREFIX_.'order_return_link_number` - SET `number` = '.(int) $cpt.' - WHERE `carrier` = "mondialrelay" - '); - Db::getInstance()->Execute('COMMIT'); - Db::getInstance()->Execute('SET AUTOCOMMIT = 1'); - $cpt = sprintf('%06d', $cpt); - $return_number = 'R'.substr($cpt, 0, 2).chr(65 + rand(0, 25)).substr($cpt, 2, 2).$chars[rand(0, count($chars) - 1)].substr($cpt, 4, 2).'P'.$pcode.substr($pcode, 0, 1).substr($cpt, 5, 1).substr($pcode, 1, 1); - $return_link .= '&Email='.rawurlencode(Db::getInstance()->getValue(' - SELECT `email` - FROM `'._DB_PREFIX_.'customer` - WHERE `id_customer` = '.(int) $order->id_customer.' - ')).'&CustomReference='.$return_number.'&Adress1='.rawurlencode($address_delivery['lastname']).'&Adress2='.rawurlencode($address_delivery['firstname']).'&Adress3='.rawurlencode($address_delivery['address1']).'&Adress4='.rawurlencode($address_delivery['address2']).'&PostCode='.rawurlencode($address_delivery['postcode']).'&City='.rawurlencode($address_delivery['city']).'&WeightInGramm='.((int) ($total_weight * 1000)); - Db::getInstance()->Execute(' - INSERT INTO `'._DB_PREFIX_.'order_return_link` - VALUES ( - '.(int) $id_order_return.', - '.(int) $cookie->id_employee.', - NOW(), - '.((int) Tools::getValue('return_option') == 2? 1: 0).', - 0, - "mondialrelay", - "'.pSQL($return_number).'", - "'.pSQL($return_link).'", - "'.pSQL(nl2br2(strip_tags(trim(Tools::getValue('return_comment')))), TRUE).'" - ) - '); - $subject = array( - 1 => 'Your order return #'.$id_order_return, - 2 => 'Votre demande de retour n°'.$id_order_return, - 3 => 'Solicitud de devolución n°'.$id_order_return, - 5 => 'La vostra domanda di restituzione #'.$id_order_return, - 6 => 'Your order return #'.$id_order_return, - ); - $customer = new Customer($order->id_customer); - Mail::Send( - intval($order->id_lang), - 'order_return_'.((int) Tools::getValue('return_option') == 2? '2': '3'), - $subject[(int) $order->id_lang], - array( - '{id_order}' => $order->id, - '{return_link}' => $return_link, - '{product_list}' => $product_list, - '{product_list_txt}' => implode("\r\n", $product_list_txt), - ), - $customer->email, - $customer->firstname.' '.$customer->lastname - ); - } - header('Location: '.$_SERVER['REQUEST_URI']); - exit; - } - - - /* Change order state, add a new entry in order history and send an e-mail to the customer if needed */ - 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 - { - $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 == Configuration::get('PS_OS_SHIPPING') AND $order->shipping_number) - $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url)); - elseif ($history->id_order_state == Configuration::get('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 == Configuration::get('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 (Tools::getValue('noSendMail')) { - if ($history->add()) - Tools::redirectAdmin($currentIndex.'&id_order='.$id_order.'&vieworder'.'&token='.$this->token); - } else { - 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.'); - } - - /* Add a new message for the current order and send an e-mail to the customer if needed */ - 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').' '.$field.' '.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').' '.$field.' '.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').' '.$field.' '.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, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true)) - 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.'); - } - - /* Cancel product from order */ - 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)); - - // @Addition Antadis - prevent reinjection when the product is sent by Philea - $is_philea = DB::getInstance()->getValue(' - SELECT p.`id_sale` - FROM `'._DB_PREFIX_.'philea_sync` p - LEFT JOIN `'._DB_PREFIX_.'product_ps_cache` ps ON (ps.`id_sale` = p.`id_sale`) - WHERE ps.`id_product`='.$orderDetail->product_id - ); - - // Reinject product - if (!$order->hasBeenDelivered() OR ($order->hasBeenDelivered() AND Tools::isSubmit('reinjectQuantities') AND !$is_philea)) - { - if(($is_philea && !$order->hasBeenShipped() && !$order->hasBeenDelivered()) || !$is_philea) - { - $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').' '.$orderDetail->product_name.''; - 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.').' '.$orderDetail->product_name.''; - 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']) OR isset($_POST['generateDiscount2'])) AND !sizeof($this->_errors)) - { - $customer = new Customer((int)($order->id_customer)); - $params['{lastname}'] = $customer->lastname; - $params['{firstname}'] = $customer->firstname; - $params['{id_order}'] = $order->id; - - /* PRODUIT REMBOURSE */ - $products_refund = ""; - $total_refund = 0; - foreach ($productList as $key => $id_order_detail) { - $details_refund = new OrderDetail($id_order_detail); - - $tprice = $details_refund->product_price * (1 - $details_refund->reduction_percent / 100) - $details_refund->reduction_amount; - $tprice = $tprice * ( 1+ $details_refund->tax_rate / 100 ); - - $products_refund .= " - - ". $details_refund->product_name . " - " . Tools::displayPrice($tprice) . " - ". (int)$full_quantity_list[$id_order_detail] ." - " . Tools::displayPrice(($tprice * (int)$full_quantity_list[$id_order_detail])) . " - - "; - $total_refund = $total_refund + ($tprice * (int)$full_quantity_list[$id_order_detail]); - } - - $params['{products}'] = $products_refund; - $params['{total_products}'] = Tools::displayPrice($total_refund); - - $fraisport = ""; - if(isset($_POST['shippingBack'])) - { - $order = new Order($details_refund->id_order); - Module::hookExec('cancelShipping', array('order' => $order)); - $fraisport .= " - - Frais de port - " . Tools::displayPrice($order->total_shipping) . " - - "; - } - - $params['{fraisport}'] = $fraisport; - - } - - // Generate voucher - if (isset($_POST['generateDiscount']) AND !sizeof($this->_errors)) - { - if (!$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Geste commercial concernant la commande '), 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, NULL, NULL, NULL, - // NULL, _PS_MAIL_DIR_, true); - - /* MODIF MAIL ANTADIS */ - - $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); - $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); - $params['{voucher_num}'] = $voucher->name; - $params['{voucher_value}'] = $voucher->value; - @Mail::Send((int)($order->id_lang), 'refundorder', Mail::l('New voucher regarding your order'), - $params, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL, - NULL, _PS_MAIL_DIR_, true); - } - } - - // Generate voucher 2 @Addition Antadis - if (isset($_POST['generateDiscount2']) AND !sizeof($this->_errors)) - { - if (!$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Geste commercial concernant la commande '), isset($_POST['shippingBack']),0,0,5)) - $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; - $params['{voucher_value}'] = $voucher->value; - @Mail::Send((int)($order->id_lang), 'refundorder', Mail::l('New voucher regarding your order'), - $params, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL, - NULL, _PS_MAIL_DIR_, true); - } - } - - // 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', $order->id_lang), - $params, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL, NULL, - _PS_MAIL_DIR_, true); - } - } - - // update order state if it's partial - if($order->getCurrentState() == 17) { - $partial = true; - - $to_send = Db::getInstance()->ExecuteS(' - SELECT `id_order_detail`, (`product_quantity` - IF(`product_quantity_return` > 0, `product_quantity_return`, `product_quantity_refunded`)) AS `quantity`, `product_id` - FROM `'._DB_PREFIX_.'order_detail` - WHERE `id_order` = '.(int) $order->id.' - AND (`product_quantity` - IF(`product_quantity_return` > 0, `product_quantity_return`, `product_quantity_refunded`)) > 0 - '); - - if(count($to_send) == 0) { - $partial = false; - } else { - include_once dirname(__FILE__).'/../../modules/privatesales/Sale.php'; - $quantities_sent = array(); - - $product_ids = array(); - foreach(Db::getInstance()->ExecuteS(' - SELECT `product_id` - FROM `'._DB_PREFIX_.'order_detail` - WHERE `id_order` = '.(int) $order->id.' - ') as $row) { - $product_ids[] = (int) $row['product_id']; - } - - /** - * @Override Philea - */ - if(Db::getInstance()->getRow(' - SELECT * - FROM `'._DB_PREFIX_.'philea_parcel` - WHERE `id_order` = '.(int) $order->id.' - ')) { - foreach(Db::getInstance()->ExecuteS(' - SELECT c.`id_product` - FROM `'._DB_PREFIX_.'product_ps_cache` c - WHERE c.`id_product` IN ('.implode(', ', $products_ids).') - ') as $row) { - $quantities_sent[(int) $row['id_product']] = -1; - } - } - - $parcel_quantities = array(); - foreach($to_send as $ts) { - if(!isset($quantities_sent[(int) $ts['product_id']])) { - $parcel_quantities[(int) $ts['id_order_detail']] = $ts; - } - } - - if(count($parcel_quantities) > 0) { - $partial = false; - $sent_logistics = array(); - - foreach(Db::getInstance()->ExecuteS(' - SELECT SUM(`quantity`) AS `quantity`, `id_order_detail` - FROM `'._DB_PREFIX_.'lapostews` - WHERE `id_order_detail` IN ('.implode(', ', array_keys($parcel_quantities)).') - GROUP BY `id_order_detail` - ') as $row) { - $sent_logistics[(int) $row['id_order_detail']] = (int) $row['quantity']; - } - - foreach(Db::getInstance()->ExecuteS(' - SELECT SUM(`quantity`) AS `quantity`, `id_order_detail` - FROM `'._DB_PREFIX_.'mondialrelay_parcel` - WHERE `id_order_detail` IN ('.implode(', ', array_keys($parcel_quantities)).') - GROUP BY `id_order_detail` - ') as $row) { - $sent_logistics[(int) $row['id_order_detail']] = (int) $row['quantity']; - } - - foreach(Db::getInstance()->ExecuteS(' - SELECT SUM(`quantity`) AS `quantity`, `id_order_detail` - FROM `'._DB_PREFIX_.'exapaqws` - WHERE `id_order_detail` IN ('.implode(', ', array_keys($parcel_quantities)).') - GROUP BY `id_order_detail` - ') as $row) { - $sent_logistics[(int) $row['id_order_detail']] = (int) $row['quantity']; - } - - if(count($sent_logistics) == 0) { - $partial = true; - } else { - foreach($parcel_quantities as $k => $v) { - if(!isset($sent_logistics[(int) $k])) { - $partial = true; - break; - } else { - if($sent_logistics[(int) $k] < $v['quantity']) { - $partial = true; - break; - } - } - } - } - } else { - $partial = false; - } - - if(!$partial) { - global $cookie; - Db::getInstance()->ExecuteS(' - INSERT INTO `'._DB_PREFIX_.'order_history` - VALUES ( - DEFAULT, - '.(int) $cookie->id_employee.', - '.(int) $order->id.', - '.Configuration::get('PS_OS_SHIPPING').', - NOW() - ) - '); - Db::getInstance()->ExecuteS(' - INSERT INTO `'._DB_PREFIX_.'order_state_current` - VALUES ( - '.(int) $order->id.', - '.Configuration::get('PS_OS_SHIPPING').', - NOW() - ) - ON DUPLICATE KEY UPDATE - `id_order_state` = '.Configuration::get('PS_OS_SHIPPING').', - `date_upd` = NOW() - '); - $newOS = new OrderState((int)(Configuration::get('PS_OS_SHIPPING')), $order->id_lang); - Module::hookExec('updateOrderStatus', array('newOrderStatus' => $newOS, 'id_order' => (int)($order->id))); - } - } - } - } - 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 (isset($_GET['messageReaded'])) - { - Message::markAsReaded((int)($_GET['messageReaded']), (int)($cookie->id_employee)); - } - parent::postProcess(); - } - - private function displayCustomizedDatas(&$customizedDatas, &$product, &$currency, &$image, $tokenCatalog, $id_order_detail) - { - if (!($order = $this->loadObject())) - return; - - if (is_array($customizedDatas) AND isset($customizedDatas[(int)($product['product_id'])][(int)($product['product_attribute_id'])])) - { - $imageObj = new Image($image['id_image']); - echo ' - - '.(isset($image['id_image']) ? cacheImage(_PS_IMG_DIR_.'p/'.$imageObj->getExistingImgPath().'.jpg', - 'product_mini_'.(int)($product['product_id']).(isset($product['product_attribute_id']) ? '_'.(int)($product['product_attribute_id']) : '').'.jpg', 45, 'jpg') : '--').' - - '.$product['product_name'].' - '.$this->l('customized').'
- '.($product['product_reference'] ? $this->l('Ref:').' '.$product['product_reference'].'
' : '') - .($product['product_supplier_reference'] ? $this->l('Ref Supplier:').' '.$product['product_supplier_reference'] : '') - .'
- '.Tools::displayPrice($product['product_price_wt'], $currency, false).' - '.$product['customizationQuantityTotal'].' - '.($order->hasBeenPaid() ? ''.$product['customizationQuantityRefunded'].'' : '').' - '.($order->hasBeenDelivered() ? ''.$product['customizationQuantityReturned'].'' : '').' - - - '.Tools::displayPrice(Tools::ps_round($order->getTaxCalculationMethod() == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'], 2) * $product['customizationQuantityTotal'], $currency, false).' - -- - '; - foreach ($customizedDatas[(int)($product['product_id'])][(int)($product['product_attribute_id'])] AS $customizationId => $customization) - { - echo ' - - '; - foreach ($customization['datas'] AS $type => $datas) - if ($type == _CUSTOMIZE_FILE_) - { - $i = 0; - echo ''; - } - elseif ($type == _CUSTOMIZE_TEXTFIELD_) - { - $i = 0; - echo ''; - } - echo ' - - - '.$customization['quantity'].' - '.($order->hasBeenPaid() ? ''.$customization['quantity_refunded'].'' : '').' - '.($order->hasBeenDelivered() ? ''.$customization['quantity_returned'].'' : '').' - - - '.Tools::displayPrice(Tools::ps_round($order->getTaxCalculationMethod() == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'], 2) * $customization['quantity'], $currency, false).' - - - - '; - if ((!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) AND (int)(($customization['quantity_returned']) < (int)($customization['quantity']))) - echo ' - = (int)($customization['quantity'])) ? 'disabled="disabled" ' : '').'/>'; - else - echo '--'; - echo ' - - '; - if ((int)($customization['quantity_returned'] + $customization['quantity_refunded']) >= (int)($customization['quantity'])) - echo ''; - elseif (!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) - echo ' - '; - echo ($order->hasBeenDelivered() ? (int)($customization['quantity_returned']).'/'.((int)($customization['quantity']) - (int)($customization['quantity_refunded'])) : ($order->hasBeenPaid() ? (int)($customization['quantity_refunded']).'/'.(int)($customization['quantity']) : '')).' - '; - echo ' - '; - } - } - } - - private function getCancelledProductNumber(&$order, &$product) - { - $productQuantity = array_key_exists('customizationQuantityTotal', $product) ? $product['product_quantity'] - $product['customizationQuantityTotal'] : $product['product_quantity']; - $productRefunded = $product['product_quantity_refunded']; - $productReturned = $product['product_quantity_return']; - $content = '0/'.$productQuantity; - if ($order->hasBeenDelivered()) - $content = $productReturned.'/'.($productQuantity - $productRefunded); - elseif ($order->hasBeenPaid()) - $content = $productRefunded.'/'.$productQuantity; - return $content; - } - - public function viewDetails() - { - global $currentIndex, $cookie, $link; - $irow = 0; - if (!($order = $this->loadObject())) - return; - - $customer = new Customer($order->id_customer); - $customerStats = $customer->getStats(); - $addressInvoice = new Address($order->id_address_invoice, (int)($cookie->id_lang)); - if (Validate::isLoadedObject($addressInvoice) AND $addressInvoice->id_state) - $invoiceState = new State((int)($addressInvoice->id_state)); - $addressDelivery = new Address($order->id_address_delivery, (int)($cookie->id_lang)); - if (Validate::isLoadedObject($addressDelivery) AND $addressDelivery->id_state) - $deliveryState = new State((int)($addressDelivery->id_state)); - $carrier = new Carrier($order->id_carrier); - $history = $order->getHistory($cookie->id_lang); - $products = $order->getProducts(); - $customizedDatas = Product::getAllCustomizedDatas((int)($order->id_cart)); - Product::addCustomizationPrice($products, $customizedDatas); - $discounts = $order->getDiscounts(); - $messages = Message::getMessagesByOrderId($order->id, true); - $states = OrderState::getOrderStates((int)($cookie->id_lang)); - $currency = new Currency($order->id_currency); - $currentLanguage = new Language((int)($cookie->id_lang)); - $currentState = OrderHistory::getLastOrderState($order->id); - $sources = ConnectionsSource::getOrderSources($order->id); - $cart = Cart::getCartByOrderId($order->id); - - $row = array_shift($history); - - if ($prevOrder = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders WHERE id_order < '.(int)$order->id.' ORDER BY id_order DESC')) - $prevOrder = ''; - if ($nextOrder = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders WHERE id_order > '.(int)$order->id.' ORDER BY id_order ASC')) - $nextOrder = ''; - - - if ($order->total_paid != $order->total_paid_real) - echo '
'.$this->l('Warning:').' '.Tools::displayPrice($order->total_paid_real, $currency, false).' '.$this->l('paid instead of').' '.Tools::displayPrice($order->total_paid, $currency, false).' !


'; - - // display bar code if module enabled - $hook = Module::hookExec('invoice', array('id_order' => $order->id)); - if ($hook !== false) - { - echo '
'; - echo $hook; - echo '

'; - } - - // display order header - echo ' -
'; - echo '

- '.$prevOrder.' - '.(Validate::isLoadedObject($customer) ? $customer->firstname.' '.$customer->lastname.' - ' : '').$this->l('Order #').sprintf('%06d', $order->id).' - '.$nextOrder.' -

-
- '.((($currentState->invoice OR $order->invoice_number) AND count($products)) - ? ''.$this->l('View invoice').' '.$this->l('View invoice').'' - : ''.$this->l('No invoice').' '.$this->l('No invoice')).' - - '.(($currentState->delivery OR $order->delivery_number) - ? ''.$this->l('View delivery slip').' '.$this->l('View delivery slip').'' - : ''.$this->l('No delivery slip').' '.$this->l('No delivery slip')).' - - '.$this->l('Print order').' '.$this->l('Print page').' -
-
 
'; - - /* Display current status */ - echo ' - - - - - - - '; - /* Display previous status */ - foreach ($history AS $row) - { - echo ' - - - - - - '; - } - echo ' -
'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).''.stripslashes($row['ostate_name']).''.((!empty($row['employee_lastname'])) ? '('.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'
'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).''.stripslashes($row['ostate_name']).''.((!empty($row['employee_lastname'])) ? '('.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'
-
'; - - /* Display status form */ - echo ' -
- -
- Ne pas envoyer de mail - - - -
'; - - /* Display customer information */ - if (Validate::isLoadedObject($customer)) - { - echo '
-
- '.$this->l('Customer information').' - '.$customer->firstname.' '.$customer->lastname.' ('.$this->l('#').$customer->id.')
- ('.$customer->email.')

'; - if ($customer->isGuest()) - { - echo ' - '.$this->l('This order has been placed by a').' '.$this->l('guest').''; - if (!Customer::customerExists($customer->email)) - { - echo '
- -

- '.$this->l('This feature will generate a random password and send an e-mail to the customer').' -
'; - } - else - echo '
'.$this->l('A registered customer account exists with the same email address').'
'; - } - else - { - echo $this->l('Account registered:').' '.Tools::displayDate($customer->date_add, (int)($cookie->id_lang), true).'
- '.$this->l('Valid orders placed:').' '.$customerStats['nb_orders'].'
- '.$this->l('Total paid since registration:').' '.Tools::displayPrice(Tools::ps_round(Tools::convertPrice($customerStats['total_orders'], $currency), 2), $currency, false).'
'; - } - echo '
'; - } - - /* Display sources */ - if (sizeof($sources)) - { - echo '
-
'.$this->l('Sources').'
'; - } - // display hook specified to this page : AdminOrder - if (($hook = Module::hookExec('adminOrder', array('id_order' => $order->id))) !== false) - echo $hook; - - echo ' -
-
'; - - /* Display invoice information */ - echo '
'; - if (($currentState->invoice OR $order->invoice_number) AND count($products)) - echo ' '.$this->l('Invoice').' - '.$this->l('Invoice #').''.Configuration::get('PS_INVOICE_PREFIX', (int)($cookie->id_lang)).sprintf('%06d', $order->invoice_number).' -
'.$this->l('Created on:').' '.Tools::displayDate($order->invoice_date, (int)$cookie->id_lang, true); - else - echo ''.$this->l('Invoice').' - '.$this->l('No invoice yet.'); - echo '

'; - - /* Display shipping infos */ - $sql = "SELECT `shipping_number`, `date_add` FROM `ps_lapostews` WHERE `id_order` =". $order->id; - $sql2 = "SELECT DISTINCT ppp.`shipping_number`, ppp.`date_add` - FROM `ps_philea_parcel` ppp - LEFT JOIN `ps_order_detail` od ON (od.`id_order_detail` = ppp.`id_order_detail`) - WHERE od.`id_order` =". $order->id; - $numbers = Db::getInstance()->ExecuteS($sql); - $numbers2 = Db::getInstance()->ExecuteS($sql2); - echo ' -
'; - if(count($numbers) > 0){ - foreach ($numbers as $key => $number) { - $date = new DateTime($number['date_add']); - echo '

Numéro de suivi : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .'

'; - } - } - if(count($numbers2) > 0){ - foreach ($numbers2 as $key => $number) { - $date = new DateTime($number['date_add']); - echo '

Numéro de suivi : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .'

'; - } - } - echo ' '.$this->l('Shipping information').' - '.$this->l('Total weight:').' '.number_format($order->getTotalWeight(), 3).' '.Configuration::get('PS_WEIGHT_UNIT').'
- '.$this->l('Carrier:').' '.($carrier->name == '0' ? Configuration::get('PS_SHOP_NAME') : $carrier->name).'
- '.(($currentState->delivery OR $order->delivery_number) ? '
'.$this->l('Delivery slip #').''.Configuration::get('PS_DELIVERY_PREFIX', (int)($cookie->id_lang)).sprintf('%06d', $order->delivery_number).'
' : ''); - if ($order->shipping_number) - echo $this->l('Tracking number:').' '.$order->shipping_number.' '.(!empty($carrier->url) ? '('.$this->l('Track the shipment').')' : ''); - - /* Carrier module */ - if ($carrier->is_module == 1) - { - $module = Module::getInstanceByName($carrier->external_module_name); - if (method_exists($module, 'displayInfoByCart')) - echo call_user_func(array($module, 'displayInfoByCart'), $order->id_cart); - } - - /* Display shipping number field */ - if ($carrier->url && $order->hasBeenShipped()) - echo ' -
- - - -
'; - echo ' -
'; - - $shippings = Db::getInstance()->ExecuteS(' - SELECT p.* - FROM `'._DB_PREFIX_.'lapostews` p - LEFT JOIN `'._DB_PREFIX_.'order_detail` o ON o.`id_order_detail` = p.`id_order_detail` - WHERE o.id_order = ' .(int)$order->id . ' - GROUP BY p.`shipping_number` - ORDER BY `date_add` - '); - - if ($shippings) { - echo ' -
-
- '.$this->l('Numéro(s) de suivi').' - - - - - - '; - foreach ($shippings as $key => $shipping) { - echo ' - - - - '; - } - echo '
'.$this->l('Date').''.$this->l('Numéro de suivi').''.$this->l('Lien').'
'.date('d/m/Y', strtotime($shipping['date_add'])).''. $shipping['shipping_number'] .''.$this->l('Voir').'
-
'; - } - - /* Display summary order */ - echo ' -
-
- '.$this->l('Order details').' - -
'.$this->l('Cart #').sprintf('%06d', $cart->id).'
- -
'.Tools::substr($order->payment, 0, 32).' '.($order->module ? '('.$order->module.')' : '').'
-
- - - '.($order->total_discounts > 0 ? '' : '').' - '.($order->total_wrapping > 0 ? '' : '').' - - -
'.$this->l('Products').''.Tools::displayPrice($order->getTotalProductsWithTaxes(), $currency, false).'
'.$this->l('Discounts').'-'.Tools::displayPrice($order->total_discounts, $currency, false).'
'.$this->l('Wrapping').''.Tools::displayPrice($order->total_wrapping, $currency, false).'
'.$this->l('Shipping').''.Tools::displayPrice($order->total_shipping, $currency, false).'
'.$this->l('Total').''.Tools::displayPrice($order->total_paid, $currency, false).($order->total_paid != $order->total_paid_real ? '
('.$this->l('Paid:').' '.Tools::displayPrice($order->total_paid_real, $currency, false, false).')' : '').'
-
-
- '.$this->l('Recycled package:').' - '.($order->recyclable ? '' : '').' -
-
- '.$this->l('Gift wrapping:').' - '.($order->gift ? ' -
-
- '.(!empty($order->gift_message) ? '
'.$this->l('Message:').'
'.nl2br2($order->gift_message).'
' : '') : '').' -
-
'; - - echo '
-
 
'; - - /* Display adresses : delivery & invoice */ - echo '
 
-
-
- '.$this->l('Shipping address').''.$this->l('Shipping address').' -
- - -
- '.$this->displayAddressDetail($addressDelivery) - .(!empty($addressDelivery->other) ? '
'.$addressDelivery->other.'
' : '') - .'
-
-
-
- '.$this->l('Invoice address').''.$this->l('Invoice address').' -
- '.$this->displayAddressDetail($addressInvoice) - .(!empty($addressInvoice->other) ? '
'.$addressInvoice->other.'
' : '') - - .'
-
-
 
'; - - $product_psale = array(); - $products_ids = array(); - foreach(Db::getInstance()->ExecuteS(' - SELECT DISTINCT `product_id` - FROM `'._DB_PREFIX_.'order_detail` - WHERE `id_order` = '.(int) $order->id.' - ') as $row) { - $products_ids[] = (int) $row['product_id']; - } - foreach(Db::getInstance()->ExecuteS(' - SELECT * - FROM `'._DB_PREFIX_.'product_ps_cache` - WHERE `id_product` IN ('.implode(', ', $products_ids).') - ') as $row) { - $product_psale[(int) $row['id_product']] = (int) $row['id_sale']; - } - - // List of products - echo ' -
-
- -
- '.$this->l('Products').''.$this->l('Products').' -
- - - - - - - '.($order->hasBeenPaid() ? '' : '').' - '.($order->hasBeenDelivered() ? '' : '').' - - - '; - echo ' - '; - $tokenCatalog = Tools::getAdminToken('AdminCatalog'.(int)(Tab::getIdFromClassName('AdminCatalog')).(int)($cookie->id_employee)); - foreach ($products as $k => $product) - { - if ($order->getTaxCalculationMethod() == PS_TAX_EXC) - $product_price = $product['product_price'] + $product['ecotax']; - else - $product_price = $product['product_price_wt']; - - $image = array(); - if (isset($product['product_attribute_id']) AND (int)($product['product_attribute_id'])) - $image = Db::getInstance()->getRow(' - SELECT id_image - FROM '._DB_PREFIX_.'product_attribute_image - WHERE id_product_attribute = '.(int)($product['product_attribute_id'])); - if (!isset($image['id_image']) OR !$image['id_image']) - $image = Db::getInstance()->getRow(' - SELECT id_image - FROM '._DB_PREFIX_.'image - WHERE id_product = '.(int)($product['product_id']).' AND cover = 1'); - $stock = Db::getInstance()->getRow(' - SELECT '.($product['product_attribute_id'] ? 'pa' : 'p').'.quantity - FROM '._DB_PREFIX_.'product p - '.($product['product_attribute_id'] ? 'LEFT JOIN '._DB_PREFIX_.'product_attribute pa ON p.id_product = pa.id_product' : '').' - WHERE p.id_product = '.(int)($product['product_id']).' - '.($product['product_attribute_id'] ? 'AND pa.id_product_attribute = '.(int)($product['product_attribute_id']) : '')); - if (isset($image['id_image'])) - { - $target = _PS_TMP_IMG_DIR_.'product_mini_'.(int)($product['product_id']).(isset($product['product_attribute_id']) ? '_'.(int)($product['product_attribute_id']) : '').'.jpg'; - if (file_exists($target)) - $products[$k]['image_size'] = getimagesize($target); - } - // Customization display - $this->displayCustomizedDatas($customizedDatas, $product, $currency, $image, $tokenCatalog, $k); - - // Normal display - if ($product['product_quantity'] > $product['customizationQuantityTotal']) - { - $quantity = $product['product_quantity'] - $product['customizationQuantityTotal']; - $imageObj = new Image($image['id_image']); - echo ' - - - - - - '.($order->hasBeenPaid() ? '' : '').' - '.($order->hasBeenDelivered() ? '' : '').' - - - - - '; - } - } - echo ' -
 '.$this->l('Product').''.$this->l('UP').' *'.$this->l('Qty').''.$this->l('Refunded').''.$this->l('Returned').''.$this->l('Stock').''.$this->l('Total').' *'.$this->l('Products').' '.($order->hasBeenDelivered() ? $this->l('Return') : ($order->hasBeenPaid() ? $this->l('Refund') : $this->l('Cancel'))).'
'.(isset($image['id_image']) ? cacheImage(_PS_IMG_DIR_.'p/'.$imageObj->getExistingImgPath().'.jpg', - 'product_mini_'.(int)($product['product_id']).(isset($product['product_attribute_id']) ? '_'.(int)($product['product_attribute_id']) : '').'.jpg', 45, 'jpg') : '--').' - '.$product['product_name'].'
- '.($product['product_reference'] ? $this->l('Ref:').' '.$product['product_reference'].'
' : '') - .($product['product_supplier_reference'] ? $this->l('Ref Supplier:').' '.$product['product_supplier_reference'] : '') - .'
'.Tools::displayPrice($product_price, $currency, false).' 1 ? 'style="font-weight:700;font-size:1.1em;color:red"' : '').'>'.(int)$quantity.''.(int)($product['product_quantity_refunded']).''.(int)($product['product_quantity_return']).''.(int)$stock['quantity'].''.Tools::displayPrice(Tools::ps_round($product_price, 2) * ((int)($product['product_quantity']) - $product['customizationQuantityTotal']), $currency, false).' - - - '; - if ((!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) AND (int)($product['product_quantity_return']) < (int)($product['product_quantity'])) - echo ' - = (int)($product['product_quantity'])) ? 'disabled="disabled" ' : '').'/>'; - else - echo '--'; - echo ' - '; - if ((int)($product['product_quantity_return'] + $product['product_quantity_refunded']) >= (int)($product['product_quantity'])) - echo ''; - elseif (!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) - echo ' - '; - echo $this->getCancelledProductNumber($order, $product).' -
-
* '.$this->l('According to the group of this customer, prices are printed:').' '.($order->getTaxCalculationMethod() == PS_TAX_EXC ? $this->l('tax excluded.') : $this->l('tax included.')).(!Configuration::get('PS_ORDER_RETURN') ? '

'.$this->l('Merchandise returns are disabled') : '').'
'; - if (sizeof($discounts)) - { - echo ' -
- - - - - '; - foreach ($discounts as $discount) - echo ' - - - - '; - echo ' -
'.$this->l('Discounts').''.$this->l('Discount name').''.$this->l('Value').'
'.$discount['name'].''.($discount['value'] != 0.00 ? '- ' : '').Tools::displayPrice($discount['value'], $currency, false).'
'; - } - echo ' -
'; - - // Cancel product - echo ' -
 
-
'; - if ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN')) - echo ' -  
'; - if ((!$order->hasBeenDelivered() AND $order->hasBeenPaid()) OR ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN'))) - echo ' -  
-  
-  
- '; - if (!$order->hasBeenDelivered() OR ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN'))) - echo ' -
'; - echo ' -
'; - echo ' -
-
-
 
'; - - /* Display send a message to customer & returns/credit slip*/ - $returns = OrderReturn::getOrdersReturn($order->id_customer, $order->id); - $slips = OrderSlip::getOrdersSlip($order->id_customer, $order->id); - echo ' -
-
-
- '.$this->l('New message').' - -
-

- '.$this->l('Display to consumer?').' - '.$this->l('Yes').' - '.$this->l('No').' -



-

- - - -
-
-
'; - /* Display list of messages */ - if (sizeof($messages)) - { - echo ' -
-
- '.$this->l('Messages').''; - foreach ($messages as $message) - { - echo '
'; - if ($message['is_new_for_me']) - echo ''; - echo $this->l('At').' '.Tools::displayDate($message['date_add'], (int)($cookie->id_lang), true); - echo ' '.$this->l('from').' '.(($message['elastname']) ? ($message['efirstname'].' '.$message['elastname']) : ($message['cfirstname'].' '.$message['clastname'])).''; - echo ((int)($message['private']) == 1 ? ''.$this->l('Private:').'' : ''); - echo '

'.nl2br2($message['message']).'

'; - echo '
'; - echo '
'; - } - echo '

'.$this->l('When you read a message, please click on the green check.').'

'; - echo '
'; - } - echo '
'; - - - /* Display return product */ - echo '
'; - - require_once dirname(__FILE__).'/../../modules/paybox/paybox.php'; - $refundsPaybox = Paybox::getAllRefundbyOrder($order->id); - if (sizeof($refundsPaybox)) - { - echo ' -
-
- '.$this->l('Remboursement e-Transaction').''; - foreach ($refundsPaybox as $refund) - { - echo '
- Remboursement d\'un montant de '. $refund['amount'] / 100 . ' €
'; - - if( !empty($refund['product_name']) ) { - echo '' . $refund['product_name'] . ''; - } else { - echo 'Frais de port'; - } - - echo '
'; - } - echo '

'; - } - - echo '
- '.$this->l('Merchandise returns').''.$this->l('Merchandise returns').''; - if (!sizeof($returns)) - echo $this->l('No merchandise return for this order.'); - else - foreach ($returns as $return) - { - $state = new OrderReturnState($return['state']); - - /* Mondial relay return */ - $return_link = FALSE; - if($state->id == 2) { - $return_link = Db::getInstance()->getRow(' - SELECT `return_number`, `link` - FROM `'._DB_PREFIX_.'order_return_link` - WHERE `id_order_return` = '.(int) $return['id_order_return'].' - '); - } - - echo '('.Tools::displayDate($return['date_upd'], $cookie->id_lang).') : - '.$this->l('#').sprintf('%06d', $return['id_order_return']).' - - '.$state->name[$cookie->id_lang].'
'.($return_link? ' ('.$this->l('return link:').' '.$return_link['return_number'].' '.$this->l('Renvoyer les instructions retour').')': ''); - } - - if(in_array($addressDelivery->id_country, array(3, 6, 8))) { - $returnable = array(); - foreach ($products as $k => $product) { - $product['id_sale'] = $product_psale[(int) $product['product_id']]; - $qty = OrderReturn::getOrderDetailReturnQty($product); - if($qty > 0) { - $returnable[$product['id_order_detail']] = array($product['product_name'], $qty); - } - } - if(count($returnable) > 0) { - $instructions = array( - 1 => 'Remboursement + Mise en stock', - 2 => 'Échange', - 3 => 'Défectueux', - ); - $reasons = array( - // 1 => 'CLIENT : Annulation pré-envoi', - 2 => 'CLIENT : Rétractation post-envoi', - 11 => 'CLIENT : Annulation pour ré-achat', - 4 => 'FEUR : Problème SAV', - 5 => 'FEUR : Produit manquant', - 3 => 'BBB : Erreur Achat / Prod', - 6 => 'BBB : Erreur Logistique ', - 8 => 'BBB : Pbme Site / Paiment', - 12 => 'BBB : Suspicion de fraude', - 9 => 'TRANS : Colis détruit', - 10 => 'TRANS : Colis perdu', - 7 => 'Autre' - ); - - echo ' -

-

'.$this->l('Create a product return').'

-
-
    '; - foreach($returnable as $id_order_detail => $product) { - echo ' -
  • x '.$product[0]. '
  • -
  • '; - for($i = 1; $i <= $product[1]; $i++) { - echo '

    - -
    - - -


    '; - } - echo '
  • '; - } - echo '
-

- - -

-

+ (SELECT COUNT(od.`id_order`) FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order` = a.`id_order` GROUP BY `id_order`) AS product_number, + a.id_order AS `mixed`, + x.`id_country` + '; + + $this->_join = 'LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = a.`id_customer`) + LEFT JOIN `'._DB_PREFIX_.'address` x ON (x.`id_address` = a.`id_address_delivery`) + LEFT JOIN `'._DB_PREFIX_.'order_history` oh ON (oh.`id_order` = a.`id_order`) + LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = oh.`id_order_state`) + LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)($cookie->id_lang).')'; + $this->_where = 'AND oh.`id_order_history` = (SELECT MAX(`id_order_history`) FROM `'._DB_PREFIX_.'order_history` moh WHERE moh.`id_order` = a.`id_order` GROUP BY moh.`id_order`)'; + + $statesArray = array(); + $states = OrderState::getOrderStates((int)($cookie->id_lang)); + + $order_errors = Db::getInstance()->ExecuteS('SELECT id_order FROM ps_orders WHERE id_order NOT IN (select id_order from ps_order_history)'); + if(count($order_errors) > 0) echo '

'; + foreach($order_errors as $error_order) { + echo 'Erreur commande n°'.$error_order['id_order'].'
'; + } + if(count($order_errors) > 0) echo '

'; + + $country_array = array(); + foreach(Country::getCountries((int) $cookie->id_lang, TRUE) as $country) { + $country_array[(int) $country['id_country']] = $country['name']; + } + + foreach ($states AS $state) + $statesArray[$state['id_order_state']] = $state['name']; + $this->fieldsDisplay = array( + 'id_order' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25), + 'new' => array('title' => $this->l('New'), 'width' => 25, 'align' => 'center', 'type' => 'bool', 'filter_key' => 'new', 'tmpTableFilter' => true, 'icon' => array(0 => 'blank.gif', 1 => 'news-new.gif'), 'orderby' => false), + 'customer' => array('title' => $this->l('Customer'), 'widthColumn' => 160, 'width' => 140, 'filter_key' => 'customer', 'tmpTableFilter' => true), + 'total_paid' => array('title' => $this->l('Total'), 'width' => 70, 'align' => 'right', 'prefix' => '', 'suffix' => '', 'price' => true, 'currency' => true), + 'payment' => array('title' => $this->l('Payment'), 'width' => 100), + 'osname' => array('title' => $this->l('Status'), 'widthColumn' => 230, 'type' => 'select', 'select' => $statesArray, 'filter_key' => 'os!id_order_state', 'filter_type' => 'int', 'width' => 200), + 'date_add' => array('title' => $this->l('Date'), 'width' => 35, 'align' => 'right', 'type' => 'datetime', 'filter_key' => 'a!date_add'), + //'mixed' => array('title' => $this->l('Mixed'), 'callback' => 'printMixedSale', 'orderby' => false, 'search' => false), + 'id_pdf' => array('title' => $this->l('PDF'), 'callback' => 'printPDFIcons', 'orderby' => false, 'search' => false), + 'id_country' => array('title' => $this->l('Pays'), 'callback' => 'printCountry', 'orderby' => false, 'type' => 'select', 'select' => $country_array, 'filter_key' => 'x!id_country', 'filter_type' => 'int', 'width' => 35,), + ); + parent::__construct(); + + if(!isset($_POST['submitFilter']) && !isset($_POST['orderFilter_a!date_add'])) { + $_POST['orderFilter_a!date_add'][0] = date('Y-m-d'); + $_POST['orderFilter_a!date_add'][1] = date('Y-m-d'); + $_POST['submitFilter'] = 1; + $_POST['submitFilterorder'] = 1; + } + } + + /** + * @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( + '{followup}' => str_replace('@', $order->shipping_number, $carrier->url), + '{firstname}' => $customer->firstname, + '{lastname}' => $customer->lastname, + '{id_order}' => (int)($order->id) + ); + @Mail::Send((int)($order->id_lang), 'in_transit', Mail::l('Package in transit'), $templateVars, + $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL, NULL, + _PS_MAIL_DIR_, true); + } + } + else + $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); + } + + elseif(Tools::getValue('send_return_instruction') && Tools::getValue('id_order_return')) { + $id_order = (int) Tools::getValue('id_order'); + $id_order_return = (int) Tools::getValue('id_order_return'); + if(Validate::isLoadedObject($order = new Order($id_order))) { + $customer = new Customer($order->id_customer); + $return_link = Db::getInstance()->getRow(' + SELECT `return_number`, `link` + FROM `'._DB_PREFIX_.'order_return_link` + WHERE `id_order_return` = '.(int) $id_order_return.' + '); + $products = Db::getInstance()->ExecuteS(' + SELECT `id_order_detail`, `product_quantity` + FROM `'._DB_PREFIX_.'order_return_detail` + WHERE `id_order_return` = '.(int) $id_order_return.' + '); + $product_list = '
    '; + $product_list_txt = array(); + foreach($products as $key => $product){ + $product_name = Db::getInstance()->getValue(' + SELECT `product_name` + FROM `'._DB_PREFIX_.'order_detail` + WHERE `id_order_detail` = '.(int) $product['id_order_detail'].' + '); + $product_list_txt[] = (int) $product['product_quantity'].' x '.$product_name; + $product_list .= '
  • '.(int) $product['product_quantity'].' x '.htmlentities($product_name).'
  • '; + } + $product_list .= '
'; + Mail::Send( + intval($order->id_lang), + 'order_return_2', + $subject[(int) $order->id_lang], + array( + '{id_order}' => $order->id, + '{return_link}' => $return_link['link'], + '{product_list}' => $product_list, + '{product_list_txt}' => implode("\r\n", $product_list_txt), + ), + $customer->email, + $customer->firstname.' '.$customer->lastname + ); + } + } + elseif(Tools::isSubmit('submitCreateReturn')) { + $id_order = (int) Tools::getValue('id_order'); + if(Validate::isLoadedObject($order = new Order($id_order)) && ($address_delivery = Db::getInstance()->getRow(' + SELECT * + FROM `'._DB_PREFIX_.'address` + WHERE `id_address` = '.(int) $order->id_address_delivery.' + ')) && in_array((int) $address_delivery['id_country'], array(3, 6, 8, 12))) { + $returnable = array(); + foreach(Db::getInstance()->ExecuteS(' + SELECT d.`id_order_detail`, d.`id_order`, d.`product_name`, d.`product_quantity_return`, d.`product_quantity_refunded`, d.`product_quantity`, c.`id_sale`, d.`product_weight` + FROM `'._DB_PREFIX_.'order_detail` d + LEFT JOIN `'._DB_PREFIX_.'product_ps_cache` c + ON d.`product_id` = c.`id_product` + WHERE d.`id_order` = '.(int) $order->id.' + ') as $product) { + $qty = OrderReturn::getOrderDetailReturnQty($product); + if($qty > 0) { + $returnable[$product['id_order_detail']] = array($product['product_name'], $qty, $product['product_weight']); + } + } + } + $error = FALSE; + $total_weight = 0.0; + $return_reasons = array(); + foreach(Tools::getValue('return_product') as $id_order_detail => $qty) { + if(!isset($returnable[(int) $id_order_detail]) || $returnable[(int) $id_order_detail][1] < $qty) { + $error = TRUE; + } else { + for($i = 1; $i <= $qty; $i++) { + if(!($return_reason = Tools::getValue('return_reason_'.$id_order_detail.'_'.$i))) { + $error = true; + $this->_errors[] = Tools::displayError('Order detail #%s empty return reason'); + } elseif(!($return_instruction = Tools::getValue('return_instruction_'.$id_order_detail.'_'.$i))) { + $error = true; + $this->_errors[] = Tools::displayError('Order detail #%s empty return instruction'); + } else { + $return_reasons[] = array($id_order_detail, $i, $return_reason, $return_instruction); + } + } + $total_weight += $qty * $returnable[(int) $id_order_detail][2]; + } + } + if(!$error) { + Db::getInstance()->Execute(' + INSERT INTO `'._DB_PREFIX_.'order_return` + VALUES ( + DEFAULT, + '.(int) $order->id_customer.', + '.(int) $order->id.', + 2, + "'.''/* QUESTION */.'", + NOW(), + NOW() + ) + '); + $id_order_return = Db::getInstance()->Insert_ID(); + foreach($return_reasons as $return_reason) { + Db::getInstance()->Execute(' + INSERT INTO `'._DB_PREFIX_.'order_return_detail_qty` (`id_order_return`, `id_order_detail`, `qty`, `reason`, `instruction`) + VALUES ( + '.(int) $id_order_return.', + '.(int) $return_reason[0].', + '.(int) $return_reason[1].', + '.(int) $return_reason[2].', + '.(int) $return_reason[3].' + ) + '); + } + $product_list = '
    '; + $product_list_txt = array(); + foreach(Tools::getValue('return_product') as $id_order_detail => $qty) { + if($qty > 0) { + Db::getInstance()->Execute(' + INSERT INTO `'._DB_PREFIX_.'order_return_detail` + VALUES ( + '.(int) $id_order_return.', + '.(int) $id_order_detail.', + 0, + '.(int) $qty.' + ) + '); + $product_name = Db::getInstance()->getValue(' + SELECT `product_name` + FROM `'._DB_PREFIX_.'order_detail` + WHERE `id_order_detail` = '.(int) $id_order_detail.' + '); + $product_list_txt[] = (int) $qty.' x '.$product_name; + $product_list .= '
  • '.(int) $qty.' x '.htmlentities($product_name).'
  • '; + } + } + $product_list .= '
'; + if($order->id_lang == 3) { + // Spain + if((int) Tools::getValue('return_option') == 2) { + // Free + $pcode = '11'; + $chars = array('I', 'O', 'P', 'S', 'T', ); + $return_link = 'http://devoluciones.puntopack.es/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=ES&Language=es'; + } + // else { + // // Paid + // $pcode = '08'; + // $chars = array('A', 'E', 'K', 'R', 'Z', ); + // $return_link = 'http://devoluciones.puntopack.es/d/F1BEBEBO/?SiteId=F1BEBEBO4&Country=ES&Language=es'; + // } + } else { + if((int) $address_delivery['id_country'] == 3) { + // Belgium + if((int) Tools::getValue('return_option') == 2) { + // Free + $pcode = '36'; + $chars = array('K', 'P', 'T', 'S', 'W', 'Z', ); + $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=BE&Language=fr'; + } + // else { + // // Paid + // $pcode = '24'; + // $chars = array('C', 'J', 'L', 'M', 'N', 'R', ); + // $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO5&Country=BE&Language=fr'; + // } + } elseif((int) $address_delivery['id_country'] == 6) { + // Spain + if((int) Tools::getValue('return_option') == 2) { + // Free + $pcode = '11'; + $chars = array('I', 'O', 'P', 'S', 'T', ); + $return_link = 'http://devoluciones.puntopack.es/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=ES&Language=fr'; + } + // else { + // // Paid + // $pcode = '08'; + // $chars = array('A', 'E', 'K', 'R', 'Z', ); + // $return_link = 'http://devoluciones.puntopack.es/d/F1BEBEBO/?SiteId=F1BEBEBO4&Country=ES&Language=fr'; + // } + } elseif((int) $address_delivery['id_country'] == 8) { + // France + if((int) Tools::getValue('return_option') == 2) { + // Free + $pcode = '05'; + $chars = array('L', 'J', 'R', 'N', 'W', ); + $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=FR&Language=fr'; + } + // else { + // // Paid + // $pcode = '01'; + // $chars = array('B', 'C', 'D', 'G', 'V', ); + // $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO6&Country=FR&Language=fr'; + // } + } + // elseif((int) $address_delivery['id_country'] == 12) { + // // Luxemburg + // if((int) Tools::getValue('return_option') == 2) { + // // Free + // $pcode = '05'; + // $chars = array('L', 'J', 'R', 'N', 'W', ); + // $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO&Country=LU&Language=fr'; + // } else { + // // Paid + // $pcode = '01'; + // $chars = array('B', 'C', 'D', 'G', 'V', ); + // $return_link = 'http://retours.mondialrelay.com/d/F1BEBEBO/?SiteId=F1BEBEBO6&Country=LU&Language=fr'; + // } + // } + } + Db::getInstance()->Execute('SET AUTOCOMMIT = 0'); + Db::getInstance()->Execute('START TRANSACTION'); + $cpt = Db::getInstance()->ExecuteS(' + SELECT `number` + FROM `'._DB_PREFIX_.'order_return_link_number` + WHERE `carrier` = "mondialrelay" + FOR UPDATE + '); + $cpt = (int) $cpt[0]['number'] + 1; + Db::getInstance()->ExecuteS(' + UPDATE `'._DB_PREFIX_.'order_return_link_number` + SET `number` = '.(int) $cpt.' + WHERE `carrier` = "mondialrelay" + '); + Db::getInstance()->Execute('COMMIT'); + Db::getInstance()->Execute('SET AUTOCOMMIT = 1'); + $cpt = sprintf('%06d', $cpt); + $return_number = 'R'.substr($cpt, 0, 2).chr(65 + rand(0, 25)).substr($cpt, 2, 2).$chars[rand(0, count($chars) - 1)].substr($cpt, 4, 2).'P'.$pcode.substr($pcode, 0, 1).substr($cpt, 5, 1).substr($pcode, 1, 1); + $return_link .= '&Email='.rawurlencode(Db::getInstance()->getValue(' + SELECT `email` + FROM `'._DB_PREFIX_.'customer` + WHERE `id_customer` = '.(int) $order->id_customer.' + ')).'&CustomReference='.$return_number.'&Adress1='.rawurlencode($address_delivery['lastname']).'&Adress2='.rawurlencode($address_delivery['firstname']).'&Adress3='.rawurlencode($address_delivery['address1']).'&Adress4='.rawurlencode($address_delivery['address2']).'&PostCode='.rawurlencode($address_delivery['postcode']).'&City='.rawurlencode($address_delivery['city']).'&WeightInGramm='.((int) ($total_weight * 1000)); + Db::getInstance()->Execute(' + INSERT INTO `'._DB_PREFIX_.'order_return_link` + VALUES ( + '.(int) $id_order_return.', + '.(int) $cookie->id_employee.', + NOW(), + '.((int) Tools::getValue('return_option') == 2? 1: 0).', + 0, + "mondialrelay", + "'.pSQL($return_number).'", + "'.pSQL($return_link).'", + "'.pSQL(nl2br2(strip_tags(trim(Tools::getValue('return_comment')))), TRUE).'" + ) + '); + $subject = array( + 1 => 'Your order return #'.$id_order_return, + 2 => 'Votre demande de retour n°'.$id_order_return, + 3 => 'Solicitud de devolución n°'.$id_order_return, + 5 => 'La vostra domanda di restituzione #'.$id_order_return, + 6 => 'Your order return #'.$id_order_return, + ); + $customer = new Customer($order->id_customer); + Mail::Send( + intval($order->id_lang), + 'order_return_'.((int) Tools::getValue('return_option') == 2? '2': '3'), + $subject[(int) $order->id_lang], + array( + '{id_order}' => $order->id, + '{return_link}' => $return_link, + '{product_list}' => $product_list, + '{product_list_txt}' => implode("\r\n", $product_list_txt), + ), + $customer->email, + $customer->firstname.' '.$customer->lastname + ); + } + header('Location: '.$_SERVER['REQUEST_URI']); + exit; + } + + + /* Change order state, add a new entry in order history and send an e-mail to the customer if needed */ + 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 + { + $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 == Configuration::get('PS_OS_SHIPPING') AND $order->shipping_number) + $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url)); + elseif ($history->id_order_state == Configuration::get('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 == Configuration::get('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 (Tools::getValue('noSendMail')) { + if ($history->add()) + Tools::redirectAdmin($currentIndex.'&id_order='.$id_order.'&vieworder'.'&token='.$this->token); + } else { + 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.'); + } + + /* Add a new message for the current order and send an e-mail to the customer if needed */ + 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').' '.$field.' '.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').' '.$field.' '.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').' '.$field.' '.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, NULL, NULL, NULL, NULL, _PS_MAIL_DIR_, true)) + 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.'); + } + + /* Cancel product from order */ + 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)); + + // @Addition Antadis - prevent reinjection when the product is sent by Philea + $is_philea = DB::getInstance()->getValue(' + SELECT p.`id_sale` + FROM `'._DB_PREFIX_.'philea_sync` p + LEFT JOIN `'._DB_PREFIX_.'product_ps_cache` ps ON (ps.`id_sale` = p.`id_sale`) + WHERE ps.`id_product`='.$orderDetail->product_id + ); + // @Addition Antadis - prevent reinjection when the product is in Braderie + $is_braderie = (int)DB::getInstance()->getValue(' + SELECT p.`braderie` + FROM `'._DB_PREFIX_.'privatesale` p + LEFT JOIN `'._DB_PREFIX_.'product_ps_cache` ps ON (ps.`id_sale` = p.`id_sale`) + WHERE ps.`id_product`='.$orderDetail->product_id + ); + + // Reinject product + if ( + !$order->hasBeenDelivered() + OR ($order->hasBeenDelivered() AND Tools::isSubmit('reinjectQuantities') AND !$is_philea AND !$is_braderie) + ){ + if( + (($is_philea || $is_braderie) && !$order->hasBeenShipped() && !$order->hasBeenDelivered()) + || (!$is_philea && !$is_braderie) + ){ + $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').' '.$orderDetail->product_name.''; + 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.').' '.$orderDetail->product_name.''; + 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']) OR isset($_POST['generateDiscount2'])) AND !sizeof($this->_errors)) + { + $customer = new Customer((int)($order->id_customer)); + $params['{lastname}'] = $customer->lastname; + $params['{firstname}'] = $customer->firstname; + $params['{id_order}'] = $order->id; + + /* PRODUIT REMBOURSE */ + $products_refund = ""; + $total_refund = 0; + foreach ($productList as $key => $id_order_detail) { + $details_refund = new OrderDetail($id_order_detail); + + $tprice = $details_refund->product_price * (1 - $details_refund->reduction_percent / 100) - $details_refund->reduction_amount; + $tprice = $tprice * ( 1+ $details_refund->tax_rate / 100 ); + + $products_refund .= " + + ". $details_refund->product_name . " + " . Tools::displayPrice($tprice) . " + ". (int)$full_quantity_list[$id_order_detail] ." + " . Tools::displayPrice(($tprice * (int)$full_quantity_list[$id_order_detail])) . " + + "; + $total_refund = $total_refund + ($tprice * (int)$full_quantity_list[$id_order_detail]); + } + + $params['{products}'] = $products_refund; + $params['{total_products}'] = Tools::displayPrice($total_refund); + + $fraisport = ""; + if(isset($_POST['shippingBack'])) + { + $order = new Order($details_refund->id_order); + Module::hookExec('cancelShipping', array('order' => $order)); + $fraisport .= " + + Frais de port + " . Tools::displayPrice($order->total_shipping) . " + + "; + } + + $params['{fraisport}'] = $fraisport; + + } + + // Generate voucher + if (isset($_POST['generateDiscount']) AND !sizeof($this->_errors)) + { + if (!$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Geste commercial concernant la commande '), 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, NULL, NULL, NULL, + // NULL, _PS_MAIL_DIR_, true); + + /* MODIF MAIL ANTADIS */ + + $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); + $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false); + $params['{voucher_num}'] = $voucher->name; + $params['{voucher_value}'] = $voucher->value; + @Mail::Send((int)($order->id_lang), 'refundorder', Mail::l('New voucher regarding your order'), + $params, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL, + NULL, _PS_MAIL_DIR_, true); + } + } + + // Generate voucher 2 @Addition Antadis + if (isset($_POST['generateDiscount2']) AND !sizeof($this->_errors)) + { + if (!$voucher = Discount::createOrderDiscount($order, $full_product_list, $full_quantity_list, $this->l('Geste commercial concernant la commande '), isset($_POST['shippingBack']),0,0,5)) + $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; + $params['{voucher_value}'] = $voucher->value; + @Mail::Send((int)($order->id_lang), 'refundorder', Mail::l('New voucher regarding your order'), + $params, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL, + NULL, _PS_MAIL_DIR_, true); + } + } + + // 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', $order->id_lang), + $params, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, NULL, NULL, + _PS_MAIL_DIR_, true); + } + } + + // update order state if it's partial + if($order->getCurrentState() == 17) { + $partial = true; + + $to_send = Db::getInstance()->ExecuteS(' + SELECT `id_order_detail`, (`product_quantity` - IF(`product_quantity_return` > 0, `product_quantity_return`, `product_quantity_refunded`)) AS `quantity`, `product_id` + FROM `'._DB_PREFIX_.'order_detail` + WHERE `id_order` = '.(int) $order->id.' + AND (`product_quantity` - IF(`product_quantity_return` > 0, `product_quantity_return`, `product_quantity_refunded`)) > 0 + '); + + if(count($to_send) == 0) { + $partial = false; + } else { + include_once dirname(__FILE__).'/../../modules/privatesales/Sale.php'; + $quantities_sent = array(); + + $product_ids = array(); + foreach(Db::getInstance()->ExecuteS(' + SELECT `product_id` + FROM `'._DB_PREFIX_.'order_detail` + WHERE `id_order` = '.(int) $order->id.' + ') as $row) { + $product_ids[] = (int) $row['product_id']; + } + + /** + * @Override Philea + */ + if(Db::getInstance()->getRow(' + SELECT * + FROM `'._DB_PREFIX_.'philea_parcel` + WHERE `id_order` = '.(int) $order->id.' + ')) { + foreach(Db::getInstance()->ExecuteS(' + SELECT c.`id_product` + FROM `'._DB_PREFIX_.'product_ps_cache` c + WHERE c.`id_product` IN ('.implode(', ', $products_ids).') + ') as $row) { + $quantities_sent[(int) $row['id_product']] = -1; + } + } + + $parcel_quantities = array(); + foreach($to_send as $ts) { + if(!isset($quantities_sent[(int) $ts['product_id']])) { + $parcel_quantities[(int) $ts['id_order_detail']] = $ts; + } + } + + if(count($parcel_quantities) > 0) { + $partial = false; + $sent_logistics = array(); + + foreach(Db::getInstance()->ExecuteS(' + SELECT SUM(`quantity`) AS `quantity`, `id_order_detail` + FROM `'._DB_PREFIX_.'lapostews` + WHERE `id_order_detail` IN ('.implode(', ', array_keys($parcel_quantities)).') + GROUP BY `id_order_detail` + ') as $row) { + $sent_logistics[(int) $row['id_order_detail']] = (int) $row['quantity']; + } + + foreach(Db::getInstance()->ExecuteS(' + SELECT SUM(`quantity`) AS `quantity`, `id_order_detail` + FROM `'._DB_PREFIX_.'mondialrelay_parcel` + WHERE `id_order_detail` IN ('.implode(', ', array_keys($parcel_quantities)).') + GROUP BY `id_order_detail` + ') as $row) { + $sent_logistics[(int) $row['id_order_detail']] = (int) $row['quantity']; + } + + foreach(Db::getInstance()->ExecuteS(' + SELECT SUM(`quantity`) AS `quantity`, `id_order_detail` + FROM `'._DB_PREFIX_.'exapaqws` + WHERE `id_order_detail` IN ('.implode(', ', array_keys($parcel_quantities)).') + GROUP BY `id_order_detail` + ') as $row) { + $sent_logistics[(int) $row['id_order_detail']] = (int) $row['quantity']; + } + + if(count($sent_logistics) == 0) { + $partial = true; + } else { + foreach($parcel_quantities as $k => $v) { + if(!isset($sent_logistics[(int) $k])) { + $partial = true; + break; + } else { + if($sent_logistics[(int) $k] < $v['quantity']) { + $partial = true; + break; + } + } + } + } + } else { + $partial = false; + } + + if(!$partial) { + global $cookie; + Db::getInstance()->ExecuteS(' + INSERT INTO `'._DB_PREFIX_.'order_history` + VALUES ( + DEFAULT, + '.(int) $cookie->id_employee.', + '.(int) $order->id.', + '.Configuration::get('PS_OS_SHIPPING').', + NOW() + ) + '); + Db::getInstance()->ExecuteS(' + INSERT INTO `'._DB_PREFIX_.'order_state_current` + VALUES ( + '.(int) $order->id.', + '.Configuration::get('PS_OS_SHIPPING').', + NOW() + ) + ON DUPLICATE KEY UPDATE + `id_order_state` = '.Configuration::get('PS_OS_SHIPPING').', + `date_upd` = NOW() + '); + $newOS = new OrderState((int)(Configuration::get('PS_OS_SHIPPING')), $order->id_lang); + Module::hookExec('updateOrderStatus', array('newOrderStatus' => $newOS, 'id_order' => (int)($order->id))); + } + } + } + } + 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 (isset($_GET['messageReaded'])) + { + Message::markAsReaded((int)($_GET['messageReaded']), (int)($cookie->id_employee)); + } + parent::postProcess(); + } + + private function displayCustomizedDatas(&$customizedDatas, &$product, &$currency, &$image, $tokenCatalog, $id_order_detail) + { + if (!($order = $this->loadObject())) + return; + + if (is_array($customizedDatas) AND isset($customizedDatas[(int)($product['product_id'])][(int)($product['product_attribute_id'])])) + { + $imageObj = new Image($image['id_image']); + echo ' + + '.(isset($image['id_image']) ? cacheImage(_PS_IMG_DIR_.'p/'.$imageObj->getExistingImgPath().'.jpg', + 'product_mini_'.(int)($product['product_id']).(isset($product['product_attribute_id']) ? '_'.(int)($product['product_attribute_id']) : '').'.jpg', 45, 'jpg') : '--').' + + '.$product['product_name'].' - '.$this->l('customized').'
+ '.($product['product_reference'] ? $this->l('Ref:').' '.$product['product_reference'].'
' : '') + .($product['product_supplier_reference'] ? $this->l('Ref Supplier:').' '.$product['product_supplier_reference'] : '') + .'
+ '.Tools::displayPrice($product['product_price_wt'], $currency, false).' + '.$product['customizationQuantityTotal'].' + '.($order->hasBeenPaid() ? ''.$product['customizationQuantityRefunded'].'' : '').' + '.($order->hasBeenDelivered() ? ''.$product['customizationQuantityReturned'].'' : '').' + - + '.Tools::displayPrice(Tools::ps_round($order->getTaxCalculationMethod() == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'], 2) * $product['customizationQuantityTotal'], $currency, false).' + -- + '; + foreach ($customizedDatas[(int)($product['product_id'])][(int)($product['product_attribute_id'])] AS $customizationId => $customization) + { + echo ' + + '; + foreach ($customization['datas'] AS $type => $datas) + if ($type == _CUSTOMIZE_FILE_) + { + $i = 0; + echo '
    '; + foreach ($datas AS $data) + echo '
  • + +
  • '; + echo '
'; + } + elseif ($type == _CUSTOMIZE_TEXTFIELD_) + { + $i = 0; + echo '
    '; + foreach ($datas AS $data) + echo '
  • '.($data['name'] ? $data['name'] : $this->l('Text #').++$i).$this->l(':').' '.$data['value'].'
  • '; + echo '
'; + } + echo ' + - + '.$customization['quantity'].' + '.($order->hasBeenPaid() ? ''.$customization['quantity_refunded'].'' : '').' + '.($order->hasBeenDelivered() ? ''.$customization['quantity_returned'].'' : '').' + - + '.Tools::displayPrice(Tools::ps_round($order->getTaxCalculationMethod() == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'], 2) * $customization['quantity'], $currency, false).' + + + + '; + if ((!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) AND (int)(($customization['quantity_returned']) < (int)($customization['quantity']))) + echo ' + = (int)($customization['quantity'])) ? 'disabled="disabled" ' : '').'/>'; + else + echo '--'; + echo ' + + '; + if ((int)($customization['quantity_returned'] + $customization['quantity_refunded']) >= (int)($customization['quantity'])) + echo ''; + elseif (!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) + echo ' + '; + echo ($order->hasBeenDelivered() ? (int)($customization['quantity_returned']).'/'.((int)($customization['quantity']) - (int)($customization['quantity_refunded'])) : ($order->hasBeenPaid() ? (int)($customization['quantity_refunded']).'/'.(int)($customization['quantity']) : '')).' + '; + echo ' + '; + } + } + } + + private function getCancelledProductNumber(&$order, &$product) + { + $productQuantity = array_key_exists('customizationQuantityTotal', $product) ? $product['product_quantity'] - $product['customizationQuantityTotal'] : $product['product_quantity']; + $productRefunded = $product['product_quantity_refunded']; + $productReturned = $product['product_quantity_return']; + $content = '0/'.$productQuantity; + if ($order->hasBeenDelivered()) + $content = $productReturned.'/'.($productQuantity - $productRefunded); + elseif ($order->hasBeenPaid()) + $content = $productRefunded.'/'.$productQuantity; + return $content; + } + + public function viewDetails() + { + global $currentIndex, $cookie, $link; + $irow = 0; + if (!($order = $this->loadObject())) + return; + + $customer = new Customer($order->id_customer); + $customerStats = $customer->getStats(); + $addressInvoice = new Address($order->id_address_invoice, (int)($cookie->id_lang)); + if (Validate::isLoadedObject($addressInvoice) AND $addressInvoice->id_state) + $invoiceState = new State((int)($addressInvoice->id_state)); + $addressDelivery = new Address($order->id_address_delivery, (int)($cookie->id_lang)); + if (Validate::isLoadedObject($addressDelivery) AND $addressDelivery->id_state) + $deliveryState = new State((int)($addressDelivery->id_state)); + $carrier = new Carrier($order->id_carrier); + $history = $order->getHistory($cookie->id_lang); + $products = $order->getProducts(); + $customizedDatas = Product::getAllCustomizedDatas((int)($order->id_cart)); + Product::addCustomizationPrice($products, $customizedDatas); + $discounts = $order->getDiscounts(); + $messages = Message::getMessagesByOrderId($order->id, true); + $states = OrderState::getOrderStates((int)($cookie->id_lang)); + $currency = new Currency($order->id_currency); + $currentLanguage = new Language((int)($cookie->id_lang)); + $currentState = OrderHistory::getLastOrderState($order->id); + $sources = ConnectionsSource::getOrderSources($order->id); + $cart = Cart::getCartByOrderId($order->id); + + $row = array_shift($history); + + if ($prevOrder = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders WHERE id_order < '.(int)$order->id.' ORDER BY id_order DESC')) + $prevOrder = ''; + if ($nextOrder = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders WHERE id_order > '.(int)$order->id.' ORDER BY id_order ASC')) + $nextOrder = ''; + + + if ($order->total_paid != $order->total_paid_real) + echo '
'.$this->l('Warning:').' '.Tools::displayPrice($order->total_paid_real, $currency, false).' '.$this->l('paid instead of').' '.Tools::displayPrice($order->total_paid, $currency, false).' !


'; + + // display bar code if module enabled + $hook = Module::hookExec('invoice', array('id_order' => $order->id)); + if ($hook !== false) + { + echo '
'; + echo $hook; + echo '

'; + } + + // display order header + echo ' +
'; + echo '

+ '.$prevOrder.' + '.(Validate::isLoadedObject($customer) ? $customer->firstname.' '.$customer->lastname.' - ' : '').$this->l('Order #').sprintf('%06d', $order->id).' + '.$nextOrder.' +

+
+ '.((($currentState->invoice OR $order->invoice_number) AND count($products)) + ? ''.$this->l('View invoice').' '.$this->l('View invoice').'' + : ''.$this->l('No invoice').' '.$this->l('No invoice')).' - + '.(($currentState->delivery OR $order->delivery_number) + ? ''.$this->l('View delivery slip').' '.$this->l('View delivery slip').'' + : ''.$this->l('No delivery slip').' '.$this->l('No delivery slip')).' - + '.$this->l('Print order').' '.$this->l('Print page').' +
+
 
'; + + /* Display current status */ + echo ' + + + + + + + '; + /* Display previous status */ + foreach ($history AS $row) + { + echo ' + + + + + + '; + } + echo ' +
'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).''.stripslashes($row['ostate_name']).''.((!empty($row['employee_lastname'])) ? '('.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'
'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).''.stripslashes($row['ostate_name']).''.((!empty($row['employee_lastname'])) ? '('.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'
+
'; + + /* Display status form */ + echo ' + + +
+ Ne pas envoyer de mail + + + + '; + + /* Display customer information */ + if (Validate::isLoadedObject($customer)) + { + echo '
+
+ '.$this->l('Customer information').' + '.$customer->firstname.' '.$customer->lastname.' ('.$this->l('#').$customer->id.')
+ ('.$customer->email.')

'; + if ($customer->isGuest()) + { + echo ' + '.$this->l('This order has been placed by a').' '.$this->l('guest').''; + if (!Customer::customerExists($customer->email)) + { + echo '
+ +

+ '.$this->l('This feature will generate a random password and send an e-mail to the customer').' +
'; + } + else + echo '
'.$this->l('A registered customer account exists with the same email address').'
'; + } + else + { + echo $this->l('Account registered:').' '.Tools::displayDate($customer->date_add, (int)($cookie->id_lang), true).'
+ '.$this->l('Valid orders placed:').' '.$customerStats['nb_orders'].'
+ '.$this->l('Total paid since registration:').' '.Tools::displayPrice(Tools::ps_round(Tools::convertPrice($customerStats['total_orders'], $currency), 2), $currency, false).'
'; + } + echo '
'; + } + + /* Display sources */ + if (sizeof($sources)) + { + echo '
+
'.$this->l('Sources').'
    3 ? 'style="height: 200px; overflow-y: scroll; width: 360px;"' : '').'>'; + foreach ($sources as $source) + echo '
  • + '.Tools::displayDate($source['date_add'], (int)($cookie->id_lang), true).'
    + '.$this->l('From:').' '.preg_replace('/^www./', '', parse_url($source['http_referer'], PHP_URL_HOST)).'
    + '.$this->l('To:').' '.$source['request_uri'].'
    + '.($source['keywords'] ? ''.$this->l('Keywords:').' '.$source['keywords'].'
    ' : '').'
    +
  • '; + echo '
'; + } + // display hook specified to this page : AdminOrder + if (($hook = Module::hookExec('adminOrder', array('id_order' => $order->id))) !== false) + echo $hook; + + echo ' +
+
'; + + /* Display invoice information */ + echo '
'; + if (($currentState->invoice OR $order->invoice_number) AND count($products)) + echo ' '.$this->l('Invoice').' + '.$this->l('Invoice #').''.Configuration::get('PS_INVOICE_PREFIX', (int)($cookie->id_lang)).sprintf('%06d', $order->invoice_number).' +
'.$this->l('Created on:').' '.Tools::displayDate($order->invoice_date, (int)$cookie->id_lang, true); + else + echo ''.$this->l('Invoice').' + '.$this->l('No invoice yet.'); + echo '

'; + + /* Display shipping infos */ + $sql = "SELECT `shipping_number`, `date_add` FROM `ps_lapostews` WHERE `id_order` =". $order->id; + $sql2 = "SELECT DISTINCT ppp.`shipping_number`, ppp.`date_add` + FROM `ps_philea_parcel` ppp + LEFT JOIN `ps_order_detail` od ON (od.`id_order_detail` = ppp.`id_order_detail`) + WHERE od.`id_order` =". $order->id; + $numbers = Db::getInstance()->ExecuteS($sql); + $numbers2 = Db::getInstance()->ExecuteS($sql2); + echo ' +
'; + if(count($numbers) > 0){ + foreach ($numbers as $key => $number) { + $date = new DateTime($number['date_add']); + echo '

Numéro de suivi : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .'

'; + } + } + if(count($numbers2) > 0){ + foreach ($numbers2 as $key => $number) { + $date = new DateTime($number['date_add']); + echo '

Numéro de suivi : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .'

'; + } + } + echo ' '.$this->l('Shipping information').' + '.$this->l('Total weight:').' '.number_format($order->getTotalWeight(), 3).' '.Configuration::get('PS_WEIGHT_UNIT').'
+ '.$this->l('Carrier:').' '.($carrier->name == '0' ? Configuration::get('PS_SHOP_NAME') : $carrier->name).'
+ '.(($currentState->delivery OR $order->delivery_number) ? '
'.$this->l('Delivery slip #').''.Configuration::get('PS_DELIVERY_PREFIX', (int)($cookie->id_lang)).sprintf('%06d', $order->delivery_number).'
' : ''); + if ($order->shipping_number) + echo $this->l('Tracking number:').' '.$order->shipping_number.' '.(!empty($carrier->url) ? '('.$this->l('Track the shipment').')' : ''); + + /* Carrier module */ + if ($carrier->is_module == 1) + { + $module = Module::getInstanceByName($carrier->external_module_name); + if (method_exists($module, 'displayInfoByCart')) + echo call_user_func(array($module, 'displayInfoByCart'), $order->id_cart); + } + + /* Display shipping number field */ + if ($carrier->url && $order->hasBeenShipped()) + echo ' +
+ + + +
'; + echo ' +
'; + + $shippings = Db::getInstance()->ExecuteS(' + SELECT p.* + FROM `'._DB_PREFIX_.'lapostews` p + LEFT JOIN `'._DB_PREFIX_.'order_detail` o ON o.`id_order_detail` = p.`id_order_detail` + WHERE o.id_order = ' .(int)$order->id . ' + GROUP BY p.`shipping_number` + ORDER BY `date_add` + '); + + if ($shippings) { + echo ' +
+
+ '.$this->l('Numéro(s) de suivi').' + + + + + + '; + foreach ($shippings as $key => $shipping) { + echo ' + + + + '; + } + echo '
'.$this->l('Date').''.$this->l('Numéro de suivi').''.$this->l('Lien').'
'.date('d/m/Y', strtotime($shipping['date_add'])).''. $shipping['shipping_number'] .''.$this->l('Voir').'
+
'; + } + + /* Display summary order */ + echo ' +
+
+ '.$this->l('Order details').' + +
'.$this->l('Cart #').sprintf('%06d', $cart->id).'
+ +
'.Tools::substr($order->payment, 0, 32).' '.($order->module ? '('.$order->module.')' : '').'
+
+ + + '.($order->total_discounts > 0 ? '' : '').' + '.($order->total_wrapping > 0 ? '' : '').' + + +
'.$this->l('Products').''.Tools::displayPrice($order->getTotalProductsWithTaxes(), $currency, false).'
'.$this->l('Discounts').'-'.Tools::displayPrice($order->total_discounts, $currency, false).'
'.$this->l('Wrapping').''.Tools::displayPrice($order->total_wrapping, $currency, false).'
'.$this->l('Shipping').''.Tools::displayPrice($order->total_shipping, $currency, false).'
'.$this->l('Total').''.Tools::displayPrice($order->total_paid, $currency, false).($order->total_paid != $order->total_paid_real ? '
('.$this->l('Paid:').' '.Tools::displayPrice($order->total_paid_real, $currency, false, false).')' : '').'
+
+
+ '.$this->l('Recycled package:').' + '.($order->recyclable ? '' : '').' +
+
+ '.$this->l('Gift wrapping:').' + '.($order->gift ? ' +
+
+ '.(!empty($order->gift_message) ? '
'.$this->l('Message:').'
'.nl2br2($order->gift_message).'
' : '') : '').' +
+
'; + + echo '
+
 
'; + + /* Display adresses : delivery & invoice */ + echo '
 
+
+
+ '.$this->l('Shipping address').''.$this->l('Shipping address').' +
+ + +
+ '.$this->displayAddressDetail($addressDelivery) + .(!empty($addressDelivery->other) ? '
'.$addressDelivery->other.'
' : '') + .'
+
+
+
+ '.$this->l('Invoice address').''.$this->l('Invoice address').' +
+ '.$this->displayAddressDetail($addressInvoice) + .(!empty($addressInvoice->other) ? '
'.$addressInvoice->other.'
' : '') + + .'
+
+
 
'; + + $product_psale = array(); + $products_ids = array(); + foreach(Db::getInstance()->ExecuteS(' + SELECT DISTINCT `product_id` + FROM `'._DB_PREFIX_.'order_detail` + WHERE `id_order` = '.(int) $order->id.' + ') as $row) { + $products_ids[] = (int) $row['product_id']; + } + foreach(Db::getInstance()->ExecuteS(' + SELECT * + FROM `'._DB_PREFIX_.'product_ps_cache` + WHERE `id_product` IN ('.implode(', ', $products_ids).') + ') as $row) { + $product_psale[(int) $row['id_product']] = (int) $row['id_sale']; + } + + // List of products + echo ' +
+
+ +
+ '.$this->l('Products').''.$this->l('Products').' +
+ + + + + + + '.($order->hasBeenPaid() ? '' : '').' + '.($order->hasBeenDelivered() ? '' : '').' + + + '; + echo ' + '; + $tokenCatalog = Tools::getAdminToken('AdminCatalog'.(int)(Tab::getIdFromClassName('AdminCatalog')).(int)($cookie->id_employee)); + foreach ($products as $k => $product) + { + if ($order->getTaxCalculationMethod() == PS_TAX_EXC) + $product_price = $product['product_price'] + $product['ecotax']; + else + $product_price = $product['product_price_wt']; + + $image = array(); + if (isset($product['product_attribute_id']) AND (int)($product['product_attribute_id'])) + $image = Db::getInstance()->getRow(' + SELECT id_image + FROM '._DB_PREFIX_.'product_attribute_image + WHERE id_product_attribute = '.(int)($product['product_attribute_id'])); + if (!isset($image['id_image']) OR !$image['id_image']) + $image = Db::getInstance()->getRow(' + SELECT id_image + FROM '._DB_PREFIX_.'image + WHERE id_product = '.(int)($product['product_id']).' AND cover = 1'); + $stock = Db::getInstance()->getRow(' + SELECT '.($product['product_attribute_id'] ? 'pa' : 'p').'.quantity + FROM '._DB_PREFIX_.'product p + '.($product['product_attribute_id'] ? 'LEFT JOIN '._DB_PREFIX_.'product_attribute pa ON p.id_product = pa.id_product' : '').' + WHERE p.id_product = '.(int)($product['product_id']).' + '.($product['product_attribute_id'] ? 'AND pa.id_product_attribute = '.(int)($product['product_attribute_id']) : '')); + if (isset($image['id_image'])) + { + $target = _PS_TMP_IMG_DIR_.'product_mini_'.(int)($product['product_id']).(isset($product['product_attribute_id']) ? '_'.(int)($product['product_attribute_id']) : '').'.jpg'; + if (file_exists($target)) + $products[$k]['image_size'] = getimagesize($target); + } + // Customization display + $this->displayCustomizedDatas($customizedDatas, $product, $currency, $image, $tokenCatalog, $k); + + // Normal display + if ($product['product_quantity'] > $product['customizationQuantityTotal']) + { + $quantity = $product['product_quantity'] - $product['customizationQuantityTotal']; + $imageObj = new Image($image['id_image']); + echo ' + + + + + + '.($order->hasBeenPaid() ? '' : '').' + '.($order->hasBeenDelivered() ? '' : '').' + + + + + '; + } + } + echo ' +
 '.$this->l('Product').''.$this->l('UP').' *'.$this->l('Qty').''.$this->l('Refunded').''.$this->l('Returned').''.$this->l('Stock').''.$this->l('Total').' *'.$this->l('Products').' '.($order->hasBeenDelivered() ? $this->l('Return') : ($order->hasBeenPaid() ? $this->l('Refund') : $this->l('Cancel'))).'
'.(isset($image['id_image']) ? cacheImage(_PS_IMG_DIR_.'p/'.$imageObj->getExistingImgPath().'.jpg', + 'product_mini_'.(int)($product['product_id']).(isset($product['product_attribute_id']) ? '_'.(int)($product['product_attribute_id']) : '').'.jpg', 45, 'jpg') : '--').' + '.$product['product_name'].'
+ '.($product['product_reference'] ? $this->l('Ref:').' '.$product['product_reference'].'
' : '') + .($product['product_supplier_reference'] ? $this->l('Ref Supplier:').' '.$product['product_supplier_reference'] : '') + .'
'.Tools::displayPrice($product_price, $currency, false).' 1 ? 'style="font-weight:700;font-size:1.1em;color:red"' : '').'>'.(int)$quantity.''.(int)($product['product_quantity_refunded']).''.(int)($product['product_quantity_return']).''.(int)$stock['quantity'].''.Tools::displayPrice(Tools::ps_round($product_price, 2) * ((int)($product['product_quantity']) - $product['customizationQuantityTotal']), $currency, false).' + + + '; + if ((!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) AND (int)($product['product_quantity_return']) < (int)($product['product_quantity'])) + echo ' + = (int)($product['product_quantity'])) ? 'disabled="disabled" ' : '').'/>'; + else + echo '--'; + echo ' + '; + if ((int)($product['product_quantity_return'] + $product['product_quantity_refunded']) >= (int)($product['product_quantity'])) + echo ''; + elseif (!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) + echo ' + '; + echo $this->getCancelledProductNumber($order, $product).' +
+
* '.$this->l('According to the group of this customer, prices are printed:').' '.($order->getTaxCalculationMethod() == PS_TAX_EXC ? $this->l('tax excluded.') : $this->l('tax included.')).(!Configuration::get('PS_ORDER_RETURN') ? '

'.$this->l('Merchandise returns are disabled') : '').'
'; + if (sizeof($discounts)) + { + echo ' +
+ + + + + '; + foreach ($discounts as $discount) + echo ' + + + + '; + echo ' +
'.$this->l('Discounts').''.$this->l('Discount name').''.$this->l('Value').'
'.$discount['name'].''.($discount['value'] != 0.00 ? '- ' : '').Tools::displayPrice($discount['value'], $currency, false).'
'; + } + echo ' +
'; + + // Cancel product + echo ' +
 
+
'; + if ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN')) + echo ' +  
'; + if ((!$order->hasBeenDelivered() AND $order->hasBeenPaid()) OR ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN'))) + echo ' +  
+  
+  
+ '; + if (!$order->hasBeenDelivered() OR ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN'))) + echo ' +
'; + echo ' +
'; + echo ' +
+
+
 
'; + + /* Display send a message to customer & returns/credit slip*/ + $returns = OrderReturn::getOrdersReturn($order->id_customer, $order->id); + $slips = OrderSlip::getOrdersSlip($order->id_customer, $order->id); + echo ' +
+
+
+ '.$this->l('New message').' + +
+

+ '.$this->l('Display to consumer?').' + '.$this->l('Yes').' + '.$this->l('No').' +



+

+ + + +
+
+
'; + /* Display list of messages */ + if (sizeof($messages)) + { + echo ' +
+
+ '.$this->l('Messages').''; + foreach ($messages as $message) + { + echo '
'; + if ($message['is_new_for_me']) + echo ''; + echo $this->l('At').' '.Tools::displayDate($message['date_add'], (int)($cookie->id_lang), true); + echo ' '.$this->l('from').' '.(($message['elastname']) ? ($message['efirstname'].' '.$message['elastname']) : ($message['cfirstname'].' '.$message['clastname'])).''; + echo ((int)($message['private']) == 1 ? ''.$this->l('Private:').'' : ''); + echo '

'.nl2br2($message['message']).'

'; + echo '
'; + echo '
'; + } + echo '

'.$this->l('When you read a message, please click on the green check.').'

'; + echo '
'; + } + echo '
'; + + + /* Display return product */ + echo '
'; + + require_once dirname(__FILE__).'/../../modules/paybox/paybox.php'; + $refundsPaybox = Paybox::getAllRefundbyOrder($order->id); + if (sizeof($refundsPaybox)) + { + echo ' +
+
+ '.$this->l('Remboursement e-Transaction').''; + foreach ($refundsPaybox as $refund) + { + echo '
+ Remboursement d\'un montant de '. $refund['amount'] / 100 . ' €
'; + + if( !empty($refund['product_name']) ) { + echo '' . $refund['product_name'] . ''; + } else { + echo 'Frais de port'; + } + + echo '
'; + } + echo '

'; + } + + echo '
+ '.$this->l('Merchandise returns').''.$this->l('Merchandise returns').''; + if (!sizeof($returns)) + echo $this->l('No merchandise return for this order.'); + else + foreach ($returns as $return) + { + $state = new OrderReturnState($return['state']); + + /* Mondial relay return */ + $return_link = FALSE; + if($state->id == 2) { + $return_link = Db::getInstance()->getRow(' + SELECT `return_number`, `link` + FROM `'._DB_PREFIX_.'order_return_link` + WHERE `id_order_return` = '.(int) $return['id_order_return'].' + '); + } + + echo '('.Tools::displayDate($return['date_upd'], $cookie->id_lang).') : + '.$this->l('#').sprintf('%06d', $return['id_order_return']).' - + '.$state->name[$cookie->id_lang].'
'.($return_link? ' ('.$this->l('return link:').' '.$return_link['return_number'].' '.$this->l('Renvoyer les instructions retour').')': ''); + } + + if(in_array($addressDelivery->id_country, array(3, 6, 8))) { + $returnable = array(); + foreach ($products as $k => $product) { + $product['id_sale'] = $product_psale[(int) $product['product_id']]; + $qty = OrderReturn::getOrderDetailReturnQty($product); + if($qty > 0) { + $returnable[$product['id_order_detail']] = array($product['product_name'], $qty); + } + } + if(count($returnable) > 0) { + $instructions = array( + 1 => 'Remboursement + Mise en stock', + 2 => 'Échange', + 3 => 'Défectueux', + ); + $reasons = array( + // 1 => 'CLIENT : Annulation pré-envoi', + 2 => 'CLIENT : Rétractation post-envoi', + 11 => 'CLIENT : Annulation pour ré-achat', + 4 => 'FEUR : Problème SAV', + 5 => 'FEUR : Produit manquant', + 3 => 'BBB : Erreur Achat / Prod', + 6 => 'BBB : Erreur Logistique ', + 8 => 'BBB : Pbme Site / Paiment', + 12 => 'BBB : Suspicion de fraude', + 9 => 'TRANS : Colis détruit', + 10 => 'TRANS : Colis perdu', + 7 => 'Autre' + ); + + echo ' +

+

'.$this->l('Create a product return').'

+
+
    '; + foreach($returnable as $id_order_detail => $product) { + echo ' +
  • x '.$product[0]. '
  • +
  • '; + for($i = 1; $i <= $product[1]; $i++) { + echo '

    + +
    + + +


    '; + } + echo '
  • '; + } + echo '
+

+ + +

+

-

-

-
'; - } else { - echo '

'.$this->l('No product can currently be returned on this order').'

'; - } - } - echo '
'; +

+

+ '; + } else { + echo '

'.$this->l('No product can currently be returned on this order').'

'; + } + } + echo '
'; - /* Display credit slip */ - echo ' -
-
- '.$this->l('Credit slip').''.$this->l('Credit slip').''; - if (!sizeof($slips)) - echo $this->l('No slip for this order.'); - else - foreach ($slips as $slip) - echo '('.Tools::displayDate($slip['date_upd'], $cookie->id_lang).') : '.$this->l('#').sprintf('%06d', $slip['id_order_slip']).'
'; - echo '
-
'; - echo '
 
'; - echo '

'.$this->l('Back to list').'
'; - } + /* Display credit slip */ + echo ' +
+
+ '.$this->l('Credit slip').''.$this->l('Credit slip').''; + if (!sizeof($slips)) + echo $this->l('No slip for this order.'); + else + foreach ($slips as $slip) + echo '('.Tools::displayDate($slip['date_upd'], $cookie->id_lang).') : '.$this->l('#').sprintf('%06d', $slip['id_order_slip']).'
'; + echo '
+ '; + echo '
 
'; + echo '

'.$this->l('Back to list').'
'; + } - public function displayAddressDetail($addressDelivery) - { - // Allow to add specific rules - $patternRules = array( - 'avoid' => array() - //'avoid' => array('address2') - ); - return AddressFormat::generateAddress($addressDelivery, $patternRules, '
'); - } + public function displayAddressDetail($addressDelivery) + { + // Allow to add specific rules + $patternRules = array( + 'avoid' => array() + //'avoid' => array('address2') + ); + return AddressFormat::generateAddress($addressDelivery, $patternRules, '
'); + } - public function display() - { - global $cookie; + public function display() + { + global $cookie; - if (isset($_GET['view'.$this->table])) - $this->viewDetails(); - else - { - $this->getList((int)($cookie->id_lang), !Tools::getValue($this->table.'Orderby') ? 'date_add' : NULL, !Tools::getValue($this->table.'Orderway') ? 'DESC' : NULL); - $currency = new Currency((int)(Configuration::get('PS_CURRENCY_DEFAULT'))); - $this->displayList(); - echo '

'.$this->l('Total:').' '.Tools::displayPrice($this->getTotal(), $currency).'

'; + if (isset($_GET['view'.$this->table])) + $this->viewDetails(); + else + { + $this->getList((int)($cookie->id_lang), !Tools::getValue($this->table.'Orderby') ? 'date_add' : NULL, !Tools::getValue($this->table.'Orderway') ? 'DESC' : NULL); + $currency = new Currency((int)(Configuration::get('PS_CURRENCY_DEFAULT'))); + $this->displayList(); + echo '

'.$this->l('Total:').' '.Tools::displayPrice($this->getTotal(), $currency).'

'; - if(!empty($_POST['orderFilter_a!date_add']) ){ - $date = $_POST['orderFilter_a!date_add']; - $state = Tools::getValue('orderFilter_os!id_order_state' , 0); + if(!empty($_POST['orderFilter_a!date_add']) ){ + $date = $_POST['orderFilter_a!date_add']; + $state = Tools::getValue('orderFilter_os!id_order_state' , 0); - $total_duree = Order::getTotalbyDate($date[0], $date[1], $state); + $total_duree = Order::getTotalbyDate($date[0], $date[1], $state); - echo '

'.$this->l('Total durée :').' '.Tools::displayPrice($total_duree, $currency).'

'; - } - } - } + echo '

'.$this->l('Total durée :').' '.Tools::displayPrice($total_duree, $currency).'

'; + } + } + } - private function getTotal() - { - $total = 0; - foreach($this->_list AS $item) - if ($item['id_currency'] == Configuration::get('PS_CURRENCY_DEFAULT')) - $total += (float)($item['total_paid']); - else - { - $currency = new Currency((int)($item['id_currency'])); - $total += Tools::ps_round((float)($item['total_paid']) / (float)($currency->conversion_rate), 2); - } - return $total; - } + private function getTotal() + { + $total = 0; + foreach($this->_list AS $item) + if ($item['id_currency'] == Configuration::get('PS_CURRENCY_DEFAULT')) + $total += (float)($item['total_paid']); + else + { + $currency = new Currency((int)($item['id_currency'])); + $total += Tools::ps_round((float)($item['total_paid']) / (float)($currency->conversion_rate), 2); + } + return $total; + } }