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

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;