Files
b2b.redline.com.pl/modules/inpostship/controllers/admin/AdminInpostshipDispatchHistoryController.php
2025-06-24 14:14:35 +02:00

552 lines
26 KiB
PHP

<?php
/**
* NOTICE OF LICENSE
*
* This file is licenced under the Software License Agreement.
* With the purchase or the installation of the software in your application
* you accept the licence agreement.
*
* You must not modify, adapt or create derivative works of this source code
*
* @author PrestaHelp.com
* @copyright 2019 PrestaHelp
* @license LICENSE.txt
*/
require_once __DIR__.'/../../classes/ShipX.php';
require_once __DIR__.'/../../classes/InpostPoint.php';
require_once __DIR__.'/../../classes/InpostPack.php';
require_once __DIR__.'/../../classes/InpostDispatch.php';
require_once __DIR__.'/../../classes/AuthDS.php';
require_once __DIR__.'/../../classes/PrintNodeApi.php';
class AdminInpostshipDispatchHistoryController extends ModuleAdminController
{
private $nameModule = 'inpostship';
public $shipx;
private $debug;
private $debug_shop;
private $perPage = 10;
private $plPage = 0;
public function __construct()
{
$this->bootstrap = true;
$this->className = 'AdminInpostshipDispatchHistory';
parent::__construct();
$this->debug = Configuration::get('INPOSTSHIP_DEBUG');
$this->debug_shop = Configuration::get('INPOSTSHIP_DEBUG_SHOP');
if ($this->debug_shop == 1) {
@ini_set('display_errors', 'on');
@error_reporting(E_ALL | E_STRICT);
}
$this->perPage = Configuration::get('INPOSTSHIP_PL_PERPAGE');
$this->shipx = new ShipX(Configuration::get('INPOSTSHIP_API_KEY'), (bool)Configuration::get('INPOSTSHIP_SANDBOX'), $this->debug);
}
private function isActiveModule()
{
$shop = new Shop((int)$this->context->shop->id);
$auth = new AuthDS($this->nameModule, $shop->getBaseURL());
return (int)$auth->checkLicence();
}
public function initPageHeaderToolbar()
{
parent::initPageHeaderToolbar();
}
public function initHeader()
{
parent::initHeader();
}
public function display()
{
if ($this->isActiveModule()) {
$tpl = 'dispatch-list.tpl';
} else {
$tpl = 'nolic.tpl';
}
$this->context->smarty->assign(array(
'content' => $this->context->smarty->fetch($this->getTemplatePath().$tpl)
));
parent::display();
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
}
public function initContent()
{
parent::initContent();
if ($this->isActiveModule()) {
$shop = new Shop((int)$this->context->shop->id);
$this->addJqueryUI('ui.tooltip');
$this->addJqueryUI('ui.popover');
$this->addJqueryUI('ui.datepicker');
$this->addCSS(__DIR__ . '/../../assets/css/phelp.css');
// $this->addCSS('//min.gitcdn.xyz/repo/wintercounter/Protip/master/protip.min.css');
$token = Tools::getAdminTokenLite('AdminOrders');
$tokenCustomer = Tools::getAdminTokenLite('AdminCustomers');
$tokenCusrrent = Tools::getAdminTokenLite('AdminInpostshipPackage');
$dispatch_order_list = $this->shipx->getDispatchOrder(Configuration::get('INPOSTSHIP_API_ORGANIZATION'));
$dispatch_orders = $dispatch_order_list['result']->items;
if (!empty($dispatch_orders)) {
foreach ($dispatch_orders as &$dispatch_order) {
$dispatch_order->date = date('Y-m-d H:i:s', strtotime($dispatch_order->created_at));
$dispatch_order->cena = $dispatch_order->price == null ? '-,--' : $dispatch_order->price;
}
}
// dump($dispatch_orders);
// die;
$module = Module::getInstanceByName('inpostship');
$mversion = $module->version;
$ssl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://';
/* prestahelp API - do not remove! */
$auth = new AuthDS('inpostship', $shop->getBaseURL());
$chlogInfo = $auth->getChangelog();
$chlogInfoOther = $auth->getChangelogOther();
$currentVersion = $auth->getCurrentModuleVersion();
/* prestahelp API - do not remove! */
$banersHtml = AuthDS::getBanersHtml();
$phelpTop = __DIR__ . '/../../views/templates/admin/phelp-top.tpl';
$phelpBtm = __DIR__ . '/../../views/templates/admin/phelp-bottom.tpl';
$moduleAssets = $ssl . $this->context->shop->domain . $this->context->shop->physical_uri . 'modules/inpostship/assets/';
$lastestVersion = $currentVersion['version'] == $mversion ? true : false;
$updateLink = 'https://modules.prestahelp.com/moduly/inpostship/inpostship' . $currentVersion['version'] . '.zip';
$indexLink = 'https://modules.prestahelp.com/moduly/inpostship/';
$ssl = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$request_uri = explode('&plPage', $_SERVER['REQUEST_URI']);
$currentPage = $ssl . $_SERVER['HTTP_HOST'] . $request_uri[0];
$pagination = array(
10, 25, 50, 100, 300
);
$licence = $auth->getLicence();
$this->context->smarty->assign(array(
'dispatch_orders' => $dispatch_orders,
'token' => $token,
'trackingUrl' => ShipX::TRACKING_PACKAGE_URL,
'printUrl' => $ssl . $this->context->shop->domain . '/' . basename(_PS_ADMIN_DIR_) . '/index.php?controller=AdminInpostShipPackage&token=' . $tokenCusrrent . '&printLabel=',
'dispatchUrl' => $ssl . $this->context->shop->domain . '/' . basename(_PS_ADMIN_DIR_) . '/index.php?controller=AdminInpostShipPackage&token=' . $tokenCusrrent . '&orderCourier=',
'banersHtml' => $banersHtml,
'phelpTop' => $phelpTop,
'phelpBtm' => $phelpBtm,
'chlogInfo' => $chlogInfo,
'chlogInfoOther' => $chlogInfoOther,
'moduleAssets' => $moduleAssets,
'lastestVersion' => $lastestVersion,
'updateLink' => $updateLink,
'indexLink' => $indexLink,
'moduleName' => $module->displayName,
'moduleNameInfo' => $module->name,
'moduleVersion' => $mversion,
'currentModuleVersion' => $currentVersion['version'],
'currentPage' => $currentPage,
'plPage' => $this->plPage + 1,
'updated_date' => date('d-m-Y', strtotime($licence['licence']->date_expire_update)),
'licence_update' => $licence['licence']->licence_update,
'support_date' =>date('d-m-Y', strtotime($licence['licence']->date_expire_support)),
'licence_date' => date('d-m-Y', strtotime($licence['licence']->date_expire)),
'activeted' => $licence,
'licence' => $licence['licence'],
'pagination' => $pagination,
'selected_pagination' => (int)Configuration::get('INPOSTSHIP_PL_PERPAGE'),
'pn_isset' => false,
));
}
}
public function postProcess()
{
parent::postProcess();
if (Tools::getIsset('submitGenerateLabels')) {
$labels = Tools::getValue('actions', array());
if (!empty($labels)) {
$format = Configuration::get('INPOSTSHIP_PRINT_FORMAT');
$file_name = 'etykiety-'.(date('Y-m-d-H-i-s'));
$content = $this->shipx->getMultiLabels((int)Configuration::get('INPOSTSHIP_API_ORGANIZATION'), $labels, Configuration::get('INPOSTSHIP_PRINT_TYPE'), $format);
$contents = $this->GetHeaders($content);
if (!empty($contents['file_type'])) {
switch ($contents['file_type']) {
case 'zip':case 'zip; filename*':
$file = time() . '-' . $contents['file'];
$dir = __DIR__ . '/../../files/' . $file;
file_put_contents($dir, $contents['http_code']);
$size = filesize($dir);
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: public');
header('Content-Type: application/zip');
header('Content-Transfer-Encoding: Binary');
header('Content-Length: ' . $size);
header('Content-Disposition: attachment; filename="' . basename($contents['file']) . '"');
ob_end_flush();
@readfile($dir);
exit();
break;
case 'pdf':case 'pdf; filename*':
$dir = __DIR__ . '/../../files/' . $contents['file'];
file_put_contents($dir, $contents['http_code']);
$size = filesize($dir);
header('Content-Type: application/pdf');
header('Content-Length: ' . $size);
header('Content-Disposition: attachment; filename="' . basename($contents['file']) . '"');
ob_end_flush();
@readfile($dir);
exit();
break;
case 'epl':
$dir = __DIR__ . '/../../files/' . $contents['file'];
file_put_contents($dir, $contents['http_code']);
$size = filesize($dir);
header('Content-Type: application/octet-stream');
header('Content-Length: ' . $size);
header('Content-Disposition: attachment; filename="' . basename($contents['file']) . '"');
ob_end_flush();
@readfile($dir);
exit();
break;
}
} else {
$this->context->smarty->assign(array(
'errors' => 'Brak pliku do pobrania!'
));
}
} else {
$this->context->smarty->assign(array(
'errors' => 'Brak wybranych przesyłek!'
));
}
}
if (Tools::getIsset('submitGenerateLabelsPrint')) {
$labels = Tools::getValue('actions', array());
if (!empty($labels)) {
$format = Configuration::get('INPOSTSHIP_PRINT_FORMAT');
$file_name = 'etykiety-'.(date('Y-m-d-H-i-s'));
$content = $this->shipx->getMultiLabels((int)Configuration::get('INPOSTSHIP_API_ORGANIZATION'), $labels, Configuration::get('INPOSTSHIP_PRINT_TYPE'), $format);
$contents = $this->GetHeaders($content);
if (!empty($contents['file_type'])) {
switch ($contents['file_type']) {
case 'zip':case 'zip; filename*':
$file = time() . '-' . $contents['file'];
$dir = __DIR__ . '/../../files/' . $file;
file_put_contents($dir, $contents['http_code']);
$size = filesize($dir);
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: public');
header('Content-Type: application/zip');
header('Content-Transfer-Encoding: Binary');
header('Content-Length: ' . $size);
header('Content-Disposition: attachment; filename="' . basename($contents['file']) . '"');
ob_end_flush();
@readfile($dir);
exit();
break;
case 'pdf':case 'pdf; filename*':
$fileName = explode(';', $contents['file']);
$fName = date('Y-m-d-H-i-s').'-'.$fileName[0];
$dir = __DIR__ . '/../../files/' . $fName;
file_put_contents($dir, $contents['http_code']);
$printer = (int)Configuration::get('INPOSTSHIP_PRINTNODE_PRINTER');
$errors = '';
if ($printer > 0) {
$ssl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://';
$apiKey = Configuration::get('INPOSTSHIP_PRINTNODE_API');
if (file_exists($dir)) {
$printNode = new PrintNodeApi($apiKey);
$url = $ssl . $this->context->shop->domain . $this->context->shop->physical_uri . 'modules/inpostship/files/' . $fName;
$job = $printNode->printJob($printer, $url, 'Wydruk etykiety ' . $fName);
if ((int)$job > 0) {
$this->context->smarty->assign(array(
'success' => 'Pomyślnie wysłano do druku.',
));
} else {
$error = json_decode($job);
$errors = '&error='.base64_encode('Wystąpił błąd! '.$error->code.': '.$error->message);
}
} else {
$errors = 'Błąd! Nie można zapisać pliku z etykietą na serwerze.';
}
} else {
$errors = 'Błąd! Nie wybrano drukarki domyślnej w integracji z Print Node';
}
$this->context->smarty->assign(array(
'errors' => $errors,
));
break;
case 'epl':
$fileName = explode(';', $contents['file']);
$fName = date('Y-m-d-H-i-s').'-'.$fileName[0];
$dir = __DIR__ . '/../../files/' . $fName;
$dr = 1;
file_put_contents($dir, $contents['http_code']);
$printer = (int)Configuration::get('INPOSTSHIP_PRINTNODE_PRINTER');
$errors = '';
if ($printer > 0) {
$ssl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://';
$apiKey = Configuration::get('INPOSTSHIP_PRINTNODE_API');
if (file_exists($dir)) {
$printNode = new PrintNodeApi($apiKey);
$url = $ssl . $this->context->shop->domain . $this->context->shop->physical_uri . 'modules/inpostship/files/' . $fName;
$job = $printNode->printJob($printer, $url, 'Wydruk etykiety ' . $fName);
if ((int)$job > 0) {
$this->context->smarty->assign(array(
'success' => 'Pomyślnie wysłano do druku.',
));
} else {
$error = json_decode($job);
$errors = '&error='.base64_encode('Wystąpił błąd! '.$error->code.': '.$error->message);
}
} else {
$errors = 'Błąd! Nie można zapisać pliku z etykietą na serwerze.';
}
} else {
$errors = 'Błąd! Nie wybrano drukarki domyślnej w integracji z Print Node';
}
$this->context->smarty->assign(array(
'errors' => $errors,
));
break;
}
} else {
$this->context->smarty->assign(array(
'errors' => 'Brak pliku do pobrania!'
));
}
} else {
$this->context->smarty->assign(array(
'errors' => 'Brak wybranych przesyłek!'
));
}
}
if (Tools::getIsset('submitGenerateDispatches')) {
$dispatches = Tools::getValue('actions', array());
if (!empty($dispatches)) {
$dispatches_ids = array();
foreach ($dispatches as $d) {
$dispatches_ids[] = $d;
}
$format = Configuration::get('INPOSTSHIP_PRINT_FORMAT');
$file_name = 'listy-'.(date('Y-m-d-H-i-s'));
$content = $this->shipx->getMultiDispatchOrder((int)Configuration::get('INPOSTSHIP_API_ORGANIZATION'), $dispatches_ids, Configuration::get('INPOSTSHIP_PRINT_TYPE'), $format);
if (!empty($content) && !isset($inp->status)) {
ob_start();
$file_type = 'pdf';
header('Content-Type: application/pdf');
header("Content-Disposition: attachment; filename=\"$file_name.$file_type\"");
exit($content);
} else {
$result = json_decode($content);
$detailList = (array)$result->details;
$details = '';
if (is_array($detailList)) {
foreach ($detailList as $key => $detail) {
foreach ($detail as $item) {
$details .= $item.' ';
}
}
} else {
$details = $result->details;
}
$error = Tools::displayError($result->message.': '.$details);
$this->context->smarty->assign(array(
'error' => $error
));
}
} else {
$this->context->smarty->assign(array(
'errors' => 'Brak wybranych przesyłek!'
));
}
}
if (Tools::getIsset('submitPickupDispatches')) {
$pickups = Tools::getValue('actions', array());
if (!empty($pickups)) {
$dispatch = $this->shipx->setDispatchOrders($pickups, (int)Configuration::get('INPOSTSHIP_DISPATCH_POINT'), (int)Configuration::get('INPOSTSHIP_API_ORGANIZATION'));
if (empty($dispatch['error'])) {
$info = (array)$dispatch['result'];
foreach ($pickups as $p) {
Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'inpostship SET dispatch_id = "'.(int)$info['id'].'" WHERE packcode = '.(int)$p);
}
} else {
$this->context->smarty->assign(array(
'errors' => $dispatch['error']
));
}
} else {
$this->context->smarty->assign(array(
'errors' => 'Brak wybranych przesyłek!'
));
}
}
if (Tools::getIsset('printLabel')) {
$label = (int)Tools::getValue('printLabel');
if (!empty($label) && $label > 0) {
$format = Configuration::get('INPOSTSHIP_PRINT_FORMAT');
$pack = InpostPack::getInpostShipByIdPack((int)$label);
$content = $this->shipx->getLabel($pack['packcode'], $format, Configuration::get('INPOSTSHIP_PRINT_TYPE'));
$file_name = $pack['reference_number'];
// ob_end_clean();
ob_start();
if ($format == 'PDF') {
$file_type = 'pdf';
header('Content-Type: application/pdf');
} else {
$file_type = 'epl';
header('Content-Type: application/octet-stream');
}
header("Content-Disposition: attachment; filename=\"$file_name.$file_type\"");
exit($content);
}
}
if (Tools::getIsset('orderCourier')) {
$pickups = Tools::getValue('orderCourier');
if (!empty($pickups)) {
$pick[] = $pickups;
$dispatch = $this->shipx->setDispatchOrders($pick, (int)Configuration::get('INPOSTSHIP_DISPATCH_POINT'), (int)Configuration::get('INPOSTSHIP_API_ORGANIZATION'));
if (empty($dispatch['error'])) {
$id_pack = Db::getInstance()->getValue('SELECT `id_pack` FROM `'._DB_PREFIX_.'inpostship` WHERE `packcode` = "'.$pickups.'"');
$info = (array)$dispatch['result'];
InpostPack::updateDispatchId((int)$id_pack, (int)$info['id']);
} else {
$this->context->smarty->assign(array(
'error' => $dispatch['error']
));
}
}
}
if (Tools::getIsset('INPOSTSHIP_PL_PERPAGE')) {
Configuration::updateValue('INPOSTSHIP_PL_PERPAGE', (int)Tools::getValue('INPOSTSHIP_PL_PERPAGE'));
Tools::redirect($_SERVER['HTTP_REFERER']);
}
if (isset($_POST['plPage'])) {
$url = Tools::getValue('plUrl').'&plPage='.(int)Tools::getValue('plPage');
Tools::redirectLink($url);
}
}
private function GetHeaders($response) {
$headers = [];
$xx = explode("\r\n\r\n", $response);
foreach($xx as $i => $line) {
if($i == 1) {
$headers['http_code'] = $line;
} else {
$xxx2 = nl2br($line);
$xxx = explode('<br />', $xxx2);
if (!empty($xxx)) {
foreach ($xxx as $x) {
$hd = explode(':', $x);
if (count($hd) > 1) {
$headers[trim($hd[0])] = $hd[1];
if (trim($hd[0]) == 'Content-Disposition') {
$file2 = explode('=', $hd[1]);
$file = str_replace('"', '', $file2[1]);
$headers['file'] = $file;
$ext2 = explode('.', $file);
$ext = $ext2[1];
switch ($ext2[1]) {
case 'zip':
$ext = 'zip';
break;
case 'pdf':
$ext = 'pdf';
break;
}
$headers['file_type'] = $ext;
}
} else {
$headers['file'] = '';
$headers['file_type'] = '';
}
}
}
$headers['head'] = $line;
}
}
return $headers;
}
private function getInpostCart($statuses)
{
// $result = Db::getInstance()->executeS('SELECT * FROM '._DB_PREFIX_.'fusioninpost WHERE `status` IS NOT NULL ORDER BY date_add DESC');
$result = Db::getInstance()->executeS('SELECT * FROM '._DB_PREFIX_.'fusioninpost WHERE dispatch_order_id IS NOT NULL ORDER BY date_add DESC');
if (!empty($result)) {
foreach ($result as &$r) {
$r['state'] = !empty($r['status']) ? $this->separateStatus($statuses, $r['status']) : '';
if (!empty($r['dispatch_order_id']) && $r['dispatch_order_id'] > 0) {
$order = new Order((int)$r['dispatch_order_id']);
$r['reference_order'] = $order->reference;
} else {
$r['reference_order'] = '';
}
if (!empty($r['reference_number'])) {
$status = $this->inpostapi->getTracking($r['reference_number']);
} else {
$status = array();
}
$r['current_state'] = $status;
$package_type = 'Inpost Paczkomaty';
if ($r['courier'] > 0) {
$package_type = 'Inpost Kurier';
}
$r['package_type'] = $package_type;
switch ($r['self_send']) {
case 'dispatch_order':
$r['package_send'] = 'Odbiór przez kuriera';
break;
case 'pop':
$r['package_send'] = 'Nadanie w POP';
break;
case 'parcel_locker':
$r['package_send'] = 'Nadanie w paczkomacie';
break;
default:
$r['package_send'] = '';
break;
}
}
}
return $result;
}
private function separateStatus($statuses, $state)
{
$return = array();
if (is_array($statuses)) {
foreach ($statuses as $s) {
if ($s->name == trim($state)) {
$return['title'] = $s->title;
$return['description'] = $s->description;
return $return;
}
}
}
return $return;
}
}