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,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));
}
}
}