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

2229 lines
102 KiB
PHP

<?php
/**
* Module made by Nukium
*
* @author Nukium
* @copyright 2018 Nukium SAS
* @license All rights reserved
*
* ███ ██ ██ ██ ██ ██ ██ ██ ██ ███ ███
* ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ████
* ██ ██ ██ ██ ██ █████ ██ ██ ██ ██ ████ ██
* ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
* ██ ████ ██████ ██ ██ ██ ██████ ██ ██
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
use PrestaShop\PrestaShop\Core\Module\WidgetInterface;
if (!class_exists('GlsLogClass')) {
require_once dirname(__FILE__).'/classes/GlsLogClass.php';
}
if (!class_exists('GlsController')) {
require_once dirname(__FILE__).'/classes/GlsController.php';
}
if (!class_exists('NkmCsv')) {
require_once(dirname(__FILE__).'/lib/NkmCsv.php');
}
if (!class_exists('AdminGlsOrderController')) {
require_once dirname(__FILE__).'/controllers/admin/AdminGlsOrderController.php';
}
if (!class_exists('AdminGlsAjaxController')) {
require_once dirname(__FILE__).'/controllers/admin/AdminGlsAjaxController.php';
}
if (!class_exists('AdminGlsLabelController')) {
require_once dirname(__FILE__).'/controllers/admin/AdminGlsLabelController.php';
}
class NkmGls extends CarrierModule implements WidgetInterface
{
/**
* Lang available for the documentation
* @var array
*/
public static $lang_doc = array('fr', 'en');
public static $carrier_definition = array(
'GLSCHEZVOUS' => array(
'name' => 'GLS Chez vous',
'delay' => array('fr' => 'Colis livré en 24h à 48h.'),
'grade' => 9,
),
'GLSRELAIS' => array(
'name' => 'GLS Point Relais®',
'delay' => array('fr' => 'Retrait en Point Relais® de votre choix. Vous êtes informé par E-mail ou SMS de l\'arrivé de votre colis.'),
'grade' => 9,
),
'GLSCHEZVOUSPLUS' => array(
'name' => 'GLS Chez vous +',
'delay' => array('fr' => 'Vous êtes prévenus par mail et SMS de la date et du créneau horaire de livraison.'),
'grade' => 9,
),
'GLS13H' => array(
'name' => 'GLS avant 13h',
'delay' => array('fr' => 'Livraison Express en 24H en France métropolitaine, remise en mains propres le lendemain avant 13H.'),
'grade' => 9,
),
);
public static $trackingUrl = 'https://gls-group.eu/FR/fr/suivi-colis?match=@';
private static $ftp_host = 'ftp.gls-france.com';
private static $ftp_login = 'addonline';
private static $ftp_pwd = '-mAfXmTqC';
public $importDirectory = '';
/**
* Liste des templates de hooks
* @var unknown
*/
private $templates = array (
'displayCarrierExtraContent' => 'carrier_extra_content.tpl',
'displayOrderDetail' => 'order_detail.tpl',
'displayAfterCarrier' => 'error.tpl',
'displayInfoByCart' => 'info_by_cart.tpl',
'displayWorkingsDay' => 'working_day.tpl'
);
/**
* Utile pour ne pas afficher certains transporteurs
* @var int
*/
public $id_carrier = null;
private static $old_shop_context = array();
public function __construct()
{
$this->name = 'nkmgls';
$this->tab = 'shipping_logistics';
$this->version = '1.2.1';
$this->author = 'Nukium';
$this->module_key = 'd792bc0479dc21963d46aae4c3fa0dbd';
$this->need_instance = 0;
$this->bootstrap = true;
if (version_compare(_PS_VERSION_, '1.7.', '<')) {
$this->ps_versions_compliancy = array(
'min' => '1.6',
'max' => _PS_VERSION_
);
} else {
$this->ps_versions_compliancy = array(
'min' => '1.7.0.0',
'max' => _PS_VERSION_
);
}
$this->displayName = $this->l('GLS, your shipping partner');
$this->description = $this->l('Give your customers the choice of the shipping method that suits them.');
parent::__construct();
$this->initialize();
}
private function initialize()
{
$secure_key = Configuration::get('GLS_SECURE_KEY');
if ($secure_key === false) {
Configuration::updateValue('GLS_SECURE_KEY', Tools::strtoupper(Tools::passwdGen(16)));
}
$this->importDirectory = _PS_MODULE_DIR_.$this->name.DIRECTORY_SEPARATOR.'import'.DIRECTORY_SEPARATOR;
}
public function install()
{
self::$old_shop_context['type'] = Shop::getContext();
if (Shop::getContext() == Shop::CONTEXT_GROUP) {
self::$old_shop_context['id'] = Shop::getContextShopGroupID(true);
} else {
self::$old_shop_context['id'] = Shop::getContextShopID(true);
}
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
Configuration::updateValue('GLS_GLSRELAIS_XL_ONLY', '');
Configuration::updateValue('GLS_WSLOGIN', '');
Configuration::updateValue('GLS_WSPWD', '');
Configuration::updateValue('GLS_AGENCY_CODE', '');
Configuration::updateValue('GLS_GOOGLE_MAPS_API_KEY', '');
Configuration::updateValue('GLS_GOOGLE_MAPS_API_SCRIPT_ENABLE', '1');
Configuration::updateValue('GLS_ORDER_PREFIX_ENABLE', '1');
Configuration::updateValue('GLS_LAST_SYNCHRO_DATE', date('Y-m-d H:i:s'));
Configuration::updateValue('GLS_SYNCHRO_FILE_CONTENT_HASH', '');
Configuration::updateValue('GLS_EXPORT_AUTOMATION', '');
Configuration::updateValue('GLS_EXPORT_NEW_ORDER_STATE', '');
Configuration::updateValue('GLS_EXPORT_ORDER_STATE', '');
Configuration::updateValue('GLS_IMPORT_AUTOMATION', '');
Configuration::updateValue('GLS_IMPORT_NEW_ORDER_STATE', '');
Configuration::updateValue('GLS_API_CUSTOMER_ID', '');
Configuration::updateValue('GLS_API_CONTACT_ID', '');
Configuration::updateValue('GLS_API_DELIVERY_LABEL_FORMAT', 'A6');
Configuration::updateValue('GLS_API_SHOP_RETURN_SERVICE', '0');
Configuration::updateValue('GLS_API_SHOP_RETURN_EMAIL_ALERT', '0');
Configuration::updateValue('GLS_API_LOGIN', '');
Configuration::updateValue('GLS_API_PWD', '');
Configuration::updateValue('GLS_API_SHOP_RETURN_ADDRESS', '1');
foreach (array_keys(self::$carrier_definition) as $key) {
Configuration::updateValue('GLS_'.$key.'_ID', '');
Configuration::updateValue('GLS_'.$key.'_LOG', '');
}
$installDB = $this->installDBConfig();
// On a reinit le context initial pour la création des transporteurs
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
return parent::install()
&& $installDB
&& AdminGlsOrderController::installInBO()
&& AdminGlsLabelController::installInBO()
&& AdminGlsAjaxController::installInBO()
&& $this->registerHook('displayBackOfficeHeader')
&& $this->registerHook('actionAdminControllerSetMedia')
&& $this->registerHook('actionFrontControllerSetMedia')
&& $this->registerHook('displayHeader')
&& $this->registerHook('displayCarrierExtraContent')
&& $this->registerHook('actionCarrierUpdate')
&& $this->registerHook('actionObjectCarrierUpdateAfter')
&& $this->registerHook('displayOrderDetail')
&& $this->registerHook('displayAfterCarrier')
&& $this->registerHook('actionValidateStepComplete')
&& $this->registerHook('actionValidateOrder')
&& $this->registerHook('actionCarrierProcess')
&& $this->registerHook('registerGDPRConsent')
&& $this->registerHook('actionDeleteGDPRCustomer')
&& $this->registerHook('actionObjectCustomerDeleteAfter')
&& $this->registerHook('actionExportGDPRData');
}
public function uninstall()
{
Configuration::deleteByName('GLS_GLSRELAIS_XL_ONLY');
Configuration::deleteByName('GLS_WSLOGIN');
Configuration::deleteByName('GLS_WSPWD');
Configuration::deleteByName('GLS_AGENCY_CODE');
Configuration::deleteByName('GLS_GOOGLE_MAPS_API_KEY');
Configuration::deleteByName('GLS_GOOGLE_MAPS_API_SCRIPT_ENABLE');
Configuration::deleteByName('GLS_ORDER_PREFIX_ENABLE');
Configuration::deleteByName('GLS_LAST_SYNCHRO_DATE');
Configuration::deleteByName('GLS_SYNCHRO_FILE_CONTENT_HASH');
Configuration::deleteByName('GLS_SECURE_KEY');
Configuration::deleteByName('GLS_EXPORT_AUTOMATION');
Configuration::deleteByName('GLS_EXPORT_NEW_ORDER_STATE');
Configuration::deleteByName('GLS_EXPORT_ORDER_STATE');
Configuration::deleteByName('GLS_IMPORT_AUTOMATION');
Configuration::deleteByName('GLS_IMPORT_NEW_ORDER_STATE');
Configuration::deleteByName('GLS_API_CUSTOMER_ID');
Configuration::deleteByName('GLS_API_CONTACT_ID');
Configuration::deleteByName('GLS_API_DELIVERY_LABEL_FORMAT');
Configuration::deleteByName('GLS_API_SHOP_RETURN_SERVICE');
Configuration::deleteByName('GLS_API_SHOP_RETURN_EMAIL_ALERT');
Configuration::deleteByName('GLS_API_LOGIN');
Configuration::deleteByName('GLS_API_PWD');
Configuration::deleteByName('GLS_API_SHOP_RETURN_ADDRESS');
Configuration::deleteByName('GLS_API_SHOP_RETURN_ADDRESS_NAME');
Configuration::deleteByName('GLS_API_SHOP_RETURN_ADDRESS_ADDRESS1');
Configuration::deleteByName('GLS_API_SHOP_RETURN_ADDRESS_ADDRESS2');
Configuration::deleteByName('GLS_API_SHOP_RETURN_ADDRESS_POSTCODE');
Configuration::deleteByName('GLS_API_SHOP_RETURN_ADDRESS_CITY');
Configuration::deleteByName('GLS_API_SHOP_RETURN_ADDRESS_COUNTRY');
foreach (array_keys(self::$carrier_definition) as $key) {
// Il faut conserver LOG pour l'historique des commandes
$gls_carrier_id = Configuration::get('GLS_'.$key.'_ID');
if (!empty($gls_carrier_id)) {
$history_log = explode('|', Configuration::get('GLS_'.$key.'_LOG'));
$history_log[] = $gls_carrier_id;
Configuration::updateValue('GLS_'.$key.'_LOG', implode('|', array_map('intval', $history_log)));
// désactivation du transporteur anciennement associé
if (Validate::isLoadedObject($object = new Carrier((int)$gls_carrier_id))) {
$object->active = false;
$object->update();
}
}
$gls_carrier_id = Configuration::deleteByName('GLS_'.$key.'_ID');
}
return parent::uninstall()
&& Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'gls_agency_postcode`')
&& GlsLogClass::removeDbTable()
&& AdminGlsOrderController::removeFromBO()
&& AdminGlsLabelController::removeFromBO()
&& AdminGlsAjaxController::removeFromBO();
}
private function installDBConfig()
{
//__ Création d'une table sauvegardant les points relais sélectionnés au moment de la commande
if (!Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'gls_cart_carrier` (
`id_cart` int(10) UNSIGNED NOT NULL DEFAULT \'0\',
`id_customer` int(10) unsigned NOT NULL DEFAULT \'0\',
`id_carrier` int(10) UNSIGNED NOT NULL DEFAULT \'0\',
`gls_product` varchar(255) NOT NULL,
`parcel_shop_id` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`address1` varchar(255) DEFAULT NULL,
`address2` varchar(255) DEFAULT NULL,
`postcode` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`phone_mobile` varchar(255) DEFAULT NULL,
`customer_phone_mobile` varchar(255) NOT NULL,
`id_country` int(10) unsigned DEFAULT NULL,
`parcel_shop_working_day` TEXT DEFAULT NULL,
PRIMARY KEY (`id_cart`,`id_customer`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;')) {
return false;
}
//__ Création d'une table contenant la restriction par codes postaux et code agence GLS pour le sevice de livraison avant 13H
if (Db::getInstance()->Execute('CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'gls_agency_postcode` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`agency_code` varchar(255) NOT NULL,
`postcode_start` varchar(5) NOT NULL,
`postcode_end` varchar(5) NOT NULL,
PRIMARY KEY (`id`),
KEY `agency_code` (`agency_code`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;')) {
// File parsing
$csv_file = new NkmCSVReader();
$csv_content = $csv_file->parse_file($this->importDirectory.'tbzipdeltimes.csv', false, true);
$this->synchronizeAgencyPostcodeRestriction(true, $csv_content);
} else {
return false;
}
//__ table des logs
if (!GlsLogClass::createDbTable()) {
return false;
}
//__ Création d'une zone France si innexistante
$sql = new DbQuery();
$sql->select('z.`id_zone`')
->from('zone', 'z')
->where('z.`name` LIKE \'%France%\'');
$id_zone_france = Db::getInstance()->getValue($sql);
if (!$id_zone_france) {
$zone = new Zone();
$zone->name = 'France';
$zone->active = true;
if (!$zone->add()) {
$this->_errors[] = $this->l('Impossible to create carrier zone France.');
return false;
}
$id_zone_france = $zone->id;
}
$id_country_france = Country::getByIso('FR');
if (!$id_country_france) {
$this->_errors[] = $this->l('Country FR not found.');
return false;
}
//__ Vérification que le pays est bien dans la zone sinon insertion
$old_id_zone_france = Country::getIdZone($id_country_france);
if ($id_zone_france != $old_id_zone_france) {
$country = new Country();
$country->affectZoneToSelection(array($id_country_france), $id_zone_france);
//__ Reconfiguration de cette zone sur les autres modes de livraison livrant en France
$sql = new DbQuery();
$sql->select('c.*')
->from('carrier', 'c')
->leftJoin('carrier_zone', 'cz', 'cz.`id_carrier` = c.`id_carrier`')
->leftJoin('zone', 'z', 'z.`id_zone` = '.(int)$old_id_zone_france)
->where('c.`active` = 1')
->where('cz.`id_zone` = '.(int) $old_id_zone_france)
->where('z.`active` = 1');
foreach (Db::getInstance()->executeS($sql) as $value) {
$sql = new DbQuery();
$sql->select('*')
->from('carrier_zone')
->where('`id_carrier` = '.(int) $value['id_carrier'])
->where('`id_zone` = '.(int) $id_zone_france);
if (!Db::getInstance()->getValue($sql)) {
Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'carrier_zone` (`id_carrier`, `id_zone`) VALUES ('.(int) $value['id_carrier'].', '.(int) $id_zone_france.')');
// Copy existing ranges price to new zone if non exist
Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'delivery` (`id_carrier`, `id_shop`, `id_shop_group`, `id_range_price`, `id_range_weight`, `id_zone`, `price`) (
SELECT '.(int) $value['id_carrier'].', `id_shop`, `id_shop_group`, `id_range_price`, `id_range_weight`, '.(int) $id_zone_france.', `price`
FROM `'._DB_PREFIX_.'delivery`
WHERE `id_carrier` = '.(int) $value['id_carrier'].'
AND `id_zone` = '.(int) $old_id_zone_france.'
)
');
}
}
}
//__ Création des transporteurs GLS
$create_carrier = true;
foreach (self::$carrier_definition as $key => $value) {
$create_carrier &= $this->createCarrier($key, $id_zone_france);
}
return $create_carrier;
}
/**
* Load the configuration form
*/
public function getContent()
{
$output = null;
/**
* If values have been submitted in the form, process.
*/
if ((bool)Tools::isSubmit('submit'.$this->name) === true) {
$output = $this->postProcess();
}
//__ Use for documentations links
if (in_array($this->context->language->iso_code, self::$lang_doc)) {
$this->context->smarty->assign('iso_lang', $this->context->language->iso_code);
} else {
$this->context->smarty->assign('iso_lang', 'en');
}
$this->context->smarty->assign(array(
'ps_version' => $this->getPrestaShopVersion(),
'order_link' => $this->context->link->getAdminLink('AdminGlsOrder'),
'label_link' => $this->context->link->getAdminLink('AdminGlsLabel'),
'carrier_link' => $this->context->link->getAdminLink('AdminCarriers'),
));
$header = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure_header.tpl');
$footer = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
return $output . $header . $this->renderForm() . $this->renderLog() . $footer;
}
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submit' . $this->name;
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.
$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->title = $this->l('Configure carriers');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
'ajax_uri' => $this->context->link->getAdminLink('AdminGlsAjax').'&ajax=1&action=createCarrier',
);
return $helper->generateForm($this->getConfigForm());
}
public function renderLog()
{
$helper = $this->initList();
if (Tools::getIsset('submitReset'.$helper->table)) {
$_POST = array();
$this->_filter = false;
unset($this->_filterHaving);
unset($this->_having);
}
$sql = new DbQuery();
$sql->select('l.*')
->from('gls_log', 'l');
// Process list filtering
if ((bool)Tools::isSubmit('submitFilter'.$helper->table) === true && Tools::getValue('action') != 'reset_filters') {
$date_add = Tools::getValue($helper->table.'Filter_date_add');
if ($date_add && is_array($date_add) && count($date_add) > 0) {
if (isset($date_add[0]) && !empty($date_add[0])) {
if (!Validate::isDate($date_add[0])) {
$this->errors[] = $this->trans('The \'From\' date format is invalid (YYYY-MM-DD)', array(), 'Admin.Notifications.Error');
} else {
$sql->where('date_add >= \''.pSQL(Tools::dateFrom($date_add[0])).'\'');
}
}
if (isset($date_add[1]) && !empty($date_add[1])) {
if (!Validate::isDate($date_add[1])) {
$this->errors[] = $this->trans('The \'To\' date format is invalid (YYYY-MM-DD)', array(), 'Admin.Notifications.Error');
} else {
$sql->where('date_add <= \''.pSQL(Tools::dateTo($date_add[1])).'\'');
}
}
}
$message = Tools::getValue($helper->table.'Filter_message');
if ($message) {
$sql->where('message LIKE \'%'.pSQL(trim($message)).'%\'');
}
}
$orderBy = Tools::getValue($helper->table.'Orderby', 'l.date_add');
$orderWay = Tools::getValue($helper->table.'Orderway', 'DESC');
if (Validate::isOrderBy($orderBy) && Validate::isOrderWay($orderWay)) {
$sql->orderBy($orderBy.' '.$orderWay);
}
$data = Db::getInstance()->ExecuteS($sql);
$helper->listTotal = count($data);
if ($helper->listTotal > 0) {
/* Paginate the result */
$page = ($page = Tools::getValue('submitFilter'.$helper->table)) ? $page : 1;
$pagination = ($pagination = Tools::getValue($helper->table.'_pagination')) ? $pagination : 50;
$data = $this->paginateLog($data, $page, $pagination);
$content = $helper->generateList($data, $this->fields_list);
} else {
$content = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/log.tpl');
}
return $content;
}
protected function getConfigForm()
{
$carriers = Carrier::getCarriers($this->context->language->id, false, false, false, null, null);
foreach ($carriers as $key => $value) {
$carriers[$key]['name'] .= ' ('.$this->l('ID:').' '.$value['id_carrier'].')';
}
$address = $this->context->shop->getAddress();
$this->context->smarty->assign(array('gls_logo' => __PS_BASE_URI__.'modules/'.$this->name.'/views/img/admin/'.'gls-logo.jpg'));
$fields_form = array();
$fields_form[0] = array(
'form' => array(
'legend' => array(
'title' => $this->l('Welcome to the GLS official module')
),
'input' => array(
array(
'type' => 'html',
'name' => $this->context->smarty->fetch($this->local_path . 'views/templates/admin/config_intro.tpl'),
'label' => '',
'col' => '12',
),
),
)
);
$input = array();
$i = 0;
$len = count(self::$carrier_definition);
foreach (self::$carrier_definition as $key => $value) {
$this->context->smarty->assign(array('carrier_key' => $key));
$input[] = array(
'type' => 'select',
'label' => $value['name'],
'name' => 'GLS_'.$key.'_ID',
'required' => true,
'options' => array(
'query' => $carriers,
'id' => 'id_carrier',
'name' => 'name',
'default' => array('value' => 0, 'label' => $this->l('None - Disable this service')),
),
'col' => '12',
'form_group_class' => 'col-lg-4',
'carrier_img' => __PS_BASE_URI__.'modules/'.$this->name.'/views/img/admin/'.Tools::strtolower($key).'.jpg',
);
$input[] = array(
'type' => 'html',
'name' => $this->context->smarty->fetch($this->local_path . 'views/templates/admin/config_btn_create_carrier.tpl'),
'label' => '&nbsp;',
'col' => '12',
'form_group_class' => 'col-lg-6 new-carrier',
);
/**
* Specific options
*/
if ($key == 'GLSRELAIS') {
$input[] = array(
'type' => 'switch',
'label' => $this->l('Display only XL Points Relais®'),
'name' => 'GLS_GLSRELAIS_XL_ONLY',
'required' => true,
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('No')
)
),
'hint' => $this->l('Points Relais® that can store packages greater than 20 kg, if the length exceeds 120cm or dimension l x 2w x h exceeds 180cm.'),
'lang' => false,
'form_group_class' => 'col-lg-10 extra-config',
);
}
if ($i !== $len - 1) {
$input[] = array(
'type' => 'hr',
'name' => 'hr',
);
}
$i++;
}
$fields_form[1] = array(
'form' => array(
'legend' => array(
'title' => $this->l('Select a carrier for each GLS service you want to propose'),
),
'input' => $input,
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right'
)
)
);
$this->context->smarty->assign(array(
'anchor_title' => $this->l('Click here to retrieve your Google Maps API Key'),
'anchor_link' => 'https://developers.google.com/maps/documentation/javascript/get-api-key',
'anchor_target' => 'target="_blank"',
));
$fields_form[2] = array(
'form' => array(
'legend' => array(
'title' => $this->l('Fill in your account details'),
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Webservice login'),
'required' => true,
'lang' => false,
'name' => 'GLS_WSLOGIN',
'col' => '12',
),
array(
'type' => 'text',
'label' => $this->l('Webservice password'),
'required' => true,
'lang' => false,
'name' => 'GLS_WSPWD',
'col' => '12',
),
array(
'type' => 'text',
'label' => $this->l('GLS agency code'),
'required' => true,
'lang' => false,
'name' => 'GLS_AGENCY_CODE',
'hint' => $this->l('Fill in the GLS agency code from where the package is sent.'),
'col' => '12',
),
array(
'type' => 'text',
'label' => $this->l('Google Maps API Key'),
'required' => true,
'lang' => false,
'name' => 'GLS_GOOGLE_MAPS_API_KEY',
'desc' => $this->context->smarty->fetch($this->local_path . 'views/templates/admin/anchor.tpl'),
'col' => '12',
),
array(
'type' => 'switch',
'label' => $this->l('Include Google Maps API Script'),
'required' => true,
'lang' => false,
'name' => 'GLS_GOOGLE_MAPS_API_SCRIPT_ENABLE',
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('No')
)
),
'hint' => $this->l('Disable this option if you have a problem to display the map.'),
'col' => '12',
),
array(
'type' => 'switch',
'label' => $this->l('Include an order prefix in GLS export/import'),
'required' => true,
'lang' => false,
'name' => 'GLS_ORDER_PREFIX_ENABLE',
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('No')
)
),
'hint' => $this->l('This option is required for multishops, it is enabled by default.'),
'col' => '12',
),
array(
'type' => 'html',
'name' => $this->l('Labels printing'),
'label' => '',
'col' => '12',
'form_group_class' => 'panel-heading',
),
array(
'type' => 'text',
'label' => $this->l('Web API login'),
'required' => false,
'lang' => false,
'name' => 'GLS_API_LOGIN',
'col' => '12',
),
array(
'type' => 'text',
'label' => $this->l('Web API password'),
'required' => false,
'lang' => false,
'name' => 'GLS_API_PWD',
'col' => '12',
),
array(
'type' => 'text',
'label' => $this->l('Customer ID (Web API)'),
'required' => false,
'lang' => false,
'name' => 'GLS_API_CUSTOMER_ID',
'col' => '12',
),
array(
'type' => 'text',
'label' => $this->l('Contact ID (Web API)'),
'required' => false,
'lang' => false,
'name' => 'GLS_API_CONTACT_ID',
'col' => '12',
),
array(
'type' => 'select',
'label' => $this->l('Delivery label format'),
'name' => 'GLS_API_DELIVERY_LABEL_FORMAT',
'required' => false,
'options' => array(
'query' => array(
array('id' => 'A4', 'name' => $this->l('A4')),
array('id' => 'A5', 'name' => $this->l('A5')),
array('id' => 'A6', 'name' => $this->l('A6'))
),
'id' => 'id',
'name' => 'name',
),
'col' => '12',
),
array(
'type' => 'switch',
'label' => $this->l('Enable shop return service'),
'required' => false,
'name' => 'GLS_API_SHOP_RETURN_SERVICE',
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('No')
)
),
'col' => '12',
),
array(
'type' => 'switch',
'label' => $this->l('Enable shop return notification email'),
'required' => false,
'name' => 'GLS_API_SHOP_RETURN_EMAIL_ALERT',
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('No')
)
),
'hint' => $this->l('Enable this option if you want to notify the customer after return label is generated.'),
'col' => '12',
),
array(
'type' => 'switch',
'label' => $this->l('Use the same return address as the one configured for the shop'),
'required' => false,
'name' => 'GLS_API_SHOP_RETURN_ADDRESS',
'is_bool' => true,
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Yes')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('No')
)
),
'col' => '12',
),
array(
'type' => 'text',
'label' => $this->l('Company or return contact name'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_NAME',
'required' => true,
'col' => '12',
'form_group_class' => 'return-address',
),
array(
'type' => 'text',
'label' => $this->trans('Address', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_ADDRESS1',
'required' => true,
'default_value' => $address->address1,
'col' => '12',
'form_group_class' => 'return-address',
),
array(
'type' => 'text',
'label' => $this->trans('Address (2)', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_ADDRESS2',
'col' => '12',
'form_group_class' => 'return-address',
),
array(
'type' => 'text',
'label' => $this->trans('Zip/postal code', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_POSTCODE',
'required' => true,
'col' => '12',
'form_group_class' => 'return-address',
),
array(
'type' => 'text',
'label' => $this->trans('City', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_CITY',
'required' => true,
'col' => '12',
'form_group_class' => 'return-address',
),
array(
'type' => 'select',
'label' => $this->trans('Country', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_COUNTRY',
'required' => true,
'options' => array(
'query' => Country::getCountries($this->context->language->id),
'id' => 'id_country',
'name' => 'name',
),
'col' => '12',
'form_group_class' => 'return-address',
),
array(
'type' => 'text',
'label' => $this->trans('Name', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_NAME_DEFAULT',
'required' => true,
'disabled' => true,
'col' => '12',
'form_group_class' => 'return-address default-address',
),
array(
'type' => 'text',
'label' => $this->trans('Address', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_ADDRESS1_DEFAULT',
'required' => true,
'default_value' => $address->address1,
'disabled' => true,
'col' => '12',
'form_group_class' => 'return-address default-address',
),
array(
'type' => 'text',
'label' => $this->trans('Address (2)', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_ADDRESS2_DEFAULT',
'disabled' => true,
'col' => '12',
'form_group_class' => 'return-address default-address',
),
array(
'type' => 'text',
'label' => $this->trans('Zip/postal code', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_POSTCODE_DEFAULT',
'required' => true,
'disabled' => true,
'col' => '12',
'form_group_class' => 'return-address default-address',
),
array(
'type' => 'text',
'label' => $this->trans('City', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_CITY_DEFAULT',
'required' => true,
'disabled' => true,
'col' => '12',
'form_group_class' => 'return-address default-address',
),
array(
'type' => 'select',
'label' => $this->trans('Country', array(), 'Admin.Global'),
'name' => 'GLS_API_SHOP_RETURN_ADDRESS_COUNTRY_DEFAULT',
'required' => true,
'options' => array(
'query' => Country::getCountries($this->context->language->id),
'id' => 'id_country',
'name' => 'name',
),
'disabled' => true,
'col' => '12',
'form_group_class' => 'return-address default-address',
),
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right'
)
)
);
$this->context->smarty->assign(array(
'gls_logo' => __PS_BASE_URI__.'modules/'.$this->name.'/views/img/admin/'.'gls-logo.jpg',
'zones_link' => $this->context->link->getAdminLink('AdminZones'),
));
$fields_form[3] = array(
'form' => array(
'legend' => array(
'title' => $this->l('Support')
),
'input' => array(
array(
'type' => 'html',
'name' => $this->context->smarty->fetch($this->local_path . 'views/templates/admin/config_faq.tpl'),
'label' => '',
'col' => '12',
),
),
)
);
$fields_form[4] = array(
'form' => array(
'legend' => array(
'title' => $this->l('Logs')
)
)
);
return $fields_form;
}
public function paginateLog($data, $page = 1, $pagination = 50)
{
if (count($data) > $pagination) {
$data = array_slice($data, $pagination * ($page - 1), $pagination);
}
return $data;
}
private function initList()
{
$this->fields_list = array(
'message' => array(
'title' => $this->l('Message'),
'type' => 'text',
'filter_key' => 'message',
'width' => '500',
),
'date_add' => array(
'title' => $this->l('Date'),
'filter_key' => 'date_add',
'type' => 'date',
'width' => '245',
'align' => 'right',
),
);
$helper = new HelperList();
$helper->module = $this;
$helper->shopLinkType = '';
$helper->no_link = true;
$helper->show_toolbar = false;
$helper->simple_header = false;
$helper->row_hover = false;
$helper->actions = array('');
$helper->identifier = 'id_gls_log';
$helper->table = 'gls_log';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
return $helper;
}
public function getConfigFormValues()
{
$address = $this->context->shop->getAddress();
$fields_values = array(
'GLS_GLSRELAIS_XL_ONLY' => Tools::getValue('GLS_GLSRELAIS_XL_ONLY', Configuration::get('GLS_GLSRELAIS_XL_ONLY')),
'GLS_WSLOGIN' => Tools::getValue('GLS_WSLOGIN', Configuration::get('GLS_WSLOGIN')),
'GLS_WSPWD' => Tools::getValue('GLS_WSPWD', Configuration::get('GLS_WSPWD')),
'GLS_AGENCY_CODE' => Tools::getValue('GLS_AGENCY_CODE', Configuration::get('GLS_AGENCY_CODE')),
'GLS_GOOGLE_MAPS_API_KEY' => Tools::getValue('GLS_GOOGLE_MAPS_API_KEY', Configuration::get('GLS_GOOGLE_MAPS_API_KEY')),
'GLS_GOOGLE_MAPS_API_SCRIPT_ENABLE' => Tools::getValue('GLS_GOOGLE_MAPS_API_SCRIPT_ENABLE', Configuration::get('GLS_GOOGLE_MAPS_API_SCRIPT_ENABLE')),
'GLS_ORDER_PREFIX_ENABLE' => Tools::getValue('GLS_ORDER_PREFIX_ENABLE', Configuration::get('GLS_ORDER_PREFIX_ENABLE')),
'GLS_API_CUSTOMER_ID' => Tools::getValue('GLS_API_CUSTOMER_ID', Configuration::get('GLS_API_CUSTOMER_ID')),
'GLS_API_CONTACT_ID' => Tools::getValue('GLS_API_CONTACT_ID', Configuration::get('GLS_API_CONTACT_ID')),
'GLS_API_DELIVERY_LABEL_FORMAT' => Tools::getValue('GLS_API_DELIVERY_LABEL_FORMAT', Configuration::get('GLS_API_DELIVERY_LABEL_FORMAT')),
'GLS_API_SHOP_RETURN_SERVICE' => Tools::getValue('GLS_API_SHOP_RETURN_SERVICE', Configuration::get('GLS_API_SHOP_RETURN_SERVICE')),
'GLS_API_SHOP_RETURN_EMAIL_ALERT' => Tools::getValue('GLS_API_SHOP_RETURN_EMAIL_ALERT', Configuration::get('GLS_API_SHOP_RETURN_EMAIL_ALERT')),
'GLS_API_LOGIN' => Tools::getValue('GLS_API_LOGIN', Configuration::get('GLS_API_LOGIN')),
'GLS_API_PWD' => Tools::getValue('GLS_API_PWD', Configuration::get('GLS_API_PWD')),
'GLS_API_SHOP_RETURN_ADDRESS' => Tools::getValue('GLS_API_SHOP_RETURN_ADDRESS', Configuration::get('GLS_API_SHOP_RETURN_ADDRESS')),
'GLS_API_SHOP_RETURN_ADDRESS_NAME' => Tools::getValue('GLS_API_SHOP_RETURN_ADDRESS_NAME', Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_NAME', null, null, null, Configuration::get('PS_SHOP_NAME'))),
'GLS_API_SHOP_RETURN_ADDRESS_ADDRESS1' => Tools::getValue('GLS_API_SHOP_RETURN_ADDRESS_ADDRESS1', Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_ADDRESS1', null, null, null, $address->address1)),
'GLS_API_SHOP_RETURN_ADDRESS_ADDRESS2' => Tools::getValue('GLS_API_SHOP_RETURN_ADDRESS_ADDRESS2', Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_ADDRESS2', null, null, null, $address->address2)),
'GLS_API_SHOP_RETURN_ADDRESS_POSTCODE' => Tools::getValue('GLS_API_SHOP_RETURN_ADDRESS_POSTCODE', Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_POSTCODE', null, null, null, $address->postcode)),
'GLS_API_SHOP_RETURN_ADDRESS_CITY' => Tools::getValue('GLS_API_SHOP_RETURN_ADDRESS_CITY', Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_CITY', null, null, null, $address->city)),
'GLS_API_SHOP_RETURN_ADDRESS_COUNTRY' => Tools::getValue('GLS_API_SHOP_RETURN_ADDRESS_COUNTRY', Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_COUNTRY', null, null, null, (int)$address->id_country)),
'GLS_API_SHOP_RETURN_ADDRESS' => Tools::getValue('GLS_API_SHOP_RETURN_ADDRESS', Configuration::get('GLS_API_SHOP_RETURN_ADDRESS')),
'GLS_API_SHOP_RETURN_ADDRESS_NAME_DEFAULT' => Configuration::get('PS_SHOP_NAME'),
'GLS_API_SHOP_RETURN_ADDRESS_ADDRESS1_DEFAULT' => $address->address1,
'GLS_API_SHOP_RETURN_ADDRESS_ADDRESS2_DEFAULT' => $address->address2,
'GLS_API_SHOP_RETURN_ADDRESS_POSTCODE_DEFAULT' => $address->postcode,
'GLS_API_SHOP_RETURN_ADDRESS_CITY_DEFAULT' => $address->city,
'GLS_API_SHOP_RETURN_ADDRESS_COUNTRY_DEFAULT' => (int)$address->id_country,
);
//__ GLS Carrier configuration
foreach (array_keys(self::$carrier_definition) as $key) {
$fields_values['GLS_'.$key.'_ID'] = Tools::getValue('GLS_'.$key.'_ID', Configuration::get('GLS_'.$key.'_ID'));
}
return $fields_values;
}
/**
* Save form data.
*/
protected function postProcess()
{
$output = null;
$output_info = '';
$form_values = $this->getConfigFormValues();
//__ GLS avant 13H: Test du renseignement du code agence GLS
if ($form_values['GLS_GLS13H_ID']) {
if (!$form_values['GLS_AGENCY_CODE']) {
$output .= $this->displayError($this->l('Your GLS agency code is necessary to propose the service GLS before 13H.'));
}
}
//__ Tests spécifiques pour le service GLS Relais
if ($form_values['GLS_GLSRELAIS_ID']) {
if (!$form_values['GLS_WSLOGIN'] || !$form_values['GLS_WSPWD']) {
$output .= $this->displayError($this->l('Your webservice login and password are necessary to propose the service GLS Point Relais®.'));
} else {
// Used when gls webservice is down
@ini_set('default_socket_timeout', '5');
//__ Test de connexion
$gls = new GlsController($form_values);
$result = $gls->searchRelay('34000');
@ini_restore('default_socket_timeout');
if (!$result) {
$output_info .= $this->displayWarning($this->l('GLS WebService temporarily unavailable.'));
} elseif ($result && isset($result->exitCode->ErrorCode) && $result->exitCode->ErrorCode == 502) {
$output .= $this->displayError($this->l('Incorrect GLS webservice login and/or password.'));
}
}
$this->context->smarty->assign(array(
'anchor_title' => $this->l('Click here to get an API Key'),
'anchor_link' => 'https://developers.google.com/maps/documentation/javascript/get-api-key',
'anchor_target' => 'target="_blank"',
));
//__ Erreur si affichage du script Google mais Google Maps API KEY non renseigné
if (!$form_values['GLS_GOOGLE_MAPS_API_KEY'] && $form_values['GLS_GOOGLE_MAPS_API_SCRIPT_ENABLE']) {
$output .= $this->displayError($this->l('A Google Maps API Key is necessary to locate Points Relais® using Google Maps.')
.Tools::nl2br("\n").$this->context->smarty->fetch($this->local_path . 'views/templates/admin/anchor.tpl'));
}
}
if (!$output) {
foreach ($form_values as $key => $value) {
switch ($key) {
case 'GLS_GLSRELAIS_ID':
case 'GLS_GLS13H_ID':
case 'GLS_GLSCHEZVOUS_ID':
case 'GLS_GLSCHEZVOUSPLUS_ID':
$old_carrier_id = Configuration::get($key);
if (is_numeric($value) && (int)$value > 0 && (int)$value != (int)$old_carrier_id) {
$this->defineCarrierAsModule((int)$value);
// activation du nouveau transporteur
if (Validate::isLoadedObject($object = new Carrier((int)$value))) {
$object->active = true;
$object->update();
}
}
if ((int)$old_carrier_id > 0 && (int)$value != (int)$old_carrier_id) {
// désactivation du transporteur anciennement associé
if (Validate::isLoadedObject($object = new Carrier((int)$old_carrier_id))) {
$object->active = false;
$object->update();
}
// On sauvegarde l'ancien ID dans les logs
$log_key = Tools::strReplaceFirst('_ID', '_LOG', $key);
$history_log = explode('|', Configuration::get($log_key));
$history_log[] = $old_carrier_id;
Configuration::updateValue($log_key, implode('|', array_map('intval', $history_log)));
}
break;
default:
break;
}
Configuration::updateValue($key, trim($value));
}
$output = $this->displayConfirmation($this->l('Settings updated')).$output_info;
}
return $output;
}
/**
* CSS and JS files added on the BO for PS 17
*/
public function hookActionAdminControllerSetMedia()
{
}
/**
* CSS and JS files added on the BO for PS16
*/
public function hookDisplayBackOfficeHeader()
{
if (Tools::getValue('controller') == 'AdminModules' && Tools::getValue('configure') == $this->name) {
if (method_exists($this->context->controller, 'addJquery')) {
$this->context->controller->addJquery();
}
$this->context->controller->addCSS($this->_path . '/views/css/admin.css');
$this->context->controller->addJS($this->_path . '/views/js/admin.js');
}
}
/**
* Display module in hooks
* @param string $hookName
* @param array $params
* TODO: à compléter même si non utilisé pour retro compatibilité 1.6
*/
public function renderWidget($hookName, array $_params)
{
switch ($hookName) {
case 'displayHeader':
$this->hookDisplayHeader();
break;
case 'displayCarrierExtraContent':
return $this->hookDisplayCarrierExtraContent($_params);
default:
break;
}
// $result = $this->getWidgetVariables($hookName, $_params);
// $this->smarty->assign($result);
// $template_file = $this->templates[$hookName];
// return $this->fetch('module:'.$this->name.'/views/templates/hook/'.$template_file);
}
public function getWidgetVariables($hookName, array $params)
{
}
/**
* Création des transporteurs GLS
* @param string $_code
* @param int $_id_zone_france
*/
public function createCarrier($_code, $_id_zone_france = null)
{
if (!array_key_exists($_code, self::$carrier_definition)) {
$this->_errors[] = $this->l('GLS carrier code is wrong.');
return false;
}
if (Shop::isFeatureActive() && !empty(self::$old_shop_context)) {
Shop::setContext(self::$old_shop_context['type'], self::$old_shop_context['id']);
}
$carrier = new Carrier();
$carrier->name = self::$carrier_definition[$_code]['name'];
$carrier->id_tax_rules_group = 0;
$carrier->active = true;
$carrier->deleted = 0;
$carrier->url = self::$trackingUrl;
$carrier->delay = self::$carrier_definition[$_code]['delay'];
$carrier->shipping_handling = false;
//__ If out-of-range behavior carrier is set to "Deactivate carrier"
$carrier->range_behavior = 0;
$carrier->is_module = true;
/*
* Défini à true pour pouvoir interragir sur le prix et l'affichage du transporteur
* (restriction quelconque en fonction des données de l'utilisateur et du marchand)
*/
$carrier->need_range = true;
$carrier->shipping_external = true;
$carrier->external_module_name = 'nkmgls';
$carrier->grade = self::$carrier_definition[$_code]['grade'];
foreach (Language::getLanguages(true) as $language) {
if (array_key_exists($language['iso_code'], self::$carrier_definition[$_code]['delay'])) {
$carrier->delay[$language['id_lang']] =self::$carrier_definition[$_code]['delay'][$language['iso_code']];
} else {
$carrier->delay[$language['id_lang']] = self::$carrier_definition[$_code]['delay']['fr'];
}
}
if ($carrier->add()) {
//__ Groups restriction
$groups = Group::getgroups(true);
$tmp_groups = array();
foreach ($groups as $value) {
$tmp_groups[] = $value['id_group'];
}
$carrier->setGroups($tmp_groups, false);
/**
* Zone configuration
*/
switch ($_code) {
case 'GLSRELAIS':
case 'GLSCHEZVOUSPLUS':
case 'GLS13H':
if (is_null($_id_zone_france)) {
$sql = new DbQuery();
$sql->select('z.`id_zone`')
->from('zone', 'z')
->where('z.`name` LIKE \'%France%\'');
foreach (Db::getInstance()->ExecuteS($sql) as $value) {
$carrier->addZone((int)$value['id_zone']);
}
} else {
$carrier->addZone((int)$_id_zone_france);
}
break;
default:
$zones = Zone::getZones();
foreach ($zones as $zone) {
$carrier->addZone($zone['id_zone']);
}
break;
}
/**
* Aucun prix par défaut
*/
//__ Range price default
// $rp = new RangePrice();
// $rp->id_carrier = $carrier->id;
// $rp->delimiter1 = 0;
// $rp->delimiter2 = 100000;
// $rp->add();
//__ Range weight default
// $rw = new RangeWeight();
// $rw->id_carrier = $carrier->id;
// $rw->delimiter1 = '0';
// $rw->delimiter2 = '30';
// $rw->add();
// Db::getInstance()->update(
// 'delivery',
// array('price' => 4.90),
// 'id_carrier='.(int)$carrier->id.' AND (id_range_price='.(int)$rp->id.' OR id_range_weight='.(int)$rw->id.')'
// );
//__ carrier logo (format JPG)
if (!copy(dirname(__FILE__).'/views/img/admin/'.Tools::strtolower($_code).'.jpg', _PS_SHIP_IMG_DIR_.'/'.$carrier->id.'.jpg')) {
$this->_errors[] = sprintf($this->l('Error to copy GLS carrier logo %s'), $_code);
}
} else {
$this->_errors[] = sprintf($this->l('Error to create GLS carrier %s'), $_code);
return false;
}
//__ Si le service est déjà associé à un transporteur alors il faut le désactiver et gérer l'historique
$old_id_carrier = Configuration::get('GLS_'.Tools::strtoupper($_code).'_ID');
if ($old_id_carrier) {
$history_log = explode('|', Configuration::get('GLS_'.Tools::strtoupper($_code).'_LOG'));
$history_log[] = $old_id_carrier;
Configuration::updateValue('GLS_'.Tools::strtoupper($_code).'_LOG', implode('|', array_map('intval', $history_log)));
if (Validate::isLoadedObject($object = new Carrier((int)$old_id_carrier))) {
$object->active = false;
$object->update();
}
}
return Configuration::updateValue('GLS_'.Tools::strtoupper($_code).'_ID', (int)$carrier->id);
}
public function getOrderShippingCost($params, $shipping_cost)
{
if ((int)$this->id_carrier == (int)Configuration::get('GLS_GLS13H_ID')) {
if (Configuration::get('GLS_AGENCY_CODE')) {
// Run synchronisation check
$this->synchronizeAgencyPostcodeRestriction();
$address = new Address((int)$this->context->cart->id_address_delivery);
$query = new DbQuery();
$query->select('g.*')
->from('gls_agency_postcode', 'g')
->where('g.`agency_code` = \''.pSQL(Configuration::get('GLS_AGENCY_CODE')).'\'')
->where('\''.pSQL($address->postcode).'\' >= `postcode_start`')
->where('\''.pSQL($address->postcode).'\' <= `postcode_end`');
if (!Db::getInstance()->getRow($query)) {
return false;
}
} else {
return false;
}
} elseif ((int)$this->id_carrier == (int)Configuration::get('GLS_GLSRELAIS_ID')) {
if (!Configuration::get('GLS_WSLOGIN') || !Configuration::get('GLS_WSPWD')) {
return false;
}
}
return $shipping_cost;
}
public function getOrderShippingCostExternal($params)
{
return $params;
}
/**
* Récupération des informations supplémentaires en fonction du transporteur
* @param array $_params
* @return mixed
*/
public function hookDisplayCarrierExtraContent($_params)
{
if (isset($_params['carrier'])) {
$error = array();
$config = $this->getConfigFormValues();
//__ récupération d'une éventuelle sélection déjà effectuée
$cart_carrier_detail = self::getCartCarrierDetail($_params['cart']->id, $_params['cart']->id_customer, $_params['carrier']['id']);
//__ récupération du numéro de mobile en session
$customer_default_phone_mobile = '';
if (isset($this->context->cart->id_address_delivery)) {
$customer_default_delivery_address = new Address($this->context->cart->id_address_delivery);
$customer_default_phone_mobile = $customer_default_delivery_address->phone_mobile;
if (empty($customer_default_phone_mobile) && !empty($customer_default_delivery_address->phone)) {
$customer_default_phone_mobile = $customer_default_delivery_address->phone;
}
}
if ($_params['carrier']['id'] == $config['GLS_GLSRELAIS_ID']) {
$relay_points = '';
//__ Récupération de l'adresse de livraison du client
if ($this->context->cart->id_address_delivery) {
$address = new Address((int)$this->context->cart->id_address_delivery);
// FIXME: cela n'est peut être pas nécessaire car on peut directement récupérer le postcode de cette manière $address->postcode non ?
$address_details = $address->getFields();
$country_iso = Country::getIsoById($address_details['id_country']);
// Used when gls webservice is down
@ini_set('default_socket_timeout', '5');
$gls = new GlsController($config);
$result = $gls->searchRelay($address_details['postcode'], $address_details['city'], $country_iso, $address_details['address1']);
@ini_restore('default_socket_timeout');
//__ gestion des erreurs du webservice
if (isset($result->exitCode->ErrorCode)) {
if ((int)$result->exitCode->ErrorCode == 998 || (int)$result->exitCode->ErrorCode == 999) {
//__ Aucun relais trouvé, recherche alternative
$error = array('code' => $result->exitCode->ErrorCode, 'message' => $this->l('We haven\'t found any Points Relais® in your delivery area. Please expand your search.'));
} elseif ((int)$result->exitCode->ErrorCode == 0) {
$relay_points = $result->SearchResults;
/**
* FIXME: ne fonctionne pas sur la version 1.7.2.4
*/
// $cookie_data = array(
// 'search_address' => array('country' => $country_iso, 'postcode' => $address_details['postcode'], 'city' => $address_details['city'])
// );
//__ Si restriction sur relais XL
if ($config['GLS_GLSRELAIS_XL_ONLY']) {
foreach ($relay_points as $key => $value) {
if (!empty($value->Parcelshop->Address->Name1) && Tools::substr($value->Parcelshop->Address->Name1, -2) != 'XL') {
unset($relay_points[$key]);
}
}
$relay_points = array_values($relay_points);
}
if (count($relay_points) <= 0) {
$error = array('code' => 998, 'message' => $this->l('We haven\'t found any Points Relais® in your delivery area. Please expand your search.'));
}
//__ On sauvegarde le résultat de la recherche dans session
// foreach ($relay_points as $value) {
// $cookie_data[$value->Parcelshop->ParcelShopId] = array(
// 'airLineDistance' => $value->AirLineDistance,
// 'Name1' => $value->Parcelshop->Address->Name1,
// 'Street1' => $value->Parcelshop->Address->Street1,
// 'ZipCode' => $value->Parcelshop->Address->ZipCode,
// 'City' => $value->Parcelshop->Address->City,
// 'Country' => $value->Parcelshop->Address->Country,
// 'Phone' => $value->Parcelshop->Phone->Contact,
// 'Mobile' => $value->Parcelshop->Mobile->Contact,
// 'email' => $value->Parcelshop->Email,
// 'url' => $value->Parcelshop->URL,
// 'latitude' => $value->Parcelshop->GLSCoordinates->Latitude,
// 'longitude' => $value->Parcelshop->GLSCoordinates->Longitude,
// 'GLSWorkingDay' => $value->Parcelshop->GLSWorkingDay,
// 'Name2' => (!empty($value->Parcelshop->Address->Name2) ? $value->Parcelshop->Address->Name2 : ''),
// 'Name3' => (!empty($value->Parcelshop->Address->Name3) ? $value->Parcelshop->Address->Name3 : ''),
// 'ContactName' => (!empty($value->Parcelshop->Address->ContactName) ? $value->Parcelshop->Address->ContactName : ''),
// 'BlockNo1' => (!empty($value->Parcelshop->Address->BlockNo1) ? $value->Parcelshop->Address->BlockNo1 : ''),
// 'Street2' => (!empty($value->Parcelshop->Address->Street2) ? $value->Parcelshop->Address->Street2 : ''),
// 'BlockNo2' => (!empty($value->Parcelshop->Address->BlockNo2) ? $value->Parcelshop->Address->BlockNo2 : ''),
// 'Province' => (!empty($value->Parcelshop->Address->Province) ? $value->Parcelshop->Address->Province : ''),
// );
// }
//__ Enregistrement des données de recherche dans le contexte cookie
// $this->context->cookie->__set('gls_cookie', json_encode($cookie_data));
/**
* Fin du FIXME
*/
} else {
$error = array('code' => $result->exitCode->ErrorCode, 'message' => $result->exitCode->ErrorDscr);
}
} else {
$error = array('code' => '', 'message' => $this->l('Service temporarily unavailable, try again later.'));
}
}
// TODO: passer le nombre de relais à afficher en paramètre
$this->smarty->assign(array(
'trans_days' => array(
'0' => $this->l('Monday'),
'1' => $this->l('Tuesday'),
'2' => $this->l('Wednesday'),
'3' => $this->l('Thursday'),
'4' => $this->l('Friday'),
'5' => $this->l('Saturday'),
'6' => $this->l('Sunday')),
'only_xl' => $config['GLS_GLSRELAIS_XL_ONLY'],
'relay_points' => $relay_points,
'force_gsm' => true,
'is_relay_carrier' => true,
'error' => $error,
'name_carrier' => $_params['carrier']['name'],
'id_carrier' => $_params['carrier']['id'],
'current_relay' => ($cart_carrier_detail && !empty($cart_carrier_detail['parcel_shop_id']) ? $cart_carrier_detail['parcel_shop_id'] : ''),
'current_customer_mobile' => ($cart_carrier_detail && !empty($cart_carrier_detail['customer_phone_mobile']) ? $cart_carrier_detail['customer_phone_mobile'] : $customer_default_phone_mobile),
'customer_mobile_title' => $this->l('Please fill in your mobile number, you will be notified by sms for the delivery'),
));
//__ Contraintes sur le mode de livraison en point relais
return $this->fetch('module:'.$this->name.'/views/templates/hook/'.$this->templates['displayCarrierExtraContent']);
} elseif ($_params['carrier']['id'] == $config['GLS_GLS13H_ID'] || $_params['carrier']['id'] == $config['GLS_GLSCHEZVOUSPLUS_ID']) {
$this->smarty->assign(array(
'relay_points' => false,
'force_gsm' => true,
'is_relay_carrier' => false,
'error' => $error,
'name_carrier' => $_params['carrier']['name'],
'id_carrier' => $_params['carrier']['id'],
'current_relay' => '',
'current_customer_mobile' => ($cart_carrier_detail && !empty($cart_carrier_detail['customer_phone_mobile']) ? $cart_carrier_detail['customer_phone_mobile'] : $customer_default_phone_mobile),
'customer_mobile_title' => ($_params['carrier']['id'] == $config['GLS_GLSCHEZVOUSPLUS_ID'] ? $this->l('Please fill in your mobile number, you will be notified by sms for the delivery') : $this->l('Please fill in your mobile number to make use of')),
));
//__ Contraintes sur le mode de livraison avant 13H
return $this->fetch('module:'.$this->name.'/views/templates/hook/'.$this->templates['displayCarrierExtraContent']);
}
}
}
/**
* CSS & JavaScript files added on the FO.
*/
public function hookDisplayHeader()
{
}
// In a module class
public function hookActionFrontControllerSetMedia($params)
{
//__ TODO: attention registerStylesheet non compatibles PS16
if (isset($this->context->controller->page_name) && $this->context->controller->page_name == 'checkout') {
Media::addJsDef(array(
'gls_display_delivery_option_url' => $this->context->link->getModuleLink($this->name, 'checkout', array(), true),
'glsrelais_carrier_id' => (int)Configuration::get('GLS_GLSRELAIS_ID'),
'gls13h_carrier_id' => (int)Configuration::get('GLS_GLS13H_ID'),
'glschezvousplus_carrier_id' => (int)Configuration::get('GLS_GLSCHEZVOUSPLUS_ID'),
'gls_js_general_error' => $this->l('Unexpected error occured.'),
'gls_js_relay_error' => $this->l('Please select a Point Relais® on the list.'),
'gls_js_search_error' => $this->l('Please fill-in a valid postcode.'),
'gls_js_mobile_error' => $this->l('Please fill-in a valid mobile number (e.g. +XXXXXXXXXXX or 0XXXXXXXXX).'),
));
if (Configuration::get('GLS_GOOGLE_MAPS_API_SCRIPT_ENABLE')) {
$this->context->controller->registerJavascript(
'module-gls-googlemaps',
'https://maps.googleapis.com/maps/api/js?key='.Configuration::get('GLS_GOOGLE_MAPS_API_KEY'),
array('server' => 'remote', 'attributes' => array('async', 'defer'))
);
}
$this->context->controller->registerJavascript(
'module-gls-frontjs',
'modules/'.$this->name.'/views/js/front.js',
array('position' => 'bottom', 'priority' => 100)
);
}
$this->context->controller->registerStylesheet(
'module-gls-frontcss',
'modules/'.$this->name.'/views/css/front.css',
array('media' => 'all')
);
}
/**
* Permet de sauvegarder l'historique de modification des transporteurs GLS
* On est obligatoirement en contexte ALLSHOP car forcé par prestashop
* @param array $params
*/
public function hookActionCarrierUpdate($params)
{
foreach (array_keys(self::$carrier_definition) as $key) {
if (Shop::isFeatureActive()) {
foreach (Shop::getShops(true) as $shop) {
if ((int)$params['id_carrier'] == (int)Configuration::get('GLS_'.$key.'_ID', null, $shop['id_shop_group'], $shop['id_shop'])) {
Configuration::updateValue('GLS_'.$key.'_ID', (int)$params['carrier']->id, false, $shop['id_shop_group'], $shop['id_shop']);
$history_log = explode('|', Configuration::get('GLS_'.$key.'_LOG', null, $shop['id_shop_group'], $shop['id_shop']));
$history_log[] = $params['id_carrier'];
Configuration::updateValue('GLS_'.$key.'_LOG', implode('|', array_map('intval', $history_log)), false, $shop['id_shop_group'], $shop['id_shop']);
}
}
} elseif ((int)$params['id_carrier'] == (int)Configuration::get('GLS_'.$key.'_ID')) {
Configuration::updateValue('GLS_'.$key.'_ID', (int)$params['carrier']->id);
$history_log = explode('|', Configuration::get('GLS_'.$key.'_LOG'));
$history_log[] = $params['id_carrier'];
Configuration::updateValue('GLS_'.$key.'_LOG', implode('|', array_map('intval', $history_log)));
}
}
}
/**
* Suppression d'un transporteur
* On est obligatoirement en contexte ALLSHOP car forcé par prestashop
* @param array $params
*/
public function hookActionObjectCarrierUpdateAfter($params)
{
if (Validate::isLoadedObject($params['object']) && $params['object']->deleted) {
// Si le transporteur a été supprimé définitivement
if (!Carrier::getCarrierByReference($params['object']->id_reference)) {
foreach (array_keys(self::$carrier_definition) as $key) {
if (Shop::isFeatureActive()) {
foreach (Shop::getShops(true) as $shop) {
if ((int)$params['object']->id == (int)Configuration::get('GLS_'.$key.'_ID', null, $shop['id_shop_group'], $shop['id_shop'])) {
Configuration::updateValue('GLS_'.$key.'_ID', '', false, $shop['id_shop_group'], $shop['id_shop']);
$history_log = explode('|', Configuration::get('GLS_'.$key.'_LOG', null, $shop['id_shop_group'], $shop['id_shop']));
$history_log[] = $params['object']->id;
Configuration::updateValue('GLS_'.$key.'_LOG', implode('|', array_map('intval', $history_log)), false, $shop['id_shop_group'], $shop['id_shop']);
}
}
} elseif ((int)$params['object']->id == (int)Configuration::get('GLS_'.$key.'_ID')) {
Configuration::updateValue('GLS_'.$key.'_ID', '');
$history_log = explode('|', Configuration::get('GLS_'.$key.'_LOG'));
$history_log[] = $params['object']->id;
Configuration::updateValue('GLS_'.$key.'_LOG', implode('|', array_map('intval', $history_log)));
}
}
}
}
}
/**
* Sets some parameters when a carrier is define as a GLS module
* @param int $id_carrier
*/
public function defineCarrierAsModule($id_carrier)
{
$sql = new DbQuery();
$sql->select('external_module_name')
->from('carrier')
->where('id_carrier = '.(int)$id_carrier);
$external_module = Db::getInstance()->getValue($sql);
if ($external_module !== false && $external_module != 'nkmgls') {
Db::getInstance()->execute('
UPDATE '._DB_PREFIX_.'carrier
SET shipping_handling = 0,
is_module = 1,
shipping_external = 1,
need_range = 1,
external_module_name = \'nkmgls\'
WHERE id_carrier = '.(int)$id_carrier);
}
}
public function hookDisplayOrderDetail($params)
{
//__ TODO: a décommenter lorsqu'on aura ajouté plus de détail sur le point relais (horaires, map)
// $glsRelaisIds = $this->getCarrierIdHistory('GLSRELAIS');
// $addressDelivery = $this->getGlsRelayAddress($params['order']->id_cart, $params['order']->id_carrier, $params['order']->id_customer);
// if ($addressDelivery
// && $addressDelivery['addressObject']
// && isset($glsRelaisIds['GLSRELAIS'])
// && in_array($params['order']->id_carrier, $glsRelaisIds['GLSRELAIS'])) {
// $this->smarty->assign(array(
// 'address_delivery' => $addressDelivery['addressObject'],
// 'address_delivery_formatted' => AddressFormat::generateAddress($addressDelivery['addressObject'], array(), Tools::nl2br("\n")),
// ));
// return $this->fetch('module:'.$this->name.'/views/templates/hook/'.$this->templates['displayOrderDetail']);
// }
}
/**
* permet de récupérer les informations enregistrées concernant le panier et le transporteur GLS
* @param unknown $_id
*/
public static function getCartCarrierDetail($_id_cart, $_id_customer, $_id_carrier = null)
{
$query = new DbQuery();
$query->select('c.*')
->from('gls_cart_carrier', 'c')
->where('c.`id_customer` = '.(int)$_id_customer)
->where('c.`id_cart` = '.(int)$_id_cart);
if (!empty($_id_carrier)) {
$query->where('c.`id_carrier` = '.(int)$_id_carrier);
}
return Db::getInstance()->getRow($query);
}
public function hookDisplayAfterCarrier()
{
return $this->fetch('module:'.$this->name.'/views/templates/hook/'.$this->templates['displayAfterCarrier']);
}
/**
* Permet de définir si l'étape de choix de livraison est complète
* @param unknown $params
*/
public function hookActionValidateStepComplete($params)
{
if ($params['step_name'] == 'delivery') {
if (isset($params['request_params']['delivery_option'])) {
//__ Get the first value
$id_carrier_selected = (int)reset($params['request_params']['delivery_option']);
if ($id_carrier_selected == (int)Configuration::get('GLS_GLSRELAIS_ID')
|| $id_carrier_selected == (int)Configuration::get('GLS_GLS13H_ID')
|| $id_carrier_selected == (int)Configuration::get('GLS_GLSCHEZVOUSPLUS_ID')
) {
//__ Test de saisie du numéro de mobile si nécessaire
if (!isset($params['request_params']['gls_customer_mobile_'.$id_carrier_selected])
|| (isset($params['request_params']['gls_customer_mobile_'.$id_carrier_selected])
&& empty($params['request_params']['gls_customer_mobile_'.$id_carrier_selected]))
) {
$params['completed'] &= false;
}
//__ Test de sélection d'un point relay
if ($id_carrier_selected == (int)Configuration::get('GLS_GLSRELAIS_ID')) {
if (!self::getCartCarrierDetail($params['cookie']->id_cart, $params['cookie']->id_customer, $id_carrier_selected)) {
$params['completed'] &= false;
}
}
}
}
}
return $params['completed'];
}
/**
* Permet de faire une action à la validation de l'étape du choix des modes de livraison
* @param unknown $params
*/
public function hookActionCarrierProcess($params)
{
// Suppression des donénes GLS si le transporteur sélectionné n'est pas GLS
if (!empty($params['cart'])) {
$cart_detail = self::getCartCarrierDetail((int)$params['cart']->id, (int)$params['cart']->id_customer);
if ($cart_detail && (int)$cart_detail['id_carrier'] != (int)$params['cart']->id_carrier) {
Db::getInstance()->delete('gls_cart_carrier', 'id_cart = "'.pSQL((int)$params['cart']->id).'"');
}
}
}
/**
* Permet de récupérer et d'importer le fichier CSV contenant les restrictions par codes postaux en fonction du code agence de point retrait
* @param bool $_force
* @param string $_file_content
*/
public function synchronizeAgencyPostcodeRestriction($_force = false, $_file_content = null)
{
// Dont call on ajax context
if (Tools::getValue('ajax') != '1') {
//__ Get last update date
$toSynchronize = false;
$last_update_date = Configuration::get('GLS_LAST_SYNCHRO_DATE', '');
// Si la dernière synchro date de plus de 24h
$last_update = new DateTime($last_update_date);
$now = new DateTime();
if (empty($last_update_date) || $last_update->format('Ymd') < $now->format('Ymd')) {
// Mise à jour de la date de synchro
Configuration::updateValue('GLS_LAST_SYNCHRO_DATE', date('Y-m-d H:i:s'));
// Ressource locale qui contiendra le fichier téléchargé
$filename = 'tbzipdeltimes_'.date('Ymd').'.csv';
$handle = fopen($this->importDirectory.$filename, 'w');
// Connexion basique avec timeout de 5s
$conn_id = ftp_connect(self::$ftp_host, 21, 5);
$login_result = ftp_login($conn_id, self::$ftp_login, self::$ftp_pwd);
if ($login_result) {
foreach (ftp_nlist($conn_id, ".") as $f) {
// il existe un fichier au format
if (preg_match('/^tbzipdeltimes_(\d{8}).csv$/i', $f, $date)) {
// Le fichier est plus récent que la date de dernière synchro
if (empty($last_update_date) || $date[1] > $last_update->format('Ymd')) {
// download the file into $handle
if (ftp_fget($conn_id, $handle, $f, FTP_ASCII, 0)) {
// Check hash of the file
$hash = md5_file($this->importDirectory.$filename);
if ($hash != Configuration::get('GLS_SYNCHRO_FILE_CONTENT_HASH', '')) {
Configuration::updateValue('GLS_SYNCHRO_FILE_CONTENT_HASH', $hash);
$toSynchronize = true;
$csv_file = new NkmCSVReader();
$_file_content = $csv_file->parse_file($this->importDirectory.$filename, false, true);
break;
}
}
}
}
}
}
// Fermeture de la connexion et du pointeur de fichier
ftp_close($conn_id);
fclose($handle);
unlink($this->importDirectory.$filename);
}
if ($_force || $toSynchronize) {
if (!empty($_file_content) && is_array($_file_content) && count($_file_content) > 0) {
$query = '';
foreach ($_file_content as $line) {
$query .= '(\''.pSQL($line[0]).'\', \''.pSQL($line[1]).'\', \''.pSQL($line[2]).'\'),';
}
$query = trim($query, ',');
if (!empty($query)) {
if (Db::getInstance()->execute('TRUNCATE TABLE `' . _DB_PREFIX_ . 'gls_agency_postcode`')) {
Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'gls_agency_postcode` (`agency_code`, `postcode_start`, `postcode_end`) VALUES '.$query);
}
}
}
}
}
}
/**
* Retourne tous les IDs des modes de livraison du module GLS (historique compris en cas de modification du transporteur)
*/
public function getCarrierIdHistory($_code = null)
{
$search = array();
if (!is_null($_code) && array_key_exists($_code, self::$carrier_definition)) {
$search[$_code] = self::$carrier_definition[$_code];
} else {
$search = self::$carrier_definition;
}
$result = array();
foreach (array_keys($search) as $key) {
$log = Configuration::get('GLS_'.$key.'_LOG', null, $this->context->shop->id_shop_group, $this->context->shop->id);
if (!empty($log)) {
$history_log = explode('|', Configuration::get('GLS_'.$key.'_LOG', null, $this->context->shop->id_shop_group, $this->context->shop->id));
} else {
$history_log = array();
}
$carrier_id = Configuration::get('GLS_'.$key.'_ID', 0, $this->context->shop->id_shop_group, $this->context->shop->id);
if ((int)$carrier_id > 0) {
$history_log[] = Configuration::get('GLS_'.$key.'_ID', null, $this->context->shop->id_shop_group, $this->context->shop->id);
}
foreach ($history_log as $k => $v) {
if (empty($v)) {
unset($history_log[$k]);
}
}
$result[$key] = $history_log;
}
return $result;
}
/**
* Cron Export/import GLS
*/
public function cronTask()
{
try {
$controller = new AdminGlsOrderController(true);
$exportConfig = $controller->getConfigFormValues('export');
$importConfig = $controller->getConfigFormValues('import');
/**
* Import des commandes
*/
if ($importConfig['GLS_IMPORT_AUTOMATION']
&& (!Tools::getIsset('action') || (Tools::getIsset('action') && Tools::getValue('action') === 'import'))
) {
$controller->importWinexpe();
if (!empty($controller->errors)) {
// LOG
$gls_log = new GlsLogClass();
$gls_log->log($this->l('Automatic import:') .' '. implode(Tools::nl2br("\n"), array_map('pSQL', $controller->errors)));
}
}
/**
* Export des commandes
*/
if ($exportConfig['GLS_EXPORT_AUTOMATION']
&& (!Tools::getIsset('action') || (Tools::getIsset('action') && Tools::getValue('action') === 'export'))
) {
$controller->exportWinexpe();
if (!empty($controller->errors)) {
// LOG
$gls_log = new GlsLogClass();
$gls_log->log($this->l('Automatic export:') .' '. implode(Tools::nl2br("\n"), array_map('pSQL', $controller->errors)));
}
}
} catch (Exception $e) {
die($e->getMessage());
}
}
public function displayInfoByCart($_id_cart)
{
// TODO: Essayer de factoriser le code ci-dessous avec celui affichant l'adresse du point relais dans l'historique de commande
$query = new DbQuery();
$query->select('c.*')
->from('gls_cart_carrier', 'c')
->where('c.`id_cart` = '.(int)$_id_cart);
if ($result = Db::getInstance()->getRow($query)) {
//__ Define a delivery address to display
$addressDelivery = new Address();
$addressDelivery->company = $result['name'];
$addressDelivery->address1 = $result['address1'];
$addressDelivery->address2 = $result['address2'];
$addressDelivery->postcode = $result['postcode'];
$addressDelivery->city = $result['city'];
$addressDelivery->phone_mobile = $result['phone_mobile'];
$addressDelivery->phone = $result['phone'];
$addressDelivery->id_country = $result['id_country'];
$addressDelivery->country = Country::getNameById($this->context->language->id, (int)$result['id_country']);
$this->context->smarty->assign(array(
'parcel_shop_id' => $result['parcel_shop_id'],
'address_delivery' => $addressDelivery,
'address_delivery_formatted' => AddressFormat::generateAddress($addressDelivery, array(), Tools::nl2br("\n")),
));
return $this->context->smarty->fetch($this->local_path . 'views/templates/admin/'.$this->templates['displayInfoByCart']);
}
}
private function getPrestaShopVersion()
{
if (version_compare(_PS_VERSION_, '1.7.', '<')) {
return '1.6';
} elseif (version_compare(_PS_VERSION_, '1.7.1', '<')) {
return '1.7.0';
} elseif (version_compare(_PS_VERSION_, '1.7.2', '<')) {
return '1.7.1';
} else {
return '1.7';
}
}
/**
* Envoi d'un email de confirmation commande GLS
* Modification de l'adresse de livraison
* @param array $params
*/
public function hookActionValidateOrder($params)
{
// Suppression des donénes GLS si le transporteur sélectionné n'est pas GLS
$order_detail = self::getCartCarrierDetail($params['order']->id_cart, $params['order']->id_customer);
if ($order_detail && (int)$order_detail['id_carrier'] != (int)$params['order']->id_carrier) {
Db::getInstance()->delete('gls_cart_carrier', 'id_cart = "'.pSQL($params['order']->id_cart).'"');
} else {
$glsRelaisIds = $this->getCarrierIdHistory('GLSRELAIS');
$addressDelivery = $this->getGlsRelayAddress($params['order']->id_cart, $params['order']->id_carrier, $params['order']->id_customer);
if ($addressDelivery
&& $addressDelivery['addressObject']
&& isset($glsRelaisIds['GLSRELAIS'])
&& in_array($params['order']->id_carrier, $glsRelaisIds['GLSRELAIS'])
) {
$id_lang = (int)$params['order']->id_lang;
$customer = new Customer($params['order']->id_customer);
$carrier = new Carrier((int)$params['order']->id_carrier);
//__ Modification de l'adresse de livraison du client
try {
$new_address = clone $addressDelivery['addressObject'];
$customer_address = new Address($params['order']->id_address_delivery);
//__ Ajout de certaines informations client
$new_address->alias = $carrier->name;
$new_address->id_customer = $params['order']->id_customer;
$new_address->firstname = $customer_address->firstname;
$new_address->lastname = $customer_address->lastname;
if (empty($new_address->phone_mobile)) {
$new_address->phone_mobile = $addressDelivery['glsOrderDetail']['customer_phone_mobile'];
}
$new_address->deleted = true;
$new_address->add();
$params['order']->id_address_delivery = $new_address->id;
$params['order']->update();
} catch (Exception $e) {
// TODO: Log error
}
if (isset($addressDelivery['glsOrderDetail'])) {
$GLSWorkingDayObject = json_decode($addressDelivery['glsOrderDetail']['parcel_shop_working_day'], true);
}
$working_days = $this->displayWorkingsDay($GLSWorkingDayObject);
if (!is_array($working_days) || empty($working_days)) {
$working_days = array('html' => '', 'txt' => '');
}
$vars = array(
'{gls_logo}' => $this->context->shop->getBaseURL(true, false).$this->_path.'views/img/mails/gls-logo.jpg',
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{order_name}' => $params['order']->reference,
'{date}' => Tools::displayDate($params['order']->date_add, null),
'{payment}' => Tools::substr($params['order']->payment, 0, 255),
'{carrier}' => $carrier->name,
'{address_delivery_formatted_html}' => AddressFormat::generateAddress($addressDelivery['addressObject'], array(), Tools::nl2br("\n")),
'{address_delivery_formatted_txt}' => AddressFormat::generateAddress($addressDelivery['addressObject'], array(), "\n"),
'{address_delivery_hours_html}' => $working_days['html'],
'{address_delivery_hours_txt}' => $working_days['txt'],
);
return Mail::Send(
(int)$id_lang,
'gls_new_order',
$this->l('GLS Order confirmation', false, (int)$id_lang),
$vars,
$customer->email,
$customer->firstname.' '.$customer->lastname,
null,
null,
null,
null,
dirname(__FILE__).'/mails/',
false
);
}
}
}
/**
* Display relay working day in table
* @param object $_GLSWorkingDayObject
*/
public function displayWorkingsDay($_GLSWorkingDayObject = array())
{
$trans_days = array(
'0' => $this->l('Monday'),
'1' => $this->l('Tuesday'),
'2' => $this->l('Wednesday'),
'3' => $this->l('Thursday'),
'4' => $this->l('Friday'),
'5' => $this->l('Saturday'),
'6' => $this->l('Sunday'),
);
$html = '';
$txt = '';
if ($_GLSWorkingDayObject && is_array($_GLSWorkingDayObject) && count($_GLSWorkingDayObject) > 0) {
$this->smarty->assign(array(
'trans_days' => $trans_days,
'workingDayObject' => $_GLSWorkingDayObject,
));
$html = $this->fetch('module:'.$this->name.'/views/templates/hook/'.$this->templates['displayWorkingsDay']);
foreach ($trans_days as $day => $dname) {
if (isset($_GLSWorkingDayObject[$day])) {
if ($_GLSWorkingDayObject[$day]['Breaks']['Hours']['From']) {
$txt .= $dname.': '."\n".
Tools::substr($_GLSWorkingDayObject[$day]['OpeningHours']['Hours']['From'], 0, 2).':'.Tools::substr($_GLSWorkingDayObject[$day]['OpeningHours']['Hours']['From'], 2, 2).
' - '.Tools::substr($_GLSWorkingDayObject[$day]['Breaks']['Hours']['From'], 0, 2).':'.Tools::substr($_GLSWorkingDayObject[$day]['Breaks']['Hours']['From'], 2, 2).
"\n".Tools::substr($_GLSWorkingDayObject[$day]['Breaks']['Hours']['To'], 0, 2).':'.Tools::substr($_GLSWorkingDayObject[$day]['Breaks']['Hours']['To'], 2, 2).
' - '.Tools::substr($_GLSWorkingDayObject[$day]['OpeningHours']['Hours']['To'], 0, 2).':'.Tools::substr($_GLSWorkingDayObject[$day]['OpeningHours']['Hours']['To'], 2, 2);
} else {
$txt .= $dname.': '.Tools::substr($_GLSWorkingDayObject[$day]['OpeningHours']['Hours']['From'], 0, 2).':'.Tools::substr($_GLSWorkingDayObject[$day]['OpeningHours']['Hours']['From'], 2, 2).
Tools::substr($_GLSWorkingDayObject[$day]['OpeningHours']['Hours']['To'], 0, 2).':'.Tools::substr($_GLSWorkingDayObject[$day]['OpeningHours']['Hours']['To'], 2, 2);
}
} else {
$txt .= $dname.': '.$this->l('Closed');
}
$txt .= "\n";
}
}
return array('txt' => $txt, 'html' => $html);
}
/**
* Retourne l'adresse du point relay sous format d'objet Address
* @param unknown $_id_cart
* @param unknown $_id_carrier
* @param unknown $_id_customer
*/
public function getGlsRelayAddress($_id_cart, $_id_carrier, $_id_customer)
{
if (empty($_id_cart) || empty($_id_carrier) || empty($_id_customer)) {
return false;
}
$order_detail = self::getCartCarrierDetail($_id_cart, $_id_customer, $_id_carrier);
if ($order_detail) {
//__ Define a delivery address to display
$addressDelivery = new Address();
$addressDelivery->company = $order_detail['name'];
$addressDelivery->address1 = $order_detail['address1'];
$addressDelivery->address2 = $order_detail['address2'];
$addressDelivery->postcode = $order_detail['postcode'];
$addressDelivery->city = $order_detail['city'];
$addressDelivery->phone_mobile = $order_detail['phone_mobile'];
$addressDelivery->phone = $order_detail['phone'];
$addressDelivery->id_country = $order_detail['id_country'];
$addressDelivery->country = Country::getNameById($this->context->language->id, (int)$order_detail['id_country']);
return array('addressObject' => $addressDelivery, 'glsOrderDetail' => $order_detail);
}
return false;
}
/**
* Envoi du mail au client avec le numéro de suivi
* @param object $_order_carrier
* @param object $_order
*/
public function sendInTransitEmail($_order_carrier, $_order, $_id_carrier = null)
{
if (version_compare(_PS_VERSION_, '1.7.1', '<') || Shop::isFeatureActive()) {
if (is_null($_id_carrier)) {
$_id_carrier = $_order->id_carrier;
}
$customer = new Customer((int)$_order->id_customer);
$carrier = new Carrier((int)$_id_carrier, $_order->id_lang);
if (Validate::isLoadedObject($customer) && Validate::isLoadedObject($carrier)) {
$translator = Context::getContext()->getTranslator();
$orderLanguage = new Language((int) $_order->id_lang);
$templateVars = array(
'{followup}' => str_replace('@', $_order->shipping_number, $carrier->url),
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{id_order}' => $_order->id,
'{shipping_number}' => $_order->shipping_number,
'{order_name}' => $_order->getUniqReference()
);
return Mail::Send(
(int)$_order->id_lang,
'in_transit',
$translator->trans(
'Package in transit',
array(),
'Emails.Subject',
$orderLanguage->locale
),
$templateVars,
$customer->email,
$customer->firstname . ' ' . $customer->lastname,
null,
null,
null,
null,
_PS_MAIL_DIR_,
false,
(int)$_order->id_shop
);
}
} else {
// Exception possible en mode debug
return @$_order_carrier->sendInTransitEmail($_order);
}
// TODO: est il utile d'executer le hook à ce niveau ?
// $customer = new Customer((int)$order->id_customer);
// $carrier = new Carrier((int)$order->id_carrier, $order->id_lang);
// Hook::exec('actionAdminOrdersTrackingNumberUpdate', array(
// 'order' => $order,
// 'customer' => $customer,
// 'carrier' => $carrier
// ), null, false, true, false, $order->id_shop);
return false;
}
public function hookActionDeleteGDPRCustomer($customer)
{
if (!empty($customer['id_customer']) &&
Validate::isLoadedObject(new Customer((int)$customer['id']))) {
if (Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'gls_cart_carrier` SET `customer_phone_mobile`=\'\', `id_customer`='.(int)Configuration::get('PSGDPR_ANONYMOUS_CUSTOMER').' WHERE id_customer = '.(int)$customer['id'])) {
return json_encode(true);
}
return json_encode($this->l('GLS : Unable to delete customer using id.'));
}
}
public function hookActionObjectCustomerDeleteAfter($params)
{
Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'gls_cart_carrier` SET `customer_phone_mobile`=\'\', `id_customer`='.(int)Configuration::get('PSGDPR_ANONYMOUS_CUSTOMER').' WHERE id_customer = '.(int)$params['object']->id);
}
public function hookActionExportGDPRData($customer)
{
if (!empty($customer['id']) &&
Validate::isLoadedObject(new Customer((int)$customer['id']))) {
$data = array();
$res = Db::getInstance()->ExecuteS("SELECT * FROM "._DB_PREFIX_."gls_cart_carrier WHERE id_customer = '".(int)$customer['id']."'");
if ($res) {
foreach ($res as $value) {
array_push($data, array(
$this->l('ID cart') => $value['id_cart'],
$this->l('Customer phone mobile') => $value['customer_phone_mobile'],
));
}
return json_encode($data);
}
return json_encode($this->l('No data found.'));
}
}
}