2017-08-30 11:37:48 +02:00

1525 lines
62 KiB
PHP

<?php
/**
* TNT OFFICIAL MODULE FOR PRESTASHOP.
*
* @author GFI Informatique <www.gfi.fr>
* @copyright 2016-2017 GFI Informatique, 2016-2017 TNT
* @license https://opensource.org/licenses/MIT MIT License
*/
if (!defined('_PS_VERSION_')) {
exit;
}
require_once _PS_MODULE_DIR_.'tntofficiel/classes/TNTOfficielCart.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_JsonRPCClient.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_DbUtils.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_PasswordManager.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_Logger.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_Install.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_Debug.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_Carrier.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_Cart.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_Address.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/helper/TNTOfficiel_CarrierHelper.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/helper/TNTOfficiel_AddressHelper.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/helper/TNTOfficiel_RelayPointsHelper.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/helper/TNTOfficiel_ParcelsHelper.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/helper/TNTOfficiel_OrderHelper.php';
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/helper/TNTOfficiel_ShipmentHelper.php';
/**
* Class TNTOfficiel.
*/
class TNTOfficiel extends CarrierModule
{
/**
* Module name identifier.
*/
const MODULE_NAME = 'tntofficiel';
const LOG_DIR = 'log/';
/**
* The directory where the BT are stored.
*/
const TNT_MEDIA_BT_DIR = 'tnt_media/media/bt/';
const TNT_MEDIA_DIR = 'tnt_media/media/';
const TNT_DIR = 'tnt_media/';
/** @var TNTOfficiel_Logger */
private $logger;
public static $arrSmartyFunctions = array(
'tnt_shipping_method_get_schedules' => 'TNTOfficiel_ShippingMethodSmartyFunction::getSchedules',
'tnt_order_get_data' => 'TNTOfficiel_OrderSmartyFunction::getTntOrder',
);
/**
* Reserved by Cart Model.
* Set when retrieving shipping cost from module.
* @var null
*/
public $id_carrier = null;
/**
* TNTOfficiel constructor.
*/
public function __construct()
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
// Bootstrap activated.
$this->bootstrap = true;
// Version.
$this->version = '1.2.21';
// Prestashop supported version.
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => '1.6');
// Prestashop modules dependencies.
$this->dependencies = array();
// Name.
$this->name = 'tntofficiel'; // TNTOfficiel::MODULE_NAME;
// Displayed Name.
$this->displayName = $this->l('TNT Express France');
// Description.
$this->description = $this->l('Offer your customers, different delivery methods with TNT');
// Confirmation message before uninstall.
//$this->confirmUninstall = $this->l( 'Êtes-vous sûre de vouloir supprimer ce module ?' );
// Author.
$this->author = 'Gfi Informatique';
// Module key provided by addons.prestashop.com.
//$this->module_key = '';
// Is this instance required on module when it is displayed in the module list.
// This can be useful if the module has to perform checks on the PrestaShop configuration,
// and display warning message accordingly.
$this->need_instance = 0;
// Type.
$this->tab = 'shipping_logistics';
// Module Constructor.
parent::__construct();
// Logger.
$this->logger = new TNTOfficiel_Logger();
TNTOfficiel_Carrier::forceGlobalCarrierDefaultValues();
}
/**
* Performs installation checks.
*
* @return bool
*/
public function install()
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
// If MultiShop and more than 1 Shop.
if (Shop::isFeatureActive()) {
// Define Shop context to all Shops.
Shop::setContext(Shop::CONTEXT_ALL);
}
$this->logger->logInstall('Starting TNT module install');
if (!parent::install()) {
$this->logger->logInstall('parent::install KO');
$this->_errors[] = Tools::displayError('Parent::install KO');
return false;
}
$this->logger->logInstall('parent::install OK');
// Update settings.
if (!TNTOfficiel_Install::updateSettings()) {
$this->logger->logInstall('updateSettings KO');
$this->_errors[] = Tools::displayError('Impossible de définir la configuration');
return false;
}
$this->logger->logInstall('updateSettings OK');
// Register hooks.
foreach (TNTOfficiel_Install::$arrHookList as $strHookName) {
if (!$this->registerHook($strHookName)) {
$this->logger->logInstall('register hook '.$strHookName.' KO');
$this->_errors[] = Tools::displayError(sprintf('Impossible d\'inscrire le hook "%s".', $strHookName));
return false;
}
}
$this->logger->logInstall('register hooks OK');
// Create the TNT tab.
$arrTabNameLang = array(
(int)(Configuration::get('PS_LANG_DEFAULT')) => $this->l('TNT')
);
if (!TNTOfficiel_Install::createTab($arrTabNameLang)) {
$this->logger->logInstall('create tab KO');
$this->_errors[] = Tools::displayError('Impossible d\'ajouter l\'onglet du menu.');
return false;
}
$this->logger->logInstall('create tab OK');
// Create the tables.
if (!TNTOfficiel_Install::createTables()) {
$this->logger->logInstall('create database tables KO');
$this->_errors[] = Tools::displayError('Impossible de créer les tables de la base de donnée.');
return false;
}
$this->logger->logInstall('create database tables OK');
// Create the TNT carrier.
if (!TNTOfficiel_Install::installCarrier()) {
$this->logger->logInstall('install carrier KO');
$this->_errors[] = Tools::displayError('Impossible d\'installer le transporteur.');
return false;
}
$this->logger->logInstall('install carrier OK');
// Override templates.
$arrErrors = TNTOfficiel_Install::overrideTemplates($this->getLocalPath());
if (count($arrErrors) > 0) {
$this->logger->logInstall('override templates KO');
$this->_errors += $arrErrors;
return false;
}
$this->logger->logInstall('override templates OK');
// Create directories.
if (!TNTOfficiel_Install::makeModuleDir(
array(TNTOfficiel::TNT_DIR, TNTOfficiel::TNT_MEDIA_DIR, TNTOfficiel::TNT_MEDIA_BT_DIR)
)) {
$this->logger->logInstall('create directories KO');
$this->_errors[] = Tools::displayError('Impossible de créer les dossiers.');
return false;
}
$this->logger->logInstall('create directories OK');
$this->logger->logInstall('TNT module installation complete');
return true;
}
/**
* Performs uninstall checks.
*
* @return bool
*/
public function uninstall()
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$this->logger->logUninstall('Starting TNT module uninstall');
// Unoverride templates.
$arrErrors = TNTOfficiel_Install::unOverrideTemplates();
if (count($arrErrors) > 0) {
$this->logger->logUninstall('unoverride templates KO');
$this->_errors += $arrErrors;
return false;
}
$this->logger->logUninstall('unoverride templates OK');
foreach (TNTOfficiel_Install::$arrHookList as $strHookName) {
if (!$this->unregisterHook($strHookName)) {
$this->logger->logUninstall('unregister hook '.$strHookName.' KO');
$this->_errors[] = sprintf(Tools::displayError('Impossible de supprimer le hook "%s"'), $strHookName);
return false;
}
}
$this->logger->logUninstall('Unregister hooks OK');
if (!TNTOfficiel_Install::deleteTab()) {
$this->logger->logUninstall('Delete tab KO');
$this->_errors[] = sprintf(Tools::displayError('Impossible de supprimer l\'onglet du menu'));
return false;
}
$this->logger->logUninstall('Delete tab OK');
if (!TNTOfficiel_Carrier::deleteGlobalCarrier()) {
$this->logger->logUninstall('Delete TNT carrier KO');
$this->_errors[] = sprintf(Tools::displayError('Impossible de désactiver le transporteur'));
return false;
}
$this->logger->logUninstall('Delete TNT carrier OK');
if (!TNTOfficiel_Install::deleteSettings()) {
$this->logger->logUninstall('Delete settings KO');
$this->_errors[] = sprintf(Tools::displayError('Impossible de supprimer la configuration'));
return false;
}
$this->logger->logUninstall('Delete settings OK');
if (!parent::uninstall()) {
$this->logger->logUninstall('Parent::uninstall KO');
$this->_errors[] = sprintf(Tools::displayError('Parent::uninstall KO'));
return false;
}
$this->logger->logUninstall('Parent::uninstall OK');
$this->logger->logUninstall('TNT module uninstall complete');
// TODO: check default carrier is not TNT.
// Configuration::get('PS_CARRIER_DEFAULT')
return true;
}
/**
* Module configuration page. Shows the configure link.
*
* @return string HTML content.
*/
public function getContent()
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$strDisplayErrors = '';
$strDisplayConfirmations = '';
// If form submitted (hidden input submittntofficiel).
if (Tools::isSubmit('submit'.TNTOfficiel::MODULE_NAME)) {
$arrErrors = $this->validateForm();
if (count($arrErrors) === 0) {
$strDisplayConfirmations .= $this->displayConfirmation($this->l('Settings updated'));
} else {
$strDisplayErrors .= $this->displayError($arrErrors);
}
// Validate the TNT credentials.
if (!$this->validateTntCredentials()) {
$strDisplayErrors .= $this->displayError($this->l('tnt credentials error'));
}
}
return $strDisplayErrors.$strDisplayConfirmations.$this->displayForm();
}
/**
* Get the configuration form.
* /modules/<MODULE>/views/templates/admin/_configure/helpers/form/form.tpl
* extends /<ADMIN>/themes/default/template/helpers/form/form.tpl
*
* @return mixed
*/
public function displayForm()
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$objHelperForm = new HelperForm();
// Smarty assign().
$objHelperForm->tpl_vars['tntofficiel'] = array(
'titleImgSrc' => $this->getPathUri().'/views/img/carrier.jpg',
'downloadLogsURL' => $this->context->link->getAdminLink('AdminTNTOfficiel').'&action=downloadLogs',
'TNTCarrierTrad' => $this->l('TNT Carrier'),
'exportLogsTrad' => $this->l('Export logs')
);
// Module using this form.
$objHelperForm->module = $this;
// Controller name.
$objHelperForm->name_controller = TNTOfficiel::MODULE_NAME;
// Token.
$objHelperForm->token = Tools::getAdminTokenLite('AdminModules');
// Form action attribute.
$objHelperForm->currentIndex = AdminController::$currentIndex.'&configure='.TNTOfficiel::MODULE_NAME;
// Get default language.
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
// Language.
$objHelperForm->default_form_language = $default_lang;
$objHelperForm->allow_employee_form_lang = $default_lang;
// Title and toolbar.
$objHelperForm->title = $this->displayName;
// Toolbar is always visible on the top of the screen.
$objHelperForm->toolbar_scroll = true;
// false -> remove toolbar
$objHelperForm->show_toolbar = true;
$objHelperForm->toolbar_btn = array(
'save' => array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex.'&configure='.TNTOfficiel::MODULE_NAME.
'&save'.TNTOfficiel::MODULE_NAME.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list'),
),
);
// Define form fields.
$arrFieldsForm = array(
'fieldset' => array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
//'icon' => 'icon-cogs'
//'icon' => 'icon-briefcase'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('username'),
'name' => 'TNT_CARRIER_USERNAME',
'size' => 80,
'required' => true,
),
array(
'type' => 'text',
'label' => $this->l('account'),
'name' => 'TNT_CARRIER_ACCOUNT',
'size' => 10,
'required' => true,
),
array(
'type' => 'password',
'label' => $this->l('password'),
'name' => 'TNT_CARRIER_PASSWORD',
'size' => 40,
'required' => true,
),
array(
'type' => 'checkbox',
'label' => $this->l('Show pickup number'),
'name' => 'TNT_CARRIER_PICKUP_NUMBER',
'values' => array(
'query' => array(
array(
'id' => 'SHOW',
'name' => '',
'val' => 1,
),
),
'id' => 'id',
'name' => 'name',
),
),
array(
'type' => 'text',
'label' => $this->l('Google Maps API'),
'name' => 'TNT_GOOGLE_MAP_API_KEY',
'size' => 60,
'desc' => "
Il s'agit de la clé d'API pour pouvoir utiliser le service de cartographie de Google Maps.
Après un certain nombre d'utilisations quotidiennes du service, vous devez avoir une clé pour continuer à l'utiliser.
<br />Pour plus d'informations concernant cette clé,
<a target='_blank' href='https://console.developers.google.com/apis/credentials/wizard?api=maps_backend '>
Cliquez ici</a> ou reportez vous à notre manuel d'installation
",
'required' => false,
),
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right',
)/*,
'buttons' => array(
'back' => array(
'title' => $this->l( 'Back to list' ),
'href' => $this->context->link->getAdminLink( 'AdminModules' ),
'icon' => 'process-icon-back'
)
)*/
)
)
);
// Set form values.
$objHelperForm->fields_value = array(
'TNT_CARRIER_USERNAME' => Configuration::get('TNT_CARRIER_USERNAME'),
'TNT_CARRIER_ACCOUNT' => Configuration::get('TNT_CARRIER_ACCOUNT'),
'TNT_CARRIER_ACTIVATED' => Configuration::get('TNT_CARRIER_ACTIVATED'),
'TNT_CARRIER_PICKUP_NUMBER_SHOW' => Configuration::get('TNT_CARRIER_PICKUP_NUMBER_SHOW'),
'TNT_GOOGLE_MAP_API_KEY' => Configuration::get('TNT_GOOGLE_MAP_API_KEY')
);
// Submit ID.
$objHelperForm->submit_action = 'submit'.TNTOfficiel::MODULE_NAME;
// Return generated form.
return $objHelperForm->generateForm($arrFieldsForm);
}
/**
* Validate the configuration form and return error messages.
*/
private function validateForm()
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$arrErrors = array();
$strMyTNTID = pSQL(Tools::getValue('TNT_CARRIER_USERNAME'));
$strAccountNumber = pSQL(Tools::getValue('TNT_CARRIER_ACCOUNT'));
$strMyTNTPassword = pSQL(Tools::getValue('TNT_CARRIER_PASSWORD'));
$boolShowPickupNumber = (bool)pSQL(Tools::getValue('TNT_CARRIER_PICKUP_NUMBER_SHOW'));
$strGMAPAPIKey = pSQL(Tools::getValue('TNT_GOOGLE_MAP_API_KEY'));
if (!$strMyTNTID) {
$arrErrors[] = $this->l('The username is required');
}
if (!$strAccountNumber) {
$arrErrors[] = $this->l('The account is required');
}
if (!$strMyTNTPassword) {
$arrErrors[] = $this->l('The password is required');
}
// If no errors.
if (count($arrErrors) == 0) {
Configuration::updateValue('TNT_CARRIER_USERNAME', pSQL(Tools::getValue('TNT_CARRIER_USERNAME')));
Configuration::updateValue('TNT_CARRIER_ACCOUNT', $strAccountNumber);
Configuration::updateValue('TNT_CARRIER_PICKUP_NUMBER_SHOW', $boolShowPickupNumber);
if ($strMyTNTPassword != '%p#c`Q9,6GSP?U4]e]Zst') {
$strMyTNTEncryptedPassword = TNTOfficiel_PasswordManager::encrypt($strMyTNTPassword);
Configuration::updateValue('TNT_CARRIER_PASSWORD', $strMyTNTEncryptedPassword);
}
Configuration::updateValue('TNT_GOOGLE_MAP_API_KEY', $strGMAPAPIKey);
}
Configuration::updateValue('TNT_CARRIER_ADDRESS_EMAIL', 'customer.email');
Configuration::updateValue('TNT_CARRIER_ADDRESS_PHONE', 'address.phone_mobile');
return $arrErrors;
}
/**
* Call the middleware to check the tnt credentials.
*/
private function validateTntCredentials()
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$client = new TNTOfficiel_JsonRPCClient(Configuration::get('TNT_CARRIER_MIDDLEWARE_URL'));
$params = array(
'merchant' => array(
'identity' => Configuration::get('TNT_CARRIER_USERNAME'),
'password' => TNTOfficiel_PasswordManager::getHash(),
'merchant_number' => Configuration::get('TNT_CARRIER_ACCOUNT'),
),
);
// Disable the module if authentication fail.
try {
$result = $client->execute('isCorrectAuthentication', $params);
$this->logger->logMessageTnt('isCorrectAuthentication', null, 'JSON', true, 'SUCCESS');
} catch (Exception $objException) {
$strStatus = ($objException->getCode() == 500) ? 'FATAL' : 'ERROR';
$strMsg = $objException->getMessage();
$this->logger->logMessageTnt('isCorrectAuthentication', $strMsg, 'JSON', false, $strStatus);
return false;
}
if (!$result['response']) {
Configuration::updateValue('TNT_CARRIER_ACTIVATED', false);
return false;
}
Configuration::updateValue('TNT_CARRIER_ACTIVATED', true);
return true;
}
/**
* HOOK (AKA backOfficeHeader) called between the HEAD tags. Ideal location for adding JavaScript and CSS files.
* Add CSS file to the header in order to display the icon in the Back-Office tab.
*
* @param $arrArgHookParams
*/
public function hookDisplayBackOfficeHeader($arrArgHookParams)
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
//$objHookCookie = $arrArgHookParams['cookie'];
//$objHookCart = $arrArgHookParams['cart'];
$this->smartyRegisterFunctions();
$shippedOrderStateId = Configuration::get('PS_OS_SHIPPING');
$this->smarty->assign(array(
'shippedOrderStateId' => $shippedOrderStateId,
));
TNTOfficiel_Debug::log(array('msg' => '<<', 'file' => __FILE__, 'line' => __LINE__));
}
/**
* HOOK called to include CSS or JS files in the Back-Office header.
*
* @param array $arrArgHookParams
*/
public function hookActionAdminControllerSetMedia($arrArgHookParams)
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
//$objHookCookie = $arrArgHookParams['cookie'];
//$objHookCart = $arrArgHookParams['cart'];
// Controller.
$objController = $this->context->controller;
// Get Controller Name.
//$strCurrentControllerName = get_class($objController);
$objController->addJS($this->getPathUri().'views/js/adminTntOrders.js');
$objController->addCSS($this->getPathUri().'views/css/style.css', 'all');
}
/**
* HOOK (AKA Header) displayed in head tag on Front-Office.
*
* @param array $arrArgHookParams
* @return string
*/
public function hookDisplayHeader($arrArgHookParams)
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
//$objHookCookie = $arrArgHookParams['cookie'];
$objHookCart = $arrArgHookParams['cart'];
$objContext = $this->context;
$objLink = $objContext->link;
$objShop = $objContext->shop;
// Controller.
$objController = $objContext->controller;
// Get Controller Name.
$strCurrentControllerName = get_class($objController);
$this->smartyRegisterFunctions();
// Javascript config.
$arrJSONTNTOfficiel = array(
'timestamp' => microtime(true) * 1000,
'module' => array(
'name' => TNTOfficiel::MODULE_NAME,
'version' => $this->version,
'enabled' => (bool)Configuration::get('TNT_CARRIER_ACTIVATED')
),
'config' => array(
'google' => array(
'map' => array(
'url' => 'https://maps.googleapis.com/maps/api/js',
'data' => array(
'v' => '3.20',
'key' => Configuration::get('TNT_GOOGLE_MAP_API_KEY')
),
'default' => array(
"lat" => 46.227638,
"lng" => 2.213749,
"zoom" => 4
)
)
)
),
'link' => array(
'front' => array(
'shop' => $objShop->getBaseURL(true),
'module' => array(
'boxRelayPoints' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'shippingMethod',
array('action' => 'boxRelayPoints')
),
'boxDropOffPoints' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'shippingMethod',
array('action' => 'boxDropOffPoints')
),
'saveProductInfo' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'shippingMethod',
array('action' => 'saveProductInfo')
),
'saveProductCode' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'shippingMethod',
array('action' => 'saveProductCode')
),
'checkProductCode' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'carrier',
array('action' => 'checkProductCode')
),
'storeProductPrice' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'carrier',
array('action' => 'storeProductPrice')
),
'storeDeliveryInfo' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'address',
array('action' => 'storeDeliveryInfo')
),
'getAddressCities' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'address',
array('action' => 'getCities')
),
'updateAddressDelivery' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'address',
array('action' => 'updateDeliveryAddress')
),
'checkAddressPostcodeCity' => $objLink->getModuleLink(
TNTOfficiel::MODULE_NAME,
'address',
array('action' => 'checkPostcodeCity')
)
),
'page' => array(
'order' => $objLink->getPageLink('order')
)
),
'image' => _MODULE_DIR_.TNTOfficiel::MODULE_NAME.'/views/img/'
),
'carrier' => array(
'id' => (int)TNTOfficiel_Carrier::getGlobalCarrierID()
),
'order' => array(
// Is One Page Checkout.
// $strCurrentControllerName === 'OrderOpcController'
'isOPC' => Configuration::get('PS_ORDER_PROCESS_TYPE') == 1
)
);
// Google Font: Open Sans.
$objController->addCSS('https://fonts.googleapis.com/css?family=Open+Sans:400,700', 'all');
switch ($strCurrentControllerName) {
// Front-Office Address.
case 'AddressController':
// FancyBox required to display form (cp/ville check).
$objController->addJqueryPlugin('fancybox');
$objController->addJS($this->getPathUri().'views/js/address-city-check.js');
break;
// Front-Office Cart Process.
case 'OrderController':
// (int)Tools::getValue('step')
$intOrderStep = (int)$objController->step;
// Fix for undefined constant in PS 1.6.0.5.
$intOrderStepAddresses = (int)(defined('OrderController::STEP_ADDRESSES') ?
OrderController::STEP_ADDRESSES : 1);
$intOrderStepDelivery = (int)(defined('OrderController::STEP_DELIVERY') ?
OrderController::STEP_DELIVERY : 2);
//$intOrderStepPayment = (int)(defined('OrderController::STEP_PAYMENT') ?
// OrderController::STEP_PAYMENT : 3);
if ($intOrderStep == $intOrderStepAddresses) {
// Step 1 : 03. Address.
$objTNTAddressHelper = TNTOfficiel_AddressHelper::getInstance();
$postcodeCityIsValid = $objTNTAddressHelper->checkPostCodeCityForCart($objHookCart);
if (!$postcodeCityIsValid) {
$objController->addJS($this->getPathUri().'views/js/order-city-check.js');
}
} elseif ($intOrderStep == $intOrderStepDelivery) {
// Step 2 : 04. Delivery.
} else {
// No need to load more JS/CSS.
break;
}
// Front-Office Cart Process (OnePageCheckout).
case 'OrderOpcController':
//
$objController->addCSS($this->getPathUri().'views/css/deliveryPointsBox.css', 'all');
// Extra data
$objController->addCSS($this->getPathUri().'views/css/extraAddressData.css', 'all');
// base64_encode, required by deliveryPointsBox.js
$objController->addJS($this->getPathUri().'views/js/lib/kvz/phpjs/url/base64_encode.js');
// base64_decode, required by deliveryPointsBox.js
$objController->addJS($this->getPathUri().'views/js/lib/kvz/phpjs/url/base64_decode.js');
// $.fn.nanoScroller, required by deliveryPointsBox.js
$objController->addJS($this->getPathUri().'views/js/lib/nanoscroller/jquery.nanoscroller.min.js');
$objController->addCSS($this->getPathUri().'views/js/lib/nanoscroller/nanoscroller.css');
// TNTOfficiel_deliveryPointsBox, used in deliveryPointsBox.tpl
$objController->addJS($this->getPathUri().'views/js/deliveryPointsBox.js');
break;
default:
break;
}
$strJSONTNTOfficiel = Tools::jsonEncode($arrJSONTNTOfficiel);
TNTOfficiel_Debug::log(array('trace' => array(), 'dump' => array(
'ajax' => $objController->ajax,
'controller_type' => $objController->controller_type,
'classname' => get_class($objController),
'classfilename' => Dispatcher::getInstance()->getController(),
'js' => $arrJSONTNTOfficiel
)));
return <<<HTML
<script type="text/javascript">
var TNTOfficiel = TNTOfficiel || {};
$.extend( true, TNTOfficiel, $strJSONTNTOfficiel );
</script>
HTML;
}
/**
* HOOK (AKA beforeCarrier) displayed before the carrier list on Front-Office.
* @param type $arrArgHookParams
* @return type
*/
public function hookDisplayBeforeCarrier($arrArgHookParams)
{
TNTOfficiel_Debug::log(array(
'msg' => '>>', 'file' => __FILE__, 'line' => __LINE__, 'dump' => array(
'cookie' => array($arrArgHookParams['cookie']->getName() => $arrArgHookParams['cookie']->getFamily(''))
)
));
//$objHookCookie = $arrArgHookParams['cookie'];
//$objHookCart = $arrArgHookParams['cart'];
//$arrHookCarrierList = $arrArgHookParams['carriers'];
//$arrHookDeliveryOptionList = $arrArgHookParams['delivery_option_list'];
//$arrHookDeliveryOption = $arrArgHookParams['delivery_option'];
//$strHookCarrierChecked = Cart::desintifier($arrArgHookParams['checked']);
return $this->display(__FILE__, 'views/templates/hook/displayBeforeCarrier.tpl');
}
/**
* Callback used to sort carriers by price.
*
* @param $a
* @param $b
* @return bool
*/
private function callbackSortCarriersByPrice($a, $b)
{
if (Configuration::get('PS_CARRIER_DEFAULT_ORDER')) {
return (float)$b['price'] > (float)$a['price'];
}
return (float)$b['price'] < (float)$a['price'];
}
/**
* HOOK (AKA extraCarrier) called after the list of available carriers, during the order process.
* Ideal location to add a carrier, as added by a module.
* Display TNT products during the order process.
*
* 5 Steps :
* global.js:28 ready()
* global.js:428 bindUniform()
* Output of this hook is also applied after a delivery mode selection.
* cart-summary.js:1047 updateExtraCarrier() {"content":"…"} inside #HOOK_EXTRACARRIER_<IDADDRESS>.
*
* OPC :
* order-opc.js:539 updateCarrierSelectionAndGift()
* AJAX: updateCarrierAndGetPayments >>> HOOK: actionCarrierProcess
* cart-summary.js:786 updateCartSummary() {"summary":"…"}
* order-opc.js:315 updatePaymentMethods() {"HOOK_TOP_PAYMENT":"…","HOOK_PAYMENT":"…"}
* order-opc.js:306 updateCarrierList() {"HOOK_BEFORECARRIER":"…"}
* global.js:428 bindUniform()
*
* @param $arrArgHookParams array
* @return mixed
*/
public function hookDisplayCarrierList($arrArgHookParams)
{
TNTOfficiel_Debug::log(array(
'msg' => '>>', 'file' => __FILE__, 'line' => __LINE__, 'dump' => array(
'cookie' => array($arrArgHookParams['cookie']->getName() => $arrArgHookParams['cookie']->getFamily(''))
)
));
// Get current TNT carrier ID.
$intCarrierIDTNT = TNTOfficiel_Carrier::getGlobalCarrierID();
// Load current TNT carrier object.
$objCarrierTNT = TNTOfficiel_Carrier::loadGlobalCarrier();
// If TNT carrier object not available.
if ($objCarrierTNT === null) {
return;
}
$objContext = $this->context;
//$objHookCookie = $arrArgHookParams['cookie'];
$objHookCart = $arrArgHookParams['cart'];
$intCartID = (int)$objHookCart->id;
$objHookAddress = $arrArgHookParams['address'];
// Get available carriers for address.
$arrCartDeliveryOption = $objHookCart->getDeliveryOptionList();
// If current Carrier not available for current Address.
if (!array_key_exists($objHookAddress->id, $arrCartDeliveryOption) ||
!array_key_exists($intCarrierIDTNT.',', $arrCartDeliveryOption[$objHookAddress->id])
) {
// Do nothing.
return;
}
// Get the default values for the extra address data fields
$arrFormCartAddressDefault = TNTOfficiel_Address::getDefaultValues(
$objHookAddress->id,
$objHookCart->id_customer
);
// Check if the city match the postcode in the selected delivery address
$cityPostCodeIsValid = true;
$countryCode = Country::getIsoById($objHookAddress->id_country);
if ($countryCode == 'FR') {
$response = TNTOfficiel_AddressHelper::getInstance()->checkPostcodeCityFromMiddleware(
$objHookAddress->postcode,
$objHookAddress->city,
$objHookCart->id_shop
);
$cityPostCodeIsValid = $response['response'];
}
// Load TNT cart info or create a new one for it's ID.
$objTNTCartModel = TNTOfficielCart::loadCartID($intCartID);
$strTNTProductCode = 0;
$arrCarriers = array();
if ($cityPostCodeIsValid) {
// Get the carriers from the middleware
$arrCarriers = TNTOfficiel_CarrierHelper::getInstance()->getMDWTNTCarrierList($objContext->customer);
if (Validate::isLoadedObject($objTNTCartModel)) {
$strTNTProductCode = $objTNTCartModel->carrier_code;
}
// If core TNT selected, but no virtual TNT mode set.
if ($intCarrierIDTNT == $objHookCart->id_carrier && empty($strTNTProductCode)) {
// Unselect carrier from cart.
$objHookCart->setDeliveryOption(null);
$objHookCart->save();
}
}
// Prevent AJAX bug with carrier id inconsistency.
// AJAX URL : /module/<MODULE>/carrier?action=checkProductCode
$objHookCart->save();
$floatTaxesRate = $objCarrierTNT->getTaxesRate($objHookAddress);
$boolIsFree = TNTOfficiel_Cart::isCartShippingFree($objHookCart);
// Get additional shipping cost for cart.
$fltCartExtraShippingCost = TNTOfficiel_Cart::getCartExtraShippingCost($objHookCart);
if (!empty($arrCarriers) && !empty($arrCarriers['products'])) {
// Sort array by price.
usort($arrCarriers['products'], array($this, 'callbackSortCarriersByPrice'));
// Parse.
foreach ($arrCarriers['products'] as &$arrProduct) {
$fltShippingAmount = ($boolIsFree ? 0 : ($arrProduct['price'] + $fltCartExtraShippingCost));
$arrProduct['total_price_without_tax'] = $fltShippingAmount;
$arrProduct['total_price_with_tax'] = round($fltShippingAmount * (100 + $floatTaxesRate) / 100, 2);
$arrProduct['is_free'] = !($fltShippingAmount > 0);
unset($arrProduct['price']);
}
} else {
$arrCarriers['products'] = array();
}
$arrDeliveryPoint = array();
if (Validate::isLoadedObject($objTNTCartModel)) {
$arrDeliveryPoint = $objTNTCartModel->getDeliveryPoint();
}
$this->smarty->assign(array(
'carriers' => $arrCarriers,
'extraAddressDataValues' => $arrFormCartAddressDefault,
'idAddress' => $objHookAddress->id,
'idTntCarrier' => $intCarrierIDTNT,
'deliveryOption' => $strTNTProductCode,
'current_delivery_option' => unserialize($objHookCart->delivery_option),
'cityPostcodeIsValid' => $cityPostCodeIsValid,
'postcode' => $objHookAddress->postcode,
'deliveryPoint' => $arrDeliveryPoint,
// already set in ParentOrderController, etc.
//'free_shipping' => null,
// already set in FrontController.
//'use_taxes' => (int)Configuration::get('PS_TAX'),
//'priceDisplay' => Product::getTaxCalculationMethod((int)$objHookCookie->id_customer),
//'display_tax_label' => $this->context->country->display_tax_label,
));
return $this->display(__FILE__, 'views/templates/hook/displayCarrierList.tpl');
}
/**
* HOOK (AKA newOrder) called during the new order creation process, right after it has been created.
* Manage parcels.
*
* @param $arrArgHookParams array
* @return bool
*/
public function hookActionValidateOrder($arrArgHookParams)
{
TNTOfficiel_Debug::log(array(
'msg' => '>>', 'file' => __FILE__, 'line' => __LINE__, 'dump' => array(
'cookie' => array($arrArgHookParams['cookie']->getName() => $arrArgHookParams['cookie']->getFamily(''))
)
));
//$objHookCookie = $arrArgHookParams['cookie'];
//$objHookCart = $arrArgHookParams['cart'];
$objHookOrder = $arrArgHookParams['order'];
$intOrderID = (int)$objHookOrder->id;
//$objHookCustomer = $arrArgHookParams['customer'];
//$objHookCurrency = $arrArgHookParams['currency'];
//$objHookOrderStatus = $arrArgHookParams['orderStatus'];
// Obtenir le panier d'une commande.
$objCart = Cart::getCartByOrderId($intOrderID);
// $objCart = new Cart($objHookOrder->id_cart);
$intCartID = (int)$objCart->id;
// Get current TNT carrier ID.
$intCarrierIDTNT = TNTOfficiel_Carrier::getGlobalCarrierID();
// If TNT carrier ID not availaible.
if ($intCarrierIDTNT === null) {
return true;
}
// If cart carrier is not the TNT module carrier.
if ($objCart->id_carrier != $intCarrierIDTNT) {
// Do not have to save this cart.
return true;
}
// Creates parcels for order.
TNTOfficiel_ParcelsHelper::getInstance()->createParcels($objCart, $intOrderID);
$strTNTProductCode = '';
$strTNTProductLabel = '';
$arrDeliveryPoint = array();
// Load TNT cart info or create a new one for it's ID.
$objTNTCartModel = TNTOfficielCart::loadCartID($intCartID);
if (Validate::isLoadedObject($objTNTCartModel)) {
$strTNTProductCode = $objTNTCartModel->carrier_code;
$strTNTProductLabel = $objTNTCartModel->carrier_label;
$arrDeliveryPoint = $objTNTCartModel->getDeliveryPoint();
}
$arrTNTOrder = array(
'id_order' => $intOrderID,
'carrier_code' => pSQL($strTNTProductCode),
'carrier_label' => pSQL($strTNTProductLabel),
);
// Create Address for delivery point.
// J_DEPOT (Dépôt restant) : PEX
// JD_DROPOFFPOINT (En Relais Colis®) : XETT
if (isset($arrDeliveryPoint['pex']) && strpos($strTNTProductCode, 'DEPOT')) {
TNTOfficiel_OrderHelper::createNewAddress($arrDeliveryPoint, $intOrderID);
$arrTNTOrder['carrier_pex'] = pSQL($arrDeliveryPoint['pex']);
} elseif (isset($arrDeliveryPoint['xett']) && strpos($strTNTProductCode, 'DROPOFFPOINT')) {
TNTOfficiel_OrderHelper::createNewAddress($arrDeliveryPoint, $intOrderID);
$arrTNTOrder['carrier_xett'] = pSQL($arrDeliveryPoint['xett']);
}
try {
// Save TNT order.
Db::getInstance()->insert('tntofficiel_order', $arrTNTOrder);
// Load TNT order.
$arrTNTOrder = TNTOfficiel_OrderHelper::getInstance()->getOrderData($intOrderID);
} catch (PrestaShopDatabaseException $objException) {
$objFileLogger = new FileLogger();
$objFileLogger->setFilename(_PS_ROOT_DIR_.'/log/'.date('Ymd').'_tnt_exception.log');
$objFileLogger->logError($objException->getMessage());
return false;
}
$objTNTShipmentHelper = TNTOfficiel_ShipmentHelper::getInstance();
$arrMDWShippingDate = $objTNTShipmentHelper->getShippingDate($intOrderID);
$firstShippingDate = $arrMDWShippingDate['shippingDate'];
//$shippingDatePrepa = $response['shippingDatePrepa'];
$shippingDatePrepa = $arrMDWShippingDate['shippingDate'];
$arrMDWShippingDate = $objTNTShipmentHelper->checkSaveShipmentDate($intOrderID, $shippingDatePrepa);
if (array_key_exists('shippingDate', $arrMDWShippingDate) && array_key_exists('dueDate', $arrMDWShippingDate)) {
Db::getInstance()->update('tntofficiel_order', array(
'shipping_date' => pSQL($arrMDWShippingDate['shippingDate']),
'due_date' => pSQL($arrMDWShippingDate['dueDate']),
'start_date' => pSQL($firstShippingDate)
), 'id_tntofficiel_order = '.(int)$arrTNTOrder['id_tntofficiel_order']);
}
return true;
}
/**
* HOOK (AKA adminOrder) called when the order's details are displayed, below the Client Information block.
* Parcel management for orders with a tnt carrier.
*
* @param $arrArgHookParams array
* @return mixed
*/
public function hookDisplayAdminOrder($arrArgHookParams)
{
TNTOfficiel_Debug::log(array(
'msg' => '>>', 'file' => __FILE__, 'line' => __LINE__, 'dump' => array(
'cookie' => array($arrArgHookParams['cookie']->getName() => $arrArgHookParams['cookie']->getFamily(''))
)
));
$objHookCookie = $arrArgHookParams['cookie'];
$objHookCart = $arrArgHookParams['cart'];
$intHookOrderID = $arrArgHookParams['id_order'];
//TODO : Check using order ID ??
// Check if it's a TNT carrier.
if (!TNTOfficiel_Carrier::isTNTOfficielCarrierID($objHookCart->id_carrier)) {
return '';
}
$arrTNTOrder = TNTOfficiel_OrderHelper::getInstance()->getOrderData($intHookOrderID);
// For compatibility on shipments created before tnt v1.2.2
if ($arrTNTOrder['is_shipped'] && !$arrTNTOrder['shipping_date']) {
$tempDate = new DateTime('1970-01-01');
$date = $tempDate->format('Y-m-d');
$arrTNTOrder['shipping_date'] = $arrTNTOrder['due_date'] = $arrTNTOrder['start_date'] = $date;
}
$shippingDate = $arrTNTOrder['shipping_date'];
$dueDate = '';
if ($arrTNTOrder['due_date']) {
$tempDate = explode('-', $arrTNTOrder['due_date']);
$dueDate = $tempDate[2].'/'.$tempDate[1].'/'.$tempDate[0];
}
$tempDate = explode('-', $arrTNTOrder['start_date']);
$firstAvailableDate = $tempDate[2].'/'.$tempDate[1].'/'.$tempDate[0];
$isAddressEditable = true;
if (preg_match('/DROPOFFPOINT|DEPOT/', $arrTNTOrder['carrier_code'])) {
$isAddressEditable = false;
}
$token = Tools::getAdminToken(
'AdminTNTOfficiel'.(int)Tab::getIdFromClassName('AdminTNTOfficiel').(int)$objHookCookie->id_employee
);
//get the parcels
$parcels = TNTOfficiel_ParcelsHelper::getInstance()->getParcels($intHookOrderID);
$arrTNTOrder2 = TNTOfficiel_OrderHelper::getInstance()->getOrderData($intHookOrderID);
$this->smarty->assign(array(
'parcels' => $parcels,
'AdminTNTOfficielToken' => $token,
'order' => new Order($intHookOrderID),
'bt_filename' => $arrTNTOrder2['bt_filename'],
'pickupNumber' =>
(Configuration::get('TNT_CARRIER_PICKUP_NUMBER_SHOW')) ? $arrTNTOrder2['pickup_number'] : null,
'isShipped' => (bool)$arrTNTOrder['is_shipped'],
'firstAvailableDate' => $firstAvailableDate,
'shippingDate' => $shippingDate,
'dueDate' => $dueDate,
'isAddressEditable' => (bool)$isAddressEditable,
'removeParcelUrl' =>
$this->context->link->getAdminLink('AdminTNTOfficiel').'&action=removeParcel&ajax=true',
'addParcelUrl' =>
$this->context->link->getAdminLink('AdminTNTOfficiel').'&action=addParcel&ajax=true',
'updateParcelUrl' =>
$this->context->link->getAdminLink('AdminTNTOfficiel').'&action=updateParcel&ajax=true',
'checkShippingDateValidUrl' =>
$this->context->link->getAdminLink('AdminTNTOfficiel').'&action=checkShippingDateValid&ajax=true',
));
// Add error message to the order admin page if exists.
if (!empty($objHookCookie->saveShippingError)) {
$this->context->controller->errors[] = $objHookCookie->saveShippingError;
$objHookCookie->saveShippingError = null;
}
$this->context->controller->addJS($this->getPathUri().'views/js/displayAdminOrder.js', 'all');
return $this->display(__FILE__, 'views/templates/hook/displayAdminOrder.tpl');
}
/**
* HOOK (AKA updateCarrier) called when a carrier is updated.
* After editing a Carrier, it is automatically archived and a new carrier is created.
*
* @param $arrArgHookParams
* @return bool
*/
public function hookActionCarrierUpdate($arrArgHookParams)
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
//$objHookCookie = $arrArgHookParams['cookie'];
//$objHookCart = $arrArgHookParams['cart'];
$intHookCarrierIDModified = $arrArgHookParams['id_carrier'];
$objHookCarrierNew = $arrArgHookParams['carrier'];
// Get current TNT carrier ID.
$intCarrierIDTNT = TNTOfficiel_Carrier::getGlobalCarrierID();
// If TNT carrier ID is availaible.
if ($intCarrierIDTNT !== null) {
// If modified carrier ID is the current TNT carrier ID.
if ($intHookCarrierIDModified == $intCarrierIDTNT) {
// Update it.
$boolResult = TNTOfficiel_Carrier::setCarrierID($objHookCarrierNew->id);
return $boolResult;
}
}
return true;
}
/**
* Carrier module : Method triggered form Cart Model if $carrier->need_range == false.
* Get the cart shipping price without using the ranges.
* (best price).
*
* @param Cart $objArgCart
* @return mixed
*/
public function getOrderShippingCostExternal($objArgCart)
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$fltPrice = $this->getOrderShippingCost($objArgCart, 0.0);
return $fltPrice;
}
/**
* Carrier module : Method triggered form Cart Model if $carrier->need_range == true.
* Get the shipping price depending on the ranges that were set in the back office.
* Get the shipping cost for a cart (best price), if carrier need range (default).
*
* @param Cart $objArgCart
* @return mixed
*/
public function getOrderShippingCost($objArgCart, $fltArgShippingCost)
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$objContext = $this->context;
$intCartID = (int)$objArgCart->id;
$fltCartExtraShippingCost = (float)$fltArgShippingCost;
// Get current TNT carrier ID.
$intCarrierIDTNT = TNTOfficiel_Carrier::getGlobalCarrierID();
// If TNT carrier ID not availaible.
if ($intCarrierIDTNT === null) {
return false;
}
// Check carrier is current TNT installed one.
// See comment about current class $id_carrier property.
if ($this->id_carrier != $intCarrierIDTNT) {
// Carrier unknow.
return false;
}
$arrTNTCarrierList = TNTOfficiel_CarrierHelper::getInstance()->getMDWTNTCarrierList($objContext->customer);
// If no available carrier.
if (empty($arrTNTCarrierList) || empty($arrTNTCarrierList['products'])) {
return false;
}
// Get additional shipping cost for cart.
$fltCartExtraShippingCost = TNTOfficiel_Cart::getCartExtraShippingCost($objArgCart);
// Load TNT cart info or create a new one for it's ID.
$objTNTCartModel = TNTOfficielCart::loadCartID($intCartID);
if (Validate::isLoadedObject($objTNTCartModel)) {
// If a TNT product is selected.
if (!empty($objTNTCartModel->carrier_code)) {
// Get price from selected product (middleware).
foreach ($arrTNTCarrierList['products'] as $arrProduct) {
if ($arrProduct['id'] === $objTNTCartModel->carrier_code) {
$fltPrice = (float)$arrProduct['price'];
// Save price.
$objTNTCartModel->delivery_price = $fltPrice + $fltCartExtraShippingCost;
$objTNTCartModel->save();
return $fltPrice + $fltCartExtraShippingCost;
}
}
}
}
// No product selected, then get best price.
$fltPrice = (float)$arrTNTCarrierList['products'][0]['price'];
foreach ($arrTNTCarrierList['products'] as $arrProduct) {
if ((float)$arrProduct['price'] < $fltPrice) {
$fltPrice = (float)$arrProduct['price'];
}
}
return $fltPrice + $fltCartExtraShippingCost;
}
/**
* HOOK (AKA updateOrderStatus) called when an order's status is changed, right before it is actually changed.
* If status become shipped or in delivery (PS_OS_SHIPPING), then
* creates a shipment using middleware service 'saveShipment'
* and also save previous_state in tntofficiel_order table.
*/
public function hookActionOrderStatusUpdate($arrArgHookParams)
{
TNTOfficiel_Debug::log(array(
'msg' => '>>', 'file' => __FILE__, 'line' => __LINE__, 'dump' => array(
'cookie' => array($arrArgHookParams['cookie']->getName() => $arrArgHookParams['cookie']->getFamily(''))
)
));
$objHookCookie = $arrArgHookParams['cookie'];
$objHookCart = $arrArgHookParams['cart'];
$objHookOrderStatusNew = $arrArgHookParams['newOrderStatus'];
$intHookOrderID = $arrArgHookParams['id_order'];
// Check if it's a TNT carrier.
$carrierId = null;
if ($objHookCart) {
$carrierId = $objHookCart->id_carrier;
} elseif (!$objHookCart && $intHookOrderID) {
$order = new Order($intHookOrderID);
$carrierId = $order->id_carrier;
}
if (!TNTOfficiel_Carrier::isTNTOfficielCarrierID($carrierId)) {
return;
}
// Check if the new status is shipping.
if (Configuration::get('PS_OS_SHIPPING') == $objHookOrderStatusNew->id) {
try {
TNTOfficiel_ShipmentHelper::getInstance()->saveShipment($objHookCart, $intHookOrderID);
} catch (Exception $objException) {
$objHookCookie->saveShippingError = $this->l('Error create shipping');
}
}
$arrTNTOrder = TNTOfficiel_OrderHelper::getInstance()->getOrderData($intHookOrderID);
$order = new Order($intHookOrderID);
Db::getInstance()->update(
'tntofficiel_order',
array('previous_state' => (int)$order->current_state),
'id_tntofficiel_order = '.(int)$arrTNTOrder['id_tntofficiel_order']
);
}
/**
* HOOK (AKA postUpdateOrderStatus) called when an order's status is changed, right after it is actually changed.
* Revert the order status if the shipment could not be saved.
*/
public function hookActionOrderStatusPostUpdate($arrArgHookParams)
{
TNTOfficiel_Debug::log(array(
'msg' => '>>', 'file' => __FILE__, 'line' => __LINE__, 'dump' => array(
'cookie' => array($arrArgHookParams['cookie']->getName() => $arrArgHookParams['cookie']->getFamily(''))
)
));
$objHookCookie = $arrArgHookParams['cookie'];
$objHookCart = $arrArgHookParams['cart'];
$objHookOrderStatusNew = $arrArgHookParams['newOrderStatus'];
$intHookOrderID = $arrArgHookParams['id_order'];
// Check if it's a TNT carrier.
if (!Validate::isLoadedObject($objHookCart)
|| !TNTOfficiel_Carrier::isTNTOfficielCarrierID($objHookCart->id_carrier)
) {
return;
}
// Check if the new state is shipping and the shipment was not created.
if (Configuration::get('PS_OS_SHIPPING') == $objHookOrderStatusNew->id
&& !TNTOfficiel_ShipmentHelper::getInstance()->isShipmentSaved($intHookOrderID)
) {
// Revert the order state.
TNTOfficiel_OrderHelper::getInstance()->revertState($intHookOrderID);
$objHookCookie->saveShippingError = $this->l('Error create shipping');
}
}
/**
* HOOK (AKA orderDetailDisplayed) displayed on order detail on Front-Office.
* Insert parcel tracking block on order detail.
*/
public function hookDisplayOrderDetail($arrArgHookParams)
{
TNTOfficiel_Debug::log(array(
'msg' => '>>', 'file' => __FILE__, 'line' => __LINE__, 'dump' => array(
'cookie' => array($arrArgHookParams['cookie']->getName() => $arrArgHookParams['cookie']->getFamily(''))
)
));
//$objHookCookie = $arrArgHookParams['cookie'];
//$objHookCart = $arrArgHookParams['cart'];
$objHookOrder = $arrArgHookParams['order'];
// If order does not have a TNT carrier.
if (!TNTOfficiel_Carrier::isTNTOfficielCarrierID($objHookOrder->id_carrier)) {
return;
}
// If order has no shipment created.
if (!TNTOfficiel_ShipmentHelper::getInstance()->isShipmentSaved($objHookOrder->id)) {
return;
}
$this->smarty->assign(array(
'trackingUrl' => $this->context->link->getModuleLink(
TNTOfficiel::MODULE_NAME,
'tracking',
array('action' => 'tracking')
),
));
return $this->display(__FILE__, 'views/templates/hook/displayOrderDetail.tpl');
}
/**
* Prepare all smarty functions to register.
*/
private function smartyRegisterFunctions()
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$smartyClassPath = $this->getLocalPath().'libraries'.DIRECTORY_SEPARATOR.'smarty';
foreach (TNTOfficiel::$arrSmartyFunctions as $tag => $smartyFunction) {
$smartyFunctionArray = explode('::', $smartyFunction);
$className = current($smartyFunctionArray);
$functionName = end($smartyFunctionArray);
require_once sprintf('%s/%s.php', $smartyClassPath, $className);
$class = new $className();
$callback = array($class, $functionName);
// Doing unregisterPlugin() before registerPlugin() prevent Exception,
// Method smartyRegisterFunctions() may be call multiple times.
// Exemple : AdminCmsContentController loading AdminCmsCategoriesController and AdminCmsController.
$this->context->smarty
->unregisterPlugin('function', $tag, $callback)
->registerPlugin('function', $tag, $callback);
}
}
public function updateShippingDate($objArgOrder)
{
TNTOfficiel_Debug::log(array('msg' => '>>', 'file' => __FILE__, 'line' => __LINE__));
$intOrderID = (int)$objArgOrder->id;
if (!TNTOfficiel_Carrier::isTNTOfficielCarrierID($objArgOrder->id_carrier)) {
return;
}
$arrTNTOrder = TNTOfficiel_OrderHelper::getInstance()->getOrderData($intOrderID);
if ($arrTNTOrder['is_shipped']) {
return;
}
$objTNTShipmentHelper = TNTOfficiel_ShipmentHelper::getInstance();
// TODO : unused ?
$objTNTShipmentHelper->getShippingDate($intOrderID);
/* $startDate = $arrMDWShippingDate['shippingDate']; */
$objDateTimeNow = new DateTime('today');
$strDateStart = $objDateTimeNow->format('Y-m-d');
if (!$arrTNTOrder['shipping_date']) {
$arrMDWShippingDate = $objTNTShipmentHelper->getNewShippingDate($intOrderID);
} else {
$arrMDWShippingDate = $objTNTShipmentHelper->checkSaveShipmentDate(
$intOrderID,
$arrTNTOrder['shipping_date']
);
}
if (array_key_exists('shippingDate', $arrMDWShippingDate)) {
// Update shipping & due date
Db::getInstance()->update(
'tntofficiel_order',
array(
'shipping_date' => pSQL($arrMDWShippingDate['shippingDate']),
'due_date' => pSQL($arrMDWShippingDate['dueDate']),
'start_date' => pSQL($strDateStart),
),
'id_tntofficiel_order = '.(int)$arrTNTOrder['id_tntofficiel_order']
);
} elseif (array_key_exists('error', $arrMDWShippingDate) && $arrMDWShippingDate['error'] == 0) {
// Start date = today
Db::getInstance()->update(
'tntofficiel_order',
array('start_date' => pSQL($strDateStart)),
'id_tntofficiel_order = '.(int)$arrTNTOrder['id_tntofficiel_order']
);
} elseif (array_key_exists('error', $arrMDWShippingDate) && $arrMDWShippingDate['error'] == 1) {
// Request new shipping and due date
if (!$arrMDWShippingDate = $objTNTShipmentHelper->getNewShippingDate($intOrderID)) {
return false;
}
Db::getInstance()->update(
'tntofficiel_order',
array(
'shipping_date' => pSQL($arrMDWShippingDate['shippingDate']),
'due_date' => pSQL($arrMDWShippingDate['dueDate']),
'start_date' => pSQL($strDateStart),
),
'id_tntofficiel_order = '.(int)$arrTNTOrder['id_tntofficiel_order']
);
} else {
return false;
}
return true;
}
}