Initial commit

This commit is contained in:
2020-10-07 10:37:15 +02:00
commit ce5f440392
28157 changed files with 4429172 additions and 0 deletions

View File

@@ -0,0 +1,225 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.4.0] - 2020-07-31
### Added
- Compatibility with PrestaShop 1.7.7 for Admin Orders
- Allow direct thermal printing (ZPL or DPL)
### Changed
- Remove PrestUI
### Fixed
- Fix conditions for documents purge
- Fix conditions of display for older parcels in Deposit Slip page
- Fix bug when the cart includes customized products & the delivery type is "Pickup Point"
## [1.3.1] - 2020-05-28
### Fixed
- Fix table field
## [1.3.0] - 2020-05-20
### Added
- Pre-fill mobile number in widget area
- Allow pickup delivery in Hungary
- Add TagUsers in Coliship exports
- Add JS file to allow placeholder modification for mobile
- Allow merchants to disable PNA mail after label generation
- Allow customers to generate return label
- Implement ACE
- Allow merchants to hide shipments in Postage page (step 1)
### Changed
- Changed postage post-process logic
- Add confirmation message after tracking updates in Dashboard
- Add Logs controller to secure logfile download
- Lighten log files
- Brighten placeholder for mobile phone in widget area
- Add "Parcels of the day" selection in Deposit slips page
### Fixed
- Fix SQL query in Dashboard
- Fix Dashboard tracking updates
- Fix product name filled in CN23
- Fix credentials in single store mode
- Fix service changes & insurance in Postage page (step 2)
- Fix address & commercial name in labels
- Rename Overseas services
- Fix jQuery 3 compatibility
## [1.2.1] - 2019-11-05
### Added
- Add CN23 exceptions with some EU countries
### Fixed
- Fix default country for sender address in multistore All Shops context
- Fix table names
- Use pickup points address instead of invoice address in Coliship export
- Fix JS bug in widget
- Fix paginations and filters in backend lists (1.6)
- Fix PHP compatibility
## [1.2.0] - 2019-10-09
### Added
- Add Brexit mode to anticipate the withdrawal of the UK from EU
- Add CSV shipping numbers import in "postage in BO" mode
- Allow merchants to send return labels by mail to customers
- Allow merchants to ship from overseas departments
- Allow merchants to configure a return address different from the sender address
- Allow configuration of HS code + origin country + short description in a product and category level
- Add product codes for shipments inside overseas departments
- Allow merchants to print PDF documents without downloading them
- Allow merchants to download and print PDF documents in a single file
### Changed
- Update Front-Tracking page with a new Timeline
- Add ID column in dashboard, postage and deposit slip forms
- Add EORI number in CN23
- Move pickup point selection button below delivery option in PS 1.6
### Fixed
- Fix CSV MIME types
- Fix PHP compatibility
- Fix files management configuration save process
- Fix total weight and product weights for CN23
## [1.1.2] - 2019-09-04
### Fixed
- Fix mobile input on OPC mode
## [1.1.1] - 2019-08-28
### Fixed
- Fix Colissimo label table creation for fresh install
- Fix widget and mobile input init process on 1.6
## [1.1.0] - 2019-08-07
### Added
- Allow merchants to tie an order placed with a carrier different than Colissimo to the module
- Allow merchants to change the Colissimo service (home deliveries, pickup point) when creating a label
- Allow merchants to delete labels
- Allow merchants to select/unselect all shipments in one click when generating deposit slips
- Allow merchants to change the state of an order after creating labels
- Allow merchants to change the state of an order after creating deposit slips
- Add two CSS and JS empty files to be overridden
- Display insurance information for each shipments
### Changed
- New mobile input for Front Widget with prefix and country
- Update order shipping number after deleting labels
- Restrict the pickup point country to the customer's country
- Check if SOAP extension is loaded and display a warning in Deposit Slip page if it's not
### Fixed
- Improve compatibility of modal
- Fix display rules of carriers for Monaco & Andorra
- Replaced array_column with array_map for PHP < 5.5
- Remove Material icons for PS 1.7 themes compatibility reasons
- Fix escape of Widget addresses in PS 1.7
- Add missing id_customer in pickup point address
- Remove Content-Length header for compatibility reasons
- Fix translations in Admin Controllers
- Fix help texts in Colissimo Dashboard
- Fix return labels generation with "Franc de Taxe et de Douane" option
## [1.0.6] - 2019-06-06
### Changed
- Remove Content-Length header for ZPL/DPL label download
- Fix display of modal in BO
- Add check if zip PHP extension is enabled
- Prevent customers to validate an order without choosing a pickup point and providing a valid mobile number in OPC mode
### Fixed
- Fix compatibility of modal
- Fix conflict with autocomplete JS plugin
- Add phone number in pickup point address
- Add missing countDown JS function in few PS 1.6 versions
- Fix display of widget for tablets
- Anonymize password field of Colissimo account in BO
## [1.0.5] - 2019-04-09
### Added
- Add new field for EORI number in BO configuration
- Allow merchant to use local files or remote files for Widget
- Add PCS service (EU pickup-points)
- Add "What's new?" modal with latest changes
### Changed
- Replace "other" field with Colissimo Pickup Point ID in address
- Rename carriers name (fresh install only)
- Improve logs in hook newOrder
### Fixed
- Fix product code sent when Pickup Point shipment (handle aliases)
## [1.0.4] - 2019-02-04
### Added
- Improve error management and add more logs in Coliship
- Add CPassID value in Coliship export
- Add logs in case of failed return label download (Front-Office)
- Override of module's front templates is now possible
- Handle gr weight unit abbreviation
- Allow return shipment from Outre-Mer
- Allow "without signature" service for Outre-Mer destination
- Add more country available for pudo service
### Changed
- Update Colissimo webservices version to 2.0
- Handle 9-digits reference in FO tracking URL
- Add mobile phone format example when validating pickup-point
- Convert weight unit to grams in Coliship export
- Convert EOL character to CRLF in Coliship export
- Handle INet encoding in Coliship export
- Replace hard-coded country ISO
- Check HS Code format in module configuration (Back-Office tab)
- Hide cancelled orders in the Colissimo Deposit Slip interface
- Hide and prevent tracking update of orders older than 90 days in Colissimo Dashboard
### Fixed
- Fix mobile validation in PrestaShop 1.6.1.x + One-Page-Checkout mode
- Fix escape for address and city fields inside Front Widget
- Fix valid label formats
- Fix hook registration for carrier process
- Fix phone numbers fields in Coliship export
- Fix error in order history in PrestaShop 1.6.1.x
- Fix UX in module configuration (Back-Office tab)
- Fix Euro conversion
- Fix PHP error on version 5.3 & 5.4
- Fix SQL query cast
- Fix JS variable name
- Fix widget endpoint URL
- Fix Colissimo EU Zone 1 & 3 country list
- Fix menu creation for PrestaShop 1.7.0.x & 1.7.1.x
## [1.0.3] - 2018-12-21
### Changed
- Change documents storage & download process
### Fixed
- Fix file extension of CN23 when downloading
## [1.0.2] - 2018-12-13
### Fixed
- Fix BO field validation function
## [1.0.1] - 2018-12-12
### Added
- Pickup point ID is now displayed on order page after pickup point address inside Colissimo section
### Changed
- Remove check WS credentials
### Fixed
- Fix Front Widget compatibility with OPC
- Fix choice of carrier when customer is not logged in
- Fix URL after validating pickup point in the Front Widget
- Fix minor security issues
- Fix missing translation
- Add fields format checks in module configuration
- Fix missing JS variable
## [1.0.0] - 2018-10-12
### Added
- First stable version

View File

@@ -0,0 +1,23 @@
{
"sEmptyTable": "No data available in table",
"sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
"sInfoEmpty": "Showing 0 to 0 of 0 entries",
"sInfoFiltered": "(filtered from _MAX_ total entries)",
"sInfoPostFix": "",
"sInfoThousands": ",",
"sLengthMenu": "Show _MENU_ entries",
"sLoadingRecords": "Loading...",
"sProcessing": "Processing...",
"sSearch": "Search:",
"sZeroRecords": "No matching records found",
"oPaginate": {
"sFirst": "First",
"sLast": "Last",
"sNext": "Next",
"sPrevious": "Previous"
},
"oAria": {
"sSortAscending": ": activate to sort column ascending",
"sSortDescending": ": activate to sort column descending"
}
}

View File

@@ -0,0 +1,34 @@
{
"sEmptyTable": "Aucune donnée disponible dans le tableau",
"sInfo": "Affichage de l'élément _START_ à _END_ sur _TOTAL_ éléments",
"sInfoEmpty": "Affichage de l'élément 0 à 0 sur 0 élément",
"sInfoFiltered": "(filtré à partir de _MAX_ éléments au total)",
"sInfoPostFix": "",
"sInfoThousands": ",",
"sLengthMenu": "Afficher _MENU_ éléments",
"sLoadingRecords": "Chargement...",
"sProcessing": "Traitement...",
"sSearch": "Rechercher :",
"sZeroRecords": "Aucun élément correspondant trouvé",
"oPaginate": {
"sFirst": "Premier",
"sLast": "Dernier",
"sNext": "Suivant",
"sPrevious": "Précédent"
},
"oAria": {
"sSortAscending": ": activer pour trier la colonne par ordre croissant",
"sSortDescending": ": activer pour trier la colonne par ordre décroissant"
},
"select": {
"rows": {
"_": "%d lignes sélectionnées",
"0": "Aucune ligne sélectionnée",
"1": "1 ligne sélectionnée"
}
},
"buttons": {
"selectAll": "Tout sélectionner",
"selectNone": "Tout désélectionner"
}
}

View File

@@ -0,0 +1,59 @@
[GENERAL]
DELIMITE=O
SEPARATEUR=59
DELIMITEUR=34
FINDELIGNE=CRLF
Unité poids=G
CN23=O
EntetLigneColis=EXP
EntetLigneArticle=CN2
UnitePoidsARTICLE=G
[CHAMPS]
EntenteLigneColis=1
ReferenceExpedition=2
RaisonSocialeExpediteur=3
NomCommercialChargeur=4
PrenomExpediteur=5
Adresse1Expediteur=6
Adresse2Expediteur=7
Adresse3Expediteur=8
Adresse4Expediteur=9
CodePostalExpediteur=10
CommuneExpediteur=11
CodePaysExpediteur=12
MailExpediteur=13
TelephoneExpediteur=14
RaisonSociale=15
NomDestinataire=16
Prenom=17
Adresse1=18
Adresse2=19
Adresse3=20
Adresse4=21
CodePostal=22
Commune=23
CodePays=24
Portable=25
Telephone=26
Mail=27
CodePointRetrait=28
CodeProduit=29
FTD=30
LangueNotification=31
LivraisonAvecSignature=32
Poids=33
NatureEnvoi=34
MontantADV=35
NumCPASSID=36
TagUsers=37
[CN23]
EntetLigneArticle=1
CN23Imprimee=2
LibelleArticle=3
PoidsArticle=4
Quantite=5
ValeurArticle=6
PaysOrigine=7
Devise=8
ReferenceArticle=9
NumTarifaire=10

View File

@@ -0,0 +1,31 @@
# Colissimo Official App
:white_check_mark: Current stable version: v1.4.0
## Compatibility
The module is compatible with PrestaShop:
- 1.6.1
- 1.7+
## Requirements
### Technical requirements
- cURL
- SOAP
- zip (PHP extension)
### Colissimo contract requiremnts
Make sure your contract is eligible for the following services:
- Widget PUDO display
- Webservice 'affranchissement'
- Unitary Webservice for tracking
Please contact your representative sales if you have any doubt
## Install
1. Upload the zip file via the PrestaShop back-office
2. Click the "Install" button
3. Fill your account details in the configuration of the module
:warning: Please **do not** delete carriers associated with the module. If you don't want to display them, disable them instead.

View File

@@ -0,0 +1,148 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoACE
*/
class ColissimoACE extends ObjectModel
{
/** @var int $id_colissimo_ace */
public $id_colissimo_ace;
/** @var int $ref_order */
public $ref_order;
/** @var string $shipping_number */
public $shipping_number;
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_ace',
'primary' => 'id_colissimo_ace',
'fields' => array(
'ref_order' => array('type' => self::TYPE_INT, 'required' => false),
'shipping_number' => array('type' => self::TYPE_STRING, 'required' => false, 'size' => 64),
),
);
/**
* @var array $webserviceParameters
*/
protected $webserviceParameters = array(
'objectMethods' => array('add' => 'addWs'),
'objectNodeName' => 'colissimo_ace',
'fields' => array(
'id_order' => array(),
'shipping_number' => array(),
),
);
/**
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function addWs()
{
/** @var Colissimo $module */
$module = Module::getInstanceByName('colissimo');
$module->logger->setChannel('ACE');
if (ColissimoOrder::exists($this->ref_order)) {
$order = new Order((int) $this->ref_order);
$colissimoLabel = new ColissimoLabel();
$colissimoLabel->id_colissimo_order = (int) ColissimoOrder::getIdByOrderId($this->ref_order);
$colissimoLabel->id_colissimo_deposit_slip = 0;
$colissimoLabel->shipping_number = pSQL($this->shipping_number);
$colissimoLabel->label_format = 'pdf';
$colissimoLabel->return_label = 0;
$colissimoLabel->cn23 = 0;
$colissimoLabel->coliship = 1;
$colissimoLabel->migration = 0;
$colissimoLabel->insurance = null;
$colissimoLabel->file_deleted = 0;
$colissimoLabel->save(true);
$orderCarrier = ColissimoOrderCarrier::getByIdOrder($this->ref_order);
if (Validate::isLoadedObject($orderCarrier) && !$orderCarrier->tracking_number) {
$orderCarrier->tracking_number = pSQL($colissimoLabel->shipping_number);
$orderCarrier->save();
$hash = md5($order->reference.$order->secure_key);
$link = Context::getContext()->link->getModuleLink(
'colissimo',
'tracking',
array('order_reference' => $order->reference, 'hash' => $hash)
);
$isoLangOrder = Language::getIsoById($order->id_lang);
if (isset($this->module->PNAMailObject[$isoLangOrder])) {
$object = $module->PNAMailObject[$isoLangOrder];
} else {
$object = $module->PNAMailObject['en'];
}
ColissimoTools::sendHandlingShipmentMail(
$order,
sprintf($object, $order->reference),
$link
);
$module->logger->info('Send tracking mail for shipment '.$colissimoLabel->shipping_number);
}
if (Configuration::get('COLISSIMO_USE_SHIPPING_IN_PROGRESS')) {
$idShippingInProgressOS = Configuration::get('COLISSIMO_OS_SHIPPING_IN_PROGRESS');
$shippingInProgressOS = new OrderState((int) $idShippingInProgressOS);
if (Validate::isLoadedObject($shippingInProgressOS)) {
if (!$order->getHistory(Context::getContext()->language->id, (int) $idShippingInProgressOS)) {
$history = new OrderHistory();
$history->id_order = (int) $order->id;
$history->changeIdOrderState($idShippingInProgressOS, (int) $order->id);
try {
$history->add();
} catch (Exception $e) {
$module->logger->error(sprintf('Cannot change status of order #%d', $order->id));
}
}
} else {
$module->logger->error('Shipping in Progress order state is not valid');
}
}
$module->logger->info('Label imported successfully.');
return true;
}
return false;
}
/**
* @param bool $die
* @param bool $error_return
* @return bool|string
*/
public function validateFields($die = true, $error_return = false)
{
if (($id = ColissimoLabel::getLabelIdByShippingNumber($this->shipping_number)) !== 0) {
return sprintf('Colissimo label already exists (label ID #%d)', (int) $id);
}
return true;
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class DhlCarrier
*/
class ColissimoCarrier extends Carrier
{
/**
* @param array $zones
* @param bool|true $delete
* @return bool
*/
public function setZones($zones, $delete = true)
{
if ($delete) {
Db::getInstance()->delete('carrier_zone', 'id_carrier = '.(int) $this->id);
}
if (!is_array($zones) || !count($zones)) {
return true;
}
$return = true;
foreach ($zones as $zone) {
$this->addZone((int) $zone['id_zone']);
}
return $return;
}
/**
* @param array $groups
* @param bool|true $delete
* @return bool
* @throws PrestaShopDatabaseException
*/
public function setGroups($groups, $delete = true)
{
if ($delete) {
Db::getInstance()->delete('carrier_group', 'id_carrier = '.(int) $this->id);
}
if (!is_array($groups) || !count($groups)) {
return true;
}
$return = true;
foreach ($groups as $group) {
Db::getInstance()->insert(
'carrier_group',
array('id_carrier' => (int) $this->id, 'id_group' => (int) $group['id_group'])
);
}
return $return;
}
/**
* @return bool
*/
public function setRanges()
{
$rangeWeight = new RangeWeight();
$rangeWeight->id_carrier = (int) $this->id;
$rangeWeight->delimiter1 = 0;
$rangeWeight->delimiter2 = 99999;
return $rangeWeight->add();
}
/**
* @param string $logoPath
* @param int $idLang
*/
public function setLogo($logoPath, $idLang)
{
ColissimoTools::copyLogo($logoPath, _PS_SHIP_IMG_DIR_.(int) $this->id.'.jpg');
ColissimoTools::copyLogo($logoPath, _PS_TMP_IMG_DIR_.'carrier_mini_'.(int) $this->id.'_'.$idLang.'.png');
}
}

View File

@@ -0,0 +1,97 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoCartPickupPoint
*/
class ColissimoCartPickupPoint
{
/**
* @param int $idCart
* @return int
*/
public static function getByCartId($idCart)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_pickup_point')
->from('colissimo_cart_pickup_point')
->where('id_cart = '.(int) $idCart);
return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @param int $idCart
* @param int $idPickupPoint
* @param string $mobilePhone
* @throws PrestaShopDatabaseException
*/
public static function updateCartPickupPoint($idCart, $idPickupPoint, $mobilePhone)
{
Db::getInstance()
->insert(
'colissimo_cart_pickup_point',
array(
'id_cart' => (int) $idCart,
'id_colissimo_pickup_point' => (int) $idPickupPoint,
'mobile_phone' => pSQL($mobilePhone),
),
false,
false,
Db::REPLACE
);
}
/**
* @param int $idCart
* @param string $mobilePhone
*/
public static function updateMobilePhoneByCartId($idCart, $mobilePhone)
{
Db::getInstance()
->update(
'colissimo_cart_pickup_point',
array('mobile_phone' => pSQL($mobilePhone)),
'id_cart = '.(int) $idCart
);
}
/**
* @param int $idCart
* @return false|null|string
*/
public static function getMobilePhoneByCartId($idCart)
{
$dbQuery = new DbQuery();
$dbQuery->select('mobile_phone')
->from('colissimo_cart_pickup_point')
->where('id_cart = '.(int) $idCart);
return Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
}

View File

@@ -0,0 +1,84 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoCustomCategory
*/
class ColissimoCustomCategory extends ObjectModel
{
/** @var int $id_category */
public $id_category;
/** @var string $short_desc */
public $short_desc;
/** @var int $id_country_origin */
public $id_country_origin;
/** @var string $hs_code */
public $hs_code;
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_custom_category',
'primary' => 'id_colissimo_custom_category',
'fields' => array(
'id_category' => array('type' => self::TYPE_INT, 'required' => false),
'short_desc' => array('type' => self::TYPE_STRING, 'required' => false, 'size' => 64),
'id_country_origin' => array('type' => self::TYPE_INT, 'required' => false),
'hs_code' => array('type' => self::TYPE_STRING, 'required' => false, 'size' => 8),
),
);
/**
* @var array $webserviceParameters
*/
protected $webserviceParameters = array(
'objectsNodeName' => 'colissimo_custom_categories',
'fields' => array(
'id_category' => array('xlink_resource' => 'categories'),
'id_country_origin' => array('xlink_resource' => 'countries'),
),
);
/**
* @param int $idCategory
* @return ColissimoCustomCategory
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public static function getByIdCategory($idCategory)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_custom_category')
->from('colissimo_custom_category')
->where('id_category = '.(int) $idCategory);
$id = Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
return new self((int) $id);
}
}

View File

@@ -0,0 +1,83 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoCustomProduct
*/
class ColissimoCustomProduct extends ObjectModel
{
/** @var int $id_product */
public $id_product;
/** @var string $short_desc */
public $short_desc;
/** @var int $id_country_origin */
public $id_country_origin;
/** @var string $hs_code */
public $hs_code;
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_custom_product',
'primary' => 'id_colissimo_custom_product',
'fields' => array(
'id_product' => array('type' => self::TYPE_INT, 'required' => false),
'short_desc' => array('type' => self::TYPE_STRING, 'required' => false, 'size' => 64),
'id_country_origin' => array('type' => self::TYPE_INT, 'required' => false),
'hs_code' => array('type' => self::TYPE_STRING, 'required' => false, 'size' => 8),
),
);
/**
* @var array $webserviceParameters
*/
protected $webserviceParameters = array(
'fields' => array(
'id_product' => array('xlink_resource' => 'products'),
'id_country_origin' => array('xlink_resource' => 'countries'),
),
);
/**
* @param int $idProduct
* @return ColissimoCustomProduct
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public static function getByIdProduct($idProduct)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_custom_product')
->from('colissimo_custom_product')
->where('id_product = '.(int) $idProduct);
$id = Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
return new self((int) $id);
}
}

View File

@@ -0,0 +1,166 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoDepositSlip
*/
class ColissimoDepositSlip extends ObjectModel
{
/** @var int $id_colissimo_deposit_slip */
public $id_colissimo_deposit_slip;
/** @var string $filename */
public $filename;
/** @var int $number Deposit slip number */
public $number;
/** @var int $nb_parcel Number of parcels included in the deposit slip */
public $nb_parcel;
/** @var bool $file_deleted Flag to indicate if the file is deleted */
public $file_deleted;
/** @var string $date_add */
public $date_add;
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_deposit_slip',
'primary' => 'id_colissimo_deposit_slip',
'fields' => array(
'filename' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 45),
'number' => array('type' => self::TYPE_INT, 'required' => true, 'size' => 10),
'nb_parcel' => array('type' => self::TYPE_INT, 'required' => true, 'size' => 11),
'file_deleted' => array(
'type' => self::TYPE_BOOL,
'validate' => 'isBool',
'required' => true,
'default' => 0,
),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
),
);
/**
* @return bool
* @throws Exception
*/
public function download()
{
$file = $this->getFilePath();
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
exit;
} else {
return false;
}
}
/**
* @param string $content Base64 encoded string
* @return bool|int
* @throws Exception
*/
public function writeDepositSlip($content)
{
$depositSlipPath = $this->getFilePath(false);
return file_put_contents($depositSlipPath, $content);
}
/**
* @return bool
* @throws Exception
*/
public function deleteFile()
{
$depositSlipPath = $this->getFilePath();
if (file_exists($depositSlipPath)) {
return unlink($depositSlipPath);
}
return false;
}
/**
* @param bool $fileExistsCheck
* @return bool|string
* @throws Exception
*/
public function getFilePath($fileExistsCheck = true)
{
if (Tools::substr($this->filename, -4) !== '.pdf') {
throw new Exception('Deposit slip filename has an incorrect extension.');
}
$basename = Tools::substr($this->filename, 0, -4);
if (strpos($basename, '.') === false) {
if (!ctype_digit($basename)) {
throw new Exception('Deposit slip filename has an incorrect format.');
}
} elseif (!preg_match('/^[0-9]{8}\.[0-9]{14}$/', $basename)) {
throw new Exception('Deposit slip filename has an incorrect format.');
}
$safePath = realpath(_PS_MODULE_DIR_.'colissimo/documents/deposit_slip/');
if ($safePath === false) {
throw new Exception('Invalid pathname.');
}
if (!$fileExistsCheck) {
return $safePath.DIRECTORY_SEPARATOR.$this->filename;
}
$path = dirname(__FILE__).'/../documents/deposit_slip/'.$this->filename;
$realpath = realpath($path);
if ($realpath === false) {
throw new Exception('The path of deposit slip file is incorrect.');
}
if (Tools::substr($realpath, 0, Tools::strlen($safePath)) != $safePath) {
throw new Exception('Possible directory traversal attempt.');
}
return $realpath;
}
/**
* @return array
* @throws PrestaShopDatabaseException
*/
public function getLabelIds()
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_label')
->from('colissimo_label')
->where('id_colissimo_deposit_slip = '.(int) $this->id);
return (array) Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($dbQuery);
}
}

View File

@@ -0,0 +1,472 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoLabel
*/
class ColissimoLabel extends ObjectModel
{
const FRANCE_RETURN_PREFIX = '8R';
const INTER_RETURN_PREFIX = '7R';
/** @var int $id_colissimo_label */
public $id_colissimo_label;
/** @var int $id_colissimo_order */
public $id_colissimo_order;
/** @var int $id_colissimo_deposit_slip */
public $id_colissimo_deposit_slip;
/** @var string $shipping_number */
public $shipping_number;
/** @var string $label_format Format of the label (PDF/ZPL...) */
public $label_format;
/** @var int $return_label Flag to indicate if the label is a return label */
public $return_label;
/** @var bool $cn23 Flag to indicate if the label has a CN23 file associated */
public $cn23;
/** @var bool $coliship Flag to indicate if the label comes from Coliship */
public $coliship;
/** @var bool $migration Flag to indicate if the label has been migrated from other module */
public $migration;
/** @var int $insurance NULL = no indication, 0 = shipment not insured, 1 = shipment insured */
public $insurance;
/** @var bool $file_deleted Flag to indicate if the file is deleted */
public $file_deleted;
/** @var string $date_add */
public $date_add;
/** @var array $validFormats Valid file extensions for labels */
private $validFormats = array('pdf', 'dpl', 'zpl');
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_label',
'primary' => 'id_colissimo_label',
'fields' => array(
'id_colissimo_order' => array(
'type' => self::TYPE_INT,
'validate' => 'isNullOrUnsignedId',
'required' => true,
),
'id_colissimo_deposit_slip' => array(
'type' => self::TYPE_INT,
'validate' => 'isNullOrUnsignedId',
'required' => false,
),
'shipping_number' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 45),
'label_format' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 3),
'return_label' => array(
'type' => self::TYPE_INT,
'validate' => 'isNullOrUnsignedId',
'required' => true,
),
'cn23' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool', 'required' => true),
'coliship' => array(
'type' => self::TYPE_BOOL,
'validate' => 'isBool',
'required' => true,
'default' => 0,
),
'migration' => array(
'type' => self::TYPE_BOOL,
'validate' => 'isBool',
'required' => true,
'default' => 0,
),
'insurance' => array(
'type' => self::TYPE_NOTHING,
'validate' => 'isUnsignedId',
'required' => false,
'default' => null,
),
'file_deleted' => array(
'type' => self::TYPE_BOOL,
'validate' => 'isBool',
'required' => true,
'default' => 0,
),
'date_add' => array(
'type' => self::TYPE_DATE,
'validate' => 'isDate',
'copy_post' => false,
),
),
);
/**
* @return bool
* @throws Exception
*/
public function download()
{
$file = $this->getFilePath();
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
exit;
} else {
return false;
}
}
/**
* @return bool
* @throws Exception
*/
public function view()
{
$file = $this->getFilePath();
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: inline; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
exit;
} else {
return false;
}
}
/**
* @param string $content Base64 encoded string
* @return bool|int
* @throws Exception
*/
public function writeLabel($content)
{
$labelPath = $this->getFilePath(false);
return file_put_contents($labelPath, $content);
}
/**
* @return bool
* @throws Exception
*/
public function deleteFile()
{
$labelPath = $this->getFilePath();
if (file_exists($labelPath)) {
return unlink($labelPath);
}
return false;
}
/**
* @param bool $fileExistsCheck
* @return bool|string
* @throws Exception
*/
public function getFilePath($fileExistsCheck = true)
{
if ((!$this->return_label && !in_array($this->label_format, $this->validFormats)) ||
($this->return_label && $this->label_format != 'pdf') ||
!ctype_alnum($this->shipping_number)
) {
throw new Exception('Label filename has an incorrect extension or format.');
}
$safePath = realpath(_PS_MODULE_DIR_.'colissimo/documents/labels/');
$returnLabel = $this->return_label ? 'RET-' : '';
$fileExtension = $this->return_label ? 'pdf' : $this->label_format;
$filename = sprintf('%s%d-%s.%s', $returnLabel, (int) $this->id, $this->shipping_number, $fileExtension);
if ($safePath === false) {
throw new Exception('Invalid pathname.');
}
if (!$fileExistsCheck) {
return $safePath.DIRECTORY_SEPARATOR.$filename;
}
$path = dirname(__FILE__).'/../documents/labels/'.$filename;
$realpath = realpath($path);
if ($realpath === false) {
throw new Exception('The path of label file is incorrect. '.$path);
}
if (Tools::substr($realpath, 0, Tools::strlen($safePath)) != $safePath) {
throw new Exception('Possible directory traversal attempt.');
}
return $realpath;
}
/**
* @return bool
* @throws Exception
*/
public function downloadCN23()
{
$file = $this->getCN23Path();
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
exit;
} else {
return false;
}
}
/**
* @return bool
* @throws Exception
*/
public function viewCN23()
{
$file = $this->getCN23Path();
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: inline; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
exit;
} else {
return false;
}
}
/**
* @return bool
* @throws Exception
*/
public function deleteCN23()
{
$file = $this->getCN23Path();
if (file_exists($file)) {
return unlink($file);
} else {
return false;
}
}
/**
* @param string $content Base64 encoded string
* @return bool|int
* @throws Exception
*/
public function writeCN23File($content)
{
$cn23Path = $this->getCN23Path(false);
return file_put_contents($cn23Path, $content);
}
/**
* @param bool $fileExistsCheck
* @return string
* @throws Exception
*/
public function getCN23Path($fileExistsCheck = true)
{
if (!ctype_alnum($this->shipping_number)) {
throw new Exception('CN23 filename has an incorrect format.');
}
$safePath = realpath(_PS_MODULE_DIR_.'colissimo/documents/cn23/');
$filename = sprintf('%d-CN23-%s.pdf', (int) $this->id, $this->shipping_number);
if ($safePath === false) {
throw new Exception('Invalid pathname.');
}
if (!$fileExistsCheck) {
return $safePath.DIRECTORY_SEPARATOR.$filename;
}
$path = dirname(__FILE__).'/../documents/cn23/'.$filename;
$realpath = realpath($path);
if ($realpath === false) {
throw new Exception('The path of CN23 file is incorrect.');
}
if (Tools::substr($realpath, 0, Tools::strlen($safePath)) != $safePath) {
throw new Exception('Possible directory traversal attempt.');
}
return $realpath;
}
/**
* @return array|false|mysqli_result|null|PDOStatement|resource
* @throws PrestaShopDatabaseException
*/
public function getLastTrackingDetailsKnown()
{
$dbQuery = new DbQuery();
$dbQuery->select('*')
->from('colissimo_shipment_tracking')
->where('id_colissimo_label = '.(int) $this->id);
return Db::getInstance(_PS_USE_SQL_SLAVE_)
->getRow($dbQuery);
}
/**
* @param string $shippingNumber
* @return int
*/
public static function getLabelIdByShippingNumber($shippingNumber)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_label')
->from('colissimo_label')
->where('shipping_number = "'.pSQL($shippingNumber).'"');
return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @return bool
*/
public function hasMailboxPickup()
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_label')
->from('colissimo_mailbox_return')
->where('id_colissimo_label = '.(int) $this->id);
return (bool) Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @return array|bool|null|object
*/
public function getMailboxPickupDetails()
{
$dbQuery = new DbQuery();
$dbQuery->select('*')
->from('colissimo_mailbox_return')
->where('id_colissimo_label = '.(int) $this->id);
return Db::getInstance(_PS_USE_SQL_SLAVE_)
->getRow($dbQuery);
}
/**
* @return int
*/
public function getReturnLabelId()
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_label')
->from('colissimo_label')
->where('return_label = '.(int) $this->id);
return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* Determine if a label is downloadable. We cannot download label that are:
* - deleted physically on the server
* - created from Coliship
* - created from another Colissimo module and migrated
*
* @return bool
*/
public function isDownloadable()
{
if ($this->file_deleted) {
return false;
}
if ($this->coliship) {
return false;
}
if ($this->migration) {
return false;
}
return true;
}
/**
* Determine if a label is deletable. We cannot delete label that are:
* - linked to a deposit slip
*
* @return bool
*/
public function isDeletable()
{
if ($this->id_colissimo_deposit_slip) {
return false;
}
return true;
}
/**
* @return bool
*/
public function isFranceReturnLabel()
{
if (!$this->shipping_number) {
return false;
}
return (Tools::substr($this->shipping_number, 0, 2) == self::FRANCE_RETURN_PREFIX) ? true : false;
}
/**
* @return string
* @throws PrestaShopDatabaseException
*/
public function getNextShippingNumber()
{
$dbQuery = new DbQuery();
$dbQuery->select('shipping_number')
->from('colissimo_label')
->where('id_colissimo_order = '.(int) $this->id_colissimo_order)
->where('shipping_number != "'.pSQL($this->shipping_number).'"')
->where('return_label = 0');
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($dbQuery);
if (!$result) {
return '';
} else {
return $result[0]['shipping_number'];
}
}
}

View File

