Files
bio-concept-pharma/web/modules/glstrackingnumber/glstrackingnumber.php
2019-11-17 19:14:07 +01:00

898 lines
42 KiB
PHP

<?php
/**
* 2008-today Mediacom87
*
* NOTICE OF LICENSE
*
* Read in the module
*
* 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 Mediacom87 <support@mediacom87.net>
* @copyright 2008-today Mediacom87
* @license define in the module
* @version 1.5.7
*/
if (!defined('_PS_VERSION_')) {
exit;
}
include_once dirname(__FILE__) . '/class/mediacom87.php';
class GlsTrackingNumber extends GlsTrackingNumberClass
{
public function __construct()
{
$this->name = 'glstrackingnumber';
$this->tab = 'shipping_logistics';
$this->version = '1.5.7';
$this->author = 'Mediacom87';
$this->need_instance = 0;
$this->module_key = 'af4ef1c76599c9dfc7a85f9d2a921ea3';
$this->addons_id = '4361'; // 4361
parent::__construct();
$this->displayName = $this->l('GLS Update Tracking Number');
$this->description = $this->l('This module allows you to update the status and the tracking number of your order with an export file of the software provided by the carrier GLS');
if (version_compare(_PS_VERSION_, '1.6.0.0', '>=')) {
$this->bootstrap = true;
} else {
$this->bootstrap = false;
}
}
public function install()
{
if (!parent::install()
|| !Configuration::updateValue('GLSSTRACKING_STATES', 4)
|| !Configuration::updateValue('GLSSTRACKING_SEPARATOR', ';')
|| !Configuration::updateValue('GLSSTRACKING_ORDERNUM', 5)
|| !Configuration::updateValue('GLSSTRACKING_ID', 18)
|| !Configuration::updateValue('GLSSTRACKING_HEADLINE', 1)
|| !Configuration::updateValue('GLSSTRACKING_ACCOUNTCOL', 16)
|| !Configuration::updateValue('GLSSTRACKING_ACCOUNT', 0)
|| !Configuration::updateValue('GLSSTATUS_BEFORE', 4)
|| !Configuration::updateValue('GLSSTATUS_RELAY', 4)
|| !Configuration::updateValue('GLSSTATUS_AFTER', 5)
|| !Configuration::updateValue('GLSSTRACKING_TL', 12)
|| !Configuration::updateValue('GLSSTRACKING_SECURE_KEY', Tools::strtoupper(Tools::passwdGen(8)))
|| !Configuration::updateValue('GLSSTRACKING_CRONHOURS', 3)
|| !Configuration::updateValue('GLSSTRACKING_NBORDERS', 30)
|| !Configuration::updateValue('GLSSTRACKING_CRONUPDATE', '')
) {
return false;
}
if (version_compare(_PS_VERSION_, '1.7.0.0', '<')) {
if (!$this->installModuleTab('AdminGlsTracking', 'AdminOrders')) {
return false;
}
}
return true;
}
public function uninstall()
{
if (!parent::uninstall()
|| !Configuration::deleteByName('GLSSTRACKING_STATES')
|| !Configuration::deleteByName('GLSSTRACKING_SEPARATOR')
|| !Configuration::deleteByName('GLSSTRACKING_ORDERNUM')
|| !Configuration::deleteByName('GLSSTRACKING_ID')
|| !Configuration::deleteByName('GLSSTRACKING_HEADLINE')
|| !Configuration::deleteByName('GLSSTRACKING_ACCOUNTCOL')
|| !Configuration::deleteByName('GLSSTRACKING_ACCOUNT')
|| !Configuration::deleteByName('GLSSTATUS_RELAY')
|| !Configuration::deleteByName('GLSSTATUS_BEFORE')
|| !Configuration::deleteByName('GLSSTATUS_AFTER')
|| !Configuration::deleteByName('GLSSTRACKING_TL')
|| !Configuration::deleteByName('GLSSTRACKING_SECURE_KEY')
|| !Configuration::deleteByName('GLSSTRACKING_CRONHOURS')
|| !Configuration::deleteByName('GLSSTRACKING_NBORDERS')
|| !Configuration::deleteByName('GLSSTRACKING_CRONUPDATE')
) {
return false;
}
if (version_compare(_PS_VERSION_, '1.7.0.0', '<')) {
if (!$this->uninstallModuleTab('AdminGlsTracking')) {
return false;
}
}
return true;
}
private function installModuleTab($tab_class, $tab_parent)
{
if (version_compare(_PS_VERSION_, '1.5.5.0', '>=')) {
Tools::copy(_PS_MODULE_DIR_.$this->name.'/logo.gif', _PS_IMG_DIR_.'t/'.$tab_class.'.gif');
} else {
@copy(_PS_MODULE_DIR_.$this->name.'/views/img/AdminGlsTracking.gif', _PS_IMG_DIR_.'t/'.$tab_class.'.gif'); // prestashop bug
@copy(_PS_MODULE_DIR_.$this->name.'/views/img/AdminGlsTracking.gif', _PS_MODULE_DIR_.$this->name.'/'.$tab_class.'.gif'); // prestashop bug
}
if (version_compare(_PS_VERSION_, '1.5.0.0', '<')) {
rename(_PS_MODULE_DIR_.$this->name.'/_AdminGlsTracking.php', _PS_MODULE_DIR_.$this->name.'/AdminGlsTracking.php');
}
$tab = new Tab();
$tab->class_name = $tab_class;
$tab->module = $this->name;
$tab->id_parent = Tab::getIdFromClassName($tab_parent);
$tab->position = Tab::getNbTabs($tab->id_parent);
$tab->name = array((int) Configuration::get('PS_LANG_DEFAULT') => 'GLS Tracking Number');
if (!$tab->add()) {
return false;
}
return true;
}
public function uninstallModuleTab($tab_class)
{
$id_tab = Tab::getIdFromClassName($tab_class);
if ($id_tab != 0) {
$tab = new Tab($id_tab);
$tab->delete();
@unlink(_PS_IMG_DIR_.'t/'.$tab_class.'.gif');
return true;
}
return false;
}
public function getContent($tab = 'AdminModules', $subtab = '')
{
if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
$this->currentIndex = AdminController::$currentIndex;
$this->cookie = Context::getContext()->cookie;
} else {
global $cookie, $currentIndex; // old version compatibility
$this->currentIndex = $currentIndex;
$this->cookie = $cookie;
}
if (!$link = Context::getContext()->link) {
$link = new link();
}
$output = '';
$this->token = Tools::getValue('token');
if (!$this->token) {
$this->token = Tools::getAdminToken($tab . (int) Tab::getIdFromClassName($tab) . (int) $this->cookie->id_employee);
}
if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
$this->form = $link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name.'&token='.$this->token;
} else {
$this->form = $this->currentIndex . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name . '&token=' . $this->token;
}
$conf = Configuration::getMultiple(array('GLSSTRACKING_ACCOUNT', 'GLSSTRACKING_ORDERNUM', 'GLSSTRACKING_ACCOUNTCOL', 'GLSSTRACKING_ACCOUNT', 'GLSSTRACKING_ID', 'GLSSTRACKING_SEPARATOR', 'GLSSTRACKING_HEADLINE', 'GLSSTRACKING_STATES'));
$output = '';
if ($conf['GLSSTRACKING_ACCOUNT'] == '1234-1235' || Tools::isEmpty($conf['GLSSTRACKING_ACCOUNT'])) {
$output = '<div class="bootstrap"><div class="alert alert-warning warn">'.$this->l('You need to configure propertly your accounts to use this module').'</div></div>';
}
$output .= '
<script src="'.$this->_path.'libraries/JS/tipTip.js"></script>
<link rel="stylesheet" type="text/css" href="'.$this->_path.'libraries/css/tipTip.css" />
<script>
$(function(){
$(".tips").tipTip({delay: 0, edgeOffset: 10, defaultPosition:"right"});
$(".tipstop").tipTip({delay: 0, edgeOffset: 10, defaultPosition:"top"});
});
</script>
<style>
label span{
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #edf7fb;
border-color: -moz-use-text-color -moz-use-text-color #d8edf7;
border-image: none;
border-radius: 3px;
border-style: none none solid;
border-width: medium medium 1px;
color: #3586ae;
font-size: 13px;
padding: 0 5px;
text-decoration: none;
cursor:help
}
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">';
if (Tools::isSubmit('savefile') && isset($_FILES['import'])) {
$errors = array();
$file = $_FILES['import'];
$ordernumber = $conf['GLSSTRACKING_ORDERNUM'] - 1;
$accountcol = $conf['GLSSTRACKING_ACCOUNTCOL'] - 1;
$accounts = explode('-', $conf['GLSSTRACKING_ACCOUNT']);
$shipping_number = $conf['GLSSTRACKING_ID'] - 1;
$row = 0;
$order_counter = 0;
$line = 0;
$formats = array('text/comma-separated-values', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel', 'text/anytext', 'text/tsv', 'text/tab-separated-values');
if (!in_array($file['type'], $formats)) {
$errors[] = $this->l('Your file must be in CSV format!');
} elseif (!$file['error'] && (int) $file['size'] && $file['tmp_name'] && ($handle = fopen($file['tmp_name'], 'r')) !== false) {
while (($data = fgetcsv($handle, 1000, $conf['GLSSTRACKING_SEPARATOR'])) !== false) { // Lecture du fichier
$line++;
if (($conf['GLSSTRACKING_HEADLINE'] && $row > 0) || !$conf['GLSSTRACKING_HEADLINE']) {
if ((isset($accounts[0]) && $accounts[0] == 0 || in_array($data[$accountcol], $accounts))) { // On vérifie que la ligne comporte bien un numéro de compte valide
if (Tools::isEmpty($data[$ordernumber])) { // on test la présence d'un n° de commande
$errors[] = sprintf($this->l('No order id at line %s'), $line);
continue;
}
$history = new OrderHistory();
$history->id_order = (int) $data[$ordernumber];
$history->id_employee = (int) $this->cookie->id_employee;
$order = new Order((int) $data[$ordernumber]);
if (!$order->id_carrier) {
$errors[] = sprintf($this->l('No order id at line %1$s with order id %2$s'), $line, $data[$ordernumber]);
continue;
}
if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
$status = $order->getCurrentOrderState();
} else {
$status = $history->getLastOrderState((int) $data[$ordernumber]);
}
if ($status->id != (int) $conf['GLSSTRACKING_STATES']) { // On vérifie que le dernier statut de la commande n'est pas déjà au stade définie dans la configuration
if (Validate::isLoadedObject($order)) {
if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
if (!$id_order_carrier = $this->getIdOrderCarrier((int) $data[$ordernumber])) {
$errors[] = sprintf($this->l('There is no carrier associate to order id %2$s at line %1$s '), $line, $data[$ordernumber]);
continue;
}
$order_carrier = new OrderCarrier($id_order_carrier);
$order_carrier->tracking_number = pSQL($data[$shipping_number]);
if (!$order_carrier->update()) {
$data[$shipping_number] = '';
}
} else {
$order->shipping_number = $data[$shipping_number];
if (!$order->update()) {
$data[$shipping_number] = '';
}
}
$carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang);
if (!Validate::isLoadedObject($carrier)) {
$errors[] = sprintf($this->l('Error with Carrier Object for id order %s'), $order->id);
} elseif (!$this->checkCarrierUrl($carrier)) { // On contrôle que le transporteur de la commande a une url de suivi valide
$errors[] = sprintf($this->l('The url for tracking parcels of the carrier of the %s command seems not valid.'), $order->id);
} elseif ($data[$shipping_number] && $data[$shipping_number] != '') {
$customer = new Customer((int) $order->id_customer);
if (!Validate::isLoadedObject($customer)) {
$errors[] = sprintf($this->l('Error with Customer Object for id order %1$s and Customer id %2$s'), $order->id, $order->id_customer);
}
$template_vars = array(
'{followup}' => str_replace('@', $data[$shipping_number], $carrier->url),
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{id_order}' => (int) $order->id
);
if (method_exists('Mail', 'l')) { // 1.4.x.x
if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
$template_vars['{shipping_number}'] = $order->shipping_number;
$template_vars['{order_name}'] = $order->getUniqReference();
Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $template_vars, $customer->email, $customer->firstname.' '.$customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
} else {
Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $template_vars, $customer->email, $customer->firstname.' '.$customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true);
}
} else { // 1.3 and <
global $langmail; // old version compatibility
$subject = 'Package in transit';
Mail::Send((int) $order->id_lang, 'in_transit', ((is_array($langmail) && key_exists($subject, $langmail)) ? $langmail[$subject] : $subject), $template_vars, $customer->email, $customer->firstname.' '.$customer->lastname);
}
} else {
$errors[] = sprintf($this->l('Error with Tracking Number (%1$s) for id order %2$s'), $data[$shipping_number], $order->id);
}
}
$history->changeIdOrderState((int) $conf['GLSSTRACKING_STATES'], (int) $data[$ordernumber]);
$history->addWithemail();
$order_counter++;
} else {
$errors[] = sprintf($this->l('Order "%s" has already set in your configuration status'), $order->id);
}
}
}
$row++;
}
}
if (!count($errors)) {
$output .= $this->displayConfirmation(sprintf($this->l('%1$s lines of the file processed for %2$s orders updated'), $line, $order_counter));
} else {
$output .= $this->displayError(implode('<br />', $errors).($line && $order_counter ? '<br />'.sprintf($this->l('%1$s lines of the file processed for %2$s orders updated'), $line, $order_counter) : ''));
}
} elseif (Tools::isSubmit('saveconf')) {
Configuration::updateValue('GLSSTRACKING_STATES', (int) Tools::getValue('GLSSTRACKING_STATES'));
Configuration::updateValue('GLSSTRACKING_SEPARATOR', Tools::getValue('GLSSTRACKING_SEPARATOR'));
Configuration::updateValue('GLSSTRACKING_ORDERNUM', (int) Tools::getValue('GLSSTRACKING_ORDERNUM'));
Configuration::updateValue('GLSSTRACKING_ID', (int) Tools::getValue('GLSSTRACKING_ID'));
Configuration::updateValue('GLSSTRACKING_HEADLINE', (int) Tools::getValue('GLSSTRACKING_HEADLINE'));
Configuration::updateValue('GLSSTRACKING_ACCOUNTCOL', (int) Tools::getValue('GLSSTRACKING_ACCOUNTCOL'));
Configuration::updateValue('GLSSTRACKING_ACCOUNT', Tools::getValue('GLSSTRACKING_ACCOUNT'));
Tools::redirectAdmin($this->form.'&conf=6');
} elseif (Tools::isSubmit('savecron')) {
Configuration::updateValue('GLSSTATUS_BEFORE', (int) Tools::getValue('GLSSTATUS_BEFORE'));
Configuration::updateValue('GLSSTATUS_RELAY', (int) Tools::getValue('GLSSTATUS_RELAY'));
Configuration::updateValue('GLSSTATUS_AFTER', (int) Tools::getValue('GLSSTATUS_AFTER'));
Configuration::updateValue('GLSSTRACKING_TL', (int) Tools::getValue('GLSSTRACKING_TL'));
Configuration::updateValue('GLSSTRACKING_NBORDERS', (int) Tools::getValue('GLSSTRACKING_NBORDERS'));
Configuration::updateValue('GLSSTRACKING_CRONHOURS', (int) Tools::getValue('GLSSTRACKING_CRONHOURS'));
Tools::redirectAdmin($this->form.'&conf=6');
}
$this->conf = Configuration::getMultiple(array('GLSSTRACKING_ACCOUNT', 'GLSSTRACKING_ORDERNUM', 'GLSSTRACKING_ACCOUNTCOL', 'GLSSTRACKING_ACCOUNT', 'GLSSTRACKING_ID', 'GLSSTRACKING_SEPARATOR', 'GLSSTRACKING_HEADLINE', 'GLSSTRACKING_STATES', 'GLSSTRACKING_CRONUPDATE', 'GLSSTRACKING_ACCOUNTCOL', 'GLSSTATUS_BEFORE', 'GLSSTATUS_RELAY', 'GLSSTATUS_AFTER', 'GLSSTRACKING_NBORDERS', 'GLSSTRACKING_TL', 'PS_SSL_ENABLED', 'GLSSTRACKING_SECURE_KEY', 'GLSSTRACKING_CRONHOURS'));
if (version_compare(_PS_VERSION_, '1.6.0.0', '>=')) {
return $output . $this->displayForm16($subtab);
} else {
return $output . $this->displayForm($subtab);
}
}
public function getIdOrderCarrier($idorder)
{
return Db::getInstance()->getValue('
SELECT `id_order_carrier`
FROM `'._DB_PREFIX_.'order_carrier`
WHERE `id_order` = '.(int) $idorder);
}
/**
* displayForm function.
*
* @access public
* @return void
*/
public function displayForm($subtab = '')
{
$output = '
<h2><img src="'.$this->_path.'logo.png" /> '.$this->displayName.'</h2>
<script src="'.$this->_path.'libraries/JS/tabpane.js"></script>
<link rel="stylesheet" type="text/css" href="'.$this->_path.'libraries/css/tabpane.css" />
<div class="tab-pane" id="tab-pane-100">
<div class="tab-page" id="tab-page-1">
<span class="tab"><i class="fa fa-download"></i> '.$this->l('Import').'</span>
'.$this->displaySettings1().'
</div>
';
if ($subtab != 'order') {
$output .= '
<div class="tab-page" id="tab-page-2">
<span class="tab"><i class="fa fa-cogs"></i> '.$this->l('Configuration').'</span>
'.$this->displaySettings2().'
</div>
<div class="tab-page" id="tab-page-3">
<span class="tab"><i class="fa fa-barcode"></i> '.$this->l('Configuration').'</span>
'.$this->displaySettings3().'
</div>
';
}
$output .= '
<div class="tab-page" id="tab-page-4">
<span class="tab"><i class="fa fa-info-circle"></i> '.$this->l('About').'</span>
'.$this->aboutUsTab().'
</div>
<div class="tab-page" id="tab-page-5">
<span class="tab"><i class="fa fa-key"></i> '.$this->l('License').'</span>
'.$this->licenceTab().'
</div>
</div>
<script type="text/javascript">
'.(isset($this->tabpage) && $this->tabpage ? $this->tabPaneSelected('tab-pane-100', $this->tabpage) : '').'
setupAllTabs();
</script>
';
return $output;
}
/**
* displayForm16 function.
*
* @access public
* @return void
*/
public function displayForm16($subtab = '')
{
if ($subtab != 'order') {
$display_conf_tab = true;
} else {
$display_conf_tab = false;
}
$output = '
<style type="text/css">
.tab-pane h3{color:#09F}
.tab-pane ol li p{display: inline;font-size: inherit}
.tab-pane > ol > li{border-top:1px solid #bababa;margin:0;padding:5px}
.tab-pane > ol > li:first-child{border-top:none}
.tab-pane ol {counter-reset: item;list-style: none outside none;padding-left: 20px}
.tab-pane ol li:before {font-size:1.em;content: counters(item, ".", decimal) ". ";counter-increment: item}
.tab-pane ul.license{padding-left: 25px;list-style: square inside}
</style>
<!-- Nav tabs -->
<ul class="nav nav-tabs" style="margin-left:1em">
<li class="active"><a href="#tab-page-1" data-toggle="tab"><i class="fa fa-download"></i><span class="hidden-xs"> '.$this->l('Import').'</span></a></li>
';
if ($display_conf_tab) {
$output .= '
<li><a href="#tab-page-2" data-toggle="tab"><i class="icon-cogs"></i><span class="hidden-xs"> '.$this->l('Configuration').'</span></a></li>
<li><a href="#tab-page-3" data-toggle="tab"><i class="fa fa-barcode"></i><span class="hidden-xs"> '.$this->l('Package delivery tracking').'</span></a></li>
';
}
$output .= '
<li><a href="#tab-page-4" data-toggle="tab"><i class="icon-info-circle"></i><span class="hidden-xs"> '.$this->l('About').'</span></a></li>
<li><a href="#tab-page-5" data-toggle="tab"><i class="icon-legal"></i><span class="hidden-xs"> '.$this->l('License').'</span></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane panel active" id="tab-page-1">
'.$this->displaySettings1().'
</div>
';
if ($display_conf_tab) {
$output .= '
<div class="tab-pane panel" id="tab-page-2">
'.$this->displaySettings2().'
</div>
';
}
$output .= '
<div class="tab-pane panel" id="tab-page-3">
'.$this->displaySettings3().'
</div>
<div class="tab-pane panel" id="tab-page-4">
'.$this->aboutUsTab().'
</div>
<div class="tab-pane panel" id="tab-page-5">
'.$this->licenceTab().'
</div>
</div>
<script type="text/javascript">
$("#tab-page-1 a").click(function (e) {$(this).tab("show")});
$("#tab-page-2 a").click(function (e) {$(this).tab("show")});
$("#tab-page-3 a").click(function (e) {$(this).tab("show")});
$("#tab-page-4 a").click(function (e) {$(this).tab("show")});
$("#tab-page-5 a").click(function (e) {$(this).tab("show")});
</script>';
return $output;
}
/**
* displaySettings1 function.
*
* @access public
* @return void
*/
public function displaySettings1()
{
$output = $this->panelHeading($this->l('Tracking codes importation'), 'fa-download');
$output .= '
<form action="'.$this->form.'" method="post" class="defaultForm form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-3">'.$this->l('File').'</label>
<div class="margin-form col-md-8">
<input type="file" name="import" />
</div>
</div>
';
$output .= $this->submitButton($this->l('Import'), 'savefile');
$output .= '
</form>
';
$output .= $this->panelEnding();
$output .= $this->panelHeading($this->l('Example of french header file to import'), 'fa-file-o');
$output .= $this->displayInfoMessage('No;Date;Colis;Produit;Référence 1;Ref Destinataire;Nom;Contact;Adresse 1;Adresse 2;Adresse 3;ZipCode;VILLE;Code Pays;Référence 2;Compte GLS;Chargeur secondaire;TRACKID;GLSNO;Poids;Quantième;Total Colis;Utilisateur;EMAIL;URL');
$output .= $this->panelEnding();
return $output;
}
/**
* displaySettings2 function.
*
* @access public
* @return void
*/
public function displaySettings2()
{
$elements = array();
foreach (OrderState::getOrderStates((int) $this->cookie->id_lang) as $state) {
$elements[$state['id_order_state']] = $state['name'];
}
$output = '
<form action="'.$this->form.'" method="post" class="defaultForm form-horizontal" enctype="multipart/form-data">
';
$output .= $this->panelHeading($this->l('Manage import file'));
$output .= '
<div class="form-group">
<label class="control-label col-md-3">'.$this->l('Orders State').' '.$this->displayHelpMessage($this->l('Status of order after importing the file')).'</label>
<div class="margin-form col-md-8">
'.$this->selectElement('GLSSTRACKING_STATES', $this->conf, $elements).'
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">'.$this->l('Header line').' '.$this->displayHelpMessage($this->l('If the first line of your file consists of information about the file structure and not data to process, so please select Yes')).'</label>
<div class="margin-form col-md-8">
'.$this->radioButton('GLSSTRACKING_HEADLINE', $this->l('Yes'), $this->l('No')).'
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">'.$this->l('Separator').' '.$this->displayHelpMessage($this->l('It is best to use a file in CSV format using the ";" as separator')).'</label>
<div class="margin-form col-md-8">
'.$this->selectElement('GLSSTRACKING_SEPARATOR', $this->conf, array(',' => ',', ';' => ';', '\t' => $this->l('Tabulation'))).'
</div>
</div>
'.$this->displayInputGroup($this->l('Order column'), 'GLSSTRACKING_ORDERNUM', Tools::getValue('GLSSTRACKING_ORDERNUM', $this->conf['GLSSTRACKING_ORDERNUM']), $this->l('Column number corresponding to order number'), 'col-md-2', '5', $this->l('column number')).'
'.$this->displayInputGroup($this->l('Tracking ID column'), 'GLSSTRACKING_ID', Tools::getValue('GLSSTRACKING_ID', $this->conf['GLSSTRACKING_ID']), $this->l('Column number corresponding to the GLS Tracking ID of the order'), 'col-md-2', '5', $this->l('column number')).'
'.$this->displayInputGroup($this->l('Account column'), 'GLSSTRACKING_ACCOUNTCOL', Tools::getValue('GLSSTRACKING_ACCOUNTCOL', $this->conf['GLSSTRACKING_ACCOUNTCOL']), $this->l('Column number corresponding to the GLS account of the order'), 'col-md-2', '5', $this->l('column number')).'
';
$output .= $this->submitButton($this->l('Save'), 'saveconf');
$output .= $this->panelEnding();
$output .= $this->panelHeading($this->l('GLS Accounts'));
$output .= $this->displayInputGroup($this->l('Account number'), 'GLSSTRACKING_ACCOUNT', Tools::getValue('GLSSTRACKING_ACCOUNT', $this->conf['GLSSTRACKING_ACCOUNT']), $this->l('Account number to be considered in the import file. If you have multiple account numbers to consider when importing please list like this: 7258-2356-8459, separated by dashes').'<br /><strong>'.$this->l('If you want to import all orders lines without checking GLS account numbers, simply enter 0 to disable this control').'</strong>', 'col-md-5', '50');
$output .= $this->submitButton($this->l('Save'), 'saveconf');
$output .= $this->panelEnding();
$output .= '
</form>
';
return $output;
}
/**
* displaySettings3 function.
*
* @access public
* @return void
*/
public function displaySettings3()
{
$elements = array();
foreach (OrderState::getOrderStates((int) $this->cookie->id_lang) as $state) {
$elements[$state['id_order_state']] = $state['name'];
}
$url_cron = ($this->conf['PS_SSL_ENABLED'] ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].__PS_BASE_URI__.'modules/'.$this->name.'/cron.php?secure_key='.$this->conf['GLSSTRACKING_SECURE_KEY'];
$output = '
<form action="'.$this->form.'" method="post" class="defaultForm form-horizontal" enctype="multipart/form-data">
';
$output .= $this->panelHeading($this->l('Configure automatic processing'));
$output .= '
<div class="form-group">
<label class="control-label col-md-3">'.$this->l('Orders State before').' '.$this->displayHelpMessage($this->l('Order status prior to processing the cron job')).'</label>
<div class="margin-form col-md-8">
'.$this->selectElement('GLSSTATUS_BEFORE', $this->conf, $elements).'
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">'.$this->l('Package pending in point relay').' '.$this->displayHelpMessage($this->l('Order status when a package is waiting in a relay point')).'</label>
<div class="margin-form col-md-8">
'.$this->selectElement('GLSSTATUS_RELAY', $this->conf, $elements).'
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">'.$this->l('Orders State after').' '.$this->displayHelpMessage($this->l('Order status after treatment of the cron job if the package is delivered')).'</label>
<div class="margin-form col-md-8">
'.$this->selectElement('GLSSTATUS_AFTER', $this->conf, $elements).'
</div>
</div>
'.$this->displayInputGroup($this->l('Number of orders'), 'GLSSTRACKING_NBORDERS', Tools::getValue('GLSSTRACKING_NBORDERS', $this->conf['GLSSTRACKING_NBORDERS']), $this->l('Number of orders processed by cron job. This limitation exists to prevent the GLS servers to block your own server due to too many calls from the same page.'), 'col-md-2', '5').'
'.$this->displayInputGroup($this->l('Time limit'), 'GLSSTRACKING_TL', Tools::getValue('GLSSTRACKING_TL', $this->conf['GLSSTRACKING_TL']), $this->l('Older than this time orders with "Orders State before" will be automatically passed to "Orders State after".'), 'col-md-2', '5', false, $this->l('month')).'
';
$output .= $this->submitButton($this->l('Save'), 'savecron');
$output .= $this->panelEnding();
$output .= '
</form>
';
$output .= $this->panelHeading($this->l('Cron'));
$output .= '
<form action="'.$url_cron.'" method="post" target="_blank" class="defaultForm form-horizontal" enctype="multipart/form-data">
';
if ($this->conf['GLSSTRACKING_CRONUPDATE']) {
list($lastupdatedate, $lastupdatenborders, $onxorders) = explode('-', $this->conf['GLSSTRACKING_CRONUPDATE']);
$output .= $this->displayInfoMessage($this->l('Last execution:').' '.Tools::displayDate(date('Y-m-d H:i:s', $lastupdatedate), $this->cookie->id_lang, true).' '.$this->l('with').' '.$lastupdatenborders.' '.$this->l('orders update on').' '.$onxorders.' '.$this->l('analysis'));
}
$output .= $this->submitButton($this->l('Manual Cron'), 'cron');
$output .= '
</form>
';
$output .= $this->panelEnding();
$output .= $this->panelHeading($this->l('How to set your CronJob'));
$message = '
<p style="clear: both">'.$this->l('You can set up a cron job to automatically update the status of your order status to Delivered').'.</p>
<p style="clear: both">'.$this->l('You must choose the articles to analyze and control the module will do the rest by analyzing the GLS site').'.</p>
<p style="clear: both">'.$this->l('Attention, it may appear that the GLS site is not fully up to date, up to you to regularly monitor the proper conduct of this task.').'.</p>
<p style="clear: both">'.$this->l('If you wish, you can run the cron job manually by clicking the link below').'<br />
<a href="'.$url_cron.'" target="_blank" style="color:#268CCD">'.$url_cron.'</a></p>
<p style="clear: both">'.$this->l('You can also set up a call from the url above with a Webcron as:').'</p>
<ul style="list-style: disc inside none;margin-left:15px">
<li><a href="http://cron.hiwit.org/" target="_blank">cron.hiwit.org</a> (fr)</li>
<li><a href="http://bit.ly/easycron" target="_blank">easycron.com</a> (en)</li>
</ul>
<p style="clear: both;">'.$this->l('Otherwise, you can also create a cron job on your server by calling the file').'<br /> '.dirname(__FILE__).'/cron.php '.$this->l('every').' 3 '.$this->l('hours').'</p>
<p>'.$this->l('For example : ').'<br />* 8-23/3 * * 1-6 php -d '.dirname(__FILE__).'/cron.php?secure_key='.$this->conf['GLSSTRACKING_SECURE_KEY'].'<br />Or<br />* 8-23/'.$this->conf['GLSSTRACKING_CRONHOURS'].' * * 1-6 GET '.$url_cron.'</p>
';
$output .= $this->displayInfoMessage($message);
$output .= $this->panelEnding();
return $output;
}
public function getOrderIdsByStatus($id_order_state)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT id_order
FROM '._DB_PREFIX_.'orders o
WHERE '.(int) $id_order_state.' = (
SELECT id_order_state
FROM '._DB_PREFIX_.'order_history oh
WHERE oh.id_order = o .id_order
ORDER BY date_add DESC, id_order_history DESC
LIMIT 1
)
ORDER BY invoice_date ASC');
$orders = array();
foreach ($result as $order) {
$orders[] = (int) $order['id_order'];
}
return $orders;
}
public function getOrderIdsByStatus15($id_order_state)
{
$sql = 'SELECT o.id_order
FROM '._DB_PREFIX_.'orders o
LEFT JOIN '._DB_PREFIX_.'order_carrier oc ON o.id_order = oc.id_order
INNER JOIN '._DB_PREFIX_.'carrier c ON o.id_carrier = c.id_carrier
WHERE o.`current_state` = '.(int) $id_order_state.'
AND c.url LIKE "%gls%"
AND (o.shipping_number != "" OR oc.tracking_number != "")
AND DATE(o.date_upd) < NOW()
'.Shop::addSqlRestriction(false, 'o').'
ORDER BY date_upd ASC';
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
$orders = array();
foreach ($result as $order) {
$orders[] = (int) $order['id_order'];
}
return $orders;
}
public function checkCarrierUrl($carrier)
{
if ($carrier->url) {
if (stripos($carrier->url, 'gls') !== false && stripos($carrier->url, '@') !== false) {
return true;
}
}
return false;
}
public function cron()
{
$start = time();
$lastupdate = time();
if (Validate::isLoadedObject($this) && $this->active) {
$orders = array();
$orders_before = array();
$orders_relay = array();
$conf = Configuration::getMultiple(array('GLSSTRACKING_NBORDERS', 'GLSSTATUS_BEFORE', 'GLSSTATUS_RELAY', 'GLSSTATUS_AFTER', 'GLSSTRACKING_TL'));
if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
$orders_before = $this->getOrderIdsByStatus15((int) $conf['GLSSTATUS_BEFORE']);
} elseif (version_compare(_PS_VERSION_, '1.4.0.0', '>=')) {
$orders_before = Order::getOrderIdsByStatus((int) $conf['GLSSTATUS_BEFORE']);
} else {
$orders_before = $this->getOrderIdsByStatus((int) $conf['GLSSTATUS_BEFORE']);
}
if ((int) $conf['GLSSTATUS_BEFORE'] != (int) $conf['GLSSTATUS_RELAY']) {
if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
$orders_relay = $this->getOrderIdsByStatus15((int) $conf['GLSSTATUS_RELAY']);
} elseif (version_compare(_PS_VERSION_, '1.4.0.0', '>=')) {
$orders_relay = Order::getOrderIdsByStatus((int) $conf['GLSSTATUS_RELAY']);
} else {
$orders_relay = $this->getOrderIdsByStatus((int) $conf['GLSSTATUS_RELAY']);
}
}
$orders = array_merge($orders_before, $orders_relay);
$number_of_orders = 0;
$i = 0;
$j = 0;
$time_limit = strtotime('-'.(int) $conf['GLSSTRACKING_TL'].' month');
$limite = (int) $conf['GLSSTRACKING_NBORDERS']; // On limite le nombre de commandes traitées à chaque cron pour éviter de se faire rejeter par le site de GLS
foreach ($orders as $o) {
$up = 0;
$order = new Order($o);
$carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang);
if (stripos($carrier->url, 'gls') !== false) { // on test que l'url de tracking est bien celle de GLS afin de ne pas tester les autres transporteurs
if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
$order_carrier = new OrderCarrier($this->getIdOrderCarrier($o));
$shipping_number = $order_carrier->tracking_number;
}
if (!isset($shipping_number) && !$shipping_number) {
$shipping_number = $order->shipping_number;
}
if ($shipping_number) {
$j++;
$file = 'https://gls-group.eu/app/service/open/rest/FR/fr/rstt001?match=' . $shipping_number . '&caller=witt002&milis=1463564337227';
$url_suivi = 'https://gls-group.eu/FR/fr/suivi-colis?match=' . $shipping_number;
if (($time_limit > strtotime($order->date_upd) || $delivery_states = $this->packageDelivery($file)) && (($delivery_states == 3.124 && $this->getMedLastOrderState($order) != (int) $conf['GLSSTATUS_RELAY']) || $delivery_states == 3.0)) {
$i++;
$history = new OrderHistory();
$history->id_order = $o;
if ($delivery_states == 3.124) {
$history->changeIdOrderState((int) $conf['GLSSTATUS_RELAY'], $o);
} else {
$history->changeIdOrderState((int) $conf['GLSSTATUS_AFTER'], $o);
}
$history->addWithemail();
$number_of_orders++;
$up = 1;
}
echo '<p style="clear: both'.(($up == 1)?';color:#900;font-weight:bold':'').'">'.$j.' - '.$this->l('Order n°').' '.$o.' '.($delivery_states == 3.124 ? $this->l('Pending relay packages since'): $this->l('shipped since')).' '.Tools::displayDate($order->date_upd).' '.$this->l('with tracking ID').' <a href="'.$url_suivi.'" target="_blank">'.$shipping_number.'</a> '.(($up == 1)?$this->l('updated'):$this->l('not updated')).'</p>';
} else {
echo '<p style="clear: both">'.$this->l('Order n°').' '.$o.' '.$this->l('with no tracking ID').' '.$this->l('not updated').'</p>';
}
}
unset($order, $carrier);
$lastupdate = time();
Configuration::updateValue('GLSSTRACKING_CRONUPDATE', $lastupdate.'-'.$number_of_orders.'-'.$j);
if ($i == $limite || $j == 2 * $limite) {
break;
}
}
$during = $lastupdate - $start;
echo '<p style="clear: both">' . $number_of_orders . ' ' . $this->l('updated orders') . ' ' . $this->l('in') . ' ' . $during . 's</p>';
}
}
/**
* packageDelivery function.
*
* @access public
* @param mixed $url
* @return void
*/
public function packageDelivery($url)
{
$opts = array(
'http'=>array(
'ignore_errors' => true
)
);
$cont = stream_context_create($opts);
$extractor = (version_compare(_PS_VERSION_, '1.4.0.0', '<') ? json_decode(file_get_contents($url, false, $cont)) : json_decode(Tools::file_get_contents($url)));
$toto = reset($extractor);
if (isset($toto[0]->progressBar->evtNos[0]) && $toto[0]->progressBar->evtNos[0]) {
switch ($toto[0]->progressBar->evtNos[0]) {
case 3.0:
return 3.0;
case 3.120:
return 3.0;
case 3.121:
return 3.0;
case 3.124:
return 3.124;
}
}
return false;
}
/**
* getMedLastOrderState function.
*
* @access public
* @param mixed $order
* @return void
*/
public function getMedLastOrderState($order)
{
if (version_compare(_PS_VERSION_, '1.5.0.4', '<')) {
return OrderHistory::getLastOrderState((int) $order->id);
} else {
return $order->current_state;
}
}
}