✏️ 正在编辑: AdminDPDFranceController.php
路径:
/home/bpioifn/www/pigmentse/modules/dpdfrance/controllers/admin/AdminDPDFranceController.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php /** * 2007-2022 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author DPD France S.A.S. <support.ecommerce@dpd.fr> * @copyright 2022 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; } require_once(__DIR__ . '/../../vendor/PDFMerger-master/PDFMerger.php'); use PDFMerger\PDFMerger as DPDPDFMerger; class AdminDPDFranceController extends ModuleAdminController { public $identifier = 'DPDFrance'; private $pdf; private $erreurLabel; private $dirPdf; public function __construct() { $this->name = 'DPDFrance'; $this->bootstrap = true; $this->display = 'view'; $this->meta_title = 'Gestion des expéditions'; $this->dirPdf = __DIR__ . "/../../pdf"; if (!is_dir($this->dirPdf)) { mkdir($this->dirPdf); } parent::__construct(); if (!$this->module->active) { Tools::redirectAdmin($this->context->link->getAdminLink('AdminHome')); } } /** * @inheritdoc * @param $isNewTheme */ public function setMedia($isNewTheme = false) { parent::setMedia($isNewTheme); $this->addCSS([ _PS_MODULE_DIR_ . '/dpdfrance/views/js/admin/jquery/plugins/fancybox/jquery.fancybox.css', _PS_MODULE_DIR_ . '/dpdfrance/views/css/admin/AdminDPDFrance.css' ]); $this->addJS([ _PS_MODULE_DIR_ . '/dpdfrance/views/js/admin/jquery/plugins/marquee/jquery.marquee.min.js', _PS_MODULE_DIR_ . '/dpdfrance/views/js/admin/admin_france_pdf.js' ]); } /** * @inheritdoc * @return void */ public function initToolBarTitle() { $this->toolbar_title[] = $this->l('Orders'); $this->toolbar_title[] = $this->l('DPD deliveries management'); } public function translationLog() { $this->l('Permission denied'); $this->l('customer-Permission denied Invalid Customer '); $this->l('No name in address given'); $this->l('No city in address given'); $this->l('No street in address given'); $this->l('No zipCode in address given / zipCode is not valid'); $this->l('CountryPrefix-ZipCode-City is invalid'); $this->l('No countryPrefix in address given'); $this->l('CountryPrefix is invalid'); $this->l('Invalid shipper CenterNumber for customer CenterNumber'); $this->l('The maximum weight allowed for a Pickup parcelshop delivery is 20 kg, please modify the parcel weight'); $this->l('The maximum weight allowed for a Predict delivery is 30 kg, please modify the parcel weight'); $this->l('The maximum weight allowed for a Classic delivery is 30 kg, please modify the parcel weight'); $this->l('The maximum weight allowed for a Europe and Intercontinental delivery is 30 kg, please modify the parcel weight'); $this->l('Invalid weight - No decimal'); $this->l('Invalid weight - 0'); $this->l('Length of ZipCode is wrong. (3 instead of 4)'); $this->l('CountryPrefix-ZipCode-City is invalid '); $this->l('RoutingError: Error occured in DPD routing'); $this->l('AutoConsolidation not possible on MultiServices'); $this->l('No contact information (email/sms) given.'); $this->l('No email given'); $this->l('No sms number given'); $this->l('Shopid is not set'); $this->l('Parcelshop Error: Shopid not found'); $this->l('Print Master label is not allowed'); $this->l('Service is denied (2PSZustellung = Relais) '); $this->l('Invalid consolidation type '); $this->l('Predict and Consolidation are not compatible!'); $this->l('2PS delivery and Consolidation are not compatible!'); $this->l('Predict and 2PS delivery are not compatible! '); $this->l('Reverse Shop and Consolidation are not compatible!'); $this->l('Service not exportable'); $this->l('Service not exportable - eServiceTypPredict - only national possible'); $this->l('Service not exportable - eServiceTypPredict - only national possible'); $this->l('Service not importable/exportable - eServiceTypReverseShop - only national possible'); $this->l('no sms given number'); $this->l('Service not exportable - eServiceTypReverseShop - only national possible'); return true; } /** * * Sync order status with parcel status, adds tracking number * * @param string $id_employee * @param string $force * @throws PrestaShopDatabaseException * @throws PrestaShopException */ public function syncShipments(string $id_employee, string $force) { /** * ! Check if last tracking call is more than 1h old */ if ($force !== '1' && (time() - (int)Configuration::get('DPDFRANCE_LAST_TRACKING') < 3600)) { die('DPD France parcel tracking update is done once every hour. - Last update on : ' . date('d/m/Y - H:i:s', Configuration::get('DPDFRANCE_LAST_TRACKING'))); } /** ! Update the last tracking time */ Configuration::updateValue('DPDFRANCE_LAST_TRACKING', time()); $predict_carrier_log = $classic_carrier_log = $relais_carrier_log = $predict_carrier_sql = $classic_carrier_sql = $relais_carrier_sql = ''; /** * * If the DPD Marketplace setting is enabled then check all carriers ELSE check only DPD carriers */ $opt_marketplace_sql = Configuration::get('DPDFRANCE_MARKETPLACE_MODE') ? 'CA.name LIKE \'%%\'' : 'CA.name LIKE \'%DPD%\''; /** * * IF it is a MULTI-STORE */ if (Shop::isFeatureActive()) { foreach (Shop::getShops(true) as $shop) { if (Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, $shop['id_shop'])) { $predict_carrier_log .= Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, $shop['id_shop']) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_PREDICT_CARRIER_LOG', null, null, $shop['id_shop']), 1)))); } if (Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, $shop['id_shop'])) { $classic_carrier_log .= Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, $shop['id_shop']) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_CLASSIC_CARRIER_LOG', null, null, $shop['id_shop']), 1)))); } if (Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, $shop['id_shop'])) { $relais_carrier_log .= Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, $shop['id_shop']) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_RELAIS_CARRIER_LOG', null, null, $shop['id_shop']), 1)))); } } } /** * * IF it's NOT a MULTI STORE */ if (Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, null)) { if (!empty($predict_carrier_log)) { $predict_carrier_log .= ','; } $predict_carrier_log .= Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, null) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_PREDICT_CARRIER_LOG', null, null, null), 1)))); $predict_carrier_sql = 'CA.id_carrier IN (' . implode(',', array_unique(explode(',', $predict_carrier_log))) . ') OR '; } if (Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, null)) { if (!empty($classic_carrier_log)) { $classic_carrier_log .= ','; } $classic_carrier_log .= Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, null) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_CLASSIC_CARRIER_LOG', null, null, null), 1)))); $classic_carrier_sql = 'CA.id_carrier IN (' . implode(',', array_unique(explode(',', $classic_carrier_log))) . ') OR '; } if (Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, null)) { if (!empty($relais_carrier_log)) { $relais_carrier_log .= ','; } $relais_carrier_log .= Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, null) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_RELAIS_CARRIER_LOG', null, null, null), 1)))); $relais_carrier_sql = 'CA.id_carrier IN (' . implode(',', array_unique(explode(',', $relais_carrier_log))) . ') OR '; } /** * * GET DPD ORDER WHICH IS NOT WITH THE ORDER STATUS DELIVERED, CANCELLED, REFUNDED AND PAYMENT ERROR */ $sql = ' SELECT O.reference as reference, O.id_carrier as id_carrier, O.id_order as id_order, O.shipping_number as shipping_number, O.id_shop as id_shop FROM ' . _DB_PREFIX_ . 'orders AS O, ' . _DB_PREFIX_ . 'carrier AS CA WHERE CA.id_carrier = O.id_carrier AND O.current_state NOT IN (' . (int)Configuration::get('DPDFRANCE_ETAPE_LIVRE') . ',' . DPDTools::ORDER_STATUS_DELIVERED . ',' . DPDTools::ORDER_STATUS_CANCELLED . ',' . DPDTools::ORDER_STATUS_REFUNDED . ',' . DPDTools::ORDER_STATUS_PAYEMENT_ERROR . ') AND (' . $predict_carrier_sql . $classic_carrier_sql . $relais_carrier_sql . $opt_marketplace_sql . ') ORDER BY id_order DESC LIMIT 1000 '; /** * @var array $orderList * [ * "parcelnumber" => [...Cargo status list of the parcel ] * ] */ $orderList = Db::getInstance()->ExecuteS($sql); if (empty($orderList) === false) { echo 'DPD France - Sync started <br/>'; foreach ($orderList as $orderInfos) { $statusList = []; $order = new Order($orderInfos['id_order']); if (Validate::isLoadedObject($order)) { $internalRef = (int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_ORDER_ID ? $order->id : $order->reference; /** * * Vérification dans l'historique des statuts de livraison du colis,<br> * * $past_states à 1, s'il a été en "Expédié"<br> * * $past_states à 2, s'il a été en "Livré" */ $pastStates = 0; $orderHistory = $order->getHistory($order->id_lang); foreach ($orderHistory as $state) { if ((string)$state['id_order_state'] === (string)Configuration::get('DPDFRANCE_ETAPE_EXPEDIEE', null, null, (int)$order->id_shop)) { $pastStates = 1; } elseif ((string)$state['id_order_state'] === (string)Configuration::get('DPDFRANCE_ETAPE_LIVRE', null, null, (int)$order->id_shop)) { $pastStates = 2; break; } } /** * * Passe a la prochaine commande si la commande en cours de synchronisation est au statut "Livré" */ if ($pastStates === 2) { continue; } /** * * Vérifie l'option de livraison de la commande actuelle */ $service = DPDTools::getService($order, (int)Context::getContext()->language->id); /** * * Récupère les identifiants du compte en relation à l'option de livraison de la commande actuelle */ switch ($service) { case 'HDP_PRE': case 'PRE': $compte_chargeur = Configuration::get('DPDFRANCE_PREDICT_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_PREDICT_DEPOT_CODE', null, null, (int)$order->id_shop); break; case 'REL': $compte_chargeur = Configuration::get('DPDFRANCE_RELAIS_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_RELAIS_DEPOT_CODE', null, null, (int)$order->id_shop); break; case 'HDP_CLA': case 'CLA': $compte_chargeur = Configuration::get('DPDFRANCE_CLASSIC_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_CLASSIC_DEPOT_CODE', null, null, (int)$order->id_shop); break; } /** * * S'il n'y a aucun identifiant à l'option de livraison de la commande, je passe à la prochaine commande */ if (empty($compte_chargeur) === true || empty($depot_code) === true) { continue; } $prefixLog = 'Order [ id : ' . $order->id . ' | reference: ' . $order->reference . ' ] - '; $variables = [ 'customer_center' => '3', 'customer' => DPDTools::decrypt(Configuration::get('DPDFRANCE_WEBTRACE_LOGIN')), 'password' => DPDTools::decrypt(Configuration::get('DPDFRANCE_WEBTRACE_PASSWORD')), 'reference' => $internalRef, 'shipping_customer_center' => $depot_code, 'shipping_customer' => $compte_chargeur ]; /** * * Appel du webservice Webtrace pour récupérer les informations de la commande */ try { $soapClientTrace = DPDTools::getSoapTraceInit(); $response = $soapClientTrace->getShipmentTraceByReferenceGlobalWithCenterAsArray($variables); /** @var clsShipmentTrace[]|clsShipmentTrace $result */ $result = $response->getShipmentTraceByReferenceGlobalWithCenterAsArrayResult->clsShipmentTrace; unset($variables); /** * * Vérification réponse webservice trace OLD */ if (empty($result->LastError) === false) { echo $prefixLog . 'Error : ' . $result->LastError . ' <br/>'; continue; } /** * * Constitution d'un contenant la liste des statuts cargo ($statutList) */ if (is_array($result) === false) { /** * $result ne contient qu'un seul colis */ /** @var clsTrace|clsTrace[] $traces */ $traces = $result->Traces->clsTrace; if ( (string)$internalRef === (string)$result->Reference || (string)$internalRef === (string)$result->Reference2 || (string)$internalRef === (string)$result->Reference3 ) { if (is_array($traces) === false) { /** * Le colis ne contient qu'un seul statut */ if (DPDTools::PASSTRHOUGHT_CEDI === false && $traces->StatusNumber === DPDTools::CARGO_CEDI) { continue; } $statusList[$result->ShipmentNumber][] = $traces->StatusNumber; } else { /** * Le colis contient plusieurs statuts */ foreach ($traces as $trace) { $statusList[$result->ShipmentNumber][] = $trace->StatusNumber; } } } unset($traces); } else { /** * $result contient plusieurs colis */ foreach ($result as $parcelTrace) { if ( (string)$internalRef === (string)$parcelTrace->Reference || (string)$internalRef === (string)$parcelTrace->Reference2 || (string)$internalRef === (string)$parcelTrace->Reference3 ) { $datas = [ 'customer_center' => '3', 'customer' => DPDTools::decrypt(Configuration::get('DPDFRANCE_WEBTRACE_LOGIN')), 'password' => DPDTools::decrypt(Configuration::get('DPDFRANCE_WEBTRACE_PASSWORD')), 'shipmentnumber' => $parcelTrace->ShipmentNumber ]; $parcelDatas = $soapClientTrace->getShipmentTrace($datas); /** * @var clsTrace[]|clsTrace $parcelTraces */ $parcelTraces = $parcelDatas->getShipmentTraceResult->Traces->clsTrace; if (is_array($parcelTraces) === false) { /** * Le colis ne contient qu'un seul statut */ if (DPDTools::PASSTRHOUGHT_CEDI === false && $parcelTraces->StatusNumber === DPDTools::CARGO_CEDI) { continue; } $statusList[$parcelTrace->ShipmentNumber][] = $parcelTraces->StatusNumber; } else { /** * Le colis contient plusieurs statuts */ foreach ($parcelTraces as $trace) { $statusList[$parcelTrace->ShipmentNumber][] = $trace->StatusNumber; } } } break; // Stop at first parcel } } $shippingNumber = key($statusList); /** * * Si le tableau est vide, je passe à la prochaine commande */ if (empty($statusList) === true) { echo $prefixLog . 'Parcel ' . $shippingNumber . ' is found, not yet handled by DPD <br/>'; continue; } /** * * Affectation du flag de statut de livraison selon l'historique de statut de colis venant du webservice */ $deliveryState = 0; $cargoStatusEventTriggerForOnGoingDelivery = [ DPDTools::CARGO_COEC, DPDTools::CARGO_CPCH, DPDTools::CARGO_PICK, DPDTools::CARGO_HISTORIQUE_CPCH, DPDTools::CARGO_SMAN, ]; $cargoStatusEventTriggerForDelivered = [ DPDTools::CARGO_REMI, DPDTools::CARGO_LIVPT, ]; if (DPDTools::PASSTRHOUGHT_CEDI === true) { $cargoStatusEventTriggerForOnGoingDelivery[] = DPDTools::CARGO_CEDI; } foreach ($statusList as $events) { // * Vérification de la liste des status de la commande si la commande est en cours de preparation alors affectation du flag "Expédié" if (array_intersect($cargoStatusEventTriggerForOnGoingDelivery, $events)) { $deliveryState = 1; } // * Vérification de la liste des status de la commande si la commande est livré alors affectation du flag "Livré" if (array_intersect($cargoStatusEventTriggerForDelivered, $events)) { $deliveryState = 2; } } $url = null; /** * * Ajout du suivi de commande si la commande n'en a pas */ if (empty($order->shipping_number) === true && $deliveryState !== 0) { $url = (int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_PARCEL_NUMBER ? DPDTools::PREFIX_TRACES_URL . $shippingNumber : DPDTools::PREFIX_TRACEX_URL . $internalRef . '_' . $depot_code . $compte_chargeur; $order->shipping_number = (int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_PARCEL_NUMBER ? $shippingNumber : $internalRef . '_' . $depot_code . $compte_chargeur; Db::getInstance()->update( 'orders', array( 'shipping_number' => pSQL($order->shipping_number) ), 'id_order = '.(int)$order->id ); Db::getInstance()->update( 'order_carrier', array( 'tracking_number' => pSQL($order->shipping_number) ), 'id_order = '.(int)$order->id ); $order->update(); echo $prefixLog . 'Tracking number ' . $shippingNumber . ' added <br/>'; } /** * * Si la commande est flagué comme ayant le statut livré et qui n'ait jamais eu de statut livré sur son historique de commande * ? $deliveryState est défini via l'historique de status du colis du webservice * ? $past_states est défini via l'historique de status de commande de Prestashop * ! → Mise à jour du statut de commande en "Livré", envoi de mail */ if ($deliveryState === 2) { /** * Changement de status */ $history = new OrderHistory(); $history->id_order = $order->id; $history->id_employee = (int)$id_employee; $history->id_order_state = (int)Configuration::get('DPDFRANCE_ETAPE_LIVRE', null, null, (int)$order->id_shop); $history->changeIdOrderState((int)Configuration::get('DPDFRANCE_ETAPE_LIVRE', null, null, (int)$order->id_shop), $order->id); $history->addWithemail(); echo $prefixLog . 'Tracking number ' . $shippingNumber . ' is delivered <br/>'; continue; } /** * * Si la commande est en statut 'en cours de preparation' et qu'il n'a pas eu de statut "Expédié" ou "livré" dans son historique de statut Prestashop * ? $deliveryState est défini via l'historique de status du colis du webservice * ? $past_states est défini via l'historique de status de commande de Prestashop * ! → Mise à jour du statut de commande en "Expédié" et envoi de mail */ if ($deliveryState === 1 && $pastStates === 0) { /** * Changement de status */ $history = new OrderHistory(); $history->id_order = $order->id; $history->id_employee = (int)$id_employee; $history->id_order_state = (int)Configuration::get('DPDFRANCE_ETAPE_EXPEDIEE', null, null, (int)$order->id_shop); $history->changeIdOrderState((int)Configuration::get('DPDFRANCE_ETAPE_EXPEDIEE', null, null, (int)$order->id_shop), $order->id); /** * Envoi de mail */ $customer = new Customer($order->id_customer); $template_vars = [ '{followup}' => $url, '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{order_name}' => $order->reference, '{id_order}' => $order->id, ]; $subject = null; switch (Language::getIsoById($order->id_lang)) { case 'fr': $subject = 'Votre commande sera livrée par DPD'; break; case 'en': $subject = 'Your parcel will be delivered by DPD'; break; case 'es': $subject = 'Su pedido será enviado por DPD'; break; case 'it': $subject = 'Il vostro pacchetto sará trasportato da DPD'; break; case 'de': $subject = 'Ihre Bestellung wird per DPD geliefert werden'; break; } $history->addWithemail(true, $template_vars); Mail::Send( $order->id_lang, 'in_transit', $subject, $template_vars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int)$order->id_shop ); echo $prefixLog . 'Parcel ' . $shippingNumber . ' is handled by DPD <br/>'; continue; } echo $prefixLog . 'No update for parcel ' . $shippingNumber . ' <br/>'; } catch (SoapFault $e) { echo $prefixLog . 'Error : ' . $e->getMessage() . '<br/>'; continue; } } } echo 'DPD France - Sync complete. <br/>'; } else { echo 'DPD France - No orders to update.'; } } /** * ? Get eligible orders and builds up display Admin DPD France * @return string|void * @throws PrestaShopDatabaseException * @throws PrestaShopException * @throws PrestaShopExceptionCore * @throws SoapFault */ public function renderView() { $this->fields_form[]['form'] = []; $helper = $this->buildHelper(); $msg = ''; /** * ? Ajax call - Export label */ if (Tools::getIsset('exportLabel')) { // get the PS config weight unit and check for correct unit $psWeightUnit = strtolower(trim(Configuration::get('PS_WEIGHT_UNIT'))); $psWeightUnitType = 'kg'; switch ($psWeightUnit) { case ($psWeightUnit === 'g' || $psWeightUnit === 'gr' || $psWeightUnit === 'gram' || $psWeightUnit === 'grams' || $psWeightUnit === 'gramme' || $psWeightUnit === 'grammes'): $psWeightUnitType = 'g'; break; case ($psWeightUnit === 'lb' || $psWeightUnit === 'lbs' || $psWeightUnit === 'pound' || $psWeightUnit === 'livre' || $psWeightUnit === 'pounds' || $psWeightUnit === 'livres'): $psWeightUnitType = 'lb'; break; case ($psWeightUnit === 'oz' || $psWeightUnit === 'ounce' || $psWeightUnit === 'once' || $psWeightUnit === 'ounces' || $psWeightUnit === 'onces'): $psWeightUnitType = 'oz'; break; } file_put_contents(__DIR__ . "/../../session.txt", "start"); if (Tools::getIsset('checkbox')) { $orders = Tools::getValue('checkbox'); $print_format = Configuration::get('DPDFRANCE_FORMAT_PRINT'); $return = Tools::getValue('retour'); $extraInsurance = Tools::getValue('advalorem'); $parcelWeight = Tools::getValue('parcelweight'); if (is_string($orders)) { $orders = explode(',', $orders); } if (!empty($orders)) { $this->pdf = new DPDPDFMerger(); $zplPath = []; foreach ($orders as $order) { $this->erreurLabel = false; $order = new Order($order); $hasDpdOrder = false; if ($hasDpdOrder) { $this->generatedLabelAndTracking($order, 0, $print_format); } elseif (isset($parcelWeight[$order->id])) { $this->cleanLabel($order); $weights = $parcelWeight[$order->id]; $hasCreate = []; $insurance = false; $hasReturn = false; if($extraInsurance) { foreach ($extraInsurance as $insurances) { if ($insurances == $order->id) { $insurance = true; } } } if($return){ foreach ($return as $item) { if($item == $order->id) { $hasReturn = true; } } } if (!empty($order->id_address_delivery)) { foreach ($weights as $weight) { // Check weight for a comma and incorrect format $weight = DPDTools::formatWeightToFloatSyntax($weight); // Get the converted weight $weight = DPDTools::convertWeightToKilograms((float)$weight, $psWeightUnitType); if (Configuration::get('DPDFRANCE_FORMAT_MOD') === 'pdf' && Configuration::get('DPDFRANCE_PRINTER_CONNECT') !== 'ip') { $hasCreate[] = $this->generatedLabelAndTracking($order, $weight, $print_format, $hasDpdOrder, $hasReturn, $insurance); } else { $hasCreate[] = $this->generatedLabelAndTracking($order, $weight, $print_format, $hasDpdOrder, $hasReturn, $insurance, $zplPath); $zplPath = array_unique($zplPath); } } } } if (!$this->erreurLabel && Configuration::get('DPDFRANCE_FORMAT_MOD') !== 'pdf') { if (count($zplPath) > 0) { if (Configuration::get('DPDFRANCE_PRINTER_CONNECT') === 'ip') { foreach ($zplPath as $path) { unlink($path); } file_put_contents(__DIR__ . "/../../session.txt", "finish"); echo "<script type='text/javascript'>"; echo "window.close();"; echo "</script>"; exit; } } else { file_put_contents(__DIR__ . "/../../session.txt", "finish"); echo "<script type='text/javascript'>"; echo "window.close();"; echo "</script>"; exit; } } } file_put_contents(__DIR__ . "/../../session.txt", "finish"); ob_clean(); if (Configuration::get('DPDFRANCE_FORMAT_MOD') === 'pdf' && Configuration::get('DPDFRANCE_PRINTER_CONNECT') !== 'ip') { $pdfCreate = false; foreach ($hasCreate as $create) { if ($create) { $pdfCreate = true; } } if ($pdfCreate) { $this->pdf->merge('browser', 'label.pdf'); foreach (scandir($this->dirPdf) as $file) { $file = $this->dirPdf . "/" . $file; if (is_file($file)) { unlink($file); } } } else { echo "<script type='text/javascript'>"; echo "window.close();"; echo "</script>"; exit; } } else { file_put_contents(__DIR__ . "/../../session.txt", "finish"); echo "<script type='text/javascript'>"; echo "window.close();"; echo "</script>"; exit; } } } } /** * ? Ajax call - Update delivered orders */ if (Tools::getIsset('updateDeliveredOrders')) { if (Tools::getIsset('checkbox')) { $orders = Tools::getValue('checkbox'); //Sanitize $orders foreach ($orders as $order => $orderId) { $orders[$order] = pSQL($orderId); } if (is_string($orders)) { $orders = explode(',', $orders); } if (!empty($orders)) { /** * If error modify SQL select method * Look for the same SQL query in updateShippedOrders * SELECT O.`id_order` AS id_order * FROM ' . _DB_PREFIX_ . 'orders AS O, * ' . _DB_PREFIX_ . 'carrier AS CA */ $sql = new DbQuery(); $sql->select('id_order') ->from('orders', 'O') ->from('carrier', 'CA') ->where('CA.id_carrier = O.id_carrier') ->where('id_order IN ('.implode(',', array_map('intval', $orders)).')'); $orderlist = Db::getInstance()->executeS($sql); if (!empty($orderlist)) { // Check if there are DPD orders foreach ($orderlist as $orders) { $id_order = $orders['id_order']; if (Validate::isLoadedObject($order = new Order($id_order))) { $history = new OrderHistory(); $history->id_order = (int)$id_order; $history->id_order_state = (int)Configuration::get('DPDFRANCE_ETAPE_LIVRE', null, null, (int)$order->id_shop); $history->changeIdOrderState((int)Configuration::get('DPDFRANCE_ETAPE_LIVRE', null, null, (int)$order->id_shop), $id_order); $history->id_employee = Context::getContext()->employee->id; $history->addWithemail(); } } $msg = '<div class="okmsg">' . $this->l('Delivered orders statuses were updated') . '</div>'; } else { $msg = '<div class="warnmsg">' . $this->l('No DPD trackings to generate.') . '</div>'; } } else { $msg = '<div class="warnmsg">' . $this->l('No order selected.') . '</div>'; } } else { $msg = '<div class="warnmsg">' . $this->l('No order selected.') . '</div>'; } } /** * ? Ajax call - Update shipped orders */ if (Tools::getIsset('updateShippedOrders')) { if (Tools::getIsset('checkbox')) { $orders = Tools::getValue('checkbox'); //Sanitize $orders foreach ($orders as $order => $orderId) { $orders[$order] = pSQL($orderId); } if (is_string($orders)) { $orders = explode(',', $orders); } $sql = new DbQuery(); $sql->select('id_order') ->from('orders', 'O') ->from('carrier', 'CA') ->where('CA.id_carrier = O.id_carrier') ->where('id_order IN ('.implode(',', array_map('intval', $orders)).')'); $orderlist = Db::getInstance()->executeS($sql); // Check if there are DPD orders if (!empty($orderlist)) { foreach ($orderlist as $orders) { $id_order = $orders['id_order']; if (Validate::isLoadedObject($order = new Order($id_order))) { /* If order choices is 3 then use id order otherwise use order reference*/ $internalref = (int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_ORDER_ID ? $order->id : $order->reference; $service = DPDTools::getService($order, (int)Context::getContext()->language->id); switch ($service) { case 'HDP_PRE': case 'PRE': $compte_chargeur = Configuration::get('DPDFRANCE_PREDICT_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_PREDICT_DEPOT_CODE', null, null, (int)$order->id_shop); break; case 'REL': $compte_chargeur = Configuration::get('DPDFRANCE_RELAIS_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_RELAIS_DEPOT_CODE', null, null, (int)$order->id_shop); break; case 'HDP_CLA': case 'CLA': $compte_chargeur = Configuration::get('DPDFRANCE_CLASSIC_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_CLASSIC_DEPOT_CODE', null, null, (int)$order->id_shop); break; } $customer = new Customer($order->id_customer); if ((int)Configuration::get('DPDFRANCE_AUTO_UPDATE') !== DPDTools::DPD_AUTOUPDATE_PARCEL_NUMBER) { $order->shipping_number = $internalref . '_' . $depot_code . $compte_chargeur; Db::getInstance()->update( 'orders', array( 'shipping_number' => pSQL($order->shipping_number) ), 'id_order = '.$id_order ); Db::getInstance()->update( 'order_carrier', array( 'tracking_number' => pSQL($order->shipping_number) ), 'id_order = '.$id_order ); $order->update(); } $history = new OrderHistory(); $history->id_order = (int)$id_order; $history->changeIdOrderState(Configuration::get('DPDFRANCE_ETAPE_EXPEDIEE', null, null, (int)$order->id_shop), $id_order); $history->id_employee = $this->context->employee->id; $carrier = new Carrier($order->id_carrier, (int)Context::getContext()->language->id); $url = DPDTools::PREFIX_TRACEX_URL . $internalref . '_' . $depot_code . $compte_chargeur; $template_vars = [ '{followup}' => $url, '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => $order->id, '{order_name}' => $order->reference, ]; switch (Language::getIsoById((int)$order->id_lang)) { case 'fr': $subject = 'Votre commande sera livrée par DPD'; break; case 'en': $subject = 'Your parcel will be delivered by DPD'; break; case 'es': $subject = 'Su pedido será enviado por DPD'; break; case 'it': $subject = 'Il vostro pacchetto sará trasportato da DPD'; break; case 'de': $subject = 'Ihre Bestellung wird per DPD geliefert werden'; break; } if (!$history->addWithemail(true, $template_vars)) { $this->_errors[] = Tools::displayError('an error occurred while changing status or was unable to send e-mail to the customer'); } if (!Validate::isLoadedObject($customer) || !Validate::isLoadedObject($carrier)) { die(Tools::displayError()); } Mail::Send($order->id_lang, 'in_transit', $subject, $template_vars, $customer->email, $customer->firstname . ' ' . $customer->lastname); } } $msg = '<div class="okmsg">' . $this->l('Shipped orders statuses were updated and tracking numbers added.') . '</div>'; } else { $msg = '<div class="warnmsg">' . $this->l('No trackings to generate.') . '</div>'; } } else { $msg = '<div class="warnmsg">' . $this->l('No order selected.') . '</div>'; } } /** * ? Ajax call - Export DAT File of the selected order */ if (Tools::getIsset('exportOrders')) { if (Tools::getIsset('checkbox')) { $orders = Tools::getValue('checkbox'); //Sanitize $orders foreach ($orders as $order => $orderId) { $orders[$order] = pSQL($orderId); } if (is_string($orders)) { $orders = explode(',', $orders); } $liste_expeditions = 'O.id_order IN (' . implode(',', array_map('intval', $orders)) . ')'; if (!empty($orders)) { $sql = new DbQuery(); $sql->select('O.id_order, AD.lastname, AD.firstname, AD.postcode, AD.city, CL.iso_code, C.email') ->from('orders', 'O') ->from('carrier', 'CA') ->from('customer', 'C') ->from('address', 'AD') ->from('country', 'CL') ->where('O.id_address_delivery = AD.id_address') ->where('C.id_customer = O.id_customer') ->where('CL.id_country = AD.id_country') ->where('CA.id_carrier = O.id_carrier') ->where('('.$liste_expeditions.')') ->orderBy('id_order DESC'); /** @var array $orderlist */ $orderlist = Db::getInstance()->executeS($sql); if (!empty($orderlist)) { // File creation require_once(_PS_MODULE_DIR_ . 'dpdfrance/classes/admin/DPDStation.php'); $record = new DPDStation(); foreach ($orderlist as $order_var) { // Shipper information retrieval $order = new Order($order_var['id_order']); if (((int)Configuration::get('DPDFRANCE_ETAPE_EXPEDIEE', null, null, $this->context->shop->id) === $order->current_state)) { continue; } $nom_exp = Configuration::get('DPDFRANCE_NOM_EXP', null, null, (int)$order->id_shop); // Raison sociale expéditeur $address_exp = Configuration::get('DPDFRANCE_ADDRESS_EXP', null, null, (int)$order->id_shop); // Adresse $address2_exp = Configuration::get('DPDFRANCE_ADDRESS2_EXP', null, null, (int)$order->id_shop); // Complément d'adresse $cp_exp = Configuration::get('DPDFRANCE_CP_EXP', null, null, (int)$order->id_shop); // Code postal $ville_exp = Configuration::get('DPDFRANCE_VILLE_EXP', null, null, (int)$order->id_shop); // Ville $code_pays_exp = 'F'; // Code pays $tel_exp = Configuration::get('DPDFRANCE_TEL_EXP', null, null, (int)$order->id_shop); // Téléphone $email_exp = Configuration::get('DPDFRANCE_EMAIL_EXP', null, null, (int)$order->id_shop); // E-mail $gsm_exp = Configuration::get('DPDFRANCE_GSM_EXP', null, null, (int)$order->id_shop); // N° GSM $internalref = (int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_ORDER_ID ? $order->id : $order->reference; // Reference ou id de la commande $customer = new Customer($order->id_customer); $address_invoice = new Address($order->id_address_invoice, Context::getContext()->language->id); $address_delivery = new Address($order->id_address_delivery, Context::getContext()->language->id); $code_pays_dest = DPDTools::getIsoCodeByIdCountry($address_delivery->id_country); // Ireland override if ($code_pays_dest === 'IRL') { $address_delivery->postcode = stripos($address_delivery->city, 'Dublin') !== false ? 1 : 2; } $instr_liv_cleaned = ''; $order_messages = Message::getMessagesByOrderId($order->id); if ($order_messages) { foreach ($order_messages as $message) { $instr_liv_cleaned = str_replace(["\r\n", "\n", "\r", "\t"], ' ', html_entity_decode($message['message'], ENT_QUOTES)); break; } } $service = DPDTools::getService($order, (int)Context::getContext()->language->id); $relay_id = ''; preg_match('/P\d{5}/i', $address_delivery->company, $matches, PREG_OFFSET_CAPTURE); if ($matches) { $relay_id = $matches[0][0]; } $sqlQuery = new DbQuery(); $sqlQuery->select('gsm_dest') ->from('dpdfrance_shipping') ->where('id_cart = '.$order->id_cart); $tel_dest = Db::getInstance()->getValue($sqlQuery); if (empty($tel_dest)) { $tel_dest = DPDTools::getPhoneNumberFromAddress($address_invoice, $address_delivery); } $mobile = preg_replace('/\s+/', '', $tel_dest); if (!DPDTools::checkGsmValidity($mobile)) { $mobile = "invalid gsm number"; } $poids_all = Tools::getValue('parcelweight'); $poids = null; if (Tools::strtolower(Configuration::get('PS_WEIGHT_UNIT', null, null, (int)$order->id_shop)) === 'kg') { $poids = (int)($poids_all[$order->id] * 100); } if (Tools::strtolower(Configuration::get('PS_WEIGHT_UNIT', null, null, (int)$order->id_shop)) === 'g') { $poids = (int)($poids_all[$order->id] * 0.1); } $retour_option = (int)Configuration::get('DPDFRANCE_RETOUR_OPTION', null, null, (int)$order->id_shop); /* 2: Inverse, 3: Sur demande, 4: Préparée */ switch ($service) { case 'HDP_PRE': case 'PRE': $compte_chargeur = Configuration::get('DPDFRANCE_PREDICT_SHIPPER_CODE', null, null, (int)$order->id_shop); break; case 'REL': $compte_chargeur = Configuration::get('DPDFRANCE_RELAIS_SHIPPER_CODE', null, null, (int)$order->id_shop); break; case 'HDP_CLA': case 'CLA': $compte_chargeur = Configuration::get('DPDFRANCE_CLASSIC_SHIPPER_CODE', null, null, (int)$order->id_shop); break; } /** ? Send datas for the exporting DAT FILE */ $record->formatRow( $internalref, $order->id, $service, Tools::getValue('advalorem'), $order->total_paid, Tools::getValue('retour'), $retour_option, $poids, $address_delivery, $code_pays_dest, $mobile, $tel_dest, $relay_id, $customer->email, $nom_exp, $address2_exp, $cp_exp, $ville_exp, $address_exp, $code_pays_exp, $tel_exp, $instr_liv_cleaned, $compte_chargeur, $email_exp, $gsm_exp ); } $record->download(); } else { $msg = '<div class="warnmsg">' . $this->l('No orders to export.') . '</div>'; } } else { $msg = '<div class="warnmsg">' . $this->l('No orders to export.') . '</div>'; } } else { $msg = '<div class="warnmsg">' . $this->l('No order selected.') . '</div>'; } } // Display section // Error message if shipper info is missing if ((Configuration::get('DPDFRANCE_PARAM') === '0')) { echo '<div class="warnmsg">' . $this->l('Warning! Your DPD Depot code and contract number are missing. You must configure the DPD module in order to use the export and tracking features.') . '</div>'; exit; } // Calls function to get orders $order_info = []; $orderStatusList = []; $statuses = OrderState::getOrderStates(Context::getContext()->language->id); foreach ($statuses as $status) { $orderStatusList[$status['id_order_state']] = $status['name']; } $currentShopId = (int)Tools::substr($this->context->cookie->shopContext, 2); $orders = DPDTools::getAllOrders($currentShopId); $liste_expeditions = 'O.id_order IN (' . implode(',', $orders) . ')'; $predict_carrier_sql = $classic_carrier_sql = $relais_carrier_sql = ''; $opt_marketplace_sql = Configuration::get('DPDFRANCE_MARKETPLACE_MODE') ? 'CA.name LIKE "%%"' : 'CA.name LIKE "%DPD%"'; if ($currentShopId == 0 && Shop::isFeatureActive()) { $predict_carrier_log = Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, null) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_PREDICT_CARRIER_LOG', null, null, null), 1)))); $classic_carrier_log = Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, null) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_CLASSIC_CARRIER_LOG', null, null, null), 1)))); $relais_carrier_log = Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, null) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_RELAIS_CARRIER_LOG', null, null, null), 1)))); foreach (Shop::getShops() as $shop) { if (Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, $shop['id_shop'])) { $predict_carrier_log .= Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, $shop['id_shop']) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_PREDICT_CARRIER_LOG', null, null, $shop['id_shop']), 1)))); $predict_carrier_sql = 'CA.id_carrier IN (' . $predict_carrier_log . ') OR '; } if (Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, $shop['id_shop'])) { $classic_carrier_log .= Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, $shop['id_shop']) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_CLASSIC_CARRIER_LOG', null, null, $shop['id_shop']), 1)))); $classic_carrier_sql = 'CA.id_carrier IN (' . $classic_carrier_log . ') OR '; } if (Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, $shop['id_shop'])) { $relais_carrier_log .= Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, $shop['id_shop']) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_RELAIS_CARRIER_LOG', null, null, $shop['id_shop']), 1)))); $relais_carrier_sql = 'CA.id_carrier IN (' . $relais_carrier_log . ') OR '; } } } else { if (Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, $currentShopId)) { $predict_carrier_log = Configuration::get('DPDFRANCE_PREDICT_CARRIER_ID', null, null, $currentShopId) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_PREDICT_CARRIER_LOG', null, null, $currentShopId), 1)))); $predict_carrier_sql = 'CA.id_carrier IN (' . $predict_carrier_log . ') OR '; } if (Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, $currentShopId)) { $classic_carrier_log = Configuration::get('DPDFRANCE_CLASSIC_CARRIER_ID', null, null, $currentShopId) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_CLASSIC_CARRIER_LOG', null, null, $currentShopId), 1)))); $classic_carrier_sql = 'CA.id_carrier IN (' . $classic_carrier_log . ') OR '; } if (Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, $currentShopId)) { $relais_carrier_log = Configuration::get('DPDFRANCE_RELAIS_CARRIER_ID', null, null, $currentShopId) . ',' . implode(',', array_map('intval', explode('|', Tools::substr(Configuration::get('DPDFRANCE_RELAIS_CARRIER_LOG', null, null, $currentShopId), 1)))); $relais_carrier_sql = 'CA.id_carrier IN (' . $relais_carrier_log . ') OR '; } } if (!empty($orders)) { $sql = 'SELECT O.id_order, O.id_cart, AD.lastname, AD.firstname, AD.postcode, AD.city, CL.iso_code, C.email, CA.name FROM ' . _DB_PREFIX_ . 'orders AS O, ' . _DB_PREFIX_ . 'carrier AS CA, ' . _DB_PREFIX_ . 'customer AS C, ' . _DB_PREFIX_ . 'address AS AD, ' . _DB_PREFIX_ . 'country AS CL WHERE O.id_address_delivery = AD.id_address AND C.id_customer = O.id_customer AND CL.id_country = AD.id_country AND CA.id_carrier = O.id_carrier AND (' . $predict_carrier_sql . $classic_carrier_sql . $relais_carrier_sql . $opt_marketplace_sql . ') AND (' . $liste_expeditions . ') ORDER BY id_order DESC'; $orderlist = Db::getInstance()->ExecuteS($sql); if (!empty($orderlist)) { foreach ($orderlist as $order_var) { $order = new Order($order_var['id_order']); $address_delivery = new Address($order->id_address_delivery, Context::getContext()->language->id); $current_state_id = $order->current_state; $current_state_name = $orderStatusList[$order->current_state]; $internalref = (int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_ORDER_ID ? $order->id : $order->reference; switch ($current_state_id) { default: $dernierstatutcolis = ''; break; case Configuration::get('DPDFRANCE_ETAPE_LIVRE', null, null, (int)$order->id_shop): $dernierstatutcolis = '<img src="../modules/dpdfrance/views/img/admin/tracking.png" title="Trace du colis" alt="tracking" />'; break; case Configuration::get('DPDFRANCE_ETAPE_EXPEDIEE', null, null, (int)$order->id_shop): $dernierstatutcolis = '<img src="../modules/dpdfrance/views/img/admin/tracking.png" title="Trace du colis" alt="tracking" />'; } $weight = $order->getTotalWeight(); $amount = number_format($order->total_paid, 2, '.', '.') . ' €'; $service = DPDTools::getService($order, (int)Context::getContext()->language->id); $code_pays_dest = DPDTools::getIsoCodeByIdCountry($address_delivery->id_country); switch ($service) { case 'HDP_PRE': case 'PRE': $type = $code_pays_dest !== 'F' ? 'Predict Export<img src="../modules/dpdfrance/views/img/admin/service_predict.png" title="Predict Export" alt="predict export"/>' : 'Predict<img src="../modules/dpdfrance/views/img/admin/service_predict.png" title="Predict" alt="predict"/>'; $compte_chargeur = Configuration::get('DPDFRANCE_PREDICT_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_PREDICT_DEPOT_CODE', null, null, (int)$order->id_shop); $address = '<a class="popup" href="' . DPDTools::PREFIX_GOOGLE_URL . str_replace(' ', '+', $address_delivery->address1) . ',' . str_replace(' ', '+', $address_delivery->postcode) . '+' . str_replace(' ', '+', $address_delivery->city) . '&output=embed" target="_blank">' . ($address_delivery->company ? $address_delivery->company . '<br/>' : '') . $address_delivery->address1 . '<br/>' . $address_delivery->postcode . ' ' . $address_delivery->city . '</a>'; break; case 'REL': $type = 'Relais<img src="../modules/dpdfrance/views/img/admin/service_relais.png" title="Relais" alt="relais"/>'; $compte_chargeur = Configuration::get('DPDFRANCE_RELAIS_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_RELAIS_DEPOT_CODE', null, null, (int)$order->id_shop); $relay_id = ''; preg_match('/P\d{5}/i', $address_delivery->company, $matches, PREG_OFFSET_CAPTURE); if ($matches) { $relay_id = $matches[0][0]; } $address = '<a class="popup" href="'. DPDTools::PREFIX_RELAIS_URL . $relay_id . '" target="_blank">' . $address_delivery->company . '<br/>' . $address_delivery->postcode . ' ' . $address_delivery->city . '</a>'; break; case 'HDP_CLA': case 'CLA': $type = $code_pays_dest !== 'F' ? 'Classic Export<img src="../modules/dpdfrance/views/img/admin/service_world.png" title="Classic Export" alt="classic export"/>' : 'Classic<img src="../modules/dpdfrance/views/img/admin/service_dom.png" title="Classic" alt="classic"/>'; $compte_chargeur = Configuration::get('DPDFRANCE_CLASSIC_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_CLASSIC_DEPOT_CODE', null, null, (int)$order->id_shop); $address = '<a class="popup" href="' . DPDTools::PREFIX_GOOGLE_URL . str_replace(' ', '+', $address_delivery->address1) . ',' . str_replace(' ', '+', $address_delivery->postcode) . '+' . str_replace(' ', '+', $address_delivery->city) . '&output=embed" target="_blank">' . ($address_delivery->company ? $address_delivery->company . '<br/>' : '') . $address_delivery->address1 . '<br/>' . $address_delivery->postcode . ' ' . $address_delivery->city . '</a>'; break; } $errorMessage = ""; $orderDpd = $this->getDpdOrder($order, $errorMessage); $sqlCountry = new DbQuery(); $sqlCountry->select('iso_code') ->from('country') ->innerJoin('address', null, _DB_PREFIX_.'country.id_country = '._DB_PREFIX_.'address.id_country') ->where(_DB_PREFIX_.'address.id_address = '.$order->id_address_delivery); $countrys = Db::getInstance()->executeS($sqlCountry); $order_info[] = [ 'checked' => ($current_state_id == Configuration::get('DPDFRANCE_ETAPE_EXPEDITION', null, null, (int)$order->id_shop) ? 'checked="checked"' : ''), 'id' => $order->id, 'reference' => $order->reference, 'date' => date('d/m/Y H:i:s', strtotime($order->date_add)), 'nom' => $address_delivery->firstname . ' ' . $address_delivery->lastname, 'type' => $type, 'address' => $address, 'poids' => $weight, 'weightunit' => Configuration::get('PS_WEIGHT_UNIT', null, null, (int)$order->id_shop), 'prix' => $amount, 'advalorem_checked' => (Configuration::get('DPDFRANCE_AD_VALOREM', null, null, (int)$order->id_shop) === '1' ? 'checked="checked"' : ''), 'retour_checked' => ((int)Configuration::get('DPDFRANCE_RETOUR_OPTION', null, null, (int)$order->id_shop) !== DPDTools::NO_RETURN ? 'checked="checked"' : ''), 'statut' => $current_state_name, 'depot_code' => $depot_code, 'shipper_code' => $compte_chargeur, 'dernier_statut_colis' => $dernierstatutcolis, 'labelprint' => ($this->hasDpdOrder($order) && $orderDpd !== "0"), 'statuslabel' => ($orderDpd === "0"), 'statustext' => $errorMessage, "expediee" => ((int)Configuration::get('DPDFRANCE_ETAPE_EXPEDIEE', null, null, $this->context->shop->id) === $order->current_state), "country" => $countrys[0]['iso_code'] ]; } } else { $order_info['error'] = true; } } else { $order_info['error'] = true; } /** * ? Assign smarty variables */ $this->context->smarty->assign( [ 'msg' => $msg, 'stream' => DPDTools::getDPDRssInfos(), 'token' => $this->token, 'dpdfrance_auto_update_option' => (int)Configuration::get('DPDFRANCE_AUTO_UPDATE', null, null, (int)Context::getContext()->shop->id), 'order_info' => $order_info, 'service' => Configuration::get('DPDFRANCE_SERVICE_TYPE'), 'dpdfrance_retour_option' => (int)Configuration::get('DPDFRANCE_RETOUR_OPTION', null, null, (int)Context::getContext()->shop->id), 'dpdfrance_mode_format' => Configuration::get('DPDFRANCE_FORMAT_MOD', null, null, (int)Context::getContext()->shop->id), 'dpdfrance_usb_name' => Configuration::get('DPDFRANCE_PRINTER_SERIAL', null, null, Context::getContext()->shop->id), 'dpdfrance_base_dir' => __PS_BASE_URI__ . 'modules/' . Tools::strtolower($this->name), 'dpdfrance_token' => Tools::hash('dpdfrance/ajax'), ] ); return $helper->generateForm($this->fields_form); } protected function buildHelper() { $helper = new HelperForm(); $helper->module = $this->module; $helper->override_folder = 'dpdfrance/'; $helper->identifier = $this->identifier; $helper->token = Tools::getAdminTokenLite('Admin' . $this->name); $helper->languages = $this->_languages; $helper->currentIndex = $this->context->link->getAdminLink('Admin' . $this->name); $helper->default_form_language = $this->default_form_language; $helper->allow_employee_form_lang = $this->allow_employee_form_lang; $helper->toolbar_scroll = true; $helper->toolbar_btn = $this->initToolbar(); $helper->background_color = 'red'; return $helper; } /** * ? Remove old label * @param $order * @return bool * @throws PrestaShopDatabaseException * @throws PrestaShopException */ public function cleanLabel($order): bool { if (is_int($order)) { $order = new Order($order); } if (!($order instanceof Order)) { return false; } Db::getInstance()->delete( 'dpdfrance_order', 'id_order = '.(int)$order->id ); return true; } /** * Generate X pdf page with the label for one order * A la generation de l'étiquette, cela va mettre le lien de tracking dans les details de la commande * * @param $order : int|order * @param string $weight * @param string $print_format * @param bool $hasDpdOrder * @param bool $return * @param bool $extraInsurance * @param array $zplPath * @return bool * @throws PrestaShopDatabaseException * @throws PrestaShopException * @throws PrestaShopExceptionCore */ public function generatedLabelAndTracking($order, string $weight, string $print_format = "a4", bool $hasDpdOrder = true, bool $return = false, bool $extraInsurance = false, array &$zplPath = []) { if (is_int($order)) { $order = new Order($order); } if (!($order instanceof Order)) { return false; } $parcelIds = []; $error = false; $soapClient = DPDTools::getSoapInitEPrint(); if ($soapClient === false) { return false; } if (((int)Configuration::get('DPDFRANCE_ETAPE_EXPEDIEE', null, null, (int)Context::getContext()->shop->id) === (int)$order->current_state)) { return false; } $address_delivery = new Address($order->id_address_delivery); $country = new Country($address_delivery->id_country); $service = DPDTools::getService($order, (int)Context::getContext()->language->id); switch ($service) { case 'HDP_PRE': case 'PRE': $compte_chargeur = Configuration::get('DPDFRANCE_PREDICT_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_PREDICT_DEPOT_CODE', null, null, (int)$order->id_shop); break; case 'REL': $compte_chargeur = Configuration::get('DPDFRANCE_RELAIS_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_RELAIS_DEPOT_CODE', null, null, (int)$order->id_shop); break; case 'HDP_CLA': case 'CLA': $compte_chargeur = Configuration::get('DPDFRANCE_CLASSIC_SHIPPER_CODE', null, null, (int)$order->id_shop); $depot_code = Configuration::get('DPDFRANCE_CLASSIC_DEPOT_CODE', null, null, (int)$order->id_shop); break; } $referenceNumber = (int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_ORDER_ID ? (string)$order->id : $order->reference; $parcelValidWeight = true; // Create shipment if not exist if (!$hasDpdOrder) { $StdShipmentLabelRequest = [ "customer_countrycode" => 250, "customer_centernumber" => (int)$depot_code, "customer_number" => (int)$compte_chargeur, "weight" => $weight, "referencenumber" => $referenceNumber, "receiveraddress" => [ "name" => $address_delivery->firstname . " " . $address_delivery->lastname, /** * Ajout du code ISO selon le filtre du webservice de Cargo */ "countryPrefix" => DPDTools::getCargoFilteredIsoCodeByIdCountry($address_delivery->id_country), "zipCode" => $address_delivery->postcode, "city" => $address_delivery->city, "street" => $address_delivery->address1 . " " . $address_delivery->address2, "phoneNumber" => empty($address_delivery->phone) ? $address_delivery->phone_mobile : $address_delivery->phone, ], /** * Ajout du nom de la société du destinataire */ "receiverinfo" => [ "name2" => $address_delivery->company, ], "shipperaddress" => [ "name" => Configuration::get('DPDFRANCE_NOM_EXP'), "countryPrefix" => "FR", "zipCode" => Configuration::get('DPDFRANCE_CP_EXP'), "city" => Configuration::get('DPDFRANCE_VILLE_EXP'), "street" => Configuration::get('DPDFRANCE_ADDRESS_EXP') . " " . Configuration::get('DPDFRANCE_ADDRESS2_EXP'), "phoneNumber" => Configuration::get('DPDFRANCE_TEL_EXP'), ], "services" => [] ]; /** * Assurance Advalorem */ if ($extraInsurance) { $StdShipmentLabelRequest['services']['extraInsurance'] = [ "value" => $order->total_paid, "type" => "byShipments" ]; } /** * Retour en relais*/ if ( $return && ( (int)Configuration::get('DPDFRANCE_RETOUR_OPTION') === DPDTools::RETURN_ON_DEMAND || (int)Configuration::get('DPDFRANCE_RETOUR_OPTION') === DPDTools::RETURN_PREPARED ) ) { $StdShipmentLabelRequest['services']['reverse'] = [ "expireOffset" => 175, "type" => (int)Configuration::get('DPDFRANCE_RETOUR_OPTION') === DPDTools::RETURN_ON_DEMAND ? "OnDemand" : "Prepared", "retour_receiver" => [ "name" => Configuration::get('DPDFRANCE_NOM_EXP'), "countryPrefix" => "FR", "zipCode" => Configuration::get('DPDFRANCE_CP_EXP'), "city" => Configuration::get('DPDFRANCE_VILLE_EXP'), "street" => Configuration::get('DPDFRANCE_ADDRESS_EXP') . " " . Configuration::get('DPDFRANCE_ADDRESS2_EXP'), "phoneNumber" => Configuration::get('DPDFRANCE_TEL_EXP'), ], ]; } //__ If Predict OU Hors DPD Predict if ((string)$service === 'PRE' || (string)$service === 'HDP_PRE') { $phoneNumber = ''; if ($service === 'PRE') { $sqlQuery = new DbQuery(); $sqlQuery->select('gsm_dest') ->from('dpdfrance_shipping') ->where('id_cart = '.(int)$order->id_cart) ->where('id_carrier = '.(int)$order->id_carrier); $phoneNumber = Db::getInstance()->getValue($sqlQuery); } if (empty($phoneNumber) === true) { $address_invoice = new Address($order->id_address_invoice, Context::getContext()->language->id); $address_delivery = new Address($order->id_address_delivery, Context::getContext()->language->id); $phoneNumber = DPDTools::getPhoneNumberFromAddress($address_invoice, $address_delivery); unset($address_invoice, $address_delivery); } $customer = new Customer($order->id_customer); $StdShipmentLabelRequest['services']['contact']['sms'] = $phoneNumber; $StdShipmentLabelRequest['services']['contact']['email'] = $customer->email; $StdShipmentLabelRequest['services']['contact']['type'] = 'Predict'; } //__ If Relay if ((string)$service === 'REL') { $sqlQuery = new DbQuery(); $sqlQuery->select('*') ->from('dpdfrance_shipping') ->where('id_cart = '.(int)$order->id_cart) ->where('id_carrier = '.(int)$order->id_carrier); $shipping = Db::getInstance()->getRow($sqlQuery); $customer = new Customer($order->id_customer); $StdShipmentLabelRequest['services']['contact']['email'] = $customer->email; $StdShipmentLabelRequest['services']['contact']['type'] = 'No'; $StdShipmentLabelRequest['services']['parcelshop']['shopaddress']['countryPrefix'] = 'FR'; $StdShipmentLabelRequest['services']['parcelshop']['shopaddress']['zipCode'] = $shipping['postcode']; $StdShipmentLabelRequest['services']['parcelshop']['shopaddress']['city'] = $shipping['city']; $StdShipmentLabelRequest['services']['parcelshop']['shopaddress']['street'] = $shipping['address1'] . ' ' . ($shipping['address2'] ?: ''); $StdShipmentLabelRequest['services']['parcelshop']['shopaddress']['name'] = $shipping['company']; $StdShipmentLabelRequest['services']['parcelshop']['shopaddress']['shopid'] = $shipping['relay_id']; } // Check valid weight for each delivery type (relay, predict, classic and world) if ((string)$service === 'REL') { if ($weight > 20) { $parcelValidWeight = false; $error = true; $errorMessage = "The maximum weight allowed for a Pickup parcelshop delivery is 20 kg, please modify the parcel weight"; } } else { if ($weight > 30) { $parcelValidWeight = false; $error = true; //Retrieve the id of the world carrier (SQL select may be incorrect due to back office carrier change name function) $sqlGetWorldCarrierId = "SELECT id_carrier FROM " . _DB_PREFIX_ . "carrier WHERE name = 'Livraison internationale par DPD';"; $result = db::getInstance()->executeS($sqlGetWorldCarrierId); $carrierWorldId = $result[0]['id_carrier']; if ($order->id_carrier === $carrierWorldId) { $errorMessage = "The maximum weight allowed for a Europe and Intercontinental delivery is 30 kg, please modify the parcel weight"; } else { if ((string)$service === 'PRE' || (string)$service === 'HDP_PRE') { $errorMessage = "The maximum weight allowed for a Predict delivery is 30 kg, please modify the parcel weight"; } else { $errorMessage = "The maximum weight allowed for a Classic delivery is 30 kg, please modify the parcel weight"; } } } } //If parcel weight is not valid skip try and catch if ($parcelValidWeight) { try { $data = $soapClient->CreateShipment(["request" => $StdShipmentLabelRequest]); } catch (\Exception $e) { $this->erreurLabel = true; $error = true; $errorMessage = $e->getMessage(); } } if ($error) { Db::getInstance()->insert( 'dpdfrance_order', [ 'id_order' => $order->id, 'id_order_dpd' => '0', 'id_shipment_number_dpd' => '', 'error_message' => $this->l($errorMessage), ], false, true, Db::INSERT_IGNORE ); return false; } if ( $return && ( (int)Configuration::get('DPDFRANCE_RETOUR_OPTION') === DPDTools::RETURN_ON_DEMAND || (int)Configuration::get('DPDFRANCE_RETOUR_OPTION') === DPDTools::RETURN_PREPARED ) ) { $parcelIds[] = $data->CreateShipmentResult->Shipment[0]->parcelnumber; $barCode = $data->CreateShipmentResult->Shipment[0]->barcode; } else { $parcelIds[] = $data->CreateShipmentResult->Shipment->parcelnumber; $barCode = $data->CreateShipmentResult->Shipment->barcode; } } else { $parcelIds = $this->getDpdOrder($order, $error, true); } // Get label foreach ($parcelIds as $parcelId) { $receiveLabelRequest = [ "countrycode" => 250, "centernumber" => (int)$depot_code, "parcelnumber" => $parcelId, ]; if ($print_format === 'a6' && Configuration::get('DPDFRANCE_FORMAT_MOD') === 'pdf') { $receiveLabelRequest["labelType"] = [ 'type' => 'PDF_A6' ]; } elseif ( $print_format === 'a4' && Configuration::get('DPDFRANCE_FORMAT_MOD') === 'pdf') { $receiveLabelRequest["labelType"] = [ 'type' => 'PDF' ]; } else { $receiveLabelRequest["labelType"] = [ 'type' => Tools::strtoupper(Configuration::get('DPDFRANCE_FORMAT_MOD')) ]; } try { $data = $soapClient->GetLabel(["request" => $receiveLabelRequest]); } catch (\Exception $e) { $this->erreurLabel = true; $error = true; } if ($error || empty($data->GetLabelResult->labels->Label[0]->label)) { return false; } $labels = $data->GetLabelResult->labels->Label; if ( Configuration::get('DPDFRANCE_FORMAT_MOD') === 'pdf' && Configuration::get('DPDFRANCE_PRINTER_CONNECT') !== 'ip' ) { if (empty($this->pdf)) { $this->pdf = new DPDPDFMerger(); } if (!$return) { $pathPdf = $this->dirPdf . "/PDF_" . $parcelId . $labels[0]->type . ".pdf"; file_put_contents($pathPdf, $labels[0]->label); $this->pdf->addPDF($pathPdf); } else { foreach ($labels as $key => $label) { if ($label->type !== 'EPRINTATTACHMENT') { $pathPdf = $this->dirPdf . "/PDF_" . $parcelId . $key . ".pdf"; file_put_contents($pathPdf, $label->label); $this->pdf->addPDF($pathPdf); } } } } elseif ( (string)Configuration::get('DPDFRANCE_FORMAT_MOD') === 'pdf' && (string)Configuration::get('DPDFRANCE_PRINTER_CONNECT') === 'ip' ) { $i = 0; foreach ($labels as $label) { if ((string)Configuration::get('DPDFRANCE_PRINTER_CONNECT') === 'ip') { if ( ($conn = fsockopen( Configuration::get('DPDFRANCE_PRINTER_IP'), Configuration::get('DPDFRANCE_PRINTER_PORT'), $errno, $errstr )) === false ) { echo 'configuration not ok'; } fwrite($conn, $label->label, Tools::strlen($label->label)); fclose($conn); } $path = __DIR__ . "/../../pdfLabel_" . $parcelId . '_' . $i . '.' . Configuration::get('DPDFRANCE_FORMAT_MOD'); file_put_contents($path, $label->label); $i++; $zplPath[] = $path; } } else { $i = 0; foreach ($labels as $label) { if ((string)Configuration::get('DPDFRANCE_PRINTER_CONNECT') === 'ip') { if ( ($conn = fsockopen( Configuration::get('DPDFRANCE_PRINTER_IP'), Configuration::get('DPDFRANCE_PRINTER_PORT'), $errno, $errstr )) === false ) { echo 'configuration not ok'; } fwrite($conn, $label->label, Tools::strlen($label->label)); fclose($conn); } $path = __DIR__ . "/../../zplLabel_" . $parcelId . '_' . $i . '.' . Configuration::get('DPDFRANCE_FORMAT_MOD'); file_put_contents($path, $label->label); $i++; $zplPath[] = $path; } } } if (!$hasDpdOrder) { Db::getInstance()->insert( 'dpdfrance_order', [ 'id_order' => $order->id, 'id_order_dpd' => $parcelId, 'id_shipment_number_dpd' => $barCode, ], false, true, Db::INSERT_IGNORE ); $orderCarrier = new OrderCarrier($order->getIdOrderCarrier()); $trackingNumber = null; // Mode 1 : références internes if ((int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_ORDER_REF) { $trackingNumber = $order->getUniqReference() . '_' . str_pad($depot_code, 3, '0') . $compte_chargeur; } // Mode 2 : numero de la commande if ((int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_PARCEL_NUMBER) { $trackingNumber = '250' . str_pad($depot_code, 3, '0') . $parcelId; } // Mode 3 : id de la commande if ((int)Configuration::get('DPDFRANCE_AUTO_UPDATE') === DPDTools::DPD_AUTOUPDATE_ORDER_ID) { $trackingNumber = (string)$order->id . '_' . str_pad($depot_code, 3, '0') . $compte_chargeur ; } $orderCarrier->tracking_number = $trackingNumber; $orderCarrier->save(); } return true; } /** * @param $order * @param bool $error * @return bool if order not empty or === 0 * @throws PrestaShopDatabaseException * @throws PrestaShopException */ public function hasDpdOrder($order, bool $error = true): bool { $dpdOrder = $this->getDpdOrder($order); if (!empty($dpdOrder)) { return true; } if (isset($dpdOrder) && $dpdOrder === "0" && $error) { return true; } return false; } /** * Get one or list of id_order_dpd * @param $order : int|Order * @param $error : array|null * @param bool $all * @return array|mixed|string * @throws PrestaShopDatabaseException * @throws PrestaShopException */ public function getDpdOrder($order, &$error = null, bool $all = false) { if (is_int($order)) { $order = new Order($order); } if ($order instanceof Order && !empty($order->id)) { $sql = new DbQuery(); $sql->select('*') ->from('dpdfrance_order') ->where('id_order = '.(int)$order->id); $result = Db::getInstance()->executeS($sql); if ( !empty($result[0]['id_order_dpd']) || (isset ($result[0]['id_order_dpd']) && $result[0]['id_order_dpd'] === "0") ) { $error = $result[0]['error_message']; if ($all) { $resultArray = []; foreach ($result as $dpd) { $resultArray[] = $dpd['id_order_dpd']; } return $resultArray; } return $result[0]['id_order_dpd']; } } return ''; } }
💾 保存文件
← 返回文件管理器