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

2055 lines
63 KiB
PHP

<?php
/**
* TNT OFFICIAL MODULE FOR PRESTASHOP
*
* @author GFI Informatique <www.gfi.world>
* @copyright 2016-2019 GFI Informatique, 2016-2019 TNT
* @license https://opensource.org/licenses/MIT MIT License
*/
require_once _PS_MODULE_DIR_.'tntofficiel/libraries/TNTOfficiel_ClassLoader.php';
/**
* Class TNTOfficielAccount
*/
class TNTOfficielAccount extends ObjectModel
{
const PASSWORD_REPLACE = '%p#c`Q9,6GSP?U4]e]Zst';
// id_tntofficiel_account
public $id;
/** @var int Shop Group ID association. */
public $id_shop_group;
/** @var int Shop ID association. */
public $id_shop;
/*
* Account.
*/
/** @var string Account number (8 digits). */
public $account_number;
/** @var string MyTNT user email (ID). */
public $account_login;
/** @var string SHA1 Hex of MyTNT password. */
public $account_password;
/** @var int UNIX timestamp of the last validation (e.g :: 1523019418). */
public $account_validated;
/*
* Sender.
*/
/** @var string Sender Company. */
public $sender_company;
/** @var string Sender address line 1. */
public $sender_address1;
/** @var string Sender address line 2.*/
public $sender_address2;
/** @var string Sender zip code. */
public $sender_zipcode;
/** @var string Sender city. */
public $sender_city;
/** @var string first name. */
public $sender_firstname;
/** @var string Sender last name. */
public $sender_lastname;
/** @var string Sender email. */
public $sender_email;
/** @var string Sender phone (without separators). */
public $sender_phone;
/*
* Pickup.
*/
/** @var string Pickup type ['REGULAR', 'OCCASIONAL']. */
public $pickup_type;
/** @var string Pickup delivery time for type REGULAR. */
public $pickup_driver_time;
/** @var string Pickup closing time for type OCCASIONAL. */
public $pickup_closing_time;
/** @var int Pickup days of preparation. */
public $pickup_preparation_days;
/** @var string Pickup label type ['STDA4', 'THERMAL', 'THERMAL,NO_LOGO']. */
public $pickup_label_type;
/** @var bool Pickup display number (BO). */
public $pickup_display_number;
/*
* Delivery.
*/
/** @var bool Display EDD (Estimated Delivery Date) on FO. */
public $delivery_display_edd;
/** @var bool Delivery customer notification. */
public $delivery_notification;
/*
* Zone.
*/
/** @var string Departments list in zone 1 (PHP serialized). */
public $zone1_departments;
/** @var string Departments list in zone 2 (PHP serialized). */
public $zone2_departments;
/*
* API.
*/
/** @var string */
public $api_google_map_key;
/*
* State.
*/
/** @var bool status */
public $active = true;
/** @var bool True if has been deleted (staying in database as deleted) */
public $deleted = 0;
/** @var string creation date */
public $date_add;
/** @var string last modification date */
public $date_upd;
/** @var TNTOfficiel_SoapClient */
protected $objWebServiceTNT = null;
public static $definition = array(
'table' => 'tntofficiel_account',
'primary' => 'id_tntofficiel_account',
'fields' => array(
'id_shop_group' => array(
'type' => ObjectModel::TYPE_NOTHING,
'validate' => 'isUnsignedId'
),
'id_shop' => array(
'type' => ObjectModel::TYPE_NOTHING,
'validate' => 'isUnsignedId'
),
'account_number' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 8
),
'account_login' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 128
),
'account_password' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 40
),
'account_validated' => array(
'type' => ObjectModel::TYPE_INT,
),
'sender_company' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 32
),
'sender_address1' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 32
),
'sender_address2' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 32
),
'sender_zipcode' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 10
),
'sender_city' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 32
),
'sender_firstname' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 32
),
'sender_lastname' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 32
),
'sender_email' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 80 // 128 ?
),
'sender_phone' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 15
),
'pickup_type' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 16
),
'pickup_driver_time' => array(
'type' => ObjectModel::TYPE_STRING,
),
'pickup_closing_time' => array(
'type' => ObjectModel::TYPE_STRING,
),
'pickup_preparation_days' => array(
'type' => ObjectModel::TYPE_INT,
),
'pickup_label_type' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 32
),
'pickup_display_number' => array(
'type' => ObjectModel::TYPE_BOOL,
'validate' => 'isBool'
),
'delivery_display_edd' => array(
'type' => ObjectModel::TYPE_BOOL,
'validate' => 'isBool'
),
'delivery_notification' => array(
'type' => ObjectModel::TYPE_BOOL,
'validate' => 'isBool'
),
'zone1_departments' => array(
'type' => ObjectModel::TYPE_STRING,
),
'zone2_departments' => array(
'type' => ObjectModel::TYPE_STRING,
),
'api_google_map_key' => array(
'type' => ObjectModel::TYPE_STRING,
'size' => 64
),
'active' => array(
'type' => self::TYPE_BOOL,
'validate' => 'isBool'
),
'deleted' => array(
'type' => self::TYPE_BOOL,
'validate' => 'isBool'
),
'date_add' => array(
'type' => self::TYPE_DATE,
'validate' => 'isDate'
),
'date_upd' => array(
'type' => self::TYPE_DATE,
'validate' => 'isDate'
),
),
);
private static $arrDepartments = array(
'Ain' => '01',
'Aisne' => '02',
'Allier' => '03',
'Alpes-de-Haute-Provence' => '04',
'Hautes-Alpes' => '05',
'Alpes-Maritimes' => '06',
'Ardèche' => '07',
'Ardennes' => '08',
'Ariège' => '09',
'Aube' => '10',
'Aude' => '11',
'Aveyron' => '12',
'Bouches-du-Rhône' => '13',
'Calvados' => '14',
'Cantal' => '15',
'Charente' => '16',
'Charente-Maritime' => '17',
'Cher' => '18',
'Corrèze' => '19',
'Corse' => '20',
'Côte-d\'Or' => '21',
'Côtes-d\'Armor' => '22',
'Creuse' => '23',
'Dordogne' => '24',
'Doubs' => '25',
'Drôme' => '26',
'Eure' => '27',
'Eure-et-Loir' => '28',
'Finistère' => '29',
'Gard' => '30',
'Haute-Garonne' => '31',
'Gers' => '32',
'Gironde' => '33',
'Hérault' => '34',
'Ille-et-Vilaine' => '35',
'Indre' => '36',
'Indre-et-Loire' => '37',
'Isère' => '38',
'Jura' => '39',
'Landes' => '40',
'Loir-et-Cher' => '41',
'Loire' => '42',
'Haute-Loire' => '43',
'Loire-Atlantique' => '44',
'Loiret' => '45',
'Lot' => '46',
'Lot-et-Garonne' => '47',
'Lozère' => '48',
'Maine-et-Loire' => '49',
'Manche' => '50',
'Marne' => '51',
'Haute-Marne' => '52',
'Mayenne' => '53',
'Meurthe-et-Moselle' => '54',
'Meuse' => '55',
'Morbihan' => '56',
'Moselle' => '57',
'Nièvre' => '58',
'Nord' => '59',
'Oise' => '60',
'Orne' => '61',
'Pas-de-Calais' => '62',
'Puy-de-Dôme' => '63',
'Pyrénées-Atlantiques' => '64',
'Hautes-Pyrénées' => '65',
'Pyrénées-Orientales' => '66',
'Bas-Rhin' => '67',
'Haut-Rhin' => '68',
'Rhône' => '69',
'Haute-Saône' => '70',
'Saône-et-Loire' => '71',
'Sarthe' => '72',
'Savoie' => '73',
'Haute-Savoie' => '74',
'Paris' => '75',
'Seine-Maritime' => '76',
'Seine-et-Marne' => '77',
'Yvelines' => '78',
'Deux-Sèvres' => '79',
'Somme' => '80',
'Tarn' => '81',
'Tarn-et-Garonne' => '82',
'Var' => '83',
'Vaucluse' => '84',
'Vendée' => '85',
'Vienne' => '86',
'Haute-Vienne' => '87',
'Vosges' => '88',
'Yonne' => '89',
'Territoire-de-Belfort' => '90',
'Essonne' => '91',
'Hauts-de-Seine' => '92',
'Seine-Saint-Denis' => '93',
'Val-de-Marne' => '94',
'Val-d\'Oise' => '95',
'Monaco' => '98',
);
/** @var array Available pickup label Type. */
private static $arrPickupLabelTypes = array(
'STDA4',
'THERMAL',
'THERMAL,NO_LOGO'
);
// cache and prevent race condition.
private static $arrLoadedEntities = array();
/**
* Creates the tables needed by the model.
*
* @return bool
*/
public static function createTables()
{
TNTOfficiel_Logstack::log();
$strLogMessage = sprintf('%s::%s', __CLASS__, __FUNCTION__);
$strTablePrefix = _DB_PREFIX_;
$strTableEngine = _MYSQL_ENGINE_;
$strTableName = $strTablePrefix.TNTOfficielAccount::$definition['table'];
// Create table.
$strSQLCreateAccount = <<<SQL
CREATE TABLE IF NOT EXISTS `${strTableName}` (
`id_tntofficiel_account` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_shop_group` INT(10) UNSIGNED DEFAULT NULL,
`id_shop` INT(10) UNSIGNED DEFAULT NULL,
-- Account.
`account_number` VARCHAR(10) NOT NULL DEFAULT '',
`account_login` VARCHAR(128) NOT NULL DEFAULT '',
`account_password` VARCHAR(40) NOT NULL DEFAULT '',
`account_validated` INT(10) UNSIGNED NULL DEFAULT NULL,
-- Sender.
`sender_company` VARCHAR(32) NOT NULL DEFAULT '',
`sender_address1` VARCHAR(32) NOT NULL DEFAULT '',
`sender_address2` VARCHAR(32) NOT NULL DEFAULT '',
`sender_zipcode` VARCHAR(10) NOT NULL DEFAULT '',
`sender_city` VARCHAR(32) NOT NULL DEFAULT '',
`sender_firstname` VARCHAR(32) NOT NULL DEFAULT '',
`sender_lastname` VARCHAR(32) NOT NULL DEFAULT '',
`sender_email` VARCHAR(80) NOT NULL DEFAULT '',
`sender_phone` VARCHAR(15) NOT NULL DEFAULT '',
-- Pickup.
`pickup_type` VARCHAR(25) NOT NULL DEFAULT 'REGULAR',
`pickup_driver_time` TIME NOT NULL DEFAULT '17:00:00',
`pickup_closing_time` TIME NOT NULL DEFAULT '17:00:00',
`pickup_preparation_days` INT(10) UNSIGNED NOT NULL DEFAULT '0',
`pickup_label_type` VARCHAR(32) NOT NULL DEFAULT 'STDA4',
`pickup_display_number` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
`delivery_display_edd` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
`delivery_notification` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',
-- Zone.
`zone1_departments` TEXT NULL,
`zone2_departments` TEXT NULL,
-- API.
`api_google_map_key` VARCHAR(64) NOT NULL DEFAULT '',
-- State.
`active` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
`deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
-- Dates d'ajout et de modification.
`date_add` DATETIME NOT NULL DEFAULT '0000-00-00',
`date_upd` DATETIME NOT NULL DEFAULT '0000-00-00',
-- Key.
PRIMARY KEY (`id_tntofficiel_account`),
INDEX `id_shop` (`id_shop`),
INDEX `id_shop_group` (`id_shop_group`)
) ENGINE = ${strTableEngine} DEFAULT CHARSET='utf8' COLLATE='utf8_general_ci';
SQL;
$objDB = Db::getInstance();
if (!$objDB->execute($strSQLCreateAccount)) {
TNTOfficiel_Logger::logInstall($strLogMessage.' : '.$objDB->getMsgError(), false);
return false;
}
TNTOfficiel_Logger::logInstall($strLogMessage);
return true;
}
/**
* Constructor.
*/
public function __construct($intArgID = null)
{
TNTOfficiel_Logstack::log();
parent::__construct($intArgID);
$this->initWebService();
}
/**
* Do shop ID and shop group ID consistency.
*
* @param int $intArgShopID
* @param int $intArgShopGroupID
*
* @return bool
*/
private static function correctShopAndGroupId(&$intArgShopID = null, &$intArgShopGroupID = null)
{
TNTOfficiel_Logstack::log();
$intShopID = null;
$objShop = null;
if (Shop::isFeatureActive() && $intArgShopID > 0) {
$intShopID = (int)$intArgShopID;
$objShop = new Shop($intShopID);
if (Validate::isLoadedObject($objShop)
&& (int)$objShop->id === $intShopID
) {
$intArgShopGroupID = (int)$objShop->id_shop_group;
} else {
$intShopID = null;
$objShop = null;
$intArgShopGroupID = null;
}
}
$intShopGroupID = null;
$objShopGroup = null;
if (Shop::isFeatureActive() && $intArgShopGroupID > 0) {
$intShopGroupID = (int)$intArgShopGroupID;
$objShopGroup = new ShopGroup($intShopGroupID);
if (!Validate::isLoadedObject($objShopGroup)
|| (int)$objShopGroup->id !== $intShopGroupID
) {
$intShopGroupID = null;
$objShopGroup = null;
}
}
// Correct.
$intArgShopID = (int)$intShopID;
$intArgShopGroupID = (int)$intShopGroupID;
return true;
}
/**
* Load an existing object model or create a new one with a new ID.
*
* @param int $intArgAccountID
*
* @return TNTOfficielAccount|null
*/
public static function loadAccountID($intArgAccountID = null)
{
TNTOfficiel_Logstack::log();
$intAccountID = (int)$intArgAccountID;
// Create.
if ($intAccountID === 0) {
// Create a new TNT account entry.
$objTNTAccountModelCreate = new TNTOfficielAccount(null);
// Apply default.
$objTNTAccountModelCreate->setPickupType('REGULAR');
$objTNTAccountModelCreate->pickup_driver_time = '17:00:00';
$objTNTAccountModelCreate->pickup_closing_time = '17:00:00';
$objTNTAccountModelCreate->pickup_label_type = 'STDA4';
$objTNTAccountModelCreate->delivery_notification = '1';
$objTNTAccountModelCreate->save();
$intAccountID = (int)$objTNTAccountModelCreate->id;
unset($objTNTAccountModelCreate);
}
// No new account ID.
if (!($intAccountID > 0)) {
return null;
}
$strEntityID = $intAccountID.'-'.(int)null.'-'.(int)null;
// If already loaded.
if (array_key_exists($strEntityID, TNTOfficielAccount::$arrLoadedEntities)) {
$objTNTAccountModel = TNTOfficielAccount::$arrLoadedEntities[$strEntityID];
// Check.
if ((int)$objTNTAccountModel->id === $intAccountID && Validate::isLoadedObject($objTNTAccountModel)) {
return $objTNTAccountModel;
}
}
// Load existing TNT account entry.
// or reload after create, to get default DB values after creation.
$objTNTAccountModel = new TNTOfficielAccount($intAccountID);
// Check.
if ((int)$objTNTAccountModel->id !== $intAccountID || !Validate::isLoadedObject($objTNTAccountModel)) {
return null;
}
$objTNTAccountModel->id = (int)$objTNTAccountModel->id;
$objTNTAccountModel->id_shop_group = (int)$objTNTAccountModel->id_shop_group;
$objTNTAccountModel->id_shop = (int)$objTNTAccountModel->id_shop;
TNTOfficielAccount::$arrLoadedEntities[$strEntityID] = $objTNTAccountModel;
return $objTNTAccountModel;
}
/**
* @param TNTOfficielAccount $objArgTNTAccountModelSource
*
* @return $this
*/
private function inherit(TNTOfficielAccount $objArgTNTAccountModelSource = null)
{
TNTOfficiel_Logstack::log();
$arrExcludingProperties = array(
'id_shop_group',
'id_shop',
//'account_number',
'date_add',
'date_upd',
);
// If a source model exist.
if ($objArgTNTAccountModelSource !== null) {
// Copy.
foreach (TNTOfficielAccount::$definition['fields'] as $strPropName => $arrPropDefinition) {
if (in_array($strPropName, $arrExcludingProperties, true)) {
continue;
}
if (property_exists($objArgTNTAccountModelSource, $strPropName)) {
$this->{$strPropName} = $objArgTNTAccountModelSource->{$strPropName};
}
}
}
// Init webservice and auth.
$this->initWebService();
return $this;
}
/**
* Create an account using shop or shop group ID, optionally cloned from any other account object model.
*
* @param int $intArgShopID
* @param int $intArgShopGroupID
* @param TNTOfficielAccount $objTNTAccountModelSource
*
* @return TNTOfficielAccount
*/
private static function createContextShopID(
$intArgShopID = null,
$intArgShopGroupID = null,
TNTOfficielAccount $objTNTAccountModelSource = null
) {
TNTOfficiel_Logstack::log();
$intShopID = (int)$intArgShopID;
$intShopGroupID = (int)$intArgShopGroupID;
TNTOfficielAccount::correctShopAndGroupId($intShopID, $intShopGroupID);
// Create a new Account model.
$objTNTAccountModelCreate = TNTOfficielAccount::loadAccountID();
// Inherit.
$objTNTAccountModelCreate->inherit($objTNTAccountModelSource);
// Apply shop and group ID.
$objTNTAccountModelCreate->id_shop_group = $intShopGroupID;
$objTNTAccountModelCreate->id_shop = $intShopID;
$objTNTAccountModelCreate->save();
return $objTNTAccountModelCreate;
}
/**
* Load the account depending of the current shop context. If unexist, create an account from the nearest parent.
*
* @param bool $boolArgAllowCreate Create
*
* @return TNTOfficielAccount
*/
public static function loadContextShop($intArgShopID = null, $intArgShopGroupID = null, $boolArgAllowCreate = true)
{
TNTOfficiel_Logstack::log();
if ($intArgShopID === null) {
$intShopID = (int)Shop::getContextShopID();
} else {
$intShopID = (int)$intArgShopID;
}
if ($intArgShopID === null) {
$intShopGroupID = (int)Shop::getContextShopGroupID(true);
} else {
$intShopGroupID = (int)$intArgShopGroupID;
}
TNTOfficielAccount::correctShopAndGroupId($intShopID, $intShopGroupID);
try {
$objTNTAccountModelStrict = TNTOfficielAccount::searchContextShopID(
$intShopID,
$intShopGroupID,
true,
true
);
// Create an account if unexist, or shop ID is different from source,
// or shop group ID is different from source.
if ($boolArgAllowCreate
&& ($objTNTAccountModelStrict === null
|| ($intShopID !== $objTNTAccountModelStrict->id_shop
|| $intShopGroupID !== $objTNTAccountModelStrict->id_shop_group
)
)
) {
$objTNTAccountModelInherit = TNTOfficielAccount::searchContextShopID(
$intShopID,
$intShopGroupID,
true,
false
);
return TNTOfficielAccount::createContextShopID($intShopID, $intShopGroupID, $objTNTAccountModelInherit);
}
} catch (Exception $objException) {
TNTOfficiel_Logger::logException($objException);
$objTNTAccountModelStrict = null;
}
return $objTNTAccountModelStrict;
}
/**
* Search for a list of non deleted account object model, via shop or shop group ID.
*
* @param int $intArgShopID
* @param int $intArgShopGroupID
* @param bool $boolArgActive true to search only active account.
* @param bool $boolArgStrict true to match exact context.
*
* @return TNTOfficielAccount|null.
*/
public static function searchContextShopID(
$intArgShopID = null,
$intArgShopGroupID = null,
$boolArgActive = false,
$boolArgStrict = false
) {
TNTOfficiel_Logstack::log();
$intShopID = (int)$intArgShopID;
$intShopGroupID = (int)$intArgShopGroupID;
TNTOfficielAccount::correctShopAndGroupId($intShopID, $intShopGroupID);
/*
* Search.
*/
$arrObjTNTAccountModelFound = array();
$objDB = Db::getInstance();
// No new shop ID.
if ($intShopID > 0) {
// Search row for shop ID.
$objDbQuery = new DbQuery();
$objDbQuery->select('*');
$objDbQuery->from(TNTOfficielAccount::$definition['table']);
$objDbQuery->where('id_shop = '.$intShopID);
$objDbQuery->where('deleted = 0');
if ($boolArgActive === true) {
$objDbQuery->where('active = 1');
}
$arrResult = $objDB->executeS($objDbQuery);
// If row found and match accound ID.
if (is_array($arrResult) && count($arrResult) > 0) {
foreach ($arrResult as $arrValue) {
if ($intShopID === (int)$arrValue['id_shop']) {
$intTNTAccountID = (int)$arrValue['id_tntofficiel_account'];
$objTNTAccountModel = TNTOfficielAccount::loadAccountID($intTNTAccountID);
// If TNT carrier object not available.
if (Validate::isLoadedObject($objTNTAccountModel)
&& (int)$objTNTAccountModel->id === $intTNTAccountID
) {
$arrObjTNTAccountModelFound[] = $objTNTAccountModel;
}
}
}
}
}
// No new shop group ID.
if ($intShopGroupID > 0 && (!$boolArgStrict || $intShopID === 0)) {
// Search row for shop group ID.
$objDbQuery = new DbQuery();
$objDbQuery->select('*');
$objDbQuery->from(TNTOfficielAccount::$definition['table']);
$objDbQuery->where('id_shop_group = '.$intShopGroupID);
$objDbQuery->where('id_shop = 0');
$objDbQuery->where('deleted = 0');
if ($boolArgActive === true) {
$objDbQuery->where('active = 1');
}
$arrResult = $objDB->executeS($objDbQuery);
// If row found and match accound ID.
if (is_array($arrResult) && count($arrResult) > 0) {
foreach ($arrResult as $arrValue) {
if ($intShopGroupID === (int)$arrValue['id_shop_group']) {
$intTNTAccountID = (int)$arrValue['id_tntofficiel_account'];
$objTNTAccountModel = TNTOfficielAccount::loadAccountID($intTNTAccountID);
// If TNT carrier object not available.
if (Validate::isLoadedObject($objTNTAccountModel)
&& (int)$objTNTAccountModel->id === $intTNTAccountID
) {
$arrObjTNTAccountModelFound[] = $objTNTAccountModel;
}
}
}
}
}
if (!$boolArgStrict || ($intShopID === 0 && $intShopGroupID === 0)) {
// Search row for global.
$objDbQuery = new DbQuery();
$objDbQuery->select('*');
$objDbQuery->from(TNTOfficielAccount::$definition['table']);
$objDbQuery->where('id_shop IS NULL OR id_shop = 0');
$objDbQuery->where('id_shop_group IS NULL OR id_shop_group = 0');
$objDbQuery->where('deleted = 0');
if ($boolArgActive === true) {
$objDbQuery->where('active = 1');
}
$arrResult = $objDB->executeS($objDbQuery);
// If row found and match accound ID.
if (is_array($arrResult) && count($arrResult) > 0) {
foreach ($arrResult as $arrValue) {
$intTNTAccountID = (int)$arrValue['id_tntofficiel_account'];
$objTNTAccountModel = TNTOfficielAccount::loadAccountID($intTNTAccountID);
// If TNT carrier object not available.
if (Validate::isLoadedObject($objTNTAccountModel)
&& (int)$objTNTAccountModel->id === $intTNTAccountID
) {
$arrObjTNTAccountModelFound[] = $objTNTAccountModel;
}
}
}
}
// From most to less qualified.
foreach ($arrObjTNTAccountModelFound as $objTNTAccountModel) {
// return AccountModel object or null;
return $objTNTAccountModel;
}
return null;
}
/**
* Save for context (account list).
*/
public function saveContextShop()
{
TNTOfficiel_Logstack::log();
// get this account context shop list.
$arrObjPSShopList = $this->getPSShopList();
// If account context is a shop.
if ($this->id_shop > 0) {
// remove from the shop list.
unset($arrObjPSShopList[$this->id_shop]);
}
foreach ($arrObjPSShopList as $intShopID => $objPSShop) {
// Get current account for this shop (or create it from inherit).
$objTNTShopAccountModel = TNTOfficielAccount::loadContextShop($intShopID);
// If fail.
if ($objTNTShopAccountModel === null) {
continue;
}
$objTNTShopAccountModel->inherit($this);
$objTNTShopAccountModel->save();
}
$this->save();
}
/**
* Get account context object shop list.
*
* @return array
*/
public function getPSShopList()
{
TNTOfficiel_Logstack::log();
$intShopID = (int)$this->id_shop;
$intShopGroupID = (int)$this->id_shop_group;
$arrIDList = array();
if ($intShopID > 0) {
// Get shop ID.
$arrIDList = array($intShopID);
} elseif ($intShopGroupID > 0) {
// Get shop ID list from a group ID.
$arrIDList = Shop::getShops(true, $intShopGroupID, true);
} else {
// Get all shop ID List.
$arrIDList = Shop::getShops(true, null, true);
}
$arrObjPSShopList = array();
foreach ($arrIDList as $intShopIDCurrent) {
$intShopIDCurrent = (int)$intShopIDCurrent;
$objPSShopCurrent = new Shop($intShopIDCurrent);
if (!Validate::isLoadedObject($objPSShopCurrent)
|| (int)$objPSShopCurrent->id !== $intShopIDCurrent
) {
continue;
}
$arrObjPSShopList[$intShopIDCurrent] = $objPSShopCurrent;
}
return $arrObjPSShopList;
}
/**
* Restoring account shop context.
*/
private function restorePSShopContext()
{
TNTOfficiel_Logstack::log();
if ($this->id_shop > 0) {
Shop::setContext(Shop::CONTEXT_SHOP, $this->id_shop);
} elseif ($this->id_shop_group > 0) {
Shop::setContext(Shop::CONTEXT_GROUP, $this->id_shop_group);
} else {
Shop::setContext(Shop::CONTEXT_ALL);
}
}
/**
* Store account number.
*
* @param string $strArgAccountNumber
*
* @return bool
*/
public function setAccountNumber($strArgAccountNumber)
{
TNTOfficiel_Logstack::log();
$this->account_number = Tools::substr($strArgAccountNumber, 0, 8);
$this->initWebService();
return true;
}
/**
* Store account login
*
* @param string $strArgAccountLogin
*
* @return bool
*/
public function setAccountLogin($strArgAccountLogin)
{
TNTOfficiel_Logstack::log();
$this->account_login = Tools::substr($strArgAccountLogin, 0, 128);
$this->initWebService();
return true;
}
/**
* Store clear account password to SHA1.
*
* @param string $strArgAccountPassword
*
* @return bool
*/
public function setAccountPassword($strArgAccountPassword)
{
TNTOfficiel_Logstack::log();
$this->account_password = sha1($strArgAccountPassword);
$this->initWebService();
return true;
}
/**
* Get account password.
*
* @return string
*/
public function getAccountPassword()
{
TNTOfficiel_Logstack::log();
return $this->account_password;
}
/**
* Get DateTime of the last credentials validation.
*
* @return DateTime|null null if invalid credentials.
*/
public function getAuthValidatedDateTime()
{
TNTOfficiel_Logstack::log();
$strCredentialCurrentState = $this->account_validated;
if (!$strCredentialCurrentState) {
return null;
}
try {
$objValidatedDateTime = new DateTime('@'.$strCredentialCurrentState);
} catch (Exception $objException) {
$objValidatedDateTime = null;
}
return $objValidatedDateTime;
}
/**
* Call the WS to check the credentials.
* Save invalidation or validation date.
*
* @param int $intArgRefreshDelay
*
* @return bool true if valid or always valid, false if invalid, null if error.
*/
public function updateAuthValidation($intArgRefreshDelay = 0)
{
TNTOfficiel_Logstack::log();
$intRefreshDelay = (int)$intArgRefreshDelay;
if (!($intRefreshDelay >= 0)) {
$intRefreshDelay = 0;
}
$objDateTimeNow = new DateTime('now');
$intTSNow = (int)$objDateTimeNow->format('U');
$objValidatedDateTime = $this->getAuthValidatedDateTime();
// If activated
if ($objValidatedDateTime !== null) {
$intTSValidated = (int)$objValidatedDateTime->format('U');
// If current timestamp earlier than previous saved timestamp + delay before refreshing.
// Means that check is always done until validated
// or been recheck after an amount of time from last validation.
if ($intTSNow < ($intTSValidated + $intRefreshDelay)) {
return true;
}
}
// Get WS Response.
$boolIsAuth = $this->isCorrectAuthentication();
// If request fail.
if ($boolIsAuth === null) {
return null;
} elseif ($boolIsAuth !== true) {
// Disable the module if authentication fail.
$this->account_validated = false;
$this->save();
return false;
}
$this->account_validated = $intTSNow;
$this->save();
return true;
}
/**
* Set sender company name.
*
* @param string $strArgSenderCompany
*
* @return bool
*/
public function setSenderCompany($strArgSenderCompany)
{
TNTOfficiel_Logstack::log();
$this->sender_company = Tools::substr($strArgSenderCompany, 0, 32);
return true;
}
/**
* Store sender address 1.
*
* @param string $strArgSenderAddress1
*
* @return bool
*/
public function setSenderAddress1($strArgSenderAddress1)
{
TNTOfficiel_Logstack::log();
$this->sender_address1 = Tools::substr($strArgSenderAddress1, 0, 32);
return true;
}
/**
* Set sender address 2.
*
* @param string $strArgSenderAddress2
*
* @return bool
*/
public function setSenderAddress2($strArgSenderAddress2)
{
TNTOfficiel_Logstack::log();
$this->sender_address2 = Tools::substr($strArgSenderAddress2, 0, 32);
return true;
}
/**
* Set sender zip code.
*
* @param string $strArgSenderZipCode
*
* @return bool
*/
public function setSenderZipCode($strArgSenderZipCode)
{
TNTOfficiel_Logstack::log();
$this->sender_zipcode = Tools::substr($strArgSenderZipCode, 0, 10);
return true;
}
/**
* Set sender city.
*
* @param string $strArgSenderCity
*
* @return bool
*/
public function setSenderCity($strArgSenderCity)
{
TNTOfficiel_Logstack::log();
$this->sender_city = Tools::substr($strArgSenderCity, 0, 32);
return true;
}
/**
* Set sender first name.
*
* @param string $strArgSenderFirstName
*
* @return bool
*/
public function setSenderFirstName($strArgSenderFirstName)
{
TNTOfficiel_Logstack::log();
$this->sender_firstname = Tools::substr($strArgSenderFirstName, 0, 32);
return true;
}
/**
* Set sender last name.
*
* @param string $strArgSenderLastName
*
* @return bool
*/
public function setSenderLastName($strArgSenderLastName)
{
TNTOfficiel_Logstack::log();
$this->sender_lastname = Tools::substr($strArgSenderLastName, 0, 32);
return true;
}
/**
* Store sender email.
*
* @param string $strArgSenderEMail
*
* @return bool
*/
public function setSenderEMail($strArgSenderEMail)
{
TNTOfficiel_Logstack::log();
$this->sender_email = Tools::substr($strArgSenderEMail, 0, 80);
return true;
}
/**
* Set sender phone.
*
* @param string $strArgSenderPhone
*
* @return bool
*/
public function setSenderPhone($strArgSenderPhone)
{
TNTOfficiel_Logstack::log();
$this->sender_phone = Tools::substr($strArgSenderPhone, 0, 15);
return true;
}
/**
* Set sender phone.
*
* @param string $strArgPickupLabelType
*
* @return bool
*/
public function setPickupLabelType($strArgPickupLabelType)
{
TNTOfficiel_Logstack::log();
if (in_array($strArgPickupLabelType, TNTOfficielAccount::$arrPickupLabelTypes, true)) {
$this->pickup_label_type = Tools::substr($strArgPickupLabelType, 0, 32);
}
return true;
}
/**
* Set pickup type.
*
* @param string $strArgSenderPphone
*
* @return bool
*/
public function setPickupType($strArgPickupType)
{
TNTOfficiel_Logstack::log();
$strPickupType = Tools::strtoupper($strArgPickupType);
if ($strPickupType !== 'OCCASIONAL') {
$strPickupType = 'REGULAR';
}
$this->pickup_type = $strPickupType;
return true;
}
/**
* Is pickup type occasional.
*
* @return bool
*/
public function isPickupTypeOccasional()
{
TNTOfficiel_Logstack::log();
if ($this->pickup_type !== 'OCCASIONAL') {
return false;
}
return true;
}
/**
* Get pickup driver time (REGULAR).
*
* @return DateTime
*/
public function getPickupDriverTime()
{
TNTOfficiel_Logstack::log();
$strArgPDT = $this->pickup_driver_time;
// Check Time.
if ($strArgPDT && preg_match('/^([0-9]{2}):([0-9]{2}):([0-9]{2})$/ui', $strArgPDT) === 1) {
$objDateTimePDTCheck = DateTime::createFromFormat('H:i:s', $strArgPDT);
if (is_object($objDateTimePDTCheck)) {
$strPDTCheck = $objDateTimePDTCheck->format('H:i:s');
if ($strArgPDT === $strPDTCheck) {
return $objDateTimePDTCheck;
}
}
}
$objDateTimePDTDefault = DateTime::createFromFormat('H:i:s', '17:00:00');
return $objDateTimePDTDefault;
}
/**
* Get pickup closing time (OCCASIONAL).
*
* @return DateTime
*/
public function getPickupClosingTime()
{
TNTOfficiel_Logstack::log();
$strArgPCT = $this->pickup_closing_time;
// Check EDD.
if ($strArgPCT && preg_match('/^([0-9]{2}):([0-9]{2}):([0-9]{2})$/ui', $strArgPCT) === 1) {
$objDateTimePCTCheck = DateTime::createFromFormat('H:i:s', $strArgPCT);
if (is_object($objDateTimePCTCheck)) {
$strPCTCheck = $objDateTimePCTCheck->format('H:i:s');
if ($strArgPCT === $strPCTCheck) {
return $objDateTimePCTCheck;
}
}
}
$objDateTimePCTDefault = DateTime::createFromFormat('H:i:s', '17:00:00');
return $objDateTimePCTDefault;
}
/**
* Create a new Prestashop carrier, flagged with module name.
* Save TNT associated account, type and code to model.
*
* @param string $strArgCarrierType
* @param string $strArgCarrierCode1
* @param string $strArgCarrierCode2
*
* @return bool
*/
public function createCarrier($strArgAccountType, $strArgCarrierType, $strArgCarrierCode1, $strArgCarrierCode2)
{
TNTOfficiel_Logstack::log();
if (!TNTOfficielCarrier::isWhiteListed(
$strArgAccountType,
$strArgCarrierType,
$strArgCarrierCode1,
$strArgCarrierCode2
)) {
return false;
}
$arrObjPSShopList = $this->getPSShopList();
$arrCarrierCreated = array();
foreach ($arrObjPSShopList as $intShopID => $objShop) {
$boolExist = TNTOfficielCarrier::isExist(
$intShopID,
$strArgAccountType,
$strArgCarrierType,
$strArgCarrierCode1,
$strArgCarrierCode2
);
if ($boolExist) {
continue;
}
$boolResult = true;
// Creating a new Prestashop Carrier.
$objPSCarrierNew = new Carrier();
$objPSCarrierNew->active = true;
$objPSCarrierNew->deleted = false;
// Carrier used for module.
$objPSCarrierNew->is_module = true;
$objPSCarrierNew->external_module_name = TNTOfficiel::MODULE_NAME;
// Carrier name.
$objPSCarrierNew->name = TNTOfficiel::CARRIER_NAME;
// Carrier delay description per language ISO code [1-128] characters.
$arrDelay = array(
'fr' => '-'
);
$arrDelay[Configuration::get('PS_LANG_DEFAULT')] = '-';
$objPSCarrierNew->delay = $arrDelay;
// Applying tax rules group (0: Disable).
$objPSCarrierNew->id_tax_rules_group = 0;
// Use default shipping method (weight or price).
$objPSCarrierNew->shipping_method = Carrier::SHIPPING_METHOD_DEFAULT;
// Disable adding handling charges from config PS_SHIPPING_HANDLING.
$objPSCarrierNew->shipping_handling = false;
// Enable use of Cart getPackageShippingCost, getOrderShippingCost or getOrderShippingCostExternal
$objPSCarrierNew->shipping_external = true;
// Enable calculations for the ranges.
$objPSCarrierNew->need_range = true;
$objPSCarrierNew->range_behavior = 0;
// If unable to create new Prestashop Carrier.
// NOTE : Add() set the carrier id_reference. Do not use save().
if (!$objPSCarrierNew->add()) {
return false;
}
// Get new ID.
$intCarrierIDNew = (int)$objPSCarrierNew->id;
// Reload
$objPSCarrierCreated = TNTOfficielCarrier::getPSCarrier($intCarrierIDNew);
if ($objPSCarrierCreated === null) {
return false;
}
// Create a new TNT carrier model using the created Prestashop carrier ID.
$objTNTCarrierModel = TNTOfficielCarrier::loadCarrierID($intCarrierIDNew, true);
// If fail.
if ($objTNTCarrierModel === null) {
return false;
}
// Get current account for this shop (or create it from inherit).
$objTNTShopAccountModel = TNTOfficielAccount::loadContextShop($intShopID);
// If fail.
if ($objTNTShopAccountModel === null) {
return false;
}
$objTNTCarrierModel->id_account = $objTNTShopAccountModel->id;
$objTNTCarrierModel->id_shop = $intShopID;
$objTNTCarrierModel->account_type = $strArgAccountType;
$objTNTCarrierModel->carrier_type = $strArgCarrierType;
$objTNTCarrierModel->carrier_code1 = $strArgCarrierCode1;
$objTNTCarrierModel->carrier_code2 = $strArgCarrierCode2;
$boolResult = $objTNTCarrierModel->save() && $boolResult;
$objCarrierInfos = $objTNTCarrierModel->getCarrierInfos();
if ($objCarrierInfos === null) {
return false;
}
// Carrier name.
$objPSCarrierCreated->name = $objCarrierInfos->label;
$objPSCarrierCreated->name = Tools::substr($objPSCarrierCreated->name, 0, 64);
// Carrier delay description per language ISO code [1-128] characters.
$arrDelay = array(
'fr' => $objCarrierInfos->delay
);
$arrDelay[Configuration::get('PS_LANG_DEFAULT')] = $objCarrierInfos->delay;
foreach ($arrDelay as $k => $strDelay) {
$arrDelay[$k] = Tools::substr($strDelay, 0, 128);
}
//
$objPSCarrierCreated->delay = $arrDelay;
// Shortest shipping delay.
$objPSCarrierCreated->grade = 9;
// All shop context required for lang.
Shop::setContext(Shop::CONTEXT_ALL);
$boolResult = $objPSCarrierCreated->save() && $boolResult;
// Restore shop context according to account.
$this->restorePSShopContext();
$intCarrierTaxRulesGroupID = 0;
// Find Taxe Rule Group : FR 20%, Enabled, Non-Deleted, named like 'FR\ Taux\ standard'.
$intCountryFRID = (int)Country::getByIso('FR');
$arrTaxRulesGroup = TaxRulesGroup::getAssociatedTaxRatesByIdCountry($intCountryFRID);
foreach ($arrTaxRulesGroup as $intTaxRulesGroupID => $strTaxAmount) {
if ((int)$strTaxAmount === 20) {
$objTaxRulesGroup = new TaxRulesGroup((int)$intTaxRulesGroupID);
if ($objTaxRulesGroup->active
&& (!property_exists($objTaxRulesGroup, 'deleted') || !$objTaxRulesGroup->deleted)
&& preg_match('/^FR\ Taux\ standard/ui', $objTaxRulesGroup->name) === 1
) {
$intCarrierTaxRulesGroupID = (int)$intTaxRulesGroupID;
break;
}
}
}
// Applying tax rules group (0: Disable).
$objPSCarrierCreated->setTaxRulesGroup($intCarrierTaxRulesGroupID);
// Add groups.
$arrGroupID = array();
$arrGroupList = Group::getGroups(Context::getContext()->language->id, $intShopID);
foreach ($arrGroupList as $arrGroup) {
$arrGroupID[] = (int)$arrGroup['id_group'];
$objPSCarrierCreated->setGroups($arrGroupID);
}
// Add Price Range.
$objRangePrice = new RangePrice();
$objRangePrice->id_carrier = $intCarrierIDNew;
$objRangePrice->delimiter1 = '0';
$objRangePrice->delimiter2 = '1000000';
$objRangePrice->add();
// Add Weight Range.
$objRangeWeight = new RangeWeight();
$objRangeWeight->id_carrier = $intCarrierIDNew;
$objRangeWeight->delimiter1 = '0';
$objRangeWeight->delimiter2 = '1000000';
$objRangeWeight->add();
// Add active zones list.
$arrZoneList = Zone::getZones(true);
foreach ($arrZoneList as $arrZone) {
$objPSCarrierCreated->addZone((int)$arrZone['id_zone']);
}
// Add carrier logo.
$boolResult = copy(
_PS_MODULE_DIR_.TNTOfficiel::MODULE_NAME.'/views/img/logo/96x60.png',
_PS_SHIP_IMG_DIR_.$objTNTCarrierModel->id_carrier.'.jpg'
) && $boolResult;
$arrCarrierCreated[] = $intCarrierIDNew;
}
return $arrCarrierCreated;
}
/**
* Get default zone department list.
*
* @return array
*/
public function getZoneDefaultDepartments()
{
TNTOfficiel_Logstack::log();
$arrZoneDefaultDepartments = array_diff(
TNTOfficielAccount::$arrDepartments,
array_merge(
$this->getZone1Departments(),
$this->getZone2Departments()
)
);
return $arrZoneDefaultDepartments;
}
/**
* Get all department list.
*
* @return array
*/
public function getZoneAllDepartments()
{
TNTOfficiel_Logstack::log();
return TNTOfficielAccount::$arrDepartments;
}
/**
* set zone 1 & 2 department list.
*
* @param array $arrZone1Departments
* @param array $arrZone2Departments
*
* @return bool true if success, false if Zone 1 and 2 have common departments.
*/
public function setZoneDepartments($arrZone1Departments, $arrZone2Departments)
{
TNTOfficiel_Logstack::log();
if (!is_array($arrZone1Departments)) {
$arrZone1Departments = array();
}
if (!is_array($arrZone2Departments)) {
$arrZone2Departments = array();
}
$arrZone1Departments = array_intersect(TNTOfficielAccount::$arrDepartments, $arrZone1Departments);
$arrZone2Departments = array_intersect(TNTOfficielAccount::$arrDepartments, $arrZone2Departments);
if (count(array_intersect($arrZone1Departments, $arrZone2Departments)) > 0) {
return false;
}
$this->zone1_departments = serialize($arrZone1Departments);
$this->zone2_departments = serialize($arrZone2Departments);
return true;
}
/**
* @return array
*/
public function getZone1Departments()
{
TNTOfficiel_Logstack::log();
$arrZone1Departments = Tools::unSerialize($this->zone1_departments);
if (!is_array($arrZone1Departments)) {
$arrZone1Departments = array();
}
return $arrZone1Departments;
}
/**
* @return array
*/
public function getZone2Departments()
{
TNTOfficiel_Logstack::log();
$arrZone2Departments = Tools::unSerialize($this->zone2_departments);
if (!is_array($arrZone2Departments)) {
$arrZone2Departments = array();
}
return $arrZone2Departments;
}
public function getZipCodeZone($strArgZipCode = null)
{
TNTOfficiel_Logstack::log();
if ($strArgZipCode === null) {
return 0;
}
$strDepartment = Tools::substr($strArgZipCode, 0, 2);
$arrZone1Departments = $this->getZone1Departments();
$arrZone2Departments = $this->getZone2Departments();
if (in_array($strDepartment, $arrZone2Departments)) {
return 2;
}
if (in_array($strDepartment, $arrZone1Departments)) {
return 1;
}
return 0;
}
/**
*
* @return TNTOfficiel_SoapClient
*/
private function initWebService()
{
TNTOfficiel_Logstack::log();
$this->objWebServiceTNT = new TNTOfficiel_SoapClient(
$this->account_number,
$this->account_login,
$this->getAccountPassword()
);
}
public function isCorrectAuthentication()
{
TNTOfficiel_Logstack::log();
return $this->objWebServiceTNT->isCorrectAuthentication();
}
public function citiesGuide($strArgCountryISO, $strArgZipCode, $strArgCity = null)
{
TNTOfficiel_Logstack::log();
return $this->objWebServiceTNT->citiesGuide($strArgCountryISO, $strArgZipCode, $strArgCity);
}
public function dropOffPoints($strArgZipCode, $strArgCity, $strArgEDD = null)
{
TNTOfficiel_Logstack::log();
if ($this->getAuthValidatedDateTime() === null) {
return null;
}
return $this->objWebServiceTNT->dropOffPoints($strArgZipCode, $strArgCity, $strArgEDD);
}
public function tntDepots($strArgZipCode, $strArgCity, $strArgEDD = null)
{
TNTOfficiel_Logstack::log();
if ($this->getAuthValidatedDateTime() === null) {
return null;
}
return $this->objWebServiceTNT->tntDepots($strArgZipCode, $strArgCity, $strArgEDD);
}
public function availabilities()
{
TNTOfficiel_Logstack::log();
$arrResult = array();
if ($this->getAuthValidatedDateTime() === null) {
return $arrResult;
}
$arrResultFeasibilities = array(
'boolIsRequestComError' => false,
'arrTNTServiceList' => array()
);
foreach (TNTOfficielCarrier::$arrCarrierTypeList as $strCarrierType) {
$arrResultFeasibility = $this->objWebServiceTNT->feasibility($strCarrierType);
$arrResultFeasibilities['boolIsRequestComError']
= $arrResultFeasibilities['boolIsRequestComError'] || $arrResultFeasibility['boolIsRequestComError'];
$arrResultFeasibilities['arrTNTServiceList'] = array_merge(
$arrResultFeasibilities['arrTNTServiceList'],
$arrResultFeasibility['arrTNTServiceList']
);
}
// Filtering ...
foreach ($arrResultFeasibilities['arrTNTServiceList'] as $arrCarrierFeasibilities) {
if (TNTOfficielCarrier::isWhiteListed(
$arrCarrierFeasibilities['accountType'],
$arrCarrierFeasibilities['carrierType'],
$arrCarrierFeasibilities['carrierCode1'],
$arrCarrierFeasibilities['carrierCode2']
)) {
$strID = implode(':', array(
$arrCarrierFeasibilities['accountType'],
$arrCarrierFeasibilities['carrierType'],
$arrCarrierFeasibilities['carrierCode1'],
$arrCarrierFeasibilities['carrierCode2']
));
$arrResult[$strID] = array_intersect_key(
$arrCarrierFeasibilities,
array(
'accountType' => null,
'carrierType' => null,
'carrierCode1' => null,
'carrierCode2' => null,
'carrierLabel' => null
)
);
}
}
return $arrResult;
}
/**
* @param string $strArgReceiverZipCode
* @param string $strArgReceiverCity
* @param string $strArgShippingDate
* @param array $arrArgCarrierTypeList
*
* @return array
*/
public function feasibility(
$strArgReceiverZipCode,
$strArgReceiverCity,
$strArgShippingDate = null,
array $arrArgCarrierTypeList = array()
) {
TNTOfficiel_Logstack::log();
if ($this->getAuthValidatedDateTime() === null) {
return null;
}
$arrCarrierTypeList = TNTOfficielCarrier::$arrCarrierTypeList;
if (count($arrArgCarrierTypeList) > 0) {
$arrCarrierTypeList = array_intersect(TNTOfficielCarrier::$arrCarrierTypeList, $arrArgCarrierTypeList);
}
$arrResult = array(
'arrTNTServiceList' => array()
);
// For each carrier type.
foreach ($arrCarrierTypeList as $strCarrierType) {
$arrResultFeasibility = $this->objWebServiceTNT->feasibility(
$strCarrierType,
$this->sender_zipcode,
$this->sender_city,
$strArgReceiverZipCode,
$strArgReceiverCity,
null,
$strArgShippingDate
);
// If communication error.
if ($arrResultFeasibility['boolIsRequestComError']) {
// Stop search here.
break;
}
$arrResult['arrTNTServiceList'] = array_merge(
$arrResult['arrTNTServiceList'],
$arrResultFeasibility['arrTNTServiceList']
);
}
// Filtering : Saturday delivery is excluded for 'ENTERPRISE' or 'DEPOT' (non free option).
$arrTNTServiceList = array();
foreach ($arrResult['arrTNTServiceList'] as $arrTNTService) {
if ($arrTNTService['saturdayDelivery'] == 0
&& in_array($arrTNTService['carrierType'], array('ENTERPRISE', 'DEPOT'))
|| in_array($arrTNTService['carrierType'], array('INDIVIDUAL', 'DROPOFFPOINT'))
) {
$arrTNTServiceList[] = $arrTNTService;
}
}
return $arrTNTServiceList;
}
/**
* feasibility like, but takes into account :
* - the order's preparation delay before shipment.
* - the first pickup date available, and cutoff time.
* - 2nd try using the next weekday.
*
* @param string $strArgReceiverZipCode
* @param string $strArgReceiverCity
* @param int $intArgShippingDelay Delay in weekdays.
* @param array $arrArgCarrierTypeList
*
* @return array
*/
public function feasibilities(
$strArgReceiverZipCode,
$strArgReceiverCity,
array $arrArgCarrierTypeList = array()
) {
TNTOfficiel_Logstack::log();
if ($this->getAuthValidatedDateTime() === null) {
return null;
}
$arrResult = array(
'arrTNTServiceList' => array()
);
// Date Today.
$objDateTimeToday = new DateTime('midnight');
$strDateToday = $objDateTimeToday->format('Y-m-d');
$arrResultPickup = $this->getPickupDate($strDateToday);
// Pickup cut-off time ('H:i').
$strPickupCutOffTime = $arrResultPickup['cutOffTime'];
// Pickup first available date ('Y-m-d').
$strPickupDateOrigin = $arrResultPickup['pickupDate'];
$intPickupDateOrigin = strtotime($strPickupDateOrigin);
$intShippingDelay = (int)$this->pickup_preparation_days;
// Undo
if (date('Hi') >= str_replace(':', '', $strPickupCutOffTime)) {
$intShippingDelay--;
if ($intShippingDelay < 0) {
$intShippingDelay = 0;
}
}
$strShippingDateDelayed = date('Y-m-d', strtotime('+'.$intShippingDelay.' weekdays', $intPickupDateOrigin));
TNTOfficiel_Logstack::dump(array(
'strDateToday' => $strDateToday,
'strPickupDateOrigin' => $strPickupDateOrigin,
'strPickupCutOffTime' => $strPickupCutOffTime,
'intShippingDelay' => $intShippingDelay,
'strShippingDateDelayed' => $strShippingDateDelayed
));
$arrShippingDateList = array(
$strShippingDateDelayed,
// Try next open day (weekdays).
date('Y-m-d', strtotime('+1 weekdays', strtotime($strShippingDateDelayed)))
);
// For each date.
foreach ($arrShippingDateList as $strShippingDate) {
$arrResult['arrTNTServiceList'] = $this->feasibility(
$strArgReceiverZipCode,
$strArgReceiverCity,
$strShippingDate,
$arrArgCarrierTypeList
);
// If any result.
if (count($arrResult['arrTNTServiceList']) > 0) {
// Stop search here.
break;
}
// else its may be holidays...loop using next date.
}
return $arrResult['arrTNTServiceList'];
}
/**
* Get the pickup date and the cut-off time depending on the pickup type.
*
* @param string $strArgPickupDate
*
* @return array
*/
public function getPickupDate($strArgPickupDate = null)
{
TNTOfficiel_Logstack::log();
if ($this->getAuthValidatedDateTime() === null) {
return null;
}
// Date Now.
$objDateTimeNow = new DateTime('now');
// Date Today.
$objDateTimeToday = new DateTime('midnight');
$strDateToday = $objDateTimeToday->format('Y-m-d');
// Date Next WeekDay.
$objDateTimeNextWeekDay = new DateTime('midnight +1 weekdays');
$strDateNextWeekDay = $objDateTimeNextWeekDay->format('Y-m-d');
// Default Pickup date requested is today.
$strPickupDate = $strDateToday;
// Check pickup date for apply.
if (is_string($strArgPickupDate)
&& preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/ui', $strArgPickupDate, $arrBackRef) === 1
&& checkdate((int)$arrBackRef[2], (int)$arrBackRef[3], (int)$arrBackRef[1])
) {
$strPickupDate = $strArgPickupDate;
}
// If pickup type is occasional, else is regular.
if ($this->isPickupTypeOccasional()) {
// Get today pickup availability for sender location.
$arrResultPickup = $this->objWebServiceTNT->getPickupContext(
$this->sender_zipcode,
$this->sender_city,
$strPickupDate
);
} else {
$arrResultPickup = array(
'boolIsRequestComError' => false,
'strResponseMsgError' => null,
// Pickup first available date is the requested date ('Y-m-d').
'pickupDate' => $strPickupDate,
// Pickup cut-off time is the driver time from account ('H:i').
'cutOffTime' => $this->getPickupDriverTime()->format('H:i'),
'pickupOnMorning' => null
);
// If the requested date is today and the current time is greater than the driver time.
if ($strPickupDate === $strDateToday
&& $objDateTimeNow->format('Hi') > $this->getPickupDriverTime()->format('Hi')
) {
// Available date is the next weekday.
$arrResultPickup['pickupDate'] = $strDateNextWeekDay;
}
}
return $arrResultPickup;
}
/**
* @param string $strArgReceiverType
* @param string $strDeliveryPointCode
* @param string $strArgReceiverCompany
* @param string $strArgReceiverAddress1
* @param string $strArgReceiverAddress2
* @param string $strArgReceiverZipCode
* @param string $strArgReceiverCity
* @param string $strArgReceiverLastName
* @param string $strArgReceiverFirstName
* @param string $strArgReceiverEMail
* @param string $strArgReceiverPhone
* @param string $strArgReceiverBuilding
* @param string $strArgReceiverAccessCode
* @param string $strArgReceiverFloor
* @param string $strArgCarrierCode
* @param string $strArgPickupDate
* @param array $arrArgParcelRequest
* @param bool $boolArgNewPickup
*
* @return type
*/
public function expeditionCreation(
$strArgReceiverType,
$strDeliveryPointCode,
$strArgReceiverCompany,
$strArgReceiverAddress1,
$strArgReceiverAddress2,
$strArgReceiverZipCode,
$strArgReceiverCity,
$strArgReceiverLastName,
$strArgReceiverFirstName,
$strArgReceiverEMail,
$strArgReceiverPhone,
$strArgReceiverBuilding,
$strArgReceiverAccessCode,
$strArgReceiverFloor,
$strArgCarrierCode,
$strArgPickupDate,
$arrArgParcelRequest,
$boolArgNewPickup,
$fltArgPaybackAmount = null
) {
TNTOfficiel_Logstack::log();
if ($this->getAuthValidatedDateTime() === null) {
return array(
'boolIsRequestComError' => false,
'strResponseMsgError' => 'TNTOfficielAccount invalid credentials for TNTOfficielAccount ID #'.$this->id
);
}
if ($fltArgPaybackAmount !== null
&& $fltArgPaybackAmount > 10000.0
) {
return array(
'boolIsRequestComError' => false,
'strResponseMsgError' => 'Le contre paiement par chèque est de 10 000 Euros maximum.'
);
}
$arrResult = $this->objWebServiceTNT->expeditionCreation(
$this->sender_company,
$this->sender_address1,
$this->sender_address2,
$this->sender_zipcode,
$this->sender_city,
$this->sender_lastname,
$this->sender_firstname,
$this->sender_email,
$this->sender_phone,
$strArgReceiverType,
$strDeliveryPointCode,
$strArgReceiverCompany,
$strArgReceiverAddress1,
$strArgReceiverAddress2,
$strArgReceiverZipCode,
$strArgReceiverCity,
$strArgReceiverLastName,
$strArgReceiverFirstName,
$strArgReceiverEMail,
$strArgReceiverPhone,
$strArgReceiverBuilding,
$strArgReceiverAccessCode,
$strArgReceiverFloor,
$this->delivery_notification,
$strArgCarrierCode,
$strArgPickupDate,
$arrArgParcelRequest,
$this->isPickupTypeOccasional(),
$this->pickup_label_type,
$this->getPickupClosingTime()->format('H:i'),
$boolArgNewPickup,
$fltArgPaybackAmount
);
return $arrResult;
}
public function trackingByConsignment($strArgParcelNumber)
{
TNTOfficiel_Logstack::log();
if ($this->getAuthValidatedDateTime() === null) {
return null;
}
return $this->objWebServiceTNT->trackingByConsignment($strArgParcelNumber);
}
}