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;