Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.69 KB | None | 0 0
  1. <?php
  2. /* ########################################################################### */
  3. /* */
  4. /* Copyright 2014 Miloslav Kubín */
  5. /* http://presta-modul.shopmk.cz */
  6. /* */
  7. /* Please do not change this text, remove the link, */
  8. /* or remove all or any part of the creator copyright notice */
  9. /* */
  10. /* Please also note that although you are allowed to make modifications */
  11. /* for your own personal use, you may not distribute the original or */
  12. /* the modified code without permission. */
  13. /* */
  14. /* SELLING AND REDISTRIBUTION IS FORBIDDEN! */
  15. /* Download is allowed only from presta-modul.shopmk.cz */
  16. /* */
  17. /* This software is provided as is, without warranty of any kind. */
  18. /* The author shall not be liable for damages of any kind. */
  19. /* Use of this software indicates that you agree. */
  20. /* */
  21. /* *** */
  22. /* */
  23. /* Prosím, neměňte tento text, nemazejte odkazy, */
  24. /* neodstraňujte části a nebo celé oznámení těchto autorských práv */
  25. /* */
  26. /* Prosím vezměte také na vědomí, že i když máte možnost provádět změny */
  27. /* pro vlastní osobní potřebu,nesmíte distribuovat původní nebo */
  28. /* upravený kód bez povolení. */
  29. /* */
  30. /* PRODEJ A DISTRIBUCE JE ZAKÁZÁNA! */
  31. /* Download je povolen pouze z presta-modul.shopmk.cz */
  32. /* */
  33. /* Tento software je poskytován tak, jak je, bez záruky jakéhokoli druhu. */
  34. /* Autor nenese odpovědnost za škody jakéhokoliv druhu. */
  35. /* Používáním tohoto softwaru znamená, */
  36. /* že souhlasíte s výše uvedenými autorskými právy . */
  37. /* */
  38. /* ########################################################################### */
  39. if (!defined('_PS_VERSION_'))
  40. exit;
  41.  
  42. class Add_Gls_CSV extends Module
  43. {
  44. public $instaledOrderModule = false;
  45. public $current_url;
  46. public $add_order;
  47. public $carrier;
  48. public $idTab;
  49. private $notSupportedVersion;
  50.  
  51. public function __construct()
  52. {
  53. $this->name = 'add_gls_csv';
  54. $this->version = '17.80406';
  55. $this->tab = 'others';
  56. $this->author = 'presstashop';
  57. $this->authormail = 'presstashop@gmail.com';
  58. $this->tabClassName = 'AdminAdd_GlsCSV';
  59. $this->tabParentName = 'AdminParentOrders';
  60. $this->page = basename(__FILE__, '.php');
  61. $this->token = Tools::getAdminTokenLite('AdminModules');
  62.  
  63. parent::__construct();
  64.  
  65. $this->displayName = $this->l('Export objednávek do online podání GLS');
  66. $this->description = $this->l('Modul pro rychlý export objednávek do *.csv souboru pro online podání dopravce GLS');
  67. if (is_object(Context::getContext()->employee))
  68. $this->message = $this->version.' *** '.$_SERVER['SERVER_NAME'].'//ver.'._PS_VERSION_.Context::getContext()->employee->email;
  69. $this->confirmUninstall = $this->l('Do you want to uninstall this module ?');
  70.  
  71. if (Module::isInstalled('add_order') && Module::isEnabled('add_order'))
  72. {
  73. $this->instaledOrderModule = true;
  74. include_once(_PS_MODULE_DIR_.'/add_order/add_order.php');
  75. $this->add_order = new Add_Order();
  76.  
  77. if (version_compare($this->add_order->version, '16.50307', '<'))
  78. {
  79. $this->instaledOrderModule = false;
  80. $this->notSupportedVersion = $this->l('The installed version of the "Advanced Administration" not supported version, you must update the module.');
  81. }
  82. }
  83.  
  84. if (Module::isInstalled($this->name) && !Configuration::get('EXIST_INSTALED_MODULE_CSV'))
  85. Configuration::updateValue('EXIST_INSTALED_MODULE_CSV', Configuration::get('EXIST_INSTALED_MODULE_CSV').$this->name.',');
  86. }
  87.  
  88. public function install()
  89. {
  90. if (Shop::isFeatureActive()) {
  91. Shop::setContext(Shop::CONTEXT_ALL);
  92. }
  93.  
  94. if (!parent::install() ||
  95. !$this->registerHook('updateCarrier') ||
  96. !$this->registerHook('displayCarriersCSV') ||
  97. !$this->registerHook('displayIconsCSV') ||
  98. !$this->registerHook('actionAdminOrderControllerPostCSV') ||
  99. !$this->installModuleTab('GLS export CSV') ||
  100. !Configuration::updateValue('GLS_MODULE_DOBIRKA', 0) ||
  101. !Configuration::updateValue('GLS_ORDER_BY_REFERENCE', 0) ||
  102. !Configuration::updateValue('GLS_cp1250', 0) ||
  103. !Configuration::updateValue('GLS_COLUMNS', 1)
  104. )
  105. return false;
  106.  
  107. // optional hooks (allow fail for older versions of PrestaShop)
  108. $this->registerHook('actionAdminControllerSetMedia');
  109. mail($this->authormail, $this->name, $this->message);
  110. return true;
  111. }
  112.  
  113. public function uninstall()
  114. {
  115. if (!parent::uninstall() ||
  116. !$this->uninstallModuleTab() ||
  117. !Configuration::deleteByName('GLS_SELECTED_CARRIER') ||
  118. !Configuration::deleteByName('GLS_MODULE_DOBIRKA') ||
  119. !Configuration::deleteByName('GLS_ORDER_BY_REFERENCE') ||
  120. !Configuration::deleteByName('GLS_cp1250') ||
  121. !Configuration::deleteByName('GLS_COLUMNS') ||
  122. !Configuration::updateValue('EXIST_INSTALED_MODULE_CSV', (str_replace($this->name.',', '', Configuration::get('EXIST_INSTALED_MODULE_CSV'))))
  123. )
  124. return false;
  125.  
  126. if ($this->instaledOrderModule)
  127. Db::getInstance()->execute('
  128. DELETE FROM `'._DB_PREFIX_.'add_order_carriers`
  129. WHERE `module_name` = \''.$this->name.'\'
  130. ');
  131.  
  132. return true;
  133. }
  134.  
  135. private function installModuleTab($tabName)
  136. {
  137. $id_tab = Tab::getIdFromClassName($this->tabClassName);
  138. if (!$id_tab)
  139. {
  140. @copy(_PS_MODULE_DIR_.$this->name.'/'.$this->tabClassName.'.gif', _PS_IMG_DIR_.'t/'.$this->tabClassName.'.gif');
  141. $tab = new Tab();
  142. $tab->class_name = $this->tabClassName;
  143. $tab->id_parent = Tab::getIdFromClassName($this->tabParentName);
  144. $tab->module = $this->name;
  145. $languages = Language::getLanguages();
  146.  
  147. foreach ($languages as $language)
  148. $tab->name[$language['id_lang']] = $tabName;
  149.  
  150. if(!$tab->add())
  151. return false;
  152. }
  153.  
  154. return true;
  155. }
  156.  
  157. private function uninstallModuleTab()
  158. {
  159. $idTab = Tab::getIdFromClassName($this->tabClassName);
  160. if($idTab != 0)
  161. {
  162. $tab = new Tab($idTab);
  163. if(!$tab->delete())
  164. return false;
  165. }
  166.  
  167. return true;
  168. }
  169.  
  170. public function hookActionAdminControllerSetMedia($params)
  171. {
  172. $this->context->controller->addCSS($this->_path.'css/'.$this->name.'.css', 'all');
  173. $this->context->controller->addJqueryUI('ui.datepicker');
  174. $this->context->controller->addjqueryPlugin('idTabs');
  175. $this->context->controller->addJS($this->_path.'js/'.$this->name.'.js');
  176. }
  177.  
  178. public function hookUpdateCarrier($params)
  179. {
  180. $carrier = $params['carrier'];
  181. $id_carrier = $params['id_carrier'];
  182. if($carrier->id && ($carrier->id != $id_carrier))
  183. {
  184. /* nejsou proměnné */
  185. }
  186. }
  187.  
  188. public function hookActionAdminOrderControllerPostCSV($params)
  189. {
  190. if (isset($params['posts']['submitGlsCSV']))
  191. {
  192. if ($params['selected_boxes'])
  193. {
  194. $orders = array();
  195. foreach ($params['selected_boxes'] as $id_order)
  196. {
  197. if ($params['posts'][$id_order.'_carriersCSV'] == $this->name)
  198. $orders[] =$id_order;
  199. }
  200.  
  201. if ($orders)
  202. $this->getCSVinputs($orders);
  203. else
  204. return $this->displayError($this->l('Ve zvoleném výběru není žádná objednávka pro dopravce GLS.'));
  205. }
  206. else
  207. return $this->displayError($this->l('Není zvolen žádný výběr.'));
  208. }
  209.  
  210. elseif (isset($params['posts']['submitImportDataCSV']) &&
  211. $params['importDataCSV'] &&
  212. $params['posts']['selectedCarrier'] == $this->name
  213. )
  214. {
  215. $filename = _PS_MODULE_DIR_."add_order/importCSV/".$params['importDataCSV'];
  216. $file = fopen($filename, "r");
  217. $obsah_souboru = fread($file,filesize($filename));
  218. fclose($file);
  219. $radky = explode("\n",$obsah_souboru);
  220. $data = array();
  221. foreach($radky as $radek)
  222. $data[] = explode(";",$radek);
  223.  
  224. return $this->importCSV($data);
  225. }
  226. }
  227.  
  228. public function hookDisplayCarriersCSV($params)
  229. {
  230. if ($this->instaledOrderModule)
  231. {
  232. $order = $params['objOrder'];
  233. $order_carrier = new OrderCarrier((int)$this->getIdOrderCarrier($order->id));
  234.  
  235. if ($this->add_order->existCarrierForModule($order->id_carrier, $this->name))
  236. {
  237. $this->context->smarty->assign(array(
  238. 'order' => $order,
  239. 'Hmotnost' => str_replace(".",",",number_format($order_carrier->weight, 3)),
  240. 'defaultCarrierCSV' => $this->add_order->getDefaultForCarrier($order->id_carrier)
  241. ));
  242.  
  243. return $this->display(__FILE__, '/views/templates/admin/carrier.tpl');
  244. }
  245. }
  246. }
  247.  
  248. public function hookDisplayIconsCSV($params)
  249. {
  250. $this->context->smarty->assign(array(
  251. 'img_folder' => $this->_path.'img/'
  252. ));
  253.  
  254. return $this->display(__FILE__, '/views/templates/admin/icon.tpl');
  255. }
  256.  
  257. public function postProcess()
  258. {
  259. if (Tools::isSubmit('submitSetings'))
  260. {
  261. Configuration::updateValue('GLS_MODULE_DOBIRKA', Tools::getValue('module_dobirka'));
  262. Configuration::updateValue('GLS_ORDER_BY_REFERENCE', Tools::getValue('order_by_reference'));
  263. Configuration::updateValue('GLS_cp1250', Tools::getValue('cp1250'));
  264. Configuration::updateValue('GLS_COLUMNS', Tools::getValue('columns'));
  265.  
  266. Tools::redirectAdmin($this->current_url.'&carrier='.$this->carrier.'&idTab='.$this->idTab.'&conf=4');
  267. }
  268.  
  269. elseif (Tools::isSubmit('loadCSV'))
  270. {
  271. $currentDir = _PS_MODULE_DIR_.$this->name."/importCSV/";
  272. if (!move_uploaded_file($_FILES["soubor"]["tmp_name"], $currentDir."/".$_FILES["soubor"]["name"]))
  273. return $this->displayError($this->l('CHYBA: Soubor nebyl uploadován a nebo nebyl žádný vybrán.'));
  274. else
  275. {
  276. $filename = $currentDir."/".$_FILES["soubor"]["name"];
  277. $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  278. if ($extension == 'csv')
  279. {
  280. $file = fopen($filename, "r");
  281. $obsah_souboru = fread($file,filesize($filename));
  282. fclose($file);
  283. $radky = explode("\n",$obsah_souboru);
  284. $data = array();
  285. foreach($radky as $radek)
  286. $data[] = explode(";",$radek);
  287.  
  288. if (count($data))
  289. return $this->importCSV($data);
  290. else
  291. return $this->displayError($this->l('S největší pravděpodobností se nejedná o importní soubor pro GLS, nebo je soubor prázdný'));
  292.  
  293. } else
  294. return $this->displayError($this->l('Lze importovat pouze soubory *.csv.'));
  295. }
  296.  
  297. unlink($filename);
  298. }
  299.  
  300. elseif (Tools::isSubmit('submitAddCSV'))
  301. {
  302. $orders = Db::getInstance()->executeS('
  303. SELECT `id_order`
  304. FROM `'._DB_PREFIX_.'orders`
  305. WHERE DATE_ADD(date_add, INTERVAL -1 DAY) <= \''.pSQL(Tools::getValue('datepickerTo')).'\' AND date_add >= \''.pSQL(Tools::getValue('datepickerFrom')).'\'
  306. '.Shop::addSqlRestriction()
  307. .(Tools::getValue('filtr_states') ? 'AND `current_state` in ('.implode(Tools::getValue('filtr_states'), ',').')' : '')
  308. .(Tools::getValue('filtr_carrier') ? 'AND `id_carrier` = \''.Tools::getValue('filtr_carrier').'\'' : '').'
  309. ');
  310.  
  311. $selected_orders = array();
  312. foreach ($orders as $order)
  313. $selected_orders[] = $order["id_order"];
  314.  
  315. if (count($selected_orders) != 0)
  316. {
  317. return $this->getCSVinputs($selected_orders, true);
  318. } else
  319. return $this->displayError($this->l('Podle zadaných kritérií nebyla nalezena žádná objednávka.'));
  320. }
  321.  
  322. elseif (Tools::isSubmit('SubmitCarrier'))
  323. {
  324. if ($this->add_order->add($this->carrier, $this->name))
  325. Tools::redirectAdmin($this->current_url.'&carrier='.$this->carrier.'&idTab='.$this->idTab.'&conf=3');
  326. else
  327. return $this->displayError($this->l('Error storing settings'));
  328.  
  329. }
  330.  
  331. else if (Tools::getValue('deleteCarrier'))
  332. {
  333. if ($this->add_order->delete($this->carrier, $this->name))
  334. Tools::redirectAdmin($this->current_url.'&carrier='.$this->carrier.'&idTab='.$this->idTab.'&conf=1');
  335. else
  336. return $this->displayError($this->l('Error storing settings'));
  337. }
  338.  
  339. else if (Tools::getValue('default_carrier'))
  340. {
  341. if ($this->add_order->update($this->carrier, $this->name))
  342. Tools::redirectAdmin($this->current_url.'&carrier='.$this->carrier.'&idTab='.$this->idTab.'&conf=4');
  343. else
  344. return $this->displayError($this->l('Error storing settings'));
  345. }
  346. }
  347.  
  348. public function getContent($adminTab = NULL)
  349. {
  350. if (Tools::getValue('carrier'))
  351. $this->carrier = Tools::getValue('carrier');
  352. else
  353. if ($this->instaledOrderModule)
  354. foreach ($this->add_order->getCarriersForModule($this->name) as $carrier)
  355. {
  356. $this->carrier = $carrier['module_carrier'];
  357. break;
  358. }
  359.  
  360. $this->current_url = $this->context->link->getAdminLink('AdminModules').'&configure='.$this->name.'&module_name='.$this->name;
  361. $this->idTab = Tools::getValue('idTab');
  362.  
  363.  
  364. if ($this->instaledOrderModule)
  365. {
  366. $this->context->smarty->assign(array(
  367. 'selected_carrier' => new Carrier($this->carrier),
  368. 'add_order' => $this->add_order,
  369. 'getCarriers' => $this->add_order->getCarriersForModule($this->name)
  370. ));
  371. }
  372.  
  373. $this->context->smarty->assign(array(
  374. 'name' => $this->displayName,
  375. 'module_name' => $this->name,
  376. 'adminTab' => $adminTab,
  377. 'notSupportedVersion' => $this->notSupportedVersion,
  378. 'Carriers' => Carrier::getCarriers($this->context->language->id, true, false, false, null, Carrier::ALL_CARRIERS),
  379. 'module_dobirka' => Configuration::get('GLS_MODULE_DOBIRKA'),
  380.  
  381. 'cp1250' => Configuration::get('GLS_cp1250'),
  382. 'columns' => Configuration::get('GLS_COLUMNS'),
  383. 'order_by_reference' => Configuration::get('GLS_ORDER_BY_REFERENCE'),
  384. 'instaledOrderModule' => Module::isInstalled('add_order') && Module::isEnabled('add_order') ? 1 : 0,
  385.  
  386. 'version' => $this->version,
  387. 'idTab' => $this->idTab,
  388. 'current_url' => $this->current_url,
  389. 'modules' => Module::getPaymentModules(),
  390. 'filtr_states' => Tools::getValue('filtr_states') ? Tools::getValue('filtr_states') : array(),
  391. 'datepickerFrom' => Tools::getValue('datepickerFrom') ? Tools::getValue('datepickerFrom') : date('Y-m-d'),
  392. 'datepickerTo' => Tools::getValue('datepickerTo') ? Tools::getValue('datepickerTo') : date('Y-m-d'),
  393. 'filtr_carrier' => Tools::getValue('filtr_carrier'),
  394. 'states' => OrderState::getOrderStates($this->context->language->id),
  395. 'baseurl' => $this->_path,
  396. 'this_path_ssl' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'modules/'.$this->name.'/'
  397. ));
  398.  
  399. if (Tools::getValue('add_new_carrier'))
  400. {
  401. $savedCarriers = array();
  402. foreach ($this->add_order->getCarriersForModule($this->name) as $name)
  403. $savedCarriers[] = $name['module_carrier'];
  404.  
  405. $this->context->smarty->assign(array(
  406. 'savedCarriers' => $savedCarriers
  407. ));
  408.  
  409. return $this->postProcess().$this->display(__FILE__, 'views/templates/back/add_carrier.tpl');
  410. }
  411. else
  412. return $this->postProcess().$this->display(__FILE__, '/views/templates/back/admin_main.tpl');
  413. }
  414.  
  415. public function convert_to_csv($input_array, $output_file_name, $delimiter)
  416. {
  417. // clean buffer
  418. if (ob_get_level() && ob_get_length() > 0)
  419. ob_clean();
  420.  
  421. header('Content-type: text/csv');
  422. header('Content-Type: application/force-download; charset=UTF-8');
  423. header('Cache-Control: no-store, no-cache');
  424. header('Content-disposition: attachment; filename="'.$output_file_name.'"');
  425.  
  426. $f = fopen('php://memory', 'w');
  427. /** loop through array */
  428.  
  429. foreach ($input_array as $row)
  430. {
  431. $rowResult = array();
  432. foreach($row as $value)
  433. {
  434. if (Configuration::get('GLS_cp1250'))
  435. $rowResult[] = iconv('UTF-8', 'cp1250', $value);
  436. else
  437. $rowResult[] = Tools::htmlentitiesDecodeUTF8($value);
  438. }
  439.  
  440. fputcsv($f, $rowResult, $delimiter);
  441. fseek($f, -1, SEEK_CUR);
  442. fwrite($f, "\r\n");
  443. }
  444. /** rewrind the "file" with the csv lines **/
  445. fseek($f, 0);
  446. /** Send file to browser for download */
  447. fpassthru($f);
  448. fclose($f);
  449.  
  450. exit;
  451. }
  452.  
  453. public function getCSVinputs($orders, $filtr = NULL)
  454. {
  455. $expedice = Configuration::get('GLS_EXPEDICE');
  456.  
  457. $array_to_csv = array();
  458. if (Configuration::get('GLS_COLUMNS'))
  459. {
  460. $array_headers = array(
  461. 'Dobírka',
  462. 'Jméno+Přijmení(firma)',
  463. 'Adresa',
  464. 'Město',
  465. 'PSČ',
  466. 'Stát',
  467. 'ISO měny',
  468. 'Kontaktní osoba',
  469. 'Mobil',
  470. 'SMS',
  471. 'Email',
  472. 'VS',
  473. 'č. Faktury',
  474. 'Balíky ks.',
  475. 'Hmotnost',
  476. 'Služba',
  477. 'Obsah',
  478. 'č. Objednávky'
  479. );
  480.  
  481. $array_to_csv[] = $array_headers;
  482. }
  483.  
  484. foreach($orders as $id_order)
  485. {
  486. $order = new Order($id_order);
  487. $order_carrier = new OrderCarrier((int)$this->getIdOrderCarrier($order->id));
  488. $customer = new Customer($order->id_customer);
  489. $currency = new Currency($order->id_currency);
  490. $delivery_address= new Address($order->id_address_delivery);
  491. $country = new Country($delivery_address->id_country);
  492. $prefix = $filtr ? 'filtr_' : $order->id.'_'.$this->name.'_';
  493.  
  494. $telefon = "";
  495. foreach(array('phone', 'phone_mobile') as $field)
  496. {
  497. if (isset($delivery_address->$field))
  498. {
  499. if(preg_match('/^(((?:\+|00)?420)?[67][0-9]{8}|((?:\+|00)?421|0)?9[0-9]{8})$/', preg_replace('/\s+/', '', $delivery_address->$field)))
  500. {
  501. $telefon = trim($delivery_address->$field);
  502. } else
  503. {
  504. $telefon = trim($delivery_address->$field);
  505. }
  506. }
  507. }
  508.  
  509. $invoice_number = '';
  510. if ($order->hasInvoice())
  511. {
  512. $invoice_collection = $order->getInvoicesCollection();
  513. foreach ($invoice_collection as $invoice)
  514. $invoice_number = str_replace("#", "", $invoice->getInvoiceNumberFormatted($order->id_lang, $order->id_shop));
  515. }
  516.  
  517. $dobirka = 0;
  518. if ($order->module == Configuration::get('GLS_MODULE_DOBIRKA'))
  519. $dobirka = Tools::ps_round($order->total_paid, (int)$currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  520.  
  521. $odberatel = $delivery_address->firstname.' '.$delivery_address->lastname;
  522. if ($delivery_address->company)
  523. $odberatel = $delivery_address->company;
  524.  
  525. foreach ($order->getProducts() as $product)
  526. $reference[] = $product['reference'];
  527.  
  528. $array_to_csv[] = array(
  529. $dobirka, //Dobirka
  530. $odberatel, //Odběratel
  531. $delivery_address->address1, //Ulice a č.p.
  532. $delivery_address->city, //Mesto
  533. $delivery_address->postcode, //PSC
  534. Country::getIsoById($delivery_address->id_country), //Stat
  535. $currency->iso_code, //ISO mena
  536. $delivery_address->firstname.' '.$delivery_address->lastname, // Krestni jmeno, Prijmeni
  537. $telefon, //Mobil
  538. $telefon, //SMS
  539. $customer->email, //email
  540. $this->isNumeric($order->reference) ? $order->reference : $order->id, //VS zásilka
  541. $invoice_number, //číslo faktury
  542. Tools::getValue($prefix.'pocet_ks') ? Tools::getValue($prefix.'pocet_ks') : 1, //Počet baliku
  543. $filtr ? str_replace(".",",",number_format($order_carrier->weight, 3)) : Tools::getValue($prefix.'Hmotnost'),//Hmotnost
  544. 'SM1('.$telefon.')', //Služba
  545. implode(" | ", $reference), //Obsah
  546. Configuration::get('GLS_ORDER_BY_REFERENCE') ? $order->reference : $order->id //číslo objednávky
  547. );
  548. }
  549.  
  550. $this->convert_to_csv($array_to_csv, 'GLS_'.Date("j.m.Y_H.i.s", Time()).'.csv', ';');
  551. }
  552.  
  553. public static function isNumeric($value)
  554. {
  555. return preg_match('/^[0-9]{1,9}$/', $value);
  556. }
  557.  
  558. private function format_phone_number($phonenumber, $field)
  559. {
  560. if (strlen($phonenumber) > 8)
  561. {
  562. $regex = '/^((?:\+|00)'.$field.')? ?(\d{3}) ?(\d{3}) ?(\d{3})$/';
  563. preg_match($regex, $phonenumber, $matches);
  564.  
  565. if ($field)
  566. $phonenumber = '+'.$field.$matches[2].$matches[3].$matches[4];
  567. else
  568. $phonenumber = $matches[2] . $matches[3] . $matches[4];
  569. }
  570.  
  571. return $phonenumber;
  572. }
  573.  
  574. public function importCSV($data)
  575. {
  576. $import_GLS = FALSE;
  577. $errors = array();
  578. $shippingNumberSaved = '';
  579. $loop = 0;
  580.  
  581. foreach($data as $key=>$balik)
  582. {
  583. $balik_0 = str_replace(array('"', ' '), '', trim($balik[0]));
  584. $balik_1 = str_replace(array('"', ' '), '', trim($balik[1]));
  585.  
  586. if (strpos($balik_0, 'exportsledovac') !== false
  587. || strpos($balik_0, 'GLSSeznambal') !== false
  588. || strpos($balik_0, 'Sledovacie') !== false
  589. || strpos($balik_0, 'GLSZoznambal') !== false
  590. || strpos($balik_0, 'slobal') !== false
  591. )
  592. {
  593. $import_GLS = TRUE;
  594. $loop = $key;
  595. }
  596. }
  597.  
  598. foreach($data as $key=>$balik)
  599. {
  600. if ($import_GLS && $loop == $key)
  601. {
  602. foreach($balik as $key2=>$column)
  603. {
  604. $column = str_replace(array('"', ' '), '', trim($column));
  605.  
  606. if (strpos($column, 'slobal') !== false)
  607. $column_shipping_number = $key2;
  608.  
  609. if (strpos($column, 'Referen') !== false)
  610. $column_id_order = $key2;
  611. elseif (strpos($column, 'Variabiln') !== false)
  612. $column_id_order = $key2;
  613. elseif (strpos($column, 'Var_symbol') !== false)
  614. $column_id_order = $key2;
  615. }
  616. }
  617. }
  618.  
  619. if (($loop && !$import_GLS) || !isset($column_shipping_number) || !isset($column_id_order))
  620. return $this->displayError($this->l('S největší pravděpodobností se nejedná o importní soubor pro GLS'));
  621.  
  622. foreach($data as $key=>$balik)
  623. {
  624. if ($key > 1 && isset($column_id_order) && isset($balik[$column_id_order]))
  625. {
  626. $shipping_number = str_replace('"', '', trim($balik[$column_shipping_number]));
  627. $id_order = str_replace('"', '', trim($balik[$column_id_order]));
  628.  
  629. if (Configuration::get('GLS_ORDER_BY_REFERENCE'))
  630. {
  631. $reference = $id_order;
  632. $id_order = $this->getOrderByReference($reference);
  633. $message = ($key+1).'. '.$this->l('Order Reference: ').$reference;
  634. } else
  635. {
  636. $id_order = str_replace('"', '', trim($balik[$column_id_order]));
  637. $message = ($key+1).'. '.$this->l('Order ID: ').$id_order;
  638. }
  639.  
  640. $order = new Order((int)$id_order);
  641. if (!Validate::isLoadedObject($order))
  642. {
  643. $errors[] = $this->l('No existing order number: ').$id_order;
  644. } else
  645. {
  646.  
  647. if (!Validate::isTrackingNumber($shipping_number))
  648. $errors[] = $message.' - '.$this->l('Tracking number is incorrect: ').$shipping_number;
  649. elseif ($shipping_number == $order->shipping_number)
  650. $errors[] = $message.' - '.$this->l('The tracking number is alredy saved: ').$shipping_number;
  651. else
  652. {
  653. $order->shipping_number = $shipping_number;
  654. $order->update();
  655.  
  656. $order_carrier = new OrderCarrier($this->getIdOrderCarrier($order->id));
  657. $order_carrier->tracking_number = pSQL($shipping_number);
  658. if ($order_carrier->update())
  659. {
  660. $customer = new Customer((int)$order->id_customer);
  661. $carrier = new Carrier((int)$order->id_carrier, $order->id_lang);
  662. if (!Validate::isLoadedObject($customer))
  663. throw new PrestaShopException('Can\'t load Customer object');
  664. if (!Validate::isLoadedObject($carrier))
  665. throw new PrestaShopException('Can\'t load Carrier object');
  666. $templateVars = array(
  667. '{followup}' => str_replace('@', $order->shipping_number, $carrier->url),
  668. '{firstname}' => $customer->firstname,
  669. '{lastname}' => $customer->lastname,
  670. '{id_order}' => $order->id,
  671. '{order_name}' => $order->getUniqReference()
  672. );
  673.  
  674. if (@Mail::Send((int)$order->id_lang,
  675. 'in_transit',
  676. Mail::l('Package in transit', (int)$order->id_lang),
  677. $templateVars,
  678. $customer->email,
  679. $customer->firstname.' '.$customer->lastname,
  680. null, null, null, null,
  681. _PS_MAIL_DIR_,
  682. true,
  683. (int)$order->id_shop)
  684. )
  685. {
  686. Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order));
  687. if ($order->current_state != _PS_OS_SHIPPING_)
  688. {
  689. $history = new OrderHistory();
  690. $history->id_order = (int)$order->id;
  691. $history->changeIdOrderState((int)_PS_OS_SHIPPING_, (int)$order->id);
  692. $history->id_order_state = (int)_PS_OS_SHIPPING_;
  693. $history->save();
  694. }
  695.  
  696. $shippingNumberSaved .= $this->l('ID order: ').$order->id.$this->l(' updated!').'<br>';
  697. }
  698. else
  699. $errors[] = $this->l('An error occurred while sending e-mail to the customer.');
  700. }
  701. else
  702. $errors[] = $this->l('Order carrier can\'t be updated');
  703. }
  704. }
  705. }
  706. }
  707.  
  708. if (count($errors) > 0)
  709. {
  710. $display_errors = '';
  711. foreach($errors as $error)
  712. $display_errors .= $error.'<br>';
  713.  
  714. return $this->displayError($this->l('Import finished with these errors (').count($errors).'):<br>'.$display_errors).
  715. $this->displayConfirmation($this->l('File was imported !').'<br><br>'.$shippingNumberSaved);
  716. }
  717. else
  718. return $this->displayConfirmation($this->l('File was imported !').'<br><br>'.$shippingNumberSaved);
  719. }
  720.  
  721. public static function getOrderByReference($reference)
  722. {
  723. $sql = 'SELECT `id_order`
  724. FROM `'._DB_PREFIX_.'orders`
  725. WHERE `reference` = \''.$reference.'\'
  726. '.Shop::addSqlRestriction();
  727. $result = Db::getInstance()->getRow($sql);
  728.  
  729. return isset($result['id_order']) ? $result['id_order'] : false;
  730. }
  731.  
  732. public function getIdOrderCarrier($id_order)
  733. {
  734. return (int)Db::getInstance()->getValue('
  735. SELECT `id_order_carrier`
  736. FROM `'._DB_PREFIX_.'order_carrier`
  737. WHERE `id_order` = '.(int)$id_order);
  738. }
  739. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement