* @copyright 2023 DPD France S.A.S.
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
if (!defined('_PS_VERSION_')) {
exit;
}
// Autoloader Composer. Doit être chargé avant tout le reste.
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config/config.inc.php';
use PrestaShop\Module\DPDFrance\ExternalContentProvider\EprintProvider;
use PrestaShop\Module\DPDFrance\ExternalContentProvider\PudoProvider;
use PrestaShop\Module\DPDFrance\ExternalContentProvider\LeadtimeProvider;
use PrestaShop\Module\DPDFrance\Util\DPDCompliancy;
use PrestaShop\Module\DPDFrance\Util\DPDConfig;
use PrestaShop\Module\DPDFrance\Util\DPDTools;
class DPDFrance extends CarrierModule
{
// DPD CLASS PROPERTIES
/**
* @var string
*/
private $jsPath;
/**
* @var string
*/
private $cssPath;
/**
* @var string
*/
private $imgPath;
/**
* @var string
*/
private $docsPath;
/**
* @var string
*/
private $logoPath;
/**
* @var string
*/
private $modulePath;
/**
* Configuration Relais
* @var array
*/
private $configCarrierRelais;
/**
* Configuration Predict
* @var array
*/
private $configCarrierPredict;
/**
* Configuration Classic
* @var array
*/
private $configCarrierClassic;
/**
* Configuration World
* @var array
*/
private $configCarrierWorld;
public $multishop_context;
private $multishop_context_group;
public function __construct()
{
$this->name = 'dpdfrance';
$this->tab = 'shipping_logistics';
$this->version = '6.2.0';
$this->author = 'DPD France S.A.S. debug by Eolia';
$this->module_key = '41c64060327b5afada101ff25bd38850';
$this->ps_versions_compliancy = ['min' => '1.6.1.0', 'max' => '1.7.0.0'];
$this->multishop_context = Shop::CONTEXT_ALL | Shop::CONTEXT_GROUP | Shop::CONTEXT_SHOP;
$this->multishop_context_group = Shop::CONTEXT_GROUP;
parent::__construct();
$this->displayName = $this->l('DPD France');
$this->description = $this->l("Offer DPD's fast and reliable delivery services to your customers");
$this->limited_countries = ['fr'];
$this->confirmUninstall = $this->l('Warning: all the data saved in your database will be deleted. Are you sure you want uninstall this module?');
// Settings paths
$this->modulePath = $this->_path;
$this->jsPath = $this->_path . 'views/js/';
$this->cssPath = $this->_path . 'views/css/';
$this->imgPath = $this->_path . 'views/img/';
$this->docsPath = $this->_path . 'docs/';
$this->logoPath = $this->_path . 'logo.png';
// Settings Carrier configuration
$this->configCarrierRelais = [
'name' => 'Livraison en relais Pickup',
'id_tax_rules_group' => 0,
'url' => DPDTools::PREFIX_TRACEX_URL . '@',
'active' => true,
'deleted' => 0,
'shipping_handling' => false,
'range_behavior' => 1,
'is_module' => true,
'delay' => [
'fr' => 'Livraison 24-48h en France vers plus de 8500 relais Pickup.',
'en' => '24-48h delivery in one of our 8500 pick-up points.',
'es' => 'Entrega en 24 a 48 horas en una de nuestras 8500 tiendas.',
'it' => 'Consegna in 24 a 48 ore in uno dei nostri 8.500 negozi.',
'de' => '24-48 Stunden Lieferung in einem unserer 8.500 Geschäften.',
],
'id_zone' => 1,
'shipping_external' => true,
'external_module_name' => 'dpdfrance',
'need_range' => true,
'grade' => 9,
];
$this->configCarrierPredict = [
'name' => 'Livraison à domicile Predict sur créneau horaire',
'id_tax_rules_group' => 0,
'url' => DPDTools::PREFIX_TRACEX_URL . '@',
'active' => true,
'deleted' => 0,
'shipping_handling' => false,
'range_behavior' => 1,
'is_module' => true,
'delay' => [
'fr' => 'Livraison sur créneau horaire sous 24-48h en France',
'en' => 'Time slot delivery within 24-48 hours in France',
'es' => 'Entrega en una franja horaria en 24/48 horas en Francia',
'it' => 'Consegna della fascia oraria entro 24-48 ore in Francia',
'de' => 'Zeitfenster-Zustellung innerhalb von 24-48 Stunden in Frankreich',
],
'id_zone' => 1,
'shipping_external' => true,
'external_module_name' => 'dpdfrance',
'need_range' => true,
'grade' => 9,
];
$this->configCarrierClassic = [
'name' => 'Livraison sur lieu de travail',
'id_tax_rules_group' => 0,
'url' => DPDTools::PREFIX_TRACEX_URL . '@',
'active' => true,
'deleted' => 0,
'shipping_handling' => false,
'range_behavior' => 1,
'is_module' => true,
'delay' => [
'fr' => 'Livraison 24-48h du lundi au vendredi pour tous ceux qui font le choix de recevoir leur colis sur leur lieu de travail.',
'en' => '24-48h delivery at your workplace only.',
'es' => 'Entrega en 24 a 48 horas en su lugar de trabajo.',
'it' => 'Consegna in 24 a 48 ore sul posto di lavoro.',
'de' => '24-48 Stunden Lieferung an Ihrem Arbeitsplatz.',
],
'id_zone' => 1,
'shipping_external' => true,
'external_module_name' => 'dpdfrance',
'need_range' => true,
'grade' => 9,
];
$this->configCarrierWorld = [
'name' => 'Livraison internationale par DPD',
'id_tax_rules_group' => 0,
'url' => DPDTools::PREFIX_TRACEX_URL . '@',
'active' => true,
'deleted' => 0,
'shipping_handling' => false,
'range_behavior' => 1,
'is_module' => true,
'delay' => [
'fr' => 'Livraison partout en Europe et dans le monde entier avec la fiabilité du réseau DPD.',
'en' => 'Delivery all over the world with the reliability of DPD network.',
'es' => 'Entrega mundial con la confiabilidad de la red DPD.',
'it' => 'Consegna in tutto il mondo con l affidabilità della rete di DPD.',
'de' => 'Lieferung in der ganzen Welt mit der Zuverlässigkeit der DPD Netzwerk.',
],
'id_zone' => 1,
'shipping_external' => true,
'external_module_name' => 'dpdfrance',
'need_range' => true,
'grade' => 9,
];
// Check if the module is DISABLED
if (!DPDConfig::isModuleEnabled()) {
$this->warning = $this->l('Please proceed to the configuration of the DPD plugin');
}
// Check if php soap extension is load
if (!extension_loaded('soap')) {
$this->warning = $this->l('Warning! The PHP extension SOAP is not installed on this server. You must activate it in order to use the DPD plugin');
}
// Check if php xml extension is load
if (!extension_loaded('xml')) {
$this->warning = $this->l('Warning! The PHP extension XML is not installed on this server. You must activate it in order to use the DPD plugin');
}
// Check if php xml extension is load
if (!extension_loaded('curl')) {
$this->warning = $this->l('Warning! The PHP extension CURL is not installed on this server. You must activate it in order to use the DPD plugin');
}
}
// METHODS ABSTRACT CARRIER MODULE CLASS
/**
* Manage the Island and Mountain zones overcost calculation to the shipping fee
* @param $params
* @param float $shipping_cost
* @return false|float
*/
public function getOrderShippingCost($params, $shipping_cost)
{
if (!$this->context->cart instanceof Cart) {
$this->context->cart = new Cart((int)$params->id);
}
$address = new Address($this->context->cart->id_address_delivery);
$isoCode = Country::getIsoById($address->id_country);
if ($isoCode !== 'FR') {
return $shipping_cost;
}
$idAddress = $this->context->cart->id_address_delivery;
$postCode = DPDTools::getPostcodeByAddress($idAddress);
if (Tools::substr($postCode, 0, 2) === '20') {
$shipping_cost += DPDConfig::get('DPDFRANCE_SUPP_ILES');
if (DPDConfig::get('DPDFRANCE_SUPP_ILES') < 0) {
return false;
}
}
if (in_array($postCode, DPDTools::ISLANDS_ZONE, true)) {
$shipping_cost += DPDConfig::get('DPDFRANCE_SUPP_ILES');
if (DPDConfig::get('DPDFRANCE_SUPP_ILES') < 0) {
return false;
}
}
if (in_array($postCode, DPDTools::MOUNTAINS_ZONE, true)) {
$shipping_cost += DPDConfig::get('DPDFRANCE_SUPP_MONTAGNE');
if (DPDConfig::get('DPDFRANCE_SUPP_MONTAGNE') < 0) {
return false;
}
}
return $shipping_cost;
}
/**
* @param $params
* @return mixed
*/
public function getOrderShippingCostExternal($params)
{
return $params;
}
// INSTALL
/**
* Install Admin Tab AdminDPDFrance and AdminDPDFranceReturn,
* Register Hooks,
* Register Module's Settings Options
*
* @return bool
* @throws PrestaShopDatabaseException
*/
public function install()
{
if (
parent::install()
&& $this->registerAllHooks()
&& $this->installConfigDB()
&& $this->installDPDConfigurations()
&& $this->installModuleTab('AdminDPDFrance', 'DPD France livraison', Tab::getInstanceFromClassName('AdminParentOrders')->id)
&& $this->installModuleTab('AdminDPDFranceReturn', 'DPD France retour', Tab::getInstanceFromClassName('AdminParentOrders')->id)
) {
return true;
}
$this->_errors[] = $this->l('An error occurred during the installation. Please contact our technical support at support.ecommerce@dpd.fr for more information.');
return false;
}
/**
* Register all hooks
* @return bool
*/
protected function registerAllHooks()
{
return !(
!$this->registerHook('displayHeader')
|| !$this->registerHook('displayBackOfficeHeader')
|| !$this->registerHook('displayCarrierList')
|| !$this->registerHook('actionCarrierUpdate')
|| !$this->registerHook('actionValidateOrder')
|| !$this->registerHook('displayCheckoutSummaryTop')
|| !$this->registerHook('displayPaymentTop')
|| !$this->registerHook('moduleRoutes')
);
}
/**
* Install default DPD France configuration
* @return bool
*/
protected function installDPDConfigurations()
{
return Configuration::updateValue('DPDFRANCE_PARAM', '0')
&& Configuration::updateValue('DPDFRANCE_NOM_EXP', '')
&& Configuration::updateValue('DPDFRANCE_ADDRESS_EXP', '')
&& Configuration::updateValue('DPDFRANCE_ADDRESS2_EXP', '')
&& Configuration::updateValue('DPDFRANCE_CP_EXP', '')
&& Configuration::updateValue('DPDFRANCE_VILLE_EXP', '')
&& Configuration::updateValue('DPDFRANCE_TEL_EXP', '')
&& Configuration::updateValue('DPDFRANCE_GSM_EXP', '')
&& Configuration::updateValue('DPDFRANCE_EMAIL_EXP', '')
&& Configuration::updateValue('DPDFRANCE_RELAIS_CARRIER_ID', '')
&& Configuration::updateValue('DPDFRANCE_RELAIS_DEPOT_CODE', '')
&& Configuration::updateValue('DPDFRANCE_RELAIS_SHIPPER_CODE', '')
&& Configuration::updateValue('DPDFRANCE_PREDICT_CARRIER_ID', '')
&& Configuration::updateValue('DPDFRANCE_PREDICT_DEPOT_CODE', '')
&& Configuration::updateValue('DPDFRANCE_PREDICT_SHIPPER_CODE', '')
&& Configuration::updateValue('DPDFRANCE_CLASSIC_CARRIER_ID', '')
&& Configuration::updateValue('DPDFRANCE_CLASSIC_DEPOT_CODE', '')
&& Configuration::updateValue('DPDFRANCE_CLASSIC_SHIPPER_CODE', '')
&& Configuration::updateValue('DPDFRANCE_WEBTRACE_LOGIN', DPDTools::encrypt('1064'))
&& Configuration::updateValue('DPDFRANCE_WEBTRACE_PASSWORD', DPDTools::encrypt('Pr2%5sHg'))
// API = EPRINT
&& Configuration::updateValue('DPDFRANCE_API_LOGIN', '')
&& Configuration::updateValue('DPDFRANCE_API_PASSWORD', '')
// API = LEADTIME
&& Configuration::updateValue('DPDFRANCE_DAY_DEFINITE_MODE', '0')
&& Configuration::updateValue('DPDFRANCE_LEADTIME_API_KEY', '')
// Suppléments
&& Configuration::updateValue('DPDFRANCE_SUPP_ILES', '')
&& Configuration::updateValue('DPDFRANCE_SUPP_MONTAGNE', '')
&& Configuration::updateValue('DPDFRANCE_GOOGLE_API_KEY', '')
&& Configuration::updateValue('DPDFRANCE_FORMAT_MOD', '')
&& Configuration::updateValue('DPDFRANCE_PRINTER_CONNECT', '')
&& Configuration::updateValue('DPDFRANCE_PRINTER_PORT', '')
&& Configuration::updateValue('DPDFRANCE_PRINTER_IP', '')
&& Configuration::updateValue('DPDFRANCE_HIDE_NETWORK', '')
&& Configuration::updateValue('DPDFRANCE_PRINTER_SERIAL', '')
&& Configuration::updateValue('DPDFRANCE_FORMAT_PRINT', '')
&& Configuration::updateValue('DPDFRANCE_SERVICE_TYPE', '')
&& Configuration::updateValue('DPDFRANCE_ETAPE_EXPEDITION', (string)DPDTools::ORDER_STATUS_PROCESSING_IN_PROGRESS)
&& Configuration::updateValue('DPDFRANCE_ETAPE_EXPEDIEE', (string)DPDTools::ORDER_STATUS_SHIPPED)
&& Configuration::updateValue('DPDFRANCE_ETAPE_LIVRE', (string)DPDTools::ORDER_STATUS_DELIVERED)
&& Configuration::updateValue('DPDFRANCE_AD_VALOREM', '')
&& Configuration::updateValue('DPDFRANCE_AUTO_UPDATE', (string)DPDTools::DPD_AUTOUPDATE_DISABLED)
&& Configuration::updateValue('DPDFRANCE_MARKETPLACE_MODE', '')
&& Configuration::updateValue('DPDFRANCE_RETOUR_OPTION', (string)DPDTools::NO_RETURN)
&& Configuration::updateValue('DPDFRANCE_LAST_TRACKING', '');
}
/**
* Create Table DPDFRANCE_ORDER, DPDFRANCE_SHIPPING, DPDFRANCE_RELAIS_STORAGE, Alter Column Properties
* @return bool
* @throws PrestaShopDatabaseException
*/
public function installConfigDB()
{
// Creation de la table dpdfrance_order
$sqlDPDOrder = '
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'dpdfrance_order` (
`id_order` int(10) unsigned NOT NULL,
`id_order_dpd` varchar(20) NOT NULL,
# Compatibilité GEOLABEL
`id_shipment_number_dpd` varchar(64),
`id_retour_order_dpd` varchar(64),
`error_message` text,
`override_return_street` varchar(35),
`override_return_zip` varchar(10),
`override_return_city` varchar(35),
`override_return_phone` varchar(30),
`return_print` tinyint(1),
PRIMARY KEY(id_order,id_order_dpd))
ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;';
if (!Db::getInstance()->Execute($sqlDPDOrder)) {
return false;
}
// Creation de la table dpdfrance_shipping
$sqlDPDShipping = '
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'dpdfrance_shipping` (
`id` int(10) unsigned NULL AUTO_INCREMENT,
`id_customer` int(10) unsigned NOT NULL,
`id_cart` int(10) unsigned NOT NULL,
`id_carrier` int(5) unsigned DEFAULT NULL,
`service` varchar(3) DEFAULT NULL,
`relay_id` varchar(8) DEFAULT NULL,
`company` varchar(32) DEFAULT NULL,
`address1` varchar(128) DEFAULT NULL,
`address2` varchar(128) DEFAULT NULL,
`postcode` varchar(10) DEFAULT NULL,
`city` varchar(100) DEFAULT NULL,
`id_country` int(11) DEFAULT NULL,
`gsm_dest` varchar(14) DEFAULT NULL,
PRIMARY KEY(id_cart))
ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;';
if (!Db::getInstance()->Execute($sqlDPDShipping)) {
return false;
}
// Creation de la table dpdfrance_relais_storage
$sqlDPDRelais = '
CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'dpdfrance_relais_storage` (
`id_cart` INT UNSIGNED NOT NULL,
`id_customer` INT UNSIGNED NOT NULL,
`search_relay` TEXT NOT NULL,
`relay_list` TEXT NOT NULL,
PRIMARY KEY (`id_cart`, `id_customer`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;';
if (!Db::getInstance()->Execute($sqlDPDRelais)) {
return false;
}
if (DPDCompliancy::isMyPrestashopVersion('<', '8.0.0')) {
// Alteration de la colonne shipping_number de 32 a 64 chars
// Celle-ci n'existe plus à partir de la version 8 et était dépréciée en 1.7.
$sqlDPDAlterationTable = 'ALTER TABLE ' . _DB_PREFIX_ . 'orders CHANGE `shipping_number` `shipping_number` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL';
if (!Db::getInstance()->Execute($sqlDPDAlterationTable)) {
return false;
}
}
// Modification des caractéristiques des colonnes de la table dpdfrance_order
$this->updateSql();
// Recuperation d'un ou des zones géographiques ayant le mot "France"
$resGetZone = DPDTools::getAllFranceZones();
// Si aucune zone ayant le mot "France", on crée la zone "France", on l'active, puis on assigne le pays a la France
if (empty($resGetZone)) {
DPDTools::createFranceZone();
}
// #29526 Règle retenue : on crée la zone si elle n'existe pas. C'est tout.
// On ne touche à rien de la configuration du propriétaire de la boutique.
//$id_zone_france = [];
//if (!empty($resGetZone)) {
// // Si plusieurs zones avec France
// foreach ($resGetZone as $zone) {
// $id_zone_france[] = $zone['id_zone'];
// }
//
// // Affectation de la zone France au pays France et active le pays
// $sqlUpdateCountryZone = Db::getInstance()->update(
// 'country',
// ['id_zone' => $id_zone_france],
// 'iso_code = "FR" and active = 1'
// );
// if (!$sqlUpdateCountryZone) {
// return false;
// }
//}
return true;
}
/**
* Si un champs est manquant alors modification des caractéristiques des colonnes de la table dpdfrance_order
* @return bool
* @throws PrestaShopDatabaseException
*/
protected function updateSql()
{
$fieldsDescription = [
'id_order' => ['null' => false, 'type' => 'int(10) unsigned'],
'id_order_dpd' => ['null' => false, 'type' => 'varchar(50)'],
'id_retour_order_dpd' => ['null' => false, 'type' => 'varchar(20)'],
'id_shipment_number_dpd' => ['null' => false, 'type' => 'varchar(50)'],
'error_message' => ['null' => true, 'type' => 'text'],
'override_return_street' => ['null' => true, 'type' => 'varchar(35)'],
'override_return_zip' => ['null' => true, 'type' => 'varchar(10)'],
'override_return_city' => ['null' => true, 'type' => 'varchar(35)'],
'override_return_phone' => ['null' => true, 'type' => 'varchar(30)'],
'return_print' => ['null' => true, 'type' => 'varchar(30)'],
];
$fields = [
'id_order' => true,
'id_order_dpd' => true,
'id_retour_order_dpd' => true,
'id_shipment_number_dpd' => true,
'error_message' => true,
'override_return_street' => true,
'override_return_zip' => true,
'override_return_city' => true,
'override_return_phone' => true,
'return_print' => true,
];
$sql = 'DESCRIBE ' . _DB_PREFIX_ . 'dpdfrance_order';
$results = Db::getInstance()->executeS($sql);
foreach ($results as $field) {
if ($fields[$field['Field']]) {
$fields[$field['Field']] = false;
}
}
foreach ($fields as $key => $field) {
if ($field) {
$sql = ' ALTER TABLE ' . _DB_PREFIX_ . 'dpdfrance_order ADD ' . $key . ' ' . $fieldsDescription[$key]['type'];
if (!$fieldsDescription[$key]['null']) {
$sql .= ' NOT NULL';
}
Db::getInstance()->execute($sql);
}
}
return true;
}
/**
* Install Admin Tab
* @param string $tab_class
* @param string $tab_name
* @param false|int $id_tab_parent
* @return bool
*/
protected function installModuleTab($tab_class, $tab_name, $id_tab_parent)
{
$tab = new Tab();
$languages = Language::getLanguages(false);
foreach ($languages as $language) {
$tab->name[$language['id_lang']] = $tab_name;
}
$tab->class_name = $tab_class;
$tab->module = $this->name;
$tab->id_parent = $id_tab_parent;
return $tab->save();
}
// UPDATE
/**
* Update Admin DPD Tab
* @return void
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function updateModuleTab()
{
// On supprime les onglets du backoffice
$this->uninstallModuleTab('AdminDPDFrance');
$this->uninstallModuleTab('AdminDPDFranceReturn');
// On recrée ces onglets
$this->installModuleTab('AdminDPDFrance', 'DPD France livraison', Tab::getInstanceFromClassName('AdminParentOrders')->id);
$this->installModuleTab('AdminDPDFranceReturn', 'DPD France retour', Tab::getInstanceFromClassName('AdminParentOrders')->id);
}
// UNINSTALL
/**
* Uninstall Module , Uninstall DPD Admin tab, DPD configuration
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function uninstall()
{
return !(
!parent::uninstall()
|| !$this->uninstallModuleTab('AdminDPDFrance')
|| !$this->uninstallModuleTab('AdminDPDFranceReturn')
|| !Configuration::deleteByName('DPDFRANCE_NOM_EXP')
|| !Configuration::deleteByName('DPDFRANCE_ADDRESS_EXP')
|| !Configuration::deleteByName('DPDFRANCE_ADDRESS2_EXP')
|| !Configuration::deleteByName('DPDFRANCE_CP_EXP')
|| !Configuration::deleteByName('DPDFRANCE_VILLE_EXP')
|| !Configuration::deleteByName('DPDFRANCE_TEL_EXP')
|| !Configuration::deleteByName('DPDFRANCE_EMAIL_EXP')
|| !Configuration::deleteByName('DPDFRANCE_GSM_EXP')
|| !Configuration::deleteByName('DPDFRANCE_RELAIS_CARRIER_ID')
|| !Configuration::deleteByName('DPDFRANCE_RELAIS_DEPOT_CODE')
|| !Configuration::deleteByName('DPDFRANCE_RELAIS_SHIPPER_CODE')
|| !Configuration::deleteByName('DPDFRANCE_PREDICT_CARRIER_ID')
|| !Configuration::deleteByName('DPDFRANCE_PREDICT_DEPOT_CODE')
|| !Configuration::deleteByName('DPDFRANCE_PREDICT_SHIPPER_CODE')
|| !Configuration::deleteByName('DPDFRANCE_CLASSIC_CARRIER_ID')
|| !Configuration::deleteByName('DPDFRANCE_CLASSIC_DEPOT_CODE')
|| !Configuration::deleteByName('DPDFRANCE_CLASSIC_SHIPPER_CODE')
|| !Configuration::deleteByName('DPDFRANCE_RELAIS_MYPUDO_URL')
|| !Configuration::deleteByName('DPDFRANCE_API_LOGIN')
|| !Configuration::deleteByName('DPDFRANCE_API_PASSWORD')
|| !Configuration::deleteByName('DPDFRANCE_WEBTRACE_LOGIN')
|| !Configuration::deleteByName('DPDFRANCE_WEBTRACE_PASSWORD')
|| !Configuration::deleteByName('DPDFRANCE_DAY_DEFINITE_MODE')
|| !Configuration::deleteByName('DPDFRANCE_LEADTIME_API_KEY')
|| !Configuration::deleteByName('DPDFRANCE_SUPP_ILES')
|| !Configuration::deleteByName('DPDFRANCE_SUPP_MONTAGNE')
|| !Configuration::deleteByName('DPDFRANCE_GOOGLE_API_KEY')
|| !Configuration::deleteByName('DPDFRANCE_FORMAT_MOD')
|| !Configuration::deleteByName('DPDFRANCE_PRINTER_CONNECT')
|| !Configuration::deleteByName('DPDFRANCE_PRINTER_PORT')
|| !Configuration::deleteByName('DPDFRANCE_PRINTER_IP')
|| !Configuration::deleteByName('DPDFRANCE_HIDE_NETWORK')
|| !Configuration::deleteByName('DPDFRANCE_PRINTER_SERIAL')
|| !Configuration::deleteByName('DPDFRANCE_FORMAT_PRINT')
|| !Configuration::deleteByName('DPDFRANCE_SERVICE_TYPE')
|| !Configuration::deleteByName('DPDFRANCE_ETAPE_EXPEDITION')
|| !Configuration::deleteByName('DPDFRANCE_ETAPE_EXPEDIEE')
|| !Configuration::deleteByName('DPDFRANCE_ETAPE_LIVRE')
|| !Configuration::deleteByName('DPDFRANCE_AUTO_UPDATE')
|| !Configuration::deleteByName('DPDFRANCE_MARKETPLACE_MODE')
|| !Configuration::deleteByName('DPDFRANCE_AD_VALOREM')
|| !Configuration::deleteByName('DPDFRANCE_RETOUR_OPTION')
|| !Configuration::deleteByName('DPDFRANCE_DATA_SENT')
|| !Configuration::deleteByName('DPDFRANCE_LAST_TRACKING')
|| !Configuration::deleteByName('DPDFRANCE_PARAM')
);
}
/**
* Delete DPD Admin Tab
* @param $tab_class
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
protected function uninstallModuleTab($tab_class)
{
$tab = Tab::getInstanceFromClassName($tab_class);
if (!Validate::isLoadedObject($tab)) {
// N'existe déjà plus
return true;
}
return $tab->delete();
}
// ADMIN MODULE CONFIGURATION PAGE
/**
* [BACK OFFICE - SETUP] Method used to display the Settings option of DPD.
* @return string
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function getContent()
{
// Load dependencies
$this->loadAsset();
$output = '
' . $this->displayName . ' ';
// BEGINNING DPD DELIVERY OPTIONS
// DPD Relais carrier creation
if (Tools::isSubmit('submitCreateCarrierRelais')) {
$this->createCarrier($this->configCarrierRelais, 'relais');
$output .= '' . $this->l('DPD Relais carrier created') . '
';
$output .= '';
}
// DPD Predict carrier creation
if (Tools::isSubmit('submitCreateCarrierPredict')) {
$this->createCarrier($this->configCarrierPredict, 'predict');
$output .= '' . $this->l('Predict carrier created') . '
';
$output .= '';
}
// DPD Classic carrier creation
if (Tools::isSubmit('submitCreateCarrierClassic')) {
$this->createCarrier($this->configCarrierClassic, 'classic');
$output .= '' . $this->l('Classic carrier created') . '
';
$output .= '';
}
// DPD Intercontinental carrier creation
if (Tools::isSubmit('submitCreateCarrierWorld')) {
$this->createCarrier($this->configCarrierWorld, 'world');
$output .= '' . $this->l('Intercontinental carrier created') . '
';
$output .= '';
}
// END DPD DELIVERY OPTIONS
// * SUBMIT ALL FORM
if (Tools::isSubmit('submitRcReferer')) {
// Vos données d'expéditeur
DPDConfig::updateValue('DPDFRANCE_NOM_EXP', Tools::getValue('nom_exp'));
DPDConfig::updateValue('DPDFRANCE_ADDRESS_EXP', Tools::getValue('address_exp'));
DPDConfig::updateValue('DPDFRANCE_ADDRESS2_EXP', Tools::getValue('address2_exp'));
DPDConfig::updateValue('DPDFRANCE_CP_EXP', Tools::getValue('cp_exp'));
DPDConfig::updateValue('DPDFRANCE_VILLE_EXP', Tools::getValue('ville_exp'));
DPDConfig::updateValue('DPDFRANCE_TEL_EXP', Tools::getValue('tel_exp'));
DPDConfig::updateValue('DPDFRANCE_EMAIL_EXP', Tools::getValue('email_exp'));
DPDConfig::updateValue('DPDFRANCE_GSM_EXP', Tools::getValue('gsm_exp'));
// Services de livraison
// DPD Relais carrier reassignment
if ((int)Tools::getValue('dpdfrance_relais_carrier_id') !== DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID')) {
// Le Log ID DPD Relais est mis à jour automatiquement dans la fonction DPDConfig::updateValue()
DPDConfig::updateValue('DPDFRANCE_RELAIS_CARRIER_ID', Tools::getValue('dpdfrance_relais_carrier_id'));
$this->reaffectationCarrier(DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID'));
}
DPDConfig::updateValue('DPDFRANCE_RELAIS_DEPOT_CODE', Tools::getValue('relais_depot_code'));
DPDConfig::updateValue('DPDFRANCE_RELAIS_SHIPPER_CODE', Tools::getValue('relais_shipper_code'));
// DPD Predict carrier reassignment
if ((int)Tools::getValue('dpdfrance_predict_carrier_id') !== DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID')) {
// Le Log ID DPD Predict est mis à jour automatiquement dans la fonction DPDConfig::updateValue()
DPDConfig::updateValue('DPDFRANCE_PREDICT_CARRIER_ID', Tools::getValue('dpdfrance_predict_carrier_id'));
$this->reaffectationCarrier(DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID'));
}
DPDConfig::updateValue('DPDFRANCE_PREDICT_DEPOT_CODE', Tools::getValue('predict_depot_code'));
DPDConfig::updateValue('DPDFRANCE_PREDICT_SHIPPER_CODE', Tools::getValue('predict_shipper_code'));
// DPD Classic carrier reassignment
if ((int)Tools::getValue('dpdfrance_classic_carrier_id') !== DPDConfig::get('DPDFRANCE_CLASSIC_CARRIER_ID')) {
// Le Log ID DPD Classic est mis à jour automatiquement dans la fonction DPDConfig::updateValue()
DPDConfig::updateValue('DPDFRANCE_CLASSIC_CARRIER_ID', Tools::getValue('dpdfrance_classic_carrier_id'));
$this->reaffectationCarrier(DPDConfig::get('DPDFRANCE_CLASSIC_CARRIER_ID'));
}
DPDConfig::updateValue('DPDFRANCE_CLASSIC_DEPOT_CODE', Tools::getValue('classic_depot_code'));
DPDConfig::updateValue('DPDFRANCE_CLASSIC_SHIPPER_CODE', Tools::getValue('classic_shipper_code'));
// Réglages avancés
DPDConfig::updateValue('DPDFRANCE_RELAIS_MYPUDO_URL', Tools::getValue('mypudo_url'));
DPDConfig::updateValue('DPDFRANCE_SUPP_ILES', Tools::getValue('supp_iles'));
DPDConfig::updateValue('DPDFRANCE_SUPP_MONTAGNE', Tools::getValue('supp_montagne'));
// On ne met la valeur des clés à jour que si elles on étaient saisies
if (!in_array(trim(Tools::getValue('google_api_key')), ['', false])) {
DPDConfig::updateValue('DPDFRANCE_GOOGLE_API_KEY', Tools::getValue('google_api_key'));
}
DPDConfig::updateValue('DPDFRANCE_DAY_DEFINITE_MODE', Tools::getValue('day_definite_mode'));
if (!in_array(trim(Tools::getValue('leadtime_api_key')), ['', false])) {
DPDConfig::updateValue('DPDFRANCE_LEADTIME_API_KEY', Tools::getValue('leadtime_api_key'));
}
DPDConfig::updateValue('DPDFRANCE_API_LOGIN', Tools::getValue('api_login'));
// On ne met la valeur de mot de passe à jour que si elle a été saisie
if (!in_array(trim(Tools::getValue('api_password')), ['', false])) {
DPDConfig::updateValue('DPDFRANCE_API_PASSWORD', Tools::getValue('api_password'));
}
if (!empty(trim(Tools::getValue('webtrace_login')))) {
DPDConfig::updateValue('DPDFRANCE_WEBTRACE_LOGIN', Tools::getValue('webtrace_login'));
}
if (!empty(trim(Tools::getValue('webtrace_password')))) {
DPDConfig::updateValue('DPDFRANCE_WEBTRACE_PASSWORD', Tools::getValue('webtrace_password'));
}
// Si la personne a joué avec le formulaire login Webtrace et password Webtrace
if (empty(trim(Tools::getValue('webtrace_login'))) && empty(trim(Tools::getValue('webtrace_password')))) {
DPDConfig::updateValue('DPDFRANCE_WEBTRACE_LOGIN', '1064');
DPDConfig::updateValue('DPDFRANCE_WEBTRACE_PASSWORD', 'Pr2%5sHg');
}
// Gestion des expeditions
DPDConfig::updateValue('DPDFRANCE_ETAPE_EXPEDITION', Tools::getValue('id_expedition'));
DPDConfig::updateValue('DPDFRANCE_ETAPE_EXPEDIEE', Tools::getValue('id_expedie'));
DPDConfig::updateValue('DPDFRANCE_ETAPE_LIVRE', Tools::getValue('id_livre'));
if ((int)Tools::getValue('auto_update') !== DPDConfig::get('DPDFRANCE_AUTO_UPDATE')) {
DPDConfig::updateValue('DPDFRANCE_AUTO_UPDATE', Tools::getValue('auto_update'));
$this->setTrackingURLs(DPDConfig::get('DPDFRANCE_AUTO_UPDATE'));
}
DPDConfig::updateValue('DPDFRANCE_MARKETPLACE_MODE', Tools::getValue('marketplace_mode'));
DPDConfig::updateValue('DPDFRANCE_AD_VALOREM', Tools::getValue('ad_valorem'));
DPDConfig::updateValue('DPDFRANCE_RETOUR_OPTION', Tools::getValue('retour'));
DPDConfig::updateValue('DPDFRANCE_SERVICE_TYPE', Tools::getValue('service_type'));
DPDConfig::updateValue('DPDFRANCE_PRINTER_CONNECT', Tools::getValue('format_printer_connect'));
DPDConfig::updateValue('DPDFRANCE_PRINTER_PORT', Tools::getValue('format_printer_port'));
DPDConfig::updateValue('DPDFRANCE_PRINTER_IP', Tools::getValue('format_printer_ip'));
DPDConfig::updateValue('DPDFRANCE_HIDE_NETWORK', Tools::getValue('format_hide_network'));
DPDConfig::updateValue('DPDFRANCE_PRINTER_SERIAL', Tools::getValue('format_printer_serial'));
// Gestion des extensions autorisées à l'aide d'une "liste blanche"
switch (trim(Tools::getValue('format_mod'))) {
case 'zpl':
case 'epl':
case 'pdf':
DPDConfig::updateValue('DPDFRANCE_FORMAT_MOD', Tools::getValue('format_mod'));
break;
default:
DPDConfig::updateValue('DPDFRANCE_FORMAT_MOD', 'pdf');
}
DPDConfig::updateValue('DPDFRANCE_FORMAT_PRINT', Tools::getValue('format_print'));
DPDConfig::updateValue('DPDFRANCE_PARAM', true);
$output .= '' . $this->l('Settings updated') . '
';
}
return $output . $this->displayForm();
}
/**
* [BACK OFFICE - SETUP] Module configuration page - FORM
*/
protected function displayForm()
{
// Check if PHP SOAP AND XML extensions is loaded
if (!extension_loaded('soap') || !extension_loaded('xml') || !extension_loaded('curl')) {
if (!extension_loaded('soap')) {
echo '' . $this->l('Warning! The PHP extension SOAP is not installed on this server. You must activate it in order to use the DPD plugin') . '
';
}
if (!extension_loaded('xml')) {
echo '' . $this->l('Warning! The PHP extension XML is not installed on this server. You must activate it in order to use the DPD plugin') . '
';
}
if (!extension_loaded('curl')) {
echo '' . $this->l('Warning! The PHP extension CURL is not installed on this server. You must activate it in order to use the DPD plugin') . '
';
}
return false;
}
$optionAutoUpdate = [
$this->l('Disabled'),
$this->l('Enabled - Tracking links by reference'),
$this->l('Enabled - Tracking links by parcel no.'),
$this->l('Enabled - Tracking links by id order'),
];
$optionMarketPlace = $optionDayDefinite = [
$this->l('Disabled'),
$this->l('Enabled'),
];
$optionVd = [
$this->l('Integrated parcel insurance service (33 € / kg)'),
$this->l('Ad Valorem insurance service'),
];
$optionRetour = [
'0' => $this->l('No returns'),
'4' => $this->l('Prepared'),
'3' => $this->l('On Demand'),
];
$id_lang = Context::getContext()->language->id;
$docPath = $this->getDocsPath() . 'readme_dpdfrance_prestashop.pdf';
// Generate variables to check if dpd configuration is already registered in database for these options.
$dpdfranceGoogle = Configuration::get('DPDFRANCE_GOOGLE_API_KEY') ? true : '';
$dpdfranceLeadtime = Configuration::get('DPDFRANCE_LEADTIME_API_KEY') ? true : '';
$dpdfranceApi = Configuration::get('DPDFRANCE_API_PASSWORD') ? true : '';
$dpdfranceWebtrace = Configuration::get('DPDFRANCE_WEBTRACE_PASSWORD') ? true : '';
// Send variable to Smarty
$this->context->smarty->assign([
'is_debug' => DPDFRANCE_DEV_MODE,
'js_path' => $this->getJsPath(),
'css_path' => $this->getCssPath(),
'docs_path' => $docPath,
'img_path' => $this->getImgPath(),
'nom_exp' => Tools::getValue('nom_exp', DPDConfig::get('DPDFRANCE_NOM_EXP')),
'address_exp' => Tools::getValue('address_exp', DPDConfig::get('DPDFRANCE_ADDRESS_EXP')),
'address2_exp' => Tools::getValue('address2_exp', DPDConfig::get('DPDFRANCE_ADDRESS2_EXP')),
'cp_exp' => Tools::getValue('cp_exp', DPDConfig::get('DPDFRANCE_CP_EXP')),
'ville_exp' => Tools::getValue('ville_exp', DPDConfig::get('DPDFRANCE_VILLE_EXP')),
'tel_exp' => Tools::getValue('tel_exp', DPDConfig::get('DPDFRANCE_TEL_EXP')),
'email_exp' => Tools::getValue('email_exp', DPDConfig::get('DPDFRANCE_EMAIL_EXP')),
'gsm_exp' => Tools::getValue('gsm_exp', DPDConfig::get('DPDFRANCE_GSM_EXP')),
// On affichera les depot_code sur 3 digits dans le formulaire
'relais_depot_code' => sprintf('%03d', Tools::getValue('relais_depot_code', DPDConfig::get('DPDFRANCE_RELAIS_DEPOT_CODE'))),
'predict_depot_code' => sprintf('%03d', Tools::getValue('predict_depot_code', DPDConfig::get('DPDFRANCE_PREDICT_DEPOT_CODE'))),
'classic_depot_code' => sprintf('%03d', Tools::getValue('classic_depot_code', DPDConfig::get('DPDFRANCE_CLASSIC_DEPOT_CODE'))),
'relais_shipper_code' => Tools::getValue('relais_shipper_code', DPDConfig::get('DPDFRANCE_RELAIS_SHIPPER_CODE')),
'predict_shipper_code' => Tools::getValue('predict_shipper_code', DPDConfig::get('DPDFRANCE_PREDICT_SHIPPER_CODE')),
'classic_shipper_code' => Tools::getValue('classic_shipper_code', DPDConfig::get('DPDFRANCE_CLASSIC_SHIPPER_CODE')),
'carriers' => Carrier::getCarriers($id_lang, false, false, false, null, (defined('ALL_CARRIERS') ? ALL_CARRIERS : null)),
'dpdfrance_relais_carrier_id' => Tools::getValue('dpdfrance_relais_carrier_id', DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID')),
'dpdfrance_predict_carrier_id' => Tools::getValue('dpdfrance_predict_carrier_id', DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID')),
'dpdfrance_classic_carrier_id' => Tools::getValue('dpdfrance_classic_carrier_id', DPDConfig::get('DPDFRANCE_CLASSIC_CARRIER_ID')),
'mypudo_url' => Tools::getValue('mypudo_url', DPDConfig::get('DPDFRANCE_RELAIS_MYPUDO_URL')),
'format_mod' => Tools::getValue('format_mod', DPDConfig::get('DPDFRANCE_FORMAT_MOD')),
'format_printer_connect' => Tools::getValue('format_printer_connect', DPDConfig::get('DPDFRANCE_PRINTER_CONNECT')),
'format_printer_port' => Tools::getValue('format_printer_port', DPDConfig::get('DPDFRANCE_PRINTER_PORT')),
'format_printer_ip' => Tools::getValue('format_printer_ip', DPDConfig::get('DPDFRANCE_PRINTER_IP')),
'format_hide_network' => Tools::getValue('format_hide_network', DPDConfig::get('DPDFRANCE_HIDE_NETWORK')),
'format_printer_serial' => Tools::getValue('format_printer_serial', DPDConfig::get('DPDFRANCE_PRINTER_SERIAL')),
'format_print' => Tools::getValue('format_print', DPDConfig::get('DPDFRANCE_FORMAT_PRINT')),
'service_type' => Tools::getValue('service_type', DPDConfig::get('DPDFRANCE_SERVICE_TYPE')),
'supp_iles' => Tools::getValue('supp_iles', DPDConfig::get('DPDFRANCE_SUPP_ILES')),
'supp_montagne' => Tools::getValue('supp_montagne', DPDConfig::get('DPDFRANCE_SUPP_MONTAGNE')),
'dpdfrance_google' => $dpdfranceGoogle,
'dpdfrance_leadtime' => $dpdfranceLeadtime,
'dpdfrance_api' => $dpdfranceApi,
'dpdfrance_webtrace' => $dpdfranceWebtrace,
// On ne renvoie pas les mots de passe enregistrés dans le front pour empêcher leur récupération par un tiers.
// Eprint
'api_login' => Tools::getValue('api_login', DPDConfig::get('DPDFRANCE_API_LOGIN')),
// Webtrace
'webtrace_login' => Tools::getValue('webtrace_login',
DPDConfig::get('DPDFRANCE_WEBTRACE_LOGIN') !== '1064'
? DPDConfig::get('DPDFRANCE_WEBTRACE_LOGIN')
: ''
),
'etats_factures' => OrderState::getOrderStates($id_lang),
'dpdfrance_etape_expedition' => Tools::getValue('id_expedition', DPDConfig::get('DPDFRANCE_ETAPE_EXPEDITION')),
'dpdfrance_etape_expediee' => Tools::getValue('id_expedie', DPDConfig::get('DPDFRANCE_ETAPE_EXPEDIEE')),
'dpdfrance_etape_livre' => Tools::getValue('id_livre', DPDConfig::get('DPDFRANCE_ETAPE_LIVRE')),
'auto_update' => Tools::getValue('auto_update', DPDConfig::get('DPDFRANCE_AUTO_UPDATE')),
'marketplace_mode' => Tools::getValue('marketplace_mode', DPDConfig::get('DPDFRANCE_MARKETPLACE_MODE') ? '1' : '0'),
'day_definite_mode' => Tools::getValue('day_definite_mode', DPDConfig::get('DPDFRANCE_DAY_DEFINITE_MODE') ? '1' : '0'),
'dpdfrance_ad_valorem' => Tools::getValue('ad_valorem', DPDConfig::get('DPDFRANCE_AD_VALOREM') ? '1' : '0'),
'dpdfrance_retour_option' => Tools::getValue('retour', DPDConfig::get('DPDFRANCE_RETOUR_OPTION')),
'cron_url' => $this->context->shop->getBaseURL(true).'modules/dpdfrance/cron.php?token='.urlencode(Tools::passwdHash('dpdfrance-cron')),
// Options des
'option_auto_update' => $optionAutoUpdate,
'option_marketplace' => $optionMarketPlace,
'option_day_definite' => $optionDayDefinite,
'option_vd' => $optionVd,
'option_retour' => $optionRetour,
'form_submit_url' => $_SERVER['REQUEST_URI'],
]);
if (DPDFRANCE_DEV_MODE) {
$this->context->smarty->assign([
'dpdfrance_dev_badge' => DPDTools::getHtmlDevBadge(),
]);
}
return $this->display(__FILE__, 'views/templates/admin/config.tpl');
}
/**
* [BACK OFFICE - SETUP] Load dependencies in the configuration of the module
*/
protected function loadAsset()
{
// Load CSS
$css = [
$this->getCssPath() . 'utils.css',
$this->getCssPath() . 'admin/dpdfrance_config.css',
$this->getCssPath() . 'admin/jquery/plugins/fancybox/jquery.fancybox.css',
];
if (DPDFRANCE_DEV_MODE === true) {
$css[] = $this->getCssPath() . 'dev.css';
}
$this->context->controller->addCSS($css);
// Load JS
$jss = [
$this->getJsPath() . 'admin/jquery/plugins/validation/jquery.validate.min.js',
$this->getJsPath() . 'admin/admin_config.js',
];
$this->context->controller->addJS($jss);
// Clean memory
unset($jss, $css);
}
/**
* [BACK OFFICE - SETUP] Carrier creation function
* @param array $config carrier configuration
* @param string $type carrier name
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
protected function createCarrier($config, $type)
{
$carrier = new Carrier();
$carrier->name = $config['name'];
$carrier->id_tax_rules_group = $config['id_tax_rules_group'];
$carrier->url = $config['url'];
$carrier->active = $config['active'];
$carrier->deleted = $config['deleted'];
$carrier->delay = $config['delay'];
$carrier->shipping_handling = $config['shipping_handling'];
$carrier->range_behavior = $config['range_behavior'];
$carrier->is_module = true;
$carrier->shipping_external = $config['shipping_external'];
$carrier->external_module_name = $config['external_module_name'];
$carrier->need_range = $config['need_range'];
$carrier->grade = $config['grade'];
$languages = Language::getLanguages();
foreach ($languages as $language) {
if ($language['iso_code'] === 'fr') {
$carrier->delay[$language['id_lang']] = $config['delay'][$language['iso_code']];
}
if ($language['iso_code'] === 'en') {
$carrier->delay[$language['id_lang']] = $config['delay'][$language['iso_code']];
}
if ($language['iso_code'] === 'es') {
$carrier->delay[$language['id_lang']] = $config['delay'][$language['iso_code']];
}
if ($language['iso_code'] === 'it') {
$carrier->delay[$language['id_lang']] = $config['delay'][$language['iso_code']];
}
if ($language['iso_code'] === 'de') {
$carrier->delay[$language['id_lang']] = $config['delay'][$language['iso_code']];
}
}
if ($carrier->add()) {
$groups = Group::getgroups(true);
foreach ($groups as $group) {
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'carrier_group VALUE (' . (int)$carrier->id . ',' . (int)$group['id_group'] . ')');
}
// Price range creation
$range_price = new RangePrice();
$range_price->id_carrier = $carrier->id;
$range_price->delimiter1 = '0';
$range_price->delimiter2 = '10000';
$range_price->add();
// Weight range creation
$range_weight = new RangeWeight();
$range_weight->id_carrier = $carrier->id;
$range_weight->delimiter1 = '0';
if ($type === 'relais') {
$range_weight->delimiter2 = '20';
} else {
$range_weight->delimiter2 = '30';
}
$range_weight->add();
if ($type === 'world') {
// Get All enabled zone for the Carrier WORLD which doesn't have "France" word in the name
$sql = 'SELECT id_zone FROM ' . _DB_PREFIX_ . 'zone WHERE name NOT LIKE "%France%" AND active = 1';
} else {
// Get All enabled zone for the Carrier PREDICT, RELAIS, Classic which have "France" word in the name
$sql = 'SELECT id_zone FROM ' . _DB_PREFIX_ . 'zone WHERE name LIKE "%France%" AND active = 1';
}
$res = Db::getInstance()->ExecuteS($sql);
foreach ($res as $zone) {
// Insert in PS_CARRIER_ZONE, the relationship of carrier and zone
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'carrier_zone (id_carrier, id_zone) VALUE (' . (int)$carrier->id . ', ' . (int)$zone['id_zone'] . ')');
// Insert in PS_DELIVERY, the specific detail for the carrier with range weight and range price
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'delivery (id_carrier, id_range_price, id_range_weight, id_zone, price) VALUE (' . (int)$carrier->id . ', ' . (int)$range_price->id . ', NULL,' . (int)$zone['id_zone'] . ',' . 5.95 . ')');
Db::getInstance()->execute('INSERT INTO ' . _DB_PREFIX_ . 'delivery (id_carrier, id_range_price, id_range_weight, id_zone, price) VALUE (' . (int)$carrier->id . ', NULL, ' . (int)$range_weight->id . ', ' . (int)$zone['id_zone'] . ',' . 5.95 . ')');
}
// Assign Logo to the carrier
return !(
in_array($type, ['relais', 'predict', 'classic', 'world']) &&
!copy(
__DIR__ . '/views/img/front/' . $type . '/carrier_logo.jpg',
_PS_SHIP_IMG_DIR_ . '/' . $carrier->id . '.jpg'
)
);
}
return false;
}
/**
* [BACK OFFICE - SETUP] When a carrier is hooked to DPD module, sets some parameters
* @param int $id_carrier
* @return void
*/
protected function reaffectationCarrier($id_carrier)
{
Db::getInstance()->update(
'carrier',
[
'shipping_handling' => 0,
'is_module' => 1,
'shipping_external' => 1,
'need_range' => 1,
'external_module_name' => $this->name,
],
'id_carrier = ' . (int)$id_carrier
);
}
/**
* [BACK OFFICE - SETUP] When dpd option's auto update by parcel no. mode is enabled, change tracking URLs
* Mode 1 : références internes
* Mode 2 : numero de la commande
* Mode 3 : id de la commande
* @param int $mode
* @return void
*/
protected function setTrackingURLs($mode)
{
$url = $mode === DPDTools::DPD_AUTOUPDATE_PARCEL_NUMBER ?
DPDTools::PREFIX_TRACES_URL . '@' :
DPDTools::PREFIX_TRACEX_URL . '@';
Db::getInstance()->update(
'carrier',
['url' => pSQL($url)],
'url LIKE "%dpd.fr/trace%"'
);
}
// FRONT OFFICE DISPLAY AFTER CARRIER PAGE METHODS
/**
* [PREDICT] Delete previous phone number and register the new phone number
* @return bool|string
*/
public function ajaxRegisterGsm()
{
// Check if user is authorized to proceed
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(true);
if (!$ajaxAuthorized) {
return 'Error : Access Denied';
}
$context = $this->context;
$cart = $context->cart;
$input_tel = Tools::getValue('gsm_dest');
$id_carrier = (int)Tools::getValue('id_carrier');
$gsm = str_replace([' ', '.', '-', ',', ';', '/', '\\', '(', ')'], '', $input_tel);
// We verify if the id_carrier of the current processed order is the same as the configured predict carrier
if ($id_carrier !== DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID')) {
return false;
}
if (Tools::substr($gsm, 0, 2) === '00') {
$gsm = str_replace('00', '+', $gsm);
}
// DELETE PREVIOUS ENTRY IN DATABASE
Db::getInstance()->delete('dpdfrance_shipping', 'id_cart = ' . (int)$cart->id);
return Db::getInstance()->insert(
'dpdfrance_shipping',
[
'id_customer' => (int)$cart->id_customer,
'id_cart' => (int)$cart->id,
'id_carrier' => (int)$id_carrier,
'service' => 'PRE',
'relay_id' => '',
'company' => '',
'address1' => '',
'address2' => '',
'postcode' => '',
'city' => '',
'id_country' => '',
'gsm_dest' => pSQL($gsm),
],
false,
true,
Db::INSERT_IGNORE
);
}
/**
* [PREDICT] Rretrieve the gsm from the selected address in the checkout process
* @param array $param
* @return false|string
* @throws PrestaShopDatabaseException
*/
public function ajaxGetGsmFromSelectedAddress($param)
{
// Check if user is authorized to proceed
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(true);
if (!$ajaxAuthorized) {
return 'Error : Access Denied';
}
/**
* Check if the [address_id] parameter of the user is the same as the current user in the checkout process
* If not then we return an error message
*/
if ((int)$this->context->cart->id_address_delivery !== (int)$param['address_id']) {
return 'Error : Access Denied';
}
$sql = new DbQuery();
$sql->select('phone, phone_mobile')
->from('address')
->where('id_address = ' . (int)$param['address_id']);
$result = Db::getInstance()->executeS($sql);
if (!empty($result[0]['phone_mobile'])) {
return $result[0]['phone_mobile'];
} else {
if (!empty($result[0]['phone'])) {
return $result[0]['phone'];
}
}
return '';
}
/**
* Retrieve the Leadtime from the Lead Time API
* @param array $param
* @return string
*/
public function ajaxGetLeadtime($param)
{
// Check if user is authorized to proceed
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(true);
if (!$ajaxAuthorized) {
return '';
}
if ($param['carrier_id']) {
$isCarrierDpd = false;
if (
(int)$param['carrier_id'] === DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID')
|| (int)$param['carrier_id'] === DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID')
|| (int)$param['carrier_id'] === DPDConfig::get('DPDFRANCE_CLASSIC_CARRIER_ID')
) {
$isCarrierDpd = true;
}
return ($isCarrierDpd && $param['address_id']) ?
DPDTools::getLeadtime(
$param['address_id'],
$this->context->language->iso_code,
false
) : '';
}
return '';
}
/**
* Delete previous entry in dpdfrance_shipping table when the carrier selected is not Predict or Relais
* @return bool|string
*/
public function ajaxUpdateShipping()
{
// Check if user is authorized to proceed
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(true);
if (!$ajaxAuthorized) {
return 'Error : Access Denied';
}
$context = $this->context;
$cart = $context->cart;
return Db::getInstance()->delete('dpdfrance_shipping', 'id_cart = ' . (int)$cart->id);
}
/**
* [RELAIS] Delete the previous relais information and register the new one
* @return bool|string
*/
public function ajaxRegisterPudo()
{
// Check if user is authorized to proceed
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(true);
if (!$ajaxAuthorized) {
return 'Error : Access Denied';
}
$context = $this->context;
$cart = $context->cart;
$id_carrier = Tools::getValue('id_carrier');
$relay_id = Tools::getValue('pudo_id');
// We verify if the id_carrier of the current processed order is the same as the configured relay carrier
if ((int)$id_carrier !== DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID')) {
return $this->l('We have encountered a temporary problem with the registration of your DPD Pickup. Please select another Pickup Relay.');
}
// Retrieve gsm number from customer delivery address
$customerAddress = new Address($cart->id_address_delivery);
$customerGsm = '';
if (!empty($customerAddress->phone_mobile)) {
$customerGsm = $customerAddress->phone_mobile;
} else {
if (!empty($customerAddress->phone)) {
$customerGsm = $customerAddress->phone;
}
}
$currentRelaisDatasSearchAndRelaisList = DPDTools::getCurrentRelaisDatasSearchAndRelaisList(
$cart->id,
$context->customer->id
);
if (
empty($relay_id) ||
empty($currentRelaisDatasSearchAndRelaisList)
) {
return $this->l('We have encountered a temporary problem with the registration of your DPD Pickup. Please select another Pickup Relay.');
}
$selectedRelaisDetails = $currentRelaisDatasSearchAndRelaisList['relay_list'][$relay_id];
$selectedRelaisCheckDetails = [
'company' => $selectedRelaisDetails['shop_name'],
'address1' => isset($selectedRelaisDetails['address1']) ? $selectedRelaisDetails['address1'] : '',
'address2' => isset($selectedRelaisDetails['address2']) ? $selectedRelaisDetails['address2'] : '',
'postcode' => $selectedRelaisDetails['postal_code'],
'city' => $selectedRelaisDetails['city'],
];
// Check for relais details not empty
$selectedRelaisDetailsEmpty = $selectedRelaisDetailsNotEmpty = false;
foreach ($selectedRelaisCheckDetails as $value) {
$value = trim($value);
if (empty($value)) {
$selectedRelaisDetailsEmpty = true;
} else {
$selectedRelaisDetailsNotEmpty = true;
}
}
if ($selectedRelaisDetailsEmpty === true && $selectedRelaisDetailsNotEmpty === false) {
return $this->l('We have encountered a temporary problem with the registration of your DPD Pickup. Please select another Pickup Relay.');
}
// DELETE PREVIOUS ENTRY IN DATABASE
Db::getInstance()->delete('dpdfrance_shipping', 'id_cart = ' . (int)$cart->id);
$address1 = isset($selectedRelaisDetails['address1']) ? $selectedRelaisDetails['address1'] : '';
$address2 = isset($selectedRelaisDetails['address2']) ? $selectedRelaisDetails['address2'] : '';
// INSERT TO THE DATABASE
$sqlResult = Db::getInstance()->insert(
'dpdfrance_shipping',
[
'id_customer' => (int)$cart->id_customer,
'id_cart' => (int)$cart->id,
'id_carrier' => (int)$id_carrier,
'service' => 'REL',
'relay_id' => pSQL($relay_id),
'company' => pSQL($selectedRelaisDetails['shop_name']),
'address1' => pSQL($address1),
'address2' => pSQL($address2),
'postcode' => pSQL($selectedRelaisDetails['postal_code']),
'city' => pSQL($selectedRelaisDetails['city']),
'id_country' => pSQL($selectedRelaisDetails['id_country']),
'gsm_dest' => isset($customerGsm) ? pSQL($customerGsm) : DPDTools::getPhoneNumberFromDpdShipping($cart->id, $id_carrier),
],
false,
true,
Db::INSERT_IGNORE
);
return !($sqlResult !== true);
}
/**
* [RELAIS] Ajax Action for updating relay pick up point
* @param array $params
* @return false|string|void
*/
public function ajaxUpdatePoints($params)
{
// Check if user is authorized to proceed
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(true);
if (!$ajaxAuthorized) {
// If not then we return an error message
return 'Error : Access Denied';
}
$cart = new Cart((int)$params['dpdfrance_cart_id']);
// Check if user is the same as the current user in the checkout process
if ($cart->id_customer !== $this->context->cart->id_customer) {
// If not then we return an error message
return 'Error : Access Denied';
}
$address = new Address((int)$cart->id_address_delivery);
$addressFormDetails = Tools::getValue('action') === 'search' ? [
'address1' => pSQL($params['address1']),
'postcode' => pSQL($params['postcode']),
'city' => pSQL($params['city']),
'id_country' => (int)$address->id_country,
'id_address' => (int)$cart->id_address_delivery,
'dpdfrance_cart_id' => (int)$cart->id,
] : [
'address1' => pSQL($address->address1),
'postcode' => pSQL($address->postcode),
'city' => pSQL($address->city),
'id_country' => (int)$address->id_country,
'id_address' => (int)$cart->id_address_delivery,
];
$deliveryInfos = DPDTools::getDeliveryInfos((int)$cart->id);
$isoCode = $this->context->country->iso_code;
if ($isoCode === 'FR') {
$dpdfrance_relais_points = $this->getPoints($addressFormDetails);
$currentSearchAndRelaisList = DPDTools::getCurrentRelaisDatasSearchAndRelaisList(
(int)$this->context->cart->id,
$this->context->cart->id_customer
);
$selectedRelay = null;
if (!empty($currentSearchAndRelaisList['relay_list']) && !empty($deliveryInfos['relay_id'])) {
$selectedRelay = $this->getSelectedRelay(
$deliveryInfos['relay_id'],
$currentSearchAndRelaisList['relay_list']
);
}
$this->context->smarty->assign(
[
'error' => (isset($dpdfrance_relais_points['error']) ? $this->l($dpdfrance_relais_points['error']) : null),
'dpdfrance_relais_empty' => (empty($dpdfrance_relais_points) ? $this->l('No DPD pickup relais are available around your location') : null),
'dpdfrance_relais_carrier_id' => DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID'),
'dpdfrance_relais_status' => (!empty(Tools::getValue('dpdrelais')) ? Tools::getValue('dpdrelais') : null),
'dpdfrance_relais_points' => (!isset($dpdfrance_relais_points['error']) ? $dpdfrance_relais_points : null),
'dpdfrance_selectedrelay' => $selectedRelay,
'dpdfrance_selectedRelayAddress' => $currentSearchAndRelaisList['relay_list'][$selectedRelay],
'dpdfrance_base_dir' => __PS_BASE_URI__ . 'modules/' . $this->name,
'dpdfrance_predict_gsm_dest' => (isset($deliveryInfos['gsm_dest']) ? $deliveryInfos['gsm_dest'] : $address->phone_mobile),
'dpdfrance_predict_status' => (Tools::getValue('dpdpredict') ? Tools::getValue('dpdpredict') : null),
'dpdfrance_predict_carrier_id' => DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID'),
'ssl' => (int)Configuration::get('PS_SSL_ENABLED'),
'ssl_everywhere' => (int)Configuration::get('PS_SSL_ENABLED_EVERYWHERE'),
]
);
return $this->display(__FILE__, 'views/templates/front/aftercarrier.tpl');
}
}
/**
* [RELAIS] MyPudo webservice calling method
* @param array $input
* @return array
*/
protected function getPoints($input)
{
$dpdfrance_relais_points = [];
$currentDate = date('d/m/Y');
$this->address = DPDTools::stripAccents($input['address1']);
$this->zipcode = $input['postcode'];
$this->city = DPDTools::stripAccents($input['city']);
// ! Zip code is MANDATORY
if (empty($this->zipcode)) {
$dpdfrance_relais_points['error'] = $this->l('Postal code in missing in the address. Please, modify it.');
return $dpdfrance_relais_points;
}
$pudoCallParams = [
'carrier' => 'EXA',
'key' => 'deecd7bc81b71fcc0e292b53e826c48f',
'address' => $this->address,
'zipCode' => $this->zipcode,
'city' => $this->city,
'countrycode' => 'FR',
'requestID' => '1234',
'request_id' => '1234',
'date_from' => $currentDate,
'max_pudo_number' => '',
'max_distance_search' => '',
'weight' => '',
'category' => '',
'holiday_tolerant' => '',
];
try {
ini_set('default_socket_timeout', 5);
// Handle the case when no webService DPD Relais url was provided
if (PudoProvider::initSoapClient(DPDConfig::get('DPDFRANCE_RELAIS_MYPUDO_URL')) === false) {
throw new Exception();
}
$pudoList = PudoProvider::getPudoList($pudoCallParams);
if (Tools::strlen($pudoList->ERROR) > 0) {
$dpdfrance_relais_points['error'] = $this->l('DPD Relais is not available at the moment, please try again shortly.');
} else {
$relais_items = $pudoList->PUDO_ITEMS;
$relaisDatas['cartId'] = $this->context->cart->id;
$relaisDatas['customerId'] = $this->context->customer->id;
$relaisDatas['search'] = $input;
$relaisDatas['search']['address1'] = $this->address;
$relaisDatas['search']['city'] = $this->city;
$indexPickup = 0;
foreach ($relais_items->PUDO_ITEM as $item) {
$point = [];
$item = (array)$item;
$id_address = $this->context->cart->id_address_delivery;
$postcode = DPDTools::getPostcodeByAddress($id_address);
$pickupDisplayed = 5;
// Island zone disabled : exclude Pickup point
if (
DPDConfig::get('DPDFRANCE_SUPP_ILES') < 0 &&
(in_array($item['ZIPCODE'], DPDTools::ISLANDS_ZONE, true) || (Tools::substr($item['ZIPCODE'], 0, 2) === '20'))
) {
continue;
}
// Mountain zone disabled : exclude Pickup point
if (
DPDConfig::get('DPDFRANCE_SUPP_MONTAGNE') < 0 &&
in_array($item['ZIPCODE'], DPDTools::MOUNTAINS_ZONE, true)
) {
continue;
}
// Customer in island zone + island overcost set : exclude Pickup point if outside island
// Si le Montant supp iles est supérieure à 0
// FIXME #46150 Le code fait la même chose dans les deux conditions
if (DPDConfig::get('DPDFRANCE_SUPP_ILES') > 0) {
// Si l'adresse de livraison est en zone Iles
if (in_array($postcode, DPDTools::ISLANDS_ZONE, true)) {
// Si l'adresse du point relais est en zone Iles
if (in_array($item['ZIPCODE'], DPDTools::ISLANDS_ZONE, true)) {
continue;
}
} else {
// Customer outside island zone + island overcost set : exclude Pickup point if inside island
// Si l'adresse du point relais est en zone Iles
if (in_array($item['ZIPCODE'], DPDTools::ISLANDS_ZONE, true)) {
continue;
}
}
}
// Customer in Corsica + island overcost set : exclude Pickup point if outside Corsica
// Montant zone des iles supérieure à 0
if (DPDConfig::get('DPDFRANCE_SUPP_ILES') > 0) {
// Si le code postal de l'adresse de livraison commence par 20 ?
if (Tools::substr($postcode, 0, 2) === '20') {
// Si le code postal de l'adresse du point relais ne commence pas par 20 ?
if (Tools::substr($item['ZIPCODE'], 0, 2) !== '20') {
continue;
}
} else {
// Customer outside Corsica + island overcost set : exclude Pickup point if inside Corsica
// Si le code postal de l'adresse du point relais commence par 20 ?
if (Tools::substr($item['ZIPCODE'], 0, 2) === '20') {
continue;
}
}
}
// Customer in mountain zone + mountain overcost set : exclude Pickup point if outside mountain
// Montant zone montagneuse supérieure à 0
// FIXME #46150 Le code dans les conditions fait la même chose ?
if (DPDConfig::get('DPDFRANCE_SUPP_MONTAGNE') > 0) {
// Adresse de livraison est dans la zone montagneuse ?
if (in_array($postcode, DPDTools::MOUNTAINS_ZONE, true)) {
// Adresse du point relais est pas dans la zone montagneuse ?
if (in_array($item['ZIPCODE'], DPDTools::MOUNTAINS_ZONE, true)) {
continue;
}
} else {
// Customer outside mountain zone + mountain overcost set : exclude Pickup point if inside mountain
// Adresse du point relais est dans la zone montagneuse ?
if (in_array($item['ZIPCODE'], DPDTools::MOUNTAINS_ZONE, true)) {
continue;
}
}
}
$point['relay_id'] = !empty($item['PUDO_ID']) ? $item['PUDO_ID'] : '';
$point['shop_name'] = !empty($item['NAME']) ? DPDTools::stripAccents($item['NAME']) : '';
$point['address1'] = !empty($item['ADDRESS1']) ? DPDTools::stripAccents($item['ADDRESS1']) : '';
$point['address2'] = !empty($item['ADDRESS2']) ? DPDTools::stripAccents($item['ADDRESS2']) : '';
$point['address3'] = !empty($item['ADDRESS3']) ? DPDTools::stripAccents($item['ADDRESS3']) : '';
$point['local_hint'] = !empty($item['LOCAL_HINT']) ? DPDTools::stripAccents($item['LOCAL_HINT']) : '';
$point['postal_code'] = !empty($item['ZIPCODE']) ? $item['ZIPCODE'] : '';
$point['city'] = !empty($item['CITY']) ? DPDTools::stripAccents($item['CITY']) : '';
$point['id_country'] = !empty($input['id_country']) ? $input['id_country'] : '';
$relaisDatas['relaisList'][$point['relay_id']] = $point;
$point['distance'] = number_format($item['DISTANCE'] / 1000, 2);
$point['coord_lat'] = (float)str_replace(',', '.', $item['LATITUDE']);
$point['coord_long'] = (float)str_replace(',', '.', $item['LONGITUDE']);
$days = [
1 => 'monday',
2 => 'tuesday',
3 => 'wednesday',
4 => 'thursday',
5 => 'friday',
6 => 'saturday',
7 => 'sunday',
];
if (count($item['OPENING_HOURS_ITEMS']->OPENING_HOURS_ITEM) > 0) {
foreach ($item['OPENING_HOURS_ITEMS']->OPENING_HOURS_ITEM as $oh_item) {
$oh_item = (array)$oh_item;
$point[$days[$oh_item['DAY_ID']]][] = $oh_item['START_TM'] . ' - ' . $oh_item['END_TM'];
}
}
if (count($item['HOLIDAY_ITEMS']->HOLIDAY_ITEM) > 0) {
$x = 0;
}
foreach ($item['HOLIDAY_ITEMS']->HOLIDAY_ITEM as $holiday_item) {
$holiday_item = (array)$holiday_item;
$point['closing_period'][$x] = $holiday_item['START_DTM'] . ' - ' . $holiday_item['END_DTM'];
++$x;
}
// insertion du point relais dans un tableau
$dpdfrance_relais_points[] = $point;
// Affiche 5 relais
if (++$indexPickup === $pickupDisplayed) {
break;
}
}
$currentRelaisDatasSearchAndRelaisList = DPDTools::getCurrentRelaisDatasSearchAndRelaisList(
(int)$this->context->cart->id,
$this->context->customer->id
);
// If there is a current cart session
if (!empty($currentRelaisDatasSearchAndRelaisList)) {
// If it has data in Database then store in Database
DPDTools::updateCurrentRelaisDatasSearchAndRelaisList(
$relaisDatas['cartId'],
$relaisDatas['customerId'],
json_encode($relaisDatas['search']),
json_encode($relaisDatas['relaisList'])
);
} else {
// If it has no data in Database then store in Database
DPDTools::setCurrentRelaisDatasSearchAndRelaisList(
$relaisDatas['cartId'],
$relaisDatas['customerId'],
json_encode($relaisDatas['search']),
json_encode($relaisDatas['relaisList'])
);
}
}
} catch (Exception $e) {
$dpdfrance_relais_points['error'] = $this->l('DPD Relais is not available at the moment, please verify the DPD Relais WebService url in the module configuration panel.');
}
return $dpdfrance_relais_points;
}
/**
* [RELAIS] Check if there is a relay Id registered in database
* and compare it to the relay list if one matches
* THEN we return the match relay
* ELSE we return the first relay pickup from the list
* @param string $deliveryInfosRelayId
* @param array $currentRelaisList
* @return string
*/
protected function getSelectedRelay($deliveryInfosRelayId, $currentRelaisList)
{
if (!array_key_exists($deliveryInfosRelayId, $currentRelaisList)) {
return array_key_first($currentRelaisList);
}
return $deliveryInfosRelayId;
}
/**
* [RETURN] Get the return Address data either from dpdfrance_order or the webservice EPRINT
* @param array $param
* @return false|string
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws SoapFault
*/
public function ajaxGetAddressOrder($param)
{
/**
* Check if user is authorized to proceed
*/
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(false);
if (!$ajaxAuthorized) {
return 'Error : Access Denied';
}
$eprintUser = DPDConfig::get('DPDFRANCE_API_LOGIN');
$eprintPassword = DPDConfig::get('DPDFRANCE_API_PASSWORD');
if (EprintProvider::initSoapClient($eprintUser, $eprintPassword, DPDFRANCE_DEV_USE_WS_TEST) === false) {
return false;
}
$dpdOrder = $this->getDpdOrder($param['order']);
if (!is_null($dpdOrder['override_return_zip'])) {
$shipperedArray = [
'zip' => $dpdOrder['override_return_zip'],
'city' => $dpdOrder['override_return_city'],
'street' => $dpdOrder['override_return_street'],
'phone' => $dpdOrder['override_return_phone'],
];
} else {
$order = new Order($dpdOrder['id_order']);
$service = DPDTools::getService($order, (int)Context::getContext()->language->id);
$serviceLivraisonInfos = DPDConfig::getServiceLivraisonInfos($service, (int)$order->id_shop);
$getRetourLabel = [
'countrycode' => 250,
'centernumber' => $serviceLivraisonInfos['depot_code'],
'customer_number' => $serviceLivraisonInfos['shipper_code'],
'original_parcelnumber' => $dpdOrder['id_order_dpd'],
];
try {
$retourShipmentData = EprintProvider::getRetourShipmentData($getRetourLabel, DPDFRANCE_EPRINT_BC);
} catch (Exception $e) {
return false;
}
// Le receiver initial devient l'envoyeur
// FIXME #46150 à vérifier quand même
$shippered = $retourShipmentData->receiveraddress;
$shipperedArray = [
'zip' => $shippered->zipCode,
'city' => $shippered->city,
'street' => $shippered->street,
'phone' => $shippered->phoneNumber,
];
}
return json_encode($shipperedArray);
}
/**
* [RETURN] Change in the table dpdfrance_order the return address datas
* @param array $param
* @return false|string
* @throws PrestaShopDatabaseException
*/
public function ajaxSetAddressOrder($param)
{
/**
* Check if user is authorized to proceed
*/
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(false);
if (!$ajaxAuthorized) {
return 'Error : Access Denied';
}
Db::getInstance()->update(
'dpdfrance_order',
[
'override_return_street' => pSQL($param['street']),
'override_return_zip' => pSQL($param['zip']),
'override_return_city' => pSQL($param['city']),
'override_return_phone' => pSQL($param['phone']),
],
'id_order_dpd = ' . (int)$param['order']
);
$response = ['update' => true];
return json_encode($response);
}
/**
* [RETURN] Get DPD Order by colis from dpdfrance_order table
* @param $colis
* @return array|string list order dpd
* @throws PrestaShopDatabaseException
*/
public function getDpdOrder($colis)
{
$sql = new DbQuery();
$sql->select('*')
->from('dpdfrance_order')
->where('id_order_dpd = ' . (int)$colis);
$result = Db::getInstance()->executeS($sql);
if (
!empty($result[0]['id_order_dpd']) ||
(isset($result[0]['id_order_dpd']) && $result[0]['id_order_dpd'] === '0')
) {
return $result[0];
}
return '';
}
/**
* [IMPRESSION MODE] Check if there is session file
* @return string
*/
public function ajaxRefreshListPdf()
{
/**
* Check if user is authorized to proceed
*/
$ajaxAuthorized = DPDTools::checkAjaxAuthValidity(false);
if (!$ajaxAuthorized) {
return 'Error : Access Denied';
}
if (is_file(__DIR__ . '/session.txt')) {
$exportPdf = Tools::file_get_contents(__DIR__ . '/session.txt');
} else {
$exportPdf = '';
}
if (!empty($exportPdf) && $exportPdf === 'finish') {
unlink(__DIR__ . '/session.txt');
return 'true';
}
return 'false';
}
// HOOKS
/**
* [BACK OFFICE] Manage to update tracking status of orders
*
* @param array $params
* @return string|void
*/
public function hookDisplayBackOfficeHeader($params)
{
return;
if (DPDConfig::get('DPDFRANCE_AUTO_UPDATE')
&& Configuration::get('PS_SHOP_ENABLE')
&& ((time() - DPDConfig::get('DPDFRANCE_LAST_TRACKING')) > 3600)
) {
$cron_url = $this->getModulePath() . 'cron.php?token=' . urlencode(Tools::passwdHash('dpdfrance-cron')) . '&employee=' . $this->context->employee->id;
return '';
}
}
/**
* [BACK OFFICE] Maintains DPD France Carriers' ID up to date for multistore and single store
* @param array $params
*/
public function hookActionCarrierUpdate($params)
{
if (Shop::isFeatureActive()) {
foreach (Shop::getShops() as $shop) {
if ((int)$params['id_carrier'] === DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID', null, $shop['id_shop_group'], $shop['id_shop'])) {
DPDConfig::updateValue('DPDFRANCE_RELAIS_CARRIER_ID', (int)$params['carrier']->id, false, $shop['id_shop_group'], $shop['id_shop']);
}
if ((int)$params['id_carrier'] === DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID', null, $shop['id_shop_group'], $shop['id_shop'])) {
DPDConfig::updateValue('DPDFRANCE_PREDICT_CARRIER_ID', (int)$params['carrier']->id, false, $shop['id_shop_group'], $shop['id_shop']);
}
if ((int)$params['id_carrier'] === DPDConfig::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, $shop['id_shop_group'], $shop['id_shop'])) {
DPDConfig::updateValue('DPDFRANCE_CLASSIC_CARRIER_ID', (int)$params['carrier']->id, false, $shop['id_shop_group'], $shop['id_shop']);
}
}
} else {
if ((int)$params['id_carrier'] === DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, null)) {
DPDConfig::updateValue('DPDFRANCE_RELAIS_CARRIER_ID', (int)$params['carrier']->id, false, null, null);
}
if ((int)$params['id_carrier'] === DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, null)) {
DPDConfig::updateValue('DPDFRANCE_PREDICT_CARRIER_ID', (int)$params['carrier']->id, false, null, null);
}
if ((int)$params['id_carrier'] === DPDConfig::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, null)) {
DPDConfig::updateValue('DPDFRANCE_CLASSIC_CARRIER_ID', (int)$params['carrier']->id, false, null, null);
}
}
}
/**
* [FRONT OFFICE] Calls CSS and JS files on header of front-office order pages
*
* @return false|string|void
*/
public function hookDisplayHeader()
{
if (!($file = basename(Tools::getValue('controller')))) {
$file = str_replace('.php', '', basename($_SERVER['SCRIPT_NAME']));
}
Media::addJsDefL('pudoSelected', $this->l('Selected'));
Media::addJsDefL('pudoNotSelected', $this->l('Choose'));
Media::addJsDefL('pudoError', $this->l('It seems that you haven\'t selected a DPD Pickup point, please pick one from this list'));
if (in_array($file, array('order', 'orderopc', 'order-opc'))) {
$this->context->controller->addCSS($this->_path . 'views/css/front/dpdfrance.css');
$this->context->controller->addJS($this->_path . 'views/js/front/dpdfrance_front.js');
if(DPDConfig::get('DPDFRANCE_GOOGLE_API_KEY')) {
$this->context->controller->addJS('https://maps.googleapis.com/maps/api/js?key=' . DPDConfig::get('DPDFRANCE_GOOGLE_API_KEY'));
}
else {
$this->context->controller->addJS('https://maps.googleapis.com/maps/api/js');
}
$this->context->smarty->assign(
[
'dpdfrance_base_dir' => __PS_BASE_URI__ . 'modules/' . $this->name,
'dpdfrance_relais_carrier_id' => DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID'),
'dpdfrance_predict_carrier_id' => DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID'),
'dpdfrance_cart' => $this->context->cart,
]
);
return $this->display(__FILE__, 'views/templates/front/header.tpl');
}
}
/**
* [FRONT OFFICE] Calls TPL files and executes corresponding actions upon carrier selection
* @param array $params
* @return false|string|void
*/
public function hookDisplayCarrierList($params)
{
if(Tools::getIsset('relay_error')) {
$this->context->controller->errors[] = $this->l('Please, select your parcel point !');
}
if ($params['cart']->id_address_delivery) {
$address = new Address((int)$params['cart']->id_address_delivery);
$deliveryInfos = DPDTools::getDeliveryInfos((int)$this->context->cart->id);
if ($this->context->country->iso_code === 'FR') {
$currentSearchAndRelaisList = DPDTools::getCurrentRelaisDatasSearchAndRelaisList(
(int)$this->context->cart->id,
$this->context->cart->id_customer
);
// Search Pickup points near a manually entered address only if same id_address_delivery
if (
!empty($currentSearchAndRelaisList['search_relay']['postcode'])
&& $currentSearchAndRelaisList['search_relay']['id_address'] === (int)$this->context->cart->id_address_delivery
) {
$search = $currentSearchAndRelaisList['search_relay'];
$dpdfrance_relais_points = $this->getPoints($search);
} else {
// Search Pickup points near of our registered address
$address_details = [
'address1' => $address->address1,
'postcode' => $address->postcode,
'city' => $address->city,
'id_country' => $address->id_country,
'id_address' => $address->id,
];
$dpdfrance_relais_points = $this->getPoints($address_details);
}
} else {
$dpdfrance_relais_points['error'] = true;
}
$newCurrentSearchAndRelaisList = DPDTools::getCurrentRelaisDatasSearchAndRelaisList(
(int)$this->context->cart->id,
$this->context->cart->id_customer
);
$selectedRelay = null;
if (!empty($newCurrentSearchAndRelaisList['relay_list']) && !empty($deliveryInfos['relay_id'])) {
$selectedRelay = $this->getSelectedRelay(
$deliveryInfos['relay_id'],
$newCurrentSearchAndRelaisList['relay_list']
);
}
// Si le client a un numero mobile
$telephone = !empty($address->phone_mobile) ? $address->phone_mobile : $address->phone;
$this->context->smarty->assign(
[
'dpdfrance_base_dir' => __PS_BASE_URI__ . 'modules/' . $this->name,
'ssl' => (int)Configuration::get('PS_SSL_ENABLED'),
'ssl_everywhere' => (int)Configuration::get('PS_SSL_ENABLED_EVERYWHERE'),
'dpdfrance_relais_points' => (!isset($dpdfrance_relais_points['error']) ? $dpdfrance_relais_points : null),
'error' => (isset($dpdfrance_relais_points['error']) ? $this->l($dpdfrance_relais_points['error']) : null),
'dpdfrance_selectedrelay' => $selectedRelay,
'dpdfrance_selectedRelayAddress' => isset($newCurrentSearchAndRelaisList['relay_list'][$selectedRelay]) ? $newCurrentSearchAndRelaisList['relay_list'][$selectedRelay] : null,
'dpdfrance_relais_status' => (Tools::getValue('dpdrelais') ? Tools::getValue('dpdrelais') : null),
'dpdfrance_relais_carrier_id' => DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID'),
'dpdfrance_predict_gsm_dest' => !empty($deliveryInfos['gsm_dest']) ? $deliveryInfos['gsm_dest'] : $telephone,
'dpdfrance_predict_status' => (Tools::getValue('dpdpredict') ? Tools::getValue('dpdpredict') : null),
'dpdfrance_predict_carrier_id' => DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID'),
]
);
return $this->display(__FILE__, 'views/templates/front/aftercarrier.tpl');
}
}
/**
* [FRONT OFFICE] When the order is complete
* If DPD France is selected, replaces customer shipping address by pudo's or Predict number
* @return void
*/
public function hookActionValidateOrder($params)
{
$order = $params['order'];
$cart = $params['cart'];
$customer = $params['customer'];
switch ((int)$order->id_carrier) {
case DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID'):
// Retrieve default order address and fetch its ID
$ps_address = new Address($cart->id_address_delivery);
$id_address_delivery = (int)$ps_address->id;
// Retrieve DPD Pickup point selection
$address_relais = DPDTools::getDeliveryInfos((int)$cart->id);
// DPD Pickup address will become one of customer's
if (is_array($address_relais) && !empty($address_relais['relay_id'])) {
$new_address = new Address();
$new_address->id_customer = $ps_address->id_customer;
$new_address->lastname = $ps_address->lastname;
$new_address->firstname = $ps_address->firstname;
$new_address->company = Tools::substr($address_relais['company'], 0, 23) . ' (' . $address_relais['relay_id'] . ')';
$new_address->address1 = Tools::substr($address_relais['address1'], 0, 128);
$new_address->address2 = Tools::substr($address_relais['address2'], 0, 128);
$new_address->postcode = $address_relais['postcode'];
$new_address->city = $address_relais['city'];
$new_address->phone = $ps_address->phone;
$new_address->phone_mobile = $ps_address->phone_mobile;
$new_address->id_country = $address_relais['id_country'];
$new_address->alias = 'DPD Relais ' . $address_relais['relay_id'];
$new_address->deleted = 1;
$new_address->add();
$id_address_delivery = (int)$new_address->id;
}
// Update order
$order->id_address_delivery = $id_address_delivery;
$order->update();
break;
case DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID'):
// Retrieve default order address and fetch its ID
$ps_address = new Address($cart->id_address_delivery);
$id_address_delivery = (int)$ps_address->id;
// Retrieve GSM number for Predict
$address_predict = DPDTools::getDeliveryInfos((int)$cart->id);
// Predict address will become one of customer's
if (is_array($address_predict) && !empty($address_predict['gsm_dest'])) {
$new_address = new Address();
$new_address->id_customer = $ps_address->id_customer;
$new_address->lastname = $ps_address->lastname;
$new_address->firstname = $ps_address->firstname;
$new_address->company = $ps_address->company;
$new_address->address1 = $ps_address->address1;
$new_address->address2 = $ps_address->address2;
$new_address->postcode = $ps_address->postcode;
$new_address->city = $ps_address->city;
$new_address->id_country = $ps_address->id_country;
$new_address->phone = $ps_address->phone;
$new_address->phone_mobile = $ps_address->phone_mobile;
$new_address->alias = 'DPD Predict ' . $address_predict['gsm_dest'];
$new_address->deleted = 1;
$new_address->add();
$id_address_delivery = (int)$new_address->id;
}
// Update order
$order->id_address_delivery = $id_address_delivery;
$order->update();
break;
}
// Si jamais la personne a recherché des points relais PUDO (même si finalement elle a utilisé un autre mode de livraison)
if (
$cart instanceof Cart && !empty($cart->id)
&& $customer instanceof Customer && !empty($customer->id)
&& !empty(DPDTools::getCurrentRelaisDatasSearchAndRelaisList((int)$cart->id, (int)$customer->id))
) {
// On supprime les relais temporaires rattachés à son panier
DPDTools::deleteCurrentRelaisDatasSearchAndRelaisList((int)$cart->id, (int)$customer->id);
}
}
/**
* [FRONT OFFICE] When processing the order (order checkout process), if the options is enabled, display the lead time in the top summary
*
* @param array $params
* @return string|void
*/
public function hookDisplayCheckoutSummaryTop($params)
{
if ($params['cart']->id_carrier) {
$isCarrierDpd = false;
if (
(int)$params['cart']->id_carrier === DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID')
|| (int)$params['cart']->id_carrier === DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID')
|| (int)$params['cart']->id_carrier === DPDConfig::get('DPDFRANCE_CLASSIC_CARRIER_ID')
) {
$isCarrierDpd = true;
}
if ($isCarrierDpd && $params['cart']->id_address_delivery) {
$leadtimeJson = DPDTools::getLeadtime(
$params['cart']->id_address_delivery,
$this->context->language->iso_code,
true
);
if ($leadtimeJson) {
$leadtimeInfo = json_decode($leadtimeJson);
$this->context->smarty->assign(
[
'leadtime' => $leadtimeInfo->date
]
);
return $this->display(__FILE__, 'views/templates/hook/checkout_summary_top.tpl');
}
}
}
}
/**
* [FRONT OFFICE] If the final order summary option is enabled,
* handle the order summary with DPD complementary delivery information
*
* @param array $params
* @return string|void
*/
public function hookDisplayPaymentTop($params)
{
if ($params['cart']->id_carrier &&
(int)$params['cart']->id_carrier === DPDConfig::get('DPDFRANCE_RELAIS_CARRIER_ID')) {
//Handle the order summary with the PUDO point
$shippingAddress = DPDTools::getDeliveryInfos($params['cart']->id);
if(empty($shippingAddress['relay_id']) && !Configuration::get('PS_ORDER_PROCESS_TYPE')) {
Tools::redirect('index.php?controller=order&step=2&relay_error=true');
}
$summaryShippingAddress = [
'type' => 'relay',
'name' => $shippingAddress['company'] . ' ' . $shippingAddress['relay_id'],
'customer' => $this->context->customer->firstname . ' ' . $this->context->customer->lastname,
'location' => $shippingAddress['address1'],
'address' => $shippingAddress['postcode'] . ' ' . $shippingAddress['city'],
];
$this->context->smarty->assign(
[
'summary_shipping_address' => $summaryShippingAddress
]
);
return $this->display(__FILE__, 'views/templates/hook/payment_top.tpl');
} elseif ($params['cart']->id_carrier &&
(int)$params['cart']->id_carrier === DPDConfig::get('DPDFRANCE_PREDICT_CARRIER_ID')) {
//Handle the order summary with the predict phone number registered
$shippingPhone = DPDTools::getPhoneNumberFromDpdShipping((int)$params['cart']->id, (int)$params['cart']->id_carrier);
$summaryShippingAddress = [
'type' => 'predict',
'customer' => $this->context->customer->firstname . ' ' . $this->context->customer->lastname,
'phone' => $shippingPhone,
];
$this->context->smarty->assign(
[
'summary_shipping_address' => $summaryShippingAddress
]
);
return $this->display(__FILE__, 'views/templates/hook/payment_top.tpl');
}
}
// GETTERS
/**
* @return string
*/
public function getJsPath()
{
return $this->jsPath;
}
/**
* @return string
*/
public function getCssPath()
{
return $this->cssPath;
}
/**
* @return string
*/
public function getImgPath()
{
return $this->imgPath;
}
/**
* @return string
*/
public function getDocsPath()
{
return $this->docsPath;
}
/**
* @return string
*/
public function getLogoPath()
{
return $this->logoPath;
}
/**
* @return string
*/
public function getModulePath()
{
return $this->modulePath;
}
}