bebeboutik/adm/tabs/AdminOrders.php
2017-12-04 10:25:31 +01:00

2976 lines
202 KiB
PHP
Executable File

<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 8783 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
require_once(PS_ADMIN_DIR . '/helpers/HelperFormBootstrap.php');
class AdminOrders extends AdminTab
{
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,
a.id_carrier,
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 '<div class="error">';
foreach($order_errors as $error_order) {
echo '<a href="index.php?tab=AdminOrders&token='.(isset($_POST['token'])?$_POST['token']:(isset($_GET['token'])?$_GET['token']:$this->token)).'&vieworder&id_order='.$error_order['id_order'].'">Erreur commande n°'.$error_order['id_order'].'</a><br />';
}
if(count($order_errors) > 0) echo '</div><br />';
$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'];
$carriers = Db::getInstance()->ExecuteS('
SELECT c.`id_carrier`, IF(c.`name` = "0", "'.Configuration::get('PS_SHOP_NAME').'", c.`name`) AS `name`'.($this->cursale !== NULL? ', (
SELECT IFNULL(p.`id_sale`, NULL) FROM `'._DB_PREFIX_.'privatesale_carrier` p WHERE c.`id_carrier` = p.`id_carrier` AND p.`id_sale` = '.$this->cursale->id.'
) AS `id_sale`': '').'
FROM `'._DB_PREFIX_.'carrier` c
WHERE c.`deleted` != 1 AND c.active =1
');
$carriersArray = array();
foreach ($carriers as $row) {
$carriersArray[(int)$row['id_carrier']] = $row['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' => 100, 'width' => 140, 'filter_key' => 'customer', 'tmpTableFilter' => true),
'total_paid' => array('title' => $this->l('Total'), 'width' => 70, 'align' => 'right', 'prefix' => '<b>', 'suffix' => '</b>', 'price' => true, 'currency' => true),
'payment' => array('title' => $this->l('Payment'), 'width' => 80),
'osname' => array('title' => $this->l('Status'), 'widthColumn' => 230, 'type' => 'select', 'select' => $statesArray, 'filter_key' => 'os!id_order_state', 'filter_type' => 'int', 'width' => 200),
'id_carrier' => array('title' => $this->l('Carrier'), 'align' => 'center', 'width' => 80, 'callback' => 'printCarrier', 'orderby' => false, 'type' => 'select', 'select' => $carriersArray, 'filter_key' => 'a!id_carrier', 'filter_type' => 'int'),
'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 = '<ul>';
$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 .= '<li>'.(int) $product['product_quantity'].' x '.htmlentities($product_name).'</li>';
}
$product_list .= '</ul>';
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('submitSupplierDemand')) {
$id_order = (int) Tools::getValue('id_order');
$id_order_detail = (int) Tools::getValue('id_order_detail');
$qty = (int) Tools::getValue('qty');
if($qty!==0 && $id_order_detail && $id_order) {
if(!class_exists('SupplierDemand')){
require_once(_PS_MODULE_DIR_.'ant_supplierdemand/models/SupplierDemand.php');
}
$supplierDemand = new SupplierDemand();
$supplierDemand->id_order = $id_order;
$supplierDemand->id_order_detail = $id_order_detail;
$supplierDemand->qty = $qty;
$supplierDemand->id_state = 1;
$supplierDemand->solution = 0;
$supplierDemand->comment = Tools::getValue('demand_comment');
if($supplierDemand->save()){
SupplierDemand::addHistoryStatic($supplierDemand->id,1);
}
}
header('Location: '.$_SERVER['REQUEST_URI']);
exit;
}
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();
Db::getInstance()->ExecuteS('
INSERT INTO `'._DB_PREFIX_.'order_return_history`
VALUES (
DEFAULT,
'.(int) $cookie->id_employee.',
'.(int) $id_order_return.',
2,
NOW()
)
');
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 = '<ul>';
$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 .= '<li>'.(int) $qty.' x '.htmlentities($product_name).'</li>';
}
}
$product_list .= '</ul>';
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').' <b>'.$field.'</b> '.Tools::displayError('is required.');
foreach ($rules['size'] AS $field => $maxLength)
if (Tools::getValue($field) AND Tools::strlen(Tools::getValue($field)) > $maxLength)
$this->_errors[] = Tools::displayError('field').' <b>'.$field.'</b> '.Tools::displayError('is too long.').' ('.$maxLength.' '.Tools::displayError('chars max').')';
foreach ($rules['validate'] AS $field => $function)
if (Tools::getValue($field))
if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8')))
$this->_errors[] = Tools::displayError('field').' <b>'.$field.'</b> '.Tools::displayError('is invalid.');
if (!sizeof($this->_errors))
{
$message = new Message();
$message->id_employee = (int)($cookie->id_employee);
$message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8');
$message->id_order = $id_order;
$message->private = Tools::getValue('visibility');
if (!$message->add())
$this->_errors[] = Tools::displayError('An error occurred while sending message.');
elseif ($message->private)
Tools::redirectAdmin($currentIndex.'&id_order='.$id_order.'&vieworder&conf=11'.'&token='.$this->token);
elseif (Validate::isLoadedObject($customer = new Customer($id_customer)))
{
$order = new Order((int)($message->id_order));
if (Validate::isLoadedObject($order))
{
$varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => (Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message)));
if (@Mail::Send((int)($order->id_lang), 'order_merchant_comment',
Mail::l('New message regarding your order'), $varsTpl, $customer->email,
$customer->firstname.' '.$customer->lastname, 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').' <span class="bold">'.$orderDetail->product_name.'</span>';
else
{
$updProductAttributeID = !empty($orderDetail->product_attribute_id) ? (int)($orderDetail->product_attribute_id) : NULL;
$newProductQty = Product::getQuantity((int)($orderDetail->product_id), $updProductAttributeID);
$product = get_object_vars(new Product((int)($orderDetail->product_id), false, (int)($cookie->id_lang)));
if (!empty($orderDetail->product_attribute_id))
{
$updProduct['quantity_attribute'] = (int)($newProductQty);
$product['quantity_attribute'] = $updProduct['quantity_attribute'];
}
else
{
$updProduct['stock_quantity'] = (int)($newProductQty);
$product['stock_quantity'] = $updProduct['stock_quantity'];
}
Hook::updateQuantity($product, $order);
}
}
}
// Delete product
if (!$order->deleteProduct($order, $orderDetail, $qtyCancelProduct))
$this->_errors[] = Tools::displayError('An error occurred during deletion of the product.').' <span class="bold">'.$orderDetail->product_name.'</span>';
Module::hookExec('cancelProduct', array('order' => $order, 'id_order_detail' => $id_order_detail));
}
if (!sizeof($this->_errors) AND $customizationList)
foreach ($customizationList AS $id_customization => $id_order_detail)
{
$orderDetail = new OrderDetail((int)($id_order_detail));
$qtyCancelProduct = abs($customizationQtyList[$id_customization]);
if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $orderDetail))
$this->_errors[] = Tools::displayError('An error occurred during deletion of product customization.').' '.$id_customization;
}
// E-mail params
if ((isset($_POST['generateCreditSlip']) OR isset($_POST['generateDiscount']) 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 .= "
<tr>
<td>". $details_refund->product_name . "</td>
<td style='text-align:right;'>" . Tools::displayPrice($tprice) . " </td>
<td style='text-align:right;'>". (int)$full_quantity_list[$id_order_detail] ."</td>
<td style='text-align:right;'>" . Tools::displayPrice(($tprice * (int)$full_quantity_list[$id_order_detail])) . "</td>
</tr>
";
$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 .= "
<tr style='text-align:right;'>
<td colspan='3' style='background-color:#e2e2e1; padding:0.6em 0.4em;'>Frais de port</td>
<td style='background-color:#e2e2e1; padding:0.6em 0.4em;'>" . Tools::displayPrice($order->total_shipping) . "</td>
</tr>
";
}
$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,
'shippingBack' => isset($_POST['shippingBack']) ? true : false,
));
@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 '
<tr>
<td align="center">'.(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') : '--').'</td>
<td><a href="index.php?tab=AdminCatalog&id_product='.$product['product_id'].'&updateproduct&token='.$tokenCatalog.'">
<span class="productName">'.$product['product_name'].' - '.$this->l('customized').'</span><br />
'.($product['product_reference'] ? $this->l('Ref:').' '.$product['product_reference'].'<br />' : '')
.($product['product_supplier_reference'] ? $this->l('Ref Supplier:').' '.$product['product_supplier_reference'] : '')
.'</a></td>
<td align="center">'.Tools::displayPrice($product['product_price_wt'], $currency, false).'</td>
<td align="center" class="productQuantity">'.$product['customizationQuantityTotal'].'</td>
'.($order->hasBeenPaid() ? '<td align="center" class="productQuantity">'.$product['customizationQuantityRefunded'].'</td>' : '').'
'.($order->hasBeenDelivered() ? '<td align="center" class="productQuantity">'.$product['customizationQuantityReturned'].'</td>' : '').'
<td align="center" class="productQuantity"> - </td>
<td align="center">'.Tools::displayPrice(Tools::ps_round($order->getTaxCalculationMethod() == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'], 2) * $product['customizationQuantityTotal'], $currency, false).'</td>
<td align="center" class="cancelCheck">--</td>
</tr>';
foreach ($customizedDatas[(int)($product['product_id'])][(int)($product['product_attribute_id'])] AS $customizationId => $customization)
{
echo '
<tr>
<td colspan="2">';
foreach ($customization['datas'] AS $type => $datas)
if ($type == _CUSTOMIZE_FILE_)
{
$i = 0;
echo '<ul style="margin: 4px 0px 4px 0px; padding: 0px; list-style-type: none;">';
foreach ($datas AS $data)
echo '<li style="display: inline; margin: 2px;">
<a href="displayImage.php?img='.$data['value'].'&name='.(int)($order->id).'-file'.++$i.'" target="_blank"><img src="'._THEME_PROD_PIC_DIR_.$data['value'].'_small" alt="" /></a>
</li>';
echo '</ul>';
}
elseif ($type == _CUSTOMIZE_TEXTFIELD_)
{
$i = 0;
echo '<ul style="margin: 0px 0px 4px 0px; padding: 0px 0px 0px 6px; list-style-type: none;">';
foreach ($datas AS $data)
echo '<li>'.($data['name'] ? $data['name'] : $this->l('Text #').++$i).$this->l(':').' '.$data['value'].'</li>';
echo '</ul>';
}
echo '</td>
<td align="center">-</td>
<td align="center" class="productQuantity">'.$customization['quantity'].'</td>
'.($order->hasBeenPaid() ? '<td align="center">'.$customization['quantity_refunded'].'</td>' : '').'
'.($order->hasBeenDelivered() ? '<td align="center">'.$customization['quantity_returned'].'</td>' : '').'
<td align="center">-</td>
<td align="center">'.Tools::displayPrice(Tools::ps_round($order->getTaxCalculationMethod() == PS_TAX_EXC ? $product['product_price'] : $product['product_price_wt'], 2) * $customization['quantity'], $currency, false).'</td>
<td align="center" class="cancelCheck">
<input type="hidden" name="totalQtyReturn" id="totalQtyReturn" value="'.(int)($customization['quantity_returned']).'" />
<input type="hidden" name="totalQty" id="totalQty" value="'.(int)($customization['quantity']).'" />
<input type="hidden" name="productName" id="productName" value="'.$product['product_name'].'" />';
if ((!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) AND (int)(($customization['quantity_returned']) < (int)($customization['quantity'])))
echo '
<input type="checkbox" name="id_customization['.$customizationId.']" id="id_customization['.$customizationId.']" value="'.$id_order_detail.'" onchange="setCancelQuantity(this, \''.$customizationId.'\', \''.$customization['quantity'].'\')" '.(((int)($customization['quantity_returned'] + $customization['quantity_refunded']) >= (int)($customization['quantity'])) ? 'disabled="disabled" ' : '').'/>';
else
echo '--';
echo '
</td>
<td class="cancelQuantity">';
if ((int)($customization['quantity_returned'] + $customization['quantity_refunded']) >= (int)($customization['quantity']))
echo '<input type="hidden" name="cancelCustomizationQuantity['.$customizationId.']" value="0" />';
elseif (!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN'))
echo '
<input type="text" id="cancelQuantity_'.$customizationId.'" name="cancelCustomizationQuantity['.$customizationId.']" size="2" onclick="selectCheckbox(this);" value="" /> ';
echo ($order->hasBeenDelivered() ? (int)($customization['quantity_returned']).'/'.((int)($customization['quantity']) - (int)($customization['quantity_refunded'])) : ($order->hasBeenPaid() ? (int)($customization['quantity_refunded']).'/'.(int)($customization['quantity']) : '')).'
</td>';
echo '
</tr>';
}
}
}
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;
$tokenCatalog = Tools::getAdminToken('AdminCatalog'.(int)(Tab::getIdFromClassName('AdminCatalog')).(int)($cookie->id_employee));
$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);
$data = $this->_getOrderDetail($cart,(int)$cart->id_lang,$order);
$carriers_socol = explode(',', Configuration::get('ANT_CARRIERS_SOCOL'));
$carriers_mr = explode(',', Configuration::get('ANT_CARRIERS_MR'));
$currentStateTab = $order->getCurrentStateFull($cookie->id_lang);
$shipping_numbers = array();
foreach(Db::getInstance()->ExecuteS('
SELECT DISTINCT lpws.`shipping_number`, lpws.`date_add`
FROM `'._DB_PREFIX_.'lapostews` lpws
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = lpws.`id_order_detail`)
WHERE `id_order` ='. (int)$order->id.'
GROUP BY lpws.`shipping_number`'
) as $row){
$shipping_numbers[$row['shipping_number']] = $row;
}
foreach(Db::getInstance()->ExecuteS('
SELECT DISTINCT ppp.`shipping_number`, ppp.`date_add`
FROM `'._DB_PREFIX_.'philea_parcel` ppp
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = ppp.`id_order_detail`)
WHERE od.`id_order` ='. (int)$order->id.'
GROUP BY ppp.`shipping_number`'
) as $row){
$shipping_numbers[$row['shipping_number']] = $row;
}
foreach(Db::getInstance()->ExecuteS('
SELECT DISTINCT mrp.`shipping_number`, mrp.`date_add`
FROM `'._DB_PREFIX_.'mondialrelay_parcel` mrp
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = mrp.`id_order_detail`)
WHERE od.`id_order` ='. (int)$order->id.'
GROUP BY mrp.`shipping_number`'
) as $row){
$shipping_numbers[$row['shipping_number']] = $row;
}
foreach(Db::getInstance()->ExecuteS('
SELECT DISTINCT drp.`shipping_number`, drp.`date_add`
FROM `'._DB_PREFIX_.'ant_dropshipping_parcel` drp
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = drp.`id_order_detail`)
WHERE od.`id_order` ='. (int)$order->id.'
GROUP BY drp.`shipping_number`'
) as $row){
$shipping_numbers[$row['shipping_number']] = $row;
}
if(!empty($order->shipping_number) && !isset($shipping_numbers[$order->shipping_number])){
$shipping_numbers[$order->shipping_number] = array(
'shipping_number' => $order->shipping_number
);
}
$row = array_shift($history);
$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 $r) {
$products_ids[] = (int) $r['product_id'];
}
foreach(Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'product_ps_cache`
WHERE `id_product` IN ('.implode(', ', $products_ids).')
') as $r) {
$product_psale[(int) $r['id_product']] = (int) $r['id_sale'];
}
$helper = new HelperFormBootstrap();
$helper->_select2 = true;
$helper->_inputMask = true;
$html = $helper->renderStyle();
if ($prevOrder = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders WHERE id_order < '.(int)$order->id.' ORDER BY id_order DESC'))
$prevOrder = '<a class="btn btn-primary" href="'.$currentIndex.'&token='.Tools::getValue('token').'&vieworder&id_order='.$prevOrder.'"><span class="anticon anticon-arrow-left"></span></a>';
if ($nextOrder = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders WHERE id_order > '.(int)$order->id.' ORDER BY id_order ASC'))
$nextOrder = '<a class="btn btn-primary" href="'.$currentIndex.'&token='.Tools::getValue('token').'&vieworder&id_order='.$nextOrder.'"><span class="anticon anticon-arrow-right"></span></a>';
if ($order->total_paid != $order->total_paid_real) {
$html.= '<center><span class="warning" style="font-size: 16px">'.$this->l('Warning:').' '.Tools::displayPrice($order->total_paid_real, $currency, false).' '.$this->l('paid instead of').' '.Tools::displayPrice($order->total_paid, $currency, false).' !</span></center><div class="clear"><br /><br /></div>';
}
$html .= '
<div class="row">
<div class="col-md-12">
<div class="panel">
<div class="panel-content">
<h2 class="text-center high_title">
<span class="pull-left">'.$prevOrder.'</span>
'.(Validate::isLoadedObject($customer) ? $customer->firstname.' '.$customer->lastname.' - ' : '').'<span class="text-rose">'.$this->l('Order #').sprintf('%06d', $order->id).'</span>
<span class="pull-right">'.$nextOrder.'</span>
</h2>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>';
$html.='
<div class="row">
<div class="col-md-6">
<div class="panel">
<div class="panel-title">
<h2>'.$this->_displayStateIcon($currentStateTab['id_order_state'],stripslashes($row['ostate_name'])).' <span style="font-size:12px;">(<b>'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).'</b>'.((!empty($row['employee_lastname'])) ? ' - '.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).'' : '').')</span></h2>
<div class="clearfix"></div>
</div>
<div class="panel-content">
<a role="button" role="button" data-toggle="collapse" href="#collapseStateHistory"><span class="anticon anticon-info"></span> Voir historique</a>
<div class="collapse" id="collapseStateHistory">
<table class="table" width="100%">
<tbody>
<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
<td>'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).'</td>
<td>'.stripslashes($row['ostate_name']).'</td>
<td>'.((!empty($row['employee_lastname'])) ? '('.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'</td>
</tr>';
foreach ($history AS $row)
{
$html.= '
<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
<td>'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).'</td>
<td>'.stripslashes($row['ostate_name']).'</td>
<td>'.((!empty($row['employee_lastname'])) ? '('.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'</td>
</tr>';
}
$html.= '</tbody>
</table>
</div>
<form style="padding:10px 20px;background:#efefef;" class="text-center center" action="'.$currentIndex.'&view'.$this->table.'&token='.$this->token.'" method="post">
<div class="form-group">
<select class="form-control" name="id_order_state">';
foreach ($states AS $state){
$html .= '<option value="'.$state['id_order_state'].'"'.(($state['id_order_state'] == $currentStateTab['id_order_state']) ? ' selected="selected"' : '').'>'.stripslashes($state['name']).'</option>';
}
$html .= '
</select>
</div>
<div class="checkbox">
<label style="min-height:0px;">
<input type="checkbox" value="1" name="noSendMail" /> Ne pas envoyer de mail
</label>
</div>
<input type="hidden" name="id_order" value="'.$order->id.'" />
<input type="submit" name="submitState" value="'.$this->l('Change').'" class="btn btn-primary btn-block" />
</form>
</div>
</div>
</div>';
/* Display customer information */
if (Validate::isLoadedObject($customer)){
$html.= '
<div class="col-md-6">
<div class="panel" style="min-height:247px;">
<div class="panel-title">
<h2><span style="font-size:20px" class="anticon anticon-user"></span> '.$this->l('Customer information').'</h2>
<div class="clearfix"></div>
</div>
<div class="panel-content">
<p>
<span style="font-weight: bold; font-size: 14px;"><a href="?tab=AdminCustomers&id_customer='.$customer->id.'&viewcustomer&token='.Tools::getAdminToken('AdminCustomers'.(int)(Tab::getIdFromClassName('AdminCustomers')).(int)($cookie->id_employee)).'"> '.$customer->firstname.' '.$customer->lastname.'</a></span> ('.$this->l('#').$customer->id.')<br />
(<a href="mailto:'.$customer->email.'">'.$customer->email.'</a>)
</p>';
if ($customer->isGuest())
{
$html.= '
'.$this->l('This order has been placed by a').' <b>'.$this->l('guest').'</b>';
if (!Customer::customerExists($customer->email))
{
$html.= '
<form method="POST" action="index.php?tab=AdminCustomers&id_customer='.(int)$customer->id.'&token='.Tools::getAdminTokenLite('AdminCustomers').'">
<input type="hidden" name="id_lang" value="'.(int)$order->id_lang.'" />
<p class="center"><input class="button" type="submit" name="submitGuestToCustomer" value="'.$this->l('Transform to customer').'" /></p>
'.$this->l('This feature will generate a random password and send an e-mail to the customer').'
</form>';
}
else
$html.= '<div><b style="color:red;">'.$this->l('A registered customer account exists with the same email address').'</b></div>';
}
else
{
$html.='<p>'.$this->l('Account registered:').' '.Tools::displayDate($customer->date_add, (int)($cookie->id_lang), true).'<br />
'.$this->l('Valid orders placed:').' <span class="label label-primary">'.$customerStats['nb_orders'].'</span><br />
'.$this->l('Total paid since registration:').' <span class="label label-primary">'.Tools::displayPrice(Tools::ps_round(Tools::convertPrice($customerStats['total_orders'], $currency), 2), $currency, false).'</span></p>';
}
$html.= '
</div>
</div>
</div>';
}
$html.= '
</div>';
// $html.= ' <div class="row">
// <div class="col-md-12">';
// // display bar code if module enabled
// $hook = Module::hookExec('invoice', array('id_order' => $order->id));
// if ($hook !== false)
// {
// $html.= '<div style="float: right; margin: -40px 40px 10px 0;">';
// $html.= $hook;
// $html.= '</div><br class="clear" />';
// }
// $html.='
// </div>
// </div>';
$html.= '<div class="row">';
// display hook specified to this page : AdminOrder
if (($hook = Module::hookExec('adminOrderNew', array('id_order' => $order->id))) !== false){
$html.= $hook;
}
$html.='
</div>';
$html.='<div class="row">
<div class="col-md-12">
<div class="panel">
<div class="panel-title">
<h2><span class="glyphicon glyphicon-tag"></span> Résumé Commande</h2>
<a class="pull-right btn btn-default" href="javascript:window.print()" title="'.$this->l('Print order').'"><span class="anticon anticon-printer"></span></a>
'.(($currentState->delivery OR $order->delivery_number)
? '<a class="pull-right btn btn-default" style="margin-right:5px;" href="pdf.php?id_delivery='.$order->delivery_number.'" title="'.$this->l('View delivery').'"><span class="pull-right anticon anticon-truck"></span></a>'
: '<button class="pull-right btn btn-disable" style="margin-right:5px;"><span class="anticon anticon-truck"></span></button>').'
'.((($currentState->invoice OR $order->invoice_number) AND count($products))
? '<a class="pull-right btn btn-default" style="margin-right:5px;" href="pdf.php?id_order='.$order->id.'&pdf" title="'.$this->l('View invoice').'"><span class="pull-right anticon anticon-file-text2"></span></a>'
: '<button class="pull-right btn btn-disable" style="margin-right:5px;"><span class="anticon anticon-file-text2"></span></button>').'
<div class="clearfix"></div>
</div>
<div class="panel-content">
<div class="row">
<div class="col-md-12" id="collapseOrder">
<div class="row"/>
<div class="col-md-6">
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;"><span class="anticon anticon-credit-card"></span> Détails paiement</h5>
<div class="row">
<div class="col-md-6" style="padding-right:0;">
<div style="background:#efefef;padding:10px;">
'.($order->appli?'<p style="margin-bottom:0px;"><span class="anticon anticon-mobile"></span> '.$this->l('Commande faite via l\'appli').'</p>':'').'
<p style="margin-bottom:0px;"><span class="anticon anticon-credit-card"></span> '.Tools::substr($order->payment, 0, 32).' '.($order->module ? '('.$order->module.')' : '').'</p>
<p><span class="anticon anticon-cart"></span> <a href="?tab=AdminCarts&id_cart='.$cart->id.'&viewcart&token='.Tools::getAdminToken('AdminCarts'.(int)(Tab::getIdFromClassName('AdminCarts')).(int)($cookie->id_employee)).'">'.$this->l('Cart #').sprintf('%06d', $cart->id).'</a></p>
<p style="margin-bottom:0px;"><span class="anticon anticon-cross '.($order->recyclable ? 'text-green-light' : 'text-rose').'"></span> '.$this->l('Recycled package').'</p>
<p><span class="anticon anticon-gift '.($order->gift ? 'text-green-light' : 'text-rose').'"></span> '.(!empty($order->gift_message) ? ' <a role="button" data-toggle="collapse" href="#collapseGiftMessage">'.$this->l('Gift wrapping').'</a>':$this->l('Gift wrapping')).'</p>
</div>
</div>
<div class="col-md-6">
<table class="table table-condensed" width="100%;" cellspacing="0" cellpadding="0">
<tr style="font-size: 13px"><td class="text-purple-dark">'.$this->l('Products').'</td><td align="right" class="text-purple-dark">'.Tools::displayPrice($order->getTotalProductsWithTaxes(), $currency, false).'</td></tr>
'.($order->total_discounts > 0 ? '<tr style="font-size: 13px"><td class="text-purple-dark">'.$this->l('Discounts').'</td><td align="right" class="text-purple-dark">-'.Tools::displayPrice($order->total_discounts, $currency, false).'</td></tr>' : '').'
'.($order->total_wrapping > 0 ? '<tr style="font-size: 13px"><td class="text-purple-dark">'.$this->l('Wrapping').'</td><td align="right" class="text-purple-dark">'.Tools::displayPrice($order->total_wrapping, $currency, false).'</td></tr>' : '').'
<tr style="font-size: 13px"><td class="text-purple-dark">'.$this->l('Shipping').'</td><td align="right" class="text-purple-dark">'.Tools::displayPrice($order->total_shipping, $currency, false).'</td></tr>
<tr style="font-size: 16px"><td>'.$this->l('Total').'</td><td align="right" class="text-rose">'.Tools::displayPrice($order->total_paid, $currency, false).($order->total_paid != $order->total_paid_real ? '<br /><font color="red">('.$this->l('Paid:').' '.Tools::displayPrice($order->total_paid_real, $currency, false, false).')</font>' : '').'</td></tr>
</table>
</div>
'.(!empty($order->gift_message) ? '<div class="col-md-12 collapse" id="collapseGiftMessage"><b>'.$this->l('Message:').'</b><br />'.nl2br2($order->gift_message).'</div>' : '').'
</div>
</div>
<div class="col-md-6">
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;"><span class="anticon anticon-truck"></span> Transporteur</h5>';
// carrier info
$html .= '
<div class="row">
<div class="col-md-5" style="padding-right:0px;">
<div style="background:#efefef;padding: 10px;">
<p class="text-center">'.$order->printCarrier($order->id_carrier,array()).' <span><b>'.($carrier->name == '0' ? Configuration::get('PS_SHOP_NAME') : $carrier->name).'</b></span></p>
<p class="text-left" style="margin-bottom:0px;"><i class="glyphicon glyphicon-scale"></i> <b>'.number_format($order->getTotalWeight(), 3).' '.Configuration::get('PS_WEIGHT_UNIT').'</b></p>';
// delivery delay
if (Module::isInstalled('privatesales_delay')) {
if (!class_exists('SaleDelay')) {
require_once _PS_ROOT_DIR_.'/modules/privatesales_delay/saledelay.php';
}
$delay_products = SaleDelay::associateDelay($products);
$delays = array_keys($delay_products);
$date = new DateTime($order->date_add);
$delivery_date = SaleDelay::getDeliveryDate($delays, null, $date, true);
foreach($delivery_date as $k => $date) {
if($k == 1) {
$html .= '<p class="delivery-date text-left" style="margin-bottom:0px;">
<span class="anticon anticon-truck"></span> <strong>'.$date['date_start']->format('d/m/Y').'</strong> - <strong>'.$date['date_end']->format('d/m/Y').'</strong>
</p>';
} elseif ($k == 5){
$html .= '<p class="delivery-date text-left" style="margin-bottom:0px;"><span class="anticon anticon-truck"></span> <strong>'.$this->l('avant le 24/12').'</strong></p>';
} elseif ($k == 8){
$html .= '<p class="delivery-date text-left" style="margin-bottom:0px;"><span class="anticon anticon-truck"></span> <strong>'.$this->l('envoi en 48h').'</strong></p>';
} elseif ($k == 9){
$html .= '<p class="delivery-date text-left" style="margin-bottom:0px;"><span class="anticon anticon-truck"></span> '.$this->l('Delai indiqué sur la fiche produit').'</p>';
}
}
}
$html.='</div>
</div>';
// shipping numbers
$html.='
<div class="col-md-7">';
if(!empty($shipping_numbers)){
$html .= '<table class="table table-condensed th-grey" style="width:100%;margin-bottom:5px;">
<tbody>
<tr>
<th style="font-size:12px;">'.$this->l('Date').'</th>
<th style="font-size:12px;">'.$this->l('Numéro de suivi').'</th>
</tr>';
foreach($shipping_numbers as $number){
$link ='';
if(isset($number['link']) && !empty($number['link'])){
$link = $number['link'];
} else {
$link = str_replace('@', $number['shipping_number'],$carrier->url);
}
$html.='
<tr>
<td style="font-size:11px;">'.(isset($number['date_add'])?date('d/m/Y',strtotime($number['date_add'])):'/').'</td>
<td style="font-size:11px;"><a target="_blank" href="'.$link.'">'.$number['shipping_number'].'</a></td>
</tr>';
}
$html .= '
</tbody>
</table>';
}
/* Display shipping number field */
if ($carrier->url && $order->hasBeenShipped()){
$html .= '
<form class="form-inline text-center" style="margin-bottom:10px;" action="'.$currentIndex.'&view'.$this->table.'&token='.$this->token.'" method="post">
<input type="text" class="form-control input-sm" name="shipping_number" value="'. $order->shipping_number.'" />
<input type="hidden" name="id_order" value="'.$order->id.'" />
<input type="submit" class="btn btn-default btn-sm" name="submitShippingNumber" value="'.$this->l('Set shipping number').'"/>
</form>';
}
/* Carrier module */
// if ($carrier->is_module == 1)
// {
// $module = Module::getInstanceByName($carrier->external_module_name);
// if (method_exists($module, 'displayInfoByCart'))
// $html .= call_user_func(array($module, 'displayInfoByCart'), $order->id_cart);
// }
$html .= '</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="ln_solid"></div>
<div class="row"/>
<div class="col-md-4">
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;">
Adresse Facturation (Presta)
<a class="pull-right" style="color:#fff;" href="?tab=AdminAddresses&id_address='.$addressInvoice->id.'&addaddress&realedit=1&id_order='.$order->id.($addressDelivery->id == $addressInvoice->id ? '&address_type=2' : '').'&back='.urlencode($_SERVER['REQUEST_URI']).'&token='.Tools::getAdminToken('AdminAddresses'.(int)(Tab::getIdFromClassName('AdminAddresses')).(int)($cookie->id_employee)).'"><i class="glyphicon glyphicon-edit"></i></a>
</h5>
<p style="padding:5px 20px;background:#efefef;">'.$data['order_invoice_address'].'</p>
</div>
<div class="col-md-4">
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;">
Adresse Livraison (Presta)
<a style="color:#fff;" class="pull-right" href="?tab=AdminAddresses&id_address='.$addressDelivery->id.'&addaddress&realedit=1&id_order='.$order->id.($addressDelivery->id == $addressInvoice->id ? '&address_type=1' : '').'&token='.Tools::getAdminToken('AdminAddresses'.(int)(Tab::getIdFromClassName('AdminAddresses')).(int)($cookie->id_employee)).'&back='.urlencode($_SERVER['REQUEST_URI']).'"><i class="glyphicon glyphicon-edit"></i></a>
</h5>
<p style="padding:5px 20px;background:#efefef;">'.$data['order_delivery_address'].'</p>
</div>
<div class="col-md-4">
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;">
'.$order->printCarrier($order->id_carrier,array()).' Adresse Livraison
'.($cart->id_carrier!=(int)Configuration::get('ANT_CARRIER_DOM') && in_array($cart->id_carrier,$carriers_socol)?'<a style="color:#fff;cursor:pointer;" class="pull-right" id="changeAddress" data-url="scaddressedit.php?id_cart='.(int)$order->id_cart.'"><i class="glyphicon glyphicon-edit"></i></a>':'').'
'.(in_array($cart->id_carrier,$carriers_mr)?'<a style="color:#fff;cursor:pointer" class="pull-right" id="changeAddress" data-url="mraddressedit.php?id_cart='.(int)$order->id_cart.'"><i class="glyphicon glyphicon-edit"></i></a>':'').'
</h5>
<p style="padding:5px 20px;background:#efefef;">'.$data['order_address'].'</p>
</div>
</div>
<div class="clearfix"></div>
<div class="ln_solid"></div>
</div>
<div class="col-md-12">
<div class="panel-content">
<!--div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="anticon anticon-barcode"></i></span>
<input type="text" data-table="product_detail" class="form-control input_ean" placeholder="Sélection par EAN..."/>
</div>
</div-->
<form action="'.$currentIndex.'&submitCreditSlip&vieworder&token='.$this->token.'" method="post" onsubmit="return orderDeleteProduct(\''.$this->l('Cannot return this product').'\', \''.$this->l('Quantity to cancel is greater than quantity available').'\');">
<div class="table-responsive">
<table id="product_detail" class="table table-custombordered" style="margin-bottom:0;">
<thead>
<tr>
<th><span class="anticon anticon-cart"></span> '.$this->l('Produit').'</th>
<th>'.$this->l('Prix U').'</th>
<th>'.$this->l('Qté').'</th>
'.($order->hasBeenPaid() ?'<th class="text-center">'.$this->l('Remb').'*</th>':'').'
<th class="text-center">'.$this->l('Stock').'</th>
<th>'.$this->l('Total').'</th>
<th class="text-center">'.($order->module ? ($order->module=="paybox"?'<span class="anticon anticon-credit-card"></span> ':'<span class="anticon anticon-paypal"></span> ') : '').'<span class="anticon anticon-redo2"></span></th>
</tr>
</thead>
<tbody>';
foreach ($order->getProducts() as $key => $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');
}
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);
}
}
if ($product['product_quantity'] > $product['customizationQuantityTotal'])
{
$imageObj = new Image($image['id_image']);
$quantity = $product['product_quantity'] - $product['customizationQuantityTotal'];
$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']) : '')
);
$html .='
<tr '.(in_array($product['product_id'],$productReturned)?'style="background:rgba(234, 161, 193, 0.45);"':'').'>
<td style="vertical-align:middle;color:#444;">
'.(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') : '--').'
<a style="color:#444;display: inline-block;vertical-align: middle;" href="index.php?tab=AdminCatalog&id_product='.$product['product_id'].'&updateproduct&token='.$tokenCatalog.'">
<span style="font-weight:bold;font-size:11px" class="productName">'.$product['product_name'].'</span><br />
'.($product['product_reference'] ? '<span style="font-size:10px">'.$this->l('Ref:').' '.$product['product_reference'].'</span><br />' : '')
.($product['product_supplier_reference'] ? '<span style="font-size:10px">'.$this->l('Ref Supplier:').' '.$product['product_supplier_reference'].'</span>' : '')
.'</a>
</td>
<td style=" width:70px;vertical-align:middle;color:#444;">'.Tools::displayPrice($product_price,$currency).'</td>
<td style="vertical-align:middle;color:#444;"><span class="label '.($quantity>1?'label-rose':'label-purple').'">'.$quantity.'</span></td>
'.($order->hasBeenPaid() ? '<td style="vertical-align:middle;color:#444;" align="center" class="productQuantity"><span class="text-rose">'.(int)($product['product_quantity_refunded']).'</span> | <span class="text-rose">'.(int)($product['product_quantity_return']).'</span></td>' : '').'
<td style="vertical-align:middle;color:#444;" align="center" class="productQuantity">'.(int)$stock['quantity'].'</td>
<td style=" width:70px;vertical-align:middle;color:#444;" align="center">'.Tools::displayPrice(Tools::ps_round($product_price, 2) * ((int)($product['product_quantity']) - $product['customizationQuantityTotal']), $currency, false).'</td>
<td width="70" style="vertical-align:middle;color:#444;">
<input class="form-control input-quantity" type="number" data-ean="'.$product['product_ean13'].'" id="cancelQuantity_'.(int)($product['id_order_detail']).'" name="cancelQuantity['.(int)($product['id_order_detail']).']" min="0" max="'.((int)($product['product_quantity']) - (int)($product['product_quantity_return'] + $product['product_quantity_refunded'])).'" value="0" '.(((int)($product['product_quantity_return'] + $product['product_quantity_refunded']) >= (int)($product['product_quantity'])) ? 'disabled="disabled" ' : '').'/>
'.(((int)($product['product_quantity_return'] + $product['product_quantity_refunded']) >= (int)($product['product_quantity'])) ? '' : '<input class="form-control" type="hidden" id="id_order_detail_'.(int)($product['id_order_detail']).'" name="id_order_detail['.(int)($product['id_order_detail']).']" value="'.$product['id_order_detail'].'" />').'
</td>
</tr>';
}
}
if (sizeof($discounts))
{
foreach ($discounts as $discount){
$html .= '
<tr>
<td class="text-purple-dark" colspan="5" style="vertical-align:middle;color:#444;padding:2px 8px;" align="left"><span style="font-weight:bold;font-size:11px" class="productName">'.$this->l('Bon réduction').'</span><br />'.$discount['name'].'</td>
<td class="text-purple-dark" style="width:70px;vertical-align:middle;color:#444;" align="center">'.($discount['value'] != 0.00 ? '- ' : '').Tools::displayPrice($discount['value'], $currency, false).'</td>
<td class="text-purple-dark" width="70" style="vertical-align:middle;color:#444;"></td>
</tr>';
}
}
$html .= '</tbody>
</table>
<p class="col-md-12" style="font-size:11px; margin:0 0 10px 0;"><i>* Le chiffre de gauche correspond à la quantité remboursée pré-envoi et celui de droite post-envoi</i></p>';
$html .= '
<div class="col-md-offset-9 col-md-3">';
if ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN')){
$html .= '<input type="checkbox" id="reinjectQuantities" name="reinjectQuantities" class="button" />&nbsp;<label for="reinjectQuantities" style="float:none; font-weight:normal;">'.$this->l('Re-stock products').'</label><br />';
}
if ((!$order->hasBeenDelivered() AND $order->hasBeenPaid()) OR ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN'))) {
$html .= '
<input type="checkbox" id="generateCreditSlip" name="generateCreditSlip" class="button" />&nbsp;<label for="generateCreditSlip" style="float:none; font-weight:normal;">'.$this->l('Generate a credit slip').'</label><br />
<input type="checkbox" id="generateDiscount" name="generateDiscount" class="button" />&nbsp;<label for="generateDiscount" style="float:none; font-weight:normal;">'.$this->l('Bon 10€ pour produit manquant').'</label><br />
<input type="checkbox" id="generateDiscount2" name="generateDiscount2" class="button" />&nbsp;<label for="generateDiscount2" style="float:none; font-weight:normal;">'.$this->l('Bon 5€ pour produit manquant').'</label><br />
<span id="spanShippingBack" style="display:none;"><input type="checkbox" id="shippingBack" name="shippingBack" class="button" />&nbsp;<label for="shippingBack" style="float:none; font-weight:normal;">'.$this->l('Repay shipping costs').'</label><br /></span>';
}
if (!$order->hasBeenDelivered() OR ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN'))){
$html .= '<div style="margin-top:5px;"><input class="btn btn-primary pull-right" type="submit" name="cancelProduct" value="'.($order->hasBeenDelivered() ? $this->l('Return products') : ($order->hasBeenPaid() ? $this->l('Refund products') : $this->l('Cancel products'))).'"/></div>';
}
$html .= '<input type="hidden" name="id_order" value="'.(int)($order->id).'" />
</div>';
$html .= '
</div>
</form>';
if($order->module && $order->module=="paypal"){
$html.='
<form style="margin-top:10px;" action="" method="post">
<div class="form-horizontal text-right col-md-offset-9 col-md-3">
<input type="hidden" name="id_order" value="'.$order->id.'" />
<button type="submit" class="btn btn-primary pull-right" name="submitPayPalRefund">Remboursement Total Paypal <span class="anticon anticon-paypal"></span></button>
</div>
</form>';
}
$html.='
</div>
<div class="clearfix"></div>
<div class="ln_solid"></div>
<div class="row">
<div class="col-md-12">
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;">'.($order->module ? ($order->module=="paybox"?'<span class="anticon anticon-credit-card"></span> ':'<span class="anticon anticon-paypal"></span> ') : '').' Info Remboursement</h5>';
$slips = OrderSlip::getOrdersSlip($order->id_customer, $order->id);
if (sizeof($slips)){
$html .= '<div style="padding:0px 20px 10px;font-size: 12px;" class="col-md-4">
<table class="table table-condensed th-grey" width="100%">
<tbody>
<tr>
<th>Date</th>
<th>ID</th>
<th>Raison</th>
</tr>';
foreach ($slips as $slip){
$reason = Db::getInstance()->getRow('
SELECT *
FROM `'._DB_PREFIX_.'order_slip` s
LEFT JOIN `'._DB_PREFIX_.'refundreason` r ON s.`id_order_slip` = r.`id_order_slip`
WHERE s.`id_order_slip` ='.(int)$slip['id_order_slip']
);
$html .= '
<tr>
<td><b>'.Tools::displayDate($slip['date_upd'], $cookie->id_lang).'</b></td>
<td><b><a href="pdf.php?id_order_slip='.$slip['id_order_slip'].'">'.$this->l('#').sprintf('%06d', $slip['id_order_slip']).'</a></b></td>
<td>'.($reason?$this->l('#'.$reason['id_reason']):'').'</td>
</tr>';
}
$html .= '</tbody>
</table>
</div>';
}
$html .= '<div style="padding:10px 20px;background:#efefef;font-size: 12px;" '.(sizeof($slips)?'class="col-md-8"':'').'>';
if($order->module && $order->module=="paybox"){
require_once dirname(__FILE__).'/../../modules/paybox/paybox.php';
$refundsPaybox = Paybox::getAllRefundbyOrder($order->id);
if (sizeof($refundsPaybox))
{
$html .='<table class="table table-condensed" width="100%;" cellspacing="0" cellpadding="0">';
foreach ($refundsPaybox as $refund) {
$html .='
<tr>
<td><b>'.(!empty($refund['product_name'])?$refund['product_name']:'Frais de port').'</b></td>
<td>'. $refund['amount'] / 100 . '€</td>
</tr>';
}
$html .='</table>';
} else {
$html .= '<p class="text-center">Pas de remboursement</p>';
}
} elseif($order->module && $order->module=="paypal") {
$messages = Db::getInstance()->ExecuteS('
SELECT `message`, `date_add`
FROM `ps_message`
WHERE `id_order` = '.$order->id.'
AND (`message` LIKE "%Refund operation%" || `message` LIKE "%Cancel products%")
ORDER BY `date_add` DESC
');
if($messages && !empty($messages)) {
foreach ($messages as $message) {
$html .= '<p>('.date('d/m/Y',strtotime($message['message'])).'):<br>'.$message['message'].'</p>';
}
}
if(empty($messages)){
$html .= '<p class="text-center">Pas de remboursement</p>';
}
}
$html .='</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>';
/* Display send a message to customer & returns/supplier demands*/
$returns = OrderReturn::getOrdersReturn($order->id_customer, $order->id);
$html.= '
<div class="row">
<div class="col-md-6">
<div class="panel">
<div class="panel-title">
<h2><span style="cursor: pointer;" onclick="$(\'#message\').slideToggle();$(\'#message_m\').slideToggle();return false"><span class="anticon anticon-bubbles"></span> Nouveau Message</span></h2>
<div class="clearfix"></div>
</div>
<div class="panel-content">
<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'&token='.$this->token.'" method="post" onsubmit="if (getE(\'visibility\').checked == true) return confirm(\''.$this->l('Do you want to send this message to the customer?', __CLASS__, true, false).'\');">
<div id="message_m" style="display: '.(Tools::getValue('message') ? 'none' : 'block').'; overflow: auto;">
<a href="#" onclick="$(\'#message\').slideToggle();$(\'#message_m\').slideToggle();return false"><b>'.$this->l('Click here').'</b> '.$this->l('to add a comment or send a message to the customer').'</a>
</div>
<div id="message" style="display: '.(Tools::getValue('message') ? 'block' : 'none').'">
<select class="form-control" name="order_message" id="order_message" onchange="orderOverwriteMessage(this, \''.$this->l('Do you want to overwrite your existing message?').'\')">
<option value="0" selected="selected">-- '.$this->l('Choose a standard message').' --</option>';
$orderMessages = OrderMessage::getOrderMessages((int)($order->id_lang));
foreach ($orderMessages AS $orderMessage){
$html.= '<option value="'.htmlentities($orderMessage['message'], ENT_COMPAT, 'UTF-8').'">'.$orderMessage['name'].'</option>';
}
$html.= '
</select>
<p>
<b>'.$this->l('Display to consumer?').'</b>
<input type="radio" name="visibility" id="visibility" value="0" /> '.$this->l('Yes').'
<input type="radio" name="visibility" value="1" checked="checked" /> '.$this->l('No').'
</p>
<p id="nbchars" style="display:inline;font-size:10px;color:#666;"></p>
<textarea class="form-control" id="txt_msg" name="message" cols="50" rows="8" onKeyUp="var length = document.getElementById(\'txt_msg\').value.length; if (length > 600) length = \'600+\'; document.getElementById(\'nbchars\').innerHTML = \''.$this->l('600 chars max').' (\' + length + \')\';">'.htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8').'</textarea>
<input type="hidden" name="id_order" value="'.(int)($order->id).'" />
<input type="hidden" name="id_customer" value="'.(int)($order->id_customer).'" />
<div class="ln_solid"></div>
<input class="btn btn-primary btn-block" type="submit" class="button" name="submitMessage" value="'.$this->l('Send').'" />
</div>
</form>
</div>
</div>
<div class="panel">
<div class="panel-title">
<h2><span class="anticon anticon-bubble2"></span> '.$this->l('Messages').'</h2>
<div class="clearfix"></div>
</div>
<div class="panel-content">';
if (sizeof($messages)) {
foreach ($messages as $message)
{
$html.= '<div style="background:#efefef;padding:5px;margin-bottom:10px;overflow:auto;" '.($message['is_new_for_me'] ?'class="new_message"':'').'>';
if ($message['is_new_for_me']){
$html.= '<a class="new_message" title="'.$this->l('Mark this message as \'viewed\'').'" href="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'&token='.$this->token.'&messageReaded='.(int)($message['id_message']).'"><img src="../img/admin/enabled.gif" alt="" /></a>';
}
$html.= '
<a href="#collaspeMessage_'.$message['id_message'].'" data-toggle="collapse">
<span class="anticon anticon-bubble"></span> '.$this->l('At').' <i>'.Tools::displayDate($message['date_add'], (int)($cookie->id_lang), true)
.'</i> '.$this->l('from').' <b>'.(($message['elastname']) ? ($message['efirstname'].' '.$message['elastname']) : ($message['cfirstname'].' '.$message['clastname'])).'</b> '
.((int)($message['private']) == 1 ? '<span style="color:red; font-weight:bold;">'.$this->l('Private:').'</span>' : '');
$html.= '
</a>
<p class="collapse" id="collaspeMessage_'.$message['id_message'].'">'.nl2br2($message['message']).'</p>';
$html.= '</div>';
}
$html.= '<p class="text-info">'.$this->l('When you read a message, please click on the green check.').'</p>';
} else {
$html.= '<div class="alert alert-info">'.$this->l('No Message for this order.').'</div>';
}
$html.= '</div>
</div>
</div>
<div class="col-md-6">
<div class="panel">
<div class="panel-title">
<h2><span class="anticon anticon-loop"></span> '.$this->l('Merchandise returns').'</h2>
<div class="clearfix"></div>
</div>
<div class="panel-content">';
if (!sizeof($returns)){
$html.= '
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;cursor:pointer" data-toggle="collapse" href="#div_returns">'.$this->l('Create a product return').'</h5>
<div class="alert alert-info collapse" id="div_returns">'.$this->l('No merchandise return for this order.').'</div>';
} else {
$html.='
<table class="table table-condensed th-grey" width="100%" >
<tbody>
<tr style="'.($key%2==0?'':'background:#efefef;').'">
<th>'.$this->l('Date').'</th>
<th>'.$this->l('ID').'</th>
<th>'.$this->l('Status').'</th>
<th>'.$this->l('Link').'</th>
<th>'.$this->l('Resend').'</th>
</tr>';
foreach ($returns as $key => $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'].'
');
}
$html.= '
<tr style="'.($key%2==0?'':'background:#efefef;').'">
<td style="font-size:12px;">'.Tools::displayDate($return['date_upd'], $cookie->id_lang).'</td>
<td style="font-size:12px;"><b><a class="text-purple-dark" href="index.php?tab=AdminAntReturnprocess&id_order_return='.$return['id_order_return'].'&updateorder_return&token='.Tools::getAdminToken('AdminAntReturnprocess'.(int)(Tab::getIdFromClassName('AdminAntReturnprocess')).(int)($cookie->id_employee)).'">'.$this->l('#').sprintf('%06d', $return['id_order_return']).'</a></b></td>
<td style="font-size:12px;">'.$state->name[$cookie->id_lang].'</td>
<td style="font-size:12px;">'.($return_link?'<a class="text-purple-dark" href="'.$return_link['link'].'" onclick="window.open(this.href); return false;">'.$return_link['return_number'].'</a>': '/').'</td>
<td style="font-size:14px;text-align:center">'.($return_link?'<a class="text-purple-dark" href="'.$currentIndex.'&send_return_instruction=1&id_order_return='.$return['id_order_return'].'&id_order='.(int)($order->id).'&vieworder&token='.$this->token.'" title="'.$this->l('Renvoyer les instructions retour').'"><i class="glyphicon glyphicon-send"></i></a>': '/').'</td>
</tr>';
}
$html.='</tbody>
</table>';
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, $currentState->id);
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',
4 => 'Commande à ré-expédier',
5 => 'Commande à rembourser',
);
$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'
);
$helper->_js .= '<script type="text/javascript">
$(document).ready(function() {
$(".return_input").change(function() {
var id_order_detail = $(this).attr("data-order-detail");
var qty = parseInt($(this).val());
var max = parseInt($(this).attr("max"));
if(qty == 0) {
$(".return_" + id_order_detail).hide();
}
for(var j = 1; j <= max; j=j+1) {
var id = "#return_" + id_order_detail + "_" + j;
if(j <= qty) {
$(id).show();
} else {
$(id).hide();
}
}
});
$(".return_input").trigger("change");
});
</script>';
$html.= '
<div>
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;cursor:pointer" data-toggle="collapse" href="#new_product_return">'.$this->l('Create a product return').'</h5>
<form id="new_product_return" class="collapse" action="" method="post">
<ul style="list-style: outside none; margin: 0; padding: 0;">';
foreach($returnable as $id_order_detail => $product) {
$html.= '
<li style="padding: 5px; background: #eee;"><input data-order-detail="'.(int) $id_order_detail.'" class="return_input" style="width: 30px; text-align: right; border: 1px solid #E0D0B1; padding: 2px 4px;" type="number" name="return_product['.(int) $id_order_detail.']" value="0" autocomplete="off" step="1" max="'.(int) $product[1].'" min="0" /> x '.$product[0]. '</li>
<li id="reason_'.$id_order_detail.'">';
for($i = 1; $i <= $product[1]; $i++) {
$html.= '
<div id="return_'.(int) $id_order_detail.'_'.$i.'">
<label style="margin: 0px; padding: 0px; float: none; text-align: left; font-weight: normal; display: block; margin-bottom: 5px;">'.sprintf($this->l('Return reason product #%s'), $i).'</label>
<select class="form-control" autocomplete="off" name="return_reason_'.(int) $id_order_detail.'_'.$i.'">';
foreach($reasons as $id_reason => $label) {
$html.= '<option value="'.$id_reason.'">'.$label.'</option>';
}
$html.= '
</select>
<label style="margin: 0px; padding: 0px; float: none; text-align: left; font-weight: normal;display: block; margin-bottom: 5px;">'.sprintf($this->l('Return instruction product #%s'), $i).'</label>
<select class="form-control" autocomplete="off" name="return_instruction_'.(int) $id_order_detail.'_'.$i.'">';
foreach($instructions as $id_instruction => $label) {
$html.= '<option value="'.$id_instruction.'">'.$this->l($label).'</option>';
}
$html.= '
</select>
<div class="ln_solid"></div>
</div>';
}
$html.= '</li>';
}
$html.= '</ul>
<p>
<label for="return_option" style="margin: 0px; padding: 0px; float: none; text-align: left; font-weight: bold;">'.$this->l('This return will be').'</label>
<select class="form-control" autocomplete="off" name="return_option" id="return_option">
<!--option value="1">'.$this->l('paid by the customer').'</option-->
<option value="2">'.$this->l('free').'</option>
</select>
</p>
<p>
<label style="width: auto; margin-bottom: 5px;">'.$this->l('Insert a comment (optional):').'</label>
<textarea class="form-control" name="return_comment" rows="5" cols="50" style="resize: vertical"></textarea>
</p>
<div style="text-right">
<input type="submit" value="'.$this->l('Confirm').'" name="submitCreateReturn" class="btn btn-primary" />
</div>
</form>
</div>';
} else {
$html.= '
<h5 style="background:#504D8B;color:#fff;padding:5px; text-align:center;cursor:pointer" data-toggle="collapse" href="#div_returns">'.$this->l('Create a product return').'</h5>
<div class="alert alert-warning-light collapse" id="div_returns">'.$this->l('No product can currently be returned on this order').'</div>';
}
}
}
$html.= '</div>
</div>
';
if(!class_exists('SupplierDemand')){
require_once(_PS_MODULE_DIR_.'ant_supplierdemand/models/SupplierDemand.php');
$supplierDemands = SupplierDemand::getDemands(array(),'sd.id_order='.$order->id);
$alreadyDemand = array();
$html .= '
<div class="panel">
<div class="panel-title">
<h2><span class="anticon anticon-folder-open"></span> '.$this->l('Supplier demands').'</h2>
<div class="clearfix"></div>
</div>
<div class="panel-content">';
$demand_product = 0;
if(sizeof($supplierDemands)) {
$html .= '
<table class="table table-condensed th-grey" width="100%">
<tbody>
<tr>
<th>'.$this->l('Date').'</th>
<th>'.$this->l('ID').'</th>
<th>'.$this->l('Status').'</th>
<th>'.$this->l('Product').'</th>
</tr>';
foreach ($supplierDemands as $demand) {
$alreadyDemand[] = $demand['id_order_detail'];
$demandStates = SupplierDemand::$states;
$demandProduct = SupplierDemand::getProductStatic((int)$demand['id_supplier_demand']);
$html .= '
<tr>
<td>'.Tools::displayDate($demand['date_upd'], $cookie->id_lang).'</td>
<td><b><a class="text-purple-dark" href="index.php?tab=AdminAntSupplierDemand&id='.$demand['id_supplier_demand'].'&updateSupplierDemand=1&token='.Tools::getAdminToken('AdminAntSupplierDemand'.(int)(Tab::getIdFromClassName('AdminAntSupplierDemand')).(int)($cookie->id_employee)).'">'.$this->l('#').sprintf('%06d', $demand['id_supplier_demand']).'</a></b></td>
<td>'.$demandStates[$demand['id_state']]['name'].'</td>
<td>'.$demandProduct['product_name'].'</td>
</tr>';
}
$html .= '</tbody>
</table>';
}
$html .= '
<div>
<h5 style="background:#504D8B;color:#fff;padding:5px;text-align:center;cursor:pointer" data-toggle="collapse" href="#new_supplier_demand">'.$this->l('Make a supplier demand').'</h5>
<form class="collapse" id="new_supplier_demand" action="" method="post">
<p>
<label style="width: auto; margin-bottom: 5px;">'.$this->l('Product').'</label>
<select class="form-control" name="id_order_detail">';
foreach($products as $product) {
if(in_array($product['id_order_detail'],$alreadyDemand)){
continue;
}
$demand_product++;
$html .= '<option value="'.$product['id_order_detail'].'">'.$product['product_name'].'</option>';
}
$html .= '</select>
</p>';
if ($demand_product==0){
$html .= '<p class="alert alert-warning-light">'.$this->l('All products are in demand').'</p>';
} else {
$html .= '
<p>
<label style="width: auto; margin-bottom: 5px;">'.$this->l('Quantity').'</label>
<input class="form-control" type="number" name="qty" value="0"/>
</p>
<p>
<label style="width: auto; margin-bottom: 5px;">'.$this->l('Insert a comment (optional):').'</label>
<textarea class="form-control" name="demand_comment" rows="5" cols="50" style="resize: vertical"></textarea>
</p>
<input type="hidden" value="'.$order->id.'" name="id_order/>
<div style="text-align: right;">
<input type="submit" value="'.$this->l('Confirm').'" name="submitSupplierDemand" class="btn btn-primary" />
</div>';
}
$html .= '
</form>
</div>
</div>
</div>
</div>';
}
$html .='
</div>';
$helper->_js .= '
<script type="text/javascript">
$(function() {
$("#changeAddress").click(function(){
url = $(this).data("url");
var p = window.open(url, "Modification Addresse de livraison", "width=720, height=360, resizable=1, scrollbars=1");
return false;
});
$(".input-quantity").change(function(){
if($(this).val()==0){
}
});
$("#generateDiscount, #generateDiscount2, #generateCreditSlip").click(function(){
if($(this).is(":checked")){
$("#spanShippingBack").css("display", "block");
} else {
$("#spanShippingBack").css("display", "none");
}
});
});
</script>';
$html .= $helper->renderScript();
echo $html;
}
public function viewDetails()
{
if((int)Configuration::get('ANT_BOOTSTRAP_TPL') == 1){
return $this->_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 = '<a href="'.$currentIndex.'&token='.Tools::getValue('token').'&vieworder&id_order='.$prevOrder.'"><img style="width:24px;height:24px" src="../img/admin/arrow-left.png" /></a>';
if ($nextOrder = Db::getInstance()->getValue('SELECT id_order FROM '._DB_PREFIX_.'orders WHERE id_order > '.(int)$order->id.' ORDER BY id_order ASC'))
$nextOrder = '<a href="'.$currentIndex.'&token='.Tools::getValue('token').'&vieworder&id_order='.$nextOrder.'"><img style="width:24px;height:24px" src="../img/admin/arrow-right.png" /></a>';
if ($order->total_paid != $order->total_paid_real)
echo '<center><span class="warning" style="font-size: 16px">'.$this->l('Warning:').' '.Tools::displayPrice($order->total_paid_real, $currency, false).' '.$this->l('paid instead of').' '.Tools::displayPrice($order->total_paid, $currency, false).' !</span></center><div class="clear"><br /><br /></div>';
// display bar code if module enabled
$hook = Module::hookExec('invoice', array('id_order' => $order->id));
if ($hook !== false)
{
echo '<div style="float: right; margin: -40px 40px 10px 0;">';
echo $hook;
echo '</div><br class="clear" />';
}
// display order header
echo '
<div style="float:left" style="width:440px">';
echo '<h2>
'.$prevOrder.'
'.(Validate::isLoadedObject($customer) ? $customer->firstname.' '.$customer->lastname.' - ' : '').$this->l('Order #').sprintf('%06d', $order->id).'
'.$nextOrder.'
</h2>
<div style="width:429px">
'.((($currentState->invoice OR $order->invoice_number) AND count($products))
? '<a href="pdf.php?id_order='.$order->id.'&pdf"><img src="../img/admin/charged_ok.gif" alt="'.$this->l('View invoice').'" /> '.$this->l('View invoice').'</a>'
: '<img src="../img/admin/charged_ko.gif" alt="'.$this->l('No invoice').'" /> '.$this->l('No invoice')).' -
'.(($currentState->delivery OR $order->delivery_number)
? '<a href="pdf.php?id_delivery='.$order->delivery_number.'"><img src="../img/admin/delivery.gif" alt="'.$this->l('View delivery slip').'" /> '.$this->l('View delivery slip').'</a>'
: '<img src="../img/admin/delivery_ko.gif" alt="'.$this->l('No delivery slip').'" /> '.$this->l('No delivery slip')).' -
<a href="javascript:window.print()"><img src="../img/admin/printer.gif" alt="'.$this->l('Print order').'" title="'.$this->l('Print order').'" /> '.$this->l('Print page').'</a>
</div>
<div class="clear">&nbsp;</div>';
/* Display current status */
echo '
<table cellspacing="0" cellpadding="0" class="table" style="width: 429px">
<tr>
<th>'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).'</th>
<th><img src="../img/os/'.$row['id_order_state'].'.gif" /></th>
<th>'.stripslashes($row['ostate_name']).'</th>
<th>'.((!empty($row['employee_lastname'])) ? '('.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'</th>
</tr>';
/* Display previous status */
foreach ($history AS $row)
{
echo '
<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
<td>'.Tools::displayDate($row['date_add'], (int)($cookie->id_lang), true).'</td>
<td><img src="../img/os/'.$row['id_order_state'].'.gif" /></td>
<td>'.stripslashes($row['ostate_name']).'</td>
<td>'.((!empty($row['employee_lastname'])) ? '('.stripslashes(Tools::substr($row['employee_firstname'], 0, 1)).'. '.stripslashes($row['employee_lastname']).')' : '').'</td>
</tr>';
}
echo '
</table>
<br />';
/* Display status form */
echo '
<form action="'.$currentIndex.'&view'.$this->table.'&token='.$this->token.'" method="post" style="text-align:center;">
<select name="id_order_state">';
$currentStateTab = $order->getCurrentStateFull($cookie->id_lang);
foreach ($states AS $state)
echo '<option value="'.$state['id_order_state'].'"'.(($state['id_order_state'] == $currentStateTab['id_order_state']) ? ' selected="selected"' : '').'>'.stripslashes($state['name']).'</option>';
echo '
</select>
<br />
Ne pas envoyer de mail
<input type="checkbox" value="1" name="noSendMail" />
<input type="hidden" name="id_order" value="'.$order->id.'" />
<input type="submit" name="submitState" value="'.$this->l('Change').'" class="button" />
</form>';
/* Display customer information */
if (Validate::isLoadedObject($customer))
{
echo '<br />
<fieldset style="width: 400px">
<legend><img src="../img/admin/tab-customers.gif" /> '.$this->l('Customer information').'</legend>
<span style="font-weight: bold; font-size: 14px;"><a href="?tab=AdminCustomers&id_customer='.$customer->id.'&viewcustomer&token='.Tools::getAdminToken('AdminCustomers'.(int)(Tab::getIdFromClassName('AdminCustomers')).(int)($cookie->id_employee)).'"> '.$customer->firstname.' '.$customer->lastname.'</a></span> ('.$this->l('#').$customer->id.')<br />
(<a href="mailto:'.$customer->email.'">'.$customer->email.'</a>)<br /><br />';
if ($customer->isGuest())
{
echo '
'.$this->l('This order has been placed by a').' <b>'.$this->l('guest').'</b>';
if (!Customer::customerExists($customer->email))
{
echo '<form method="POST" action="index.php?tab=AdminCustomers&id_customer='.(int)$customer->id.'&token='.Tools::getAdminTokenLite('AdminCustomers').'">
<input type="hidden" name="id_lang" value="'.(int)$order->id_lang.'" />
<p class="center"><input class="button" type="submit" name="submitGuestToCustomer" value="'.$this->l('Transform to customer').'" /></p>
'.$this->l('This feature will generate a random password and send an e-mail to the customer').'
</form>';
}
else
echo '<div><b style="color:red;">'.$this->l('A registered customer account exists with the same email address').'</b></div>';
}
else
{
echo $this->l('Account registered:').' '.Tools::displayDate($customer->date_add, (int)($cookie->id_lang), true).'<br />
'.$this->l('Valid orders placed:').' <b>'.$customerStats['nb_orders'].'</b><br />
'.$this->l('Total paid since registration:').' <b>'.Tools::displayPrice(Tools::ps_round(Tools::convertPrice($customerStats['total_orders'], $currency), 2), $currency, false).'</b><br />';
}
echo '</fieldset>';
}
/* Display sources */
if (sizeof($sources))
{
echo '<br />
<fieldset style="width: 400px;"><legend><img src="../img/admin/tab-stats.gif" /> '.$this->l('Sources').'</legend><ul '.(sizeof($sources) > 3 ? 'style="height: 200px; overflow-y: scroll; width: 360px;"' : '').'>';
foreach ($sources as $source)
echo '<li>
'.Tools::displayDate($source['date_add'], (int)($cookie->id_lang), true).'<br />
<b>'.$this->l('From:').'</b> <a href="'.$source['http_referer'].'">'.preg_replace('/^www./', '', parse_url($source['http_referer'], PHP_URL_HOST)).'</a><br />
<b>'.$this->l('To:').'</b> '.$source['request_uri'].'<br />
'.($source['keywords'] ? '<b>'.$this->l('Keywords:').'</b> '.$source['keywords'].'<br />' : '').'<br />
</li>';
echo '</ul></fieldset>';
}
// display hook specified to this page : AdminOrder
if (($hook = Module::hookExec('adminOrder', array('id_order' => $order->id))) !== false)
echo $hook;
echo '
</div>
<div style="float: left; margin-left: 40px">';
/* Display invoice information */
echo '<fieldset style="width: 400px">';
if (($currentState->invoice OR $order->invoice_number) AND count($products))
echo '<legend><a href="pdf.php?id_order='.$order->id.'&pdf"><img src="../img/admin/charged_ok.gif" /> '.$this->l('Invoice').'</a></legend>
<a href="pdf.php?id_order='.$order->id.'&pdf">'.$this->l('Invoice #').'<b>'.Configuration::get('PS_INVOICE_PREFIX', (int)($cookie->id_lang)).sprintf('%06d', $order->invoice_number).'</b></a>
<br />'.$this->l('Created on:').' '.Tools::displayDate($order->invoice_date, (int)$cookie->id_lang, true);
else
echo '<legend><img src="../img/admin/charged_ko.gif" />'.$this->l('Invoice').'</legend>
'.$this->l('No invoice yet.');
echo '</fieldset><br />';
/* Display shipping infos */
$sql = "SELECT `shipping_number`, `date_add` FROM `"._DB_PREFIX_."lapostews` WHERE `id_order` =". $order->id;
$sql2 = "SELECT DISTINCT ppp.`shipping_number`, ppp.`date_add`
FROM `"._DB_PREFIX_."philea_parcel` ppp
LEFT JOIN `"._DB_PREFIX_."order_detail` od ON (od.`id_order_detail` = ppp.`id_order_detail`)
WHERE od.`id_order` =". $order->id;
$sql3 = 'SELECT lpr.`shipping_number`, lpr.`date_add`
FROM '._DB_PREFIX_.'lapostews_return lpr
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = lpr.`id_order_detail`)
WHERE od.`id_order` ='. $order->id;
$sql4 = 'SELECT DISTINCT mrp.`shipping_number`, mrp.`date_add`
FROM '._DB_PREFIX_.'mondialrelay_parcel mrp
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = mrp.`id_order_detail`)
WHERE od.`id_order` ='. $order->id;
$sql5 = 'SELECT drp.`shipping_number`, drp.`date_add`, drp.`link`
FROM '._DB_PREFIX_.'ant_dropshipping_parcel drp
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = drp.`id_order_detail`)
WHERE od.`id_order` ='. $order->id.'
GROUP BY drp.`shipping_number`';
$numbers = Db::getInstance()->ExecuteS($sql);
$numbers2 = Db::getInstance()->ExecuteS($sql2);
$numbers3 = Db::getInstance()->ExecuteS($sql3);
$numbers4 = Db::getInstance()->ExecuteS($sql4);
$numbers5 = Db::getInstance()->ExecuteS($sql5);
echo '
<fieldset style="width:400px">';
if(count($numbers) > 0){
foreach ($numbers as $key => $number) {
$date = new DateTime($number['date_add']);
echo '<p><b>Numéro de suivi </b> : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .'</p>';
}
}
if(count($numbers2) > 0){
foreach ($numbers2 as $key => $number) {
$date = new DateTime($number['date_add']);
echo '<p><b>Numéro de suivi </b> : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .'</p>';
}
}
if(count($numbers3) > 0){
foreach ($numbers3 as $key => $number) {
$date = new DateTime($number['date_add']);
echo '<p><b>Numéro de suivi </b> : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .'</p>';
}
}
if(count($numbers4) > 0){
foreach ($numbers4 as $key => $number) {
$date = new DateTime($number['date_add']);
echo '<p><b>Numéro de suivi </b> : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .'</p>';
}
}
if(count($numbers5) > 0){
foreach ($numbers5 as $key => $number) {
$date = new DateTime($number['date_add']);
if(!preg_match('/http/i', $number['link'])){
$number['link'] = 'http://'.$number['link'];
}
echo '<p><b>Numéro de suivi </b> : '. $number['shipping_number'] .' ajouté le '. $date->format('d m Y') .' - <a target="_blank" href="'.$number['link'].'"><b>Lien</b></a></p>';
}
}
// assign delay to Products
if (Module::isInstalled('privatesales_delay')) {
if (!class_exists('SaleDelay')) {
require_once _PS_ROOT_DIR_.'/modules/privatesales_delay/saledelay.php';
}
$delay_products = SaleDelay::associateDelay($products);
$delays = array_keys($delay_products);
$date = new DateTime($order->date_add);
$delivery_date = SaleDelay::getDeliveryDate($delays, null, $date, true);
foreach($delivery_date as $k => $date) {
if($k == 1) {
echo '<p class="delivery-date">
'.$this->l('Date d\'expédition : entre le').' <strong>'.$date['date_start']->format('d/m/Y').'</strong> '.$this->l('et le').' <strong>'.$date['date_end']->format('d/m/Y').'</strong>
</p>';
} elseif ($k == 5){
echo '<p class="delivery-date">'.$this->l('Date d\'expédition :').' <strong>'.$this->l('avant le 24/12').'</strong></p>';
} elseif ($k == 8){
echo '<p class="delivery-date">'.$this->l('Date d\'expédition :').' <strong>'.$this->l('envoi en 48h').'</strong></p>';
} elseif ($k == 9){
echo '<p class="delivery-date">'.$this->l('Date d\'expédition :').' '.$this->l('Delai indiqué sur la fiche produit').'</p>';
}
}
}
echo '<legend><img src="../img/admin/delivery.gif" /> '.$this->l('Shipping information').'</legend>
'.$this->l('Total weight:').' <b>'.number_format($order->getTotalWeight(), 3).' '.Configuration::get('PS_WEIGHT_UNIT').'</b><br />
'.$this->l('Carrier:').' <b>'.($carrier->name == '0' ? Configuration::get('PS_SHOP_NAME') : $carrier->name).'</b><br />
'.(($currentState->delivery OR $order->delivery_number) ? '<br /><a href="pdf.php?id_delivery='.$order->delivery_number.'">'.$this->l('Delivery slip #').'<b>'.Configuration::get('PS_DELIVERY_PREFIX', (int)($cookie->id_lang)).sprintf('%06d', $order->delivery_number).'</b></a><br />' : '');
if ($order->shipping_number)
echo $this->l('Tracking number:').' <b>'.$order->shipping_number.'</b> '.(!empty($carrier->url) ? '(<a href="'.str_replace('@', $order->shipping_number, $carrier->url).'" target="_blank">'.$this->l('Track the shipment').'</a>)' : '');
/* 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 '
<form action="'.$currentIndex.'&view'.$this->table.'&token='.$this->token.'" method="post" style="margin-top:10px;">
<input type="text" name="shipping_number" value="'. $order->shipping_number.'" />
<input type="hidden" name="id_order" value="'.$order->id.'" />
<input type="submit" name="submitShippingNumber" value="'.$this->l('Set shipping number').'" class="button" />
</form>';
echo '
</fieldset>';
$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 '
<br />
<fieldset style="width: 400px">
<legend>'.$this->l('Numéro(s) de suivi').'</legend>
<table class="table" style="width:100%">
<tr>
<th>'.$this->l('Date').'</th>
<th>'.$this->l('Numéro de suivi').'</th>
<th>'.$this->l('Lien').'</th>
</tr>';
foreach ($shippings as $key => $shipping) {
echo '<tr>
<td>'.date('d/m/Y', strtotime($shipping['date_add'])).'</td>
<td>'. $shipping['shipping_number'] .'</td>
<td><a onclick="window.open(this.href); return false;" href="http://www.colissimo.fr/portail_colissimo/suivreResultat.do?parcelnumber='.$shipping['shipping_number'].'">'.$this->l('Voir').'</a></td>
</tr>';
}
echo '</table>
</fieldset>';
}
/* Display summary order */
echo '
<br />
<fieldset style="width: 400px">
<legend><img src="../img/admin/details.gif" /> '.$this->l('Order details').'</legend>
<label>'.$this->l('Depuis l\'Appli :').' </label>
<div style="margin: 2px 0 1em 50px;">'.($order->appli?'OUI':'NON').'</div>
<label>'.$this->l('Original cart:').' </label>
<div style="margin: 2px 0 1em 190px;"><a href="?tab=AdminCarts&id_cart='.$cart->id.'&viewcart&token='.Tools::getAdminToken('AdminCarts'.(int)(Tab::getIdFromClassName('AdminCarts')).(int)($cookie->id_employee)).'">'.$this->l('Cart #').sprintf('%06d', $cart->id).'</a></div>
<label>'.$this->l('Payment mode:').' </label>
<div style="margin: 2px 0 1em 190px;">'.Tools::substr($order->payment, 0, 32).' '.($order->module ? '('.$order->module.')' : '').'</div>
<div style="margin: 2px 0 1em 50px;">
<table class="table" width="300px;" cellspacing="0" cellpadding="0">
<tr><td width="150px;">'.$this->l('Products').'</td><td align="right">'.Tools::displayPrice($order->getTotalProductsWithTaxes(), $currency, false).'</td></tr>
'.($order->total_discounts > 0 ? '<tr><td>'.$this->l('Discounts').'</td><td align="right">-'.Tools::displayPrice($order->total_discounts, $currency, false).'</td></tr>' : '').'
'.($order->total_wrapping > 0 ? '<tr><td>'.$this->l('Wrapping').'</td><td align="right">'.Tools::displayPrice($order->total_wrapping, $currency, false).'</td></tr>' : '').'
<tr><td>'.$this->l('Shipping').'</td><td align="right">'.Tools::displayPrice($order->total_shipping, $currency, false).'</td></tr>
<tr style="font-size: 20px"><td>'.$this->l('Total').'</td><td align="right">'.Tools::displayPrice($order->total_paid, $currency, false).($order->total_paid != $order->total_paid_real ? '<br /><font color="red">('.$this->l('Paid:').' '.Tools::displayPrice($order->total_paid_real, $currency, false, false).')</font>' : '').'</td></tr>
</table>
</div>
<div style="float: left; margin-right: 10px; margin-left: 42px;">
<span class="bold">'.$this->l('Recycled package:').'</span>
'.($order->recyclable ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />').'
</div>
<div style="float: left; margin-right: 10px;">
<span class="bold">'.$this->l('Gift wrapping:').'</span>
'.($order->gift ? '<img src="../img/admin/enabled.gif" />
</div>
<div style="clear: left; margin: 0px 42px 0px 42px; padding-top: 2px;">
'.(!empty($order->gift_message) ? '<div style="border: 1px dashed #999; padding: 5px; margin-top: 8px;"><b>'.$this->l('Message:').'</b><br />'.nl2br2($order->gift_message).'</div>' : '') : '<img src="../img/admin/disabled.gif" />').'
</div>
</fieldset>';
echo '</div>
<div class="clear">&nbsp;</div>';
/* Display adresses : delivery & invoice */
echo '<div class="clear">&nbsp;</div>
<div style="float: left">
<fieldset style="width: 400px;">
<legend><img src="../img/admin/delivery.gif" alt="'.$this->l('Shipping address').'" />'.$this->l('Shipping address').'</legend>
<div style="float: right">
<a href="?tab=AdminAddresses&id_address='.$addressDelivery->id.'&addaddress&realedit=1&id_order='.$order->id.($addressDelivery->id == $addressInvoice->id ? '&address_type=1' : '').'&token='.Tools::getAdminToken('AdminAddresses'.(int)(Tab::getIdFromClassName('AdminAddresses')).(int)($cookie->id_employee)).'&back='.urlencode($_SERVER['REQUEST_URI']).'"><img src="../img/admin/edit.gif" /></a>
<a href="http://maps.google.com/maps?f=q&hl='.$currentLanguage->iso_code.'&geocode=&q='.$addressDelivery->address1.' '.$addressDelivery->postcode.' '.$addressDelivery->city.($addressDelivery->id_state ? ' '.$deliveryState->name: '').'" target="_blank"><img src="../img/admin/google.gif" alt="" class="middle" /></a>
</div>
'.$this->displayAddressDetail($addressDelivery)
.(!empty($addressDelivery->other) ? '<hr />'.$addressDelivery->other.'<br />' : '')
.'</fieldset>
</div>
<div style="float: left; margin-left: 40px">
<fieldset style="width: 400px;">
<legend><img src="../img/admin/invoice.gif" alt="'.$this->l('Invoice address').'" />'.$this->l('Invoice address').'</legend>
<div style="float: right"><a href="?tab=AdminAddresses&id_address='.$addressInvoice->id.'&addaddress&realedit=1&id_order='.$order->id.($addressDelivery->id == $addressInvoice->id ? '&address_type=2' : '').'&back='.urlencode($_SERVER['REQUEST_URI']).'&token='.Tools::getAdminToken('AdminAddresses'.(int)(Tab::getIdFromClassName('AdminAddresses')).(int)($cookie->id_employee)).'"><img src="../img/admin/edit.gif" /></a></div>
'.$this->displayAddressDetail($addressInvoice)
.(!empty($addressInvoice->other) ? '<hr />'.$addressInvoice->other.'<br />' : '')
.'</fieldset>
</div>
<div class="clear">&nbsp;</div>';
$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 '
<a name="products"><br /></a>
<form action="'.$currentIndex.'&submitCreditSlip&vieworder&token='.$this->token.'" method="post" onsubmit="return orderDeleteProduct(\''.$this->l('Cannot return this product').'\', \''.$this->l('Quantity to cancel is greater than quantity available').'\');">
<input type="hidden" name="id_order" value="'.$order->id.'" />
<fieldset style="width: 868px; ">
<legend><img src="../img/admin/cart.gif" alt="'.$this->l('Products').'" />'.$this->l('Products').'</legend>
<div style="float:left;">
<table style="width: 868px;" cellspacing="0" cellpadding="0" class="table" id="orderProducts">
<tr>
<th align="center" style="width: 60px">&nbsp;</th>
<th>'.$this->l('Product').'</th>
<th style="width: 80px; text-align: center">'.$this->l('UP').' <sup>*</sup></th>
<th style="width: 20px; text-align: center">'.$this->l('Qty').'</th>
'.($order->hasBeenPaid() ? '<th style="width: 20px; text-align: center">'.$this->l('Refunded').'</th>' : '').'
'.($order->hasBeenDelivered() ? '<th style="width: 20px; text-align: center">'.$this->l('Returned').'</th>' : '').'
<th style="width: 30px; text-align: center">'.$this->l('Stock').'</th>
<th style="width: 90px; text-align: center">'.$this->l('Total').' <sup>*</sup></th>
<th colspan="2" style="width: 120px;"><img src="../img/admin/delete.gif" alt="'.$this->l('Products').'" /> '.($order->hasBeenDelivered() ? $this->l('Return') : ($order->hasBeenPaid() ? $this->l('Refund') : $this->l('Cancel'))).'</th>';
echo '
</tr>';
$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 '
<tr'.((isset($image['id_image']) AND isset($products[$k]['image_size'])) ? ' height="'.($products[$k]['image_size'][1] + 7).'"' : '').'>
<td align="center">'.(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') : '--').'</td>
<td><a href="index.php?tab=AdminCatalog&id_product='.$product['product_id'].'&updateproduct&token='.$tokenCatalog.'">
<span class="productName">'.$product['product_name'].'</span><br />
'.($product['product_reference'] ? $this->l('Ref:').' '.$product['product_reference'].'<br />' : '')
.($product['product_supplier_reference'] ? $this->l('Ref Supplier:').' '.$product['product_supplier_reference'] : '')
.'</a></td>
<td align="center">'.Tools::displayPrice($product_price, $currency, false).'</td>
<td align="center" class="productQuantity" '.($quantity > 1 ? 'style="font-weight:700;font-size:1.1em;color:red"' : '').'>'.(int)$quantity.'</td>
'.($order->hasBeenPaid() ? '<td align="center" class="productQuantity">'.(int)($product['product_quantity_refunded']).'</td>' : '').'
'.($order->hasBeenDelivered() ? '<td align="center" class="productQuantity">'.(int)($product['product_quantity_return']).'</td>' : '').'
<td align="center" class="productQuantity">'.(int)$stock['quantity'].'</td>
<td align="center">'.Tools::displayPrice(Tools::ps_round($product_price, 2) * ((int)($product['product_quantity']) - $product['customizationQuantityTotal']), $currency, false).'</td>
<td align="center" class="cancelCheck">
<input type="hidden" name="totalQtyReturn" id="totalQtyReturn" value="'.(int)($product['product_quantity_return']).'" />
<input type="hidden" name="totalQty" id="totalQty" value="'.(int)($product['product_quantity']).'" />
<input type="hidden" name="productName" id="productName" value="'.$product['product_name'].'" />';
if ((!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN')) AND (int)($product['product_quantity_return']) < (int)($product['product_quantity']))
echo '
<input type="checkbox" name="id_order_detail['.$k.']" id="id_order_detail['.$k.']" value="'.$product['id_order_detail'].'" onchange="setCancelQuantity(this, '.(int)($product['id_order_detail']).', '.(int)($product['product_quantity_in_stock'] - $product['customizationQuantityTotal'] - $product['product_quantity_reinjected']).')" '.(((int)($product['product_quantity_return'] + $product['product_quantity_refunded']) >= (int)($product['product_quantity'])) ? 'disabled="disabled" ' : '').'/>';
else
echo '--';
echo '
</td>
<td class="cancelQuantity">';
if ((int)($product['product_quantity_return'] + $product['product_quantity_refunded']) >= (int)($product['product_quantity']))
echo '<input type="hidden" name="cancelQuantity['.$k.']" value="0" />';
elseif (!$order->hasBeenDelivered() OR Configuration::get('PS_ORDER_RETURN'))
echo '
<input type="text" id="cancelQuantity_'.(int)($product['id_order_detail']).'" name="cancelQuantity['.$k.']" size="2" onclick="selectCheckbox(this);" value="" /> ';
echo $this->getCancelledProductNumber($order, $product).'
</td>
</tr>';
}
}
echo '
</table>
<div style="float:left; width:280px; margin-top:15px;"><sup>*</sup> '.$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') ? '<br /><br />'.$this->l('Merchandise returns are disabled') : '').'</div>';
if (sizeof($discounts))
{
echo '
<div style="float:right; width:280px; margin-top:15px;">
<table cellspacing="0" cellpadding="0" class="table" style="width:100%;">
<tr>
<th><img src="../img/admin/coupon.gif" alt="'.$this->l('Discounts').'" />'.$this->l('Discount name').'</th>
<th align="center" style="width: 100px">'.$this->l('Value').'</th>
</tr>';
foreach ($discounts as $discount)
echo '
<tr>
<td>'.$discount['name'].'</td>
<td align="center">'.($discount['value'] != 0.00 ? '- ' : '').Tools::displayPrice($discount['value'], $currency, false).'</td>
</tr>';
echo '
</table></div>';
}
echo '
</div>';
// Cancel product
echo '
<div style="clear:both; height:15px;">&nbsp;</div>
<div style="float: right; width: 160px;">';
if ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN'))
echo '
<input type="checkbox" id="reinjectQuantities" name="reinjectQuantities" class="button" />&nbsp;<label for="reinjectQuantities" style="float:none; font-weight:normal;">'.$this->l('Re-stock products').'</label><br />';
if ((!$order->hasBeenDelivered() AND $order->hasBeenPaid()) OR ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN')))
echo '
<input type="checkbox" id="generateCreditSlip" name="generateCreditSlip" class="button" onclick="toogleShippingCost(this)" />&nbsp;<label for="generateCreditSlip" style="float:none; font-weight:normal;">'.$this->l('Generate a credit slip').'</label><br />
<input type="checkbox" id="generateDiscount" name="generateDiscount" class="button" onclick="toogleShippingCost(this)" />&nbsp;<label for="generateDiscount" style="float:none; font-weight:normal;">'.$this->l('Bon 10€ pour produit manquant').'</label><br />
<input type="checkbox" id="generateDiscount2" name="generateDiscount2" class="button" onclick="toogleShippingCost(this)" />&nbsp;<label for="generateDiscount2" style="float:none; font-weight:normal;">'.$this->l('Bon 5€ pour produit manquant').'</label><br />
<span id="spanShippingBack" style="display:none;"><input type="checkbox" id="shippingBack" name="shippingBack" class="button" />&nbsp;<label for="shippingBack" style="float:none; font-weight:normal;">'.$this->l('Repay shipping costs').'</label><br /></span>';
if (!$order->hasBeenDelivered() OR ($order->hasBeenDelivered() AND Configuration::get('PS_ORDER_RETURN')))
echo '
<div style="text-align:center; margin-top:5px;"><input type="submit" name="cancelProduct" value="'.($order->hasBeenDelivered() ? $this->l('Return products') : ($order->hasBeenPaid() ? $this->l('Refund products') : $this->l('Cancel products'))).'" class="button" style="margin-top:8px;" /></div>';
echo '
</div>';
echo '
</fieldset>
</form>
<div class="clear" style="height:20px;">&nbsp;</div>';
/* 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 '
<div style="float: left">
<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'&token='.$this->token.'" method="post" onsubmit="if (getE(\'visibility\').checked == true) return confirm(\''.$this->l('Do you want to send this message to the customer?', __CLASS__, true, false).'\');">
<fieldset style="width: 400px;">
<legend style="cursor: pointer;" onclick="$(\'#message\').slideToggle();$(\'#message_m\').slideToggle();return false"><img src="../img/admin/email_edit.gif" /> '.$this->l('New message').'</legend>
<div id="message_m" style="display: '.(Tools::getValue('message') ? 'none' : 'block').'; overflow: auto; width: 400px;">
<a href="#" onclick="$(\'#message\').slideToggle();$(\'#message_m\').slideToggle();return false"><b>'.$this->l('Click here').'</b> '.$this->l('to add a comment or send a message to the customer').'</a>
</div>
<div id="message" style="display: '.(Tools::getValue('message') ? 'block' : 'none').'">
<select name="order_message" id="order_message" onchange="orderOverwriteMessage(this, \''.$this->l('Do you want to overwrite your existing message?').'\')">
<option value="0" selected="selected">-- '.$this->l('Choose a standard message').' --</option>';
$orderMessages = OrderMessage::getOrderMessages((int)($order->id_lang));
foreach ($orderMessages AS $orderMessage)
echo ' <option value="'.htmlentities($orderMessage['message'], ENT_COMPAT, 'UTF-8').'">'.$orderMessage['name'].'</option>';
echo ' </select><br /><br />
<b>'.$this->l('Display to consumer?').'</b>
<input type="radio" name="visibility" id="visibility" value="0" /> '.$this->l('Yes').'
<input type="radio" name="visibility" value="1" checked="checked" /> '.$this->l('No').'
<p id="nbchars" style="display:inline;font-size:10px;color:#666;"></p><br /><br />
<textarea id="txt_msg" name="message" cols="50" rows="8" onKeyUp="var length = document.getElementById(\'txt_msg\').value.length; if (length > 600) length = \'600+\'; document.getElementById(\'nbchars\').innerHTML = \''.$this->l('600 chars max').' (\' + length + \')\';">'.htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8').'</textarea><br /><br />
<input type="hidden" name="id_order" value="'.(int)($order->id).'" />
<input type="hidden" name="id_customer" value="'.(int)($order->id_customer).'" />
<input type="submit" class="button" name="submitMessage" value="'.$this->l('Send').'" />
</div>
</fieldset>
</form>';
/* Display list of messages */
if (sizeof($messages))
{
echo '
<br />
<fieldset style="width: 400px;">
<legend><img src="../img/admin/email.gif" /> '.$this->l('Messages').'</legend>';
foreach ($messages as $message)
{
echo '<div style="overflow:auto; width:400px;" '.($message['is_new_for_me'] ?'class="new_message"':'').'>';
if ($message['is_new_for_me'])
echo '<a class="new_message" title="'.$this->l('Mark this message as \'viewed\'').'" href="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'&token='.$this->token.'&messageReaded='.(int)($message['id_message']).'"><img src="../img/admin/enabled.gif" alt="" /></a>';
echo $this->l('At').' <i>'.Tools::displayDate($message['date_add'], (int)($cookie->id_lang), true);
echo '</i> '.$this->l('from').' <b>'.(($message['elastname']) ? ($message['efirstname'].' '.$message['elastname']) : ($message['cfirstname'].' '.$message['clastname'])).'</b>';
echo ((int)($message['private']) == 1 ? '<span style="color:red; font-weight:bold;">'.$this->l('Private:').'</span>' : '');
echo '<p>'.nl2br2($message['message']).'</p>';
echo '</div>';
echo '<br />';
}
echo '<p class="info">'.$this->l('When you read a message, please click on the green check.').'</p>';
echo '</fieldset>';
}
echo '</div>';
/* Display return product */
echo '<div style="float: left; margin-left: 40px">';
require_once dirname(__FILE__).'/../../modules/paybox/paybox.php';
$refundsPaybox = Paybox::getAllRefundbyOrder($order->id);
if (sizeof($refundsPaybox))
{
echo '
<br />
<fieldset style="width: 400px;">
<legend><img src="../img/admin/payment.gif" /> '.$this->l('Remboursement e-Transaction').'</legend>';
foreach ($refundsPaybox as $refund)
{
echo '<div style="margin-bottom: 25px;">
Remboursement d\'un montant de '. $refund['amount'] / 100 . ' € <br />';
if( !empty($refund['product_name']) ) {
echo '<b>' . $refund['product_name'] . '</b>';
} else {
echo '<b>Frais de port</b>';
}
echo '</div>';
}
echo '</fieldset> <br />';
}
echo '<fieldset style="width: 400px;">
<legend><img src="../img/admin/return.gif" alt="'.$this->l('Merchandise returns').'" />'.$this->l('Merchandise returns').'</legend>';
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).') :
<b><a href="index.php?tab=AdminAntReturnprocess&id_order_return='.$return['id_order_return'].'&updateorder_return&token='.Tools::getAdminToken('AdminAntReturnprocess'.(int)(Tab::getIdFromClassName('AdminAntReturnprocess')).(int)($cookie->id_employee)).'">'.$this->l('#').sprintf('%06d', $return['id_order_return']).'</a></b> -
'.$state->name[$cookie->id_lang].'<br />'.($return_link? ' ('.$this->l('return link:').' <a href="'.$return_link['link'].'" onclick="window.open(this.href); return false;">'.$return_link['return_number'].'</a> <a class="button" href="'.$currentIndex.'&send_return_instruction=1&id_order_return='.$return['id_order_return'].'&id_order='.(int)($order->id).'&vieworder&token='.$this->token.'">'.$this->l('Renvoyer les instructions retour').'</a>)': '');
}
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, $currentState->id);
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',
4 => 'Commande à ré-expédier',
5 => 'Commande à rembourser',
);
$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 '<script type="text/javascript">
$(document).ready(function() {
$(".return_input").change(function() {
var id_order_detail = $(this).attr("data-order-detail");
var qty = parseInt($(this).val());
var max = parseInt($(this).attr("max"));
if(qty == 0) {
$(".return_" + id_order_detail).hide();
}
for(var j = 1; j <= max; j=j+1) {
var id = "#return_" + id_order_detail + "_" + j;
if(j <= qty) {
$(id).show();
} else {
$(id).hide();
}
}
});
$(".return_input").trigger("change");
});
</script>
<br /><br />
<h4>'.$this->l('Create a product return').'</h4>
<form id="new_product_return" action="" method="post">
<ul style="list-style: outside none; margin: 0; padding: 0;">';
foreach($returnable as $id_order_detail => $product) {
echo '
<li style="padding: 5px; background: #eee;"><input data-order-detail="'.(int) $id_order_detail.'" class="return_input" style="width: 30px; text-align: right; border: 1px solid #E0D0B1; padding: 2px 4px;" type="number" name="return_product['.(int) $id_order_detail.']" value="0" autocomplete="off" step="1" max="'.(int) $product[1].'" min="0" /> x '.$product[0]. '</li>
<li id="reason_'.$id_order_detail.'">';
for($i = 1; $i <= $product[1]; $i++) {
echo '<p id="return_'.(int) $id_order_detail.'_'.$i.'">
<label style="margin: 0px; padding: 0px; float: none; text-align: left; font-weight: normal; display: block; margin-bottom: 5px;">'.sprintf($this->l('Return reason product #%s'), $i).'</label>
<select autocomplete="off" name="return_reason_'.(int) $id_order_detail.'_'.$i.'">';
foreach($reasons as $id_reason => $label) {
echo '<option value="'.$id_reason.'">'.$label.'</option>';
}
echo '</select><br />
<label style="margin: 0px; padding: 0px; float: none; text-align: left; font-weight: normal;display: block; margin-bottom: 5px;">'.sprintf($this->l('Return instruction product #%s'), $i).'</label>
<select autocomplete="off" name="return_instruction_'.(int) $id_order_detail.'_'.$i.'">';
foreach($instructions as $id_instruction => $label) {
echo '<option value="'.$id_instruction.'">'.$this->l($label).'</option>';
}
echo '</select>
</p><br />';
}
echo '</li>';
}
echo '</ul>
<p>
<label for="return_option" style="margin: 0px; padding: 0px; float: none; text-align: left; font-weight: normal;">'.$this->l('This return will be').'</label>
<select autocomplete="off" name="return_option" id="return_option">
<!--option value="1">'.$this->l('paid by the customer').'</option-->
<option value="2">'.$this->l('free').'</option>
</select>
</p>
<p>
<label style="width: auto; margin-bottom: 5px;">'.$this->l('Insert a comment (optional):').'</label>
<textarea name="return_comment" rows="5" cols="50" style="resize: vertical"></textarea>
</p>
<p class="submit"><input type="submit" value="'.$this->l('Confirm').'" name="submitCreateReturn" class="button" /></p>
</form>';
} else {
echo '<br /><br /><p class="warning">'.$this->l('No product can currently be returned on this order').'</p>';
}
}
echo '</fieldset>';
// @Override Antadis - Supplier demand
if(!class_exists('SupplierDemand')){
require_once(_PS_MODULE_DIR_.'ant_supplierdemand/models/SupplierDemand.php');
}
$supplierDemands = SupplierDemand::getDemands(array(),'sd.id_order='.$order->id);
$alreadyDemand = array();
echo '<br/>
<fieldset style="width: 400px;">
<legend><img src="../img/admin/return.gif" alt="'.$this->l('Supplier demands').'" />'.$this->l('Supplier demands').'</legend>';
if (!sizeof($supplierDemands)) {
echo $this->l('No Supplier demands for this order.');
} else {
$demand_product = 0;
foreach ($supplierDemands as $demand) {
$alreadyDemand[] = $demand['id_order_detail'];
$demandStates = SupplierDemand::$states;
$demandProduct = SupplierDemand::getProductStatic((int)$demand['id_supplier_demand']);
echo '('.Tools::displayDate($demand['date_upd'], $cookie->id_lang).') :
<b><a href="index.php?tab=AdminAntSupplierDemand&id='.$demand['id_supplier_demand'].'&updateSupplierDemand=1&token='.Tools::getAdminToken('AdminAntSupplierDemand'.(int)(Tab::getIdFromClassName('AdminAntSupplierDemand')).(int)($cookie->id_employee)).'">'.$this->l('#').sprintf('%06d', $demand['id_supplier_demand']).'</a></b> -
'.$demandStates[$demand['id_state']]['name'].'<br />
<b>'.$demandProduct['product_name'].'</b><br /><br />';
}
}
echo '<br /><br />
<h4>'.$this->l('Make a supplier demand').'</h4>
<form id="new_supplier_demand" action="" method="post">
<p>
<label style="width: auto; margin-bottom: 5px;">'.$this->l('Product').'</label>
<select name="id_order_detail">';
foreach($products as $product) {
if(in_array($product['id_order_detail'],$alreadyDemand)){
continue;
}
$demand_product++;
echo '<option value="'.$product['id_order_detail'].'">'.$product['product_name'].'</option>';
}
echo '</select>
</p>';
if($demand_product==0){
echo '<p class="warning">'.$this->l('All products are in demand').'</p>';
} else {
echo '<p>
<label style="width: auto; margin-bottom: 5px;">'.$this->l('Quantity').'</label>
<input type="number" name="qty" value="0"/>
</p>
<p>
<label style="width: auto; margin-bottom: 5px;">'.$this->l('Insert a comment (optional):').'</label>
<textarea name="demand_comment" rows="5" cols="50" style="resize: vertical"></textarea>
</p>
<input type="hidden" value="'.$order->id.'" name="id_order/>
<p class="submit"><input type="submit" value="'.$this->l('Confirm').'" name="submitSupplierDemand" class="button" /></p>';
}
echo '</form>
</fieldset>';
/* Display credit slip */
echo '
<br />
<fieldset style="width: 400px;">
<legend><img src="../img/admin/slip.gif" alt="'.$this->l('Credit slip').'" />'.$this->l('Credit slip').'</legend>';
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).') : <b><a href="pdf.php?id_order_slip='.$slip['id_order_slip'].'">'.$this->l('#').sprintf('%06d', $slip['id_order_slip']).'</a></b><br />';
echo '</fieldset>
</div>';
echo '<div class="clear">&nbsp;</div>';
echo '<br /><br /><a href="'.$currentIndex.'&token='.$this->token.'"><img src="../img/admin/arrow2.gif" /> '.$this->l('Back to list').'</a><br />';
}
public function displayAddressDetail($addressDelivery)
{
// Allow to add specific rules
$patternRules = array(
'avoid' => array()
//'avoid' => array('address2')
);
return AddressFormat::generateAddress($addressDelivery, $patternRules, '<br />');
}
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 '<h2 class="space" style="text-align:right; margin-right:44px;">'.$this->l('Total:').' '.Tools::displayPrice($this->getTotal(), $currency).'</h2>';
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);
echo '<h2 class="space" style="text-align:right; margin-right:44px;">'.$this->l('Total durée :').' '.Tools::displayPrice($total_duree, $currency).'</h2>';
}
}
}
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;
}
public function _displayStateIcon($id_order_state,$name)
{
switch ($id_order_state) {
case '1': // En attente de paiement par cheque
case '10': // En attente de paiement par virement bancaire
case '11': // En attente de paiement par Paypal
return '<a style="pointer-event:none" class="btn btn-info"><span class=" anticon anticon-hour-glass"></span> '.$name.'</a>';
break;
case '2': // Paiement accepté
case '12': // Paiement à distance accepté
return '<a style="pointer-events:none" class="btn btn-info"><span class=" anticon anticon-credit-card"></span> '.$name.'</a>';
break;
case '13': // Autorisation accepté Paypal
return '<a style="pointer-events:none" class="btn btn-info"><span class=" anticon anticon-paypal"></span> '.$name.'</a>';
break;
case '14': // Ne pas expédié
case '20': // Problème adresse
return '<a style="pointer-events:none" class="btn btn-grey"><span class=" anticon anticon-cross"></span> '.$name.'</a>';
break;
case '8': // Erreur de paiement
return '<a style="pointer-events:none" class="btn btn-danger"><span class=" anticon anticon-cross"></span> '.$name.'</a>';
break;
case '15': // Commande frauduleuse
return '<a style="pointer-events:none" class="btn btn-grey"><span class="-dark anticon anticon-cross"></span> '.$name.'</a>';
break;
case '19': // Commande en attente
return '<a style="pointer-events:none" class="btn btn-warning"><span class=" anticon anticon-hour-glass"></span> '.$name.'</a>';
break;
case '3': // Préparation en cours
return '<a style="pointer-events:none" class="btn btn-warning"><span class=" anticon anticon-box-add"></span> '.$name.'</a>';
break;
case '4': // Commande expédiée
return '<a style="pointer-events:none" class="btn btn-success"><span class=" anticon anticon-truck"></span> '.$name.'</a>';
break;
case '17': // Commande partiellement expédiée
return '<a style="pointer-events:none" class="btn btn-green-light"><span class="anticon anticon-truck"></span> '.$name.'</a>';
break;
case '7': // Commande remboursée
return '<a style="pointer-events:none" class="btn btn-warning-more"><span class="anticon anticon-coin-euro"></span> '.$name.'</a>';
break;
case '18': // Commande remboursée
return '<a style="pointer-events:none" class="btn btn-red"><span class="anticon anticon-shield"></span> '.$name.'</a>';
break;
default:
return '<a style="pointer-events:none" class="btn btn-grey">'.$name.'</a>';
break;
}
}
public function _getOrderDetail($cart, $id_lang, $order)
{
if(Db::getInstance()->getValue('
SELECT `id_carrier`
FROM `'._DB_PREFIX_.'carrier`
WHERE `id_carrier` = '.(int) $cart->id_carrier.'
AND `name` LIKE "%colissimo%"
')) {
$socol = Db::getInstance()->getRow('
SELECT *
FROM `'._DB_PREFIX_.'socolissimo_delivery_info`
WHERE `id_cart` = '.(int) $cart->id.'
AND `cecountry` IN ("FR","BE","ES")
AND (`pradress1`!= "" OR `pradress2`!= "" OR `pradress3`!= "" OR `pradress4`!= "")
');
if($socol && (int)$cart->id_carrier != (int)Configuration::get('ANT_CARRIER_DOM')) {
$order_address = nl2br(preg_replace("/(\r\n){2,}/", "\r\n", implode("\r\n", array(
$socol['cefirstname'].' '.$socol['cename'],
$socol['cecompanyname'],
$socol['prname'],
$socol['prcompladress'],
$socol['pradress1'],
$socol['pradress2'],
$socol['pradress3'],
$socol['pradress4'],
$socol['przipcode'].' '.$socol['prtown'],
$socol['cecountry'],
$socol['cephonenumber'],
!empty($socol['cedoorcode1'])? 'Code porte 1 : '.$socol['cedoorcode1']: '',
!empty($socol['cedoorcode2'])? 'Code porte 2 : '.$socol['cedoorcode2']: '',
$socol['cedeliveryinformation'],
))));
} else {
$order_address = nl2br(AddressFormat::generateAddress(new Address((int) $order->id_address_delivery)));
}
} elseif(Db::getInstance()->getValue('
SELECT COUNT(*)
FROM `'._DB_PREFIX_.'mr_method`
WHERE `id_carrier` = '.(int) $cart->id_carrier.'
')) {
$mr = Db::getInstance()->getRow('
SELECT mr_s.*
FROM `' . _DB_PREFIX_ . 'mr_selected` mr_s
WHERE `id_cart` = ' . (int) $cart->id . '
AND `MR_Selected_Num` IS NOT NULL
');
if($mr) {
$order_address = nl2br(preg_replace("/(\r\n){2,}/", "\r\n", implode("\r\n", array(
$mr['MR_Selected_LgAdr1'],
$mr['MR_Selected_LgAdr2'],
$mr['MR_Selected_LgAdr3'] . ' ' . $mr['MR_Selected_LgAdr4'],
$mr['MR_Selected_CP'] . ' ' . $mr['MR_Selected_Ville'],
'FRANCE',
'Point Relais : '.$mr['MR_Selected_Num']
))));
} else {
$order_address = nl2br(AddressFormat::generateAddress(new Address((int) $order->id_address_delivery)));
}
} else {
$order_address = nl2br(AddressFormat::generateAddress(new Address((int) $order->id_address_delivery)));
}
return array(
'order_invoice_address' => nl2br(AddressFormat::generateAddress(new Address((int) $order->id_address_invoice))),
'order_delivery_address' => nl2br(AddressFormat::generateAddress(new Address((int) $order->id_address_delivery))),
'order_address' => $order_address,
);
}
}