@@ -0,0 +1,594 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoLabelGenerator
*/
class ColissimoLabelGenerator
{
const CATEGORY_GIFT = 1;
const CATEGORY_SAMPLES = 2;
const CATEGORY_COMMERCIAL = 3;
const CATEGORY_DOC = 4;
const CATEGORY_OTHER = 5;
const CATEGORY_MERCHANDISE_RETURN = 6;
const COLISHIP_CATEGORY_GIFT = 2;
const COLISHIP_CATEGORY_SAMPLES = 0;
const COLISHIP_CATEGORY_COMMERCIAL = 4;
const COLISHIP_CATEGORY_DOC = 1;
const COLISHIP_CATEGORY_OTHER = 5;
const COLISHIP_CATEGORY_MERCHANDISE_RETURN = 3;
/** @var array $data */
private $data;
/** @var ColissimoLogger $logger */
private $logger;
/** @var ColissimoGenerateLabelRequest $request */
private $request;
/**
* ColissimoLabelGenerator constructor.
* @param ColissimoLogger $logger
*/
public function __construct($logger)
{
$this->logger = $logger;
$this->logger->setChannel('GenerateLabel');
}
/**
* @param array $data
*/
public function setData($data)
{
$this->data = $data;
}
/**
* @return array
* @throws Exception
*/
public function getProductsForCustomsDeclaration()
{
/** @var Order $order */
$order = $this->data['order'];
$currency = new Currency((int) $order->id_currency);
$products = $order->getProducts();
$originCountry = 'FR';
$hsCode = Configuration::get('COLISSIMO_DEFAULT_HS_CODE');
$articles = array();
foreach ($products as $product) {
$productCustomDetails = ColissimoCustomProduct::getByIdProduct((int) $product['product_id']);
$categoryCustomDetails = ColissimoCustomCategory::getByIdCategory((int) $product['id_category_default']);
$shortDescription = $product['product_name'];
if ($productCustomDetails->short_desc) {
$shortDescription = $productCustomDetails->short_desc;
} elseif ($categoryCustomDetails->short_desc) {
$shortDescription = $categoryCustomDetails->short_desc;
}
if ($productCustomDetails->hs_code) {
$hsCode = $productCustomDetails->hs_code;
} elseif ($categoryCustomDetails->hs_code) {
$hsCode = $categoryCustomDetails->hs_code;
}
if ($productCustomDetails->id_country_origin) {
$originCountry = Country::getIsoById((int) $productCustomDetails->id_country_origin);
} elseif ($categoryCustomDetails->id_country_origin) {
$originCountry = Country::getIsoById((int) $categoryCustomDetails->id_country_origin);
}
$weight = (float) $product['product_weight'] ? ColissimoTools::weightInKG($product['product_weight']) : 0.05;
$articles[] = array(
'description' => $shortDescription,
'quantity' => $product['product_quantity'],
'weight' => $weight,
'value' => (float) $product['unit_price_tax_excl'],
'hsCode' => $hsCode,
'originCountry' => $originCountry,
'currency' => $currency->iso_code,
'artref' => $product['product_reference'],
'originalIdent' => 'A',
);
}
return $articles;
}
/**
* @param bool $forcePdf
*/
public function setLabelOutput($forcePdf = false)
{
$output = array(
'x' => 0,
'y' => 0,
'outputPrintingType' => $forcePdf ? 'PDF_A4_300dpi' : Configuration::get('COLISSIMO_LABEL_FORMAT'),
);
$this->request->setOutput($output);
}
/**
* @throws Exception
*/
public function setLabelService()
{
$isoEUCountriesWithCN23 = ColissimoTools::$isoEUCountriesWithCN23;
$isoEUCountries = ColissimoTools::$isoEUCountries;
if (Configuration::get('COLISSIMO_ENABLE_BREXIT')) {
$isoEUCountries = array_diff($isoEUCountries, array('GB'));
}
/** @var Order $order */
$order = $this->data['order'];
/** @var ColissimoService $colissimoService */
$colissimoService = $this->data['colissimo_service'];
if ($colissimoService->type == ColissimoService::TYPE_RELAIS) {
$this->logger->info(sprintf(
'Order #%d (%s) - Shipping type: PICKUP POINT DELIVERY',
$this->data['order']->id,
$this->data['order']->reference
));
$pickupPoint = new ColissimoPickupPoint((int) $this->data['colissimo_order']->id_colissimo_pickup_point);
$services = array(
'productCode' => $pickupPoint->getProductCodeForAffranchissement(),
'depositDate' => date('Y-m-d'),
);
} else {
$this->logger->info(sprintf(
'Order #%d (%s) - Shipping type: HOME DELIVERY',
$this->data['order']->id,
$this->data['order']->reference
));
$services = array(
'productCode' => $colissimoService->product_code,
'depositDate' => date('Y-m-d'),
);
}
$shippingAmountEUR = ColissimoTools::convertInEUR(
$order->total_shipping_tax_excl,
new Currency($order->id_currency)
);
$shippingAmountEUR = (float) $shippingAmountEUR ? $shippingAmountEUR : 0.01;
$services['transportationAmount'] = (int) ($shippingAmountEUR * 100);
$merchantAddress = new ColissimoMerchantAddress('sender');
/** @var Address $customerAddress */
$customerAddress = $this->data['customer_addr'];
$isoTo = Country::getIsoById((int) $customerAddress->id_country);
$isoFrom = $merchantAddress->countryCode;
if (ColissimoTools::needCN23($isoFrom, $isoTo, $customerAddress->postcode)) {
$services['totalAmount'] = $services['transportationAmount'];
$services['returnTypeChoice'] = 3;
}
$services['orderNumber'] = $this->data['order']->reference;
if ($colissimoService->type == ColissimoService::TYPE_RELAIS) {
$services['commercialName'] = $merchantAddress->companyName;
}
$this->request->setShipmentServices($services);
}
/**
*
*/
public function setLabelCustomsDeclarations()
{
$merchantAddress = new ColissimoMerchantAddress('sender');
/** @var Address $customerAddress */
$customerAddress = $this->data['customer_addr'];
$isoTo = Country::getIsoById((int) $customerAddress->id_country);
$isoFrom = $merchantAddress->countryCode;
if (ColissimoTools::needCN23($isoFrom, $isoTo, $customerAddress->postcode)) {
$customsDeclaration = array(
'includeCustomsDeclarations' => 1,
'contents' => array(
'article' => $this->getProductsForCustomsDeclaration(),
'category' => array(
'value' => self::CATEGORY_COMMERCIAL,
),
),
);
$this->logger->info(
sprintf(
'Order #%d (%s) - Include customs declarations',
$this->data['order']->id,
$this->data['order']->reference
),
array('data', $customsDeclaration)
);
$this->request->setCustomsOptions($customsDeclaration);
}
}
/**
* @param ColissimoLabel $colissimoLabel
* @throws Exception
*/
public function setReturnLabelCustomsDeclarations($colissimoLabel)
{
$merchantAddress = new ColissimoMerchantAddress('sender');
/** @var Address $customerAddress */
$customerAddress = $this->data['customer_addr'];
$isoTo = Country::getIsoById((int) $customerAddress->id_country);
$isoFrom = $merchantAddress->countryCode;
if (ColissimoTools::needCN23($isoFrom, $isoTo, $customerAddress->postcode)) {
if (Tools::substr($this->data['order']->invoice_date, 0, 10) != '0000-00-00') {
$invoiceDate = Tools::substr($this->data['order']->invoice_date, 0, 10);
} else {
$invoiceDate = date('Y-m-d');
}
$customsDeclaration = array(
'includeCustomsDeclarations' => 1,
'contents' => array(
'article' => $this->getProductsForCustomsDeclaration(),
'category' => array(
'value' => self::CATEGORY_MERCHANDISE_RETURN,
),
'original' => array(
array(
'originalIdent' => 'A',
'originalInvoiceNumber' => 'IN'.$this->data['order']->invoice_number,
'originalInvoiceDate' => $invoiceDate,
'originalParcelNumber' => $colissimoLabel->shipping_number,
),
),
),
);
$this->logger->info(
sprintf(
'Order #%d (%s) - Include customs declarations',
$this->data['order']->id,
$this->data['order']->reference
),
array('data', $customsDeclaration)
);
$this->request->setCustomsOptions($customsDeclaration);
}
}
/**
*
*/
public function setLabelAddresses()
{
/** @var ColissimoService $colissimoService */
$colissimoService = $this->data['colissimo_service'];
/** @var ColissimoMerchantAddress $senderAddrObj */
$senderAddrObj = $this->data['merchant_addr'];
$senderAddr = array(
'senderParcelRef' => $this->data['order']->reference,
'address' => array(
'companyName' => $senderAddrObj->companyName,
'lastName' => $senderAddrObj->lastName,
'firstName' => $senderAddrObj->lastName,
'line0' => $senderAddrObj->line0,
'line1' => $senderAddrObj->line1,
'line2' => $senderAddrObj->line2,
'line3' => $senderAddrObj->line3,
'countryCode' => $senderAddrObj->countryCode,
'city' => $senderAddrObj->city,
'zipCode' => $senderAddrObj->zipCode,
'phoneNumber' => $senderAddrObj->phoneNumber,
'email' => $senderAddrObj->email,
),
);
$this->request->setSenderAddress($senderAddr);
/** @var Address $customerAddrDb */
if ($colissimoService->type == ColissimoService::TYPE_RELAIS) {
$customerAddrDb = $this->data['customer_addr_inv'];
} else {
$customerAddrDb = $this->data['customer_addr'];
}
$customerAddr = array(
'addresseeParcelRef' => $this->data['order']->reference,
'codeBarForReference' => true,
'address' => array(
'companyName' => $customerAddrDb->company,
'lastName' => $customerAddrDb->lastname,
'firstName' => $customerAddrDb->firstname,
'line2' => $customerAddrDb->address1,
'line3' => $customerAddrDb->address2,
'countryCode' => Country::getIsoById($customerAddrDb->id_country),
'city' => $customerAddrDb->city,
'zipCode' => $customerAddrDb->postcode,
'phoneNumber' => $customerAddrDb->phone,
),
);
if ($colissimoService->type == ColissimoService::TYPE_RELAIS) {
$customerAddr['address']['mobileNumber'] = $this->data['form_options']['mobile_phone'];
} else {
$customerAddr['address']['mobileNumber'] = $customerAddrDb->phone_mobile;
}
$customerAddr['address']['email'] = $this->data['customer']->email;
$this->request->setAddresseeAddress($customerAddr);
}
/**
*
*/
public function setReturnLabelAddresses()
{
/** @var ColissimoMerchantAddress $merchantAddrObj */
$merchantAddrObj = $this->data['merchant_addr'];
if ($this->data['colissimo_service_initial']->type == ColissimoService::TYPE_RELAIS) {
/** @var Address $customerAddrDb */
$customerAddrDb = new Address((int) $this->data['order']->id_address_invoice);
$mobilePhone = $this->data['form_options']['mobile_phone'];
} else {
/** @var Address $customerAddrDb */
$customerAddrDb = $this->data['customer_addr'];
$mobilePhone = $customerAddrDb->phone_mobile;
}
$customerAddr = array(
'senderParcelRef' => $this->data['order']->reference,
'address' => array(
'companyName' => $customerAddrDb->company,
'lastName' => $customerAddrDb->lastname,
'firstName' => $customerAddrDb->firstname,
'line2' => $customerAddrDb->address1,
'line3' => $customerAddrDb->address2,
'countryCode' => Country::getIsoById($customerAddrDb->id_country),
'city' => $customerAddrDb->city,
'zipCode' => $customerAddrDb->postcode,
'mobileNumber' => $mobilePhone,
'email' => $this->data['customer']->email,
),
);
$this->request->setSenderAddress($customerAddr);
$merchantAddr = array(
'addresseeParcelRef' => $this->data['order']->reference,
'codeBarForReference' => true,
'address' => array(
'companyName' => $merchantAddrObj->companyName,
'lastName' => $merchantAddrObj->lastName,
'firstName' => $merchantAddrObj->firstName,
'line0' => $merchantAddrObj->line0,
'line1' => $merchantAddrObj->line1,
'line2' => $merchantAddrObj->line2,
'line3' => $merchantAddrObj->line3,
'countryCode' => $merchantAddrObj->countryCode,
'city' => $merchantAddrObj->city,
'zipCode' => $merchantAddrObj->zipCode,
'phoneNumber' => $merchantAddrObj->phoneNumber,
'email' => $merchantAddrObj->email,
),
);
$this->request->setAddresseeAddress($merchantAddr);
}
/**
* @throws Exception
*/
public function setLabelOptions()
{
/** @var ColissimoService $colissimoService */
$colissimoService = $this->data['colissimo_service'];
$labelOptions = array();
//@formatter:off
if ($this->data['form_options']['insurance']) {
/** @var Order $order */
$order = $this->data['order'];
$insuredAmount = $order->total_products;
$insuredAmountEUR = ColissimoTools::convertInEUR($insuredAmount, new Currency($order->id_currency));
$labelOptions['insuranceValue'] = $insuredAmountEUR * 100;
$this->logger->info(sprintf(
'Order #%d (%s) - Shipment insurance : %s EUR',
$this->data['order']->id,
$this->data['order']->reference,
$insuredAmountEUR
));
}
//@formatter:on
$labelOptions['weight'] = $this->data['form_options']['weight'];
if ($this->data['form_options']['d150']) {
if ($colissimoService->isMachinableOptionAvailable()) {
$labelOptions['nonMachinable'] = 1;
$this->logger->info(sprintf(
'Order #%d (%s) - Shipment non machinable',
$this->data['order']->id,
$this->data['order']->reference
));
}
}
if ($colissimoService->type == ColissimoService::TYPE_RELAIS) {
$pickupPoint = new ColissimoPickupPoint((int) $this->data['colissimo_order']->id_colissimo_pickup_point);
$labelOptions['pickupLocationId'] = $pickupPoint->colissimo_id;
$this->logger->info(sprintf(
'Order #%d (%s) - Pickup point ID #%s',
$this->data['order']->id,
$this->data['order']->reference,
$pickupPoint->colissimo_id
));
}
if ($this->data['form_options']['ta']) {
$labelOptions['ftd'] = 1;
$this->logger->info(sprintf(
'Order #%d (%s) - Shipment free of taxes and fees',
$this->data['order']->id,
$this->data['order']->reference
));
}
$this->request->setShipmentOptions($labelOptions);
}
/**
* @throws Exception
*/
public function setReturnLabelOptions()
{
/** @var ColissimoService $colissimoService */
$colissimoService = $this->data['colissimo_service'];
$labelOptions = array();
//@formatter:off
if ($this->data['form_options']['insurance']) {
/** @var Order $order */
$order = $this->data['order'];
$insuredAmount = $order->total_products;
$insuredAmountEUR = ColissimoTools::convertInEUR($insuredAmount, new Currency($order->id_currency));
$labelOptions['insuranceValue'] = $insuredAmountEUR * 100;
$this->logger->info(sprintf(
'Order #%d (%s) - Return shipment insurance : %s EUR',
$this->data['order']->id,
$this->data['order']->reference,
$insuredAmountEUR
));
}
//@formatter:on
$labelOptions['weight'] = $this->data['form_options']['weight'];
if ($this->data['form_options']['d150']) {
if ($colissimoService->isMachinableOptionAvailable()) {
$labelOptions['nonMachinable'] = 1;
$this->logger->info(sprintf(
'Order #%d (%s) - Shipment non machinable',
$this->data['order']->id,
$this->data['order']->reference
));
}
}
if ($colissimoService->type == ColissimoService::TYPE_RELAIS) {
$pickupPoint = new ColissimoPickupPoint((int) $this->data['colissimo_order']->id_colissimo_pickup_point);
$labelOptions['pickupLocationId'] = $pickupPoint->colissimo_id;
}
$labelOptions['ftd'] = 0;
$this->request->setShipmentOptions($labelOptions);
}
/**
*
*/
public function setCustomFields()
{
$infoText = array(
'key' => 'CUSER_INFO_TEXT',
'value' => sprintf('PS%s;%s', _PS_VERSION_, $this->data['version']),
);
$infoEori = array(
'key' => 'EORI',
'value' => Configuration::get('COLISSIMO_EORI_NUMBER'),
);
$fields = array($infoText, $infoEori);
$this->request->addCustomField($fields);
}
/**
* @param bool|int $returnLabel
* @return ColissimoLabel
* @throws Exception
* @throws PrestaShopException
*/
private function generateLabel($returnLabel = false)
{
$this->request->buildRequest();
$client = new ColissimoClient();
$client->setRequest($this->request);
/** @var ColissimoGenerateLabelResponse $response */
$response = $client->request();
$this->logger->info(
sprintf('Order #%d (%s) - Response', $this->data['order']->id, $this->data['order']->reference),
array('response' => $response->response)
);
if (!$response->messages[0]['id']) {
$label = new ColissimoLabel();
$label->id_colissimo_order = (int) $this->data['colissimo_order']->id;
$label->id_colissimo_deposit_slip = 0;
$extension = (int) $returnLabel ? 'pdf' : Tools::substr(Configuration::get('COLISSIMO_LABEL_FORMAT'), 0, 3);
$label->label_format = pSQL(Tools::strtolower($extension));
$label->return_label = (int) $returnLabel;
$label->cn23 = $response->cn23 ? 1 : 0;
$label->shipping_number = pSQL($response->parcelNumber);
$label->coliship = 0;
$label->migration = 0;
$label->insurance = $this->data['form_options']['insurance'] ? '1' : '0';
$label->file_deleted = 0;
$label->save();
$label->writeLabel(base64_decode($response->label));
if (null !== $response->cn23) {
$label->writeCN23File(base64_decode($response->cn23));
$this->logger->info(sprintf(
'Order #%d (%s) - CN23 generated',
$this->data['order']->id,
$this->data['order']->reference
));
}
return $label;
} else {
$message = $response->messages[0];
$this->logger->error(
'Exception thrown: '.$message['messageContent'],
array('details' => $response->messages)
);
throw new Exception(sprintf('%s (%s) - %s', $message['id'], $message['type'], $message['messageContent']));
}
}
/**
* @param ColissimoLabel $colissimoLabel
* @return ColissimoLabel
* @throws Exception
* @throws PrestaShopException
*/
public function generateReturn($colissimoLabel)
{
$this->logger->info(
sprintf('Order #%d (%s) - Generate return label', $this->data['order']->id, $this->data['order']->reference)
);
$this->request = new ColissimoGenerateLabelRequest(
ColissimoTools::getCredentials($this->data['order']->id_shop)
);
$this->setLabelOutput(true);
$this->setLabelService();
$this->setReturnLabelCustomsDeclarations($colissimoLabel);
$this->setReturnLabelAddresses();
$this->setReturnLabelOptions();
$this->setCustomFields();
return $this->generateLabel($colissimoLabel->id);
}
/**
* @return ColissimoLabel
* @throws Exception
* @throws PrestaShopException
*/
public function generate()
{
$this->logger->info(
sprintf('Order #%d (%s) - Generate label', $this->data['order']->id, $this->data['order']->reference)
);
$this->request = new ColissimoGenerateLabelRequest(
ColissimoTools::getCredentials($this->data['order']->id_shop)
);
$this->setLabelOutput();
$this->setLabelService();
$this->setLabelCustomsDeclarations();
$this->setLabelAddresses();
$this->setLabelOptions();
$this->setCustomFields();
return $this->generateLabel();
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoLink
*/
class ColissimoLink extends Link
{
/**
* getBaseLink() is public only since 1.6.1.15 (protected before)
* This method allows us to call it from outside of Link
*
* @param null $id_shop
* @param null $ssl
* @param bool $relative_protocol
* @return string
*/
public function getBaseLink($id_shop = null, $ssl = null, $relative_protocol = false)
{
return parent::getBaseLink($id_shop, $ssl, $relative_protocol);
}
}

View File

@@ -0,0 +1,155 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoMerchantAddress
*/
class ColissimoMerchantAddress
{
/** @var array $types */
private static $types = array('sender', 'return');
/** @var string $type */
public $type;
/** @var string $companyName */
public $companyName;
/** @var string $lastName */
public $lastName;
/** @var string $firstName */
public $firstName;
/** @var string $line0 */
public $line0;
/** @var string $line1 */
public $line1;
/** @var string $line2 */
public $line2;
/** @var string $line3 */
public $line3;
/** @var string $countryCode */
public $countryCode;
/** @var string $city */
public $city;
/** @var string $zipCode */
public $zipCode;
/** @var string $phoneNumber */
public $phoneNumber;
/** @var string $email */
public $email;
/**
* ColissimoMerchantAddress constructor.
* @param string $type
* @param array $addressArray
*/
public function __construct($type = 'sender', $addressArray = array())
{
if (!in_array($type, self::$types)) {
$this->type = 'sender';
} else {
$this->type = $type;
}
if (!$addressArray) {
$addressString = Configuration::get('COLISSIMO_'.Tools::strtoupper($this->type).'_ADDRESS');
$addressArray = (array) json_decode($addressString, true);
}
$this->hydrate($addressArray);
}
/**
* @param array $array
*/
private function hydrate($array)
{
$this->companyName = isset($array[$this->type.'_company']) ? $array[$this->type.'_company'] : null;
$this->lastName = isset($array[$this->type.'_lastname']) ? $array[$this->type.'_lastname'] : null;
$this->firstName = isset($array[$this->type.'_firstname']) ? $array[$this->type.'_firstname'] : null;
$this->line0 = isset($array[$this->type.'_address3']) ? $array[$this->type.'_address3'] : null;
$this->line1 = isset($array[$this->type.'_address4']) ? $array[$this->type.'_address4'] : null;
$this->line2 = isset($array[$this->type.'_address1']) ? $array[$this->type.'_address1'] : null;
$this->line3 = isset($array[$this->type.'_address2']) ? $array[$this->type.'_address2'] : null;
$this->countryCode = isset($array[$this->type.'_country']) ? $array[$this->type.'_country'] : null;
$this->city = isset($array[$this->type.'_city']) ? $array[$this->type.'_city'] : null;
$this->zipCode = isset($array[$this->type.'_zipcode']) ? $array[$this->type.'_zipcode'] : null;
$this->phoneNumber = isset($array[$this->type.'_phone']) ? $array[$this->type.'_phone'] : null;
$this->email = isset($array[$this->type.'_email']) ? $array[$this->type.'_email'] : null;
}
/**
* @return ColissimoMerchantAddress
*/
public static function getMerchantReturnAddress()
{
$useReturnAddress = Configuration::get('COLISSIMO_USE_RETURN_ADDRESS');
if ($useReturnAddress) {
return new self('return');
} else {
return new self('sender');
}
}
/**
* @return array
*/
public function toArray()
{
return array(
$this->type.'_company' => $this->companyName,
$this->type.'_lastname' => $this->lastName,
$this->type.'_firstname' => $this->firstName,
$this->type.'_address1' => $this->line2,
$this->type.'_address2' => $this->line3,
$this->type.'_address3' => $this->line0,
$this->type.'_address4' => $this->line1,
$this->type.'_country' => $this->countryCode,
$this->type.'_city' => $this->city,
$this->type.'_zipcode' => $this->zipCode,
$this->type.'_phone' => $this->phoneNumber,
$this->type.'_email' => $this->email,
);
}
/**
* @return false|string
*/
public function toJSON()
{
$array = (array) $this->toArray();
return json_encode($array);
}
}

View File

@@ -0,0 +1,300 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoModuleConfiguration
*/
class ColissimoModuleConfiguration
{
/** @var Context $context */
private $context;
/** @var string $localPath */
private $localPath;
/** @var string $pathUri */
private $pathUri;
/** @var string $version */
private $version;
/** @var array $migrateModuleFromList */
private $migrateModuleFromList = array(
'colissimo_simplicite',
'socolissimo',
'sonice_etiquetage',
'soflexibilite',
);
/** @var array $modulesToMigrate */
public $modulesToMigrate = array();
/** @var array $senderAddressFields */
public $senderAddressFields = array(
'sender_company',
'sender_lastname',
'sender_firstname',
'sender_address1',
'sender_address2',
'sender_address3',
'sender_address4',
'sender_city',
'sender_zipcode',
'sender_country',
'sender_phone',
'sender_email',
);
/** @var array $returnAddressFields */
public $returnAddressFields = array(
'return_company',
'return_lastname',
'return_firstname',
'return_address1',
'return_address2',
'return_address3',
'return_address4',
'return_city',
'return_zipcode',
'return_country',
'return_phone',
'return_email',
);
/** @var array $accountFields */
public $accountFields = array(
'COLISSIMO_LOGS',
'COLISSIMO_ACCOUNT_LOGIN',
'COLISSIMO_ACCOUNT_PASSWORD',
);
/** @var array $widgetFields */
public $widgetFields = array(
'COLISSIMO_WIDGET_REMOTE',
'COLISSIMO_WIDGET_ENDPOINT',
'COLISSIMO_WIDGET_COLOR_1',
'COLISSIMO_WIDGET_COLOR_2',
'COLISSIMO_WIDGET_FONT',
);
/** @var array $backFields */
public $backFields = array(
'COLISSIMO_ORDER_PREPARATION_TIME',
'COLISSIMO_USE_SHIPPING_IN_PROGRESS',
'COLISSIMO_USE_HANDLED_BY_CARRIER',
'COLISSIMO_ENABLE_PNA_MAIL',
'COLISSIMO_GENERATE_LABEL_PRESTASHOP',
'COLISSIMO_POSTAGE_MODE_MANUAL',
'COLISSIMO_USE_THERMAL_PRINTER',
'COLISSIMO_USE_ETHERNET',
'COLISSIMO_USB_PROTOCOLE',
'COLISSIMO_PRINTER_IP_ADDR',
'COLISSIMO_LABEL_FORMAT',
'COLISSIMO_DEFAULT_HS_CODE',
'COLISSIMO_EORI_NUMBER',
'COLISSIMO_ENABLE_BREXIT',
'COLISSIMO_USE_RETURN_ADDRESS',
);
/** @var array $defaultShipmentsFields */
public $defaultShipmentsFields = array(
'COLISSIMO_INSURE_SHIPMENTS',
'COLISSIMO_ENABLE_RETURN',
'COLISSIMO_AUTO_PRINT_RETURN_LABEL',
'COLISSIMO_DISPLAY_RETURN_LABEL_CUSTOMER',
'COLISSIMO_GENERATE_RETURN_LABEL_CUSTOMER',
'COLISSIMO_ENABLE_MAILBOX_RETURN',
);
/** @var array $defaultShipmentsFields */
public $filesFields = array(
'COLISSIMO_FILES_LIMIT',
'COLISSIMO_FILES_LIFETIME',
);
/** @var array $widgetFonts */
public static $widgetFonts = array(
'Arial',
'Arial Black',
'Comic Sans MS',
'Courrier New',
'Georgia',
'Impact',
'Lucida Console',
'Lucida Sans Unicode',
'Tahoma',
'Times New Roman',
'Trebuchet MS',
'Verdana',
'MS Sans Serif',
'MS Serif',
);
/** @var array $labelFormats */
public $labelFormats = array(
'PDF_A4_300dpi' => 'PDF A4 300dpi',
'PDF_10x15_300dpi' => 'PDF 10x15 300dpi',
'ZPL_10x15_203dpi' => 'ZPL 10x15 203dpi',
'ZPL_10x15_300dpi' => 'ZPL 10x15 300dpi',
'DPL_10x15_203dpi' => 'DPL 10x15 203dpi',
'DPL_10x15_300dpi' => 'DPL 10x15 300dpi',
);
/**
* @var array $usbPrinterProtocoles
*/
public $usbPrinterProtocoles = array(
'DATAMAX' => 'DATAMAX',
'INTERMEC' => 'INTERMEC',
'ZEBRA' => 'ZEBRA',
);
/** @var array $colissimoLinks */
public $colissimoLinks = array(
'en' => array(
'delivery_details' => 'https://www.colissimo.entreprise.laposte.fr/en/possibilites',
'subscribe' => 'https://www.colissimo.entreprise.laposte.fr/en/souscrire',
),
'fr' => array(
'delivery_details' => 'https://www.colissimo.entreprise.laposte.fr/fr/possibilites',
'subscribe' => 'https://www.colissimo.entreprise.laposte.fr/fr/souscrire',
),
);
/**
* ColissimoModuleConfiguration constructor.
* @param Context $context
* @param string $localPath
* @param string $pathUri
* @param string $version
*/
public function __construct(Context $context, $localPath, $pathUri, $version = '')
{
$this->context = $context;
$this->localPath = $localPath;
$this->pathUri = $pathUri;
$this->version = $version;
}
/**
* @throws Exception
* @throws SmartyException
*/
public function getContent()
{
$this->context->controller->addJS($this->localPath.'views/js/intlTelInput.min.js');
$this->context->controller->addCSS($this->localPath.'views/css/intlTelInput.css');
$this->context->smarty->assign('link', $this->context->link);
$merchantSenderAddress = new ColissimoMerchantAddress('sender');
$senderAddress = array_merge(
array_fill_keys($this->senderAddressFields, ''),
$merchantSenderAddress->toArray()
);
$merchantReturnAddress = new ColissimoMerchantAddress('return');
$returnAddress = array_merge(
array_fill_keys($this->returnAddressFields, ''),
$merchantReturnAddress->toArray()
);
$orderStatuses = OrderState::getOrderStates($this->context->language->id);
$states = array();
foreach ($orderStatuses as $orderStatus) {
$states[(int) $orderStatus['id_order_state']] = $orderStatus['name'];
}
$accountFieldsValue = Configuration::getMultiple($this->accountFields);
$accountFieldsValue['COLISSIMO_ACCOUNT_TYPE'] = json_decode(Configuration::get('COLISSIMO_ACCOUNT_TYPE'), true);
$widgetFieldsValue = Configuration::getMultiple($this->widgetFields);
$backFieldsValue = Configuration::getMultiple($this->backFields);
$backFieldsValue['COLISSIMO_GENERATE_LABEL_STATUSES'] = json_decode(
Configuration::get('COLISSIMO_GENERATE_LABEL_STATUSES'),
true
);
$defaultShipmentsFieldsValue = Configuration::getMultiple($this->defaultShipmentsFields);
$filesFieldsValue = ColissimoTools::getMultipleGlobal($this->filesFields);
$formData = array_merge(
$senderAddress,
$returnAddress,
$accountFieldsValue,
$widgetFieldsValue,
$backFieldsValue,
$defaultShipmentsFieldsValue,
$filesFieldsValue
);
$isoLang = Language::getIsoById($this->context->language->id);
//@formatter:off
$colissimoLinks = isset($this->colissimoLinks[$isoLang]) ? $this->colissimoLinks[$isoLang] : $this->colissimoLinks['en'];
//@formatter:on
$showMigration = $this->mustShowMigration();
if ($showMigration) {
$this->context->controller->addJS($this->localPath.'views/js/colissimo.migration.js');
if (Shop::getContext() != Shop::CONTEXT_ALL) {
Shop::setContext(Shop::CONTEXT_ALL);
}
}
$documentsDirData = ColissimoTools::getDocumentsDirDetails(dirname(__FILE__).'/../documents/');
$formData['documents_dir_size'] = ColissimoTools::formatDirectorySize($documentsDirData['total_size']);
$formData['documents_dir_count'] = $documentsDirData['count'];
$countriesList = array();
$isoSender = array_merge(ColissimoTools::$isoSender, ColissimoTools::$isoOutreMer);
foreach ($isoSender as $iso) {
$countriesList[$iso] = Country::getNameById($this->context->language->id, Country::getByIso($iso));
}
$this->context->smarty->assign(
array(
'form_data' => $formData,
'address_countries' => $countriesList,
'widget_fonts' => self::$widgetFonts,
'label_formats' => $this->labelFormats,
'usb_protocoles' => $this->usbPrinterProtocoles,
'order_states' => $states,
'colissimo_img_path' => $this->pathUri.'views/img/',
'colissimo_links' => $colissimoLinks,
'show_migration' => $showMigration,
'modules_to_migrate' => array_reverse($this->modulesToMigrate),
'module_version' => $this->version,
)
);
$tpl = $this->context->smarty->fetch($this->localPath.'views/templates/admin/configuration/layout.config.tpl');
return $tpl;
}
/**
* @return bool
*/
public function mustShowMigration()
{
if ((int) Configuration::getGlobalValue('COLISSIMO_SHOW_MIGRATION') === -1) {
return false;
}
foreach ($this->migrateModuleFromList as $module) {
if (Module::isInstalled($module) && Module::isEnabled($module)) {
$this->modulesToMigrate[] = $module;
}
}
return !empty($this->modulesToMigrate);
}
}

View File

@@ -0,0 +1,262 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoOrder
*/
class ColissimoOrder extends ObjectModel
{
/** @var int $id_colissimo_order */
public $id_colissimo_order;
/** @var int $id_order */
public $id_order;
/** @var int $id_colissimo_service */
public $id_colissimo_service;
/** @var int $id_colissimo_pickup_point */
public $id_colissimo_pickup_point;
/** @var bool $migration Flag to indicate if the label has been migrated from other module */
public $migration;
/** @var bool $hidden */
public $hidden;
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_order',
'primary' => 'id_colissimo_order',
'fields' => array(
'id_order' => array(
'type' => self::TYPE_INT,
'validate' => 'isNullOrUnsignedId',
'required' => true,
),
'id_colissimo_service' => array(
'type' => self::TYPE_INT,
'validate' => 'isNullOrUnsignedId',
'required' => false,
'default' => 0,
),
'id_colissimo_pickup_point' => array(
'type' => self::TYPE_INT,
'validate' => 'isNullOrUnsignedId',
'required' => false,
'default' => 0,
),
'migration' => array(
'type' => self::TYPE_BOOL,
'validate' => 'isBool',
'required' => true,
'default' => 0,
),
'hidden' => array(
'type' => self::TYPE_BOOL,
'validate' => 'isBool',
'required' => true,
'default' => 0,
),
),
);
/**
* @param int $idLang
* @return array|bool
* @throws PrestaShopDatabaseException
*/
public function getShipments($idLang)
{
return self::getShipmentsByColissimoOrderId($this->id, $idLang);
}
/**
* @param int $idColissimoOrder
* @param int $idLang
* @return array
* @throws PrestaShopDatabaseException
*/
public static function getShipmentsByColissimoOrderId($idColissimoOrder, $idLang)
{
$shipments = array();
$colissimoOrder = new self((int) $idColissimoOrder);
$labelIds = $colissimoOrder->getLabelIds(true);
if (!$labelIds) {
return array();
}
foreach ($labelIds as $labelId) {
$label = new ColissimoLabel((int) $labelId);
$tracking = $label->getLastTrackingDetailsKnown();
if (!$label->return_label) {
$shipments[$label->id]['id_label'] = $label->id;
$shipments[$label->id]['shipping_number'] = $label->shipping_number;
$shipments[$label->id]['cn23'] = $label->cn23;
$shipments[$label->id]['id_deposit_slip'] = $label->id_colissimo_deposit_slip;
$shipments[$label->id]['status_text'] = $tracking['status_text'];
$shipments[$label->id]['status_upd'] = $tracking['date_upd'];
$shipments[$label->id]['coliship'] = $label->coliship;
$shipments[$label->id]['insurance'] = $label->insurance;
$shipments[$label->id]['migration'] = $label->migration;
$shipments[$label->id]['file_deleted'] = $label->file_deleted;
try {
$base64 = base64_encode(Tools::file_get_contents($label->getFilePath()));
$shipments[$label->id]['base64'] = $base64;
} catch (Exception $e) {
$shipments[$label->id]['base64'] = '';
}
try {
$base64 = $label->cn23 ? base64_encode(Tools::file_get_contents($label->getCN23Path())) : '';
$shipments[$label->id]['cn23_base64'] = $base64;
} catch (Exception $e) {
$shipments[$label->id]['cn23_base64'] = '';
}
$colissimoService = new ColissimoService((int) $colissimoOrder->id_colissimo_service);
$order = new Order((int) $colissimoOrder->id_order);
if ($colissimoService->is_pickup) {
$deliveryAddr = new Address((int) $order->id_address_invoice);
} else {
$deliveryAddr = new Address((int) $order->id_address_delivery);
}
$isoCountry = Country::getIsoById($deliveryAddr->id_country);
$shipments[$label->id]['return_available'] = (bool) ColissimoTools::getReturnDestinationTypeByIsoCountry(
$isoCountry
);
$shipments[$label->id]['is_printable_pdf'] = $label->label_format == 'pdf' ? true : false;
$shipments[$label->id]['is_deletable'] = $label->isDeletable();
$shipments[$label->id]['is_downloadable'] = $label->isDownloadable();
} else {
$shipments[$label->return_label]['id_return_label'] = $label->id;
$shipments[$label->return_label]['return_shipping_number'] = $label->shipping_number;
$shipments[$label->return_label]['return_cn23'] = $label->cn23;
$shipments[$label->return_label]['return_coliship'] = $label->coliship;
$shipments[$label->return_label]['return_insurance'] = $label->insurance;
$shipments[$label->return_label]['return_migration'] = $label->migration;
$shipments[$label->return_label]['return_file_deleted'] = $label->file_deleted;
$shipments[$label->return_label]['return_is_deletable'] = $label->isDeletable();
$shipments[$label->return_label]['return_is_downloadable'] = $label->isDownloadable();
try {
$base64 = base64_encode(Tools::file_get_contents($label->getFilePath()));
$shipments[$label->return_label]['return_base64'] = $base64;
} catch (Exception $e) {
$shipments[$label->return_label]['return_base64'] = '';
}
try {
$base64 = $label->cn23 ? base64_encode(Tools::file_get_contents($label->getCN23Path())) : '';
$shipments[$label->return_label]['return_cn23_base64'] = $base64;
} catch (Exception $e) {
$shipments[$label->return_label]['return_cn23_base64'] = '';
}
}
}
return $shipments;
}
/**
* @param int $idOrder
* @return int
*/
public static function exists($idOrder)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_order')
->from('colissimo_order')
->where('id_order = '.(int) $idOrder);
return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @param bool $includeReturns
* @return array|false|mysqli_result|null|PDOStatement|resource
* @throws PrestaShopDatabaseException
*/
public function getLabelIds($includeReturns = false)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_label')
->from('colissimo_label')
->where('id_colissimo_order = '.(int) $this->id);
if (!$includeReturns) {
$dbQuery->where('return_label = 0');
}
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($dbQuery);
if ($result && is_array($result)) {
return array_map(
function ($element) {
return $element['id_colissimo_label'];
},
$result
);
}
return $result;
}
/**
* @param int $idOrder
* @return int
*/
public static function getIdByOrderId($idOrder)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_order')
->from('colissimo_order')
->where('id_order = '.(int) $idOrder);
return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @param int $idCustomer
* @param int $idShop
* @return array
* @throws PrestaShopDatabaseException
*/
public static function getCustomerColissimoOrderIds($idCustomer, $idShop)
{
$dbQuery = new DbQuery();
$dbQuery->select('co.id_colissimo_order')
->from('colissimo_order', 'co')
->leftJoin('orders', 'o', 'o.id_order = co.id_order')
->where('o.id_customer = '.(int) $idCustomer.' AND o.id_shop = '.$idShop)
->orderBy('o.date_add DESC');
$ids = array_map(
function ($element) {
return $element['id_colissimo_order'];
},
Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($dbQuery)
);
return $ids;
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoOrderCarrier
*/
class ColissimoOrderCarrier extends OrderCarrier
{
/**
* @param int $idOrder
* @return ColissimoOrderCarrier
*/
public static function getByIdOrder($idOrder)
{
$dbQuery = new DbQuery();
$dbQuery->select(self::$definition['primary'])
->from(self::$definition['table'])
->where('id_order = '.(int) $idOrder);
$id = Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
return new self((int) $id);
}
/**
* @param int $idOrder
* @return array|false|mysqli_result|null|PDOStatement|resource
*/
public static function getAllByIdOrder($idOrder)
{
$dbQuery = new DbQuery();
$dbQuery->select('*')
->from(self::$definition['table'])
->where('id_order = '.(int) $idOrder);
try {
$orderCarriers = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($dbQuery);
} catch (PrestaShopException $e) {
return array();
}
return $orderCarriers;
}
}

View File

@@ -0,0 +1,135 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoPickupPoint
*/
class ColissimoPickupPoint extends ObjectModel
{
/** @var int $id_colissimo_pickup_point */
public $id_colissimo_pickup_point;
/** @var string $colissimo_id */
public $colissimo_id;
/** @var string $company_name */
public $company_name;
/** @var string $address1 */
public $address1;
/** @var string $address2 */
public $address2;
/** @var string $address3 */
public $address3;
/** @var string $city */
public $city;
/** @var string $zipcode */
public $zipcode;
/** @var string $country */
public $country;
/** @var string $iso_country */
public $iso_country;
/** @var string $product_code */
public $product_code;
/** @var string $network */
public $network;
/** @var string $date_add */
public $date_add;
/** @var string $date_upd */
public $date_upd;
//@formatter:off
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_pickup_point',
'primary' => 'id_colissimo_pickup_point',
'fields' => array(
'colissimo_id' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 8),
'company_name' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 64),
'address1' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 120),
'address2' => array('type' => self::TYPE_STRING, 'required' => false, 'size' => 120),
'address3' => array('type' => self::TYPE_STRING, 'required' => false, 'size' => 120),
'city' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 80),
'zipcode' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 10),
'country' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 64),
'iso_country' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 2),
'product_code' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 3),
'network' => array('type' => self::TYPE_STRING, 'required' => false, 'size' => 10),
'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
),
);
/** @var array $availableIso Countries that allow pickup point (22 ISO) */
public static $availableIso = array('AD', 'AT', 'BE', 'DE', 'ES', 'FR', 'EE', 'GB', 'HU', 'LT', 'LU', 'LV', 'MC', 'NL', 'PL', 'PT', 'SE', 'DK', 'FI', 'CZ', 'SK', 'SI');
/** @var array $availableLanguages Available languages in the popup (7 languages) */
public static $availableLanguages = array('fr', 'en', 'es', 'it', 'pt', 'nl', 'de');
/** @var array $BPRAliases Product codes NOT TO USE -- Instead use BPR */
public static $BPRAliases = array('ACP', 'CDI');
//formatter:on
/**
* @param string $colissimoId
* @return ColissimoPickupPoint
*/
public static function getPickupPointByIdColissimo($colissimoId)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_pickup_point')
->from('colissimo_pickup_point')
->where('colissimo_id = "'.pSQL($colissimoId).'"');
$id = Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
return new self((int) $id);
}
/**
* @return string
*/
public function getProductCodeForAffranchissement()
{
if (in_array($this->product_code, self::$BPRAliases)) {
return 'BPR';
}
return $this->product_code;
}
}

