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

1033 lines
47 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.
*/
if (!class_exists('NkmCsv')) {
require_once(dirname(__FILE__).'/../../lib/NkmCsv.php');
}
include dirname(__FILE__).'/../../lib/NkmHelper.php';
if (!class_exists('GlsLogClass')) {
require_once dirname(__FILE__).'/../../classes/GlsLogClass.php';
}
if (!class_exists('GlsApi')) {
require_once dirname(__FILE__).'/../../classes/GlsApi.php';
}
class AdminGlsLabelController extends ModuleAdminController
{
private static $tab_lang = array('fr' => 'GLS étiquettes');
public $order_state = array();
public $carrier = array();
// use for performance
public $verifyTrackingUrl = array();
public function __construct()
{
$this->bootstrap = true;
$this->display = 'view';
$this->module = 'nkmgls';
$this->context = Context::getContext();
parent::__construct();
$this->name = 'GlsLabel';
$this->order_state = OrderState::getOrderStates($this->context->language->id);
$this->carrier = Carrier::getCarriers($this->context->language->id, false, false, false, null, null);
}
/**
* Add an entry in the tab menu
* @param Object $module
*/
public static function installInBO()
{
$tab = new Tab();
$tab->active = 1;
$tab->class_name = "AdminGlsLabel";
$tab->name = array();
foreach (Language::getLanguages(true) as $lang) {
if (isset(self::$tab_lang[$lang['iso_code']])) {
$tab->name[(int)$lang['id_lang']] = self::$tab_lang[$lang['iso_code']];
} else {
$tab->name[(int)$lang['id_lang']] = 'GLS delivery label';
}
}
$tab->id_parent = (int)Tab::getIdFromClassName('AdminParentOrders');
$tab->module = 'nkmgls';
return $tab->add();
}
/**
* Remove an entry in the tab menu
* @param Object $module
*/
public static function removeFromBO()
{
$id_tab = (int)Tab::getIdFromClassName('AdminGlsLabel');
if ($id_tab) {
$tab = new Tab($id_tab);
if (validate::isLoadedObject($tab)) {
return $tab->delete();
}
}
return false;
}
public function renderView()
{
$init_form = false;
if (empty($this->errors)
&& ((bool)Tools::isSubmit('generateLabelStep2') === true || (bool)Tools::isSubmit('generateLabelStep3Cancel') === true)
) {
$init_form = $this->initFormLabelStep2();
} elseif (empty($this->errors) && (bool)Tools::isSubmit('generateLabelStep3') === true) {
$init_form = $this->initFormLabelStep3();
}
if (!$init_form) {
$statuses = array();
foreach ($this->order_state as $value) {
$statuses[] = array('id_option'=>$value['id_order_state'], 'name'=>$value['name'], 'val'=>$value['id_order_state']);
}
$new_statuses = $statuses;
array_unshift($new_statuses, array('id_option'=>'0', 'name'=>$this->l('(No change)'), 'val'=>''));
$init_form = $this->initFormLabel($statuses, $new_statuses) . $this->initFormShopReturn($new_statuses);
}
return $init_form;
}
/**
* Retourne les données de configuration
*/
public function getConfigFormValues()
{
$fieds = array(
'GLS_LABEL_NEW_ORDER_STATE' => Tools::getValue('GLS_LABEL_NEW_ORDER_STATE', Configuration::get('GLS_LABEL_NEW_ORDER_STATE')),
'GLS_LABEL_SINGLE_NEW_ORDER_STATE' => Tools::getValue('GLS_LABEL_SINGLE_NEW_ORDER_STATE', Configuration::get('GLS_LABEL_SINGLE_NEW_ORDER_STATE')),
);
foreach ($this->order_state as $value) {
if (in_array($value['id_order_state'], explode(',', Configuration::get('GLS_LABEL_ORDER_STATE_FILTER')))) {
$fieds['GLS_LABEL_ORDER_STATE_FILTER_'.$value['id_order_state']] = true;
} else {
$fieds['GLS_LABEL_ORDER_STATE_FILTER_'.$value['id_order_state']] = false;
}
}
$carrier_filter = Configuration::get('GLS_LABEL_CARRIER_FILTER', '');
foreach ($this->carrier as $value) {
if (empty($carrier_filter) && $value['external_module_name'] == 'nkmgls') {
$fieds['GLS_LABEL_CARRIER_FILTER_'.$value['id_carrier']] = true;
} elseif (in_array($value['id_carrier'], explode(',', $carrier_filter))) {
$fieds['GLS_LABEL_CARRIER_FILTER_'.$value['id_carrier']] = true;
} else {
$fieds['GLS_LABEL_CARRIER_FILTER_'.$value['id_carrier']] = false;
}
}
return $fieds;
}
/**
* Construction du premier formulaire de recherche de commande
*/
public function initFormLabel($statuses, $new_statuses)
{
/**
* Récupération de tous les transporteurs sauf "GLS avant 13h"
*/
$carriers = array();
$gls13hCarriersIds = $this->module->getCarrierIdHistory('GLS13H');
foreach ($this->carrier as $value) {
if (!in_array($value['id_carrier'], $gls13hCarriersIds['GLS13H'])) {
$name = $value['name'] . ' (' . $this->l('ID:') . ' ' . $value['id_carrier'] .')';
if ($value['active'] == '0') {
$name .= ' [' . $this->l('Disabled') . ']';
}
$carriers[] = array('id_option'=>$value['id_carrier'], 'name'=> $name, 'val'=>$value['id_carrier']);
}
}
$this->fields_value = $this->getConfigFormValues();
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Delivery label printing'),
'icon' => 'icon-print'
),
'description' => $this->l('Generate your GLS shipping labels.'),
'input' => array(
array(
'type' => 'checkbox',
'label' => $this->l('Carriers'),
'name' => 'GLS_LABEL_CARRIER_FILTER',
'multiple' => true,
'required' => true,
'values' => array(
'query' => $carriers,
'id' => 'id_option',
'name' => 'name'
),
),
array(
'type' => 'checkbox',
'label' => $this->l('Order statuses'),
'name' => 'GLS_LABEL_ORDER_STATE_FILTER',
'multiple' => true,
'required' => true,
'values' => array(
'query' => $statuses,
'id' => 'id_option',
'name' => 'name'
),
),
array(
'type' => 'select',
'label' => $this->l('Change order status to'),
'name' => 'GLS_LABEL_NEW_ORDER_STATE',
'require' => false,
'options' => array(
'query' => $new_statuses,
'id' => 'id_option',
'name' => 'name'
)
),
),
'buttons' => array(
0 => array(
'type' => 'submit',
'title' => $this->l('Next'),
'id' => 'generateLabelStep2',
'name' => 'generateLabelStep2',
'class' => 'pull-right',
'icon' => 'process-icon-next',
'js' => '$(this).val(\'1\')',
),
),
);
$this->submit_action = 'generateLabel';
$this->show_toolbar = false;
$this->show_form_cancel_button = false;
return parent::renderForm();
}
/**
* Construction du formulaire de recherche de commande unitaire
*/
public function initFormShopReturn($new_statuses)
{
$label_type_query = array();
if (Configuration::get('GLS_API_SHOP_RETURN_SERVICE')) {
$label_type_query = array(
array('id' => 'return', 'name' => $this->l('Return')),
array('id' => 'shipment', 'name' => $this->l('Shipment'))
);
} else {
$label_type_query = array(
array('id' => 'shipment', 'name' => $this->l('Shipment'))
);
}
$this->fields_value = $this->getConfigFormValues();
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Single delivery label printing'),
'icon' => 'icon-print'
),
'description' => $this->l('Generate your GLS shipping labels for a single order by searching for its ID or reference.'),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Label type'),
'name' => 'GLS_LABEL_SINGLE_TYPE',
'require' => true,
'options' => array(
'query' => $label_type_query,
'id' => 'id',
'name' => 'name'
)
),
array(
'type' => 'text',
'label' => $this->l('Order ID'),
'lang' => false,
'name' => 'GLS_LABEL_ORDER_ID',
'class' => 'input fixed-width-xl',
),
array(
'type' => 'text',
'label' => $this->l('Order reference'),
'lang' => false,
'name' => 'GLS_LABEL_ORDER_REF',
'class' => 'input fixed-width-xl',
),
array(
'type' => 'select',
'label' => $this->l('Change order status to'),
'name' => 'GLS_LABEL_SINGLE_NEW_ORDER_STATE',
'require' => false,
'options' => array(
'query' => $new_statuses,
'id' => 'id_option',
'name' => 'name'
)
),
),
'buttons' => array(
0 => array(
'type' => 'submit',
'title' => $this->l('Next'),
'id' => 'generateLabelStep3',
'name' => 'generateLabelStep3',
'class' => 'pull-right',
'icon' => 'process-icon-next',
'js' => '$(this).val(\'1\')',
),
),
);
$this->submit_action = 'generateLabel';
$this->show_toolbar = false;
$this->show_form_cancel_button = false;
return parent::renderForm();
}
/**
* Return orders filtered
* @param array $_orders
*/
private function getOrders()
{
$sql = new DbQuery();
$sql->select('o.*,
CONCAT(LEFT(c.`firstname`, 1), \'. \', c.`lastname`) AS `customer`,
osl.`name` AS `osname`,
os.`color`,
ca.`name` AS `caname`,
a.`id_country`,
oc.`weight` as `order_weight`,
IF(gls.`customer_phone_mobile` IS NOT NULL AND gls.`customer_phone_mobile` != \'\', gls.`customer_phone_mobile`, a.`phone_mobile`) AS `customer_phone_mobile`,
a.`phone` AS `customer_phone`,
c.`email` as `customer_email`')
->from('orders', 'o')
->leftJoin('gls_cart_carrier', 'gls', 'gls.`id_cart` = o.`id_cart` AND gls.`id_customer` = o.`id_customer`')
->leftJoin('customer', 'c', 'c.`id_customer` = o.`id_customer`')
->leftJoin('order_carrier', 'oc', 'o.`id_order` = oc.`id_order`')
->leftJoin('carrier', 'ca', 'o.`id_carrier` = ca.`id_carrier`')
->leftJoin('order_state', 'os', 'os.`id_order_state` = o.`current_state`')
->leftJoin('order_state_lang', 'osl', 'os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)$this->context->language->id)
->leftJoin('address', 'a', 'a.`id_address` = o.`id_address_delivery`')
->where('ca.id_carrier IS NOT NULL')
->orderBy('o.id_order ASC');
if (Shop::isFeatureActive() && Shop::getContextShopID()) {
$sql->where('o.id_shop = '.Shop::getContextShopID());
}
if (Tools::getIsset('orderBox') && is_array(Tools::getValue('orderBox')) && count(Tools::getValue('orderBox')) > 0) {
$sql->where('o.`id_order` IN ('.implode(',', array_map('intval', Tools::getValue('orderBox'))).')');
} elseif (Tools::getIsset('GLS_LABEL_ORDER_ID') && (int)Tools::getValue('GLS_LABEL_ORDER_ID') > 0) {
$sql->where('o.`id_order` = '.(int)Tools::getValue('GLS_LABEL_ORDER_ID'));
// Etiquette de retour seule limité à la France
if (Tools::getIsset('GLS_LABEL_SINGLE_TYPE') && Tools::getValue('GLS_LABEL_SINGLE_TYPE') == 'return') {
$sql->where('a.`id_country` = '.(int)Country::getByIso('FR'));
}
} elseif (Tools::getIsset('GLS_LABEL_ORDER_REF') && !Tools::isEmpty(Tools::getValue('GLS_LABEL_ORDER_REF'))) {
$sql->where('o.`reference` = \''.pSQL(Tools::getValue('GLS_LABEL_ORDER_REF')).'\'');
// Etiquette de retour seule limité à la France
if (Tools::getIsset('GLS_LABEL_SINGLE_TYPE') && Tools::getValue('GLS_LABEL_SINGLE_TYPE') == 'return') {
$sql->where('a.`id_country` = '.(int)Country::getByIso('FR'));
}
} else {
$order_carrier = explode(',', Configuration::get('GLS_LABEL_CARRIER_FILTER'));
// Retrieve carrier_id history
$carriers_id_history = $this->module->getCarrierIdHistory();
foreach ($carriers_id_history as $value) {
foreach ($order_carrier as $c) {
if (is_array($value) && in_array($c, $value)) {
$order_carrier = array_merge($order_carrier, $value);
}
}
}
if (is_array($order_carrier) && count($order_carrier) > 0) {
$sql->where('ca.`id_carrier` IN ('.implode(',', array_map('intval', $order_carrier)).')');
}
$sql->where('o.current_state IN ('.Configuration::get('GLS_LABEL_ORDER_STATE_FILTER').')');
}
return Db::getInstance()->ExecuteS($sql);
}
/**
* Etape 2 de sélection des commandes filtrées
*/
public function initFormLabelStep2()
{
$order_state = array();
if (Configuration::get('GLS_LABEL_ORDER_STATE_FILTER')) {
$order_state = explode(',', Configuration::get('GLS_LABEL_ORDER_STATE_FILTER'));
}
$order_carrier = array();
if (Configuration::get('GLS_LABEL_CARRIER_FILTER')) {
$order_carrier = explode(',', Configuration::get('GLS_LABEL_CARRIER_FILTER'));
}
if (is_array($order_state)
&& count($order_state) > 0
&& is_array($order_carrier)
&& count($order_carrier) > 0
) {
foreach ($this->order_state as $status) {
$this->statuses_array[$status['id_order_state']] = $status['name'];
}
$data_order = $this->getOrders();
if (!empty($data_order)) {
$this->fields_list = array(
'id_order' => array(
'title' => $this->trans('ID', array(), 'Admin.Global'),
'align' => 'text-center',
'class' => 'fixed-width-xs',
),
'reference' => array(
'title' => $this->trans('Reference', array(), 'Admin.Global')
),
'customer' => array(
'title' => $this->trans('Customer', array(), 'Admin.Global'),
'havingFilter' => true,
),
'total_paid_tax_incl' => array(
'title' => $this->trans('Total', array(), 'Admin.Global'),
'align' => 'text-right',
'type' => 'price',
'currency' => true,
'badge_success' => true
),
'payment' => array(
'title' => $this->trans('Payment', array(), 'Admin.Global')
),
'osname' => array(
'title' => $this->trans('Status', array(), 'Admin.Global'),
'type' => 'select',
'color' => 'color',
'list' => $this->statuses_array,
'filter_key' => 'os!id_order_state',
'filter_type' => 'int',
'order_key' => 'osname'
),
'date_add' => array(
'title' => $this->trans('Date', array(), 'Admin.Global'),
'type' => 'datetime',
'filter_key' => 'a!date_add'
),
'caname' => array(
'title' => $this->l('Carrier'),
),
);
$helper = new HelperList();
// Step 3 : use another template
$helper->module = $this->module;
$helper->identifier = 'id_order';
$helper->shopLinkType = '';
$helper->simple_header = true;
$helper->show_toolbar = true;
$helper->bulk_actions = true;
$helper->force_show_bulk_actions = true;
$helper->no_link = true;
$helper->title = $this->l('Orders');
$helper->table = 'order';
$helper->token = Tools::getAdminTokenLite('Admin'.$this->name);
$helper->currentIndex = $this->context->link->getAdminLink('Admin'.$this->name);
return $helper->generateList($data_order, $this->fields_list);
}
}
$this->errors[] = $this->l('No orders has been found, please check your search filters.');
}
/**
* Formulaire permettant l'impression des étiquettes
*/
public function initFormLabelStep3()
{
$tpl = $this->createTemplate('label_list.tpl');
$data_order = $this->getOrders();
if (!empty($data_order)) {
// Récupération des ID des pays membre de la zone euro
$sql = new DbQuery();
$sql->select('GROUP_CONCAT(c.`id_country` SEPARATOR \',\') AS `countries`')
->from('country', 'c')
->where("c.`iso_code` IN ('DE','AT','BE','CY','ES','EE','FI','FR','GR','IE','IT','LV','LT','LU','MT','NL','PT','SK','SI','CZ','RO','BG','GB','HR','HU','DK','PL','SE')");
$result = Db::getInstance()->getRow($sql);
$glsCarriersIds = $this->module->getCarrierIdHistory();
$gls_mobile_required = array();
foreach ($glsCarriersIds as $key => $value) {
if ($key != 'GLSCHEZVOUS') {
$gls_mobile_required = array_merge($gls_mobile_required, $value);
}
}
$data = array(
'list' => $data_order,
'carriers' => $this->carrier,
'cee_countries' => explode(',', $result['countries']),
'shop_return_service' => Configuration::get('GLS_API_SHOP_RETURN_SERVICE'),
'gls_mobile_required' => $gls_mobile_required,
'gls_carriers_ids' => $glsCarriersIds,
'back_step2_url' => $this->context->link->getAdminLink('Admin'.$this->name),
'gls_label_single_type' => Tools::getValue('GLS_LABEL_SINGLE_TYPE', ''),
);
$tpl->assign($data);
return $tpl->fetch();
} else {
$this->errors[] = $this->l('No orders has been found, please check your search filters.');
return false;
}
}
public function initToolbarTitle()
{
$this->toolbar_title = $this->l('GLS delivery label');
}
public function postProcess()
{
if ((bool)Tools::isSubmit('generateLabelStep2') === true) {
/**
* Save configuration
*/
$form_values = $this->getConfigFormValues();
foreach ($form_values as $key => $value) {
if (strpos($key, 'GLS_LABEL_ORDER_STATE_FILTER') === false && strpos($key, 'GLS_LABEL_CARRIER_FILTER') === false) {
Configuration::updateValue($key, trim($value));
}
}
$order_state_selected = array();
foreach ($this->order_state as $value) {
if (Tools::getValue('GLS_LABEL_ORDER_STATE_FILTER_'.$value['id_order_state'])) {
$order_state_selected[] = $value['id_order_state'];
}
}
Configuration::updateValue('GLS_LABEL_ORDER_STATE_FILTER', implode(',', array_map('intval', $order_state_selected)));
if (count($order_state_selected) <= 0) {
$this->errors[] = $this->l('Please select one or more order status.');
}
$carrier_selected = array();
foreach ($this->carrier as $value) {
if (Tools::getValue('GLS_LABEL_CARRIER_FILTER_'.$value['id_carrier'])) {
$carrier_selected[] = $value['id_carrier'];
}
}
Configuration::updateValue('GLS_LABEL_CARRIER_FILTER', implode(',', array_map('intval', $carrier_selected)));
if (count($carrier_selected) <= 0) {
$this->errors[] = $this->l('Please select one or more carrier.');
}
} elseif ((bool)Tools::isSubmit('generateLabelStep3') === true) {
if (Tools::getIsset('orderBox') && (
!is_array(Tools::getValue('orderBox'))
|| (is_array(Tools::getValue('orderBox')) && count(Tools::getValue('orderBox')) <= 0))
) {
$this->errors[] = $this->l('Please select at least one order.');
} elseif (Tools::getIsset('GLS_LABEL_ORDER_ID') && Tools::getIsset('GLS_LABEL_ORDER_REF')) {
Configuration::updateValue('GLS_LABEL_SINGLE_NEW_ORDER_STATE', (int)Tools::getValue('GLS_LABEL_SINGLE_NEW_ORDER_STATE'));
if ((int)Tools::getValue('GLS_LABEL_ORDER_ID') <= 0 && Tools::isEmpty(Tools::getValue('GLS_LABEL_ORDER_REF'))) {
$this->errors[] = $this->l('No order has been found.');
}
} elseif (Tools::getIsset('orderBox') !== true
&& Tools::getIsset('GLS_LABEL_ORDER_ID') !== true
&& Tools::getIsset('GLS_LABEL_ORDER_REF') !== true
) {
$this->errors[] = $this->l('An error occured, please try again.');
}
}
return parent::postProcess();
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addCSS(_PS_MODULE_DIR_.$this->module->name.'/views/css/admin-order.css');
Media::addJsDef(array(
'back_url' => $this->context->link->getAdminLink('Admin'.$this->name),
'print_block' => $this->l('Fill in the order informations before you can print the associated label'),
'print_ready' => $this->l('Print label'),
'ajax_uri' => $this->context->link->getAdminLink('Admin'.$this->name).'&ajax=1&action=generateLabel',
'carrier_disabled' => $this->l('Disabled'),
));
$this->addJs(_PS_MODULE_DIR_.$this->module->name.'/views/js/admin-label.js');
}
public function ajaxProcessGenerateLabel()
{
$module_config = $this->module->getConfigFormValues();
$return = array(
'hasError' => false,
'errors' => '',
'data' => '',
);
$api = new GlsApi($module_config['GLS_API_LOGIN'], $module_config['GLS_API_PWD'], $this->context->language->iso_code);
if ($api) {
if ((int)Tools::getValue('order') > 0
&& Validate::isLoadedObject($order = new Order(Tools::getValue('order')))) {
$customer = new Customer($order->id_customer);
$id_carrier = $order->id_carrier;
$gls_service = Tools::getValue('gls_service', $id_carrier);
if ((int)$gls_service != (int)$order->id_carrier) {
$id_carrier = (int)$gls_service;
}
$carriers_id_history = $this->module->getCarrierIdHistory();
$is_gls_relais = false;
$is_chezvousplus = false;
if (isset($carriers_id_history['GLSRELAIS']) && in_array($id_carrier, $carriers_id_history['GLSRELAIS'])) {
$is_gls_relais = true;
} elseif (isset($carriers_id_history['GLSCHEZVOUSPLUS']) && in_array($id_carrier, $carriers_id_history['GLSCHEZVOUSPLUS'])) {
$is_chezvousplus = true;
}
// Customer address
$customer_address = new Address($order->id_address_delivery);
// Customer invoice address
$customer_invoice_address = new Address($order->id_address_invoice);
// Shop address
if ($module_config['GLS_API_SHOP_RETURN_ADDRESS']) {
$shop_address = $this->context->shop->getAddress();
} else {
$shop_address = new Address();
$shop_address->company = Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_NAME');
$shop_address->id_country = Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_COUNTRY');
$shop_address->address1 = Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_ADDRESS1');
$shop_address->address2 = Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_ADDRESS2');
$shop_address->postcode = Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_POSTCODE');
$shop_address->city = Configuration::get('GLS_API_SHOP_RETURN_ADDRESS_CITY');
}
if (Tools::getValue('gls_label_single_type') == 'return' || Tools::getValue('gls_label_single_type') == 'return_shipment') {
$delivery_adresses = $shop_address;
if ($is_gls_relais) {
$customer_address = $customer_invoice_address;
}
} else {
$delivery_adresses = $customer_address;
}
$delivery_country_iso = Country::getIsoById($delivery_adresses->id_country);
$customer_country_iso = Country::getIsoById($customer_address->id_country);
if (!empty($delivery_adresses->company)) {
$delivery_name = Tools::strtoupper(nkmStripAccents($delivery_adresses->company));
} else {
$delivery_name = Tools::strtoupper(nkmStripAccents($delivery_adresses->firstname.' '.$delivery_adresses->lastname));
}
if ($delivery_country_iso == 'IE') {
// TODO récupérer la province ? pas trouvé d'info sur une config de base de prestashop (états désactivés)
}
// Récupération du mobile depuis la table GLS
$query = new DbQuery();
$query->select('c.*')
->from('gls_cart_carrier', 'c')
->where('c.`id_customer` = '.(int)$order->id_customer)
->where('c.`id_cart` = '.(int)$order->id_cart);
$cart_carrier_detail = Db::getInstance()->getRow($query);
// CONTACTMOBILE
if (Tools::getValue('mobile')) {
$customer_mobile = preg_replace('/[^0-9\+]/', '', Tools::getValue('mobile'));
} elseif (!empty($cart_carrier_detail['customer_phone_mobile'])) {
$customer_mobile = preg_replace('/[^0-9\+]/', '', $cart_carrier_detail['customer_phone_mobile']);
} else {
$customer_mobile = preg_replace('/[^0-9\+]/', '', $customer_address->phone_mobile);
}
//__ limitation à 35 caractères
$tab_adresse = nkmCutSentenceMulti($delivery_adresses->address1, 35);
$data = array(
'shipperId' => $module_config['GLS_API_CUSTOMER_ID'].' '.$module_config['GLS_API_CONTACT_ID'],
'references' => array(
Tools::substr(Tools::getValue('reference1'), 0, 20),
Tools::substr(Tools::getValue('reference2'), 0, 20)
),
'addresses' => array(
'delivery' => array(
'name1' => Tools::substr($delivery_name, 0, 35),
'street1' => Tools::strtoupper(nkmStripAccents($tab_adresse[0])),
'country' => $delivery_country_iso,
'zipCode' => $delivery_adresses->postcode,
'city' => Tools::substr(Tools::strtoupper(nkmStripAccents($delivery_adresses->city)), 0, 35),
),
),
'labelSize' => $module_config['GLS_API_DELIVERY_LABEL_FORMAT'],
);
if (isset($tab_adresse[1])) {
// STREET2
$data['addresses']['delivery']['name2'] = Tools::strtoupper(nkmStripAccents($tab_adresse[1]));
// STREET3
$data['addresses']['delivery']['name3'] = Tools::substr(Tools::strtoupper(nkmStripAccents($delivery_adresses->address2)), 0, 35);
} else {
// STREET2
$data['addresses']['delivery']['name2'] = Tools::substr(Tools::strtoupper(nkmStripAccents($delivery_adresses->address2)), 0, 35);
}
// Shipment date
if (Tools::getValue('delivery_date')) {
$data['shipmentDate'] = Tools::getValue('delivery_date');
}
// Incoterm
if (Tools::getValue('incoterm')) {
$data['addresses']['delivery']['incoterm'] = Tools::getValue('incoterm');
}
// Single return label
if (Tools::getValue('gls_label_single_type') == 'return' || Tools::getValue('gls_label_single_type') == 'return_shipment') {
if (!empty($customer_address->company)) {
$customer_name = Tools::strtoupper(nkmStripAccents($customer_address->company));
} else {
$customer_name = Tools::strtoupper(nkmStripAccents($customer_address->firstname.' '.$customer_address->lastname));
}
//__ limitation à 35 caractères
$tab_adresse = nkmCutSentenceMulti($customer_address->address1, 35);
// cutomer address = pickup address
$data['addresses']['pickup'] = array(
'id' => $customer_address->id,
'name1' => Tools::substr($customer_name, 0, 35),
'street1' => Tools::strtoupper(nkmStripAccents($tab_adresse[0])),
'country' => $customer_country_iso,
'zipCode' => $customer_address->postcode,
'city' => Tools::substr(Tools::strtoupper(nkmStripAccents($customer_address->city)), 0, 35),
'email' => $customer->email,
'phone' => preg_replace('/[^0-9\+]/', '', $customer_address->phone),
'mobile' => $customer_mobile,
);
if (isset($tab_adresse[1])) {
// STREET2
$data['addresses']['pickup']['name2'] = Tools::strtoupper(nkmStripAccents($tab_adresse[1]));
// STREET3
$data['addresses']['pickup']['name3'] = Tools::substr(Tools::strtoupper(nkmStripAccents($customer_address->address2)), 0, 35);
} else {
// STREET2
$data['addresses']['pickup']['name2'] = Tools::substr(Tools::strtoupper(nkmStripAccents($customer_address->address2)), 0, 35);
}
} else {
// Informations supplémentaire sur l'adresse de livraison si ce n'est pas une etiquette de retour seule
$data['addresses']['delivery']['id'] = $delivery_adresses->id;
$data['addresses']['delivery']['email'] = $customer->email;
$data['addresses']['delivery']['phone'] = preg_replace('/[^0-9\+]/', '', $customer_address->phone);
$data['addresses']['delivery']['mobile'] = $customer_mobile;
}
/**
* Etiquette de retour dans le cadre d'une expédition aller/retour en simultanée
* Limité au service "GLS chez vous"
* Pour les services "GLS chez vous +" et "GLS Point Relais" prévoir une 2ème requête API
*/
$return_label = false;
if (Tools::getValue('return_label') && !$is_gls_relais && !$is_chezvousplus) {
$return_label = true;
//__ limitation à 35 caractères
$tab_adresse = nkmCutSentenceMulti($shop_address->address1, 35);
$data['addresses']['return'] = array(
'name1' => Tools::substr($shop_address->company, 0, 35),
'street1' => Tools::strtoupper(nkmStripAccents($tab_adresse[0])),
'country' => Country::getIsoById($shop_address->id_country),
'zipCode' => $shop_address->postcode,
'city' => Tools::substr(Tools::strtoupper(nkmStripAccents($shop_address->city)), 0, 35),
);
if (isset($tab_adresse[1])) {
// STREET2
$data['addresses']['return']['name2'] = Tools::strtoupper(nkmStripAccents($tab_adresse[1]));
// STREET3
$data['addresses']['return']['name3'] = Tools::substr(Tools::strtoupper(nkmStripAccents($shop_address->address2)), 0, 35);
} else {
// STREET2
$data['addresses']['return']['name2'] = Tools::substr(Tools::strtoupper(nkmStripAccents($shop_address->address2)), 0, 35);
}
}
// Permet l'affichage du bon service dans les parcels
if (Tools::getValue('gls_label_single_type') == 'return' || Tools::getValue('gls_label_single_type') == 'return_shipment') {
$return_label = true;
}
if (!$return_label) {
$data['addresses']['delivery']['contact'] = Tools::substr(Tools::strtoupper(nkmStripAccents($customer_address->firstname.' '.$customer_address->lastname)), 0, 35);
}
$parcels = array();
$parcels_return = array();
foreach (Tools::getValue('weight') as $key => $value) {
if (is_numeric($value) && !empty($value)) {
$tmp = array(
'weight' => (float)str_replace(',', '.', $value),
);
if ($return_label) {
$service_detail = array('name' => 'shopreturnservice');
//__ Gestion du retour seul
//__ TODO: exclure l'aller/retour de ce foreach pour renseigner uniquement 1 poids global sur 1 colis ??
if (Tools::getValue('gls_label_single_type') == 'return' || Tools::getValue('gls_label_single_type') == 'return_shipment') {
$shopreturn_infos = array();
$shopreturn_infos[] = array('name' => 'returnonly', 'value' => 'Y');
$service_detail['infos'] = $shopreturn_infos;
} else {
// Pas de return pour un retour seul
array_push($parcels_return, $tmp);
}
$tmp['services'] = array();
array_push($tmp['services'], $service_detail);
} elseif ($is_gls_relais) {
$relais_infos = array();
$relais_infos[] = array('name' => 'parcelshopid', 'value' => $cart_carrier_detail['parcel_shop_id']);
$tmp['services'] = array();
array_push($tmp['services'], array(
'name' => 'shopDeliveryService',
'infos' => $relais_infos,
));
} elseif ($is_chezvousplus) {
$tmp['services'] = array();
array_push($tmp['services'], array(
'name' => 'flexDeliveryService',
));
}
array_push($parcels, $tmp);
} else {
$return['hasError'] = true;
$return['errors'] = sprintf($this->l('Wrong weight on package #%s'), $key+1);
break;
}
}
$data['parcels'] = $parcels;
if (is_array($parcels_return) && count($parcels_return) > 0) {
$data['returns'] = $parcels_return;
}
if (!$return['hasError']) {
$result = $api->post('shipments', $data);
if ($result === false) {
$return['hasError'] = true;
$return['errors'] = '';
foreach ($api->error as $error) {
if (!empty($return['errors'])) {
$return['errors'] .= "\r\n";
}
if (is_array($error) && isset($error['message'])) {
$return['errors'] .= $error['message'] . ' - ' . $this->l('Error code:') . ' ' . $error['code'];
} else {
$return['errors'] .= $error;
}
}
} else {
/**
* récupération de l'étiquette pour envoi en impression
*/
$id_order_carrier = $order->getIdOrderCarrier();
$old_tracking_number = $order->shipping_number;
$shippingNumbers = array();
if (!empty($old_tracking_number)) {
$shippingNumbers = explode(',', $old_tracking_number);
}
if (isset($result->parcels) && is_array($result->parcels) && count($result->parcels) > 0) {
foreach ($result->parcels as $p) {
$shippingNumbers[] = $p->trackId;
}
// Récupération des trackID de retour
if (isset($result->returns) && is_array($result->returns) && count($result->returns) > 0) {
foreach ($result->returns as $p) {
$shippingNumbers[] = $p->trackId;
}
}
$tracking_number = implode(',', $shippingNumbers);
// si aucun tracking url de défini sur le transporteur récupérer celui par défaut du module
if (!isset($this->verifyTrackingUrl[$id_carrier])) {
if (Validate::isLoadedObject($carrier = new Carrier($id_carrier))) {
$this->verifyTrackingUrl[$id_carrier] = true;
if (empty($carrier->url)) {
$carrier->url = pSQL(NkmGls::$trackingUrl);
$carrier->update();
}
}
}
$order_carrier = new OrderCarrier($id_order_carrier);
if (!Validate::isLoadedObject($order_carrier)) {
$return['hasError'] = true;
$return['errors'] = $this->l('The order carrier ID is invalid.');
} else {
// Keep these two following lines for backward compatibility, remove on 1.6 version
$order->shipping_number = pSQL($tracking_number);
$order->update();
// lien de suivi tous les colis : $data['location']
// Update order_carrier
$order_carrier->tracking_number = pSQL($tracking_number);
if (!$order_carrier->update()) {
$return['hasError'] = true;
$return['errors'] = $this->l('The order carrier cannot be updated.');
}
}
} else {
$return['hasError'] = true;
$return['errors'] = $this->l('An error occured , please contact technical support.');
}
if (!$return['hasError']) {
if (Tools::getValue('gls_label_single_type') == 'return' || Tools::getValue('gls_label_single_type') == 'shipment') {
$new_order_state = (int)Configuration::get('GLS_LABEL_SINGLE_NEW_ORDER_STATE');
} else {
$new_order_state = (int)Configuration::get('GLS_LABEL_NEW_ORDER_STATE');
}
/**
* update order status
*/
if ($new_order_state > 0 && $new_order_state != (int)$order->current_state) {
$order->setCurrentState($new_order_state, (int)$this->context->employee->id);
// Pas d'email de livraison dans le cadre d'un retour seul
if (Tools::getValue('gls_label_single_type') != 'return' && Tools::getValue('gls_label_single_type') != 'return_shipment') {
if (!$this->module->sendInTransitEmail($order_carrier, $order, $id_carrier)) {
$return['hasError'] = true;
$return['errors'] = $this->l('An error occurred while sending an email to the customer.');
}
}
}
/**
* Email de notification suite à la génération d'une étiquette de retour seule si option activée
*/
if (Tools::getValue('gls_label_single_type') == 'return'
&& Configuration::get('GLS_API_SHOP_RETURN_EMAIL_ALERT')
&& isset($result->location)
&& !empty($result->location)
&& isset($result->labels)
&& is_array($result->labels)
&& count($result->labels) > 0
) {
$data = array(
'{lastname}' => $customer->lastname,
'{firstname}' => $customer->firstname,
'{followup}' => $result->location,
'{order_name}' => $order->reference
);
$file_attachment = array();
$i = 0;
foreach ($result->labels as $label) {
$i++;
$file_attachment[] = array(
'name' => $order->reference.'-return'.$i.'.pdf',
'content' => base64_decode($label),
'mime' => 'application/pdf',
);
}
if (!Mail::Send(
(int)$customer->id_lang,
'gls_label_return',
$this->l('Your order return request has been accepted'),
$data,
$customer->email,
$customer->firstname.' '.$customer->lastname,
null,
null,
$file_attachment,
null,
$this->module->getLocalPath().'mails/'
)) {
$return['hasError'] = true;
$return['errors'] = $this->l('An error occurred while sending the return confirtmation email to the customer.');
}
}
$return['data'] = $result;
}
}
}
die(json_encode($return));
} else {
// TODO : gestion d'erreur : bad order id
}
} else {
// TODO : gestion d'erreur : api connection error
}
return false;
}
}