Files
redline.com.pl/modules/inpostship/controllers/admin/AdminInpostshipMass.php
2024-11-11 18:46:54 +01:00

614 lines
28 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 AdminInpostshipMassController extends ModuleAdminController
{
private $nameModule = 'inpostship';
public $shipx;
private $debug;
private $debug_shop;
private $plPage = 0;
public function __construct()
{
$this->bootstrap = true;
$this->className = 'AdminInpostshipMass';
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->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 = 'mass-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);
$this->addJS(_PS_MODULE_DIR_ . $this->nameModule.'/views/js/mass.js');
}
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');
/* mass */
$new_pack_list = InpostPack::getNewPack();
if (!empty($new_pack_list)) {
foreach ($new_pack_list as &$new) {
$order = Db::getInstance()->getRow('SELECT `id_order`, `reference` FROM `'._DB_PREFIX_.'orders` WHERE `id_cart` = '.$new['id_cart']);
$orderShop = new Order($order['id_order']);
$orderProducts = $orderShop->getProducts();
$productList = '';
if (!empty($orderProducts)) {
foreach ($orderProducts as $orderProduct) {
$pro = new Product($orderProduct['id_product'], false, $this->context->cookie->id_lang);
$img = $this->context->link->getImageLink($pro->link_rewrite, $orderProduct['image']->id, 'home_default');
$productList = '<div class=""><table class="table"><thead><tr><th style="width: 8%;">Zdjęcie</th><th>Nazwa produktu</th><th>Indeks</th><th>Ilość</th></tr></thead><tbody><tr><td><img src="'.$img.'" alt="" style="width: 50px;" /></td><td>'.$orderProduct['product_name'].'</td><td>'.$orderProduct['reference'].'</td><td>'.$orderProduct['product_quantity'].'</td></tr></tbody></table></div>';
}
}
// dump($orderProducts);die;
$new['order_id'] = $order['id_order'];
$new['order_reference'] = $orderShop->reference;
$carrier = new Carrier((int)$new['id_carrier']);
$cref = $carrier->id;
$c1 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_1'));
$c1i = Configuration::get('INPOSTSHIP_INSTALL_CARRIER_1');
$c2 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_2'));
$c2i = Configuration::get('INPOSTSHIP_INSTALL_CARRIER_2');
$c3 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_3'));
$c3i = Configuration::get('INPOSTSHIP_INSTALL_CARRIER_3');
$c4 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_4'));
$c4i = Configuration::get('INPOSTSHIP_INSTALL_CARRIER_4');
$c5 = (array)unserialize(Configuration::get('INPOSTSHIP_CARRIER_5'));
$c6 = (array)unserialize(Configuration::get('INPOSTSHIP_CARRIER_6'));
$service = 0;
$c_type = 0;
if ($c1i == 1) {
if (in_array($cref, $c1)) {
$service = 1;
}
}
if ($c2i == 1) {
if (in_array($cref, $c2)) {
$service = 1;
$c_type = 1;
}
}
if ($c3i == 1) {
if (in_array($cref, $c3)) {
$service = 2;
}
}
if ($c4i == 1) {
if (in_array($cref, $c4)) {
$service = 2;
$c_type = 1;
}
}
if (in_array($cref, $c5)) {
$service = 5;
}
if (in_array($cref, $c6)) {
$service = 6;
$c_type = 1;
}
$new['service'] = $service;
$new['c_type'] = $c_type;
$new['cod_type'] = $c_type;
$new['cod_total'] = number_format($orderShop->total_paid, 2, '.', '');
$new['productList'] = $productList;
}
}
/* end mass */
$ssl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://';
/* prestahelp API - do not remove! */
$module = Module::getInstanceByName('inpostship');
$mversion = $module->version;
$auth = new AuthDS('inpostship', $shop->getBaseURL());
$chlogInfo = $auth->getChangelog();
$chlogInfoOther = $auth->getChangelogOther();
$currentVersion = $auth->getCurrentModuleVersion();
$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/';
$licence = $auth->getLicence();
/* prestahelp API - do not remove! */
$sendingMethods = $this->shipx->getSendingMethods();
$scv = false;
if (Configuration::get('INPOSTSHIP_SHOW_COD_VALUE') == 1) {
$scv = true;
}
if ($c2i == 1 || $c4i == 1 || !empty($c6)) {
if ($cref == $c2 || $cref == $c4 || $cref == $c6) {
$scv = true;
}
}
$this->context->smarty->assign(array(
'package_list' => $new_pack_list,
'packtype' => $this->shipx->locker,
'sendingMethods' => $sendingMethods['result']->items,
'insurance' => $this->shipx->insurance,
'packtype_default' => Configuration::get('INPOSTSHIP_PACK_SIZE'),
'dispatch' => Configuration::get('INPOSTSHIP_DISPATCH'),
'ipi' => Configuration::get('INPOSTSHIP_PACKAGE_INSURANCE'),
'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'],
'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'],
'scv' => $scv,
));
}
}
public function postProcess()
{
parent::postProcess();
if (Tools::getIsset('submitGenerateLabels')) {
$packs = Tools::getValue('pack', array());
if (!empty($packs)) {
$pack_list = $this->preparePack($packs);
$package_list = array();
if (!empty($pack_list)) {
foreach ($pack_list as $item) {
$package_list[] = $this->getPackInfo($item);
}
}
if (!empty($package_list)) {
$id_packs = array();
$org_id = (int)Configuration::get('INPOSTSHIP_API_ORGANIZATION');
$inpostapi = new ShipX(Configuration::get('INPOSTSHIP_API_KEY'), (bool)Configuration::get('INPOSTSHIP_SANDBOX'), false);
foreach ($package_list as $pl) {
$sizes = array();
if (InpostPack::setInpostPackage((int)$pl['id_order'], $pl['custom_attrib']['target_point'], '', $pl['packtype'], $pl['custom_attrib']['sending_method'], $pl['custom_attrib']['dropoff_point'], $pl['insurance']['amount'], $pl['cods']['amount'], $sizes)) {
$id_pack = Db::getInstance()->Insert_ID();
$packPrepare = $inpostapi->shipment((int)$org_id, $pl['receiver'], $pl['sender'], $pl['parcels'], $pl['custom_attrib'], $pl['cods'], $pl['insurance'], $pl['additional_services'], $pl['reference'], $pl['service'], false, $pl['weekPack']);
if (empty($packPrepare['error'])) {
InpostPack::updateInpostShipped((int)$id_pack, $packPrepare['result']->status, $packPrepare['result']->id);
$id_packcode = $packPrepare['result']->id;
sleep(5);
$offer = $inpostapi->getShipments($id_packcode, (int)$org_id);
if (empty($offer['error'])) {
$oferta = $offer['result']->selected_offer;
if (!empty($oferta)) {
InpostPack::updateInpostOffer((int)$id_pack, $offer['result']->status, $oferta->id);
}
$status = $offer['result']->status;
$tracking_number = $offer['result']->tracking_number;
if (!empty($tracking_number)) {
$module = Module::getInstanceByName($this->name);
$subject = $this->l('Order tracking e-mail');
InpostPack::updateInpostBuy((int)$id_pack, (int)$pl['id_order'], (int)$this->context->employee->id, $status, $tracking_number, $subject, $module);
InpostPack::updateCreatedCart($pl['id_cart']);
$id_packs[] = $id_packcode;
}
}
} else {
dump($packPrepare);die;
}
}
}
if (!empty($id_packs)) {
// generowanie etykiet
$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'), $id_packs, 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 wybranych przesyłek!'
));
}
}
}
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 preparePack($packs)
{
$return = array();
if (!empty($packs)) {
foreach ($packs['id_cart'] as $item) {
$return[$item] = array();
$return[$item]['id_cart'] = $item;
}
foreach ($packs['packtype'] as $key => $pack) {
if (isset($return[$key])) {
$return[$key]['packtype'] = $pack[0];
}
}
foreach ($packs['sendtype'] as $key => $pack) {
if (isset($return[$key])) {
$return[$key]['sendtype'] = $pack[0];
}
}
foreach ($packs['ins'] as $key => $pack) {
if (isset($return[$key])) {
$return[$key]['ins'] = $pack[0];
}
}
if (isset($packs['pww'])) {
foreach ($return as $key => $item) {
if (isset($return[$key])) {
if (isset($packs['pww'][$key])) {
$return[$key]['pww'] = 1;
} else {
$return[$key]['pww'] = 0;
}
}
}
} else {
foreach ($return as $key => $item) {
if (isset($return[$key])) {
$return[$key]['pww'] = 0;
}
}
}
}
return $return;
}
private function getPackInfo($pack)
{
$info = array();
if (!empty($pack)) {
$packInpost = InpostPack::getInpostShipCart((int)$pack['id_cart']);
$id_order = $this->getIdOrderByIdCart((int)$pack['id_cart']);
$order = new Order((int)$id_order);
$cod = (int)$packInpost['cod'];
$cods = array();
if ($cod == 1) {
$cods['amount'] = $order->total_paid;
$cods['currency'] = 'PLN';
}
$pww = $pack['pww'];
$carrier = new Carrier((int)$packInpost['id_carrier'], (int)$this->context->cookie->id_lang);
$cref = $carrier->id_reference;
$c1 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_1'));
$c1i = Configuration::get('INPOSTSHIP_INSTALL_CARRIER_1');
$c2 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_2'));
$c2i = Configuration::get('INPOSTSHIP_INSTALL_CARRIER_2');
$c3 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_3'));
$c3i = Configuration::get('INPOSTSHIP_INSTALL_CARRIER_3');
$c4 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_4'));
$c4i = Configuration::get('INPOSTSHIP_INSTALL_CARRIER_4');
$c5 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_5'));
$c6 = unserialize(Configuration::get('INPOSTSHIP_CARRIER_6'));
$srv = 0;
$c_type = 0;
if ($c1i == 1) {
if (in_array($cref, $c1)) {
$service = 1;
}
}
if ($c2i == 1) {
if (in_array($cref, $c2)) {
$service = 1;
$c_type = 1;
}
}
if ($c3i == 1) {
if (in_array($cref, $c3)) {
$service = 2;
}
}
if ($c4i == 1) {
if (in_array($cref, $c4)) {
$service = 2;
$c_type = 1;
}
}
if (in_array($cref, $c5)) {
$service = 5;
}
if (in_array($cref, $c6)) {
$service = 6;
$c_type = 1;
}
switch ($srv) {
case 1:$service = 'inpost_locker_standard';break; // InPost Paczkomaty 24
case 2:$service = 'inpost_courier_standard';break; // Kurier InPost
case 3:$service = 'inpost_locker_standard';break; // Allegro
case 4:$service = 'inpost_locker_standard';break;
case 5:$service = 'inpost_locker_standard';$pww = 1;break; // InPost Paczkomaty 24 Paczka w weekend
case 6:$service = 'inpost_locker_standard';$pww = 1;break; // InPost Paczkomaty 24 Paczka w weekend
default:$service = 'inpost_locker_standard';break;
}
$custom_attrib['target_point'] = $packInpost['receiver_machine'];
$custom_attrib['sending_method'] = $pack['sendtype'];
if ($custom_attrib['sending_method'] == 'parcel_locker') {
$custom_attrib['dropoff_point'] = Configuration::get('INPOSTSHIP_SENDER_MACHINE');
} else if ($custom_attrib['sending_method'] == 'pop') {
$custom_attrib['dropoff_point'] = Configuration::get('INPOSTSHIP_SENDER_MACHINE_POP');
}
$insurance = array();
if ($pack['ins']) {
$insurance['amount'] = $pack['ins'];
$insurance['currency'] = 'PLN';
}
$identity = $order->reference;
$ident = Configuration::get('INPOSTSHIP_ORDER_NUMBER');
if ($ident == 1) {
$identity = $order->id;
}
$parcels = array();
$pcount = 0;
$parcels[$pcount]['id'] = $pack['packtype'] . ' package';
$parcels[$pcount]['template'] = $pack['packtype'];
$parcels[$pcount]['weight'] = 2;
$parcels[$pcount]['info'] = $pack['packtype'];
$parcels[$pcount]["tracking_number"] = null;
$parcels[$pcount]["is_non_standard"] = false;
$address_delivery = new Address((int)$order->id_address_delivery);
$customer = new Customer((int)$order->id_customer);
$x13allegro = Configuration::get('INPOSTSHIP_INTEGRATION_X13ALLEGRO');
$receiver = array();
if ($x13allegro && ($service == 4 || $service == 5)) {
$x13orderInfo = Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.'xallegro_order` WHERE `id_order` = '.(int)$order->id);
if (!empty($x13orderInfo)) {
$x13oinfo = json_decode($x13orderInfo['checkout_form_content']);
$rec_mach = $x13oinfo->delivery->pickupPoint->id;
$address = $x13oinfo->delivery->address;
$receiver['first_name'] = Tools::stripslashes($address->firstName);
$receiver['last_name'] = $address->lastName;
$postcode = null;//$address->zipCode;
$street = str_replace('ul. ', '', $address->street);
$street = str_replace(',', '', $street);
$match = InpostTools::split_street($street);
if (!InpostValidate::isPolandPostCode($postcode)) {
$postcode = InpostTools::setPolandPostCode($postcode);
}
$city = $address->city;
$login = ' '.$x13oinfo->buyer->login;
if (!empty($rec_mach)) {
$custom_attrib['target_point'] = $rec_mach;
}
}
} else {
$postcode = $address_delivery->postcode;
$match = InpostTools::split_street(trim($address_delivery->address1.' '.$address_delivery->address2));
if (!InpostValidate::isPolandPostCode($postcode)) {
$postcode = InpostTools::setPolandPostCode($postcode);
}
$city = $address_delivery->city;
}
$receiver['first_name'] = Tools::stripslashes($address_delivery->firstname);
$receiver['last_name'] = $address_delivery->lastname;
$receiver['email'] = $customer->email;
$receiver['phone'] = InpostValidate::reValidPhone($address_delivery->phone);
$receiver['address'] = array(
'street' => $match['street'],
'building_number' => $match['numberAll'],
'city' => $city,
'post_code' => $postcode,
'country_code' => 'PL'
);
$sender = array();
$sender['first_name'] = Configuration::get('INPOSTSHIP_SENDER_FIRSTNAME');
$sender['last_name'] = Configuration::get('INPOSTSHIP_SENDER_LASTNAME');
$sender['company_name'] = Configuration::get('INPOSTSHIP_SENDER_COMPANY_NAME');
$sender['phone'] = Configuration::get('INPOSTSHIP_SENDER_PHONE');
$sender['email'] = Configuration::get('INPOSTSHIP_SENDER_EMAIL');
$sender['address'] = array(
'street' => Configuration::get('INPOSTSHIP_SENDER_STREET'),
'building_number' => Configuration::get('INPOSTSHIP_SENDER_BUILDING_NR'),
'city' => Configuration::get('INPOSTSHIP_SENDER_CITY'),
'post_code' => Configuration::get('INPOSTSHIP_SENDER_POSTCODE'),
'country_code' => 'PL'
);
if (strlen($identity) < 3) {
$identity = '00'.$identity;
}
$info['packtype'] = $pack['packtype'];
$info['service'] = $service;
$info['custom_attrib'] = $custom_attrib;
$info['weekPack'] = $pww;
$info['reference'] = $identity;
$info['additional_services'] = array();
$info['insurance'] = $insurance;
$info['cods'] = $cods;
$info['receiver'] = $receiver;
$info['sender'] = $sender;
$info['parcels'] = $parcels;
$info['id_order'] = $id_order;
$info['id_cart'] = $pack['id_cart'];
}
return $info;
}
private function getIdOrderByIdCart($id_cart)
{
if ($id_cart > 0) {
return (int)Db::getInstance()->getValue('SELECT `id_order` FROM `'._DB_PREFIX_.'orders` WHERE `id_cart` = '.(int)$id_cart);
}
return null;
}
}