View File

@@ -0,0 +1,260 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoService
*/
class ColissimoService extends ObjectModel
{
const TYPE_RELAIS = 'RELAIS';
const TYPE_RETOUR = 'RETOUR';
const TYPE_SIGN = 'AVEC_SIGNATURE';
const TYPE_NOSIGN = 'SANS_SIGNATURE';
/** @var int $id_carrier */
public $id_carrier;
/** @var string $product_code */
public $product_code;
/** @var string $commercial_name */
public $commercial_name;
/** @var string $destination_type Destination of the service (FRANCE, EUROPE, OM, WORLDWIDE) */
public $destination_type;
/** @var bool $is_signature Flag to indicate if the service requires signature at the delivery */
public $is_signature;
/** @var bool $is_pickup Flag to indicate if the delivery is in Pickup-point */
public $is_pickup;
/** @var bool $return Flag to indicate if the service is related to return shipments */
public $is_return;
/** @var string $type */
public $type;
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_service',
'primary' => 'id_colissimo_service',
'fields' => array(
'id_carrier' => array('type' => self::TYPE_INT, 'validate' => 'isNullOrUnsignedId'),
'product_code' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 5),
'commercial_name' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 50),
'destination_type' => array('type' => self::TYPE_STRING, 'required' => true, 'size' => 10),
'is_signature' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool', 'required' => true),
'is_pickup' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool', 'required' => true),
'is_return' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool', 'required' => true),
'type' => array('type' => self::TYPE_STRING, 'required' => true),
),
);
/** @var array $insurableProducts */
public static $insurableProducts = array('COL', 'BPR', 'A2P', 'CDS', 'CORE', 'CORI', 'COLI');
/** @var array $unavailableMachinableProductCodes */
public static $unavailableMachinableProductCodes = array('BPR', 'A2P', 'CMT');
/**
* @param string $isoCode
* @return bool
*/
public function isInsurable($isoCode)
{
//@formatter:off
if (in_array($this->product_code, self::$insurableProducts) || ($this->product_code == 'DOS' && $isoCode == 'FR')) {
return true;
}
//@formatter:off
return false;
}
/**
* @return bool
*/
public function isMachinableOptionAvailable()
{
return !in_array($this->product_code, self::$unavailableMachinableProductCodes);
}
/**
* @param bool $excludeReturn
* @return array|false|mysqli_result|null|PDOStatement|resource
* @throws PrestaShopDatabaseException
*/
public static function getAll($excludeReturn = true)
{
$dbQuery = new DbQuery();
$dbQuery->select('*')
->from('colissimo_service');
if ($excludeReturn) {
$dbQuery->where('is_return = 0');
}
return Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($dbQuery);
}
/**
* @param int $idCarrierReference
* @param string $destinationType
* @return int
*/
public static function getServiceIdByIdCarrierDestinationType($idCarrierReference, $destinationType)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_service')
->from('colissimo_service')
->where(
'id_carrier = '.(int) $idCarrierReference.' AND destination_type = "'.pSQL($destinationType).'"'
);
return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @param string $productCode
* @param string $destinationType
* @return int
*/
public static function getServiceIdByProductCodeDestinationType($productCode, $destinationType)
{
//@formatter:off
if (in_array($productCode, ColissimoPickupPoint::$BPRAliases)) {
$productCode = 'BPR';
}
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_service')
->from('colissimo_service')
->where('product_code = "'.pSQL($productCode).'" AND destination_type = "'.pSQL($destinationType).'"');
//@formatter:on
return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @param int $idCarrier
* @return false|null|string
*/
public static function getServiceTypeByIdCarrier($idCarrier)
{
$dbQuery = new DbQuery();
$dbQuery->select('type')
->from('colissimo_service')
->where('id_carrier = '.(int) $idCarrier);
return Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @param string $destinationType
* @param bool $includeReturn
* @return array|false|string|null
* @throws PrestaShopDatabaseException
*/
public static function getServiceIdsByDestinationType($destinationType, $includeReturn = false)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_service')
->from('colissimo_service')
->where('destination_type = "'.pSQL($destinationType).'"');
if (!$includeReturn) {
$dbQuery->where('is_return = 0');
}
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($dbQuery);
if ($result && is_array($result)) {
return array_map(
function ($element) {
return $element['id_colissimo_service'];
},
$result
);
}
return $result;
}
/**
* @param string $isoCountryCustomer
* @param array $accountType
* @return bool
*/
public function isEligibleToAccount($isoCountryCustomer, $accountType)
{
$availableIso = ColissimoPickupPoint::$availableIso;
if (Configuration::get('COLISSIMO_ENABLE_BREXIT')) {
$availableIso = array_diff($availableIso, array('GB'));
}
//@formatter:off
$destinationWorldWideEU = array(ColissimoTools::DEST_EU, ColissimoTools::DEST_WORLD);
if (in_array($this->destination_type, $destinationWorldWideEU) && !isset($accountType[$this->destination_type])) {
return false;
}
//@formatter:on
if ($this->type == ColissimoService::TYPE_RELAIS) {
if (!in_array($isoCountryCustomer, $availableIso)) {
return false;
}
}
if ($this->destination_type == ColissimoTools::DEST_EU &&
$this->is_signature == 0 &&
$this->type != ColissimoService::TYPE_RELAIS
) {
if (!in_array($isoCountryCustomer, ColissimoTools::$isoEUCountriesZone1Zone3)) {
return false;
}
}
if ($this->destination_type == ColissimoTools::DEST_OM &&
!isset($accountType[$this->destination_type])
) {
return false;
}
return true;
}
/**
* @param int $id
* @return false|string|null
*/
public static function getServiceTypeById($id)
{
$dbQuery = new DbQuery();
$dbQuery->select('type')
->from('colissimo_service')
->where('id_colissimo_service = '.(int) $id);
return Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,115 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoTrackingCode
*/
class ColissimoTrackingCode extends ObjectModel
{
const TYPO_DELIVERED = 'LIV';
const TYPO_SHIPPED = 'SHI';
const TYPO_ANOMALY = 'ANO';
const EVENT_WAITING_SHIPMENT_HANDLING = 'COMCFM';
/** @var int $id_colissimo_tracking_code */
public $id_colissimo_tracking_code;
/** @var string $clp_code */
public $clp_code;
/** @var string $inovert_code */
public $inovert_code;
/** @var string $typology Typology of the event ("LIV" / "ANO"...) */
public $typology;
/** @var string $internal_text */
public $internal_text;
/** @var array $definition */
public static $definition = array(
'table' => 'colissimo_tracking_code',
'primary' => 'id_colissimo_tracking_code',
'fields' => array(
'clp_code' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true,
'size' => 10,
),
'inovert_code' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => false,
'size' => 10,
),
'typology' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => false,
'size' => 10,
),
'internal_text' => array(
'type' => self::TYPE_STRING,
'validate' => 'isGenericName',
'required' => true,
'size' => 255,
),
),
);
/**
* @param string $inovertCode
* @return mixed
*/
public static function getTypologyByInovertCode($inovertCode)
{
$dbQuery = new DbQuery();
$dbQuery->select('typology')
->from('colissimo_tracking_code')
->where('inovert_code = "'.pSQL($inovertCode).'"');
return Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
}
/**
* @param string $clpCode
* @return ColissimoTrackingCode
*/
public static function getByClpCode($clpCode)
{
$dbQuery = new DbQuery();
$dbQuery->select('id_colissimo_tracking_code')
->from('colissimo_tracking_code')
->where('clp_code = "'.pSQL($clpCode).'"');
$id = Db::getInstance(_PS_USE_SQL_SLAVE_)
->getValue($dbQuery);
return new self((int) $id);
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,63 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class AbstractColissimoHandler
*/
abstract class AbstractColissimoHandler
{
/**
*
*/
public function __destruct()
{
$this->close();
}
/**
* @param string $level
* @param string $message
* @param string $channel
* @param array $details
* @return mixed
*/
abstract public function log($level, $message, $channel, $details);
/**
* @param string $level
* @param string $message
* @param string $channel
* @param string $xmlString
* @return mixed
*/
abstract public function logXml($level, $message, $channel, $xmlString);
/**
* @return bool
*/
abstract public function close();
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoFileHandler
*/
class ColissimoFileHandler extends AbstractColissimoHandler
{
/** @var bool|resource $fd */
protected $fd;
/**
* ColissimoFileHandler constructor.
* @param string $file
*/
public function __construct($file)
{
$this->fd = @fopen($file, 'a+');
}
/**
* @param string $level
* @param string $message
* @param string $channel
* @param array $details
* @return bool
*/
public function log($level, $message, $channel, $details)
{
if (is_resource($this->fd)) {
$string =
sprintf('[%s] %s.%s: %s %s', date('Y-m-d H:i:s'), $channel, $level, $message, json_encode($details));
@fwrite($this->fd, $string." []\r\n");
}
return true;
}
/**
* @param string $level
* @param string $message
* @param string $channel
* @param string $requestArray
* @return bool
*/
public function logXml($level, $message, $channel, $requestArray)
{
return $this->log($level, $message, $channel, array('xml' => json_decode($requestArray, true)));
}
/**
* @return bool
*/
public function close()
{
if (is_resource($this->fd)) {
return fclose($this->fd);
}
return true;
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoLogger
*/
class ColissimoLogger
{
const LEVEL_INFO = 'INFO';
const LEVEL_WARNING = 'WARNING';
const LEVEL_ERROR = 'ERROR';
/** @var AbstractColissimoHandler $handler */
protected $handler;
/** @var string $channel */
protected $channel;
/** @var string $version */
protected $version;
/**
* DhlLogger constructor.
* @param AbstractColissimoHandler $handler
* @param string $version
*/
public function __construct($handler, $version)
{
$this->handler = $handler;
$this->channel = 'Unknown';
$this->version = str_replace('.', '_', $version);
}
/**
* @param string $channel
*/
public function setChannel($channel)
{
$this->channel = 'Colissimo_'.$this->version.'_'.$channel;
}
/**
* @param string $message
* @param array $details
*/
public function info($message, $details = array())
{
$this->handler->log(self::LEVEL_INFO, $message, $this->channel, $details);
}
/**
* @param string $message
* @param string $xmlString
*/
public function infoXml($message, $xmlString)
{
$this->handler->logXml(self::LEVEL_INFO, $message, $this->channel, $xmlString);
}
/**
* @param string $message
* @param array $details
*/
public function warning($message, $details = array())
{
$this->handler->log(self::LEVEL_WARNING, $message, $this->channel, $details);
}
/**
* @param string $message
* @param array $details
*/
public function error($message, $details = array())
{
$this->handler->log(self::LEVEL_ERROR, $message, $this->channel, $details);
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoNullHandler
*/
class ColissimoNullHandler extends AbstractColissimoHandler
{
/**
* @param string $level
* @param string $message
* @param string $channel
* @param array $details
* @return bool
*/
public function log($level, $message, $channel, $details)
{
return true;
}
/**
* @param string $level
* @param string $message
* @param string $channel
* @param string $xmlString
* @return bool
*/
public function logXml($level, $message, $channel, $xmlString)
{
return true;
}
/**
* @return bool
*/
public function close()
{
return true;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,256 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoColissimoSimpliciteMigration
*/
class ColissimoColissimoSimpliciteMigration implements ColissimoOtherModuleInterface
{
/** @var ColissimoLogger $logger */
protected $logger;
/**
* ColissimoColissimoSimpliciteMigration constructor.
* @param ColissimoLogger $logger
*/
public function __construct(ColissimoLogger $logger)
{
$this->logger = $logger;
}
/**
* @return bool
*/
public function migrateCredentials()
{
if (Configuration::getGlobalValue('COLISSIMO_MIGRATION_CREDENTIALS') == 1) {
return true;
}
$login = Configuration::getMultiShopValues('COLISSIMO_LOGIN');
$passwd = Configuration::getMultiShopValues('COLISSIMO_PASSWORD');
$shops = Shop::getShops();
foreach ($shops as $shop) {
if ($login[$shop['id_shop']] && $passwd[$shop['id_shop']]) {
Configuration::updateValue(
'COLISSIMO_ACCOUNT_LOGIN',
$login[$shop['id_shop']],
false,
null,
$shop['id_shop']
);
Configuration::updateValue(
'COLISSIMO_ACCOUNT_PASSWORD',
$passwd[$shop['id_shop']],
false,
null,
$shop['id_shop']
);
}
}
return true;
}
/**
* @return bool
*/
public function migrateCarriers()
{
$idCarrier = Configuration::getGlobalValue('COLISSIMO_CARRIER_ID');
Db::getInstance()
->update('carrier', array('active' => 0), 'id_carrier = '.(int) $idCarrier);
return true;
}
/**
* @return bool
*/
public function migrateConfiguration()
{
$preparationTime = Configuration::getMultiShopValues('COLISSIMO_PREPARATION_TIME');
$shops = Shop::getShops();
foreach ($shops as $shop) {
Configuration::updateValue(
'COLISSIMO_ORDER_PREPARATION_TIME',
$preparationTime[$shop['id_shop']],
false,
null,
$shop['id_shop']
);
}
return true;
}
/**
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function migrateData()
{
$tableExists = Db::getInstance()
->executeS('SHOW TABLES LIKE "'._DB_PREFIX_.'colissimo_delivery_point"');
if (!empty($tableExists)) {
$oldThirdPatyOrdersQuery = new DbQuery();
$oldThirdPatyOrdersQuery->select('*')
->from('colissimo_delivery_point');
$oldThirdPartyOrders = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($oldThirdPatyOrdersQuery);
foreach ($oldThirdPartyOrders as $oldThirdPartyOrder) {
$pickupPointReference = $oldThirdPartyOrder['identifiant'];
$order = ColissimoTools::getOrderByCartId((int) $oldThirdPartyOrder['id_cart']);
if (!Validate::isLoadedObject($order)) {
continue;
}
$deliveryAddr = new Address((int) $order->id_address_delivery);
$deliveryMode = $oldThirdPartyOrder['typeDePoint'];
$destinationType = ColissimoTools::getDestinationTypeByIsoCountry(
Country::getIsoById($deliveryAddr->id_country)
);
$idService = ColissimoService::getServiceIdByProductCodeDestinationType(
$deliveryMode,
$destinationType
);
$idColissimoOrder = ColissimoOrder::getIdByOrderId((int) $order->id);
$colissimoOrder = new ColissimoOrder((int) $idColissimoOrder);
$colissimoOrder->id_colissimo_pickup_point = 0;
if ($pickupPointReference) {
$colissimoPickupPoint = ColissimoPickupPoint::getPickupPointByIdColissimo($pickupPointReference);
if (!Validate::isLoadedObject($colissimoPickupPoint)) {
$colissimoPickupPoint->colissimo_id = pSQL($pickupPointReference);
$colissimoPickupPoint->company_name = pSQL($oldThirdPartyOrder['nom']);
$colissimoPickupPoint->address1 = pSQL($deliveryAddr->address1);
$colissimoPickupPoint->address2 = pSQL($deliveryAddr->address2);
$colissimoPickupPoint->address3 = '';
$colissimoPickupPoint->city = pSQL($deliveryAddr->city);
$colissimoPickupPoint->zipcode = pSQL($deliveryAddr->postcode);
$colissimoPickupPoint->country = pSQL(
Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), $deliveryAddr->id_country)
);
$colissimoPickupPoint->iso_country = pSQL(Country::getIsoById($deliveryAddr->id_country));
$colissimoPickupPoint->product_code = pSQL($deliveryMode);
$colissimoPickupPoint->network = pSQL($oldThirdPartyOrder['reseau']);
try {
$colissimoPickupPoint->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
$colissimoOrder->id_colissimo_pickup_point = (int) $colissimoPickupPoint->id;
}
$colissimoOrder->id_order = (int) $order->id;
$colissimoOrder->id_colissimo_service = (int) $idService;
$colissimoOrder->migration = 1;
$colissimoOrder->hidden = 0;
try {
$colissimoOrder->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
}
$tableExists = Db::getInstance()
->executeS('SHOW TABLES LIKE "'._DB_PREFIX_.'colissimo_delivery_info"');
if (!empty($tableExists)) {
$oldColissimoOrdersQuery = new DbQuery();
$oldColissimoOrdersQuery->select('*')
->from('colissimo_delivery_info');
$oldColissimoOrders = Db::getInstance()
->executeS($oldColissimoOrdersQuery);
foreach ($oldColissimoOrders as $oldOrder) {
$pickupPointReference = $oldOrder['prid'];
$order = ColissimoTools::getOrderByCartId((int) $oldOrder['id_cart']);
if (!Validate::isLoadedObject($order)) {
continue;
}
$deliveryAddr = new Address((int) $order->id_address_delivery);
$deliveryMode = $oldOrder['delivery_mode'];
$destinationType = ColissimoTools::getDestinationTypeByIsoCountry(
Country::getIsoById($deliveryAddr->id_country)
);
$idService = ColissimoService::getServiceIdByProductCodeDestinationType(
$deliveryMode,
$destinationType
);
$idColissimoOrder = ColissimoOrder::getIdByOrderId((int) $order->id);
$colissimoOrder = new ColissimoOrder((int) $idColissimoOrder);
$colissimoOrder->id_colissimo_pickup_point = 0;
if ($pickupPointReference) {
$colissimoPickupPoint = ColissimoPickupPoint::getPickupPointByIdColissimo($pickupPointReference);
if (!Validate::isLoadedObject($colissimoPickupPoint)) {
$colissimoPickupPoint->colissimo_id = pSQL($pickupPointReference);
$colissimoPickupPoint->company_name = pSQL($oldOrder['prname']);
$colissimoPickupPoint->address1 = pSQL($deliveryAddr->address1);
$colissimoPickupPoint->address2 = pSQL($deliveryAddr->address2);
$colissimoPickupPoint->address3 = '';
$colissimoPickupPoint->city = pSQL($deliveryAddr->city);
$colissimoPickupPoint->zipcode = pSQL($deliveryAddr->postcode);
$colissimoPickupPoint->country = pSQL(
Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), $deliveryAddr->id_country)
);
$colissimoPickupPoint->iso_country = pSQL(Country::getIsoById($deliveryAddr->id_country));
$colissimoPickupPoint->product_code = pSQL($oldOrder['delivery_mode']);
$colissimoPickupPoint->network = pSQL($oldOrder['codereseau']);
try {
$colissimoPickupPoint->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
$colissimoOrder->id_colissimo_pickup_point = (int) $colissimoPickupPoint->id;
}
$colissimoOrder->id_order = (int) $order->id;
$colissimoOrder->id_colissimo_service = (int) $idService;
$colissimoOrder->migration = 1;
$colissimoOrder->hidden = 0;
try {
$colissimoOrder->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
}
return true;
}
/**
* @return bool
*/
public function migrateDocuments()
{
return true;
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoMigration
*/
class ColissimoMigration
{
/** @var ColissimoOtherModuleInterface[] $otherModules */
private $otherModules;
/**
* @param ColissimoOtherModuleInterface $module
*/
public function addModule(ColissimoOtherModuleInterface $module)
{
$this->otherModules[] = $module;
}
/**
* @param string $step
* @throws Exception
*/
public function migrate($step)
{
$methodCall = Tools::toCamelCase('migrate_'.$step);
foreach ($this->otherModules as $otherModule) {
if (method_exists($otherModule, $methodCall)) {
$otherModule->$methodCall();
} else {
throw new Exception('Cannot call migration step.');
}
}
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Interface ColissimoOtherModuleInterface
*/
interface ColissimoOtherModuleInterface
{
/**
* ColissimoOtherModuleInterface constructor.
* @param ColissimoLogger $logger
*/
public function __construct(ColissimoLogger $logger);
/**
* @return bool
*/
public function migrateCredentials();
/**
* @return bool
*/
public function migrateCarriers();
/**
* @return bool
*/
public function migrateDocuments();
/**
* @return bool
*/
public function migrateConfiguration();
/**
* @return bool
*/
public function migrateData();
}

View File

@@ -0,0 +1,254 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoSocolissimoMigration
*/
class ColissimoSocolissimoMigration implements ColissimoOtherModuleInterface
{
/** @var ColissimoLogger $logger */
protected $logger;
/**
* ColissimoColissimoSimpliciteMigration constructor.
* @param ColissimoLogger $logger
*/
public function __construct(ColissimoLogger $logger)
{
$this->logger = $logger;
}
/**
* @return bool
*/
public function migrateCredentials()
{
if (Configuration::getGlobalValue('COLISSIMO_MIGRATION_CREDENTIALS') == 1) {
return true;
}
$login = Configuration::getMultiShopValues('SOCOLISSIMO_LOGIN');
$passwd = Configuration::getMultiShopValues('SOCOLISSIMO_PASSWORD');
$shops = Shop::getShops();
foreach ($shops as $shop) {
if ($login[$shop['id_shop']] && $passwd[$shop['id_shop']]) {
Configuration::updateValue(
'COLISSIMO_ACCOUNT_LOGIN',
$login[$shop['id_shop']],
false,
null,
$shop['id_shop']
);
Configuration::updateValue(
'COLISSIMO_ACCOUNT_PASSWORD',
$passwd[$shop['id_shop']],
false,
null,
$shop['id_shop']
);
}
}
return true;
}
/**
* @return bool
*/
public function migrateConfiguration()
{
$preparationTime = Configuration::getMultiShopValues('SOCOLISSIMO_PREPARATION_TIME');
$shops = Shop::getShops();
foreach ($shops as $shop) {
Configuration::updateValue(
'COLISSIMO_ORDER_PREPARATION_TIME',
$preparationTime[$shop['id_shop']],
false,
null,
$shop['id_shop']
);
}
return true;
}
/**
* @return bool
*/
public function migrateCarriers()
{
$idCarrier = Configuration::getGlobalValue('SOCOLISSIMO_CARRIER_ID');
Db::getInstance()
->update('carrier', array('active' => 0), 'id_carrier = '.(int) $idCarrier);
return true;
}
/**
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function migrateData()
{
$tableExists = Db::getInstance()
->executeS('SHOW TABLES LIKE "'._DB_PREFIX_.'socolissimo_delivery_point"');
if (!empty($tableExists)) {
$oldThirdPatyOrdersQuery = new DbQuery();
$oldThirdPatyOrdersQuery->select('*')
->from('socolissimo_delivery_point');
$oldThirdPartyOrders = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($oldThirdPatyOrdersQuery);
foreach ($oldThirdPartyOrders as $oldThirdPartyOrder) {
$pickupPointReference = $oldThirdPartyOrder['identifiant'];
$order = ColissimoTools::getOrderByCartId((int) $oldThirdPartyOrder['id_cart']);
if (!Validate::isLoadedObject($order)) {
continue;
}
$deliveryAddr = new Address((int) $order->id_address_delivery);
$deliveryMode = $oldThirdPartyOrder['typeDePoint'];
$destinationType = ColissimoTools::getDestinationTypeByIsoCountry(
Country::getIsoById($deliveryAddr->id_country)
);
$idService = ColissimoService::getServiceIdByProductCodeDestinationType(
$deliveryMode,
$destinationType
);
$idColissimoOrder = ColissimoOrder::getIdByOrderId((int) $order->id);
$colissimoOrder = new ColissimoOrder((int) $idColissimoOrder);
$colissimoOrder->id_colissimo_pickup_point = 0;
if ($pickupPointReference) {
$colissimoPickupPoint = ColissimoPickupPoint::getPickupPointByIdColissimo($pickupPointReference);
if (!Validate::isLoadedObject($colissimoPickupPoint)) {
$colissimoPickupPoint->colissimo_id = pSQL($pickupPointReference);
$colissimoPickupPoint->company_name =
pSQL($oldThirdPartyOrder['nom']) ? pSQL($oldThirdPartyOrder['nom']) : ' ';
$colissimoPickupPoint->address1 = pSQL($deliveryAddr->address1);
$colissimoPickupPoint->address2 = pSQL($deliveryAddr->address2);
$colissimoPickupPoint->address3 = '';
$colissimoPickupPoint->city = pSQL($deliveryAddr->city);
$colissimoPickupPoint->zipcode = pSQL($deliveryAddr->postcode);
$colissimoPickupPoint->country = pSQL(
Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), $deliveryAddr->id_country)
);
$colissimoPickupPoint->iso_country = pSQL(Country::getIsoById($deliveryAddr->id_country));
$colissimoPickupPoint->product_code = pSQL($deliveryMode);
$colissimoPickupPoint->network = pSQL($oldThirdPartyOrder['reseau']);
try {
$colissimoPickupPoint->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
$colissimoOrder->id_colissimo_pickup_point = (int) $colissimoPickupPoint->id;
}
$colissimoOrder->id_order = (int) $order->id;
$colissimoOrder->id_colissimo_service = (int) $idService;
$colissimoOrder->migration = 1;
$colissimoOrder->hidden = 0;
try {
$colissimoOrder->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
}
$tableExists = Db::getInstance()
->executeS('SHOW TABLES LIKE "'._DB_PREFIX_.'socolissimo_delivery_info"');
if (!empty($tableExists)) {
$oldColissimoOrdersQuery = new DbQuery();
$oldColissimoOrdersQuery->select('*')
->from('socolissimo_delivery_info');
$oldColissimoOrders = Db::getInstance()
->executeS($oldColissimoOrdersQuery);
foreach ($oldColissimoOrders as $oldOrder) {
$pickupPointReference = $oldOrder['prid'];
$order = ColissimoTools::getOrderByCartId((int) $oldOrder['id_cart']);
if (!Validate::isLoadedObject($order)) {
continue;
}
$deliveryAddr = new Address((int) $order->id_address_delivery);
$deliveryMode = $oldOrder['delivery_mode'];
$destinationType = ColissimoTools::getDestinationTypeByIsoCountry(
Country::getIsoById($deliveryAddr->id_country)
);
$idService = ColissimoService::getServiceIdByProductCodeDestinationType(
$deliveryMode,
$destinationType
);
$idColissimoOrder = ColissimoOrder::getIdByOrderId((int) $order->id);
$colissimoOrder = new ColissimoOrder((int) $idColissimoOrder);
$colissimoOrder->id_colissimo_pickup_point = 0;
if ($pickupPointReference) {
$colissimoPickupPoint = ColissimoPickupPoint::getPickupPointByIdColissimo($pickupPointReference);
if (!Validate::isLoadedObject($colissimoPickupPoint)) {
$colissimoPickupPoint->colissimo_id = pSQL($pickupPointReference);
$colissimoPickupPoint->company_name =
pSQL($oldOrder['prname']) ? pSQL($oldOrder['prname']) : ' ';
$colissimoPickupPoint->address1 = pSQL($deliveryAddr->address1);
$colissimoPickupPoint->address2 = pSQL($deliveryAddr->address2);
$colissimoPickupPoint->address3 = '';
$colissimoPickupPoint->city = pSQL($deliveryAddr->city);
$colissimoPickupPoint->zipcode = pSQL($deliveryAddr->postcode);
$colissimoPickupPoint->country = pSQL(
Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), $deliveryAddr->id_country)
);
$colissimoPickupPoint->iso_country = pSQL(Country::getIsoById($deliveryAddr->id_country));
$colissimoPickupPoint->product_code = pSQL($oldOrder['delivery_mode']);
$colissimoPickupPoint->network = pSQL($oldOrder['codereseau']);
try {
$colissimoPickupPoint->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
$colissimoOrder->id_colissimo_pickup_point = (int) $colissimoPickupPoint->id;
}
$colissimoOrder->id_order = (int) $order->id;
$colissimoOrder->id_colissimo_service = (int) $idService;
$colissimoOrder->migration = 1;
try {
$colissimoOrder->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
}
return true;
}
public function migrateDocuments()
{
return true;
}
}

View File

@@ -0,0 +1,262 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoSoflexibiliteMigration
*/
class ColissimoSoflexibiliteMigration implements ColissimoOtherModuleInterface
{
const MODULE_NAME = 'soflexibilite';
/** @var ColissimoLogger $logger */
private $logger;
/**
* ColissimoSoflexibiliteMigration constructor.
* @param ColissimoLogger $logger
*/
public function __construct(ColissimoLogger $logger)
{
$this->logger = $logger;
}
/**
* @return bool
*/
public function migrateCredentials()
{
$login = Configuration::getMultiShopValues('SOFLEXIBILITE_LOGIN');
$passwd = Configuration::getMultiShopValues('SOFLEXIBILITE_PASSWORD');
$shops = Shop::getShops();
foreach ($shops as $shop) {
if ($login[$shop['id_shop']] && $passwd[$shop['id_shop']]) {
Configuration::updateValue(
'COLISSIMO_ACCOUNT_LOGIN',
$login[$shop['id_shop']],
false,
null,
$shop['id_shop']
);
Configuration::updateValue(
'COLISSIMO_ACCOUNT_PASSWORD',
$passwd[$shop['id_shop']],
false,
null,
$shop['id_shop']
);
// If Colissimo Simplicite has at least one login/pass configured, we considered that these credentials
// are the correct one. We won't try to migrate credentials from other modules.
Configuration::updateGlobalValue('COLISSIMO_MIGRATION_CREDENTIALS', 1);
}
}
return true;
}
/**
* @return bool
* @throws PrestaShopException
*/
public function migrateCarriers()
{
$correspondance = array(
'SOFLEXIBILITE_DOM_ID' => 'COLISSIMO_CARRIER_SANS_SIGNATURE',
'SOFLEXIBILITE_DOS_ID' => 'COLISSIMO_CARRIER_AVEC_SIGNATURE',
'SOFLEXIBILITE_A2P_ID' => 'COLISSIMO_CARRIER_RELAIS',
);
$flexibiliteCarrierIds = Configuration::getMultiple(
array(
'SOFLEXIBILITE_DOM_ID',
'SOFLEXIBILITE_DOS_ID',
'SOFLEXIBILITE_A2P_ID',
)
);
foreach ($flexibiliteCarrierIds as $key => $flexibiliteCarrierId) {
ColissimoTools::migrateCarrierData($flexibiliteCarrierId, $correspondance, $key);
}
Db::getInstance()
->update('carrier', array('active' => 0), 'external_module_name = "'.pSQL(self::MODULE_NAME).'"');
return true;
}
/**
* @return bool
*/
public function migrateConfiguration()
{
return true;
}
/**
* @return bool
*/
public function migrateDocuments()
{
return true;
}
/**
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function migrateData()
{
$tableExists = Db::getInstance()
->executeS('SHOW TABLES LIKE "'._DB_PREFIX_.'so_delivery"');
if (!empty($tableExists)) {
$oldThirdPatyOrdersQuery = new DbQuery();
$oldThirdPatyOrdersQuery->select('*')
->from('so_delivery');
$oldThirdPartyOrders = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($oldThirdPatyOrdersQuery);
foreach ($oldThirdPartyOrders as $oldThirdPartyOrder) {
$pickupPointReference = $oldThirdPartyOrder['point_id'];
$order = ColissimoTools::getOrderByCartId((int) $oldThirdPartyOrder['cart_id']);
if (!Validate::isLoadedObject($order)) {
continue;
}
$deliveryAddr = new Address((int) $order->id_address_delivery);
$deliveryMode = $oldThirdPartyOrder['type'];
$destinationType = ColissimoTools::getDestinationTypeByIsoCountry(
Country::getIsoById($deliveryAddr->id_country)
);
$idService = ColissimoService::getServiceIdByProductCodeDestinationType(
$deliveryMode,
$destinationType
);
$idColissimoOrder = ColissimoOrder::getIdByOrderId((int) $order->id);
$colissimoOrder = new ColissimoOrder((int) $idColissimoOrder);
$colissimoOrder->id_colissimo_pickup_point = 0;
if ($pickupPointReference) {
$colissimoPickupPoint = ColissimoPickupPoint::getPickupPointByIdColissimo($pickupPointReference);
if (!Validate::isLoadedObject($colissimoPickupPoint)) {
$colissimoPickupPoint->colissimo_id = pSQL($pickupPointReference);
$colissimoPickupPoint->company_name = pSQL($deliveryAddr->company);
$colissimoPickupPoint->address1 = pSQL($deliveryAddr->address1);
$colissimoPickupPoint->address2 = pSQL($deliveryAddr->address2);
$colissimoPickupPoint->address3 = '';
$colissimoPickupPoint->city = pSQL($deliveryAddr->city);
$colissimoPickupPoint->zipcode = pSQL($deliveryAddr->postcode);
$colissimoPickupPoint->country = pSQL(
Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), $deliveryAddr->id_country)
);
$colissimoPickupPoint->iso_country = pSQL(Country::getIsoById($deliveryAddr->id_country));
$colissimoPickupPoint->product_code = pSQL($oldThirdPartyOrder['type']);
$colissimoPickupPoint->network = pSQL($oldThirdPartyOrder['codereseau']);
try {
$colissimoPickupPoint->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
$colissimoOrder->id_colissimo_pickup_point = (int) $colissimoPickupPoint->id;
}
$colissimoOrder->id_order = (int) $order->id;
$colissimoOrder->id_colissimo_service = (int) $idService;
$colissimoOrder->migration = 1;
$colissimoOrder->hidden = 0;
try {
$colissimoOrder->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
}
$tableExists = Db::getInstance()
->executeS('SHOW TABLES LIKE "'._DB_PREFIX_.'socolissimo_delivery_info"');
if (!empty($tableExists)) {
$oldColissimoOrdersQuery = new DbQuery();
$oldColissimoOrdersQuery->select('*')
->from('socolissimo_delivery_info');
$oldColissimoOrders = Db::getInstance()
->executeS($oldColissimoOrdersQuery);
foreach ($oldColissimoOrders as $oldOrder) {
$pickupPointReference = $oldOrder['prid'];
$order = ColissimoTools::getOrderByCartId((int) $oldOrder['id_cart']);
if (!Validate::isLoadedObject($order)) {
continue;
}
$deliveryAddr = new Address((int) $order->id_address_delivery);
$deliveryMode = $oldOrder['delivery_mode'];
$destinationType = ColissimoTools::getDestinationTypeByIsoCountry(
Country::getIsoById($deliveryAddr->id_country)
);
$idService = ColissimoService::getServiceIdByProductCodeDestinationType(
$deliveryMode,
$destinationType
);
$idColissimoOrder = ColissimoOrder::getIdByOrderId((int) $order->id);
$colissimoOrder = new ColissimoOrder((int) $idColissimoOrder);
$colissimoOrder->id_colissimo_pickup_point = 0;
if ($pickupPointReference) {
$colissimoPickupPoint = ColissimoPickupPoint::getPickupPointByIdColissimo($pickupPointReference);
if (!Validate::isLoadedObject($colissimoPickupPoint)) {
$colissimoPickupPoint->colissimo_id = pSQL($pickupPointReference);
$colissimoPickupPoint->company_name = pSQL($deliveryAddr->company);
$colissimoPickupPoint->address1 = pSQL($deliveryAddr->address1);
$colissimoPickupPoint->address2 = pSQL($deliveryAddr->address2);
$colissimoPickupPoint->address3 = '';
$colissimoPickupPoint->city = pSQL($deliveryAddr->city);
$colissimoPickupPoint->zipcode = pSQL($deliveryAddr->postcode);
$colissimoPickupPoint->country = pSQL(
Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), $deliveryAddr->id_country)
);
$colissimoPickupPoint->iso_country = pSQL(Country::getIsoById($deliveryAddr->id_country));
$colissimoPickupPoint->product_code = pSQL($oldOrder['delivery_mode']);
$colissimoPickupPoint->network = pSQL($oldOrder['codereseau']);
try {
$colissimoPickupPoint->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
$colissimoOrder->id_colissimo_pickup_point = (int) $colissimoPickupPoint->id;
}
$colissimoOrder->id_order = (int) $order->id;
$colissimoOrder->id_colissimo_service = (int) $idService;
$colissimoOrder->migration = 1;
$colissimoOrder->hidden = 0;
try {
$colissimoOrder->save();
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
}
return true;
}
}

View File

@@ -0,0 +1,187 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoSoniceEtiquetageMigration
*/
class ColissimoSoniceEtiquetageMigration implements ColissimoOtherModuleInterface
{
/** @var ColissimoLogger $logger */
private $logger;
/**
* ColissimoSoflexibiliteMigration constructor.
* @param ColissimoLogger $logger
*/
public function __construct(ColissimoLogger $logger)
{
$this->logger = $logger;
}
/**
* @return bool
*/
public function migrateCredentials()
{
if (Configuration::getGlobalValue('COLISSIMO_MIGRATION_CREDENTIALS') == 1) {
return true;
}
$configs = Configuration::getMultiShopValues('SONICE_ETQ_CONF');
$shops = Shop::getShops();
foreach ($shops as $shop) {
$config = unserialize($configs[$shop['id_shop']]);
if ($config['ContractNumber'] && $config['Password']) {
Configuration::updateValue(
'COLISSIMO_ACCOUNT_LOGIN',
$config['ContractNumber'],
false,
null,
$shop['id_shop']
);
Configuration::updateValue(
'COLISSIMO_ACCOUNT_PASSWORD',
$config['Password'],
false,
null,
$shop['id_shop']
);
}
}
return true;
}
/**
* @return bool
*/
public function migrateCarriers()
{
return true;
}
/**
* @return bool
*/
public function migrateConfiguration()
{
$configs = Configuration::getMultiShopValues('SONICE_ETQ_CONF');
$statuses = Configuration::getMultiShopValues('SONICE_ETQ_STATUS');
$shops = Shop::getShops();
foreach ($shops as $shop) {
$config = unserialize($configs[$shop['id_shop']]);
$selectedStatuses = unserialize($statuses[$shop['id_shop']]);
$address = array(
'sender_company' => $config['companyName'],
'sender_lastname' => $config['Surname'],
'sender_firstname' => $config['Name'],
'sender_address1' => $config['Line2'],
'sender_address2' => $config['Line0'],
'sender_address3' => '',
'sender_address4' => '',
'sender_city' => $config['City'],
'sender_zipcode' => $config['PostalCode'],
'sender_country' => 'FR',
'sender_phone' => '+33'.Tools::substr($config['phoneNumber'], -9),
'sender_email' => $config['Mail'],
);
Configuration::updateValue(
'COLISSIMO_SENDER_ADDRESS',
json_encode($address),
false,
null,
$shop['id_shop']
);
Configuration::updateValue(
'COLISSIMO_LABEL_FORMAT',
$config['output_print_type'],
false,
null,
$shop['id_shop']
);
if (is_array($selectedStatuses)) {
Configuration::updateValue(
'COLISSIMO_GENERATE_LABEL_STATUSES',
json_encode(array_fill_keys(array_values($selectedStatuses), 1)),
false,
null,
$shop['id_shop']
);
}
}
return true;
}
/**
* @return bool
*/
public function migrateData()
{
return true;
}
/**
* @return bool
* @throws PrestaShopDatabaseException
*/
public function migrateDocuments()
{
$oldLabelsQuery = new DbQuery();
$oldLabelsQuery->select('*')
->from('sonice_etq_label');
$oldLabels = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($oldLabelsQuery);
foreach ($oldLabels as $oldLabel) {
$idColissimoOrder = ColissimoOrder::getIdByOrderId((int) $oldLabel['id_order']);
$colissimoOrder = new ColissimoOrder((int) $idColissimoOrder);
if (!Validate::isLoadedObject($colissimoOrder)) {
$this->logger->error('Invalid ColissimoOrder object', array('id' => $idColissimoOrder));
continue;
}
$colissimoLabel = new ColissimoLabel();
$colissimoLabel->id_colissimo_order = (int) $colissimoOrder->id;
$colissimoLabel->id_colissimo_deposit_slip = 0;
$colissimoLabel->shipping_number = pSQL($oldLabel['parcel_number']);
$colissimoLabel->label_format = 'pdf';
$colissimoLabel->coliship = 0;
$colissimoLabel->return_label = 0;
$colissimoLabel->cn23 = 0;
$colissimoLabel->date_add = pSQL($oldLabel['date_add']);
$colissimoLabel->migration = 1;
$colissimoLabel->insurance = null;
$colissimoLabel->file_deleted = 0;
try {
$colissimoLabel->save(true);
} catch (Exception $e) {
$this->logger->error($e->getMessage());
continue;
}
}
return true;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,53 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
require_once(dirname(__FILE__).'/ColissimoTools.php');
require_once(dirname(__FILE__).'/ColissimoLink.php');
require_once(dirname(__FILE__).'/ColissimoModuleConfiguration.php');
require_once(dirname(__FILE__).'/ColissimoCarrier.php');
require_once(dirname(__FILE__).'/ColissimoService.php');
require_once(dirname(__FILE__).'/ColissimoOrder.php');
require_once(dirname(__FILE__).'/ColissimoLabel.php');
require_once(dirname(__FILE__).'/ColissimoDepositSlip.php');
require_once(dirname(__FILE__).'/ColissimoLabelGenerator.php');
require_once(dirname(__FILE__).'/ColissimoPickupPoint.php');
require_once(dirname(__FILE__).'/ColissimoCartPickupPoint.php');
require_once(dirname(__FILE__).'/ColissimoTrackingCode.php');
require_once(dirname(__FILE__).'/ColissimoOrderCarrier.php');
require_once(dirname(__FILE__).'/ColissimoCustomCategory.php');
require_once(dirname(__FILE__).'/ColissimoCustomProduct.php');
require_once(dirname(__FILE__).'/ColissimoMerchantAddress.php');
require_once(dirname(__FILE__).'/ColissimoACE.php');
require_once(dirname(__FILE__).'/migration/ColissimoOtherModuleInterface.php');
require_once(dirname(__FILE__).'/migration/ColissimoMigration.php');
require_once(dirname(__FILE__).'/migration/ColissimoSoflexibiliteMigration.php');
require_once(dirname(__FILE__).'/migration/ColissimoSoniceEtiquetageMigration.php');
require_once(dirname(__FILE__).'/migration/ColissimoColissimoSimpliciteMigration.php');
require_once(dirname(__FILE__).'/migration/ColissimoSocolissimoMigration.php');
require_once(dirname(__FILE__).'/logger/AbstractColissimoHandler.php');
require_once(dirname(__FILE__).'/logger/ColissimoFileHandler.php');
require_once(dirname(__FILE__).'/logger/ColissimoNullHandler.php');
require_once(dirname(__FILE__).'/logger/ColissimoLogger.php');

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>colissimo</name>
<displayName><![CDATA[Colissimo - Officiel : G&eacute;rer vos exp&eacute;ditions avec Colissimo.]]></displayName>
<version><![CDATA[1.4.0]]></version>
<description><![CDATA[Ce module vous permettra d&rsquo;int&eacute;grer l&rsquo;affichage des points de retrait sur votre site, d&rsquo;imprimer vos &eacute;tiquettes&nbsp;depuis votre back office ou Coliship et&nbsp;de proposer le suivi des exp&eacute;ditions &agrave; vos clients.]]></description>
<author><![CDATA[Colissimo]]></author>
<tab><![CDATA[shipping_logistics]]></tab>
<is_configurable>1</is_configurable>
<need_instance>0</need_instance>
<limited_countries></limited_countries>
</module>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,484 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class AdminColissimoColishipController
*
* Processes:
* - downloadFmt
* - exportCsv
*
*/
class AdminColissimoColishipController extends ModuleAdminController
{
/** @var Colissimo $module */
public $module;
/** @var string $header */
private $header;
//@formatter:off
/** @var array MIME types authorized for CSV files */
private $authorizedFileTypes = array('application/vnd.ms-excel', 'text/csv', 'application/octet-stream', 'text/plain', 'text/comma-separated-values');
//@formatter:on
/**
* AdminColissimoAffranchissementController constructor.
* @throws PrestaShopException
*/
public function __construct()
{
$this->bootstrap = true;
parent::__construct();
$this->module->logger->setChannel('Coliship');
}
/**
* @throws SmartyException
*/
public function initModal()
{
parent::initModal();
$this->modals[] = $this->module->getWhatsNewModal();
}
/**
* @throws Exception
* @throws SmartyException
*/
public function initProcess()
{
$this->header = $this->module->setColissimoControllerHeader();
parent::initProcess();
}
/**
* @param string $file
* @return array|bool
*/
public function parseCsv($file)
{
if (($fd = @fopen($file, 'r')) == false) {
return false;
}
$csv = array();
$headers = fgetcsv($fd, 0, ';');
while (($data = fgetcsv($fd, 0, ';')) !== false) {
$csv[] = array_combine($headers, $data);
}
return $csv;
}
/**
* @return bool|ObjectModel|void
*/
public function postProcess()
{
parent::postProcess();
if (Tools::isSubmit('submitColishipImport')) {
try {
$file = $this->postProcessColishipUpload();
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$this->errors[] = $e->getMessage();
return;
}
$data = $this->parseCsv($file);
$this->importLabels($data);
}
}
/**
* @throws Exception
*/
public function initContent()
{
$modePS = Configuration::get('COLISSIMO_GENERATE_LABEL_PRESTASHOP');
$accessImportShippingNumbers = Tools::getValue('importCsv');
if (!$accessImportShippingNumbers && $modePS) {
//@formatter:off
$this->errors[] = $this->module->l('Colissimo postage mode is set to "PrestaShop". If you want to import & export orders using Coliship, change this setting in Colissimo module.', 'AdminColissimoColishipController');
//@formatter:on
return;
}
if (!ColissimoTools::isValidHsCode(Configuration::get('COLISSIMO_DEFAULT_HS_CODE'))) {
//@formatter:off
$this->warnings[] = $this->module->l('You did not fill a valid HS Code in the Colissimo module configuration. You may encounter errors when importing orders in Coliship.', 'AdminColissimoColishipController');
//@formatter:on
}
$idCurrencyEUR = Currency::getIdByIsoCode('EUR');
if ((int) !$idCurrencyEUR) {
//@formatter:off
$this->warnings[] = $this->module->l('The currency EUR is not installed. This will cause wrong product values in CN23 documents.', 'AdminColissimoColishipController');
//@formatter:on
}
$tmpDirectory = sys_get_temp_dir();
if ($tmpDirectory && Tools::substr($tmpDirectory, -1) != DIRECTORY_SEPARATOR) {
$tmpDirectory .= DIRECTORY_SEPARATOR;
}
$tmpDirectory = realpath($tmpDirectory);
if (!is_writable($tmpDirectory)) {
//@formatter:off
$this->errors[] = sprintf($this->module->l('Please grant write permissions to the temporary directory of your server (%s).', 'AdminColissimoColishipController'), $tmpDirectory);
//@formatter:on
}
$helperUpload = new HelperUploader('coliship_import');
$helperUpload->setId(null);
$helperUpload->setName('coliship_import');
$helperUpload->setUrl(null);
$helperUpload->setMultiple(false);
$helperUpload->setUseAjax(false);
$helperUpload->setMaxFiles(null);
$helperUpload->setFiles(
array(
0 => array(
'type' => HelperUploader::TYPE_FILE,
'size' => null,
'delete_url' => null,
'download_url' => null,
),
)
);
$this->context->smarty->assign(
array(
'helper_upload' => $helperUpload->render(),
'coliship_url' => Colissimo::COLISHIP_URL,
'admin_url' => $this->context->link->getAdminLink('AdminColissimoColiship'),
)
);
if ($accessImportShippingNumbers) {
$this->context->smarty->assign(
array(
'import_csv' => 1,
'csv_path' => _MODULE_DIR_.'colissimo/shippingNumbers.csv',
'img_path' => $this->module->getPathUri().'views/img/',
)
);
}
$this->content = $this->createTemplate('coliship-form.tpl')
->fetch();
$this->content = $this->header.$this->content;
parent::initContent();
}
/**
* @return string
* @throws Exception
*/
public function postProcessColishipUpload()
{
if (!isset($_FILES['coliship_import']['error']) || is_array($_FILES['coliship_import']['error'])) {
throw new Exception($this->module->l('Invalid parameters.', 'AdminColissimoColishipController'));
}
switch ($_FILES['coliship_import']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new Exception($this->module->l('No files sent.', 'AdminColissimoColishipController'));
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new Exception($this->module->l('Exceeded filesize limit.', 'AdminColissimoColishipController'));
default:
throw new Exception($this->module->l('Unknown errors.', 'AdminColissimoColishipController'));
}
$fileType = $_FILES['coliship_import']['type'];
//@formatter:off
if (!in_array($fileType, $this->authorizedFileTypes)) {
$this->module->logger->warning(sprintf('MIME type uploaded: %s', $fileType));
throw new Exception($this->module->l('You must submit CSV files only.', 'AdminColissimoColishipController'));
}
//@formatter:on
$file = _PS_MODULE_DIR_.$this->module->name.'/documents/coliship/'.date('YmdHis').'.csv';
if (!move_uploaded_file($_FILES['coliship_import']['tmp_name'], $file)) {
throw new Exception($this->module->l('Cannot upload .csv file.', 'AdminColissimoColishipController'));
}
return $file;
}
/**
* @param array $data
*/
public function importLabels($data)
{
$result = array_fill_keys(array('success', 'error'), array());
foreach ($data as $i => $label) {
$orders = Order::getByReference($label['ReferenceExpedition']);
if (!$orders->count()) {
$this->module->logger->error('Order ref. '.$label['ReferenceExpedition'].' not found.');
$result['error'][] = sprintf(
$this->module->l('Line %d - Order not found', 'AdminColissimoColishipController'),
$i + 1
);
continue;
}
if (ColissimoLabel::getLabelIdByShippingNumber($label['NumeroColis'])) {
$this->module->logger->error('Label '.$label['NumeroColis'].' already exists.');
$result['error'][] = sprintf(
$this->module->l('Line %d - Label already exists.', 'AdminColissimoColishipController'),
$i + 1
);
continue;
}
try {
/** @var Order $order */
$order = $orders->getFirst();
$colissimoLabel = new ColissimoLabel();
$colissimoLabel->id_colissimo_order = (int) ColissimoOrder::getIdByOrderId($order->id);
$colissimoLabel->id_colissimo_deposit_slip = 0;
$colissimoLabel->shipping_number = pSQL($label['NumeroColis']);
$colissimoLabel->label_format = 'pdf';
$colissimoLabel->return_label = 0;
$colissimoLabel->cn23 = 0;
$colissimoLabel->coliship = 1;
$colissimoLabel->migration = 0;
$colissimoLabel->insurance = null;
$colissimoLabel->file_deleted = 0;
$colissimoLabel->save(true);
$orderCarrier = ColissimoOrderCarrier::getByIdOrder($order->id);
if (Validate::isLoadedObject($orderCarrier) && !$orderCarrier->tracking_number) {
$orderCarrier->tracking_number = pSQL($colissimoLabel->shipping_number);
$orderCarrier->save();
$hash = md5($order->reference.$order->secure_key);
$link = $this->context->link->getModuleLink(
'colissimo',
'tracking',
array('order_reference' => $order->reference, 'hash' => $hash)
);
$isoLangOrder = Language::getIsoById($order->id_lang);
if (isset($this->module->PNAMailObject[$isoLangOrder])) {
$object = $this->module->PNAMailObject[$isoLangOrder];
} else {
$object = $this->module->PNAMailObject['en'];
}
ColissimoTools::sendHandlingShipmentMail(
$order,
sprintf($object, $order->reference),
$link
);
$this->module->logger->info('Send tracking mail for shipment '.$colissimoLabel->shipping_number);
}
if (Configuration::get('COLISSIMO_USE_SHIPPING_IN_PROGRESS')) {
$idShippingInProgressOS = Configuration::get('COLISSIMO_OS_SHIPPING_IN_PROGRESS');
$shippingInProgressOS = new OrderState((int) $idShippingInProgressOS);
if (Validate::isLoadedObject($shippingInProgressOS)) {
if (!$order->getHistory($this->context->language->id, (int) $idShippingInProgressOS)) {
$history = new OrderHistory();
$history->id_order = (int) $order->id;
$history->changeIdOrderState($idShippingInProgressOS, (int) $order->id);
try {
$history->add();
} catch (Exception $e) {
$this->module->logger->error(sprintf('Cannot change status of order #%d', $order->id));
}
}
} else {
$this->module->logger->error('Shipping in Progress order state is not valid');
}
}
} catch (Exception $e) {
$this->module->logger->error('Error thrown: '.$e->getMessage());
$result['error'][] = sprintf(
$this->module->l('Line %d - %s', 'AdminColissimoColishipController'),
$i + 1,
$e->getMessage()
);
continue;
}
$result['success'][] = $colissimoLabel->id;
}
if (!empty($result['error'])) {
$this->errors = $result['error'];
}
if (!empty($result['success'])) {
$this->confirmations = sprintf(
$this->module->l('%d label(s) have been imported successfully', 'AdminColissimoColishipController'),
count($result['success'])
);
}
}
/**
* @return bool
*/
public function processDownloadFmt()
{
$file = $this->module->getLocalPath().'PrestaShop.FMT';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
exit;
} else {
return false;
}
}
/**
* @throws PrestaShopDatabaseException
* @throws Exception
*/
public function processExportCsv()
{
$selectedStates = array_keys(json_decode(Configuration::get('COLISSIMO_GENERATE_LABEL_STATUSES'), true));
$dbQuery = new DbQuery();
//@formatter:off
$dbQuery->select('co.*')
->from('colissimo_order', 'co')
->leftJoin('orders', 'o', 'o.`id_order` = co.`id_order`')
->leftJoin('colissimo_label', 'cola', 'cola.`id_colissimo_order` = co.`id_colissimo_order`');
//@formatter:on
if (!empty($selectedStates)) {
$dbQuery->where('o.`current_state` IN ('.implode(',', array_map('intval', $selectedStates)).')');
}
$dbQuery->where('cola.id_colissimo_label IS NULL'.Shop::addSqlRestriction(false, 'o'));
$dbQuery->orderBy('o.date_add DESC');
$results = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($dbQuery);
$insuredAmountEUR = 0;
$senderAddr = new ColissimoMerchantAddress('sender');
$lines = array();
$exportDetails = array(
'nb_result' => count($results),
'restricted_states' => $selectedStates,
);
$this->module->logger->info('Export CSV', $exportDetails);
foreach ($results as $result) {
$order = new Order((int) $result['id_order']);
$colissimoService = new ColissimoService((int) $result['id_colissimo_service']);
$customerAddr = new Address((int) $order->id_address_delivery);
if ($colissimoService->type == ColissimoService::TYPE_RELAIS) {
$pickupAddr = new ColissimoPickupPoint((int) $result['id_colissimo_pickup_point']);
$ftd = '';
} else {
$pickupAddr = new ColissimoPickupPoint();
$isoCustomerAddress = Country::getIsoById((int) $customerAddr->id_country);
$isoOutreMerFtd = ColissimoTools::$isoOutreMer;
if (($key = array_search('YT', $isoOutreMerFtd)) !== false) {
unset($isoOutreMerFtd[$key]);
}
if (($key = array_search('PM', $isoOutreMerFtd)) !== false) {
unset($isoOutreMerFtd[$key]);
}
$ftd = in_array($isoCustomerAddress, $isoOutreMerFtd) ? 'O' : '';
if ($colissimoService->isInsurable($isoCustomerAddress)) {
if (Configuration::get('COLISSIMO_INSURE_SHIPMENTS')) {
$insuredAmount = $order->total_products;
$insuredAmountEUR = ColissimoTools::convertInEUR(
$insuredAmount,
new Currency($order->id_currency)
);
}
}
}
$customer = new Customer((int) $order->id_customer);
$lineExp = array(
'exp_code' => 'EXP',
'order_reference' => $order->reference,
'exp_company' => $senderAddr->companyName,
'exp_lastname' => $senderAddr->lastName,
'exp_firstname' => $senderAddr->firstName,
'exp_address1' => $senderAddr->line2,
'exp_address2' => $senderAddr->line3,
'exp_address3' => $senderAddr->line0,
'exp_address4' => $senderAddr->line1,
'exp_zipcode' => $senderAddr->zipCode,
'exp_city' => $senderAddr->city,
'exp_iso_country' => $senderAddr->countryCode,
'exp_email' => $senderAddr->email,
'exp_phone' => $senderAddr->phoneNumber,
'dest_company' => $customerAddr->company,
'dest_lastname' => $customerAddr->lastname,
'dest_firstname' => $customerAddr->firstname,
'dest_address1' => $customerAddr->address1,
'dest_address2' => $customerAddr->address2,
'dest_address3' => '',
'dest_address4' => $customerAddr->address2,
'dest_zipcode' => $customerAddr->postcode,
'dest_city' => $customerAddr->city,
'dest_iso_country' => Country::getIsoById($customerAddr->id_country),
'dest_mobile' => $customerAddr->phone_mobile,
'dest_phone' => $customerAddr->phone,
'dest_email' => $customer->email,
'pr_code' => $pickupAddr->colissimo_id,
'product_code' => $colissimoService->product_code,
'ftd' => $ftd,
'iso_lang' => Language::getIsoById($customer->id_lang),
'signature' => $colissimoService->is_signature ? 'O' : 'N',
'weight' => ColissimoTools::getOrderTotalWeightInKg($order) * 1000,
'nature' => ColissimoLabelGenerator::COLISHIP_CATEGORY_COMMERCIAL,
'insurance' => $insuredAmountEUR,
'cpass_id' => ColissimoTools::getCPassIdByOrderId($order->id),
'tag_user' => sprintf('PS%s;%s', _PS_VERSION_, $this->module->version),
);
$lines[] = $lineExp;
$isoCustomerAddress = Country::getIsoById((int) $customerAddr->id_country);
$merchantAddress = new ColissimoMerchantAddress('sender');
if (ColissimoTools::needCN23($merchantAddress->countryCode, $isoCustomerAddress, $customerAddr->postcode)) {
$currency = new Currency((int) $order->id_currency);
$products = $order->getProducts();
foreach ($products as $product) {
$productPriceEUR = ColissimoTools::convertInEUR(
$product['unit_price_tax_excl'],
new Currency($order->id_currency)
);
$productWeight = (float) $product['product_weight'] ? ColissimoTools::weightInKG(
$product['product_weight']
) : 0.05;
$lineCN23 = array(
'cn_code' => 'CN2',
'cn_print' => 'O',
'cn_article_name' => $product['product_name'],
'cn_article_weight' => $productWeight * 1000,
'cn_article_qty' => $product['product_quantity'],
'cn_article_value' => (float) $productPriceEUR,
'cn_article_origin' => 'FR',
'cn_currency' => $currency->iso_code,
'cn_article_ref' => $product['product_reference'],
'cn_hs_code' => Configuration::get('COLISSIMO_DEFAULT_HS_CODE'),
);
$lines[] = $lineCN23;
}
}
}
try {
ColissimoTools::downloadColishipExport($lines);
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
//@formatter:off
$this->errors[] = $this->module->l('Cannot export CSV file. Please check the module logs.', 'AdminColissimoColishipController');
//@formatter:on
}
}
}

View File

@@ -0,0 +1,472 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class AdminColissimoDashboardController
*
* Ajax processes:
* - orderDetails
* - updateOrderTracking
* - updateAllOrderTracking
*
*/
class AdminColissimoDashboardController extends ModuleAdminController
{
/** Time range between which we don't request update for an order */
const TIME_RANGE_UPDATE = 2;
/** @var Colissimo $module */
public $module;
/** @var string $header */
private $header;
/** @var array $ordersToUpdate */
private $ordersToUpdate = array();
/**
* AdminColissimoDashboardController constructor.
* @throws PrestaShopException
*/
public function __construct()
{
$this->bootstrap = true;
parent::__construct();
$this->module->logger->setChannel('Dashboard');
$forceUpdate = Tools::isSubmit('submitUpdateAllTracking') || Tools::getValue('force_update');
$this->setNeedTrackingUpdate($forceUpdate);
//@formatter:off
if (Tools::getValue('total_labels')) {
$this->confirmations[] = sprintf($this->module->l('%d / %d shipment trackings updated successfully.'), Tools::getValue('success_labels'), Tools::getValue('total_labels'), 'AdminColissimoDashboard');
}
//@formatter:on
}
/**
* @throws SmartyException
*/
public function initModal()
{
parent::initModal();
$this->modals[] = $this->module->getWhatsNewModal();
}
/**
* @throws Exception
* @throws SmartyException
*/
public function initProcess()
{
$this->header = $this->module->setColissimoControllerHeader();
$this->initDashboard();
parent::initProcess();
}
/**
* @param bool $isNewTheme
*/
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addJS($this->module->getLocalPath().'views/js/colissimo.dashboard.js');
}
/**
* @throws Exception
* @throws SmartyException
*/
public function initContent()
{
$trackingUpdate = '';
$intro = '';
if (!empty($this->ordersToUpdate)) {
$this->context->smarty->assign(array(
'img_path' => $this->module->getPathUri().'views/img/',
'orders_count' => count($this->ordersToUpdate),
'force_update' => Tools::isSubmit('submitUpdateAllTracking') || Tools::getValue('force_update'),
));
$trackingUpdate = $this->createTemplate('tracking-update.tpl')->fetch();
} else {
$intro = $this->createTemplate('intro.tpl')->fetch();
}
$this->content = $this->header.$intro.$this->content.$trackingUpdate;
parent::initContent();
}
/**
* @throws PrestaShopDatabaseException
*/
public function initDashboard()
{
if (!empty($this->ordersToUpdate)) {
return;
}
$idLang = $this->context->language->id;
$statusesList = array();
$statuses = OrderState::getOrderStates((int) $idLang);
foreach ($statuses as $status) {
$statusesList[$status['id_order_state']] = $status['name'];
}
$colissimoServicesList = array();
$colissimoServices = ColissimoService::getAll();
foreach ($colissimoServices as $colissimoService) {
$colissimoServicesList[$colissimoService['commercial_name']] = $colissimoService['commercial_name'];
}
ksort($colissimoServicesList, SORT_ASC);
$countriesList = array();
$countries = Country::getCountries((int) $idLang);
foreach ($countries as $country) {
$countriesList[$country['id_country']] = $country['name'];
}
$dateTime90Days = new DateTime(date('Y-m-d H:i:s'));
$dateTime90Days->sub(new DateInterval('P90D'));
$select = array(
'o.`reference`',
'o.`id_order`',
'COUNT(cola.`id_colissimo_label`) AS `nb_label`',
'MIN(cola.`date_add`) AS `date_exp`',
'DATEDIFF(NOW(), MIN(cola.`date_add`)) AS `risk_value`',
'CONCAT(IF (o.delivery_date = "0000-00-00 00:00:00", 2, 1), " ", DATEDIFF( NOW(), MIN(cola.date_add))) as `risk`',
'CONCAT(LEFT(c.`firstname`, 1), ". ", c.`lastname`) AS `customer`',
'osl.`name` AS `osname`',
'os.`color`',
'o.`date_add`',
'cs.`commercial_name`',
'cl.`name` AS `country`',
);
//@formatter:off
$join = array(
'LEFT JOIN `'._DB_PREFIX_.'orders` o ON o.`id_order` = a.`id_order`',
'LEFT JOIN `'._DB_PREFIX_.'address` ad ON ad.`id_address` = o.`id_address_delivery`',
'LEFT JOIN `'._DB_PREFIX_.'country` co ON co.`id_country` = ad.`id_country`',
'LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (cl.`id_country` = ad.`id_country` AND cl.`id_lang` = '.(int) $idLang.')',
'LEFT JOIN `'._DB_PREFIX_.'customer` c ON c.`id_customer` = o.`id_customer`',
'LEFT JOIN `'._DB_PREFIX_.'order_state` os ON os.`id_order_state` = o.`current_state`',
'LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (osl.`id_order_state` = os.`id_order_state` AND osl.`id_lang` = '.(int) $idLang.')',
'LEFT JOIN `'._DB_PREFIX_.'colissimo_service` cs ON cs.`id_colissimo_service` = a.`id_colissimo_service`',
'LEFT JOIN `'._DB_PREFIX_.'colissimo_label` cola ON cola.`id_colissimo_order` = a.`id_colissimo_order`',
);
//@formatter:on
$this->identifier = 'id_colissimo_order';
$this->table = 'colissimo_order';
$this->className = 'ColissimoOrder';
$this->list_id = 'colissimo_dashboard';
$this->_select = implode(',', $select);
$this->_join = implode(' ', $join);
$this->_where .= 'AND o.date_add > "'.$dateTime90Days->format('Y-m-d H:i:s').'"';
$this->_where .= Shop::addSqlRestriction(false, 'o');
$this->_group = 'GROUP BY a.`id_colissimo_order`';
$this->_having = ' AND COUNT(cola.`id_colissimo_label`) > 0';
$this->_filterHaving = true;
$this->list_no_link = true;
$this->_orderBy = 'risk';
$this->_orderWay = 'desc';
//@formatter:off
$this->fields_list = array(
'reference' => array(
'title' => $this->module->l('Reference', 'AdminColissimoDashboardController'),
'remove_onclick' => true,
'class' => 'pointer col-reference-plus',
),
'id_order' => array(
'title' => $this->module->l('ID', 'AdminColissimoDashboardController'),
'havingFilter' => true,
'type' => 'int',
'filter_key' => 'o!id_order',
'remove_onclick' => true,
),
'customer' => array(
'title' => $this->module->l('Customer', 'AdminColissimoDashboardController'),
'havingFilter' => true,
'remove_onclick' => true,
),
'date_add' => array(
'title' => $this->module->l('Date', 'AdminColissimoDashboardController'),
'remove_onclick' => true,
'type' => 'datetime',
'filter_key' => 'o!date_add',
),
'osname' => array(
'title' => $this->module->l('Order state', 'AdminColissimoDashboardController'),
'remove_onclick' => true,
'type' => 'select',
'color' => 'color',
'list' => $statusesList,
'filter_key' => 'os!id_order_state',
'filter_type' => 'int',
'order_key' => 'osname',
),
'commercial_name' => array(
'title' => $this->module->l('Colissimo Service', 'AdminColissimoDashboardController'),
'remove_onclick' => true,
'type' => 'select',
'list' => $colissimoServicesList,
'filter_key' => 'cs!commercial_name',
'filter_type' => 'string',
'order_key' => 'commercial_name',
),
'country' => array(
'title' => $this->module->l('Delivery country', 'AdminColissimoDashboardController'),
'remove_onclick' => true,
'type' => 'select',
'list' => $countriesList,
'filter_key' => 'co!id_country',
'filter_type' => 'int',
'order_key' => 'country',
),
'nb_label' => array(
'title' => $this->module->l('Number of', 'AdminColissimoDashboardController').'<br />'.$this->module->l('shipment(s)', 'AdminColissimoDashboardController'),
'remove_onclick' => true,
'align' => 'text-center',
),
'risk' => array(
'title' => $this->module->l('Risk', 'AdminColissimoDashboardController'),
'search' => false,
'remove_onclick' => true,
'align' => 'text-center',
'callback' => 'printRisk',
'class' => 'td-risk',
),
);
//@formatter:on
}
/**
* @param string $risk
* @param array $tr
* @return string
* @throws Exception
* @throws SmartyException
*/
public function printRisk($risk, $tr)
{
$order = new Order((int) $tr['id_order']);
$history = $order->getHistory($this->context->language->id, (int) Configuration::get('PS_OS_DELIVERED'));
if ($history) {
$flag = 0;
} else {
$flag = (int) $tr['risk_value'] > 2 ? 1 : 0;
}
$this->context->smarty->assign(array('flag' => $flag, 'tr' => $tr));
return $this->createTemplate('print-risk.tpl')->fetch();
}
/**
* @param bool $forceUpdate
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function setNeedTrackingUpdate($forceUpdate = false)
{
if (!$forceUpdate && Configuration::get('COLISSIMO_LAST_TRACKING_UPDATE')) {
$dateTime = new DateTime(date('Y-m-d H:i:s'));
$dateTime->sub(new DateInterval('PT'.self::TIME_RANGE_UPDATE.'H'));
$dateTimeLastUpdate = new DateTime(Configuration::get('COLISSIMO_LAST_TRACKING_UPDATE'));
$diff = (int) $dateTime->getTimestamp() - $dateTimeLastUpdate->getTimestamp();
if ($diff < 0) {
return;
}
}
$filteredStatuses = Configuration::getMultiple(array('PS_OS_DELIVERED', 'PS_OS_ERROR', 'PS_OS_CANCELED'));
$dateTime = new DateTime(date('Y-m-d H:i:s'));
if ($forceUpdate) {
$dateTime->sub(new DateInterval('P90D'));
$this->module->logger->info('Update tracking up to 90 days ago.');
} else {
$dateTime->sub(new DateInterval('P15D'));
$this->module->logger->info('Update tracking up to 15 days ago.');
}
$dateAdd = $dateTime->format('Y-m-d H:i:s');
$dbQuery = new DbQuery();
$dbQuery->select('cola.id_colissimo_label')
->from('colissimo_label', 'cola')
->leftJoin('colissimo_order', 'co', 'co.id_colissimo_order = cola.id_colissimo_order')
->leftJoin('orders', 'o', 'o.id_order = co.id_order')
->where('o.current_state NOT IN('.implode(',', array_map('intval', $filteredStatuses)).')')
->where('cola.date_add > "'.pSQL($dateAdd).'"')
->where('cola.return_label = 0'.Shop::addSqlRestriction(false, 'o'));
$labelIds = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($dbQuery);
if (is_array($labelIds) && !empty($labelIds)) {
$this->ordersToUpdate = array_map(
function ($element) {
return $element['id_colissimo_label'];
},
$labelIds
);
}
}
/**
* @throws Exception
* @throws SmartyException
*/
public function ajaxProcessOrderDetails()
{
$idColissimoOrder = Tools::getValue('id_colissimo_order');
$nbColumn = Tools::getValue('nb_col');
$this->module->assignColissimoOrderVariables((int) $idColissimoOrder, 'Dashboard');
$content = $this->context->smarty->fetch(sprintf(
'extends:%s|%s',
$this->module->getLocalPath().'views/templates/admin/admin_order/legacy/dashboard-layout-block.tpl',
$this->module->getLocalPath().'views/templates/admin/admin_order/legacy/order-detail.tpl'
));
$this->context->smarty->assign(array(
'id_colissimo_order' => $idColissimoOrder,
'nb_col' => $nbColumn,
'order_resume_content_html' => $content,
));
$html = $this->createTemplate('_partials/td-order-resume.tpl')->fetch();
$this->ajaxDie(
json_encode(
array(
'text' => 'ok',
'html' => $html,
)
)
);
}
/**
* @throws Exception
* @throws PrestaShopDatabaseException
* @throws SmartyException
*/
public function ajaxProcessUpdateOrderTracking()
{
if (Tools::getValue('channel')) {
$this->module->logger->setChannel(Tools::getValue('channel'));
}
$colissimoOrder = new ColissimoOrder((int) Tools::getValue('id_colissimo_order'));
$this->module->logger->info('Update tracking for order #'.$colissimoOrder->id_order);
if (!Validate::isLoadedObject($colissimoOrder)) {
$return = array(
'errors' => true,
'message' => $this->module->l('Cannot update order tracking.', 'AdminColissimoDashboardController'),
);
$this->ajaxDie(json_encode($return));
die();
}
$errors = array();
$success = array();
$labelIds = $colissimoOrder->getLabelIds();
foreach ($labelIds as $labelId) {
$colissimoLabel = new ColissimoLabel((int) $labelId);
try {
$return = $this->module->updateOrderTracking($colissimoLabel);
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$errors[] = $e->getMessage();
continue;
}
$success[] = $return;
}
$shipments = $colissimoOrder->getShipments($this->context->language->id);
$this->context->smarty->assign(array('shipments' => $shipments, 'id_colissimo_order' => $colissimoOrder->id));
$theme = Tools::getValue('newTheme') ? 'new_theme' : 'legacy';
if ($this->module->boTheme == 'legacy') {
$theme = 'legacy';
}
$html = $this->context->smarty->fetch($this->module->getLocalPath().'views/templates/admin/admin_order/'.$theme.'/_shipments.tpl');
$return = array(
'errors' => $errors,
'success' => $success,
'html' => $html,
);
$this->ajaxDie(json_encode($return));
}
/**
* @throws Exception
* @throws PrestaShopDatabaseException
* @throws SmartyException
*/
public function ajaxProcessUpdatePostageVisibility()
{
$colissimoOrder = new ColissimoOrder((int) Tools::getValue('id_colissimo_order'));
if (!Validate::isLoadedObject($colissimoOrder)) {
$return = array(
'errors' => true,
'message' => $this->module->l('Cannot load Colissimo Order', 'AdminColissimoDashboardController'),
);
$this->ajaxDie(json_encode($return));
}
if (Tools::getValue('channel')) {
$this->module->logger->setChannel(Tools::getValue('channel'));
}
$colissimoOrder->hidden = 0;
try {
$colissimoOrder->save();
} catch (Exception $e) {
$return = array(
'errors' => true,
'message' => $this->module->l('Cannot update Colissimo Order', 'AdminColissimoDashboardController'),
);
$this->ajaxDie(json_encode($return));
}
$return = array(
'errors' => false,
'message' => $this->module->l('Successful update', 'AdminColissimoDashboardController'),
);
$this->ajaxDie(json_encode($return));
}
/**
*
*/
public function ajaxProcessUpdateAllOrderTracking()
{
$totalLabels = count($this->ordersToUpdate);
$successLabels = 0;
$this->module->logger->info(
sprintf('Labels to update (%d)', count($this->ordersToUpdate)),
$this->ordersToUpdate
);
foreach ($this->ordersToUpdate as $key => $labelId) {
$this->module->logger->info(sprintf('Update label #%d (%d/%d)', $labelId, $key + 1, $totalLabels));
$colissimoLabel = new ColissimoLabel((int) $labelId);
try {
$this->module->updateOrderTracking($colissimoLabel);
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
continue;
}
$successLabels++;
}
Configuration::updateValue('COLISSIMO_LAST_TRACKING_UPDATE', date('Y-m-d H:i:s'));
$this->ajaxDie(
json_encode(
array(
'total_labels' => $totalLabels,
'success_labels' => $successLabels,
)
)
);
}
}

View File

@@ -0,0 +1,579 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class AdminColissimoDepositSlipController
*
* Ajax processes:
* - generateDepositSlip
* - displayResult
*
* Processes:
* - download
* - downloadSelected
* - delete
*
*/
class AdminColissimoDepositSlipController extends ModuleAdminController
{
/** @var Colissimo $module */
public $module;
/** @var string $header */
public $header;
/** @var string $html */
public $html;
/** @var string $page */
public $page;
/** @var ColissimoGenerateBordereauRequest $depositSlipRequest */
public $depositSlipRequest;
/**
* AdminColissimoDepositSlipController constructor.
* @throws Exception
* @throws PrestaShopException
*/
public function __construct()
{
$this->bootstrap = true;
$this->className = 'ColissimoDepositSlip';
parent::__construct();
$this->module->logger->setChannel('DepositSlip');
$this->initPage();
}
/**
* @throws SmartyException
*/
public function initModal()
{
parent::initModal();
$this->modals[] = $this->module->getWhatsNewModal();
}
/**
*
*/
public function initPage()
{
$this->page = Tools::getValue('render');
if (!$this->page) {
$this->page = 'form';
}
if (Tools::isSubmit('submitBulkprintSelectedcolissimo_deposit_slip')) {
$this->action = 'downloadSelected';
}
}
private function formatLabelData(&$labels)
{
foreach ($labels as $key => &$label) {
$orderState = new OrderState((int) $label['current_state'], $this->context->language->id);
$label['state_color'] = Tools::getBrightness($orderState->color) < 128 ? 'white' : '#383838';
$label['state_bg'] = $orderState->color;
$label['state_name'] = $orderState->name;
}
}
/**
* @throws Exception
* @throws SmartyException
*/
public function initForm()
{
$select = array(
'col.`id_colissimo_label`',
'col.`id_colissimo_order`',
'col.`date_add` AS label_date_add',
'col.`shipping_number`',
'o.`id_order`',
'o.`current_state`',
'o.`date_add` AS order_date_add',
'o.`reference`',
'CONCAT(a.`lastname`, " ", a.`firstname`) AS customer',
);
$excludedStatuses = array(
Configuration::get('PS_OS_CANCELED'),
);
$parcelOfTheDayQuery = new DbQuery();
//@formatter:off
$parcelOfTheDayQuery->select(implode(',', $select))
->from('colissimo_label', 'col')
->leftJoin('colissimo_order', 'cor', 'cor.`id_colissimo_order` = col.`id_colissimo_order`')
->leftJoin('orders', 'o', 'o.`id_order` = cor.`id_order`')
->leftJoin('address', 'a', 'a.`id_address` = o.`id_address_delivery`')
->where('col.`return_label` = 0')
->where('col.`id_colissimo_deposit_slip` = 0')
->where('o.current_state NOT IN('.implode(',', array_map('intval', $excludedStatuses)).')')
->where('col.date_add > "'.date('Y-m-d 00:00:00').'"')
->orderBy('col.date_add DESC');
//@formatter:on
$parcelOfTheDay = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($parcelOfTheDayQuery);
$olderParcelsQuery = new DbQuery();
//@formatter:off
$olderParcelsQuery->select(implode(',', $select))
->from('colissimo_label', 'col')
->leftJoin('colissimo_order', 'cor', 'cor.`id_colissimo_order` = col.`id_colissimo_order`')
->leftJoin('orders', 'o', 'o.`id_order` = cor.`id_order`')
->leftJoin('address', 'a', 'a.`id_address` = o.`id_address_delivery`')
->where('col.`return_label` = 0')
->where('col.`id_colissimo_deposit_slip` = 0')
->where('o.current_state NOT IN('.implode(',', array_map('intval', $excludedStatuses)).')')
->where('col.date_add <= "'.date('Y-m-d 00:00:00').'"')
->orderBy('col.date_add DESC');
//@formatter:on
$olderParcels = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($olderParcelsQuery);
$this->formatLabelData($parcelOfTheDay);
$this->formatLabelData($olderParcels);
$this->context->smarty->assign(
array(
'labels_of_the_day' => $parcelOfTheDay,
'older_labels' => $olderParcels,
)
);
$this->html = $this->createTemplate('deposit-slip-form.tpl')
->fetch();
}
/**
* @throws Exception
* @throws SmartyException
*/
public function initHistory()
{
$this->identifier = 'id_colissimo_deposit_slip';
$this->table = 'colissimo_deposit_slip';
//@formatter:off
$this->toolbar_title = $this->module->l('Colissimo deposit slip history', 'AdminColissimoDepositSlipController');
//@formatter:on
$this->list_id = 'colissimo-deposit-slip-history';
$this->list_no_link = true;
$this->list_simple_header = false;
$this->actions = array('print', 'delete');
$this->shopLinkType = false;
$this->show_toolbar = true;
$this->token = Tools::getAdminTokenLite('AdminColissimoDepositSlip');
$this->_select = 'a.id_colissimo_deposit_slip, a.number, a.nb_parcel, a.date_add';
$this->_where = 'AND a.file_deleted = 0';
$this->_orderBy = 'a.date_add';
$this->_orderWay = 'DESC';
$this->fields_list = array(
'number' => array(
'title' => $this->module->l('Deposit slip #', 'AdminColissimoDepositSlipController'),
),
'nb_parcel' => array(
'title' => $this->module->l('Parcels count', 'AdminColissimoDepositSlipController'),
),
'date_add' => array(
'title' => $this->module->l('Creation date', 'AdminColissimoDepositSlipController'),
'type' => 'datetime',
),
);
$this->html = $this->createTemplate('deposit-slip-history.tpl')
->fetch();
}
/**
* @throws Exception
* @throws SmartyException
*/
public function initProcess()
{
$this->header = $this->module->setColissimoControllerHeader();
$this->context->smarty->assign('page_selected', $this->page);
if (method_exists($this, 'init'.Tools::toCamelCase($this->page))) {
$this->{'init'.$this->page}();
}
parent::initProcess();
}
/**
* @param bool $isNewTheme
*/
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
$this->addJqueryPlugin('typewatch');
$this->addCSS($this->module->getLocalPath().'views/css/datatables.min.css');
$this->addJS($this->module->getLocalPath().'views/js/datatables.min.js');
$this->addJS($this->module->getLocalPath().'views/js/colissimo.depositslip.js');
$isoLang = Language::getIsoById($this->context->language->id) == 'fr' ? 'fr' : 'en';
Media::addJsDef(array(
'datatables_lang_file' => $this->module->getPathUri().sprintf('DataTables_%s.json', $isoLang),
'datatables_url' => $this->context->link->getAdminLink('AdminColissimoDepositSlip'),
'orders_url' => $this->context->link->getAdminLink('AdminOrders'),
'label_selection_text' => $this->module->l('Label scanned successfully.', 'AdminColissimoDepositSlipController'),
));
}
/**
* @param string $url
*/
public function setRedirectAfter($url)
{
parent::setRedirectAfter($url.'&render='.$this->page);
}
/**
* @return false|ObjectModel|void
* @throws PrestaShopException
*/
public function processDelete()
{
parent::processDelete();
$this->setRedirectAfter(self::$currentIndex.'&conf=1&token='.$this->token);
}
/**
*
*/
public function initContent()
{
//@formatter:off
if (extension_loaded('soap') == false) {
$this->warnings[] = $this->module->l('You need to enable the SOAP extension to generate deposit slips.', 'AdminColissimoDepositSlipController');
}
//@formatter:on
$this->content = $this->header.$this->html;
parent::initContent();
}
/**
* @param Helper $helper
*/
public function setHelperDisplay(Helper $helper)
{
parent::setHelperDisplay($helper);
$this->helper->currentIndex .= '&render=history';
$this->helper->force_show_bulk_actions = true;
}
/**
* @param int $idLang
* @param null $orderBy
* @param null $orderWay
* @param int $start
* @param null $lim
* @param bool $idLangShop
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function getList($idLang, $orderBy = null, $orderWay = null, $start = 0, $lim = null, $idLangShop = false)
{
parent::getList($idLang, $orderBy, $orderWay, $start, $lim, $idLangShop);
if ($this->_listTotal > 0) {
$this->bulk_actions = array(
'printSelected' => array(
'text' => $this->module->l('Print selected', 'AdminColissimoDepositSlipController'),
'icon' => 'icon-print',
),
);
}
}
/**
*
*/
public function processDownload()
{
$idDepositSlip = Tools::getValue('id_deposit_slip');
$depositSlip = new ColissimoDepositSlip((int) $idDepositSlip);
if (Validate::isLoadedObject($depositSlip)) {
try {
$depositSlip->download();
} catch (Exception $e) {
$this->errors[] = $e->getMessage();
}
}
}
/**
*
*/
public function processDownloadSelected()
{
$depositSlipIds = Tools::getValue('colissimo-deposit-slip-historyBox');
if ($depositSlipIds) {
$files = array();
foreach ($depositSlipIds as $depositSlipId) {
$depositSlip = new ColissimoDepositSlip((int) $depositSlipId);
if (Validate::isLoadedObject($depositSlip)) {
$files[] = $depositSlip;
}
}
$filename = 'colissimo_deposit_slips_'.date('Ymd_His').'.zip';
try {
ColissimoTools::downloadDocuments($files, $filename);
} catch (Exception $e) {
$this->module->logger->error(sprintf('Error while downloading zip: %s', $e->getMessage()));
//@formatter:off
$this->context->controller->errors[] = $this->module->l('Cannot generate zip file.', 'AdminColissimoDepositSlipController');
//@formatter:on
}
}
}
/**
* @param array $parcelNumbers
* @return int
* @throws Exception
*/
public function generateDepositSlip($parcelNumbers)
{
$this->depositSlipRequest = new ColissimoGenerateBordereauRequest(ColissimoTools::getCredentials());
$this->depositSlipRequest->setParcelsNumbers($parcelNumbers);
$this->module->logger->infoXml('Log XML request', $this->depositSlipRequest->getRequest(true));
$client = new ColissimoClient();
$client->setRequest($this->depositSlipRequest);
/** @var ColissimoGenerateBordereauResponse $response */
$response = $client->request();
if (!$response->messages[0]['id']) {
$filename = str_pad($response->bordereauHeader['bordereauNumber'], 8, '0', STR_PAD_LEFT);
$filename .= date('YmdHis').'.pdf';
$depositSlip = new ColissimoDepositSlip();
$depositSlip->filename = pSQL($filename);
$depositSlip->number = (int) $response->bordereauHeader['bordereauNumber'];
$depositSlip->nb_parcel = (int) $response->bordereauHeader['numberOfParcels'];
$depositSlip->file_deleted = 0;
$depositSlip->save();
$depositSlip->writeDepositSlip(base64_decode($response->bordereau));
return (int) $depositSlip->id;
} else {
$message = $response->messages[0];
throw new Exception(sprintf('%s (%s) - %s', $message['id'], $message['type'], $message['messageContent']));
}
}
/**
* @param string $token
* @param int $id
* @param string $name
* @return string
* @throws Exception
* @throws SmartyException
*/
public function displayPrintLink($token, $id, $name)
{
$this->context->smarty->assign(
array(
'token' => $token,
'id' => $id,
'name' => $name,
)
);
return $this->createTemplate('_partials/deposit-slip-print-action.tpl')
->fetch();
}
/**
* @throws PrestaShopDatabaseException
*/
public function ajaxProcessListParcelsOfToday()
{
$select = array(
'col.`id_colissimo_label`',
'col.`id_colissimo_order`',
'col.`date_add` AS label_date_add',
'col.`shipping_number`',
'o.`id_order`',
'o.`current_state`',
'o.`date_add` AS order_date_add',
'o.`reference`',
'CONCAT(a.`lastname`, " ", a.`firstname`) AS customer',
);
$excludedStatuses = array(
Configuration::get('PS_OS_CANCELED'),
);
$parcelOfTheDayQuery = new DbQuery();
//@formatter:off
$parcelOfTheDayQuery->select(implode(',', $select))
->from('colissimo_label', 'col')
->leftJoin('colissimo_order', 'cor', 'cor.`id_colissimo_order` = col.`id_colissimo_order`')
->leftJoin('orders', 'o', 'o.`id_order` = cor.`id_order`')
->leftJoin('address', 'a', 'a.`id_address` = o.`id_address_delivery`')
->where('col.`return_label` = 0')
->where('col.`id_colissimo_deposit_slip` = 0')
->where('o.current_state NOT IN('.implode(',', array_map('intval', $excludedStatuses)).')')
->where('col.date_add > "'.date('Y-m-d 00:00:00').'"')
->orderBy('col.date_add DESC');
//@formatter:on
$parcelOfTheDay = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($parcelOfTheDayQuery);
$this->formatLabelData($parcelOfTheDay);
$parcelOfTheDay = array('data' => $parcelOfTheDay);
die(json_encode($parcelOfTheDay));
}
/**
* @throws PrestaShopDatabaseException
*/
public function ajaxProcessListOlderParcels()
{
$select = array(
'col.`id_colissimo_label`',
'col.`id_colissimo_order`',
'col.`date_add` AS label_date_add',
'col.`shipping_number`',
'o.`id_order`',
'o.`current_state`',
'o.`date_add` AS order_date_add',
'o.`reference`',
'CONCAT(a.`lastname`, " ", a.`firstname`) AS customer',
);
$excludedStatuses = array(
Configuration::get('PS_OS_CANCELED'),
);
$dateAddFrom = new DateTime();
$dateAddFrom->sub(new DateInterval('P90D'));
$olderParcelsQuery = new DbQuery();
//@formatter:off
$olderParcelsQuery->select(implode(',', $select))
->from('colissimo_label', 'col')
->leftJoin('colissimo_order', 'cor', 'cor.`id_colissimo_order` = col.`id_colissimo_order`')
->leftJoin('orders', 'o', 'o.`id_order` = cor.`id_order`')
->leftJoin('address', 'a', 'a.`id_address` = o.`id_address_delivery`')
->where('col.`return_label` = 0')
->where('col.`id_colissimo_deposit_slip` = 0')
->where('o.current_state NOT IN('.implode(',', array_map('intval', $excludedStatuses)).')')
->where('col.date_add >= "'.$dateAddFrom->format('Y-m-d H:i:s').'" AND col.date_add < "'.date('Y-m-d').' 00:00:00"')
->orderBy('col.date_add DESC');
//@formatter:on
$olderParcels = Db::getInstance(_PS_USE_SQL_SLAVE_)
->executeS($olderParcelsQuery);
$this->formatLabelData($olderParcels);
$olderParcels = array('data' => $olderParcels);
die(json_encode($olderParcels));
}
/**
*
*/
public function ajaxProcessGenerateDepositSlip()
{
$this->module->logger->setChannel('GenerateDepositSlip');
$labelIds = json_decode(Tools::getValue('label_ids'), true);
$parcelNumbers = array();
foreach ($labelIds as $labelId) {
$label = new ColissimoLabel((int) $labelId);
$parcelNumbers[] = $label->shipping_number;
}
try {
$idDepositSlip = $this->generateDepositSlip($parcelNumbers);
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$return = array(
'error' => true,
'result_html' => $this->module->displayError($e->getMessage()),
'depositSlipId' => 0,
);
$this->ajaxDie(json_encode($return));
}
$data = array('id_colissimo_deposit_slip' => (int) $idDepositSlip);
$where = 'id_colissimo_label IN ('.implode(',', array_map('intval', $labelIds)).')';
Db::getInstance()
->update('colissimo_label', $data, $where);
if (Configuration::get('COLISSIMO_USE_HANDLED_BY_CARRIER')) {
foreach ($labelIds as $labelId) {
$label = new ColissimoLabel((int) $labelId);
$colissimoOrder = new ColissimoOrder((int) $label->id_colissimo_order);
$idOrder = $colissimoOrder->id_order;
$order = new Order((int) $idOrder);
$idHandledByCarrierOS = Configuration::get('COLISSIMO_OS_HANDLED_BY_CARRIER');
$handledByCarrierOS = new OrderState((int) $idHandledByCarrierOS);
if (Validate::isLoadedObject($handledByCarrierOS)) {
if (!$order->getHistory($this->context->language->id, (int) $idHandledByCarrierOS) &&
$order->current_state != $idHandledByCarrierOS
) {
$history = new OrderHistory();
$history->id_order = (int) $order->id;
$history->changeIdOrderState($idHandledByCarrierOS, (int) $order->id);
try {
$history->add();
} catch (Exception $e) {
$this->module->logger->error(sprintf('Cannot change status of order #%d', $order->id));
}
}
} else {
$this->module->logger->error('Handled by Carrier order state is not valid');
}
}
}
$return = array(
'error' => false,
'message' => '',
'depositSlipId' => $idDepositSlip,
);
$this->ajaxDie(json_encode($return));
}
/**
* @throws Exception
* @throws SmartyException
*/
public function ajaxProcessDisplayResult()
{
$this->module->logger->setChannel('DisplayDepositSlip');
$depositSlipIds = json_decode(Tools::getValue('deposit_slip_ids'), true);
$data = array();
$labelIds = array();
foreach ($depositSlipIds as $depositSlipId) {
$depositSlip = new ColissimoDepositSlip((int) $depositSlipId);
$data[(int) $depositSlipId] = array(
'number' => $depositSlip->number,
);
$labelIds += array_map(
function ($element) {
return $element['id_colissimo_label'];
},
$depositSlip->getLabelIds()
);
}
$this->context->smarty->assign(array('data' => $data, 'nb_deposit_slip' => count($data)));
$html = $this->createTemplate('_partials/deposit-slip-result.tpl')
->fetch();
$return = array(
'error' => false,
'message' => '',
'result_html' => $html,
'label_ids' => $labelIds,
);
$this->ajaxDie(json_encode($return));
}
}

View File

@@ -0,0 +1,733 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class AdminColissimoLabelController
*
* Ajax processes:
* - generateReturn
*
* Processes:
* - downloadLabel
* - viewLabel
* - downloadCN23
* - viewCN23
* - downloadAllLabels
* - downloadAllReturnLabels
* - downloadAllCN23
* - deletePDFDocuments
* - printAllDocuments
*
*/
class AdminColissimoLabelController extends ModuleAdminController
{
/** @var Colissimo $module */
public $module;
/**
*
*/
public function processDownloadLabel()
{
$idLabel = (int) Tools::getValue('id_label');
$colissimoLabel = new ColissimoLabel((int) $idLabel);
if (Validate::isLoadedObject($colissimoLabel)) {
try {
$colissimoLabel->download();
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
//@formatter:off
$this->errors[] = $this->module->l('Label download failed. Please check the module logs.', 'AdminColissimoLabelController');
//@formatter:on
}
}
}
/**
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function processViewLabel()
{
$idLabel = (int) Tools::getValue('id_label');
$colissimoLabel = new ColissimoLabel((int) $idLabel);
if (Validate::isLoadedObject($colissimoLabel)) {
try {
$colissimoLabel->view();
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
//@formatter:off
$this->errors[] = $this->module->l('Label view failed. Please check the module logs.', 'AdminColissimoLabelController');
//@formatter:on
}
}
}
/**
*
*/
public function processDownloadCN23()
{
$idLabel = (int) Tools::getValue('id_label');
$colissimoLabel = new ColissimoLabel((int) $idLabel);
if (Validate::isLoadedObject($colissimoLabel)) {
try {
$colissimoLabel->downloadCN23();
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
//@formatter:off
$this->errors[] = $this->module->l('CN23 download failed. Please check the module logs.', 'AdminColissimoLabelController');
//@formatter:on
}
}
}
/**
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function processViewCN23()
{
$idLabel = (int) Tools::getValue('id_label');
$colissimoLabel = new ColissimoLabel((int) $idLabel);
if (Validate::isLoadedObject($colissimoLabel)) {
try {
$colissimoLabel->viewCN23();
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
//@formatter:off
$this->errors[] = $this->module->l('CN23 view failed. Please check the module logs.', 'AdminColissimoLabelController');
//@formatter:on
}
}
}
/**
*
*/
public function processDownloadDocuments()
{
$fileType = Tools::getValue('colissimo_file_type');
$labelIds = Tools::getValue('colissimo_label_ids');
$labelIds = json_decode($labelIds);
switch ($fileType) {
case 'labels':
$documents = $this->getAllLabels($labelIds);
$filename = 'colissimo_labels_'.date('Ymd_His').'.zip';
try {
ColissimoTools::downloadDocuments($documents['label'], $filename);
} catch (Exception $e) {
$this->module->logger->error(sprintf('Error while downloading zip: %s', $e->getMessage()));
//@formatter:off
$this->context->controller->errors[] = $this->module->l('Cannot generate zip file.', 'AdminColissimoLabelController');
//@formatter:on
}
break;
case 'return_labels':
$documents = $this->getAllReturnLabels($labelIds);
$filename = 'colissimo_return_labels_'.date('Ymd_His').'.zip';
try {
ColissimoTools::downloadDocuments($documents['label'], $filename);
} catch (Exception $e) {
$this->module->logger->error(sprintf('Error while downloading zip: %s', $e->getMessage()));
//@formatter:off
$this->context->controller->errors[] = $this->module->l('Cannot generate zip file.', 'AdminColissimoLabelController');
//@formatter:on
}
break;
case 'cn23':
$documents = $this->getAllCN23($labelIds);
$filename = 'colissimo_cn23_'.date('Ymd_His').'.zip';
//@formatter:off
if (!ColissimoTools::downloadCN23Documents($documents['cn23'], $filename)) {
$this->context->controller->errors[] = $this->module->l('Cannot generate zip file.', 'AdminColissimoLabelController');
}
//@formatter:on
break;
case 'all':
default:
$documents = $this->getAllDocuments($labelIds);
$filename = 'colissimo_documents_'.date('Ymd_His').'.zip';
try {
ColissimoTools::downloadAllDocuments($documents, $filename);
} catch (Exception $e) {
$this->module->logger->error(sprintf('Error while downloading zip: %s', $e->getMessage()));
//@formatter:off
$this->context->controller->errors[] = $this->module->l('Cannot generate zip file.', 'AdminColissimoLabelController');
//@formatter:on
}
break;
}
}
/**
* @param array $labelIds
* @param bool $pdfOnly
* @return array
*/
public function getAllLabels($labelIds, $pdfOnly = false)
{
$documents = array('label' => array());
foreach ($labelIds as $labelId) {
try {
$colissimoLabel = new ColissimoLabel((int) $labelId);
if (Validate::isLoadedObject($colissimoLabel)) {
if (!$pdfOnly || $colissimoLabel->label_format == 'pdf') {
$documents['label'][] = $colissimoLabel;
}
}
} catch (Exception $e) {
continue;
}
}
return $documents;
}
/**
* @param array $labelIds
* @param bool $pdfOnly
* @return array
*/
public function getAllThermalLabels($labelIds)
{
$documents = array('label' => array());
foreach ($labelIds as $labelId) {
try {
$colissimoLabel = new ColissimoLabel((int) $labelId);
if (Validate::isLoadedObject($colissimoLabel)) {
if ($colissimoLabel->label_format != 'pdf') {
$documents['label'][] = $colissimoLabel;
}
}
} catch (Exception $e) {
continue;
}
}
return $documents;
}
/**
* @param array $labelIds
* @return array
*/
public function getAllReturnLabels($labelIds)
{
$documents = array('label' => array());
foreach ($labelIds as $labelId) {
try {
$colissimoLabel = new ColissimoLabel((int) $labelId);
if (Validate::isLoadedObject($colissimoLabel)) {
$returnLabelId = $colissimoLabel->getReturnLabelId();
if ($returnLabelId) {
$returnLabel = new ColissimoLabel((int) $returnLabelId);
if (Validate::isLoadedObject($returnLabel)) {
$documents['label'][] = $returnLabel;
}
}
}
} catch (Exception $e) {
continue;
}
}
return $documents;
}
/**
* @param array $labelIds
* @return array
*/
public function getAllCN23($labelIds)
{
$documents = array('cn23' => array());
foreach ($labelIds as $labelId) {
try {
$colissimoLabel = new ColissimoLabel((int) $labelId);
if (Validate::isLoadedObject($colissimoLabel)) {
if ($colissimoLabel->cn23) {
$documents['cn23'][] = $colissimoLabel;
}
$returnLabelId = $colissimoLabel->getReturnLabelId();
if ($returnLabelId) {
$returnLabel = new ColissimoLabel((int) $returnLabelId);
if (Validate::isLoadedObject($returnLabel)) {
if ($returnLabel->cn23) {
$documents['cn23'][] = $returnLabel;
}
}
}
}
} catch (Exception $e) {
continue;
}
}
return $documents;
}
/**
* @param array $labelIds
* @param bool $pdfOnly
* @return array
*/
public function getAllDocuments($labelIds, $pdfOnly = false)
{
$documents = array(
'label' => array(),
'cn23' => array(),
);
foreach ($labelIds as $labelId) {
try {
$colissimoLabel = new ColissimoLabel((int) $labelId);
if (Validate::isLoadedObject($colissimoLabel)) {
if (!$pdfOnly || $colissimoLabel->label_format == 'pdf') {
$documents['label'][] = $colissimoLabel;
}
if ($colissimoLabel->cn23) {
$documents['cn23'][] = $colissimoLabel;
}
$returnLabelId = $colissimoLabel->getReturnLabelId();
if ($returnLabelId) {
$returnLabel = new ColissimoLabel((int) $returnLabelId);
if (Validate::isLoadedObject($returnLabel)) {
$documents['label'][] = $returnLabel;
if ($returnLabel->cn23) {
$documents['cn23'][] = $returnLabel;
}
}
}
}
} catch (Exception $e) {
continue;
}
}
return $documents;
}
/**
* @throws Exception
* @throws PrestaShopDatabaseException
* @throws SmartyException
*/
public function ajaxProcessGenerateReturn()
{
$colissimoLabel = new ColissimoLabel((int) Tools::getValue('id_colissimo_label'));
$colissimoOrder = new ColissimoOrder((int) $colissimoLabel->id_colissimo_order);
$order = new Order((int) $colissimoOrder->id_order);
$customerAddress = new Address((int) $order->id_address_delivery);
$merchantAddress = ColissimoMerchantAddress::getMerchantReturnAddress();
$customerCountry = $customerAddress->id_country;
$returnDestinationType = ColissimoTools::getReturnDestinationTypeByIdCountry($customerCountry);
if ($returnDestinationType === false) {
//@formatter:off
$return = array(
'id' => false,
'error' => true,
'message' => $this->module->l('Cannot edit return label for this destination.', 'AdminColissimoLabelController'),
'cn23' => false,
);
//@formatter:on
$this->ajaxDie(json_encode($return));
}
$idService = ColissimoService::getServiceIdByIdCarrierDestinationType(0, $returnDestinationType);
$data = array(
'order' => $order,
'version' => $this->module->version,
'cart' => new Cart((int) $order->id_cart),
'customer' => new Customer((int) $order->id_customer),
'colissimo_order' => $colissimoOrder,
'colissimo_service' => new ColissimoService((int) $idService),
'colissimo_service_initial' => new ColissimoService((int) $colissimoOrder->id_colissimo_service),
'customer_addr' => $customerAddress,
'merchant_addr' => $merchantAddress,
'form_options' => array(
'insurance' => 0,
'ta' => 0,
'd150' => 0,
'weight' => ColissimoTools::getOrderTotalWeightInKg($order),
'mobile_phone' => $merchantAddress->phoneNumber,
),
);
$colissimoReturnLabel = false;
try {
$this->module->labelGenerator->setData($data);
$colissimoReturnLabel = $this->module->labelGenerator->generateReturn($colissimoLabel);
} catch (Exception $e) {
$this->module->logger->error('Exception throw while generating return label.', $e->getMessage());
$return = array(
'id' => false,
'error' => true,
'message' => $e->getMessage(),
'cn23' => false,
);
$this->ajaxDie(json_encode($return));
}
$warningMessage = false;
if (Tools::getValue('send_mail') && Validate::isLoadedObject($colissimoReturnLabel)) {
try {
$iso = Language::getIsoById($order->id_lang);
$iso = isset($this->module->returnLabelMailObject[$iso]) ? $iso : 'en';
ColissimoTools::sendReturnLabelMail($colissimoReturnLabel, $this->module->returnLabelMailObject[$iso]);
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
//@formatter:off
$warningMessage = $this->module->l('Could not send label to customer.', 'AdminColissimoLabelController');
//@formatter:on
}
}
$shipments = $colissimoOrder->getShipments($this->context->language->id);
$this->context->smarty->assign(
array(
'shipments' => $shipments,
'link' => $this->context->link,
'id_colissimo_order' => $colissimoOrder->id,
)
);
$theme = (bool) Tools::getValue('newTheme') ? 'new_theme' : 'legacy';
if ($this->module->boTheme == 'legacy') {
$theme = 'legacy';
}
$html = $this->context->smarty->fetch($this->module->getLocalPath().'views/templates/admin/admin_order/'.$theme.'/_shipments.tpl');
$return = array(
'error' => false,
'message' => $this->module->l('Return label generated.', 'AdminColissimoLabelController'),
'warning_message' => $warningMessage,
'success' => array(),
'html' => $html,
);
$this->ajaxDie(json_encode($return));
}
/**
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function ajaxProcessDeleteLabel()
{
$idLabel = (int) Tools::getValue('id_colissimo_label');
$colissimoLabel = new ColissimoLabel((int) $idLabel);
$return = array(
'error' => false,
'message' => $this->module->l('Label deleted successfully.', 'AdminColissimoLabelController'),
);
if (Validate::isLoadedObject($colissimoLabel)) {
$colissimoOrder = new ColissimoOrder((int) $colissimoLabel->id_colissimo_order);
if (Validate::isLoadedObject($colissimoOrder)) {
$idColissimoReturnLabel = $colissimoLabel->getReturnLabelId();
if ($idColissimoReturnLabel) {
$colissimoReturnLabel = new ColissimoLabel((int) $idColissimoReturnLabel);
if (!Validate::isLoadedObject($colissimoReturnLabel)) {
$this->module->logger->warning(
'Invalid return label object.',
array('colissimo_label' => $idLabel)
);
//@formatter:off
$return = array(
'error' => true,
'message' => $this->module->l('Invalid return label. Please refresh the page.', 'AdminColissimoLabelController'),
);
//@formatter:on
} else {
try {
$colissimoReturnLabel->deleteFile();
} catch (Exception $e) {
$this->module->logger->warning($e->getMessage());
}
try {
$colissimoReturnLabel->delete();
} catch (Exception $e) {
$this->module->logger->warning($e->getMessage());
}
}
}
if ($colissimoLabel->cn23) {
try {
$colissimoLabel->deleteCN23();
} catch (Exception $e) {
$this->module->logger->warning($e->getMessage());
}
}
$orderCarrier = ColissimoOrderCarrier::getByIdOrder($colissimoOrder->id_order);
$newShippingNumber = false;
if (Validate::isLoadedObject($orderCarrier)) {
if ($orderCarrier->tracking_number == $colissimoLabel->shipping_number) {
$newShippingNumber = $colissimoLabel->getNextShippingNumber();
}
}
try {
$colissimoLabel->deleteFile();
} catch (Exception $e) {
$this->module->logger->warning($e->getMessage());
}
try {
$colissimoLabel->delete();
if ($newShippingNumber !== false) {
$orderCarrier->tracking_number = pSQL($newShippingNumber);
$orderCarrier->save();
}
} catch (Exception $e) {
$this->module->logger->warning($e->getMessage());
}
} else {
$this->module->logger->warning('Invalid Colissimo order object.', array('colissimo_label' => $idLabel));
//@formatter:off
$return = array(
'error' => true,
'message' => $this->module->l('Invalid Colissimo order. Please refresh the page', 'AdminColissimoLabelController'),
'html' => '',
);
//@formatter:on
$this->ajaxDie(json_encode($return));
}
} else {
$this->module->logger->warning('Invalid label object.', array('colissimo_label' => $idLabel));
//@formatter:off
$return = array(
'error' => true,
'message' => $this->module->l('Invalid label. Please refresh the page', 'AdminColissimoLabelController'),
'html' => '',
);
//@formatter:on
$this->ajaxDie(json_encode($return));
}
$shipments = $colissimoOrder->getShipments($this->context->language->id);
$this->context->smarty->assign(
array(
'shipments' => $shipments,
'link' => $this->context->link,
'id_colissimo_order' => $colissimoOrder->id,
)
);
$theme = Tools::getValue('newTheme') ? 'new_theme' : 'legacy';
if ($this->module->boTheme == 'legacy') {
$theme = 'legacy';
}
$html = $this->context->smarty->fetch($this->module->getLocalPath().'views/templates/admin/admin_order/'.$theme.'/_shipments.tpl');
$return['html'] = $html;
$this->ajaxDie(json_encode($return));
}
/**
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function ajaxProcessMailReturnLabel()
{
$idReturnLabel = (int) Tools::getValue('id_colissimo_return_label');
$colissimoReturnLabel = new ColissimoLabel((int) $idReturnLabel);
if (Validate::isLoadedObject($colissimoReturnLabel)) {
try {
$colissimoOrder = new ColissimoOrder((int) $colissimoReturnLabel->id_colissimo_order);
$order = new Order((int) $colissimoOrder->id_order);
$iso = Language::getIsoById($order->id_lang);
$iso = isset($this->module->returnLabelMailObject[$iso]) ? $iso : 'en';
ColissimoTools::sendReturnLabelMail($colissimoReturnLabel, $this->module->returnLabelMailObject[$iso]);
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
//@formatter:off
$return = array(
'error' => true,
'message' => $this->module->l('Cannot send return label to customer.', 'AdminColissimoLabelController'),
);
//@formatter:on
$this->ajaxDie(json_encode($return));
}
} else {
$return = array(
'error' => true,
'message' => $this->module->l('Invalid return label.', 'AdminColissimoLabelController'),
);
$this->ajaxDie(json_encode($return));
}
$return = array(
'error' => false,
'message' => $this->module->l('Mail sent successfully.', 'AdminColissimoLabelController'),
);
$this->ajaxDie(json_encode($return));
}
/**
* @throws PrestaShopException
*/
public function ajaxProcessPrintDocuments()
{
require_once(dirname(__FILE__).'/../../vendor/autoload.php');
$fileType = Tools::getValue('colissimo_file_type');
$labelIds = Tools::getValue('colissimo_label_ids');
$labelIds = json_decode($labelIds);
switch ($fileType) {
case 'labels':
$documents = $this->getAllLabels($labelIds, true);
break;
case 'return_labels':
$documents = $this->getAllReturnLabels($labelIds);
break;
case 'cn23':
$documents = $this->getAllCN23($labelIds);
break;
case 'all':
default:
$documents = $this->getAllDocuments($labelIds, true);
break;
}
if (!empty($documents['label']) || !empty($documents['cn23'])) {
$pdf = new \Clegginabox\PDFMerger\PDFMerger();
$base64 = '';
if (isset($documents['label'])) {
foreach ($documents['label'] as $document) {
/** @var ColissimoLabel $document */
try {
$pdf->addPDF($document->getFilePath());
} catch (Exception $e) {
continue;
}
}
}
if (isset($documents['cn23'])) {
foreach ($documents['cn23'] as $document) {
/** @var ColissimoLabel $document */
try {
$pdf->addPDF($document->getCN23Path());
} catch (Exception $e) {
continue;
}
}
}
try {
$base64 = base64_encode($pdf->merge('string'));
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$return = array(
'error' => true,
'message' => $this->module->l('Cannot concatenate PDF documents.', 'AdminColissimoLabelController'),
);
$this->ajaxDie(json_encode($return));
}
$return = array(
'error' => false,
'message' => '',
'file_string' => $base64,
);
$this->ajaxDie(json_encode($return));
} else {
//@formatter:off
$return = array(
'error' => true,
'message' => $this->module->l('There are no PDF documents to print.', 'AdminColissimoLabelController'),
);
//@formatter:on
$this->ajaxDie(json_encode($return));
}
}
/**
* @throws PrestaShopException
*/
public function ajaxProcessPrintThermalLabels()
{
$fileType = Tools::getValue('colissimo_file_type');
$labelIds = Tools::getValue('colissimo_label_ids');
$labelIds = json_decode($labelIds);
switch ($fileType) {
case 'labels':
case 'all':
$documents = $this->getAllThermalLabels($labelIds);
break;
default:
//@formatter:off
$return = array(
'error' => true,
'message' => $this->module->l('There are no thermal labels to print.', 'AdminColissimoLabelController'),
);
//@formatter:on
$this->ajaxDie(json_encode($return));
break;
}
if (!empty($documents['label'])) {
if (isset($documents['label'])) {
$requests = array();
if (Configuration::get('COLISSIMO_USE_THERMAL_PRINTER') && Configuration::get('COLISSIMO_USE_ETHERNET')) {
$params = 'port=ETHERNET&adresseIp='.Configuration::get('COLISSIMO_PRINTER_IP_ADDR');
} else {
$params = 'port=USB&protocole='.Configuration::get('COLISSIMO_USB_PROTOCOLE').'&adresseIp=';
}
foreach ($documents['label'] as $document) {
/** @var ColissimoLabel $document */
$base64 = base64_encode(Tools::file_get_contents($document->getFilePath()));
$requests[] = 'http://localhost:8000/imprimerEtiquetteThermique?'.$params.'&etiquette='.$base64;
}
$return = array(
'error' => false,
'request_urls' => $requests,
'message' => $this->module->l('Printing done.', 'AdminColissimoLabelController'),
);
$this->ajaxDie(json_encode($return));
}
} else {
//@formatter:off
$return = array(
'error' => true,
'message' => $this->module->l('There are no thermal labels to print.', 'AdminColissimoLabelController'),
);
//@formatter:on
$this->ajaxDie(json_encode($return));
}
}
/**
* @throws PrestaShopException
*/
public function ajaxProcessPrintLabelThermal()
{
if (Configuration::get('COLISSIMO_USE_THERMAL_PRINTER') && Configuration::get('COLISSIMO_USE_ETHERNET')) {
$params = 'port=ETHERNET&adresseIp='.Configuration::get('COLISSIMO_PRINTER_IP_ADDR');
} else {
$params = 'port=USB&protocole='.Configuration::get('COLISSIMO_USB_PROTOCOLE').'&adresseIp=';
}
$url = 'http://localhost:8000/imprimerEtiquetteThermique?'.$params.'&etiquette='.Tools::getValue('base64');
$return = array(
'error' => false,
'request_url' => $url,
'message' => $this->module->l('Printing done.', 'AdminColissimoLabelController'),
);
$this->ajaxDie(json_encode($return));
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class AdminColissimoLogsController
*/
class AdminColissimoLogsController extends ModuleAdminController
{
/** @var Colissimo $module */
public $module;
/**
*
*/
public function processDownloadLogFile()
{
$logsPath = ColissimoTools::getCurrentLogFilePath();
if (realpath($logsPath) !== false && file_exists($logsPath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($logsPath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($logsPath);
exit;
} else {
//@formatter:off
$this->errors[] = $this->module->l('Log file not found. Make sure logs are enabled and file exists.', 'AdminColissimoLogsController');
//@formatter:on
}
}
}

View File

@@ -0,0 +1,114 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class AdminColissimoMigrationController
*
* Ajax processes:
* - startMigration
* - migrateStep
* - endMigration
*
*/
class AdminColissimoMigrationController extends ModuleAdminController
{
/** @var Colissimo $module */
public $module;
/** @var ColissimoMigration $migration */
public $migration;
/**
* @throws Exception
* @throws SmartyException
*/
public function ajaxProcessEndMigration()
{
$modules = Tools::getValue('modules_to_migrate');
foreach ($modules as $module) {
$instance = Module::getInstanceByName($module);
$instance->disable();
}
Configuration::updateGlobalValue('COLISSIMO_SHOW_MIGRATION', -1);
$this->context->smarty->assign('link', $this->context->link);
$html = $this->context->smarty->fetch(
$this->module->getLocalPath().'views/templates/admin/migration/result.tpl'
);
$return = array(
'html_result' => $html,
);
$this->ajaxDie(json_encode($return));
}
/**
* @throws Exception
*/
public function ajaxProcessMigrateStep()
{
$this->migration = new ColissimoMigration();
$modules = Tools::getValue('modules_to_migrate');
$step = Tools::getValue('step');
foreach ($modules as $module) {
$moduleClass = Tools::toCamelCase('Colissimo_'.$module.'_Migration', true);
/** @var ColissimoOtherModuleInterface $moduleInstance */
$moduleInstance = new $moduleClass($this->module->logger);
$this->migration->addModule($moduleInstance);
}
$this->module->logger->info('Migrate '.count($modules).' modules. Step: '.$step, array('modules' => $modules));
$this->migration->migrate($step);
}
/**
* @throws Exception
* @throws SmartyException
*/
public function ajaxProcessStartMigration()
{
Configuration::updateGlobalValue('COLISSIMO_LOGS', 1);
$migrate = Tools::getValue('migrate');
if (!$migrate) {
Configuration::updateGlobalValue('COLISSIMO_SHOW_MIGRATION', -1);
$moduleCarrierIds = Configuration::getMultiple(
array(
'COLISSIMO_CARRIER_AVEC_SIGNATURE',
'COLISSIMO_CARRIER_SANS_SIGNATURE',
'COLISSIMO_CARRIER_RELAIS',
)
);
foreach ($moduleCarrierIds as $carrierId) {
$carrier = ColissimoCarrier::getCarrierByReference((int) $carrierId);
$carrier->setGroups(Group::getGroups($this->context->language->id));
}
$return = array('migrate' => 0);
} else {
$html = $this->context->smarty->fetch(
$this->module->getLocalPath().'views/templates/admin/migration/process.tpl'
);
$return = array('migrate' => 1, 'html_result' => $html);
}
$this->ajaxDie(json_encode($return));
}
}

View File

@@ -0,0 +1,159 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class AdminColissimoTestCredentialsController
*
* Ajax processes:
* - testWidgetCredentials
* - testWSCredentials
*
*/
class AdminColissimoTestCredentialsController extends ModuleAdminController
{
/** @var Colissimo $module */
public $module;
/**
* AdminColissimoTestCredentialsController constructor.
* @throws PrestaShopException
*/
public function __construct()
{
parent::__construct();
$this->module->logger->setChannel('TestCredentials');
}
/**
*
*/
public function ajaxProcessTestWidgetCredentials()
{
$credentials = array(
'contract_number' => Tools::getValue('COLISSIMO_ACCOUNT_LOGIN'),
'password' => Tools::getValue('COLISSIMO_ACCOUNT_PASSWORD'),
'force_endpoint' => Tools::getValue('COLISSIMO_WIDGET_ENDPOINT'),
);
$request = new ColissimoWidgetAuthenticationRequest($credentials);
$client = new ColissimoClient();
$client->setRequest($request);
//@formatter:off
$returnError = array(
'errors' => true,
'message' => $this->module->l('Widget could not be reached at the moment. Please verify the url or try again later', 'AdminColissimoTestCredentialsController'),
);
$returnSuccess = array(
'errors' => false,
'message' => $this->module->l('Webservice connection is working.', 'AdminColissimoTestCredentialsController'),
);
//@formatter:on
try {
/** @var ColissimoWidgetAuthenticationResponse $response */
$response = $client->request();
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$this->ajaxDie(json_encode($returnError));
}
if ($response->token) {
$this->ajaxDie(json_encode($returnSuccess));
} else {
$this->ajaxDie(json_encode($returnError));
}
}
/**
*
*/
public function ajaxProcessTestWSCredentials()
{
$credentials = array(
'contract_number' => Tools::getValue('COLISSIMO_ACCOUNT_LOGIN'),
'password' => Tools::getValue('COLISSIMO_ACCOUNT_PASSWORD'),
);
$output = array(
'x' => 0,
'y' => 0,
'outputPrintingType' => 'PDF_A4_300dpi',
);
$senderAddr = array(
'address' => array(
'companyName' => 'Test Company',
'line2' => '353 Avenue Jean Jaurès',
'countryCode' => 'FR',
'city' => 'Lyon',
'zipCode' => '69007',
),
);
$addresseAddr = array(
'address' => array(
'lastName' => 'Test lastname',
'firstName' => 'Test firstname',
'line2' => '111 Boulevard Brune',
'countryCode' => 'FR',
'city' => 'Paris',
'zipCode' => '75014',
),
);
$shipmentOptions = array(
'weight' => 1,
);
$shipmentServices = array(
'productCode' => 'DOM',
"depositDate" => date('Y-m-d'),
);
$testWS = new ColissimoCheckGenerateLabelRequest($credentials);
$testWS->setOutput($output)
->setSenderAddress($senderAddr)
->setAddresseeAddress($addresseAddr)
->setShipmentOptions($shipmentOptions)
->setShipmentServices($shipmentServices)
->buildRequest();
$client = new ColissimoClient();
$client->setRequest($testWS);
$returnError = array(
'errors' => true,
'message' => $this->module->l('Please verify your credentials.', 'AdminColissimoTestCredentialsController'),
);
//@formatter:off
$returnSuccess = array(
'errors' => false,
'message' => $this->module->l('Your credentials have been verified successfully.', 'AdminColissimoTestCredentialsController'),
);
//@formatter:on
try {
/** @var ColissimoCheckGenerateLabelResponse $response */
$response = $client->request();
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$this->ajaxDie(json_encode($returnError));
}
if ($response->messages[0]['id'] != 0) {
$this->ajaxDie(json_encode($returnError));
}
$this->ajaxDie(json_encode($returnSuccess));
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,567 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoReturnModuleFrontController
*
* Ajax processes:
* - showReturnAddress
* - checkAvailability
* - confirmPickup
*
*/
class ColissimoReturnModuleFrontController extends ModuleFrontController
{
/** @var bool $auth */
public $auth = true;
/** @var string $authRedirection */
public $authRedirection = 'module-colissimo-return';
/** @var Colissimo $module */
public $module;
/** @var array $conf */
public $conf;
/**
* ColissimoReturnModuleFrontController constructor.
*/
public function __construct()
{
parent::__construct();
$this->conf = array(
1000 => $this->module->l('Return label has been generated successfully'),
);
}
/**
* @return array
*/
public function getTemplateVarPage()
{
$page = parent::getTemplateVarPage();
$page['meta']['robots'] = 'noindex';
$page['meta']['title'] = $this->module->l('Colissimo returns');
return $page;
}
/**
* @return bool
*/
public function checkAccess()
{
if (!Configuration::get('COLISSIMO_ENABLE_RETURN') ||
!Configuration::get('COLISSIMO_DISPLAY_RETURN_LABEL_CUSTOMER')
) {
$this->redirect_after = $this->context->link->getPageLink('my-account');
$this->redirect();
}
return parent::checkAccess();
}
/**
* @return bool|void
*/
public function setMedia()
{
parent::setMedia();
$this->module->registerJs(
'colissimo-module-front-return',
'front.return.js',
array('position' => 'bottom', 'priority' => 150)
);
$this->module->registerCSS('colissimo-module-front-css', 'colissimo.front.css');
if (Tools::version_compare(_PS_VERSION_, '1.7', '<')) {
$this->module->registerCSS('colissimo-module-front-modal', 'colissimo.modal.css');
}
}
/**
* @param string $template
* @param array $params
* @param null $locale
* @throws PrestaShopException
*/
public function setTemplate($template, $params = array(), $locale = null)
{
if (Tools::version_compare(_PS_VERSION_, '1.7', '<')) {
parent::setTemplate($template, $params, $locale);
} else {
parent::setTemplate('module:colissimo/views/templates/front/'.$template, $params, $locale);
}
}
/**
* @return array
*/
public function getBreadcrumbLinks()
{
$breadcrumb = parent::getBreadcrumbLinks();
$breadcrumb['links'][] = $this->addMyAccountToBreadcrumb();
return $breadcrumb;
}
/**
* @throws PrestaShopException
*/
public function initContent()
{
parent::initContent();
$shipments = $this->getColissimoOrdersByCustomer();
if (Tools::getValue('conf') > 0) {
$this->success[] = $this->conf[Tools::getValue('conf')];
} elseif (Tools::getValue('conf') < 0) {
$this->errors[] = 'TEst err';
}
$this->context->smarty->assign(
array(
'shipments' => $shipments,
'colissimo_img_path' => $this->module->getPathUri().'views/img/',
)
);
$this->setTemplate($this->module->psFolder.'/return.tpl');
}
/**
*
*/
public function postProcess()
{
$idLabel = Tools::getValue('id_label');
if (Tools::getValue('action') == 'downloadLabel' && $idLabel) {
$this->module->logger->setChannel('FrontReturn');
$label = new ColissimoLabel((int) $idLabel);
$colissimoOrder = new ColissimoOrder((int) $label->id_colissimo_order);
$order = new Order((int) $colissimoOrder->id_order);
if ($order->id_customer != $this->context->customer->id || !$label->return_label) {
return;
}
try {
$label->download();
} catch (Exception $e) {
$this->module->logger->error(
sprintf('Error while downloading return label: %s', $e->getMessage()),
array(
'id_customer' => $this->context->customer->id,
'id_colissimo_order' => $colissimoOrder->id_colissimo_order,
'id_order' => $colissimoOrder->id_order,
'id_label' => $label->id,
)
);
//@formatter:off
$this->context->controller->errors[] = $this->module->l('An error occurred while downloading the return label. Please try again or contact our support.');
//@formatter:on
}
}
if (Tools::getValue('action') == 'generateLabel' && $idLabel) {
$conf = $this->generateReturnLabel($idLabel) ? 1000 : -1;
$this->redirect_after = $this->context->link->getModuleLink('colissimo', 'return', array('conf' => $conf));
$this->redirect();
}
}
/**
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function getColissimoOrdersByCustomer()
{
$ids = ColissimoOrder::getCustomerColissimoOrderIds($this->context->customer->id, $this->context->shop->id);
$mailboxReturn = Configuration::get('COLISSIMO_ENABLE_MAILBOX_RETURN');
$data = array();
foreach ($ids as $id) {
$colissimoOrder = new ColissimoOrder((int) $id);
$labels = $colissimoOrder->getShipments($this->context->language->id);
if (empty($labels)) {
continue;
}
foreach ($labels as $label) {
$mailboxReturnText = '';
if (isset($label['id_return_label'])) {
$colissimoReturnLabel = new ColissimoLabel((int) $label['id_return_label']);
if ($colissimoReturnLabel->hasMailboxPickup()) {
$details = $colissimoReturnLabel->getMailboxPickupDetails();
if (isset($details['pickup_date']) &&
$details['pickup_date'] &&
isset($details['pickup_before']) &&
$details['pickup_before']
) {
$mailboxReturnText = sprintf(
$this->module->l('Pickup on %s before %s'),
Tools::displayDate(date('Y-m-d', $details['pickup_date'])),
$details['pickup_before']
);
}
}
} else {
if (Configuration::get('COLISSIMO_GENERATE_RETURN_LABEL_CUSTOMER')) {
$colissimoReturnLabel = new ColissimoLabel();
} else {
continue;
}
}
$colissimoOrder = new ColissimoOrder((int) $id);
$order = new Order((int) $colissimoOrder->id_order);
$orderState = new OrderState((int) $order->current_state, $this->context->language->id);
if (ColissimoService::getServiceTypeById($colissimoOrder->id_colissimo_service) != ColissimoService::TYPE_RELAIS) {
$customerAddr = new Address((int) $order->id_address_delivery);
} else {
$customerAddr = new Address((int) $order->id_address_invoice);
}
$isoCustomerAddr = Country::getIsoById($customerAddr->id_country);
if (!ColissimoTools::getReturnDestinationTypeByIsoCountry($isoCustomerAddr)) {
continue;
}
$data[] = array(
'reference' => $order->reference,
'date' => Tools::displayDate($order->date_add, null, false),
'status' => array(
'name' => $orderState->name,
'contrast' => (Tools::getBrightness($orderState->color) > 128) ? 'dark' : 'bright',
'color' => $orderState->color,
),
'label' => array(
'id' => $label['id_label'],
),
'return_available' => (bool) ColissimoTools::getReturnDestinationTypeByIsoCountry($isoCustomerAddr),
'return_label' => array(
'id' => $colissimoReturnLabel->id_colissimo_label,
'shipping_number' => $colissimoReturnLabel->shipping_number,
),
'return_file_deleted' => $colissimoReturnLabel->file_deleted,
'mailbox_return' => $mailboxReturn && $colissimoReturnLabel->isFranceReturnLabel(),
'mailbox_return_text' => $mailboxReturnText,
);
}
}
return $data;
}
/**
* @param ColissimoLabel $colissimoLabel
* @return bool
*/
public function checkLabelAccess($colissimoLabel)
{
$colissimoOrder = new ColissimoOrder((int) $colissimoLabel->id_colissimo_order);
$order = new Order((int) $colissimoOrder->id_order);
if ($order->id_customer != $this->context->customer->id) {
return false;
}
return true;
}
/**
* @throws Exception
* @throws SmartyException
*/
public function displayAjaxShowReturnAddress()
{
$idColissimoLabel = Tools::getValue('id_colissimo_label');
$colissimoLabel = new ColissimoLabel((int) $idColissimoLabel);
if (!Validate::isLoadedObject($colissimoLabel) || !$this->checkLabelAccess($colissimoLabel)) {
$return = array(
'error' => true,
'message' => $this->module->l(
'An unexpected error occurred. Please try again or contact our customer service'
),
);
$this->ajaxDie(json_encode($return));
}
$colissimoOrder = new ColissimoOrder((int) $colissimoLabel->id_colissimo_order);
$colissimoService = new ColissimoService((int) $colissimoOrder->id_colissimo_service);
$order = new Order((int) $colissimoOrder->id_order);
if ($colissimoService->is_pickup) {
$address = new Address((int) $order->id_address_invoice);
} else {
$address = new Address((int) $order->id_address_delivery);
}
$this->context->smarty->assign(array('address' => $address, 'id_colissimo_label' => $idColissimoLabel));
$psFolder = $this->module->psFolder;
$tpl = $this->module->getTemplatePath($psFolder.'/_partials/colissimo-return-modal-body-address.tpl');
$html = $this->context->smarty->fetch($tpl);
$return = array(
'error' => false,
'message' => '',
'html' => $html,
);
$this->ajaxDie(json_encode($return));
}
/**
* @throws Exception
* @throws SmartyException
*/
public function displayAjaxCheckAvailability()
{
$this->module->logger->setChannel('MailboxReturn');
$idColissimoLabel = Tools::getValue('id_colissimo_label');
$colissimoLabel = new ColissimoLabel((int) $idColissimoLabel);
if (!$this->checkLabelAccess($colissimoLabel)) {
$return = array(
'error' => true,
'message' => $this->module->l(
'An unexpected error occurred. Please try again or contact our customer service'
),
);
$this->ajaxDie(json_encode($return));
}
$senderAddress = array(
'line0' => '',
'line1' => '',
'line2' => Tools::getValue('colissimo-address1'),
'line3' => Tools::getValue('colissimo-address2'),
'countryCode' => 'FR',
'zipCode' => Tools::getValue('colissimo-postcode'),
'city' => Tools::getValue('colissimo-city'),
);
$mailboxDetailsRequest = new ColissimoMailboxDetailsRequest(ColissimoTools::getCredentials());
$mailboxDetailsRequest->setSenderAddress($senderAddress)
->buildRequest();
$client = new ColissimoClient();
$this->module->logger->info(
'Request mailbox details',
array('request' => json_decode($mailboxDetailsRequest->getRequest(true), true))
);
$client->setRequest($mailboxDetailsRequest);
try {
/** @var ColissimoMailboxDetailsResponse $response */
$response = $client->request();
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$return = array(
'error' => true,
'message' => $e->getMessage(),
);
$this->ajaxDie(json_encode($return));
}
if ($response->messages[0]['id']) {
foreach ($response->messages as $message) {
$this->module->logger->error(
'Error found',
sprintf('(%s) - %s', $message['id'], $message['messageContent'])
);
}
$return = array(
'error' => true,
'message' => $this->module->l('An error occurred. Please check your address and try again.'),
);
$this->ajaxDie(json_encode($return));
}
$pickingDate = date('Y-m-d', $response->pickingDates[0]).' 00:00:00';
$this->context->smarty->assign(
array(
'max_picking_hour' => $response->maxPickingHour,
'validity_time' => $response->validityTime,
'picking_date' => $response->pickingDates[0],
'picking_date_display' => Tools::displayDate($pickingDate),
'id_colissimo_label' => $idColissimoLabel,
'picking_address' => array(
'company' => Tools::getValue('colissimo-company'),
'lastname' => Tools::getValue('colissimo-lastname'),
'firstname' => Tools::getValue('colissimo-firstname'),
'address1' => Tools::getValue('colissimo-address1'),
'address2' => Tools::getValue('colissimo-address2'),
'postcode' => Tools::getValue('colissimo-postcode'),
'city' => Tools::getValue('colissimo-city'),
),
)
);
//@formatter:off
$psFolder = $this->module->psFolder;
$tpl = $this->module->getTemplatePath($psFolder.'/_partials/colissimo-return-modal-body-dates.tpl');
$html = $this->context->smarty->fetch($tpl);
//@formatter:on
$return = array(
'error' => false,
'html' => $html,
);
$this->ajaxDie(json_encode($return));
}
/**
* @throws Exception
* @throws PrestaShopDatabaseException
* @throws SmartyException
*/
public function displayAjaxConfirmPickup()
{
$this->module->logger->setChannel('MailboxReturn');
$idColissimoLabel = Tools::getValue('id_colissimo_label');
$pickupDate = Tools::getValue('mailbox_date');
$pickupBefore = Tools::getValue('mailbox_hour');
$colissimoLabel = new ColissimoLabel((int) $idColissimoLabel);
$errorMessage = '';
if (Validate::isLoadedObject($colissimoLabel) && $this->checkLabelAccess($colissimoLabel)) {
if (!$colissimoLabel->hasMailboxPickup()) {
$senderAddress = array(
'companyName' => Tools::getValue('mailbox_company'),
'lastName' => Tools::getValue('mailbox_lastname'),
'firstName' => Tools::getValue('mailbox_firstname'),
'line2' => Tools::getValue('mailbox_address1'),
'line3' => Tools::getValue('mailbox_address2'),
'zipCode' => Tools::getValue('mailbox_postcode'),
'city' => Tools::getValue('mailbox_city'),
'countryCode' => 'FR',
'email' => Tools::getValue('mailbox_email'),
);
$date = date('Y-m-d', Tools::getValue('mailbox_date'));
$pickupRequest = new ColissimoPlanPickupRequest(ColissimoTools::getCredentials());
$pickupRequest->setParcelNumber($colissimoLabel->shipping_number)
->setSenderAddress($senderAddress)
->setMailboxPickingDate($date)
->buildRequest();
$client = new ColissimoClient();
$client->setRequest($pickupRequest);
$this->module->logger->info(
'Mailbox pickup request',
array('request' => json_decode($pickupRequest->getRequest(true), true))
);
try {
/** @var ColissimoPlanPickupResponse $response */
$response = $client->request();
} catch (Exception $e) {
$this->module->logger->error('Error thrown: '.$e->getMessage());
}
if (isset($response) && !$response->messages[0]['id']) {
$this->module->logger->info('Mailbox pickup response', $response->response);
$insert = Db::getInstance()
->insert(
'colissimo_mailbox_return',
array(
'id_colissimo_label' => (int) $idColissimoLabel,
'pickup_date' => pSQL($pickupDate),
'pickup_before' => pSQL($pickupBefore),
)
);
if ($insert) {
$hasError = false;
} else {
// Cannot insert
$this->module->logger->error('Cannot insert mailbox request in DB.');
$hasError = true;
$errorMessage = '';
}
} else {
// Error thrown or error found
$this->module->logger->error('Errors found.', array('messages' => $response->messages));
$hasError = true;
$errorMessage = '';
}
} else {
// Pickup request already sent
$this->module->logger->error('A pickup request has already been sent for this return.');
$hasError = true;
$errorMessage = $this->module->l('A pickup request has already been sent for this return.');
}
} else {
// Invalid label
$this->module->logger->error('Invalid label');
$hasError = true;
$errorMessage = '';
}
$this->context->smarty->assign(
array(
'has_error' => $hasError,
'error_message' => $errorMessage,
)
);
//@formatter:off
$psFolder = $this->module->psFolder;
$tpl = $this->module->getTemplatePath($psFolder.'/_partials/colissimo-return-modal-body-result.tpl');
$html = $this->context->smarty->fetch($tpl);
//@formatter:on
$htmlText = sprintf(
$this->module->l('Pickup on %s before %s'),
Tools::displayDate(date('Y-m-d', $pickupDate)),
$pickupBefore
);
$return = array(
'error' => $hasError,
'html' => $html,
'text_result' => $htmlText,
'id_colissimo_label' => $idColissimoLabel,
);
$this->ajaxDie(json_encode($return));
}
/**
* @param int $idLabel
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function generateReturnLabel($idLabel)
{
$colissimoLabel = new ColissimoLabel($idLabel);
$colissimoOrder = new ColissimoOrder((int) $colissimoLabel->id_colissimo_order);
$order = new Order((int) $colissimoOrder->id_order);
$customerAddress = new Address((int) $order->id_address_delivery);
$merchantAddress = ColissimoMerchantAddress::getMerchantReturnAddress();
$customerCountry = $customerAddress->id_country;
$returnDestinationType = ColissimoTools::getReturnDestinationTypeByIdCountry($customerCountry);
if ($returnDestinationType === false) {
$this->module->logger->error('Cannot edit return label for this destination.');
return false;
}
$idService = ColissimoService::getServiceIdByIdCarrierDestinationType(0, $returnDestinationType);
$data = array(
'order' => $order,
'version' => $this->module->version,
'cart' => new Cart((int) $order->id_cart),
'customer' => new Customer((int) $order->id_customer),
'colissimo_order' => $colissimoOrder,
'colissimo_service' => new ColissimoService((int) $idService),
'colissimo_service_initial' => new ColissimoService((int) $colissimoOrder->id_colissimo_service),
'customer_addr' => $customerAddress,
'merchant_addr' => $merchantAddress,
'form_options' => array(
'insurance' => 0,
'ta' => 0,
'd150' => 0,
'weight' => ColissimoTools::getOrderTotalWeightInKg($order),
'mobile_phone' => $merchantAddress->phoneNumber,
),
);
try {
$this->module->labelGenerator->setData($data);
$this->module->labelGenerator->generateReturn($colissimoLabel);
} catch (Exception $e) {
$this->module->logger->error('Exception throw while generating return label.', $e->getMessage());
return false;
}
return true;
}
}

View File

@@ -0,0 +1,325 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoTrackingModuleFrontController
*
* Ajax processes:
* - showTracking
*
*/
class ColissimoTrackingModuleFrontController extends ModuleFrontController
{
/** @var Colissimo $module */
public $module;
/** @var Order $order */
public $order;
/** @var ColissimoOrder $colissimoOrder */
public $colissimoOrder;
/** @var array $languages */
public $languages = array(
'fr' => 'fr_FR',
'de' => 'de_DE',
'en' => 'en_GB',
'es' => 'es-ES',
'it' => 'it_IT',
'nl' => 'nl_NL',
);
/** @var array $days */
public $days = array(
1 => array('fr' => 'lundi', 'en' => 'monday,', 'de' => 'Montag,', 'nl' => 'maandag', 'it' => 'lunedi', 'es' => 'lunes,'),
2 => array('fr' => 'mardi', 'en' => 'tuesday,', 'de' => 'Dienstag,', 'nl' => 'dinsdag', 'it' => 'martedì', 'es' => 'martes,'),
3 => array('fr' => 'mercredi', 'en' => 'wednesday,', 'de' => 'Mittwoch,', 'nl' => 'woensdag', 'it' => 'mercoledì', 'es' => 'miércoles,'),
4 => array('fr' => 'jeudi', 'en' => 'thursday,', 'de' => 'Donnerstag,', 'nl' => 'donderdag', 'it' => 'giovedi', 'es' => 'jueves,'),
5 => array('fr' => 'vendredi', 'en' => 'friday,', 'de' => 'Freitag,', 'nl' => 'vrijdag', 'it' => 'venerdì', 'es' => 'viernes,'),
6 => array('fr' => 'samedi', 'en' => 'saturday,', 'de' => 'Samstag,', 'nl' => 'zaterdag', 'it' => 'sabato', 'es' => 'sábado,'),
7 => array('fr' => 'dimanche', 'en' => 'sunday,', 'de' => 'Sonntag,', 'nl' => 'zondag', 'it' => 'domenica', 'es' => 'domingo,'),
);
/** @var array $months */
public $months = array(
1 => array('fr' => 'janvier', 'en' => 'january', 'de' => 'januar', 'nl' => 'januari', 'it' => 'gennaio', 'es' => 'de enero'),
2 => array('fr' => 'février', 'en' => 'february', 'de' => 'februar', 'nl' => 'februari', 'it' => 'febbraio', 'es' => 'de febrero'),
3 => array('fr' => 'mars', 'en' => 'march', 'de' => 'märz', 'nl' => 'maart', 'it' => 'marzo', 'es' => 'de marzo'),
4 => array('fr' => 'avril', 'en' => 'april', 'de' => 'april', 'nl' => 'april', 'it' => 'aprile', 'es' => 'de abril'),
5 => array('fr' => 'mai', 'en' => 'may', 'de' => 'mai', 'nl' => 'mei', 'it' => 'maggio', 'es' => 'de mayo'),
6 => array('fr' => 'juin', 'en' => 'june', 'de' => 'juni', 'nl' => 'juni', 'it' => 'giugno', 'es' => 'de junio'),
7 => array('fr' => 'juillet', 'en' => 'july', 'de' => 'juli', 'nl' => 'juli', 'it' => 'luglio', 'es' => 'de julio'),
8 => array('fr' => 'août', 'en' => 'august', 'de' => 'august', 'nl' => 'augustus', 'it' => 'agosto', 'es' => 'de agosto'),
9 => array('fr' => 'septembre', 'en' => 'september', 'de' => 'september', 'nl' => 'september', 'it' => 'settembre', 'es' => 'de septiembre'),
10 => array('fr' => 'octobre', 'en' => 'october', 'de' => 'oktober', 'nl' => 'oktober', 'it' => 'ottobre', 'es' => 'de octubre'),
11 => array('fr' => 'novembre', 'en' => 'november', 'de' => 'november', 'nl' => 'november', 'it' => 'novembre', 'es' => 'de noviembre'),
12 => array('fr' => 'décembre', 'en' => 'december', 'de' => 'dezember', 'nl' => 'december', 'it' => 'dicembre', 'es' => 'de diciembre'),
);
/**
* @return array
*/
public function getTemplateVarPage()
{
$page = parent::getTemplateVarPage();
$page['meta']['robots'] = 'noindex';
$page['meta']['title'] = $this->module->l('Colissimo shipment tracking #').$this->order->reference;
return $page;
}
/**
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function checkAccess()
{
$reference = Tools::getValue('order_reference');
$hash = Tools::getValue('hash');
/** @var PrestaShopCollection $orders */
$orders = Order::getByReference($reference);
if (!$orders->count()) {
$this->redirect_after = $this->context->link->getPageLink('my-account');
$this->redirect();
}
/** @var Order $order */
$order = $orders->getFirst();
if (md5($reference.$order->secure_key) !== $hash) {
$this->redirect_after = $this->context->link->getPageLink('my-account');
$this->redirect();
}
$idColissimoOrder = ColissimoOrder::exists($order->id);
if (!$idColissimoOrder) {
$this->redirect_after = $this->context->link->getPageLink('my-account');
$this->redirect();
}
$this->order = $order;
$this->colissimoOrder = new ColissimoOrder((int) $idColissimoOrder);
return parent::checkAccess();
}
/**
* @return bool|void
*/
public function setMedia()
{
parent::setMedia();
$this->module->registerJs(
'colissimo-module-front-tracking',
'front.tracking.js',
array('position' => 'bottom', 'priority' => 150)
);
$this->module->registerCSS('module-colissimo-sprites-flag', 'flag.sprites.css');
$this->module->registerCSS('module-colissimo-front', 'colissimo.front.css');
}
/**
* @param string $template
* @param array $params
* @param null $locale
* @throws PrestaShopException
*/
public function setTemplate($template, $params = array(), $locale = null)
{
if (Tools::version_compare(_PS_VERSION_, '1.7', '<')) {
parent::setTemplate($template, $params, $locale);
} else {
parent::setTemplate('module:colissimo/views/templates/front/'.$template, $params, $locale);
}
}
/**
* @throws PrestaShopException
*/
public function initContent()
{
parent::initContent();
$hash = md5($this->order->reference.$this->order->secure_key);
$labels = $this->colissimoOrder->getShipments($this->context->language->id);
$this->context->smarty->assign(
array(
'colissimo_img_path' => $this->module->getPathUri().'views/img/',
'order_reference' => $this->order->reference,
'order_hash' => $hash,
'no_labels' => (!$labels || empty($labels)) ? 1 : 0,
)
);
$this->setTemplate($this->module->psFolder.'/tracking.tpl');
}
/**
* @param array $events
* @return array
* @throws PrestaShopException
*/
// public function getEvents($events)
// {
// $return = array();
// foreach ($events as $event) {
// $return[] = array_merge(
// array('dateDisplay' => Tools::displayDate(date('Y-m-d H:i:s', $event['date'] / 1000))),
// $event
// );
// }
//
// return $return;
// }
/**
* @throws Exception
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
* @throws SmartyException
*/
public function displayAjaxShowTracking()
{
$language = new Language((int) $this->context->language->id);
$iso = $language->iso_code;
$locale = isset($this->languages[$iso]) ? $this->languages[$iso] : $this->languages['en'];
$html = array();
$labels = $this->colissimoOrder->getShipments($language->id);
$order = new Order((int) $this->colissimoOrder->id_order);
$this->module->logger->setChannel('Timeline');
$this->module->logger->info(
'Start tracking for order '.$this->order->id.' ('.$this->order->reference.')'
);
foreach ($labels as $label) {
$trackingRequest = new ColissimoTrackingTimelineRequest(ColissimoTools::getCredentials($order->id_shop));
$trackingRequest->setParcelNumber($label['shipping_number'])
->setLang(str_replace('-', '_', $locale))
->setIp($_SERVER['REMOTE_ADDR'])
->buildRequest();
$this->module->logger->info(
'Request',
array('json' => json_decode($trackingRequest->getRequest(true), true))
);
$client = new ColissimoClient();
$client->setRequest($trackingRequest);
try {
/** @var ColissimoTrackingTimelineResponse $trackingResponse */
$trackingResponse = $client->request();
} catch (Exception $e) {
$this->module->logger->error('Exception thrown: '.$e->getMessage());
continue;
}
if ($trackingResponse->status[0]['code']) {
$this->module->logger->error('Error found', $trackingResponse->status[0]['message']);
continue;
}
if ($trackingResponse->parcelDetails['statusDelivery']) {
$this->module->updateTrackingByTypology(
ColissimoTrackingCode::TYPO_DELIVERED,
$this->order,
$label['id_label']
);
} elseif (is_array($trackingResponse->events) && count($trackingResponse->events) > 1) {
$this->module->updateTrackingByTypology(
ColissimoTrackingCode::TYPO_SHIPPED,
$this->order,
$label['id_label']
);
}
foreach ($trackingResponse->events as &$event) {
if ($event['date'] !== null) {
try {
$dateTime = new DateTime($event['date']);
} catch (Exception $e) {
$event['dateDisplay'] = '';
$event['dateDisplayShort'] = '';
continue;
}
$day = $this->days[$dateTime->format('N')];
$day = isset($day[$iso]) ? $day[$iso] : $day['en'];
$month = $this->months[$dateTime->format('n')];
$month = isset($month[$iso]) ? $month[$iso] : $month['en'];
$event['dateDisplay'] = $day.' '.$dateTime->format('j').' '.$month;
$event['dateDisplayShort'] = Tools::displayDate($dateTime->format('Y-m-d H:i:s'));
} else {
$event['dateDisplay'] = '';
$event['dateDisplayShort'] = '';
}
}
foreach ($trackingResponse->timeline as $key => &$step) {
if ($step['date'] !== null) {
try {
$dateTime = new DateTime($step['date']);
} catch (Exception $e) {
$step['dateDisplay'] = '';
$step['dateDisplayShort'] = '';
continue;
}
$day = $this->days[$dateTime->format('N')];
$day = isset($day[$iso]) ? $day[$iso] : $day['en'];
$month = $this->months[$dateTime->format('n')];
$month = isset($month[$iso]) ? $month[$iso] : $month['en'];
$step['dateDisplay'] = $day.' '.$dateTime->format('j').' '.$month;
$step['dateDisplayShort'] = Tools::displayDate($dateTime->format('Y-m-d H:i:s'));
} else {
$step['dateDisplay'] = '';
$step['dateDisplayShort'] = '';
}
if ($step['countryCodeISO']) {
$idCountry = Country::getByIso($step['countryCodeISO']);
$idLang = $this->context->language->id;
$step['countryName'] = $idCountry ? Country::getNameById($idLang, $idCountry) : '';
} else {
$step['countryName'] = '';
}
if ($step['status'] == 'STEP_STATUS_INACTIVE') {
$step['statusClass'] = 'inactive';
} elseif ($step['status'] == 'STEP_STATUS_ACTIVE') {
if (!isset($trackingResponse->timeline[$key + 1])) {
$trackingResponse->parcelDetails['currentStep'] = $step;
$step['statusClass'] = 'active current';
} else {
if ($trackingResponse->timeline[$key + 1]['status'] == 'STEP_STATUS_ACTIVE') {
$step['statusClass'] = 'active';
} else {
$step['statusClass'] = 'active current';
$trackingResponse->parcelDetails['currentStep'] = $step;
}
}
}
}
$shipment = array(
'messages' => $trackingResponse->messages,
'user_messages' => $trackingResponse->userMessages,
'steps_timeline' => $trackingResponse->timeline,
'steps_details' => $trackingResponse->events,
'parcel_details' => $trackingResponse->parcelDetails,
);
$this->context->smarty->assign(array('shipment' => $shipment));
$tpl = $this->module->getTemplatePath($this->module->psFolder.'/_partials/colissimo-shipments.tpl');
$html[] = $this->context->smarty->fetch($tpl);
}
$this->ajaxDie(json_encode(array('error' => count($html) ? 0 : 1, 'html_result' => implode('<hr>', $html))));
}
}

View File

@@ -0,0 +1,121 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Class ColissimoWidgetModuleFrontController
*
* Ajax processes:
* - selectPickupPoint
* - saveMobilePhoneOpc
*
*/
class ColissimoWidgetModuleFrontController extends ModuleFrontController
{
/** @var Colissimo $module */
public $module;
/**
* @throws Exception
* @throws SmartyException
*/
public function displayAjaxSelectPickupPoint()
{
$data = json_decode(Tools::getValue('infoPoint'), true);
$colissimoId = $data['colissimo_id'];
$pickupPoint = ColissimoPickupPoint::getPickupPointByIdColissimo($colissimoId);
$pickupPoint->hydrate(array_map('pSQL', $data));
$needMobileValidation = Configuration::get('PS_ORDER_PROCESS_TYPE');
$mobilePhone = str_replace(array('(', '_', ')'), '', Tools::getValue('mobilePhone'));
$deliveryAddress = new Address((int) $this->context->cart->id_address_delivery);
if (!$mobilePhone && !$needMobileValidation) {
$mobilePhone = $deliveryAddress->phone_mobile;
}
try {
$pickupPoint->save();
ColissimoCartPickupPoint::updateCartPickupPoint(
(int) $this->context->cart->id,
(int) $pickupPoint->id,
$mobilePhone
);
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$this->context->smarty->assign(
'colissimo_pickup_point_error',
$this->module->l('An unexpected error occurred. Please refresh the window.')
);
$tpl = $this->module->getTemplatePath(
'front/'.$this->module->psFolder.'/_partials/pickup-point-address.tpl'
);
$html = $this->context->smarty->fetch($tpl);
$this->ajaxDie(json_encode(array('html_result' => $html)));
}
$this->context->smarty->assign(
array(
'colissimo_pickup_point' => $pickupPoint,
'mobile_phone' => $mobilePhone,
'need_mobile_validation' => (int) $needMobileValidation,
'colissimo_img_path' => $this->module->getPathUri().'views/img/',
)
);
$tpl = $this->module->getTemplatePath('front/'.$this->module->psFolder.'/_partials/pickup-point-address.tpl');
$html = $this->context->smarty->fetch($tpl);
$this->ajaxDie(json_encode(array('html_result' => $html)));
}
/**
* @throws PrestaShopException
*/
public function displayAjaxSaveMobilePhoneOpc()
{
$this->module->logger->setChannel('MobileOPC');
$mobilePhone = Tools::getValue('mobilePhone');
$isMobileValid = Tools::getValue('isMobileValid');
if ($mobilePhone && $isMobileValid) {
try {
ColissimoCartPickupPoint::updateMobilePhoneByCartId($this->context->cart->id, $mobilePhone);
} catch (Exception $e) {
$this->module->logger->error($e->getMessage());
$result = array(
'text_result' => $this->module->l('Cannot save mobile phone number.', 'widget'),
'errors' => true,
);
$this->ajaxDie(json_encode($result));
}
$result = array(
'text_result' => $this->module->l('Mobile phone updated.', 'widget'),
'errors' => false,
);
$this->ajaxDie(json_encode($result));
} else {
$this->module->logger->error('Attempt to save mobile phone with wrong format');
$result = array(
'text_result' => $this->module->l('Please enter a valid mobile phone number value.', 'widget'),
'errors' => true,
);
$this->ajaxDie(json_encode($result));
}
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,2 @@
Order deny,allow
Deny from all

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,2 @@
Order deny,allow
Deny from all

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,2 @@
Order deny,allow
Deny from all

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,2 @@
Order deny,allow
Deny from all

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,18 @@
product_code,commercial_name,destination_type,is_signature,is_pickup,is_return,carrier_type
DOM,FR - DOMICILE sans signature,FRANCE,0,0,0,SANS_SIGNATURE
DOS,FR - DOMICILE avec signature,FRANCE,1,0,0,AVEC_SIGNATURE
BPR,FR - POINT RETRAIT,FRANCE,0,1,0,RELAIS
A2P,FR - POINT RETRAIT,FRANCE,0,1,0,RELAIS
CORE,RETOUR FRANCE,FRANCE,0,0,1,RETOUR
CDS,OM - DOMICILE avec signature,OM,1,0,0,AVEC_SIGNATURE
COM,OM - DOMICILE sans signature,OM,0,0,0,SANS_SIGNATURE
CORI,RETOUR OUTRE MER,OM,0,0,1,RETOUR
DOM,EU - DOMICILE sans signature,EUROPE,0,0,0,SANS_SIGNATURE
DOS,EU - DOMICILE avec signature,EUROPE,1,0,0,AVEC_SIGNATURE
BDP,EU - POINT RETRAIT,EUROPE,0,1,0,RELAIS
CMT,EU - POINT RETRAIT,EUROPE,0,1,0,RELAIS
PCS,EU - POINT RETRAIT,EUROPE,0,1,0,RELAIS
COLI,INT - DOMICILE avec signature,WORLDWIDE,1,0,0,AVEC_SIGNATURE
CORI,RETOUR INTERNATIONAL,WORLDWIDE,0,0,1,RETOUR
COLD,DOM - DOMICILE sans signature,INTRA_DOM,0,0,0,SANS_SIGNATURE
COL,DOM - DOMICILE avec signature,INTRA_DOM,1,0,0,AVEC_SIGNATURE
1 product_code commercial_name destination_type is_signature is_pickup is_return carrier_type
2 DOM FR - DOMICILE sans signature FRANCE 0 0 0 SANS_SIGNATURE
3 DOS FR - DOMICILE avec signature FRANCE 1 0 0 AVEC_SIGNATURE
4 BPR FR - POINT RETRAIT FRANCE 0 1 0 RELAIS
5 A2P FR - POINT RETRAIT FRANCE 0 1 0 RELAIS
6 CORE RETOUR FRANCE FRANCE 0 0 1 RETOUR
7 CDS OM - DOMICILE avec signature OM 1 0 0 AVEC_SIGNATURE
8 COM OM - DOMICILE sans signature OM 0 0 0 SANS_SIGNATURE
9 CORI RETOUR OUTRE MER OM 0 0 1 RETOUR
10 DOM EU - DOMICILE sans signature EUROPE 0 0 0 SANS_SIGNATURE
11 DOS EU - DOMICILE avec signature EUROPE 1 0 0 AVEC_SIGNATURE
12 BDP EU - POINT RETRAIT EUROPE 0 1 0 RELAIS
13 CMT EU - POINT RETRAIT EUROPE 0 1 0 RELAIS
14 PCS EU - POINT RETRAIT EUROPE 0 1 0 RELAIS
15 COLI INT - DOMICILE avec signature WORLDWIDE 1 0 0 AVEC_SIGNATURE
16 CORI RETOUR INTERNATIONAL WORLDWIDE 0 0 1 RETOUR
17 COLD DOM - DOMICILE sans signature INTRA_DOM 0 0 0 SANS_SIGNATURE
18 COL DOM - DOMICILE avec signature INTRA_DOM 1 0 0 AVEC_SIGNATURE

View File

@@ -0,0 +1,55 @@
clp_code,inovert_code,typology,internal_text
LIVBPO,LIVCFM,LIV,Votre colis est à disposition en boîte postale
LIVCFM,LIVCFM,LIV,Votre colis est livré.
LIVDIV,LIVCFM,LIV,Votre colis est livré mais le destinataire a signalé un emballage modérément dégradé.
LIVGAR,LIVGAR,LIV,Votre colis a été livré au gardien.
LIVRCA,LIVCFM,LIV,Votre colis est livré mais le destinataire a signalé un emballage fortement dégradé.
LIVRCC,LIVCFM,LIV,Votre colis est livré mais le destinataire a signalé un emballage fortement dégradé.
LIVRTI,LIVRTI,LIV,Votre colis a été livré au gardien ou à un voisin.
LIVVOI,LIVVOI,LIV,Votre colis est livré au voisin indiqué sur lavis déposé dans la boîte aux lettres du destinataire.
AACALI,CITDOC,ANO,"La livraison de votre colis dans un espace Cityssimo est impossible, le destinataire nest pas abonné à ce service."
AACEDI,CITDOC,ANO,Le colis ne peut être livré dans un automate de retrait Cityssimo en raison de labsence de coordonnées du destinataire. Le colis sera retourné à lexpéditeur.
AARLIB,,ANO,"Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises."
AARTER,AARDVY,ANO,"Votre colis a subi une erreur de tri, il a maintenant repris son acheminement."
RCDDVY,RCDDVY,ANO,Votre colis est réacheminé vers un autre site de distribution en raison dun défaut dadressage.
RDVABS,RENARV,ANO,Votre colis na pu être livré car le destinataire était absent. Il sera prochainement recontacté pour convenir dun nouveau rendez-vous.
RDVAIN,RENAIN,ANO,Votre colis na pas pu être livré sur rendez-vous. Le destinataire doit choisir une date de livraison.
RDVINC,RSTNCG,ANO,Votre colis na pas pu être livré sur rendez-vous. Le destinataire sera prochainement recontacté.
RDVREP,RENAIN,ANO,Votre colis est prêt à être livré sur rendez-vous. Nous sommes en attente de votre choix de créneau horaire.
RECALI,CITDOC,ANO,Votre colis na pas pu être livré dans lespace Cityssimo suite à une erreur sur votre compte abonné
REFALI,CITDOC,ANO,"La livraison de votre colis dans lespace Cityssimo est impossible, il est retourné à lexpéditeur."
REFCDS,CHGRCA,ANO,Lemballage de votre colis a été renforcé pour en assurer sa livraison. Il est en cours dacheminement.
REFCEX,DCHRCA,ANO,Votre colis est retourné à lexpéditeur suite à un incident.
REFDDS,CHGRCA,ANO,Lemballage de votre colis a été renforcé pour en assurer sa livraison. Il est en cours dacheminement.
REFDEX,DCHRCA,ANO,Votre colis est retourné à lexpéditeur suite à un incident.
REFISO,DCHRMA,ANO,Votre colis et/ou son étiquette sont endommagés. Votre colis est en cours de traitement
RENACO,CITDOC,ANO,La livraison de votre colis dans un espace Cityssimo est impossible. Le compte abonné est inactif ou résilié. Le colis est rééxpédié au domicile du destinataire.
RENACP,RSTFMA,ANO,"Votre colis ne peut être livré ce jour, laccès à ladresse de livraison étant impossible. Il sera remis en livraison au plus tôt."
RENAEP,CITPAM,ANO,"Lespace Colis Cityssimo est momentanément hors service, le colis est rééxpédié au domicile du destinataire."
RENAIN,RENAIN,ANO,"Votre colis ne peut actuellement être livré au destinataire, ladresse de livraison étant incomplète. Le destinataire peut contacter notre service clients pour apporter les compléments nécessaires, en cliquant sur Nous contacter en ligne."
RENCAD,RENCAD,ANO,"Votre colis ne peut actuellement être livré à son destinataire, ladresse de livraison étant incomplète. Le destinataire peut contacter notre service clients pour apporter les compléments nécessaires, en cliquant sur Nous contacter en ligne."
RENCND,RENFCO,ANO,Colis en échec de livraison : plus de casier disponible dans la consigne choisie
RENDET,CITSPO,ANO,"Votre colis est déterioré et ne peut être livré dans un espace Cityssimo, il est rééxpédié au domicile du destinataire."
RENECO,CITNCG,ANO,Le colis ne peut être livré dans un automate de retrait Cityssimo. Le colis sera adressé au domicile du Destinataire.
RENEDI,CITDOC,ANO,Le colis ne peut être livré dans un automate de retrait Cityssimo en raison de labsence de coordonnées du destinataire. Le colis sera retourné à lexpéditeur.
RENFCO,RENFCO,ANO,"Votre colis na pas pu être livré ce jour, le point de retrait choisi étant fermé. Il sera remis en livraison au plus tôt."
RENINC,CITNCG,ANO,"Votre colis nest pas compatible avec une livraison dans un espace Cityssimo, il est rééxpédié au domicile du destinataire"
RENPPL,CITPAM,ANO,Le colis ne peut être livré dans un automate de retrait Cityssimo. Le colis sera adressé au domicile du Destinataire.
RENREF,DCHRMA,ANO,Lemballage de votre colis a été renforcé pour en assurer sa livraison. Il est en cours dacheminement.
RENREL,RENFCO,ANO,Votre colis ne peut être livré dans le point de retrait choisi. Le destinataire sera informé du nouveau point de livraison.
RENRES,RSTNCG,ANO,Votre colis ne peut être livré ce jour. Il sera remis en livraison au plus tôt.
RENSCR,RENFCO,ANO,Colis refusé par le point relais car il est en surcharge
RENVLM,RENFCO,ANO,Colis trop volumineux pour le casier ou pour le point relais choisi
RENVOL,CITNCG,ANO,Le colis ne peut être livré dans lautomate de retrait Cityssimo : sa taille nest pas adaptée au casier. Il sera adressé au domicile du Destinataire.
RSTACP,RSTFHB,ANO,"Votre colis ne peut être livré ce jour, laccès à ladresse de livraison étant impossible. Il sera remis en livraison au plus tôt."
RSTCAD,RENCAD,ANO,"Votre colis ne peut actuellement être livré à son destinataire, ladresse de livraison étant incomplète. Le destinataire peut contacter notre service clients pour apporter les compléments nécessaires, en cliquant sur Nous contacter en ligne."
RSTEMP,,ANO,Non affiché
RSTPRO,RSTPRO,ANO,"Le contenu de votre colis est prohibé, il ne pourra pas être livré à son destinataire."
RSTREF,,ANO,Non affiché
RSTRES,RSTNCG,ANO,Votre colis ne peut être livré ce jour. Il sera remis en livraison au plus tôt.
RSTTRI,,ANO,Non affiché
SCCDES,CHGRCA,ANO,"Suite à un incident, votre colis est en cours dacheminement avec un nouveau numéro."
SOLDOC,SOLMQD,ANO,"Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises."
SOLMAR,SOLMQD,ANO,"Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises."
SOLMQD,SOLMQD,ANO,"Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises."
SOLVOL,SOLMQD,ANO,"Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises."
1 clp_code inovert_code typology internal_text
2 LIVBPO LIVCFM LIV Votre colis est à disposition en boîte postale
3 LIVCFM LIVCFM LIV Votre colis est livré.
4 LIVDIV LIVCFM LIV Votre colis est livré mais le destinataire a signalé un emballage modérément dégradé.
5 LIVGAR LIVGAR LIV Votre colis a été livré au gardien.
6 LIVRCA LIVCFM LIV Votre colis est livré mais le destinataire a signalé un emballage fortement dégradé.
7 LIVRCC LIVCFM LIV Votre colis est livré mais le destinataire a signalé un emballage fortement dégradé.
8 LIVRTI LIVRTI LIV Votre colis a été livré au gardien ou à un voisin.
9 LIVVOI LIVVOI LIV Votre colis est livré au voisin indiqué sur l’avis déposé dans la boîte aux lettres du destinataire.
10 AACALI CITDOC ANO La livraison de votre colis dans un espace Cityssimo est impossible, le destinataire n’est pas abonné à ce service.
11 AACEDI CITDOC ANO Le colis ne peut être livré dans un automate de retrait Cityssimo en raison de l’absence de coordonnées du destinataire. Le colis sera retourné à l’expéditeur.
12 AARLIB ANO Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises.
13 AARTER AARDVY ANO Votre colis a subi une erreur de tri, il a maintenant repris son acheminement.
14 RCDDVY RCDDVY ANO Votre colis est réacheminé vers un autre site de distribution en raison d’un défaut d’adressage.
15 RDVABS RENARV ANO Votre colis n’a pu être livré car le destinataire était absent. Il sera prochainement recontacté pour convenir d’un nouveau rendez-vous.
16 RDVAIN RENAIN ANO Votre colis n’a pas pu être livré sur rendez-vous. Le destinataire doit choisir une date de livraison.
17 RDVINC RSTNCG ANO Votre colis n’a pas pu être livré sur rendez-vous. Le destinataire sera prochainement recontacté.
18 RDVREP RENAIN ANO Votre colis est prêt à être livré sur rendez-vous. Nous sommes en attente de votre choix de créneau horaire.
19 RECALI CITDOC ANO Votre colis n’a pas pu être livré dans l’espace Cityssimo suite à une erreur sur votre compte abonné
20 REFALI CITDOC ANO La livraison de votre colis dans l’espace Cityssimo est impossible, il est retourné à l’expéditeur.
21 REFCDS CHGRCA ANO L’emballage de votre colis a été renforcé pour en assurer sa livraison. Il est en cours d’acheminement.
22 REFCEX DCHRCA ANO Votre colis est retourné à l’expéditeur suite à un incident.
23 REFDDS CHGRCA ANO L’emballage de votre colis a été renforcé pour en assurer sa livraison. Il est en cours d’acheminement.
24 REFDEX DCHRCA ANO Votre colis est retourné à l’expéditeur suite à un incident.
25 REFISO DCHRMA ANO Votre colis et/ou son étiquette sont endommagés. Votre colis est en cours de traitement
26 RENACO CITDOC ANO La livraison de votre colis dans un espace Cityssimo est impossible. Le compte abonné est inactif ou résilié. Le colis est rééxpédié au domicile du destinataire.
27 RENACP RSTFMA ANO Votre colis ne peut être livré ce jour, l’accès à l’adresse de livraison étant impossible. Il sera remis en livraison au plus tôt.
28 RENAEP CITPAM ANO L’espace Colis Cityssimo est momentanément hors service, le colis est rééxpédié au domicile du destinataire.
29 RENAIN RENAIN ANO Votre colis ne peut actuellement être livré au destinataire, l’adresse de livraison étant incomplète. Le destinataire peut contacter notre service clients pour apporter les compléments nécessaires, en cliquant sur Nous contacter en ligne.
30 RENCAD RENCAD ANO Votre colis ne peut actuellement être livré à son destinataire, l’adresse de livraison étant incomplète. Le destinataire peut contacter notre service clients pour apporter les compléments nécessaires, en cliquant sur Nous contacter en ligne.
31 RENCND RENFCO ANO Colis en échec de livraison : plus de casier disponible dans la consigne choisie
32 RENDET CITSPO ANO Votre colis est déterioré et ne peut être livré dans un espace Cityssimo, il est rééxpédié au domicile du destinataire.
33 RENECO CITNCG ANO Le colis ne peut être livré dans un automate de retrait Cityssimo. Le colis sera adressé au domicile du Destinataire.
34 RENEDI CITDOC ANO Le colis ne peut être livré dans un automate de retrait Cityssimo en raison de l’absence de coordonnées du destinataire. Le colis sera retourné à l’expéditeur.
35 RENFCO RENFCO ANO Votre colis n’a pas pu être livré ce jour, le point de retrait choisi étant fermé. Il sera remis en livraison au plus tôt.
36 RENINC CITNCG ANO Votre colis n’est pas compatible avec une livraison dans un espace Cityssimo, il est rééxpédié au domicile du destinataire
37 RENPPL CITPAM ANO Le colis ne peut être livré dans un automate de retrait Cityssimo. Le colis sera adressé au domicile du Destinataire.
38 RENREF DCHRMA ANO L’emballage de votre colis a été renforcé pour en assurer sa livraison. Il est en cours d’acheminement.
39 RENREL RENFCO ANO Votre colis ne peut être livré dans le point de retrait choisi. Le destinataire sera informé du nouveau point de livraison.
40 RENRES RSTNCG ANO Votre colis ne peut être livré ce jour. Il sera remis en livraison au plus tôt.
41 RENSCR RENFCO ANO Colis refusé par le point relais car il est en surcharge
42 RENVLM RENFCO ANO Colis trop volumineux pour le casier ou pour le point relais choisi
43 RENVOL CITNCG ANO Le colis ne peut être livré dans l’automate de retrait Cityssimo : sa taille n’est pas adaptée au casier. Il sera adressé au domicile du Destinataire.
44 RSTACP RSTFHB ANO Votre colis ne peut être livré ce jour, l’accès à l’adresse de livraison étant impossible. Il sera remis en livraison au plus tôt.
45 RSTCAD RENCAD ANO Votre colis ne peut actuellement être livré à son destinataire, l’adresse de livraison étant incomplète. Le destinataire peut contacter notre service clients pour apporter les compléments nécessaires, en cliquant sur Nous contacter en ligne.
46 RSTEMP ANO Non affiché
47 RSTPRO RSTPRO ANO Le contenu de votre colis est prohibé, il ne pourra pas être livré à son destinataire.
48 RSTREF ANO Non affiché
49 RSTRES RSTNCG ANO Votre colis ne peut être livré ce jour. Il sera remis en livraison au plus tôt.
50 RSTTRI ANO Non affiché
51 SCCDES CHGRCA ANO Suite à un incident, votre colis est en cours d’acheminement avec un nouveau numéro.
52 SOLDOC SOLMQD ANO Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises.
53 SOLMAR SOLMQD ANO Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises.
54 SOLMQD SOLMQD ANO Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises.
55 SOLVOL SOLMQD ANO Votre colis a subi un incident. Nous vous remercions de prendre contact avec notre service clients, au 3631 pour les clients Particuliers auprès de vos interlocuteurs habituels pour les clients Entreprises.

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,124 @@
<?php
/**
* Class ColissimoClient
*/
class ColissimoClient
{
const BASE_URL_PRODUCTION = 'https://ws.colissimo.fr';
const BASE_URL_TEST = 'https://ws.colissimo.fr';
const COLISSIMO_WSDL = 'https://ws.colissimo.fr/sls-ws/SlsServiceWS/2.0?wsdl';
/** @var string $baseUrl */
protected $baseUrl;
/** @var AbstractColissimoRequest $request */
private $request;
/**
* ColissimoClient constructor.
* @param int $mode
* @param array $urls
*/
public function __construct($mode = 0, $urls = array())
{
if (is_array($urls) && isset($urls['test']) && isset($urls['production'])) {
$this->baseUrl = (1 === $mode) ? $urls['production'] : $urls['test'];
} else {
$this->baseUrl = (1 === $mode) ? self::BASE_URL_PRODUCTION : self::BASE_URL_TEST;
}
}
/**
* @return mixed
* @throws Exception
*/
public function request()
{
$wsType = constant(get_class($this->request).'::WS_TYPE');
switch ($wsType) {
case 'SOAP':
$method = constant(get_class($this->request).'::WS_METHOD');
$soapClient = new SoapClient(
self::COLISSIMO_WSDL, array(
'exceptions' => 0,
'wsdl_cache' => 0,
'trace' => 1,
'soap_version' => SOAP_1_1,
'encoding' => 'UTF-8',
)
);
$responseBody = $soapClient->__doRequest(
$this->request->getRequest(),
self::COLISSIMO_WSDL,
$method,
'2.0',
0
);
$responseHeader = $soapClient->__getLastResponseHeaders();
preg_match("/HTTP\/\d\.\d\s*\K[\d]+/", $responseHeader, $matches);
$httpCode = $matches[0];
break;
case 'CURL':
if ($this->request->forceEndpoint) {
$url = $this->request->forceEndpoint;
} else {
$url = $this->baseUrl.constant(get_class($this->request).'::WS_PATH');
}
$contentType = array();
if (defined(get_class($this->request).'::WS_CONTENT_TYPE')) {
$contentType = array('Content-Type: '.constant(get_class($this->request).'::WS_CONTENT_TYPE'));
}
$body = $this->request->getRequest();
$curl = curl_init();
curl_setopt_array(
$curl,
array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $body,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_HEADER => true,
CURLOPT_VERBOSE => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => $contentType,
)
);
$response = curl_exec($curl);
if ($response === false) {
throw new Exception('Empty Response.');
}
$curlInfo = curl_getinfo($curl);
$curlError = curl_errno($curl);
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$responseHeader = substr($response, 0, $headerSize);
$responseBody = substr($response, $headerSize);
curl_close($curl);
$httpCode = $curlInfo['http_code'];
if ($curlError) {
throw new Exception('cURL error: '.$curlError);
}
break;
default:
throw new Exception('Wrong WS call.');
break;
}
if (!in_array($httpCode, array(200, 201, 400))) {
throw new Exception('Bad HTTP code: '.$httpCode);
}
return $this->request->buildResponse($responseHeader, $responseBody);
}
/**
* @param AbstractColissimoRequest $request
*/
public function setRequest(AbstractColissimoRequest $request)
{
$this->request = $request;
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* Class AbstractColissimoRequest
*/
abstract class AbstractColissimoRequest
{
/** @var array $request */
protected $request;
/** @var string $xmlLocation */
protected $xmlLocation;
/** @var string $forceEndpoint */
public $forceEndpoint;
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
*/
abstract public function buildResponse($responseHeader, $responseBody);
/**
* @return mixed
*/
abstract public function buildRequest();
/**
* AbstractColissimoRequest constructor.
* @param array $credentials
* @throws Exception
*/
public function __construct(array $credentials)
{
if (!isset($credentials['contract_number']) || !isset($credentials['password'])) {
throw new Exception('Bad credentials.');
}
$this->setIdentification($credentials);
$this->xmlLocation = dirname(__FILE__).'/../xml/';
}
/**
* @param array $credentials
*/
final private function setIdentification(array $credentials)
{
$this->request = array();
$this->request['contractNumber'] = $credentials['contract_number'];
$this->request['password'] = $credentials['password'];
if (isset($credentials['force_endpoint'])) {
$this->forceEndpoint = $credentials['force_endpoint'];
}
}
/**
* @param bool $obfuscatePassword
* @return array|string
*/
public function getRequest($obfuscatePassword = false)
{
if ($obfuscatePassword) {
$request = $this->request;
$request['password'] = '*****';
$request['contractNumber'] = '*****';
return json_encode($request);
}
return json_encode($this->request);
}
}

View File

@@ -0,0 +1,22 @@
<?php
/**
* Class ColissimoCheckGenerateLabelRequest
*/
class ColissimoCheckGenerateLabelRequest extends ColissimoGenerateLabelRequest
{
const WS_TYPE = 'CURL';
const WS_PATH = '/sls-ws/SlsServiceWSRest/2.0/checkGenerateLabel?';
const WS_CONTENT_TYPE = 'application/json';
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoCheckGenerateLabelResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* Class ColissimoGenerateBordereauRequest
*/
class ColissimoGenerateBordereauRequest extends AbstractColissimoRequest
{
const WS_TYPE = 'SOAP';
const WS_METHOD = 'generateBordereauByParcelsNumbers';
const WS_CONTENT_TYPE = 'application/xml';
/** @var SimpleXMLElement $xml */
public $xml;
/**
* ColissimoGenerateBordereauRequest constructor.
* @param array $credentials
* @throws Exception
*/
public function __construct(array $credentials)
{
parent::__construct($credentials);
$this->xml = simplexml_load_file($this->xmlLocation.self::WS_METHOD.'.xml');
$this->xml->registerXPathNamespace('sls', 'http://sls.ws.coliposte.fr');
$this->setCredentials();
}
/**
* @param array $numbers
*/
public function setParcelsNumbers(array $numbers)
{
$list = $this->xml->xpath('soapenv:Body/sls:generateBordereauByParcelsNumbers/generateBordereauParcelNumberList');
foreach ($numbers as $number) {
$list[0]->addChild('parcelsNumbers', $number);
}
}
/**
*
*/
public function setCredentials()
{
$parcels = $this->xml->xpath('soapenv:Body/sls:generateBordereauByParcelsNumbers');
$parcels[0]->contractNumber = $this->request['contractNumber'];
$parcels[0]->password = $this->request['password'];
}
/**
* @return mixed|void
*/
public function buildRequest()
{
return;
}
/**
* @param bool $obfuscatePassword
* @return string
*/
public function getRequest($obfuscatePassword = false)
{
if ($obfuscatePassword) {
$requestXml = new SimpleXMLElement($this->xml->asXML());
$requestXml->registerXPathNamespace('sls', 'http://sls.ws.coliposte.fr');
$parcels = $requestXml->xpath('soapenv:Body/sls:generateBordereauByParcelsNumbers');
$parcels[0]->password = '****';
$parcels[0]->contractNumber = '****';
$requestJsonString = json_encode($parcels);
return $requestJsonString;
}
return $this->xml->asXML();
}
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoGenerateBordereauResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,142 @@
<?php
/**
* Class ColissimoGenerateLabelRequest
*/
class ColissimoGenerateLabelRequest extends AbstractColissimoRequest
{
const WS_TYPE = 'CURL';
const WS_PATH = '/sls-ws/SlsServiceWSRest/2.0/generateLabel?';
const WS_CONTENT_TYPE = 'application/json';
/** @var array $output */
protected $output;
/** @var array $senderAddress */
protected $senderAddress;
/** @var array $addresseeAddress */
protected $addresseeAddress;
/** @var array $shipmentOptions */
protected $shipmentOptions;
/** @var array $shipmentServices */
protected $shipmentServices;
/** @var array $customsOptions */
protected $customsOptions;
/** @var array $fields */
protected $fields;
/**
* @param array $output
* @return ColissimoGenerateLabelRequest
*/
public function setOutput($output)
{
$this->output = $output;
return $this;
}
/**
* @param array $senderAddress
* @return ColissimoGenerateLabelRequest
*/
public function setSenderAddress($senderAddress)
{
$this->senderAddress = $senderAddress;
return $this;
}
/**
* @param array $addresseeAddress
* @return ColissimoGenerateLabelRequest
*/
public function setAddresseeAddress($addresseeAddress)
{
$this->addresseeAddress = $addresseeAddress;
return $this;
}
/**
* @param array $shipmentOptions
* @return ColissimoGenerateLabelRequest
*/
public function setShipmentOptions($shipmentOptions)
{
$this->shipmentOptions = $shipmentOptions;
return $this;
}
/**
* @param array $shipmentServices
* @return ColissimoGenerateLabelRequest
*/
public function setShipmentServices($shipmentServices)
{
$this->shipmentServices = $shipmentServices;
return $this;
}
/**
* @param array $customsOptions
* @return ColissimoGenerateLabelRequest
*/
public function setCustomsOptions($customsOptions)
{
$this->customsOptions = $customsOptions;
return $this;
}
/**
* @param array $customField
* @return ColissimoGenerateLabelRequest
*/
public function addCustomField($customField)
{
foreach ($customField as $key => $field) {
$this->fields['customField'][$key] = array(
'key' => $field['key'],
'value' => $field['value'],
);
}
return $this;
}
/**
* @return mixed|void
*/
public function buildRequest()
{
$this->request['outputFormat'] = $this->output;
$this->request['letter']['service'] = $this->shipmentServices;
$this->request['letter']['parcel'] = $this->shipmentOptions;
if (!empty($this->customsOptions)) {
$this->request['letter']['customsDeclarations'] = $this->customsOptions;
}
$this->request['letter']['sender'] = $this->senderAddress;
$this->request['letter']['addressee'] = $this->addresseeAddress;
$this->request['fields'] = $this->fields;
}
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoGenerateLabelResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,44 @@
<?php
/**
* Class ColissimoMailboxDetailsRequest
*/
class ColissimoMailboxDetailsRequest extends AbstractColissimoRequest
{
const WS_TYPE = 'CURL';
const WS_PATH = '/sls-ws/SlsServiceWSRest/2.0/getListMailBoxPickingDates?';
const WS_CONTENT_TYPE = 'application/json';
/** @var array $senderAddress */
protected $senderAddress;
/**
* @param mixed $senderAddress
* @return ColissimoMailboxDetailsRequest
*/
public function setSenderAddress($senderAddress)
{
$this->senderAddress = $senderAddress;
return $this;
}
/**
* @return void
*/
public function buildRequest()
{
$this->request['sender'] = $this->senderAddress;
}
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoMailboxDetailsResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* Class ColissimoPlanPickupRequest
*/
class ColissimoPlanPickupRequest extends AbstractColissimoRequest
{
const WS_TYPE = 'CURL';
const WS_PATH = '/sls-ws/SlsServiceWSRest/2.0/planPickup?';
const WS_CONTENT_TYPE = 'application/json';
/** @var string $parcelNumber */
protected $parcelNumber;
/** @var string $mailboxPickingDate */
protected $mailboxPickingDate;
/** @var array $senderAddress */
protected $senderAddress;
/**
* @param string $parcelNumber
* @return ColissimoPlanPickupRequest
*/
public function setParcelNumber($parcelNumber)
{
$this->parcelNumber = $parcelNumber;
return $this;
}
/**
* @param string $mailboxPickingDate
* @return ColissimoPlanPickupRequest
*/
public function setMailboxPickingDate($mailboxPickingDate)
{
$this->mailboxPickingDate = $mailboxPickingDate;
return $this;
}
/**
* @param array $senderAddress
* @return ColissimoPlanPickupRequest
*/
public function setSenderAddress($senderAddress)
{
$this->senderAddress = $senderAddress;
return $this;
}
/**
* @return void
*/
public function buildRequest()
{
$this->request['parcelNumber'] = $this->parcelNumber;
$this->request['mailBoxPickingDate'] = $this->mailboxPickingDate;
$this->request['sender'] = $this->senderAddress;
}
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoPlanPickupResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,92 @@
<?php
/**
* Class ColissimoTrackingEnrichiRequest
*/
class ColissimoTrackingEnrichiRequest extends AbstractColissimoRequest
{
const WS_TYPE = 'CURL';
const WS_PATH = '/tracking-unified-ws/TrackingUnifiedServiceWSRest/tracking/getTrackingMessagePickupAdressAndDeliveryDate?';
const WS_CONTENT_TYPE = 'application/json';
const TRACKING_SUBMISSION_CONTACT = 'TRACKING_PARTNER';
/** @var string $lang */
protected $lang;
/** @var string $ip */
protected $ip;
/** @var string $parcelNumber */
protected $parcelNumber;
/**
* ColissimoTrackingEnrichiRequest constructor.
* @param array $credentials
* @throws Exception
*/
public function __construct(array $credentials)
{
parent::__construct($credentials);
$this->request['login'] = $this->request['contractNumber'];
unset($this->request['contractNumber']);
}
/**
* @param mixed $lang
* @return ColissimoTrackingEnrichiRequest
*/
public function setLang($lang)
{
$this->lang = $lang;
return $this;
}
/**
* @param mixed $ip
* @return ColissimoTrackingEnrichiRequest
*/
public function setIp($ip)
{
$this->ip = $ip;
return $this;
}
/**
* @param mixed $parcelNumber
* @return ColissimoTrackingEnrichiRequest
*/
public function setParcelNumber($parcelNumber)
{
$this->parcelNumber = $parcelNumber;
return $this;
}
/**
* @return void
*/
public function buildRequest()
{
$this->request['parcelNumber'] = $this->parcelNumber;
$this->request['ip'] = $this->ip;
$this->request['lang'] = $this->lang;
$this->request['parcelNumber'] = $this->parcelNumber;
$this->request['profil'] = self::TRACKING_SUBMISSION_CONTACT;
return;
}
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoTrackingEnrichiResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* Class ColissimoTrackingSimpleRequest
*/
class ColissimoTrackingSimpleRequest extends AbstractColissimoRequest
{
const WS_TYPE = 'CURL';
const WS_PATH = '/tracking-chargeur-cxf/TrackingServiceWS/track';
const WS_CONTENT_TYPE = 'application/xml;charset=UTF-8';
/** @var SimpleXMLElement $xml */
public $xml;
/**
* ColissimoTrackingSimpleRequest constructor.
* @param array $credentials
* @throws Exception
*/
public function __construct(array $credentials)
{
parent::__construct($credentials);
$this->xml = simplexml_load_file($this->xmlLocation.'track.xml');
$this->xml->registerXPathNamespace('char', 'http://chargeur.tracking.geopost.com');
$this->setCredentials();
}
/**
*
*/
public function setCredentials()
{
$track = $this->xml->xpath('soapenv:Body/char:track');
$track[0]->accountNumber = $this->request['contractNumber'];
$track[0]->password = $this->request['password'];
}
public function setSkybillNumber($skybillNumber)
{
$track = $this->xml->xpath('soapenv:Body/char:track');
$track[0]->skybillNumber = $skybillNumber;
}
/**
* @return mixed|void
*/
public function buildRequest()
{
return;
}
/**
* @param bool $obfuscatePassword
* @return string
*/
public function getRequest($obfuscatePassword = false)
{
if ($obfuscatePassword) {
$requestXml = new SimpleXMLElement($this->xml->asXML());
$requestXml->registerXPathNamespace('char', 'http://chargeur.tracking.geopost.com');
$track = $requestXml->xpath('soapenv:Body/char:track');
$track[0]->password = '****';
$track[0]->accountNumber = '****';
$requestJsonString = json_encode($track);
return $requestJsonString;
}
return $this->xml->asXML();
}
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoTrackingSimpleResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,44 @@
<?php
/**
* Class ColissimoTrackingTimelineRequest
*/
class ColissimoTrackingTimelineRequest extends ColissimoTrackingEnrichiRequest
{
const WS_PATH = '/tracking-timeline-ws/rest/tracking/timeline';
const TRACKING_PROFILE = 'TRACKING_BNUM';
/** @var string $lang */
protected $lang;
/** @var string $ip */
protected $ip;
/** @var string $parcelNumber */
protected $parcelNumber;
/**
* @return void
*/
public function buildRequest()
{
$this->request['parcelNumber'] = $this->parcelNumber;
$this->request['ip'] = $this->ip;
$this->request['lang'] = $this->lang;
$this->request['parcelNumber'] = $this->parcelNumber;
$this->request['profil'] = self::TRACKING_PROFILE;
return;
}
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoTrackingTimelineResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* Class ColissimoWidgetAuthenticationRequest
*/
class ColissimoWidgetAuthenticationRequest extends AbstractColissimoRequest
{
const WS_TYPE = 'CURL';
const WS_PATH = '/widget-point-retrait/rest/authenticate.rest';
const WS_CONTENT_TYPE = 'application/x-www-form-urlencoded';
/**
* ColissimoWidgetAuthenticationRequest constructor.
* @param array $credentials
* @throws Exception
*/
public function __construct(array $credentials)
{
parent::__construct($credentials);
$this->request['login'] = $this->request['contractNumber'];
unset($this->request['contractNumber']);
}
/**
* @return void
*/
public function buildRequest()
{
return;
}
/**
* @param bool $obfuscatePassword
* @return array|string
*/
public function getRequest($obfuscatePassword = false)
{
if ($obfuscatePassword) {
$request = $this->request;
$request['password'] = '****';
return json_encode($request);
}
return http_build_query($this->request);
}
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public function buildResponse($responseHeader, $responseBody)
{
return ColissimoWidgetAuthenticationResponse::buildFromResponse($responseHeader, $responseBody);
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,13 @@
<?php
/**
* Class AbstractColissimoResponse
*/
class AbstractColissimoResponse
{
/** @var array $messages */
public $messages;
/** @var array $response */
public $response;
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* Class ColissimoCheckGenerateLabelResponse
*/
class ColissimoCheckGenerateLabelResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$checkGenerateLabelResponse = new self();
$responseArray = json_decode($responseBody, true);
if (!empty($responseArray)) {
$checkGenerateLabelResponse->messages = $responseArray['messages'];
$checkGenerateLabelResponse->response = $responseArray;
}
return $checkGenerateLabelResponse;
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* Class ColissimoGenerateBordereauResponse
*/
class ColissimoGenerateBordereauResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
/** @var string $bordereau */
public $bordereau;
/** @var array $bordereauHeader */
public $bordereauHeader;
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$soapResponseParser = new ColissimoResponseParser();
try {
$parsedResponse = $soapResponseParser->parseBody($responseBody);
$parsedHeaders = $soapResponseParser->parseHeaders($responseHeader);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
$generateBordereauResponse = new self();
$contentType = $soapResponseParser->parseContentType($parsedHeaders);
if (isset($parsedResponse[$contentType])) {
$xml = new SimpleXMLElement($parsedResponse[$contentType]);
$xml->registerXPathNamespace('ns2', 'http://sls.ws.coliposte.fr');
$xml->registerXPathNamespace('xop', 'http://www.w3.org/2004/08/xop/include');
$bordereau = $xml->xpath('soap:Body/ns2:generateBordereauByParcelsNumbersResponse/return/bordereau/bordereauDataHandler/xop:Include');
if (!empty($bordereau)) {
$cidBordereau = substr($bordereau[0]->attributes()->href->__toString(), 4);
if (isset($parsedResponse['<'.$cidBordereau.'>'])) {
$generateBordereauResponse->bordereau = base64_encode($parsedResponse['<'.$cidBordereau.'>']);
}
}
$bordereauHeader = $xml->xpath('soap:Body/ns2:generateBordereauByParcelsNumbersResponse/return/bordereau/bordereauHeader');
if (!empty($bordereauHeader)) {
$generateBordereauResponse->bordereauHeader = json_decode(json_encode($bordereauHeader[0]), true);
$generateBordereauResponse->response['bordereauHeader'] = $generateBordereauResponse->bordereauHeader;
}
$messages = $xml->xpath('soap:Body/ns2:generateBordereauByParcelsNumbersResponse/return/messages');
$generateBordereauResponse->messages = json_decode(json_encode($messages), true);
$generateBordereauResponse->response['messages'] = $generateBordereauResponse->messages;
}
return $generateBordereauResponse;
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* Class ColissimoGenerateLabelResponse
*/
class ColissimoGenerateLabelResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
/** @var string $label */
public $label;
/** @var string $cn23 */
public $cn23;
/** @var string $parcelNumber */
public $parcelNumber;
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$jsonResponseParser = new ColissimoResponseParser();
try {
$parsedResponse = $jsonResponseParser->parseBody($responseBody);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
$generateLabelResponse = new self();
if (isset($parsedResponse['<jsonInfos>'])) {
$generateLabelResponse->response = json_decode($parsedResponse['<jsonInfos>'], true);
$generateLabelResponse->messages = $generateLabelResponse->response['messages'];
}
if (isset($generateLabelResponse->response['labelV2Response']['parcelNumber'])) {
$generateLabelResponse->parcelNumber = $generateLabelResponse->response['labelV2Response']['parcelNumber'];
}
if (isset($parsedResponse['<label>'])) {
$generateLabelResponse->label = base64_encode($parsedResponse['<label>']);
}
if (isset($parsedResponse['<cn23>'])) {
$generateLabelResponse->cn23 = base64_encode($parsedResponse['<cn23>']);
}
return $generateLabelResponse;
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* Class ColissimoMailboxDetailsResponse
*/
class ColissimoMailboxDetailsResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
/** @var string $maxPickingHour */
public $maxPickingHour;
/** @var string $validityTime */
public $validityTime;
/** @var array $pickingDates */
public $pickingDates;
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$mailboxDetailsResponse = new self();
$responseArray = json_decode($responseBody, true);
if (!empty($responseArray)) {
$mailboxDetailsResponse->messages = $responseArray['messages'];
$mailboxDetailsResponse->response = $responseArray;
if (isset($responseArray['mailBoxPickingDateMaxHour'])) {
$mailboxDetailsResponse->maxPickingHour = $responseArray['mailBoxPickingDateMaxHour'];
}
if (isset($responseArray['validityTime'])) {
$mailboxDetailsResponse->validityTime = $responseArray['validityTime'];
}
if (isset($responseArray['mailBoxPickingDates'])) {
foreach ($responseArray['mailBoxPickingDates'] as $mailBoxPickingDate) {
$mailboxDetailsResponse->pickingDates[] = $mailBoxPickingDate / 1000;
}
}
}
return $mailboxDetailsResponse;
}
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* Class ColissimoPlanPickupResponse
*/
class ColissimoPlanPickupResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$planPickupResponse = new self();
$responseArray = json_decode($responseBody, true);
if (!empty($responseArray)) {
$planPickupResponse->messages = $responseArray['messages'];
$planPickupResponse->response = $responseArray;
}
return $planPickupResponse;
}
}

View File

@@ -0,0 +1,149 @@
<?php
/**
* Class ColissimoResponseParser
*/
class ColissimoResponseParser
{
/** Regex for separator */
const UUID = '/--uuid:/';
/** New line character in Response */
const NEW_LINE_CHAR = "\r\n";
/** @var string $uuid */
private $uuid;
/**
* @param string $rawHeaders
* @return array
*/
public function parseHeaders($rawHeaders)
{
$headers = array();
$key = '';
foreach (explode("\n", $rawHeaders) as $i => $h) {
$h = explode(':', $h, 2);
if (isset($h[1])) {
if (!isset($headers[$h[0]])) {
$headers[$h[0]] = trim($h[1]);
} elseif (is_array($headers[$h[0]])) {
$headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1])));
} else {
$headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1])));
}
$key = $h[0];
} else {
if (substr($h[0], 0, 1) == "\t") {
$headers[$key] .= "\r\n\t".trim($h[0]);
} elseif (!$key) {
$headers[0] = trim($h[0]);
}
}
}
return $headers;
}
/**
* @param string $body
* @return array
* @throws Exception
*/
public function parseBody($body)
{
$contents = $this->splitContent($body);
if (!is_array($contents) || empty($contents)) {
throw new Exception('Empty response.');
}
$parsedResponse = array();
foreach ($contents as $content) {
if ($this->uuid == null) {
$uuidStart = strpos($content, self::UUID, 0) + strlen(self::UUID);
$uuidEnd = strpos($content, self::NEW_LINE_CHAR, $uuidStart);
$this->uuid = substr($content, $uuidStart, $uuidEnd - $uuidStart);
}
$headers = $this->extractHeader($content);
if (count($headers) > 0) {
if (isset($headers['Content-ID'])) {
$parsedResponse[$headers['Content-ID']] = trim(substr($content, $headers['offsetEnd']));
}
}
}
if (empty($parsedResponse)) {
throw new Exception('Response cannot be parsed.');
}
return $parsedResponse;
}
/**
* @param array $parsedHeaders
* @return bool|string
*/
public function parseContentType($parsedHeaders)
{
if (!isset($parsedHeaders['Content-Type'])) {
return false;
}
$contentTypes = explode(';', $parsedHeaders['Content-Type']);
foreach ($contentTypes as $contentType) {
if (strpos($contentType, 'start=') !== false) {
return substr($contentType, 8, -1);
}
}
return false;
}
/**
* @param string $response
* @return array
*/
private static function splitContent($response)
{
$contents = array();
$matches = array();
preg_match_all(self::UUID, $response, $matches, PREG_OFFSET_CAPTURE);
for ($i = 0; $i < count($matches[0]) - 1; $i++) {
if ($i + 1 < count($matches[0])) {
$contents[$i] = substr(
$response,
$matches[0][$i][1],
$matches[0][$i + 1][1] - $matches[0][$i][1]
);
} else {
$contents[$i] = substr(
$response,
$matches[0][$i][1],
strlen($response)
);
}
}
return $contents;
}
/**
* @param string $part
* @return array
*/
private function extractHeader($part)
{
$header = array();
$headerLineStart = strpos($part, 'Content-', 0);
$endLine = 0;
while ($headerLineStart !== false) {
$header['offsetStart'] = $headerLineStart;
$endLine = strpos($part, self::NEW_LINE_CHAR, $headerLineStart);
$headerLine = explode(': ', substr($part, $headerLineStart, $endLine - $headerLineStart));
$header[$headerLine[0]] = $headerLine[1];
$headerLineStart = strpos($part, 'Content-', $endLine);
}
$header['offsetEnd'] = $endLine;
return $header;
}
}

View File

@@ -0,0 +1,14 @@
<?php
/**
* Interface ColissimoReturnedResponseInterface
*/
interface ColissimoReturnedResponseInterface
{
/**
* @param string $responseHeader
* @param string $responseBody
* @return mixed
*/
public static function buildFromResponse($responseHeader, $responseBody);
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* Class ColissimoTrackingEnrichiResponse
*/
class ColissimoTrackingEnrichiResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
/** @var array $parcel */
public $parcel;
/** @var array $error */
public $error;
/** @var array $message */
public $message;
/** @var string $code */
public $code;
/** @var string $messageCode */
public $messageCode;
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$trackingEnrichiResponse = new self();
$responseArray = json_decode($responseBody, true);
if (!empty($responseArray)) {
$trackingEnrichiResponse->response = $responseArray;
if (isset($responseArray['code'])) {
$trackingEnrichiResponse->code = $responseArray['code'];
}
if (isset($responseArray['messageCode'])) {
$trackingEnrichiResponse->messageCode = $responseArray['messageCode'];
}
if (isset($responseArray['message'])) {
$trackingEnrichiResponse->message = $responseArray['message'];
}
if (isset($responseArray['error'])) {
$trackingEnrichiResponse->error = $responseArray['error'];
}
if (isset($responseArray['parcel'])) {
$trackingEnrichiResponse->parcel = $responseArray['parcel'];
}
}
return $trackingEnrichiResponse;
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* Class ColissimoTrackingSimpleResponse
*/
class ColissimoTrackingSimpleResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
public $errorMessage;
public $errorCode;
public $eventCode;
public $eventDate;
public $eventLibelle;
public $eventSite;
public $recipientCity;
public $recipientCountryCode;
public $recipientZipCode;
public $skybillNumber;
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$trackingSimpleResponse = new self();
$xml = new SimpleXMLElement($responseBody);
$xml->registerXPathNamespace('ns1', 'http://chargeur.tracking.geopost.com/');
$return = $xml->xpath('soap:Body/ns1:trackResponse/return');
$array = json_decode(json_encode($return[0]), true);
$trackingSimpleResponse->errorMessage = isset($array['errorMessage']) ? $array['errorMessage'] : null;
$trackingSimpleResponse->errorCode = isset($array['errorCode']) ? $array['errorCode'] : null;
$trackingSimpleResponse->eventCode = isset($array['eventCode']) ? $array['eventCode'] : null;
$trackingSimpleResponse->eventDate = isset($array['eventDate']) ? $array['eventDate'] : null;
$trackingSimpleResponse->eventLibelle = isset($array['eventLibelle']) ? $array['eventLibelle'] : null;
$trackingSimpleResponse->eventSite = isset($array['eventSite']) ? $array['eventSite'] : null;
$trackingSimpleResponse->recipientCity = isset($array['recipientCity']) ? $array['recipientCity'] : null;
$trackingSimpleResponse->recipientCountryCode = isset($array['recipientCountryCode']) ? $array['recipientCountryCode'] : null;
$trackingSimpleResponse->recipientZipCode = isset($array['recipientZipCode']) ? $array['recipientZipCode'] : null;
$trackingSimpleResponse->skybillNumber = isset($array['skybillNumber']) ? $array['skybillNumber'] : null;
return $trackingSimpleResponse;
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* Class ColissimoTrackingTimelineResponse
*/
class ColissimoTrackingTimelineResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
/** @var array $status */
public $status;
/** @var array $userMessages */
public $userMessages;
/** @var array $parcelDetails */
public $parcelDetails;
/** @var array $events */
public $events;
/** @var array $timeline */
public $timeline;
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$trackingTimelineResponse = new self();
$responseArray = json_decode($responseBody, true);
if (!empty($responseArray)) {
$trackingTimelineResponse->response = $responseArray;
if (isset($responseArray['status'])) {
$trackingTimelineResponse->status = $responseArray['status'];
}
if (isset($responseArray['message'])) {
$trackingTimelineResponse->userMessages = $responseArray['message'];
}
if (isset($responseArray['parcel'])) {
$trackingTimelineResponse->parcelDetails = $responseArray['parcel'];
if (isset($responseArray['parcel']['event'])) {
$trackingTimelineResponse->events = $responseArray['parcel']['event'];
unset($trackingTimelineResponse->parcelDetails['event']);
}
if (isset($responseArray['parcel']['step'])) {
$trackingTimelineResponse->timeline = $responseArray['parcel']['step'];
unset($trackingTimelineResponse->parcelDetails['step']);
}
}
}
return $trackingTimelineResponse;
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Class ColissimoWidgetAuthenticationResponse
*/
class ColissimoWidgetAuthenticationResponse extends AbstractColissimoResponse implements ColissimoReturnedResponseInterface
{
/** @var string $token */
public $token;
/**
* @param mixed $responseHeader
* @param mixed $responseBody
* @return mixed
* @throws Exception
*/
public static function buildFromResponse($responseHeader, $responseBody)
{
$widgetAuthenticationResponse = new self();
$responseArray = json_decode($responseBody, true);
if (!empty($responseArray)) {
$widgetAuthenticationResponse->response = $responseArray;
$widgetAuthenticationResponse->token = $responseArray['token'];
}
return $widgetAuthenticationResponse;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,25 @@
<?php
require_once(dirname(__FILE__).'/ColissimoClient.php');
require_once(dirname(__FILE__).'/Request/AbstractColissimoRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoGenerateLabelRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoGenerateBordereauRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoWidgetAuthenticationRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoMailboxDetailsRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoTrackingEnrichiRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoTrackingSimpleRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoCheckGenerateLabelRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoPlanPickupRequest.php');
require_once(dirname(__FILE__).'/Request/ColissimoTrackingTimelineRequest.php');
require_once(dirname(__FILE__).'/Response/ColissimoReturnedResponseInterface.php');
require_once(dirname(__FILE__).'/Response/AbstractColissimoResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoResponseParser.php');
require_once(dirname(__FILE__).'/Response/ColissimoGenerateLabelResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoGenerateBordereauResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoWidgetAuthenticationResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoMailboxDetailsResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoTrackingEnrichiResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoTrackingSimpleResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoCheckGenerateLabelResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoPlanPickupResponse.php');
require_once(dirname(__FILE__).'/Response/ColissimoTrackingTimelineResponse.php');

View File

@@ -0,0 +1,13 @@
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sls="http://sls.ws.coliposte.fr">
<soapenv:Header/>
<soapenv:Body>
<sls:generateBordereauByParcelsNumbers>
<contractNumber></contractNumber>
<password></password>
<generateBordereauParcelNumberList>
<!-- 1 or more repetitions: -->
<!-- <parcelsNumbers>xxxxx</parcelsNumbers> -->
</generateBordereauParcelNumberList>
</sls:generateBordereauByParcelsNumbers>
</soapenv:Body>
</soapenv:Envelope>

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

View File

@@ -0,0 +1,11 @@
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:char="http://chargeur.tracking.geopost.com/">
<soapenv:Header/>
<soapenv:Body>
<char:track>
<accountNumber></accountNumber>
<password></password>
<skybillNumber></skybillNumber>
</char:track>
</soapenv:Body>
</soapenv:Envelope>

BIN
modules/colissimo/logo.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

BIN
modules/colissimo/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

View File

@@ -0,0 +1,2 @@
Order deny,allow
Deny from all

View File

@@ -0,0 +1,33 @@
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table services created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table order created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table label created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table deposit_slip created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table pickup_point created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table cart_pickup_point created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table shipment_tracking created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table tracking_code created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table mailbox_return created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table custom_category created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Table custom_product created. [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Creating carrier SANS_SIGNATURE [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Creating carrier AVEC_SIGNATURE [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Creating carrier RELAIS [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Services from CSV {"csv":{"SANS_SIGNATURE":[{"product_code":"DOM","commercial_name":"FR - DOMICILE sans signature","destination_type":"FRANCE","is_signature":"0","is_pickup":"0","is_return":"0"},{"product_code":"COM","commercial_name":"OM - DOMICILE sans signature","destination_type":"OM","is_signature":"0","is_pickup":"0","is_return":"0"},{"product_code":"DOM","commercial_name":"EU - DOMICILE sans signature","destination_type":"EUROPE","is_signature":"0","is_pickup":"0","is_return":"0"},{"product_code":"COLD","commercial_name":"DOM - DOMICILE sans signature","destination_type":"INTRA_DOM","is_signature":"0","is_pickup":"0","is_return":"0"}],"AVEC_SIGNATURE":[{"product_code":"DOS","commercial_name":"FR - DOMICILE avec signature","destination_type":"FRANCE","is_signature":"1","is_pickup":"0","is_return":"0"},{"product_code":"CDS","commercial_name":"OM - DOMICILE avec signature","destination_type":"OM","is_signature":"1","is_pickup":"0","is_return":"0"},{"product_code":"DOS","commercial_name":"EU - DOMICILE avec signature","destination_type":"EUROPE","is_signature":"1","is_pickup":"0","is_return":"0"},{"product_code":"COLI","commercial_name":"INT - DOMICILE avec signature","destination_type":"WORLDWIDE","is_signature":"1","is_pickup":"0","is_return":"0"},{"product_code":"COL","commercial_name":"DOM - DOMICILE avec signature","destination_type":"INTRA_DOM","is_signature":"1","is_pickup":"0","is_return":"0"}],"RELAIS":[{"product_code":"BPR","commercial_name":"FR - POINT RETRAIT","destination_type":"FRANCE","is_signature":"0","is_pickup":"1","is_return":"0"},{"product_code":"A2P","commercial_name":"FR - POINT RETRAIT","destination_type":"FRANCE","is_signature":"0","is_pickup":"1","is_return":"0"},{"product_code":"BDP","commercial_name":"EU - POINT RETRAIT","destination_type":"EUROPE","is_signature":"0","is_pickup":"1","is_return":"0"},{"product_code":"CMT","commercial_name":"EU - POINT RETRAIT","destination_type":"EUROPE","is_signature":"0","is_pickup":"1","is_return":"0"},{"product_code":"PCS","commercial_name":"EU - POINT RETRAIT","destination_type":"EUROPE","is_signature":"0","is_pickup":"1","is_return":"0"}],"RETOUR":[{"product_code":"CORE","commercial_name":"RETOUR FRANCE","destination_type":"FRANCE","is_signature":"0","is_pickup":"0","is_return":"1"},{"product_code":"CORI","commercial_name":"RETOUR OUTRE MER","destination_type":"OM","is_signature":"0","is_pickup":"0","is_return":"1"},{"product_code":"CORI","commercial_name":"RETOUR INTERNATIONAL","destination_type":"WORLDWIDE","is_signature":"0","is_pickup":"0","is_return":"1"}]}} []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service SANS_SIGNATURE: 1 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service SANS_SIGNATURE: 2 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service SANS_SIGNATURE: 3 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service SANS_SIGNATURE: 4 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service AVEC_SIGNATURE: 5 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service AVEC_SIGNATURE: 6 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service AVEC_SIGNATURE: 7 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service AVEC_SIGNATURE: 8 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service AVEC_SIGNATURE: 9 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service RELAIS: 10 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service RELAIS: 11 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service RELAIS: 12 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service RELAIS: 13 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service RELAIS: 14 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service RETOUR: 15 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service RETOUR: 16 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Saved service RETOUR: 17 [] []
[2020-10-05 18:36:06] Colissimo_1_4_0_Install.INFO: Tracking codes created. 0 errors thrown. [] []

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2020 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 PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2020 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../');
exit;

Some files were not shown because too many files have changed in this diff Show More