Files
bio-concept-labo/web/modules/sonice_retour/sonice_retour.php
2019-11-20 07:44:43 +01:00

1000 lines
38 KiB
PHP

<?php
/**
* NOTICE OF LICENSE
*
* This source file is subject to a commercial license from Common-Services Co., Ltd.
* Use, copy, modification or distribution of this source file without written
* license agreement from the SARL SMC is strictly forbidden.
* In order to obtain a license, please contact us: contact@common-services.com
* ...........................................................................
* INFORMATION SUR LA LICENCE D'UTILISATION
*
* L'utilisation de ce fichier source est soumise a une licence commerciale
* concedee par la societe Common-Services Co., Ltd.
* Toute utilisation, reproduction, modification ou distribution du present
* fichier source sans contrat de licence ecrit de la part de la Common-Services Co. Ltd. est
* expressement interdite.
* Pour obtenir une licence, veuillez contacter Common-Services Co., Ltd. a l'adresse: contact@common-services.com
* ...........................................................................
*
* @package SoNice Retour
* @author Alexandre D.
* @copyright Copyright (c) 2011-2015 Common Services Co Ltd - 90/25 Sukhumvit 81 - 10260 Bangkok - Thailand
* @license Commercial license
* Support by mail : support.sonice@common-services.com
*/
if (!defined('_PS_VERSION_')) {
exit;
}
if (!class_exists('SoNiceRetourTools')) {
require_once(_PS_MODULE_DIR_.'sonice_retour/classes/SoNiceRetourTools.php');
}
if (!class_exists('ConfigureMessage')) {
require_once(_PS_MODULE_DIR_.'sonice_retour/classes/shared/configure_message.class.php');
}
class SoNice_Retour extends Module
{
const ADD = 'a';
const REMOVE = 'd';
const UPDATE = 'u';
protected $ps16x = false;
protected $ps15x = false;
/** @var array ISO code of available countries */
protected $available_countries = array(
'fr', 'de', 'es', 'gb', 'lu', 'nl', 'be', 'ie', 'cz', 'sk', 'si', 'fi', 'at', 'it'
);
/** @var boolean Specify if the module is run in debug mode or not */
protected $debug = false;
public $path;
public $url;
public $id_lang;
public $download_folder;
public $http_download_folder;
public $function_folder;
public $change_return_state_url;
public $action_merchandise_return_url;
public $get_label_url;
public function __construct()
{
$this->name = 'sonice_retour';
$this->tab = 'shipping_logistics';
$this->version = '2.0.09';
$this->author = 'Common-Services';
$this->need_instance = 0;
$this->limited_countries = $this->available_countries;
$this->module_key = 'c9b0bd56ba47b0d88b9964dacc6ab652';
parent::__construct();
$this->displayName = 'SoNice Retour';
$this->description = $this->l(
'This service permits to generate labels with or without proof of submission according to your contract.'
);
$this->path = _PS_MODULE_DIR_.$this->name.'/';
$this->url = __PS_BASE_URI__.basename(_PS_MODULE_DIR_).'/'.$this->name.'/';
$this->download_folder = $this->path.'download/';
$this->http_download_folder = $this->url.'download/';
$this->function_folder = $this->url.'functions/';
$this->change_return_state_url = $this->function_folder.'changeReturnState.php';
$this->action_merchandise_return_url = $this->function_folder.'changeReturnState.php';
$this->get_label_url = $this->function_folder.'get_labels.php';
$this->bootstrap = true;
$this->initContext();
}
/**
* Init Prestashop context for version 1.5 & 1.4
*/
private function initContext()
{
if (version_compare(_PS_VERSION_, '1.6', '>=')) {
$this->ps16x = true;
}
if (version_compare(_PS_VERSION_, '1.5', '>=')) {
$this->context = Context::getContext();
$this->id_lang = (int)Context::getContext()->language->id;
$this->ps15x = true;
} else {
require_once(_PS_MODULE_DIR_.'sonice_retour/backward_compatibility/backward.php');
$this->context = Context::getContext();
$this->id_lang = (int)Context::getContext()->language->id;
$this->ps15x = false;
}
$this->context->smarty->assign(array(
'ps16x' => $this->ps16x,
'ps15x' => $this->ps15x,
'snr_url' => $this->url,
'snr_css' => $this->url.'views/css/',
'snr_js' => $this->url.'views/js/',
'snr_img' => $this->url.'views/img/'
));
$this->debug = (bool)Configuration::get('ETIQUETAGE_RETURN_DEBUG');
}
/**
* Set up hooks
*
* @param string $action
* @return bool
*/
private function hookSetup($action)
{
if ($this->ps15x) {
$expected_hooks = array(
'displayAdminOrder',
'actionCarrierUpdate',
'actionOrderReturn'
);
} else {
$expected_hooks = array(
'adminOrder',
'updateCarrier',
'orderReturn'
);
}
$pass = true;
if (in_array($action, array(self::REMOVE, self::UPDATE))) {
foreach ($expected_hooks as $expected_hook) {
if (!$this->unregisterHook($expected_hook)) {
$pass = false;
}
}
}
if (in_array($action, array(self::ADD, self::UPDATE))) {
foreach ($expected_hooks as $expected_hook) {
if (!$this->registerHook($expected_hook)) {
$pass = false;
}
}
}
return ($pass);
}
private function myAddJS($url)
{
if ($this->ps15x) {
$this->context->controller->addJS($url);
} else {
echo '<script type="text/javascript" src="'.$url.'"></script>';
}
}
private function myAddJQueryUI($name = null)
{
if ($this->ps15x) {
$this->context->controller->addJqueryUI($name);
} else {
echo '<script type="text/javascript" src="'._PS_JS_DIR_.'jquery/jquery-ui-1.8.10.custom.min.js"></script>';
}
return (true);
}
private function myAddCSS($url, $media)
{
if ($this->ps15x) {
return ($this->context->controller->addCSS($url, $media));
} else {
echo '<link type="text/css" rel="stylesheet" href="'.$url.'">';
}
}
private function backofficeInformations()
{
$php_infos = array();
$module_infos = array();
$module_config = unserialize(Configuration::get('ETIQUETAGE_RETURN_CONF'));
$prestashop_infos = array();
// Web service settings
if (!isset($module_config['ContractNumber']) || empty($module_config['ContractNumber'])) {
$module_infos['ws_login']['message'] = $this->l(
'You did not set a login yet, please fill the login field in the Login tab.'
);
$module_infos['ws_login']['level'] = $this->ps16x ? 'alert alert-warning' : 'warn';
}
if (!isset($module_config['Password']) || empty($module_config['Password'])) {
$module_infos['ws_pwd']['message'] = $this->l(
'You did not set a password yet, please fill the password field in the Login tab.'
);
$module_infos['ws_pwd']['level'] = $this->ps16x ? 'alert alert-warning' : 'warn';
}
if (!isset($module_config['Line2']) || empty($module_config['Line2'])
|| !isset($module_config['countryCode']) || empty($module_config['countryCode'])
|| !isset($module_config['City']) || empty($module_config['City'])
|| !isset($module_config['PostalCode']) || empty($module_config['PostalCode'])) {
$module_infos['ws_address']['message'] = $this->l(
'You did not set an address yet, please fill the address fields in the Address tab.'
);
$module_infos['ws_address']['level'] = $this->ps16x ? 'alert alert-warning' : 'warn';
}
// PHP
if (!is_writable(_PS_MODULE_DIR_.'sonice_retour/download')) {
$php_infos['dl_w']['message'] = sprintf($this->l(
'You have to set write permissions to the %s directory'
), _PS_MODULE_DIR_.'sonice_retour/download');
$php_infos['dl_w']['level'] = $this->ps16x ? 'alert alert-warning' : 'warn';
}
if (!method_exists('DOMDocument', 'createElement')) {
$php_infos['domdocument']['message'] = $this->l(
'PHP DOMDocument (XML Library) must be installed on this server. '.
'The module require this library and can\'t work without it.'
);
$php_infos['domdocument']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
$php_infos['domdocument']['link'] = 'http://php.net/manual/'.Language::getIsoById($this->id_lang).
'/class.domdocument.php';
}
if (!function_exists('curl_init')) {
$php_infos['curl']['message'] = $this->l('cURL extension must be available on your server.');
$php_infos['cur;']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
$php_infos['curl']['link'] = 'http://php.net/manual/'.Language::getIsoById($this->id_lang).'/book.curl.php';
}
if (in_array(@Tools::strtolower(ini_get('display_errors')), array('1', 'on'))) {
$php_infos['display_errors']['message'] = $this->l('PHP variable display_errors is On.');
$php_infos['display_errors']['level'] = $this->ps16x ? 'alert alert-info' : 'info';
}
if (!function_exists('mb_convert_encoding')) {
$php_infos['mbstring']['message'] = $this->l(
'PHP mb_string functions must be installed on this server. '.
'The module require this library and can\'t work without it.'
);
$php_infos['mbstring']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
$php_infos['mbstring']['link'] = 'http://php.net/manual/'.Language::getIsoById($this->id_lang).
'/mbstring.setup.php';
}
// PrestaShop
if (!(int)Configuration::get('PS_SHOP_ENABLE')) {
$prestashop_infos['maintenance']['message'] = $this->l(
'Be carefull, your shop is in maintenance mode, the module might not work in that mode'
);
$prestashop_infos['maintenance']['level'] = $this->ps16x ? 'alert alert-warning' : 'warn';
}
if (_PS_MODE_DEV_) {
$prestashop_infos['dev_mode']['message'] = $this->l('The Prestashop constant _PS_MODE_DEV_ is enabled.');
$prestashop_infos['dev_mode']['level'] = $this->ps16x ? 'alert alert-info' : 'info';
}
// URL issues for Ajax
$pass = true;
if (version_compare(_PS_VERSION_, '1.5', '>=')) {
if (Shop::isFeatureActive()) {
$shop = Context::getContext()->shop;
if ($_SERVER['HTTP_HOST'] != $shop->domain && $_SERVER['HTTP_HOST'] != $shop->domain_ssl) {
$pass = false;
}
} else {
$urls = ShopUrl::getShopUrls($this->context->shop->id)->where('main', '=', 1)->getFirst();
if ($_SERVER['HTTP_HOST'] != $urls->domain && $_SERVER['HTTP_HOST'] != $urls->domain_ssl) {
$pass = false;
}
}
} elseif (version_compare(_PS_VERSION_, '1.4', '>=')) {
if ($_SERVER['HTTP_HOST'] != Configuration::get('PS_SHOP_DOMAIN') &&
$_SERVER['HTTP_HOST'] != Configuration::get('PS_SHOP_DOMAIN_SSL')) {
$pass = false;
}
}
if (!$pass) {
$prestashop_infos['wrong_domain']['message'] = $this->l(
'Your are currently connected with the following domain name:'
).' '.$_SERVER['HTTP_HOST'].'. '.$this->l(
'This one is different from the main shop domain name set in "Preferences > SEO & URLs":'
).' '.Configuration::get('PS_SHOP_DOMAIN').'...';
$prestashop_infos['wrong_domain']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
}
$view_params = array();
$view_params['module_infos'] = $module_infos;
$view_params['module_info_ok'] = !count($module_infos);
$view_params['php_infos'] = $php_infos;
$view_params['php_info_ok'] = !count($php_infos);
$view_params['prestashop_infos'] = $prestashop_infos;
$view_params['prestashop_info_ok'] = !count($prestashop_infos);
ob_start();
try {
@phpinfo(INFO_ALL & ~INFO_CREDITS & ~INFO_LICENSE & ~INFO_ENVIRONMENT & ~INFO_VARIABLES);
} catch (Exception $excp) {
echo 'phpinfo() has been disabled for security reasons. '.$excp->getMessage();
}
$phpinfos = ob_get_clean();
$phpinfos = preg_replace(
'/(a:link.*)|(body, td, th, h1, h2.*)|(img.*)|(td, th.*)|(a:hover.*)|(class="center")/',
'',
$phpinfos
);
$view_params['phpinfo_str'] = empty($phpinfos) ?
$this->l('phpinfo() has been disabled for security reasons.') : $phpinfos;
$view_params['psinfo_str'] = $this->psInfo();
$view_params['dbinfo_str'] = $this->dbInfo();
return ($view_params);
}
public function psInfo()
{
// TODO
$prestashop_info = '';
if ($this->ps15x) {
$sort = 'ORDER by `name`,`id_shop`';
} else {
$sort = 'ORDER by `name`';
}
$results = Db::getInstance()->executeS(
'SELECT *
FROM `'._DB_PREFIX_.'configuration`
WHERE `name` LIKE "PS_%"
OR `name` LIKE "ETIQUETAGE_RETURN_%"
'.$sort
);
$ps_configuration = null;
foreach ($results as $result) {
if (strpos($result['name'], 'KEY') || strpos($result['name'], 'EMAIL') ||
strpos($result['name'], 'PASSWORD') || strpos($result['name'], 'PASSWD') ||
strpos($result['name'], 'CONTEXT_DATA')) {
continue;
}
$value = $result['value'];
if (base64_encode(base64_decode($value, true)) === $value) {
$value = base64_decode($value, true);
} else {
$value = $result['value'];
}
if (@serialize(@unserialize($value)) == $value) {
$value = '<div class="print_r">'.print_r(unserialize($value), true).'</div>';
} else {
$value = Tools::strlen($result['value']) > 128 ?
Tools::substr($result['value'], 0, 128).'...' : $result['value'];
}
if ($this->ps15x) {
$ps_configuration .= sprintf(
'%-50s %03d %03d : %s'."\n",
$result['name'],
$result['id_shop'],
$result['id_shop_group'],
$value
);
} else {
$ps_configuration .= sprintf('%-50s : %s'."\n", $result['name'], $value);
}
}
$prestashop_info .= '<h1>Prestashop</h1>';
$prestashop_info .= '<pre>';
$prestashop_info .= 'Version: '._PS_VERSION_."\n\n";
$prestashop_info .= "\n";
$prestashop_info .= $ps_configuration;
$prestashop_info .= '</pre>'."\n\n";
return ($prestashop_info);
}
public function dbInfo()
{
$tables_to_check = array(
_DB_PREFIX_.'so_return_label'
);
$query = Db::getInstance()->executeS('SHOW TABLES');
$tables = array();
foreach ($query as $rows) {
foreach ($rows as $t) {
$tables[$t] = 1;
}
}
$not_existing_tables = array();
foreach ($tables_to_check as $to_check) {
if (!isset($tables[$to_check])) {
$not_existing_tables[] = $to_check;
ConfigureMessage::error(
$this->l(
'The table `'.$to_check.'` was not found in your database.'
)
);
}
}
$tables_column = array();
foreach ($tables_to_check as $to_check) {
if (in_array($to_check, $not_existing_tables)) {
$tables_column[] = null;
continue;
}
$result = Db::getInstance()->executeS('SHOW COLUMNS FROM `'.$to_check.'`');
foreach ($result as $id => $column) {
$result[$id] = $column['Field'];
}
$tables_column[] = $result;
}
$db_info = '<h1>'.$this->l('Database').'</h1>';
$db_info .= '<pre>';
foreach ($tables_to_check as $id => $to_check) {
$db_info .= 'SHOW COLUMNS FROM `'.$to_check.'` : '.(in_array($to_check, $not_existing_tables) ?
'N/A<br>' : print_r($tables_column[$id], true));
$db_info .= 'SELECT * FROM `'.$to_check.'` ORDER BY `date_add` DESC LIMIT 5 : ';
$db_info .= print_r(Db::getInstance()->executeS(
'SELECT *
FROM `'.$to_check.'`
ORDER BY `date_add`
DESC LIMIT 5'
), true);
}
$db_info .= '</pre>';
return ($db_info);
}
private function checkhttpDownloadFolder()
{
if (!is_writable($this->download_folder)) {
@chmod($this->download_folder, 7777);
}
$content = 'Hello World !'.PHP_EOL;
if (file_put_contents($this->download_folder.'TO_DELETE.txt', $content) === false) {
printf(
'%s/%d: %s - %s',
basename(__FILE__),
__LINE__,
$this->l('Failed to write to the directory'),
$this->download_folder
);
return (false);
}
return (true);
}
public function install()
{
$pass = true;
if (!parent::install()) {
$this->_errors[] = $this->l('An error occured while installing with parent::install().');
$pass = false;
}
if (!$this->hookSetup(self::ADD)) {
$this->_errors[] = $this->l('An error occured while registering hooks.');
$pass = false;
}
if (!$this->checkhttpDownloadFolder()) {
$this->_errors[] = $this->l('An error occured while checking folder permissions.');
$pass = false;
}
// Basic configuration setup
$shop_phone = Configuration::get('PS_SHOP_PHONE');
$shop_phone = preg_replace('/\D/', '', $shop_phone);
$default_shop_informations = array(
'ContractNumber' => null,
'Password' => null,
'Name' => null,
'Surname' => null,
'ServiceInfo' => null,
'companyName' => Configuration::get('PS_SHOP_NAME'),
'Line0' => Configuration::get('PS_SHOP_ADDR2'),
'Line1' => null,
'Line2' => Configuration::get('PS_SHOP_ADDR1'),
'Line3' => null,
'PostalCode' => Configuration::get('PS_SHOP_CODE'),
'City' => Configuration::get('PS_SHOP_CITY'),
'countryCode' => 'FR',
'phoneNumber' => $shop_phone,
'Mail' => Configuration::get('PS_SHOP_EMAIL'),
'demo' => null,
'insurance' => null,
'deposit_date' => null,
'output_print_type' => 'PDF_A4_300dpi'
);
Configuration::updateValue('ETIQUETAGE_RETURN_CONF', serialize($default_shop_informations));
// Database
$sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'so_return_label` (
`id_label` INT(10) NOT NULL AUTO_INCREMENT,
`id_return` INT(10) NOT NULL,
`id_coliposte` VARCHAR(20) NOT NULL,
`date_add` DATETIME NOT NULL,
`date_upd` DATETIME NOT NULL,
PRIMARY KEY (`id_label`)
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8;';
if (!Db::getInstance()->execute($sql)) {
$pass = false;
}
return ((bool)$pass);
}
public function uninstall()
{
$pass = true;
if (!$this->hookSetup(self::REMOVE)) {
$this->_errors[] = $this->l('An error occured while unregistering hooks.');
$pass = false;
}
if (!parent::uninstall()) {
$this->_errors[] = $this->l('An error occured while uninstalling with parent::uninstall().');
$pass = false;
}
Configuration::deleteByName('ETIQUETAGE_RETURN_CONF');
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'so_return_label`');
return ((bool)$pass);
}
public function getContent()
{
$output = null;
if (Tools::isSubmit('submit'.$this->name)) {
$pass = true;
$values = Tools::getValue('return_info');
$values['ContractNumber'] = trim($values['ContractNumber']);
$values['Password'] = trim($values['Password']);
$values['deposit_date'] = (int)$values['deposit_date'];
$pass += Configuration::updateValue('ETIQUETAGE_RETURN_CONF', serialize($values));
$pass += Configuration::updateValue('ETIQUETAGE_RETURN_DEBUG', Tools::getValue('sne_debug'));
$pass += Configuration::updateValue('ETIQUETAGE_RETURN_TEST', Tools::getValue('sne_test_mode'));
// Database
$sql =
'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'so_return_label` (
`id_label` INT(10) NOT NULL AUTO_INCREMENT,
`id_return` INT(10) NOT NULL,
`id_coliposte` VARCHAR(20) NOT NULL,
`date_add` DATETIME NOT NULL,
`date_upd` DATETIME NOT NULL,
PRIMARY KEY (`id_label`)
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8;';
$pass += Db::getInstance()->execute($sql);
if ($pass) {
$output .= $this->displayConfirmation($this->l('Options updated.'));
} else {
$output .= $this->displayError($this->l('The system failed to save your options.'));
}
$this->hookSetup(self::UPDATE);
}
return $output.$this->displayForm();
}
public function displayForm()
{
require_once(dirname(__FILE__).'/classes/shared/configure_tab.class.php');
$html = '';
$alert_class = array();
$alert_class['danger'] = $this->ps16x ? 'alert alert-danger' : 'error';
$alert_class['warning'] = $this->ps16x ? 'alert alert-warning' : 'warn';
$alert_class['success'] = $this->ps16x ? 'alert alert-success' : 'conf';
$alert_class['info'] = $this->ps16x ? 'alert alert-info' : 'hint';
$this->context->smarty->assign(
array(
'sne_name' => $this->displayName,
'sne_version' => $this->version,
'ps_version' => _PS_VERSION_,
'sne_description' => $this->description,
'sne_module_dir' => $this->url,
'sne_module_path' => $this->path,
'sne_check_login' => $this->url.'functions/check_login.php?token='.md5(_COOKIE_IV_),
'sne_config' => unserialize(Configuration::get('ETIQUETAGE_RETURN_CONF')),
'sne_info' => $this->backofficeInformations(),
'selected_tab' => Tools::getValue('selected_tab') ? Tools::getValue('selected_tab') : '0',
'sne_module_name' => $this->name,
'alert_class' => $alert_class,
'sne_debug' => Configuration::get('ETIQUETAGE_RETURN_DEBUG'),
'sne_test_mode' => Configuration::get('ETIQUETAGE_RETURN_TEST'),
'sne_mails' => $this->getTemplates('fr')
)
);
$tab_list = array();
$tab_list[] = array(
'id' => 'sonice_retour', 'img' => 'sonice_retour', 'name' => 'SoNice Retour', 'selected' => true
);
$tab_list[] = array(
'id' => 'informations', 'img' => 'information', 'name' => 'Informations', 'selected' => false
);
$tab_list[] = array('id' => 'account', 'img' => 'key', 'name' => $this->l('Account'), 'selected' => false);
$tab_list[] = array('id' => 'address', 'img' => 'house', 'name' => $this->l('Address'), 'selected' => false);
$tab_list[] = array('id' => 'conf', 'img' => 'cog_edit', 'name' => $this->l('Settings'), 'selected' => false);
$this->myAddCSS($this->url.'views/css/configuration16.css', 'all');
$this->myAddCSS($this->url.'views/css/jquery.qtip.min.css', 'all');
$this->myAddJS($this->url.'views/js/configuration.js');
$this->myAddJS($this->url.'views/js/jquery.qtip.min.js');
$html .= ConfigureMessage::display();
$html .= $this->context->smarty->fetch(dirname(__FILE__).'/views/templates/admin/configuration/header.tpl');
$html .= ConfigureTab::generateTabs($tab_list);
$html .= $this->context->smarty->fetch(
dirname(__FILE__).'/views/templates/admin/configuration/configuration.tpl'
);
return ($html);
}
/**
* @see AdminStatusesController
* @param null $lang
* @return array
*/
protected function getTemplates($lang = null)
{
$default_path = '../mails/';
$theme_path = '../themes/'._THEME_NAME_.'/mails/';
$array = array();
foreach (Language::getLanguages(false) as $language) {
$iso_code = $language['iso_code'];
if ($lang && Tools::strtolower($lang) != Tools::strtolower($iso_code)) {
continue;
}
if (!@filemtime(_PS_ADMIN_DIR_.'/'.$default_path.$iso_code) &&
!@filemtime(_PS_ADMIN_DIR_.'/'.$theme_path.$iso_code)) {
continue;
}
$theme_templates_dir = _PS_ADMIN_DIR_.'/'.$theme_path.$iso_code;
$theme_templates = is_dir($theme_templates_dir) ? scandir($theme_templates_dir) : array();
$templates = array_unique(array_merge(scandir(
_PS_ADMIN_DIR_.'/'.$default_path.$iso_code
), $theme_templates));
foreach ($templates as $template) {
if (!strncmp(strrev($template), 'lmth.', 5)) {
$search_result = array_search($template, $theme_templates);
$array[$iso_code][] = array(
'id' => Tools::substr($template, 0, -5),
'name' => Tools::substr($template, 0, -5),
'folder' => ((!empty($search_result)?$theme_path:$default_path))
);
}
}
}
if ($lang && isset($array[Tools::strtolower($lang)])) {
return $array[Tools::strtolower($lang)];
}
return $array;
}
public function hookActionOrderReturn($params)
{
$customer = new Customer($params['orderReturn']->id_customer);
$order = new Order($params['orderReturn']->id_order);
$returned_products = OrderReturn::getOrdersReturnDetail($params['orderReturn']->id);
$items_list = '';
foreach ($returned_products as $id_details) {
$order_details = new OrderDetail($id_details['id_order_detail']);
$items_list .= $this->l('Reference').' : '.$order_details->product_reference.'
'.$this->l('Product').' : '.$order_details->product_name.'
'.$this->l('Quantity').' : '.$order_details->product_quantity_return;
}
$items_table = '<table>
<thead>
<tr>
<th>'.$this->l('Reference').'</th>
<th>'.$this->l('Product').'</th>
<th>'.$this->l('Quantity').'</th>
</tr>
</thead>
<tbody>';
foreach ($returned_products as $id_details) {
$order_details = new OrderDetail($id_details['id_order_detail']);
$items_table .= '
<tr>
<td>'.$order_details->product_reference.'</td>
<td>'.$order_details->product_name.'</td>
<td>'.$order_details->product_quantity_return.'</td>
</tr>';
}
$items_table .= '</tbody></table>';
// Filling-in vars for email
$template = 'returned_product';
$template_vars = array(
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{order_name}' => sprintf('%06d', $order->id),
'{shop_name}' => Configuration::get('PS_SHOP_NAME'),
'{date}' => $params['orderReturn']->date_add,
'{items}' => $items_table,
'{items_list}' => $items_list,
'{message}' => $this->l('A new return')
);
if (file_exists(dirname(__FILE__).'/mails/fr/returned_product.html')) {
Mail::Send(
Configuration::get('PS_LANG_DEFAULT'),
$template,
sprintf($this->l('Returned Order - #%06d'), $params['orderReturn']->id),
$template_vars,
Configuration::get('PS_SHOP_EMAIL'),
null,
Configuration::get('PS_SHOP_EMAIL'),
Configuration::get('PS_SHOP_NAME'),
null,
null,
dirname(__FILE__).'/mails/'
);
}
return (true);
}
public function hookDisplayAdminOrder($params)
{
$module_conf = unserialize(Configuration::get('ETIQUETAGE_RETURN_CONF'));
$already_returned = false;
$still_some = false;
$return_detail = array();
$this->context->smarty->assign('ps16x', $this->ps16x);
if ($this->ps15x) {
$order = new Order($params['id_order']);
if (!Validate::isLoadedObject($order)) {
return (false);
}
$address_delivery = new Address($order->id_address_delivery);
if (!Validate::isLoadedObject($address_delivery)) {
return (false);
}
} else {
if (!isset($params['id_order'])) {
return (false);
}
$order = new Order((int)$params['id_order']);
if (!Validate::isLoadedObject($order)) {
return (false);
}
$cart = new Cart($order->id_cart);
if (!Validate::isLoadedObject($cart)) {
return (false);
}
$address_delivery = new Address($cart->id_address_delivery);
if (!Validate::isLoadedObject($address_delivery)) {
return (false);
}
}
/* Check if return is available in the country */
// $order_country = Tools::strtolower(Country::getIsoById($address_delivery->id_country));
// if (!in_array($order_country, $this->available_countries)) {
// return (false);
// }
/* Check if order is in a proper state to be returned */
if ($this->ps15x && !$order->isPaidAndShipped()) {
return (false);
} elseif (!$order->hasBeenDelivered()) {
return (false);
}
$order_return = Db::getInstance()->executeS('
SELECT *
FROM `'._DB_PREFIX_.'order_return`
WHERE `id_customer` = '.(int)$order->id_customer.'
AND `id_order` = '.(int)$order->id.'
ORDER BY `id_order_return` ASC
');
$order_details = array();
$product_left_list = null;
if (is_array($order_return) && count($order_return)) {
$already_returned = true;
$product_returned_list = array();
foreach ($order_return as $key => $return) {
$return_details = OrderReturn::getOrdersReturnDetail((int)$return['id_order_return']);
foreach ($return_details as $detail) {
$product_returned_list['return'][$key][$detail['id_order_detail']] = $detail;
$product_returned_list['product'][$detail['id_order_detail']] = $detail['product_quantity'];
}
$order_details = $order->getProductsDetail();
foreach ($order_details as $order_detail) {
$to_minus = isset($product_returned_list['product'][$order_detail['id_order_detail']])
? $product_returned_list['product'][$order_detail['id_order_detail']]
: 0;
$product_left_list[$order_detail['id_order_detail']] =
(int)$order_detail['product_quantity'] - (int)$to_minus;
$return_detail[$key]['date'] = isset($return) ? $return['date_add'] : null;
// Get PDF, state, color
$state = null;
$state = new OrderReturnState((int)$return['state'], $this->id_lang);
if (Validate::isLoadedObject($state)) {
$return_detail[$key]['pdf'] = Db::getInstance()->getValue(
'SELECT `id_coliposte`
FROM `'._DB_PREFIX_.'so_return_label`
WHERE `id_return` = '.(int)$order_return[$key]['id_order_return']
);
$return_detail[$key]['state'] = $state->name;
$return_detail[$key]['color'] = $state->color;
} else {
$return_detail[$key]['pdf'] = $this->l('Unknown');
$return_detail[$key]['state'] = $this->l('Unknown');
$return_detail[$key]['color'] = 'red';
}
$return_detail[$key]['id_order_return'] = $return['id_order_return'];
$return_detail[$key]['metadata'] = array(
'id_order_return' => $return['id_order_return'],
// OCARAT ajout du motif du retour
'question' => $return['question'],
'pdf' => $return_detail[$key]['pdf'],
'state' => $return_detail[$key]['state'],
'color' => $return_detail[$key]['color']
);
}
}
$this->context->smarty->assign(array(
'sonice_retour_returnedProduct' => $product_returned_list,
'sonice_retour_productLeft' => $product_left_list,
// OCARAT ajout du lien pour afficher le retour dans AdminReturn
'sonice_retour_returnDetail_link' =>
$this->context->link->getAdminLink('AdminReturn') . '&updateorder_return&id_order_return=',
'sonice_retour_returnDetail' => $return_detail,
'sonice_retour_tracking_url' =>
'http://www.colissimo.fr/portail_colissimo/suivreResultat.do?parcelnumber='
));
// still some
$total_product_order = 0;
foreach ($order_details as $detail) {
$total_product_order += $detail['product_quantity'];
}
$total_product_returned = 0;
foreach ($product_returned_list['return'] as $returned_part) {
foreach ($returned_part as $product_returned) {
$total_product_returned += $product_returned['product_quantity'];
}
}
$still_some = $total_product_order - $total_product_returned;
} else {
// no product returned yet
$order_details = $order->getProductsDetail();
foreach ($order_details as $order_detail) {
$product_left_list[$order_detail['id_order_detail']] =
(int)$order_detail['product_quantity'] - (int)$order_detail['product_quantity_return'];
}
}
$token = '?token='.md5(_COOKIE_IV_);
/* Return begins */
$this->context->smarty->assign(
array(
'imgUrl' => $this->url.'views/img/',
'sonice_retour_alreadyChoseReturnProduct' => $already_returned,
'sonice_retour_stillSome' => $still_some,
'sonice_retour_id_order' => $params['id_order'],
'sonice_retour_id_customer' => $this->ps15x ? $params['cart']->id_customer : $order->id_customer,
'sonice_retour_id_delivery' => $this->ps15x ?
$params['cart']->id_address_delivery : $order->id_address_delivery,
'change_return_state_url' => $this->change_return_state_url.$token,
'action_merchandise_return_url' => $this->action_merchandise_return_url.$token,
'get_label_url' => $this->get_label_url.$token,
'sonice_retour_function_folder' => $this->function_folder,
'sonice_retour_http_download_folder' => $this->http_download_folder,
'sonice_retour_baseURL' => _PS_BASE_URL_,
'sonice_retour_productLeft' => $product_left_list,
'sonice_retour_stateList' => OrderReturnState::getOrderReturnStates($this->id_lang),
'sonice_retour_returnDetail' => $return_detail,
'sonice_retour_demo' => (isset($module_conf['demo']) && $module_conf['demo']) ?
$module_conf['demo'] : false,
'sonice_retour_printing_type' => isset($module_conf['printingType']) ?
$module_conf['printingType'] : 'tab'
)
);
$this->myAddCSS($this->url.'views/css/sonice_retour.css', 'all');
$this->myAddJS($this->url.'views/js/orderReturn.js');
$this->myAddJS($this->url.'views/js/plug.js');
// For "return all" button
$this->myAddJS($this->url.'views/js/jquery-simulate.js');
if ($this->ps15x) {
$this->myAddJQueryUI('ui.droppable');
$this->myAddJQueryUI('ui.draggable');
} else {
$this->myAddJQueryUI();
}
if (version_compare(_PS_VERSION_, '1.5', '>=')) {
return ($this->context->smarty->fetch(dirname(__FILE__).'/views/templates/admin/hook/orderReturn16.tpl'));
}
return ($this->context->smarty->fetch(dirname(__FILE__).'/views/templates/admin/hook/orderReturn.tpl'));
}
public function hookAdminOrder($params)
{
return ($this->hookDisplayAdminOrder($params));
}
public function hookOrderReturn($params)
{
return ($this->hookActionOrderReturn($params));
}
}