Advertisement
Guest User

Untitled

a guest
Nov 1st, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 49.81 KB | None | 0 0
  1. <?php
  2. /**
  3. *
  4. * @ This file is created by http://DeZender.Net
  5. * @ deZender (PHP7 Decoder for SourceGuardian Encoder)
  6. *
  7. * @ Version : 4.0.9.0
  8. * @ Author : DeZender
  9. * @ Release on : 08.08.2019
  10. * @ Official site : http://DeZender.Net
  11. *
  12. */
  13.  
  14. if (!defined('_PS_VERSION_')) {
  15. exit();
  16. }
  17.  
  18. class AnymarketPro extends Module
  19. {
  20. protected $config_form = false;
  21. public $urlany = ['http://sandbox-api.anymarket.com.br/v2/', 'http://api.anymarket.com.br/v2/'];
  22. public $sendResponse;
  23. public $orders_qty = 100;
  24. public $prod_qty = 1200;
  25. public $mktplaces = [];
  26. public $horaatual;
  27. public $ecommerce_active;
  28. public $hierarquia = false;
  29. public $referencia = true;
  30. public $erp = false;
  31.  
  32. public function __construct()
  33. {
  34. $this->name = 'anymarketpro';
  35. $this->tab = 'market_place';
  36. $this->version = '1.6.8.4';
  37. $this->author = 'PrestaBR';
  38. $this->need_instance = 1;
  39. $this->bootstrap = true;
  40. parent::__construct();
  41. $this->displayName = $this->l('AnyMarket Integration');
  42. $this->description = $this->l('Integrate your shop with many Brazilian MarketPlaces');
  43. $this->confirmUninstall = $this->l('Are you sure to uninstall the Anymarket Integration?');
  44. $this->ps_versions_compliancy = ['min' => '1.6.0.9', 'max' => _PS_VERSION_];
  45. $this->horaatual = date('d-m-Y H:i:s');
  46.  
  47. if (!Module::isEnabled('anymarketpayment')) {
  48. $this->warning = $this->l('Don\'t forget to install and enable AnyMarket Payments module, so your shop can process orders from the integrated MarketPlaces.');
  49. }
  50.  
  51. if (Module::isEnabled($this->name)) {
  52. $this->mktplaces = Db::getInstance()->executeS("\r\n\t\t\t\t" . 'SELECT * FROM `' . _DB_PREFIX_ . 'anymarketpro_places` ' . "\r\n\t\t\t\t" . 'WHERE `deleted` != 1 ' . "\r\n\t\t\t\t" . 'ORDER BY `id_mkt` ASC');
  53.  
  54. foreach ($this->mktplaces as $mktplace) {
  55. if ($mktplace['mkt_name'] == 'ecommerce') {
  56. if ($mktplace['mkt_active'] == 1) {
  57. $this->ecommerce_active = true;
  58. }
  59. }
  60. }
  61. }
  62. }
  63.  
  64. /**
  65. * Installation
  66. */
  67. public function install()
  68. {
  69. Configuration::updateValue('ANYMARKETPRO_LIVE_MODE', false);
  70. Configuration::updateValue('ANYMARKETPRO_ENV', 0, false);
  71. Configuration::updateValue('ANYMARKETPRO_TOKEN', '', false);
  72. Configuration::updateValue('ANYMARKETPRO_EMAIL', '', false);
  73. Configuration::updateValue('ANYMARKETPRO_PAGO', Configuration::get('PS_OS_PAYMENT'), false);
  74. Configuration::updateValue('ANYMARKETPRO_FATURADO', Configuration::get('PS_OS_PREPARATION'), false);
  75. Configuration::updateValue('ANYMARKETPRO_ENVIADO', Configuration::get('PS_OS_SHIPPING'), false);
  76. Configuration::updateValue('ANYMARKETPRO_CONCLUIDO', Configuration::get('PS_OS_DELIVERED'), false);
  77. Configuration::updateValue('ANYMARKETPRO_CANCELADO', Configuration::get('PS_OS_CANCELED'), false);
  78. Configuration::updateValue('ANYMARKETPRO_WAR', 'Garantia padrão de 3 meses.', false);
  79. Configuration::updateValue('ANYMARKETPRO_WAR_TIME', 3, false);
  80. Configuration::updateValue('ANYMARKETPRO_FULLOG', 1, false);
  81. Configuration::updateValue('ANYMARKETPRO_DELETEDB', 0, false);
  82. include dirname(__FILE__) . '/sql/install.php';
  83. return parent::install() && $this->installAnyTabs() && $this->registerHook('backOfficeHeader') && $this->registerHook('actionCategoryAdd') && $this->registerHook('actionCategoryDelete') && $this->registerHook('actionCategoryUpdate') && $this->registerHook('actionProductAdd') && $this->registerHook('actionProductDelete') && $this->registerHook('actionProductSave') && $this->registerHook('actionProductUpdate') && $this->registerHook('actionUpdateQuantity') && $this->registerHook('actionValidateOrder') && $this->registerHook('actionOrderStatusPostUpdate') && $this->registerHook('actionObjectManufacturerAddAfter') && $this->registerHook('actionObjectManufacturerDeleteAfter') && $this->registerHook('actionObjectManufacturerUpdateAfter') && $this->registerHook('actionAttributeGroupSave') && $this->registerHook('actionAttributeGroupDelete') && $this->registerHook('actionAttributeSave') && $this->registerHook('actionAttributeDelete');
  84. }
  85.  
  86. public function uninstall()
  87. {
  88. if ((Configuration::get('ANYMARKETPRO_DELETEDB') !== false) && (Configuration::get('ANYMARKETPRO_DELETEDB') != 0)) {
  89. include dirname(__FILE__) . '/sql/uninstall.php';
  90. }
  91.  
  92. Configuration::deleteByName('ANYMARKETPRO_LIVE_MODE');
  93. Configuration::deleteByName('ANYMARKETPRO_ENV');
  94. Configuration::deleteByName('ANYMARKETPRO_TOKEN');
  95. Configuration::deleteByName('ANYMARKETPRO_EMAIL');
  96. Configuration::deleteByName('ANYMARKETPRO_PAGO');
  97. Configuration::deleteByName('ANYMARKETPRO_FATURADO');
  98. Configuration::deleteByName('ANYMARKETPRO_ENVIADO');
  99. Configuration::deleteByName('ANYMARKETPRO_CONCLUIDO');
  100. Configuration::deleteByName('ANYMARKETPRO_CANCELADO');
  101. Configuration::deleteByName('ANYMARKETPRO_WAR');
  102. Configuration::deleteByName('ANYMARKETPRO_WAR_TIME');
  103. Configuration::deleteByName('ANYMARKETPRO_FULLOG');
  104. Configuration::deleteByName('ANYMARKETPRO_DELETEDB');
  105. return parent::uninstall() && $this->uninstallAnyTabs();
  106. }
  107.  
  108. public function installAnyTabs()
  109. {
  110. $tab0 = new Tab();
  111. $tab0->class_name = 'AdminAnyPro';
  112. $tab0->module = 'anymarketpro';
  113. $tab0->id_parent = NULL;
  114.  
  115. foreach (Language::getLanguages(false) as $lang) {
  116. $tab0->name[(int) $lang['id_lang']] = $this->l('Integração AnyMarket');
  117. }
  118.  
  119. if (!$tab0->save()) {
  120. $this->_errors[] = $this->l('Unable to create the "AnyMarket" tab');
  121. }
  122.  
  123. if (!@copy(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'logo.gif', _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . 't' . DIRECTORY_SEPARATOR . 'AdminAnyPro.gif')) {
  124. $this->_errors[] = sprintf($this->l('Unable to copy logo.gif in %s'), _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . 't' . DIRECTORY_SEPARATOR);
  125. }
  126.  
  127. return true;
  128. }
  129.  
  130. public function uninstallAnyTabs()
  131. {
  132. $id_tab = Tab::getIdFromClassName('AdminAnyPro');
  133. $tab = new Tab($id_tab);
  134.  
  135. if (!$tab->delete()) {
  136. return false;
  137. }
  138.  
  139. return true;
  140. }
  141.  
  142. /**
  143. * Load the configuration form
  144. */
  145. public function getContent()
  146. {
  147. $groups = Group::getGroups($this->context->language->id, true);
  148. $output = '';
  149. $this->mktplaces = Db::getInstance()->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'anymarketpro_places` WHERE `deleted` != 1 ORDER BY `mkt_active` DESC, `id_mkt` ASC;');
  150.  
  151. if ((bool) Tools::isSubmit('submitAnymarketProModule')) {
  152. if (!$this->postProcess()) {
  153. $output .= $this->displayError($this->l('Configuration not updated!'));
  154. }
  155. else {
  156. $output .= $this->displayConfirmation($this->l('Configuration sucessfully updated.'));
  157. }
  158. }
  159.  
  160. if ((bool) Tools::isSubmit('submitCategoriesPop')) {
  161. $this->populateCategories();
  162. $this->context->smarty->assign('postresponse', $this->sendResponse);
  163. }
  164. else if ((bool) Tools::isSubmit('submitBrandsPop')) {
  165. $this->populateBrands();
  166. $this->context->smarty->assign('postresponse', $this->sendResponse);
  167. }
  168. else if ((bool) Tools::isSubmit('submitProductsPop')) {
  169. $this->populateProducts();
  170. $this->context->smarty->assign('postresponse', $this->sendResponse);
  171. }
  172. else if ((bool) Tools::isSubmit('submitOrdersPop')) {
  173. $this->populateOrders();
  174. $this->context->smarty->assign('postresponse', $this->sendResponse);
  175. }
  176. else if ((bool) Tools::isSubmit('submitStockPop')) {
  177. $this->updateStock();
  178. $this->context->smarty->assign('postresponse', $this->sendResponse);
  179. }
  180. else if ((bool) Tools::isSubmit('submitVariationsPop')) {
  181. $this->populateVariations();
  182. $this->context->smarty->assign('postresponse', $this->sendResponse);
  183. }
  184. else if ((bool) Tools::isSubmit('submitCategoriesTree')) {
  185. $this->getAnyMarketCategory();
  186. $this->context->smarty->assign('postresponse', $this->sendResponse);
  187. }
  188. else if ((bool) Tools::isSubmit('submitMktPlaces')) {
  189. foreach ($this->mktplaces as $mktplace) {
  190. $active = Tools::getValue('mkt_active_' . $mktplace['id_mkt']);
  191.  
  192. if ($active) {
  193. $mkt_markup = str_replace(',', '.', Tools::getValue('mkt_markup_' . $mktplace['id_mkt']));
  194. $mkt_group = Tools::getValue('mkt_group_' . $mktplace['id_mkt']);
  195. Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'anymarketpro_places` SET' . "\r\n\t\t\t\t\t\t" . '`mkt_active` = 1,' . "\r\n\t\t\t\t\t\t" . '`mkt_markup` = "' . (float) $mkt_markup . '",' . "\r\n\t\t\t\t\t\t" . '`mkt_group` = ' . (int) $mkt_group . "\r\n\t\t\t\t\t\t" . 'WHERE `id_mkt` = ' . $mktplace['id_mkt'] . ';' . "\r\n\t\t\t\t\t");
  196. }
  197. else {
  198. Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'anymarketpro_places` SET `mkt_active` = 0 WHERE `id_mkt` = ' . $mktplace['id_mkt'] . ';');
  199. }
  200.  
  201. $deleted = Tools::getValue('mkt_delete_' . $mktplace['id_mkt']);
  202.  
  203. if ($deleted === true) {
  204. Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'anymarketpro_places` SET `deleted` = 1 WHERE `id_mkt` = ' . $mktplace['id_mkt'] . ';');
  205. }
  206. }
  207.  
  208. $output .= $this->displayConfirmation($this->l('MarketPlaces Updated!'));
  209. }
  210. else if ((bool) Tools::isSubmit('submitOrderGet')) {
  211. $id_any = Tools::getValue('id_order_any');
  212. $get_all = Tools::getValue('get_all_orders');
  213. if ($get_all && !$id_any) {
  214. $this->getAllOrdersAnyMarket();
  215. }
  216. else {
  217. $this->getOrderFromAnyMarket($id_any);
  218. }
  219.  
  220. $this->context->smarty->assign('postresponse', $this->sendResponse);
  221. }
  222.  
  223. $this->context->smarty->assign(['orders_qty' => $this->orders_qty, 'module_dir' => $this->_path, 'module_dir_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/', 'module_name' => $this->displayName, 'module_desc' => $this->description, 'mktplaces' => $this->mktplaces, 'form_uri' => $_SERVER['REQUEST_URI'], 'groups' => $groups, 'ecommerce_active' => $this->ecommerce_active === true ? 'true' : 'false', 'enabled' => Module::isEnabled($this->name) ? 'true' : 'false']);
  224. $output .= $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
  225. return $output . $this->renderForm();
  226. }
  227.  
  228. /**
  229. * Create the form that will be displayed in the configuration of your module.
  230. */
  231. protected function renderForm()
  232. {
  233. $helper = new HelperForm();
  234. $helper->show_toolbar = false;
  235. $helper->table = $this->table;
  236. $helper->module = $this;
  237. $helper->default_form_language = $this->context->language->id;
  238. $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
  239. $helper->identifier = $this->identifier;
  240. $helper->submit_action = 'submitAnymarketProModule';
  241. $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
  242. $helper->token = Tools::getAdminTokenLite('AdminModules');
  243. $helper->tpl_vars = ['fields_value' => $this->getConfigFormValues(), 'languages' => $this->context->controller->getLanguages(), 'id_language' => $this->context->language->id];
  244. return $helper->generateForm([$this->getConfigForm()]);
  245. }
  246.  
  247. /**
  248. * Create the structure of your form.
  249. */
  250. protected function getConfigForm()
  251. {
  252. $groups = Group::getGroups($this->context->language->id, true);
  253. $statuses = OrderState::getOrderStates($this->context->language->id);
  254. return [
  255. 'form' => [
  256. 'legend' => ['title' => $this->l('Settings'), 'icon' => 'icon-cogs'],
  257. 'input' => [
  258. [
  259. 'type' => 'switch',
  260. 'label' => $this->l('Production Environment'),
  261. 'name' => 'ANYMARKETPRO_ENV',
  262. 'is_bool' => false,
  263. 'desc' => $this->l('Use the test environment to check if everything is OK before going live'),
  264. 'values' => [
  265. ['id' => 'active_on', 'value' => 1, 'label' => $this->l('Production')],
  266. ['id' => 'active_off', 'value' => 0, 'label' => $this->l('Sandbox')]
  267. ]
  268. ],
  269. ['col' => 5, 'type' => 'text', 'prefix' => '<i class="icon icon-envelope"></i>', 'desc' => $this->l('Enter a valid email address'), 'name' => 'ANYMARKETPRO_EMAIL', 'label' => $this->l('Email')],
  270. ['col' => 5, 'type' => 'text', 'prefix' => '<i class="icon icon-key"></i>', 'name' => 'ANYMARKETPRO_TOKEN', 'label' => $this->l('Token'), 'desc' => $this->l('Set the token provided by Anymarket (Sandbox or Production)')],
  271. ['col' => 5, 'type' => 'text', 'name' => 'ANYMARKETPRO_WAR_TIME', 'label' => $this->l('Warranty Time'), 'desc' => $this->l('Set the common Warranty Time (number of months) to be sent to Anymarket (Default: 3). This text can be updated individually at AnyMarket.')],
  272. ['col' => 5, 'type' => 'text', 'name' => 'ANYMARKETPRO_WAR', 'label' => $this->l('Warranty Text'), 'desc' => $this->l('Set the default text for warranty field. This text can be updated individually at AnyMarket.')],
  273. [
  274. 'type' => 'select',
  275. 'label' => $this->l('Order Paid State'),
  276. 'name' => 'ANYMARKETPRO_PAGO',
  277. 'desc' => $this->l('Set the status which the orders are considered paid.'),
  278. 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
  279. ],
  280. [
  281. 'type' => 'select',
  282. 'label' => $this->l('Order Invoiced State'),
  283. 'name' => 'ANYMARKETPRO_FATURADO',
  284. 'desc' => $this->l('Set the status which the orders are considered invoiced.'),
  285. 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
  286. ],
  287. [
  288. 'type' => 'select',
  289. 'label' => $this->l('Order Sent State'),
  290. 'name' => 'ANYMARKETPRO_ENVIADO',
  291. 'desc' => $this->l('Set the status which the orders are considered sent.'),
  292. 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
  293. ],
  294. [
  295. 'type' => 'select',
  296. 'label' => $this->l('Order Concluded State'),
  297. 'name' => 'ANYMARKETPRO_CONCLUIDO',
  298. 'desc' => $this->l('Set the status which the orders are considered concluded.'),
  299. 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
  300. ],
  301. [
  302. 'type' => 'select',
  303. 'label' => $this->l('Order Canceled State'),
  304. 'name' => 'ANYMARKETPRO_CANCELADO',
  305. 'desc' => $this->l('Set the status which the orders are considered canceled.'),
  306. 'options' => ['query' => $statuses, 'id' => 'id_order_state', 'name' => 'name']
  307. ],
  308. ['col' => 5, 'type' => 'text', 'prefix' => '<i class="icon icon-link"></i>', 'desc' => $this->l('Set this URL in Anymarket \\"Configuration > Parameters\\" - Callback URL option.'), 'name' => 'ANYMARKETPRO_POSTBACK', 'disabled' => true, 'label' => $this->l('Callback URL')],
  309. [
  310. 'type' => 'switch',
  311. 'label' => $this->l('Generate Full LOGs'),
  312. 'name' => 'ANYMARKETPRO_FULLOG',
  313. 'is_bool' => true,
  314. 'desc' => $this->l('Full Logs register everything sent and received.'),
  315. 'values' => [
  316. ['id' => 'logs_on', 'value' => 1, 'label' => $this->l('Yes')],
  317. ['id' => 'logs_off', 'value' => 0, 'label' => $this->l('No')]
  318. ]
  319. ],
  320. [
  321. 'type' => 'switch',
  322. 'label' => $this->l('Delete Database?'),
  323. 'name' => 'ANYMARKETPRO_DELETEDB',
  324. 'is_bool' => true,
  325. 'desc' => $this->l('Delete Database upon uninstall only if you are sure you won\'t use it anymore.'),
  326. 'values' => [
  327. ['id' => 'deletebd_on', 'value' => 1, 'label' => $this->l('Yes')],
  328. ['id' => 'deletebd_off', 'value' => 0, 'label' => $this->l('No')]
  329. ]
  330. ]
  331. ],
  332. 'submit' => ['title' => $this->l('Save')]
  333. ]
  334. ];
  335. }
  336.  
  337. /**
  338. * Set values for the inputs.
  339. */
  340. protected function getConfigFormValues()
  341. {
  342. return ['ANYMARKETPRO_ENV' => Tools::getValue('ANYMARKETPRO_ENV', Configuration::get('ANYMARKETPRO_ENV')), 'ANYMARKETPRO_EMAIL' => Tools::getValue('ANYMARKETPRO_EMAIL', Configuration::get('ANYMARKETPRO_EMAIL')), 'ANYMARKETPRO_TOKEN' => Tools::getValue('ANYMARKETPRO_TOKEN', Configuration::get('ANYMARKETPRO_TOKEN')), 'ANYMARKETPRO_WAR' => Tools::getValue('ANYMARKETPRO_WAR', Configuration::get('ANYMARKETPRO_WAR')), 'ANYMARKETPRO_WAR_TIME' => Tools::getValue('ANYMARKETPRO_WAR_TIME', Configuration::get('ANYMARKETPRO_WAR_TIME')), 'ANYMARKETPRO_POSTBACK' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/update.php', 'ANYMARKETPRO_PAGO' => Tools::getValue('ANYMARKETPRO_PAGO', Configuration::get('ANYMARKETPRO_PAGO')), 'ANYMARKETPRO_FATURADO' => Tools::getValue('ANYMARKETPRO_FATURADO', Configuration::get('ANYMARKETPRO_FATURADO')), 'ANYMARKETPRO_ENVIADO' => Tools::getValue('ANYMARKETPRO_ENVIADO', Configuration::get('ANYMARKETPRO_ENVIADO')), 'ANYMARKETPRO_CONCLUIDO' => Tools::getValue('ANYMARKETPRO_CONCLUIDO', Configuration::get('ANYMARKETPRO_CONCLUIDO')), 'ANYMARKETPRO_CANCELADO' => Tools::getValue('ANYMARKETPRO_CANCELADO', Configuration::get('ANYMARKETPRO_CANCELADO')), 'ANYMARKETPRO_FULLOG' => Tools::getValue('ANYMARKETPRO_FULLOG', Configuration::get('ANYMARKETPRO_FULLOG')), 'ANYMARKETPRO_DELETEDB' => Tools::getValue('ANYMARKETPRO_DELETEDB', Configuration::get('ANYMARKETPRO_DELETEDB'))];
  343. }
  344.  
  345. /**
  346. * Save form data.
  347. */
  348. protected function postProcess()
  349. {
  350. $form_values = $this->getConfigFormValues();
  351. $erro = false;
  352.  
  353. foreach (array_keys($form_values) as $key) {
  354. if (!Configuration::updateValue($key, Tools::getValue($key))) {
  355. $erro = true;
  356. }
  357. }
  358.  
  359. if ($erro) {
  360. return false;
  361. }
  362. else {
  363. return true;
  364. }
  365. }
  366.  
  367. /**
  368. * Add the CSS & JavaScript files you want to be loaded in the BO.
  369. */
  370. public function hookBackOfficeHeader()
  371. {
  372. $id_product = Tools::getValue('id_product');
  373. if (isset($id_product) && ($id_product != '')) {
  374. $id_prod_any = $this->getAnymarketData('products', $id_product);
  375. $this->context->controller->addJquery();
  376. $this->context->controller->addJS($this->_path . 'views/js/button.js');
  377.  
  378. if ((bool) Tools::isSubmit('submitProductInitial')) {
  379. $this->sendProductData($id_product, 'POST');
  380. }
  381.  
  382. if ((bool) Tools::isSubmit('submitUpdateAnyImages')) {
  383. $this->sendProdImages($id_product, $id_prod_any);
  384. }
  385.  
  386. if ((bool) Tools::isSubmit('submitDeleteFromDb')) {
  387. $this->deleteAnymarketData('products', $id_product);
  388. }
  389.  
  390. $this->context->smarty->assign('id_prod_any', $id_prod_any);
  391. return $this->display(__FILE__, 'admin_product.tpl');
  392. }
  393. if ((Tools::getValue('module_name') == $this->name) || (Tools::getValue('configure') == $this->name)) {
  394. $this->context->controller->addJS($this->_path . 'views/js/anymarketpro.js');
  395. }
  396.  
  397. $this->context->controller->addCSS($this->_path . 'views/css/anymarketpro.css');
  398. }
  399.  
  400. public function curl_post($post_url, $method, $post_string, $action = false)
  401. {
  402. if (is_array($post_string)) {
  403. $post_string = json_encode($post_string);
  404. }
  405.  
  406. $any_base_url = $this->urlany[Configuration::get('ANYMARKETPRO_ENV')];
  407. $post_header = ['Content-Type: application/json', 'gumgaToken: ' . Configuration::get('ANYMARKETPRO_TOKEN') . ''];
  408. $request = curl_init($any_base_url . $post_url);
  409. curl_setopt($request, CURLOPT_HTTPHEADER, $post_header);
  410. curl_setopt($request, CURLOPT_CONNECTTIMEOUT, 0);
  411. curl_setopt($request, CURLOPT_TIMEOUT, 500);
  412. curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
  413.  
  414. if ($method == 'POST') {
  415. curl_setopt($request, CURLOPT_POST, true);
  416. curl_setopt($request, CURLOPT_POSTFIELDS, $post_string);
  417. }
  418. else if ($method == 'PUT') {
  419. curl_setopt($request, CURLOPT_CUSTOMREQUEST, 'PUT');
  420. curl_setopt($request, CURLOPT_POSTFIELDS, $post_string);
  421. }
  422. else if ($method == 'DELETE') {
  423. curl_setopt($request, CURLOPT_CUSTOMREQUEST, 'DELETE');
  424. }
  425.  
  426. $post_response = curl_exec($request);
  427. $err = curl_error($request);
  428. $status = curl_getinfo($request, CURLINFO_HTTP_CODE);
  429. if (($status == 200) || ($status == 204) || ($status == 201)) {
  430. $retorno = ['error' => '0', 'json' => $post_string, 'return' => json_decode($post_response)];
  431. }
  432. else if ($err) {
  433. $retorno = ['error' => '1', 'json' => $post_string, 'return' => 'Error Curl: ' . $err];
  434. }
  435. else {
  436. $retJsonCurlResp = json_decode($post_response);
  437. $retString = '';
  438.  
  439. if (isset($retJsonCurlResp->message)) {
  440. $retString = 'Message: ' . utf8_encode($retJsonCurlResp->message);
  441. }
  442.  
  443. if (isset($retJsonCurlResp->details)) {
  444. $retString .= '; Details: ' . utf8_encode($retJsonCurlResp->details);
  445. }
  446.  
  447. if (isset($retJsonCurlResp->fieldErrors)) {
  448. $retString .= '; Field Erros: (';
  449.  
  450. foreach ($retJsonCurlResp->fieldErrors as $error) {
  451. $retString .= 'Field: ' . utf8_encode($error->field);
  452. $retString .= ', Message: ' . utf8_encode($error->message) . ';';
  453. }
  454.  
  455. $retString .= ')';
  456. }
  457.  
  458. if ($retString != '') {
  459. $retorno = ['error' => '1', 'json' => '', 'return' => $retString];
  460. }
  461. else {
  462. $retorno = ['error' => '1', 'json' => '', 'return' => utf8_encode($post_response)];
  463. }
  464. }
  465.  
  466. curl_close($request);
  467.  
  468. if ((bool) Configuration::get('ANYMARKETPRO_FULLOG') !== false) {
  469. $this->saveLog('curl', $method, $post_string, json_encode($retorno), $post_url);
  470. }
  471.  
  472. $this->sendResponse[] = $post_response;
  473. $r_json = json_decode($post_response);
  474.  
  475. if (isset($r_json->id)) {
  476. if ($post_url == 'products') {
  477. $p_json = json_decode($post_string);
  478. $this->updateAnymarketData('products', $p_json->product_id, $r_json->id);
  479. }
  480. else if ($post_url == 'categories') {
  481. $this->updateAnymarketData($post_url, $r_json->partnerId, $r_json->id);
  482. }
  483. else if (strpos($post_url, 'brands') !== false) {
  484. $brand = json_decode($post_string);
  485. $this->updateAnymarketData('brands', $r_json->partnerId, $r_json->id);
  486. }
  487. else if ((strpos($post_url, 'variations') !== false) && !strpos($post_url, '/values')) {
  488. $this->updateAnymarketData('variations', $r_json->partnerId, $r_json->id);
  489. $this->updateVariations();
  490. }
  491. else if ((strpos($post_url, 'variations') !== false) && (strpos($post_url, '/values') !== false)) {
  492. $attribute = json_decode($post_string);
  493. $this->updateAnymarketData('var_value', $r_json->partnerId, $r_json->id);
  494. }
  495. else {
  496. $type = substr($post_url, 0, strpos($post_url, '/'));
  497. if (!$type || ($type == '')) {
  498. $type = $post_url;
  499. }
  500. }
  501. }
  502.  
  503. if (empty($post_response)) {
  504. $retorno = 'Curl error.';
  505. }
  506.  
  507. return $retorno;
  508. }
  509.  
  510. public function saveLog($type, $method, $json, $response = false, $url = false)
  511. {
  512. if (!$response) {
  513. $response = '';
  514. }
  515.  
  516. if (!$url) {
  517. $url = '';
  518. }
  519.  
  520. $query = 'INSERT INTO `' . _DB_PREFIX_ . 'anymarketpro_logs` (`datetime`, `type`, `method`, `url`, `json`, `response`) VALUES (NOW(), "' . $type . '", "' . $method . '", "' . addslashes($url) . '", "' . addslashes($json) . '", "' . addslashes($response) . '")';
  521.  
  522. if (Db::getInstance()->execute($query) === false) {
  523. return false;
  524. }
  525.  
  526. return true;
  527. }
  528.  
  529. public function populateCategories()
  530. {
  531. $categories = Category::getCategories($this->context->language->id, false, false);
  532. $this->sendResponse = [];
  533.  
  534. foreach ($categories as $category) {
  535. $id_any = $this->getAnymarketData('categories', $category['id_category']);
  536. $cat = new Category($category['id_category']);
  537. $cat_name = '';
  538. $parents = $cat->getParentsCategories($this->context->language->id);
  539.  
  540. foreach (array_reverse($parents) as $parent) {
  541. if ($parent !== end($parents)) {
  542. $cat_name .= $parent['name'];
  543. }
  544. if (($parent !== reset($parents)) && ($parent !== end($parents))) {
  545. $cat_name .= ' > ';
  546. }
  547. }
  548. if (!$id_any || ($id_any == '')) {
  549. if ($category['id_parent'] < 2) {
  550. $id_parent = (int) Configuration::get('PS_HOME_CATEGORY');
  551. }
  552. else {
  553. $id_parent = (int) $category['id_parent'];
  554. }
  555.  
  556. if (1 < $category['id_category']) {
  557. $this->sendCategoryData($cat_name, $category['id_category'], $id_parent);
  558. }
  559. }
  560. }
  561.  
  562. $this->getAnyMarketCategory();
  563. }
  564.  
  565. public function sendCategoryData($cat_name, $cat_id, $cat_id_parent)
  566. {
  567. $cat_name = substr($cat_name, 0, 78);
  568.  
  569. if ($this->hierarquia === true) {
  570. $id_parent_category = (int) $this->getAnymarketData('categories', $cat_id_parent);
  571. }
  572. else {
  573. $id_parent_category = (int) $this->getAnymarketData('categories', Configuration::get('PS_HOME_CATEGORY'));
  574. }
  575.  
  576. if (1 < $cat_id) {
  577. if ($cat_id != Configuration::get('PS_HOME_CATEGORY')) {
  578. $cat_array = [
  579. 'name' => str_replace('/', '-', $cat_name),
  580. 'partnerId' => $cat_id,
  581. 'parent' => ['id' => isset($id_parent_category) && $id_parent_category ? $id_parent_category : 'null'],
  582. 'priceFactor' => 1,
  583. 'calculatedPrice' => true
  584. ];
  585. }
  586. else {
  587. $category = new Category($cat_id);
  588. $cat_array = ['name' => str_replace('/', '-', $category->name[$this->context->language->id]), 'partnerId' => $cat_id, 'priceFactor' => 1, 'calculatedPrice' => true];
  589. }
  590. }
  591.  
  592. $cat_exists = $this->getAnymarketData('categories', $cat_id);
  593.  
  594. if ($cat_exists === false) {
  595. $this->curl_post('categories', 'POST', $cat_array);
  596. }
  597. else {
  598. $this->curl_post('categories/' . $cat_exists, 'PUT', $cat_array);
  599. }
  600. }
  601.  
  602. public function populateBrands()
  603. {
  604. $brands = Manufacturer::getManufacturers(false, $this->context->language->id);
  605. $this->sendResponse = [];
  606.  
  607. foreach ($brands as $brand) {
  608. if (!$this->getAnymarketData('brands', $brand['id_manufacturer'])) {
  609. $this->sendBrandData($brand['id_manufacturer'], $brand['name']);
  610. }
  611. }
  612.  
  613. if (!$this->getAnymarketData('brands', 'loja')) {
  614. $this->sendBrandData('loja', Configuration::get('PS_SHOP_NAME'));
  615. }
  616. }
  617.  
  618. public function sendBrandData($id_manufacturer, $manu_name)
  619. {
  620. $man_array = ['name' => str_replace('/', '-', $manu_name), 'partnerId' => $id_manufacturer];
  621. $this->curl_post('brands', 'POST', $man_array);
  622. }
  623.  
  624. public function updateBrandData($id_any, $id_manufacturer, $manu_name)
  625. {
  626. $man_array = ['name' => str_replace('/', '-', $manu_name), 'partnerId' => $id_manufacturer];
  627. $this->curl_post('brands/' . $id_any, 'PUT', $man_array);
  628. }
  629.  
  630. public function populateVariations()
  631. {
  632. $attribute_groups = AttributeGroup::getAttributesGroups($this->context->language->id);
  633.  
  634. foreach ($attribute_groups as $group) {
  635. $id_variation_any = $this->getAnymarketData('variations', $group['id_attribute_group']);
  636. $attributes = AttributeGroup::getAttributes($this->context->language->id, $group['id_attribute_group']);
  637. $values = [];
  638.  
  639. foreach ($attributes as $attribute) {
  640. $values[] = [
  641. 'description' => $attribute['name'],
  642. 'partnerId' => $attribute['id_attribute'],
  643. 'type' => ['id' => $id_variation_any, 'name' => $group['name']]
  644. ];
  645. }
  646.  
  647. if ($id_variation_any !== false) {
  648. $variation = ['id' => $id_variation_any, 'name' => $group['name'], 'partnerId' => $group['id_attribute_group'], 'visualVariation' => $group['is_color_group'] == 1 ? 'true' : 'false', 'values' => $values];
  649. $this->sendVariationData($variation, $id_variation_any);
  650. }
  651. else {
  652. $variation = ['name' => $group['name'], 'partnerId' => $group['id_attribute_group'], 'visualVariation' => $group['is_color_group'] == 1 ? 'true' : 'false', 'values' => $values];
  653. $this->sendVariationData($variation);
  654. }
  655. }
  656. }
  657.  
  658. public function sendVariationData($variation, $id_variation_any = false)
  659. {
  660. if (!$id_variation_any) {
  661. $this->curl_post('variations', 'POST', $variation);
  662. }
  663. else {
  664. $this->curl_post('variations/' . $id_variation_any, 'PUT', $variation);
  665. }
  666. }
  667.  
  668. public function sendVariationValue($attribute, $id_variation_any, $id_attribute_any = false)
  669. {
  670. if (!$id_attribute_any) {
  671. $this->curl_post('variations/' . $id_variation_any . '/values', 'POST', $attribute);
  672. }
  673. else {
  674. $this->curl_post('variations/' . $id_variation_any . '/values/' . $id_attribute_any, 'PUT', $attribute);
  675. }
  676. }
  677.  
  678. public function populateProducts()
  679. {
  680. $prods = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS("\r\n\t\t\t" . 'SELECT p.`id_product` FROM `' . _DB_PREFIX_ . 'product` p' . "\r\n\t\t\t" . 'WHERE p.`active` = 1' . "\r\n\t\t\t" . 'ORDER BY `id_product` ASC;' . "\r\n\t\t");
  681. $this->sendResponse = [];
  682.  
  683. foreach ($prods as $prod) {
  684. $id_any = $this->getAnymarketData('products', $prod['id_product']);
  685. if (!$id_any || ($id_any == '')) {
  686. $this->sendProductData($prod['id_product'], 'POST');
  687. }
  688. }
  689. }
  690.  
  691. public function sendProductData($id_product, $post_type)
  692. {
  693. $product = new Product($id_product);
  694.  
  695. if ((bool) $product->active !== true) {
  696. return NULL;
  697. }
  698.  
  699. $id_any = $this->checkProductAnyMarket($id_product);
  700. $imgs = $product->getImages($this->context->language->id);
  701. $comb_imgs = $product->getCombinationImages($this->context->language->id);
  702. $img_var = '';
  703. $prod_img = [];
  704.  
  705. foreach ($imgs as $k => $img) {
  706. foreach ($comb_imgs as $k => $comb_img) {
  707. foreach ($comb_img as $attrib) {
  708. if ($attrib['id_image'] == $img['id_image']) {
  709. $var = $product->getAttributeCombinationsById($attrib['id_product_attribute'], $this->context->language->id);
  710.  
  711. foreach ($var as $combination) {
  712. $var_name = '';
  713.  
  714. if ((bool) $combination['is_color_group'] !== false) {
  715. $var_name .= trim($combination['attribute_name']);
  716.  
  717. if (end($var) !== $combination) {
  718. $var_name .= ' / ';
  719. }
  720. }
  721. }
  722. }
  723. }
  724. }
  725. $prod_img[] = ['index' => $k, 'main' => $img['cover'] ? true : false, 'url' => str_replace('https://', 'http://', $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], (int) $product->id . '-' . (int) $img['id_image'], ImageType::getFormatedName('thickbox'))), 'thumbnailUrl' => str_replace('https://', 'http://', $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], (int) $product->id . '-' . (int) $img['id_image'], ImageType::getFormatedName('medium'))), 'lowResolutionUrl' => str_replace('https://', 'http://', $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], (int) $product->id . '-' . (int) $img['id_image'], ImageType::getFormatedName('home'))), 'standardUrl' => str_replace('https://', 'http://', $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], (int) $product->id . '-' . (int) $img['id_image'], ImageType::getFormatedName('large'))), 'variation' => isset($var_name) && $var_name ? $var_name : ''];
  726. }
  727.  
  728. $features = $product->getFrontFeatures($this->context->language->id);
  729. $prod_features = [];
  730.  
  731. foreach ($features as $k => $feature) {
  732. $prod_features[] = ['index' => $k, 'name' => $feature['name'], 'value' => $feature['value']];
  733. }
  734.  
  735. $combination_ids = $product->getProductAttributesIds($product->id);
  736. $skus = [];
  737. if (isset($combination_ids) && !empty($combination_ids)) {
  738. foreach ($combination_ids as $attribute) {
  739. $combinations = $product->getAttributeCombinationsById($attribute['id_product_attribute'], $this->context->language->id);
  740. $attribute_name = '';
  741. $variations = [];
  742.  
  743. foreach ($combinations as $combination) {
  744. $attribute_name .= trim($combination['group_name']) . '(' . trim($combination['attribute_name']) . ') ';
  745. $cod_barras = $combination['ean13'];
  746. $variations = array_merge($variations, [trim($combination['group_name']) => trim($combination['attribute_name'])]);
  747.  
  748. if ($this->referencia === true) {
  749. $partId = (isset($combination['reference']) && $combination['reference'] ? $combination['reference'] : $product->reference);
  750. }
  751. else {
  752. $partId = $product->id . '-' . $attribute['id_product_attribute'];
  753. }
  754. }
  755.  
  756. if (!$cod_barras) {
  757. $cod_barras = $product->ean13;
  758. }
  759.  
  760. $skus[] = ['title' => substr($product->name[$this->context->language->id] . ' - ' . $attribute_name, 0, 145), 'partnerId' => $partId, 'ean' => $this->validateEAN13($cod_barras) === true ? $cod_barras : '', 'amount' => StockAvailable::getQuantityAvailableByProduct($product->id, $attribute['id_product_attribute']), 'price' => $product->getPrice(true, $attribute['id_product_attribute'], 2), 'variations' => $variations];
  761. }
  762. }
  763. else {
  764. if ($this->referencia === true) {
  765. $partId = $product->reference;
  766. }
  767. else {
  768. $partId = $product->id;
  769. }
  770. $skus[] = ['title' => substr($product->name[$this->context->language->id], 0, 145), 'partnerId' => $partId, 'ean' => $this->validateEAN13($product->ean13) === true ? $product->ean13 : '', 'amount' => isset($product->id_product_attribute) && ($product->id_product_attribute != '') ? $product->getQuantity((int) $product->id, $product->id_product_attribute, NULL) : $product->getQuantity((int) $product->id), 'price' => $product->getPrice(true, NULL, 2)];
  771. }
  772.  
  773. if ($post_type == 'PUT') {
  774. $this->updateProductSkus($product->id);
  775. }
  776. $prod_brand = (isset($product->id_manufacturer) && $product->id_manufacturer ? $product->id_manufacturer : 'loja');
  777. if (isset($product->id_manufacturer) && ($product->id_manufacturer != '')) {
  778. $marca = new Manufacturer($product->id_manufacturer);
  779. $prod_manu = $marca->name;
  780. }
  781. else {
  782. $prod_manu = htmlentities(Configuration::get('PS_SHOP_NAME'), ENT_QUOTES, 'UTF-8');
  783. }
  784.  
  785. $permitted = '<p><b><strong><i><br>';
  786. if (isset($product->description[$this->context->language->id]) && $product->description[$this->context->language->id]) {
  787. $prod_desc = strip_tags($product->description[$this->context->language->id], $permitted);
  788. }
  789. else {
  790. $prod_desc = strip_tags($product->description_short[$this->context->language->id], $permitted);
  791. }
  792.  
  793. if (strtoupper($prod_desc) == $prod_desc) {
  794. $prod_desc = ucwords($prod_desc);
  795. }
  796.  
  797. $prod_desc = substr(nl2br($prod_desc), 0, 10000);
  798. $id_cat_any = $this->getAnymarketData('categories', $product->id_category_default);
  799. if (!$id_cat_any && $id_any) {
  800. $id_cat_any = $this->getProductCategoryFromAnyMarket($id_any);
  801. }
  802.  
  803. $prod_array = [
  804. 'product_id' => $product->id,
  805. 'title' => str_replace('/', '-', substr($product->name[$this->context->language->id], 0, 145)),
  806. 'description' => $prod_desc,
  807. 'category' => ['id' => $id_cat_any, 'partnerId' => $product->id_category_default],
  808. 'brand' => ['id' => $this->getAnymarketData('brands', $prod_brand), 'name' => $prod_manu, 'partnerId' => $prod_brand],
  809. 'nbm' => ['id' => isset($product->ncm[$this->context->language->id]) ? $product->ncm[$this->context->language->id] : ''],
  810. 'origin' => ['id' => isset($product->orig[$this->context->language->id]) ? $product->orig[$this->context->language->id] : 0],
  811. 'model' => $product->reference,
  812. 'gender' => $product->gender,
  813. 'warrantyTime' => Configuration::get('ANYMARKETPRO_WAR_TIME'),
  814. 'warrantyText' => Configuration::get('ANYMARKETPRO_WAR'),
  815. 'height' => 0 < $product->height ? $product->height : '',
  816. 'width' => 0 < $product->width ? $product->width : '',
  817. 'weight' => 0 < $product->weight ? $product->weight : '',
  818. 'length' => 0 < $product->depth ? $product->depth : '',
  819. 'priceFactor' => 1,
  820. 'calculatedPrice' => true,
  821. 'videoUrl' => '',
  822. 'characteristics' => $prod_features,
  823. 'images' => $prod_img,
  824. 'skus' => $skus
  825. ];
  826.  
  827. if ($post_type == 'POST') {
  828. $this->curl_post('products', $post_type, $prod_array);
  829. }
  830. else {
  831. if (!$id_any || ($id_any == '')) {
  832. $id_any = $this->getAnymarketData('products', $product->id);
  833. }
  834.  
  835. $this->curl_post('products/' . $id_any, $post_type, $prod_array);
  836. }
  837. }
  838.  
  839. public function updateProductSkus($id_product, $action = false)
  840. {
  841. if ($this->erp === true) {
  842. return NULL;
  843. }
  844.  
  845. $product = new Product($id_product);
  846. $idAny = $this->getAnymarketData('products', $id_product);
  847. if (!$idAny || ($idAny == '')) {
  848. $idAny = $this->checkProductAnyMarket($id_product);
  849. }
  850.  
  851. $skus = [];
  852. $combs = [];
  853. $estoques = [];
  854. $callback = $this->curl_post('products/' . $idAny . '/skus', 'GET', '', $action);
  855.  
  856. if (is_array($callback['return'])) {
  857. $skusAnymarket = json_decode(json_encode($callback['return']));
  858. }
  859. else if (!is_object($callback['return'])) {
  860. $skusAnymarket = json_decode($callback['return']);
  861. }
  862. else {
  863. $skusAnymarket = $callback['return'];
  864. }
  865.  
  866. foreach ($skusAnymarket as $skuAny) {
  867. $skus[$skuAny->partnerId] = $skuAny->id;
  868. }
  869.  
  870. $combination_ids = $product->getProductAttributesIds($product->id);
  871. if (isset($combination_ids) && !empty($combination_ids)) {
  872. foreach ($combination_ids as $attribute) {
  873. $stock = StockAvailable::getQuantityAvailableByProduct($product->id, $attribute['id_product_attribute']);
  874. $cost = $product->getPrice(true, $attribute['id_product_attribute'], 2);
  875. $combinations = $product->getAttributeCombinationsById($attribute['id_product_attribute'], $this->context->language->id);
  876. $attribute_name = false;
  877. $cod_barras = false;
  878. $variations = [];
  879.  
  880. foreach ($combinations as $combination) {
  881. if ($combination['id_product_attribute'] == $attribute['id_product_attribute']) {
  882. $attribute_name .= trim($combination['group_name']) . '(' . trim($combination['attribute_name']) . ') ';
  883. $cod_barras = $combination['ean13'];
  884. $variations = array_merge($variations, [trim($combination['group_name']) => trim($combination['attribute_name'])]);
  885.  
  886. if ($this->referencia === true) {
  887. $partId = (isset($combination['reference']) && $combination['reference'] ? $combination['reference'] : $product->reference);
  888. }
  889. else {
  890. $partId = $product->id . '-' . $attribute['id_product_attribute'];
  891. }
  892.  
  893. if (!$cod_barras) {
  894. $cod_barras = $product->ean13;
  895. }
  896.  
  897. if ((bool) $skus[$partId] !== false) {
  898. $p_type = 'PUT';
  899. $idSkuAny = $skus[$partId];
  900. }
  901. else {
  902. $p_type = 'POST';
  903. $idSkuAny = false;
  904. }
  905.  
  906. $combs[$partId] = $attribute['id_product_attribute'];
  907. $skuAtual = ['id' => (bool) $idSkuAny !== false ? $idSkuAny : '', 'title' => substr($product->name[$this->context->language->id] . ' - ' . $attribute_name, 0, 145), 'partnerId' => $partId, 'ean' => $this->validateEAN13($cod_barras) === true ? $cod_barras : '', 'amount' => $stock, 'price' => $cost, 'variations' => $variations];
  908. }
  909. }
  910. if (($p_type == 'PUT') && ((bool) $idSkuAny !== false)) {
  911. if (!$this->curl_post('products/' . $idAny . '/skus/' . $idSkuAny, 'PUT', $skuAtual)) {
  912. $this->saveLog('error', 'product', json_encode($skuAtual), 'SKU nao atualizado');
  913. }
  914.  
  915. $estoques[] = ['id' => $idSkuAny, 'partnerId' => $partId, 'quantity' => $stock, 'cost' => $cost, 'additionalTime' => 0];
  916. }
  917. else if (!$this->curl_post('products/' . $idAny . '/skus/', 'POST', $skuAtual)) {
  918. $this->saveLog('error', 'product', json_encode($skuAtual), 'SKU nao incluido');
  919. }
  920. }
  921.  
  922. foreach ($skus as $k => $sku) {
  923. if (array_key_exists($k, $combs) === false) {
  924. }
  925. }
  926. }
  927. else {
  928. $stock = StockAvailable::getQuantityAvailableByProduct($product->id);
  929. $cost = $product->getPrice(true, NULL, 2);
  930. $cod_barras = $product->ean13;
  931.  
  932. if ($this->referencia === true) {
  933. $partId = $product->reference;
  934. }
  935. else {
  936. $partId = $product->id;
  937. }
  938.  
  939. if ((bool) $skus[$partId] !== false) {
  940. $p_type = 'PUT';
  941. $idSkuAny = $skus[$partId];
  942. }
  943. else {
  944. $p_type = 'POST';
  945. $idSkuAny = false;
  946. }
  947.  
  948. $skuAtual = ['id' => (bool) $idSkuAny !== false ? $idSkuAny : '', 'title' => substr($product->name[$this->context->language->id], 0, 145), 'partnerId' => $partId, 'ean' => $this->validateEAN13($cod_barras) === true ? $cod_barras : '', 'amount' => $stock, 'price' => $cost];
  949. if (($p_type == 'PUT') && ((bool) $idSkuAny !== false)) {
  950. if (!$this->curl_post('products/' . $idAny . '/skus/' . $idSkuAny, 'PUT', $skuAtual)) {
  951. $this->saveLog('error', 'product', json_encode($skuAtual), 'SKU nao atualizado');
  952. }
  953.  
  954. $estoques[] = ['id' => $idSkuAny, 'partnerId' => $partId, 'quantity' => $stock, 'cost' => $cost, 'additionalTime' => 0];
  955. }
  956. else if (!$this->curl_post('products/' . $idAny . '/skus/', 'POST', $skuAtual)) {
  957. $this->saveLog('error', 'product', json_encode($skuAtual), 'SKU nao incluido');
  958. }
  959. }
  960.  
  961. if (!$this->curl_post('stocks/', 'PUT', $estoques)) {
  962. $this->saveLog('error', 'stocks', json_encode($estoques), 'Estoque nao atualizado.');
  963. }
  964. }
  965.  
  966. public function sendProdImages($id_product, $id_prod_any = false)
  967. {
  968. if (!$id_prod_any) {
  969. $id_prod_any = $this->getAnymarketData('products', $id_product);
  970. }
  971.  
  972. if (!$id_prod_any) {
  973. return NULL;
  974. }
  975.  
  976. $callback = $this->curl_post('products/' . $id_prod_any . '/images', 'GET', '');
  977.  
  978. if (is_array($callback['return'])) {
  979. $prod_imgs_any = json_decode(json_encode($callback['return']));
  980. }
  981. else if (!is_object($callback['return'])) {
  982. $prod_imgs_any = json_decode($callback['return']);
  983. }
  984. else {
  985. $prod_imgs_any = $callback['return'];
  986. }
  987.  
  988. foreach ($prod_imgs_any as $img_any) {
  989. $this->curl_post('products/' . $id_prod_any . '/images/' . $img_any->id, 'DELETE', '');
  990. $this->saveLog('delete', 'images', $img_any->id, 'Imagem do Produto ' . $id_prod_any . ' apagada ');
  991. }
  992.  
  993. $product = new Product($id_product);
  994. $imgs = $product->getImages($this->context->language->id);
  995. $comb_imgs = $product->getCombinationImages($this->context->language->id);
  996.  
  997. foreach ($imgs as $k => $img) {
  998. foreach ($comb_imgs as $k => $comb_img) {
  999. foreach ($comb_img as $attrib) {
  1000. if ($attrib['id_image'] == $img['id_image']) {
  1001. $var = $product->getAttributeCombinationsById($attrib['id_product_attribute'], $this->context->language->id);
  1002.  
  1003. foreach ($var as $combination) {
  1004. $var_name = '';
  1005.  
  1006. if ((bool) $combination['is_color_group'] !== false) {
  1007. $var_name .= trim($combination['attribute_name']);
  1008.  
  1009. if (end($var) !== $combination) {
  1010. $var_name .= ' / ';
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. }
  1017. $prod_img = ['index' => $k, 'main' => $img['cover'] ? true : false, 'url' => str_replace('https://', 'http://', $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], (int) $product->id . '-' . (int) $img['id_image'], ImageType::getFormatedName('thickbox'))), 'thumbnailUrl' => str_replace('https://', 'http://', $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], (int) $product->id . '-' . (int) $img['id_image'], ImageType::getFormatedName('medium'))), 'lowResolutionUrl' => str_replace('https://', 'http://', $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], (int) $product->id . '-' . (int) $img['id_image'], ImageType::getFormatedName('home'))), 'standardUrl' => str_replace('https://', 'http://', $this->context->link->getImageLink($product->link_rewrite[$this->context->language->id], (int) $product->id . '-' . (int) $img['id_image'], ImageType::getFormatedName('large'))), 'variation' => isset($var_name) && $var_name ? $var_name : ''];
  1018. $this->curl_post('products/' . $id_prod_any . '/images', 'POST', $prod_img);
  1019. }
  1020.  
  1021. return true;
  1022. }
  1023.  
  1024. public function getAttributeIdFromReference($reference)
  1025. {
  1026. $query = 'SELECT * FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `reference` = "' . $reference . '";';
  1027.  
  1028. if (!($attribute = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query))) {
  1029. return false;
  1030. }
  1031. else {
  1032. return $attribute['id_product_attribute'];
  1033. }
  1034. }
  1035.  
  1036. public function getIdProductFromReference($reference)
  1037. {
  1038. $query = 'SELECT * FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `reference` = "' . $reference . '";';
  1039.  
  1040. if (!($attribute = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($query))) {
  1041. return false;
  1042. }
  1043. else {
  1044. return $attribute['id_product'];
  1045. }
  1046. }
  1047.  
  1048. public function populateOrders()
  1049. {
  1050. if ($this->ecommerce_active !== true) {
  1051. return NULL;
  1052. }
  1053.  
  1054. $query_orders = 'SELECT `id_order`' . "\r\n\t\t\t" . 'FROM `' . _DB_PREFIX_ . 'orders`' . "\r\n\t\t\t" . 'WHERE `valid` = 1 AND `current_state` != ' . Configuration::get('PS_OS_CANCELED') . "\r\n\t\t\t" . 'LIMIT 0, 10' . "\r\n\t\t";
  1055. $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query_orders);
  1056. $this->sendResponse = [];
  1057.  
  1058. foreach ($result as $order) {
  1059. $any_order = $this->getAnymarketData('orders', (int) $order['id_order']);
  1060.  
  1061. if (!$any_order) {
  1062. $this->sendOrderData((int) $order['id_order']);
  1063. }
  1064. }
  1065. }
  1066.  
  1067. public function sendOrderData($id_order)
  1068. {
  1069. if ($this->ecommerce_active !== true) {
  1070. return NULL;
  1071. }
  1072.  
  1073. if ($this->getAnymarketData('orders', $id_order)) {
  1074. return NULL;
  1075. }
  1076.  
  1077. $order = new Order($id_order);
  1078. if (isset($order->shipping_number) && ($order->shipping_number != '')) {
  1079. if (isset($order->delivery_number) && ($order->delivery_number != '')) {
  1080. $ship_status = 'ENTREGUE';
  1081. }
  1082. else {
  1083. $ship_status = 'ENVIADO';
  1084. }
  1085. }
  1086. else {
  1087. $ship_status = '';
  1088. }
  1089.  
  1090. $customer = new Customer($order->id_customer);
  1091. $address_delivery = new Address($order->id_address_delivery);
  1092. $address_invoice = new Address($order->id_address_invoice);
  1093. $state_delivery = new State($address_delivery->id_state);
  1094. $nfe = $this->getNfeData($order->id);
  1095. $carrier = new Carrier($order->id_carrier);
  1096. $cart = new Cart($order->id_cart);
  1097. $prods = $order->getProducts();
  1098. $cpf_field = false;
  1099. $cnpj_field = false;
  1100.  
  1101. if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'customer" AND COLUMN_NAME = "cpf"')) {
  1102. $cpf_field = 'cpf';
  1103. $cnpj_field = 'siret';
  1104. }
  1105. else if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'customer" AND COLUMN_NAME = "cpf_cnpj"')) {
  1106. $cpf_field = 'cpf_cnpj';
  1107. $cnpj_field = 'cpf_cnpj';
  1108. }
  1109. else if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'customer" AND COLUMN_NAME = "document"')) {
  1110. $cpf_field = 'document';
  1111. $cnpj_field = 'document';
  1112.  
  1113. if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'customer" AND COLUMN_NAME = "doc_type"')) {
  1114. $doc_type = true;
  1115. }
  1116. }
  1117. else if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'cpfmodule_data" AND COLUMN_NAME = "doc"') && Module::isEnabled('cpfmodule')) {
  1118. $cpf_field = 'doc';
  1119. $cnpj_field = 'doc';
  1120. }
  1121. else if (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = "' . _DB_PREFIX_ . 'djtalbrazilianregister" AND COLUMN_NAME = "cpf"')) {
  1122. $cpf_field = 'djtal';
  1123. $cnpj_field = 'djtal';
  1124. }
  1125. if (($cpf_field === false) || ($cnpj_field === false)) {
  1126. $this->saveLog('error', 'cpf/cnpj', json_encode($customer), 'Campo CPF/CNPJ nao encontrado.');
  1127. }
  1128. if (($cpf_field == 'djtal') || ($cnpj_field == 'djtal')) {
  1129. $document = Db::getInstance()->getValue('SELECT `cpf` FROM `' . _DB_PREFIX_ . 'djtalbrazilianregister` WHERE `id_customer` = ' . $customer->id);
  1130.  
  1131. if (!$document) {
  1132. $document = Db::getInstance()->getValue('SELECT `cnpj` FROM `' . _DB_PREFIX_ . 'djtalbrazilianregister` WHERE `id_customer` = ' . $customer->id);
  1133. }
  1134. }
  1135. else if ($cnpj_field == 'doc') {
  1136. $document = Db::getInstance()->getValue('SELECT `doc` FROM `' . _DB_PREFIX_ . 'cpfmodule` WHERE`id_customer` = ' . $customer->id);
  1137. }
  1138. else {
  1139. $document = $customer->{$cpf_field};
  1140.  
  1141. if (!$document) {
  1142. $document = $customer->{$cnpj_field};
  1143. }
  1144. }
  1145.  
  1146. $items = [];
  1147.  
  1148. foreach ($prods as $prod) {
  1149. $product_id = $prod['product_id'];
  1150. $prod_reference = $prod['product_reference'];
  1151. if (isset($prod['product_attribute_id']) && ($prod['product_attribute_id'] != '')) {
  1152. if ($this->referencia === true) {
  1153. $ps_sku = $prod['product_reference'];
  1154. }
  1155. else {
  1156. $ps_sku = $product_id;
  1157. }
  1158. }
  1159. else if ($this->referencia === true) {
  1160. $ps_sku = $prod_reference;
  1161. }
  1162. else {
  1163. $ps_sku = $product_id;
  1164. }
  1165.  
  1166. $id_prod_any = $this->getAnymarketData('products', $product_id);
  1167. $callback = $this->curl_post('products/' . $id_prod_any . '/skus', 'GET', '');
  1168.  
  1169. if (is_array($callback['return'])) {
  1170. $skusAnymarket = json_decode(json_encode($callback['return']));
  1171. }
  1172. else if (!is_object($callback['return'])) {
  1173. $skusAnymarket = json_decode($callback['return']);
  1174. }
  1175. else {
  1176. $skusAnymarket = $callback['return'];
  1177. }
  1178.  
  1179. foreach ($skusAnymarket as $sku) {
  1180. if ($sku->partnerId == $ps_sku) {
  1181. $id_sku = $sku->id;
  1182. }
  1183. }
  1184.  
  1185. if ($this->referencia === true) {
  1186. $partnerId = $prod_reference;
  1187. }
  1188. else {
  1189. $partnerId = $product_id;
  1190. }
  1191.  
  1192. $prod_name = $prod['product_name'];
  1193. if (isset($prod_reference) && ($prod_reference != '')) {
  1194. $prod_name = $prod_name . ' (' . $prod_reference . ')';
  1195. }
  1196. if (isset($prod['attributes']) && ($prod['attributes'] != '')) {
  1197. $prod_name = $prod_name . ' - ' . $prod['attributes'];
  1198. }
  1199.  
  1200. $prod_amount = $prod['product_quantity'];
  1201. $prod_price = (float) $prod['original_product_price'];
  1202. $prod_discount = (float) ($prod['original_product_price'] - $prod['product_price']) * $prod['product_quantity'];
  1203. $prod_gross = (float) $prod['product_price'] * $prod['product_quantity'];
  1204. $prod_total = (float) $prod['total_price'];
  1205. $items[] = [
  1206. 'sku' => ['id' => $id_sku, 'title' => substr($prod_name, 0, 145), 'partnerId' => $partnerId],
  1207. 'product' => ['id' => id_prod_any, 'title' => substr($prod_name, 0, 145)],
  1208. 'amount' => $prod_amount,
  1209. 'unit' => $prod_price,
  1210. 'discount' => $prod_discount,
  1211. 'gross' => $prod_gross,
  1212. 'total' => $prod_total,
  1213. 'shippings' => [
  1214. ['id' => id_prod_any, 'shippingtype' => $carrier->name]
  1215. ..............................................................................................
  1216. ...........................................................
  1217. ........................
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement